Open source CapCut alternative.
TypeScript
fix(site): keep onboarding true to the account [rebuild]
David Led9ec13df8609
diff --git a/site/src/app/api/account/onboarding/route.ts b/site/src/app/api/account/onboarding/route.tsindex 9329dc0e..89bf42fb 100644--- a/site/src/app/api/account/onboarding/route.ts+++ b/site/src/app/api/account/onboarding/route.ts@@ -79,7 +79,7 @@ const updateSchema = z// 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+// sends an account whose replayed slides just ended through the tour 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));@@ -103,18 +103,11 @@ export const PUT = withDonkeyAuth(async (request: DonkeyAuthenticatedRequest) =>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 ="slidesDone" in update? { slidesDoneAt: new Date() }: "restart" in update- ? { completedAt: null, skipped: false, slidesDoneAt: null, tourSteps: [] }+ ? { completedAt: null, skipped: false, slidesDoneAt: new Date(), tourSteps: [] }: "referralSources" in update? {referralSources: [...new Set(update.referralSources)],@@ -137,6 +130,15 @@ export const PUT = withDonkeyAuth(async (request: DonkeyAuthenticatedRequest) =>create: { userId, version: ONBOARDING_VERSION, ...data },update: data,});++ // 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.+ // The progress is written first: a seed that fails still fails the call,+ // and the account row it leaves sends the account on to the plans.+ // Seeding an existing starter is a no-op.+ if ("slidesDone" in update || "restart" in update) {+ await seedStarterProject(userId);+ }return NextResponse.json(await toState(userId, row));});diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsxindex c9c348df..c37ce98a 100644--- a/site/src/cut/components/ProjectsHome.tsx+++ b/site/src/cut/components/ProjectsHome.tsx@@ -78,6 +78,7 @@ import { creatorLocale, creatorNames } from "@/cut/lib/defaultNames";import { dropLocalProjectCopy, localMediaUrl } from "@/cut/lib/mediaSync";import { copyProjectAcross } from "@/cut/lib/projectCopy";import { newProjectAllowed } from "@/cut/lib/projectLimit";+import { useStarterGone } from "@/cut/lib/tourLock";import { checkoutErrorCode } from "@/cut/lib/proUpgrade";import { homeHref, projectHref, useCutBase } from "@/cut/lib/nav";import { daysUntil, formatDate, formatTime } from "@/cut/lib/time";@@ -279,6 +280,7 @@ export function ProjectsHome() {);const client = useQueryClient();+ const starterGone = useStarterGone();// Hooks can't run in a loop, so both sections are always wired and the// inactive one simply stays disabled.const localSection = useProjectsSection("local", {@@ -642,6 +644,7 @@ export function ProjectsHome() {// with the project itself, as does a cloud project's browser-store copy.clearProjectThreads(p.id);if (source === "cloud") void dropLocalProjectCopy(p.id);+ starterGone(p.id);await Promise.all([refresh(source), refresh(dest)]);} catch (e) {setDupError(describeError(e, t("projects.moveFailed")));@@ -656,6 +659,7 @@ export function ProjectsHome() {// render-resume guard reads to keep a deleted thread's render from// landing), and the cached copy of its document.const purgeProject = (id: string, residency: Residency) => {+ starterGone(id);useGenScene.getState().killProject(id);useGenerate.getState().cancelForOwner({ projectId: id });clearProjectThreads(id);diff --git a/site/src/cut/components/ViewerTopBar.tsx b/site/src/cut/components/ViewerTopBar.tsxindex a61cab9a..951fa555 100644--- a/site/src/cut/components/ViewerTopBar.tsx+++ b/site/src/cut/components/ViewerTopBar.tsx@@ -12,7 +12,8 @@ import { apiFetch } from "@/cut/lib/backend";import { projectHref, useCutBase } from "@/cut/lib/nav";import { OperationError, operationFailure } from "@/cut/lib/operationFailure";import { useEditor } from "@/cut/lib/store";-import { tourHoldsProjects } from "@/cut/lib/tourLock";+import { useEnvironment } from "@/cut/lib/environment";+import { tourHoldsCopy } from "@/cut/lib/tourLock";import { errorFromBody } from "@/cut/lib/userError";import { useSession } from "@/lib/auth-client";@@ -29,6 +30,7 @@ export function ViewerTopBar({ chatStatus }: { chatStatus: ChatStatus }) {const projectName = useEditor((s) => s.projectName);const chatShared = useEditor((s) => s.sharedFeatures?.chat === true);const { data: session } = useSession();+ const { chatgpt } = useEnvironment();const [copying, setCopying] = useState(false);const [copyError, setCopyError] = useState<string | null>(null);@@ -38,13 +40,13 @@ export function ViewerTopBar({ chatStatus }: { chatStatus: ChatStatus }) {window.location.href = authHrefFor("/sign-in", here);return;}- // A copy is a new project, and the starter tour holds those.- if (tourHoldsProjects()) {- return;- }setCopying(true);setCopyError(null);try {+ // A copy is a new project, and the starter tour holds those.+ if (!chatgpt && (await tourHoldsCopy(session.user.id, base))) {+ return;+ }const res = await apiFetch("/api/cut/copy", { method: "POST" });const body = (await res.json().catch(() => null)) as| { jobId?: string; error?: string }diff --git a/site/src/cut/components/onboarding/CutOnboarding.tsx b/site/src/cut/components/onboarding/CutOnboarding.tsxindex 6b7f5989..e5e57a14 100644--- a/site/src/cut/components/onboarding/CutOnboarding.tsx+++ b/site/src/cut/components/onboarding/CutOnboarding.tsx@@ -94,6 +94,9 @@ export function CutOnboarding() {const referralOther = otherDraft ?? savedOther;const [dismissed, setDismissed] = useState(false);const [handedOver, setHandedOver] = useState(false);+ // Whether the write that hands over to the tour landed, with the starter+ // seeded behind it.+ const [seeded, setSeeded] = useState(false);const openedStarter = useRef(false);const router = useRouter();const [replaying, setReplaying] = useState(false);@@ -199,29 +202,18 @@ export function CutOnboarding() {// An account past the slides teaches this browser to stop waiting.useEffect(() => {- if (!state || onboardingStage(state) === "slides") return;- localStorage.setItem(doneKey(userId), String(state.version));- }, [state, userId]);-- // A replay is the whole run again: the account row starts over, so the- // slides hand over to the starter tour and the plans close it, the same as a- // first run. Once per open.- const restarted = useRef(false);- useEffect(() => {- if (run !== "replay") {- restarted.current = false;+ if (!state || onboardingStage(state) === "slides") {return;}- if (restarted.current || !state || onboardingStage(state) === "slides") return;- restarted.current = true;- save.mutate({ restart: true });- }, [run, state, save]);+ localStorage.setItem(doneKey(userId), String(state.version));+ }, [state, userId]);useEffect(() =>onOpenOnboarding(() => {setStep(0);setHandedOver(false);+ setSeeded(false);openedStarter.current = false;setReplaying(true);}),@@ -244,7 +236,9 @@ export function CutOnboarding() {const finish = useCallback((skipped: boolean) => {- if (!run) return;+ if (!run) {+ return;+ }commitReferrals();track("onboarding_completed", { source: run, skipped, step });save.mutate({ completed: true, skipped });@@ -257,14 +251,20 @@ export function CutOnboarding() {// The slides' end on a computer: the account records it and the overlay// lifts onto the starter project, where the tour picks up. Subscribers take- // the tour too; the plans at its end show the plan they hold.+ // the tour too; the plans at its end show the plan they hold. A replay+ // starts the account's tour over here, at the slides' end, so a replay+ // closed partway leaves a finished account finished.const leave = useCallback((skipped: boolean) => {- if (!run) return;- if (!toTour) return finish(skipped);+ if (!run) {+ return;+ }+ if (!toTour) {+ return finish(skipped);+ }commitReferrals();track("onboarding_slides_done", { source: run, skipped, step });- save.mutate({ slidesDone: true });+ save.mutate(run === "replay" ? { restart: true } : { slidesDone: true }, { onSuccess: () => setSeeded(true) });setHandedOver(true);localStorage.setItem(doneKey(userId), String(ONBOARDING_VERSION));setReplaying(false);@@ -275,16 +275,23 @@ export function CutOnboarding() {// The tour runs on the starter project, so on a computer it opens behind// the slides, and lifting them reveals it loaded. A starter the server only- // seeds as the slides end opens then. Once per open, and never over the- // starter already underneath.+ // seeds as the slides end opens once that write lands. Once per open, and+ // never over the starter already underneath.const starterReady = state?.starterReady ?? false;useEffect(() => {- if (!toTour || !starterReady || !userId || (!run && !handedOver) || openedStarter.current) return;+ if (!toTour || !starterReady || !userId || (!run && !handedOver) || openedStarter.current) {+ return;+ }+ if (handedOver && !seeded) {+ return;+ }openedStarter.current = true;const href = projectHref(base, starterProjectId(userId), "projects");- if (underneath.current === href) return;+ if (underneath.current === href) {+ return;+ }router.push(href);- }, [toTour, handedOver, run, starterReady, userId, router, base]);+ }, [toTour, handedOver, seeded, run, starterReady, userId, router, base]);const back = useCallback(() => {commitReferrals();@@ -301,7 +308,9 @@ export function CutOnboarding() {// third, silent one, so forward stops there. A subscriber never sees that// slide, and on a computer the tour comes next, so forward off their last// one is how the sequence ends.- if (isPro || toTour) leave(false);+ if (isPro || toTour) {+ leave(false);+ }return;}setStep(step + 1);diff --git a/site/src/cut/components/onboarding/StarterTour.tsx b/site/src/cut/components/onboarding/StarterTour.tsxindex b3e3ebb0..4cff3598 100644--- a/site/src/cut/components/onboarding/StarterTour.tsx+++ b/site/src/cut/components/onboarding/StarterTour.tsx@@ -279,7 +279,8 @@ export function StarterTour({ projectId }: { projectId: string }) {});};- // Doing the thing counts from the start, even before the highlight lands.+ // Doing the thing counts from the start, even before the highlight lands,+ // once the state it reads is clear.unwatch = watchDone(spec.done, complete);void (spec.approach?.(abort.signal) ?? Promise.resolve()).then(show);@@ -514,11 +515,18 @@ function replyLanded(): Promise<void> {});}-// Calls `onDone` once `done` holds, checking now and on every editor or tour-// signal change.+// Calls `onDone` once `done` turns true, checking now and on every editor or+// tour signal change. It has to read false first, so state left from before+// the step, such as the Media tab already open, waits for the step's prepare+// to clear it and counts only once the person does the thing again.function watchDone(done: () => boolean, onDone: () => void): () => void {+ let armed = false;const check = () => {- if (done()) {+ if (!done()) {+ armed = true;+ return;+ }+ if (armed) {onDone();}};diff --git a/site/src/cut/lib/tourLock.ts b/site/src/cut/lib/tourLock.tsindex e86a767f..e79c40d2 100644--- a/site/src/cut/lib/tourLock.ts+++ b/site/src/cut/lib/tourLock.ts@@ -3,11 +3,13 @@// The starter tour's hold on new projects. While an account owes the tour, the// onboarding host in the app shell registers here, and every way of making a// project asks first: newProjectAllowed for the home, the sidebar, a file drop-// and a duplicate, and the shared view's copy. A held ask sends the account-// back to the tour. The ChatGPT card mounts no host, so nothing holds there.+// and a duplicate. The shared view runs outside the app shell, so its copy+// reads the account's stage itself. A held ask sends the account back to the+// tour. The ChatGPT card mounts no host, so nothing holds there.import { useCallback } from "react";import { useRouter } from "next/navigation";+import { useQueryClient } from "@tanstack/react-query";import { useEngineUser } from "@/cut/lib/backend/hooks";import { useEnvironment } from "@/cut/lib/environment";@@ -15,7 +17,7 @@ import { projectHref, useCutBase } from "@/cut/lib/nav";import { starterProjectId } from "@/cut/lib/starter";import { track } from "@/lib/analytics";import { onboardingStage } from "@/lib/onboarding/stage";-import { useOnboardingState } from "@/queries/onboarding";+import { fetchOnboardingState, onboardingQueryKey, useOnboardingState } from "@/queries/onboarding";let resumeTour: (() => void) | null = null;@@ -39,6 +41,18 @@ export function tourHoldsProjects(): boolean {return true;}+/** The shared view's copy: true when the tour holds new projects, with the+ * account already on its way to its starter. Read fresh, since the view has+ * no app shell keeping the account's stage. */+export async function tourHoldsCopy(userId: string, base: string): Promise<boolean> {+ if (onboardingStage(await fetchOnboardingState()) !== "tour") {+ return false;+ }+ track("onboarding_tour_resumed");+ window.location.href = projectHref(base, starterProjectId(userId), "projects");+ return true;+}+/** Whether the tour holds new projects for this account, and the way back to* it: the starter project, where the tour picks up at its next step. */export function useTourLock(): { locked: boolean; resume: () => void } {@@ -67,3 +81,20 @@ export function useTourHoldsStarter(projectId: string | null): boolean {const userId = useEngineUser();return locked && userId !== null && projectId === starterProjectId(userId);}++/** Rereads the account's onboarding once a removed project was its starter.+ * The account row then says the starter is gone, the tour hands over to the+ * plans, and nothing sends the account to a project that no longer exists. */+export function useStarterGone(): (projectId: string) => void {+ const queryClient = useQueryClient();+ const userId = useEngineUser();+ return useCallback(+ (projectId: string) => {+ if (!userId || projectId !== starterProjectId(userId)) {+ return;+ }+ void queryClient.invalidateQueries({ queryKey: onboardingQueryKey });+ },+ [queryClient, userId],+ );+}diff --git a/site/src/cut/server/cloud/starter.ts b/site/src/cut/server/cloud/starter.tsindex 0d32bebc..fb07a492 100644--- a/site/src/cut/server/cloud/starter.ts+++ b/site/src/cut/server/cloud/starter.ts@@ -15,12 +15,14 @@ import path from "node:path";import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";import { starterProjectId } from "@/cut/lib/starter";import type { ProjectDoc } from "@/cut/lib/types";-import type { Prisma } from "@/generated/prisma/client";+import { Prisma } from "@/generated/prisma/client";import { prisma } from "@/lib/prisma";import { contentTypeFor } from "../serveFile";import { copy, head, projectMediaKey, putObject } from "./r2";const STARTER_DIR = "cut-starter";+// Prisma's code for a unique constraint the write would break.+const UNIQUE_VIOLATION = "P2002";const starterMediaKey = (fileName: string) => `cut/starter/media/${fileName}`;/** A file from public/cut-starter — from disk where the public folder is on the@@ -74,6 +76,25 @@ export async function seedStarterProject(userId: string): Promise<void> {}));+ // Two seeds racing on one account land one project; the second finds the+ // id taken and has nothing left to do.+ try {+ await landStarter(userId, id, doc, media, threads);+ } catch (e) {+ if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === UNIQUE_VIOLATION) {+ return;+ }+ throw e;+ }+}++async function landStarter(+ userId: string,+ id: string,+ doc: ProjectDoc,+ media: { fileName: string; bytes: number; mime: string }[],+ threads: { id: string }[],+): Promise<void> {await prisma.$transaction(async (tx) => {await tx.cutProject.create({data: { id, userId, name: doc.name, doc: doc as unknown as Prisma.InputJsonValue },diff --git a/site/src/queries/onboarding.ts b/site/src/queries/onboarding.tsindex bcbc8343..a7d827d9 100644--- a/site/src/queries/onboarding.ts+++ b/site/src/queries/onboarding.ts@@ -27,9 +27,14 @@ type OnboardingUpdate =| { restart: true }| { tourStep: TourStep };+/** The account's onboarding row as it stands now. */+export async function fetchOnboardingState(): Promise<OnboardingState> {+ return readState(await apiFetch<Partial<OnboardingState>>("/api/account/onboarding"));+}+export function useOnboardingState() {return useQuery({- queryFn: async () => readState(await apiFetch<Partial<OnboardingState>>("/api/account/onboarding")),+ queryFn: fetchOnboardingState,queryKey: onboardingQueryKey,// The sequence decides once per load whether to open; refetching behind an// open overlay could only close it mid-run.@@ -94,12 +99,20 @@ function readState(state: Partial<OnboardingState>): OnboardingState {// 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.+ // The server seeds the starter as the slides end, so the stage moves on to+ // the tour; the starter itself opens once the reply lands.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: [] };+ return {+ ...state,+ completedAt: null,+ skipped: false,+ slidesDoneAt: new Date().toISOString(),+ starterReady: true,+ tourSteps: [],+ };}if ("tourStep" in update) {return state.tourSteps.includes(update.tourStep)