Skip to content

Open source CapCut alternative.

TypeScript

feat(site): record onboarding progress past the slides

David Le4372bc5b237f
diff --git a/site/prisma/Onboarding.prisma b/site/prisma/Onboarding.prisma
index d0e0f6e6..53920491 100644
--- a/site/prisma/Onboarding.prisma
+++ b/site/prisma/Onboarding.prisma
@@ -12,6 +12,10 @@ model UserOnboarding {
// Null until the sequence ends; `skipped` says how it ended.
completedAt DateTime?
skipped Boolean @default(false)
+ // When the slides ended and the starter tour took over; null until then.
+ slidesDoneAt DateTime?
+ // The starter tour steps this account has done (TOUR_STEPS ids).
+ tourSteps String[] @default([])
// Every source the account picked; the question takes more than one answer.
referralSources String[] @default([])
// The free text that comes with picking "other".
diff --git a/site/prisma/migrations/20261029081332/migration.sql b/site/prisma/migrations/20261029081332/migration.sql
new file mode 100644
index 00000000..04ae5684
--- /dev/null
+++ b/site/prisma/migrations/20261029081332/migration.sql
@@ -0,0 +1,3 @@
+-- AlterTable
+ALTER TABLE "UserOnboarding" ADD COLUMN "slidesDoneAt" TIMESTAMP(3),
+ADD COLUMN "tourSteps" TEXT[] DEFAULT ARRAY[]::TEXT[];
diff --git a/site/src/app/api/account/onboarding/route.ts b/site/src/app/api/account/onboarding/route.ts
index 0e0b733a..9329dc0e 100644
--- a/site/src/app/api/account/onboarding/route.ts
+++ b/site/src/app/api/account/onboarding/route.ts
@@ -1,6 +1,8 @@
import { NextResponse } from "next/server";
import { z } from "zod";
+import { starterProjectId } from "@/cut/lib/starter";
+import { seedStarterProject } from "@/cut/server/cloud/starter";
import { creditMicrosToString } from "@/lib/credits/amounts";
import {
withDonkeyAuth,
@@ -10,6 +12,7 @@ import {
ONBOARDING_VERSION,
REFERRAL_OTHER_MAX_LENGTH,
REFERRAL_SOURCES,
+ TOUR_STEPS,
isKnownReferralSource,
} from "@/lib/onboarding/sequence";
import { prisma } from "@/lib/prisma";
@@ -18,6 +21,8 @@ type OnboardingRow = {
version: number;
completedAt: Date | null;
skipped: boolean;
+ slidesDoneAt: Date | null;
+ tourSteps: string[];
referralSources: string[];
referralOther: string | null;
};
@@ -26,6 +31,12 @@ type OnboardingState = {
version: number;
completedAt: string | null;
skipped: boolean;
+ slidesDoneAt: string | null;
+ tourSteps: string[];
+ // Whether the starter project exists, so the tour has somewhere to run. A
+ // restart and the slides' end seed it; an account that deletes it mid-tour
+ // goes on to the plans.
+ starterReady: boolean;
referralSources: string[];
referralOther: string | null;
// USD the signup grant landed on this account, or null when none did: the
@@ -42,6 +53,8 @@ const UNSTARTED: OnboardingRow = {
version: ONBOARDING_VERSION,
completedAt: null,
skipped: false,
+ slidesDoneAt: null,
+ tourSteps: [],
referralSources: [],
referralOther: null,
};
@@ -59,10 +72,15 @@ const updateSchema = z
.max(REFERRAL_SOURCES.length),
referralOther: z.string().trim().max(REFERRAL_OTHER_MAX_LENGTH).optional(),
})
- .or(z.object({ completed: z.literal(true), skipped: z.boolean() }));
+ .or(z.object({ completed: z.literal(true), skipped: z.boolean() }))
+ .or(z.object({ slidesDone: z.literal(true) }))
+ .or(z.object({ restart: z.literal(true) }))
+ .or(z.object({ tourStep: z.enum(TOUR_STEPS) }));
-// One write for both things the sequence records: the referral answer when it's
-// given, and the run's end. Either is the account's first row, so both upsert.
+// One write for everything the sequence records: the referral answer when it's
+// given, the slides' end, each tour step, the run's end, and a restart that
+// sends a finished account through the whole run again. Any of them can be the
+// account's first row, so all upsert.
export const PUT = withDonkeyAuth(async (request: DonkeyAuthenticatedRequest) => {
const parsed = updateSchema.safeParse(await request.json().catch(() => null));
if (!parsed.success) {
@@ -70,21 +88,47 @@ export const PUT = withDonkeyAuth(async (request: DonkeyAuthenticatedRequest) =>
}
const userId = request.donkey.userId;
+ const update = parsed.data;
+
+ // A tour step appends once: a repeat send leaves the list as it is.
+ if ("tourStep" in update) {
+ const current = await prisma.userOnboarding.findUnique({ where: { userId } });
+ const row = current?.tourSteps.includes(update.tourStep)
+ ? current
+ : await prisma.userOnboarding.upsert({
+ where: { userId },
+ create: { userId, version: ONBOARDING_VERSION, tourSteps: [update.tourStep] },
+ update: { tourSteps: { push: update.tourStep } },
+ });
+ return NextResponse.json(await toState(userId, row));
+ }
+
+ // The tour runs on the starter project, which opens behind the slides, so a
+ // restart and the slides' end put it back for an account that deleted it.
+ // Seeding an existing starter is a no-op.
+ if ("slidesDone" in update || "restart" in update) {
+ await seedStarterProject(userId);
+ }
+
const data =
- "referralSources" in parsed.data
+ "slidesDone" in update
+ ? { slidesDoneAt: new Date() }
+ : "restart" in update
+ ? { completedAt: null, skipped: false, slidesDoneAt: null, tourSteps: [] }
+ : "referralSources" in update
? {
- referralSources: [...new Set(parsed.data.referralSources)],
+ referralSources: [...new Set(update.referralSources)],
// The text only means anything as the "other" answer; without that
// pick it stores nothing.
referralOther:
- (parsed.data.referralSources.includes("other") &&
- parsed.data.referralOther) ||
+ (update.referralSources.includes("other") &&
+ update.referralOther) ||
null,
referralAnsweredAt: new Date(),
}
: {
completedAt: new Date(),
- skipped: parsed.data.skipped,
+ skipped: update.skipped,
version: ONBOARDING_VERSION,
};
@@ -98,10 +142,16 @@ export const PUT = withDonkeyAuth(async (request: DonkeyAuthenticatedRequest) =>
async function toState(userId: string, row: OnboardingRow): Promise<OnboardingState> {
// The expiry is shown while it is still ahead of a live grant.
- const grant = await prisma.userCreditGrant.findFirst({
- where: { userId, source: "signup" },
- select: { expiresAt: true, originalAmountMicros: true, status: true },
- });
+ const [grant, starter] = await Promise.all([
+ prisma.userCreditGrant.findFirst({
+ where: { userId, source: "signup" },
+ select: { expiresAt: true, originalAmountMicros: true, status: true },
+ }),
+ prisma.cutProject.findFirst({
+ where: { id: starterProjectId(userId), userId },
+ select: { id: true },
+ }),
+ ]);
const expiresAt =
grant?.status === "active" && grant.expiresAt && grant.expiresAt > new Date()
? grant.expiresAt
@@ -110,6 +160,9 @@ async function toState(userId: string, row: OnboardingRow): Promise<OnboardingSt
version: row.version,
completedAt: row.completedAt?.toISOString() ?? null,
skipped: row.skipped,
+ slidesDoneAt: row.slidesDoneAt?.toISOString() ?? null,
+ tourSteps: row.tourSteps,
+ starterReady: starter !== null,
referralSources: row.referralSources,
referralOther: row.referralOther,
signupCredits: grant ? creditMicrosToString(grant.originalAmountMicros) : null,
diff --git a/site/src/lib/onboarding/sequence.ts b/site/src/lib/onboarding/sequence.ts
index 385cc6f8..46661a6b 100644
--- a/site/src/lib/onboarding/sequence.ts
+++ b/site/src/lib/onboarding/sequence.ts
@@ -31,3 +31,13 @@ export const isKnownReferralSource = (id: string): id is ReferralSource =>
// The sequence an account is measured against. Raise it when the slides change
// enough that people who finished the old one should see the new one.
export const ONBOARDING_VERSION = 1;
+
+// The starter tour that follows the slides: each step is something the account
+// does in the starter project. New projects stay locked until every step is
+// done, and the route accepts only these ids.
+export const TOUR_STEPS = ["play", "clip", "media", "chat"] as const;
+
+export type TourStep = (typeof TOUR_STEPS)[number];
+
+export const isTourStep = (id: string): id is TourStep =>
+ (TOUR_STEPS as readonly string[]).includes(id);
diff --git a/site/src/lib/onboarding/stage.test.ts b/site/src/lib/onboarding/stage.test.ts
new file mode 100644
index 00000000..ae6dc3fa
--- /dev/null
+++ b/site/src/lib/onboarding/stage.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, test } from "bun:test";
+
+import { ONBOARDING_VERSION, TOUR_STEPS } from "@/lib/onboarding/sequence";
+import { nextTourStep, onboardingStage } from "@/lib/onboarding/stage";
+
+const DONE_AT = "2026-10-29T00:00:00.000Z";
+
+// A brand-new account: nothing done, starter seeded.
+const fresh = {
+ version: ONBOARDING_VERSION,
+ completedAt: null,
+ slidesDoneAt: null,
+ tourSteps: [] as string[],
+ starterReady: true,
+};
+
+describe("onboardingStage", () => {
+ test("waits for the account read", () => {
+ expect(onboardingStage(undefined)).toBeNull();
+ });
+
+ test("starts on the slides", () => {
+ expect(onboardingStage(fresh)).toBe("slides");
+ });
+
+ test("tours the starter once the slides are done", () => {
+ expect(onboardingStage({ ...fresh, slidesDoneAt: DONE_AT })).toBe("tour");
+ expect(onboardingStage({ ...fresh, slidesDoneAt: DONE_AT, tourSteps: ["play", "clip"] })).toBe("tour");
+ });
+
+ test("shows the plans once every tour step is done", () => {
+ expect(onboardingStage({ ...fresh, slidesDoneAt: DONE_AT, tourSteps: [...TOUR_STEPS] })).toBe("plans");
+ });
+
+ test("goes from the slides to the plans without a starter", () => {
+ expect(onboardingStage({ ...fresh, slidesDoneAt: DONE_AT, starterReady: false })).toBe("plans");
+ });
+
+ // Every account that finished the old sequence has completedAt and none of
+ // the new fields; it must never land back in the tour or the lock.
+ test("leaves a finished account done", () => {
+ expect(onboardingStage({ ...fresh, completedAt: DONE_AT })).toBe("done");
+ });
+});
+
+describe("nextTourStep", () => {
+ test("walks the steps in order and skips done ones", () => {
+ expect(nextTourStep({ tourSteps: [] })).toBe("play");
+ expect(nextTourStep({ tourSteps: ["play"] })).toBe("clip");
+ expect(nextTourStep({ tourSteps: ["play", "media"] })).toBe("clip");
+ expect(nextTourStep({ tourSteps: [...TOUR_STEPS] })).toBeNull();
+ });
+});
diff --git a/site/src/lib/onboarding/stage.ts b/site/src/lib/onboarding/stage.ts
new file mode 100644
index 00000000..84e17f6d
--- /dev/null
+++ b/site/src/lib/onboarding/stage.ts
@@ -0,0 +1,46 @@
+// Where an account stands on the way in, read off its onboarding row: the
+// slides, the starter tour, the plans that close it, or done. The overlay, the
+// tour, the plans dialog and the project lock all derive from this one answer.
+
+import { ONBOARDING_VERSION, TOUR_STEPS, type TourStep } from "@/lib/onboarding/sequence";
+
+export type OnboardingStage = "slides" | "tour" | "plans" | "done";
+
+type StageFields = {
+ version: number;
+ completedAt: string | null;
+ slidesDoneAt: string | null;
+ tourSteps: string[];
+ starterReady: boolean;
+};
+
+/** Whether this account still owes us a run of the current sequence. */
+export function needsOnboarding(state: StageFields | undefined): boolean {
+ if (!state) {
+ return false;
+ }
+ return state.completedAt === null || state.version < ONBOARDING_VERSION;
+}
+
+/** The stage this account is at, or null while the read is in flight. The tour
+ * needs the starter project; an account without one goes on to the plans. */
+export function onboardingStage(state: StageFields | undefined): OnboardingStage | null {
+ if (!state) {
+ return null;
+ }
+ if (!needsOnboarding(state)) {
+ return "done";
+ }
+ if (state.slidesDoneAt === null) {
+ return "slides";
+ }
+ if (state.starterReady && nextTourStep(state) !== null) {
+ return "tour";
+ }
+ return "plans";
+}
+
+/** The first tour step this account has yet to do, or null when all are done. */
+export function nextTourStep(state: Pick<StageFields, "tourSteps">): TourStep | null {
+ return TOUR_STEPS.find((step) => !state.tourSteps.includes(step)) ?? null;
+}
diff --git a/site/src/queries/onboarding.ts b/site/src/queries/onboarding.ts
index 9e7f15c7..bcbc8343 100644
--- a/site/src/queries/onboarding.ts
+++ b/site/src/queries/onboarding.ts
@@ -2,7 +2,7 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { ONBOARDING_VERSION, type ReferralSource } from "@/lib/onboarding/sequence";
+import { ONBOARDING_VERSION, type ReferralSource, type TourStep } from "@/lib/onboarding/sequence";
import { apiFetch } from "@/queries/apiClient";
export const onboardingQueryKey = ["account-onboarding"] as const;
@@ -11,6 +11,9 @@ export type OnboardingState = {
version: number;
completedAt: string | null;
skipped: boolean;
+ slidesDoneAt: string | null;
+ tourSteps: string[];
+ starterReady: boolean;
referralSources: string[];
referralOther: string | null;
signupCredits: string | null;
@@ -19,17 +22,14 @@ export type OnboardingState = {
type OnboardingUpdate =
| { referralSources: ReferralSource[]; referralOther?: string }
- | { completed: true; skipped: boolean };
-
-/** Whether this account still owes us a run of the current sequence. */
-export function needsOnboarding(state: OnboardingState | undefined): boolean {
- if (!state) return false;
- return state.completedAt === null || state.version < ONBOARDING_VERSION;
-}
+ | { completed: true; skipped: boolean }
+ | { slidesDone: true }
+ | { restart: true }
+ | { tourStep: TourStep };
export function useOnboardingState() {
return useQuery({
- queryFn: () => apiFetch<OnboardingState>("/api/account/onboarding"),
+ queryFn: async () => readState(await apiFetch<Partial<OnboardingState>>("/api/account/onboarding")),
queryKey: onboardingQueryKey,
// The sequence decides once per load whether to open; refetching behind an
// open overlay could only close it mid-run.
@@ -41,13 +41,73 @@ export function useOnboardingState() {
export function useSaveOnboarding() {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: (update: OnboardingUpdate) =>
- apiFetch<OnboardingState>("/api/account/onboarding", {
- body: JSON.stringify(update),
- method: "PUT",
- }),
- onSuccess: (state) => {
- queryClient.setQueryData(onboardingQueryKey, state);
+ mutationFn: async (update: OnboardingUpdate) =>
+ readState(
+ await apiFetch<Partial<OnboardingState>>("/api/account/onboarding", {
+ body: JSON.stringify(update),
+ method: "PUT",
+ }),
+ ),
+ // The stage moves the moment a step lands, so the tour, the project lock
+ // and the plans follow the person without waiting on the write.
+ onMutate: (update) => {
+ queryClient.setQueryData<OnboardingState>(onboardingQueryKey, (state) => state && applyUpdate(state, update));
+ },
+ // Progress only moves forward, so a reply that left the server before a
+ // later write keeps what that write already put here. A restart's reply is
+ // the account row as it starts over.
+ onSuccess: (state, update) => {
+ queryClient.setQueryData<OnboardingState>(onboardingQueryKey, (prev) =>
+ prev && !("restart" in update)
+ ? {
+ ...state,
+ slidesDoneAt: state.slidesDoneAt ?? prev.slidesDoneAt,
+ completedAt: state.completedAt ?? prev.completedAt,
+ tourSteps: [...new Set([...prev.tourSteps, ...state.tourSteps])],
+ }
+ : state,
+ );
+ },
+ // A write that failed hands the stage back to the account row.
+ onError: () => {
+ void queryClient.invalidateQueries({ queryKey: onboardingQueryKey });
},
});
}
+
+// The account's answer with every field present: a server from before the tour
+// sends no tour fields, and reads as an account with nothing toured.
+function readState(state: Partial<OnboardingState>): OnboardingState {
+ return {
+ version: state.version ?? ONBOARDING_VERSION,
+ completedAt: state.completedAt ?? null,
+ skipped: state.skipped ?? false,
+ slidesDoneAt: state.slidesDoneAt ?? null,
+ tourSteps: state.tourSteps ?? [],
+ starterReady: state.starterReady ?? false,
+ referralSources: state.referralSources ?? [],
+ referralOther: state.referralOther ?? null,
+ signupCredits: state.signupCredits ?? null,
+ signupCreditsExpiresAt: state.signupCreditsExpiresAt ?? null,
+ };
+}
+
+// What the account row will say once the write lands.
+function applyUpdate(state: OnboardingState, update: OnboardingUpdate): OnboardingState {
+ // The server seeds the starter as the slides end.
+ if ("slidesDone" in update) {
+ return { ...state, slidesDoneAt: new Date().toISOString(), starterReady: true };
+ }
+ if ("restart" in update) {
+ return { ...state, completedAt: null, skipped: false, slidesDoneAt: null, tourSteps: [] };
+ }
+ if ("tourStep" in update) {
+ return state.tourSteps.includes(update.tourStep)
+ ? state
+ : { ...state, tourSteps: [...state.tourSteps, update.tourStep] };
+ }
+ if ("completed" in update) {
+ return { ...state, completedAt: new Date().toISOString(), skipped: update.skipped, version: ONBOARDING_VERSION };
+ }
+ return state;
+}