Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(onboarding): merge About-you step, collect source after agents deliver value (#5786)
Jiayuan Zhanga61a8ecfed9a
diff --git a/e2e/onboarding-smoke.spec.ts b/e2e/onboarding-smoke.spec.tsnew file mode 100644index 0000000000..3e3c52cfe5--- /dev/null+++ b/e2e/onboarding-smoke.spec.ts@@ -0,0 +1,93 @@+import { test, expect } from "@playwright/test";+import { TestApiClient } from "./fixtures";+import { waitForPageText } from "./helpers";++// Smoke test for the onboarding flow: welcome → About you (role ++// use case on ONE screen) → workspace → runtime. The source question+// is intentionally absent — it moved to the workspace source-backfill+// prompt (MUL-5159). Captures screenshots for review. Uses a unique+// email per run so the user is always a fresh, un-onboarded user+// landing on /onboarding.++const EMAIL = `onboarding-v3-${Date.now()}@localhost`;+const SHOTS_DIR = "/tmp/onboarding-v3-shots";++test.use({ viewport: { width: 1440, height: 900 } });++test("onboarding — welcome → about you (answer path)", async ({ page }) => {+ const api = new TestApiClient();+ await api.login(EMAIL, "OBv3 Tester");+ const token = api.getToken();++ await page.addInitScript((t) => {+ localStorage.setItem("multica_token", t);+ }, token);+ await page.goto("/onboarding", { waitUntil: "domcontentloaded" });+ await waitForPageText(page, "Continue on web");++ // 1. Welcome screen+ await expect(page.getByRole("button", { name: "Continue on web" })).toBeVisible({ timeout: 15000 });+ await page.screenshot({ path: `${SHOTS_DIR}/01-welcome.png`, fullPage: false });++ // Click Continue on web to advance to About you+ await page.getByRole("button", { name: "Continue on web" }).click();++ // 2. About you step — both questions live on this one screen and the+ // source question must NOT exist anywhere in the flow.+ await expect(page.getByText("Tell us a bit about you.")).toBeVisible({ timeout: 10000 });+ await expect(page.getByText("Which best describes you?")).toBeVisible();+ await expect(page.getByText("What do you want to use Multica for?")).toBeVisible();+ await expect(page.getByText(/Step 1 of 3/)).toBeVisible();+ await expect(page.getByText("How did you hear about Multica?")).toHaveCount(0);+ await page.waitForTimeout(500);+ await page.screenshot({ path: `${SHOTS_DIR}/02-about-you.png` });++ // Answer both groups, then Continue → workspace step.+ await page.getByRole("radio", { name: /Engineer \/ developer/i }).click();+ await page.getByRole("checkbox", { name: /Ship code with AI agents/i }).click();+ await page.getByRole("button", { name: "Continue" }).click();++ // 3. Workspace step+ await expect(page.getByRole("heading", { name: /Name your workspace/i })).toBeVisible({ timeout: 10000 });+ await expect(page.getByText(/Step 2 of 3/)).toBeVisible();+ await page.screenshot({ path: `${SHOTS_DIR}/03-workspace.png` });+});++test("onboarding — one skip clears the whole questionnaire step", async ({ page }) => {+ const api = new TestApiClient();+ await api.login(`skip-${Date.now()}@localhost`, "Skipper");+ const token = api.getToken();++ await page.addInitScript((t) => localStorage.setItem("multica_token", t), token);+ await page.goto("/onboarding", { waitUntil: "domcontentloaded" });+ await waitForPageText(page, "Continue on web");++ await page.getByRole("button", { name: "Continue on web" }).click();+ await expect(page.getByText("Tell us a bit about you.")).toBeVisible({ timeout: 10000 });++ // A single Skip covers role + use case — next stop is workspace.+ await page.getByRole("button", { name: "Skip" }).click();+ await expect(page.getByRole("heading", { name: /Name your workspace/i })).toBeVisible({ timeout: 10000 });+ await page.screenshot({ path: `${SHOTS_DIR}/04-after-skip.png` });+});++test("onboarding — zh-Hans renders Chinese labels", async ({ page, context }) => {+ await context.addCookies([+ { name: "multica-locale", value: "zh-Hans", url: "http://localhost:13442" },+ ]);+ const api = new TestApiClient();+ await api.login(`zh-${Date.now()}@localhost`, "中文用户");+ const token = api.getToken();++ await page.addInitScript((t) => localStorage.setItem("multica_token", t), token);+ await page.goto("/onboarding", { waitUntil: "domcontentloaded" });+ await waitForPageText(page, "在 web 端继续");++ await page.getByRole("button").first().click().catch(() => {});++ // About-you screen — Chinese headline + both sub-questions.+ await expect(page.getByText("简单介绍一下你自己。")).toBeVisible({ timeout: 10000 });+ await expect(page.getByText("你是什么角色?")).toBeVisible();+ await page.waitForTimeout(500);+ await page.screenshot({ path: `${SHOTS_DIR}/05-about-you-zh.png` });+});diff --git a/e2e/onboarding-v2-smoke.spec.ts b/e2e/onboarding-v2-smoke.spec.tsdeleted file mode 100644index 6253d82eff..0000000000--- a/e2e/onboarding-v2-smoke.spec.ts+++ /dev/null@@ -1,109 +0,0 @@-import { test, expect } from "@playwright/test";-import { TestApiClient } from "./fixtures";-import { waitForPageText } from "./helpers";--// Smoke test for Onboarding V2: verifies the new per-question flow-// renders and captures screenshots for review. Uses a unique email-// per run so the user is always a fresh, un-onboarded user landing-// on /onboarding.--const EMAIL = `onboarding-v2-${Date.now()}@localhost`;-const SHOTS_DIR = "/tmp/onboarding-v2-shots";--test.use({ viewport: { width: 1440, height: 900 } });--test("onboarding v2 — welcome → source → role → use_case (skip path)", async ({ page }) => {- const api = new TestApiClient();- await api.login(EMAIL, "OBv2 Tester");- const token = api.getToken();-- await page.addInitScript((t) => {- localStorage.setItem("multica_token", t);- }, token);- await page.goto("/onboarding", { waitUntil: "domcontentloaded" });- await waitForPageText(page, "Continue on web");-- // 1. Welcome screen- await expect(page.getByRole("button", { name: "Continue on web" })).toBeVisible({ timeout: 15000 });- await page.screenshot({ path: `${SHOTS_DIR}/01-welcome.png`, fullPage: false });-- // Click Start exploring to advance to Source- await page.getByRole("button", { name: "Continue on web" }).click();-- // 2. Source step- await expect(page.getByText("How did you hear about Multica?")).toBeVisible({ timeout: 10000 });- await expect(page.getByText(/Step 1 of \d+/)).toBeVisible();- await page.waitForTimeout(500);- await page.screenshot({ path: `${SHOTS_DIR}/02-source.png` });-- // Pick Friends/colleagues then click Continue to advance.- await page.getByRole("radio", { name: /Friends or colleagues/i }).click();- await page.getByRole("button", { name: "Continue" }).click();-- // 3. Role step- await expect(page.getByText("Which best describes you?")).toBeVisible({ timeout: 10000 });- await expect(page.getByText(/Step 2 of \d+/)).toBeVisible();- await page.waitForTimeout(500);- await page.screenshot({ path: `${SHOTS_DIR}/03-role.png` });-- // Skip role- await page.getByRole("button", { name: "Skip" }).click();-- // 4. Use case step- await expect(page.getByText("What do you want to use Multica for?")).toBeVisible({ timeout: 10000 });- await expect(page.getByText(/Step 3 of \d+/)).toBeVisible();- await page.waitForTimeout(500);- await page.screenshot({ path: `${SHOTS_DIR}/04-use-case.png` });-- // Pick ship_code then Continue → workspace step.- await page.getByRole("checkbox", { name: /Ship code with AI agents/i }).click();- await page.getByRole("button", { name: "Continue" }).click();-- // 5. Workspace step (legacy)- await expect(page.getByRole("heading", { name: /Name your workspace/i })).toBeVisible({ timeout: 10000 });- await page.screenshot({ path: `${SHOTS_DIR}/05-workspace.png` });-});--test("onboarding v2 — rage-skip all 3 questions", async ({ page }) => {- const api = new TestApiClient();- await api.login(`rage-skip-${Date.now()}@localhost`, "Rage Skipper");- const token = api.getToken();-- await page.addInitScript((t) => localStorage.setItem("multica_token", t), token);- await page.goto("/onboarding", { waitUntil: "domcontentloaded" });- await waitForPageText(page, "Continue on web");-- await page.getByRole("button", { name: "Continue on web" }).click();- await expect(page.getByText("How did you hear about Multica?")).toBeVisible({ timeout: 10000 });-- // Skip × 3- await page.getByRole("button", { name: "Skip" }).click();- await expect(page.getByText("Which best describes you?")).toBeVisible({ timeout: 10000 });- await page.getByRole("button", { name: "Skip" }).click();- await expect(page.getByText("What do you want to use Multica for?")).toBeVisible({ timeout: 10000 });- await page.getByRole("button", { name: "Skip" }).click();-- // Lands on workspace step- await expect(page.getByRole("heading", { name: /Name your workspace/i })).toBeVisible({ timeout: 10000 });- await page.screenshot({ path: `${SHOTS_DIR}/06-after-rage-skip.png` });-});--test("onboarding v2 — zh-Hans renders Chinese labels", async ({ page, context }) => {- await context.addCookies([- { name: "multica-locale", value: "zh-Hans", url: "http://localhost:13442" },- ]);- const api = new TestApiClient();- await api.login(`zh-${Date.now()}@localhost`, "中文用户");- const token = api.getToken();-- await page.addInitScript((t) => localStorage.setItem("multica_token", t), token);- await page.goto("/onboarding", { waitUntil: "domcontentloaded" });- await waitForPageText(page, "在 web 端继续");-- await page.getByRole("button").first().click().catch(() => {});-- // Source screen — Chinese question- await expect(page.getByText("你是从哪里了解到 Multica 的?")).toBeVisible({ timeout: 10000 });- await page.waitForTimeout(500);- await page.screenshot({ path: `${SHOTS_DIR}/07-source-zh.png` });-});diff --git a/packages/core/onboarding/index.ts b/packages/core/onboarding/index.tsindex 5ad16e4da3..f1e2a82d1b 100644--- a/packages/core/onboarding/index.ts+++ b/packages/core/onboarding/index.ts@@ -15,7 +15,9 @@ export { ONBOARDING_STEP_ORDER } from "./step-order";export {needsSourceBackfill,SOURCE_BACKFILL_MAX_DISMISSALS,+ SOURCE_BACKFILL_MIN_AGENT_DONE_ISSUES,} from "./needs-backfill";+export { agentCompletedIssueCountOptions } from "./queries";export {useWelcomeStore,type WelcomeSignal,diff --git a/packages/core/onboarding/needs-backfill.ts b/packages/core/onboarding/needs-backfill.tsindex 4274415372..718cec3ba3 100644--- a/packages/core/onboarding/needs-backfill.ts+++ b/packages/core/onboarding/needs-backfill.ts@@ -13,6 +13,23 @@ import type { QuestionnaireAnswers } from "./types";*/export const SOURCE_BACKFILL_MAX_DISMISSALS = 3;+/**+ * Minimum number of issues completed by an AI assignee (agent or+ * squad) in the current workspace before the source prompt may open.+ *+ * Source is not asked during onboarding at all — attribution is a+ * zero-payoff question for the user, so we wait until Multica has+ * demonstrably delivered value (agents finished real work) before+ * spending goodwill on it. Answer rates for "how did you hear about+ * us" prompts are also materially better after an activation moment+ * than at signup. 3 ≈ one Helper starter-task batch, so an engaged+ * new user typically crosses it within the first session.+ *+ * The count itself comes from `agentCompletedIssueCountOptions` in+ * `./queries.ts`; the modal combines it with `needsSourceBackfill`.+ */+export const SOURCE_BACKFILL_MIN_AGENT_DONE_ISSUES = 3;+/*** Should we ask this already-onboarded user where they heard about* Multica?@@ -20,9 +37,15 @@ export const SOURCE_BACKFILL_MAX_DISMISSALS = 3;* Returns true for users who:* - have completed onboarding (`onboarded_at` set), and* - have not recorded any source (empty array or absent), and- * - did not previously click Skip on the onboarding `source` step, and+ * - did not previously decline the source question (skip marker), and* - have not closed this backfill prompt enough times to dismiss it.*+ * This is the user-level half of the gate. The workspace-level half —+ * "have agents completed at least SOURCE_BACKFILL_MIN_AGENT_DONE_ISSUES+ * issues here?" — needs a server query, so it lives in the modal+ * (`source-backfill-modal.tsx`), which also uses this predicate to+ * decide whether that query is worth running at all.+ ** Pure function — `dismissCount` is passed in so this stays callable* from core (no localStorage / StorageAdapter dependency).*/diff --git a/packages/core/onboarding/queries.ts b/packages/core/onboarding/queries.tsnew file mode 100644index 0000000000..75d35ceef1--- /dev/null+++ b/packages/core/onboarding/queries.ts@@ -0,0 +1,34 @@+import { queryOptions } from "@tanstack/react-query";+import { api } from "../api";+import { issueKeys } from "../issues/queries";++/**+ * Count of issues in the workspace completed by an AI assignee (agent+ * or squad). Sole consumer is the source-backfill gate: the prompt+ * waits until the user has watched agents finish real work before+ * asking the attribution question (SOURCE_BACKFILL_MIN_AGENT_DONE_ISSUES+ * in `needs-backfill.ts`).+ *+ * `limit: 1` because only `total` matters — the issue rows themselves+ * are discarded. Keyed under `issueKeys.all(wsId)` on purpose: issue+ * mutations and realtime events invalidate that prefix, so the count+ * refreshes as agents complete work and the prompt can appear without+ * a reload. The query is expected to be `enabled` only for the small+ * cohort that still owes a source answer, so the extra refetches don't+ * follow users around forever.+ */+export function agentCompletedIssueCountOptions(wsId: string) {+ return queryOptions({+ queryKey: [...issueKeys.all(wsId), "agent-done-count"] as const,+ queryFn: async () => {+ const res = await api.listIssues({+ workspace_id: wsId,+ statuses: ["done"],+ assignee_types: ["agent", "squad"],+ limit: 1,+ });+ return res.total;+ },+ staleTime: 30_000,+ });+}diff --git a/packages/core/onboarding/step-order.ts b/packages/core/onboarding/step-order.tsindex faaf63bfff..7bda76e712 100644--- a/packages/core/onboarding/step-order.ts+++ b/packages/core/onboarding/step-order.ts@@ -14,15 +14,24 @@ import type { OnboardingStep } from "./types";* for the same reason — users shouldn't think of reading the intro* as progress toward completing setup.*+ * Two questions are intentionally NOT steps anymore:+ *+ * - "source" (How did you hear about Multica?) is pure attribution+ * data with zero user-facing payoff, so it no longer taxes the+ * critical path. It is collected post-onboarding by the workspace+ * source-backfill prompt, and only after agents have completed+ * work for the user — see `needs-backfill.ts`.+ * - "role" / "use_case" merged into the single "about_you" step:+ * they share the same consumer (the Helper "About me" context+ * block) and one screen keeps the flow at three steps.+ ** Note: "teammate" (the old "Create your first agent" step) is no longer* part of the in-flow sequence. Helper agent creation now happens after* onboarding exits, in the workspace shell — see* `packages/views/workspace/welcome-after-onboarding.tsx`.*/export const ONBOARDING_STEP_ORDER: readonly OnboardingStep[] = [- "source",- "role",- "use_case",+ "about_you","workspace","runtime",] as const;diff --git a/packages/core/onboarding/types.ts b/packages/core/onboarding/types.tsindex 8bbebadd48..49ab4eeed2 100644--- a/packages/core/onboarding/types.ts+++ b/packages/core/onboarding/types.ts@@ -1,8 +1,6 @@export type OnboardingStep =| "welcome"- | "source"- | "role"- | "use_case"+ | "about_you"| "workspace"| "runtime";@@ -63,12 +61,20 @@ export type UseCase =* for clean self-reported-attribution math (the array shape is* preserved for back-compat with v2 multi-select rows; the client* now always commits a one-element array), and `role` stays single- * because the agent template recommendation wants a primary identity.+ * because downstream personalization (the Helper "About me" context)+ * wants a primary identity.*- * `*_skipped: true` distinguishes an explicit Skip click from a slot- * the user never reached. Both states are "unknown" for recommendation- * purposes; the skip marker exists for analytics and so future- * re-prompts can avoid nagging users who already declined.+ * `role` / `use_case` are collected in-flow on the About-you step;+ * `source` is no longer asked during onboarding — it is collected+ * after the user has seen agents complete work, via the workspace+ * source-backfill prompt (see `needs-backfill.ts`). The slots stay in+ * this one shape because they share the same JSONB column and PATCH+ * endpoint.+ *+ * `*_skipped: true` distinguishes an explicit Skip / decline from a+ * slot the user never reached. Both states are "unknown" for+ * personalization purposes; the skip marker exists for analytics and+ * so future re-prompts can avoid nagging users who already declined.** Backward compat: prior versions of this app wrote `source` and* `use_case` as a single string. `mergeQuestionnaire` indiff --git a/packages/views/locales/en/onboarding.json b/packages/views/locales/en/onboarding.jsonindex ae606ac24b..9b40b47ec5 100644--- a/packages/views/locales/en/onboarding.json+++ b/packages/views/locales/en/onboarding.json@@ -45,12 +45,15 @@},"source_backfill": {"eyebrow": "Quick question",- "lede": "We noticed you didn't pick this during signup — it helps us understand who finds Multica useful. One question, then you're back to your work.",+ "lede": "One quick question — it helps us understand who finds Multica useful. Answer once and you're back to your work.","submit": "Submit","hint_ready": "Looks good. Hit Submit when you're ready."},"questions": {"eyebrow_about_you": "About you",+ "about_you": {+ "question": "Tell us a bit about you."+ },"source": {"question": "How did you hear about Multica?","friends_colleagues": "Friends or colleagues",diff --git a/packages/views/locales/ja/onboarding.json b/packages/views/locales/ja/onboarding.jsonindex d5f4654ccb..5f3ef88688 100644--- a/packages/views/locales/ja/onboarding.json+++ b/packages/views/locales/ja/onboarding.json@@ -45,12 +45,15 @@},"source_backfill": {"eyebrow": "ちょっと質問",- "lede": "登録時にお答えいただかなかった項目です。Multica がどんな方に役立っているかを把握するのに役立ちます。一問だけ、終わればすぐ作業に戻れます。",+ "lede": "ひとつだけ質問です。Multica がどんな方に役立っているかを把握するのに役立ちます。答えたらすぐ作業に戻れます。","submit": "送信","hint_ready": "OK です。準備ができたら送信を押してください。"},"questions": {"eyebrow_about_you": "あなたについて",+ "about_you": {+ "question": "あなたについて少し教えてください。"+ },"source": {"question": "Multica をどこで知りましたか?","friends_colleagues": "友人または同僚",diff --git a/packages/views/locales/ko/onboarding.json b/packages/views/locales/ko/onboarding.jsonindex 6dad826a89..53fbd014f3 100644--- a/packages/views/locales/ko/onboarding.json+++ b/packages/views/locales/ko/onboarding.json@@ -45,12 +45,15 @@},"source_backfill": {"eyebrow": "간단한 질문 하나",- "lede": "가입할 때 선택하지 않으셨더라고요. 어떤 사용자에게 Multica가 유용한지 파악하는 데 도움이 됩니다. 답하시면 바로 작업으로 돌아가실 수 있어요.",+ "lede": "간단한 질문 하나예요. 어떤 사용자에게 Multica가 유용한지 파악하는 데 도움이 됩니다. 답하시면 바로 작업으로 돌아가실 수 있어요.","submit": "제출","hint_ready": "좋습니다. 준비되면 제출을 눌러주세요."},"questions": {"eyebrow_about_you": "내 정보",+ "about_you": {+ "question": "당신에 대해 간단히 알려주세요."+ },"source": {"question": "Multica를 어디서 알게 되셨나요?","friends_colleagues": "친구 또는 동료",diff --git a/packages/views/locales/zh-Hans/onboarding.json b/packages/views/locales/zh-Hans/onboarding.jsonindex 505b1919f5..411a968480 100644--- a/packages/views/locales/zh-Hans/onboarding.json+++ b/packages/views/locales/zh-Hans/onboarding.json@@ -45,12 +45,15 @@},"source_backfill": {"eyebrow": "顺便问一句",- "lede": "我们注意到你之前没有勾选这一项——花一秒补一下,能帮我们更了解像你一样的用户。完成后立刻回到你正在做的事。",+ "lede": "一个小问题——能帮我们更了解像你一样的用户。答完立刻回到你正在做的事。","submit": "提交","hint_ready": "看起来不错,准备好就点提交。"},"questions": {"eyebrow_about_you": "关于你",+ "about_you": {+ "question": "简单介绍一下你自己。"+ },"source": {"question": "你是从哪里了解到 Multica 的?","friends_colleagues": "朋友或同事",diff --git a/packages/views/onboarding/components/icon-option-card.tsx b/packages/views/onboarding/components/icon-option-card.tsxindex be8c6da6a9..0ee7af7c04 100644--- a/packages/views/onboarding/components/icon-option-card.tsx+++ b/packages/views/onboarding/components/icon-option-card.tsx@@ -6,15 +6,32 @@ import { cn } from "@multica/ui/lib/utils";const OTHER_INPUT_MAX_LENGTH = 80;/**- * Card-grid option used by the per-question questionnaire steps- * (Source / Role / Use case). One row = icon + label. Clicking the- * card selects it; the parent step decides when to advance (an- * explicit Continue button gates the transition so users can change- * their mind before committing). The `Other` variant swaps its- * label area for a free-text input when selected.+ * One option in a questionnaire card grid. `slug` is the persisted+ * enum value; `icon` is a React node (lucide icon, brand SVG, or emoji+ * span); `label` is the localized string already resolved by the+ * caller. `isOther` flips this card into a free-text input row.+ *+ * Shared by the About-you onboarding step and the workspace+ * source-backfill prompt, which both render their options through the+ * cards below.+ */+export interface QuestionOption {+ slug: string;+ icon: ReactNode;+ label: string;+ isOther?: boolean;+}++/**+ * Card-grid option used by the questionnaire surfaces (the About-you+ * onboarding step, the source-backfill prompt). One row = icon ++ * label. Clicking the card selects it; the parent decides when to+ * advance (an explicit Continue button gates the transition so users+ * can change their mind before committing). The `Other` variant swaps+ * its label area for a free-text input when selected.** `mode` controls ARIA role: `"radio"` for single-select questions- * (role), `"checkbox"` for multi-select (source, use case). Visual+ * (role, source), `"checkbox"` for multi-select (use case). Visual* style is identical — the border/shadow treatment already conveys* "selected"; multi-select cards just additionally don't deselect* other cards when clicked, which is the parent's responsibility.diff --git a/packages/views/onboarding/components/step-header.test.tsx b/packages/views/onboarding/components/step-header.test.tsxindex 1f3dcfe13e..4faebd8989 100644--- a/packages/views/onboarding/components/step-header.test.tsx+++ b/packages/views/onboarding/components/step-header.test.tsx@@ -25,23 +25,23 @@ function render(ui: React.ReactElement, options?: RenderOptions) {describe("StepHeader", () => {it("renders one dot per step in ONBOARDING_STEP_ORDER", () => {- const { container } = render(<StepHeader currentStep="source" />);+ const { container } = render(<StepHeader currentStep="about_you" />);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 3 (after source/role/use_case) → Step 4.+ // workspace is index 1 (after about_you) → Step 2.render(<StepHeader currentStep="workspace" />);expect(- screen.getByText(`Step 4 of ${ONBOARDING_STEP_ORDER.length}`),+ screen.getByText(`Step 2 of ${ONBOARDING_STEP_ORDER.length}`),).toBeInTheDocument();});it("sets accessible progressbar attrs", () => {render(<StepHeader currentStep="runtime" />);const bar = screen.getByRole("progressbar");- expect(bar).toHaveAttribute("aria-valuenow", "5"); // runtime is index 4 → step 5+ expect(bar).toHaveAttribute("aria-valuenow", "3"); // runtime is index 2 → step 3expect(bar).toHaveAttribute("aria-valuemax", String(ONBOARDING_STEP_ORDER.length));});diff --git a/packages/views/onboarding/onboarding-flow.tsx b/packages/views/onboarding/onboarding-flow.tsxindex 9461adc6fd..ddc1797d17 100644--- a/packages/views/onboarding/onboarding-flow.tsx+++ b/packages/views/onboarding/onboarding-flow.tsx@@ -16,9 +16,7 @@ import {import { workspaceListOptions } from "@multica/core/workspace/queries";import type { AgentRuntime, Workspace } from "@multica/core/types";import { StepWelcome } from "./steps/step-welcome";-import { StepSource } from "./steps/step-source";-import { StepRole } from "./steps/step-role";-import { StepUseCase } from "./steps/step-use-case";+import { StepAboutYou } from "./steps/step-about-you";import { StepWorkspace } from "./steps/step-workspace";import { StepRuntimeConnect } from "./steps/step-runtime-connect";import { StepPlatformFork } from "./steps/step-platform-fork";@@ -260,7 +258,7 @@ export function OnboardingFlow({const handleBack = useCallback((from: OnboardingStep) => {const idx = ONBOARDING_STEP_ORDER.indexOf(from);if (idx <= 0) {- // Source (the first persisted step) returns to Welcome.+ // About you (the first persisted step) returns to Welcome.setStep("welcome");return;}@@ -281,38 +279,14 @@ export function OnboardingFlow({);}- if (step === "source") {+ if (step === "about_you") {return (- <StepSource+ <StepAboutYouanswers={answers}onChange={applyAnswers}- onAdvance={() => advanceFrom("source")}- onSkip={() => advanceFrom("source")}- onBack={() => handleBack("source")}- />- );- }-- if (step === "role") {- return (- <StepRole- answers={answers}- onChange={applyAnswers}- onAdvance={() => advanceFrom("role")}- onSkip={() => advanceFrom("role")}- onBack={() => handleBack("role")}- />- );- }-- if (step === "use_case") {- return (- <StepUseCase- answers={answers}- onChange={applyAnswers}- onAdvance={() => advanceFrom("use_case")}- onSkip={() => advanceFrom("use_case")}- onBack={() => handleBack("use_case")}+ onAdvance={() => advanceFrom("about_you")}+ onSkip={() => advanceFrom("about_you")}+ onBack={() => handleBack("about_you")}/>);}diff --git a/packages/views/onboarding/source-backfill-modal.test.tsx b/packages/views/onboarding/source-backfill-modal.test.tsxindex 7e6dc9fc6d..40d454699d 100644--- a/packages/views/onboarding/source-backfill-modal.test.tsx+++ b/packages/views/onboarding/source-backfill-modal.test.tsx@@ -1,16 +1,23 @@import { act, render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../locales/en/common.json";import enOnboarding from "../locales/en/onboarding.json";const TEST_RESOURCES = { en: { common: enCommon, onboarding: enOnboarding } };-const { mockUser, mockSaveQuestionnaire } = vi.hoisted(() => ({- mockUser: { value: null as null | Record<string, unknown> },- mockSaveQuestionnaire: vi.fn(),-}));+const { mockUser, mockSaveQuestionnaire, mockWorkspace, mockAgentDoneTotal, mockListIssues } =+ vi.hoisted(() => ({+ mockUser: { value: null as null | Record<string, unknown> },+ mockSaveQuestionnaire: vi.fn(),+ mockWorkspace: {+ value: { id: "ws-1", slug: "ws-1" } as null | { id: string; slug: string },+ },+ mockAgentDoneTotal: { value: 3 },+ mockListIssues: vi.fn(),+ }));vi.mock("@multica/core/auth", async () => {const actual =@@ -33,6 +40,28 @@ vi.mock("@multica/core/onboarding", async () => {return { ...actual, saveQuestionnaire: mockSaveQuestionnaire };});+vi.mock("@multica/core/paths", async () => {+ const actual =+ await vi.importActual<typeof import("@multica/core/paths")>(+ "@multica/core/paths",+ );+ return { ...actual, useCurrentWorkspace: () => mockWorkspace.value };+});++vi.mock("@multica/core/api", async () => {+ const actual =+ await vi.importActual<typeof import("@multica/core/api")>(+ "@multica/core/api",+ );+ return {+ ...actual,+ api: {+ ...actual.api,+ listIssues: mockListIssues,+ },+ };+});+import { SourceBackfillModal } from "./source-backfill-modal";function setUser(partial: Record<string, unknown> | null) {@@ -75,6 +104,16 @@ function mockPrefersReducedMotion(matches: boolean) {beforeEach(() => {mockSaveQuestionnaire.mockReset();mockSaveQuestionnaire.mockResolvedValue(undefined);+ mockListIssues.mockReset();+ // Default: agents have already completed enough issues that the+ // workspace-level gate passes — tests about the user-level gate and+ // submit/skip semantics shouldn't have to care about it.+ mockAgentDoneTotal.value = 3;+ mockListIssues.mockImplementation(async () => ({+ issues: [],+ total: mockAgentDoneTotal.value,+ }));+ mockWorkspace.value = { id: "ws-1", slug: "ws-1" };setUser(null);wipeDismissCounters();mockPrefersReducedMotion(true);@@ -85,10 +124,15 @@ afterEach(() => {});function renderModal() {+ const qc = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });return render(- <I18nProvider locale="en" resources={TEST_RESOURCES}>- <SourceBackfillModal />- </I18nProvider>,+ <QueryClientProvider client={qc}>+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <SourceBackfillModal />+ </I18nProvider>+ </QueryClientProvider>,);}@@ -110,9 +154,11 @@ describe("SourceBackfillModal", () => {expect(screen.queryByText(/How did you hear about Multica/i),).not.toBeInTheDocument();+ // A settled user must not even pay for the count query.+ expect(mockListIssues).not.toHaveBeenCalled();});- it("opens for an onboarded user with empty source", async () => {+ it("opens for an onboarded user with empty source once agents completed enough issues", async () => {setUser({id: "u1",onboarded_at: "2026-01-01T00:00:00Z",@@ -126,6 +172,54 @@ describe("SourceBackfillModal", () => {});});+ it("stays closed while agents have completed fewer issues than the threshold", async () => {+ mockAgentDoneTotal.value = 2;+ setUser({+ id: "u1",+ onboarded_at: "2026-01-01T00:00:00Z",+ onboarding_questionnaire: { source: [] },+ });+ renderModal();+ // Let the count query settle before asserting the negative.+ await waitFor(() => {+ expect(mockListIssues).toHaveBeenCalled();+ });+ expect(+ screen.queryByText(/How did you hear about Multica/i),+ ).not.toBeInTheDocument();+ });++ it("stays closed outside a workspace context", async () => {+ mockWorkspace.value = null;+ setUser({+ id: "u1",+ onboarded_at: "2026-01-01T00:00:00Z",+ onboarding_questionnaire: { source: [] },+ });+ renderModal();+ expect(+ screen.queryByText(/How did you hear about Multica/i),+ ).not.toBeInTheDocument();+ expect(mockListIssues).not.toHaveBeenCalled();+ });++ it("counts done issues assigned to agents or squads in the current workspace", async () => {+ setUser({+ id: "u1",+ onboarded_at: "2026-01-01T00:00:00Z",+ onboarding_questionnaire: { source: [] },+ });+ renderModal();+ await waitFor(() => {+ expect(mockListIssues).toHaveBeenCalledWith({+ workspace_id: "ws-1",+ statuses: ["done"],+ assignee_types: ["agent", "squad"],+ limit: 1,+ });+ });+ });+it("Submit PATCHes the merged questionnaire preserving role / use_case", async () => {setUser({id: "u1",@@ -193,20 +287,10 @@ describe("SourceBackfillModal", () => {).not.toBeInTheDocument();});- it("renders the GitHub channel rebased from origin/main", async () => {- setUser({- id: "u1",- onboarded_at: "2026-01-01T00:00:00Z",- onboarding_questionnaire: { source: [] },- });- renderModal();- expect(await screen.findByText("GitHub")).toBeInTheDocument();- });-it("picking a second option replaces the first (single-select primary source)", async () => {- // The modal is now a single-select radio. Industry default for- // HDYHAU is to capture the primary acquisition source, so picking- // a second option must replace the first — never accumulate.+ // The modal is a single-select radio. Industry default for HDYHAU+ // is to capture the primary acquisition source, so picking a+ // second option must replace the first — never accumulate.setUser({id: "u1",onboarded_at: "2026-01-01T00:00:00Z",@@ -242,6 +326,10 @@ describe("SourceBackfillModal", () => {it("defers the entrance by ~700ms when the user has not opted into reduced motion", async () => {mockPrefersReducedMotion(false);+ // Fake timers from the very start so the 700ms entrance timer is+ // scheduled on the fake clock. The count query itself is+ // promise-based; advanceTimersByTimeAsync flushes the microtasks+ // that deliver its data and let the gate open.vi.useFakeTimers();try {setUser({@@ -250,8 +338,10 @@ describe("SourceBackfillModal", () => {onboarding_questionnaire: { source: [] },});renderModal();- // Immediately after mount: still hidden — the workspace gets a- // beat to render before the modal floats in.+ // Flush the count query → gate passes → timer scheduled (t=0).+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });expect(screen.queryByText(/How did you hear about Multica/i),).not.toBeInTheDocument();@@ -265,7 +355,7 @@ describe("SourceBackfillModal", () => {await vi.advanceTimersByTimeAsync(50);});expect(- screen.queryByText(/How did you hear about Multica/i),+ screen.getByText(/How did you hear about Multica/i),).toBeInTheDocument();} finally {vi.useRealTimers();@@ -283,5 +373,6 @@ describe("SourceBackfillModal", () => {expect(screen.queryByText(/How did you hear about Multica/i),).not.toBeInTheDocument();+ expect(mockListIssues).not.toHaveBeenCalled();});});diff --git a/packages/views/onboarding/source-backfill-modal.tsx b/packages/views/onboarding/source-backfill-modal.tsxindex 39b65c80db..c61317308d 100644--- a/packages/views/onboarding/source-backfill-modal.tsx+++ b/packages/views/onboarding/source-backfill-modal.tsx@@ -1,6 +1,7 @@"use client";import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useQuery } from "@tanstack/react-query";import {Briefcase,CalendarDays,@@ -13,11 +14,14 @@ import {import { toast } from "sonner";import { useAuthStore } from "@multica/core/auth";import {+ agentCompletedIssueCountOptions,needsSourceBackfill,saveQuestionnaire,+ SOURCE_BACKFILL_MIN_AGENT_DONE_ISSUES,type QuestionnaireAnswers,type Source,} from "@multica/core/onboarding";+import { useCurrentWorkspace } from "@multica/core/paths";import { Button } from "@multica/ui/components/ui/button";import {Dialog,@@ -34,8 +38,8 @@ import {import {IconOptionCard,IconOtherOptionCard,+ type QuestionOption,} from "./components/icon-option-card";-import type { QuestionOption } from "./steps/step-question";import { mergedQuestionnairePatch } from "./source-backfill-merge";import { useSourceBackfillDismissCount } from "./source-backfill-dismiss";import { useT } from "../i18n";@@ -50,18 +54,27 @@ const EMPTY_BACKFILL: Pick<};/**- * Source-attribution backfill prompt for already-onboarded users whose- * questionnaire never recorded a source. Rendered as a Dialog overlay- * on top of the workspace shell — the user keeps their workspace- * context visible behind a dimmed backdrop.+ * Source-attribution prompt for onboarded users whose questionnaire+ * never recorded a source. The question is not asked during+ * onboarding at all — this prompt is its only collection point.+ * Rendered as a Dialog overlay on top of the workspace shell — the+ * user keeps their workspace context visible behind a dimmed backdrop.** Self-mounted: the caller drops `<SourceBackfillModal />` once inside- * the dashboard layout. The component reads the predicate- * `needsSourceBackfill(user, dismissCount)` and opens the dialog when- * it flips to true. Once the dialog opens we capture the open decision- * in a ref so subsequent re-renders that flip the predicate to false- * (e.g. after submit, before refreshMe round-trips) don't tear the- * dialog away mid-animation.+ * the dashboard layout. Two gates decide whether the dialog opens:+ *+ * 1. User-level: `needsSourceBackfill(user, dismissCount)` — no+ * source recorded, never declined, dismiss cap not reached.+ * 2. Workspace-level: agents (or squads) have completed at least+ * SOURCE_BACKFILL_MIN_AGENT_DONE_ISSUES issues here. Attribution+ * is a zero-payoff ask for the user, so it waits until Multica+ * has visibly delivered value. The count query only runs while+ * gate 1 passes, so settled users never pay for it.+ *+ * Once the dialog opens we capture the open decision in a ref so+ * subsequent re-renders that flip the predicate to false (e.g. after+ * submit, before refreshMe round-trips) don't tear the dialog away+ * mid-animation.** Three exit shapes:* - Submit → PATCH merged questionnaire, terminal.@@ -81,9 +94,22 @@ export function SourceBackfillModal() {const [dismissCount, bumpDismissCount] =useSourceBackfillDismissCount(userId);- // Decide once per (user, dismissCount delta) whether the prompt- // should open. After it opens we stop reconsulting the predicate so- // a midflight refreshMe (which sets source) doesn't unmount the+ // Gate 1 first: it's pure and free. Gate 2 costs a (tiny) issues+ // query, so it's `enabled` only while gate 1 says this user still+ // owes an answer and we know which workspace to count in.+ const userEligible = needsSourceBackfill(user, dismissCount);+ const wsId = useCurrentWorkspace()?.id ?? null;+ const { data: agentDoneCount } = useQuery({+ ...agentCompletedIssueCountOptions(wsId ?? ""),+ enabled: userEligible && wsId !== null,+ });+ const shouldPrompt =+ userEligible &&+ (agentDoneCount ?? 0) >= SOURCE_BACKFILL_MIN_AGENT_DONE_ISSUES;++ // Decide once per (user, gate delta) whether the prompt should+ // open. After it opens we stop reconsulting the predicate so a+ // midflight refreshMe (which sets source) doesn't unmount the// dialog while the submit animation is still running. `openedRef`// is reset when the user identity changes.//@@ -102,7 +128,7 @@ export function SourceBackfillModal() {return;}if (openedForUserRef.current === user.id) return;- if (!needsSourceBackfill(user, dismissCount)) return;+ if (!shouldPrompt) return;// Soft entrance: let the user see the workspace for a beat before// the modal floats in, so it doesn't feel like a hard block. Common// delight pattern — ~700ms is short enough that nobody starts an@@ -123,7 +149,7 @@ export function SourceBackfillModal() {setOpen(true);}, 700);return () => window.clearTimeout(timer);- }, [user, dismissCount]);+ }, [user, shouldPrompt]);return (<Dialogdiff --git a/packages/views/onboarding/steps/step-about-you.test.tsx b/packages/views/onboarding/steps/step-about-you.test.tsxnew file mode 100644index 0000000000..53f7257edc--- /dev/null+++ b/packages/views/onboarding/steps/step-about-you.test.tsx@@ -0,0 +1,187 @@+import { describe, expect, it, vi, beforeEach } from "vitest";+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import type { QuestionnaireAnswers } from "@multica/core/onboarding";+import { I18nProvider } from "@multica/core/i18n/react";+import enCommon from "../../locales/en/common.json";+import enOnboarding from "../../locales/en/onboarding.json";+import { StepAboutYou } from "./step-about-you";++const TEST_RESOURCES = { en: { common: enCommon, onboarding: enOnboarding } };++const EMPTY: QuestionnaireAnswers = {+ source: [],+ source_other: null,+ source_skipped: false,+ role: null,+ role_other: null,+ role_skipped: false,+ use_case: [],+ use_case_other: null,+ use_case_skipped: false,+ version: 2,+};++function renderStep(answers: QuestionnaireAnswers = EMPTY) {+ const onChange = vi.fn();+ const onAdvance = vi.fn();+ const onSkip = vi.fn();+ render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <StepAboutYou+ answers={answers}+ onChange={onChange}+ onAdvance={onAdvance}+ onSkip={onSkip}+ />+ </I18nProvider>,+ );+ return { onChange, onAdvance, onSkip };+}++describe("StepAboutYou", () => {+ beforeEach(() => vi.restoreAllMocks());++ it("renders both question groups on one screen", () => {+ renderStep();+ expect(+ screen.getByText("Which best describes you?"),+ ).toBeInTheDocument();+ expect(+ screen.getByText("What do you want to use Multica for?"),+ ).toBeInTheDocument();+ });++ it("selecting a role patches the slug and clears Other/skip", async () => {+ const user = userEvent.setup();+ const { onChange, onAdvance } = renderStep();++ await user.click(screen.getByRole("radio", { name: /engineer/i }));++ expect(onChange).toHaveBeenCalledWith({+ role: "engineer",+ role_other: null,+ role_skipped: false,+ });+ expect(onAdvance).not.toHaveBeenCalled();+ });++ it("toggling a use case patches the array and clears skip", async () => {+ const user = userEvent.setup();+ const { onChange } = renderStep();++ await user.click(+ screen.getByRole("checkbox", { name: /ship code with ai agents/i }),+ );++ expect(onChange).toHaveBeenCalledWith({+ use_case: ["ship_code"],+ use_case_skipped: false,+ });+ });++ it("Continue is disabled until one group has a committed answer", async () => {+ const user = userEvent.setup();+ const { onAdvance } = renderStep();++ const cont = screen.getByRole("button", { name: /continue/i });+ expect(cont).toBeDisabled();+ await user.click(cont);+ expect(onAdvance).not.toHaveBeenCalled();+ });++ it("Continue with only role answered marks use_case as skipped", async () => {+ const user = userEvent.setup();+ const { onChange, onAdvance } = renderStep({+ ...EMPTY,+ role: "engineer",+ });++ await user.click(screen.getByRole("button", { name: /continue/i }));++ expect(onChange).toHaveBeenCalledWith({+ use_case: [],+ use_case_other: null,+ use_case_skipped: true,+ });+ expect(onAdvance).toHaveBeenCalledTimes(1);+ });++ it("Continue with only use_case answered marks role as skipped", async () => {+ const user = userEvent.setup();+ const { onChange, onAdvance } = renderStep({+ ...EMPTY,+ use_case: ["ship_code"],+ });++ await user.click(screen.getByRole("button", { name: /continue/i }));++ expect(onChange).toHaveBeenCalledWith({+ role: null,+ role_other: null,+ role_skipped: true,+ });+ expect(onAdvance).toHaveBeenCalledTimes(1);+ });++ it("Continue with both groups answered patches nothing extra", async () => {+ const user = userEvent.setup();+ const { onChange, onAdvance } = renderStep({+ ...EMPTY,+ role: "engineer",+ use_case: ["ship_code"],+ });++ await user.click(screen.getByRole("button", { name: /continue/i }));++ expect(onChange).not.toHaveBeenCalled();+ expect(onAdvance).toHaveBeenCalledTimes(1);+ });++ it("a lone empty-text Other role does not enable Continue", () => {+ renderStep({ ...EMPTY, role: "other" });+ expect(screen.getByRole("button", { name: /continue/i })).toBeDisabled();+ });++ it("an Other role with text enables Continue", () => {+ renderStep({ ...EMPTY, role: "other", role_other: "teacher" });+ expect(+ screen.getByRole("button", { name: /continue/i }),+ ).toBeEnabled();+ });++ it("Skip declines both groups in one patch and advances", async () => {+ const user = userEvent.setup();+ const { onChange, onSkip } = renderStep();++ await user.click(screen.getByRole("button", { name: /skip/i }));++ expect(onChange).toHaveBeenCalledWith({+ role: null,+ role_other: null,+ role_skipped: true,+ use_case: [],+ use_case_other: null,+ use_case_skipped: true,+ });+ expect(onSkip).toHaveBeenCalledTimes(1);+ });++ it("pre-fills both groups from stored answers on re-entry", () => {+ renderStep({+ ...EMPTY,+ role: "designer",+ use_case: ["plan_research", "write_publish"],+ });++ expect(+ screen.getByRole("radio", { name: /designer/i }),+ ).toHaveAttribute("aria-checked", "true");+ expect(+ screen.getByRole("checkbox", { name: /plan, brainstorm, research/i }),+ ).toHaveAttribute("aria-checked", "true");+ expect(+ screen.getByRole("checkbox", { name: /write, edit, publish/i }),+ ).toHaveAttribute("aria-checked", "true");+ });+});diff --git a/packages/views/onboarding/steps/step-about-you.tsx b/packages/views/onboarding/steps/step-about-you.tsxnew file mode 100644index 0000000000..8daa6461aa--- /dev/null+++ b/packages/views/onboarding/steps/step-about-you.tsx@@ -0,0 +1,342 @@+"use client";++import { useRef } from "react";+import {+ ArrowLeft,+ ArrowRight,+ Brain,+ Briefcase,+ Code2,+ Compass,+ FileEdit,+ GraduationCap,+ ListChecks,+ Megaphone,+ MoreHorizontal,+ Palette,+ PenLine,+ Rocket,+ Search,+ Settings2,+ User,+} from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";+import type { QuestionnaireAnswers, Role, UseCase } from "@multica/core/onboarding";+import { DragStrip } from "@multica/views/platform";+import { StepHeader } from "../components/step-header";+import {+ IconOptionCard,+ IconOtherOptionCard,+ type QuestionOption,+} from "../components/icon-option-card";+import { useT } from "../../i18n";++/**+ * Step 1 — "About you": role (single-select) and use case+ * (multi-select) on ONE screen. They were separate steps once, but+ * they share the same eyebrow, the same consumer (the Helper "About+ * me" context block built by `buildUserContextSection`), and neither+ * deserves a full screen of its own — merging them cut the onboarding+ * progress bar from five steps to three.+ *+ * Answering is optional per group:+ * - Continue is enabled as soon as EITHER group has a committed+ * answer (an "Other" pick only counts once its free-text is+ * non-empty). On Continue, any group left unanswered gets its+ * `*_skipped` marker — the user saw the question and moved on,+ * which is exactly what the skip marker means downstream+ * (analytics + never re-prompting).+ * - Skip declines both groups at once.+ *+ * Every selection change PATCHes through `onChange` immediately (the+ * flow's `applyAnswers` fire-and-forgets persistence), so re-entry+ * pre-fills both groups.+ */+export function StepAboutYou({+ answers,+ onChange,+ onAdvance,+ onSkip,+ onBack,+}: {+ answers: QuestionnaireAnswers;+ onChange: (patch: Partial<QuestionnaireAnswers>) => void;+ onAdvance: () => void;+ onSkip: () => void;+ onBack?: () => void;+}) {+ const { t } = useT("onboarding");+ const mainRef = useRef<HTMLElement>(null);+ const fadeStyle = useScrollFade(mainRef);++ const roleOptions: QuestionOption[] = [+ { slug: "engineer", icon: <Code2 className="h-4 w-4" />, label: t(($) => $.questions.role.engineer) },+ { slug: "product", icon: <Briefcase className="h-4 w-4" />, label: t(($) => $.questions.role.product) },+ { slug: "designer", icon: <Palette className="h-4 w-4" />, label: t(($) => $.questions.role.designer) },+ { slug: "founder", icon: <Rocket className="h-4 w-4" />, label: t(($) => $.questions.role.founder) },+ { slug: "marketing", icon: <Megaphone className="h-4 w-4" />, label: t(($) => $.questions.role.marketing) },+ { slug: "writer", icon: <PenLine className="h-4 w-4" />, label: t(($) => $.questions.role.writer) },+ { slug: "research", icon: <Search className="h-4 w-4" />, label: t(($) => $.questions.role.research) },+ { slug: "ops", icon: <Settings2 className="h-4 w-4" />, label: t(($) => $.questions.role.ops) },+ { slug: "student", icon: <GraduationCap className="h-4 w-4" />, label: t(($) => $.questions.role.student) },+ { slug: "other", icon: <MoreHorizontal className="h-4 w-4" />, label: t(($) => $.questions.role.other), isOther: true },+ ];++ const useCaseOptions: QuestionOption[] = [+ { slug: "ship_code", icon: <Code2 className="h-4 w-4" />, label: t(($) => $.questions.use_case.ship_code) },+ { slug: "manage_team", icon: <ListChecks className="h-4 w-4" />, label: t(($) => $.questions.use_case.manage_team) },+ { slug: "personal_tasks", icon: <User className="h-4 w-4" />, label: t(($) => $.questions.use_case.personal_tasks) },+ { slug: "plan_research", icon: <Brain className="h-4 w-4" />, label: t(($) => $.questions.use_case.plan_research) },+ { slug: "write_publish", icon: <FileEdit className="h-4 w-4" />, label: t(($) => $.questions.use_case.write_publish) },+ { slug: "automate_ops", icon: <Settings2 className="h-4 w-4" />, label: t(($) => $.questions.use_case.automate_ops) },+ { slug: "evaluate", icon: <Compass className="h-4 w-4" />, label: t(($) => $.questions.use_case.evaluate) },+ { slug: "other", icon: <MoreHorizontal className="h-4 w-4" />, label: t(($) => $.questions.use_case.other), isOther: true },+ ];++ // Role stays single-select — downstream personalization (the Helper+ // "About me" block, the tailored intro slides) wants one primary+ // identity, not a blend.+ const roleSelected: readonly string[] = answers.role ? [answers.role] : [];+ const roleOtherFilled = (answers.role_other ?? "").trim().length > 0;+ const roleAnswered =+ answers.role !== null && (answers.role !== "other" || roleOtherFilled);++ const useCaseSlugs = answers.use_case ?? [];+ const useCaseOtherFilled =+ (answers.use_case_other ?? "").trim().length > 0;+ const useCaseHasNonOther = useCaseSlugs.some((s) => s !== "other");+ // Mirrors the old per-step rule: a lone "Other" pick only counts as+ // an answer once its free-text has content.+ const useCaseAnswered =+ useCaseSlugs.length > 0 && (useCaseHasNonOther || useCaseOtherFilled);++ const canContinue = roleAnswered || useCaseAnswered;++ const pickRole = (slug: string) => {+ if (slug === "other") {+ onChange({ role: "other", role_skipped: false });+ return;+ }+ onChange({ role: slug as Role, role_other: null, role_skipped: false });+ };++ const toggleUseCase = (slug: string) => {+ const current = answers.use_case ?? [];+ if (slug === "other") {+ if (current.includes("other")) {+ onChange({+ use_case: current.filter((s) => s !== "other"),+ use_case_other: null,+ });+ } else {+ onChange({ use_case: [...current, "other"], use_case_skipped: false });+ }+ return;+ }+ const typed = slug as UseCase;+ const next = current.includes(typed)+ ? current.filter((s) => s !== typed)+ : [...current, typed];+ onChange({ use_case: next, use_case_skipped: false });+ };++ const confirmAdvance = () => {+ if (!canContinue) return;+ // A group the user looked at but left unanswered is a decline —+ // stamp its skip marker so analytics see the decision and the+ // slot isn't treated as "never reached". Also clears a dangling+ // empty-text "Other" role pick.+ const patch: Partial<QuestionnaireAnswers> = {};+ if (!roleAnswered) {+ patch.role = null;+ patch.role_other = null;+ patch.role_skipped = true;+ }+ if (!useCaseAnswered) {+ patch.use_case = [];+ patch.use_case_other = null;+ patch.use_case_skipped = true;+ }+ if (Object.keys(patch).length > 0) onChange(patch);+ onAdvance();+ };++ const handleSkip = () => {+ onChange({+ role: null,+ role_other: null,+ role_skipped: true,+ use_case: [],+ use_case_other: null,+ use_case_skipped: true,+ });+ onSkip();+ };++ const footerHint = canContinue+ ? t(($) => $.step_question.hint_continue)+ : t(($) => $.step_question.hint_pick);++ return (+ <div className="animate-onboarding-enter flex h-full min-h-0 flex-col bg-background">+ <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" />+ {t(($) => $.common.back)}+ </button>+ ) : (+ <span aria-hidden className="w-0" />+ )}+ <div className="flex-1">+ <StepHeader currentStep="about_you" />+ </div>+ </header>++ <main+ ref={mainRef}+ style={fadeStyle}+ className="min-h-0 flex-1 overflow-y-auto"+ >+ <div className="mx-auto w-full max-w-[920px] px-6 py-10 sm:px-10 md:px-14 lg:py-14">+ <div className="mb-2 text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">+ {t(($) => $.questions.eyebrow_about_you)}+ </div>+ <h1 className="text-balance font-serif text-[34px] font-medium leading-[1.15] tracking-tight text-foreground">+ {t(($) => $.questions.about_you.question)}+ </h1>++ <QuestionGroup+ number={1}+ question={t(($) => $.questions.role.question)}+ options={roleOptions}+ selectedSlugs={roleSelected}+ otherValue={answers.role_other ?? ""}+ onOtherChange={(v) => onChange({ role_other: v })}+ otherPlaceholder={t(($) => $.questions.role.other_placeholder)}+ onAnswer={pickRole}+ onConfirm={confirmAdvance}+ />++ <QuestionGroup+ number={2}+ question={t(($) => $.questions.use_case.question)}+ options={useCaseOptions}+ selectedSlugs={useCaseSlugs}+ otherValue={answers.use_case_other ?? ""}+ onOtherChange={(v) => onChange({ use_case_other: v })}+ otherPlaceholder={t(($) => $.questions.use_case.other_placeholder)}+ onAnswer={toggleUseCase}+ onConfirm={confirmAdvance}+ multiSelect+ />++ <div className="mt-10 flex flex-wrap items-center justify-end gap-x-4 gap-y-2">+ <span+ aria-live="polite"+ className="mr-auto text-xs text-muted-foreground"+ >+ {footerHint}+ </span>+ <div className="flex items-center gap-2">+ <Button size="lg" variant="secondary" onClick={handleSkip}>+ {t(($) => $.common.skip)}+ </Button>+ <Button size="lg" disabled={!canContinue} onClick={confirmAdvance}>+ {t(($) => $.common.continue)}+ <ArrowRight className="h-4 w-4" />+ </Button>+ </div>+ </div>+ </div>+ </main>+ </div>+ );+}++StepAboutYou.displayName = "StepAboutYou";++/**+ * One question group: mono index + sub-question heading + option card+ * grid. Selection semantics live in the parent's handlers; this stays+ * a layout shell so both groups render identically.+ */+function QuestionGroup({+ number,+ question,+ options,+ selectedSlugs,+ otherValue,+ onOtherChange,+ otherPlaceholder,+ onAnswer,+ onConfirm,+ multiSelect = false,+}: {+ number: number;+ question: string;+ options: readonly QuestionOption[];+ selectedSlugs: readonly string[];+ otherValue: string;+ onOtherChange: (value: string) => void;+ otherPlaceholder: string;+ onAnswer: (slug: string) => void;+ /** Enter inside the "Other" input — parent decides if it advances. */+ onConfirm: () => void;+ multiSelect?: boolean;+}) {+ const otherOption = options.find((o) => o.isOther) ?? null;+ const otherSelected = otherOption+ ? selectedSlugs.includes(otherOption.slug)+ : false;++ return (+ <section className="mt-10">+ <div className="flex items-baseline gap-3">+ <span aria-hidden className="font-mono text-xs text-muted-foreground">+ {String(number).padStart(2, "0")}+ </span>+ <h2 className="text-[17px] font-medium leading-snug text-foreground">+ {question}+ </h2>+ </div>+ <fieldset+ role={multiSelect ? "group" : "radiogroup"}+ aria-label={question}+ className="m-0 mt-4 grid grid-cols-1 gap-3 p-0 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"+ >+ {options.map((option) =>+ option.isOther ? (+ <IconOtherOptionCard+ key={option.slug}+ icon={option.icon}+ label={option.label}+ selected={otherSelected}+ onSelect={() => onAnswer(option.slug)}+ otherValue={otherValue}+ onOtherChange={onOtherChange}+ onConfirm={onConfirm}+ placeholder={otherPlaceholder}+ mode={multiSelect ? "checkbox" : "radio"}+ />+ ) : (+ <IconOptionCard+ key={option.slug}+ icon={option.icon}+ label={option.label}+ selected={selectedSlugs.includes(option.slug)}+ onSelect={() => onAnswer(option.slug)}+ mode={multiSelect ? "checkbox" : "radio"}+ />+ ),+ )}+ </fieldset>+ </section>+ );+}diff --git a/packages/views/onboarding/steps/step-question.test.tsx b/packages/views/onboarding/steps/step-question.test.tsxdeleted file mode 100644index 498137edf5..0000000000--- a/packages/views/onboarding/steps/step-question.test.tsx+++ /dev/null@@ -1,125 +0,0 @@-import { describe, expect, it, vi, beforeEach } from "vitest";-import { render, screen } from "@testing-library/react";-import userEvent from "@testing-library/user-event";-import { I18nProvider } from "@multica/core/i18n/react";-import enCommon from "../../locales/en/common.json";-import enOnboarding from "../../locales/en/onboarding.json";-import { StepQuestion, type QuestionOption } from "./step-question";--const TEST_RESOURCES = { en: { common: enCommon, onboarding: enOnboarding } };--const OPTIONS: readonly QuestionOption[] = [- { slug: "a", icon: <span>A</span>, label: "Alpha" },- { slug: "b", icon: <span>B</span>, label: "Beta" },- { slug: "other", icon: <span>O</span>, label: "Other", isOther: true },-];--function renderShell(overrides: Partial<React.ComponentProps<typeof StepQuestion>> = {}) {- const onAnswer = vi.fn();- const onAdvance = vi.fn();- const onSkip = vi.fn();- const onBack = vi.fn();- const onOtherChange = vi.fn();- render(- <I18nProvider locale="en" resources={TEST_RESOURCES}>- <StepQuestion- step="source"- number={1}- question="Test question"- options={OPTIONS}- selectedSlugs={[]}- otherValue=""- onOtherChange={onOtherChange}- otherPlaceholder="type here"- onAnswer={onAnswer}- onAdvance={onAdvance}- onSkip={onSkip}- onBack={onBack}- {...overrides}- />- </I18nProvider>,- );- return { onAnswer, onAdvance, onSkip, onBack, onOtherChange };-}--describe("StepQuestion", () => {- beforeEach(() => vi.restoreAllMocks());-- it("Continue is disabled when nothing is selected", () => {- renderShell();- const continueBtn = screen.getByRole("button", { name: /continue/i });- expect(continueBtn).toBeDisabled();- });-- it("non-Other option: clicking records the slug but does not auto-advance", async () => {- const user = userEvent.setup();- const { onAnswer, onAdvance } = renderShell();- await user.click(screen.getByRole("radio", { name: /alpha/i }));- expect(onAnswer).toHaveBeenCalledWith("a");- expect(onAdvance).not.toHaveBeenCalled();- });-- it("with a non-Other slug selected, Continue is enabled and fires onAdvance", async () => {- const user = userEvent.setup();- const { onAdvance } = renderShell({ selectedSlugs: ["a"] });- const continueBtn = screen.getByRole("button", { name: /continue/i });- expect(continueBtn).toBeEnabled();- await user.click(continueBtn);- expect(onAdvance).toHaveBeenCalledTimes(1);- });-- it("Other selected with empty input → Continue stays disabled", async () => {- const user = userEvent.setup();- renderShell();- await user.click(screen.getByRole("radio", { name: /^other$/i }));- // pendingOther is now true; Continue must remain disabled until the- // free-text input has content.- expect(screen.getByRole("button", { name: /continue/i })).toBeDisabled();- });-- it("Other selected with non-blank otherValue → Continue is enabled", async () => {- const user = userEvent.setup();- const { onAdvance } = renderShell({- selectedSlugs: ["other"],- otherValue: "hello",- });- const continueBtn = screen.getByRole("button", { name: /continue/i });- expect(continueBtn).toBeEnabled();- await user.click(continueBtn);- expect(onAdvance).toHaveBeenCalledTimes(1);- });-- it("Other selected with whitespace-only otherValue → Continue is disabled", () => {- renderShell({ selectedSlugs: ["other"], otherValue: " " });- expect(screen.getByRole("button", { name: /continue/i })).toBeDisabled();- });-- it("Skip is always enabled and fires onSkip", async () => {- const user = userEvent.setup();- const { onSkip } = renderShell();- await user.click(screen.getByRole("button", { name: /^skip$/i }));- expect(onSkip).toHaveBeenCalledTimes(1);- });-- it("Back button is rendered only when onBack is provided", () => {- const { unmount } = render(- <I18nProvider locale="en" resources={TEST_RESOURCES}>- <StepQuestion- step="source"- number={1}- question="Test"- options={OPTIONS}- selectedSlugs={[]}- otherValue=""- onOtherChange={vi.fn()}- otherPlaceholder="type"- onAnswer={vi.fn()}- onAdvance={vi.fn()}- onSkip={vi.fn()}- />- </I18nProvider>,- );- expect(screen.queryByRole("button", { name: /^back$/i })).not.toBeInTheDocument();- unmount();- });-});diff --git a/packages/views/onboarding/steps/step-question.tsx b/packages/views/onboarding/steps/step-question.tsxdeleted file mode 100644index fdf20e833d..0000000000--- a/packages/views/onboarding/steps/step-question.tsx+++ /dev/null@@ -1,226 +0,0 @@-"use client";--import { type ReactNode, useRef, useState } from "react";-import { ArrowLeft, ArrowRight } from "lucide-react";-import { Button } from "@multica/ui/components/ui/button";-import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";-import type { OnboardingStep } from "@multica/core/onboarding";-import { DragStrip } from "@multica/views/platform";-import { StepHeader } from "../components/step-header";-import {- IconOptionCard,- IconOtherOptionCard,-} from "../components/icon-option-card";-import { useT } from "../../i18n";--/**- * One option in the card grid. `slug` is the persisted enum value;- * `icon` is a React node (lucide icon, brand SVG, or emoji span);- * `label` is the localized string already resolved by the caller.- * `isOther` flips this card into a free-text input row.- */-export interface QuestionOption {- slug: string;- icon: ReactNode;- label: string;- isOther?: boolean;-}--/**- * Generic per-question step used by Source / Role / Use case. Back- * lives in the page header next to the step indicator; Skip + Continue- * sit inline directly below the options grid (with a status hint),- * not in a sticky bottom footer — the form usually only fills the top- * third of the viewport, and a footer pinned to the page bottom left a- * large dead zone between the options and the action buttons.- *- * Supports both single-select (`multiSelect=false`, the default — Role- * and Source) and multi-select (`multiSelect=true` — Use case). The- * contract is always an array of selected slugs and an `onAnswer(slug)`- * callback fired when a card is clicked; the parent decides whether to- * replace (single) or toggle (multi) the selection in its own state.- */-export function StepQuestion({- step,- number,- eyebrow,- question,- options,- selectedSlugs,- otherValue,- onOtherChange,- otherPlaceholder,- onAnswer,- onAdvance,- onSkip,- onBack,- multiSelect = false,-}: {- step: OnboardingStep;- number: number;- eyebrow?: string;- question: string;- options: readonly QuestionOption[];- selectedSlugs: readonly string[];- otherValue: string;- onOtherChange: (value: string) => void;- otherPlaceholder: string;- /** Record the click in the parent — does NOT advance. Parent- * decides replace vs. toggle based on its own multi/single mode. */- onAnswer: (slug: string) => void;- /** Commit the current selection and move to the next step. */- onAdvance: () => void;- onSkip: () => void;- onBack?: () => void;- multiSelect?: boolean;-}) {- const { t } = useT("onboarding");- const [pendingOther, setPendingOther] = useState(false);- const mainRef = useRef<HTMLElement>(null);- const fadeStyle = useScrollFade(mainRef);-- const handleSelect = (option: QuestionOption) => {- if (option.isOther) {- setPendingOther(true);- onOtherChange(otherValue);- onAnswer(option.slug);- return;- }- setPendingOther(false);- onAnswer(option.slug);- };-- const otherOption = options.find((o) => o.isOther) ?? null;- const otherSelected = otherOption- ? selectedSlugs.includes(otherOption.slug)- : false;- const otherActive = otherSelected || pendingOther;- const otherFilled = (otherValue ?? "").trim().length > 0;- // Continue is enabled when:- // - at least one non-Other option is selected, OR- // - Other is selected AND the free-text input has content.- // In multi-select (Use case) Other can stack with regular picks; we- // treat the non-Other selections as sufficient to advance even if- // Other's text is empty.- const hasNonOtherSelection = selectedSlugs.some(- (slug) => slug !== otherOption?.slug,- );- const canContinue =- selectedSlugs.length > 0 &&- (hasNonOtherSelection || !otherActive || otherFilled);-- const confirmAdvance = () => {- if (canContinue) onAdvance();- };-- // Footer label:- // - single select (Role / Source): name the picked option- // ("hint_selected").- // - multi-select (Use case) with 1 pick: same.- // - multi-select with >1 pick: show count via the existing- // "hint_continue" key (locale-friendly, doesn't grow a new key- // just for "N selected").- const singlePicked =- selectedSlugs.length === 1- ? options.find((o) => o.slug === selectedSlugs[0]) ?? null- : null;- const singlePickedLabel = singlePicked?.label ?? null;- const footerHint = canContinue- ? singlePickedLabel- ? t(($) => $.step_runtime.hint_selected, { name: singlePickedLabel })- : t(($) => $.step_question.hint_continue)- : t(($) => $.step_question.hint_pick);-- return (- <div className="animate-onboarding-enter flex h-full min-h-0 flex-col bg-background">- <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" />- {t(($) => $.common.back)}- </button>- ) : (- <span aria-hidden className="w-0" />- )}- <div className="flex-1">- <StepHeader currentStep={step} />- </div>- </header>-- <main- ref={mainRef}- style={fadeStyle}- className="min-h-0 flex-1 overflow-y-auto"- >- <div className="mx-auto w-full max-w-[920px] px-6 py-10 sm:px-10 md:px-14 lg:py-14">- {eyebrow ? (- <div className="mb-2 text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">- {eyebrow}- </div>- ) : null}- <div className="mb-1 font-mono text-xs text-muted-foreground">- {String(number).padStart(2, "0")}- </div>- <h1 className="text-balance font-serif text-[34px] font-medium leading-[1.15] tracking-tight text-foreground">- {question}- </h1>-- <fieldset- role={multiSelect ? "group" : "radiogroup"}- aria-label={question}- className="mt-10 m-0 grid grid-cols-1 gap-3 p-0 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"- >- {options.map((option) =>- option.isOther ? (- <IconOtherOptionCard- key={option.slug}- icon={option.icon}- label={option.label}- selected={otherActive}- onSelect={() => handleSelect(option)}- otherValue={otherValue}- onOtherChange={onOtherChange}- onConfirm={confirmAdvance}- placeholder={otherPlaceholder}- mode={multiSelect ? "checkbox" : "radio"}- />- ) : (- <IconOptionCard- key={option.slug}- icon={option.icon}- label={option.label}- selected={selectedSlugs.includes(option.slug)}- onSelect={() => handleSelect(option)}- mode={multiSelect ? "checkbox" : "radio"}- />- ),- )}- </fieldset>-- <div className="mt-8 flex flex-wrap items-center justify-end gap-x-4 gap-y-2">- <span- aria-live="polite"- className="mr-auto text-xs text-muted-foreground"- >- {footerHint}- </span>- <div className="flex items-center gap-2">- <Button size="lg" variant="secondary" onClick={onSkip}>- {t(($) => $.common.skip)}- </Button>- <Button size="lg" disabled={!canContinue} onClick={confirmAdvance}>- {t(($) => $.common.continue)}- <ArrowRight className="h-4 w-4" />- </Button>- </div>- </div>- </div>- </main>- </div>- );-}diff --git a/packages/views/onboarding/steps/step-role.test.tsx b/packages/views/onboarding/steps/step-role.test.tsxdeleted file mode 100644index 0215927db9..0000000000--- a/packages/views/onboarding/steps/step-role.test.tsx+++ /dev/null@@ -1,87 +0,0 @@-import { describe, expect, it, vi, beforeEach } from "vitest";-import { render, screen } from "@testing-library/react";-import userEvent from "@testing-library/user-event";-import type { QuestionnaireAnswers } from "@multica/core/onboarding";-import { I18nProvider } from "@multica/core/i18n/react";-import enCommon from "../../locales/en/common.json";-import enOnboarding from "../../locales/en/onboarding.json";-import { StepRole } from "./step-role";--const TEST_RESOURCES = { en: { common: enCommon, onboarding: enOnboarding } };--const EMPTY: QuestionnaireAnswers = {- source: [],- source_other: null,- source_skipped: false,- role: null,- role_other: null,- role_skipped: false,- use_case: [],- use_case_other: null,- use_case_skipped: false,- version: 2,-};--function renderStep(answers: QuestionnaireAnswers = EMPTY) {- const onChange = vi.fn();- const onAdvance = vi.fn();- const onSkip = vi.fn();- render(- <I18nProvider locale="en" resources={TEST_RESOURCES}>- <StepRole- answers={answers}- onChange={onChange}- onAdvance={onAdvance}- onSkip={onSkip}- />- </I18nProvider>,- );- return { onChange, onAdvance, onSkip };-}--describe("StepRole", () => {- beforeEach(() => vi.restoreAllMocks());-- it("selecting a role patches the slug and clears Other/skip", async () => {- const user = userEvent.setup();- const { onChange, onAdvance } = renderStep();-- await user.click(screen.getByRole("radio", { name: /engineer/i }));-- expect(onChange).toHaveBeenCalledWith({- role: "engineer",- role_other: null,- role_skipped: false,- });- expect(onAdvance).not.toHaveBeenCalled();- });-- it("Skip clears slot and marks role_skipped", async () => {- const user = userEvent.setup();- const { onChange, onSkip } = renderStep();-- await user.click(screen.getByRole("button", { name: /skip/i }));-- expect(onChange).toHaveBeenCalledWith({- role: null,- role_other: null,- role_skipped: true,- });- expect(onSkip).toHaveBeenCalledTimes(1);- });-- it("Other: selecting + typing writes role_other through onChange", async () => {- const user = userEvent.setup();- const { onChange } = renderStep();-- await user.click(screen.getByRole("radio", { name: /^other$/i }));- expect(onChange).toHaveBeenCalledWith({- role: "other",- role_skipped: false,- });-- const input = await screen.findByPlaceholderText(/teacher/i);- await user.type(input, "y");- expect(onChange).toHaveBeenLastCalledWith({ role_other: "y" });- });-});diff --git a/packages/views/onboarding/steps/step-role.tsx b/packages/views/onboarding/steps/step-role.tsxdeleted file mode 100644index 799c2c63b8..0000000000--- a/packages/views/onboarding/steps/step-role.tsx+++ /dev/null@@ -1,90 +0,0 @@-"use client";--import {- Briefcase,- Code2,- GraduationCap,- Megaphone,- MoreHorizontal,- Palette,- PenLine,- Rocket,- Search,- Settings2,-} from "lucide-react";-import type { QuestionnaireAnswers, Role } from "@multica/core/onboarding";-import { StepQuestion, type QuestionOption } from "./step-question";-import { useT } from "../../i18n";--/**- * Step 2 — "Which best describes you?" Primary signal for the- * onboarding assistant.- */-export function StepRole({- answers,- onChange,- onAdvance,- onSkip,- onBack,-}: {- answers: QuestionnaireAnswers;- onChange: (patch: Partial<QuestionnaireAnswers>) => void;- onAdvance: () => void;- onSkip: () => void;- onBack?: () => void;-}) {- const { t } = useT("onboarding");-- const options: QuestionOption[] = [- { slug: "engineer", icon: <Code2 className="h-4 w-4" />, label: t(($) => $.questions.role.engineer) },- { slug: "product", icon: <Briefcase className="h-4 w-4" />, label: t(($) => $.questions.role.product) },- { slug: "designer", icon: <Palette className="h-4 w-4" />, label: t(($) => $.questions.role.designer) },- { slug: "founder", icon: <Rocket className="h-4 w-4" />, label: t(($) => $.questions.role.founder) },- { slug: "marketing", icon: <Megaphone className="h-4 w-4" />, label: t(($) => $.questions.role.marketing) },- { slug: "writer", icon: <PenLine className="h-4 w-4" />, label: t(($) => $.questions.role.writer) },- { slug: "research", icon: <Search className="h-4 w-4" />, label: t(($) => $.questions.role.research) },- { slug: "ops", icon: <Settings2 className="h-4 w-4" />, label: t(($) => $.questions.role.ops) },- { slug: "student", icon: <GraduationCap className="h-4 w-4" />, label: t(($) => $.questions.role.student) },- { slug: "other", icon: <MoreHorizontal className="h-4 w-4" />, label: t(($) => $.questions.role.other), isOther: true },- ];-- // Role stays single-select — the agent template recommender treats- // role as the primary identity signal; allowing several would force- // the recommender to pick a tiebreaker the user never expressed.- const selectedSlug =- answers.role ?? (answers.role_other ? "other" : null);- const selected: readonly string[] = selectedSlug ? [selectedSlug] : [];-- return (- <StepQuestion- step="role"- number={2}- eyebrow={t(($) => $.questions.eyebrow_about_you)}- question={t(($) => $.questions.role.question)}- options={options}- selectedSlugs={selected}- otherValue={answers.role_other ?? ""}- onOtherChange={(v) => onChange({ role_other: v })}- otherPlaceholder={t(($) => $.questions.role.other_placeholder)}- onAnswer={(slug) => {- if (slug === "other") {- onChange({ role: "other", role_skipped: false });- } else {- onChange({- role: slug as Role,- role_other: null,- role_skipped: false,- });- }- }}- onAdvance={onAdvance}- onSkip={() => {- onChange({ role: null, role_other: null, role_skipped: true });- onSkip();- }}- onBack={onBack}- />- );-}--StepRole.displayName = "StepRole";diff --git a/packages/views/onboarding/steps/step-source.test.tsx b/packages/views/onboarding/steps/step-source.test.tsxdeleted file mode 100644index 447834127e..0000000000--- a/packages/views/onboarding/steps/step-source.test.tsx+++ /dev/null@@ -1,125 +0,0 @@-import { describe, expect, it, vi, beforeEach } from "vitest";-import { render, screen } from "@testing-library/react";-import userEvent from "@testing-library/user-event";-import type { QuestionnaireAnswers } from "@multica/core/onboarding";-import { I18nProvider } from "@multica/core/i18n/react";-import enCommon from "../../locales/en/common.json";-import enOnboarding from "../../locales/en/onboarding.json";-import { StepSource } from "./step-source";--const TEST_RESOURCES = { en: { common: enCommon, onboarding: enOnboarding } };--const EMPTY: QuestionnaireAnswers = {- source: [],- source_other: null,- source_skipped: false,- role: null,- role_other: null,- role_skipped: false,- use_case: [],- use_case_other: null,- use_case_skipped: false,- version: 2,-};--function renderStep(answers: QuestionnaireAnswers = EMPTY) {- const onChange = vi.fn();- const onAdvance = vi.fn();- const onSkip = vi.fn();- const onBack = vi.fn();- render(- <I18nProvider locale="en" resources={TEST_RESOURCES}>- <StepSource- answers={answers}- onChange={onChange}- onAdvance={onAdvance}- onSkip={onSkip}- onBack={onBack}- />- </I18nProvider>,- );- return { onChange, onAdvance, onSkip, onBack };-}--describe("StepSource (single-select primary source)", () => {- beforeEach(() => vi.restoreAllMocks());-- it("clicking a non-Other option writes a one-element source array", async () => {- const user = userEvent.setup();- const { onChange, onAdvance } = renderStep();-- await user.click(screen.getByRole("radio", { name: /linkedin/i }));-- expect(onChange).toHaveBeenCalledWith({- source: ["social_linkedin"],- source_other: null,- source_skipped: false,- });- // A click only records — it must NOT auto-advance.- expect(onAdvance).not.toHaveBeenCalled();- });-- it("picking a second option replaces the first (no stacking)", async () => {- const user = userEvent.setup();- const { onChange } = renderStep({- ...EMPTY,- source: ["social_linkedin"],- });-- await user.click(screen.getByRole("radio", { name: /twitter/i }));-- expect(onChange).toHaveBeenCalledWith({- source: ["social_x"],- source_other: null,- source_skipped: false,- });- });-- it("Skip clears source + source_other and marks the step skipped, then calls onSkip", async () => {- const user = userEvent.setup();- const { onChange, onSkip } = renderStep();-- await user.click(screen.getByRole("button", { name: /skip/i }));-- expect(onChange).toHaveBeenCalledWith({- source: [],- source_other: null,- source_skipped: true,- });- expect(onSkip).toHaveBeenCalledTimes(1);- });-- it("Other: clicking writes `source: ['other']` and lets the user type into source_other", async () => {- const user = userEvent.setup();- const { onChange } = renderStep();-- await user.click(screen.getByRole("radio", { name: /^other$/i }));-- expect(onChange).toHaveBeenCalledWith({- source: ["other"],- source_other: null,- source_skipped: false,- });-- const input = await screen.findByPlaceholderText(/podcast/i);- await user.type(input, "x");- expect(onChange).toHaveBeenLastCalledWith({ source_other: "x" });- });-- it("switching away from Other clears source_other so a stale value can't leak", async () => {- const user = userEvent.setup();- const { onChange } = renderStep({- ...EMPTY,- source: ["other"],- source_other: "a podcast",- });-- await user.click(screen.getByRole("radio", { name: /linkedin/i }));-- expect(onChange).toHaveBeenCalledWith({- source: ["social_linkedin"],- source_other: null,- source_skipped: false,- });- });-});diff --git a/packages/views/onboarding/steps/step-source.tsx b/packages/views/onboarding/steps/step-source.tsxdeleted file mode 100644index fa9476fff1..0000000000--- a/packages/views/onboarding/steps/step-source.tsx+++ /dev/null@@ -1,102 +0,0 @@-"use client";--import {- Briefcase,- CalendarDays,- Globe,- HelpCircle,- MoreHorizontal,- Newspaper,- Users,-} from "lucide-react";-import type { QuestionnaireAnswers, Source } from "@multica/core/onboarding";-import {- GoogleIcon,- LinkedInIcon,- OpenAIIcon,- XIcon,- YouTubeIcon,- GitHubIcon,-} from "../components/brand-icons";-import { StepQuestion, type QuestionOption } from "./step-question";-import { useT } from "../../i18n";--/**- * Step 1 — "How did you hear about Multica?" Pure attribution, does- * not influence the agent template recommendation.- */-export function StepSource({- answers,- onChange,- onAdvance,- onSkip,- onBack,-}: {- answers: QuestionnaireAnswers;- onChange: (patch: Partial<QuestionnaireAnswers>) => void;- onAdvance: () => void;- onSkip: () => void;- onBack?: () => void;-}) {- const { t } = useT("onboarding");-- const options: QuestionOption[] = [- { slug: "friends_colleagues", icon: <Users className="h-4 w-4" />, label: t(($) => $.questions.source.friends_colleagues) },- { slug: "search", icon: <GoogleIcon className="h-[18px] w-[18px]" />, label: t(($) => $.questions.source.search) },- { slug: "social_x", icon: <XIcon className="h-[15px] w-[15px]" />, label: t(($) => $.questions.source.social_x) },- { slug: "social_linkedin", icon: <LinkedInIcon className="h-[18px] w-[18px]" />, label: t(($) => $.questions.source.social_linkedin) },- { slug: "social_youtube", icon: <YouTubeIcon className="h-[18px] w-[18px]" />, label: t(($) => $.questions.source.social_youtube) },- { slug: "social_github", icon: <GitHubIcon className="h-[18px] w-[18px]" />, label: t(($) => $.questions.source.social_github) },- { slug: "social_other", icon: <Globe className="h-4 w-4" />, label: t(($) => $.questions.source.social_misc) },- { slug: "blog_newsletter", icon: <Newspaper className="h-4 w-4" />, label: t(($) => $.questions.source.blog_newsletter) },- { slug: "ai_assistant", icon: <OpenAIIcon className="h-[16px] w-[16px]" />, label: t(($) => $.questions.source.ai_assistant) },- { slug: "from_work", icon: <Briefcase className="h-4 w-4" />, label: t(($) => $.questions.source.from_work) },- { slug: "event_conference", icon: <CalendarDays className="h-4 w-4" />, label: t(($) => $.questions.source.event_conference) },- { slug: "dont_remember", icon: <HelpCircle className="h-4 w-4" />, label: t(($) => $.questions.source.dont_remember) },- { slug: "other", icon: <MoreHorizontal className="h-4 w-4" />, label: t(($) => $.questions.source.other), isOther: true },- ];-- // Single-select on the primary acquisition source. The server schema- // keeps `source` as a string array for back-compat with v2 multi-- // select rows, but the UI only ever commits a one-element array —- // primary-source attribution is the documented industry default for- // HDYHAU prompts (Fairing, Recast, HockeyStack) and keeps channel- // weights clean for analytics.- const selected: readonly string[] = answers.source?.[0] ? [answers.source[0]] : [];-- const pick = (slug: string) => {- const typed = slug as Source;- onChange({- source: [typed],- // Switching off Other clears the free-text input so a stale- // value can't leak into the next pick. Picking Other keeps the- // existing text so the user can finish typing without losing- // their input.- source_other: typed === "other" ? answers.source_other : null,- source_skipped: false,- });- };-- return (- <StepQuestion- step="source"- number={1}- eyebrow={t(($) => $.questions.eyebrow_about_you)}- question={t(($) => $.questions.source.question)}- options={options}- selectedSlugs={selected}- otherValue={answers.source_other ?? ""}- onOtherChange={(v) => onChange({ source_other: v })}- otherPlaceholder={t(($) => $.questions.source.other_placeholder)}- onAnswer={pick}- onAdvance={onAdvance}- onSkip={() => {- onChange({ source: [], source_other: null, source_skipped: true });- onSkip();- }}- onBack={onBack}- />- );-}--StepSource.displayName = "StepSource";diff --git a/packages/views/onboarding/steps/step-use-case.test.tsx b/packages/views/onboarding/steps/step-use-case.test.tsxdeleted file mode 100644index 00c8894699..0000000000--- a/packages/views/onboarding/steps/step-use-case.test.tsx+++ /dev/null@@ -1,98 +0,0 @@-import { describe, expect, it, vi, beforeEach } from "vitest";-import { render, screen } from "@testing-library/react";-import userEvent from "@testing-library/user-event";-import type { QuestionnaireAnswers } from "@multica/core/onboarding";-import { I18nProvider } from "@multica/core/i18n/react";-import enCommon from "../../locales/en/common.json";-import enOnboarding from "../../locales/en/onboarding.json";-import { StepUseCase } from "./step-use-case";--const TEST_RESOURCES = { en: { common: enCommon, onboarding: enOnboarding } };--const EMPTY: QuestionnaireAnswers = {- source: [],- source_other: null,- source_skipped: false,- role: null,- role_other: null,- role_skipped: false,- use_case: [],- use_case_other: null,- use_case_skipped: false,- version: 2,-};--function renderStep(answers: QuestionnaireAnswers = EMPTY) {- const onChange = vi.fn();- const onAdvance = vi.fn();- const onSkip = vi.fn();- render(- <I18nProvider locale="en" resources={TEST_RESOURCES}>- <StepUseCase- answers={answers}- onChange={onChange}- onAdvance={onAdvance}- onSkip={onSkip}- />- </I18nProvider>,- );- return { onChange, onAdvance, onSkip };-}--describe("StepUseCase (multi-select)", () => {- beforeEach(() => vi.restoreAllMocks());-- it("clicking a use case appends it to the array", async () => {- const user = userEvent.setup();- const { onChange, onAdvance } = renderStep();-- await user.click(screen.getByRole("checkbox", { name: /ship code/i }));-- expect(onChange).toHaveBeenCalledWith({- use_case: ["ship_code"],- use_case_skipped: false,- });- expect(onAdvance).not.toHaveBeenCalled();- });-- it("clicking an already-selected use case removes it (toggle)", async () => {- const user = userEvent.setup();- const { onChange } = renderStep({ ...EMPTY, use_case: ["ship_code"] });-- await user.click(screen.getByRole("checkbox", { name: /ship code/i }));-- expect(onChange).toHaveBeenCalledWith({- use_case: [],- use_case_skipped: false,- });- });-- it("Skip clears slot and marks use_case_skipped", async () => {- const user = userEvent.setup();- const { onChange, onSkip } = renderStep();-- await user.click(screen.getByRole("button", { name: /skip/i }));-- expect(onChange).toHaveBeenCalledWith({- use_case: [],- use_case_other: null,- use_case_skipped: true,- });- expect(onSkip).toHaveBeenCalledTimes(1);- });-- it("Other: selecting + typing writes use_case_other through onChange", async () => {- const user = userEvent.setup();- const { onChange } = renderStep();-- await user.click(screen.getByRole("checkbox", { name: /^other$/i }));- expect(onChange).toHaveBeenCalledWith({- use_case: ["other"],- use_case_skipped: false,- });-- const input = await screen.findByPlaceholderText(/study group/i);- await user.type(input, "z");- expect(onChange).toHaveBeenLastCalledWith({ use_case_other: "z" });- });-});diff --git a/packages/views/onboarding/steps/step-use-case.tsx b/packages/views/onboarding/steps/step-use-case.tsxdeleted file mode 100644index 8222e26757..0000000000--- a/packages/views/onboarding/steps/step-use-case.tsx+++ /dev/null@@ -1,104 +0,0 @@-"use client";--import {- Brain,- Code2,- Compass,- FileEdit,- ListChecks,- MoreHorizontal,- Settings2,- User,-} from "lucide-react";-import type { QuestionnaireAnswers, UseCase } from "@multica/core/onboarding";-import { StepQuestion, type QuestionOption } from "./step-question";-import { useT } from "../../i18n";--/**- * Step 3 — "What do you want to use Multica for?" Tiebreaker for- * the agent template recommendation when role alone is ambiguous.- */-export function StepUseCase({- answers,- onChange,- onAdvance,- onSkip,- onBack,-}: {- answers: QuestionnaireAnswers;- onChange: (patch: Partial<QuestionnaireAnswers>) => void;- onAdvance: () => void;- onSkip: () => void;- onBack?: () => void;-}) {- const { t } = useT("onboarding");-- const options: QuestionOption[] = [- { slug: "ship_code", icon: <Code2 className="h-4 w-4" />, label: t(($) => $.questions.use_case.ship_code) },- { slug: "manage_team", icon: <ListChecks className="h-4 w-4" />, label: t(($) => $.questions.use_case.manage_team) },- { slug: "personal_tasks", icon: <User className="h-4 w-4" />, label: t(($) => $.questions.use_case.personal_tasks) },- { slug: "plan_research", icon: <Brain className="h-4 w-4" />, label: t(($) => $.questions.use_case.plan_research) },- { slug: "write_publish", icon: <FileEdit className="h-4 w-4" />, label: t(($) => $.questions.use_case.write_publish) },- { slug: "automate_ops", icon: <Settings2 className="h-4 w-4" />, label: t(($) => $.questions.use_case.automate_ops) },- { slug: "evaluate", icon: <Compass className="h-4 w-4" />, label: t(($) => $.questions.use_case.evaluate) },- { slug: "other", icon: <MoreHorizontal className="h-4 w-4" />, label: t(($) => $.questions.use_case.other), isOther: true },- ];-- // Multi-select: a user is realistically here for several things at- // once (ship code AND manage team, etc). Keeping it a single radio- // forced a primary that often isn't truthful; the template recommender- // already supports multi via includes(...) priority.- const selected: readonly string[] = [- ...(answers.use_case ?? []),- ...(!answers.use_case?.includes("other") && answers.use_case_other- ? ["other"]- : []),- ];-- const toggle = (slug: string) => {- const current = answers.use_case ?? [];- if (slug === "other") {- if (current.includes("other")) {- onChange({- use_case: current.filter((s) => s !== "other"),- use_case_other: null,- });- } else {- onChange({- use_case: [...current, "other"],- use_case_skipped: false,- });- }- return;- }- const typed = slug as UseCase;- const next = current.includes(typed)- ? current.filter((s) => s !== typed)- : [...current, typed];- onChange({ use_case: next, use_case_skipped: false });- };-- return (- <StepQuestion- step="use_case"- number={3}- eyebrow={t(($) => $.questions.eyebrow_about_you)}- question={t(($) => $.questions.use_case.question)}- options={options}- selectedSlugs={selected}- otherValue={answers.use_case_other ?? ""}- onOtherChange={(v) => onChange({ use_case_other: v })}- otherPlaceholder={t(($) => $.questions.use_case.other_placeholder)}- onAnswer={toggle}- onAdvance={onAdvance}- onSkip={() => {- onChange({ use_case: [], use_case_other: null, use_case_skipped: true });- onSkip();- }}- onBack={onBack}- multiSelect- />- );-}--StepUseCase.displayName = "StepUseCase";diff --git a/server/internal/analytics/events.go b/server/internal/analytics/events.goindex 67e03bc039..4f25f06bb7 100644--- a/server/internal/analytics/events.go+++ b/server/internal/analytics/events.go@@ -20,6 +20,7 @@ const (EventTeamInviteAccepted = "team_invite_accepted"EventOnboardingStarted = "onboarding_started"EventOnboardingQuestionnaireSubmit = "onboarding_questionnaire_submitted"+ EventOnboardingSourceSubmit = "onboarding_source_submitted"EventAgentCreated = "agent_created"EventOnboardingCompleted = "onboarding_completed"EventCloudWaitlistJoined = "cloud_waitlist_joined"@@ -61,6 +62,7 @@ var metricsOnlyEvents = map[string]struct{}{EventTeamInviteAccepted: {},EventOnboardingStarted: {},EventOnboardingQuestionnaireSubmit: {},+ EventOnboardingSourceSubmit: {},EventAgentCreated: {},EventOnboardingCompleted: {},EventCloudWaitlistJoined: {},@@ -497,6 +499,49 @@ func OnboardingQuestionnaireSubmitted(userID string, source []string, role strin}}+// OnboardingSourceSubmitted fires when the user's acquisition source+// transitions from unresolved to resolved — answered or explicitly+// declined. The source question is no longer part of the onboarding+// flow (MUL-5159): it is asked by the workspace backfill prompt after+// agents have completed work for the user, so this lands well after+// `onboarding_questionnaire_submitted` (which now covers role ++// use_case only). A dedicated event gives the backfill prompt its own+// Grafana counter (answer/decline rate) without stalling the+// questionnaire funnel step. Metrics-only like every server event+// (MUL-4127); the per-user source value reaches analytics through the+// client-side person-property mirror in saveQuestionnaire.+//+// `source` stays a slice for the same v2 back-compat reason as the+// questionnaire event; the client commits a one-element array. $set+// is only attached when the user actually answered — moot while the+// event stays metrics-only, but kept accurate should it ever ship.+func OnboardingSourceSubmitted(userID string, source []string, skipped, hasOther bool) Event {+ if source == nil {+ source = []string{}+ }+ // Property key is acquisition_source, not source — core properties+ // stamp the event-source dimension into props["source"]+ // (withCoreProperties), and the acquisition answer must not fight+ // it for the slot. The $set person property below keeps the plain+ // "source" name for cohort continuity with the client-side mirror.+ ev := Event{+ Name: EventOnboardingSourceSubmit,+ DistinctID: userID,+ Properties: withCoreProperties(map[string]any{+ "acquisition_source": source,+ "source_skipped": skipped,+ "source_has_other": hasOther,+ }, CoreProperties{+ UserID: userID,+ Source: SourceOnboarding,+ }),+ }+ if len(source) > 0 {+ ev.Set = map[string]any{"source": source}+ }+ return ev+}+// AgentCreated fires whenever a new agent is added to a workspace — not// just inside onboarding. `isFirstAgentInWorkspace` lets the funnel// isolate the Step 4 signal from later agent additions.diff --git a/server/internal/analytics/events_test.go b/server/internal/analytics/events_test.goindex f6d9d3613d..085ddc64e0 100644--- a/server/internal/analytics/events_test.go+++ b/server/internal/analytics/events_test.go@@ -34,7 +34,8 @@ func TestIsMetricsOnly(t *testing.T) {// product-behaviour events (now DB + Grafana only)EventSignup, EventWorkspaceCreated, EventIssueCreated, EventIssueExecuted,EventChatMessageSent, EventTeamInviteSent, EventTeamInviteAccepted,- EventOnboardingStarted, EventOnboardingQuestionnaireSubmit, EventAgentCreated,+ EventOnboardingStarted, EventOnboardingQuestionnaireSubmit, EventOnboardingSourceSubmit,+ EventAgentCreated,EventOnboardingCompleted, EventCloudWaitlistJoined, EventFeedbackSubmitted,EventContactSalesSubmitted, EventSquadCreated, EventAutopilotCreated,} {@@ -47,3 +48,27 @@ func TestIsMetricsOnly(t *testing.T) {t.Errorf("IsMetricsOnly(%q) = true, want false (frontend-only event)", "$exception")}}++func TestOnboardingSourceSubmittedSetOnlyWhenAnswered(t *testing.T) {+ answered := OnboardingSourceSubmitted("u1", []string{"search"}, false, false)+ if answered.Properties["source_skipped"] != false {+ t.Fatalf("answered: source_skipped = %v, want false", answered.Properties["source_skipped"])+ }+ if answered.Set == nil || answered.Set["source"] == nil {+ t.Fatalf("answered: expected $set source, got %v", answered.Set)+ }++ declined := OnboardingSourceSubmitted("u1", nil, true, false)+ if declined.Properties["source_skipped"] != true {+ t.Fatalf("declined: source_skipped = %v, want true", declined.Properties["source_skipped"])+ }+ if declined.Set != nil {+ t.Fatalf("declined: a skip has nothing to mirror — expected nil Set, got %v", declined.Set)+ }+ // nil slice must normalize to [] so property types stay stable.+ // (Key is acquisition_source — plain "source" is the event-source+ // dimension stamped by core properties.)+ if src, ok := declined.Properties["acquisition_source"].([]string); !ok || src == nil {+ t.Fatalf("declined: acquisition_source property = %#v, want empty []string", declined.Properties["acquisition_source"])+ }+}diff --git a/server/internal/handler/onboarding.go b/server/internal/handler/onboarding.goindex b05f820edf..99e14cec75 100644--- a/server/internal/handler/onboarding.go+++ b/server/internal/handler/onboarding.go@@ -193,15 +193,22 @@ func (q questionnaireAnswers) useCaseResolved() bool {}// questionnaireSchemaVersion is the schema this handler understands.-// `complete()` and the funnel event are scoped to this version so a+// `complete()` and the funnel events are scoped to this version so a// future v3 row can't be silently mis-counted against v2 semantics.const questionnaireSchemaVersion = 2+// complete covers the IN-FLOW questionnaire only: role + use_case.+// Source moved out of the onboarding flow (MUL-5159) — it is collected+// later by the workspace backfill prompt, and its resolution is+// tracked by the separate `onboarding_source_submitted` emission in+// PatchOnboarding. Requiring source here would stall the funnel's+// "questionnaire submitted" step for days (or forever, for users who+// never see the backfill prompt).func (q questionnaireAnswers) complete() bool {if q.Version != questionnaireSchemaVersion {return false}- return q.sourceResolved() && q.roleResolved() && q.useCaseResolved()+ return q.roleResolved() && q.useCaseResolved()}// PatchOnboarding persists the user's questionnaire answers. The@@ -210,9 +217,12 @@ func (q questionnaireAnswers) complete() bool {// onboarding entry starts at Welcome.//// Emits `onboarding_questionnaire_submitted` exactly once per user:-// the first PATCH that transitions the answers from "at least one-// slot empty" to "all three filled". Revisions past that point don't-// re-emit — the funnel counts users, not edits.+// the first PATCH that transitions role + use_case from "at least one+// slot empty" to "both resolved". Emits `onboarding_source_submitted`+// exactly once on the source slot's own unresolved → resolved+// transition, which normally happens later via the workspace backfill+// prompt. Revisions past those points don't re-emit — the funnel+// counts users, not edits.func (h *Handler) PatchOnboarding(w http.ResponseWriter, r *http.Request) {userID, ok := requireUserID(w, r)if !ok {@@ -280,6 +290,22 @@ func (h *Handler) PatchOnboarding(w http.ResponseWriter, r *http.Request) {))}+ // Source resolves on its own timeline — typically days after the+ // in-flow questionnaire, via the workspace backfill prompt (it can+ // no longer resolve in-flow). Emit on the unresolved → resolved+ // transition so the backfill prompt's answer/decline rate shows up+ // in Grafana; the transition check keeps the emission+ // once-per-user, mirroring the questionnaire event above.+ if after.Version == questionnaireSchemaVersion &&+ after.sourceResolved() && !before.sourceResolved() {+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.OnboardingSourceSubmitted(+ userID,+ []string(after.Source),+ after.SourceSkipped,+ after.SourceOther != "",+ ))+ }+writeJSON(w, http.StatusOK, userToResponse(user))}diff --git a/server/internal/handler/onboarding_test.go b/server/internal/handler/onboarding_test.goindex d047b56a57..8434d38855 100644--- a/server/internal/handler/onboarding_test.go+++ b/server/internal/handler/onboarding_test.go@@ -9,6 +9,10 @@ import ("strings""testing""time"++ "github.com/prometheus/client_golang/prometheus"++ obsmetrics "github.com/multica-ai/multica/server/internal/metrics")// newWaitlistTestUser inserts a fresh user row, returns its id, and@@ -662,3 +666,121 @@ func TestBootstrapOnboardingNoRuntimeUsesChineseGuideForChineseUsers(t *testing.}}}++// counterValue sums a named Prometheus counter across all label+// combinations on the given BusinessMetrics. Events are metrics-only+// since MUL-4127, so PatchOnboarding's emissions are observable ONLY+// through these counters — there is no PostHog capture to record.+func counterValue(t *testing.T, m *obsmetrics.BusinessMetrics, name string) float64 {+ t.Helper()+ reg := prometheus.NewRegistry()+ for _, c := range m.Collectors() {+ if err := reg.Register(c); err != nil {+ t.Fatalf("register collector: %v", err)+ }+ }+ families, err := reg.Gather()+ if err != nil {+ t.Fatalf("gather metrics: %v", err)+ }+ for _, mf := range families {+ if mf.GetName() != name {+ continue+ }+ var sum float64+ for _, mm := range mf.GetMetric() {+ sum += mm.GetCounter().GetValue()+ }+ return sum+ }+ return 0+}++func patchOnboardingAs(t *testing.T, h *Handler, userID, questionnaire string) {+ t.Helper()+ body := `{"questionnaire": ` + questionnaire + `}`+ req := httptest.NewRequest("PATCH", "/api/me/onboarding", strings.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("X-User-ID", userID)+ w := httptest.NewRecorder()+ h.PatchOnboarding(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("patch onboarding: expected 200, got %d: %s", w.Code, w.Body.String())+ }+}++// The in-flow questionnaire is role + use_case only (MUL-5159): its+// funnel counter must move without source, and source's own counter+// must move exactly once when source resolves later via the workspace+// backfill prompt.+func TestPatchOnboardingSplitsQuestionnaireAndSourceEvents(t *testing.T) {+ userID := newWaitlistTestUser(t, "[email protected]")++ m := obsmetrics.NewBusinessMetrics()+ h := *testHandler+ h.Metrics = m++ const questionnaireCounter = "multica_onboarding_questionnaire_submitted_total"+ const sourceCounter = "multica_onboarding_source_submitted_total"++ const inFlow = `{"source":[],"source_other":null,"source_skipped":false,` ++ `"role":"engineer","role_other":null,"role_skipped":false,` ++ `"use_case":["ship_code"],"use_case_other":null,"use_case_skipped":false,"version":2}`++ // Role + use_case resolved, source untouched → questionnaire counter+ // moves now; source counter must NOT.+ patchOnboardingAs(t, &h, userID, inFlow)+ if got := counterValue(t, m, questionnaireCounter); got != 1 {+ t.Fatalf("expected questionnaire counter 1 after role+use_case resolve, got %v", got)+ }+ if got := counterValue(t, m, sourceCounter); got != 0 {+ t.Fatalf("expected source counter 0 while source unresolved, got %v", got)+ }++ // Idempotency: replaying the same answers re-emits nothing.+ patchOnboardingAs(t, &h, userID, inFlow)+ if got := counterValue(t, m, questionnaireCounter); got != 1 {+ t.Fatalf("expected questionnaire counter to stay at 1 after replay, got %v", got)+ }++ // Source lands later (the backfill prompt merges it into the row).+ const withSource = `{"source":["search"],"source_other":null,"source_skipped":false,` ++ `"role":"engineer","role_other":null,"role_skipped":false,` ++ `"use_case":["ship_code"],"use_case_other":null,"use_case_skipped":false,"version":2}`+ patchOnboardingAs(t, &h, userID, withSource)+ if got := counterValue(t, m, sourceCounter); got != 1 {+ t.Fatalf("expected source counter 1 after source resolves, got %v", got)+ }+ if got := counterValue(t, m, questionnaireCounter); got != 1 {+ t.Fatalf("expected questionnaire counter to stay at 1 after source lands, got %v", got)+ }++ // Replaying the source answer re-emits nothing.+ patchOnboardingAs(t, &h, userID, withSource)+ if got := counterValue(t, m, sourceCounter); got != 1 {+ t.Fatalf("expected source counter to stay at 1 after replay, got %v", got)+ }+}++// Declining every question at once (the About-you Skip writes both+// role and use_case skip markers; a backfill Skip writes source's) is+// a resolution too: both counters move exactly once.+func TestPatchOnboardingAllSkippedResolvesBothCounters(t *testing.T) {+ userID := newWaitlistTestUser(t, "[email protected]")++ m := obsmetrics.NewBusinessMetrics()+ h := *testHandler+ h.Metrics = m++ const skipped = `{"source":[],"source_other":null,"source_skipped":true,` ++ `"role":null,"role_other":null,"role_skipped":true,` ++ `"use_case":[],"use_case_other":null,"use_case_skipped":true,"version":2}`+ patchOnboardingAs(t, &h, userID, skipped)++ if got := counterValue(t, m, "multica_onboarding_questionnaire_submitted_total"); got != 1 {+ t.Fatalf("expected questionnaire counter 1 for all-skip, got %v", got)+ }+ if got := counterValue(t, m, "multica_onboarding_source_submitted_total"); got != 1 {+ t.Fatalf("expected source counter 1 for an explicit decline, got %v", got)+ }+}diff --git a/server/internal/metrics/business_events.go b/server/internal/metrics/business_events.goindex 67edefb1fd..dca60058a3 100644--- a/server/internal/metrics/business_events.go+++ b/server/internal/metrics/business_events.go@@ -36,6 +36,7 @@ type businessEventMetrics struct {teamInviteAccepted *prometheus.CounterVeconboardingStarted *prometheus.CounterVeconboardingQuestionnaireSubmit *prometheus.CounterVec+ onboardingSourceSubmit *prometheus.CounterVeconboardingCompleted *prometheus.CounterVeccloudWaitlistJoined *prometheus.CounterVecissueCreated *prometheus.CounterVec@@ -91,6 +92,10 @@ func newBusinessEventMetrics() *businessEventMetrics {Name: "multica_onboarding_questionnaire_submitted_total",Help: "Total onboarding questionnaires submitted.",}, metricLabels("multica_onboarding_questionnaire_submitted_total")),+ onboardingSourceSubmit: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_onboarding_source_submitted_total",+ Help: "Total acquisition-source answers or declines recorded (workspace backfill prompt).",+ }, metricLabels("multica_onboarding_source_submitted_total")),onboardingCompleted: prometheus.NewCounterVec(prometheus.CounterOpts{Name: "multica_onboarding_completed_total",Help: "Total onboarding flows completed.",@@ -216,6 +221,7 @@ func (e *businessEventMetrics) collectors() []prometheus.Collector {e.teamInviteAccepted,e.onboardingStarted,e.onboardingQuestionnaireSubmit,+ e.onboardingSourceSubmit,e.onboardingCompleted,e.cloudWaitlistJoined,e.issueCreated,@@ -290,6 +296,8 @@ func (m *BusinessMetrics) IncForEvent(ev analytics.Event) {m.events.onboardingStarted.WithLabelValues(NormalizePlatform(stringProp(ev.Properties, "platform"))).Inc()case analytics.EventOnboardingQuestionnaireSubmit:m.events.onboardingQuestionnaireSubmit.WithLabelValues().Inc()+ case analytics.EventOnboardingSourceSubmit:+ m.events.onboardingSourceSubmit.WithLabelValues().Inc()case analytics.EventOnboardingCompleted:m.events.onboardingCompleted.WithLabelValues(NormalizeOnboardingPath(stringProp(ev.Properties, "completion_path"))).Inc()case analytics.EventCloudWaitlistJoined:diff --git a/server/internal/metrics/business_test.go b/server/internal/metrics/business_test.goindex 18d27aaff3..691643d985 100644--- a/server/internal/metrics/business_test.go+++ b/server/internal/metrics/business_test.go@@ -118,6 +118,7 @@ func TestBusinessMetricsRegistryExposesAllFamilies(t *testing.T) {exerciseEvent(m, analytics.EventTeamInviteAccepted, nil)exerciseEvent(m, analytics.EventOnboardingStarted, map[string]any{"platform": "web"})exerciseEvent(m, analytics.EventOnboardingQuestionnaireSubmit, nil)+ exerciseEvent(m, analytics.EventOnboardingSourceSubmit, nil)exerciseEvent(m, analytics.EventOnboardingCompleted, map[string]any{"completion_path": "full"})exerciseEvent(m, analytics.EventCloudWaitlistJoined, nil)exerciseEvent(m, analytics.EventIssueCreated, map[string]any{"source": "manual", "platform": "web"})diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.goindex b730ed6cf0..58fd87d16a 100644--- a/server/internal/metrics/labels.go+++ b/server/internal/metrics/labels.go@@ -59,6 +59,7 @@ var businessMetricLabels = map[string][]string{"multica_team_invite_accepted_total": {},"multica_onboarding_started_total": {labelPlatform},"multica_onboarding_questionnaire_submitted_total": {},+ "multica_onboarding_source_submitted_total": {},"multica_onboarding_completed_total": {labelPath},"multica_cloud_waitlist_joined_total": {},"multica_issue_created_total": {labelSource, labelPlatform},