Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(onboarding): decouple from workspace state and route invitees correctly (#1936)
Naiyuan Qing51bc5a818fac
diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsxindex 2084d38c63..9718c55820 100644--- a/apps/desktop/src/renderer/src/App.tsx+++ b/apps/desktop/src/renderer/src/App.tsx@@ -110,22 +110,58 @@ function AppContent() {: undefined;useDaemonIPCBridge(activeWsId);- // Workspace presence wins over onboarding state: a user invited into an- // existing workspace must enter that workspace, not be trapped in the- // onboarding overlay just because their personal `onboarded_at` is null.- // Onboarding is only the right destination when the account has zero- // workspaces AND has never onboarded.+ // Pre-workspace overlay routing for desktop. Mirrors the web entry-point+ // judgment in callback / login:+ // un-onboarded:+ // pending invites on email → /invitations overlay+ // no invites → /onboarding overlay+ // already onboarded:+ // zero workspaces → /workspaces/new overlay+ // ≥1 workspaces → no overlay, fall through to dashboard+ //+ // The "un-onboarded but in workspace" state is now physically impossible+ // because backend transactions atomically set onboarded_at when a user+ // joins the `member` table. Anyone with workspaces is by definition+ // onboarded.useEffect(() => {- if (!user || !workspaceListFetched) return;+ if (!user || !workspaceListFetched) return undefined;const { overlay, open } = useWindowOverlayStore.getState();- if (overlay) return;- if (wsCount > 0) return;+ if (overlay) return undefined;+ if (wsCount > 0) return undefined;if (!hasOnboarded) {- open({ type: "onboarding" });- } else {- open({ type: "new-workspace" });+ // Look up pending invitations by email. Network blip is non-fatal —+ // fall through to onboarding so the user isn't stuck on a blank+ // window. The sidebar's pending-invitations dropdown will surface+ // missed invites later once they're onboarded.+ let cancelled = false;+ void api+ .listMyInvitations()+ .then((invites) => {+ if (cancelled) return;+ const { overlay: latestOverlay, open: latestOpen } =+ useWindowOverlayStore.getState();+ if (latestOverlay) return;+ if (invites.length > 0) {+ qc.setQueryData(workspaceKeys.myInvitations(), invites);+ latestOpen({ type: "invitations" });+ } else {+ latestOpen({ type: "onboarding" });+ }+ })+ .catch(() => {+ if (cancelled) return;+ const { overlay: latestOverlay, open: latestOpen } =+ useWindowOverlayStore.getState();+ if (latestOverlay) return;+ latestOpen({ type: "onboarding" });+ });+ return () => {+ cancelled = true;+ };}- }, [user, workspaceListFetched, wsCount, workspaces, hasOnboarded]);+ open({ type: "new-workspace" });+ 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 useLayoutEffectdiff --git a/apps/desktop/src/renderer/src/components/pageview-tracker.tsx b/apps/desktop/src/renderer/src/components/pageview-tracker.tsxindex abaf2b9019..2c07e42f90 100644--- a/apps/desktop/src/renderer/src/components/pageview-tracker.tsx+++ b/apps/desktop/src/renderer/src/components/pageview-tracker.tsx@@ -65,5 +65,7 @@ function overlayPath(overlay: WindowOverlay): string {return "/onboarding";case "invite":return `/invite/${overlay.invitationId}`;+ case "invitations":+ return "/invitations";}}diff --git a/apps/desktop/src/renderer/src/components/window-overlay.tsx b/apps/desktop/src/renderer/src/components/window-overlay.tsxindex 99dfe37027..b8d0bb715e 100644--- a/apps/desktop/src/renderer/src/components/window-overlay.tsx+++ b/apps/desktop/src/renderer/src/components/window-overlay.tsx@@ -1,6 +1,7 @@import { useQuery } from "@tanstack/react-query";import { NewWorkspacePage } from "@multica/views/workspace/new-workspace-page";import { InvitePage } from "@multica/views/invite";+import { InvitationsPage } from "@multica/views/invitations";import { OnboardingFlow } from "@multica/views/onboarding";import { useNavigation } from "@multica/views/navigation";import { paths } from "@multica/core/paths";@@ -58,6 +59,7 @@ function WindowOverlayInner() {onBack={onBack}/>)}+ {overlay.type === "invitations" && <InvitationsPage />}{overlay.type === "onboarding" && (<OnboardingFlowonComplete={(ws) => {diff --git a/apps/desktop/src/renderer/src/platform/navigation.tsx b/apps/desktop/src/renderer/src/platform/navigation.tsxindex 494916ed59..729071cf5f 100644--- a/apps/desktop/src/renderer/src/platform/navigation.tsx+++ b/apps/desktop/src/renderer/src/platform/navigation.tsx@@ -61,6 +61,13 @@ function tryRouteToOverlay(path: string, router?: DataRouter): boolean {}return true;}+ if (path === "/invitations") {+ overlay.open({ type: "invitations" });+ if (router && router.state.location.pathname !== "/") {+ router.navigate("/", { replace: true });+ }+ return true;+ }if (path.startsWith("/invite/")) {let id = "";try {diff --git a/apps/desktop/src/renderer/src/stores/window-overlay-store.ts b/apps/desktop/src/renderer/src/stores/window-overlay-store.tsindex 2041d5b63d..78aefe0512 100644--- a/apps/desktop/src/renderer/src/stores/window-overlay-store.ts+++ b/apps/desktop/src/renderer/src/stores/window-overlay-store.ts@@ -15,6 +15,7 @@ import { create } from "zustand";export type WindowOverlay =| { type: "new-workspace" }| { type: "invite"; invitationId: string }+ | { type: "invitations" }| { type: "onboarding" };interface WindowOverlayStore {diff --git a/apps/web/app/(auth)/invitations/page.tsx b/apps/web/app/(auth)/invitations/page.tsxnew file mode 100644index 0000000000..54efecad1f--- /dev/null+++ b/apps/web/app/(auth)/invitations/page.tsx@@ -0,0 +1,28 @@+"use client";++import { useEffect } from "react";+import { useRouter } from "next/navigation";+import { useAuthStore } from "@multica/core/auth";+import { paths } from "@multica/core/paths";+import { InvitationsPage } from "@multica/views/invitations";++export default function InvitationsRoutePage() {+ const router = useRouter();+ const user = useAuthStore((s) => s.user);+ const isLoading = useAuthStore((s) => s.isLoading);++ // Unauthenticated users have nowhere meaningful to land here — kick them+ // through login and bring them back. The login page will eventually run+ // its own listMyInvitations() check and route them here again.+ useEffect(() => {+ if (!isLoading && !user) {+ router.replace(+ `${paths.login()}?next=${encodeURIComponent(paths.invitations())}`,+ );+ }+ }, [isLoading, user, router]);++ if (isLoading || !user) return null;++ return <InvitationsPage />;+}diff --git a/apps/web/app/(auth)/login/page.tsx b/apps/web/app/(auth)/login/page.tsxindex 7115fac21f..4fbbe9e1f2 100644--- a/apps/web/app/(auth)/login/page.tsx+++ b/apps/web/app/(auth)/login/page.tsx@@ -2,7 +2,7 @@import { Suspense, useEffect, useState } from "react";import { useSearchParams, useRouter } from "next/navigation";-import { useQueryClient } from "@tanstack/react-query";+import { useQueryClient, type QueryClient } from "@tanstack/react-query";import { sanitizeNextUrl, useAuthStore } from "@multica/core/auth";import { useConfigStore } from "@multica/core/config";import { workspaceKeys } from "@multica/core/workspace/queries";@@ -27,6 +27,32 @@ import { setLoggedInCookie } from "@/features/auth/auth-cookie";import Link from "next/link";import { LoginPage, validateCliCallback } from "@multica/views/auth";+/**+ * Pick where a logged-in user with no explicit `?next=` should land.+ * Un-onboarded users with pending invitations on their email get routed to+ * the batch /invitations page; everyone else falls through to the standard+ * resolver. A network blip on listMyInvitations is non-fatal — we fall+ * through rather than trap the user on an error screen.+ */+async function resolveLoggedInDestination(+ qc: QueryClient,+ hasOnboarded: boolean,+ workspaces: Workspace[],+): Promise<string> {+ if (!hasOnboarded) {+ try {+ const invites = await api.listMyInvitations();+ if (invites.length > 0) {+ qc.setQueryData(workspaceKeys.myInvitations(), invites);+ return paths.invitations();+ }+ } catch {+ // fall through+ }+ }+ return resolvePostAuthDestination(workspaces, hasOnboarded);+}+function LoginPageContent() {const router = useRouter();const qc = useQueryClient();@@ -77,10 +103,12 @@ function LoginPageContent() {return;}const list = qc.getQueryData<Workspace[]>(workspaceKeys.list()) ?? [];- router.replace(resolvePostAuthDestination(list, hasOnboarded));+ void resolveLoggedInDestination(qc, hasOnboarded, list).then((dest) =>+ router.replace(dest),+ );}, [isLoading, user, router, nextUrl, cliCallbackRaw, isDesktopHandoff, hasOnboarded, qc]);- const handleSuccess = () => {+ const handleSuccess = async () => {// Read the latest user snapshot directly — the closure's `hasOnboarded`// was captured before login completed and would be stale here.const currentUser = useAuthStore.getState().user;@@ -90,7 +118,8 @@ function LoginPageContent() {return;}const list = qc.getQueryData<Workspace[]>(workspaceKeys.list()) ?? [];- router.push(resolvePostAuthDestination(list, onboarded));+ const dest = await resolveLoggedInDestination(qc, onboarded, list);+ router.push(dest);};// Build Google OAuth state: encode platform + next URL so the callbackdiff --git a/apps/web/app/(auth)/onboarding/page.tsx b/apps/web/app/(auth)/onboarding/page.tsxindex 7a3e567267..43a944ae51 100644--- a/apps/web/app/(auth)/onboarding/page.tsx+++ b/apps/web/app/(auth)/onboarding/page.tsx@@ -34,7 +34,6 @@ export default function OnboardingPage() {...workspaceListOptions(),enabled: !!user,});- const hasWorkspaces = workspaces.length > 0;useEffect(() => {if (isLoading || !user) {@@ -42,15 +41,19 @@ export default function OnboardingPage() {return;}if (!workspacesFetched) return;- // Bounce out if onboarding doesn't apply: either already onboarded, or- // the user already has a workspace (e.g. arrived via invitation) — we- // never trap an in-workspace user on the onboarding screen.- if (hasOnboarded || hasWorkspaces) {+ // Bounce out only when onboarding genuinely doesn't apply: the user is+ // already onboarded. We deliberately don't bounce on `workspaces.length`+ // here — Step 3 of the flow creates a workspace mid-onboarding, and a+ // hasWorkspaces bounce here would kick the user out before Steps 4–5+ // (runtime / agent / first issue) can run. The new entry-point+ // judgment in callback / login handles "where should this user go on+ // login" so OnboardingPage no longer needs to second-guess it.+ if (hasOnboarded) {router.replace(resolvePostAuthDestination(workspaces, hasOnboarded));}- }, [isLoading, user, hasOnboarded, workspacesFetched, workspaces, hasWorkspaces, router]);+ }, [isLoading, user, hasOnboarded, workspacesFetched, workspaces, router]);- if (isLoading || !user || hasOnboarded || hasWorkspaces) return null;+ if (isLoading || !user || hasOnboarded) return null;// Layout: page owns its own scroll (root layout sets `body {// overflow: hidden }` for the app-shell convention). OnboardingFlowdiff --git a/apps/web/app/auth/callback/page.test.tsx b/apps/web/app/auth/callback/page.test.tsxindex 87b4cea549..6e612d6468 100644--- a/apps/web/app/auth/callback/page.test.tsx+++ b/apps/web/app/auth/callback/page.test.tsx@@ -2,13 +2,21 @@ import { describe, it, expect, vi, beforeEach } from "vitest";import { render, waitFor } from "@testing-library/react";import { paths } from "@multica/core/paths";-const { mockPush, mockSearchParams, mockLoginWithGoogle, mockListWorkspaces } =- vi.hoisted(() => ({- mockPush: vi.fn(),- mockSearchParams: new URLSearchParams(),- mockLoginWithGoogle: vi.fn(),- mockListWorkspaces: vi.fn(),- }));+const {+ mockPush,+ mockSearchParams,+ mockLoginWithGoogle,+ mockListWorkspaces,+ mockListMyInvitations,+ mockSetQueryData,+} = vi.hoisted(() => ({+ mockPush: vi.fn(),+ mockSearchParams: new URLSearchParams(),+ mockLoginWithGoogle: vi.fn(),+ mockListWorkspaces: vi.fn(),+ mockListMyInvitations: vi.fn(),+ mockSetQueryData: vi.fn(),+}));const makeUser = (overrides: Partial<{ onboarded_at: string | null }> = {}) => ({id: "user-1",@@ -28,7 +36,7 @@ vi.mock("next/navigation", () => ({}));vi.mock("@tanstack/react-query", () => ({- useQueryClient: () => ({ setQueryData: vi.fn() }),+ useQueryClient: () => ({ setQueryData: mockSetQueryData }),}));// Preserve the real sanitizeNextUrl so the "drop unsafe ?next=" behavior is@@ -46,12 +54,16 @@ vi.mock("@multica/core/auth", async () => {});vi.mock("@multica/core/workspace/queries", () => ({- workspaceKeys: { list: () => ["workspaces"] },+ workspaceKeys: {+ list: () => ["workspaces"],+ myInvitations: () => ["invitations", "mine"],+ },}));vi.mock("@multica/core/api", () => ({api: {listWorkspaces: mockListWorkspaces,+ listMyInvitations: mockListMyInvitations,googleLogin: vi.fn(),},}));@@ -69,6 +81,7 @@ describe("CallbackPage", () => {mockSearchParams.set("code", "test-code");mockLoginWithGoogle.mockResolvedValue(makeUser());mockListWorkspaces.mockResolvedValue([]);+ mockListMyInvitations.mockResolvedValue([]);});it("unonboarded user honors a safe next= (e.g. /invite/{id}) so invitees aren't trapped", async () => {@@ -78,16 +91,39 @@ describe("CallbackPage", () => {expect(mockPush).toHaveBeenCalledWith("/invite/abc123");});expect(mockPush).not.toHaveBeenCalledWith(paths.onboarding());+ // nextUrl is a fast path — listMyInvitations should not be queried.+ expect(mockListMyInvitations).not.toHaveBeenCalled();});- it("unonboarded user with no next= and zero workspaces lands on /onboarding", async () => {+ it("unonboarded user with no next= and no pending invitations lands on /onboarding", async () => {render(<CallbackPage />);await waitFor(() => {expect(mockPush).toHaveBeenCalledWith(paths.onboarding());});+ expect(mockListMyInvitations).toHaveBeenCalled();+ });++ it("unonboarded user with pending invitations lands on /invitations", async () => {+ mockListMyInvitations.mockResolvedValue([+ {+ id: "inv-1",+ workspace_id: "ws-1",+ workspace_name: "Acme",+ role: "member",+ status: "pending",+ },+ ]);+ render(<CallbackPage />);+ await waitFor(() => {+ expect(mockPush).toHaveBeenCalledWith(paths.invitations());+ });+ expect(mockPush).not.toHaveBeenCalledWith(paths.onboarding());});- it("unonboarded user with existing workspace lands in that workspace, not /onboarding", async () => {+ it("onboarded user with workspace lands in that workspace", async () => {+ mockLoginWithGoogle.mockResolvedValue(+ makeUser({ onboarded_at: "2026-01-01T00:00:00Z" }),+ );mockListWorkspaces.mockResolvedValue([{id: "ws-1",@@ -106,7 +142,9 @@ describe("CallbackPage", () => {await waitFor(() => {expect(mockPush).toHaveBeenCalledWith(paths.workspace("acme").issues());});- expect(mockPush).not.toHaveBeenCalledWith(paths.onboarding());+ // Already-onboarded users skip the listMyInvitations check; new invites+ // surface in the sidebar instead of the wall.+ expect(mockListMyInvitations).not.toHaveBeenCalled();});it("onboarded user ignores unsafe next= targets and lands on the default destination", async () => {@@ -135,4 +173,12 @@ describe("CallbackPage", () => {expect(mockPush).toHaveBeenCalledWith("/invite/abc123");});});++ it("falls through to /onboarding when listMyInvitations errors", async () => {+ mockListMyInvitations.mockRejectedValue(new Error("network"));+ render(<CallbackPage />);+ await waitFor(() => {+ expect(mockPush).toHaveBeenCalledWith(paths.onboarding());+ });+ });});diff --git a/apps/web/app/auth/callback/page.tsx b/apps/web/app/auth/callback/page.tsxindex d68befca30..b6e730d6a3 100644--- a/apps/web/app/auth/callback/page.tsx+++ b/apps/web/app/auth/callback/page.tsx@@ -66,13 +66,42 @@ function CallbackContent() {const wsList = await api.listWorkspaces();qc.setQueryData(workspaceKeys.list(), wsList);const onboarded = loggedInUser.onboarded_at != null;- // Workspace presence beats onboarding state: an invitee with zero- // `onboarded_at` but a real workspace must land in that workspace,- // not in the new-workspace wizard. A `next=` (e.g. /invite/<id>)- // always wins so invite acceptance flows survive auth round-trips.- router.push(- nextUrl || resolvePostAuthDestination(wsList, onboarded),- );++ // 1. nextUrl wins: a `next=/invite/<id>` always survives the OAuth+ // round-trip — the user clicked a specific link and we should+ // honor exactly that destination.+ if (nextUrl) {+ router.push(nextUrl);+ return;+ }++ // 2. Un-onboarded users may have pending invitations on their+ // email even when no `next=` was carried (came from a fresh+ // login on app.multica.ai instead of clicking the email link,+ // or `state` was lost across the round-trip). Look them up by+ // email and route to the batch /invitations page if any.+ // Already-onboarded users skip this lookup — their new invites+ // surface in the sidebar dropdown, not as a forced wall.+ if (!onboarded) {+ try {+ const invites = await api.listMyInvitations();+ if (invites.length > 0) {+ qc.setQueryData(workspaceKeys.myInvitations(), invites);+ router.push(paths.invitations());+ return;+ }+ } catch {+ // Network blip on the invite lookup is non-fatal — fall through+ // to the normal post-auth destination so the user isn't stuck+ // on a blank callback screen. Worst case they land on+ // /onboarding and the sidebar will surface invites later.+ }+ }++ // 3. Default: hand off to the resolver (onboarding for first-timers,+ // first workspace for returning users, /workspaces/new for+ // onboarded users with zero workspaces).+ router.push(resolvePostAuthDestination(wsList, onboarded));}).catch((err) => {setError(err instanceof Error ? err.message : "Login failed");diff --git a/packages/core/onboarding/types.ts b/packages/core/onboarding/types.tsindex 1ab9c42e60..192cc48762 100644--- a/packages/core/onboarding/types.ts+++ b/packages/core/onboarding/types.ts@@ -16,7 +16,8 @@ export type OnboardingCompletionPath =| "full" // Reached Step 5 (first_issue) with a runtime connected| "runtime_skipped" // Step 3 skipped (no runtime) but still completed| "cloud_waitlist" // Submitted the cloud waitlist form and skipped Step 3- | "skip_existing"; // "I've done this before" from Welcome+ | "skip_existing" // "I've done this before" from Welcome+ | "invite_accept"; // Accepted at least one invite from /invitationsexport type TeamSize = "solo" | "team" | "other";diff --git a/packages/core/paths/paths.ts b/packages/core/paths/paths.tsindex 27b0b3cd37..e911fa408b 100644--- a/packages/core/paths/paths.ts+++ b/packages/core/paths/paths.ts@@ -43,6 +43,7 @@ export const paths = {login: () => "/login",newWorkspace: () => "/workspaces/new",invite: (id: string) => `/invite/${encode(id)}`,+ invitations: () => "/invitations",onboarding: () => "/onboarding",authCallback: () => "/auth/callback",root: () => "/",@@ -54,7 +55,7 @@ export type WorkspacePaths = ReturnType<typeof workspaceScoped>;// A path is global if it equals or begins with any of these.// Note: `/workspaces/` (trailing slash) is the prefix — `workspaces` is reserved,// so any path starting with `/workspaces/...` is system-owned, not user-owned.-const GLOBAL_PREFIXES = ["/login", "/workspaces/", "/invite/", "/onboarding", "/auth/", "/logout", "/signup"];+const GLOBAL_PREFIXES = ["/login", "/workspaces/", "/invite/", "/invitations", "/onboarding", "/auth/", "/logout", "/signup"];export function isGlobalPath(path: string): boolean {return GLOBAL_PREFIXES.some((p) => path === p || path.startsWith(p));diff --git a/packages/core/paths/reserved-slugs.ts b/packages/core/paths/reserved-slugs.tsindex caa2fe1487..15c8235427 100644--- a/packages/core/paths/reserved-slugs.ts+++ b/packages/core/paths/reserved-slugs.ts@@ -20,6 +20,7 @@ export const RESERVED_SLUGS = new Set(["oauth","callback","invite",+ "invitations","verify","reset","password",diff --git a/packages/core/paths/resolve.test.ts b/packages/core/paths/resolve.test.tsindex ba6992ac79..33072dbb41 100644--- a/packages/core/paths/resolve.test.ts+++ b/packages/core/paths/resolve.test.ts@@ -19,24 +19,26 @@ function makeWs(slug: string): Workspace {}describe("resolvePostAuthDestination", () => {- it("has workspace → /<first.slug>/issues regardless of onboarded state", () => {- const ws = [makeWs("acme"), makeWs("beta")];- expect(resolvePostAuthDestination(ws, true)).toBe(- paths.workspace("acme").issues(),- );- expect(resolvePostAuthDestination(ws, false)).toBe(- paths.workspace("acme").issues(),- );+ it("!onboarded → /onboarding regardless of workspace count", () => {+ // Un-onboarded users are routed back to the onboarding flow. The+ // "un-onboarded but in workspace" state is now physically impossible+ // (backend invariant + migration 065 backfill), but the resolver still+ // does the right thing if it ever appears: send the user to onboarding+ // rather than dropping them into a workspace with `onboarded_at` null.+ expect(resolvePostAuthDestination([], false)).toBe(paths.onboarding());expect(resolvePostAuthDestination([makeWs("acme")], false)).toBe(- paths.workspace("acme").issues(),+ paths.onboarding(),);});- it("zero workspaces + !onboarded → /onboarding", () => {- expect(resolvePostAuthDestination([], false)).toBe(paths.onboarding());+ it("onboarded + has workspace → /<first.slug>/issues", () => {+ const ws = [makeWs("acme"), makeWs("beta")];+ expect(resolvePostAuthDestination(ws, true)).toBe(+ paths.workspace("acme").issues(),+ );});- it("zero workspaces + onboarded → /workspaces/new", () => {+ it("onboarded + zero workspaces → /workspaces/new", () => {expect(resolvePostAuthDestination([], true)).toBe(paths.newWorkspace());});});diff --git a/packages/core/paths/resolve.ts b/packages/core/paths/resolve.tsindex e380d9ffa9..69cf41c1db 100644--- a/packages/core/paths/resolve.ts+++ b/packages/core/paths/resolve.ts@@ -4,23 +4,34 @@ import { paths } from "./paths";/*** Priority:- * has workspace → /<first.slug>/issues- * zero workspaces && !hasOnboarded → /onboarding- * zero workspaces && hasOnboarded → /workspaces/new+ * !hasOnboarded → /onboarding+ * hasOnboarded && has workspace → /<first.slug>/issues+ * hasOnboarded && zero workspaces → /workspaces/new*- * Workspace presence wins over onboarding state: a user invited into an- * existing workspace must NOT be bounced into the new-workspace wizard- * just because their personal `onboarded_at` is still null.+ * `onboarded_at` is the single source of truth for whether the user has+ * passed first-contact. Backend transactions (CreateWorkspace,+ * AcceptInvitation) atomically set this field whenever a user joins a+ * `member` row, so "has workspace but !onboarded" is now a+ * physically impossible state — see migration 065 for the existing-data+ * backfill that closed the door retroactively.+ *+ * Callers that need invitation-aware routing (callback / login) handle the+ * "un-onboarded with pending invites" branch themselves before calling+ * this resolver — this resolver only deals with the post-invite-check+ * destination.*/export function resolvePostAuthDestination(workspaces: Workspace[],hasOnboarded: boolean,): string {+ if (!hasOnboarded) {+ return paths.onboarding();+ }const first = workspaces[0];if (first) {return paths.workspace(first.slug).issues();}- return hasOnboarded ? paths.newWorkspace() : paths.onboarding();+ return paths.newWorkspace();}/**diff --git a/packages/views/invitations/index.ts b/packages/views/invitations/index.tsnew file mode 100644index 0000000000..f1dd868352--- /dev/null+++ b/packages/views/invitations/index.ts@@ -0,0 +1 @@+export { InvitationsPage } from "./invitations-page";diff --git a/packages/views/invitations/invitations-page.test.tsx b/packages/views/invitations/invitations-page.test.tsxnew file mode 100644index 0000000000..acdd30d431--- /dev/null+++ b/packages/views/invitations/invitations-page.test.tsx@@ -0,0 +1,170 @@+import { describe, expect, it, vi, beforeEach } from "vitest";+import { render, screen, waitFor, fireEvent } from "@testing-library/react";+import {+ QueryClient,+ QueryClientProvider,+} from "@tanstack/react-query";++const {+ navigate,+ logout,+ refreshMe,+ acceptInvitation,+ markOnboardingComplete,+ listMyInvitations,+ listWorkspaces,+} = vi.hoisted(() => ({+ navigate: vi.fn(),+ logout: vi.fn(),+ refreshMe: vi.fn(),+ acceptInvitation: vi.fn(),+ markOnboardingComplete: vi.fn(),+ listMyInvitations: vi.fn(),+ listWorkspaces: vi.fn(),+}));++vi.mock("../navigation", () => ({+ useNavigation: () => ({ push: navigate, replace: navigate }),+}));++vi.mock("../auth", () => ({+ useLogout: () => logout,+}));++vi.mock("../platform", () => ({+ DragStrip: () => null,+}));++vi.mock("@multica/core/auth", () => ({+ useAuthStore: Object.assign(+ (selector?: (s: unknown) => unknown) => {+ const state = { refreshMe };+ return selector ? selector(state) : state;+ },+ {+ getState: () => ({ refreshMe }),+ },+ ),+}));++vi.mock("@multica/core/api", () => ({+ api: {+ acceptInvitation,+ markOnboardingComplete,+ listMyInvitations,+ listWorkspaces,+ },+}));++import { InvitationsPage } from "./invitations-page";++function renderWithClient(client: QueryClient = new QueryClient()) {+ return render(+ <QueryClientProvider client={client}>+ <InvitationsPage />+ </QueryClientProvider>,+ );+}++const mkInvite = (id: string, wsId: string, wsName: string) => ({+ id,+ workspace_id: wsId,+ inviter_id: "u-2",+ invitee_email: "[email protected]",+ invitee_user_id: null,+ role: "member" as const,+ status: "pending" as const,+ created_at: "",+ updated_at: "",+ expires_at: "",+ workspace_name: wsName,+ inviter_name: "Alice",+});++const mkWs = (id: string, slug: string) => ({+ id,+ name: slug,+ slug,+ description: null,+ context: null,+ settings: {},+ repos: [],+ issue_prefix: slug.toUpperCase(),+ created_at: "",+ updated_at: "",+});++describe("InvitationsPage", () => {+ beforeEach(() => {+ navigate.mockReset();+ logout.mockReset();+ refreshMe.mockReset();+ acceptInvitation.mockReset();+ markOnboardingComplete.mockReset();+ listMyInvitations.mockReset();+ listWorkspaces.mockReset();+ refreshMe.mockResolvedValue(undefined);+ acceptInvitation.mockResolvedValue({});+ markOnboardingComplete.mockResolvedValue({});+ });++ it("renders pending invitations with workspace names", async () => {+ listMyInvitations.mockResolvedValue([+ mkInvite("inv-1", "ws-1", "Acme"),+ mkInvite("inv-2", "ws-2", "Beta Corp"),+ ]);+ renderWithClient();+ await waitFor(() => {+ expect(screen.getByText("Acme")).toBeInTheDocument();+ expect(screen.getByText("Beta Corp")).toBeInTheDocument();+ });+ });++ it("with no selections, submitting routes to /onboarding", async () => {+ listMyInvitations.mockResolvedValue([mkInvite("inv-1", "ws-1", "Acme")]);+ renderWithClient();+ await waitFor(() => screen.getByText("Acme"));+ fireEvent.click(screen.getByRole("button", { name: /skip/i }));+ expect(navigate).toHaveBeenCalledWith("/onboarding");+ // Empty submit doesn't accept anything or touch onboarding state.+ expect(acceptInvitation).not.toHaveBeenCalled();+ expect(markOnboardingComplete).not.toHaveBeenCalled();+ });++ it("accepts selected invitations, marks onboarded, navigates to first ws", async () => {+ listMyInvitations.mockResolvedValue([+ mkInvite("inv-1", "ws-1", "Acme"),+ mkInvite("inv-2", "ws-2", "Beta"),+ ]);+ listWorkspaces.mockResolvedValue([mkWs("ws-1", "acme"), mkWs("ws-2", "beta")]);+ renderWithClient();++ await waitFor(() => screen.getByText("Acme"));+ // Select Acme via its label/checkbox row.+ fireEvent.click(screen.getByText("Acme"));++ fireEvent.click(screen.getByRole("button", { name: /join 1 workspace/i }));++ await waitFor(() => {+ expect(acceptInvitation).toHaveBeenCalledWith("inv-1");+ expect(markOnboardingComplete).toHaveBeenCalledWith({+ completion_path: "invite_accept",+ });+ expect(refreshMe).toHaveBeenCalled();+ expect(navigate).toHaveBeenCalledWith("/acme/issues");+ });+ });++ it("empty list falls through to onboarding via Continue button", async () => {+ listMyInvitations.mockResolvedValue([]);+ renderWithClient();++ await waitFor(() =>+ screen.getByRole("button", { name: /continue to setup/i }),+ );+ fireEvent.click(+ screen.getByRole("button", { name: /continue to setup/i }),+ );+ expect(navigate).toHaveBeenCalledWith("/onboarding");+ });+});diff --git a/packages/views/invitations/invitations-page.tsx b/packages/views/invitations/invitations-page.tsxnew file mode 100644index 0000000000..f6a08ddacd--- /dev/null+++ b/packages/views/invitations/invitations-page.tsx@@ -0,0 +1,280 @@+"use client";++import { useState, type ReactNode } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { api } from "@multica/core/api";+import { useAuthStore } from "@multica/core/auth";+import {+ myInvitationListOptions,+ workspaceKeys,+ workspaceListOptions,+} from "@multica/core/workspace/queries";+import { paths } from "@multica/core/paths";+import type { Invitation } from "@multica/core/types";+import { useNavigation } from "../navigation";+import { useLogout } from "../auth";+import { DragStrip } from "../platform";+import { Button } from "@multica/ui/components/ui/button";+import { Card, CardContent } from "@multica/ui/components/ui/card";+import { Checkbox } from "@multica/ui/components/ui/checkbox";+import { Skeleton } from "@multica/ui/components/ui/skeleton";+import { LogOut, Mail, Users } from "lucide-react";++/**+ * Batch invitation handling page for first-contact users who land here+ * because callback / login detected pending invitations on their email.+ *+ * Design:+ * - This route is only reachable for un-onboarded users (the entry-point+ * judgment in callback/login routes already-onboarded users straight+ * into their workspace; new invites for those users surface in the+ * sidebar's pending-invitations dropdown instead).+ * - The user picks zero or more invitations to accept. "Submit" then:+ * • zero selected → continue to /onboarding+ * • ≥1 selected → accept each, mark onboarding complete, navigate+ * into the first accepted workspace.+ * - Unselected invitations are intentionally left as `pending` in the DB.+ * The user can later decline them from the sidebar; we don't auto-decline+ * here because closing/refreshing this page should not be a destructive+ * action.+ */+export function InvitationsPage() {+ const { push } = useNavigation();+ const qc = useQueryClient();+ const [selected, setSelected] = useState<Set<string>>(new Set());+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const {+ data: invitations,+ isLoading,+ error: fetchError,+ refetch,+ } = useQuery(myInvitationListOptions());++ const toggle = (id: string) => {+ setSelected((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ };++ const handleSubmit = async () => {+ setError(null);++ // Zero selected: hand off to onboarding. Pending invites stay pending and+ // can be picked up later from the sidebar.+ if (selected.size === 0) {+ push(paths.onboarding());+ return;+ }++ setSubmitting(true);+ const acceptedIds: string[] = [];+ try {+ for (const id of selected) {+ await api.acceptInvitation(id);+ acceptedIds.push(id);+ }++ // markOnboardingComplete is a frontend-side belt to the backend braces:+ // each AcceptInvitation transaction already sets onboarded_at via+ // MarkUserOnboarded, but calling this from the client makes sure the+ // returned `User` is freshly written and gives refreshMe something+ // canonical to read.+ await api.markOnboardingComplete({ completion_path: "invite_accept" });+ await useAuthStore.getState().refreshMe();++ qc.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });+ const wsList = await qc.fetchQuery({+ ...workspaceListOptions(),+ staleTime: 0,+ });++ const firstAcceptedInvite = invitations?.find(+ (inv) => inv.id === acceptedIds[0],+ );+ const targetWs = firstAcceptedInvite+ ? wsList.find((w) => w.id === firstAcceptedInvite.workspace_id)+ : undefined;++ // If we can't resolve the just-accepted workspace by id (shouldn't+ // happen — the backend just inserted the membership and we just+ // refetched), fall back to the resolver. Don't blindly route to+ // wsList[0]: that could teleport the user into an unrelated old+ // workspace they happen to also belong to.+ push(+ targetWs ? paths.workspace(targetWs.slug).issues() : paths.newWorkspace(),+ );+ } catch (e) {+ setError(+ e instanceof Error+ ? e.message+ : "Failed to process invitations. Please try again.",+ );+ // Partial success: any accepts that landed before the failure ALREADY+ // set onboarded_at on the backend (the AcceptInvitation transaction+ // is atomic per invite). Refresh local user + workspace state so the+ // sidebar reflects the partial accept and the user isn't stuck with a+ // stale `onboarded_at == null` view. The next submit is safe — the+ // server returns 4xx on re-accept and the catch path will surface that.+ if (acceptedIds.length > 0) {+ await useAuthStore.getState().refreshMe().catch(() => {});+ qc.invalidateQueries({ queryKey: workspaceKeys.list() });+ }+ qc.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });+ refetch();+ } finally {+ setSubmitting(false);+ }+ };++ if (isLoading) {+ return (+ <InvitationsShell>+ <Card className="w-full max-w-lg">+ <CardContent className="flex flex-col gap-4 py-12">+ <Skeleton className="h-6 w-48" />+ <Skeleton className="h-4 w-72" />+ <Skeleton className="h-16 w-full" />+ <Skeleton className="h-16 w-full" />+ </CardContent>+ </Card>+ </InvitationsShell>+ );+ }++ // Empty / error: send the user on to onboarding so they're never stuck.+ // Genuine fetch failure is rare; treating it as "no invites" is safer than+ // trapping the user on an error screen they can't act on.+ if (fetchError || !invitations || invitations.length === 0) {+ return (+ <InvitationsShell>+ <Card className="w-full max-w-md">+ <CardContent className="flex flex-col items-center gap-4 py-12">+ <div className="flex h-12 w-12 items-center justify-center rounded-full bg-muted">+ <Mail className="h-6 w-6 text-muted-foreground" />+ </div>+ <h2 className="text-lg font-semibold">No pending invitations</h2>+ <p className="text-sm text-muted-foreground text-center">+ Continue to set up your own workspace.+ </p>+ <Button onClick={() => push(paths.onboarding())}>+ Continue to setup+ </Button>+ </CardContent>+ </Card>+ </InvitationsShell>+ );+ }++ const submitLabel =+ selected.size === 0+ ? "Skip and set up my own workspace"+ : selected.size === 1+ ? "Join 1 workspace"+ : `Join ${selected.size} workspaces`;++ return (+ <InvitationsShell>+ <Card className="w-full max-w-lg">+ <CardContent className="flex flex-col gap-6 py-10">+ <div className="flex flex-col items-center gap-3 text-center">+ <div className="flex h-12 w-12 items-center justify-center rounded-full bg-primary/10">+ <Users className="h-6 w-6 text-primary" />+ </div>+ <div className="space-y-1">+ <h2 className="text-xl font-semibold">+ You've been invited+ </h2>+ <p className="text-sm text-muted-foreground">+ Pick the workspaces you want to join. You can always handle the+ rest later from the sidebar.+ </p>+ </div>+ </div>++ <ul className="flex flex-col gap-2">+ {invitations.map((inv) => (+ <InvitationRow+ key={inv.id}+ invitation={inv}+ checked={selected.has(inv.id)}+ onToggle={() => toggle(inv.id)}+ />+ ))}+ </ul>++ <Button+ className="w-full"+ onClick={handleSubmit}+ disabled={submitting}+ >+ {submitting ? "Joining..." : submitLabel}+ </Button>++ {error && (+ <p className="text-sm text-destructive text-center">{error}</p>+ )}+ </CardContent>+ </Card>+ </InvitationsShell>+ );+}++function InvitationRow({+ invitation,+ checked,+ onToggle,+}: {+ invitation: Invitation;+ checked: boolean;+ onToggle: () => void;+}) {+ const inviter = invitation.inviter_name || invitation.inviter_email || "Someone";+ return (+ <li>+ <label+ className="flex cursor-pointer items-start gap-3 rounded-md border border-border bg-card p-4 hover:bg-accent/40"+ >+ <Checkbox+ checked={checked}+ onCheckedChange={onToggle}+ className="mt-1"+ />+ <div className="flex-1 min-w-0 space-y-1">+ <div className="font-medium truncate">+ {invitation.workspace_name ?? "Workspace"}+ </div>+ <div className="text-xs text-muted-foreground truncate">+ {inviter} invited you as{" "}+ {invitation.role === "admin" ? "an admin" : "a member"}+ </div>+ </div>+ </label>+ </li>+ );+}++function InvitationsShell({ children }: { children: ReactNode }) {+ const logout = useLogout();+ return (+ <div className="relative flex min-h-svh flex-col bg-background">+ <DragStrip />+ <Button+ variant="ghost"+ size="sm"+ className="absolute top-16 right-12 text-muted-foreground hover:text-destructive"+ onClick={logout}+ >+ <LogOut />+ Log out+ </Button>+ <div className="flex flex-1 flex-col items-center justify-center px-6 pb-12">+ {children}+ </div>+ </div>+ );+}diff --git a/packages/views/invite/invite-page.tsx b/packages/views/invite/invite-page.tsxindex 8438fe78b8..4c236c8562 100644--- a/packages/views/invite/invite-page.tsx+++ b/packages/views/invite/invite-page.tsx@@ -3,6 +3,7 @@import { useState, type ReactNode } from "react";import { useQuery, useQueryClient } from "@tanstack/react-query";import { api } from "@multica/core/api";+import { useAuthStore } from "@multica/core/auth";import {workspaceKeys,workspaceListOptions,@@ -62,6 +63,12 @@ export function InvitePage({ invitationId, onBack }: InvitePageProps) {setError(null);try {await api.acceptInvitation(invitationId);+ // Belt to the backend's braces: AcceptInvitation already sets+ // onboarded_at inside the same transaction, but explicitly calling+ // markOnboardingComplete + refreshMe here keeps local user state in+ // sync immediately so downstream guards don't see stale `null`.+ await api.markOnboardingComplete({ completion_path: "invite_accept" });+ await useAuthStore.getState().refreshMe();setDone("accepted");// Fetch the refreshed workspace list so we know the joined workspace's slug.const nextList = await qc.fetchQuery({diff --git a/packages/views/layout/use-dashboard-guard.ts b/packages/views/layout/use-dashboard-guard.tsindex a56f04e5e7..e276a25ca7 100644--- a/packages/views/layout/use-dashboard-guard.ts+++ b/packages/views/layout/use-dashboard-guard.ts@@ -21,14 +21,15 @@ import { useNavigation } from "../navigation";* - Not logged in → /login* - Logged in but workspace list not yet loaded → wait (don't bounce prematurely)* - Logged in but URL slug doesn't resolve to any workspace →- * `resolvePostAuthDestination(list, hasOnboarded)` — first workspace if any,- * onboarding for first-timers, /workspaces/new for returning users who- * deleted out.+ * `resolvePostAuthDestination(list, hasOnboarded)`:+ * • un-onboarded → /onboarding+ * • onboarded with workspaces → first workspace+ * • onboarded with zero workspaces → /workspaces/new*- * Onboarding is NOT a separate gate: a user invited into a workspace can have- * `onboarded_at == null` yet legitimately belong inside a workspace, and must- * not be bounced to the new-workspace wizard. The onboarding redirect only- * fires from the resolver when the user has zero workspaces.+ * The "un-onboarded but in workspace" state is now physically impossible:+ * CreateWorkspace and AcceptInvitation both atomically set `onboarded_at`+ * inside the same transaction that inserts the `member` row.+ * Existing dirty rows from PR #1868 are cleaned by migration 065.** We read the workspace list query state directly (rather than relying on* useCurrentWorkspace's null return) so we can distinguish "list loading"diff --git a/packages/views/onboarding/components/starter-content-prompt.tsx b/packages/views/onboarding/components/starter-content-prompt.tsxindex 29e0d376e2..8ef1872b08 100644--- a/packages/views/onboarding/components/starter-content-prompt.tsx+++ b/packages/views/onboarding/components/starter-content-prompt.tsx@@ -3,7 +3,7 @@import { useState } from "react";import { Loader2 } from "lucide-react";import { toast } from "sonner";-import { useQueryClient } from "@tanstack/react-query";+import { useQuery, useQueryClient } from "@tanstack/react-query";import { api } from "@multica/core/api";import { useAuthStore } from "@multica/core/auth";import { useNavigation } from "@multica/views/navigation";@@ -12,7 +12,10 @@ import type { QuestionnaireAnswers } from "@multica/core/onboarding";import { pinKeys } from "@multica/core/pins";import { projectKeys } from "@multica/core/projects";import { issueKeys } from "@multica/core/issues/queries";-import { workspaceKeys } from "@multica/core/workspace/queries";+import {+ memberListOptions,+ workspaceKeys,+} from "@multica/core/workspace/queries";import { Button } from "@multica/ui/components/ui/button";import {Dialog,@@ -50,11 +53,26 @@ export function StarterContentPrompt() {null,);+ // Member-list fetch is the proxy we use to detect "did this user CREATE+ // this workspace, or were they invited into it?" An invitee is by definition+ // not the only member (the inviter is also there); a fresh self-created+ // workspace has exactly one member — the creator. `starter_content_state`+ // is a user-level field and can't represent (user, workspace) state directly,+ // so we layer this membership check on top until that field is migrated to+ // the `member` table. See follow-up issue: starter_content_state per-workspace.+ const { data: members = [] } = useQuery({+ ...memberListOptions(workspace?.id ?? ""),+ enabled: !!workspace?.id,+ });+ const isSoloMember =+ members.length === 1 && members[0]?.user_id === user?.id;+const shouldShow =!!user &&!!workspace &&user.onboarded_at != null &&- user.starter_content_state == null;+ user.starter_content_state == null &&+ isSoloMember;if (!shouldShow || !workspace || !user) return null;diff --git a/packages/views/package.json b/packages/views/package.jsonindex a5d5d2e882..753e1564d5 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -38,6 +38,7 @@"./chat": "./chat/index.ts","./settings": "./settings/index.ts","./invite": "./invite/index.ts",+ "./invitations": "./invitations/index.ts","./onboarding": "./onboarding/index.ts","./platform": "./platform/index.ts"},diff --git a/server/internal/analytics/events.go b/server/internal/analytics/events.goindex 6290462b62..1230155804 100644--- a/server/internal/analytics/events.go+++ b/server/internal/analytics/events.go@@ -24,6 +24,7 @@ const (OnboardingPathRuntimeSkipped = "runtime_skipped" // completed without connecting a runtimeOnboardingPathCloudWaitlist = "cloud_waitlist" // completed via cloud waitlist soft exitOnboardingPathSkipExisting = "skip_existing" // "I've done this before" from welcome+ OnboardingPathInviteAccept = "invite_accept" // accepted at least one invitation from /invitationsOnboardingPathUnknown = "unknown" // fallback when the server can't derive the path)diff --git a/server/internal/handler/invitation.go b/server/internal/handler/invitation.goindex 7c6bc789ed..3f7b949f4a 100644--- a/server/internal/handler/invitation.go+++ b/server/internal/handler/invitation.go@@ -414,6 +414,16 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {return}+ // Accepting an invite is the physical event that "completes" onboarding for an+ // invitee — atomic with CreateMember so the invariant+ // "member row exists ↔ onboarded_at != null" cannot be violated.+ // COALESCE in MarkUserOnboarded keeps this idempotent for users joining+ // additional workspaces after their first.+ if _, err := qtx.MarkUserOnboarded(r.Context(), user.ID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to mark user onboarded")+ return+ }+if err := tx.Commit(r.Context()); err != nil {writeError(w, http.StatusInternalServerError, "failed to accept invitation")returndiff --git a/server/internal/handler/onboarding.go b/server/internal/handler/onboarding.goindex f77ef5e5c4..7d04e21efa 100644--- a/server/internal/handler/onboarding.go+++ b/server/internal/handler/onboarding.go@@ -52,6 +52,7 @@ var validCompletionPaths = map[string]struct{}{analytics.OnboardingPathRuntimeSkipped: {},analytics.OnboardingPathCloudWaitlist: {},analytics.OnboardingPathSkipExisting: {},+ analytics.OnboardingPathInviteAccept: {},}// CompleteOnboarding marks the authenticated user as having completeddiff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.goindex c6c2222a97..ed01afb680 100644--- a/server/internal/handler/workspace.go+++ b/server/internal/handler/workspace.go@@ -201,6 +201,14 @@ func (h *Handler) CreateWorkspace(w http.ResponseWriter, r *http.Request) {return}+ // Becoming a workspace member is the physical event that "completes" onboarding —+ // keep this atomic with CreateMember so `member` and `onboarded_at`+ // can never disagree. COALESCE in MarkUserOnboarded keeps it idempotent.+ if _, err := qtx.MarkUserOnboarded(r.Context(), parseUUID(userID)); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to mark user onboarded")+ return+ }+if err := tx.Commit(r.Context()); err != nil {writeError(w, http.StatusInternalServerError, "failed to create workspace")returndiff --git a/server/internal/handler/workspace_reserved_slugs.go b/server/internal/handler/workspace_reserved_slugs.goindex 1307ded8e2..c45aa8a957 100644--- a/server/internal/handler/workspace_reserved_slugs.go+++ b/server/internal/handler/workspace_reserved_slugs.go@@ -12,19 +12,20 @@ package handler// (`/new-workspace`, `/create-team`) collide with common user workspace names.var reservedSlugs = map[string]bool{// Auth flow- "login": true,- "logout": true,- "signin": true,- "signout": true,- "signup": true,- "auth": true,- "oauth": true,- "callback": true,- "invite": true,- "verify": true,- "reset": true,- "password": true,- "onboarding": true, // historical, kept reserved post-removal+ "login": true,+ "logout": true,+ "signin": true,+ "signout": true,+ "signup": true,+ "auth": true,+ "oauth": true,+ "callback": true,+ "invite": true,+ "invitations": true,+ "verify": true,+ "reset": true,+ "password": true,+ "onboarding": true, // historical, kept reserved post-removal// Platform / marketing routes (current + likely-future)"api": true,diff --git a/server/migrations/065_backfill_onboarded_at.down.sql b/server/migrations/065_backfill_onboarded_at.down.sqlnew file mode 100644index 0000000000..42694f1ffd--- /dev/null+++ b/server/migrations/065_backfill_onboarded_at.down.sql@@ -0,0 +1,4 @@+-- Backfill is intentionally irreversible: setting onboarded_at back to NULL+-- would re-introduce the dirty state we just cleaned up. This down migration+-- is a no-op so the migration can be ratcheted forward only.+SELECT 1;diff --git a/server/migrations/065_backfill_onboarded_at.up.sql b/server/migrations/065_backfill_onboarded_at.up.sqlnew file mode 100644index 0000000000..29c6c07067--- /dev/null+++ b/server/migrations/065_backfill_onboarded_at.up.sql@@ -0,0 +1,13 @@+-- Backfill onboarded_at for users who already belong to a workspace.+-- PR #1868 (since reverted) routed users by hasWorkspace instead of onboarded_at,+-- producing a population of users with workspace memberships but+-- onboarded_at == NULL. After the new design enforces+-- "member row exists ↔ onboarded_at != null" via backend transactions,+-- this one-shot backfill cleans existing dirty rows.+--+-- Uses created_at as the timestamp because these users were de facto onboarded+-- when their account was first created — backfilling with now() would distort+-- onboarding-funnel analytics. COALESCE keeps it idempotent.+UPDATE "user"+SET onboarded_at = COALESCE(onboarded_at, created_at)+WHERE id IN (SELECT DISTINCT user_id FROM member);