Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(onboarding): redesigned flow + post-landing starter content opt-in (#1411)

Naiyuan Qing3fd2fb2ae3b2
diff --git a/CLAUDE.md b/CLAUDE.md
index 487c323637..bfc1fe6e1e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -106,6 +106,7 @@ pnpm ui:add badge # Adds component to packages/ui/components/ui/
# Infrastructure
make db-up # Start shared PostgreSQL (pgvector/pg17 image)
make db-down # Stop shared PostgreSQL
+make db-reset # Drop + recreate current env's DB, then re-run migrations (local only; stop backend first)
```
### CI Requirements
@@ -219,26 +220,35 @@ Cross-workspace `push(path)` is detected by the navigation adapter (`platform/na
### Drag region (macOS window-move)
-Every full-window desktop view (login, overlay, any page that covers the native title bar) needs a top drag strip so users can move the window. On macOS the traffic lights are hidden via `useImmersiveMode` in overlay-style contexts, so the drag strip also gives back that corner for pointer-drag.
+Every full-window desktop view (login, onboarding, new-workspace, invite, no-access, create-workspace modal) — i.e. anything that isn't inside the dashboard shell — needs a top drag strip so users can move the window. The native macOS traffic lights are **kept visible** for every such surface (Linear/Notion/Arc pattern); no `useImmersiveMode` by default.
-**Pattern**: flex child at top, not absolute overlay.
+**Pattern**: use the shared `<DragStrip />` from `@multica/views/platform` as the first flex child of the page root. It's a 48px transparent row with `-webkit-app-region: drag` — the parent's bg fills through it so the page reads edge-to-edge while the top 48px stays draggable under the traffic lights.
```tsx
-<div className="fixed inset-0 z-50 flex flex-col bg-background">
- <div className="h-12 shrink-0" style={{ WebkitAppRegion: "drag" }} />
- <div className="flex-1 overflow-auto" style={{ WebkitAppRegion: "no-drag" }}>
- {/* page content — interactive elements need their own "no-drag" */}
+import { DragStrip } from "@multica/views/platform";
+
+return (
+ <div className="flex min-h-svh flex-col bg-background">
+ <DragStrip />
+ <div className="flex flex-1 flex-col px-6 pb-12">
+ {/* page content — interactive elements placed at y ≥ 48 clear the strip;
+ any element at y < 48 needs WebkitAppRegion: "no-drag" */}
+ </div>
</div>
-</div>
+);
```
-Why flex, not absolute: the absolute-strip + `z-index` approach relies on stacking-context hit-testing, which isn't reliable for `-webkit-app-region`. A real flex row with no siblings at that pixel is unambiguous. Height matches `MainTopBar` (48px / `h-12`) for consistency.
+Why flex, not absolute: the absolute-strip + `z-index` approach relies on stacking-context hit-testing, which isn't reliable for `-webkit-app-region`. A real flex row with no siblings at that pixel is unambiguous. Web browsers silently ignore `-webkit-app-region`, so shared views render the strip as a plain 48px spacer on web — safe cross-platform.
-Canonical examples: `components/window-overlay.tsx`, `pages/login.tsx`.
+**Horizontal clearance**: traffic lights occupy roughly x ∈ [16, 76] on macOS. Interactive UI (Back buttons, menus) should start at x ≥ 80 on desktop-sized viewports. The shared views default to sufficient `lg:px-20` padding; re-examine when laying out anything in the top-left corner.
+
+Canonical example: `packages/views/platform/drag-strip.tsx`. Used by `onboarding/steps/step-welcome.tsx` (per-column), `onboarding/onboarding-flow.tsx`, `workspace/new-workspace-page.tsx`, `invite/invite-page.tsx`, `workspace/no-access-page.tsx`, `modals/create-workspace.tsx`, and desktop's `pages/login.tsx`.
+
+**When to use `useImmersiveMode`**: only when a view must place interactive UI in the traffic-light hit-zone (y < 28 AND x < 80). For every current non-dashboard surface, buttons sit at y ≥ 48, so immersive mode is unnecessary. Hook is preserved as an escape hatch but has no callers.
### UX vs platform chrome
-UX affordances (Back button, Log out button, welcome copy, invite card) belong in `packages/views/` so web and desktop render identical content. Platform chrome (drag strip, `useImmersiveMode`, tab system interaction, traffic-light accommodation) lives in desktop-only code. Violating this split always produces platform divergence — if a button exists on desktop but not on web for the same flow, it's a signal the UX escaped into platform code.
+UX affordances (Back button, Log out button, welcome copy, invite card) belong in `packages/views/` so web and desktop render identical content. Platform chrome (tab system interaction, native-window IPC, `useImmersiveMode`) lives in desktop-only code. The `DragStrip` + `useImmersiveMode` primitives live in `packages/views/platform/` because they're cross-platform safe (web no-op) and need to be callable from shared views that own the page layout — keeping them in desktop-only would force every shared page to leave top-padding decisions to the platform shell, fragmenting the design.
## UI/UX Rules
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index c447461abc..b15178db9d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -592,6 +592,19 @@ If you want to stop PostgreSQL and keep your local databases:
make db-down
```
+If you want a fresh database for the current checkout only (drops the
+database named in `POSTGRES_DB`, recreates it, and runs all migrations):
+
+```bash
+make stop # stop backend/frontend first
+make db-reset
+make start
+```
+
+- only affects the current env's database; other worktree databases are untouched
+- refuses to run if `DATABASE_URL` points at a remote host
+- pass `ENV_FILE=.env.worktree` to target a specific worktree
+
If you want to wipe all local PostgreSQL data for this repo:
```bash
diff --git a/Makefile b/Makefile
index 13f3a2dfce..9a03926466 100644
--- a/Makefile
+++ b/Makefile
@@ -1,4 +1,4 @@
-.PHONY: dev server daemon cli multica build test migrate-up migrate-down sqlc seed clean setup start stop check worktree-env setup-main start-main stop-main check-main setup-worktree start-worktree stop-worktree check-worktree db-up db-down selfhost selfhost-stop
+.PHONY: dev server daemon cli multica build test migrate-up migrate-down sqlc seed clean setup start stop check worktree-env setup-main start-main stop-main check-main setup-worktree start-worktree stop-worktree check-worktree db-up db-down db-reset selfhost selfhost-stop
MAIN_ENV_FILE ?= .env
WORKTREE_ENV_FILE ?= .env.worktree
@@ -137,6 +137,26 @@ db-up:
db-down:
@$(COMPOSE) down
+# Drop + recreate the current env's database, then run all migrations.
+# Use for a clean slate in local dev. Only affects the DB named in
+# ENV_FILE (POSTGRES_DB); the shared postgres container and other
+# worktree DBs are untouched. Refuses to run against a remote host.
+db-reset:
+ $(REQUIRE_ENV)
+ @case "$(DATABASE_URL)" in \
+ ""|*@localhost:*|*@localhost/*|*@127.0.0.1:*|*@127.0.0.1/*|*@\[::1\]:*|*@\[::1\]/*) ;; \
+ *) echo "Refusing to reset: DATABASE_URL points at a remote host."; exit 1 ;; \
+ esac
+ @bash scripts/ensure-postgres.sh "$(ENV_FILE)"
+ @echo "==> Dropping and recreating database '$(POSTGRES_DB)'..."
+ @$(COMPOSE) exec -T postgres psql -U $(POSTGRES_USER) -d postgres -v ON_ERROR_STOP=1 \
+ -c "DROP DATABASE IF EXISTS \"$(POSTGRES_DB)\" WITH (FORCE);" \
+ -c "CREATE DATABASE \"$(POSTGRES_DB)\";"
+ @echo "==> Running migrations..."
+ cd server && go run ./cmd/migrate up
+ @echo ""
+ @echo "✓ Database '$(POSTGRES_DB)' reset. Run 'make start' to launch the app."
+
worktree-env:
@bash scripts/init-worktree-env.sh .env.worktree
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 941c661838..b57c79c5be 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -38,6 +38,7 @@
"@electron-toolkit/preload": "^3.0.2",
"@electron-toolkit/utils": "^4.0.0",
"@fontsource-variable/inter": "^5.2.5",
+ "@fontsource-variable/source-serif-4": "^5.2.9",
"@fontsource/geist-mono": "^5.2.7",
"@multica/core": "workspace:*",
"@multica/ui": "workspace:*",
diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsx
index ebd13d8fb4..54d1faac68 100644
--- a/apps/desktop/src/renderer/src/App.tsx
+++ b/apps/desktop/src/renderer/src/App.tsx
@@ -4,6 +4,7 @@ import { CoreProvider } from "@multica/core/platform";
import { useAuthStore } from "@multica/core/auth";
import { workspaceKeys, workspaceListOptions } from "@multica/core/workspace/queries";
import { api } from "@multica/core/api";
+import { useHasOnboarded } from "@multica/core/paths";
import { ThemeProvider } from "@multica/ui/components/common/theme-provider";
import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
import { Toaster } from "sonner";
@@ -90,11 +91,28 @@ function AppContent() {
// account switches (user A logout → user B login) should not trigger a
// daemon restart here — daemon-manager already restarts on user change
// via syncToken.
- const { data: workspaces, isFetched: workspaceListFetched } = useQuery({
+ const { data: workspaces = [], isFetched: workspaceListFetched } = useQuery({
...workspaceListOptions(),
enabled: !!user,
});
- const wsCount = workspaces?.length ?? 0;
+ const wsCount = workspaces.length;
+ const hasOnboarded = useHasOnboarded();
+
+ // Onboarding and zero-workspace both resolve to an overlay, but
+ // onboarding wins: a user who hasn't completed it gets the onboarding
+ // overlay regardless of how many workspaces already exist.
+ useEffect(() => {
+ if (!user || !workspaceListFetched) return;
+ const { overlay, open } = useWindowOverlayStore.getState();
+ if (overlay) return;
+ if (!hasOnboarded) {
+ open({ type: "onboarding" });
+ return;
+ }
+ if (wsCount === 0) {
+ open({ type: "new-workspace" });
+ }
+ }, [user, workspaceListFetched, wsCount, workspaces, hasOnboarded]);
// Validate persisted tab state against the current user's workspace list,
// and pick an active workspace if none is set. Runs in useLayoutEffect
@@ -114,22 +132,6 @@ function AppContent() {
}
}, [workspaces]);
- // Bidirectional new-workspace overlay: visible when there are no
- // workspaces to enter, hidden as soon as one exists. Gated on
- // `workspaceListFetched` so the initial render doesn't flash the
- // overlay before the list arrives. The overlay's own `invite` type is
- // not touched here — that's an in-flight task owned by the user.
- useEffect(() => {
- if (!user) return;
- if (!workspaceListFetched) return;
- const { overlay, open, close } = useWindowOverlayStore.getState();
- const isEmpty = wsCount === 0;
- if (isEmpty) {
- if (!overlay) open({ type: "new-workspace" });
- } else if (overlay?.type === "new-workspace") {
- close();
- }
- }, [user, workspaceListFetched, wsCount]);
// null = undecided (pre-login or list hasn't settled yet)
// true = session started with zero workspaces; next transition to >=1 triggers restart
// false = session started with >=1 workspace, OR we've already restarted; skip
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
index 78c0e4a468..15f488a8ff 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
@@ -13,6 +13,7 @@ import { ModalRegistry } from "@multica/views/modals/registry";
import { AppSidebar } from "@multica/views/layout";
import { SearchCommand, SearchTrigger } from "@multica/views/search";
import { ChatFab, ChatWindow } from "@multica/views/chat";
+import { StarterContentPrompt } from "@multica/views/onboarding";
import { WorkspaceSlugProvider } from "@multica/core/paths";
import { getCurrentSlug, subscribeToCurrentSlug } from "@multica/core/platform";
import { DesktopNavigationProvider } from "@/platform/navigation";
@@ -134,6 +135,7 @@ export function DesktopShell() {
</div>
{slug && <ModalRegistry />}
{slug && <SearchCommand />}
+ {slug && <StarterContentPrompt />}
<WindowOverlay />
</WorkspaceSlugProvider>
</DesktopNavigationProvider>
diff --git a/apps/desktop/src/renderer/src/components/window-overlay.tsx b/apps/desktop/src/renderer/src/components/window-overlay.tsx
index 9ef5b291ab..99dfe37027 100644
--- a/apps/desktop/src/renderer/src/components/window-overlay.tsx
+++ b/apps/desktop/src/renderer/src/components/window-overlay.tsx
@@ -1,7 +1,7 @@
import { useQuery } from "@tanstack/react-query";
-import { useImmersiveMode } from "@multica/views/platform";
import { NewWorkspacePage } from "@multica/views/workspace/new-workspace-page";
import { InvitePage } from "@multica/views/invite";
+import { OnboardingFlow } from "@multica/views/onboarding";
import { useNavigation } from "@multica/views/navigation";
import { paths } from "@multica/core/paths";
import { workspaceListOptions } from "@multica/core/workspace/queries";
@@ -9,18 +9,21 @@ import { useWindowOverlayStore } from "@/stores/window-overlay-store";
/**
* Window-level transition overlay: renders above the tab system when the
- * user is in a pre-workspace flow (create workspace, accept invite).
+ * user is in a pre-workspace flow (onboarding, create workspace, accept
+ * invite).
*
- * This component is a thin **platform shell**:
- * - Hands the window-drag strip and macOS traffic-light hiding
- * (`useImmersiveMode`) — both are platform-specific, web has neither
- * - Covers the tab system (fixed inset, z-50) so the Shell's own TabBar
- * doesn't leak through
+ * This component is intentionally thin — just a fixed positioning shell
+ * that covers the tab system. It does NOT hide traffic lights or provide
+ * a drag strip: each contained view (OnboardingFlow, NewWorkspacePage,
+ * InvitePage) renders its own `<DragStrip />` as a flex-child at top so
+ * native macOS traffic lights stay visible and the page content can fill
+ * the window edge-to-edge. This matches the Linear/Notion/Arc pattern for
+ * pre-dashboard flows and keeps platform chrome consistent across every
+ * "not-in-dashboard" surface.
*
* All UX affordances (Back button, Log out button, welcome copy, invite
- * card) live inside the shared `NewWorkspacePage` / `InvitePage`
- * components under `packages/views/`, so web and desktop render identical
- * content. The platform split is: UX in shared code, chrome here.
+ * card) live inside the shared view components under `packages/views/`,
+ * so web and desktop render identical content.
*/
export function WindowOverlay() {
const overlay = useWindowOverlayStore((s) => s.overlay);
@@ -34,8 +37,6 @@ function WindowOverlayInner() {
const { push } = useNavigation();
const { data: wsList = [] } = useQuery(workspaceListOptions());
- useImmersiveMode();
-
if (!overlay) return null;
// Back is only meaningful when there's somewhere to go — i.e. the user
@@ -44,42 +45,35 @@ function WindowOverlayInner() {
const onBack = wsList.length > 0 ? close : undefined;
return (
- <div className="fixed inset-0 z-50 flex flex-col bg-background">
- {/* Window-drag strip. Rendered as a flex *child* (not absolute
- overlay) so it owns its own 48px of real layout space — the
- prior absolute-positioned approach relied on z-index stacking
- to beat the content wrapper's no-drag, which in practice didn't
- hit-test reliably for `-webkit-app-region` on the welcome
- screen. A real flex row with nothing else in it has no such
- ambiguity: any pixel at top-48 is drag, full stop.
-
- Height matches `MainTopBar` (48px) so the drag-to-grab area
- feels consistent with the rest of the app. The strip is
- invisible; macOS traffic lights would normally sit here but
- `useImmersiveMode` has hidden them for the overlay's lifetime. */}
- <div
- aria-hidden
- className="h-12 shrink-0"
- style={{ WebkitAppRegion: "drag" } as React.CSSProperties}
- />
-
- <div
- className="flex-1 min-h-0 overflow-auto"
- style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
- >
- {overlay.type === "new-workspace" && (
- <NewWorkspacePage
- onSuccess={(ws) => push(paths.workspace(ws.slug).issues())}
- onBack={onBack}
- />
- )}
- {overlay.type === "invite" && (
- <InvitePage
- invitationId={overlay.invitationId}
- onBack={onBack}
- />
- )}
- </div>
+ <div className="fixed inset-0 z-50 flex flex-col overflow-auto bg-background">
+ {overlay.type === "new-workspace" && (
+ <NewWorkspacePage
+ onSuccess={(ws) => push(paths.workspace(ws.slug).issues())}
+ onBack={onBack}
+ />
+ )}
+ {overlay.type === "invite" && (
+ <InvitePage
+ invitationId={overlay.invitationId}
+ onBack={onBack}
+ />
+ )}
+ {overlay.type === "onboarding" && (
+ <OnboardingFlow
+ onComplete={(ws) => {
+ close();
+ // Post-onboarding landing is always the workspace issues
+ // list. The welcome-issue flow moved into a dialog that
+ // renders on that page (StarterContentPrompt), so the
+ // flow doesn't need to thread a target issue id back here.
+ if (ws) {
+ push(paths.workspace(ws.slug).issues());
+ } else {
+ push(paths.root());
+ }
+ }}
+ />
+ )}
</div>
);
}
diff --git a/apps/desktop/src/renderer/src/globals.css b/apps/desktop/src/renderer/src/globals.css
index 475efdf145..ae4da4a990 100644
--- a/apps/desktop/src/renderer/src/globals.css
+++ b/apps/desktop/src/renderer/src/globals.css
@@ -25,6 +25,8 @@
--font-sans: "Inter Variable", "Inter", -apple-system, BlinkMacSystemFont,
"Segoe UI", "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC",
sans-serif;
+ --font-serif: "Source Serif 4 Variable", "Source Serif 4", "Iowan Old Style",
+ "Apple Garamond", Baskerville, "Times New Roman", serif;
--font-mono: "Geist Mono", ui-monospace, SFMono-Regular, Menlo, Consolas,
monospace;
}
diff --git a/apps/desktop/src/renderer/src/main.tsx b/apps/desktop/src/renderer/src/main.tsx
index ad276ee037..1dd7ee22ba 100644
--- a/apps/desktop/src/renderer/src/main.tsx
+++ b/apps/desktop/src/renderer/src/main.tsx
@@ -4,6 +4,11 @@ import App from "./App";
// Geist Mono kept as-is for code blocks; CJK is handled by system font fallback
// (see globals.css --font-sans chain). Keep font stack in sync with apps/web/app/layout.tsx.
import "@fontsource-variable/inter";
+// Editorial serif — matches web's next/font Source_Serif_4. Loaded app-wide so
+// onboarding headings and any future editorial surface can use `font-serif`
+// (see tokens.css @theme inline). Variable font = one file covers all weights.
+import "@fontsource-variable/source-serif-4";
+import "@fontsource-variable/source-serif-4/wght-italic.css";
import "@fontsource/geist-mono/400.css";
import "@fontsource/geist-mono/700.css";
import "./globals.css";
diff --git a/apps/desktop/src/renderer/src/pages/login.tsx b/apps/desktop/src/renderer/src/pages/login.tsx
index df8ab5ac51..e0f7efdc27 100644
--- a/apps/desktop/src/renderer/src/pages/login.tsx
+++ b/apps/desktop/src/renderer/src/pages/login.tsx
@@ -1,4 +1,5 @@
import { LoginPage } from "@multica/views/auth";
+import { DragStrip } from "@multica/views/platform";
import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
const WEB_URL = import.meta.env.VITE_APP_URL || "http://localhost:3000";
@@ -14,11 +15,7 @@ export function DesktopLoginPage() {
return (
<div className="flex h-screen flex-col">
- {/* Traffic light inset */}
- <div
- className="h-[38px] shrink-0"
- style={{ WebkitAppRegion: "drag" } as React.CSSProperties}
- />
+ <DragStrip />
<LoginPage
logo={<MulticaIcon bordered size="lg" />}
onSuccess={() => {
diff --git a/apps/desktop/src/renderer/src/platform/navigation.tsx b/apps/desktop/src/renderer/src/platform/navigation.tsx
index efe14fe6eb..4a303a64a3 100644
--- a/apps/desktop/src/renderer/src/platform/navigation.tsx
+++ b/apps/desktop/src/renderer/src/platform/navigation.tsx
@@ -54,6 +54,13 @@ function tryRouteToOverlay(path: string, router?: DataRouter): boolean {
}
return true;
}
+ if (path === "/onboarding") {
+ overlay.open({ type: "onboarding" });
+ if (router && router.state.location.pathname !== "/") {
+ router.navigate("/", { replace: true });
+ }
+ return true;
+ }
if (path.startsWith("/invite/")) {
let id = "";
try {
diff --git a/apps/desktop/src/renderer/src/stores/window-overlay-store.ts b/apps/desktop/src/renderer/src/stores/window-overlay-store.ts
index c0839afed9..2041d5b63d 100644
--- a/apps/desktop/src/renderer/src/stores/window-overlay-store.ts
+++ b/apps/desktop/src/renderer/src/stores/window-overlay-store.ts
@@ -14,7 +14,8 @@ import { create } from "zustand";
*/
export type WindowOverlay =
| { type: "new-workspace" }
- | { type: "invite"; invitationId: string };
+ | { type: "invite"; invitationId: string }
+ | { type: "onboarding" };
interface WindowOverlayStore {
overlay: WindowOverlay | null;
diff --git a/apps/docs/content/docs/developers/contributing.mdx b/apps/docs/content/docs/developers/contributing.mdx
index 90daea6851..f31e0dd61d 100644
--- a/apps/docs/content/docs/developers/contributing.mdx
+++ b/apps/docs/content/docs/developers/contributing.mdx
@@ -169,6 +169,16 @@ Stop PostgreSQL and keep local databases:
make db-down
```
+Reset only the current checkout's database (drops `POSTGRES_DB`, recreates it, re-runs all migrations). Other worktree databases are untouched.
+
+```bash
+make stop
+make db-reset
+make start
+```
+
+> `make db-reset` refuses to run if `DATABASE_URL` points at a remote host.
+
Wipe all local PostgreSQL data:
```bash
diff --git a/apps/web/app/(auth)/login/page.tsx b/apps/web/app/(auth)/login/page.tsx
index 7693b6725e..ceebf15bf5 100644
--- a/apps/web/app/(auth)/login/page.tsx
+++ b/apps/web/app/(auth)/login/page.tsx
@@ -5,7 +5,11 @@ import { useSearchParams, useRouter } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
import { sanitizeNextUrl, useAuthStore } from "@multica/core/auth";
import { workspaceKeys } from "@multica/core/workspace/queries";
-import { paths } from "@multica/core/paths";
+import {
+ paths,
+ resolvePostAuthDestination,
+ useHasOnboarded,
+} from "@multica/core/paths";
import { api } from "@multica/core/api";
import type { Workspace } from "@multica/core/types";
import {
@@ -42,9 +46,10 @@ function LoginPageContent() {
const [desktopToken, setDesktopToken] = useState<string | null>(null);
const [desktopError, setDesktopError] = useState("");
+ const hasOnboarded = useHasOnboarded();
// Already authenticated — honor ?next= or fall back to first workspace
- // (or /workspaces/new if the user has none). Skip this entire path when
+ // (or /onboarding if the user has none). Skip this entire path when
// the user arrived to authorize the CLI.
useEffect(() => {
if (isLoading || !user || cliCallbackRaw) return;
@@ -65,29 +70,33 @@ function LoginPageContent() {
});
return;
}
+ if (!hasOnboarded) {
+ router.replace(paths.onboarding());
+ return;
+ }
if (nextUrl) {
router.replace(nextUrl);
return;
}
const list = qc.getQueryData<Workspace[]>(workspaceKeys.list()) ?? [];
- const [first] = list;
- router.replace(
- first ? paths.workspace(first.slug).issues() : paths.newWorkspace(),
- );
- }, [isLoading, user, router, nextUrl, cliCallbackRaw, isDesktopHandoff, qc]);
+ router.replace(resolvePostAuthDestination(list, hasOnboarded));
+ }, [isLoading, user, router, nextUrl, cliCallbackRaw, isDesktopHandoff, hasOnboarded, qc]);
const handleSuccess = () => {
+ // Read the latest user snapshot directly — the closure's `hasOnboarded`
+ // was captured before login completed and would be stale here.
+ const currentUser = useAuthStore.getState().user;
+ const onboarded = currentUser?.onboarded_at != null;
+ if (!onboarded) {
+ router.push(paths.onboarding());
+ return;
+ }
if (nextUrl) {
router.push(nextUrl);
return;
}
- // The LoginPage view populates the workspace list cache before calling
- // onSuccess, so it's safe to read here.
const list = qc.getQueryData<Workspace[]>(workspaceKeys.list()) ?? [];
- const [first] = list;
- router.push(
- first ? paths.workspace(first.slug).issues() : paths.newWorkspace(),
- );
+ router.push(resolvePostAuthDestination(list, onboarded));
};
// Build Google OAuth state: encode platform + next URL so the callback
diff --git a/apps/web/app/(auth)/onboarding/page.tsx b/apps/web/app/(auth)/onboarding/page.tsx
new file mode 100644
index 0000000000..0308e7bf12
--- /dev/null
+++ b/apps/web/app/(auth)/onboarding/page.tsx
@@ -0,0 +1,84 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { useRouter } from "next/navigation";
+import { useQuery } from "@tanstack/react-query";
+import { useAuthStore } from "@multica/core/auth";
+import {
+ paths,
+ resolvePostAuthDestination,
+ useHasOnboarded,
+} from "@multica/core/paths";
+import { workspaceListOptions } from "@multica/core/workspace/queries";
+import { CliInstallInstructions, OnboardingFlow } from "@multica/views/onboarding";
+
+/**
+ * Web shell for the onboarding flow. The route is the platform chrome on
+ * web (matching `WindowOverlay` on desktop); content is the shared
+ * `<OnboardingFlow />`. Kept minimal — guard on auth, render, exit.
+ *
+ * On complete: if a workspace was just created, navigate into it;
+ * otherwise fall back to root (proxy / landing picks the user's first ws
+ * or bounces to onboarding if still zero).
+ *
+ * The CLI install card is wired here so its `multica setup` command
+ * points at THIS server — dev landing on localhost gets a localhost
+ * self-host command, prod cloud gets the plain `multica setup`, prod
+ * self-host gets one with explicit URLs. `appUrl` lives in useState
+ * so SSR doesn't error on `window` — it fills in on mount.
+ */
+export default function OnboardingPage() {
+ const router = useRouter();
+ const user = useAuthStore((s) => s.user);
+ const isLoading = useAuthStore((s) => s.isLoading);
+ const hasOnboarded = useHasOnboarded();
+ const { data: workspaces = [], isFetched: workspacesFetched } = useQuery({
+ ...workspaceListOptions(),
+ enabled: !!user && hasOnboarded,
+ });
+ const [appUrl, setAppUrl] = useState<string | undefined>(undefined);
+
+ useEffect(() => {
+ setAppUrl(window.location.origin);
+ }, []);
+
+ useEffect(() => {
+ if (isLoading || !user) {
+ if (!isLoading && !user) router.replace(paths.login());
+ return;
+ }
+ if (hasOnboarded && workspacesFetched) {
+ router.replace(resolvePostAuthDestination(workspaces, hasOnboarded));
+ }
+ }, [isLoading, user, hasOnboarded, workspacesFetched, workspaces, router]);
+
+ if (isLoading || !user || hasOnboarded) return null;
+
+ // Layout: page owns its own scroll (root layout sets `body {
+ // overflow: hidden }` for the app-shell convention). OnboardingFlow
+ // owns the per-step width constraint internally — Welcome renders a
+ // wide two-column hero, all other steps wrap themselves at max-w-xl.
+ return (
+ <div className="h-full overflow-y-auto bg-background">
+ <OnboardingFlow
+ onComplete={(ws) => {
+ // No more firstIssueId handoff — the welcome issue is created
+ // inside the workspace via StarterContentPrompt, not during
+ // onboarding. Always land on the workspace issues list (or
+ // root if the flow never produced a workspace).
+ if (ws) {
+ router.push(paths.workspace(ws.slug).issues());
+ } else {
+ router.push(paths.root());
+ }
+ }}
+ runtimeInstructions={
+ <CliInstallInstructions
+ apiUrl={process.env.NEXT_PUBLIC_API_URL}
+ appUrl={appUrl}
+ />
+ }
+ />
+ </div>
+ );
+}
diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx
index a2ecebf9e6..43769cc98e 100644
--- a/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx
+++ b/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx
@@ -4,13 +4,21 @@ import { DashboardLayout } from "@multica/views/layout";
import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
import { SearchCommand, SearchTrigger } from "@multica/views/search";
import { ChatFab, ChatWindow } from "@multica/views/chat";
+import { StarterContentPrompt } from "@multica/views/onboarding";
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<DashboardLayout
loadingIndicator={<MulticaIcon className="size-6" />}
searchSlot={<SearchTrigger />}
- extra={<><SearchCommand /><ChatWindow /><ChatFab /></>}
+ extra={
+ <>
+ <SearchCommand />
+ <ChatWindow />
+ <ChatFab />
+ <StarterContentPrompt />
+ </>
+ }
>
{children}
</DashboardLayout>
diff --git a/apps/web/app/auth/callback/page.test.tsx b/apps/web/app/auth/callback/page.test.tsx
index 913c055832..da6cbca86e 100644
--- a/apps/web/app/auth/callback/page.test.tsx
+++ b/apps/web/app/auth/callback/page.test.tsx
@@ -10,6 +10,18 @@ const { mockPush, mockSearchParams, mockLoginWithGoogle, mockListWorkspaces } =
mockListWorkspaces: vi.fn(),
}));
+const makeUser = (overrides: Partial<{ onboarded_at: string | null }> = {}) => ({
+ id: "user-1",
+ name: "Test",
+ email: "[email protected]",
+ avatar_url: null,
+ onboarded_at: null,
+ onboarding_questionnaire: {},
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ ...overrides,
+});
+
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: mockPush }),
useSearchParams: () => mockSearchParams,
@@ -51,30 +63,44 @@ describe("CallbackPage", () => {
vi.clearAllMocks();
mockSearchParams.forEach((_v, k) => mockSearchParams.delete(k));
mockSearchParams.set("code", "test-code");
- mockLoginWithGoogle.mockResolvedValue(undefined);
+ mockLoginWithGoogle.mockResolvedValue(makeUser());
mockListWorkspaces.mockResolvedValue([]);
});
- it("falls back to paths.newWorkspace() when no next= is present and the user has no workspace", async () => {
+ it("unonboarded user lands on /onboarding regardless of next=", async () => {
+ mockSearchParams.set("state", "next:/invite/abc123");
render(<CallbackPage />);
+ await waitFor(() => {
+ expect(mockPush).toHaveBeenCalledWith(paths.onboarding());
+ });
+ expect(mockPush).not.toHaveBeenCalledWith("/invite/abc123");
+ });
+ it("unonboarded user with no next= also lands on /onboarding", async () => {
+ render(<CallbackPage />);
await waitFor(() => {
- expect(mockPush).toHaveBeenCalledWith(paths.newWorkspace());
+ expect(mockPush).toHaveBeenCalledWith(paths.onboarding());
});
});
- it("ignores unsafe next= targets from the OAuth state and still lands on the default destination", async () => {
+ it("onboarded user ignores unsafe next= targets and lands on the default destination", async () => {
+ mockLoginWithGoogle.mockResolvedValue(
+ makeUser({ onboarded_at: "2026-01-01T00:00:00Z" }),
+ );
mockSearchParams.set("state", "next:https://evil.example");
render(<CallbackPage />);
await waitFor(() => {
- expect(mockPush).toHaveBeenCalledWith(paths.newWorkspace());
+ expect(mockPush).toHaveBeenCalled();
});
expect(mockPush).not.toHaveBeenCalledWith("https://evil.example");
});
- it("honors a safe next= target (e.g. /invite/{id})", async () => {
+ it("onboarded user honors a safe next= target (e.g. /invite/{id})", async () => {
+ mockLoginWithGoogle.mockResolvedValue(
+ makeUser({ onboarded_at: "2026-01-01T00:00:00Z" }),
+ );
mockSearchParams.set("state", "next:/invite/abc123");
render(<CallbackPage />);
diff --git a/apps/web/app/auth/callback/page.tsx b/apps/web/app/auth/callback/page.tsx
index 4af77afea2..a6a44a4fb2 100644
--- a/apps/web/app/auth/callback/page.tsx
+++ b/apps/web/app/auth/callback/page.tsx
@@ -5,7 +5,7 @@ import { useSearchParams, useRouter } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
import { sanitizeNextUrl, useAuthStore } from "@multica/core/auth";
import { workspaceKeys } from "@multica/core/workspace/queries";
-import { paths } from "@multica/core/paths";
+import { paths, resolvePostAuthDestination } from "@multica/core/paths";
import { api } from "@multica/core/api";
import {
Card,
@@ -62,18 +62,17 @@ function CallbackContent() {
} else {
// Normal web flow
loginWithGoogle(code, redirectUri)
- .then(async () => {
+ .then(async (loggedInUser) => {
const wsList = await api.listWorkspaces();
qc.setQueryData(workspaceKeys.list(), wsList);
- // URL is now the source of truth for the current workspace — the
- // [workspaceSlug]/layout syncs stores + cookie once we navigate.
- // Honor ?next= first (e.g. came from /invite/{id}), otherwise land
- // in the first workspace's issues, or /workspaces/new for zero-workspace users.
- const [first] = wsList;
- const defaultDest = first
- ? paths.workspace(first.slug).issues()
- : paths.newWorkspace();
- router.push(nextUrl || defaultDest);
+ const onboarded = loggedInUser.onboarded_at != null;
+ if (!onboarded) {
+ router.push(paths.onboarding());
+ return;
+ }
+ router.push(
+ nextUrl || resolvePostAuthDestination(wsList, onboarded),
+ );
})
.catch((err) => {
setError(err instanceof Error ? err.message : "Login failed");
diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx
index 39573a3951..389057d389 100644
--- a/apps/web/app/layout.tsx
+++ b/apps/web/app/layout.tsx
@@ -1,5 +1,5 @@
import type { Metadata, Viewport } from "next";
-import { Inter, Geist_Mono } from "next/font/google";
+import { Inter, Geist_Mono, Source_Serif_4 } from "next/font/google";
import { ThemeProvider } from "@/components/theme-provider";
import { Toaster } from "@multica/ui/components/ui/sonner";
import { cn } from "@multica/ui/lib/utils";
@@ -39,6 +39,23 @@ const geistMono = Geist_Mono({
variable: "--font-mono",
fallback: ["ui-monospace", "SFMono-Regular", "Menlo", "Consolas", "monospace"],
});
+// Editorial serif used for onboarding headlines. Italic support for h1 em
+// accents (e.g. "...on one shared board."). Only loaded on routes that
+// render the font; layout-shift-prevention handled by next/font's synthetic
+// fallback metrics, same as Inter.
+const sourceSerif = Source_Serif_4({
+ subsets: ["latin"],
+ style: ["normal", "italic"],
+ variable: "--font-serif",
+ fallback: [
+ "ui-serif",
+ "Iowan Old Style",
+ "Apple Garamond",
+ "Baskerville",
+ "Times New Roman",
+ "serif",
+ ],
+});
export const viewport: Viewport = {
width: "device-width",
@@ -89,7 +106,7 @@ export default function RootLayout({
<html
lang="en"
suppressHydrationWarning
- className={cn("antialiased font-sans h-full", inter.variable, geistMono.variable)}
+ className={cn("antialiased font-sans h-full", inter.variable, geistMono.variable, sourceSerif.variable)}
>
<body className="h-full overflow-hidden">
<LocaleSync />
diff --git a/apps/web/features/landing/components/redirect-if-authenticated.tsx b/apps/web/features/landing/components/redirect-if-authenticated.tsx
index 8572355bbd..2337e8ca46 100644
--- a/apps/web/features/landing/components/redirect-if-authenticated.tsx
+++ b/apps/web/features/landing/components/redirect-if-authenticated.tsx
@@ -5,7 +5,7 @@ import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { useAuthStore } from "@multica/core/auth";
import { workspaceListOptions } from "@multica/core/workspace";
-import { paths } from "@multica/core/paths";
+import { resolvePostAuthDestination, useHasOnboarded } from "@multica/core/paths";
/**
* Client-side fallback redirect for authenticated visitors on the landing page.
@@ -16,7 +16,7 @@ import { paths } from "@multica/core/paths";
* login* — before the user has ever visited a workspace — the cookie is
* absent, so the proxy falls through to the landing page. This component
* covers that gap: once auth is resolved and the workspace list has loaded,
- * push the user into their workspace (or /workspaces/new if they have none).
+ * push the user into their workspace (or /onboarding if they have none).
*
* Renders nothing. Uses `router.replace` so the landing page never enters
* browser history for authenticated users.
@@ -25,21 +25,17 @@ export function RedirectIfAuthenticated() {
const router = useRouter();
const user = useAuthStore((s) => s.user);
const isLoading = useAuthStore((s) => s.isLoading);
+ const hasOnboarded = useHasOnboarded();
- const { data: list } = useQuery({
+ const { data: list = [], isFetched } = useQuery({
...workspaceListOptions(),
enabled: !!user,
});
useEffect(() => {
- if (isLoading || !user || !list) return;
- const [first] = list;
- if (!first) {
- router.replace(paths.newWorkspace());
- return;
- }
- router.replace(paths.workspace(first.slug).issues());
- }, [isLoading, user, list, router]);
+ if (isLoading || !user || !isFetched) return;
+ router.replace(resolvePostAuthDestination(list, hasOnboarded));
+ }, [isLoading, user, isFetched, list, hasOnboarded, router]);
return null;
}
diff --git a/apps/web/test/helpers.tsx b/apps/web/test/helpers.tsx
index 63abda8517..60148302e9 100644
--- a/apps/web/test/helpers.tsx
+++ b/apps/web/test/helpers.tsx
@@ -9,6 +9,11 @@ export const mockUser: User = {
name: "Test User",
avatar_url: null,
+ onboarded_at: "2026-01-01T00:00:00Z",
+ onboarding_questionnaire: {},
+ // Matches real server behavior for anyone who onboarded before this
+ // field shipped — migration 054 backfills 'skipped_legacy'.
+ starter_content_state: "skipped_legacy",
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
};
diff --git a/docs/onboarding-redesign-proposal.md b/docs/onboarding-redesign-proposal.md
new file mode 100644
index 0000000000..7704be15b9
--- /dev/null
+++ b/docs/onboarding-redesign-proposal.md
@@ -0,0 +1,611 @@
+# Onboarding 重新设计 — 项目提案
+
+**日期**:2026-04-21
+**作者**:Naiyuan
+**状态**:方案定稿,待评审后进入执行
+
+---
+
+## 一、为什么要做
+
+### 1.1 数据层面的两个漏斗
+
+当前产品数据暴露了两个关键的用户流失点:
+
+1. **第一漏斗**:很多用户创建完 workspace 后,**从未连接本地 daemon**。没有 runtime = 没有 agent = 产品价值归零。这是最严重的漏斗。
+2. **第二漏斗**:连接了 daemon 的用户中,**约一半从未创建 issue**。他们跨过了最难的技术门槛,却倒在了空 issue 列表面前——因为"该让 agent 做什么"对新用户并不直观。
+
+这两个漏斗说明:**我们把用户送到了门口,但没有送他们进门**。
+
+### 1.2 当前 Onboarding 的不足
+
+代码层面现状(`packages/views/onboarding/` + `apps/web/app/(auth)/onboarding/page.tsx` + `apps/desktop/src/renderer/src/components/window-overlay.tsx`):
+
+| 环节 | 现状 | 问题 |
+|---|---|---|
+| Welcome | 纯打招呼 + "Get started" 按钮 | 0 价值、+1 次点击、文案"takes about a minute"对 web 用户不诚实 |
+| Workspace 创建 | 复用 `CreateWorkspaceForm` | ✅ 基本合理,保留 |
+| Runtime 连接 | Desktop 静默、Web 显示 CLI 指南 | ✅ 机制对,但 web 体验上**一路走到第 3 步才撞上 CLI 这堵墙**,没有提前分流 |
+| Agent 创建 | 2 个模板(Master / Coding)+ 手填 name | Master 模板对 96% 的 solo 用户是噪音;手填 name 是多余决策;没有 Assistant 这种零门槛兜底 |
+| Complete | 仪式感庆祝 + "Enter workspace" | **aha moment 没发生**。用户被告知 agent 准备好,却看不到它工作,进去就是空 issue 列表——正好是第二漏斗 |
+| 个性化 | 无 | 所有用户看到同一套流程,不利用任何已知信息 |
+| 进度持久化 | `useHasOnboarded()` 硬编码 `false` | 中途退出会从头开始;跨端切换完全无法恢复 |
+
+### 1.3 行业对标
+
+调研多篇一线案例和数据后,业界已收敛到几条硬原则:
+
+- **激活 > 教育**:Onboarding 唯一的 KPI 是用户到达 aha moment 的速度和比例。Slack 的 "2000 条消息 → 留存 93%" 是最经典案例
+- **2 分钟到首次价值**:通用 SaaS 目标
+- **<90 秒 TTFAC**:Stripe / Vercel 为开发者工具设定的标杆
+- **开发者工具转化率天然低**:通用 SaaS 试用转化 15–25%,开发者工具只有 8–15%,**68% 放弃原因是 setup 太复杂**
+- **问卷是杀手**:每多一个表单字段完成率下降 3–5%,某 case 强制问卷导致转化率下降 80%+,另一 case 6→3 题响应率 +11%
+- **Progressive disclosure 淘汰前置大 tour**:学习应该分散在使用过程中,不是一次性塞给用户
+- **Notion 模式是黄金范本**:1 题驱动模板选择 + 邮件路径 + 界面预览——"一题多用"
+
+### 1.4 对标 Multica 的定位
+
+Multica 不是"做一个 agent"的产品。它的核心价值是**把一支由用户编排的 AI agent 小队组织起来协作**——一个 agent 写代码、一个规划任务、一个做研究、一个写内容——每个 agent 是带配置(provider / runtime / instructions / skills)的独立工作者,像同事一样被指派 issue。
+
+这意味着:
+- 用户不是单一场景("AI 帮我写代码"),而是多角色用户都在编排 agent:开发者、产品 / 项目负责人、writer、founder
+- "用户在用什么本地 CLI"是 daemon 自动探测的技术事实(`claude` / `codex` / `opencode` / `openclaw` / `hermes` / `gemini` / `pi` / `cursor-agent` 扫 PATH 即可),**不需要问用户**
+- 真正值得问的是**用户是谁、想让 agent 干什么**——这个答案驱动 Step 4 模板、Step 5 first issue 和 Onboarding Project 的内容
+
+---
+
+## 二、调研结论与核心原则
+
+- 主流程必须严格以激活为目的——Welcome、功能介绍、问卷这些"非激活"内容都要极限压缩或后置
+- 问卷题数 ≤3 题,且每题答案必须能直接改变下游某个屏的内容,否则砍掉
+- "Onboarding Project + sub-issues" 属于**教育载体**,不是 onboarding 主流程——它应该在 aha moment 发生后以侧边栏常驻形式出现
+- Web 不应该是 desktop 的"平行路径",而应该是**漏斗入口**:鼓励用户下载 desktop,保留 web+CLI 作为备选
+- 进度必须后端持久化,跨端 resume 是硬要求
+
+主要 Sources 列在文末第八节。
+
+---
+
+## 三、方案要点
+
+### 3.1 主流程:5 步(严格有序)
+
+```
+Step 0: Welcome (产品介绍, 首次进入时展示, 不入后端 state)
+Step 1: 3-Q 问卷 (team_size / role / use_case)
+Step 2: 创建 workspace
+Step 3: 连接 runtime ← 两端最大差异在这一步
+Step 4: 创建 agent ← 按 Q1 × Q3 预填
+Step 5: 🎯 First Issue ← aha moment,按 Q3 驱动文案
+```
+
+**Onboarding Project** 在 Step 5 完成的那一刻后台创建,作为进入 workspace 之后的侧边栏常驻项——**不算 onboarding 的一步**。
+
+### 3.2 两端差异表
+
+| Step | Desktop | Web |
+|---|---|---|
+| 1. 问卷 | 一屏 3 题 | 一屏 3 题(完全一致) |
+| 2. Workspace | `CreateWorkspaceForm` | 完全一致 |
+| 3. Runtime | **静默自动**:bundled daemon 1–2s 内 online → 直接跳 Step 4。只在失败时显示诊断 | **分流决策屏**(见 3.3) |
+| 4. Agent | 一键 Create(按 Q1×Q3 预填模板 + provider) | 完全一致 |
+| 5. First issue | 跳到 issue 详情页,观察 agent reply | 完全一致 |
+
+唯一真正不同的是 Step 3。其他"差异"本质是问卷答案驱动的个性化,跨端一致。
+
+### 3.3 Web 端 Step 3 分流屏
+
+这是 web 用户创建完 workspace 后看到的屏,**取代当前直接展示 CLI install 指南的做法**:
+
+```
+┌─────────────────────────────────────────────┐
+│ Multica runs on your machine │
+│ Agents need a local runtime to run. │
+│ How would you like to set up? │
+│ │
+│ ┌───────────────────────────────────────┐ │
+│ │ [Primary CTA, 80% 视觉权重] │ │
+│ │ ⬇ Download for macOS (recommended) │ │
+│ │ Fastest setup, bundled runtime │ │
+│ └───────────────────────────────────────┘ │
+│ │
+│ Or: Continue on web with CLI │
+│ Or: I want cloud agents (join waitlist) │
+└─────────────────────────────────────────────┘
+```
+
+三条路径:
+
+- **下载桌面端(默认,目标 60%+)**:点下载 → 写 `platform_preference: "desktop"` → 桌面端装完登录同账号 → 后端 state 触发跳 Step 3 → bundled daemon 1s pass → 进 Step 4
+- **CLI 继续(次选)**:保留现有 `CliInstallInstructions`,但新增预期管理("通常 2–4 分钟")和 60s stuck-state fallback("Stuck? 常见问题")
+- **Cloud waitlist(soft exit)**:邮箱 capture → 标记为"临时完成"(`onboarded_at` 写当前时间,保留 `cloud_waitlist_email`)→ 进 workspace + 顶部 banner
+
+### 3.4 三个问题的设计
+
+**Q1:Who will use this workspace?**(单选)
+- ○ Just me
+- ○ My team (2–10 people)
+- ○ Other ⇒ 展开 80 字符文本框
+
+注意:删掉了"Just exploring for now"——它本质是"态度"而不是"人数结构",和这题的题意不契合;评估型用户如果真的选项都不合适,可以通过 Other 写自由文本("just trying it out" 等)表达。
+
+**Q2:What best describes you?**(单选)
+- ○ Software developer
+- ○ Product / project lead
+- ○ Writer or content creator
+- ○ Founder / solo operator
+- ○ Other ⇒ 展开 80 字符文本框
+
+**Q3:What do you want to do first?**(单选)
+- ○ Write and ship code
+- ○ Plan and manage projects
+- ○ Research or write
+- ○ Just explore what's possible
+- ○ Other ⇒ 展开 80 字符文本框
+
+**提交策略(必答)**:
+- Continue 按钮只在**三题全部有具体选择**时启用;否则禁用
+- 任一问题选了 Other 但文本框为空 → 也禁用
+- 从 Other 切回其他选项 → 对应的 `*_other` 字段自动清空
+- **没有 Skip 路径**。理由:三个答案驱动 Step 4 agent template、Step 5 first-issue prompt、Onboarding Project sub-issue 排序;partial 答案会在下游每一步都留洞。Other 自由文本(+ 80 字符上限)已经兜住所有非典型用户,不需要再开 null 这个口子
+- 之前允许"全部不选 Skip"的策略在 commit 中已反悔——实测下来"给自由 = 问卷质量塌方"的风险比"多一点摩擦"更值得警惕
+
+**"Other" 的下游价值——不是兜底,是 escape hatch + 个性化输入**
+
+Q3 的 `use_case_other` 会**直接嵌入到 Step 5 first issue 的 prompt** 里:
+
+> "Hi, I'm {user}. I told Multica I want to use you for \"{use_case_other}\". Introduce yourself and give me 3 concrete ways you could help with that."
+
+也就是说,选 Other 的用户**反而**得到最个性化的 first issue——他们给 agent 的任务描述就是他们亲口写的。Q2 `role_other` 没有同样的嵌入位置,但会存进 state 给市场研究用。
+
+**被砍掉的问题及理由**:
+
+- ~~"你在用哪些 AI agent?"~~(原方案 Q1)→ daemon 启动时自动扫 PATH 探测已安装的 CLI(`claude` / `codex` / `opencode` / `openclaw` / `hermes` / `gemini` / `pi` / `cursor-agent`),比问用户更准——用户可能说"我用 Claude Code"但 PATH 里并不存在。从"问"改成"测",问卷压掉一题
+- ~~"你是做什么的"(职业)~~ → 原方案砍掉过;现因为定位校准(Multica 不是 coding-focused 产品),重新作为 Q2 加回,驱动 agent template 选择
+- ~~"公司规模"~~ → solo/team 二分已经够用;具体公司规模属于 Day 3 邮件采集范围
+- ~~"从哪里知道 Multica"~~ → 归因数据走分析系统,不占问卷位
+
+### 3.5 个性化映射
+
+所有个性化来自这三个答案 + daemon 自动探测到的 runtime 列表。**不做 Q 之外的任何猜测**——透明、可预期、可调试。
+
+#### Runtime 优先级(来自 daemon 探测,不来自问卷)
+
+Step 3 结束时 daemon 会报告"当前 PATH 上探测到的 CLI 列表"。Step 4 的 provider 预选逻辑:
+
+| daemon 探测结果 | Step 4 provider 预选 |
+|---|---|
+| 有 online runtime | 第一个 online 的 provider |
+| 列表非空但全 offline | 列表中第一个 |
+| 列表为空(Cloud waitlist 或 CLI 没装成功) | 不预选,在 Step 4 给用户手选或跳过 |
+
+provider 值对齐 `packages/views/runtimes/components/provider-logo.tsx` 中已支持的:`claude` / `codex` / `opencode` / `openclaw` / `hermes` / `gemini` / `pi` / `cursor`。
+
+#### Q1 (team_size) → Onboarding Project sub-issue 排序
+
+| Q1 | Onboarding Project 顶部 sub-issue |
+|---|---|
+| `solo` | "Assign a real task to your agent" |
+| `team` | **"Invite teammates"** 置顶 |
+| `other` | 按 `solo` 路径处理(不强行归类;`team_size_other` 文本存下做市场研究) |
+
+#### Q2 (role) → Step 4 agent template 默认选择(× Q3 细化)
+
+Multica 是服务多角色 agent 编排用户的平台,不同 role 在 agent template 上应该看到默认的 role-matched 模板:
+
+| Q2 role | Q3 use_case | 默认 template |
+|---|---|---|
+| `developer` | `coding` | Coding Agent |
+| `developer` | `planning` | Planning Agent |
+| `developer` | `writing_research` / `explore` / `other` | Coding Agent(仍默认,因为角色是开发者) |
+| `product_lead` | `coding` | Coding Agent |
+| `product_lead` | `planning` | Planning Agent |
+| `product_lead` | `writing_research` / `explore` / `other` | Planning Agent |
+| `writer` | `writing_research` | Writing Agent |
+| `writer` | 其他 | Writing Agent |
+| `founder` | 任意 | Assistant(founder 什么都干,通用兜底) |
+| `other` | 任意 | Assistant |
+
+**Agent 模板集从 3 个扩到 4 个**:Coding Agent / Planning Agent / **Writing Agent(新增)** / Assistant。砍掉旧的 "Master Agent"(对 solo 用户完全不适用)。Writing Agent 的增加是因为产品定位校准——原方案默认 coding-focused,新方案支持 writer 作为一等用户。
+
+#### Q3 (use_case) → Step 5 first issue prompt
+
+First issue 的标题和 prompt 都由 Q3 单独驱动(与 Q2 role 解耦——同一个 role 做不同的 first task 是正常的):
+
+| Q3 | First Issue 标题 | First Issue 描述(= 给 agent 的 prompt) |
+|---|---|---|
+| `coding` | "Welcome me and show me what you can do" | "Hi, I'm {user}. I'll use you mostly for coding work. Introduce yourself and suggest 3 concrete coding tasks I could try." |
+| `planning` | "Help me plan my first project" | "Hi, I'm {user}. I want you to help me plan and break down work. Introduce yourself and suggest 3 types of projects we could tackle." |
+| `writing_research` | "Show me how you help with research and writing" | "Hi, I'm {user}. I'll use you for research and writing. Introduce yourself and give me 3 examples of how you can help — drafting, summarizing, analysis, etc." |
+| `explore` | "What can you do?" | "Hi. I'm exploring what Multica can do. Give me a quick tour of what you can help with and suggest 3 concrete things to try." |
+| `other` | "Help me with what I had in mind" | "Hi, I'm {user}. I told Multica I want to use you for \"{use_case_other}\". Introduce yourself and give me 3 concrete ways you could help with that." |
+
+`{use_case_other}` 的嵌入是 Other 选项的关键价值——选 Other 的用户不是被降级成通用兜底,反而得到最精准的 first issue。
+
+### 3.6 Onboarding Project 设计
+
+Project 名称:"Getting Started"。在 Step 5 完成那一刻后台创建,包含以下 sub-issues。
+
+**Core sub-issues(所有用户都有)**:
+
+1. **"Chat with your agent without creating an issue"**
+ > Some tasks are quick back-and-forth — you don't need a full issue. Open the chat panel from the top-right and try asking your agent a question.
+
+2. **"Assign a real task to your agent"**
+ > You've seen your agent reply in this welcome issue. Now try assigning them something you actually need done. Create a new issue, describe the task, assign it to {agent_name}.
+
+3. **"Write your Workspace Context"**
+ > Workspace Context is the shared system prompt every agent in this workspace sees. Tell them who you are, what you're building, and how they should behave. Go to Workspace settings → Context.
+
+4. **"Create a second agent with a different role"**
+ > Multica's real power is running a small team of specialized agents. Create a Planning agent to complement your Coding agent, or a Writing agent to draft content. Go to Agents → "New agent".
+
+5. **"Configure your agent's skills"**
+ > Skills let you give your agent specific tools and capabilities. Go to your agent's settings and try toggling a skill.
+
+6. **"Set up an Autopilot for recurring work"**
+ > Autopilot creates issues on a schedule — daily standup summaries, weekly bug triage, monthly reports. Your agent picks them up automatically. Go to Autopilots → "New autopilot".
+
+**Conditional sub-issues**(按答案插入 / 置顶 / 过滤):
+
+- **Q1 = `team`** → "**Invite your teammates**" 置顶
+- **Q2 = `developer`** 或 **Q3 = `coding`** → "**Connect a repo to your workspace**" 加入 core #2 之后
+- **Q2 = `product_lead`** → "**Create a project with sub-issues**" 置顶
+- **Q2 = `writer`** → 跳过 "Connect a repo"(coding-specific),其余 core 保留
+- **runtime 列表为空**(Cloud waitlist 或 CLI 未装成功)→ 插入 "**Install your first local runtime**" 置顶
+
+**设计原则**:每个 sub-issue 都可以直接 assign 给 agent。Agent 读到 description 后,用自然语言给用户一句引导 + 一个具体建议。这样 sub-issue 既是"教程"又是"和 agent 互动"的自然场景——学习动作本身就是使用产品。
+
+### 3.7 Resume 策略
+
+**核心原则**:恢复到上次 step,不重头开始,MVP 阶段不设过期时间,允许任意回退改答案。
+
+理由:
+- Onboarding 总时长 <10 分钟,绝大多数用户一口气走完
+- 中途离开再回来的,基本都是被别的事打断——重头开始是侮辱
+- 过期策略(7 天后重置之类)是用代码解决还没发生的问题——**等真观察到 abandon-return 模式再加**
+
+跨端 resume 的完整行为表:
+
+| 场景 | 预期行为 |
+|---|---|
+| Web 完成 Step 1&2,关浏览器,2h 后重开 web | 读 state → 跳过 Step 1/2 → 直接 Step 3 |
+| Web 到 Step 3 点"下载桌面端",装完登录 desktop | Desktop 读 state → 跳 Step 3 → bundled daemon 1s pass → 进 Step 4 |
+| Web 到 Step 3 点"下载桌面端",没装,3 天后回 web | 检测到 `platform_preference=desktop` 但当前是 web → 显示 "Waiting for you on desktop" 屏 + "改用 web/CLI 继续" 入口 |
+| Desktop Step 5 first issue 刚创建但没看 agent reply 就关闭 | 重开 desktop → current_step 仍是 `first_issue` → 直接打开那个 issue 详情页 |
+| Onboarding 完成后再登录 | `onboarded_at` 非 null → 跳过 onboarding → 正常进 workspace |
+| Onboarding 中创建的 workspace 被删(边缘 case) | `workspace_id` 变 NULL → 下次进 onboarding 检测到 `current_step=runtime` 但 `workspace_id=null` → 回退到 Step 2 重新建 |
+
+**"回退改答案" 的 UX 细节**:每一步有 "Back" 按钮回上一步。回退**不清空已保存的数据**——用户只是修改,不是重置。
+
+---
+
+## 四、后端数据设计
+
+### 4.1 `user_onboarding` 表 schema
+
+**设计决策**:稳定字段用列,灵活字段用 JSONB。问卷答案放 JSONB(题目可能演化),其他字段(FK、控制字段、enum)都是独立列。
+
+```sql
+CREATE TABLE user_onboarding (
+ user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
+
+ -- 控制状态
+ started_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ onboarded_at TIMESTAMPTZ, -- null = 未完成
+ current_step TEXT, -- null after onboarded_at
+ -- 'questionnaire'|'workspace'|'runtime'|'agent'|'first_issue'
+
+ -- 问卷答案(会演化,放 JSONB)
+ questionnaire JSONB NOT NULL DEFAULT '{}'::jsonb,
+ -- 期望结构:
+ -- {
+ -- "team_size": "solo" | "team" | "other", -- Q1
+ -- "team_size_other": "<= 80 chars" | null, -- Q1 自由文本(选 other 时必填)
+ -- "role": "developer" | "product_lead" | "writer" | "founder" | "other", -- Q2
+ -- "role_other": "<= 80 chars" | null, -- Q2 自由文本
+ -- "use_case": "coding" | "planning" | "writing_research" | "explore" | "other", -- Q3
+ -- "use_case_other": "<= 80 chars" | null -- Q3 自由文本(会嵌入 Step 5 prompt)
+ -- }
+
+ -- Onboarding 产物(FK,要 join / 查询)
+ workspace_id UUID REFERENCES workspaces(id) ON DELETE SET NULL,
+ runtime_id UUID REFERENCES agent_runtimes(id) ON DELETE SET NULL,
+ agent_id UUID REFERENCES agents(id) ON DELETE SET NULL,
+ first_issue_id UUID REFERENCES issues(id) ON DELETE SET NULL,
+ onboarding_project_id UUID REFERENCES projects(id) ON DELETE SET NULL,
+
+ -- Platform 偏好(决定 handoff 和 resume 行为)
+ platform_preference TEXT, -- 'web' | 'desktop' | null
+
+ -- Cloud waitlist 支路(soft exit 记录)
+ cloud_waitlist_email TEXT,
+
+ -- 约束
+ CONSTRAINT current_step_valid CHECK (
+ current_step IS NULL OR
+ current_step IN ('questionnaire','workspace','runtime','agent','first_issue')
+ ),
+ CONSTRAINT onboarded_clears_step CHECK (
+ onboarded_at IS NULL OR current_step IS NULL
+ )
+);
+
+-- 只对未完成的做 index(完成后不查),analytics 用
+CREATE INDEX idx_user_onboarding_incomplete
+ ON user_onboarding (updated_at)
+ WHERE onboarded_at IS NULL;
+```
+
+**几个关键决策的理由**:
+
+- **`ON DELETE SET NULL`** 而不是 CASCADE:用户手动删了 onboarding 中创建的 workspace,不应丢失整条 onboarding 记录。保留痕迹作为 analytics 信号,同时支持 3.7 表中"回退到 Step 2" 的自愈逻辑
+- **`onboarded_clears_step` 约束**:保证不会出现"已完成但还在某 step"的脏状态,发现非法组合直接 DB 层拒绝
+- **Partial index `WHERE onboarded_at IS NULL`**:绝大多数用户最终会完成,索引只关注未完成 cohort,省空间且 query 更快
+- **不存步骤时间戳历史**:步骤转化漏斗走 PostHog 事件系统(项目里 agent/j/db4fefb5 分支已经在做 analytics 基建);state 表负责流程控制,事件系统负责分析。分工清晰,不混
+
+### 4.2 API 设计
+
+**读**:
+```
+GET /api/me/onboarding
+→ 200 OK { current_step, questionnaire, workspace_id, ... }
+→ 404 if never started (客户端 treat as "start fresh")
+```
+
+**写(每步结束时)**:
+```
+PATCH /api/me/onboarding
+Body: {
+ current_step: "workspace", // 下一步
+ questionnaire: { ... }, // 只在 Step 1 提交
+ workspace_id: "ws_xxx", // 只在 Step 2 提交
+ // ... 对应字段
+}
+→ 200 OK { 完整 state }
+```
+
+**完成**:
+```
+POST /api/me/onboarding/complete
+Body: { first_issue_id, onboarding_project_id }
+→ 200 OK { onboarded_at, current_step: null }
+```
+
+**关键**:每步结束立即 PATCH server。不要在前端 batch 到最后一起提交——这是 resume 能工作的前提。
+
+### 4.3 State 流转
+
+```
+状态机:
+ (record not exists)
+ ↓ 用户首次进 onboarding
+ current_step: "questionnaire"
+ ↓ PATCH 提交问卷
+ current_step: "workspace" + questionnaire
+ ↓ PATCH 工作区创建成功
+ current_step: "runtime" + workspace_id
+ ↓ PATCH runtime 选择
+ current_step: "agent" + runtime_id
+ ↓ PATCH agent 创建
+ current_step: "first_issue" + agent_id
+ ↓ POST /complete
+ current_step: null + onboarded_at, first_issue_id, onboarding_project_id
+
+支路(Cloud waitlist):
+ current_step: "runtime"
+ ↓ 用户选 cloud waitlist
+ current_step: null + onboarded_at + cloud_waitlist_email
+```
+
+---
+
+## 五、当前代码影响面
+
+### 5.1 后端(Go)
+
+**新增**:
+- Migration:`server/migrations/0xx_create_user_onboarding.up.sql` + `.down.sql`
+- sqlc queries:`server/pkg/db/queries/onboarding.sql`(GetOnboarding / UpsertOnboarding / CompleteOnboarding)
+- Handler:`server/internal/handler/onboarding.go`(GET / PATCH / POST)
+- Router 挂载:`/api/me/onboarding` 路由组
+- 可能需要:`GetUserOnboarding` 也需暴露给认证回调决定重定向(或前端自取)
+
+**迁移 sqlc**:`make sqlc` 重生成。
+
+### 5.2 前端(TypeScript / React)
+
+**新增**:
+- `packages/core/onboarding/types.ts` — `OnboardingState` 类型定义
+- `packages/core/onboarding/queries.ts` — TanStack Query options
+- `packages/core/onboarding/mutations.ts` — advance / complete mutation
+- `packages/views/onboarding/steps/step-welcome.tsx` — 产品介绍屏(首次进入时展示;回访自动跳过)
+- `packages/views/onboarding/steps/step-questionnaire.tsx` — 3 题问卷屏
+- `packages/views/onboarding/steps/step-platform-fork.tsx` — web Step 3 的分流屏
+- `packages/views/onboarding/steps/step-first-issue.tsx` — **关键**,aha moment 所在
+- 可能拆分 `packages/views/onboarding/utils/personalization.ts` — Q1/Q2/Q3 → 下游映射的纯函数(方便单测)
+
+**需要改动的现有文件**:
+- `packages/views/onboarding/onboarding-flow.tsx` — 移除本地 `useState<OnboardingStep>`,改读 `useOnboardingStore`;每次 step 转换调 `advance` mutation
+- `packages/views/onboarding/steps/step-welcome.tsx` — **删除**,内容合并到新的 step-questionnaire
+- `packages/views/onboarding/steps/step-runtime.tsx` — web 分支改为渲染 `<StepPlatformFork />`
+- `packages/views/onboarding/steps/step-agent.tsx` — 模板集改为 Coding / Planning / Writing / Assistant,按 Q2×Q3 预填,新增"Advanced"折叠区让用户改 name
+- `packages/views/onboarding/steps/step-complete.tsx` — **替换**为 StepFirstIssue,或作为其前置过渡屏
+- `packages/core/paths/resolve.ts` — `useHasOnboarded` 当前已从 store 读;联调期替换为 TanStack Query against `GET /api/me/onboarding`
+- `packages/views/layout/use-dashboard-guard.ts` — guard 条件增加 `!hasOnboarded`,支持 "abandon 后回来自动回到 onboarding" 的 resume 行为
+- `apps/web/app/(auth)/onboarding/page.tsx` — 调整 shell 以支持 resume(读 state 决定进入哪一步)
+- `apps/desktop/src/renderer/src/components/window-overlay.tsx` — 同上
+- `apps/desktop/src/renderer/src/stores/window-overlay-store.ts` — 可能需要 `WindowOverlay` 类型微调
+
+**不变**:
+- `packages/views/workspace/create-workspace-form.tsx` — 复用
+- `packages/views/onboarding/steps/cli-install-instructions.tsx` — 仍用,在 CLI 分支里渲染
+- 大部分 desktop 的 bundled daemon 启动逻辑 — Step 3 desktop 静默 pass 的前提
+
+### 5.3 影响面估算
+
+| 类别 | 数量 |
+|---|---|
+| 后端新文件 | ~4 |
+| 后端修改文件 | 1–2(router) |
+| 前端新文件 | ~6 |
+| 前端修改文件 | ~10 |
+| 测试新文件 | ~5(核心逻辑 + personalization 映射 + resume scenarios) |
+
+---
+
+## 六、成功指标(上线 30 天内评估)
+
+参考调研结论设定:
+
+| 指标 | 业界标杆 | Multica 目标 |
+|---|---|---|
+| Time-to-value | < 3 分钟 | Desktop 直达:≤ 3 min;Web→Desktop:≤ 5 min(含装机);Web→CLI:≤ 8 min |
+| Onboarding 完成率 | 60–80% | 目标 70% |
+| Day 7 留存 | 25–40% | 目标 30% |
+| Activation 率 | 40–60% | 目标 50% |
+| Web→Desktop 转化(Step 3 fork) | in-product 高于 42% 冷推上限 | 目标 50–70% |
+
+**第一漏斗目标**:workspace → runtime 连接率从当前水平提升至 80%+(主要靠 web 分流推 desktop 降 CLI 门槛)。
+**第二漏斗目标**:runtime → 首个 issue 由产品主动创建,比例应接近 100%(因为 StepFirstIssue 自动完成这件事)。
+
+---
+
+## 七、已做的决策(不再讨论)
+
+| 决策 | 选择 | 理由 |
+|---|---|---|
+| 前置问卷题数 | **3 题**:team_size / role / use_case | Notion 范式、调研甜蜜点;每题答案必须驱动下游内容 |
+| 问卷 Q1 "已在用哪些 agent" | **不问**,daemon 自动探测 PATH | 技术事实不该问用户;扫 PATH 比问答更准 |
+| 问卷 Q2 role | **问**,5 个具体选项 + Other | 驱动 Step 4 template 默认选择;用户画像数据回到一等位 |
+| "Other" 选项机制 | **每题都有 Other**,点击展开 80 字符文本框 | Escape hatch;Q3 use_case_other 还会嵌入 Step 5 first issue prompt |
+| 问卷必填 | **全可选**(Other 选了必填文本) | 给评估型用户零摩擦通道;0 选时 Continue 变 Skip |
+| Welcome 步骤 | **保留独立 welcome**,但改造为"产品介绍屏"(不是打招呼);只在首次进入时看到,回访 resume 自动跳过 | 多一次点击换来的是首次用户真正理解 Multica 是什么;Multica 无心智对标物,没有前置介绍就进问卷 = 用户没有 frame of reference;Welcome 不入后端 state,不影响 server schema |
+| Web Step 3 分流 | **默认推 desktop**,CLI 次选,cloud waitlist 兜底 | 96% 是个人用户,desktop 是最快路径 |
+| Cloud waitlist 放哪 | **Web Step 3 分流屏**,不作为主步骤 | 保留原方案 #3 的数据价值,但不侵占主流程 |
+| Agent 模板 | **4 个**:Coding / Planning / Writing / Assistant(砍 Master) | Multica 服务多角色 agent 编排用户;Writer 不能被 Assistant 兜底 |
+| Onboarding Project | **不算步骤**,Step 5 完成后台创建,侧边栏常驻 | Progressive disclosure 原则 |
+| Resume 策略 | **恢复到上次 step,不过期,允许回退改答案** | 未见 abandon-return 数据前不提前优化 |
+| Schema 方式 | **专门表 + JSONB 混合** | 稳定字段列化、灵活字段(问卷)JSON 化 |
+| FK 删除行为 | **ON DELETE SET NULL**,不 CASCADE | 保留 analytics 痕迹 + 自愈能力 |
+| 步骤时间戳 | **走 PostHog 事件系统**,不进 state 表 | 职责分离:state 管流程,events 管分析 |
+| 进度 handoff 机制 | **纯后端 state**,不用 token 或 deep link | 用户 auth session 已绑身份,简化架构 |
+| 开发顺序 | **前端全部搭完 → 后端实现 → 联调测试 → 上线** | 保持当前开发节奏不被后端阻塞;前端本身可以一个 step 一个 step 独立推进 |
+| State 访问抽象 | **全部走 `useOnboardingStore()` 一个 hook**,component 严禁直接碰 storage | 换后端时只动这一个文件,component 不感知——让"先前端后后端"成本低的关键 |
+
+---
+
+## 八、开放问题 / 不在本次范围
+
+- **Cloud agent runtime 本身**:本次只实现 waitlist 邮箱捕获,不做 cloud runtime。这是下一阶段的产品决策
+- **Onboarding project sub-issue 文案的 iterate**:先上线现有文案(见 3.6),等真实用户反馈再打磨
+- **A/B test 框架**:等用户量达到业界标准(每组 ≥500)再启动,现阶段全量发
+- **个性化 Day 3 邮件**:问卷只问 3 题,剩余的用户画像数据(团队规模、角色等)可以后置到运营邮件收集,本次不实现
+- **Onboarding 完成后的 re-engagement**:如"用户 7 天没创建第 2 个 agent 时发通知",属于 retention loop,不属于 onboarding
+- **自定义 agent template**:当前 3 个硬编码模板够用,自定义模板留到后面
+
+---
+
+## 九、执行计划
+
+### 9.1 详细执行文档
+
+本提案评审通过后,拆出 `docs/plans/2026-04-21-onboarding-redesign.md`,按现有 plan 文档格式(参考 `docs/plans/2026-04-16-remove-onboarding-and-fix-daemon-bootstrap.md`)精确到文件 + 行号 + 代码片段。
+
+### 9.2 执行阶段
+
+**原则:前端全部搭完 → 后端实现 → 联调测试 → 上线。**
+
+目的是让当前开发节奏不被后端阻塞——前端可以一个 step 一个 step 独立迭代,每完成一个 step 都能在浏览器里直接看到效果。后端在前端定稿之后一次性实现,联调阶段统一解决跨端 resume 等场景。
+
+**前端阶段**(按顺序推进,每个 step 独立可交付):
+
+1. **建立 `useOnboardingStore()` 骨架**(已完成)——位于 `packages/core/onboarding/`。dev 期间是内存 Zustand store(刷新重置,方便迭代),联调阶段换成 TanStack Query + PATCH mutation。严禁 component 绕过
+2. **Step 1(welcome + 问卷拆两屏)**:新建 `step-welcome.tsx`(产品介绍,首次进入时展示)+ `step-questionnaire.tsx`(3 题);抽出 `<OptionCard>` / `<OtherOptionCard>` 复用组件
+3. **Step 2(workspace)**:基本保留,接入 `useOnboardingStore()`
+4. **Step 3(runtime)**:在 web 分支里新建 `step-platform-fork.tsx`;desktop 分支保留静默自动;CLI 分支加预期管理和 60s fallback
+5. **Step 4(agent)**:模板集从 3 扩成 4(加 Writing),按 Q2×Q3 预填 template + provider(provider 来自 daemon 探测),移除手填 name 的强制性
+6. **Step 5(first issue)**:新建 `step-first-issue.tsx`,这是 aha moment 发生的地方;`use_case=other` 时把 `use_case_other` 嵌入 prompt
+7. **Flow orchestrator 改造**:`onboarding-flow.tsx` 改由 `useOnboardingStore()` 驱动,不再用本地 useState 管 step 切换
+8. **Web + Desktop shell 适配**:读 store 决定进入哪一步,支持单浏览器内的 resume
+
+**后端阶段**:
+
+9. Migration + sqlc queries + handler + router(API shape 见 4.2)
+10. 按 4.1 schema 实现 `user_onboarding` 表 + partial index + 约束
+
+**联调阶段**:
+
+11. `useOnboardingState()` 实现从 localStorage 切换为 TanStack Query + PATCH mutation——**component 0 改动**,这是 hook 抽象的回报
+12. 跨端 / 多 session resume 全场景验证(3.7 表)
+13. E2E 覆盖 4 类用户路径 + 分流屏三条支路 + resume 一条
+
+建议独立 worktree 开发(参考 `superpowers:using-git-worktrees`),避免污染主 checkout。
+
+### 9.3 测试阶段
+
+**本地自测**(按用户类型逐一跑):
+- A 类:solo + Claude Code + coding → 最短路径 3 分钟
+- B 类:team + Claude Code + coding/planning → 完成后侧边栏 "Invite teammates" 置顶
+- C 类:无 agent + 评估 → web 分流选 cloud waitlist
+- D 类:solo + writing → Assistant 模板 + 对应 first issue 文案
+
+**Resume 场景**(按 3.7 表逐一验证):
+- Web 中途关浏览器 → 重开恢复
+- Web → desktop 跨端 handoff
+- Web 选下载未装 → 回 web 的"waiting"屏
+- 已完成用户重登录 → 跳过 onboarding
+
+**E2E** 测试必须覆盖:
+- 完整 happy path(至少 desktop A 类)
+- Resume 一条
+- 分流屏三条路径各一条
+
+**上线指标监控**:PostHog 看板跟踪第六节定义的 5 个 KPI,上线后每周 review 一次,2 周内若主指标偏离 20%+ 需排查。
+
+---
+
+## 十、调研参考
+
+### 核心理论与激活
+- [Chameleon — How to find your product's "Aha" moment](https://www.chameleon.io/blog/successful-user-onboarding)
+- [Amplitude — The "Aha" Moment: A Guide](https://amplitude.com/blog/aha-moment)
+- [Growth Letter — Slack's $3B Growth Loop](https://www.growth-letter.com/p/slacks-3-billion-growth-strategy)
+- [June.so — Activation Playbook](https://www.june.so/blog/activation-playbook)
+
+### 开发者工具特有数据
+- [Daily.dev — Developer Onboarding Optimization](https://business.daily.dev/resources/developer-onboarding-optimization-from-first-click-to-paying-customer/)
+- [Startup Design Journal — Hidden Micro-Friction Killing Conversion](https://startupdesignjournal.com/p/the-hidden-micro-friction-thats-killing)
+
+### 问卷 / 表单 drop-off
+- [involve.me — 6→3 题 +11% case](https://www.involve.me/blog/case-study-how-we-use-an-onboarding-survey-in-a-saas-product)
+- [SaaSFactor — Why Users Drop Off During Onboarding](https://www.saasfactor.co/blogs/why-users-drop-off-during-onboarding-and-how-to-fix-it)
+- [GrowthMentor — Friction Case Study](https://www.growthmentor.com/blog/user-onboarding-friction/)
+- [Formbricks — Essential Onboarding Survey Questions](https://formbricks.com/blog/onboarding-survey-questions)
+
+### Progressive Disclosure
+- [LogRocket — Progressive Disclosure](https://blog.logrocket.com/ux-design/progressive-disclosure-ux-types-use-cases/)
+- [Pendo — Onboarding, Progressive Disclosure, Memory](https://www.pendo.io/pendo-blog/onboarding-progressive-disclosure/)
+- [Interaction Design Foundation — Progressive Disclosure](https://ixdf.org/literature/topics/progressive-disclosure)
+
+### Notion / Linear 案例
+- [Candu — How Notion Crafts Personalized Onboarding](https://www.candu.ai/blog/how-notion-crafts-a-personalized-onboarding-experience-6-lessons-to-guide-new-users)
+- [Appcues Goodux — Notion's Lightweight Onboarding](https://goodux.appcues.com/blog/notions-lightweight-onboarding)
+- [DesignerUp — 200 Onboarding Flows Studied](https://designerup.co/blog/i-studied-the-ux-ui-of-over-200-onboarding-flows-heres-everything-i-learned/)
+
+### Schema / 持久化
+- [Shekhar Gulati — When to use JSON data type](https://shekhargulati.com/2022/01/08/when-to-use-json-data-type-in-database-schema-design/)
+- [TigerData — Wide vs Narrow Postgres Tables](https://www.tigerdata.com/learn/designing-your-database-schema-wide-vs-narrow-postgres-tables)
+- [DbSchema — PostgreSQL JSONB Operators](https://dbschema.com/blog/postgresql/jsonb-in-postgresql/)
+- [Pravin Tripathi — Start and Resume Journey for Onboarding](https://medium.com/@pravinyo/approaches-for-start-and-resume-journey-for-user-onboarding-to-platform-part-i-e077c73b4cd7)
+
+### A/B 测试 & 分段
+- [Appcues — A/B Testing Onboarding Flows](https://www.appcues.com/blog/flow-variation-a-b-testing)
+- [M Accelerator — A/B Testing Onboarding Guide](https://maccelerator.la/en/blog/entrepreneurship/ultimate-guide-to-ab-testing-onboarding-flows/)
+- [CXL — Segment A/B Test Results](https://cxl.com/blog/segment-ab-test-results/)
+
+### 2025 综合最佳实践
+- [Aakash Gupta — 10 Customer Onboarding Best Practices for PMs 2025](https://www.aakashg.com/customer-onboarding-best-practices/)
+- [ProductLed — SaaS Onboarding Best Practices 2025](https://productled.com/blog/5-best-practices-for-better-saas-user-onboarding)
+- [Branch — Desktop-to-App Conversions](https://www.branch.io/resources/blog/optimizing-desktop-web-to-app-conversions/)
diff --git a/docs/product-overview.md b/docs/product-overview.md
new file mode 100644
index 0000000000..66693bb3bf
--- /dev/null
+++ b/docs/product-overview.md
@@ -0,0 +1,983 @@
+# Multica 产品全景文档
+
+> **文档说明**
+>
+> 这份文档的目的是:**让任何没有写过代码的新同事,在 30 分钟内完全理解 Multica 这个产品到底有哪些功能、每个功能在整体中处于什么位置、一个功能和另一个功能如何协同**。
+>
+> 它的受众包括:
+>
+> - **新加入的工程师 / 产品 / 设计 / 运营**——用它做 onboarding 的第一份材料
+> - **产品介绍工作**——需要对外讲解 Multica 时的事实基础
+> - **文案工作者**——写交互文案、营销文案、帮助文档时,需要知道某个词(比如 "Skill"、"Runtime"、"Autopilot")在产品体系里代表什么
+> - **任何需要在修改某个局部前,先理解它与整体关系的人**
+>
+> 它**不是**:开发者文档、架构决策记录(ADR)、或者销售话术。它是**功能事实的汇总**——每一条描述都能在代码、schema 或 API 里找到对应。
+>
+> 文档基于对整个 monorepo(server、apps、packages、migrations、daemon、CLI)的系统性调研生成,数据截止日期 2026-04-21。
+
+---
+
+## 目录
+
+1. [Multica 是什么](#1-multica-是什么)
+2. [核心概念词典](#2-核心概念词典)
+3. [功能全景(按模块)](#3-功能全景按模块)
+ - 3.1 [Workspace 工作区](#31-workspace-工作区)
+ - 3.2 [Issue 议题管理](#32-issue-议题管理)
+ - 3.3 [Project 项目](#33-project-项目)
+ - 3.4 [Agent 智能体](#34-agent-智能体)
+ - 3.5 [Runtime 运行时 & Daemon 守护进程](#35-runtime-运行时--daemon-守护进程)
+ - 3.6 [Skill 技能](#36-skill-技能)
+ - 3.7 [Autopilot 自动驾驶](#37-autopilot-自动驾驶)
+ - 3.8 [Chat 对话](#38-chat-对话)
+ - 3.9 [Inbox 收件箱与通知](#39-inbox-收件箱与通知)
+ - 3.10 [成员、邀请与权限](#310-成员邀请与权限)
+ - 3.11 [搜索与命令面板](#311-搜索与命令面板)
+ - 3.12 [认证、登录与 Onboarding](#312-认证登录与-onboarding)
+ - 3.13 [设置与个人资料](#313-设置与个人资料)
+ - 3.14 [CLI 命令行工具](#314-cli-命令行工具)
+4. [系统架构全景](#4-系统架构全景)
+5. [产品地图(全部路由)](#5-产品地图全部路由)
+6. [跨平台差异:Web vs 桌面](#6-跨平台差异web-vs-桌面)
+7. [附录:关键数据表速查](#7-附录关键数据表速查)
+
+---
+
+## 1. Multica 是什么
+
+### 一句话定位
+
+**Multica 把编码智能体变成真正的团队成员。**
+
+像给同事分配任务一样,把一个 issue 指派给一个 agent,它会自己认领、写代码、汇报进度、更新状态——不需要你一直守着。
+
+### 解决的问题
+
+传统方式用 AI coding agent 的痛点:
+
+- 每次都要复制粘贴 prompt
+- 必须盯着终端,看它跑不跑得完
+- 没有跨任务的记忆,每次都从零开始
+- 多个 agent 同时工作时,没有一个"看板"能看到全局
+
+Multica 做的事:
+
+- Agent 和人**共用同一个任务看板**(issue board)
+- Agent **有 profile**,会出现在 assignee 下拉里、会在评论区发言、会自己创建 issue
+- 同一个 (agent, issue) 的多轮对话**自动恢复会话**——上一次的上下文、工作目录都保留
+- **Skill 系统**让历史上解决过的问题沉淀成可复用的能力
+- **Autopilot** 让 agent 按定时规则自动开工(比如每天早上 9 点做 bug triage)
+
+### 定位一句话版本
+
+> Multica 不是一个 AI 工具,而是一个**人 + AI 协作的任务管理平台**。agent 是一等公民,和人在同一个工作流里。
+
+### 部署形态
+
+- **云版本(Multica Cloud)**:官方托管服务,agent 通过你本地跑的 daemon 执行
+- **自托管(Self-Host)**:完整后端可以部署在自己的服务器
+- **客户端**:Next.js web 版 + Electron 桌面版(两端体验基本一致,桌面独有:多标签、原生托盘、自动更新)
+
+### 支持的 Coding Agent
+
+Multica **不自己训模型**,也不锁定某一家厂商。它是调度器,本地 daemon 会自动探测以下 CLI 工具并接入:
+
+Claude Code · Codex · OpenClaw · OpenCode · Hermes · Gemini · Pi · Cursor Agent
+
+每个 agent 可以配置自己的模型、API Key、环境变量、MCP 服务器。
+
+---
+
+## 2. 核心概念词典
+
+**理解这些名词是理解产品的前提。每个概念的定义都严格对应数据库表。**
+
+| 概念 | 定义 | 映射的数据表 |
+|------|------|-------------|
+| **User 用户** | 一个人类账号,可以登录,属于多个 workspace | `user` |
+| **Workspace 工作区** | 一切资源的容器。issue、agent、project、skill 全部隔离在 workspace 里。就是 Linear/Notion 里的 workspace/team 概念 | `workspace` |
+| **Member 成员** | 用户在某个 workspace 里的身份。一个用户在不同 workspace 可以有不同角色(owner/admin/member) | `member` |
+| **Agent 智能体** | 可被指派任务的 AI 工作者。有 profile(名字、头像、说明)、会指定 runtime 和 provider、可以配自定义 prompt 和技能 | `agent` |
+| **Runtime 运行时** | Agent 实际跑在哪里的**执行环境**。可以是用户本地机器(通过 daemon)或云端实例。**一个 runtime = 一台可以跑 agent 的机器** | `agent_runtime` |
+| **Daemon 守护进程** | 用户本地运行的后台程序,自动发现已安装的 coding CLI 并注册为 runtime,然后不停轮询 server 认领任务 | (进程,不是表) |
+| **Issue 议题** | 一个工作单元——任务、bug、feature。最核心的产品对象。可以分配给人或 agent | `issue` |
+| **Comment 评论** | Issue 下的讨论回复。人和 agent 都能发。在评论里 `@某个 agent` 会自动触发这个 agent 的新任务 | `comment` |
+| **Task 任务** | Agent 执行一次 issue 所产生的一次运行。本质是"一次 agent 跑起来的会话"。队列化执行 | `agent_task_queue` |
+| **Skill 技能** | 工作区级别的可复用说明文档。作用是给 agent 提供"怎么做某件事"的上下文。Agent 开跑时会把挂载的 skill 内容注入到工作目录让 CLI 能读到 | `skill`, `skill_file`, `agent_skill` |
+| **Project 项目** | 议题的高层归属,类似"里程碑"或"版本"。issue 可以归属到 project | `project` |
+| **Autopilot 自动驾驶** | 定时或被触发的自动化规则。按 cron 或 webhook 触发,自动创建 issue 并分配给 agent | `autopilot`, `autopilot_trigger`, `autopilot_run` |
+| **Chat 对话** | 用户和 agent 的持久化多轮对话。不依附于 issue | `chat_session`, `chat_message` |
+| **Inbox 收件箱** | 个人通知中心。被 @、被分配、订阅的 issue 有更新都会进这里 | `inbox_item` |
+| **Subscriber 订阅者** | 谁关注某个 issue。被分配、被 @、评论过都会自动订阅。订阅者会收到 inbox 通知 | `issue_subscriber` |
+| **Activity 活动 / Timeline 时间线** | 所有关键动作的审计记录。issue 详情页的"时间线"就是这个表的数据 | `activity_log` |
+| **Pin 固定** | 个人侧边栏快捷方式,把常用的 issue/project 置顶 | `pinned_item` |
+| **Reaction 反应** | Issue 或评论上的 emoji 反应,跟 GitHub/Slack 一样 | `issue_reaction`, `comment_reaction` |
+| **Attachment 附件** | Issue 或评论的文件上传,支持 S3/CloudFront 或本地存储 | `attachment` |
+| **Personal Access Token (PAT)** | 用户级 API token,CLI 和自动化用。`mul_` 前缀 | `personal_access_token` |
+| **Daemon Token** | 单 workspace 单 daemon 的 token。`mdt_` 前缀,比 PAT 权限范围更小 | `daemon_token` |
+| **Session Resumption 会话恢复** | 同一对 (agent, issue) 的下一次任务会自动复用上次 Claude Code 的 `session_id` 和工作目录——历史对话、文件状态都保留 | `agent_task_queue.session_id`, `.work_dir` |
+| **MCP (Model Context Protocol)** | Anthropic 提出的协议,让 agent 通过标准接口调用外部工具。每个 agent 可配自己的 MCP server 列表 | `agent.mcp_config` (JSONB) |
+| **Workspace Context 工作区上下文** | 工作区级别的 agent 系统提示词。所有该工作区的 agent 都会感知到它 | `workspace.context` |
+| **Polymorphic Actor 多态行动者** | 设计范式:几乎所有"谁做了什么"的字段都是 `actor_type` (`member`/`agent`) + `actor_id`。这就是为什么 agent 能像人一样创建 issue、发评论、被订阅 | 贯穿所有表 |
+
+---
+
+## 3. 功能全景(按模块)
+
+### 3.1 Workspace 工作区
+
+> **角色**:一切的容器。Multica 的多租户边界。
+
+#### 功能
+
+- **多工作区**:一个用户可以属于多个 workspace,每个 workspace 完全隔离(issue、agent、skill、成员都独立)。
+- **创建工作区**:只需要一个名字;自动生成 slug(URL 中使用的短 ID)。
+- **切换工作区**:侧边栏下拉;桌面端每个工作区有独立的标签组。
+- **离开工作区**:非 owner 成员可自行离开。
+- **删除工作区**:只有 owner 可以,硬删除+级联。
+- **Workspace 设置**:名称、slug、描述、**Workspace Context**(给该工作区所有 agent 的统一系统提示)、**仓库列表**(workspace 允许 agent 访问的 Git 仓库 URL 白名单)。
+- **Workspace 头像 / issue 前缀**:每个工作区可以有自己的 issue 编号前缀(如 `ACME-42`)。
+
+#### 产品里的位置
+
+Workspace 不是一个功能,而是**所有功能的坐标系**。URL 的形态永远是 `/{workspace-slug}/...`,API 请求永远带 `X-Workspace-Slug` 头。一个 issue、一个 agent、一个 skill,脱离了 workspace 就没有意义。
+
+#### 对应表
+
+`workspace`, `member`, `workspace_invitation`
+
+---
+
+### 3.2 Issue 议题管理
+
+> **角色**:Multica 的核心工作对象。
+
+Issue 对应的概念在 Linear 叫 Issue、在 Jira 叫 Ticket、在 GitHub 叫 Issue——就是一个任务单元。Multica 的特色在于**issue 可以分配给 agent,和分配给人完全对等**。
+
+#### 核心字段
+
+- 标题、描述(Tiptap 富文本)、状态、优先级
+- 编号(自动递增,带 workspace 前缀)
+- **Assignee(可以是 member 或 agent)**
+- **Creator(可以是 member 或 agent)**——agent 也能创建 issue
+- Parent issue(用来做子任务)
+- Project(归属的项目)
+- Due date(截止日期)
+- Labels(多对多标签)
+- Dependencies(依赖/阻塞关系)
+- Acceptance criteria(验收标准,JSONB)
+- Origin(如果是 autopilot 创建的,会记录来源 autopilot run)
+
+#### 视图
+
+- **List 列表视图**:表格形式,可按 status/priority/assignee/creator/project 过滤、按名称/优先级/截止日/手动位置排序;支持开放和已完成分页。
+- **Board 看板视图**:Kanban,按状态分列;支持拖拽(拖动会自动切到"手动排序"模式)。
+- **My Issues 我的议题**:专属视图,三个 scope:分配给我 / 我创建的 / 我的 agent 负责的。
+
+#### 交互
+
+- **快速创建**:侧边栏单行快速创建、或弹窗富文本创建(支持草稿本地持久化)
+- **批量操作**:多选后批量改 status/priority/assignee/删除
+- **子 issue**:父 issue 显示子任务完成比例圆环
+- **订阅(subscribe)**:默认 creator、assignee、被 @ 的人会自动订阅
+- **Reaction**:issue 和评论都能加 emoji 反应
+- **Pin 固定**:把 issue 置顶到侧边栏快捷栏
+- **复制链接 / 快捷键跳转(Cmd+K)**
+- **Timeline 时间线**:所有关键动作(状态变更、指派变更、评论)按时间顺序展示,混合 `activity_log` + `comment` 两类记录
+
+#### 评论与讨论
+
+- Tiptap 富文本编辑器,支持 `@` 提到 member 或 agent
+- 嵌套回复(一层)
+- emoji 反应
+- **@agent 触发任务**:在评论里提到某个 agent,会自动生成一个新的 agent task,让它来回复/处理
+
+#### 附件
+
+- 拖拽上传或按钮上传
+- 图片内联预览
+- 存储后端:S3/CloudFront 或本地磁盘(自托管)
+
+#### 产品里的位置
+
+Issue 是**所有工作流的载体**:
+- Agent 通过"被分配到 issue"获得任务
+- Autopilot 通过"创建 issue"来触发 agent
+- 评论通过"@agent" 追加任务
+- Inbox 通知围绕 issue 生成
+
+#### 对应表
+
+`issue`, `comment`, `issue_label`, `issue_to_label`, `issue_dependency`, `issue_subscriber`, `issue_reaction`, `comment_reaction`, `attachment`, `activity_log`, `pinned_item`
+
+---
+
+### 3.3 Project 项目
+
+> **角色**:多个 issue 的高层容器,类似 Linear 的 Project、Jira 的 Epic。
+
+#### 功能
+
+- 标题、描述、图标(emoji 或标识符)
+- 状态:`planned` / `in_progress` / `paused` / `completed` / `cancelled`
+- 优先级:urgent / high / medium / low / none
+- **Lead 负责人**:可以是 member 或 agent(跟 issue 的 assignee 一样是多态)
+- 详情页展示项目内的所有 issue
+- 支持搜索项目
+
+#### 产品里的位置
+
+Project 相比 Issue 是更高层的组织单元。一个 issue 可以不属于任何 project,但如果属于,会在列表页的筛选、侧边栏导航、面包屑里集中展示。
+
+#### 对应表
+
+`project`
+
+---
+
+### 3.4 Agent 智能体
+
+> **角色**:AI 工作者。Multica 最独特的对象。
+
+一个 Agent 不是一个"AI 模型",而是一个**带配置的工作者身份**。它有名字、头像、个人描述、说明书(系统提示词)、绑定的运行时、挂载的技能。在 UI 上它和人一样会出现在 assignee 下拉、评论作者、订阅者列表里。
+
+#### 配置字段
+
+- **基本信息**:名字、描述、头像(自动生成)
+- **Provider**:选择底层是 Claude / Codex / OpenClaw / OpenCode / Hermes / Gemini / Pi / Cursor 中的哪一个
+- **Runtime**:绑定到哪个运行时(即在哪台机器上跑)
+- **Instructions 说明书**:agent 的系统提示词("你是一个资深工程师...")
+- **Custom Env**:要注入到 CLI 进程的环境变量(如 `ANTHROPIC_API_KEY`、`ANTHROPIC_BASE_URL`、`CLAUDE_CODE_USE_BEDROCK`)
+- **Custom Args**:附加给 CLI 的启动参数(如 `--model`, `--thinking`)
+- **MCP Config**:Model Context Protocol 服务器列表(让 agent 有额外工具能力)
+- **Max Concurrent Tasks**:同时最多跑几个任务
+- **Skills**:关联多个 skill(见 3.6)
+- **Visibility**:`workspace`(工作区可见)或 `private`(仅创建者可见)
+
+#### 状态
+
+- `idle` / `working` / `blocked` / `error` / `offline`——由 runtime heartbeat 决定
+- 可以被 archive(软删除)
+
+#### 交互
+
+- 在 **Settings → Agents** 页面创建、编辑、归档
+- 在 issue 的 assignee 下拉里选择
+- 在评论里 `@agent` 触发
+- 在 chat 面板里直接聊
+
+#### 产品里的位置
+
+Agent 是 Multica 的灵魂。几乎所有功能都围绕"如何让一个 agent 干活"展开:
+- Issue 通过分配触发 agent
+- Skill 通过挂载赋能 agent
+- Runtime 提供 agent 的运行环境
+- Autopilot 调度 agent 自动开工
+- Chat 提供 agent 的对话界面
+
+#### 对应表
+
+`agent`, `agent_skill`
+
+---
+
+### 3.5 Runtime 运行时 & Daemon 守护进程
+
+> **角色**:Agent 真正跑起来的物理/虚拟机器。
+
+这是 Multica **分布式执行架构**的核心设计:**agent 不在 server 上运行,而在用户自己的机器上运行**。Server 只做任务调度、状态同步、数据存储。
+
+#### Daemon 是什么
+
+`multica` CLI 在用户的机器上启动一个后台进程(macOS launchd / Linux systemd / Windows 服务风格),它:
+
+1. **自动探测** `$PATH` 上安装的 coding CLI(`claude`, `codex`, `opencode`, `openclaw`, `hermes`, `gemini`, `pi`, `cursor-agent`)
+2. 向 server **注册** 为一组 runtime(一个 CLI = 一个 runtime)
+3. 每 3 秒 **轮询** 一次 server,有任务就认领
+4. 每 15 秒 **心跳**(keepalive),报告自己还活着
+5. 认领任务后,在本机的隔离工作目录里**启动 agent CLI**,把 agent 的输出流**实时推回 server**
+6. 任务完成后上报结果、token 用量、session id 和工作目录(用于下次恢复)
+
+#### Runtime 展示
+
+在 **Settings → Runtimes** 页面可以看到:
+
+- 每个 runtime 的名字、提供方(图标)、owner(谁的机器)、状态指示(在线/离线)、last seen 时间
+- Ping 诊断:手动戳一下看响应
+- Usage 用量:近期的 token 消耗统计
+- Activity:任务活动情况
+- CLI 安装指引(自托管模式下)
+- 桌面端独有:**本地 daemon 卡片**,显示本机 daemon 状态、可一键重启
+
+#### Runtime 的生命周期
+
+- **注册**:daemon 启动时 POST `/api/daemon/register` 得到 runtime ID
+- **在线**:15 秒一次心跳
+- **离线**:如果 server 45 秒没收到心跳,把 runtime 标记为离线(server 后台 sweeper 每 30 秒巡检)
+- **孤儿任务回收**:超过 5 分钟还在 dispatched 或超过 2.5 小时还在 running 的任务,sweeper 会把它标记为失败
+- **长期离线 GC**:7 天没心跳且没活跃 agent 的 runtime 会被回收
+
+#### CLI 与 Daemon 的关系
+
+| 命令 | 说明 |
+|------|------|
+| `multica setup` | 一键配置:填 URL + 登录 + 启动 daemon |
+| `multica login` | 浏览器打开 OAuth 登录,保存 90 天 PAT 到 `~/.multica/config.json` |
+| `multica login --token <pat>` | 无头登录(SSH/CI) |
+| `multica daemon start` | 后台启动 daemon(写 PID 到 `~/.multica/daemon.pid`,日志到 `~/.multica/daemon.log`) |
+| `multica daemon stop` | 发 SIGTERM,优雅关闭(等待进行中的任务完成,超时 30s) |
+| `multica daemon status` | 打印 daemon 状态、探测到的 agent、watch 中的 workspace |
+| `multica daemon logs -f` | 实时跟随日志 |
+| `multica daemon start --profile <name>` | 启动独立配置的 daemon(用于多环境,比如同时连 staging 和生产) |
+
+#### 安全边界
+
+- 每个任务一个**独立工作目录** `~/multica_workspaces/{ws}/{task_short_id}/workdir/`
+- 环境变量**过滤**:阻止 agent 覆盖 daemon 的认证变量(`MULTICA_TOKEN` 等)
+- 仓库访问**白名单**:agent 只能 checkout workspace 配置的仓库
+- Codex 有**版本相关的 sandbox 策略**
+
+#### 产品里的位置
+
+Runtime 是让"给 agent 分配任务"这件事**能真正发生**的基础设施。没有 runtime,所有 agent 就是空壳。用户第一次 onboarding 时必须至少有一个 runtime 在线,否则 agent 没法干活。
+
+#### 对应表
+
+`agent_runtime`, `daemon_token`, `daemon_pairing_session`(弃用中), `daemon_connection`(弃用中), `runtime_usage`
+
+---
+
+### 3.6 Skill 技能
+
+> **角色**:让 agent "学会"某种工作方式的可复用说明文档。
+
+Skill 是一组 Markdown 文档 + 配套文件。它**不是代码**,**不是 prompt 模板**,而是**给 agent CLI 读的说明**。
+
+#### 数据形态
+
+```
+skill
+ ├─ name: "react-patterns"
+ ├─ description: "Common React patterns and best practices"
+ ├─ content: "## Overview\n..." # 主要说明文档
+ └─ files:
+ ├─ examples/hooks.md
+ └─ examples/useState.jsx
+```
+
+#### 它怎么工作
+
+1. **创建**:在 **Settings → Skills** 页面创建或从 URL 导入(如 clawhub.ai、skills.sh)
+2. **挂载**:给某个 agent 勾选要用的 skill
+3. **注入**:当 agent 认领任务时,daemon 把挂载的 skill 内容写到任务工作目录的 **provider 原生位置**:
+ - Claude Code → `.claude/skills/{name}/SKILL.md`
+ - Codex → `CODEX_HOME/skills/{name}/`
+ - OpenCode → `.config/opencode/skills/{name}/SKILL.md`
+ - Pi → `.pi/agent/skills/{name}/SKILL.md`
+ - Cursor → `.cursor/skills/{name}/SKILL.md`
+ - GitHub Copilot → `.github/skills/{name}/SKILL.md`
+ - 其他 → `.agent_context/skills/{name}/SKILL.md`
+4. **使用**:agent CLI 自己按照 provider 约定发现并读取这些文件
+
+> 💡 **Skill 是静态的**——不是 AI 生成的,也不会随执行变化。它是人写的经验文档。未来可能扩展成"AI 从历史任务中沉淀技能",但当前版本不是。
+
+#### CLI 对应命令
+
+```bash
+multica skill list
+multica skill get <id>
+multica skill create --title ...
+multica skill import --url https://...
+multica skill files upsert <skill-id> --path ...
+```
+
+#### 产品里的位置
+
+Skill 是 Multica 区别于"每次都要写长 prompt"的关键机制。它让团队的专业知识**沉淀成可复用的组件**,绑在 agent 上就生效——就像给员工写的 SOP/playbook。
+
+从架构角度:skill 不参与执行逻辑,只参与**上下文注入**。它在整个任务生命周期里只出现一次——在 daemon 启动 CLI 之前的环境准备阶段。
+
+#### 对应表
+
+`skill`, `skill_file`, `agent_skill`
+
+---
+
+### 3.7 Autopilot 自动驾驶
+
+> **角色**:让 agent 在没人触发的时候也能自己开工的调度器。
+
+Autopilot 解决的问题:很多工作是**周期性**的——每天早上的 bug triage、每周的依赖审计、每月的安全扫描。人手动触发太烦,Autopilot 是规则化自动触发。
+
+#### 数据形态
+
+```
+autopilot
+ ├─ title, description
+ ├─ assignee: <agent_id> # 指定哪个 agent 跑
+ ├─ execution_mode: create_issue | run_only
+ ├─ issue_title_template: "Daily triage - {{date}}"
+ ├─ concurrency_policy: skip | queue | replace
+ └─ triggers (多个):
+ ├─ kind: schedule | webhook | api
+ ├─ cron_expression
+ ├─ timezone
+ └─ webhook_token
+```
+
+#### 两种执行模式
+
+- **`create_issue`(默认)**:触发时先创建一个新 issue(标题用 `issue_title_template` 渲染),再把 issue 分配给 agent,走正常 agent 任务流程
+- **`run_only`**:直接创建 task,不关联 issue(适合"只执行不留下 ticket"的场景,比如每小时检查某状态)
+
+#### 三种触发方式
+
+- **Schedule(cron)**:server 后台每 30 秒扫一次 `autopilot_trigger`,到点的触发出去
+- **Webhook**:给出一个带 `webhook_token` 的 URL,外部 POST 即可触发
+- **API / Manual**:UI 上点"立即运行"按钮,或用 CLI `multica autopilot trigger <id>`
+
+#### 并发策略
+
+- `skip`:同一个 autopilot 上一次还没跑完,跳过这次(去重)
+- `queue`:排队等上一次跑完
+- `replace`:中止上一次,换成这次
+
+#### 运行记录
+
+每次触发都在 `autopilot_run` 里留一条记录:`pending → issue_created → running → completed/failed/skipped`。在 UI 的 autopilot 详情页可以看全部历史。
+
+#### 内置模板
+
+产品提供一些现成的 autopilot 模板,一键创建:
+
+- Daily news digest(每天 9:00)
+- PR review reminder(工作日 10:00)
+- Bug triage(工作日 9:00)
+- Weekly progress report(每周 17:00)
+- Dependency audit(每周 10:00)
+- Security scan(每周 02:00)
+
+#### 产品里的位置
+
+Autopilot 让 Multica 从"你分配 → agent 做"升级到"agent 自己发起工作"。配合 `run_only` 模式,甚至可以在没有 issue 的前提下跑定时任务。Issue 上的 `origin_type=autopilot` + `origin_id` 字段留下了"这个 issue 是哪个 autopilot run 创建的"的追溯链。
+
+#### 对应表
+
+`autopilot`, `autopilot_trigger`, `autopilot_run`
+
+---
+
+### 3.8 Chat 对话
+
+> **角色**:用户和 agent 的持久多轮对话界面,不依附于 issue。
+
+有时候你不想为了和 agent 说一句话就开一个 issue。Chat 就是为这种"轻量对话"准备的——像 ChatGPT 的对话界面,但是你在和你工作区的某个 agent 对话。
+
+#### 功能
+
+- **创建会话**:选一个 agent 开始
+- **消息列表**:支持 Markdown 渲染、代码块高亮
+- **发送消息**:消息会被 queue 成一个 task,agent 执行后把响应作为消息写回
+- **流式响应**:通过 WebSocket 实时推送
+- **未读跟踪**:`unread_since` 字段记录第一条未读消息的时间戳
+- **归档**:把旧会话移出活跃列表
+- **Session 复用**:同一个 chat session 下的多轮消息会复用底层 CLI 的 `session_id`(Claude Code 能保留对话上下文)
+
+#### 和 Issue 评论的区别
+
+| | Chat | Issue 评论 |
+|---|---|---|
+| 上下文载体 | 独立 session(chat_session) | 某个 issue |
+| 是否公开 | 个人和 agent 对话(私有) | 工作区所有成员可见 |
+| 触发 agent | 每条 user 消息都触发 | 需要 `@agent` |
+| 用途 | 探索、提问、一次性任务 | 和 issue 强绑定的工作推进 |
+
+#### 产品里的位置
+
+Chat 填补了"不够正式到需要开 issue、但又需要持久化"的对话空白。同时也是体验上更像常规聊天软件的入口。
+
+#### 对应表
+
+`chat_session`, `chat_message`;底层执行仍走 `agent_task_queue`(`chat_session_id` 字段区分)
+
+---
+
+### 3.9 Inbox 收件箱与通知
+
+> **角色**:每个人的个人通知中心。
+
+#### 数据形态
+
+`inbox_item` 是推给特定"recipient"的条目:
+
+- recipient_type = `member` 或 `agent`(agent 也能有 inbox!)
+- type(e.g. `issue_assigned`, `comment_mention`, `task_completed`, `invitation_created`)
+- severity(`action_required` / `attention` / `info`)
+- 关联的 issue(如果有)
+- read / archived 状态
+
+#### 通知触发场景
+
+- Issue 被分配给你
+- 被 @ 提到
+- 订阅的 issue 状态变化
+- 订阅的 issue 有新评论
+- 工作区邀请
+- 你的 agent 任务完成/失败
+
+#### 订阅机制(自动)
+
+Server 的 subscriber listener 自动把以下人加入 `issue_subscriber`:
+
+- issue creator
+- 当前 assignee(变更会同步更新)
+- 评论里被 @ 的人
+- 手动订阅的人
+
+#### UI
+
+- **Inbox 页面**:两栏布局,左边列表 + 右边 issue 详情
+- **批量操作**:全部标记已读 / 仅归档已读 / 归档已完成 issue 的通知
+- **徽标**:侧边栏导航上显示未读数
+- **WebSocket 推送**:新 inbox 条目实时到达(`inbox:new` 事件只发给目标用户)
+
+#### 产品里的位置
+
+Inbox 是"主动注意力系统",让用户不必一直盯着看板也知道哪些事要自己处理。
+
+#### 对应表
+
+`inbox_item`, `issue_subscriber`
+
+---
+
+### 3.10 成员、邀请与权限
+
+#### 角色体系
+
+| 角色 | 权限 |
+|------|------|
+| **Owner** | 全部;唯一能删除工作区的角色 |
+| **Admin** | 管理成员、管理设置;不能删工作区,不能移除其他 admin |
+| **Member** | 创建 issue、评论、自我分配、使用 agent |
+
+#### 邀请流程
+
+- Admin 在 **Settings → Members** 输入邮箱邀请
+- Server 生成 `workspace_invitation` 记录(7 天过期)
+- 发送邮件(Resend 集成,未配置时打到 stderr)
+- 被邀请人收到邀请:如果已有账号,会出现在个人 Inbox;如果没账号,邮件里有注册链接
+- 接受 / 拒绝 / 过期
+
+#### UI
+
+- 成员列表:头像、邮箱、角色徽章、操作菜单(改角色、移除)
+- 待处理邀请列表:可 resend、revoke
+- Invite 接受页面(`/invite/[id]`):展示工作区信息、接受/拒绝按钮
+
+#### 邀请接受的桌面特殊处理
+
+桌面端的 `multica://invite/{id}` 深链接**不是走路由**,而是触发 `WindowOverlay`——共享视图组件 `InvitePage` 装在原生窗口覆盖层里,保证拖拽移动窗口等原生体验。
+
+#### 产品里的位置
+
+成员管理是**一切协作的前提**。但在 Multica 里它有一个独特之处:成员系统也管 agent。之所以要有 `assignee_type` 区分 member 和 agent,就是为了让两者在同一套 API 里表达"谁可以被分配"。
+
+#### 对应表
+
+`member`, `workspace_invitation`
+
+---
+
+### 3.11 搜索与命令面板
+
+#### 命令面板(Cmd+K)
+
+全局搜索入口,覆盖:
+
+- **Issues**(按标题、编号匹配)
+- **Projects**(按名称匹配)
+- **Workspaces**(按名称匹配,用于快速切换)
+- **Navigation**(跳转到设置、runtimes、skills 等)
+- **Actions**(新建 issue、新建 project、切换主题)
+- **Recent Issues**(最近访问过的,自动记录)
+
+#### 列表过滤
+
+Issue 列表、project 列表、inbox 等都有本地 filter chips 和 search input。
+
+#### 全文搜索
+
+`GET /api/issues/search` 支持对 issue 的标题、描述、评论内容做全文搜索,返回命中片段。
+
+> **当前没有基于向量的语义搜索**——产品宣传是 AI-native,但没有用 pgvector。Schema 里也没启用向量扩展。未来可能扩展。
+
+#### 产品里的位置
+
+Cmd+K 是 keyboard-first 用户(Linear-style)的主要导航方式,比点击侧边栏更快。
+
+---
+
+### 3.12 认证、登录与 Onboarding
+
+#### 登录方式
+
+- **邮箱验证码(Magic Link 风格)**:输入邮箱 → 收 6 位验证码 → 输入验证码登录
+- **Google OAuth**:一键 Google 登录
+- **PAT(CLI)**:用户在 Settings → API Tokens 里生成的 token,CLI/脚本场景
+
+#### Onboarding 流程(正在重设计中)
+
+位于 `packages/views/onboarding/` 和 `apps/web/app/(auth)/onboarding/`。
+
+经典 5 步:
+
+1. **Welcome** — 欢迎页
+2. **Workspace** — 创建工作区(或跳过,如果已有)
+3. **Runtime** — 展示可用的 runtime 和 CLI 安装指引
+4. **Agent** — 创建第一个 agent(需要有 runtime)
+5. **Complete** — 展示创建好的 workspace 和 agent,跳转到 dashboard
+
+#### 邀请接受(Zero-workspace)
+
+如果新用户是被邀请进来的(还没有自己的 workspace),接受邀请后直接进入该工作区,跳过 onboarding。
+
+#### 认证后的跳转规则
+
+- 已登录且有至少一个 workspace:跳到 `/{slug}/issues`
+- 已登录但没有 workspace:进入 `/workspaces/new` 或 onboarding
+- 未登录:跳到 `/login`
+
+#### Signup 限流
+
+Server 支持:
+- `ALLOW_SIGNUP=false` 关闭注册
+- `ALLOWED_EMAILS` / `ALLOWED_EMAIL_DOMAINS` 白名单
+
+#### 产品里的位置
+
+Onboarding 是新用户能不能成功把 agent 跑起来的关键漏斗。任何一步没完成(尤其是 runtime 没连上),后续功能都是空壳。
+
+#### 对应表
+
+`user`, `verification_code`, `personal_access_token`
+
+---
+
+### 3.13 设置与个人资料
+
+#### My Account 标签
+
+- **Profile**:名字、头像(不可上传,系统生成)、邮箱(只读)
+- **Appearance**:主题(light / dark / system)
+- **API Tokens**:创建/查看/撤销 PAT;创建时一次性展示完整 token
+- **Daemon**(桌面独有):本机 daemon 状态、重启、开机自启开关
+- **Updates**(桌面独有):当前版本、检查更新、自动更新开关
+
+#### Workspace 标签
+
+- **General**:名字、描述、**Workspace Context**(agent 系统级提示)
+- **Members**:见 3.10
+- **Repositories**:GitHub 集成,连接仓库列表,agent 白名单
+- **Agents / Runtimes / Skills / Autopilots**:各自独立页面(实际上这些在侧边栏直接有入口,settings 里也有对应管理 tab)
+
+#### 产品里的位置
+
+Settings 是所有"配置即工作"动作的汇总:agent 的 prompt、workspace 的 context、仓库白名单、skill 的内容——都在这里。**对运营和文案来说最重要的一句话**:用户在 Multica 的 settings 页面做的配置,每一项都会影响 agent 实际执行时读到的上下文。
+
+---
+
+### 3.14 CLI 命令行工具
+
+`multica` 不只是启动 daemon 的工具,也是完整的命令行操作层。很多用户喜欢在终端里推进工作而不是开 UI。
+
+#### 工作区 / 议题
+
+```bash
+multica workspace list | get | watch | unwatch
+multica issue list | get | create | update | assign | status
+multica issue comment list | add | delete
+multica issue runs <id> # 查看任务执行历史
+multica issue run-messages <task-id> # 查看某次执行的消息
+```
+
+#### Agent / Skill / Autopilot / Project / Repo
+
+```bash
+multica agent list | get | create | update | archive
+multica skill list | get | create | update | delete | import | files upsert
+multica autopilot list | get | create | update | trigger
+multica autopilot trigger-add --cron "0 9 * * 1-5"
+multica project list | get | create | update
+multica repo list | add | update | delete
+```
+
+#### Runtime
+
+```bash
+multica runtime list | get | ping | delete
+```
+
+#### 配置 / 更新
+
+```bash
+multica config show | set server_url ...
+multica auth status | logout
+multica version | update
+```
+
+#### 产品里的位置
+
+CLI 是 Multica 对开发者友好度的体现。对于 agent 自己来说,也同等重要——**agent 在执行任务时能调用 `multica` 命令读写 issue、评论、查文档**,这正是 CLI 在 "agent 作为一等公民"架构里的作用。
+
+---
+
+## 4. 系统架构全景
+
+```
+┌─────────────────────┐ ┌────────────────────┐ ┌──────────────────┐
+│ Next.js Web App │ │ Electron Desktop │ │ multica CLI │
+│ apps/web │ │ apps/desktop │ │ server/cmd/ │
+└──────────┬──────────┘ └──────────┬─────────┘ └────────┬─────────┘
+ │ HTTP + WebSocket │ │ HTTP
+ │ │ │
+ └──────────────┬────────────────┴───────────────┬───────────┘
+ │ │
+ ▼ ▼
+ ┌─────────────────────────────────────────────────┐
+ │ Go Backend (server/) │
+ │ • Chi HTTP router • gorilla/websocket hub │
+ │ • sqlc generated queries │
+ │ • In-process event bus │
+ │ • Background workers (sweeper / scheduler) │
+ └──────────────────┬──────────────────────────────┘
+ │
+ ▼
+ ┌──────────────────────┐
+ │ PostgreSQL 17 │
+ │ + pgcrypto │
+ │ (28 tables) │
+ └──────────────────────┘
+
+ ▲
+ │ HTTPS poll + heartbeat
+ │
+ ┌─────────────────────────────────────────────────┐
+ │ Local Daemon (用户机器上运行) │
+ │ • 每 3s 认领任务 • 每 15s 心跳 │
+ │ • 探测并启动 agent CLI 子进程 │
+ │ • 为任务准备隔离工作目录 │
+ └───────────────┬─────────────────────────────────┘
+ │ spawns
+ ┌───────────────┼─────────────────────────────────┐
+ ▼ ▼ ▼ ▼
+ Claude Code Codex OpenCode …其他 CLI
+ (子进程) (子进程) (子进程)
+```
+
+### 分层职责
+
+| 层 | 负责什么 | 不负责什么 |
+|---|---|---|
+| **Web / Desktop 客户端** | UI、本地客户端状态(Zustand)、服务器状态缓存(TanStack Query)、WebSocket 订阅 | 业务规则、AI 调用 |
+| **Server** | 持久化、权限、任务编排、事件广播、Autopilot 调度、Runtime 健康监测 | 不直接执行 agent、不调 LLM |
+| **Daemon** | 探测并启动本地 CLI、管理任务工作目录、流式上报消息、session 恢复 | 不做业务决策、只认 server 给它的任务 |
+| **Agent CLI(Claude Code 等)** | 实际调用 LLM、执行工具调用、写文件、跑测试 | 不感知 Multica 的数据模型(所有上下文通过 `multica` CLI 命令读回) |
+
+### 实时层(WebSocket)
+
+Server 启动一个 WebSocket hub:
+
+- **鉴权**:URL 参数里的 JWT 或 PAT + workspace_slug
+- **房间模型**:按 workspace 分房间,一个 workspace 的事件只广播给该房间的连接
+- **个人定向推送**:`inbox:new`, `invitation:created` 等个人事件用 `SendToUser`
+- **心跳**:server 每 54 秒 ping,客户端 60 秒内必须 pong
+
+**全部事件类型(供文案参考,共约 60+ 个)**:
+- `issue:created` / `issue:updated` / `issue:deleted`
+- `comment:created` / `comment:updated` / `comment:deleted` / `reaction:added` / `issue_reaction:added`
+- `agent:created` / `agent:status` / `agent:archived`
+- `task:dispatch` / `task:progress` / `task:message` / `task:completed` / `task:failed` / `task:cancelled`
+- `inbox:new` / `inbox:read` / `inbox:archived` / `inbox:batch-*`
+- `workspace:updated` / `workspace:deleted` / `member:added` / `member:updated` / `member:removed`
+- `invitation:created` / `invitation:accepted` / `invitation:declined` / `invitation:revoked`
+- `chat:message` / `chat:done` / `chat:session_read`
+- `skill:created` / `skill:updated` / `skill:deleted`
+- `project:created` / `project:updated` / `project:deleted`
+- `autopilot:created` / `autopilot:updated` / `autopilot:run_start` / `autopilot:run_done`
+- `subscriber:added` / `activity:created`
+- `daemon:heartbeat` / `daemon:register`
+
+客户端收到事件后的模式:要么直接 patch 本地缓存(issue / comment / task 这类需要即时更新的),要么触发对应 query 的失效重拉(less-critical 数据)。
+
+### AI / LLM 在哪里
+
+**Multica 本身不直接调 LLM API**。所有 LLM 调用都在 agent CLI 子进程里发生(Claude Code 调 Anthropic API、Codex 调 OpenAI API 等)。
+
+Server 和 daemon 做的事情是:
+
+1. 准备 prompt(见 `server/internal/daemon/prompt.go`)
+2. 准备环境变量(agent.custom_env 注入)
+3. 准备工作目录(注入 CLAUDE.md / AGENTS.md / skills / issue context)
+4. 启动 CLI 子进程
+5. 流式读 CLI 的 stdout,把消息分类并转发
+
+**所以看不到大段的 prompt 工程代码**——prompt 只有几个模板(task prompt、chat prompt、comment-triggered prompt),核心内容是 agent instructions + issue context + skill files,真正的 LLM 对话由 CLI 自己管理。
+
+### 后台任务
+
+Server 启动三个 goroutine:
+
+1. **Runtime Sweeper**(每 30s):标记离线 runtime、回收孤儿任务、GC 长期离线 runtime
+2. **Autopilot Scheduler**(每 30s):扫 cron 触发器,到点就 dispatch
+3. **DB Stats Logger**:周期性打印 pgxpool 连接池状态
+
+---
+
+## 5. 产品地图(全部路由)
+
+### 公共 / 认证
+
+- `/` — 首页
+- `/login` — 登录
+- `/auth/callback` — OAuth 回调
+- `/workspaces/new` — 创建工作区
+- `/invite/[id]` — 接受邀请
+- `/onboarding` — 首次引导
+
+### 工作区内(`/{slug}/...`)
+
+- `/issues` — Issue 列表(board / list 视图)
+- `/issues/[id]` — Issue 详情
+- `/my-issues` — 我的 issue(三 scope)
+- `/projects` — 项目列表
+- `/projects/[id]` — 项目详情
+- `/autopilots` — Autopilot 列表
+- `/autopilots/[id]` — Autopilot 详情
+- `/agents` — Agent 列表
+- `/runtimes` — Runtime 列表
+- `/skills` — Skill 库
+- `/inbox` — 收件箱
+- `/settings` — 设置(包含多个 tab:profile / appearance / tokens / workspace / members / repos / daemon / updates)
+
+### 桌面端特有(不是路由,是 WindowOverlay)
+
+- **Create workspace overlay**
+- **Invite accept overlay**(来自 `multica://invite/{id}` 深链接)
+- **Onboarding overlay**(首次或零工作区时)
+
+---
+
+## 6. 跨平台差异:Web vs 桌面
+
+### 共享(绝大部分功能)
+
+所有业务页面(issues / projects / autopilots / agents / runtimes / skills / inbox / settings / chat / login / onboarding)的实际 UI 都在 `packages/views/` 里,web 和桌面共用同一套组件。
+
+### Web 特有
+
+- 地址栏 + 浏览器前进后退
+- 服务端渲染(SSR)
+- `/login` 的 OAuth 回调处理 localhost 端口(方便 CLI 登录)
+
+### 桌面特有
+
+- **多标签**:每个 workspace 独立标签组,可以拖拽重排
+- **WindowOverlay**:邀请接受、创建工作区、onboarding 不走路由,而是原生窗口层
+- **Daemon 集成**:设置里能直接重启本机 daemon、看状态
+- **本地 daemon runtime 卡片**:在 Runtimes 页面自动显示本机 daemon
+- **自动更新**:`Settings → Updates` 检查/下载/安装新版本
+- **Immersive mode**:全屏模式,隐藏侧边栏
+- **深链接**:`multica://auth/callback?token=...` 和 `multica://invite/{id}`
+- **拖动区**:macOS 的红绿灯 + 顶部 48px 拖拽条(`h-12`)用来移动窗口
+- **Workspace 单例守护**:`setCurrentWorkspace()` 管理当前活跃工作区的全局身份
+
+### 为什么两端要做差异
+
+Web 有 URL 栏——错误状态(比如"你没有访问这个 workspace 的权限")作为一个可分享的 URL 页面是有意义的。桌面没有 URL 栏——同样的状态只会把用户困住,所以桌面选择**静默自愈**:把失效的 tab 从 store 里移除即可。这个差异直接影响多个细节:
+
+- Web 有 `NoAccessPage`,桌面没有
+- Web 有 `/workspaces/new` 页面,桌面把它做成 overlay
+- Web 的 deep link 直接路由,桌面的深链接转 WindowOverlay
+
+---
+
+## 7. 附录:关键数据表速查
+
+共 **28 张表**,覆盖 10 个产品域。以下按域列出最重要的字段,供文案/产品查询"某个功能背后到底存了什么"。
+
+### 身份 / 认证
+
+- `user` — 基础账号(id, email, name, avatar_url)
+- `verification_code` — 邮箱验证码(code, expires_at, attempts)
+- `personal_access_token` — 用户 API token(token_hash, token_prefix, revoked)
+
+### 工作区 / 成员
+
+- `workspace` — 容器(name, slug, description, context, settings, repos, issue_prefix, issue_counter)
+- `member` — 成员身份(role: owner/admin/member)
+- `workspace_invitation` — 邀请(invitee_email, status: pending/accepted/declined/expired)
+
+### Agent / Runtime / Skill
+
+- `agent` — Agent 主表(instructions, custom_env, custom_args, mcp_config, runtime_mode, visibility, status)
+- `agent_runtime` — 运行时(daemon_id, provider, status: online/offline, last_seen_at)
+- `agent_skill` — agent 挂载 skill 的 n-n 关联
+- `skill` — 技能主文档(name, description, content)
+- `skill_file` — 技能附带文件(path, content)
+- `daemon_token` — 守护进程级 token
+- `daemon_connection` / `daemon_pairing_session` — 早期设计(弃用中)
+
+### Issue / 协作
+
+- `issue` — 议题(status, priority, assignee_type+assignee_id, creator_type+creator_id, parent_issue_id, project_id, origin_type, origin_id, acceptance_criteria, due_date, position)
+- `issue_label` / `issue_to_label` — 标签
+- `issue_dependency` — 依赖关系(blocks / blocked_by / related)
+- `issue_subscriber` — 订阅者(reason: creator/assignee/commenter/mentioned/manual)
+- `issue_reaction` / `comment_reaction` — emoji 反应
+- `comment` — 评论(type: comment/status_change/progress_update/system, parent_id for threading)
+- `attachment` — 附件
+
+### 任务执行
+
+- `agent_task_queue` — 任务主表(status: queued/dispatched/running/completed/failed/cancelled, context, result, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id)
+- `task_message` — 每次执行的消息流水(seq, type, tool, input, output)
+- `task_usage` — Token 用量(input/output/cache_read/cache_write tokens)
+
+### 对话
+
+- `chat_session` — 聊天会话(unread_since, session_id, work_dir)
+- `chat_message` — 消息(role: user/assistant)
+
+### 项目与组织
+
+- `project` — 项目(status, priority, lead_type+lead_id, icon)
+- `pinned_item` — 侧边栏置顶(item_type, item_id, position)
+
+### 自动化
+
+- `autopilot` — 规则(assignee_id, execution_mode: create_issue/run_only, issue_title_template, concurrency_policy)
+- `autopilot_trigger` — 触发器(kind: schedule/webhook/api, cron_expression, timezone, next_run_at, webhook_token)
+- `autopilot_run` — 执行记录(status: pending/issue_created/running/skipped/completed/failed)
+
+### 通知与审计
+
+- `inbox_item` — 收件箱条目(recipient_type, type, severity, read, archived)
+- `activity_log` — 审计日志(actor_type: member/agent/system, action, details)
+- `runtime_usage` — 运行时按日聚合 token 用量(给计费/容量规划用)
+
+---
+
+## 尾声
+
+Multica 的设计可以归结为一句话:**把"人在一个看板上协作"这件事,扩展到了"人 + AI agent 在同一个看板上协作"**。
+
+所有功能都是围绕这个核心展开:
+- 为了让 agent 能像人一样被分配任务 → polymorphic actor(`assignee_type`)
+- 为了让 agent 能自己开工 → Autopilot
+- 为了让 agent 的工作方式能沉淀复用 → Skill
+- 为了让 agent 执行在用户控制的环境里 → Runtime + Daemon
+- 为了让人不被通知淹没 → Inbox + 自动订阅
+- 为了让一次会话有连续性 → Session Resumption
+
+当你读到某段文案、某个 UI 模块、某张表时,请把它放回这个"人 + AI 协作"的坐标系里去理解它的位置。
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index a7b3ed2b04..80e74cd460 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -79,6 +79,52 @@ export interface LoginResponse {
user: User;
}
+// --- Starter content (post-onboarding import) -----------------------------
+// Shape mirrors the Go request/response in handler/onboarding.go.
+//
+// The client sends both branches of sub-issues and an unbound welcome
+// issue template (title + description, no `agent_id`). The SERVER picks
+// the branch by inspecting the workspace's agent list inside the
+// import transaction. This removes the client as a trusted decider —
+// even if the client has a stale agent cache or lies, the server uses
+// the DB as source of truth.
+
+export interface ImportStarterIssuePayload {
+ title: string;
+ description: string;
+ status: string;
+ priority: string;
+ /** Server uses `user_id` (per app-wide AssigneePicker convention)
+ * as assignee when true. No member_id is threaded through. */
+ assign_to_self: boolean;
+}
+
+export interface ImportStarterWelcomeIssueTemplate {
+ title: string;
+ description: string;
+ /** Defaults to "high" on server when empty. */
+ priority: string;
+}
+
+export interface ImportStarterContentPayload {
+ workspace_id: string;
+ project: { title: string; description: string; icon: string };
+ /** Always sent. Server creates it only when an agent exists in the
+ * workspace; ignored otherwise. Agent id is picked by the server. */
+ welcome_issue_template: ImportStarterWelcomeIssueTemplate;
+ /** Used when the workspace has at least one agent. */
+ agent_guided_sub_issues: ImportStarterIssuePayload[];
+ /** Used when the workspace has zero agents. */
+ self_serve_sub_issues: ImportStarterIssuePayload[];
+}
+
+export interface ImportStarterContentResponse {
+ user: User;
+ project_id: string;
+ /** Non-null when server took the agent-guided branch. */
+ welcome_issue_id: string | null;
+}
+
export class ApiError extends Error {
readonly status: number;
readonly statusText: string;
@@ -220,6 +266,54 @@ export class ApiClient {
return this.fetch("/api/me");
}
+ async markOnboardingComplete(): Promise<User> {
+ return this.fetch("/api/me/onboarding/complete", { method: "POST" });
+ }
+
+ async joinCloudWaitlist(payload: {
+ email: string;
+ reason?: string;
+ }): Promise<User> {
+ return this.fetch("/api/me/onboarding/cloud-waitlist", {
+ method: "POST",
+ body: JSON.stringify(payload),
+ });
+ }
+
+ async patchOnboarding(payload: {
+ questionnaire?: Record<string, unknown>;
+ }): Promise<User> {
+ return this.fetch("/api/me/onboarding", {
+ method: "PATCH",
+ body: JSON.stringify(payload),
+ });
+ }
+
+ /**
+ * Imports the Getting Started project + optional welcome issue + sub-issues
+ * in a single server-side transaction. Gated by an atomic
+ * starter_content_state: NULL → 'imported' claim — a second call returns
+ * 409 (already decided) and creates nothing new.
+ *
+ * The content templates live in TypeScript (see
+ * @multica/views/onboarding/utils/starter-content-templates) and are
+ * rendered from the user's questionnaire answers before being sent.
+ */
+ async importStarterContent(
+ payload: ImportStarterContentPayload,
+ ): Promise<ImportStarterContentResponse> {
+ return this.fetch("/api/me/starter-content/import", {
+ method: "POST",
+ body: JSON.stringify(payload),
+ });
+ }
+
+ async dismissStarterContent(): Promise<User> {
+ return this.fetch("/api/me/starter-content/dismiss", {
+ method: "POST",
+ });
+ }
+
async updateMe(data: UpdateMeRequest): Promise<User> {
return this.fetch("/api/me", {
method: "PATCH",
diff --git a/packages/core/api/index.ts b/packages/core/api/index.ts
index ea9372db84..3d26b86188 100644
--- a/packages/core/api/index.ts
+++ b/packages/core/api/index.ts
@@ -1,5 +1,11 @@
export { ApiClient, ApiError } from "./client";
-export type { ApiClientOptions } from "./client";
+export type {
+ ApiClientOptions,
+ ImportStarterContentPayload,
+ ImportStarterContentResponse,
+ ImportStarterIssuePayload,
+ ImportStarterWelcomeIssueTemplate,
+} from "./client";
export { WSClient } from "./ws-client";
import type { ApiClient as ApiClientType } from "./client";
diff --git a/packages/core/auth/store.ts b/packages/core/auth/store.ts
index 0f0251e4f1..a5fd472f97 100644
--- a/packages/core/auth/store.ts
+++ b/packages/core/auth/store.ts
@@ -24,6 +24,7 @@ export interface AuthState {
loginWithToken: (token: string) => Promise<User>;
logout: () => void;
setUser: (user: User) => void;
+ refreshMe: () => Promise<void>;
}
export function createAuthStore(options: AuthStoreOptions) {
@@ -128,5 +129,10 @@ export function createAuthStore(options: AuthStoreOptions) {
setUser: (user: User) => {
set({ user });
},
+
+ refreshMe: async () => {
+ const user = await api.getMe();
+ set({ user });
+ },
}));
}
diff --git a/packages/core/onboarding/index.ts b/packages/core/onboarding/index.ts
new file mode 100644
index 0000000000..e4aec8eb99
--- /dev/null
+++ b/packages/core/onboarding/index.ts
@@ -0,0 +1,14 @@
+export type {
+ OnboardingStep,
+ QuestionnaireAnswers,
+ TeamSize,
+ Role,
+ UseCase,
+} from "./types";
+export {
+ saveQuestionnaire,
+ completeOnboarding,
+ joinCloudWaitlist,
+} from "./store";
+export { ONBOARDING_STEP_ORDER } from "./step-order";
+export { recommendTemplate, type AgentTemplateId } from "./recommend-template";
diff --git a/packages/core/onboarding/recommend-template.test.ts b/packages/core/onboarding/recommend-template.test.ts
new file mode 100644
index 0000000000..8e23f928f0
--- /dev/null
+++ b/packages/core/onboarding/recommend-template.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it } from "vitest";
+import { recommendTemplate } from "./recommend-template";
+import type { Role, UseCase } from "./types";
+
+const ALL_USE_CASES: UseCase[] = [
+ "coding",
+ "planning",
+ "writing_research",
+ "explore",
+ "other",
+];
+
+describe("recommendTemplate", () => {
+ describe("identity fallbacks — role alone decides", () => {
+ it.each(ALL_USE_CASES)(
+ "role=other (use_case=%s) → assistant",
+ (use_case) => {
+ expect(recommendTemplate({ role: "other", use_case })).toBe(
+ "assistant",
+ );
+ },
+ );
+
+ it.each(ALL_USE_CASES)(
+ "role=founder (use_case=%s) → assistant",
+ (use_case) => {
+ expect(recommendTemplate({ role: "founder", use_case })).toBe(
+ "assistant",
+ );
+ },
+ );
+
+ it.each(ALL_USE_CASES)(
+ "role=writer (use_case=%s) → writing",
+ (use_case) => {
+ expect(recommendTemplate({ role: "writer", use_case })).toBe(
+ "writing",
+ );
+ },
+ );
+ });
+
+ describe("developer × use_case tiebreaker", () => {
+ it("developer × planning → planning", () => {
+ expect(
+ recommendTemplate({ role: "developer", use_case: "planning" }),
+ ).toBe("planning");
+ });
+
+ it.each<UseCase>([
+ "coding",
+ "writing_research",
+ "explore",
+ "other",
+ ])("developer × %s → coding", (use_case) => {
+ expect(recommendTemplate({ role: "developer", use_case })).toBe(
+ "coding",
+ );
+ });
+
+ it("developer × null use_case → coding (default)", () => {
+ expect(
+ recommendTemplate({ role: "developer", use_case: null }),
+ ).toBe("coding");
+ });
+ });
+
+ describe("product_lead × use_case tiebreaker", () => {
+ it("product_lead × coding → coding", () => {
+ expect(
+ recommendTemplate({ role: "product_lead", use_case: "coding" }),
+ ).toBe("coding");
+ });
+
+ it.each<UseCase>([
+ "planning",
+ "writing_research",
+ "explore",
+ "other",
+ ])("product_lead × %s → planning", (use_case) => {
+ expect(recommendTemplate({ role: "product_lead", use_case })).toBe(
+ "planning",
+ );
+ });
+
+ it("product_lead × null use_case → planning (default)", () => {
+ expect(
+ recommendTemplate({ role: "product_lead", use_case: null }),
+ ).toBe("planning");
+ });
+ });
+
+ describe("unanswered questionnaire", () => {
+ it("null role → assistant regardless of use_case", () => {
+ expect(recommendTemplate({ role: null, use_case: null })).toBe(
+ "assistant",
+ );
+ expect(recommendTemplate({ role: null, use_case: "coding" })).toBe(
+ "assistant",
+ );
+ });
+ });
+
+ describe("exhaustive role coverage", () => {
+ const roles: Role[] = [
+ "developer",
+ "product_lead",
+ "writer",
+ "founder",
+ "other",
+ ];
+ it.each(roles)("role=%s returns a valid template id", (role) => {
+ const result = recommendTemplate({ role, use_case: null });
+ expect(["coding", "planning", "writing", "assistant"]).toContain(result);
+ });
+ });
+});
diff --git a/packages/core/onboarding/recommend-template.ts b/packages/core/onboarding/recommend-template.ts
new file mode 100644
index 0000000000..24572c741a
--- /dev/null
+++ b/packages/core/onboarding/recommend-template.ts
@@ -0,0 +1,41 @@
+import type { QuestionnaireAnswers } from "./types";
+
+/**
+ * Identifier for the four agent templates offered during onboarding Step 4.
+ * Keep in sync with the template registry inside StepAgent in
+ * `packages/views/onboarding/steps/step-agent.tsx`.
+ */
+export type AgentTemplateId = "coding" | "planning" | "writing" | "assistant";
+
+/**
+ * Pick a recommended agent template for a user based on their
+ * questionnaire answers. Role is treated as the primary signal (who the
+ * user is); use_case is only a tiebreaker for roles that legitimately
+ * split between templates (developer / product_lead).
+ *
+ * `role = other` and `role = founder` both fall back to the generic
+ * Assistant: "other" means the user declined to claim a role, and
+ * "founder" means they wear every hat, so a single specialized agent is
+ * a poor default.
+ *
+ * Pure / deterministic — safe to call on every render.
+ */
+export function recommendTemplate(
+ answers: Pick<QuestionnaireAnswers, "role" | "use_case">,
+): AgentTemplateId {
+ const { role, use_case } = answers;
+
+ if (role === "other" || role === "founder") return "assistant";
+ if (role === "writer") return "writing";
+
+ if (role === "developer") {
+ return use_case === "planning" ? "planning" : "coding";
+ }
+
+ if (role === "product_lead") {
+ return use_case === "coding" ? "coding" : "planning";
+ }
+
+ // Unknown / null role — user hasn't answered Q2 yet.
+ return "assistant";
+}
diff --git a/packages/core/onboarding/step-order.ts b/packages/core/onboarding/step-order.ts
new file mode 100644
index 0000000000..4e6d9d3b44
--- /dev/null
+++ b/packages/core/onboarding/step-order.ts
@@ -0,0 +1,23 @@
+import type { OnboardingStep } from "./types";
+
+/**
+ * Canonical order of the persisted onboarding steps.
+ *
+ * Single source of truth for "what step comes after what" — consumed
+ * by the UI progress indicator to compute `index of current_step` and
+ * `total step count`. Inserting, reordering, or removing a step only
+ * requires changing this array; every call site that reads it updates
+ * automatically.
+ *
+ * Intentionally excludes "welcome": welcome is a first-entry product
+ * intro, not a persisted step. It doesn't show a progress indicator
+ * for the same reason — users shouldn't think of reading the intro
+ * as progress toward completing setup.
+ */
+export const ONBOARDING_STEP_ORDER: readonly OnboardingStep[] = [
+ "questionnaire",
+ "workspace",
+ "runtime",
+ "agent",
+ "first_issue",
+] as const;
diff --git a/packages/core/onboarding/store.ts b/packages/core/onboarding/store.ts
new file mode 100644
index 0000000000..3ae1d2bd2c
--- /dev/null
+++ b/packages/core/onboarding/store.ts
@@ -0,0 +1,46 @@
+import { api } from "../api";
+import { useAuthStore } from "../auth";
+import type { QuestionnaireAnswers } from "./types";
+
+/**
+ * Persist Q1/Q2/Q3 answers and sync the refreshed user into the auth
+ * store. Source of truth is `user.onboarding_questionnaire` (JSONB on
+ * the server). No client-side cache here.
+ *
+ * Resume-by-step is intentionally not persisted: every onboarding
+ * entry starts at Welcome. The questionnaire is the only piece of
+ * progress that survives a re-entry — it pre-fills Step 1 so the
+ * user doesn't re-answer.
+ */
+export async function saveQuestionnaire(
+ answers: Partial<QuestionnaireAnswers>,
+): Promise<void> {
+ const user = await api.patchOnboarding({ questionnaire: answers });
+ useAuthStore.getState().setUser(user);
+}
+
+/**
+ * Finalize onboarding. POST /complete marks `onboarded_at` atomically
+ * (COALESCE-guarded for idempotency). We then refresh the auth store
+ * so every gate sees the updated user.
+ */
+export async function completeOnboarding(): Promise<void> {
+ await api.markOnboardingComplete();
+ await useAuthStore.getState().refreshMe();
+}
+
+/**
+ * Records interest in cloud runtimes. Pure side effect — does NOT
+ * complete onboarding; the user still has to pick a real Step 3
+ * path (CLI with a detected runtime) or Skip to move on.
+ *
+ * Returned user object is not synced into the auth store because no
+ * user-visible field (`onboarded_at`, anything in `UserResponse`)
+ * actually changes here.
+ */
+export async function joinCloudWaitlist(
+ email: string,
+ reason: string,
+): Promise<void> {
+ await api.joinCloudWaitlist({ email, reason });
+}
diff --git a/packages/core/onboarding/types.ts b/packages/core/onboarding/types.ts
new file mode 100644
index 0000000000..df82654488
--- /dev/null
+++ b/packages/core/onboarding/types.ts
@@ -0,0 +1,32 @@
+export type OnboardingStep =
+ | "welcome"
+ | "questionnaire"
+ | "workspace"
+ | "runtime"
+ | "agent"
+ | "first_issue";
+
+export type TeamSize = "solo" | "team" | "other";
+
+export type Role =
+ | "developer"
+ | "product_lead"
+ | "writer"
+ | "founder"
+ | "other";
+
+export type UseCase =
+ | "coding"
+ | "planning"
+ | "writing_research"
+ | "explore"
+ | "other";
+
+export interface QuestionnaireAnswers {
+ team_size: TeamSize | null;
+ team_size_other: string | null;
+ role: Role | null;
+ role_other: string | null;
+ use_case: UseCase | null;
+ use_case_other: string | null;
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index c27e562761..43b781397a 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -55,6 +55,7 @@
"./realtime": "./realtime/index.ts",
"./navigation": "./navigation/index.ts",
"./modals": "./modals/index.ts",
+ "./onboarding": "./onboarding/index.ts",
"./paths": "./paths/index.ts",
"./hooks": "./hooks.tsx",
"./hooks/*": "./hooks/*.ts",
diff --git a/packages/core/paths/index.ts b/packages/core/paths/index.ts
index de15fceffc..172af2bdca 100644
--- a/packages/core/paths/index.ts
+++ b/packages/core/paths/index.ts
@@ -1,6 +1,7 @@
export { paths, isGlobalPath } from "./paths";
export type { WorkspacePaths } from "./paths";
export { RESERVED_SLUGS, isReservedSlug } from "./reserved-slugs";
+export { resolvePostAuthDestination, useHasOnboarded } from "./resolve";
export {
WorkspaceSlugProvider,
useWorkspaceSlug,
diff --git a/packages/core/paths/paths.ts b/packages/core/paths/paths.ts
index f46a528cd0..9b5e110f75 100644
--- a/packages/core/paths/paths.ts
+++ b/packages/core/paths/paths.ts
@@ -40,6 +40,7 @@ export const paths = {
login: () => "/login",
newWorkspace: () => "/workspaces/new",
invite: (id: string) => `/invite/${encode(id)}`,
+ onboarding: () => "/onboarding",
authCallback: () => "/auth/callback",
root: () => "/",
};
@@ -50,7 +51,7 @@ export type WorkspacePaths = ReturnType<typeof workspaceScoped>;
// A path is global if it equals or begins with any of these.
// Note: `/workspaces/` (trailing slash) is the prefix — `workspaces` is reserved,
// so any path starting with `/workspaces/...` is system-owned, not user-owned.
-const GLOBAL_PREFIXES = ["/login", "/workspaces/", "/invite/", "/auth/", "/logout", "/signup"];
+const GLOBAL_PREFIXES = ["/login", "/workspaces/", "/invite/", "/onboarding", "/auth/", "/logout", "/signup"];
export function isGlobalPath(path: string): boolean {
return GLOBAL_PREFIXES.some((p) => path === p || path.startsWith(p));
diff --git a/packages/core/paths/resolve.test.ts b/packages/core/paths/resolve.test.ts
new file mode 100644
index 0000000000..19522659bf
--- /dev/null
+++ b/packages/core/paths/resolve.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vitest";
+import type { Workspace } from "../types";
+import { paths } from "./paths";
+import { resolvePostAuthDestination } from "./resolve";
+
+function makeWs(slug: string): Workspace {
+ return {
+ id: `id-${slug}`,
+ name: slug,
+ slug,
+ description: null,
+ context: null,
+ settings: {},
+ repos: [],
+ issue_prefix: slug.toUpperCase(),
+ created_at: "",
+ updated_at: "",
+ };
+}
+
+describe("resolvePostAuthDestination", () => {
+ it("not onboarded → /onboarding regardless of workspaces", () => {
+ expect(resolvePostAuthDestination([], false)).toBe(paths.onboarding());
+ expect(resolvePostAuthDestination([makeWs("acme")], false)).toBe(
+ paths.onboarding(),
+ );
+ expect(
+ resolvePostAuthDestination([makeWs("acme"), makeWs("beta")], false),
+ ).toBe(paths.onboarding());
+ });
+
+ it("onboarded + has workspace → /<first.slug>/issues", () => {
+ const ws = [makeWs("acme"), makeWs("beta")];
+ expect(resolvePostAuthDestination(ws, true)).toBe(
+ paths.workspace("acme").issues(),
+ );
+ });
+
+ it("onboarded + zero workspaces → /workspaces/new", () => {
+ expect(resolvePostAuthDestination([], true)).toBe(paths.newWorkspace());
+ });
+});
diff --git a/packages/core/paths/resolve.ts b/packages/core/paths/resolve.ts
new file mode 100644
index 0000000000..5fcc66e94b
--- /dev/null
+++ b/packages/core/paths/resolve.ts
@@ -0,0 +1,28 @@
+import type { Workspace } from "../types";
+import { useAuthStore } from "../auth";
+import { paths } from "./paths";
+
+/**
+ * Priority:
+ * !hasOnboarded → /onboarding
+ * hasOnboarded && has workspace → /<first.slug>/issues
+ * hasOnboarded && zero workspaces → /workspaces/new
+ */
+export function resolvePostAuthDestination(
+ workspaces: Workspace[],
+ hasOnboarded: boolean,
+): string {
+ if (!hasOnboarded) {
+ return paths.onboarding();
+ }
+ const first = workspaces[0];
+ return first ? paths.workspace(first.slug).issues() : paths.newWorkspace();
+}
+
+/**
+ * Single source of truth: backed by `users.onboarded_at`, which
+ * arrives with the user object on every auth response.
+ */
+export function useHasOnboarded(): boolean {
+ return useAuthStore((s) => s.user?.onboarded_at != null);
+}
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index b25d256b2e..d73a0adc56 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -1,6 +1,6 @@
"use client";
-import { useEffect } from "react";
+import { useEffect, useRef } from "react";
import { useQueryClient } from "@tanstack/react-query";
import type { WSClient } from "../api/ws-client";
import type { StoreApi, UseBoundStore } from "zustand";
@@ -23,7 +23,7 @@ import { onInboxNew, onInboxInvalidate, onInboxIssueStatusChanged, onInboxIssueD
import { inboxKeys } from "../inbox/queries";
import { workspaceKeys, workspaceListOptions } from "../workspace/queries";
import { chatKeys } from "../chat/queries";
-import { paths } from "../paths";
+import { resolvePostAuthDestination, useHasOnboarded } from "../paths";
import type {
MemberAddedPayload,
WorkspaceDeletedPayload,
@@ -81,6 +81,14 @@ export function useRealtimeSync(
) {
const { authStore } = stores;
const qc = useQueryClient();
+
+ // Captured via ref so the (rare) hasOnboarded change doesn't re-subscribe
+ // every WS handler in this effect. The resolver reads `.current` at the
+ // moment workspace-loss fires, which is what we want.
+ const hasOnboarded = useHasOnboarded();
+ const hasOnboardedRef = useRef(hasOnboarded);
+ hasOnboardedRef.current = hasOnboarded;
+
// Main sync: onAny -> refreshMap with debounce
useEffect(() => {
if (!ws) return;
@@ -274,8 +282,11 @@ export function useRealtimeSync(
...workspaceListOptions(),
staleTime: 0,
});
- const next = wsList.find((w) => w.id !== lostWsId);
- const target = next ? paths.workspace(next.slug).issues() : paths.newWorkspace();
+ const remaining = wsList.filter((w) => w.id !== lostWsId);
+ const target = resolvePostAuthDestination(
+ remaining,
+ hasOnboardedRef.current,
+ );
if (typeof window !== "undefined") {
window.location.assign(target);
}
diff --git a/packages/core/types/workspace.ts b/packages/core/types/workspace.ts
index 4238cc8e5f..99ed28862f 100644
--- a/packages/core/types/workspace.ts
+++ b/packages/core/types/workspace.ts
@@ -31,6 +31,25 @@ export interface User {
name: string;
email: string;
avatar_url: string | null;
+ onboarded_at: string | null;
+ /**
+ * JSONB payload from the server. Typed as `unknown` here so this module
+ * stays independent of the questionnaire shape — the onboarding views
+ * cast into `Partial<QuestionnaireAnswers>` when reading. Server always
+ * returns an object (defaults to `{}`), never null.
+ */
+ onboarding_questionnaire: Record<string, unknown>;
+ /**
+ * Terminal state for the post-onboarding "import starter content" prompt.
+ * null → new user, dialog will show on issues-list landing
+ * 'imported' → accepted, starter project + issues were seeded
+ * 'dismissed' → declined, never ask again
+ * 'skipped_legacy' → backfilled for users who finished onboarding
+ * before this feature shipped
+ * Kept as a generic `string | null` here so future states (e.g.
+ * 'retry_after_error') can be added without churning this type.
+ */
+ starter_content_state: string | null;
created_at: string;
updated_at: string;
}
diff --git a/packages/ui/styles/base.css b/packages/ui/styles/base.css
index 72422005cc..e0ce8612ea 100644
--- a/packages/ui/styles/base.css
+++ b/packages/ui/styles/base.css
@@ -25,6 +25,46 @@
animation: entrance-spin 0.6s ease-out forwards;
}
+/* Onboarding: step / phase entry — 400ms fade + 4px rise.
+ * Matches the design prototype's .fade-in. Applied on mount so every new
+ * step (and intra-step phase switch, via key=phase remount) plays once.
+ * `both` fill-mode commits the `from` styles pre-animation to avoid a
+ * single-frame flash at natural state before the animation grabs. */
+@keyframes onboarding-enter {
+ from { opacity: 0; transform: translateY(4px); }
+}
+
+.animate-onboarding-enter {
+ animation: onboarding-enter 0.4s ease both;
+}
+
+/* Onboarding completion: success badge spring-pop.
+ * Lands with a subtle overshoot (scale 1.12 → 1) so the circle feels
+ * physical rather than linearly interpolated. Paired with the drawn
+ * checkmark below which kicks in after the badge has settled. */
+@keyframes completion-badge {
+ 0% { transform: scale(0); opacity: 0; }
+ 60% { transform: scale(1.12); opacity: 1; }
+ 100% { transform: scale(1); opacity: 1; }
+}
+
+.animate-completion-badge {
+ animation: completion-badge 500ms cubic-bezier(0.5, 1.5, 0.4, 1) both;
+}
+
+/* Onboarding completion: SVG checkmark drawn by animating
+ * stroke-dashoffset from 1 → 0. Requires the target <path> to declare
+ * `pathLength={1}` and `strokeDasharray={1}` so the stroke length is
+ * normalized and the animation is geometry-agnostic. */
+@keyframes completion-check {
+ from { stroke-dashoffset: 1; }
+ to { stroke-dashoffset: 0; }
+}
+
+.animate-completion-check {
+ animation: completion-check 400ms ease-out 350ms both;
+}
+
/* Chat FAB: gentle color + border tint while a chat task is running.
* Keeps the ring at the same thickness — only hue shifts towards brand
* at half-cycle, no outer glow. */
diff --git a/packages/ui/styles/tokens.css b/packages/ui/styles/tokens.css
index a0804490ce..e0bd46d512 100644
--- a/packages/ui/styles/tokens.css
+++ b/packages/ui/styles/tokens.css
@@ -3,6 +3,7 @@
@theme inline {
--font-heading: var(--font-sans);
--font-sans: var(--font-sans);
+ --font-serif: var(--font-serif);
--font-mono: var(--font-mono);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
diff --git a/packages/views/invite/invite-page.tsx b/packages/views/invite/invite-page.tsx
index 86bfa8e8b6..8438fe78b8 100644
--- a/packages/views/invite/invite-page.tsx
+++ b/packages/views/invite/invite-page.tsx
@@ -7,9 +7,14 @@ import {
workspaceKeys,
workspaceListOptions,
} from "@multica/core/workspace/queries";
-import { paths } from "@multica/core/paths";
+import {
+ paths,
+ resolvePostAuthDestination,
+ useHasOnboarded,
+} from "@multica/core/paths";
import { useNavigation } from "../navigation";
import { useLogout } from "../auth";
+import { DragStrip } from "../platform";
import { Button } from "@multica/ui/components/ui/button";
import { Card, CardContent } from "@multica/ui/components/ui/card";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
@@ -49,8 +54,8 @@ export function InvitePage({ invitationId, onBack }: InvitePageProps) {
// Workspace list for the fallback "Go to dashboard" destinations. The invite
// page is a pre-workspace global route so we can't rely on WorkspaceSlugProvider.
const { data: wsList = [] } = useQuery(workspaceListOptions());
- const fallbackDest =
- wsList[0] ? paths.workspace(wsList[0].slug).issues() : paths.newWorkspace();
+ const hasOnboarded = useHasOnboarded();
+ const fallbackDest = resolvePostAuthDestination(wsList, hasOnboarded);
const handleAccept = async () => {
setAccepting(true);
@@ -232,12 +237,13 @@ function InviteShell({
}) {
const logout = useLogout();
return (
- <div className="relative flex min-h-svh flex-col items-center justify-center bg-background px-6 py-12">
+ <div className="relative flex min-h-svh flex-col bg-background">
+ <DragStrip />
{onBack && (
<Button
variant="ghost"
size="sm"
- className="absolute top-12 left-12 text-muted-foreground"
+ className="absolute top-16 left-12 text-muted-foreground"
onClick={onBack}
>
<ArrowLeft />
@@ -247,13 +253,15 @@ function InviteShell({
<Button
variant="ghost"
size="sm"
- className="absolute top-12 right-12 text-muted-foreground hover:text-destructive"
+ className="absolute top-16 right-12 text-muted-foreground hover:text-destructive"
onClick={logout}
>
<LogOut />
Log out
</Button>
- {children}
+ <div className="flex flex-1 flex-col items-center justify-center px-6 pb-12">
+ {children}
+ </div>
</div>
);
}
diff --git a/packages/views/layout/use-dashboard-guard.ts b/packages/views/layout/use-dashboard-guard.ts
index 1fbcdd6aa4..5ff51bb480 100644
--- a/packages/views/layout/use-dashboard-guard.ts
+++ b/packages/views/layout/use-dashboard-guard.ts
@@ -4,7 +4,12 @@ import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { useNavigationStore } from "@multica/core/navigation";
import { useAuthStore } from "@multica/core/auth";
-import { useCurrentWorkspace, paths } from "@multica/core/paths";
+import {
+ paths,
+ resolvePostAuthDestination,
+ useCurrentWorkspace,
+ useHasOnboarded,
+} from "@multica/core/paths";
import { workspaceListOptions } from "@multica/core/workspace";
import { useNavigation } from "../navigation";
@@ -15,19 +20,22 @@ import { useNavigation } from "../navigation";
* - Auth still loading → wait
* - Not logged in → /login
* - Logged in but workspace list not yet loaded → wait (don't bounce prematurely)
- * - Logged in but URL slug doesn't resolve to any workspace → /workspaces/new
+ * - Logged in but URL slug doesn't resolve to any workspace →
+ * `resolvePostAuthDestination(list, hasOnboarded)` — onboarding for
+ * first-timers, /workspaces/new for returning users who deleted out.
*
* We read the workspace list query state directly (rather than relying on
* useCurrentWorkspace's null return) so we can distinguish "list loading"
* from "slug not found". Otherwise users could see a transient redirect
- * to /workspaces/new before their workspace list arrives.
+ * before their workspace list arrives.
*/
export function useDashboardGuard() {
const { pathname, replace } = useNavigation();
const user = useAuthStore((s) => s.user);
const isLoading = useAuthStore((s) => s.isLoading);
const workspace = useCurrentWorkspace();
- const { isFetched: workspaceListFetched } = useQuery({
+ const hasOnboarded = useHasOnboarded();
+ const { data: workspaces = [], isFetched: workspaceListFetched } = useQuery({
...workspaceListOptions(),
enabled: !!user,
});
@@ -38,12 +46,15 @@ export function useDashboardGuard() {
replace(paths.login());
return;
}
- // Wait for workspace list to settle before deciding "no workspace".
if (!workspaceListFetched) return;
+ if (!hasOnboarded) {
+ replace(paths.onboarding());
+ return;
+ }
if (!workspace) {
- replace(paths.newWorkspace());
+ replace(resolvePostAuthDestination(workspaces, hasOnboarded));
}
- }, [user, isLoading, workspaceListFetched, workspace, replace]);
+ }, [user, isLoading, workspaceListFetched, workspace, workspaces, hasOnboarded, replace]);
useEffect(() => {
useNavigationStore.getState().onPathChange(pathname);
diff --git a/packages/views/modals/create-workspace.tsx b/packages/views/modals/create-workspace.tsx
index 9763979d99..a61d225211 100644
--- a/packages/views/modals/create-workspace.tsx
+++ b/packages/views/modals/create-workspace.tsx
@@ -1,7 +1,7 @@
"use client";
import { useNavigation } from "../navigation";
-import { useImmersiveMode } from "../platform";
+import { DragStrip } from "../platform";
import { ArrowLeft } from "lucide-react";
import { Button } from "@multica/ui/components/ui/button";
import {
@@ -14,10 +14,6 @@ import { paths } from "@multica/core/paths";
import { CreateWorkspaceForm } from "../workspace/create-workspace-form";
export function CreateWorkspaceModal({ onClose }: { onClose: () => void }) {
- // This modal is full-screen, so it covers the app titlebar. On macOS desktop
- // we hide the traffic lights for its lifetime so the Back button in the top-
- // left corner isn't stolen by the native controls' hit-test. No-op elsewhere.
- useImmersiveMode();
const router = useNavigation();
return (
@@ -30,21 +26,19 @@ export function CreateWorkspaceModal({ onClose }: { onClose: () => void }) {
<DialogContent
finalFocus={false}
showCloseButton={false}
- className="inset-0 flex h-full w-full max-w-none sm:max-w-none translate-0 flex-col items-center justify-center rounded-none bg-background ring-0 shadow-none"
+ className="inset-0 flex h-full w-full max-w-none sm:max-w-none translate-0 flex-col rounded-none bg-background ring-0 shadow-none"
>
- {/* Top drag region — restores window-drag ability that the full-screen
- modal would otherwise swallow. Transparent; web browsers ignore the
- -webkit-app-region property, so this is safe cross-platform. */}
- <div
- aria-hidden
- className="absolute inset-x-0 top-0 h-10"
- style={{ WebkitAppRegion: "drag" } as React.CSSProperties}
- />
+ {/* DragStrip as flex child — macOS traffic lights stay visible and
+ the top 48px is draggable. Back button sits just below the strip
+ (top-16 = 64px), clear of both traffic lights (y<=27) and the
+ strip (y<=48). `no-drag` is a belt-and-braces guard in case the
+ button's layout ever creeps up into the strip zone. */}
+ <DragStrip />
<Button
variant="ghost"
size="sm"
- className="absolute top-12 left-12 text-muted-foreground"
+ className="absolute top-16 left-12 text-muted-foreground"
style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
onClick={onClose}
>
@@ -52,27 +46,29 @@ export function CreateWorkspaceModal({ onClose }: { onClose: () => void }) {
Back
</Button>
- <div className="flex w-full max-w-md flex-col items-center gap-6">
- <div className="text-center">
- <DialogTitle className="text-2xl font-semibold">
- Create a new workspace
- </DialogTitle>
- <DialogDescription className="mt-2">
- Workspaces are shared environments where teams can work on
- projects and issues.
- </DialogDescription>
+ <div className="flex flex-1 flex-col items-center justify-center px-6 pb-12">
+ <div className="flex w-full max-w-md flex-col items-center gap-6">
+ <div className="text-center">
+ <DialogTitle className="text-2xl font-semibold">
+ Create a new workspace
+ </DialogTitle>
+ <DialogDescription className="mt-2">
+ Workspaces are shared environments where teams can work on
+ projects and issues.
+ </DialogDescription>
+ </div>
+ <CreateWorkspaceForm
+ onSuccess={(newWs) => {
+ onClose();
+ // Navigate INTO the new workspace. The mutation's own onSuccess
+ // (in core/workspace/mutations.ts) runs before this callback and
+ // has already seeded the workspace list cache, so the destination
+ // [workspaceSlug]/layout will resolve newWs.slug → workspace
+ // synchronously without a loading flash.
+ router.push(paths.workspace(newWs.slug).issues());
+ }}
+ />
</div>
- <CreateWorkspaceForm
- onSuccess={(newWs) => {
- onClose();
- // Navigate INTO the new workspace. The mutation's own onSuccess
- // (in core/workspace/mutations.ts) runs before this callback and
- // has already seeded the workspace list cache, so the destination
- // [workspaceSlug]/layout will resolve newWs.slug → workspace
- // synchronously without a loading flash.
- router.push(paths.workspace(newWs.slug).issues());
- }}
- />
</div>
</DialogContent>
</Dialog>
diff --git a/packages/views/onboarding/components/cloud-waitlist-expand.tsx b/packages/views/onboarding/components/cloud-waitlist-expand.tsx
new file mode 100644
index 0000000000..4085c46389
--- /dev/null
+++ b/packages/views/onboarding/components/cloud-waitlist-expand.tsx
@@ -0,0 +1,135 @@
+"use client";
+
+import { useState } from "react";
+import { ArrowRight, Check, Loader2 } from "lucide-react";
+import { toast } from "sonner";
+import { Button } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
+import { Label } from "@multica/ui/components/ui/label";
+import { Textarea } from "@multica/ui/components/ui/textarea";
+import { joinCloudWaitlist } from "@multica/core/onboarding";
+
+const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+const REASON_MAX = 500;
+
+/**
+ * Cloud waitlist inline form — used from both:
+ * - web Step 3 (`StepPlatformFork` cloud fork)
+ * - desktop Step 3 empty state (`StepRuntimeConnect`)
+ *
+ * Submitting calls `joinCloudWaitlist` and disables the form. Does NOT
+ * advance the onboarding flow — the caller owns navigation (usually
+ * "Skip for now" in the footer). That keeps the contract consistent:
+ * waitlist is interest capture, Skip is the actual exit.
+ */
+export function CloudWaitlistExpand({
+ submitted,
+ onSubmitted,
+}: {
+ submitted: boolean;
+ onSubmitted: () => void;
+}) {
+ const [email, setEmail] = useState("");
+ const [reason, setReason] = useState("");
+ const [submitting, setSubmitting] = useState(false);
+
+ const canSubmit =
+ !submitted &&
+ !submitting &&
+ EMAIL_PATTERN.test(email.trim()) &&
+ reason.trim().length <= REASON_MAX;
+
+ const submit = async () => {
+ if (!canSubmit) return;
+ setSubmitting(true);
+ try {
+ await joinCloudWaitlist(email.trim(), reason.trim());
+ toast.success(
+ "You're on the list. We'll email when cloud runtimes are live.",
+ );
+ onSubmitted();
+ } catch (err) {
+ toast.error(
+ err instanceof Error ? err.message : "Failed to join waitlist",
+ );
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ return (
+ <div className="flex flex-col gap-4 rounded-lg border bg-muted/40 p-5">
+ <p className="text-[13.5px] leading-[1.55] text-foreground/85">
+ Cloud runtimes aren&apos;t live yet. Leave your email and we&apos;ll
+ reach out when they are.{" "}
+ <span className="text-foreground/70">
+ Heads-up: agents can&apos;t execute tasks without a runtime — if
+ you hit Skip now, your workspace is read-only until you come back
+ and install one.
+ </span>
+ </p>
+
+ <div className="flex flex-col gap-1.5">
+ <Label
+ htmlFor="waitlist-email"
+ className="text-xs font-medium text-muted-foreground"
+ >
+ Email
+ </Label>
+ <Input
+ id="waitlist-email"
+ type="email"
+ autoComplete="email"
+ value={email}
+ disabled={submitted}
+ placeholder="[email protected]"
+ onChange={(e) => setEmail(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ submit();
+ }
+ }}
+ />
+ </div>
+
+ <div className="flex flex-col gap-1.5">
+ <Label
+ htmlFor="waitlist-reason"
+ className="text-xs font-medium text-muted-foreground"
+ >
+ Why cloud?
+ <span className="ml-2 font-normal text-muted-foreground/70">
+ Optional
+ </span>
+ </Label>
+ <Textarea
+ id="waitlist-reason"
+ value={reason}
+ disabled={submitted}
+ onChange={(e) => setReason(e.target.value)}
+ placeholder="e.g. we want agents running 24/7, or my team works across different devices."
+ rows={3}
+ maxLength={REASON_MAX}
+ />
+ </div>
+
+ <div className="flex items-center justify-end">
+ <Button size="lg" disabled={submitted || !canSubmit} onClick={submit}>
+ {submitting && <Loader2 className="h-4 w-4 animate-spin" />}
+ {submitted ? (
+ <>
+ <Check className="h-4 w-4" />
+ You&apos;re on the list
+ </>
+ ) : (
+ <>
+ Join waitlist
+ <ArrowRight className="h-4 w-4" />
+ </>
+ )}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/onboarding/components/compact-runtime-row.tsx b/packages/views/onboarding/components/compact-runtime-row.tsx
new file mode 100644
index 0000000000..64ea4e5dca
--- /dev/null
+++ b/packages/views/onboarding/components/compact-runtime-row.tsx
@@ -0,0 +1,54 @@
+import { cn } from "@multica/ui/lib/utils";
+import type { AgentRuntime } from "@multica/core/types";
+import { ProviderLogo } from "../../runtimes/components/provider-logo";
+
+/**
+ * One-line runtime row for Step 3's web CLI expand. Provider logo,
+ * name + subtitle, online indicator on the right. Selection state is
+ * driven by the caller (kept stateless so both StepPlatformFork and
+ * any future embedder can share it without duplicating the picker
+ * plumbing).
+ */
+export function CompactRuntimeRow({
+ runtime,
+ selected,
+ onSelect,
+}: {
+ runtime: AgentRuntime;
+ selected: boolean;
+ onSelect: () => void;
+}) {
+ const online = runtime.status === "online";
+ return (
+ <div
+ role="button"
+ tabIndex={0}
+ onClick={onSelect}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ onSelect();
+ }
+ }}
+ className={cn(
+ "flex cursor-pointer flex-row items-center gap-3 rounded-lg border bg-card p-4 transition-colors",
+ selected
+ ? "border-primary ring-1 ring-primary"
+ : "hover:border-foreground/20",
+ )}
+ >
+ <ProviderLogo provider={runtime.provider} className="h-5 w-5" />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-sm font-medium">{runtime.name}</div>
+ <div className="text-xs text-muted-foreground">{runtime.provider}</div>
+ </div>
+ <span
+ className={cn(
+ "h-2 w-2 shrink-0 rounded-full",
+ online ? "bg-success" : "bg-muted-foreground/40",
+ )}
+ aria-label={online ? "Online" : "Offline"}
+ />
+ </div>
+ );
+}
diff --git a/packages/views/onboarding/components/option-card.tsx b/packages/views/onboarding/components/option-card.tsx
new file mode 100644
index 0000000000..3a4ae8c00b
--- /dev/null
+++ b/packages/views/onboarding/components/option-card.tsx
@@ -0,0 +1,122 @@
+"use client";
+
+import { Input } from "@multica/ui/components/ui/input";
+import { cn } from "@multica/ui/lib/utils";
+
+const OTHER_INPUT_MAX_LENGTH = 80;
+
+/**
+ * Editorial radio-style option row used in the Step 1 questionnaire.
+ *
+ * Design reference: onboarding(3) `.opt` — thin border resting, and on
+ * select: filled inset ring + radio marker turns into a filled dot.
+ * Enter/Space select; full row is the hit target. ARIA radio inside a
+ * containing `<fieldset role="radiogroup">` in StepQuestionnaire.
+ */
+export function OptionCard({
+ selected,
+ onSelect,
+ label,
+}: {
+ selected: boolean;
+ onSelect: () => void;
+ label: string;
+}) {
+ return (
+ <button
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ onClick={onSelect}
+ className={cn(
+ "group flex w-full items-center gap-3.5 rounded-lg border bg-card px-4 py-2.5 text-left transition-all",
+ selected
+ ? "border-foreground shadow-[inset_0_0_0_1px_var(--color-foreground)]"
+ : "hover:border-foreground/20 hover:bg-accent/30",
+ )}
+ >
+ <RadioMark selected={selected} />
+ <span className="text-[14.5px] font-normal leading-tight text-foreground">
+ {label}
+ </span>
+ </button>
+ );
+}
+
+/**
+ * "Other" variant — reveals an 80-char text input below the row once
+ * selected. Auto-focus on first open saves the user a click.
+ *
+ * Clearing `otherValue` when the user picks a sibling option is the
+ * parent questionnaire's job; this component stays focus-stable while
+ * the user is mid-typing.
+ */
+export function OtherOptionCard({
+ selected,
+ onSelect,
+ otherValue,
+ onOtherChange,
+ placeholder,
+}: {
+ selected: boolean;
+ onSelect: () => void;
+ otherValue: string;
+ onOtherChange: (value: string) => void;
+ placeholder: string;
+}) {
+ return (
+ <div
+ className={cn(
+ "flex w-full flex-col rounded-lg border bg-card transition-all",
+ selected
+ ? "border-foreground shadow-[inset_0_0_0_1px_var(--color-foreground)]"
+ : "hover:border-foreground/20",
+ )}
+ >
+ <button
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ onClick={onSelect}
+ className="flex w-full items-center gap-3.5 px-4 py-2.5 text-left"
+ >
+ <RadioMark selected={selected} />
+ <span className="text-[14.5px] font-normal leading-tight text-foreground">
+ Other
+ </span>
+ </button>
+ {selected && (
+ <div className="px-4 pb-3 pl-[44px]">
+ <Input
+ autoFocus
+ type="text"
+ value={otherValue}
+ onChange={(e) => onOtherChange(e.target.value)}
+ placeholder={placeholder}
+ maxLength={OTHER_INPUT_MAX_LENGTH}
+ className="h-8 rounded-none border-x-0 border-t-0 border-b px-0 text-sm shadow-none focus-visible:border-foreground focus-visible:ring-0"
+ aria-label={placeholder}
+ />
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function RadioMark({ selected }: { selected: boolean }) {
+ return (
+ <span
+ aria-hidden
+ className={cn(
+ "relative inline-block h-4 w-4 shrink-0 rounded-full border-[1.5px] transition-colors",
+ selected ? "border-foreground" : "border-border",
+ )}
+ >
+ {selected && (
+ <span className="absolute inset-[3px] rounded-full bg-foreground" />
+ )}
+ </span>
+ );
+}
+
+export { OTHER_INPUT_MAX_LENGTH };
diff --git a/packages/views/onboarding/components/runtime-aside-panel.tsx b/packages/views/onboarding/components/runtime-aside-panel.tsx
new file mode 100644
index 0000000000..fdb8c22397
--- /dev/null
+++ b/packages/views/onboarding/components/runtime-aside-panel.tsx
@@ -0,0 +1,70 @@
+/**
+ * Shared right-rail aside for Step 3 (runtime).
+ *
+ * Same content on both paths — desktop (runtime-connect FancyView)
+ * and web (platform-fork). Explains what a runtime is and reassures
+ * the user they can swap later. Designed to live inside a two-column
+ * editorial shell's `<aside>` column.
+ */
+export function RuntimeAsidePanel() {
+ return (
+ <div className="flex flex-col gap-6">
+ <section>
+ <div className="mb-3 text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">
+ What&apos;s a runtime?
+ </div>
+ <p className="text-[14px] leading-[1.6] text-foreground/80">
+ A <strong className="font-medium text-foreground">runtime</strong>{" "}
+ is a small background process that runs on your machine. It
+ connects your workspace to AI coding tools like Claude Code or
+ Codex, and executes the tasks your agents pick up.
+ </p>
+ </section>
+
+ <section>
+ <div className="mb-3 text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">
+ Good to know
+ </div>
+ <div className="flex flex-col gap-4">
+ <AsideItem
+ glyph="↻"
+ title="Swap anytime"
+ body="Each agent's runtime is just a setting. Change it whenever you want."
+ />
+ <AsideItem
+ glyph="∞"
+ title="Add more later"
+ body="You can connect a second runtime on another machine for a team, or a dedicated one per agent."
+ />
+ </div>
+ </section>
+ </div>
+ );
+}
+
+function AsideItem({
+ glyph,
+ title,
+ body,
+}: {
+ glyph: string;
+ title: string;
+ body: string;
+}) {
+ return (
+ <div className="grid grid-cols-[22px_1fr] gap-3">
+ <div
+ aria-hidden
+ className="flex h-[20px] w-[20px] items-center justify-center text-[14px] text-muted-foreground"
+ >
+ {glyph}
+ </div>
+ <div className="flex flex-col">
+ <div className="text-[13.5px] font-medium text-foreground">{title}</div>
+ <div className="mt-1 text-[12.5px] leading-[1.55] text-muted-foreground">
+ {body}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/onboarding/components/starter-content-prompt.tsx b/packages/views/onboarding/components/starter-content-prompt.tsx
new file mode 100644
index 0000000000..5d69192e92
--- /dev/null
+++ b/packages/views/onboarding/components/starter-content-prompt.tsx
@@ -0,0 +1,167 @@
+"use client";
+
+import { useState } from "react";
+import { Loader2 } from "lucide-react";
+import { toast } from "sonner";
+import { api } from "@multica/core/api";
+import { useAuthStore } from "@multica/core/auth";
+import { useNavigation } from "@multica/views/navigation";
+import { useCurrentWorkspace, paths } from "@multica/core/paths";
+import type { QuestionnaireAnswers } from "@multica/core/onboarding";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { buildImportPayload } from "../utils/starter-content-templates";
+
+/**
+ * Post-onboarding opt-in dialog.
+ *
+ * Shown exactly once per user, on the first workspace landing where
+ * `user.starter_content_state === null`. The dialog is mandatory —
+ * Import and Dismiss are the only exits. Both are terminal state
+ * transitions server-side (NULL → 'imported' or NULL → 'dismissed'),
+ * so the dialog never reappears on a subsequent visit.
+ *
+ * Client-side knowledge of agents is INTENTIONALLY zero here. The
+ * dialog description is branch-agnostic and the POST payload carries
+ * both sub-issue template arrays plus a welcome-issue template. The
+ * SERVER inspects the workspace's agent list and picks the branch —
+ * no client-side cache timing, no stale decisions, no Unknown bugs.
+ */
+export function StarterContentPrompt() {
+ const workspace = useCurrentWorkspace();
+ const user = useAuthStore((s) => s.user);
+ const refreshMe = useAuthStore((s) => s.refreshMe);
+ const { push } = useNavigation();
+
+ const [submitting, setSubmitting] = useState<"import" | "dismiss" | null>(
+ null,
+ );
+
+ const shouldShow =
+ !!user &&
+ !!workspace &&
+ user.onboarded_at != null &&
+ user.starter_content_state == null;
+
+ if (!shouldShow || !workspace || !user) return null;
+
+ const onImport = async () => {
+ if (submitting) return;
+ setSubmitting("import");
+ try {
+ const questionnaire = mergeQuestionnaire(user.onboarding_questionnaire);
+ const payload = buildImportPayload({
+ workspaceId: workspace.id,
+ userName: user.name || user.email,
+ questionnaire,
+ });
+ const result = await api.importStarterContent(payload);
+
+ // Sync the new starter_content_state into the auth store so this
+ // component unmounts cleanly on the next render.
+ await refreshMe();
+
+ toast.success("Starter tasks added — check your sidebar");
+
+ // If the server took the agent-guided branch, a welcome issue
+ // exists and we jump to it. Otherwise, stay on the issues list —
+ // the new Getting Started project appears via realtime events.
+ if (result.welcome_issue_id) {
+ push(
+ paths.workspace(workspace.slug).issueDetail(result.welcome_issue_id),
+ );
+ }
+ } catch (err) {
+ toast.error(
+ err instanceof Error ? err.message : "Import failed — please retry",
+ );
+ setSubmitting(null);
+ }
+ };
+
+ const onDismiss = async () => {
+ if (submitting) return;
+ setSubmitting("dismiss");
+ try {
+ await api.dismissStarterContent();
+ await refreshMe();
+ } catch (err) {
+ toast.error(
+ err instanceof Error
+ ? err.message
+ : "Could not dismiss — please retry",
+ );
+ setSubmitting(null);
+ }
+ };
+
+ return (
+ <Dialog
+ open
+ // `disablePointerDismissal` stops outside-click close; the
+ // `onOpenChange` handler cancels Base UI's ESC-close path via
+ // `eventDetails.cancel()`. Import / Dismiss are the only exits.
+ disablePointerDismissal
+ onOpenChange={(_open, eventDetails) => {
+ eventDetails.cancel();
+ }}
+ >
+ <DialogContent showCloseButton={false} className="sm:max-w-[440px]">
+ <DialogHeader>
+ <DialogTitle className="text-balance font-serif text-[22px] leading-[1.2] font-medium tracking-tight">
+ Welcome — add starter tasks?
+ </DialogTitle>
+ <DialogDescription className="pt-2 text-[14px] leading-[1.55]">
+ A{" "}
+ <span className="font-medium text-foreground">
+ Getting Started
+ </span>{" "}
+ project with short tasks that walk through how agents, issues,
+ and context work in Multica.
+ </DialogDescription>
+ </DialogHeader>
+
+ <DialogFooter className="mt-2 gap-2 sm:justify-end">
+ <Button
+ variant="ghost"
+ onClick={onDismiss}
+ disabled={submitting !== null}
+ >
+ {submitting === "dismiss" && (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ )}
+ Start blank workspace
+ </Button>
+ <Button onClick={onImport} disabled={submitting !== null}>
+ {submitting === "import" && (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ )}
+ Add starter tasks
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+// Local helper — mirrors the onboarding flow's mergeQuestionnaire.
+function mergeQuestionnaire(
+ raw: Record<string, unknown>,
+): QuestionnaireAnswers {
+ const empty: QuestionnaireAnswers = {
+ team_size: null,
+ team_size_other: null,
+ role: null,
+ role_other: null,
+ use_case: null,
+ use_case_other: null,
+ };
+ return { ...empty, ...(raw as Partial<QuestionnaireAnswers>) };
+}
diff --git a/packages/views/onboarding/components/step-header.test.tsx b/packages/views/onboarding/components/step-header.test.tsx
new file mode 100644
index 0000000000..859222550c
--- /dev/null
+++ b/packages/views/onboarding/components/step-header.test.tsx
@@ -0,0 +1,37 @@
+import { describe, expect, it } from "vitest";
+import { render, screen } from "@testing-library/react";
+import { ONBOARDING_STEP_ORDER } from "@multica/core/onboarding";
+import { StepHeader } from "./step-header";
+
+describe("StepHeader", () => {
+ it("renders one dot per step in ONBOARDING_STEP_ORDER", () => {
+ const { container } = render(<StepHeader currentStep="questionnaire" />);
+ const dots = container.querySelectorAll('[aria-hidden="true"]');
+ expect(dots).toHaveLength(ONBOARDING_STEP_ORDER.length);
+ });
+
+ it("shows 'Step N of M' text matching the current step's position", () => {
+ // workspace is index 1 (0-indexed) → Step 2 of 5
+ render(<StepHeader currentStep="workspace" />);
+ expect(
+ screen.getByText(`Step 2 of ${ONBOARDING_STEP_ORDER.length}`),
+ ).toBeInTheDocument();
+ });
+
+ it("sets accessible progressbar attrs", () => {
+ render(<StepHeader currentStep="agent" />);
+ const bar = screen.getByRole("progressbar");
+ expect(bar).toHaveAttribute("aria-valuenow", "4"); // agent is index 3 → step 4
+ expect(bar).toHaveAttribute("aria-valuemax", String(ONBOARDING_STEP_ORDER.length));
+ });
+
+ it("falls back to step 1 when given an unknown step", () => {
+ // TS would normally prevent this, but at runtime the store enum and
+ // the flow's local step could drift during a refactor — the header
+ // must not crash. Assert the defensive fallback lands on step 1.
+ render(<StepHeader currentStep={"bogus" as never} />);
+ expect(
+ screen.getByText(`Step 1 of ${ONBOARDING_STEP_ORDER.length}`),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/onboarding/components/step-header.tsx b/packages/views/onboarding/components/step-header.tsx
new file mode 100644
index 0000000000..7959efb591
--- /dev/null
+++ b/packages/views/onboarding/components/step-header.tsx
@@ -0,0 +1,72 @@
+"use client";
+
+import {
+ ONBOARDING_STEP_ORDER,
+ type OnboardingStep,
+} from "@multica/core/onboarding";
+import { cn } from "@multica/ui/lib/utils";
+
+/**
+ * Horizontal step indicator shown at the top of every onboarding step
+ * except Welcome.
+ *
+ * Layout: a row of dots on the left (one per step in
+ * `ONBOARDING_STEP_ORDER`) and a plaintext "Step N of M" counter on
+ * the right. The dots show three states driven by the current step's
+ * position in the canonical order:
+ *
+ * - `done` filled with primary color (index < current)
+ * - `current` filled + ring for emphasis (index === current)
+ * - `pending` hollow / muted (index > current)
+ *
+ * The indicator derives both its dots and text from the same source —
+ * the canonical ONBOARDING_STEP_ORDER plus the caller-provided
+ * `currentStep` — so adding, removing, or reordering a step only
+ * requires editing the array.
+ *
+ * Not rendered on the Welcome screen: the caller (OnboardingFlow)
+ * decides whether to include this component based on whether the
+ * current render step is "welcome". See flow orchestrator for the
+ * mapping from local UI step to the canonical `OnboardingStep`.
+ */
+export function StepHeader({ currentStep }: { currentStep: OnboardingStep }) {
+ const total = ONBOARDING_STEP_ORDER.length;
+ const currentIndex = ONBOARDING_STEP_ORDER.indexOf(currentStep);
+ // Defensive: unknown step → render a disabled-looking header rather
+ // than throw. Happens if the caller's local step union and the store
+ // enum drift during refactors.
+ const safeIndex = currentIndex === -1 ? 0 : currentIndex;
+
+ return (
+ <div
+ role="progressbar"
+ aria-valuemin={1}
+ aria-valuemax={total}
+ aria-valuenow={safeIndex + 1}
+ aria-label={`Step ${safeIndex + 1} of ${total}`}
+ className="flex w-full items-center justify-between py-2"
+ >
+ <div className="flex items-center gap-2">
+ {ONBOARDING_STEP_ORDER.map((stepId, i) => {
+ const isDone = i < safeIndex;
+ const isCurrent = i === safeIndex;
+ return (
+ <span
+ key={stepId}
+ aria-hidden
+ className={cn(
+ "h-2 w-2 rounded-full transition-colors",
+ isDone && "bg-primary",
+ isCurrent && "bg-primary ring-2 ring-primary/30 ring-offset-2 ring-offset-background",
+ !isDone && !isCurrent && "bg-muted",
+ )}
+ />
+ );
+ })}
+ </div>
+ <span className="text-xs font-medium text-muted-foreground">
+ Step {safeIndex + 1} of {total}
+ </span>
+ </div>
+ );
+}
diff --git a/packages/views/onboarding/components/use-runtime-picker.ts b/packages/views/onboarding/components/use-runtime-picker.ts
new file mode 100644
index 0000000000..41b29c3c07
--- /dev/null
+++ b/packages/views/onboarding/components/use-runtime-picker.ts
@@ -0,0 +1,61 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { useWSEvent } from "@multica/core/realtime";
+import {
+ runtimeKeys,
+ runtimeListOptions,
+} from "@multica/core/runtimes/queries";
+import type { AgentRuntime } from "@multica/core/types";
+
+/**
+ * Step 3's runtime data layer, shared by Desktop (`StepRuntimeConnect`)
+ * and Web (`StepPlatformFork`):
+ *
+ * - Polls every 2s while the list is empty so the UI flips to
+ * "found" the moment a runtime registers.
+ * - `daemon:register` WS event triggers an instant refetch — no
+ * polling lag for online users.
+ * - Auto-selects online first, falls back to the first runtime.
+ * Only runs when the user hasn't picked anything, so a manual
+ * selection survives subsequent refetches.
+ */
+export function useRuntimePicker(wsId: string): {
+ runtimes: AgentRuntime[];
+ selected: AgentRuntime | null;
+ selectedId: string | null;
+ setSelectedId: (id: string) => void;
+ hasRuntimes: boolean;
+} {
+ const qc = useQueryClient();
+
+ const { data: runtimes = [] } = useQuery({
+ ...runtimeListOptions(wsId, "me"),
+ refetchInterval: (q) => (q.state.data?.length ? false : 2000),
+ });
+
+ const handleDaemonEvent = useCallback(() => {
+ qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
+ }, [qc, wsId]);
+ useWSEvent("daemon:register", handleDaemonEvent);
+
+ const [selectedId, setSelectedId] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (selectedId) return;
+ const preferred =
+ runtimes.find((r) => r.status === "online") ?? runtimes[0];
+ if (preferred) setSelectedId(preferred.id);
+ }, [runtimes, selectedId]);
+
+ const selected = runtimes.find((r) => r.id === selectedId) ?? null;
+
+ return {
+ runtimes,
+ selected,
+ selectedId,
+ setSelectedId,
+ hasRuntimes: runtimes.length > 0,
+ };
+}
diff --git a/packages/views/onboarding/index.ts b/packages/views/onboarding/index.ts
new file mode 100644
index 0000000000..1dc95a2b6f
--- /dev/null
+++ b/packages/views/onboarding/index.ts
@@ -0,0 +1,3 @@
+export { OnboardingFlow, type OnboardingStep } from "./onboarding-flow";
+export { CliInstallInstructions } from "./steps/cli-install-instructions";
+export { StarterContentPrompt } from "./components/starter-content-prompt";
diff --git a/packages/views/onboarding/onboarding-flow.tsx b/packages/views/onboarding/onboarding-flow.tsx
new file mode 100644
index 0000000000..f6d8d85525
--- /dev/null
+++ b/packages/views/onboarding/onboarding-flow.tsx
@@ -0,0 +1,243 @@
+"use client";
+
+import { useCallback, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { setCurrentWorkspace } from "@multica/core/platform";
+import { useAuthStore } from "@multica/core/auth";
+import {
+ completeOnboarding,
+ ONBOARDING_STEP_ORDER,
+ saveQuestionnaire,
+ type OnboardingStep,
+ type QuestionnaireAnswers,
+} from "@multica/core/onboarding";
+import { workspaceListOptions } from "@multica/core/workspace/queries";
+import type { Agent, AgentRuntime, Workspace } from "@multica/core/types";
+import { DragStrip } from "@multica/views/platform";
+import { StepHeader } from "./components/step-header";
+import { StepWelcome } from "./steps/step-welcome";
+import { StepQuestionnaire } from "./steps/step-questionnaire";
+import { StepWorkspace } from "./steps/step-workspace";
+import { StepRuntimeConnect } from "./steps/step-runtime-connect";
+import { StepPlatformFork } from "./steps/step-platform-fork";
+import { StepAgent } from "./steps/step-agent";
+import { StepFirstIssue } from "./steps/step-first-issue";
+
+const EMPTY_QUESTIONNAIRE: QuestionnaireAnswers = {
+ team_size: null,
+ team_size_other: null,
+ role: null,
+ role_other: null,
+ use_case: null,
+ use_case_other: null,
+};
+
+function mergeQuestionnaire(
+ raw: Record<string, unknown>,
+): QuestionnaireAnswers {
+ return { ...EMPTY_QUESTIONNAIRE, ...(raw as Partial<QuestionnaireAnswers>) };
+}
+
+/**
+ * Shell's onComplete contract:
+ * onComplete(workspace?) — if present, navigate into its issues list;
+ * if omitted, fall back to root. A Starter-content opt-in dialog runs
+ * on the issues page itself (see `StarterContentPrompt`), so the flow
+ * doesn't carry `firstIssueId` any more — there is no welcome issue
+ * created by onboarding.
+ */
+export function OnboardingFlow({
+ onComplete,
+ runtimeInstructions,
+}: {
+ onComplete: (workspace?: Workspace) => void;
+ runtimeInstructions?: React.ReactNode;
+}) {
+ const user = useAuthStore((s) => s.user);
+ if (!user) {
+ throw new Error("OnboardingFlow requires an authenticated user");
+ }
+
+ // Questionnaire answers are server-persisted and pre-fill Step 1
+ // on re-entry. That's the only piece of onboarding state persisted
+ // across sessions — which step the user is on is deliberately not
+ // saved, so every entry starts at Welcome.
+ const storedQuestionnaire = mergeQuestionnaire(user.onboarding_questionnaire);
+
+ const [step, setStep] = useState<OnboardingStep>("welcome");
+ const [workspace, setWorkspace] = useState<Workspace | null>(null);
+ const [runtime, setRuntime] = useState<AgentRuntime | null>(null);
+ const [, setAgent] = useState<Agent | null>(null);
+
+ // Fetched at Step 0 + Step 2. Step 2 uses it to detect a pre-existing
+ // workspace from an earlier abandoned onboarding (so StepWorkspace shows
+ // "Continue with {name}" instead of CreateWorkspaceForm — avoiding the
+ // slug conflict that creation would hit). Step 0 uses it to decide
+ // whether to render the "I've done this before" skip button — only
+ // shown when the user already has at least one workspace, otherwise
+ // skipping would land them in limbo.
+ const { data: workspaces = [], isFetched: workspacesFetched } = useQuery({
+ ...workspaceListOptions(),
+ enabled: step === "welcome" || step === "workspace",
+ });
+ const existingWorkspace = workspace ?? workspaces[0] ?? null;
+ const canSkipWelcome = workspacesFetched && workspaces.length > 0;
+
+ const handleWelcomeNext = useCallback(() => {
+ setStep("questionnaire");
+ }, []);
+
+ // "I've done this before" path — returning user who already has a
+ // workspace and just wants to land there. Marks onboarding complete
+ // server-side (idempotent via COALESCE on onboarded_at) and navigates
+ // to their first workspace. Because starter_content_state is NULL for
+ // any user reaching this button (it's freshly added), they'll see the
+ // StarterContentPrompt dialog on arrival — which is correct, since
+ // they never got a starter project and may want one now.
+ const handleWelcomeSkip = useCallback(async () => {
+ try {
+ await completeOnboarding();
+ } catch (err) {
+ toast.error(
+ err instanceof Error ? err.message : "Failed to finish onboarding",
+ );
+ return;
+ }
+ onComplete(workspaces[0] ?? undefined);
+ }, [workspaces, onComplete]);
+
+ const handleQuestionnaireSubmit = useCallback(
+ async (answers: QuestionnaireAnswers) => {
+ await saveQuestionnaire(answers);
+ setStep("workspace");
+ },
+ [],
+ );
+
+ const handleWorkspaceCreated = useCallback((ws: Workspace) => {
+ setWorkspace(ws);
+ setCurrentWorkspace(ws.slug, ws.id);
+ setStep("runtime");
+ }, []);
+
+ const handleRuntimeNext = useCallback((rt: AgentRuntime | null) => {
+ setRuntime(rt);
+ // No runtime → no agent possible; skip Step 4 and go straight to
+ // the finalizer. The post-landing StarterContentPrompt will detect
+ // "no agent in this workspace" and offer the self-serve template.
+ setStep(rt ? "agent" : "first_issue");
+ }, []);
+
+ const handleAgentCreated = useCallback((created: Agent) => {
+ setAgent(created);
+ setStep("first_issue");
+ }, []);
+
+ const handleBack = useCallback((from: OnboardingStep) => {
+ const idx = ONBOARDING_STEP_ORDER.indexOf(from);
+ if (idx <= 0) return;
+ const prev = ONBOARDING_STEP_ORDER[idx - 1]!;
+ setStep(prev);
+ }, []);
+
+ // Step 5 fired `completeOnboarding` itself. Here we just route the
+ // user to their workspace — the starter-content decision happens
+ // inside the workspace via the `StarterContentPrompt` dialog.
+ const handleFinished = useCallback(() => {
+ onComplete(workspace ?? undefined);
+ }, [workspace, onComplete]);
+
+ // Welcome, Questionnaire, and Workspace own full-bleed two-column
+ // layouts (hero / side panel) with their own DragStrip + StepHeader.
+ // The remaining steps (runtime / agent / first_issue) still render
+ // inside a narrow legacy single-column shell below — they'll each
+ // move out as they get redesigned.
+ if (step === "welcome") {
+ return (
+ <StepWelcome
+ onNext={handleWelcomeNext}
+ onSkip={canSkipWelcome ? handleWelcomeSkip : undefined}
+ />
+ );
+ }
+
+ if (step === "questionnaire") {
+ return (
+ <StepQuestionnaire
+ initial={storedQuestionnaire}
+ onSubmit={handleQuestionnaireSubmit}
+ />
+ );
+ }
+
+ if (step === "workspace") {
+ return (
+ <StepWorkspace
+ existing={existingWorkspace}
+ onCreated={handleWorkspaceCreated}
+ onBack={() => handleBack("workspace")}
+ />
+ );
+ }
+
+ // Step 3. Both paths own full-bleed two-column layouts.
+ // - Desktop (no cliInstructions slot) → StepRuntimeConnect drives
+ // the local daemon's runtime list directly.
+ // - Web → StepPlatformFork offers Download / CLI / Cloud paths.
+ // Under the CLI path it embeds StepRuntimeConnect for the live
+ // probe; the Cloud path is a soft exit via the waitlist.
+ if (step === "runtime" && workspace) {
+ if (!runtimeInstructions) {
+ return (
+ <StepRuntimeConnect
+ wsId={workspace.id}
+ onNext={handleRuntimeNext}
+ onBack={() => handleBack("runtime")}
+ />
+ );
+ }
+ return (
+ <StepPlatformFork
+ wsId={workspace.id}
+ onNext={handleRuntimeNext}
+ onBack={() => handleBack("runtime")}
+ cliInstructions={runtimeInstructions}
+ />
+ );
+ }
+
+ // Step 4 owns the same full-bleed editorial shell as Workspace /
+ // Questionnaire. `questionnaire` is threaded through so StepAgent
+ // can recommend a template based on the user's Q1–Q3 answers.
+ // No skip path: reaching Step 4 means a runtime was picked at
+ // Step 3, so creating the agent IS the step's purpose. Users who
+ // want a runtime-less workspace bypass at Step 3 and skip Step 4
+ // entirely (flow routes runtime=null → first_issue directly).
+ if (step === "agent" && runtime) {
+ return (
+ <StepAgent
+ runtime={runtime}
+ questionnaire={storedQuestionnaire}
+ onCreated={handleAgentCreated}
+ onBack={() => handleBack("agent")}
+ />
+ );
+ }
+
+ return (
+ <div className="animate-onboarding-enter flex min-h-full flex-col">
+ <DragStrip />
+ <div className="flex flex-1 flex-col items-center px-6 pb-12">
+ <div className="flex w-full max-w-xl flex-col gap-8">
+ <StepHeader currentStep={step} />
+ {step === "first_issue" && (
+ <StepFirstIssue onFinished={handleFinished} />
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export type { OnboardingStep };
diff --git a/packages/views/onboarding/steps/cli-install-instructions.tsx b/packages/views/onboarding/steps/cli-install-instructions.tsx
new file mode 100644
index 0000000000..a11940f532
--- /dev/null
+++ b/packages/views/onboarding/steps/cli-install-instructions.tsx
@@ -0,0 +1,117 @@
+"use client";
+
+import { useState } from "react";
+import { Check, Copy, Terminal } from "lucide-react";
+import { Card, CardContent } from "@multica/ui/components/ui/card";
+
+const INSTALL_CMD =
+ "curl -fsSL https://raw.githubusercontent.com/multica-ai/multica/main/scripts/install.sh | bash";
+
+const CLOUD_API_URL = "https://api.multica.ai";
+
+/**
+ * Build the right `multica setup` command for the current deployment.
+ *
+ * - Cloud (api.multica.ai) or no apiUrl hint → plain `multica setup`
+ * (the CLI hardcodes the cloud endpoints inside setupCloud).
+ * - Any other apiUrl → `multica setup self-host --server-url ... --app-url ...`
+ * so dev (localhost) and on-prem both land on THIS server, not the
+ * public cloud. Dev is just the localhost case of self-host — no
+ * separate branch needed.
+ */
+function buildSetupCommand(apiUrl?: string, appUrl?: string): string {
+ if (!apiUrl || apiUrl === CLOUD_API_URL) return "multica setup";
+ const appPart = appUrl ? ` --app-url ${appUrl}` : "";
+ return `multica setup self-host --server-url ${apiUrl}${appPart}`;
+}
+
+function CopyButton({ text }: { text: string }) {
+ const [copied, setCopied] = useState(false);
+
+ const handleCopy = () => {
+ navigator.clipboard.writeText(text);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ };
+
+ return (
+ <button
+ type="button"
+ onClick={handleCopy}
+ className="shrink-0 rounded p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
+ aria-label="Copy"
+ >
+ {copied ? (
+ <Check className="h-3.5 w-3.5 text-success" />
+ ) : (
+ <Copy className="h-3.5 w-3.5" />
+ )}
+ </button>
+ );
+}
+
+/**
+ * CLI install instructions for the runtime step. Web-only by default —
+ * desktop has a bundled daemon that auto-starts, so install guidance is
+ * noise there. Rendered as an `instructions` slot inside the CLI dialog.
+ *
+ * Structure: two numbered steps shown in natural execution order. Install
+ * (step 1) MUST come before setup (step 2) — without the `multica` binary
+ * on PATH, step 2 can't run. A user who already has the CLI can safely
+ * skip step 1, but the numbering stays for the majority case of a fresh
+ * install.
+ *
+ * The `apiUrl` / `appUrl` props point the setup command at the right
+ * server. The web shell passes `process.env.NEXT_PUBLIC_API_URL` and
+ * `window.location.origin`; a self-host / dev deployment gets a
+ * `multica setup self-host --server-url ... --app-url ...` command;
+ * cloud gets the plain `multica setup`.
+ */
+export function CliInstallInstructions({
+ apiUrl,
+ appUrl,
+}: {
+ apiUrl?: string;
+ appUrl?: string;
+}) {
+ const setupCmd = buildSetupCommand(apiUrl, appUrl);
+ const steps = [
+ {
+ label: "Install the Multica CLI",
+ cmd: INSTALL_CMD,
+ note: null as string | null,
+ },
+ {
+ label: "Start the daemon",
+ cmd: setupCmd,
+ note:
+ "Opens a browser tab to sign you in, then starts a background daemon. The daemon keeps running after you close the terminal — your agents still pick up tasks.",
+ },
+ ];
+
+ return (
+ <Card className="w-full">
+ <CardContent className="space-y-4 pt-4">
+ {steps.map((step, i) => (
+ <div key={i}>
+ <p className="mb-1.5 text-xs font-medium text-foreground">
+ {i + 1}. {step.label}
+ </p>
+ <div className="flex items-start gap-2 rounded-lg bg-muted px-3 py-2.5 font-mono text-sm">
+ <Terminal className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <code className="min-w-0 flex-1 whitespace-pre-wrap break-all">
+ {step.cmd}
+ </code>
+ <CopyButton text={step.cmd} />
+ </div>
+ {step.note && (
+ <p className="mt-2 text-xs leading-[1.55] text-muted-foreground">
+ {step.note}
+ </p>
+ )}
+ </div>
+ ))}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/packages/views/onboarding/steps/step-agent.tsx b/packages/views/onboarding/steps/step-agent.tsx
new file mode 100644
index 0000000000..f78c7ba81b
--- /dev/null
+++ b/packages/views/onboarding/steps/step-agent.tsx
@@ -0,0 +1,360 @@
+"use client";
+
+import { useRef, useState } from "react";
+import { ArrowLeft, ArrowRight, Loader2 } from "lucide-react";
+import { toast } from "sonner";
+import { Button } from "@multica/ui/components/ui/button";
+import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";
+import { cn } from "@multica/ui/lib/utils";
+import { api } from "@multica/core/api";
+import {
+ recommendTemplate,
+ type AgentTemplateId,
+ type QuestionnaireAnswers,
+} from "@multica/core/onboarding";
+import type {
+ Agent,
+ AgentRuntime,
+ CreateAgentRequest,
+} from "@multica/core/types";
+import { DragStrip } from "@multica/views/platform";
+import { StepHeader } from "../components/step-header";
+
+/**
+ * Step 4 — create the user's first agent.
+ *
+ * Picks a recommended template from the questionnaire answers
+ * (`recommendTemplate()` maps role × use_case → one of 4 templates),
+ * attaches the template's default name + instructions, and ships a
+ * ready-to-work agent on Create. Layout mirrors Questionnaire /
+ * Workspace: a 2-column editorial shell with DragStrip + 3-region
+ * app column (header / scrollable main / footer) + "About agents"
+ * side panel hidden below lg.
+ *
+ * No rename, runtime-swap, or instructions editor on this step —
+ * every template defaults are good enough to ship immediately, and
+ * the agent settings page handles all customization post-onboarding.
+ * Intentional: minimizing surface area keeps time-to-first-agent low.
+ *
+ * No skip path either — if the user arrived here they have a runtime
+ * (Step 3 only routes to Step 4 when a runtime was picked), so
+ * creating an agent is the purpose of this step. Users who want a
+ * runtime-less workspace skip out at Step 3.
+ */
+interface AgentTemplate {
+ id: AgentTemplateId;
+ label: string;
+ defaultName: string;
+ emoji: string;
+ blurb: string;
+ instructions: string;
+}
+
+const AGENT_TEMPLATES: readonly AgentTemplate[] = [
+ {
+ id: "coding",
+ label: "Coding Agent",
+ defaultName: "Atlas",
+ emoji: "⌘",
+ blurb: "Writes, refactors, and ships code. Reads your repo.",
+ instructions:
+ "You are a Coding Agent on a product team. Pick up coding issues — implement features, fix bugs, write tests, and open pull requests. Read the repository before you start, follow existing code conventions, and keep diffs focused. Ask for clarification when the acceptance criteria are ambiguous.",
+ },
+ {
+ id: "planning",
+ label: "Planning Agent",
+ defaultName: "Orion",
+ emoji: "◐",
+ blurb: "Breaks down work, drafts specs, keeps the board tidy.",
+ instructions:
+ "You are a Planning Agent. Turn loose ideas and open issues into scoped, ready-to-execute work: break them down into subtasks, write acceptance criteria, and propose owners and sequencing. Prefer clarity over speed. When blocked by missing context, ask one specific question rather than guessing.",
+ },
+ {
+ id: "writing",
+ label: "Writing Agent",
+ defaultName: "Mira",
+ emoji: "✎",
+ blurb: "Drafts, summarizes, researches. Long-form friendly.",
+ instructions:
+ "You are a Writing Agent. Draft documents, summarize long content, and research topics on the web when needed. Structure your output as finished prose a reader can use directly — not an outline. Cite sources when you draw from them. Match the tone the user establishes in the issue.",
+ },
+ {
+ id: "assistant",
+ label: "Assistant",
+ defaultName: "Vega",
+ emoji: "✦",
+ blurb: "General-purpose. Good default when the task is unclear.",
+ instructions:
+ "You are a general-purpose teammate. Handle varied tasks — light coding, writing, research, planning — and stay pragmatic about scope. When the task is ambiguous, ask one clarifying question before diving in. Default to short, useful outputs over exhaustive ones.",
+ },
+] as const;
+
+const TEMPLATE_BY_ID: Record<AgentTemplateId, AgentTemplate> =
+ Object.fromEntries(AGENT_TEMPLATES.map((t) => [t.id, t])) as Record<
+ AgentTemplateId,
+ AgentTemplate
+ >;
+
+export function StepAgent({
+ runtime,
+ questionnaire,
+ onCreated,
+ onBack,
+}: {
+ runtime: AgentRuntime;
+ questionnaire: QuestionnaireAnswers;
+ onCreated: (agent: Agent) => void | Promise<void>;
+ onBack?: () => void;
+}) {
+ const recommendedId = recommendTemplate(questionnaire);
+ const recommended = TEMPLATE_BY_ID[recommendedId];
+
+ const [templateId, setTemplateId] =
+ useState<AgentTemplateId>(recommendedId);
+ const template = TEMPLATE_BY_ID[templateId];
+
+ const [creating, setCreating] = useState(false);
+
+ const handleCreate = async () => {
+ if (creating) return;
+ setCreating(true);
+ try {
+ const req: CreateAgentRequest = {
+ name: template.defaultName,
+ description: template.blurb,
+ instructions: template.instructions,
+ runtime_id: runtime.id,
+ visibility: "workspace",
+ };
+ const agent = await api.createAgent(req);
+ await onCreated(agent);
+ } catch (err) {
+ toast.error(
+ err instanceof Error ? err.message : "Failed to create agent",
+ );
+ setCreating(false);
+ }
+ };
+
+ const mainRef = useRef<HTMLElement>(null);
+ const fadeStyle = useScrollFade(mainRef);
+
+ return (
+ <div className="animate-onboarding-enter grid h-full min-h-0 grid-cols-1 lg:grid-cols-[minmax(0,1fr)_480px]">
+ {/* Left column — DragStrip + 3-region app shell */}
+ <div className="flex min-h-0 flex-col">
+ <DragStrip />
+ {/* Fixed header — Back + progress indicator */}
+ <header className="flex shrink-0 items-center gap-4 bg-background px-6 py-3 sm:px-10 md:px-14 lg:px-16">
+ {onBack ? (
+ <button
+ type="button"
+ onClick={onBack}
+ className="flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
+ >
+ <ArrowLeft className="h-3.5 w-3.5" />
+ Back
+ </button>
+ ) : (
+ <span aria-hidden className="w-0" />
+ )}
+ <div className="flex-1">
+ <StepHeader currentStep="agent" />
+ </div>
+ </header>
+
+ {/* Scrollable middle. `useScrollFade` softly masks content at
+ the header / footer edges as the user scrolls, replacing a
+ hard divider line. */}
+ <main
+ ref={mainRef}
+ style={fadeStyle}
+ className="min-h-0 flex-1 overflow-y-auto"
+ >
+ <div className="mx-auto w-full max-w-[620px] px-6 py-10 sm:px-10 md:px-14 lg:px-0 lg:py-14">
+ <div className="mb-2 text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">
+ Your first agent
+ </div>
+ <h1 className="text-balance font-serif text-[36px] font-medium leading-[1.1] tracking-tight text-foreground">
+ Meet your first teammate.
+ </h1>
+ <p className="mt-4 text-[15.5px] leading-[1.55] text-foreground/80">
+ Your answers point to a{" "}
+ <strong className="font-medium text-foreground">
+ {recommended.label}
+ </strong>
+ . Pick whichever of the four fits you — each template ships
+ ready to take its first issue. You can retune its
+ instructions from the agent settings page later.
+ </p>
+
+ <div className="mt-10 grid grid-cols-1 gap-3 sm:grid-cols-2">
+ {AGENT_TEMPLATES.map((t) => (
+ <TemplateCard
+ key={t.id}
+ template={t}
+ selected={templateId === t.id}
+ recommended={recommendedId === t.id}
+ onSelect={() => setTemplateId(t.id)}
+ />
+ ))}
+ </div>
+ </div>
+ </main>
+
+ {/* Fixed footer — hint + Create CTA. No skip path: reaching
+ Step 4 means a runtime was picked at Step 3, so creating
+ the agent IS this step. */}
+ <footer className="flex shrink-0 items-center justify-between gap-4 bg-background px-6 py-4 sm:px-10 md:px-14 lg:px-16">
+ <span className="hidden text-xs text-muted-foreground sm:block">
+ One agent is enough to start. Add more from the sidebar later.
+ </span>
+ <Button size="lg" onClick={handleCreate} disabled={creating}>
+ {creating && <Loader2 className="h-4 w-4 animate-spin" />}
+ Create {template.defaultName}
+ <ArrowRight className="h-4 w-4" />
+ </Button>
+ </footer>
+ </div>
+
+ {/* Right — About agents side panel, independent scroll */}
+ <aside className="hidden min-h-0 border-l bg-muted/40 lg:flex lg:flex-col">
+ <DragStrip />
+ <div className="min-h-0 flex-1 overflow-y-auto px-12 py-12">
+ <AboutAgentsSide />
+ </div>
+ </aside>
+ </div>
+ );
+}
+
+function TemplateCard({
+ template,
+ selected,
+ recommended,
+ onSelect,
+}: {
+ template: AgentTemplate;
+ selected: boolean;
+ recommended: boolean;
+ onSelect: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ onClick={onSelect}
+ className={cn(
+ "flex flex-col items-start gap-3 rounded-lg border bg-card px-4 py-4 text-left transition-all",
+ selected
+ ? "border-foreground shadow-[inset_0_0_0_1px_var(--color-foreground)]"
+ : "hover:border-foreground/20 hover:bg-accent/30",
+ )}
+ >
+ <div className="flex w-full items-start justify-between gap-2">
+ <span
+ aria-hidden
+ className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-muted/70 font-serif text-lg text-foreground/80"
+ >
+ {template.emoji}
+ </span>
+ {recommended && (
+ <span className="shrink-0 rounded-full bg-brand/10 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wider text-brand">
+ Recommended
+ </span>
+ )}
+ </div>
+ <div className="flex flex-col gap-1">
+ <div className="text-sm font-medium text-foreground">
+ {template.label}
+ </div>
+ <p className="text-xs leading-snug text-muted-foreground">
+ {template.blurb}
+ </p>
+ </div>
+ </button>
+ );
+}
+
+function AboutAgentsSide() {
+ return (
+ <div className="flex max-w-[380px] flex-col gap-8">
+ <section className="flex flex-col gap-4">
+ <div className="text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">
+ What&apos;s an agent
+ </div>
+ <h2 className="font-serif text-[22px] font-medium leading-[1.25] tracking-tight text-foreground">
+ An AI teammate that lives in your workspace.
+ </h2>
+ <p className="text-[14px] leading-[1.6] text-foreground/80">
+ Agents show up in every assignee picker, just like any other
+ colleague — except they can work 24/7 on whatever runtime you
+ give them.
+ </p>
+ </section>
+
+ <section className="flex flex-col gap-4">
+ <div className="text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">
+ Ways to work with an agent
+ </div>
+ <div className="flex flex-col gap-4">
+ <WayItem
+ glyph="→"
+ title="Assign it an issue"
+ body="It picks up the task and reports back in the thread."
+ />
+ <WayItem
+ glyph="@"
+ title="@mention in a comment"
+ body="Pull it into a conversation for a quick take."
+ />
+ <WayItem
+ glyph="◯"
+ title="Chat one-on-one"
+ body="Ask quick questions without creating an issue."
+ />
+ <WayItem
+ glyph="↻"
+ title="Put it on Autopilot"
+ body="Daily triage, weekly digest, monthly audit — on a schedule."
+ />
+ </div>
+ </section>
+
+ <p className="text-[13px] leading-[1.55] text-muted-foreground">
+ Add more agents anytime. A small team of specialized agents beats
+ one jack-of-all-trades.
+ </p>
+ </div>
+ );
+}
+
+function WayItem({
+ glyph,
+ title,
+ body,
+}: {
+ glyph: string;
+ title: string;
+ body: string;
+}) {
+ return (
+ <div className="grid grid-cols-[22px_1fr] gap-3">
+ <div
+ aria-hidden
+ className="flex h-[20px] w-[20px] items-center justify-center text-[14px] text-muted-foreground"
+ >
+ {glyph}
+ </div>
+ <div className="flex flex-col gap-1">
+ <div className="text-[14px] font-medium leading-tight text-foreground">
+ {title}
+ </div>
+ <p className="text-[13px] leading-[1.5] text-muted-foreground">
+ {body}
+ </p>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/onboarding/steps/step-first-issue.tsx b/packages/views/onboarding/steps/step-first-issue.tsx
new file mode 100644
index 0000000000..7348293b7f
--- /dev/null
+++ b/packages/views/onboarding/steps/step-first-issue.tsx
@@ -0,0 +1,102 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { Loader2, AlertCircle } from "lucide-react";
+import { toast } from "sonner";
+import { Button } from "@multica/ui/components/ui/button";
+import { completeOnboarding } from "@multica/core/onboarding";
+
+/**
+ * Step 5 — the final onboarding beat.
+ *
+ * All this step does now is flip `onboarded_at` on the server. The former
+ * in-flight bootstrap (welcome issue + Getting Started project + sub-issues)
+ * moved out of onboarding entirely: it's a post-landing opt-in dialog
+ * (`StarterContentPrompt`) that runs inside the workspace after navigation.
+ * Two consequences of that move:
+ *
+ * 1. This step can't fail in user-visible ways any more. `completeOnboarding`
+ * is one PATCH to `/api/me`; the only failure mode is a network error,
+ * which we surface as a toast + Retry, not a full error screen.
+ * 2. The sub-issue "Unknown" assignee race is gone for free — by the time
+ * the import runs, the user has already landed in the workspace, so
+ * `listMembers` has resolved and the current user's member_id is in
+ * the query cache.
+ */
+export function StepFirstIssue({
+ onFinished,
+}: {
+ /** Called after `onboarded_at` is set server-side. Parent handles
+ * navigation to the workspace landing page. */
+ onFinished: () => void;
+}) {
+ const [error, setError] = useState<string | null>(null);
+ const [retrying, setRetrying] = useState(false);
+ const started = useRef(false);
+ const onFinishedRef = useRef(onFinished);
+ onFinishedRef.current = onFinished;
+
+ useEffect(() => {
+ if (started.current) return;
+ started.current = true;
+ (async () => {
+ try {
+ await completeOnboarding();
+ onFinishedRef.current();
+ } catch (err) {
+ setError(
+ err instanceof Error ? err.message : "Failed to finish onboarding",
+ );
+ }
+ })();
+ }, []);
+
+ const retry = async () => {
+ if (retrying) return;
+ setRetrying(true);
+ setError(null);
+ try {
+ await completeOnboarding();
+ onFinishedRef.current();
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Retry failed");
+ toast.error(err instanceof Error ? err.message : "Retry failed");
+ } finally {
+ setRetrying(false);
+ }
+ };
+
+ if (error) {
+ return (
+ <div className="animate-onboarding-enter flex w-full flex-col items-center gap-6 text-center">
+ <div className="flex h-12 w-12 items-center justify-center rounded-full bg-destructive/10 text-destructive">
+ <AlertCircle className="h-6 w-6" />
+ </div>
+ <div className="flex flex-col gap-2">
+ <h1 className="text-2xl font-semibold tracking-tight">
+ Something went wrong
+ </h1>
+ <p className="text-sm text-muted-foreground">{error}</p>
+ </div>
+ <Button onClick={retry} disabled={retrying}>
+ {retrying && <Loader2 className="h-4 w-4 animate-spin" />}
+ Retry
+ </Button>
+ </div>
+ );
+ }
+
+ return (
+ <div className="animate-onboarding-enter flex w-full flex-col items-center gap-6 text-center">
+ <Loader2 className="h-10 w-10 animate-spin text-primary" />
+ <div className="flex flex-col gap-2">
+ <h1 className="text-2xl font-semibold tracking-tight">
+ Finishing up
+ </h1>
+ <p className="text-sm text-muted-foreground">
+ Almost there — opening your workspace.
+ </p>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/onboarding/steps/step-platform-fork.test.tsx b/packages/views/onboarding/steps/step-platform-fork.test.tsx
new file mode 100644
index 0000000000..d117fdead0
--- /dev/null
+++ b/packages/views/onboarding/steps/step-platform-fork.test.tsx
@@ -0,0 +1,289 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import { render, screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import type { AgentRuntime } from "@multica/core/types";
+
+// Mock the core onboarding module BEFORE the SUT imports it.
+const mocks = vi.hoisted(() => ({
+ joinCloudWaitlist: vi.fn(),
+ pickerState: {
+ runtimes: [] as AgentRuntime[],
+ selected: null as AgentRuntime | null,
+ selectedId: null as string | null,
+ setSelectedId: vi.fn<(id: string) => void>(),
+ hasRuntimes: false,
+ },
+}));
+
+// Partial mock — preserve ONBOARDING_STEP_ORDER etc. that StepHeader
+// (rendered inside the fork) reaches for, while replacing the network
+// call we want to assert on.
+vi.mock("@multica/core/onboarding", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("@multica/core/onboarding")>();
+ return {
+ ...actual,
+ joinCloudWaitlist: mocks.joinCloudWaitlist,
+ };
+});
+
+// Swap out the runtime picker so tests can drive runtimes / selection
+// without a real TanStack Query + WS stack.
+vi.mock("../components/use-runtime-picker", () => ({
+ useRuntimePicker: () => mocks.pickerState,
+}));
+
+import { StepPlatformFork } from "./step-platform-fork";
+
+function makeRuntime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {
+ return {
+ id: "rt_test",
+ workspace_id: "ws_test",
+ name: "Claude Code",
+ provider: "claude",
+ status: "online",
+ runtime_mode: "local",
+ runtime_config: {},
+ device_info: "",
+ metadata: {},
+ daemon_id: null,
+ last_seen_at: new Date().toISOString(),
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
+ ...overrides,
+ } as unknown as AgentRuntime;
+}
+
+function renderFork(
+ overrides: Partial<React.ComponentProps<typeof StepPlatformFork>> = {},
+) {
+ const onNext = vi.fn();
+ render(
+ <StepPlatformFork
+ wsId="ws_test"
+ onNext={onNext}
+ cliInstructions={<div data-testid="cli-instructions">install me</div>}
+ {...overrides}
+ />,
+ );
+ return { onNext };
+}
+
+function resetPicker(patch: Partial<typeof mocks.pickerState> = {}) {
+ mocks.pickerState.runtimes = patch.runtimes ?? [];
+ mocks.pickerState.selected = patch.selected ?? null;
+ mocks.pickerState.selectedId = patch.selectedId ?? null;
+ mocks.pickerState.hasRuntimes = patch.hasRuntimes ?? false;
+ mocks.pickerState.setSelectedId = vi.fn();
+}
+
+describe("StepPlatformFork", () => {
+ beforeEach(() => {
+ mocks.joinCloudWaitlist.mockReset();
+ resetPicker();
+ vi.restoreAllMocks();
+ // Stub navigator so the component's post-hydration isMac check
+ // lands on the macOS branch by default. One test below overrides
+ // this to cover the non-Mac variant.
+ Object.defineProperty(window.navigator, "userAgent", {
+ value:
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
+ configurable: true,
+ });
+ });
+
+ it("renders the three fork options at rest", () => {
+ renderFork();
+ expect(screen.getByText(/download the desktop app/i)).toBeInTheDocument();
+ expect(screen.getByText(/^install the cli$/i)).toBeInTheDocument();
+ expect(screen.getByText(/^cloud runtime$/i)).toBeInTheDocument();
+ // Dialogs closed at rest → no CLI instructions, no email field.
+ expect(screen.queryByTestId("cli-instructions")).not.toBeInTheDocument();
+ expect(screen.queryByLabelText(/email/i)).not.toBeInTheDocument();
+ });
+
+ it("footer: Skip only + explanatory hint (no Continue)", () => {
+ renderFork();
+ expect(
+ screen.getByRole("button", { name: /skip for now/i }),
+ ).toBeEnabled();
+ // Continue is gone — it lived in the footer before; now advancement
+ // for the CLI path is owned by the CLI dialog's own button.
+ expect(
+ screen.queryByRole("button", { name: /^continue$/i }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByText(/pick a path above — or skip and configure/i),
+ ).toBeInTheDocument();
+ });
+
+ it("Skip is always enabled and calls onNext(null)", async () => {
+ const user = userEvent.setup();
+ const { onNext } = renderFork();
+ await user.click(screen.getByRole("button", { name: /skip for now/i }));
+ expect(onNext).toHaveBeenCalledTimes(1);
+ expect(onNext).toHaveBeenCalledWith(null);
+ });
+
+ it("opens the download URL and flips the card to a post-click state", async () => {
+ const openSpy = vi.spyOn(window, "open").mockReturnValue(null);
+ const user = userEvent.setup();
+ renderFork();
+
+ await user.click(screen.getByText(/download the desktop app/i));
+
+ expect(openSpy).toHaveBeenCalledWith(
+ "https://github.com/multica-ai/multica/releases/latest",
+ "_blank",
+ "noopener,noreferrer",
+ );
+ expect(screen.getByText(/downloading multica/i)).toBeInTheDocument();
+ });
+
+ it("CLI dialog: opens with instructions + 'waiting' and a disabled Connect button", async () => {
+ const user = userEvent.setup();
+ renderFork();
+
+ await user.click(screen.getByRole("button", { name: /show steps/i }));
+
+ const dialog = await screen.findByRole("dialog");
+ expect(within(dialog).getByTestId("cli-instructions")).toBeInTheDocument();
+ expect(
+ within(dialog).getByText(/listening for your daemon/i),
+ ).toBeInTheDocument();
+ // Connect & continue stays disabled while no runtime is selected.
+ expect(
+ within(dialog).getByRole("button", { name: /connect & continue/i }),
+ ).toBeDisabled();
+ });
+
+ it("CLI dialog with a selected runtime: Connect enables and fires onNext(runtime)", async () => {
+ const rt = makeRuntime({ id: "rt_claude", name: "Claude Code" });
+ resetPicker({
+ runtimes: [rt],
+ selected: rt,
+ selectedId: rt.id,
+ hasRuntimes: true,
+ });
+ const user = userEvent.setup();
+ const { onNext } = renderFork();
+
+ await user.click(screen.getByRole("button", { name: /show steps/i }));
+
+ const dialog = await screen.findByRole("dialog");
+ expect(within(dialog).getByText(/1 runtime connected/i)).toBeInTheDocument();
+ expect(
+ within(dialog).getByText(/selected: claude code/i),
+ ).toBeInTheDocument();
+
+ const connect = within(dialog).getByRole("button", {
+ name: /connect & continue/i,
+ });
+ expect(connect).toBeEnabled();
+ await user.click(connect);
+ expect(onNext).toHaveBeenCalledTimes(1);
+ expect(onNext).toHaveBeenCalledWith(rt);
+ });
+
+ it("Cloud dialog submission does NOT advance the flow", async () => {
+ // Even with runtimes detected in the background, submitting the
+ // cloud waitlist form must not call onNext — it's pure interest
+ // capture. The user still has to hit Skip explicitly afterwards.
+ const rt = makeRuntime();
+ resetPicker({
+ runtimes: [rt],
+ selected: rt,
+ selectedId: rt.id,
+ hasRuntimes: true,
+ });
+ mocks.joinCloudWaitlist.mockResolvedValue(undefined);
+ const user = userEvent.setup();
+ const { onNext } = renderFork();
+
+ await user.click(screen.getByRole("button", { name: /^join waitlist$/i }));
+ const dialog = await screen.findByRole("dialog");
+ await user.type(within(dialog).getByLabelText(/email/i), "[email protected]");
+ await user.click(
+ within(dialog).getByRole("button", { name: /^join waitlist$/i }),
+ );
+
+ expect(mocks.joinCloudWaitlist).toHaveBeenCalled();
+ expect(onNext).not.toHaveBeenCalled();
+ });
+
+ it("Cloud submit: disables button, shows 'on the list', does NOT navigate", async () => {
+ mocks.joinCloudWaitlist.mockResolvedValue(undefined);
+ const user = userEvent.setup();
+ const { onNext } = renderFork();
+
+ await user.click(screen.getByRole("button", { name: /^join waitlist$/i }));
+ const dialog = await screen.findByRole("dialog");
+ await user.type(within(dialog).getByLabelText(/email/i), "[email protected]");
+ await user.type(
+ within(dialog).getByLabelText(/why cloud/i),
+ "running agents overnight",
+ );
+ await user.click(
+ within(dialog).getByRole("button", { name: /^join waitlist$/i }),
+ );
+
+ expect(mocks.joinCloudWaitlist).toHaveBeenCalledTimes(1);
+ expect(mocks.joinCloudWaitlist).toHaveBeenCalledWith(
+ "running agents overnight",
+ );
+ // Cloud submit is pure side effect — it must NOT advance the flow.
+ expect(onNext).not.toHaveBeenCalled();
+ // Form button locks out after submit.
+ expect(
+ within(dialog).getByRole("button", { name: /you're on the list/i }),
+ ).toBeDisabled();
+ // Footer hint flips to reflect submitted state.
+ expect(
+ screen.getByText(/you're on the waitlist — pick skip to keep exploring/i),
+ ).toBeInTheDocument();
+ });
+
+ it("Cloud submit: empty reason is allowed, reason forwarded as ''", async () => {
+ mocks.joinCloudWaitlist.mockResolvedValue(undefined);
+ const user = userEvent.setup();
+ renderFork();
+
+ await user.click(screen.getByRole("button", { name: /^join waitlist$/i }));
+ const dialog = await screen.findByRole("dialog");
+ await user.type(
+ within(dialog).getByLabelText(/email/i),
+ );
+ await user.click(
+ within(dialog).getByRole("button", { name: /^join waitlist$/i }),
+ );
+
+ expect(mocks.joinCloudWaitlist).toHaveBeenCalledWith(
+ "",
+ );
+ });
+
+ it("Cloud submit stays disabled until email is valid", async () => {
+ const user = userEvent.setup();
+ renderFork();
+
+ await user.click(screen.getByRole("button", { name: /^join waitlist$/i }));
+ const dialog = await screen.findByRole("dialog");
+ const submit = within(dialog).getByRole("button", {
+ name: /^join waitlist$/i,
+ });
+ expect(submit).toBeDisabled();
+
+ await user.type(within(dialog).getByLabelText(/email/i), "not-an-email");
+ expect(submit).toBeDisabled();
+
+ await user.clear(within(dialog).getByLabelText(/email/i));
+ await user.type(
+ within(dialog).getByLabelText(/email/i),
+ );
+ expect(submit).toBeEnabled();
+ });
+});
diff --git a/packages/views/onboarding/steps/step-platform-fork.tsx b/packages/views/onboarding/steps/step-platform-fork.tsx
new file mode 100644
index 0000000000..95c3471fb1
--- /dev/null
+++ b/packages/views/onboarding/steps/step-platform-fork.tsx
@@ -0,0 +1,604 @@
+"use client";
+
+import { useEffect, useRef, useState, type ReactNode } from "react";
+import { ArrowLeft, ArrowRight, Download } from "lucide-react";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";
+import { cn } from "@multica/ui/lib/utils";
+import type { AgentRuntime } from "@multica/core/types";
+import { DragStrip } from "@multica/views/platform";
+import { StepHeader } from "../components/step-header";
+import { RuntimeAsidePanel } from "../components/runtime-aside-panel";
+import { CompactRuntimeRow } from "../components/compact-runtime-row";
+import { useRuntimePicker } from "../components/use-runtime-picker";
+import { CloudWaitlistExpand } from "../components/cloud-waitlist-expand";
+
+/**
+ * Step 3 on **web**. The user is in a browser and hasn't downloaded
+ * the desktop app yet, so we can't scan their machine for runtimes.
+ * This screen is a fan-out: three clearly clickable cards, each with
+ * an explicit right-side button that says what clicking does:
+ *
+ * 1. **Download desktop** — primary card, black bg, "Download" pill.
+ * Opens the installer in a new tab; the user finishes onboarding
+ * inside the desktop app.
+ * 2. **Install the CLI** — alt card, "Show steps" pill → opens a
+ * dialog containing the real install instructions + live runtime
+ * probe. When a runtime appears and the user selects it, the
+ * dialog's "Connect & continue" button fires `onNext(runtime)`
+ * and advances the flow.
+ * 3. **Cloud waitlist** — alt card, "Join waitlist" pill → opens a
+ * dialog with an email + reason form. Submitting is pure interest
+ * capture; the dialog doesn't advance the flow. The user then
+ * closes the dialog and can hit Skip in the footer.
+ *
+ * Footer is simplified — no Continue button, since the CLI dialog
+ * owns that advancement itself. Only Skip remains.
+ */
+
+type DialogState = "cli" | "cloud" | null;
+
+// Kept in sync with the Landing page's "Download Desktop" CTA
+// (apps/web/features/landing/components/landing-hero.tsx). Both point
+// at the GitHub Releases latest page, which redirects to the current
+// tag and lists the platform-specific .dmg / .zip assets. There is no
+// multica.ai-hosted download page — do not invent one here.
+const DESKTOP_DOWNLOAD_URL =
+ "https://github.com/multica-ai/multica/releases/latest";
+
+export function StepPlatformFork({
+ wsId,
+ onNext,
+ onBack,
+ cliInstructions,
+}: {
+ wsId: string;
+ onNext: (runtime: AgentRuntime | null) => void | Promise<void>;
+ onBack?: () => void;
+ /** Platform-specific CLI install card, rendered inside the CLI dialog. */
+ cliInstructions?: ReactNode;
+}) {
+ const mainRef = useRef<HTMLElement>(null);
+ const fadeStyle = useScrollFade(mainRef);
+
+ const [dialog, setDialog] = useState<DialogState>(null);
+ const [downloaded, setDownloaded] = useState(false);
+ const [waitlistSubmitted, setWaitlistSubmitted] = useState(false);
+
+ // Desktop app currently ships macOS binaries only (see electron-builder
+ // config + release workflow). On non-mac platforms we keep the card
+ // visible but muted, and redirect users to the CLI path.
+ // Default true to match SSR; useEffect corrects post-hydration.
+ const [isMac, setIsMac] = useState(true);
+ useEffect(() => {
+ if (typeof navigator === "undefined") return;
+ const p = navigator.platform || "";
+ const ua = navigator.userAgent || "";
+ setIsMac(/Mac|iPhone|iPad|iPod/i.test(p) || /Mac OS X/i.test(ua));
+ }, []);
+
+ const picker = useRuntimePicker(wsId);
+
+ const pickDesktop = () => {
+ window.open(DESKTOP_DOWNLOAD_URL, "_blank", "noopener,noreferrer");
+ setDownloaded(true);
+ };
+
+ const handleCliConnect = () => {
+ if (!picker.selected) return;
+ setDialog(null);
+ onNext(picker.selected);
+ };
+
+ const footerHint = (() => {
+ if (waitlistSubmitted) {
+ return "You're on the waitlist — pick Skip to keep exploring.";
+ }
+ if (downloaded) {
+ return "Downloading… finish setup in the desktop app, or pick another path.";
+ }
+ if (!isMac) {
+ return "Install the CLI to connect a runtime, or skip for now.";
+ }
+ return "Pick a path above — or skip and configure a runtime later.";
+ })();
+
+ return (
+ <div className="animate-onboarding-enter grid h-full min-h-0 grid-cols-1 lg:grid-cols-[minmax(0,1fr)_480px]">
+ {/* Left — DragStrip + 3-region app shell */}
+ <div className="flex min-h-0 flex-col">
+ <DragStrip />
+
+ <header className="flex shrink-0 items-center gap-4 bg-background px-6 py-3 sm:px-10 md:px-14 lg:px-16">
+ {onBack ? (
+ <button
+ type="button"
+ onClick={onBack}
+ className="flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
+ >
+ <ArrowLeft className="h-3.5 w-3.5" />
+ Back
+ </button>
+ ) : (
+ <span aria-hidden className="w-0" />
+ )}
+ <div className="flex-1">
+ <StepHeader currentStep="runtime" />
+ </div>
+ </header>
+
+ <main
+ ref={mainRef}
+ style={fadeStyle}
+ className="min-h-0 flex-1 overflow-y-auto"
+ >
+ <div className="mx-auto w-full max-w-[620px] px-6 py-10 sm:px-10 md:px-14 lg:px-0 lg:py-14">
+ <div className="mb-2 text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">
+ Step 3 · Runtime
+ </div>
+ <h1 className="text-balance font-serif text-[36px] font-medium leading-[1.1] tracking-tight text-foreground">
+ Connect a runtime.
+ </h1>
+ <p className="mt-4 max-w-[560px] text-[15.5px] leading-[1.55] text-muted-foreground">
+ A runtime is what actually runs your agents&apos; work. Pick
+ how you&apos;d like to set one up.
+ </p>
+
+ <div className="mt-10 flex max-w-[560px] flex-col gap-3.5">
+ <ForkPrimary
+ onClick={pickDesktop}
+ downloaded={downloaded}
+ isMac={isMac}
+ />
+
+ <ForkAlt
+ title="Install the CLI"
+ subtitle="Run the Multica daemon yourself — a couple of terminal commands."
+ actionLabel="Show steps"
+ onAction={() => setDialog("cli")}
+ />
+
+ <ForkAlt
+ title="Cloud runtime"
+ subtitle="We host it for you. Not live yet — leave your email and we'll let you know."
+ actionLabel={
+ waitlistSubmitted ? "On the list" : "Join waitlist"
+ }
+ onAction={() => setDialog("cloud")}
+ />
+ </div>
+ </div>
+ </main>
+
+ {/* Footer — hint on the left, Skip on the right. Advancement
+ for the CLI path is owned by the CLI dialog's own
+ "Connect & continue" button; Skip is the self-serve exit. */}
+ <footer className="flex shrink-0 items-center justify-between gap-4 bg-background px-6 py-4 sm:px-10 md:px-14 lg:px-16">
+ <span
+ aria-live="polite"
+ className="text-xs text-muted-foreground"
+ >
+ {footerHint}
+ </span>
+ <Button variant="secondary" onClick={() => onNext(null)}>
+ Skip for now
+ </Button>
+ </footer>
+ </div>
+
+ {/* Right — always-visible aside */}
+ <aside className="hidden min-h-0 border-l bg-muted/40 lg:flex lg:flex-col">
+ <DragStrip />
+ <div className="min-h-0 flex-1 overflow-y-auto px-12 py-12">
+ <RuntimeAsidePanel />
+ </div>
+ </aside>
+
+ <CliInstallDialog
+ open={dialog === "cli"}
+ onClose={() => setDialog(null)}
+ onConnect={handleCliConnect}
+ runtimes={picker.runtimes}
+ selectedId={picker.selectedId}
+ onSelect={picker.setSelectedId}
+ hasRuntimes={picker.hasRuntimes}
+ canConnect={picker.selected !== null}
+ selectedName={picker.selected?.name ?? null}
+ cliInstructions={cliInstructions}
+ />
+
+ <CloudWaitlistDialog
+ open={dialog === "cloud"}
+ onClose={() => setDialog(null)}
+ submitted={waitlistSubmitted}
+ onSubmitted={() => setWaitlistSubmitted(true)}
+ />
+ </div>
+ );
+}
+
+// ------------------------------------------------------------
+// Fork cards
+// ------------------------------------------------------------
+
+function ForkPrimary({
+ onClick,
+ downloaded,
+ isMac,
+}: {
+ onClick: () => void;
+ downloaded: boolean;
+ isMac: boolean;
+}) {
+ // On non-mac platforms we can't deliver a binary yet. The card stays
+ // visible so users understand the desktop app exists, but it's muted
+ // and steers them down to the CLI path.
+ if (!isMac) {
+ return (
+ <div
+ aria-disabled="true"
+ className="flex cursor-not-allowed items-center justify-between gap-4 rounded-xl border bg-muted/40 px-6 py-5 text-left"
+ >
+ <div className="min-w-0">
+ <div className="flex items-center gap-2 text-[17px] font-medium tracking-tight text-muted-foreground">
+ <Download className="h-4 w-4" aria-hidden />
+ Desktop app — macOS only for now
+ </div>
+ <div className="mt-1 text-[13px] text-muted-foreground/80">
+ Windows and Linux builds are on the way. In the meantime,
+ install the CLI below — it takes about two minutes.
+ </div>
+ </div>
+ <span
+ aria-hidden
+ className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground"
+ >
+ <ArrowRight className="h-4 w-4" />
+ </span>
+ </div>
+ );
+ }
+
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={cn(
+ "group flex items-center justify-between gap-4 rounded-xl bg-foreground px-6 py-5 text-left text-background transition-transform",
+ "hover:-translate-y-0.5",
+ )}
+ >
+ <div className="min-w-0">
+ <div className="flex items-center gap-2 text-[17px] font-medium tracking-tight">
+ <Download className="h-4 w-4" aria-hidden />
+ {downloaded ? "Downloading Multica…" : "Download the desktop app"}
+ </div>
+ <div className="mt-1 text-[13px] text-background/60">
+ {downloaded
+ ? "Opened in a new tab. Finish setup inside the desktop app."
+ : "macOS · runtime bundled — detects your tools automatically, nothing to install."}
+ </div>
+ </div>
+ <span
+ aria-hidden
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-full bg-background/10 px-4 py-2 text-[13px] font-medium transition-colors group-hover:bg-background/20"
+ >
+ Download
+ <ArrowRight className="h-3.5 w-3.5" />
+ </span>
+ </button>
+ );
+}
+
+/**
+ * Alt card with an explicit right-side action pill. The whole card is
+ * clickable (so you can hit the title/subtitle too), but the pill is the
+ * visual anchor — it's what tells the user "this card is a button".
+ * Pressing it opens a dialog that owns the real content + action.
+ */
+function ForkAlt({
+ title,
+ subtitle,
+ actionLabel,
+ onAction,
+}: {
+ title: string;
+ subtitle: ReactNode;
+ actionLabel: ReactNode;
+ onAction: () => void;
+}) {
+ return (
+ <div className="flex items-center justify-between gap-4 rounded-lg border bg-card px-5 py-4">
+ <div className="min-w-0">
+ <div className="text-[14.5px] font-medium text-foreground">{title}</div>
+ <div className="mt-1 text-[12.5px] leading-[1.5] text-muted-foreground">
+ {subtitle}
+ </div>
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ className="shrink-0"
+ onClick={onAction}
+ >
+ {actionLabel}
+ </Button>
+ </div>
+ );
+}
+
+// ------------------------------------------------------------
+// CLI install dialog
+// ------------------------------------------------------------
+
+/**
+ * Modal dialog for the CLI install path. Contains the real install
+ * instructions card (via the `cliInstructions` slot) plus the live
+ * runtime probe. Owns its own "Connect & continue" advancement — when
+ * a runtime has registered and the user picks it, clicking that button
+ * closes the dialog and fires the parent's `onConnect`.
+ */
+function CliInstallDialog({
+ open,
+ onClose,
+ onConnect,
+ runtimes,
+ selectedId,
+ onSelect,
+ hasRuntimes,
+ canConnect,
+ selectedName,
+ cliInstructions,
+}: {
+ open: boolean;
+ onClose: () => void;
+ onConnect: () => void;
+ runtimes: AgentRuntime[];
+ selectedId: string | null;
+ onSelect: (id: string) => void;
+ hasRuntimes: boolean;
+ canConnect: boolean;
+ selectedName: string | null;
+ cliInstructions?: ReactNode;
+}) {
+ return (
+ <Dialog open={open} onOpenChange={(o) => (o ? null : onClose())}>
+ <DialogContent className="sm:max-w-[560px]">
+ <DialogHeader>
+ <DialogTitle>Install the CLI</DialogTitle>
+ <DialogDescription>
+ Runs the same daemon the desktop app bundles — you install
+ it yourself. This screen watches for it to come online.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="flex flex-col gap-4 pt-2">
+ {cliInstructions}
+
+ {/* Live probe. Shows a staged waiting message with elapsed-
+ time fallbacks while no runtime is detected; flips to
+ a success list once the daemon registers via WS. */}
+ {hasRuntimes ? (
+ <>
+ <div className="flex items-center gap-2 pt-1 text-sm">
+ <div className="h-2 w-2 rounded-full bg-success" />
+ <span className="font-medium">
+ {runtimes.length} runtime{runtimes.length > 1 ? "s" : ""}{" "}
+ connected
+ </span>
+ </div>
+ <div className="flex flex-col gap-2">
+ {runtimes.map((rt) => (
+ <CompactRuntimeRow
+ key={rt.id}
+ runtime={rt}
+ selected={rt.id === selectedId}
+ onSelect={() => onSelect(rt.id)}
+ />
+ ))}
+ </div>
+ </>
+ ) : (
+ <CliWaitingStatus dialogOpen={open} />
+ )}
+ </div>
+
+ <DialogFooter className="flex items-center justify-between gap-3 sm:justify-between">
+ <span className="text-xs text-muted-foreground">
+ {canConnect && selectedName
+ ? `Selected: ${selectedName}`
+ : hasRuntimes
+ ? "Pick a runtime above."
+ : "Waiting for your runtime to come online…"}
+ </span>
+ <div className="flex items-center gap-2">
+ <Button variant="ghost" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button disabled={!canConnect} onClick={onConnect}>
+ Connect &amp; continue
+ <ArrowRight className="h-4 w-4" />
+ </Button>
+ </div>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+/**
+ * Format a seconds count as `m:ss` (e.g. 75 → "1:15"). Inline helper —
+ * no existing utility matches this format (agent-live-card's
+ * formatElapsed uses "1m 15s" style, not suitable for a ticking clock).
+ */
+function formatElapsed(seconds: number) {
+ const m = Math.floor(seconds / 60);
+ const s = seconds % 60;
+ return `${m}:${s.toString().padStart(2, "0")}`;
+}
+
+/**
+ * Waiting state for the CLI dialog — shown until the first daemon
+ * registers. We can't actually observe the install / login / daemon-
+ * start phases from the frontend (they happen in the user's terminal
+ * and browser), so the best we can do is:
+ *
+ * 1. Confirm "we're listening" — a pulsing green dot + m:ss timer
+ * signals an active WS subscription (useRuntimePicker is already
+ * subscribed to `daemon:register`). This is what tells the user
+ * "the system isn't frozen, it's waiting for your daemon".
+ * 2. Progressively reveal troubleshooting hints as elapsed time
+ * crosses thresholds — so a user who stalls mid-setup gets
+ * useful guidance without being dogpiled at t=0.
+ * 3. At the 90s+ "stalled" tier, point the user at alternate paths
+ * (Skip / Cloud waitlist) — parallels desktop's EmptyView, which
+ * already exposes the same two exits when no runtime registers.
+ *
+ * Elapsed-time counter only ticks while the dialog is open so reopen
+ * after closing resets the staging.
+ */
+function CliWaitingStatus({ dialogOpen }: { dialogOpen: boolean }) {
+ const [elapsed, setElapsed] = useState(0);
+
+ useEffect(() => {
+ if (!dialogOpen) {
+ setElapsed(0);
+ return;
+ }
+ const id = window.setInterval(() => {
+ setElapsed((e) => e + 1);
+ }, 1000);
+ return () => window.clearInterval(id);
+ }, [dialogOpen]);
+
+ // Stage thresholds are rough — `multica setup` typical flow is
+ // ~1s save config → browser-tab auth (user-driven, 5–30s) →
+ // ~2s daemon boot → immediate WS register. So under 15s means
+ // "still normal", 15–45s means "probably stuck on browser auth",
+ // 45–90s means "probably an error in the terminal", 90s+ means
+ // "nothing's coming through, suggest alt paths" (the stalled tier
+ // parallels desktop StepRuntimeConnect's EmptyView — by that point
+ // it's worth pointing the user at Skip or Cloud waitlist).
+ const stage: "normal" | "midway" | "slow" | "stalled" =
+ elapsed < 15
+ ? "normal"
+ : elapsed < 45
+ ? "midway"
+ : elapsed < 90
+ ? "slow"
+ : "stalled";
+
+ return (
+ <div className="flex flex-col gap-3 rounded-lg border bg-muted/30 p-4">
+ <div className="flex items-center gap-2 text-sm">
+ {/* Pulsing green dot signals active WS subscription — the
+ useRuntimePicker hook is already subscribed to `daemon:register`,
+ this is the visual confirmation that "we're listening". */}
+ <span
+ aria-hidden
+ className="inline-block size-2 shrink-0 rounded-full bg-success animate-pulse"
+ />
+ <span className="font-medium text-foreground">
+ Live · Listening for your daemon
+ </span>
+ <span className="ml-auto font-mono text-xs tabular-nums text-muted-foreground">
+ {formatElapsed(elapsed)}
+ </span>
+ </div>
+
+ <p
+ aria-live="polite"
+ className="text-[12.5px] leading-[1.55] text-muted-foreground"
+ >
+ {stage === "normal" && (
+ <>
+ Run the command above. As soon as{" "}
+ <span className="font-mono">multica setup</span> finishes
+ browser sign-in and the daemon starts, your runtime will
+ appear here automatically (usually 10–30 seconds).
+ </>
+ )}
+ {stage === "midway" && (
+ <>
+ Still listening. Make sure you finished the browser tab that{" "}
+ <span className="font-mono">multica setup</span> opened — it
+ needs you to approve the sign-in before the daemon can start.
+ </>
+ )}
+ {stage === "slow" && (
+ <>
+ Taking longer than usual. Check the terminal where you ran{" "}
+ <span className="font-mono">multica setup</span> for errors.
+ </>
+ )}
+ {stage === "stalled" && (
+ <>
+ Nothing coming through yet. Close this dialog and try another
+ path on the previous screen —{" "}
+ <span className="font-medium text-foreground">Skip for now</span>{" "}
+ (in the footer) enters your workspace in read-only mode, or
+ the <span className="font-medium text-foreground">Cloud runtime</span>{" "}
+ card lets you join the waitlist.
+ </>
+ )}
+ </p>
+ </div>
+ );
+}
+
+// ------------------------------------------------------------
+// Cloud waitlist dialog
+// ------------------------------------------------------------
+
+/**
+ * Modal dialog for the cloud waitlist path. Wraps the shared
+ * `CloudWaitlistExpand` form. Submitting it records interest — the
+ * dialog does NOT advance the onboarding flow. After submit, the user
+ * closes the dialog and can hit Skip in the footer.
+ */
+function CloudWaitlistDialog({
+ open,
+ onClose,
+ submitted,
+ onSubmitted,
+}: {
+ open: boolean;
+ onClose: () => void;
+ submitted: boolean;
+ onSubmitted: () => void;
+}) {
+ return (
+ <Dialog open={open} onOpenChange={(o) => (o ? null : onClose())}>
+ <DialogContent className="sm:max-w-[520px]">
+ <DialogHeader>
+ <DialogTitle>Join the cloud runtime waitlist</DialogTitle>
+ <DialogDescription>
+ Cloud runtimes aren&apos;t live yet. Leave your email and
+ we&apos;ll email you when they are.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="pt-2">
+ <CloudWaitlistExpand
+ submitted={submitted}
+ onSubmitted={onSubmitted}
+ />
+ </div>
+
+ <DialogFooter>
+ <Button variant="ghost" onClick={onClose}>
+ {submitted ? "Close" : "Cancel"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/onboarding/steps/step-questionnaire.test.tsx b/packages/views/onboarding/steps/step-questionnaire.test.tsx
new file mode 100644
index 0000000000..f41fb9560a
--- /dev/null
+++ b/packages/views/onboarding/steps/step-questionnaire.test.tsx
@@ -0,0 +1,178 @@
+import { describe, expect, it, vi } from "vitest";
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import type { QuestionnaireAnswers } from "@multica/core/onboarding";
+import { StepQuestionnaire } from "./step-questionnaire";
+
+const EMPTY_ANSWERS: QuestionnaireAnswers = {
+ team_size: null,
+ team_size_other: null,
+ role: null,
+ role_other: null,
+ use_case: null,
+ use_case_other: null,
+};
+
+function renderStep(initial: Partial<QuestionnaireAnswers> = {}) {
+ const onSubmit = vi.fn();
+ render(
+ <StepQuestionnaire
+ initial={{ ...EMPTY_ANSWERS, ...initial }}
+ onSubmit={onSubmit}
+ />,
+ );
+ return { onSubmit };
+}
+
+/**
+ * The Continue button is the product of a strict "all three answered"
+ * gate — no Skip path. These tests lock down that policy so a future
+ * refactor can't silently loosen it:
+ * - Disabled by default (zero answers)
+ * - Stays disabled with 1 or 2 answers
+ * - Enabled only when all three have concrete selections
+ * - Stays disabled when any "Other" selection has empty text
+ * - Clicking while disabled never calls onSubmit
+ * - Switching away from Other clears that question's *_other field
+ */
+describe("StepQuestionnaire", () => {
+ it("Continue is disabled when no questions are answered", () => {
+ renderStep();
+ expect(
+ screen.getByRole("button", { name: /continue/i }),
+ ).toBeDisabled();
+ });
+
+ it("Continue stays disabled with only one question answered", async () => {
+ const user = userEvent.setup();
+ renderStep();
+ await user.click(screen.getByRole("radio", { name: /just me/i }));
+ expect(
+ screen.getByRole("button", { name: /continue/i }),
+ ).toBeDisabled();
+ });
+
+ it("Continue stays disabled with only two questions answered", async () => {
+ const user = userEvent.setup();
+ renderStep();
+ await user.click(screen.getByRole("radio", { name: /just me/i }));
+ await user.click(
+ screen.getByRole("radio", { name: /software developer/i }),
+ );
+ expect(
+ screen.getByRole("button", { name: /continue/i }),
+ ).toBeDisabled();
+ });
+
+ it("Continue enables when all three questions are answered", async () => {
+ const user = userEvent.setup();
+ renderStep();
+ await user.click(screen.getByRole("radio", { name: /just me/i }));
+ await user.click(
+ screen.getByRole("radio", { name: /software developer/i }),
+ );
+ await user.click(
+ screen.getByRole("radio", { name: /write and ship code/i }),
+ );
+ expect(
+ screen.getByRole("button", { name: /continue/i }),
+ ).toBeEnabled();
+ });
+
+ it("Continue stays disabled when Other is picked but its text is empty", async () => {
+ const user = userEvent.setup();
+ renderStep({
+ team_size: "solo",
+ role: "developer",
+ // Q3 will be set to Other in-test — no text typed yet.
+ });
+ const q3Other = screen.getAllByRole("radio", { name: /^other$/i })[2]!;
+ await user.click(q3Other);
+ expect(
+ screen.getByRole("button", { name: /continue/i }),
+ ).toBeDisabled();
+ });
+
+ it("Continue re-enables once Other text is filled in", async () => {
+ const user = userEvent.setup();
+ renderStep({ team_size: "solo", role: "developer" });
+ const q3Other = screen.getAllByRole("radio", { name: /^other$/i })[2]!;
+ await user.click(q3Other);
+ const input = screen.getByPlaceholderText(/automate my weekly reports/i);
+ await user.type(input, "Teach me the system");
+ expect(
+ screen.getByRole("button", { name: /continue/i }),
+ ).toBeEnabled();
+ });
+
+ it("clears Other text when the user switches to a concrete option", async () => {
+ const user = userEvent.setup();
+ const { onSubmit } = renderStep({
+ role: "developer",
+ use_case: "coding",
+ });
+
+ // Pick Q1 Other → type → switch to Just me → submit.
+ // Submitted payload must have team_size_other = null.
+ const q1Other = screen.getAllByRole("radio", { name: /^other$/i })[0]!;
+ await user.click(q1Other);
+ await user.type(
+ screen.getByPlaceholderText(/small community i help run/i),
+ "large enterprise",
+ );
+ await user.click(screen.getByRole("radio", { name: /just me/i }));
+ await user.click(screen.getByRole("button", { name: /continue/i }));
+
+ expect(onSubmit).toHaveBeenCalledTimes(1);
+ expect(onSubmit).toHaveBeenCalledWith(
+ expect.objectContaining({
+ team_size: "solo",
+ team_size_other: null,
+ }),
+ );
+ });
+
+ it("does not call onSubmit when Continue is disabled", async () => {
+ // Belt-and-suspenders against a future refactor that replaces
+ // <Button disabled> with a custom element that doesn't honor
+ // the native disabled semantics — the handler's own
+ // canContinue short-circuit catches it either way.
+ const user = userEvent.setup();
+ const { onSubmit } = renderStep();
+ await user.click(screen.getByRole("button", { name: /continue/i }));
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it("respects the initial prop (used for resume-after-back)", () => {
+ renderStep({ team_size: "team", role: "developer" });
+ expect(
+ screen.getByRole("radio", { name: /my team/i }),
+ ).toHaveAttribute("aria-checked", "true");
+ expect(
+ screen.getByRole("radio", { name: /software developer/i }),
+ ).toHaveAttribute("aria-checked", "true");
+ });
+
+ it("submits the full answer set including all three questions", async () => {
+ const user = userEvent.setup();
+ const { onSubmit } = renderStep();
+
+ await user.click(screen.getByRole("radio", { name: /just me/i }));
+ await user.click(
+ screen.getByRole("radio", { name: /software developer/i }),
+ );
+ await user.click(
+ screen.getByRole("radio", { name: /write and ship code/i }),
+ );
+ await user.click(screen.getByRole("button", { name: /continue/i }));
+
+ expect(onSubmit).toHaveBeenCalledWith({
+ team_size: "solo",
+ team_size_other: null,
+ role: "developer",
+ role_other: null,
+ use_case: "coding",
+ use_case_other: null,
+ });
+ });
+});
diff --git a/packages/views/onboarding/steps/step-questionnaire.tsx b/packages/views/onboarding/steps/step-questionnaire.tsx
new file mode 100644
index 0000000000..b2e2373d8e
--- /dev/null
+++ b/packages/views/onboarding/steps/step-questionnaire.tsx
@@ -0,0 +1,360 @@
+"use client";
+
+import { type ReactNode, useMemo, useRef, useState } from "react";
+import {
+ ArrowLeft,
+ ArrowRight,
+ Loader2,
+ PenLine,
+ Sparkles,
+} from "lucide-react";
+import { Button } from "@multica/ui/components/ui/button";
+import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";
+import type {
+ QuestionnaireAnswers,
+ Role,
+ TeamSize,
+ UseCase,
+} from "@multica/core/onboarding";
+import { DragStrip } from "@multica/views/platform";
+import { StepHeader } from "../components/step-header";
+import { OptionCard, OtherOptionCard } from "../components/option-card";
+
+/**
+ * Step 1 — three-question user profile.
+ *
+ * Classic app-shell layout: the left column is 3-region
+ * (header / scrollable middle / footer) so the progress indicator
+ * and the Continue CTA both stay visible regardless of how far the
+ * user has scrolled into the questions. The right "Why we ask" panel
+ * is a separate grid column that scrolls independently.
+ *
+ * Below lg the right panel hides and the left column fills the
+ * viewport — 3-region layout still applies.
+ */
+export function StepQuestionnaire({
+ initial,
+ onSubmit,
+ onBack,
+}: {
+ initial: QuestionnaireAnswers;
+ onSubmit: (answers: QuestionnaireAnswers) => void | Promise<void>;
+ onBack?: () => void;
+}) {
+ const [answers, setAnswers] = useState<QuestionnaireAnswers>(initial);
+ const [submitting, setSubmitting] = useState(false);
+ const mainRef = useRef<HTMLElement>(null);
+ const fadeStyle = useScrollFade(mainRef);
+
+ const setTeamSize = (v: TeamSize) =>
+ setAnswers((a) => ({
+ ...a,
+ team_size: v,
+ team_size_other: v === "other" ? a.team_size_other : null,
+ }));
+ const setRole = (v: Role) =>
+ setAnswers((a) => ({
+ ...a,
+ role: v,
+ role_other: v === "other" ? a.role_other : null,
+ }));
+ const setUseCase = (v: UseCase) =>
+ setAnswers((a) => ({
+ ...a,
+ use_case: v,
+ use_case_other: v === "other" ? a.use_case_other : null,
+ }));
+
+ // A question counts as "answered" when it has a concrete selection,
+ // and — if that selection is "other" — its free-text field is non-empty.
+ // Same rule that used to drive canContinue; we compute the per-question
+ // booleans once here and derive both the count (footer indicator) and
+ // the overall gate from it.
+ const answeredCount = useMemo(() => {
+ const q1 =
+ answers.team_size !== null &&
+ (answers.team_size !== "other" ||
+ (answers.team_size_other ?? "").trim() !== "");
+ const q2 =
+ answers.role !== null &&
+ (answers.role !== "other" || (answers.role_other ?? "").trim() !== "");
+ const q3 =
+ answers.use_case !== null &&
+ (answers.use_case !== "other" ||
+ (answers.use_case_other ?? "").trim() !== "");
+ return (q1 ? 1 : 0) + (q2 ? 1 : 0) + (q3 ? 1 : 0);
+ }, [answers]);
+ const canContinue = answeredCount === 3;
+
+ const submit = async () => {
+ if (!canContinue || submitting) return;
+ setSubmitting(true);
+ try {
+ await onSubmit(answers);
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ return (
+ <div className="animate-onboarding-enter grid h-full min-h-0 grid-cols-1 lg:grid-cols-[minmax(0,1fr)_480px]">
+ {/* Left column — DragStrip + 3-region app shell */}
+ <div className="flex min-h-0 flex-col">
+ <DragStrip />
+ {/* Fixed header — Back + progress indicator */}
+ <header className="flex shrink-0 items-center gap-4 bg-background px-6 py-3 sm:px-10 md:px-14 lg:px-16">
+ {onBack ? (
+ <button
+ type="button"
+ onClick={onBack}
+ className="flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
+ >
+ <ArrowLeft className="h-3.5 w-3.5" />
+ Back
+ </button>
+ ) : (
+ <span aria-hidden className="w-0" />
+ )}
+ <div className="flex-1">
+ <StepHeader currentStep="questionnaire" />
+ </div>
+ </header>
+
+ {/* Scrollable middle — the only region that scrolls vertically.
+ `min-h-0` is required on a flex-1 child inside a flex column
+ so it can shrink below its content height and let
+ overflow-y-auto activate. `useScrollFade` applies a dynamic
+ mask-image gradient so content softly fades into the header /
+ footer at the edges as the user scrolls, replacing the hard
+ border separator. */}
+ <main
+ ref={mainRef}
+ style={fadeStyle}
+ className="min-h-0 flex-1 overflow-y-auto"
+ >
+ <div className="mx-auto w-full max-w-[620px] px-6 py-10 sm:px-10 md:px-14 lg:px-0 lg:py-14">
+ <div className="mb-2 text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">
+ Before we start
+ </div>
+ <h1 className="text-balance font-serif text-[36px] font-medium leading-[1.1] tracking-tight text-foreground">
+ Three questions. Then we tailor the rest.
+ </h1>
+
+ <div className="mt-10 flex flex-col gap-7">
+ <QuestionBlock
+ num={1}
+ question="Who will use this workspace?"
+ ariaLabel="Who will use this workspace?"
+ >
+ <OptionCard
+ selected={answers.team_size === "solo"}
+ onSelect={() => setTeamSize("solo")}
+ label="Just me"
+ />
+ <OptionCard
+ selected={answers.team_size === "team"}
+ onSelect={() => setTeamSize("team")}
+ label="My team (2–10 people)"
+ />
+ <OtherOptionCard
+ selected={answers.team_size === "other"}
+ onSelect={() => setTeamSize("other")}
+ otherValue={answers.team_size_other ?? ""}
+ onOtherChange={(v) =>
+ setAnswers((a) => ({ ...a, team_size_other: v }))
+ }
+ placeholder="e.g. a small community I help run"
+ />
+ </QuestionBlock>
+
+ <QuestionBlock
+ num={2}
+ question="What best describes you?"
+ ariaLabel="What best describes you?"
+ >
+ <OptionCard
+ selected={answers.role === "developer"}
+ onSelect={() => setRole("developer")}
+ label="Software developer"
+ />
+ <OptionCard
+ selected={answers.role === "product_lead"}
+ onSelect={() => setRole("product_lead")}
+ label="Product or project lead"
+ />
+ <OptionCard
+ selected={answers.role === "writer"}
+ onSelect={() => setRole("writer")}
+ label="Writer or content creator"
+ />
+ <OptionCard
+ selected={answers.role === "founder"}
+ onSelect={() => setRole("founder")}
+ label="Founder or operator"
+ />
+ <OtherOptionCard
+ selected={answers.role === "other"}
+ onSelect={() => setRole("other")}
+ otherValue={answers.role_other ?? ""}
+ onOtherChange={(v) =>
+ setAnswers((a) => ({ ...a, role_other: v }))
+ }
+ placeholder="e.g. researcher, designer, ops lead"
+ />
+ </QuestionBlock>
+
+ <QuestionBlock
+ num={3}
+ question="What do you want to do with Multica?"
+ ariaLabel="What do you want to do with Multica?"
+ >
+ <OptionCard
+ selected={answers.use_case === "coding"}
+ onSelect={() => setUseCase("coding")}
+ label="Write and ship code"
+ />
+ <OptionCard
+ selected={answers.use_case === "planning"}
+ onSelect={() => setUseCase("planning")}
+ label="Plan and manage projects"
+ />
+ <OptionCard
+ selected={answers.use_case === "writing_research"}
+ onSelect={() => setUseCase("writing_research")}
+ label="Research or write"
+ />
+ <OptionCard
+ selected={answers.use_case === "explore"}
+ onSelect={() => setUseCase("explore")}
+ label="I'm just exploring for now"
+ />
+ <OtherOptionCard
+ selected={answers.use_case === "other"}
+ onSelect={() => setUseCase("other")}
+ otherValue={answers.use_case_other ?? ""}
+ onOtherChange={(v) =>
+ setAnswers((a) => ({ ...a, use_case_other: v }))
+ }
+ placeholder="e.g. automate my weekly reports"
+ />
+ </QuestionBlock>
+ </div>
+ </div>
+ </main>
+
+ {/* Fixed footer — progress counter + Continue */}
+ <footer className="flex shrink-0 items-center justify-end gap-4 bg-background px-6 py-4 sm:px-10 md:px-14 lg:px-16">
+ <span
+ aria-live="polite"
+ className="text-xs tabular-nums text-muted-foreground"
+ >
+ {answeredCount} of 3 answered
+ </span>
+ <Button
+ size="lg"
+ disabled={!canContinue || submitting}
+ onClick={submit}
+ >
+ {submitting && <Loader2 className="h-4 w-4 animate-spin" />}
+ Continue
+ <ArrowRight className="h-4 w-4" />
+ </Button>
+ </footer>
+ </div>
+
+ {/* Right — DragStrip + "Why we ask" side panel, independent scroll */}
+ <aside className="hidden min-h-0 border-l bg-muted/40 lg:flex lg:flex-col">
+ <DragStrip />
+ <div className="min-h-0 flex-1 overflow-y-auto px-12 py-12">
+ <WhyWeAsk />
+ </div>
+ </aside>
+ </div>
+ );
+}
+
+function QuestionBlock({
+ num,
+ question,
+ ariaLabel,
+ children,
+}: {
+ num: number;
+ question: string;
+ ariaLabel: string;
+ children: ReactNode;
+}) {
+ return (
+ <fieldset role="radiogroup" aria-label={ariaLabel} className="m-0 p-0">
+ <legend className="mb-3 flex items-baseline gap-3">
+ <span className="font-mono text-xs text-muted-foreground">
+ {String(num).padStart(2, "0")}
+ </span>
+ <span className="font-serif text-[22px] font-medium leading-tight tracking-tight text-foreground">
+ {question}
+ </span>
+ </legend>
+ <div className="flex flex-col gap-2">{children}</div>
+ </fieldset>
+ );
+}
+
+function WhyWeAsk() {
+ return (
+ <div className="flex max-w-[380px] flex-col gap-8">
+ <section className="flex flex-col gap-4">
+ <div className="text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">
+ Why three questions
+ </div>
+ <h2 className="font-serif text-[22px] font-medium leading-[1.25] tracking-tight text-foreground">
+ So you land running.
+ </h2>
+ </section>
+
+ <section className="flex flex-col gap-4">
+ <div className="text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">
+ What you get
+ </div>
+ <div className="flex flex-col gap-4">
+ <UnlockItem
+ icon={<PenLine className="h-4 w-4" />}
+ title="A starter project, tailored"
+ body="A Getting Started checklist shaped by your answers."
+ />
+ <UnlockItem
+ icon={<Sparkles className="h-4 w-4" />}
+ title="A head start with agents"
+ body="Connect a runtime and we'll pick a template for your role — plus write its first task."
+ />
+ </div>
+ </section>
+ </div>
+ );
+}
+
+function UnlockItem({
+ icon,
+ title,
+ body,
+}: {
+ icon: ReactNode;
+ title: string;
+ body: string;
+}) {
+ return (
+ <div className="grid grid-cols-[22px_1fr] gap-3">
+ <div
+ aria-hidden
+ className="flex h-[20px] w-[20px] items-center justify-center text-muted-foreground"
+ >
+ {icon}
+ </div>
+ <div className="flex flex-col">
+ <div className="text-[13.5px] font-medium text-foreground">{title}</div>
+ <div className="mt-1 text-[12.5px] leading-[1.55] text-muted-foreground">
+ {body}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/onboarding/steps/step-runtime-connect.tsx b/packages/views/onboarding/steps/step-runtime-connect.tsx
new file mode 100644
index 0000000000..50280c0d04
--- /dev/null
+++ b/packages/views/onboarding/steps/step-runtime-connect.tsx
@@ -0,0 +1,539 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { ArrowLeft, ArrowRight, Loader2 } from "lucide-react";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { cn } from "@multica/ui/lib/utils";
+import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";
+import type { AgentRuntime } from "@multica/core/types";
+import { DragStrip } from "@multica/views/platform";
+import { StepHeader } from "../components/step-header";
+import { RuntimeAsidePanel } from "../components/runtime-aside-panel";
+import { useRuntimePicker } from "../components/use-runtime-picker";
+import { CloudWaitlistExpand } from "../components/cloud-waitlist-expand";
+import { ProviderLogo } from "../../runtimes/components/provider-logo";
+
+/**
+ * Step 3 (desktop) — connect a runtime.
+ *
+ * Owns the full window: DragStrip + 3-region app shell (header /
+ * scrolling middle / sticky footer) on the left, permanent
+ * educational aside on the right. Built to mirror Step 1
+ * questionnaire's shell so the onboarding flow reads as one
+ * continuous surface.
+ *
+ * Data layer (`useRuntimePicker`): TanStack Query polls every 2s
+ * while empty; `daemon:register` WS event invalidates instantly;
+ * default selection prefers online, falls back to first.
+ *
+ * Web routes to `StepPlatformFork` instead — it owns its own
+ * runtime picker embedded under the CLI expand.
+ */
+export function StepRuntimeConnect({
+ wsId,
+ onNext,
+ onBack,
+}: {
+ wsId: string;
+ onNext: (runtime: AgentRuntime | null) => void | Promise<void>;
+ onBack?: () => void;
+}) {
+ const { runtimes, selected, selectedId, setSelectedId } =
+ useRuntimePicker(wsId);
+
+ return (
+ <FancyView
+ runtimes={runtimes}
+ selected={selected}
+ selectedId={selectedId}
+ setSelectedId={setSelectedId}
+ onNext={onNext}
+ onBack={onBack}
+ />
+ );
+}
+
+// ============================================================
+// Fancy desktop view
+// ============================================================
+
+type Phase = "scanning" | "found" | "empty";
+
+/** Input ms before an empty list flips from "scanning" to "empty". */
+const EMPTY_TIMEOUT_MS = 5000;
+
+function FancyView({
+ runtimes,
+ selected,
+ selectedId,
+ setSelectedId,
+ onNext,
+ onBack,
+}: {
+ runtimes: AgentRuntime[];
+ selected: AgentRuntime | null;
+ selectedId: string | null;
+ setSelectedId: (id: string) => void;
+ onNext: (runtime: AgentRuntime | null) => void | Promise<void>;
+ onBack?: () => void;
+}) {
+ const mainRef = useRef<HTMLElement>(null);
+ const fadeStyle = useScrollFade(mainRef);
+
+ // Flip to "empty" only after we've waited long enough for the daemon
+ // to report. The 5s budget covers the bundled daemon's typical 1–3s
+ // boot; anything past that is a genuine "no runtime" situation and we
+ // switch from scanning skeletons to the skip / cloud-waitlist exits.
+ const [hasTimedOut, setHasTimedOut] = useState(false);
+ useEffect(() => {
+ if (runtimes.length > 0) return;
+ const t = window.setTimeout(() => setHasTimedOut(true), EMPTY_TIMEOUT_MS);
+ return () => window.clearTimeout(t);
+ }, [runtimes.length]);
+
+ const phase: Phase =
+ runtimes.length > 0 ? "found" : hasTimedOut ? "empty" : "scanning";
+
+ const onlineCount = runtimes.filter((r) => r.status === "online").length;
+
+ const [submitting, setSubmitting] = useState(false);
+ // Cloud waitlist submission state lives here (rather than in EmptyView)
+ // so it survives phase flips — e.g. a runtime coming online after the
+ // user has already submitted the waitlist form.
+ const [waitlistSubmitted, setWaitlistSubmitted] = useState(false);
+
+ // Skip is always available — regardless of phase. Hitting Skip routes
+ // the flow through the self-serve branch (agent=null), which still
+ // completes onboarding and seeds a Getting Started project.
+ const handleSkip = async () => {
+ if (submitting) return;
+ setSubmitting(true);
+ try {
+ await onNext(null);
+ } finally {
+ setSubmitting(false);
+ }
+ };
+ // Continue only makes sense when a runtime is selected. Otherwise
+ // there's nothing to pass to Step 4.
+ const canContinue = phase === "found" && selected !== null;
+ const handleContinue = async () => {
+ if (!canContinue || submitting) return;
+ setSubmitting(true);
+ try {
+ await onNext(selected);
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ const footerHint =
+ phase === "found" && selected
+ ? `Selected: ${selected.name}`
+ : phase === "found"
+ ? "Pick a runtime above to continue."
+ : phase === "scanning"
+ ? "Waiting for the first result…"
+ : waitlistSubmitted
+ ? "You're on the waitlist — skip to keep exploring."
+ : "Skip to enter your workspace, or join the cloud waitlist above.";
+
+ return (
+ <div className="animate-onboarding-enter grid h-full min-h-0 grid-cols-1 lg:grid-cols-[minmax(0,1fr)_480px]">
+ {/* Left — DragStrip + 3-region app shell */}
+ <div className="flex min-h-0 flex-col">
+ <DragStrip />
+
+ {/* Header — Back + horizontal step indicator */}
+ <header className="flex shrink-0 items-center gap-4 bg-background px-6 py-3 sm:px-10 md:px-14 lg:px-16">
+ {onBack ? (
+ <button
+ type="button"
+ onClick={onBack}
+ className="flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
+ >
+ <ArrowLeft className="h-3.5 w-3.5" />
+ Back
+ </button>
+ ) : (
+ <span aria-hidden className="w-0" />
+ )}
+ <div className="flex-1">
+ <StepHeader currentStep="runtime" />
+ </div>
+ </header>
+
+ {/* Scrollable middle — content changes by phase but always wraps
+ at max-w-[620px] so the 2-column runtime grid has room to
+ breathe without stretching into readability territory. */}
+ <main
+ ref={mainRef}
+ style={fadeStyle}
+ className="min-h-0 flex-1 overflow-y-auto"
+ >
+ {/* key=phase forces a remount on phase transition so the
+ `animate-onboarding-enter` animation replays — otherwise CSS
+ only runs on initial mount and scanning→found would be a
+ hard cut. */}
+ <div
+ key={phase}
+ className="animate-onboarding-enter mx-auto w-full max-w-[620px] px-6 py-10 sm:px-10 md:px-14 lg:px-0 lg:py-14"
+ >
+ {phase === "scanning" && <ScanningView />}
+ {phase === "found" && (
+ <FoundView
+ runtimes={runtimes}
+ selectedId={selectedId}
+ onSelect={setSelectedId}
+ onlineCount={onlineCount}
+ />
+ )}
+ {phase === "empty" && (
+ <EmptyView
+ waitlistSubmitted={waitlistSubmitted}
+ onWaitlistSubmitted={() => setWaitlistSubmitted(true)}
+ onSkip={() => onNext(null)}
+ />
+ )}
+ </div>
+ </main>
+
+ {/* Sticky footer — Skip (always) on the left, hint + Continue
+ (gated on runtime selection) on the right. Skip is the
+ self-serve exit: onNext(null) → bootstrap runs the no-agent
+ branch, onboarding still completes. */}
+ <footer className="flex shrink-0 items-center justify-end gap-4 bg-background px-6 py-4 sm:px-10 md:px-14 lg:px-16">
+ <span
+ aria-live="polite"
+ className="mr-auto text-xs text-muted-foreground"
+ >
+ {footerHint}
+ </span>
+ <Button
+ variant="secondary"
+ disabled={submitting}
+ onClick={handleSkip}
+ >
+ Skip for now
+ </Button>
+ <Button
+ size="lg"
+ disabled={!canContinue || submitting}
+ onClick={handleContinue}
+ >
+ {submitting && <Loader2 className="h-4 w-4 animate-spin" />}
+ Continue
+ <ArrowRight className="h-4 w-4" />
+ </Button>
+ </footer>
+ </div>
+
+ {/* Right — always-visible educational aside. "You picked" subsection
+ only appears when there's a selection; the other two stay constant. */}
+ <aside className="hidden min-h-0 border-l bg-muted/40 lg:flex lg:flex-col">
+ <DragStrip />
+ <div className="min-h-0 flex-1 overflow-y-auto px-12 py-12">
+ <RuntimeAsidePanel />
+ </div>
+ </aside>
+ </div>
+ );
+}
+
+// ------------------------------------------------------------
+// Phase views (inline — all three share the same 620px column)
+// ------------------------------------------------------------
+
+function ScanningView() {
+ return (
+ <div>
+ <h1 className="text-balance font-serif text-[36px] font-medium leading-[1.1] tracking-tight text-foreground">
+ Looking for your tools…
+ </h1>
+ <p className="mt-4 max-w-[560px] text-[15.5px] leading-[1.55] text-muted-foreground">
+ Multica drives local AI coding tools like{" "}
+ <span className="font-medium text-foreground">Claude Code</span>,{" "}
+ <span className="font-medium text-foreground">Codex</span>,{" "}
+ <span className="font-medium text-foreground">Cursor</span>, and
+ others. We&apos;re waiting to hear back from your machine about
+ which ones are installed.
+ </p>
+ <div className="mt-10 grid grid-cols-1 gap-2.5 sm:grid-cols-2">
+ <SkeletonRuntimeCard />
+ <SkeletonRuntimeCard />
+ </div>
+ </div>
+ );
+}
+
+function FoundView({
+ runtimes,
+ selectedId,
+ onSelect,
+ onlineCount,
+}: {
+ runtimes: AgentRuntime[];
+ selectedId: string | null;
+ onSelect: (id: string) => void;
+ onlineCount: number;
+}) {
+ const total = runtimes.length;
+ const statusLabel =
+ onlineCount === total
+ ? "all online"
+ : onlineCount === 0
+ ? "none online"
+ : `${onlineCount} online`;
+ const statusTone =
+ onlineCount === 0 ? "text-muted-foreground" : "text-success";
+
+ return (
+ <div>
+ <h1 className="text-balance font-serif text-[36px] font-medium leading-[1.1] tracking-tight text-foreground">
+ We found your runtimes.
+ </h1>
+ <p className="mt-4 max-w-[560px] text-[15.5px] leading-[1.55] text-muted-foreground">
+ We scanned your machine for AI coding tools you&apos;ve already
+ set up. Pick one for your first agent.
+ </p>
+
+ {/* Summary strip — trust signal ("we really did scan") */}
+ <div className="mt-8 flex flex-wrap items-center gap-x-2 gap-y-1 rounded-lg bg-muted/60 px-4 py-2.5 text-xs">
+ <span className="font-semibold text-foreground">
+ {total} runtime{total === 1 ? "" : "s"}
+ </span>
+ <span className="text-muted-foreground">·</span>
+ <span className={cn("flex items-center gap-1", statusTone)}>
+ <span
+ className={cn(
+ "h-1.5 w-1.5 rounded-full",
+ onlineCount === 0 ? "bg-muted-foreground/40" : "bg-success",
+ )}
+ aria-hidden
+ />
+ {statusLabel}
+ </span>
+ </div>
+
+ <div className="mt-6 grid grid-cols-1 gap-2.5 sm:grid-cols-2">
+ {runtimes.map((rt) => (
+ <RuntimeCard
+ key={rt.id}
+ runtime={rt}
+ selected={rt.id === selectedId}
+ onSelect={() => onSelect(rt.id)}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function EmptyView({
+ waitlistSubmitted,
+ onWaitlistSubmitted,
+ onSkip,
+}: {
+ waitlistSubmitted: boolean;
+ onWaitlistSubmitted: () => void;
+ onSkip: () => void;
+}) {
+ // Two exits: "Skip for now" (enter the workspace in read-only mode)
+ // or "Join waitlist" (capture interest in the hosted runtime we
+ // haven't shipped yet). We deliberately don't link out to Claude
+ // Code / Codex / Cursor here — those are other companies' products,
+ // and nudging the user to install one would frame Multica as a
+ // launcher for them rather than a product that runs them.
+ const [waitlistOpen, setWaitlistOpen] = useState(false);
+
+ return (
+ <div>
+ <h1 className="text-balance font-serif text-[36px] font-medium leading-[1.1] tracking-tight text-foreground">
+ No supported tools detected.
+ </h1>
+ <p className="mt-4 max-w-[560px] text-[15.5px] leading-[1.55] text-muted-foreground">
+ Multica drives local AI coding tools like{" "}
+ <span className="font-medium text-foreground">Claude Code</span>,{" "}
+ <span className="font-medium text-foreground">Codex</span>,{" "}
+ <span className="font-medium text-foreground">Cursor</span>, and
+ others — we didn&apos;t find any on this machine. Install one and
+ come back, or pick a path below.
+ </p>
+
+ <div className="mt-10 flex flex-col gap-3.5">
+ <EmptyCard
+ title="Skip for now"
+ subtitle="Enter your workspace in read-only mode. Agents can't execute tasks until a runtime connects — but you can still browse, plan, and invite teammates."
+ actionLabel="Skip"
+ onAction={onSkip}
+ />
+
+ <EmptyCard
+ title="Join the cloud runtime waitlist"
+ subtitle="We'll host the runtime for you — no local install, no setup. Not live yet; click to leave your email and get notified."
+ actionLabel={waitlistSubmitted ? "On the waitlist" : "Join waitlist"}
+ onAction={() => setWaitlistOpen(true)}
+ />
+ </div>
+
+ <Dialog
+ open={waitlistOpen}
+ onOpenChange={(o) => (o ? null : setWaitlistOpen(false))}
+ >
+ <DialogContent className="flex max-h-[85vh] flex-col sm:max-w-[520px]">
+ <DialogHeader>
+ <DialogTitle>Join the cloud runtime waitlist</DialogTitle>
+ <DialogDescription>
+ Cloud runtimes aren&apos;t live yet. Leave your email and
+ we&apos;ll email you when they are.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="min-h-0 flex-1 overflow-y-auto pt-2">
+ <CloudWaitlistExpand
+ submitted={waitlistSubmitted}
+ onSubmitted={onWaitlistSubmitted}
+ />
+ </div>
+
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => setWaitlistOpen(false)}>
+ {waitlistSubmitted ? "Close" : "Cancel"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
+
+/**
+ * Card with a prominent right-side button. Mirrors the ForkAlt pattern
+ * from the web fork step — whole card is clickable, but the pill is
+ * the visual affordance that signals "this is a button".
+ */
+function EmptyCard({
+ title,
+ subtitle,
+ actionLabel,
+ onAction,
+}: {
+ title: string;
+ subtitle: string;
+ actionLabel: string;
+ onAction: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onAction}
+ className="group flex items-center justify-between gap-4 rounded-lg border bg-card px-5 py-4 text-left transition-colors hover:border-foreground/30 hover:bg-muted/30"
+ >
+ <div className="min-w-0">
+ <div className="text-[14.5px] font-medium text-foreground">{title}</div>
+ <p className="mt-1 text-[12.5px] leading-[1.55] text-muted-foreground">
+ {subtitle}
+ </p>
+ </div>
+ <span
+ aria-hidden
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-full border bg-background px-4 py-2 text-[13px] font-medium text-foreground transition-colors group-hover:border-foreground group-hover:bg-foreground group-hover:text-background"
+ >
+ {actionLabel}
+ <ArrowRight className="h-3.5 w-3.5" />
+ </span>
+ </button>
+ );
+}
+
+// ------------------------------------------------------------
+// Card components
+// ------------------------------------------------------------
+
+function RuntimeCard({
+ runtime,
+ selected,
+ onSelect,
+}: {
+ runtime: AgentRuntime;
+ selected: boolean;
+ onSelect: () => void;
+}) {
+ const online = runtime.status === "online";
+
+ return (
+ <button
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ onClick={onSelect}
+ className={cn(
+ "flex items-center gap-3 rounded-lg border bg-card p-4 text-left transition-colors",
+ selected
+ ? "border-foreground shadow-[inset_0_0_0_1px_var(--color-foreground)]"
+ : "hover:border-foreground/20",
+ )}
+ >
+ <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-accent/30">
+ <ProviderLogo provider={runtime.provider} className="h-4 w-4" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-sm font-medium text-foreground">
+ {runtime.name}
+ </div>
+ <div className="mt-0.5 flex items-center gap-1.5 font-mono text-[11px] text-muted-foreground">
+ <span
+ className={cn(
+ "h-1.5 w-1.5 rounded-full",
+ online ? "bg-success" : "bg-muted-foreground/40",
+ )}
+ aria-hidden
+ />
+ {online ? "online" : "offline"}
+ </div>
+ </div>
+ <RadioMark selected={selected} />
+ </button>
+ );
+}
+
+function SkeletonRuntimeCard() {
+ return (
+ <div
+ aria-hidden
+ className="flex animate-pulse items-center gap-3 rounded-lg border bg-card p-4"
+ >
+ <div className="h-7 w-7 shrink-0 rounded-md bg-muted" />
+ <div className="flex-1 space-y-2">
+ <div className="h-3 w-28 rounded bg-muted" />
+ <div className="h-2.5 w-16 rounded bg-muted/70" />
+ </div>
+ <div className="h-4 w-4 shrink-0 rounded-full border-[1.5px] border-muted" />
+ </div>
+ );
+}
+
+function RadioMark({ selected }: { selected: boolean }) {
+ return (
+ <span
+ aria-hidden
+ className={cn(
+ "relative inline-block h-4 w-4 shrink-0 rounded-full border-[1.5px] transition-colors",
+ selected ? "border-foreground" : "border-border",
+ )}
+ >
+ {selected && (
+ <span className="absolute inset-[3px] rounded-full bg-foreground" />
+ )}
+ </span>
+ );
+}
+
diff --git a/packages/views/onboarding/steps/step-welcome.tsx b/packages/views/onboarding/steps/step-welcome.tsx
new file mode 100644
index 0000000000..452430a39f
--- /dev/null
+++ b/packages/views/onboarding/steps/step-welcome.tsx
@@ -0,0 +1,325 @@
+"use client";
+
+import { useState } from "react";
+import { ArrowRight, Loader2 } from "lucide-react";
+import { Button } from "@multica/ui/components/ui/button";
+import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
+import { cn } from "@multica/ui/lib/utils";
+import { DragStrip } from "@multica/views/platform";
+import { STATUS_CONFIG } from "@multica/core/issues/config";
+import type { IssueStatus } from "@multica/core/types";
+import { StatusIcon } from "../../issues/components/status-icon";
+import { ProviderLogo } from "../../runtimes/components/provider-logo";
+
+/**
+ * Step 0 — the one-shot product intro shown on every onboarding
+ * entry (which-step-are-you-on is not persisted). Returning users
+ * who are already onboarded never reach this screen; they're gated
+ * out earlier by `!hasOnboarded`.
+ *
+ * Layout: two-column editorial hero on lg+, single column below.
+ * Left = wordmark + serif headline + lede + CTA; right = a stack of
+ * mock issue cards that show what human/agent collaboration looks
+ * like on the board — the thing the user is about to create. The
+ * right column is an illustration, not content: hidden below lg so
+ * the headline and CTA stay the focus on narrow viewports.
+ *
+ * `onSkip`, when provided, renders a secondary ghost CTA that marks
+ * onboarding complete server-side and sends the user straight to
+ * their existing workspace. OnboardingFlow only passes it when the
+ * user has ≥ 1 workspace — without that, skipping lands in limbo.
+ */
+export function StepWelcome({
+ onNext,
+ onSkip,
+}: {
+ onNext: () => void | Promise<void>;
+ onSkip?: () => void | Promise<void>;
+}) {
+ // Tracks which button is mid-flight so we can show a per-button
+ // spinner and disable both while one is in progress.
+ const [pending, setPending] = useState<"next" | "skip" | null>(null);
+
+ const handleNext = async () => {
+ if (pending) return;
+ setPending("next");
+ try {
+ await onNext();
+ } finally {
+ setPending(null);
+ }
+ };
+
+ const handleSkip = async () => {
+ if (pending || !onSkip) return;
+ setPending("skip");
+ try {
+ await onSkip();
+ } finally {
+ setPending(null);
+ }
+ };
+
+ return (
+ <div className="animate-onboarding-enter grid h-full min-h-[640px] grid-cols-1 lg:grid-cols-2">
+ {/* Left — prose + CTA */}
+ <div className="flex flex-col">
+ <DragStrip />
+ <div className="flex flex-1 flex-col justify-center px-6 pb-12 sm:px-10 md:px-20 lg:px-20 xl:px-24">
+ <div className="flex w-full max-w-[540px] flex-col gap-8">
+ <div className="flex items-center gap-2.5">
+ <MulticaIcon className="size-5 text-foreground" noSpin />
+ <span className="font-serif text-xl font-medium tracking-tight">
+ Welcome to Multica
+ </span>
+ </div>
+
+ <h1 className="text-balance font-serif text-5xl font-medium leading-[1.04] tracking-tight sm:text-6xl">
+ Your AI teammates,
+ <br />
+ in <em className="italic text-brand">one workspace.</em>
+ </h1>
+
+ <div className="flex flex-col gap-4">
+ <p className="text-lg leading-relaxed text-foreground/85">
+ Assign them work like you&apos;d assign a colleague — they
+ pick it up, update status, and comment when done.
+ </p>
+ <p className="text-sm leading-relaxed text-muted-foreground">
+ Takes about 3 minutes. You&apos;ll end with a real agent
+ replying to a real issue.
+ </p>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-3">
+ <Button
+ size="lg"
+ onClick={handleNext}
+ disabled={pending !== null}
+ >
+ {pending === "next" && (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ )}
+ Start exploring
+ <ArrowRight className="h-4 w-4" />
+ </Button>
+ {onSkip && (
+ <Button
+ size="lg"
+ variant="ghost"
+ onClick={handleSkip}
+ disabled={pending !== null}
+ >
+ {pending === "skip" && (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ )}
+ I&apos;ve done this before
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Right — mock issue cards illustration. Hidden on < lg. */}
+ <div className="hidden border-l bg-muted/40 lg:flex lg:flex-col lg:overflow-hidden">
+ <DragStrip />
+ <div className="flex flex-1 flex-col items-center gap-7 px-8 py-8">
+ <p className="max-w-[440px] text-balance text-center font-serif text-[15px] italic leading-snug text-muted-foreground">
+ Every issue, every thread, every decision — shared by your team and
+ agents.
+ </p>
+ <WelcomeIllustration />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+
+/**
+ * A day in a solo user's multi-agent workspace. Five activity cards
+ * woven through 3 shared issues (MCA-42 appears 3×) so the reader can
+ * *see* agents referencing each other's work — the product's
+ * "one workspace, shared context" thesis rendered concretely.
+ *
+ * Cards use slight rotations + indents to feel like a hand-stacked
+ * pile rather than a neat feed, which matches the editorial-hero
+ * aesthetic of the left column.
+ */
+function WelcomeIllustration() {
+ return (
+ <div className="flex w-full max-w-[460px] flex-col gap-3">
+ <MockActivityCard
+ actor={{ kind: "user", name: "You", initial: "N" }}
+ issueId="MCA-42"
+ content={
+ <>
+ <Mention>@Content Agent</Mention> can you draft a short launch
+ post? Pull from <Mention>@Research Agent</Mention>&apos;s interview
+ findings.
+ </>
+ }
+ />
+ <MockActivityCard
+ className="-translate-x-5 -rotate-[1.2deg]"
+ actor={{ kind: "agent", name: "Content Agent", provider: "codex" }}
+ issueId="MCA-42"
+ content={
+ <>
+ On it. Pulling Research&apos;s quotes, drafting around the
+ &ldquo;time saved&rdquo; angle…
+ </>
+ }
+ status="in_progress"
+ />
+ <MockActivityCard
+ className="translate-x-8 rotate-[1.6deg]"
+ actor={{ kind: "agent", name: "Research Agent", provider: "hermes" }}
+ issueId="MCA-38"
+ content="This week's user interviews summarized — 12 calls, 4 recurring themes, 3 pull-quotes."
+ status="done"
+ timestamp="15 min ago"
+ />
+ <MockActivityCard
+ className="-translate-x-6 -rotate-[0.8deg]"
+ actor={{ kind: "agent", name: "Review Agent", provider: "openclaw" }}
+ issueId="MCA-42"
+ content="Reviewed Monday's draft — left 4 notes on tone. Standing by for the new one."
+ status="in_review"
+ />
+ <MockActivityCard
+ className="translate-x-6 rotate-[1deg]"
+ actor={{ kind: "agent", name: "Coding Agent", provider: "claude" }}
+ issueId="MCA-35"
+ content={
+ <>
+ Shipped the export feature <Mention>@you</Mention> flagged.
+ Preview link in the PR.
+ </>
+ }
+ status="done"
+ timestamp="just now"
+ />
+ </div>
+ );
+}
+
+type ProviderName =
+ | "claude"
+ | "codex"
+ | "opencode"
+ | "openclaw"
+ | "hermes"
+ | "pi"
+ | "copilot"
+ | "cursor";
+
+type ActivityActor =
+ | { kind: "user"; name: string; initial: string }
+ | { kind: "agent"; name: string; provider: ProviderName };
+
+function MockActivityCard({
+ actor,
+ issueId,
+ content,
+ status,
+ timestamp,
+ className,
+}: {
+ actor: ActivityActor;
+ issueId: string;
+ content: React.ReactNode;
+ status?: Extract<IssueStatus, "in_progress" | "done" | "in_review">;
+ timestamp?: string;
+ className?: string;
+}) {
+ return (
+ <div
+ className={cn(
+ "rounded-lg border bg-card px-4 py-3.5 shadow-sm",
+ // Decorative hover: lift, straighten, deeper shadow. Cards aren't
+ // clickable — this is ambient polish so the illustration feels like
+ // real app UI rather than a flat screenshot.
+ "transition-all duration-200 ease-out will-change-transform",
+ "hover:-translate-y-0.5 hover:rotate-0 hover:shadow-md",
+ className,
+ )}
+ >
+ <div className="flex items-center justify-between gap-3">
+ <div className="flex min-w-0 items-center gap-2">
+ <MockAvatar actor={actor} />
+ <span className="truncate text-sm font-medium text-foreground">
+ {actor.name}
+ </span>
+ </div>
+ <span className="shrink-0 font-mono text-[11px] text-muted-foreground">
+ {issueId}
+ </span>
+ </div>
+
+ <p className="mt-2.5 text-sm leading-snug text-foreground/85">
+ {content}
+ </p>
+
+ {status && <StatusFooter status={status} timestamp={timestamp} />}
+ </div>
+ );
+}
+
+function MockAvatar({ actor }: { actor: ActivityActor }) {
+ if (actor.kind === "user") {
+ return (
+ <div
+ aria-hidden
+ className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-foreground text-[11px] font-semibold text-background"
+ >
+ {actor.initial}
+ </div>
+ );
+ }
+ return (
+ <div
+ aria-hidden
+ className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full border bg-muted/40 text-foreground"
+ >
+ <ProviderLogo provider={actor.provider} className="h-3.5 w-3.5" />
+ </div>
+ );
+}
+
+function StatusFooter({
+ status,
+ timestamp,
+}: {
+ status: IssueStatus;
+ timestamp?: string;
+}) {
+ const cfg = STATUS_CONFIG[status];
+ return (
+ <div className="mt-3 flex items-center gap-2 text-xs">
+ <span
+ className={cn("flex items-center gap-1.5 font-medium", cfg.iconColor)}
+ >
+ <StatusIcon
+ status={status}
+ className={cn(
+ "h-3.5 w-3.5",
+ status === "in_progress" && "animate-pulse",
+ )}
+ />
+ {cfg.label}
+ </span>
+ {timestamp && (
+ <>
+ <span className="text-muted-foreground">·</span>
+ <span className="text-muted-foreground">{timestamp}</span>
+ </>
+ )}
+ </div>
+ );
+}
+
+function Mention({ children }: { children: React.ReactNode }) {
+ return <span className="font-medium text-brand">{children}</span>;
+}
diff --git a/packages/views/onboarding/steps/step-workspace.tsx b/packages/views/onboarding/steps/step-workspace.tsx
new file mode 100644
index 0000000000..c5fedbb97f
--- /dev/null
+++ b/packages/views/onboarding/steps/step-workspace.tsx
@@ -0,0 +1,608 @@
+"use client";
+
+import { type ReactNode, useRef, useState } from "react";
+import {
+ ArrowLeft,
+ ArrowRight,
+ BookOpenText,
+ Bot,
+ FolderKanban,
+ Inbox,
+ ListTodo,
+ Lock,
+ MoreHorizontal,
+ Monitor,
+ Plus,
+ Zap,
+} from "lucide-react";
+import { toast } from "sonner";
+import { Button } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
+import { Label } from "@multica/ui/components/ui/label";
+import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";
+import { cn } from "@multica/ui/lib/utils";
+import { useCreateWorkspace } from "@multica/core/workspace/mutations";
+import type { Workspace } from "@multica/core/types";
+import { DragStrip } from "@multica/views/platform";
+import { StepHeader } from "../components/step-header";
+import { RadioMark } from "../components/option-card";
+import { WorkspaceAvatar } from "../../workspace/workspace-avatar";
+import {
+ WORKSPACE_SLUG_CONFLICT_ERROR,
+ WORKSPACE_SLUG_FORMAT_ERROR,
+ WORKSPACE_SLUG_REGEX,
+ isWorkspaceSlugConflict,
+ nameToWorkspaceSlug,
+} from "../../workspace/slug";
+
+/**
+ * Step 2 — create your first workspace, or continue with one set up in
+ * an earlier session.
+ *
+ * Shares Questionnaire's editorial two-column skeleton: 3-region app
+ * shell on the left, side panel on the right. One **unified footer CTA**
+ * handles both paths — `Open X` when the user picks an existing
+ * workspace, `Create X` when they name a new one. The name / slug
+ * fields are inlined here (not via the shared `CreateWorkspaceForm`)
+ * because the footer-driven interaction needs externalized submit; the
+ * shared form's own button would fight the footer CTA.
+ *
+ * The create-fields block doubles as a pedagogical preview: the URL is
+ * rendered as a `multica.ai/[slug]` pill, and a live `Issues will look
+ * like ACME-123` line shows the user what their issue IDs will read
+ * like before they've created anything.
+ *
+ * Resume path ships two picker cards (existing + create-new) and the
+ * user toggles between them. No-existing path just shows the create
+ * fields directly.
+ */
+
+function issuePrefix(slug: string): string {
+ // Mirrors the server's default prefix derivation — first 4 chars of
+ // the slug, uppercased. Falls back to "WS" when the slug is empty so
+ // the preview line never collapses to a single dangling "-".
+ const head = slug.trim().replace(/[^a-z0-9]/g, "").slice(0, 4);
+ return (head || "ws").toUpperCase();
+}
+
+export function StepWorkspace({
+ existing,
+ onCreated,
+ onBack,
+}: {
+ existing?: Workspace | null;
+ onCreated: (workspace: Workspace) => void | Promise<void>;
+ onBack?: () => void;
+}) {
+ const mainRef = useRef<HTMLElement>(null);
+ const fadeStyle = useScrollFade(mainRef);
+
+ const reusing = existing ?? null;
+ // Resume path only: user picks which card. `null` = neither yet, so
+ // the footer CTA stays disabled. Clicking either card toggles — a
+ // second click on the same card deselects it. No-existing path
+ // ignores this state entirely.
+ const [mode, setMode] = useState<"existing" | "create" | null>(null);
+ const pickExisting = () =>
+ setMode((m) => (m === "existing" ? null : "existing"));
+ const pickCreate = () =>
+ setMode((m) => (m === "create" ? null : "create"));
+
+ // Form state for the create path. Mirrors CreateWorkspaceForm's
+ // internals: slug auto-fills from name until the user manually edits
+ // it; server-side slug conflicts show inline. Kept at this level so
+ // the footer CTA can read `canCreate` and trigger `handleCreate`.
+ const [name, setName] = useState("");
+ const [slug, setSlug] = useState("");
+ const [slugServerError, setSlugServerError] = useState<string | null>(null);
+ const slugTouched = useRef(false);
+
+ const slugValidationError =
+ slug.length > 0 && !WORKSPACE_SLUG_REGEX.test(slug)
+ ? WORKSPACE_SLUG_FORMAT_ERROR
+ : null;
+ const slugError = slugValidationError ?? slugServerError;
+ const canCreate =
+ name.trim().length > 0 && slug.trim().length > 0 && !slugError;
+
+ const handleNameChange = (value: string) => {
+ setName(value);
+ if (!slugTouched.current) {
+ setSlug(nameToWorkspaceSlug(value));
+ setSlugServerError(null);
+ }
+ };
+
+ const handleSlugChange = (value: string) => {
+ slugTouched.current = true;
+ setSlug(value);
+ setSlugServerError(null);
+ };
+
+ const createWorkspace = useCreateWorkspace();
+
+ const handleCreate = () => {
+ if (!canCreate || createWorkspace.isPending) return;
+ createWorkspace.mutate(
+ { name: name.trim(), slug: slug.trim() },
+ {
+ onSuccess: onCreated,
+ onError: (error) => {
+ if (isWorkspaceSlugConflict(error)) {
+ setSlugServerError(WORKSPACE_SLUG_CONFLICT_ERROR);
+ toast.error("Choose a different workspace URL");
+ return;
+ }
+ toast.error("Failed to create workspace");
+ },
+ },
+ );
+ };
+
+ // Compute the footer CTA from whichever path the user is on. `null`
+ // is only reachable in the resume path; `existing` is only valid
+ // when we actually have a `reusing` workspace; everything else
+ // (including the no-existing path) funnels through `create`.
+ const isCreating = createWorkspace.isPending;
+ const creatingActive = !reusing || mode === "create";
+ const existingActive = Boolean(reusing) && mode === "existing";
+
+ let hint: string;
+ let continueLabel: string;
+ let continueDisabled: boolean;
+ let onContinue: () => void;
+
+ if (existingActive && reusing) {
+ hint = `Opening ${reusing.name}.`;
+ continueLabel = `Open ${reusing.name}`;
+ continueDisabled = isCreating;
+ onContinue = () => onCreated(reusing);
+ } else if (creatingActive) {
+ if (isCreating) {
+ hint = `Creating ${name.trim() || "your workspace"}…`;
+ continueLabel = "Creating…";
+ continueDisabled = true;
+ onContinue = () => {};
+ } else if (canCreate) {
+ hint = `Creating ${name.trim()}.`;
+ continueLabel = `Create ${name.trim()}`;
+ continueDisabled = false;
+ onContinue = handleCreate;
+ } else {
+ hint = "Name your workspace to create it.";
+ continueLabel = "Create workspace";
+ continueDisabled = true;
+ onContinue = () => {};
+ }
+ } else {
+ // Resume path, nothing picked yet.
+ hint = "Pick your workspace or start a new one.";
+ continueLabel = "Continue";
+ continueDisabled = true;
+ onContinue = () => {};
+ }
+
+ const createFields = (
+ <div className="flex flex-col gap-5">
+ <div className="flex flex-col gap-1.5">
+ <Label
+ htmlFor="ws-name"
+ className="text-xs font-medium text-muted-foreground"
+ >
+ Workspace name
+ </Label>
+ <Input
+ id="ws-name"
+ autoFocus
+ type="text"
+ value={name}
+ onChange={(e) => handleNameChange(e.target.value)}
+ placeholder="Acme Inc, My Lab, Side Projects…"
+ onKeyDown={(e) => e.key === "Enter" && handleCreate()}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <Label
+ htmlFor="ws-slug"
+ className="text-xs font-medium text-muted-foreground"
+ >
+ URL
+ </Label>
+ <div className="flex items-center rounded-md border bg-muted transition-colors focus-within:border-foreground">
+ <span className="select-none pl-3 font-mono text-sm text-muted-foreground">
+ multica.ai/
+ </span>
+ <Input
+ id="ws-slug"
+ type="text"
+ value={slug}
+ onChange={(e) => handleSlugChange(e.target.value)}
+ placeholder="acme"
+ className="border-0 bg-transparent font-mono shadow-none focus-visible:ring-0"
+ onKeyDown={(e) => e.key === "Enter" && handleCreate()}
+ />
+ </div>
+ {slugError && <p className="text-xs text-destructive">{slugError}</p>}
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <div className="text-xs font-medium text-muted-foreground">
+ Issue prefix
+ </div>
+ <div className="text-sm leading-[1.55] text-muted-foreground">
+ Issues will look like{" "}
+ <span className="font-mono text-foreground">
+ {issuePrefix(slug)}-123
+ </span>
+ . You can change this later in settings.
+ </div>
+ </div>
+ </div>
+ );
+
+ return (
+ <div className="animate-onboarding-enter grid h-full min-h-0 grid-cols-1 lg:grid-cols-[minmax(0,1fr)_480px]">
+ {/* Left column — DragStrip + 3-region app shell */}
+ <div className="flex min-h-0 flex-col">
+ <DragStrip />
+ <header className="flex shrink-0 items-center gap-4 bg-background px-6 py-3 sm:px-10 md:px-14 lg:px-16">
+ {onBack ? (
+ <button
+ type="button"
+ onClick={onBack}
+ disabled={isCreating}
+ className="flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40"
+ >
+ <ArrowLeft className="h-3.5 w-3.5" />
+ Back
+ </button>
+ ) : (
+ <span aria-hidden className="w-0" />
+ )}
+ <div className="flex-1">
+ <StepHeader currentStep="workspace" />
+ </div>
+ </header>
+
+ <main
+ ref={mainRef}
+ style={fadeStyle}
+ className="min-h-0 flex-1 overflow-y-auto"
+ >
+ <div className="mx-auto w-full max-w-[620px] px-6 py-10 sm:px-10 md:px-14 lg:px-0 lg:py-14">
+ <div className="mb-2 text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">
+ {reusing ? "Pick up or start fresh" : "Your first workspace"}
+ </div>
+ <h1 className="text-balance font-serif text-[36px] font-medium leading-[1.1] tracking-tight text-foreground">
+ {reusing
+ ? `Continue with ${reusing.name}, or start another.`
+ : "Name your workspace."}
+ </h1>
+ <p className="mt-4 text-[15.5px] leading-[1.55] text-foreground/80">
+ {reusing
+ ? "Resume setup with the workspace you already have, or create a new one alongside it — you can belong to any number of workspaces."
+ : "A workspace is where your issues, agents, and projects live. You can invite teammates or spin up more workspaces later."}
+ </p>
+
+ <div className="mt-10">
+ {reusing ? (
+ <div className="flex flex-col gap-3">
+ <ExistingWorkspaceCard
+ workspace={reusing}
+ selected={mode === "existing"}
+ onSelect={pickExisting}
+ />
+ <CreateNewWorkspaceCard
+ selected={mode === "create"}
+ onSelect={pickCreate}
+ >
+ {createFields}
+ </CreateNewWorkspaceCard>
+ </div>
+ ) : (
+ createFields
+ )}
+ </div>
+ </div>
+ </main>
+
+ <footer className="flex shrink-0 items-center justify-end gap-4 bg-background px-6 py-4 sm:px-10 md:px-14 lg:px-16">
+ <span aria-live="polite" className="text-xs text-muted-foreground">
+ {hint}
+ </span>
+ <Button size="lg" disabled={continueDisabled} onClick={onContinue}>
+ {continueLabel}
+ <ArrowRight className="h-4 w-4" />
+ </Button>
+ </footer>
+ </div>
+
+ {/* Right — side panel.
+ Swap sides based on what the user is currently picking:
+ switching to "create" in the resume path swaps the preview
+ from "your existing workspace + what's next" to the generic
+ "what lives inside / things you'll do here" so the preview
+ stays honest to the user's current choice. */}
+ <aside className="hidden min-h-0 border-l bg-muted/40 lg:flex lg:flex-col">
+ <DragStrip />
+ <div className="min-h-0 flex-1 overflow-y-auto px-12 py-12">
+ {reusing && mode !== "create" ? (
+ <ExistingWorkspaceSide workspace={reusing} />
+ ) : (
+ <CreateWorkspaceSide />
+ )}
+ </div>
+ </aside>
+ </div>
+ );
+}
+
+function ExistingWorkspaceCard({
+ workspace,
+ selected,
+ onSelect,
+}: {
+ workspace: Workspace;
+ selected: boolean;
+ onSelect: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ onClick={onSelect}
+ className={cn(
+ "flex w-full items-center gap-4 rounded-lg border bg-card px-5 py-4 text-left transition-all",
+ selected
+ ? "border-foreground shadow-[inset_0_0_0_1px_var(--color-foreground)]"
+ : "hover:border-foreground/20 hover:bg-accent/30",
+ )}
+ >
+ <WorkspaceAvatar name={workspace.name} size="lg" />
+ <div className="flex min-w-0 flex-1 flex-col">
+ <div className="truncate text-[14.5px] font-medium text-foreground">
+ {workspace.name}
+ </div>
+ <div className="truncate font-mono text-xs text-muted-foreground">
+ multica.ai/{workspace.slug}
+ </div>
+ </div>
+ <RadioMark selected={selected} />
+ </button>
+ );
+}
+
+/**
+ * Collapsible "Create a new workspace" radio card — shown in the resume
+ * path alongside the existing-workspace card. Clicking the header
+ * toggles selection; selected state expands to reveal the name / slug
+ * fields (passed in as children by the caller). Submission is driven
+ * by the parent's footer CTA, not a button inside this card.
+ */
+function CreateNewWorkspaceCard({
+ selected,
+ onSelect,
+ children,
+}: {
+ selected: boolean;
+ onSelect: () => void;
+ children: ReactNode;
+}) {
+ return (
+ <div
+ className={cn(
+ "overflow-hidden rounded-lg border bg-card transition-all",
+ selected
+ ? "border-foreground shadow-[inset_0_0_0_1px_var(--color-foreground)]"
+ : "hover:border-foreground/20",
+ )}
+ >
+ <button
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ aria-expanded={selected}
+ onClick={onSelect}
+ className="flex w-full items-center gap-4 px-5 py-4 text-left"
+ >
+ <div
+ aria-hidden
+ className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground"
+ >
+ <Plus className="h-4 w-4" />
+ </div>
+ <div className="flex min-w-0 flex-1 flex-col">
+ <div className="truncate text-[14.5px] font-medium text-foreground">
+ Create a new workspace
+ </div>
+ <div className="truncate text-xs text-muted-foreground">
+ Start fresh — a separate space for a different side of your work.
+ </div>
+ </div>
+ <RadioMark selected={selected} />
+ </button>
+ {selected && <div className="border-t px-5 py-5">{children}</div>}
+ </div>
+ );
+}
+
+function CreateWorkspaceSide() {
+ return (
+ <div className="flex flex-col gap-6">
+ <div className="text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">
+ What lives inside a workspace
+ </div>
+
+ <WorkspacePreviewCard name="Your workspace" slug="workspace" />
+
+ <div className="mt-2 text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">
+ Things you&apos;ll do here
+ </div>
+ <div className="flex flex-col gap-3.5">
+ <PerkRow>Assign issues to agents like you would a teammate</PerkRow>
+ <PerkRow>Chat with any agent without creating an issue</PerkRow>
+ <PerkRow>Invite teammates — they see only this workspace</PerkRow>
+ <PerkRow>Switch to other workspaces anytime from the top-left</PerkRow>
+ </div>
+ </div>
+ );
+}
+
+function ExistingWorkspaceSide({ workspace }: { workspace: Workspace }) {
+ return (
+ <div className="flex flex-col gap-6">
+ <div className="text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">
+ Your workspace
+ </div>
+
+ <WorkspacePreviewCard name={workspace.name} slug={workspace.slug} />
+
+ <div className="mt-2 text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">
+ What&apos;s next
+ </div>
+ <div className="flex flex-col gap-3.5">
+ <PerkRow>
+ Connect a runtime so your agents have somewhere to run
+ </PerkRow>
+ <PerkRow>Create your first agent matched to your role</PerkRow>
+ <PerkRow>Watch it pick up a starter task and reply</PerkRow>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Visual preview of the sidebar the user is about to land on — same
+ * icons, same labels as the live `<AppSidebar />`, so the onboarding
+ * card doubles as "this is what your sidebar will look like." Entity
+ * set mirrors the Workspace + Configure groups, lifting Members from
+ * Settings to a first-class row because it's the most intuitive way
+ * to express "workspaces are multi-player."
+ */
+function WorkspacePreviewCard({
+ name,
+ slug,
+}: {
+ name: string;
+ slug: string;
+}) {
+ return (
+ <div className="overflow-hidden rounded-xl border bg-card shadow-xs">
+ <div className="flex items-center gap-3 border-b px-4 py-3.5">
+ <WorkspaceAvatar name={name} size="md" />
+ <div className="flex min-w-0 flex-1 flex-col">
+ <div className="truncate text-[14px] font-medium text-foreground">
+ {name}
+ </div>
+ <div className="truncate font-mono text-[11.5px] text-muted-foreground">
+ multica.ai/{slug}
+ </div>
+ </div>
+ <Lock
+ aria-hidden
+ className="h-3.5 w-3.5 shrink-0 text-muted-foreground/60"
+ />
+ </div>
+ <div className="flex flex-col">
+ <EntityRow
+ icon={<Inbox className="h-4 w-4" />}
+ label="Inbox"
+ meta="your notifications"
+ />
+ <EntityRow
+ icon={<ListTodo className="h-4 w-4" />}
+ label="Issues"
+ meta="shared task board"
+ />
+ <EntityRow
+ icon={<Bot className="h-4 w-4" />}
+ label="Agents"
+ meta="your AI teammates"
+ />
+ <EntityRow
+ icon={<FolderKanban className="h-4 w-4" />}
+ label="Projects"
+ meta="group related issues"
+ />
+ <EntityRow
+ icon={<Zap className="h-4 w-4" />}
+ label="Autopilot"
+ meta="scheduled automation"
+ />
+ <EntityRow
+ icon={<Monitor className="h-4 w-4" />}
+ label="Runtimes"
+ meta="where agents run"
+ />
+ <EntityRow
+ icon={<BookOpenText className="h-4 w-4" />}
+ label="Skills"
+ meta="reusable playbooks"
+ />
+ <EntityRow
+ dim
+ icon={<MoreHorizontal className="h-4 w-4" />}
+ label="And more"
+ meta="and more"
+ />
+ </div>
+ </div>
+ );
+}
+
+function EntityRow({
+ icon,
+ label,
+ meta,
+ dim,
+}: {
+ icon: ReactNode;
+ label: string;
+ meta: string;
+ /** Visually de-emphasized — used for the "and more" row at the bottom. */
+ dim?: boolean;
+}) {
+ return (
+ <div className="flex items-center gap-3 px-4 py-2.5 [&:not(:last-child)]:border-b">
+ <span
+ aria-hidden
+ className={cn(
+ "shrink-0",
+ dim ? "text-muted-foreground/60" : "text-muted-foreground",
+ )}
+ >
+ {icon}
+ </span>
+ <span
+ className={cn(
+ "flex-1 text-[13.5px]",
+ dim ? "text-muted-foreground" : "text-foreground",
+ )}
+ >
+ {label}
+ </span>
+ <span
+ className={cn(
+ "font-mono text-[11.5px]",
+ dim ? "text-muted-foreground/70" : "text-muted-foreground",
+ )}
+ >
+ {meta}
+ </span>
+ </div>
+ );
+}
+
+function PerkRow({ children }: { children: ReactNode }) {
+ return (
+ <div className="grid grid-cols-[18px_1fr] items-start gap-3">
+ <span
+ aria-hidden
+ className="mt-[11px] h-px w-3 shrink-0 bg-muted-foreground/40"
+ />
+ <div className="text-[13.5px] leading-[1.55] text-foreground/85">
+ {children}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/onboarding/utils/starter-content-templates.ts b/packages/views/onboarding/utils/starter-content-templates.ts
new file mode 100644
index 0000000000..bf5633ceb7
--- /dev/null
+++ b/packages/views/onboarding/utils/starter-content-templates.ts
@@ -0,0 +1,611 @@
+import type { QuestionnaireAnswers } from "@multica/core/onboarding";
+import type {
+ ImportStarterContentPayload,
+ ImportStarterIssuePayload,
+} from "@multica/core/api";
+
+// =============================================================================
+// Starter content templates.
+//
+// Pure functions that turn the user's questionnaire answers into the request
+// payload for POST /api/me/starter-content/import. No side effects, no API
+// calls, no DOM — the only consumer is `StarterContentPrompt`, which passes
+// the output straight to the server.
+//
+// Separation of concerns:
+// - Markdown/copy lives here (TypeScript, reviewed as UI)
+// - Batch creation + idempotency + assignee resolution lives in Go
+// (handler/onboarding.go → ImportStarterContent)
+// =============================================================================
+
+interface WelcomeIssueText {
+ title: string;
+ description: string;
+}
+
+// Prefix titles with 1. 2. 3. … AFTER the full list is assembled so
+// conditional items (invite team / connect repo) don't break numbering.
+function numberTitles(
+ issues: ImportStarterIssuePayload[],
+): ImportStarterIssuePayload[] {
+ return issues.map((s, i) => ({ ...s, title: `${i + 1}. ${s.title}` }));
+}
+
+export function buildWelcomeIssueText(
+ q: QuestionnaireAnswers,
+ userName: string,
+): WelcomeIssueText {
+ const name = userName.trim() || "there";
+
+ const header = [
+ `Welcome to Multica! 👋`,
+ ``,
+ `This is your workspace's first issue. Below, your agent will reply in a moment — that's how work happens here: you write what you want, your agent (or a teammate) picks it up and replies in the comments.`,
+ ``,
+ `---`,
+ ``,
+ ].join("\n");
+
+ const sharedInstructions = [
+ `In your first reply, please:`,
+ ``,
+ `1. **Introduce yourself briefly** — your name, your role, what you're good at.`,
+ `2. **Explain how we work together in Multica**:`,
+ ` - Assigning an issue to you **and** setting its status to **Todo** is what triggers you to start (Backlog pauses you)`,
+ ` - @mentioning you inside a comment is for quick questions`,
+ ` - **Workspace Context** (in Settings → General) is shared background every agent here sees`,
+ `3. **Point them at the *Getting Started* project** in the sidebar and invite them to assign you a real task when they're ready.`,
+ ``,
+ `Keep it friendly and under 200 words. End with one short question that invites ${name} to reply.`,
+ ].join("\n");
+
+ // Softer variant for users who said they're just exploring — no
+ // pressure to "assign a real task", just pull them into a
+ // low-stakes conversation.
+ const exploreInstructions = [
+ `In your first reply, please:`,
+ ``,
+ `1. **Introduce yourself briefly** — your name, your role, what you're good at.`,
+ `2. **Explain how we work together in Multica**:`,
+ ` - Assigning an issue to you **and** setting its status to **Todo** triggers you to start (Backlog pauses you)`,
+ ` - @mentioning you inside a comment is for quick questions`,
+ ` - **Workspace Context** (in Settings → General) is shared background every agent here sees`,
+ `3. **Point them at the *Getting Started* project** in the sidebar.`,
+ ``,
+ `Keep it friendly and under 200 words. End with a small, curious question — something like "what's something you've been wondering about lately?" — so ${name} has an easy way to reply without having to come up with a real task yet.`,
+ ].join("\n");
+
+ switch (q.use_case) {
+ case "coding":
+ return {
+ title: "👋 Welcome to Multica — let's work together",
+ description: `${header}Hi agent, this is ${name}'s first time using Multica. They plan to use you mostly for **coding work**.\n\n${sharedInstructions}`,
+ };
+ case "planning":
+ return {
+ title: "👋 Welcome to Multica — let's work together",
+ description: `${header}Hi agent, this is ${name}'s first time using Multica. They want your help with **planning and breaking down work**.\n\n${sharedInstructions}`,
+ };
+ case "writing_research":
+ return {
+ title: "👋 Welcome to Multica — let's work together",
+ description: `${header}Hi agent, this is ${name}'s first time using Multica. They'll use you for **research and writing** — drafting, summarizing, analysis.\n\n${sharedInstructions}`,
+ };
+ case "explore":
+ return {
+ title: "👋 Welcome to Multica — let's work together",
+ description: `${header}Hi agent, this is ${name}'s first time using Multica. They're **exploring** what Multica can do — no specific goal yet.\n\n${exploreInstructions}`,
+ };
+ case "other": {
+ const customUseCase = (q.use_case_other ?? "").trim();
+ const contextLine = customUseCase
+ ? `They told us they want to use you for: "${customUseCase}".`
+ : `They haven't narrowed down their use case yet.`;
+ return {
+ title: "👋 Welcome to Multica — let's work together",
+ description: `${header}Hi agent, this is ${name}'s first time using Multica. ${contextLine}\n\n${sharedInstructions}`,
+ };
+ }
+ default:
+ return {
+ title: "👋 Welcome to Multica — let's work together",
+ description: `${header}Hi agent, this is ${name}'s first time using Multica.\n\n${sharedInstructions}`,
+ };
+ }
+}
+
+export function buildAgentGuidedSubIssues(
+ q: QuestionnaireAnswers,
+): ImportStarterIssuePayload[] {
+ // --- Tier 1: Core must-learn (Todo / urgent) ------------------------------
+ const tier1: ImportStarterIssuePayload[] = [
+ {
+ status: "todo",
+ priority: "high",
+ assign_to_self: true,
+ title: "Learn how to trigger your agent on any issue",
+ description: [
+ `**Every issue has a right-side panel** called **Properties**. From there you control who works on what. Agents in Multica are triggered when an issue has:`,
+ ``,
+ ` Assignee = your agent AND Status = Todo (not Backlog)`,
+ ``,
+ `**Try it now**:`,
+ `1. In the sidebar, click **New Issue** at the top (or press \`C\`)`,
+ `2. Give it a title like "Test run: summarize our product in 3 bullets"`,
+ `3. On the right panel, find **Assignee** (third row) → click → pick your agent`,
+ `4. Find **Status** (top row) → click → pick **Todo**`,
+ `5. Scroll down to Activity — a **Live card** appears as your agent starts working`,
+ ``,
+ `**⚠️ Gotcha**: new issues default to Backlog. Agents pause on backlog. A hint dialog will pop up the first time — it's telling you "flip to Todo to start".`,
+ ``,
+ `**You'll know it worked when**: the Live card shows your agent thinking, and the Status flips to **In Progress** automatically.`,
+ ].join("\n"),
+ },
+ {
+ status: "todo",
+ priority: "high",
+ assign_to_self: true,
+ title: "Chat with your agent — no issue required",
+ description: [
+ `Not every question needs a whole issue. For quick back-and-forth, use the **Chat panel**.`,
+ ``,
+ `**Where to find it**: look at the **bottom-right corner of the screen** — there's a round button with a **💬 speech bubble icon**. If your agent is working, the button pulses. If there are unread replies, a red badge sits on top of it.`,
+ ``,
+ `**Try it now**:`,
+ `1. Click the 💬 button → a panel slides in from the right`,
+ `2. At the **bottom-left of the input box**, click the agent avatar → pick your agent from the dropdown`,
+ `3. Type a quick question: "What can you help me with in this workspace?"`,
+ `4. Press **Enter**`,
+ ``,
+ `**Bonus — @mention an agent inside a comment**: on any issue, scroll to the comment box at the bottom. Type \`@\` and a dropdown appears listing members, agents, and other issues. Pick an agent → write your question → send. The mentioned agent replies in the comments.`,
+ ``,
+ `**You'll know it worked when**: the agent replies in the chat panel (or comment thread) within a few seconds.`,
+ ].join("\n"),
+ },
+ {
+ status: "todo",
+ priority: "high",
+ assign_to_self: true,
+ title: "Write your Workspace Context",
+ description: [
+ `**Workspace Context** is a shared system prompt every agent in this workspace reads before starting any task. It's the single most impactful thing you can do to make agent replies sharper.`,
+ ``,
+ `**Where to find it**:`,
+ `1. Open the **sidebar** → scroll to the bottom section labeled **Configure**`,
+ `2. Click **Settings** (⚙️ gear icon, bottom-most item)`,
+ `3. In the left-side tab list, under the **[Your Workspace Name]** group, click **General**`,
+ `4. Scroll down to the **Context** textarea (placeholder says "Provide context to agents...")`,
+ ``,
+ `**Fill it with 3-5 lines**:`,
+ `- Who you are (name, role)`,
+ `- What you're building or working on`,
+ `- How agents should behave (tone, style, defaults)`,
+ ``,
+ `**Example**:`,
+ `> I'm a frontend engineer working on an AI-native task manager. Reply concisely in English. Always explain your reasoning. Prefer TypeScript over JavaScript.`,
+ ``,
+ `Click **Save**.`,
+ ``,
+ `**You'll know it worked when**: the next task you assign to an agent picks up details from this context without you explaining again.`,
+ ].join("\n"),
+ },
+ ];
+
+ // --- Tier 2: Setup (Todo / medium) ----------------------------------------
+ const tier2: ImportStarterIssuePayload[] = [];
+
+ if (q.team_size === "team") {
+ tier2.push({
+ status: "todo",
+ priority: "medium",
+ assign_to_self: true,
+ title: "Invite your teammates",
+ description: [
+ `Multica works best when a small team shares agents.`,
+ ``,
+ `**Where to find it**:`,
+ `1. Sidebar → **Settings** (⚙️, bottom)`,
+ `2. Left tab list → under **[Your Workspace]** group → click **Members** (people icon)`,
+ `3. At the top of the page, click **Add member**`,
+ `4. Enter their email, pick a role (**Owner / Admin / Member**)`,
+ `5. Click **Send invite**`,
+ ``,
+ `They'll receive an email with a join link. Pending invites show in the collapsible "Pending Invitations" section below the member list — you can revoke from there.`,
+ ].join("\n"),
+ });
+ }
+
+ if (q.role === "developer" || q.use_case === "coding") {
+ tier2.push({
+ status: "todo",
+ priority: "medium",
+ assign_to_self: true,
+ title: "Connect a Git repo",
+ description: [
+ `Once connected, any agent can clone, read, and propose changes to your repo when you assign it a task.`,
+ ``,
+ `**Where to find it**:`,
+ `1. Sidebar → **Settings** (⚙️)`,
+ `2. Left tab list → under **[Your Workspace]** group → **Repositories** (folder with Git branch icon)`,
+ `3. At the bottom of the list, click **+ Add repository**`,
+ `4. Fill the two inline fields:`,
+ ` - **URL** — e.g. \`https://github.com/you/repo.git\``,
+ ` - **Description** — what this repo is for`,
+ `5. Click **Save** at the top of the page`,
+ ``,
+ `Repeat for as many repos as you want to expose.`,
+ ].join("\n"),
+ });
+ }
+
+ tier2.push({
+ status: "todo",
+ priority: "medium",
+ assign_to_self: true,
+ title: "Create a second agent with a different role",
+ description: [
+ `Running a small team of focused agents beats a single generalist. One for coding, one for planning, one for writing — each with their own instructions.`,
+ ``,
+ `**Note**: nothing locks a "Coding Agent" to coding. Instructions are just a system prompt, editable anytime. The split is about keeping each one's replies sharp.`,
+ ``,
+ `**Where to find it**:`,
+ `1. Sidebar → under **Workspace** group → click **Agents** (🤖 bot icon)`,
+ `2. In the left list header, click the **+** button (top-right corner of the list)`,
+ `3. Fill the 4 fields in order:`,
+ ` - **Name** — e.g. "Planning Agent"`,
+ ` - **Description** — "Breaks down loose ideas into scoped work"`,
+ ` - **Visibility** — Workspace (shared) or Private (only you)`,
+ ` - **Runtime** — pick from the dropdown (your connected runtime)`,
+ `4. Click **Create**`,
+ ``,
+ `**You'll know it worked when**: the new agent appears in the Assignee dropdown on any issue, and shows up in the left list on the Agents page.`,
+ ].join("\n"),
+ });
+
+ // --- Tier 3: Advanced, discover later (Backlog) ---------------------------
+ const tier3: ImportStarterIssuePayload[] = [
+ {
+ status: "backlog",
+ priority: "low",
+ assign_to_self: true,
+ title: "Polish your agent's Instructions",
+ description: [
+ `Creating an agent is just the start. The **Instructions tab** is where you shape how it behaves.`,
+ ``,
+ `**Where to find it**:`,
+ `1. Sidebar → **Agents** (🤖)`,
+ `2. In the left list, click an agent you want to refine`,
+ `3. In the right panel, you'll see 6 tabs at the top: **Instructions / Skills / Tasks / Environment / Custom Args / Settings**`,
+ `4. Click **Instructions**`,
+ `5. Edit the markdown — changes save automatically`,
+ ``,
+ `**Good instructions include**:`,
+ `- The role/persona (e.g. "You're a senior TypeScript engineer")`,
+ `- House rules (e.g. "Always propose tests alongside code")`,
+ `- Output format (e.g. "Return a short summary first, details below")`,
+ ``,
+ `Workspace Context and agent Instructions stack — both are sent on every task. Keep Instructions specific to this agent; keep Context specific to the whole workspace.`,
+ ].join("\n"),
+ },
+ {
+ status: "backlog",
+ priority: "low",
+ assign_to_self: true,
+ title: "Watch your agent live in action",
+ description: [
+ `**Heads-up task** — nothing to do now, just know this exists.`,
+ ``,
+ `When an agent is working on an issue, a **Live card** appears at the top of the **Activity** section (it sticks to the top of the viewport as you scroll).`,
+ ``,
+ `The card shows in real time:`,
+ `- Which tool the agent is calling (e.g. reading a file, web search)`,
+ `- Streaming thoughts and partial output`,
+ `- Current status (thinking / tool-running / done / failed)`,
+ ``,
+ `After the run finishes, the **Task Run History** below the card lists every past run. Click **View transcript** on any row to open the full interactive transcript — a timeline of every message, thinking step, tool call, and result.`,
+ ``,
+ `**Try it next time you assign an agent**: keep the issue open and watch the Live card appear below the description.`,
+ ].join("\n"),
+ },
+ {
+ status: "backlog",
+ priority: "low",
+ assign_to_self: true,
+ title: "Check your Inbox for @mentions and updates",
+ description: [
+ `When someone — or an agent — @mentions you or assigns you an issue, it lands in your **Inbox**.`,
+ ``,
+ `**Where to find it**:`,
+ `1. Sidebar → the top section (above the **Workspace** group) → click **Inbox** (📥 icon) — an unread count badge shows on the right if you have new items`,
+ ``,
+ `**How it works**:`,
+ `- Left column: notification list, newest first`,
+ `- Right column: the linked issue opens inline, and the specific comment that mentioned you is **auto-highlighted and scrolled into view**`,
+ `- Top-right dropdown: **Mark all as read / Archive all / Archive all read / Archive completed** for bulk cleanup`,
+ ``,
+ `**Tip**: "Archive completed" is the fastest way to clear the noise from issues already finished.`,
+ ].join("\n"),
+ },
+ {
+ status: "backlog",
+ priority: "low",
+ assign_to_self: true,
+ title: "Set up an Autopilot for recurring work",
+ description: [
+ `**Autopilot** turns a prompt into a scheduled task. Every day/week/hour, it auto-creates an issue and assigns it to an agent.`,
+ ``,
+ `**Where to find it**:`,
+ `1. Sidebar → under **Workspace** group → click **Autopilot** (⚡ Zap icon)`,
+ `2. If you have no autopilots yet, a grid of **6 templates** shows up: Daily news digest, PR review reminder, Bug triage, Weekly progress report, Dependency audit, Documentation check`,
+ `3. Click any template → creation dialog opens pre-filled (or click **+ New autopilot** top-right for a blank one)`,
+ `4. Fill: **Name** / **Prompt** (6-line textarea) / **Agent** / **Schedule** (frequency + time + timezone)`,
+ `5. Click **Create**`,
+ ``,
+ `**Good first autopilots**: daily digest of GitHub activity, weekly "what's blocked" check, or a Monday-morning triage of any issues still in Backlog.`,
+ ].join("\n"),
+ },
+ ];
+
+ return numberTitles([...tier1, ...tier2, ...tier3]);
+}
+
+export function buildSelfServeSubIssues(
+ q: QuestionnaireAnswers,
+): ImportStarterIssuePayload[] {
+ // --- Tier 1: Unlock agent ability (Todo / high) ---------------------------
+ // Without a runtime + an agent, nothing else in Multica works. These two
+ // are the gates — everything below them waits on them.
+ const tier1: ImportStarterIssuePayload[] = [
+ {
+ status: "todo",
+ priority: "high",
+ assign_to_self: true,
+ title: "Install a runtime (Desktop app or CLI)",
+ description: [
+ `**Why this first**: no runtime = no agents can execute. Everything below Tier 1 waits on this.`,
+ ``,
+ `A **runtime** is a small background process that runs on your machine. It connects your workspace to AI coding tools (Claude Code, Codex, …) and executes the tasks your agents pick up.`,
+ ``,
+ `**Option A — Desktop app (macOS, recommended if you're on a Mac)**:`,
+ `1. Go to [github.com/multica-ai/multica/releases/latest](https://github.com/multica-ai/multica/releases/latest) and download the \`.dmg\` for macOS`,
+ `2. Install and open the app`,
+ `3. Sign in with the same account — the runtime is built in, you're done`,
+ ``,
+ `**Option B — CLI (macOS, Linux, or Windows via WSL)**:`,
+ `1. In a terminal, install the CLI:`,
+ ` \`\`\``,
+ ` curl -fsSL https://raw.githubusercontent.com/multica-ai/multica/main/scripts/install.sh | bash`,
+ ` \`\`\``,
+ `2. Then run setup (signs you in and starts a background daemon):`,
+ ` \`\`\``,
+ ` multica setup`,
+ ` \`\`\``,
+ ` The daemon keeps running after you close the terminal — you don't have to leave anything open.`,
+ ``,
+ `**Verify**: sidebar → bottom **Configure** section → **Runtimes** → you should see at least one connected runtime.`,
+ ].join("\n"),
+ },
+ {
+ status: "todo",
+ priority: "high",
+ assign_to_self: true,
+ title: "Create your first agent",
+ description: [
+ `**Prerequisite**: task above done (runtime connected).`,
+ ``,
+ `**Where to find it**:`,
+ `1. Sidebar → under **Workspace** group → click **Agents** (🤖 bot icon)`,
+ `2. In the left list header, click the **+** button (top-right corner of the list)`,
+ `3. Fill the 4 fields in order:`,
+ ` - **Name** — e.g. "My Coding Agent"`,
+ ` - **Description** — one line about what it does`,
+ ` - **Visibility** — Workspace (shared) or Private (only you)`,
+ ` - **Runtime** — pick the one you just installed`,
+ `4. Click **Create**`,
+ ``,
+ `**Note**: an agent is just an LLM + instructions + workspace access. Nothing locks a "Coding Agent" to coding — same agent can do research, writing, planning. Keep it flexible.`,
+ ``,
+ `**You'll know it worked when**: the new agent appears in the Assignee dropdown on any issue.`,
+ ].join("\n"),
+ },
+ ];
+
+ // --- Tier 2: Core usage after unlock (Todo / medium) ----------------------
+ const tier2: ImportStarterIssuePayload[] = [
+ {
+ status: "todo",
+ priority: "medium",
+ assign_to_self: true,
+ title: "Assign your first real task to your agent",
+ description: [
+ `**Prerequisite**: you have a runtime + agent from the two tasks above.`,
+ ``,
+ `**How Multica triggers agents**:`,
+ `- Assign an issue to an agent`,
+ `- Set status to **Todo** (not Backlog — backlog pauses agents)`,
+ `- The agent picks it up automatically`,
+ ``,
+ `**Try it now**:`,
+ `1. In the sidebar, click **New Issue** at the top (or press \`C\`)`,
+ `2. Title: something you actually want done`,
+ `3. On the right panel, find **Assignee** → click → pick your agent`,
+ `4. Find **Status** → change from Backlog to **Todo**`,
+ `5. Watch the agent reply in the comments and a **Live card** appear in Activity`,
+ ``,
+ `**⚠️ Gotcha**: new issues default to **Backlog**. You must flip to **Todo** to trigger the agent.`,
+ ].join("\n"),
+ },
+ {
+ status: "todo",
+ priority: "medium",
+ assign_to_self: true,
+ title: "Write your Workspace Context",
+ description: [
+ `**Workspace Context** is a shared system prompt every agent in this workspace reads before starting any task. It's the single most impactful thing you can do to make agent replies sharper.`,
+ ``,
+ `**Where to find it**:`,
+ `1. Open the **sidebar** → scroll to the bottom section labeled **Configure**`,
+ `2. Click **Settings** (⚙️ gear icon, bottom-most item)`,
+ `3. In the left-side tab list, under the **[Your Workspace Name]** group, click **General**`,
+ `4. Scroll down to the **Context** textarea`,
+ ``,
+ `**Fill it with 3-5 lines**:`,
+ `- Who you are (name, role)`,
+ `- What you're building or working on`,
+ `- How agents should behave (tone, style, defaults)`,
+ ``,
+ `Click **Save**.`,
+ ``,
+ `**You'll know it worked when**: the next task you assign to an agent picks up details from this context without you explaining again.`,
+ ].join("\n"),
+ },
+ ];
+
+ // --- Tier 3: Advanced, discover later (Backlog) ---------------------------
+ const tier3: ImportStarterIssuePayload[] = [
+ {
+ status: "backlog",
+ priority: "low",
+ assign_to_self: true,
+ title: "Chat with an agent — once you've created one",
+ description: [
+ `**Prerequisite**: you've created at least one agent (Tier 1 #2).`,
+ ``,
+ `Not every question needs a whole issue. For quick back-and-forth, use the **Chat panel**.`,
+ ``,
+ `**Where to find it**: the **bottom-right corner of the screen** has a round button with a **💬 speech bubble icon**.`,
+ ``,
+ `**Try it**:`,
+ `1. Click the 💬 button → a panel slides in from the right`,
+ `2. At the bottom-left of the input box, pick an agent from the dropdown`,
+ `3. Type a question → press **Enter**`,
+ ``,
+ `**Bonus**: inside any issue's comment box, type \`@\` to mention an agent or member.`,
+ ].join("\n"),
+ },
+ ];
+
+ if (q.role === "developer" || q.use_case === "coding") {
+ tier3.push({
+ status: "backlog",
+ priority: "low",
+ assign_to_self: true,
+ title: "Connect a Git repo",
+ description: [
+ `Once connected, any agent can clone, read, and propose changes to your repo when you assign it a task.`,
+ ``,
+ `**Where to find it**:`,
+ `1. Sidebar → **Settings** (⚙️)`,
+ `2. Left tab list → **Repositories** (folder with Git branch icon)`,
+ `3. At the bottom of the list, click **+ Add repository**`,
+ `4. Fill **URL** (e.g. \`https://github.com/you/repo.git\`) and **Description**`,
+ `5. Click **Save** at the top of the page`,
+ ].join("\n"),
+ });
+ }
+
+ if (q.team_size === "team") {
+ tier3.push({
+ status: "backlog",
+ priority: "low",
+ assign_to_self: true,
+ title: "Invite your teammates",
+ description: [
+ `Multica works best when a small team shares agents.`,
+ ``,
+ `**Where to find it**:`,
+ `1. Sidebar → **Settings** (⚙️, bottom)`,
+ `2. Left tab list → **Members** (people icon)`,
+ `3. Click **Add member** → enter email → pick role → **Send invite**`,
+ ].join("\n"),
+ });
+ }
+
+ tier3.push(
+ {
+ status: "backlog",
+ priority: "low",
+ assign_to_self: true,
+ title: "Shape your agent's Instructions (once it's created)",
+ description: [
+ `**Prerequisite**: you have at least one agent.`,
+ ``,
+ `Creating an agent is just the start. The **Instructions tab** is where you shape how it behaves.`,
+ ``,
+ `**Where to find it**:`,
+ `1. Sidebar → **Agents** (🤖)`,
+ `2. Click an agent in the left list`,
+ `3. Right panel → click the **Instructions** tab (out of 6: Instructions / Skills / Tasks / Environment / Custom Args / Settings)`,
+ `4. Edit the markdown — changes save automatically`,
+ ``,
+ `Workspace Context and agent Instructions stack — both are sent on every task. Keep Instructions specific to this agent; keep Context specific to the whole workspace.`,
+ ].join("\n"),
+ },
+ {
+ status: "backlog",
+ priority: "low",
+ assign_to_self: true,
+ title: "Watch an agent work live (once you've assigned one a task)",
+ description: [
+ `**Heads-up task** — nothing to do now, just know this exists.`,
+ ``,
+ `When an agent is working on an issue, a **Live card** appears at the top of the **Activity** section (it sticks to the top of the viewport as you scroll).`,
+ ``,
+ `It shows in real time which tool the agent is calling, streaming thoughts, and current status. After the run finishes, the **Task Run History** below the card lists every past run — click **View transcript** to open the full timeline.`,
+ ].join("\n"),
+ },
+ {
+ status: "backlog",
+ priority: "low",
+ assign_to_self: true,
+ title: "Set up an Autopilot (once you have an agent)",
+ description: [
+ `**Prerequisite**: you have at least one agent.`,
+ ``,
+ `**Autopilot** turns a prompt into a scheduled task. Every day/week/hour, it auto-creates an issue and assigns it to an agent.`,
+ ``,
+ `**Where to find it**:`,
+ `1. Sidebar → under **Workspace** group → click **Autopilot** (⚡ Zap icon)`,
+ `2. Pick one of 6 templates, or click **+ New autopilot** top-right`,
+ `3. Fill: **Name** / **Prompt** / **Agent** / **Schedule** (frequency + time + timezone) → **Create**`,
+ ].join("\n"),
+ },
+ );
+
+ return numberTitles([...tier1, ...tier2, ...tier3]);
+}
+
+/**
+ * Builds the full import payload. The client does NOT decide between the
+ * agent-guided and self-serve branches — it always sends both sub-issue
+ * arrays and a welcome-issue template (no agent_id). The SERVER picks
+ * inside the import transaction based on whether any agent exists in
+ * the workspace at that moment. See handler/onboarding.go.
+ */
+export function buildImportPayload({
+ workspaceId,
+ userName,
+ questionnaire,
+}: {
+ workspaceId: string;
+ userName: string;
+ questionnaire: QuestionnaireAnswers;
+}): ImportStarterContentPayload {
+ const welcome = buildWelcomeIssueText(questionnaire, userName);
+ return {
+ workspace_id: workspaceId,
+ project: {
+ title: "Getting Started",
+ description:
+ "A few things to try in Multica. Work through them at your own pace.",
+ icon: "👋",
+ },
+ welcome_issue_template: {
+ title: welcome.title,
+ description: welcome.description,
+ priority: "high",
+ },
+ agent_guided_sub_issues: buildAgentGuidedSubIssues(questionnaire),
+ self_serve_sub_issues: buildSelfServeSubIssues(questionnaire),
+ };
+}
diff --git a/packages/views/package.json b/packages/views/package.json
index 00186c308e..fc0983f494 100644
--- a/packages/views/package.json
+++ b/packages/views/package.json
@@ -38,6 +38,7 @@
"./chat": "./chat/index.ts",
"./settings": "./settings/index.ts",
"./invite": "./invite/index.ts",
+ "./onboarding": "./onboarding/index.ts",
"./platform": "./platform/index.ts"
},
"dependencies": {
diff --git a/packages/views/platform/drag-strip.tsx b/packages/views/platform/drag-strip.tsx
new file mode 100644
index 0000000000..f64b45401a
--- /dev/null
+++ b/packages/views/platform/drag-strip.tsx
@@ -0,0 +1,30 @@
+import type { CSSProperties } from "react";
+
+/**
+ * 48px-tall transparent strip that claims `-webkit-app-region: drag` so
+ * macOS users can grab the window by its top edge — under (and making
+ * room for) the native traffic lights.
+ *
+ * Place as the first flex child of any full-window, non-dashboard view
+ * (onboarding, new-workspace, invite, no-access, etc.). The strip has
+ * no background of its own; the parent's bg fills through it so the
+ * page reads as "edge-to-edge" while the top 48px remains draggable.
+ *
+ * Cross-platform: `-webkit-app-region` is a Chromium-only CSS extension;
+ * regular browsers silently ignore it and the element becomes plain
+ * 48px of top breathing room. That makes it safe to keep in shared
+ * `packages/views/` without platform branching.
+ *
+ * Flex child, **not** absolute overlay: `-webkit-app-region` hit-testing
+ * with z-index stacking has been empirically unreliable in this codebase
+ * (see CLAUDE.md "Drag region" note).
+ */
+export function DragStrip() {
+ return (
+ <div
+ aria-hidden
+ className="h-12 shrink-0"
+ style={{ WebkitAppRegion: "drag" } as CSSProperties}
+ />
+ );
+}
diff --git a/packages/views/platform/index.ts b/packages/views/platform/index.ts
index 2822f4952f..b01108eabe 100644
--- a/packages/views/platform/index.ts
+++ b/packages/views/platform/index.ts
@@ -1 +1,2 @@
export { useImmersiveMode } from "./use-immersive-mode";
+export { DragStrip } from "./drag-strip";
diff --git a/packages/views/platform/use-immersive-mode.ts b/packages/views/platform/use-immersive-mode.ts
index 4409a1d7d2..79dd53b982 100644
--- a/packages/views/platform/use-immersive-mode.ts
+++ b/packages/views/platform/use-immersive-mode.ts
@@ -16,13 +16,19 @@ function getDesktopAPI(): ImmersiveCapableAPI | undefined {
* modals (e.g. create-workspace) can place UI in the top-left corner without
* fighting the native controls' hit-test. On web or non-macOS desktop this
* is a no-op.
+ *
+ * `enabled=false` skips the IPC call (and cleanup) entirely, so a caller that
+ * conditionally wants traffic lights visible — like onboarding, which has no
+ * UI in the top-left and benefits from native window chrome — can opt out
+ * without unmounting the hook.
*/
-export function useImmersiveMode(): void {
+export function useImmersiveMode(enabled: boolean = true): void {
useEffect(() => {
+ if (!enabled) return;
const api = getDesktopAPI();
api?.setImmersiveMode?.(true);
return () => {
api?.setImmersiveMode?.(false);
};
- }, []);
+ }, [enabled]);
}
diff --git a/packages/views/settings/components/workspace-tab.tsx b/packages/views/settings/components/workspace-tab.tsx
index 4d60ae419c..7025ddfc7e 100644
--- a/packages/views/settings/components/workspace-tab.tsx
+++ b/packages/views/settings/components/workspace-tab.tsx
@@ -22,14 +22,17 @@ import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useAuthStore } from "@multica/core/auth";
import { useLeaveWorkspace, useDeleteWorkspace } from "@multica/core/workspace/mutations";
import { useWorkspaceId } from "@multica/core/hooks";
-import { useCurrentWorkspace } from "@multica/core/paths";
import {
memberListOptions,
workspaceKeys,
workspaceListOptions,
} from "@multica/core/workspace/queries";
import { api } from "@multica/core/api";
-import { paths } from "@multica/core/paths";
+import {
+ resolvePostAuthDestination,
+ useCurrentWorkspace,
+ useHasOnboarded,
+} from "@multica/core/paths";
import { setCurrentWorkspace } from "@multica/core/platform";
import type { Workspace } from "@multica/core/types";
import { useNavigation } from "../../navigation";
@@ -44,6 +47,7 @@ export function WorkspaceTab() {
const leaveWorkspace = useLeaveWorkspace();
const deleteWorkspace = useDeleteWorkspace();
const navigation = useNavigation();
+ const hasOnboarded = useHasOnboarded();
/**
* Send the user to a safe URL BEFORE the leave/delete mutation fires.
@@ -69,7 +73,6 @@ export function WorkspaceTab() {
const cachedList =
qc.getQueryData<Workspace[]>(workspaceListOptions().queryKey) ?? [];
const remaining = cachedList.filter((w) => w.id !== workspace?.id);
- const next = remaining[0];
// Clear the workspace-context singleton BEFORE navigating and BEFORE
// the mutation fires. Three downstream consumers read it:
// 1. Realtime `workspace:deleted` handler's "current === deleted"
@@ -87,9 +90,7 @@ export function WorkspaceTab() {
// takes over immediately, or the new-workspace overlay takes over
// (which has no workspace context, so null is correct).
setCurrentWorkspace(null, null);
- navigation.push(
- next ? paths.workspace(next.slug).issues() : paths.newWorkspace(),
- );
+ navigation.push(resolvePostAuthDestination(remaining, hasOnboarded));
};
const [name, setName] = useState(workspace?.name ?? "");
diff --git a/packages/views/workspace/create-workspace-form.tsx b/packages/views/workspace/create-workspace-form.tsx
index 61d9e7ae8e..250ae65ccf 100644
--- a/packages/views/workspace/create-workspace-form.tsx
+++ b/packages/views/workspace/create-workspace-form.tsx
@@ -17,7 +17,7 @@ import {
} from "./slug";
export interface CreateWorkspaceFormProps {
- onSuccess: (workspace: Workspace) => void;
+ onSuccess: (workspace: Workspace) => void | Promise<void>;
}
export function CreateWorkspaceForm({ onSuccess }: CreateWorkspaceFormProps) {
diff --git a/packages/views/workspace/new-workspace-page.tsx b/packages/views/workspace/new-workspace-page.tsx
index d18ba1495c..e0f11b1ce7 100644
--- a/packages/views/workspace/new-workspace-page.tsx
+++ b/packages/views/workspace/new-workspace-page.tsx
@@ -4,6 +4,7 @@ import { ArrowLeft, LogOut } from "lucide-react";
import { Button } from "@multica/ui/components/ui/button";
import type { Workspace } from "@multica/core/types";
import { useLogout } from "../auth";
+import { DragStrip } from "../platform";
import { CreateWorkspaceForm } from "./create-workspace-form";
/**
@@ -29,12 +30,13 @@ export function NewWorkspacePage({
const logout = useLogout();
return (
- <div className="relative flex min-h-svh flex-col bg-background px-6 py-12">
+ <div className="relative flex min-h-svh flex-col bg-background">
+ <DragStrip />
{onBack && (
<Button
variant="ghost"
size="sm"
- className="absolute top-12 left-12 text-muted-foreground"
+ className="absolute top-16 left-12 text-muted-foreground"
onClick={onBack}
>
<ArrowLeft />
@@ -44,24 +46,28 @@ export function NewWorkspacePage({
<Button
variant="ghost"
size="sm"
- className="absolute top-12 right-12 text-muted-foreground hover:text-destructive"
+ className="absolute top-16 right-12 text-muted-foreground hover:text-destructive"
onClick={logout}
>
<LogOut />
Log out
</Button>
- <div className="flex flex-1 flex-col items-center justify-center">
+ <div className="flex flex-1 flex-col items-center justify-center px-6 pb-12">
<div className="flex w-full max-w-md flex-col items-center gap-6">
<div className="text-center">
<h1 className="text-3xl font-semibold tracking-tight">
Welcome to Multica
</h1>
- <p className="mt-2 text-muted-foreground">
- Create your workspace to get started.
+ <p className="mt-3 text-muted-foreground">
+ One workspace where you and your AI teammates work side by side —
+ taking issues, leaving comments, sharing the same context.
</p>
</div>
<CreateWorkspaceForm onSuccess={onSuccess} />
+ <p className="text-center text-xs text-muted-foreground">
+ You can invite teammates once your workspace is ready.
+ </p>
</div>
</div>
</div>
diff --git a/packages/views/workspace/no-access-page.tsx b/packages/views/workspace/no-access-page.tsx
index d698777a07..0afbd38036 100644
--- a/packages/views/workspace/no-access-page.tsx
+++ b/packages/views/workspace/no-access-page.tsx
@@ -4,6 +4,7 @@ import { Button } from "@multica/ui/components/ui/button";
import { paths } from "@multica/core/paths";
import { useNavigation } from "../navigation";
import { useLogout } from "../auth";
+import { DragStrip } from "../platform";
/**
* Rendered when the workspace slug in the URL does not resolve to a workspace
@@ -15,22 +16,25 @@ export function NoAccessPage() {
const nav = useNavigation();
const logout = useLogout();
return (
- <div className="flex min-h-svh flex-col items-center justify-center gap-6 px-6 text-center">
- <div className="space-y-2">
- <h1 className="text-2xl font-semibold tracking-tight">
- Workspace not available
- </h1>
- <p className="max-w-md text-muted-foreground">
- This workspace doesn't exist or you don't have access.
- </p>
- </div>
- <div className="flex flex-col gap-2 sm:flex-row">
- <Button onClick={() => nav.push(paths.root())}>
- Go to my workspaces
- </Button>
- <Button variant="outline" onClick={logout}>
- Sign in as a different user
- </Button>
+ <div className="flex min-h-svh flex-col">
+ <DragStrip />
+ <div className="flex flex-1 flex-col items-center justify-center gap-6 px-6 pb-12 text-center">
+ <div className="space-y-2">
+ <h1 className="text-2xl font-semibold tracking-tight">
+ Workspace not available
+ </h1>
+ <p className="max-w-md text-muted-foreground">
+ This workspace doesn't exist or you don't have access.
+ </p>
+ </div>
+ <div className="flex flex-col gap-2 sm:flex-row">
+ <Button onClick={() => nav.push(paths.root())}>
+ Go to my workspaces
+ </Button>
+ <Button variant="outline" onClick={logout}>
+ Sign in as a different user
+ </Button>
+ </div>
</div>
</div>
);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6a0f37fbca..eefa785a85 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -114,6 +114,9 @@ importers:
'@fontsource-variable/inter':
specifier: ^5.2.5
version: 5.2.8
+ '@fontsource-variable/source-serif-4':
+ specifier: ^5.2.9
+ version: 5.2.9
'@fontsource/geist-mono':
specifier: ^5.2.7
version: 5.2.7
@@ -1318,6 +1321,9 @@ packages:
'@fontsource-variable/[email protected]':
resolution: {integrity: sha512-kOfP2D+ykbcX/P3IFnokOhVRNoTozo5/JxhAIVYLpea/UBmCQ/YWPBfWIDuBImXX/15KH+eKh4xpEUyS2sQQGQ==}
+ '@fontsource-variable/[email protected]':
+ resolution: {integrity: sha512-PPcxjLFk/fS0WHg79pDM2YNvz61kC+oYZ5cWZZyCS0DHpJncmuYOuiZAsvj4tDxlWPBEvxxcRLQQNmSaRbPkqw==}
+
'@fontsource/[email protected]':
resolution: {integrity: sha512-xVPVFISJg/K0VVd+aQN0Y7X/sw9hUcJPyDWFJ5GpyU3bHELhoRsJkPSRSHXW32mOi0xZCUQDOaPj1sqIFJ1FGg==}
@@ -7663,6 +7669,8 @@ snapshots:
'@fontsource-variable/[email protected]': {}
+ '@fontsource-variable/[email protected]': {}
+
'@fontsource/[email protected]': {}
'@formatjs/[email protected]':
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 64687a8589..dc06a1ec3a 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -169,6 +169,11 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analytics
r.Get("/api/config", h.GetConfig)
r.Get("/api/me", h.GetMe)
r.Patch("/api/me", h.UpdateMe)
+ r.Patch("/api/me/onboarding", h.PatchOnboarding)
+ r.Post("/api/me/onboarding/complete", h.CompleteOnboarding)
+ r.Post("/api/me/onboarding/cloud-waitlist", h.JoinCloudWaitlist)
+ r.Post("/api/me/starter-content/import", h.ImportStarterContent)
+ r.Post("/api/me/starter-content/dismiss", h.DismissStarterContent)
r.Post("/api/cli-token", h.IssueCliToken)
r.Post("/api/upload-file", h.UploadFile)
diff --git a/server/internal/handler/auth.go b/server/internal/handler/auth.go
index 7c7787c6e5..4345b46fe7 100644
--- a/server/internal/handler/auth.go
+++ b/server/internal/handler/auth.go
@@ -37,22 +37,35 @@ var ErrSignupProhibited = SignupError{Message: "user registration is disabled on
var ErrEmailNotAllowed = SignupError{Message: "email address or domain not allowed on this instance"}
type UserResponse struct {
- ID string `json:"id"`
- Name string `json:"name"`
- Email string `json:"email"`
- AvatarURL *string `json:"avatar_url"`
- CreatedAt string `json:"created_at"`
- UpdatedAt string `json:"updated_at"`
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ AvatarURL *string `json:"avatar_url"`
+ OnboardedAt *string `json:"onboarded_at"`
+ OnboardingQuestionnaire json.RawMessage `json:"onboarding_questionnaire"`
+ StarterContentState *string `json:"starter_content_state"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
}
func userToResponse(u db.User) UserResponse {
+ // JSONB column is []byte with DEFAULT '{}', so it's never nil at the DB
+ // level. Defensive coalesce just in case a future ALTER makes the column
+ // nullable and some row comes back with no default applied.
+ q := u.OnboardingQuestionnaire
+ if len(q) == 0 {
+ q = []byte("{}")
+ }
return UserResponse{
- ID: uuidToString(u.ID),
- Name: u.Name,
- Email: u.Email,
- AvatarURL: textToPtr(u.AvatarUrl),
- CreatedAt: timestampToString(u.CreatedAt),
- UpdatedAt: timestampToString(u.UpdatedAt),
+ ID: uuidToString(u.ID),
+ Name: u.Name,
+ Email: u.Email,
+ AvatarURL: textToPtr(u.AvatarUrl),
+ OnboardedAt: timestampToPtr(u.OnboardedAt),
+ OnboardingQuestionnaire: json.RawMessage(q),
+ StarterContentState: textToPtr(u.StarterContentState),
+ CreatedAt: timestampToString(u.CreatedAt),
+ UpdatedAt: timestampToString(u.UpdatedAt),
}
}
diff --git a/server/internal/handler/onboarding.go b/server/internal/handler/onboarding.go
new file mode 100644
index 0000000000..c171647f11
--- /dev/null
+++ b/server/internal/handler/onboarding.go
@@ -0,0 +1,516 @@
+package handler
+
+import (
+ "encoding/json"
+ "log/slog"
+ "net/http"
+ "net/mail"
+ "strings"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/logger"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// Upper bound on free-text fields. `cloudWaitlistReasonMaxLen` is a
+// product cap ("we don't need an essay for a waitlist"); the body-size
+// cap further down is defense in depth against arbitrary storage
+// abuse via the JSON body.
+const (
+ cloudWaitlistReasonMaxLen = 500
+
+ // PatchOnboarding body is a tiny JSON with at most a 3-question
+ // questionnaire. 16 KiB is ~10x the realistic ceiling — it's the
+ // minimum that keeps the door open for future fields without
+ // letting a malicious user stuff the JSONB column.
+ patchOnboardingBodyLimit = 16 * 1024
+
+ // Import payload contains the full starter-content template. Each
+ // sub-issue's markdown description is ~2 KiB; with ~8 sub-issues,
+ // a welcome issue (~3 KiB), and a project description, 64 KiB is
+ // comfortably above realistic and still bounded.
+ importStarterContentBodyLimit = 64 * 1024
+)
+
+// CompleteOnboarding marks the authenticated user as having completed
+// onboarding. Idempotent: the underlying query uses COALESCE so the
+// original timestamp is preserved if called more than once.
+func (h *Handler) CompleteOnboarding(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ user, err := h.Queries.MarkUserOnboarded(r.Context(), parseUUID(userID))
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to mark onboarded")
+ return
+ }
+ writeJSON(w, http.StatusOK, userToResponse(user))
+}
+
+type patchOnboardingRequest struct {
+ Questionnaire *json.RawMessage `json:"questionnaire,omitempty"`
+}
+
+// PatchOnboarding persists the user's questionnaire answers. The
+// field is optional; an omitted questionnaire is preserved. Which
+// step the user is on is deliberately not persisted — every
+// onboarding entry starts at Welcome.
+func (h *Handler) PatchOnboarding(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ // Bound the body so the JSONB column can't be weaponized as bulk
+ // storage — otherwise every subsequent `/api/me` read would have
+ // to return the bloat.
+ r.Body = http.MaxBytesReader(w, r.Body, patchOnboardingBodyLimit)
+ var req patchOnboardingRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ params := db.PatchUserOnboardingParams{ID: parseUUID(userID)}
+ if req.Questionnaire != nil {
+ params.Questionnaire = []byte(*req.Questionnaire)
+ }
+ user, err := h.Queries.PatchUserOnboarding(r.Context(), params)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update onboarding")
+ return
+ }
+ writeJSON(w, http.StatusOK, userToResponse(user))
+}
+
+type joinCloudWaitlistRequest struct {
+ Email string `json:"email"`
+ Reason string `json:"reason"`
+}
+
+// JoinCloudWaitlist records a user's interest in cloud runtimes.
+// Pure side effect — does NOT complete onboarding. The user still
+// has to pick a real Step 3 path (CLI with a detected runtime) or
+// Skip to move on. Repeating the call overwrites email + reason.
+func (h *Handler) JoinCloudWaitlist(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ var req joinCloudWaitlistRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+
+ // RFC 5321 caps email at 254 chars; the column is VARCHAR(254) and
+ // the format check below rejects anything net/mail can't parse.
+ email := strings.ToLower(strings.TrimSpace(req.Email))
+ if email == "" {
+ writeError(w, http.StatusBadRequest, "email is required")
+ return
+ }
+ if len(email) > 254 {
+ writeError(w, http.StatusBadRequest, "email is too long")
+ return
+ }
+ if _, err := mail.ParseAddress(email); err != nil {
+ writeError(w, http.StatusBadRequest, "email is invalid")
+ return
+ }
+
+ reason := strings.TrimSpace(req.Reason)
+ if len(reason) > cloudWaitlistReasonMaxLen {
+ writeError(w, http.StatusBadRequest, "reason is too long")
+ return
+ }
+
+ reasonParam := pgtype.Text{}
+ if reason != "" {
+ reasonParam = pgtype.Text{String: reason, Valid: true}
+ }
+
+ user, err := h.Queries.JoinCloudWaitlist(r.Context(), db.JoinCloudWaitlistParams{
+ ID: parseUUID(userID),
+ CloudWaitlistEmail: pgtype.Text{String: email, Valid: true},
+ CloudWaitlistReason: reasonParam,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to join waitlist")
+ return
+ }
+
+ writeJSON(w, http.StatusOK, userToResponse(user))
+}
+
+// -----------------------------------------------------------------------------
+// Starter content (post-onboarding opt-in)
+// -----------------------------------------------------------------------------
+//
+// Users land in their workspace with starter_content_state=NULL and see
+// a one-time dialog offering to seed example content. Two terminal
+// transitions:
+//
+// ImportStarterContent NULL -> 'imported' (also creates project, welcome
+// issue if agent-based, sub-issues,
+// pins — all in one transaction)
+// DismissStarterContent NULL -> 'dismissed'
+//
+// Why state-first, then seeding inside the same transaction:
+// - starter_content_state is the "have we asked / done this" bit, so it
+// must be set exactly once per user
+// - if we set state AFTER creation, a mid-request crash leaves duplicates
+// on retry (the original "Not idempotent" bug)
+// - if we set state BEFORE creation, a mid-request crash leaves the user
+// with 'imported' + no content
+// - inside a transaction, both commit together or neither does — and the
+// starting state check (must be NULL) guarantees the claim is atomic
+//
+// Content generation lives in TypeScript (the markdown templates are large
+// and depend on the Q1–Q3 answers); the client POSTs the fully-rendered
+// payload here, and the server's job is to (1) gate on state, (2) do the
+// batch insert transactionally, (3) record the transition.
+
+type importIssueSpec struct {
+ Title string `json:"title"`
+ Description string `json:"description"`
+ Status string `json:"status"`
+ Priority string `json:"priority"`
+ // AssignToSelf: true for sub-issues (assigned to the current
+ // user as a member). Server uses `user_id` per the app-wide
+ // convention in AssigneePicker / resolveActor.
+ AssignToSelf bool `json:"assign_to_self"`
+}
+
+// welcomeIssueTemplate is a PRE-rendered welcome issue — title +
+// description + priority. There is no `agent_id` field on purpose:
+// the server picks the target agent itself from ListAgents inside
+// the transaction, so a stale or compromised client can't assign
+// the welcome issue to an arbitrary agent.
+type welcomeIssueTemplate struct {
+ Title string `json:"title"`
+ Description string `json:"description"`
+ // Priority optional; defaults to "high" when empty.
+ Priority string `json:"priority"`
+}
+
+type importStarterContentRequest struct {
+ WorkspaceID string `json:"workspace_id"`
+
+ Project struct {
+ Title string `json:"title"`
+ Description string `json:"description"`
+ Icon string `json:"icon"`
+ } `json:"project"`
+
+ // Welcome issue template — rendered regardless of branch. The
+ // server creates it only when at least one agent exists in the
+ // workspace; otherwise it's ignored.
+ WelcomeIssueTemplate welcomeIssueTemplate `json:"welcome_issue_template"`
+
+ // Both branches of sub-issues. The server picks which array to
+ // seed based on whether the workspace has any agents at the
+ // moment of the call — the client no longer decides. Sending
+ // both is ~15 KB extra payload, which stays well under the
+ // 64 KB MaxBytesReader cap above.
+ AgentGuidedSubIssues []importIssueSpec `json:"agent_guided_sub_issues"`
+ SelfServeSubIssues []importIssueSpec `json:"self_serve_sub_issues"`
+}
+
+type importStarterContentResponse struct {
+ User UserResponse `json:"user"`
+ ProjectID string `json:"project_id"`
+ WelcomeIssueID *string `json:"welcome_issue_id"`
+}
+
+// ImportStarterContent creates the Getting Started project, optional
+// welcome issue, sub-issues, and pins — all inside a single transaction
+// gated by the atomic NULL -> 'imported' state transition. Idempotent
+// at the state level: any second call returns 409 with the already-set
+// state, no duplicate content created.
+func (h *Handler) ImportStarterContent(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, importStarterContentBodyLimit)
+ var req importStarterContentRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if req.WorkspaceID == "" {
+ writeError(w, http.StatusBadRequest, "workspace_id is required")
+ return
+ }
+ if req.Project.Title == "" {
+ writeError(w, http.StatusBadRequest, "project.title is required")
+ return
+ }
+
+ // Start the transaction early — the state claim lives inside it so
+ // concurrent imports from another tab can't both pass the check.
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to begin transaction")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ // Claim step: user must be NULL (never asked) to proceed. A value
+ // of 'imported' / 'dismissed' / 'skipped_legacy' all short-circuit
+ // with 409 Conflict — the caller should close the dialog and
+ // refresh the user to pick up the already-final state.
+ user, err := qtx.GetUser(r.Context(), parseUUID(userID))
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load user")
+ return
+ }
+ if user.StarterContentState.Valid {
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": "starter content already decided",
+ "state": user.StarterContentState.String,
+ })
+ return
+ }
+
+ // Membership check: user must belong to the target workspace.
+ // `actorID` below is `parseUUID(userID)` — stored as `creator_id`
+ // and `assignee_id` for `type="member"` to match the app-wide
+ // convention (AssigneePicker + resolveActor). Storing `member.id`
+ // would cause `useActorName.getMemberName` to resolve to "Unknown"
+ // since members are looked up by `user_id`.
+ if _, err := qtx.GetMemberByUserAndWorkspace(r.Context(), db.GetMemberByUserAndWorkspaceParams{
+ UserID: parseUUID(userID),
+ WorkspaceID: parseUUID(req.WorkspaceID),
+ }); err != nil {
+ writeError(w, http.StatusForbidden, "not a member of this workspace")
+ return
+ }
+ actorID := parseUUID(userID)
+
+ // --- Branch decision (server-authoritative) ---
+ // Ask the DB — not the client — whether there's an agent in this
+ // workspace. `ListAgents` orders by created_at ASC, so "agents[0]"
+ // is deterministically the earliest-created agent. This replaces
+ // the old client-supplied `welcome_issue.agent_id` trust chain.
+ agents, err := qtx.ListAgents(r.Context(), parseUUID(req.WorkspaceID))
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list agents")
+ return
+ }
+ hasAgent := len(agents) > 0
+ var welcomeAgentID pgtype.UUID
+ if hasAgent {
+ welcomeAgentID = agents[0].ID
+ }
+ subSpecs := req.SelfServeSubIssues
+ if hasAgent {
+ subSpecs = req.AgentGuidedSubIssues
+ }
+
+ // --- Create project ---
+ project, err := qtx.CreateProject(r.Context(), db.CreateProjectParams{
+ WorkspaceID: parseUUID(req.WorkspaceID),
+ Title: req.Project.Title,
+ Description: strOrNullText(req.Project.Description),
+ Icon: strOrNullText(req.Project.Icon),
+ Status: "planned",
+ Priority: "none",
+ })
+ if err != nil {
+ slog.Warn("import starter content: create project failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to create project")
+ return
+ }
+
+ // --- Create welcome issue (only when an agent exists) ---
+ var welcomeIssueID *string
+ var welcomeIssueForEvent *db.Issue
+ if hasAgent && req.WelcomeIssueTemplate.Title != "" {
+ welcomeNumber, err := qtx.IncrementIssueCounter(r.Context(), parseUUID(req.WorkspaceID))
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to allocate issue number")
+ return
+ }
+ priority := req.WelcomeIssueTemplate.Priority
+ if priority == "" {
+ priority = "high"
+ }
+ welcome, err := qtx.CreateIssue(r.Context(), db.CreateIssueParams{
+ WorkspaceID: parseUUID(req.WorkspaceID),
+ Title: req.WelcomeIssueTemplate.Title,
+ Description: strOrNullText(req.WelcomeIssueTemplate.Description),
+ Status: "todo",
+ Priority: priority,
+ AssigneeType: pgtype.Text{String: "agent", Valid: true},
+ AssigneeID: welcomeAgentID,
+ CreatorType: "member",
+ CreatorID: actorID,
+ Number: welcomeNumber,
+ })
+ if err != nil {
+ slog.Warn("import starter content: create welcome issue failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to create welcome issue")
+ return
+ }
+ id := uuidToString(welcome.ID)
+ welcomeIssueID = &id
+ copy := welcome
+ welcomeIssueForEvent = &copy
+ }
+
+ // --- Create sub-issues (branch picked above) ---
+ subIssuesCreated := make([]db.Issue, 0, len(subSpecs))
+ for _, sub := range subSpecs {
+ if sub.Title == "" {
+ continue
+ }
+ number, err := qtx.IncrementIssueCounter(r.Context(), parseUUID(req.WorkspaceID))
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to allocate issue number")
+ return
+ }
+ var assigneeType pgtype.Text
+ var assigneeID pgtype.UUID
+ if sub.AssignToSelf {
+ assigneeType = pgtype.Text{String: "member", Valid: true}
+ assigneeID = actorID
+ }
+ status := sub.Status
+ if status == "" {
+ status = "backlog"
+ }
+ priority := sub.Priority
+ if priority == "" {
+ priority = "none"
+ }
+ issue, err := qtx.CreateIssue(r.Context(), db.CreateIssueParams{
+ WorkspaceID: parseUUID(req.WorkspaceID),
+ Title: sub.Title,
+ Description: strOrNullText(sub.Description),
+ Status: status,
+ Priority: priority,
+ AssigneeType: assigneeType,
+ AssigneeID: assigneeID,
+ CreatorType: "member",
+ CreatorID: actorID,
+ Number: number,
+ ProjectID: project.ID,
+ })
+ if err != nil {
+ slog.Warn("import starter content: create sub-issue failed", append(logger.RequestAttrs(r), "error", err, "title", sub.Title)...)
+ writeError(w, http.StatusInternalServerError, "failed to create sub-issues")
+ return
+ }
+ subIssuesCreated = append(subIssuesCreated, issue)
+ }
+
+ // --- Pin project (and welcome issue if present) ---
+ // Non-fatal: a pin failure shouldn't prevent the onboarding bundle
+ // from landing. We warn and move on.
+ pinnedProjectPos := float64(1)
+ if _, err := qtx.CreatePinnedItem(r.Context(), db.CreatePinnedItemParams{
+ WorkspaceID: parseUUID(req.WorkspaceID),
+ UserID: parseUUID(userID),
+ ItemType: "project",
+ ItemID: project.ID,
+ Position: pinnedProjectPos,
+ }); err != nil {
+ slog.Warn("import starter content: pin project failed", append(logger.RequestAttrs(r), "error", err)...)
+ }
+ if welcomeIssueForEvent != nil {
+ if _, err := qtx.CreatePinnedItem(r.Context(), db.CreatePinnedItemParams{
+ WorkspaceID: parseUUID(req.WorkspaceID),
+ UserID: parseUUID(userID),
+ ItemType: "issue",
+ ItemID: welcomeIssueForEvent.ID,
+ Position: pinnedProjectPos + 1,
+ }); err != nil {
+ slog.Warn("import starter content: pin welcome issue failed", append(logger.RequestAttrs(r), "error", err)...)
+ }
+ }
+
+ // --- Flip state ---
+ updatedUser, err := qtx.SetStarterContentState(r.Context(), db.SetStarterContentStateParams{
+ ID: parseUUID(userID),
+ StarterContentState: pgtype.Text{String: "imported", Valid: true},
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to record starter content state")
+ return
+ }
+
+ if err := tx.Commit(r.Context()); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to commit starter content")
+ return
+ }
+
+ // --- Post-commit: realtime events + agent task enqueue ---
+ // Realtime fan-out happens here (not inside the tx) because the DB
+ // commit must land first — otherwise subscribers could receive an
+ // event for state that's about to be rolled back.
+ projectResp := projectToResponse(project)
+ h.publish(protocol.EventProjectCreated, req.WorkspaceID, "member", userID, map[string]any{"project": projectResp})
+
+ workspacePrefix := h.getIssuePrefix(r.Context(), parseUUID(req.WorkspaceID))
+ if welcomeIssueForEvent != nil {
+ welcomeResp := issueToResponse(*welcomeIssueForEvent, workspacePrefix)
+ h.publish(protocol.EventIssueCreated, req.WorkspaceID, "member", userID, map[string]any{"issue": welcomeResp})
+ if h.shouldEnqueueAgentTask(r.Context(), *welcomeIssueForEvent) {
+ h.TaskService.EnqueueTaskForIssue(r.Context(), *welcomeIssueForEvent)
+ }
+ }
+ for _, sub := range subIssuesCreated {
+ subResp := issueToResponse(sub, workspacePrefix)
+ h.publish(protocol.EventIssueCreated, req.WorkspaceID, "member", userID, map[string]any{"issue": subResp})
+ }
+
+ writeJSON(w, http.StatusOK, importStarterContentResponse{
+ User: userToResponse(updatedUser),
+ ProjectID: uuidToString(project.ID),
+ WelcomeIssueID: welcomeIssueID,
+ })
+}
+
+// DismissStarterContent records the user's decision to skip starter
+// content. Like Import, this is a NULL -> terminal transition; a
+// second call returns 409 with the current state.
+func (h *Handler) DismissStarterContent(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ user, err := h.Queries.GetUser(r.Context(), parseUUID(userID))
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load user")
+ return
+ }
+ if user.StarterContentState.Valid {
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": "starter content already decided",
+ "state": user.StarterContentState.String,
+ })
+ return
+ }
+ updated, err := h.Queries.SetStarterContentState(r.Context(), db.SetStarterContentStateParams{
+ ID: parseUUID(userID),
+ StarterContentState: pgtype.Text{String: "dismissed", Valid: true},
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to record dismiss")
+ return
+ }
+ writeJSON(w, http.StatusOK, userToResponse(updated))
+}
+
+// strOrNullText converts an empty-meaning-absent string into a
+// nullable pgtype.Text. Empty -> SQL NULL; non-empty -> Valid.
+func strOrNullText(s string) pgtype.Text {
+ if s == "" {
+ return pgtype.Text{}
+ }
+ return pgtype.Text{String: s, Valid: true}
+}
diff --git a/server/internal/handler/onboarding_test.go b/server/internal/handler/onboarding_test.go
new file mode 100644
index 0000000000..7b18c80975
--- /dev/null
+++ b/server/internal/handler/onboarding_test.go
@@ -0,0 +1,191 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+// newWaitlistTestUser inserts a fresh user row, returns its id, and
+// registers a cleanup. Uses the test pool directly so we don't depend
+// on the handler-under-test for fixture setup.
+func newWaitlistTestUser(t *testing.T, email string) string {
+ t.Helper()
+ ctx := context.Background()
+
+ var userID string
+ if err := testPool.QueryRow(ctx,
+ `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`,
+ "Waitlist Test", email,
+ ).Scan(&userID); err != nil {
+ t.Fatalf("insert test user: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM "user" WHERE id = $1`, userID)
+ })
+ return userID
+}
+
+func newWaitlistRequest(userID string, body map[string]string) *http.Request {
+ var buf bytes.Buffer
+ if body != nil {
+ json.NewEncoder(&buf).Encode(body)
+ }
+ req := httptest.NewRequest(
+ "POST", "/api/me/onboarding/cloud-waitlist", &buf,
+ )
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-User-ID", userID)
+ return req
+}
+
+func TestJoinCloudWaitlistRecordsEmailAndReason(t *testing.T) {
+ userID := newWaitlistTestUser(t, "[email protected]")
+
+ w := httptest.NewRecorder()
+ req := newWaitlistRequest(userID, map[string]string{
+ "email": "[email protected]",
+ "reason": "evaluating for our team",
+ })
+ testHandler.JoinCloudWaitlist(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var (
+ waitlistEmail *string
+ waitlistReason *string
+ onboardedAt *time.Time
+ )
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT cloud_waitlist_email, cloud_waitlist_reason, onboarded_at
+ FROM "user" WHERE id = $1
+ `, userID).Scan(&waitlistEmail, &waitlistReason, &onboardedAt); err != nil {
+ t.Fatalf("lookup user: %v", err)
+ }
+
+ if waitlistEmail == nil || *waitlistEmail != "[email protected]" {
+ t.Fatalf("email not normalized/stored: %v", waitlistEmail)
+ }
+ if waitlistReason == nil || *waitlistReason != "evaluating for our team" {
+ t.Fatalf("reason not stored: %v", waitlistReason)
+ }
+ // Waitlist is a pure side effect — onboarding is NOT marked
+ // complete here. The user still has to pick a real Step 3
+ // path (CLI / Skip) before onboarded_at gets set.
+ if onboardedAt != nil {
+ t.Fatalf("onboarded_at should stay NULL, got %v", *onboardedAt)
+ }
+}
+
+func TestJoinCloudWaitlistAllowsEmptyReason(t *testing.T) {
+ userID := newWaitlistTestUser(t, "[email protected]")
+
+ w := httptest.NewRecorder()
+ req := newWaitlistRequest(userID, map[string]string{
+ "email": "[email protected]",
+ })
+ testHandler.JoinCloudWaitlist(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var waitlistReason *string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT cloud_waitlist_reason FROM "user" WHERE id = $1`, userID,
+ ).Scan(&waitlistReason); err != nil {
+ t.Fatalf("lookup user: %v", err)
+ }
+ if waitlistReason != nil {
+ t.Fatalf("expected NULL reason, got %q", *waitlistReason)
+ }
+}
+
+func TestJoinCloudWaitlistMissingEmailReturns400(t *testing.T) {
+ userID := newWaitlistTestUser(t, "[email protected]")
+
+ cases := []map[string]string{
+ {}, // empty body
+ {"email": ""}, // blank
+ {"email": " "}, // whitespace only
+ {"reason": "no email here"},
+ }
+
+ for i, body := range cases {
+ w := httptest.NewRecorder()
+ req := newWaitlistRequest(userID, body)
+ testHandler.JoinCloudWaitlist(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("case %d: expected 400, got %d: %s", i, w.Code, w.Body.String())
+ }
+ }
+}
+
+func TestJoinCloudWaitlistRejectsOverlongReason(t *testing.T) {
+ userID := newWaitlistTestUser(t, "[email protected]")
+
+ w := httptest.NewRecorder()
+ req := newWaitlistRequest(userID, map[string]string{
+ "email": "[email protected]",
+ "reason": strings.Repeat("x", cloudWaitlistReasonMaxLen+1),
+ })
+ testHandler.JoinCloudWaitlist(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 for overlong reason, got %d", w.Code)
+ }
+}
+
+func TestJoinCloudWaitlistSecondCallOverwrites(t *testing.T) {
+ userID := newWaitlistTestUser(t, "[email protected]")
+
+ // First submission.
+ w := httptest.NewRecorder()
+ req := newWaitlistRequest(userID, map[string]string{
+ "email": "[email protected]",
+ "reason": "first",
+ })
+ testHandler.JoinCloudWaitlist(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("first call: expected 200, got %d", w.Code)
+ }
+
+ // Second submission with different values.
+ w = httptest.NewRecorder()
+ req = newWaitlistRequest(userID, map[string]string{
+ "email": "[email protected]",
+ "reason": "changed my mind",
+ })
+ testHandler.JoinCloudWaitlist(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("second call: expected 200, got %d", w.Code)
+ }
+
+ var (
+ waitlistEmail string
+ waitlistReason string
+ onboardedAt *time.Time
+ )
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT cloud_waitlist_email, cloud_waitlist_reason, onboarded_at
+ FROM "user" WHERE id = $1
+ `, userID).Scan(&waitlistEmail, &waitlistReason, &onboardedAt); err != nil {
+ t.Fatalf("lookup user: %v", err)
+ }
+
+ if waitlistEmail != "[email protected]" {
+ t.Fatalf("second email should overwrite; got %q", waitlistEmail)
+ }
+ if waitlistReason != "changed my mind" {
+ t.Fatalf("second reason should overwrite; got %q", waitlistReason)
+ }
+ // onboarded_at is never touched by the waitlist path — stays NULL
+ // across any number of submissions.
+ if onboardedAt != nil {
+ t.Fatalf("onboarded_at should stay NULL, got %v", *onboardedAt)
+ }
+}
diff --git a/server/migrations/050_add_onboarded_at_to_users.down.sql b/server/migrations/050_add_onboarded_at_to_users.down.sql
new file mode 100644
index 0000000000..db75486a2c
--- /dev/null
+++ b/server/migrations/050_add_onboarded_at_to_users.down.sql
@@ -0,0 +1 @@
+ALTER TABLE "user" DROP COLUMN IF EXISTS onboarded_at;
diff --git a/server/migrations/050_add_onboarded_at_to_users.up.sql b/server/migrations/050_add_onboarded_at_to_users.up.sql
new file mode 100644
index 0000000000..d5128eaffd
--- /dev/null
+++ b/server/migrations/050_add_onboarded_at_to_users.up.sql
@@ -0,0 +1,9 @@
+ALTER TABLE "user" ADD COLUMN onboarded_at TIMESTAMPTZ;
+
+-- Grandfather existing users. Treat any row that already exists at the
+-- moment this column lands as already-onboarded so the deploy doesn't
+-- wall them off behind a flow they never asked for. `created_at` (not
+-- NOW()) keeps analytics honest — "signup → onboarded interval" reads
+-- as 0 for pre-launch users, which under grandfathering semantics is
+-- accurate ("they onboarded implicitly at signup").
+UPDATE "user" SET onboarded_at = created_at;
diff --git a/server/migrations/051_add_onboarding_state_to_users.down.sql b/server/migrations/051_add_onboarding_state_to_users.down.sql
new file mode 100644
index 0000000000..5fd10a1489
--- /dev/null
+++ b/server/migrations/051_add_onboarding_state_to_users.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE "user"
+ DROP COLUMN IF EXISTS onboarding_questionnaire;
diff --git a/server/migrations/051_add_onboarding_state_to_users.up.sql b/server/migrations/051_add_onboarding_state_to_users.up.sql
new file mode 100644
index 0000000000..afef11a6da
--- /dev/null
+++ b/server/migrations/051_add_onboarding_state_to_users.up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE "user"
+ ADD COLUMN onboarding_questionnaire JSONB NOT NULL DEFAULT '{}'::jsonb;
diff --git a/server/migrations/052_add_cloud_waitlist_to_users.down.sql b/server/migrations/052_add_cloud_waitlist_to_users.down.sql
new file mode 100644
index 0000000000..8d9994e799
--- /dev/null
+++ b/server/migrations/052_add_cloud_waitlist_to_users.down.sql
@@ -0,0 +1,3 @@
+ALTER TABLE "user"
+ DROP COLUMN IF EXISTS cloud_waitlist_reason,
+ DROP COLUMN IF EXISTS cloud_waitlist_email;
diff --git a/server/migrations/052_add_cloud_waitlist_to_users.up.sql b/server/migrations/052_add_cloud_waitlist_to_users.up.sql
new file mode 100644
index 0000000000..0e240f4c95
--- /dev/null
+++ b/server/migrations/052_add_cloud_waitlist_to_users.up.sql
@@ -0,0 +1,5 @@
+-- RFC 5321 caps email addresses at 254 chars. Bounded TEXT prevents
+-- the column being abused as arbitrary storage.
+ALTER TABLE "user"
+ ADD COLUMN cloud_waitlist_email VARCHAR(254),
+ ADD COLUMN cloud_waitlist_reason TEXT;
diff --git a/server/migrations/053_drop_orphan_onboarding_current_step.down.sql b/server/migrations/053_drop_orphan_onboarding_current_step.down.sql
new file mode 100644
index 0000000000..581a35e54c
--- /dev/null
+++ b/server/migrations/053_drop_orphan_onboarding_current_step.down.sql
@@ -0,0 +1,3 @@
+-- Irreversible cleanup: the column was never a shipped feature, so
+-- restoring it would only re-create a dead, never-read column.
+-- Down is intentionally a no-op.
diff --git a/server/migrations/053_drop_orphan_onboarding_current_step.up.sql b/server/migrations/053_drop_orphan_onboarding_current_step.up.sql
new file mode 100644
index 0000000000..ededdb7338
--- /dev/null
+++ b/server/migrations/053_drop_orphan_onboarding_current_step.up.sql
@@ -0,0 +1,8 @@
+-- An earlier iteration of migration 051 added `onboarding_current_step`
+-- and then later the same PR removed it (the column was never actually
+-- consumed by the shipping code). Any environment that pulled the
+-- interim revision and ran `migrate-up` has a dead column; any
+-- environment that only sees the final 051 never will. This migration
+-- collapses both into the same final schema. IF EXISTS makes it a
+-- no-op on fresh environments.
+ALTER TABLE "user" DROP COLUMN IF EXISTS onboarding_current_step;
diff --git a/server/migrations/054_add_starter_content_state_to_users.down.sql b/server/migrations/054_add_starter_content_state_to_users.down.sql
new file mode 100644
index 0000000000..5736109ffd
--- /dev/null
+++ b/server/migrations/054_add_starter_content_state_to_users.down.sql
@@ -0,0 +1 @@
+ALTER TABLE "user" DROP COLUMN IF EXISTS starter_content_state;
diff --git a/server/migrations/054_add_starter_content_state_to_users.up.sql b/server/migrations/054_add_starter_content_state_to_users.up.sql
new file mode 100644
index 0000000000..7e9b0d74f8
--- /dev/null
+++ b/server/migrations/054_add_starter_content_state_to_users.up.sql
@@ -0,0 +1,17 @@
+-- Post-onboarding starter content opt-in. State values:
+-- NULL → we haven't asked the user yet (new user just after
+-- onboarding). The workspace issues page shows the
+-- StarterContentPrompt dialog until they decide.
+-- 'imported' → user chose to import; seeding ran; never ask again.
+-- 'dismissed' → user declined; never ask again.
+-- 'skipped_legacy' → backfilled for pre-feature users so they aren't
+-- prompted when they next sign in.
+ALTER TABLE "user" ADD COLUMN starter_content_state TEXT;
+
+-- Anyone who already finished onboarding before this feature existed
+-- should NOT see the prompt — their workspace has already settled into
+-- whatever state they wanted.
+UPDATE "user"
+ SET starter_content_state = 'skipped_legacy'
+ WHERE onboarded_at IS NOT NULL
+ AND starter_content_state IS NULL;
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index f8eb8a9577..cc04858cd3 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -386,12 +386,17 @@ type TaskUsage struct {
}
type User struct {
- ID pgtype.UUID `json:"id"`
- Name string `json:"name"`
- Email string `json:"email"`
- AvatarUrl pgtype.Text `json:"avatar_url"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ ID pgtype.UUID `json:"id"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ AvatarUrl pgtype.Text `json:"avatar_url"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ OnboardedAt pgtype.Timestamptz `json:"onboarded_at"`
+ OnboardingQuestionnaire []byte `json:"onboarding_questionnaire"`
+ CloudWaitlistEmail pgtype.Text `json:"cloud_waitlist_email"`
+ CloudWaitlistReason pgtype.Text `json:"cloud_waitlist_reason"`
+ StarterContentState pgtype.Text `json:"starter_content_state"`
}
type VerificationCode struct {
diff --git a/server/pkg/db/generated/user.sql.go b/server/pkg/db/generated/user.sql.go
index ca0c5ad9c6..ad1122b150 100644
--- a/server/pkg/db/generated/user.sql.go
+++ b/server/pkg/db/generated/user.sql.go
@@ -14,7 +14,7 @@ import (
const createUser = `-- name: CreateUser :one
INSERT INTO "user" (name, email, avatar_url)
VALUES ($1, $2, $3)
-RETURNING id, name, email, avatar_url, created_at, updated_at
+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state
`
type CreateUserParams struct {
@@ -33,12 +33,17 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, e
&i.AvatarUrl,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.OnboardedAt,
+ &i.OnboardingQuestionnaire,
+ &i.CloudWaitlistEmail,
+ &i.CloudWaitlistReason,
+ &i.StarterContentState,
)
return i, err
}
const getUser = `-- name: GetUser :one
-SELECT id, name, email, avatar_url, created_at, updated_at FROM "user"
+SELECT id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state FROM "user"
WHERE id = $1
`
@@ -52,12 +57,17 @@ func (q *Queries) GetUser(ctx context.Context, id pgtype.UUID) (User, error) {
&i.AvatarUrl,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.OnboardedAt,
+ &i.OnboardingQuestionnaire,
+ &i.CloudWaitlistEmail,
+ &i.CloudWaitlistReason,
+ &i.StarterContentState,
)
return i, err
}
const getUserByEmail = `-- name: GetUserByEmail :one
-SELECT id, name, email, avatar_url, created_at, updated_at FROM "user"
+SELECT id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state FROM "user"
WHERE email = $1
`
@@ -71,6 +81,144 @@ func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error
&i.AvatarUrl,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.OnboardedAt,
+ &i.OnboardingQuestionnaire,
+ &i.CloudWaitlistEmail,
+ &i.CloudWaitlistReason,
+ &i.StarterContentState,
+ )
+ return i, err
+}
+
+const joinCloudWaitlist = `-- name: JoinCloudWaitlist :one
+UPDATE "user" SET
+ cloud_waitlist_email = $2,
+ cloud_waitlist_reason = $3,
+ updated_at = now()
+WHERE id = $1
+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state
+`
+
+type JoinCloudWaitlistParams struct {
+ ID pgtype.UUID `json:"id"`
+ CloudWaitlistEmail pgtype.Text `json:"cloud_waitlist_email"`
+ CloudWaitlistReason pgtype.Text `json:"cloud_waitlist_reason"`
+}
+
+// Records interest in cloud runtimes. Does NOT mark onboarding
+// complete — the user still has to pick a real path (CLI / Skip)
+// in Step 3. Repeating the call overwrites email + reason.
+func (q *Queries) JoinCloudWaitlist(ctx context.Context, arg JoinCloudWaitlistParams) (User, error) {
+ row := q.db.QueryRow(ctx, joinCloudWaitlist, arg.ID, arg.CloudWaitlistEmail, arg.CloudWaitlistReason)
+ var i User
+ err := row.Scan(
+ &i.ID,
+ &i.Name,
+ &i.Email,
+ &i.AvatarUrl,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.OnboardedAt,
+ &i.OnboardingQuestionnaire,
+ &i.CloudWaitlistEmail,
+ &i.CloudWaitlistReason,
+ &i.StarterContentState,
+ )
+ return i, err
+}
+
+const markUserOnboarded = `-- name: MarkUserOnboarded :one
+UPDATE "user" SET
+ onboarded_at = COALESCE(onboarded_at, now()),
+ updated_at = now()
+WHERE id = $1
+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state
+`
+
+func (q *Queries) MarkUserOnboarded(ctx context.Context, id pgtype.UUID) (User, error) {
+ row := q.db.QueryRow(ctx, markUserOnboarded, id)
+ var i User
+ err := row.Scan(
+ &i.ID,
+ &i.Name,
+ &i.Email,
+ &i.AvatarUrl,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.OnboardedAt,
+ &i.OnboardingQuestionnaire,
+ &i.CloudWaitlistEmail,
+ &i.CloudWaitlistReason,
+ &i.StarterContentState,
+ )
+ return i, err
+}
+
+const patchUserOnboarding = `-- name: PatchUserOnboarding :one
+UPDATE "user" SET
+ onboarding_questionnaire = COALESCE($1, onboarding_questionnaire),
+ updated_at = now()
+WHERE id = $2
+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state
+`
+
+type PatchUserOnboardingParams struct {
+ Questionnaire []byte `json:"questionnaire"`
+ ID pgtype.UUID `json:"id"`
+}
+
+func (q *Queries) PatchUserOnboarding(ctx context.Context, arg PatchUserOnboardingParams) (User, error) {
+ row := q.db.QueryRow(ctx, patchUserOnboarding, arg.Questionnaire, arg.ID)
+ var i User
+ err := row.Scan(
+ &i.ID,
+ &i.Name,
+ &i.Email,
+ &i.AvatarUrl,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.OnboardedAt,
+ &i.OnboardingQuestionnaire,
+ &i.CloudWaitlistEmail,
+ &i.CloudWaitlistReason,
+ &i.StarterContentState,
+ )
+ return i, err
+}
+
+const setStarterContentState = `-- name: SetStarterContentState :one
+UPDATE "user" SET
+ starter_content_state = $2,
+ updated_at = now()
+WHERE id = $1
+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state
+`
+
+type SetStarterContentStateParams struct {
+ ID pgtype.UUID `json:"id"`
+ StarterContentState pgtype.Text `json:"starter_content_state"`
+}
+
+// Atomically transition starter_content_state. The handler is
+// responsible for checking the current value first (to decide between
+// "transition NULL -> imported and run the seeding" vs "already
+// decided, short-circuit"). Using COALESCE here would swallow the
+// transition, so this is a straight assignment.
+func (q *Queries) SetStarterContentState(ctx context.Context, arg SetStarterContentStateParams) (User, error) {
+ row := q.db.QueryRow(ctx, setStarterContentState, arg.ID, arg.StarterContentState)
+ var i User
+ err := row.Scan(
+ &i.ID,
+ &i.Name,
+ &i.Email,
+ &i.AvatarUrl,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.OnboardedAt,
+ &i.OnboardingQuestionnaire,
+ &i.CloudWaitlistEmail,
+ &i.CloudWaitlistReason,
+ &i.StarterContentState,
)
return i, err
}
@@ -81,7 +229,7 @@ UPDATE "user" SET
avatar_url = COALESCE($3, avatar_url),
updated_at = now()
WHERE id = $1
-RETURNING id, name, email, avatar_url, created_at, updated_at
+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state
`
type UpdateUserParams struct {
@@ -100,6 +248,11 @@ func (q *Queries) UpdateUser(ctx context.Context, arg UpdateUserParams) (User, e
&i.AvatarUrl,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.OnboardedAt,
+ &i.OnboardingQuestionnaire,
+ &i.CloudWaitlistEmail,
+ &i.CloudWaitlistReason,
+ &i.StarterContentState,
)
return i, err
}
diff --git a/server/pkg/db/queries/user.sql b/server/pkg/db/queries/user.sql
index 8909a3885a..b6e6016cce 100644
--- a/server/pkg/db/queries/user.sql
+++ b/server/pkg/db/queries/user.sql
@@ -18,3 +18,40 @@ UPDATE "user" SET
updated_at = now()
WHERE id = $1
RETURNING *;
+
+-- name: MarkUserOnboarded :one
+UPDATE "user" SET
+ onboarded_at = COALESCE(onboarded_at, now()),
+ updated_at = now()
+WHERE id = $1
+RETURNING *;
+
+-- name: PatchUserOnboarding :one
+UPDATE "user" SET
+ onboarding_questionnaire = COALESCE(sqlc.narg('questionnaire'), onboarding_questionnaire),
+ updated_at = now()
+WHERE id = sqlc.arg('id')
+RETURNING *;
+
+-- name: JoinCloudWaitlist :one
+-- Records interest in cloud runtimes. Does NOT mark onboarding
+-- complete — the user still has to pick a real path (CLI / Skip)
+-- in Step 3. Repeating the call overwrites email + reason.
+UPDATE "user" SET
+ cloud_waitlist_email = $2,
+ cloud_waitlist_reason = $3,
+ updated_at = now()
+WHERE id = $1
+RETURNING *;
+
+-- name: SetStarterContentState :one
+-- Atomically transition starter_content_state. The handler is
+-- responsible for checking the current value first (to decide between
+-- "transition NULL -> imported and run the seeding" vs "already
+-- decided, short-circuit"). Using COALESCE here would swallow the
+-- transition, so this is a straight assignment.
+UPDATE "user" SET
+ starter_content_state = $2,
+ updated_at = now()
+WHERE id = $1
+RETURNING *;