Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
feat(onboarding): refactor onboarding logic and metadata handling
Lewis Carhart0626229e9623
diff --git a/apps/api/src/workspace/workspace.service.ts b/apps/api/src/workspace/workspace.service.tsindex 99fd8f11..ed42927d 100644--- a/apps/api/src/workspace/workspace.service.ts+++ b/apps/api/src/workspace/workspace.service.ts@@ -7,6 +7,7 @@ import {type WorkspaceRole,} from "@crm/auth";import type { Db, Prisma } from "@crm/db";+import { isOnboarded, markOnboarded } from "@crm/db/workspace";import {BadRequestException,ForbiddenException,@@ -99,7 +100,7 @@ export class WorkspaceService {async get(userId: string): Promise<Workspace> {const row = await this.db.organization.findUnique({where: { id: WORKSPACE_ID },- select: { id: true, name: true, website: true, onboardedAt: true },+ select: { id: true, name: true, website: true, metadata: true },});if (!row) {@@ -113,7 +114,7 @@ export class WorkspaceService {id: row.id,name: row.name,website: row.website,- onboarded: row.onboardedAt !== null,+ onboarded: isOnboarded(row.metadata),viewerRole: role,canRename: canRenameWorkspace(role),canChangeRoles: canChangeRole(role),@@ -134,7 +135,7 @@ export class WorkspaceService {const before = await this.db.organization.findUnique({where: { id: WORKSPACE_ID },- select: { website: true, onboardedAt: true },+ select: { website: true, metadata: true },});const website = normalizeWebsite(input.website);@@ -150,7 +151,7 @@ export class WorkspaceService {data: {name: input.name,website,- ...(before?.onboardedAt ? {} : { onboardedAt: new Date() }),+ metadata: markOnboarded(before?.metadata ?? null, new Date()),},});diff --git a/apps/app/app/(app)/layout.tsx b/apps/app/app/(app)/layout.tsxindex ad5e676e..9b3af361 100644--- a/apps/app/app/(app)/layout.tsx+++ b/apps/app/app/(app)/layout.tsx@@ -1,4 +1,3 @@-import { redirect } from "next/navigation";import { AppHeader } from "@/components/app-header";import { AppIconRail } from "@/components/app-icon-rail";import { QuickSwitcher } from "@/components/crm/quick-switcher";@@ -6,7 +5,6 @@ import { RecordSheetHost } from "@/components/crm/record-sheet/record-sheet-hostimport { MobileNavProvider } from "@/components/mobile-nav";import { requireGoogleAccess } from "@/lib/session";import { HydrateClient } from "@/lib/trpc/hydrate";-import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";export default async function AppLayout({children,@@ -15,14 +13,6 @@ export default async function AppLayout({}>) {const { user } = await requireGoogleAccess();- const workspace = await getServerQueryClient()- .fetchQuery(getServerTrpc().workspace.get.queryOptions())- .catch(() => null);-- if (workspace && !workspace.onboarded && workspace.canRename) {- redirect("/onboarding");- }-return (<MobileNavProvider><div className="isolate flex h-svh flex-col">diff --git a/apps/app/app/(auth)/onboarding/onboarding-form.tsx b/apps/app/app/(auth)/onboarding/onboarding-form.tsxindex 10422d66..4bea2fef 100644--- a/apps/app/app/(auth)/onboarding/onboarding-form.tsx+++ b/apps/app/app/(auth)/onboarding/onboarding-form.tsx@@ -31,8 +31,8 @@ export function OnboardingForm({ placeholder }: { placeholder: string }) {const save = useMutation(trpc.workspace.update.mutationOptions({onSuccess: () => {- router.replace("/");router.refresh();+ router.replace("/");},onError: (error) => toast.error(error.message),}),diff --git a/apps/app/app/(auth)/onboarding/page.tsx b/apps/app/app/(auth)/onboarding/page.tsxindex 547ab531..f9dad0cc 100644--- a/apps/app/app/(auth)/onboarding/page.tsx+++ b/apps/app/app/(auth)/onboarding/page.tsx@@ -1,9 +1,7 @@import { DEFAULT_WORKSPACE_NAME } from "@crm/auth";import type { Metadata } from "next";-import { redirect } from "next/navigation";import { AuthHeading, AuthShell } from "@/components/auth-shell";import { requireGoogleAccess } from "@/lib/session";-import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";import { OnboardingForm } from "./onboarding-form";export const metadata: Metadata = {@@ -13,14 +11,6 @@ export const metadata: Metadata = {export default async function OnboardingPage() {await requireGoogleAccess();- const workspace = await getServerQueryClient()- .fetchQuery(getServerTrpc().workspace.get.queryOptions())- .catch(() => null);-- if (workspace && (workspace.onboarded || !workspace.canRename)) {- redirect("/");- }-return (<AuthShell><AuthHeading@@ -28,7 +18,7 @@ export default async function OnboardingPage() {description="Two things, once. The name is what the CRM calls you; the website is how the agent learns what you sell."/>- <OnboardingForm placeholder={workspace?.name ?? DEFAULT_WORKSPACE_NAME} />+ <OnboardingForm placeholder={DEFAULT_WORKSPACE_NAME} /></AuthShell>);}diff --git a/apps/app/lib/onboarding.ts b/apps/app/lib/onboarding.tsnew file mode 100644index 00000000..7a797b9a--- /dev/null+++ b/apps/app/lib/onboarding.ts@@ -0,0 +1,54 @@+import type { NextRequest, NextResponse } from "next/server";+import { API_URL } from "@/lib/env";++export const ONBOARDING_PATH = "/onboarding";++export const ONBOARDING_COOKIE = "crm.onboarded";++const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;++const GATE_TIMEOUT_MS = 2_000;++export type OnboardingGate = "settled" | "required" | "unknown";++export async function readOnboardingGate(+ request: NextRequest,+): Promise<OnboardingGate> {+ const cookie = request.headers.get("cookie");++ if (!cookie) return "unknown";++ try {+ const response = await fetch(`${API_URL}/api/trpc/workspace.get`, {+ headers: { cookie },+ signal: AbortSignal.timeout(GATE_TIMEOUT_MS),+ });++ if (!response.ok) return "unknown";++ const body = (await response.json()) as {+ result?: { data?: { onboarded?: boolean; canRename?: boolean } };+ };++ const workspace = body.result?.data;++ if (typeof workspace?.onboarded !== "boolean") return "unknown";++ return workspace.onboarded || !workspace.canRename ? "settled" : "required";+ } catch {+ return "unknown";+ }+}++export function settleOnboarding(+ request: NextRequest,+ response: NextResponse,+): void {+ response.cookies.set(ONBOARDING_COOKIE, "1", {+ httpOnly: true,+ sameSite: "lax",+ secure: request.nextUrl.protocol === "https:",+ path: "/",+ maxAge: COOKIE_MAX_AGE,+ });+}diff --git a/apps/app/proxy.ts b/apps/app/proxy.tsindex 15f0b02b..fc3f0006 100644--- a/apps/app/proxy.ts+++ b/apps/app/proxy.ts@@ -1,15 +1,55 @@import { getSessionCookie } from "better-auth/cookies";import { type NextRequest, NextResponse } from "next/server";+import {+ ONBOARDING_COOKIE,+ ONBOARDING_PATH,+ readOnboardingGate,+ settleOnboarding,+} from "@/lib/onboarding";-export function proxy(request: NextRequest) {- const isSignedIn = getSessionCookie(request) !== null;- const isSignInPage = request.nextUrl.pathname === "/sign-in";+const SIGN_IN_PATH = "/sign-in";- if (!isSignedIn && !isSignInPage) {- return NextResponse.redirect(new URL("/sign-in", request.nextUrl));+const UNGATED = [SIGN_IN_PATH, "/grant-access", "/eve"];++export async function proxy(request: NextRequest) {+ const { pathname } = request.nextUrl;++ if (getSessionCookie(request) === null) {+ return pathname === SIGN_IN_PATH+ ? NextResponse.next()+ : NextResponse.redirect(new URL(SIGN_IN_PATH, request.nextUrl));}- return NextResponse.next();+ if (isUngated(pathname)) return NextResponse.next();++ if (request.cookies.has(ONBOARDING_COOKIE)) return beyondOnboarding(request);++ const gate = await readOnboardingGate(request);++ if (gate === "unknown") return NextResponse.next();++ if (gate === "required") {+ return pathname === ONBOARDING_PATH+ ? NextResponse.next()+ : NextResponse.redirect(new URL(ONBOARDING_PATH, request.nextUrl));+ }++ const response = beyondOnboarding(request);+ settleOnboarding(request, response);++ return response;+}++function isUngated(pathname: string): boolean {+ return UNGATED.some(+ (prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`),+ );+}++function beyondOnboarding(request: NextRequest): NextResponse {+ return request.nextUrl.pathname === ONBOARDING_PATH+ ? NextResponse.redirect(new URL("/", request.nextUrl))+ : NextResponse.next();}export const config = {diff --git a/docs/api.md b/docs/api.mdindex 30dfbfa9..1dfde878 100644--- a/docs/api.md+++ b/docs/api.md@@ -114,15 +114,49 @@ called, who works here, and what do we sell — and for nothing else.Renaming the workspace is data, not authentication, so it belongs on the datasurface with everything else — see the next rule.- **The name and the website are asked for once, at the door, and there is no- skipping it.** `onboardedAt` on the workspace row is the whole of that state,- and `(app)/layout.tsx` redirects to `/onboarding` while it is null. Both- fields are `required` in the form *and* in `updateWorkspaceInput`, so the- website cannot be dropped later from the settings page either — a CRM that- knows what we sell on Monday and not on Tuesday is worse than one that never- knew. The gate only catches somebody who could *answer* it (`canRename`), so a- member never meets a form they are forbidden to submit, and it posts the same- `workspace.update` mutation as the settings page rather than a second write- path.+ skipping it.** Both fields are `required` in the form *and* in+ `updateWorkspaceInput`, so the website cannot be dropped later from the+ settings page either — a CRM that knows what we sell on Monday and not on+ Tuesday is worse than one that never knew. The gate only catches somebody who+ could *answer* it (`canRename`), so a member never meets a form they are+ forbidden to submit, and it posts the same `workspace.update` mutation as the+ settings page rather than a second write path.+- **The state is `onboardedAt` inside the organization's `metadata`, not a+ column beside it.** The plugin ships that blob and owns the table; a second+ timestamp column is a second place the same fact is recorded, and the two+ drifted the first time somebody wrote a website through a revision of+ `WorkspaceService.update` that predated the column. A row with a name, a+ website and a null timestamp is a workspace that has plainly answered the+ question and is asked it forever. `isOnboarded` and `markOnboarded` in+ [`@crm/db/workspace`](../packages/db/src/workspace.ts) are the only readers+ and the only writer; `markOnboarded` keeps the first answer and preserves+ every other key, because the blob is the plugin's, not ours.+- **The gate is `proxy.ts`, and it is answered once per browser.** It used to+ live in `(app)/layout.tsx`, which meant a `workspace.get` round trip on every+ navigation into the app to re-establish a fact that changes once in the life+ of an install — and a second, opposing redirect on the `/onboarding` page to+ stop the first one looping. Two redirects pointing at each other is not a+ gate, it is a latch waiting for the two reads to disagree.+ - **`getSessionCookie()` decides signed-in, not a session lookup.** That is+ Better Auth's documented optimistic check for proxy, and it is all a+ redirect needs; every page behind it still resolves the real session+ server-side through `requireGoogleAccess()`.+ - **The answer is cached in an httpOnly `crm.onboarded` cookie**, so the+ common path costs nothing and the tRPC read happens once — twice for the+ person who actually fills the form in, since the cookie lands on the+ navigation after the mutation. The proxy is the only writer; the form does+ not set it, because two writers is how this went wrong in the first place.+ Forging the cookie skips a setup form and grants nothing, which is why it+ can be a cookie at all.+ - **`/sign-in`, `/grant-access` and `/eve` are ungated.**+ `requireGoogleAccess()` redirects to `/grant-access`, so gating it would+ ping-pong against the onboarding redirect for anyone who signed in without+ both scopes.+ - **An unreachable API fails open.** `readOnboardingGate` returns `unknown`+ on a non-200, a timeout or a parse failure, and an unknown gate lets the+ request through without writing the cookie. The alternative is an install+ that cannot reach its own API redirecting every request to a form that+ cannot be submitted.- **The name arrives as a placeholder, not as an answer.** A workspace iscreated as `DEFAULT_WORKSPACE_NAME` — the literal string `CRM` — and the fieldis empty with that behind it. It used to be derived from the sign-in domain,diff --git a/packages/auth/src/auth.ts b/packages/auth/src/auth.tsindex ce86547c..a6ca05f3 100644--- a/packages/auth/src/auth.ts+++ b/packages/auth/src/auth.ts@@ -88,10 +88,6 @@ export const auth = betterAuth({type: "string",required: false,},- onboardedAt: {- type: "date",- required: false,- },},},},diff --git a/packages/db/prisma/migrations/20260803190000_workspace_onboarded_metadata/migration.sql b/packages/db/prisma/migrations/20260803190000_workspace_onboarded_metadata/migration.sqlnew file mode 100644index 00000000..cdd32e17--- /dev/null+++ b/packages/db/prisma/migrations/20260803190000_workspace_onboarded_metadata/migration.sql@@ -0,0 +1,19 @@+-- Onboarding state moves into the organization plugin's own `metadata` blob.+-- A workspace that has a website has answered the form, whether or not the+-- column beside it ever recorded that it had.+UPDATE "organization"+SET "metadata" = (+ COALESCE(NULLIF("metadata", '')::jsonb, '{}'::jsonb)+ || jsonb_build_object(+ 'onboardedAt',+ to_char(+ COALESCE("onboardedAt", "createdAt") AT TIME ZONE 'UTC',+ 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'+ )+ )+ )::text+WHERE "website" IS NOT NULL+ AND COALESCE(NULLIF("metadata", '')::jsonb, '{}'::jsonb) -> 'onboardedAt' IS NULL;++-- AlterTable+ALTER TABLE "organization" DROP COLUMN "onboardedAt";diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prismaindex 4c2a9918..551b64e6 100644--- a/packages/db/prisma/schema.prisma+++ b/packages/db/prisma/schema.prisma@@ -623,7 +623,6 @@ model Organization {createdAt DateTimemetadata String?website String?- onboardedAt DateTime?members Member[]invitations Invitation[]diff --git a/packages/db/src/workspace.ts b/packages/db/src/workspace.tsindex 71376973..86da2765 100644--- a/packages/db/src/workspace.ts+++ b/packages/db/src/workspace.ts@@ -7,6 +7,36 @@ export const MAX_NARRATIVE = 320;export const MAX_LINE = 140;+export function isOnboarded(metadata: string | null): boolean {+ return typeof readMetadata(metadata).onboardedAt === "string";+}++export function markOnboarded(metadata: string | null, at: Date): string {+ const current = readMetadata(metadata);++ return JSON.stringify(+ typeof current.onboardedAt === "string"+ ? current+ : { ...current, onboardedAt: at.toISOString() },+ );+}++function readMetadata(metadata: string | null): Record<string, unknown> {+ if (!metadata) return {};++ try {+ const parsed: unknown = JSON.parse(metadata);++ return typeof parsed === "object" &&+ parsed !== null &&+ !Array.isArray(parsed)+ ? (parsed as Record<string, unknown>)+ : {};+ } catch {+ return {};+ }+}+export type WorkspaceProfile = {website: string;narrative: string;diff --git a/packages/db/test/workspace-onboarded.spec.ts b/packages/db/test/workspace-onboarded.spec.tsnew file mode 100644index 00000000..2e942794--- /dev/null+++ b/packages/db/test/workspace-onboarded.spec.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "bun:test";+import { isOnboarded, markOnboarded } from "../src/workspace";++const AT = new Date("2026-08-03T17:00:00.000Z");++describe("isOnboarded", () => {+ it("is false for a workspace nobody has answered for", () => {+ expect(isOnboarded(null)).toBe(false);+ expect(isOnboarded("")).toBe(false);+ expect(isOnboarded("{}")).toBe(false);+ });++ it("is true once the timestamp is in the metadata", () => {+ expect(isOnboarded('{"onboardedAt":"2026-08-03T16:59:29.675Z"}')).toBe(+ true,+ );+ });++ it("does not throw on metadata written by something else", () => {+ expect(isOnboarded("not json")).toBe(false);+ expect(isOnboarded("[1,2,3]")).toBe(false);+ expect(isOnboarded('{"onboardedAt":true}')).toBe(false);+ });+});++describe("markOnboarded", () => {+ it("records the moment the form was answered", () => {+ expect(JSON.parse(markOnboarded(null, AT))).toEqual({+ onboardedAt: AT.toISOString(),+ });+ });++ it("keeps the first answer, so saving settings again does not move it", () => {+ const first = markOnboarded(null, AT);+ const second = markOnboarded(first, new Date("2027-01-01T00:00:00.000Z"));++ expect(second).toBe(first);+ });++ it("leaves metadata the plugin owns alone", () => {+ expect(JSON.parse(markOnboarded('{"theme":"dark"}', AT))).toEqual({+ theme: "dark",+ onboardedAt: AT.toISOString(),+ });+ });+});