Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(onboarding): backfill prompt for missing source attribution (MUL-2796) (#3550)
Jiayuan Zhangf539fdba83f0
diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsxindex ea3fed71a9..4b695e3937 100644--- a/apps/desktop/src/renderer/src/App.tsx+++ b/apps/desktop/src/renderer/src/App.tsx@@ -191,6 +191,7 @@ function AppContent() {return undefined;}, [user, workspaceListFetched, wsCount, workspaces, hasOnboarded, qc]);+// Validate persisted tab state against the current user's workspace list,// and pick an active workspace if none is set. Runs in useLayoutEffect// (synchronously after render, before paint) rather than the renderdiff --git a/apps/desktop/src/renderer/src/components/workspace-route-layout.test.tsx b/apps/desktop/src/renderer/src/components/workspace-route-layout.test.tsxnew file mode 100644index 0000000000..428ed4fada--- /dev/null+++ b/apps/desktop/src/renderer/src/components/workspace-route-layout.test.tsx@@ -0,0 +1,147 @@+import { describe, expect, it, vi, beforeEach } from "vitest";+import { render } from "@testing-library/react";+import { MemoryRouter, Route, Routes } from "react-router-dom";++// vi.hoisted shared state for all the stores / hooks the layout consumes.+const state = vi.hoisted(() => ({+ user: null as { id: string } | null,+ isAuthLoading: false,+ overlay: null as { type: string } | null,+ workspace: null as { id: string; slug: string } | null,+ listFetched: true,+ wsList: [] as { id: string; slug: string }[],+ workspaceSeen: true,+ modalRenders: 0,+ modalAriaLabel: "source-backfill-modal-marker",+}));++vi.mock("@multica/core/auth", () => {+ const useAuthStore = (selector: (s: typeof state) => unknown) => {+ if (selector.toString().includes("isLoading"))+ return state.isAuthLoading;+ return state.user;+ };+ return { useAuthStore };+});++vi.mock("@multica/core/platform", () => ({+ setCurrentWorkspace: vi.fn(),+}));++vi.mock("@multica/core/workspace", async () => {+ const actual = await vi.importActual<typeof import("@multica/core/workspace")>(+ "@multica/core/workspace",+ );+ return {+ ...actual,+ workspaceBySlugOptions: () => ({+ queryKey: ["workspace-by-slug"],+ queryFn: async () => state.workspace,+ }),+ workspaceListOptions: () => ({+ queryKey: ["workspace-list"],+ queryFn: async () => state.wsList,+ }),+ };+});++vi.mock("@multica/core/paths", async () => {+ const actual = await vi.importActual<typeof import("@multica/core/paths")>(+ "@multica/core/paths",+ );+ return {+ ...actual,+ WorkspaceSlugProvider: ({ children }: { children: React.ReactNode }) => (+ <>{children}</>+ ),+ paths: {+ ...actual.paths,+ login: () => "/login",+ },+ };+});++vi.mock("@multica/views/workspace/use-workspace-seen", () => ({+ useWorkspaceSeen: () => state.workspaceSeen,+}));++vi.mock("@multica/views/workspace/welcome-after-onboarding", () => ({+ WelcomeAfterOnboarding: () => null,+}));++vi.mock("@multica/views/layout", () => ({+ WorkspacePresencePrefetch: () => null,+}));++// The point of this whole test: assert the desktop layout mounts the+// SourceBackfillModal. We stub the real component with a marker that+// renders only when the layout actually rendered it (and not e.g.+// suppressed by overlayActive).+vi.mock("@multica/views/onboarding", () => ({+ SourceBackfillModal: () => {+ state.modalRenders += 1;+ return <div data-testid={state.modalAriaLabel} />;+ },+}));++vi.mock("@/stores/tab-store", () => ({+ useTabStore: Object.assign(() => null, {+ getState: () => ({ validateWorkspaceSlugs: vi.fn() }),+ }),+}));++vi.mock("@/stores/window-overlay-store", () => {+ const useWindowOverlayStore = (selector: (s: typeof state) => unknown) =>+ selector(state);+ return { useWindowOverlayStore };+});++import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { WorkspaceRouteLayout } from "./workspace-route-layout";++function renderLayout() {+ const qc = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0 } },+ });+ // Seed the workspace queries so the gate inside the layout passes+ // synchronously — the real hook reads from cache.+ qc.setQueryData(["workspace-by-slug"], state.workspace);+ qc.setQueryData(["workspace-list"], state.wsList);+ return render(+ <QueryClientProvider client={qc}>+ <MemoryRouter initialEntries={["/acme/issues"]}>+ <Routes>+ <Route path=":workspaceSlug/*" element={<WorkspaceRouteLayout />}>+ <Route path="*" element={<div data-testid="outlet" />} />+ </Route>+ </Routes>+ </MemoryRouter>+ </QueryClientProvider>,+ );+}++beforeEach(() => {+ state.user = { id: "u1" };+ state.isAuthLoading = false;+ state.overlay = null;+ state.workspace = { id: "ws-1", slug: "acme" };+ state.listFetched = true;+ state.wsList = [{ id: "ws-1", slug: "acme" }];+ state.workspaceSeen = true;+ state.modalRenders = 0;+});++describe("WorkspaceRouteLayout", () => {+ it("mounts SourceBackfillModal when no WindowOverlay is active", () => {+ const { queryByTestId } = renderLayout();+ expect(queryByTestId(state.modalAriaLabel)).not.toBeNull();+ expect(state.modalRenders).toBeGreaterThan(0);+ });++ it("suppresses SourceBackfillModal while a WindowOverlay is active", () => {+ state.overlay = { type: "new-workspace" };+ const { queryByTestId } = renderLayout();+ expect(queryByTestId(state.modalAriaLabel)).toBeNull();+ expect(state.modalRenders).toBe(0);+ });+});diff --git a/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx b/apps/desktop/src/renderer/src/components/workspace-route-layout.tsxindex dae311ae37..959f8b6b7f 100644--- a/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx+++ b/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx@@ -11,6 +11,7 @@ import { useAuthStore } from "@multica/core/auth";import { useWorkspaceSeen } from "@multica/views/workspace/use-workspace-seen";import { WelcomeAfterOnboarding } from "@multica/views/workspace/welcome-after-onboarding";import { WorkspacePresencePrefetch } from "@multica/views/layout";+import { SourceBackfillModal } from "@multica/views/onboarding";import { useTabStore } from "@/stores/tab-store";import { useWindowOverlayStore } from "@/stores/window-overlay-store";@@ -104,6 +105,13 @@ export function WorkspaceRouteLayout() {* Modal — unless the store signal has already been consumed, in* which case the hook renders null. */}{!overlayActive && <WelcomeAfterOnboarding />}+ {/* Source-attribution backfill: same Dialog the web shell mounts+ * inside DashboardLayout. Desktop's WorkspaceRouteLayout doesn't+ * wrap DashboardLayout, so the modal has to be wired in directly+ * here. Same overlay-suppression rule as WelcomeAfterOnboarding —+ * a portal-rendered Dialog at z-50 would otherwise sit above an+ * active pre-workspace overlay. */}+ {!overlayActive && <SourceBackfillModal />}</WorkspaceSlugProvider>);}diff --git a/apps/web/app/(auth)/login/page.tsx b/apps/web/app/(auth)/login/page.tsxindex c2c005e599..a726bd4f65 100644--- a/apps/web/app/(auth)/login/page.tsx+++ b/apps/web/app/(auth)/login/page.tsx@@ -122,8 +122,7 @@ function LoginPageContent() {return;}const list = qc.getQueryData<Workspace[]>(workspaceKeys.list()) ?? [];- const dest = await resolveLoggedInDestination(qc, onboarded, list);- router.push(dest);+ router.push(await resolveLoggedInDestination(qc, onboarded, list));};// Build Google OAuth state: encode platform + next URL so the callbackdiff --git a/apps/web/app/auth/callback/page.test.tsx b/apps/web/app/auth/callback/page.test.tsxindex 701e698748..9ba984a4b8 100644--- a/apps/web/app/auth/callback/page.test.tsx+++ b/apps/web/app/auth/callback/page.test.tsx@@ -18,13 +18,18 @@ const {mockSetQueryData: vi.fn(),}));-const makeUser = (overrides: Partial<{ onboarded_at: string | null }> = {}) => ({+const makeUser = (+ overrides: Partial<{+ onboarded_at: string | null;+ onboarding_questionnaire: Record<string, unknown>;+ }> = {},+) => ({id: "user-1",name: "Test",email: "[email protected]",avatar_url: null,onboarded_at: null,- onboarding_questionnaire: {},+ onboarding_questionnaire: { source: ["search"] },created_at: "2026-01-01T00:00:00Z",updated_at: "2026-01-01T00:00:00Z",...overrides,@@ -73,6 +78,15 @@ import CallbackPage from "./page";describe("CallbackPage", () => {beforeEach(() => {vi.clearAllMocks();+ // Reset the source-backfill dismiss counter so a test that writes+ // it doesn't leak state into the next test (and the next test+ // doesn't inherit a cap-reached state from a previous run).+ for (let i = window.localStorage.length - 1; i >= 0; i--) {+ const k = window.localStorage.key(i);+ if (k && k.startsWith("multica.source_backfill.dismiss.")) {+ window.localStorage.removeItem(k);+ }+ }// Snapshot keys before deleting — forEach + delete skips entries because// the iteration index advances while the underlying list shrinks.Array.from(mockSearchParams.keys()).forEach((k) =>@@ -182,4 +196,34 @@ describe("CallbackPage", () => {expect(mockPush).toHaveBeenCalledWith(paths.onboarding());});});++ it("onboarded users with missing source land in the workspace; the source-backfill modal is mounted there", async () => {+ // Source attribution backfill is now an in-workspace modal — see+ // `<SourceBackfillModal />` mounted inside `DashboardLayout`. The+ // callback page is intentionally agnostic about it.+ mockLoginWithGoogle.mockResolvedValue(+ makeUser({+ onboarded_at: "2026-01-01T00:00:00Z",+ onboarding_questionnaire: {},+ }),+ );+ mockListWorkspaces.mockResolvedValue([+ {+ id: "ws-1",+ name: "Acme",+ slug: "acme",+ description: null,+ context: null,+ settings: {},+ repos: [],+ issue_prefix: "ACME",+ created_at: "",+ updated_at: "",+ },+ ]);+ render(<CallbackPage />);+ await waitFor(() => {+ expect(mockPush).toHaveBeenCalledWith(paths.workspace("acme").issues());+ });+ });});diff --git a/apps/web/app/auth/callback/page.tsx b/apps/web/app/auth/callback/page.tsxindex b6e730d6a3..2dca05f143 100644--- a/apps/web/app/auth/callback/page.tsx+++ b/apps/web/app/auth/callback/page.tsx@@ -100,7 +100,10 @@ function CallbackContent() {// 3. Default: hand off to the resolver (onboarding for first-timers,// first workspace for returning users, /workspaces/new for- // onboarded users with zero workspaces).+ // onboarded users with zero workspaces). Source-attribution+ // backfill for onboarded users with no recorded source is+ // handled by `<SourceBackfillModal />` inside the dashboard+ // shell — not a route detour, so we route straight to dest.router.push(resolvePostAuthDestination(wsList, onboarded));}).catch((err) => {diff --git a/packages/core/onboarding/index.ts b/packages/core/onboarding/index.tsindex df5cb3c600..34b867ba6c 100644--- a/packages/core/onboarding/index.ts+++ b/packages/core/onboarding/index.ts@@ -12,6 +12,10 @@ export {joinCloudWaitlist,} from "./store";export { ONBOARDING_STEP_ORDER } from "./step-order";+export {+ needsSourceBackfill,+ SOURCE_BACKFILL_MAX_DISMISSALS,+} from "./needs-backfill";export { recommendTemplate, type AgentTemplateId } from "./recommend-template";export {useWelcomeStore,diff --git a/packages/core/onboarding/needs-backfill.test.ts b/packages/core/onboarding/needs-backfill.test.tsnew file mode 100644index 0000000000..e2fc00ed0b--- /dev/null+++ b/packages/core/onboarding/needs-backfill.test.ts@@ -0,0 +1,119 @@+import { describe, expect, it } from "vitest";+import type { User } from "../types";+import {+ needsSourceBackfill,+ SOURCE_BACKFILL_MAX_DISMISSALS,+} from "./needs-backfill";++const BASE_USER: User = {+ id: "u1",+ name: "User",+ email: "[email protected]",+ avatar_url: null,+ onboarded_at: "2025-01-01T00:00:00Z",+ onboarding_questionnaire: {},+ starter_content_state: "imported",+ language: null,+ profile_description: "",+ timezone: null,+ created_at: "2025-01-01T00:00:00Z",+ updated_at: "2025-01-01T00:00:00Z",+};++function makeUser(partial: Partial<User> = {}): User {+ return { ...BASE_USER, ...partial };+}++describe("needsSourceBackfill", () => {+ it("returns false when no user", () => {+ expect(needsSourceBackfill(null, 0)).toBe(false);+ expect(needsSourceBackfill(undefined, 0)).toBe(false);+ });++ it("returns false when user has not onboarded yet", () => {+ const user = makeUser({ onboarded_at: null });+ expect(needsSourceBackfill(user, 0)).toBe(false);+ });++ it("returns true when onboarded with empty questionnaire", () => {+ const user = makeUser({ onboarding_questionnaire: {} });+ expect(needsSourceBackfill(user, 0)).toBe(true);+ });++ it("returns true when onboarded with source missing", () => {+ const user = makeUser({+ onboarding_questionnaire: { role: "engineer" },+ });+ expect(needsSourceBackfill(user, 0)).toBe(true);+ });++ it("returns true when source is an empty array", () => {+ const user = makeUser({+ onboarding_questionnaire: { source: [] },+ });+ expect(needsSourceBackfill(user, 0)).toBe(true);+ });++ it("returns false when source has at least one entry", () => {+ const user = makeUser({+ onboarding_questionnaire: { source: ["search"] },+ });+ expect(needsSourceBackfill(user, 0)).toBe(false);+ });++ it("returns false when user previously skipped the source step", () => {+ const user = makeUser({+ onboarding_questionnaire: { source: [], source_skipped: true },+ });+ expect(needsSourceBackfill(user, 0)).toBe(false);+ });++ it("returns false once dismissCount hits the cap", () => {+ const user = makeUser({ onboarding_questionnaire: {} });+ expect(+ needsSourceBackfill(user, SOURCE_BACKFILL_MAX_DISMISSALS),+ ).toBe(false);+ expect(+ needsSourceBackfill(user, SOURCE_BACKFILL_MAX_DISMISSALS + 5),+ ).toBe(false);+ });++ it("still returns true just below the dismiss cap", () => {+ const user = makeUser({ onboarding_questionnaire: {} });+ expect(+ needsSourceBackfill(user, SOURCE_BACKFILL_MAX_DISMISSALS - 1),+ ).toBe(true);+ });++ it("treats a legacy single-string source as already answered", () => {+ // Pre-multi-select rows wrote `source` as a bare string. The+ // backfill flow must NOT re-prompt these users — they did answer.+ // Mirrors the tolerance in `OnboardingFlow.mergeQuestionnaire`.+ const user = makeUser({+ onboarding_questionnaire: { source: "search" },+ });+ expect(needsSourceBackfill(user, 0)).toBe(false);+ });++ it("treats a legacy empty-string source as missing", () => {+ const user = makeUser({+ onboarding_questionnaire: { source: "" },+ });+ expect(needsSourceBackfill(user, 0)).toBe(true);+ });++ it("treats malformed (number, null) source as missing", () => {+ expect(+ needsSourceBackfill(+ makeUser({ onboarding_questionnaire: { source: 42 } }),+ 0,+ ),+ ).toBe(true);+ expect(+ needsSourceBackfill(+ makeUser({ onboarding_questionnaire: { source: null } }),+ 0,+ ),+ ).toBe(true);+ });+});diff --git a/packages/core/onboarding/needs-backfill.ts b/packages/core/onboarding/needs-backfill.tsnew file mode 100644index 0000000000..4274415372--- /dev/null+++ b/packages/core/onboarding/needs-backfill.ts@@ -0,0 +1,51 @@+import type { User } from "../types";+import type { QuestionnaireAnswers } from "./types";++/**+ * Maximum number of times the user can close the backfill prompt with+ * the X / ESC / outside-click before we treat it as a permanent+ * dismissal. After that the prompt stops appearing.+ *+ * Submit and explicit Skip are always terminal (they write to the+ * server). The count exists only for the "I'll think about it later"+ * close path — without a cap, a user who never decides would see the+ * prompt every login forever.+ */+export const SOURCE_BACKFILL_MAX_DISMISSALS = 3;++/**+ * Should we ask this already-onboarded user where they heard about+ * Multica?+ *+ * 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+ * - have not closed this backfill prompt enough times to dismiss it.+ *+ * Pure function — `dismissCount` is passed in so this stays callable+ * from core (no localStorage / StorageAdapter dependency).+ */+export function needsSourceBackfill(+ user: User | null | undefined,+ dismissCount: number,+): boolean {+ if (!user) return false;+ if (!user.onboarded_at) return false;+ if (dismissCount >= SOURCE_BACKFILL_MAX_DISMISSALS) return false;++ const q = user.onboarding_questionnaire as+ | Partial<QuestionnaireAnswers>+ | null+ | undefined;+ if (!q) return true;+ if (q.source_skipped === true) return false;+ // Pre-multi-select rows wrote `source` as a bare string. Treat a+ // non-empty string the same as a one-element array — the user did+ // answer. Mirrors `OnboardingFlow.mergeQuestionnaire` (views) and+ // `stringOrSlice.UnmarshalJSON` (server).+ const raw: unknown = q.source;+ if (Array.isArray(raw)) return raw.length === 0;+ if (typeof raw === "string") return raw.length === 0;+ return true;+}diff --git a/packages/core/onboarding/store.ts b/packages/core/onboarding/store.tsindex 694655098d..cb42cbbd93 100644--- a/packages/core/onboarding/store.ts+++ b/packages/core/onboarding/store.ts@@ -22,9 +22,11 @@ export async function saveQuestionnaire(useAuthStore.getState().setUser(user);// Mirror the three cohort signals into person properties so every// PostHog event on this user can be broken down by source / role /- // use_case without re-joining the DB. source / use_case are arrays- // (multi-select); PostHog accepts array property values, and- // breakdowns split each element into its own group.+ // use_case without re-joining the DB. `source` is single-select but+ // shipped as a one-element array for v2 back-compat with the JSONB+ // column; `use_case` is multi-select. PostHog accepts array property+ // values, and breakdowns split each element into its own group — so+ // single-element source still slices cleanly.const sourceList = answers.source ?? [];const useCaseList = answers.use_case ?? [];if (sourceList.length > 0 || answers.role || useCaseList.length > 0) {diff --git a/packages/core/onboarding/types.ts b/packages/core/onboarding/types.tsindex 7c42e37572..0da5e3d1ee 100644--- a/packages/core/onboarding/types.ts+++ b/packages/core/onboarding/types.ts@@ -59,10 +59,13 @@ export type UseCase =| "other";/**- * Questionnaire shape. `source` and `use_case` allow multiple values- * (users hear about us through several channels and use Multica for- * several things); `role` stays single-select since the agent template- * recommendation wants a primary identity.+ * Questionnaire shape. `use_case` allows multiple values (users hire+ * Multica for several jobs at once); `source` and `role` are single-+ * select — for `source` we capture the primary acquisition channel+ * 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.** `*_skipped: true` distinguishes an explicit Skip click from a slot* the user never reached. Both states are "unknown" for recommendationdiff --git a/packages/views/layout/dashboard-layout.tsx b/packages/views/layout/dashboard-layout.tsxindex 938535ac6b..324759c603 100644--- a/packages/views/layout/dashboard-layout.tsx+++ b/packages/views/layout/dashboard-layout.tsx@@ -3,6 +3,7 @@import type { ReactNode } from "react";import { SidebarProvider, SidebarInset } from "@multica/ui/components/ui/sidebar";import { ModalRegistry } from "../modals/registry";+import { SourceBackfillModal } from "../onboarding";import { AppSidebar } from "./app-sidebar";import { DashboardGuard } from "./dashboard-guard";import { NavigationProgress } from "./navigation-progress";@@ -39,6 +40,7 @@ export function DashboardLayout({<NavigationProgress />{children}<ModalRegistry />+ <SourceBackfillModal />{extra}</SidebarInset></SidebarProvider>diff --git a/packages/views/locales/en/onboarding.json b/packages/views/locales/en/onboarding.jsonindex 50e3622402..badd0ed107 100644--- a/packages/views/locales/en/onboarding.json+++ b/packages/views/locales/en/onboarding.json@@ -40,7 +40,14 @@"back": "Back","continue": "Continue","skip": "Skip",- "cancel": "Cancel"+ "cancel": "Cancel",+ "close": "Close"+ },+ "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.",+ "submit": "Submit",+ "hint_ready": "Looks good. Hit Submit when you're ready."},"questions": {"eyebrow_about_you": "About you",diff --git a/packages/views/locales/ja/onboarding.json b/packages/views/locales/ja/onboarding.jsonindex a4d4a13a5a..47d339e13d 100644--- a/packages/views/locales/ja/onboarding.json+++ b/packages/views/locales/ja/onboarding.json@@ -40,7 +40,14 @@"back": "戻る","continue": "続ける","skip": "スキップ",- "cancel": "キャンセル"+ "cancel": "キャンセル",+ "close": "閉じる"+ },+ "source_backfill": {+ "eyebrow": "ちょっと質問",+ "lede": "登録時にお答えいただかなかった項目です。Multica がどんな方に役立っているかを把握するのに役立ちます。一問だけ、終わればすぐ作業に戻れます。",+ "submit": "送信",+ "hint_ready": "OK です。準備ができたら送信を押してください。"},"questions": {"eyebrow_about_you": "あなたについて",diff --git a/packages/views/locales/ko/onboarding.json b/packages/views/locales/ko/onboarding.jsonindex 9f42ce74ee..870018ec4e 100644--- a/packages/views/locales/ko/onboarding.json+++ b/packages/views/locales/ko/onboarding.json@@ -40,7 +40,14 @@"back": "뒤로","continue": "계속","skip": "건너뛰기",- "cancel": "취소"+ "cancel": "취소",+ "close": "닫기"+ },+ "source_backfill": {+ "eyebrow": "간단한 질문 하나",+ "lede": "가입할 때 선택하지 않으셨더라고요. 어떤 사용자에게 Multica가 유용한지 파악하는 데 도움이 됩니다. 답하시면 바로 작업으로 돌아가실 수 있어요.",+ "submit": "제출",+ "hint_ready": "좋습니다. 준비되면 제출을 눌러주세요."},"questions": {"eyebrow_about_you": "내 정보",diff --git a/packages/views/locales/zh-Hans/onboarding.json b/packages/views/locales/zh-Hans/onboarding.jsonindex f4f98afcfa..fdd2d760da 100644--- a/packages/views/locales/zh-Hans/onboarding.json+++ b/packages/views/locales/zh-Hans/onboarding.json@@ -40,7 +40,14 @@"back": "返回","continue": "继续","skip": "跳过",- "cancel": "取消"+ "cancel": "取消",+ "close": "关闭"+ },+ "source_backfill": {+ "eyebrow": "顺便问一句",+ "lede": "我们注意到你之前没有勾选这一项——花一秒补一下,能帮我们更了解像你一样的用户。完成后立刻回到你正在做的事。",+ "submit": "提交",+ "hint_ready": "看起来不错,准备好就点提交。"},"questions": {"eyebrow_about_you": "关于你",diff --git a/packages/views/onboarding/index.ts b/packages/views/onboarding/index.tsindex 6be25cd860..af77c2ef3f 100644--- a/packages/views/onboarding/index.ts+++ b/packages/views/onboarding/index.ts@@ -1,3 +1,4 @@export { OnboardingFlow, type OnboardingStep } from "./onboarding-flow";export { CliInstallInstructions } from "./steps/cli-install-instructions";export { CloudWaitlistExpand } from "./components/cloud-waitlist-expand";+export { SourceBackfillModal } from "./source-backfill-modal";diff --git a/packages/views/onboarding/source-backfill-dismiss.ts b/packages/views/onboarding/source-backfill-dismiss.tsnew file mode 100644index 0000000000..28aee58544--- /dev/null+++ b/packages/views/onboarding/source-backfill-dismiss.ts@@ -0,0 +1,98 @@+"use client";++import { useCallback, useSyncExternalStore } from "react";++/**+ * Per-user dismiss-count storage for the source-backfill prompt.+ *+ * Lives in `localStorage` rather than the server because:+ * - It is purely a frontend UX concern (when to stop nagging) and+ * never feeds analytics or the backend.+ * - Counting in the DB would mean writing on every page view, which+ * is wasteful for a transient signal.+ *+ * Tradeoff: clearing browser storage resets the count, and the count+ * does not sync across devices. Both are acceptable — Submit and Skip+ * are the terminal paths that write to the server; dismiss is "ask me+ * later," and asking again on a fresh browser is fine.+ */++const STORAGE_PREFIX = "multica.source_backfill.dismiss.";++function storageKey(userId: string): string {+ return `${STORAGE_PREFIX}${userId}`;+}++function readCount(userId: string | null | undefined): number {+ if (!userId) return 0;+ if (typeof window === "undefined") return 0;+ try {+ const raw = window.localStorage.getItem(storageKey(userId));+ if (!raw) return 0;+ const parsed = Number.parseInt(raw, 10);+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;+ } catch {+ return 0;+ }+}++function subscribe(callback: () => void): () => void {+ if (typeof window === "undefined") return () => {};+ // Fires when another tab updates the value. Same-tab updates go+ // through `forceUpdate` below.+ const handler = (e: StorageEvent) => {+ if (e.key && e.key.startsWith(STORAGE_PREFIX)) callback();+ };+ window.addEventListener("storage", handler);+ return () => window.removeEventListener("storage", handler);+}++// Shared listener registry so `bumpDismissCount` outside the React tree+// (rare, but possible) still wakes hooks subscribed to the same key.+const listeners = new Set<() => void>();+function notify(): void {+ for (const fn of listeners) fn();+}++export function useSourceBackfillDismissCount(+ userId: string | null | undefined,+): readonly [number, () => void] {+ const count = useSyncExternalStore(+ (cb) => {+ listeners.add(cb);+ const off = subscribe(cb);+ return () => {+ listeners.delete(cb);+ off();+ };+ },+ () => readCount(userId),+ () => 0,+ );++ const bump = useCallback(() => {+ if (!userId) return;+ if (typeof window === "undefined") return;+ try {+ const next = readCount(userId) + 1;+ window.localStorage.setItem(storageKey(userId), String(next));+ notify();+ } catch {+ // localStorage write can fail in private-mode Safari and similar+ // — treat as a no-op. Worst case the prompt re-shows next login+ // without backing off.+ }+ }, [userId]);++ return [count, bump] as const;+}++/** Test helper — not exported from the package index. */+export function _resetSourceBackfillDismissCountForTests(): void {+ if (typeof window === "undefined") return;+ for (let i = window.localStorage.length - 1; i >= 0; i--) {+ const k = window.localStorage.key(i);+ if (k && k.startsWith(STORAGE_PREFIX)) window.localStorage.removeItem(k);+ }+ notify();+}diff --git a/packages/views/onboarding/source-backfill-merge.test.ts b/packages/views/onboarding/source-backfill-merge.test.tsnew file mode 100644index 0000000000..32f611501f--- /dev/null+++ b/packages/views/onboarding/source-backfill-merge.test.ts@@ -0,0 +1,115 @@+import { describe, expect, it } from "vitest";+import { mergedQuestionnairePatch } from "./source-backfill-merge";++describe("mergedQuestionnairePatch", () => {+ it("preserves role / use_case when overlaying a fresh source", () => {+ const stored: Record<string, unknown> = {+ role: "engineer",+ role_other: null,+ role_skipped: false,+ use_case: ["ship_code", "plan_research"],+ use_case_other: null,+ use_case_skipped: false,+ version: 2,+ };+ const out = mergedQuestionnairePatch(stored, {+ source: ["search"],+ source_other: null,+ source_skipped: false,+ });+ expect(out.source).toEqual(["search"]);+ expect(out.role).toBe("engineer");+ expect(out.use_case).toEqual(["ship_code", "plan_research"]);+ expect(out.version).toBe(2);+ });++ it("preserves an existing source_skipped → false transition while keeping other slots", () => {+ const stored: Record<string, unknown> = {+ source_skipped: true,+ role: "founder",+ use_case: ["manage_team"],+ };+ const out = mergedQuestionnairePatch(stored, {+ source: ["friends_colleagues"],+ source_other: null,+ source_skipped: false,+ });+ expect(out.source_skipped).toBe(false);+ expect(out.role).toBe("founder");+ expect(out.use_case).toEqual(["manage_team"]);+ });++ it("explicit skip preserves role / use_case but writes source_skipped=true", () => {+ const stored: Record<string, unknown> = {+ role: "designer",+ use_case: ["plan_research"],+ };+ const out = mergedQuestionnairePatch(stored, {+ source: [],+ source_other: null,+ source_skipped: true,+ });+ expect(out.source).toEqual([]);+ expect(out.source_skipped).toBe(true);+ expect(out.role).toBe("designer");+ expect(out.use_case).toEqual(["plan_research"]);+ });++ it("coerces legacy single-string use_case into a one-element array", () => {+ const stored: Record<string, unknown> = {+ role: "engineer",+ use_case: "ship_code",+ };+ const out = mergedQuestionnairePatch(stored, {+ source: ["search"],+ source_other: null,+ source_skipped: false,+ });+ expect(out.use_case).toEqual(["ship_code"]);+ });++ it("defaults missing role / use_case to null / [] without throwing", () => {+ const out = mergedQuestionnairePatch(null, {+ source: ["search"],+ source_other: null,+ source_skipped: false,+ });+ expect(out.role).toBeNull();+ expect(out.role_other).toBeNull();+ expect(out.role_skipped).toBe(false);+ expect(out.use_case).toEqual([]);+ expect(out.version).toBe(2);+ });++ it("treats undefined / non-string fields as their type-appropriate default", () => {+ const stored: Record<string, unknown> = {+ role: 123,+ role_other: 456,+ role_skipped: "yes",+ use_case: null,+ use_case_other: false,+ use_case_skipped: 1,+ };+ const out = mergedQuestionnairePatch(stored, {+ source: [],+ source_other: null,+ source_skipped: false,+ });+ expect(out.role).toBeNull();+ expect(out.role_other).toBeNull();+ expect(out.role_skipped).toBe(false);+ expect(out.use_case).toEqual([]);+ expect(out.use_case_other).toBeNull();+ expect(out.use_case_skipped).toBe(false);+ });++ it("forces version to 2 regardless of stored value", () => {+ const stored: Record<string, unknown> = { version: 1 };+ const out = mergedQuestionnairePatch(stored, {+ source: ["search"],+ source_other: null,+ source_skipped: false,+ });+ expect(out.version).toBe(2);+ });+});diff --git a/packages/views/onboarding/source-backfill-merge.ts b/packages/views/onboarding/source-backfill-merge.tsnew file mode 100644index 0000000000..0a97b5a7c1--- /dev/null+++ b/packages/views/onboarding/source-backfill-merge.ts@@ -0,0 +1,65 @@+import type {+ QuestionnaireAnswers,+ Role,+ UseCase,+} from "@multica/core/onboarding";++/**+ * `PATCH /api/me/onboarding` overwrites the JSONB column wholesale —+ * it does NOT JSONB-merge (see `PatchUserOnboarding` in+ * `server/internal/handler/onboarding.go`). For the backfill flow the+ * user's stored questionnaire already contains role / use_case /+ * version, so we must read those, overlay only the source-related+ * fields, and send the whole shape back. Otherwise the very users we+ * target — onboarded accounts with role/use_case answered but source+ * missing — would have their other answers wiped on Submit / Skip.+ *+ * Mirrors the legacy tolerance in `OnboardingFlow.mergeQuestionnaire`+ * and the server's `stringOrSlice` decoder: `source` and `use_case`+ * may exist on disk as a bare string from a prior single-select+ * schema, which we coerce to a single-element array.+ */+export function mergedQuestionnairePatch(+ stored: Record<string, unknown> | null | undefined,+ sourcePatch: Pick<+ QuestionnaireAnswers,+ "source" | "source_other" | "source_skipped"+ >,+): QuestionnaireAnswers {+ const raw = (stored ?? {}) as Record<string, unknown>;+ return {+ source: sourcePatch.source,+ source_other: sourcePatch.source_other,+ source_skipped: sourcePatch.source_skipped,+ role: coerceRole(raw.role),+ role_other: coerceString(raw.role_other),+ role_skipped: coerceBool(raw.role_skipped),+ use_case: coerceStringArray<UseCase>(raw.use_case),+ use_case_other: coerceString(raw.use_case_other),+ use_case_skipped: coerceBool(raw.use_case_skipped),+ version: 2,+ };+}++function coerceStringArray<T extends string>(value: unknown): T[] {+ if (Array.isArray(value)) {+ return value.filter((v): v is T => typeof v === "string" && v.length > 0);+ }+ if (typeof value === "string" && value.length > 0) {+ return [value as T];+ }+ return [];+}++function coerceString(value: unknown): string | null {+ if (typeof value !== "string") return null;+ return value.length > 0 ? value : null;+}++function coerceBool(value: unknown): boolean {+ return value === true;+}++function coerceRole(value: unknown): Role | null {+ return coerceString(value) as Role | null;+}diff --git a/packages/views/onboarding/source-backfill-modal.test.tsx b/packages/views/onboarding/source-backfill-modal.test.tsxnew file mode 100644index 0000000000..8ef72e0a2d--- /dev/null+++ b/packages/views/onboarding/source-backfill-modal.test.tsx@@ -0,0 +1,300 @@+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 { 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, mockCaptureEvent } = vi.hoisted(() => ({+ mockUser: { value: null as null | Record<string, unknown> },+ mockSaveQuestionnaire: vi.fn(),+ mockCaptureEvent: vi.fn(),+}));++vi.mock("@multica/core/auth", async () => {+ const actual =+ await vi.importActual<typeof import("@multica/core/auth")>(+ "@multica/core/auth",+ );+ const useAuthStore = Object.assign(+ (selector: (s: { user: unknown }) => unknown) =>+ selector({ user: mockUser.value }),+ { getState: () => ({ user: mockUser.value }) },+ );+ return { ...actual, useAuthStore };+});++vi.mock("@multica/core/onboarding", async () => {+ const actual =+ await vi.importActual<typeof import("@multica/core/onboarding")>(+ "@multica/core/onboarding",+ );+ return { ...actual, saveQuestionnaire: mockSaveQuestionnaire };+});++vi.mock("@multica/core/analytics", () => ({+ captureEvent: mockCaptureEvent,+ setPersonProperties: vi.fn(),+}));++import { SourceBackfillModal } from "./source-backfill-modal";++function setUser(partial: Record<string, unknown> | null) {+ mockUser.value = partial;+}++function wipeDismissCounters() {+ for (let i = window.localStorage.length - 1; i >= 0; i--) {+ const k = window.localStorage.key(i);+ if (k && k.startsWith("multica.source_backfill.dismiss.")) {+ window.localStorage.removeItem(k);+ }+ }+}++/**+ * Default tests run with reduced-motion *on* so the modal's entrance+ * delay short-circuits and the dialog opens synchronously — keeps the+ * behavioural tests focused on selection / submit / skip semantics+ * rather than fighting timers. The dedicated entrance-delay test below+ * overrides this to assert the deferred-open path.+ */+function mockPrefersReducedMotion(matches: boolean) {+ Object.defineProperty(window, "matchMedia", {+ writable: true,+ configurable: true,+ value: (q: string) => ({+ matches: q.includes("reduce") ? matches : false,+ media: q,+ onchange: null,+ addListener: () => {},+ removeListener: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ dispatchEvent: () => false,+ }),+ });+}++beforeEach(() => {+ mockSaveQuestionnaire.mockReset();+ mockSaveQuestionnaire.mockResolvedValue(undefined);+ mockCaptureEvent.mockReset();+ setUser(null);+ wipeDismissCounters();+ mockPrefersReducedMotion(true);+});++afterEach(() => {+ wipeDismissCounters();+});++function renderModal() {+ return render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <SourceBackfillModal />+ </I18nProvider>,+ );+}++describe("SourceBackfillModal", () => {+ it("does not render when there is no user", () => {+ renderModal();+ expect(+ screen.queryByText(/How did you hear about Multica/i),+ ).not.toBeInTheDocument();+ });++ it("does not render when the user already recorded a source", () => {+ setUser({+ id: "u1",+ onboarded_at: "2026-01-01T00:00:00Z",+ onboarding_questionnaire: { source: ["search"] },+ });+ renderModal();+ expect(+ screen.queryByText(/How did you hear about Multica/i),+ ).not.toBeInTheDocument();+ });++ it("opens for an onboarded user with empty source and fires the shown event", async () => {+ setUser({+ id: "u1",+ onboarded_at: "2026-01-01T00:00:00Z",+ onboarding_questionnaire: { source: [] },+ });+ renderModal();+ await waitFor(() => {+ expect(+ screen.getByText(/How did you hear about Multica/i),+ ).toBeInTheDocument();+ });+ expect(mockCaptureEvent).toHaveBeenCalledWith("source_backfill_shown");+ });++ it("Submit PATCHes the merged questionnaire preserving role / use_case", async () => {+ setUser({+ id: "u1",+ onboarded_at: "2026-01-01T00:00:00Z",+ onboarding_questionnaire: {+ source: [],+ role: "engineer",+ role_skipped: false,+ use_case: ["ship_code", "plan_research"],+ use_case_skipped: false,+ version: 2,+ },+ });+ const user = userEvent.setup();+ renderModal();+ await user.click(await screen.findByText("Friends or colleagues"));+ await user.click(screen.getByRole("button", { name: "Submit" }));++ await waitFor(() => {+ expect(mockSaveQuestionnaire).toHaveBeenCalledTimes(1);+ });+ const sent = mockSaveQuestionnaire.mock.calls[0]![0];+ expect(sent.source).toEqual(["friends_colleagues"]);+ expect(sent.source_skipped).toBe(false);+ expect(sent.role).toBe("engineer");+ expect(sent.use_case).toEqual(["ship_code", "plan_research"]);+ expect(sent.version).toBe(2);+ expect(mockCaptureEvent).toHaveBeenCalledWith(+ "source_backfill_submitted",+ expect.objectContaining({ source: ["friends_colleagues"] }),+ );+ });++ it("Skip PATCHes source_skipped=true preserving role / use_case", async () => {+ setUser({+ id: "u1",+ onboarded_at: "2026-01-01T00:00:00Z",+ onboarding_questionnaire: {+ source: [],+ role: "founder",+ use_case: ["manage_team"],+ version: 2,+ },+ });+ const user = userEvent.setup();+ renderModal();+ await user.click(+ await screen.findByRole("button", { name: "Skip" }),+ );+ await waitFor(() => {+ expect(mockSaveQuestionnaire).toHaveBeenCalledTimes(1);+ });+ const sent = mockSaveQuestionnaire.mock.calls[0]![0];+ expect(sent.source).toEqual([]);+ expect(sent.source_skipped).toBe(true);+ expect(sent.role).toBe("founder");+ expect(sent.use_case).toEqual(["manage_team"]);+ expect(mockCaptureEvent).toHaveBeenCalledWith("source_backfill_skipped");+ });++ it("treats a legacy single-string source as already answered", () => {+ setUser({+ id: "u1",+ onboarded_at: "2026-01-01T00:00:00Z",+ onboarding_questionnaire: { source: "search" },+ });+ renderModal();+ expect(+ screen.queryByText(/How did you hear about Multica/i),+ ).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.+ setUser({+ id: "u1",+ onboarded_at: "2026-01-01T00:00:00Z",+ onboarding_questionnaire: { source: [] },+ });+ const user = userEvent.setup();+ renderModal();+ await screen.findByText("Friends or colleagues");+ const radios = screen.getAllByRole("radio");+ const friends = radios[0]!;+ const search = radios[1]!;++ await user.click(friends);+ expect(friends).toHaveAttribute("aria-checked", "true");+ expect(search).toHaveAttribute("aria-checked", "false");++ // Pick a second option — the first must clear and Submit stays+ // enabled with exactly one pick in the payload.+ await user.click(search);+ expect(friends).toHaveAttribute("aria-checked", "false");+ expect(search).toHaveAttribute("aria-checked", "true");++ await user.click(screen.getByRole("button", { name: "Submit" }));+ await waitFor(() => {+ expect(mockSaveQuestionnaire).toHaveBeenCalledTimes(1);+ });+ const sent = mockSaveQuestionnaire.mock.calls[0]![0];+ // Server schema is still `source: string[]` for back-compat with+ // v2 rows; the client always sends a single-element array.+ expect(sent.source).toEqual(["search"]);+ expect(sent.source).not.toContain("friends_colleagues");+ });++ it("defers the entrance by ~700ms when the user has not opted into reduced motion", async () => {+ mockPrefersReducedMotion(false);+ vi.useFakeTimers();+ try {+ setUser({+ id: "u1",+ onboarded_at: "2026-01-01T00:00:00Z",+ onboarding_questionnaire: { source: [] },+ });+ renderModal();+ // Immediately after mount: still hidden — the workspace gets a+ // beat to render before the modal floats in.+ expect(+ screen.queryByText(/How did you hear about Multica/i),+ ).not.toBeInTheDocument();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(699);+ });+ expect(+ screen.queryByText(/How did you hear about Multica/i),+ ).not.toBeInTheDocument();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(50);+ });+ expect(+ screen.queryByText(/How did you hear about Multica/i),+ ).toBeInTheDocument();+ } finally {+ vi.useRealTimers();+ }+ });++ it("does not open once the per-user dismiss cap is reached on this browser", () => {+ window.localStorage.setItem("multica.source_backfill.dismiss.u1", "3");+ 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();+ });+});diff --git a/packages/views/onboarding/source-backfill-modal.tsx b/packages/views/onboarding/source-backfill-modal.tsxnew file mode 100644index 0000000000..39532aeccc--- /dev/null+++ b/packages/views/onboarding/source-backfill-modal.tsx@@ -0,0 +1,361 @@+"use client";++import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ Briefcase,+ CalendarDays,+ Globe,+ HelpCircle,+ MoreHorizontal,+ Newspaper,+ Users,+} from "lucide-react";+import { toast } from "sonner";+import { captureEvent } from "@multica/core/analytics";+import { useAuthStore } from "@multica/core/auth";+import {+ needsSourceBackfill,+ saveQuestionnaire,+ type QuestionnaireAnswers,+ type Source,+} from "@multica/core/onboarding";+import { Button } from "@multica/ui/components/ui/button";+import {+ Dialog,+ DialogContent,+} from "@multica/ui/components/ui/dialog";+import {+ GitHubIcon,+ GoogleIcon,+ LinkedInIcon,+ OpenAIIcon,+ XIcon,+ YouTubeIcon,+} from "./components/brand-icons";+import {+ IconOptionCard,+ IconOtherOptionCard,+} 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";++const EMPTY_BACKFILL: Pick<+ QuestionnaireAnswers,+ "source" | "source_other" | "source_skipped"+> = {+ source: [],+ source_other: null,+ source_skipped: false,+};++/**+ * 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.+ *+ * 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.+ *+ * Three exit shapes:+ * - Submit → PATCH merged questionnaire, terminal.+ * - Skip → PATCH `source_skipped=true`, terminal (never+ * ask again).+ * - Close X / ESC → bump per-user dismiss counter; predicate+ * returns false on next mount once the cap is+ * reached.+ *+ * State persistence is intentional:+ * - source / source_other: server (JSONB merged with prior answers).+ * - dismissCount: per-user localStorage, view-layer only.+ */+export function SourceBackfillModal() {+ const user = useAuthStore((s) => s.user);+ const userId = user?.id ?? null;+ 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+ // dialog while the submit animation is still running. `openedRef`+ // is reset when the user identity changes.+ //+ // Strict-mode caveat: this effect runs twice in dev. The ref MUST+ // only be stamped when the dialog actually opens — not when the+ // effect schedules the timer — or the second strict-mode pass sees+ // `openedForUserRef.current === user.id` and bails without setting+ // up a new timer to replace the one strict-mode's cleanup just+ // cleared, leaving the dialog forever closed.+ const [open, setOpen] = useState(false);+ const openedForUserRef = useRef<string | null>(null);+ useEffect(() => {+ if (!user) {+ openedForUserRef.current = null;+ setOpen(false);+ return;+ }+ if (openedForUserRef.current === user.id) return;+ if (!needsSourceBackfill(user, dismissCount)) 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+ // interaction first but long enough that the workspace renders.+ // Honour `prefers-reduced-motion: reduce`: those users have opted+ // out of incidental animations, so open immediately.+ const reducedMotion =+ typeof window !== "undefined" &&+ window.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true;+ if (reducedMotion) {+ openedForUserRef.current = user.id;+ setOpen(true);+ return;+ }+ const uid = user.id;+ const timer = window.setTimeout(() => {+ openedForUserRef.current = uid;+ setOpen(true);+ }, 700);+ return () => window.clearTimeout(timer);+ }, [user, dismissCount]);++ return (+ <Dialog+ open={open}+ onOpenChange={(next) => {+ if (next || !open) return;+ // Base UI fires onOpenChange(false) for X, ESC, and outside+ // click — all three count as "dismiss without committing".+ captureEvent("source_backfill_dismissed", { trigger: "close" });+ bumpDismissCount();+ setOpen(false);+ }}+ >+ <SourceBackfillDialogBody+ open={open}+ onComplete={() => setOpen(false)}+ />+ </Dialog>+ );+}++SourceBackfillModal.displayName = "SourceBackfillModal";++/**+ * Inner panel split out so its expensive setup (option list, effects)+ * only runs while the dialog is actually open. Closing the dialog+ * unmounts this subtree and clears the picker state — the next open+ * starts fresh.+ */+function SourceBackfillDialogBody({+ open,+ onComplete,+}: {+ open: boolean;+ onComplete: () => void;+}) {+ const { t } = useT("onboarding");++ const [answers, setAnswers] = useState(EMPTY_BACKFILL);+ const [busy, setBusy] = useState(false);+ const shownEmittedRef = useRef(false);++ // Fire the funnel-open event exactly once per open transition.+ // `open` flips back when the parent closes us, and a fresh subsequent+ // open mounts a brand-new body, so the ref starts fresh too.+ useEffect(() => {+ if (!open) return;+ if (shownEmittedRef.current) return;+ shownEmittedRef.current = true;+ captureEvent("source_backfill_shown");+ }, [open]);++ const options = useMemo<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 },+ ],+ [t],+ );++ // Single-select: at most one slug in `source` at any time. The server+ // schema keeps the array (back-compat with the v2 multi-select shape+ // and with existing rows), but the modal UI commits exactly one pick+ // — primary-source attribution is the documented industry default for+ // HDYHAU prompts (Fairing, Recast, HockeyStack) and gives the team+ // clean channel weights without splitting users across N buckets.+ const pickedSlug: string | null = answers.source[0] ?? null;+ const otherOption = options.find((o) => o.isOther) ?? null;+ const otherSelected = pickedSlug === otherOption?.slug;+ const otherFilled = (answers.source_other ?? "").trim().length > 0;+ const canSubmit =+ !busy &&+ pickedSlug !== null &&+ // If the user picked Other, gate Submit on having typed something —+ // an empty Other selection isn't useful attribution data.+ (!otherSelected || otherFilled);++ const handleSelect = useCallback(+ (option: QuestionOption) => {+ if (option.isOther) {+ const slug = option.slug as Source;+ setAnswers((a) => ({+ ...a,+ source: [slug],+ // Picking Other doesn't carry text from a prior Other pick+ // forward: the text input auto-focuses fresh so the user can+ // type immediately. A previous text value would be misleading.+ source_other: a.source[0] === "other" ? a.source_other : null,+ source_skipped: false,+ }));+ return;+ }+ const slug = option.slug as Source;+ setAnswers((a) => ({+ ...a,+ source: [slug],+ source_other: null,+ source_skipped: false,+ }));+ },+ [],+ );++ const handleOtherChange = useCallback((value: string) => {+ setAnswers((a) => ({ ...a, source_other: value }));+ }, []);++ const submit = useCallback(async () => {+ if (!canSubmit) return;+ setBusy(true);+ try {+ // PATCH /api/me/onboarding replaces the JSONB wholesale, so we+ // re-read the stored answers from the auth store and overlay+ // only the source slots — preserving role / use_case / version+ // for the historical users this prompt targets.+ const stored =+ useAuthStore.getState().user?.onboarding_questionnaire ?? null;+ await saveQuestionnaire(+ mergedQuestionnairePatch(stored, {+ source: answers.source,+ source_other: answers.source_other,+ source_skipped: false,+ }),+ );+ captureEvent("source_backfill_submitted", {+ source: answers.source,+ ...(answers.source_other ? { source_other: answers.source_other } : {}),+ });+ onComplete();+ } catch (err) {+ setBusy(false);+ toast.error(err instanceof Error ? err.message : "Failed to save");+ }+ }, [canSubmit, answers.source, answers.source_other, onComplete]);++ const skip = useCallback(async () => {+ if (busy) return;+ setBusy(true);+ try {+ const stored =+ useAuthStore.getState().user?.onboarding_questionnaire ?? null;+ await saveQuestionnaire(+ mergedQuestionnairePatch(stored, {+ source: [],+ source_other: null,+ source_skipped: true,+ }),+ );+ captureEvent("source_backfill_skipped");+ onComplete();+ } catch (err) {+ setBusy(false);+ toast.error(err instanceof Error ? err.message : "Failed to save");+ }+ }, [busy, onComplete]);++ return (+ <DialogContent className="sm:max-w-2xl p-0 gap-0 overflow-hidden">+ <div className="px-6 pt-6 pb-2">+ <div className="text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground">+ {t(($) => $.source_backfill.eyebrow)}+ </div>+ <h2 className="mt-1 text-balance font-serif text-2xl font-medium leading-tight tracking-tight text-foreground">+ {t(($) => $.questions.source.question)}+ </h2>+ <p className="mt-2 text-sm text-muted-foreground">+ {t(($) => $.source_backfill.lede)}+ </p>+ </div>++ <fieldset+ role="radiogroup"+ aria-label={t(($) => $.questions.source.question)}+ className="m-0 grid grid-cols-1 gap-2 p-0 px-6 pt-4 sm:grid-cols-2"+ >+ {options.map((option) =>+ option.isOther ? (+ <IconOtherOptionCard+ key={option.slug}+ icon={option.icon}+ label={option.label}+ selected={otherSelected}+ onSelect={() => handleSelect(option)}+ otherValue={answers.source_other ?? ""}+ onOtherChange={handleOtherChange}+ onConfirm={submit}+ placeholder={t(($) => $.questions.source.other_placeholder)}+ mode="radio"+ />+ ) : (+ <IconOptionCard+ key={option.slug}+ icon={option.icon}+ label={option.label}+ selected={pickedSlug === option.slug}+ onSelect={() => handleSelect(option)}+ mode="radio"+ />+ ),+ )}+ </fieldset>++ <div className="mt-4 flex flex-wrap items-center justify-end gap-x-4 gap-y-2 border-t bg-muted/40 px-6 py-3">+ <span+ aria-live="polite"+ className="mr-auto text-xs text-muted-foreground"+ >+ {canSubmit+ ? t(($) => $.source_backfill.hint_ready)+ : t(($) => $.step_question.hint_pick)}+ </span>+ <div className="flex items-center gap-2">+ <Button variant="secondary" disabled={busy} onClick={skip}>+ {t(($) => $.common.skip)}+ </Button>+ <Button disabled={!canSubmit} onClick={submit}>+ {t(($) => $.source_backfill.submit)}+ </Button>+ </div>+ </div>+ </DialogContent>+ );+}diff --git a/packages/views/onboarding/steps/step-question.tsx b/packages/views/onboarding/steps/step-question.tsxindex 2c27f89514..fdf20e833d 100644--- a/packages/views/onboarding/steps/step-question.tsx+++ b/packages/views/onboarding/steps/step-question.tsx@@ -34,8 +34,8 @@ export interface QuestionOption {* 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 multi-select (`multiSelect=true` — Source, Use case). The+ * 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.@@ -99,9 +99,9 @@ export function StepQuestion({// 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 Other can stack with regular picks; we treat the- // non-Other selections as sufficient to advance even if Other's- // text is empty.+ // 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,);@@ -114,8 +114,9 @@ export function StepQuestion({};// Footer label:- // - single select: name the picked option ("hint_selected").- // - multi-select with 1 pick: same.+ // - 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").diff --git a/packages/views/onboarding/steps/step-source.test.tsx b/packages/views/onboarding/steps/step-source.test.tsxindex 37a39b0dbf..447834127e 100644--- a/packages/views/onboarding/steps/step-source.test.tsx+++ b/packages/views/onboarding/steps/step-source.test.tsx@@ -41,54 +41,41 @@ function renderStep(answers: QuestionnaireAnswers = EMPTY) {return { onChange, onAdvance, onSkip, onBack };}-describe("StepSource (multi-select)", () => {+describe("StepSource (single-select primary source)", () => {beforeEach(() => vi.restoreAllMocks());- it("clicking a non-Other option appends the slug to the array", async () => {+ 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("checkbox", { name: /linkedin/i }));+ 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("clicking an already-selected option removes it (toggle)", async () => {+ 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("checkbox", { name: /linkedin/i }));+ await user.click(screen.getByRole("radio", { name: /twitter/i }));expect(onChange).toHaveBeenCalledWith({- source: [],- source_skipped: false,- });- });-- it("multi-select stacks several picks", async () => {- const user = userEvent.setup();- const { onChange } = renderStep({- ...EMPTY,- source: ["social_linkedin"],- });-- await user.click(screen.getByRole("checkbox", { name: /twitter/i }));-- expect(onChange).toHaveBeenCalledWith({- source: ["social_linkedin", "social_x"],+ source: ["social_x"],+ source_other: null,source_skipped: false,});});- it("Skip clears the array + other and marks the step skipped, then calls onSkip", async () => {+ it("Skip clears source + source_other and marks the step skipped, then calls onSkip", async () => {const user = userEvent.setup();const { onChange, onSkip } = renderStep();@@ -102,14 +89,15 @@ describe("StepSource (multi-select)", () => {expect(onSkip).toHaveBeenCalledTimes(1);});- it("Other: clicking adds 'other' to the array; free-text writes to source_other", async () => {+ 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("checkbox", { name: /^other$/i }));+ await user.click(screen.getByRole("radio", { name: /^other$/i }));expect(onChange).toHaveBeenCalledWith({source: ["other"],+ source_other: null,source_skipped: false,});@@ -117,4 +105,21 @@ describe("StepSource (multi-select)", () => {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.tsxindex a9f9e732b4..fa9476fff1 100644--- a/packages/views/onboarding/steps/step-source.tsx+++ b/packages/views/onboarding/steps/step-source.tsx@@ -56,41 +56,25 @@ export function StepSource({{ slug: "other", icon: <MoreHorizontal className="h-4 w-4" />, label: t(($) => $.questions.source.other), isOther: true },];- // Multi-select: source already had several "yes I heard via X" intents- // collapsed into a single radio pick. Letting users tick multiple- // channels keeps attribution honest without making them rank them.- // `other` is a Source enum value so it stacks into the array alongside- // regular picks; the free-text input lives in `source_other`.- const selected: readonly string[] = [- ...(answers.source ?? []),- ...(!answers.source?.includes("other") && answers.source_other- ? ["other"]- : []),- ];+ // 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 toggle = (slug: string) => {- const current = answers.source ?? [];- if (slug === "other") {- // Toggling Other: add/remove from the array; clear the text when- // removing so a re-tick starts from an empty input.- if (current.includes("other")) {- onChange({- source: current.filter((s) => s !== "other"),- source_other: null,- });- } else {- onChange({- source: [...current, "other"],- source_skipped: false,- });- }- return;- }+ const pick = (slug: string) => {const typed = slug as Source;- const next = current.includes(typed)- ? current.filter((s) => s !== typed)- : [...current, typed];- onChange({ source: next, source_skipped: false });+ 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 (@@ -104,14 +88,13 @@ export function StepSource({otherValue={answers.source_other ?? ""}onOtherChange={(v) => onChange({ source_other: v })}otherPlaceholder={t(($) => $.questions.source.other_placeholder)}- onAnswer={toggle}+ onAnswer={pick}onAdvance={onAdvance}onSkip={() => {onChange({ source: [], source_other: null, source_skipped: true });onSkip();}}onBack={onBack}- multiSelect/>);}diff --git a/server/internal/analytics/events.go b/server/internal/analytics/events.goindex cfdaf8fccf..fc9f596852 100644--- a/server/internal/analytics/events.go+++ b/server/internal/analytics/events.go@@ -394,9 +394,11 @@ func TeamInviteAccepted(inviteeID, workspaceID string, daysSinceInvite int64) Ev// The handler drives this transition — we emit from PatchOnboarding so// the single emission site stays honest even if the frontend retries.//-// `source` and `useCase` are multi-select (users can pick several);-// `role` stays single-select. Empty slice = no answer (skip is-// captured separately via the *Skipped booleans).+// `useCase` is multi-select (users can pick several); `source` is+// single-select (primary acquisition channel) but kept as a slice+// for back-compat with v2 multi-select rows — single-element in+// current data. `role` stays single-select. Empty slice = no answer+// (skip is captured separately via the *Skipped booleans).//// The three answers are also mirrored into person properties via $set// so cohorting by source / role / use_case works across every eventdiff --git a/server/internal/handler/onboarding.go b/server/internal/handler/onboarding.goindex 2829162830..3966aec5f2 100644--- a/server/internal/handler/onboarding.go+++ b/server/internal/handler/onboarding.go@@ -130,10 +130,13 @@ type patchOnboardingRequest struct {}// questionnaireAnswers mirrors the frontend's `QuestionnaireAnswers`-// shape. Source and use_case are multi-select arrays (Step 1 + Step 3-// allow picking several); role stays single-select.+// shape. `use_case` is multi-select (Step 3 allows picking several);+// `source` is single-select (primary acquisition channel) but kept+// as `stringOrSlice` for back-compat with v2 multi-select rows — the+// client now always commits a one-element array. `role` stays+// single-select.//-// stringOrSlice tolerates pre-multi-select rows that wrote a bare+// stringOrSlice also tolerates pre-array rows that wrote a bare// string into the JSONB column — `json.Unmarshal` would otherwise// fail on type mismatch when reading those back.type stringOrSlice []string@@ -150,8 +153,8 @@ func (s *stringOrSlice) UnmarshalJSON(data []byte) error {*s = arrreturn nil}- // Fall back to single string (legacy shape from before this column- // went multi-select). Empty string means "unanswered" — keep nil.+ // Fall back to single string (pre-array shape from before this+ // column held a slice). Empty string means "unanswered" — keep nil.var single stringif err := json.Unmarshal(data, &single); err != nil {return err