Open source CapCut alternative.
TypeScript
feat(site): track how the upsells convert
David Le7ead239094fa
diff --git a/site/src/app/[locale]/cut/app/(home)/settings/_components/ProCard.tsx b/site/src/app/[locale]/cut/app/(home)/settings/_components/ProCard.tsxindex 54944b6c..07830bc6 100644--- a/site/src/app/[locale]/cut/app/(home)/settings/_components/ProCard.tsx+++ b/site/src/app/[locale]/cut/app/(home)/settings/_components/ProCard.tsx@@ -158,7 +158,7 @@ export function ProCard() {) : null}<CardFooter className="gap-3">{plan !== PAID_PLANS[PAID_PLANS.length - 1] ? (- <Button onClick={() => openUpgrade("plans")}>{isActive ? t("upgrade") : t("seePlans")}</Button>+ <Button onClick={() => openUpgrade("plans", "settings")}>{isActive ? t("upgrade") : t("seePlans")}</Button>) : null}{isActive ? (<Buttondiff --git a/site/src/app/[locale]/cut/app/(home)/settings/page.tsx b/site/src/app/[locale]/cut/app/(home)/settings/page.tsxindex fbd41cf5..bbe4bdb1 100644--- a/site/src/app/[locale]/cut/app/(home)/settings/page.tsx+++ b/site/src/app/[locale]/cut/app/(home)/settings/page.tsx@@ -1,12 +1,20 @@"use client";+import { useEffect } from "react";+import { CreditsCard } from "@/app/[locale]/cut/app/(home)/settings/_components/CreditsCard";import { ProCard } from "@/app/[locale]/cut/app/(home)/settings/_components/ProCard";import { SettingsGuard } from "@/cut/components/SettingsGuard";+import { track } from "@/lib/analytics";++// The query Stripe's checkout, and an in-place upgrade, come back with.+const CHECKOUT_PARAM = "checkout";+const CHECKOUT_RESULTS = ["success", "cancelled"] as const;// Cut's billing page: the subscription that carries the monthly AI credits,// plus the credit balance.export default function CutBillingPage() {+ useCheckoutReturn();return (<SettingsGuard><div className="max-w-2xl space-y-6 pb-9">@@ -16,3 +24,18 @@ export default function CutBillingPage() {</SettingsGuard>);}++// Reports the trip back from checkout once, then drops the query so a reload+// does not count it again.+function useCheckoutReturn() {+ useEffect(() => {+ const url = new URL(window.location.href);+ const result = CHECKOUT_RESULTS.find((r) => r === url.searchParams.get(CHECKOUT_PARAM));+ if (!result) {+ return;+ }+ track("checkout_returned", { result });+ url.searchParams.delete(CHECKOUT_PARAM);+ window.history.replaceState(null, "", url);+ }, []);+}diff --git a/site/src/cut/components/CreditsPill.tsx b/site/src/cut/components/CreditsPill.tsxindex 0225e42e..573598ad 100644--- a/site/src/cut/components/CreditsPill.tsx+++ b/site/src/cut/components/CreditsPill.tsx@@ -110,7 +110,7 @@ function PlanCard({ balance }: { balance: string }) {<div className="flex items-center justify-between gap-3 px-4 py-3"><span className="font-semibold">{plan ? PLAN_TERMS[plan].name : t("creditsPill.free")}</span>{subscription.data && plan !== PAID_PLANS[PAID_PLANS.length - 1] ? (- <Button size="sm" onClick={() => openUpgrade("plans")}>+ <Button size="sm" onClick={() => openUpgrade("plans", "credits_pill")}>{t("creditsPill.upgrade")}</Button>) : null}diff --git a/site/src/cut/components/GenerateCost.tsx b/site/src/cut/components/GenerateCost.tsxindex 377e9e4d..4906e750 100644--- a/site/src/cut/components/GenerateCost.tsx+++ b/site/src/cut/components/GenerateCost.tsx@@ -42,5 +42,5 @@ export function useGenerateCost(price: (sheet: CreditPriceSheet) => bigint | nul/** The Generate button's press: the upgrade wall when the balance falls* short, the generation otherwise. */export function generateButton(cost: GenerateCost, go: () => void): { onClick: () => void } {- return { onClick: cost.short ? () => void openUpgrade("credits") : go };+ return { onClick: cost.short ? () => void openUpgrade("credits", "generate_button") : go };}diff --git a/site/src/cut/components/NavStorage.tsx b/site/src/cut/components/NavStorage.tsxindex 9d20c719..c6143e3f 100644--- a/site/src/cut/components/NavStorage.tsx+++ b/site/src/cut/components/NavStorage.tsx@@ -45,7 +45,7 @@ export function NavStorage() {<buttontype="button"className="group flex cursor-pointer items-center justify-between gap-2 rounded-lg px-2 py-2 text-xs transition-colors hover:bg-muted disabled:opacity-50"- onClick={() => openUpgrade("plans")}+ onClick={() => openUpgrade("plans", "storage_meter")}/>}>diff --git a/site/src/cut/components/PlansDialog.tsx b/site/src/cut/components/PlansDialog.tsxindex 8467b500..c2212003 100644--- a/site/src/cut/components/PlansDialog.tsx+++ b/site/src/cut/components/PlansDialog.tsx@@ -15,6 +15,7 @@ import { Dialog, DialogBody, DialogContent, DialogDescription, DialogHeader, Diaimport { priceLabel } from "@/cut/components/IntroOffer";import { OfferSticker } from "@/cut/components/OfferSticker";import { usePlanCheckout } from "@/cut/lib/proUpgrade";+import type { UpgradeEntry } from "@/cut/lib/upgrade";import { track } from "@/lib/analytics";import { planRank, RECOMMENDED_PLAN, type PaidPlan } from "@/lib/billing/plans";import { cn } from "@/lib/utils";@@ -29,13 +30,15 @@ export type PlansSource = "credits" | "projects" | "storage" | "plans";export function PlansDialog({source,+ entry,title,body,notice,onClose,}: {- // What raised it, for analytics.+ // What raised it, and the button or limit that did, for analytics.source: PlansSource;+ entry: UpgradeEntry;// The headline: one short line.title: React.ReactNode;// A small line under it, for the detail.@@ -51,29 +54,43 @@ export function PlansDialog({const subscription = useProSubscription();const current = subscription.data?.plan ?? null;const intro = useIntroOffer({ enabled: subscription.data?.isActive === false });- const checkout = usePlanCheckout();+ const checkout = usePlanCheckout({ surface: "plans_dialog", reason: source, entry });// Held until the plan is known, so no column opens buyable and then locks.const ready = subscription.isSuccess && (current !== null || !intro.isPending);// Opening focuses the card itself, so no plan's button starts out looking// picked; Tab moves into the plans.const popup = useRef<HTMLDivElement>(null);- const tracked = useRef(false);+ const shownAt = useRef<number | null>(null);useEffect(() => {- if (!ready || tracked.current) {+ if (!ready || shownAt.current !== null) {return;}- tracked.current = true;+ shownAt.current = Date.now();track("upgrade_dialog_shown", {reason: source,+ entry,pro: current !== null,plan: current ?? "free",intro: intro.data?.percentOff ?? 0,});- }, [ready, source, current, intro.data]);+ }, [ready, source, entry, current, intro.data]);++ // A close is a dismissal: a picked plan leaves the page for checkout.+ const close = () => {+ const seconds = shownAt.current === null ? 0 : Math.round((Date.now() - shownAt.current) / 1000);+ track("upgrade_dialog_closed", {+ reason: source,+ entry,+ plan: current ?? "free",+ intro: intro.data?.percentOff ?? 0,+ seconds,+ });+ onClose();+ };return (- <Dialog open={ready} onOpenChange={(open) => !open && onClose()}>+ <Dialog open={ready} onOpenChange={(open) => !open && close()}><DialogContent ref={popup} initialFocus={popup} className="gap-0 overflow-hidden p-0 sm:max-w-[60rem]">{/* A wash of the accent behind the heading. */}<div className="bg-gradient-to-b from-[#0071e3]/12 to-transparent px-6 pt-9 pb-7 text-center dark:from-[#0a84ff]/18 sm:px-10">diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsxindex 49eeabeb..c9c348df 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 { checkoutErrorCode } from "@/cut/lib/proUpgrade";import { homeHref, projectHref, useCutBase } from "@/cut/lib/nav";import { daysUntil, formatDate, formatTime } from "@/cut/lib/time";import {@@ -225,11 +226,12 @@ function GraceBanner({ enabled }: { enabled: boolean }) {className="h-auto p-0"disabled={checkout.isPending}onClick={async () => {- track("pro_checkout_started");+ track("pro_checkout_started", { plan: "pro", surface: "grace_banner" });try {const { url } = await checkout.mutateAsync();window.location.assign(url);- } catch {+ } catch (error) {+ track("pro_checkout_failed", { plan: "pro", error: checkoutErrorCode(error), surface: "grace_banner" });window.location.assign(`${base}/settings`);}}}diff --git a/site/src/cut/components/StorageUpgradeDialog.tsx b/site/src/cut/components/StorageUpgradeDialog.tsxindex 124696f5..43b7ecd6 100644--- a/site/src/cut/components/StorageUpgradeDialog.tsx+++ b/site/src/cut/components/StorageUpgradeDialog.tsx@@ -21,6 +21,7 @@ import {type StorageQuotaDetail,} from "@/cut/lib/storageQuota";import { daysUntil } from "@/cut/lib/time";+import type { UpgradeEntry } from "@/cut/lib/upgrade";import { track } from "@/lib/analytics";import { PAID_PLANS } from "@/lib/billing/plans";import { useProSubscription } from "@/queries/billing";@@ -28,6 +29,13 @@ import { useCloudUsage } from "@/cut/lib/backend/hooks";import { onOperationFailure } from "@/cut/lib/operationFailure";import { formatBytes } from "@/lib/bytes";+// What raised the storage wall, as the plans name where they were met.+const STORAGE_ENTRY: Record<StorageQuotaDetail["source"], UpgradeEntry> = {+ "quota-413": "storage_refused",+ render: "render_refused",+ pill: "storage_pill",+};+export function StorageUpgradeDialog() {const [detail, setDetail] = useState<StorageQuotaDetail | null>(null);@@ -108,6 +116,7 @@ function OpenDialog({ detail, onClose }: { detail: StorageQuotaDetail; onClose:return (<PlansDialogsource="storage"+ entry={STORAGE_ENTRY[detail.source]}title={detail.source === "pill" ? t("storage.moreTitle") : t("storage.fullTitle")}body={used}notice={grace}diff --git a/site/src/cut/components/UpgradeDialog.tsx b/site/src/cut/components/UpgradeDialog.tsxindex 0da75783..cf01b80e 100644--- a/site/src/cut/components/UpgradeDialog.tsx+++ b/site/src/cut/components/UpgradeDialog.tsx@@ -8,34 +8,35 @@ import { useEffect, useState } from "react";import { PlansDialog } from "@/cut/components/PlansDialog";import { onOperationFailure } from "@/cut/lib/operationFailure";-import { onUpgrade, openUpgrade, type UpgradeReason } from "@/cut/lib/upgrade";+import { onUpgrade, openUpgrade, type UpgradeRequest } from "@/cut/lib/upgrade";import { PAID_PLANS, PLAN_TERMS } from "@/lib/billing/plans";import { useProSubscription } from "@/queries/billing";export function UpgradeDialog() {- const [reason, setReason] = useState<UpgradeReason | null>(null);+ const [request, setRequest] = useState<UpgradeRequest | null>(null);- useEffect(() => onUpgrade(setReason), []);+ useEffect(() => onUpgrade(setRequest), []);// A request refused for credits always raises the plans.useEffect(() =>onOperationFailure((failure) => {if (failure.code === "insufficient_credits" || failure.code === "insufficient_credits_for_generation") {- openUpgrade("credits");+ openUpgrade("credits", "credits_refused");}}),[],);- if (!reason) {+ if (!request) {return null;}- return <OpenDialog reason={reason} onClose={() => setReason(null)} />;+ return <OpenDialog request={request} onClose={() => setRequest(null)} />;}// Split so the billing read only runs while the dialog is up.-function OpenDialog({ reason, onClose }: { reason: UpgradeReason; onClose: () => void }) {+function OpenDialog({ request, onClose }: { request: UpgradeRequest; onClose: () => void }) {+ const { reason, entry } = request;const t = useTranslations("billing");const format = useFormatter();const subscription = useProSubscription();@@ -61,5 +62,5 @@ function OpenDialog({ reason, onClose }: { reason: UpgradeReason; onClose: () =>? { title: t("upgrade.projectsTitle"), body: t("upgrade.projectsBody") }: { title: t("plans.chooseTitle"), body: t("plans.chooseBody") };- return <PlansDialog source={reason} {...wall} onClose={onClose} />;+ return <PlansDialog source={reason} entry={entry} {...wall} onClose={onClose} />;}diff --git a/site/src/cut/components/hostedError.tsx b/site/src/cut/components/hostedError.tsxindex fe8b4f81..836ff2bc 100644--- a/site/src/cut/components/hostedError.tsx+++ b/site/src/cut/components/hostedError.tsx@@ -10,7 +10,7 @@ import { useDescribeError } from "@/i18n/describeError";/** Opens the upgrade dialog on its credits wall. A surface without the dialog* (the ChatGPT card) opens the settings page, where plans are sold. */export function openCreditsWall(): void {- if (openUpgrade("credits")) {+ if (openUpgrade("credits", "credits_link")) {return;}window.open(creditsUrl(), "_blank", "noreferrer");diff --git a/site/src/cut/components/onboarding/CutOnboarding.tsx b/site/src/cut/components/onboarding/CutOnboarding.tsxindex 8c825b4a..8c8380e2 100644--- a/site/src/cut/components/onboarding/CutOnboarding.tsx+++ b/site/src/cut/components/onboarding/CutOnboarding.tsx@@ -336,7 +336,7 @@ export function CutOnboarding() {/>)}{slide === "ai-chat" && <AiChatSlide />}- {slide === "plans" && <PlansSlide onSkipPro={() => finish(false)} />}+ {slide === "plans" && <PlansSlide run={run} onSkipPro={() => finish(false)} />}</div><div aria-hidden className="flex-[3]" /></div>diff --git a/site/src/cut/components/onboarding/slides/Plans.tsx b/site/src/cut/components/onboarding/slides/Plans.tsxindex 9bb2ee5e..696dcb92 100644--- a/site/src/cut/components/onboarding/slides/Plans.tsx+++ b/site/src/cut/components/onboarding/slides/Plans.tsx@@ -2,6 +2,7 @@import { ArrowLeft, Check, Loader2, Sparkles } from "lucide-react";import { useLocale, useTranslations } from "next-intl";+import { useEffect, useRef } from "react";import { TapedCard } from "@/app/_components/landing/LandingPrimitives";import type { CardColor } from "@/app/_components/landing/theme";@@ -10,7 +11,9 @@ import { Button } from "@/components/ui/button";import { priceLabel } from "@/cut/components/IntroOffer";import { OfferSticker } from "@/cut/components/OfferSticker";import { usePlanCheckout } from "@/cut/lib/proUpgrade";+import { track } from "@/lib/analytics";import { RECOMMENDED_PLAN, type PaidPlan } from "@/lib/billing/plans";+import type { OnboardingRun } from "@/lib/onboarding/sequence";import { useIntroOffer, type IntroOffer } from "@/queries/billing";import "../onboarding.css";@@ -27,11 +30,23 @@ const PLAN_CARD: Record<PaidPlan, { color: CardColor; tapeColor: CardColor }> =// nobody has to take a price on faith. Checkout is the one the upgrade modal// starts. While the intro offer is open the Pro card prices the discount and// counts down to its end.-export function PlansSlide({ onSkipPro }: { onSkipPro: () => void }) {+export function PlansSlide({ run, onSkipPro }: { run: OnboardingRun; onSkipPro: () => void }) {const t = useTranslations("onboarding.plans");const plans = useCutPlans();- const checkout = usePlanCheckout();- const offer = useIntroOffer().data ?? null;+ const checkout = usePlanCheckout({ surface: "onboarding" });+ const intro = useIntroOffer();+ const offer = intro.data ?? null;++ // Reported once the offer read settles, so the event says whether the+ // discount was on the card.+ const tracked = useRef(false);+ useEffect(() => {+ if (intro.isPending || tracked.current) {+ return;+ }+ tracked.current = true;+ track("onboarding_plans_shown", { source: run, intro: intro.data?.percentOff ?? 0 });+ }, [intro.isPending, intro.data, run]);return (<div className="mx-auto w-full max-w-[1040px]">diff --git a/site/src/cut/lib/proUpgrade.ts b/site/src/cut/lib/proUpgrade.tsindex 6e2c50a3..619d5664 100644--- a/site/src/cut/lib/proUpgrade.ts+++ b/site/src/cut/lib/proUpgrade.ts@@ -6,21 +6,34 @@import { useState } from "react";import type { PaidPlan } from "@/lib/billing/plans";-import { track } from "@/lib/analytics";+import { track, type CheckoutOrigin } from "@/lib/analytics";+import { ApiError } from "@/queries/apiClient";import { useStartCheckout } from "@/queries/billing";-export function usePlanCheckout() {+/** A checkout's failure as analytics names it: the API's error code, the+ * HTTP status when the route sent none, or "network". */+export function checkoutErrorCode(error: unknown): string {+ if (!(error instanceof ApiError)) {+ return "network";+ }+ return error.code ?? `http_${error.status}`;+}++export function usePlanCheckout(origin: CheckoutOrigin) {const checkout = useStartCheckout();const [pendingPlan, setPendingPlan] = useState<PaidPlan | null>(null);const start = (plan: PaidPlan) => {- track("pro_checkout_started", { plan });+ track("pro_checkout_started", { plan, ...origin });setPendingPlan(plan);checkout.mutate({ plan },{onSuccess: ({ url }) => window.location.assign(url),- onError: () => setPendingPlan(null),+ onError: (error) => {+ setPendingPlan(null);+ track("pro_checkout_failed", { plan, error: checkoutErrorCode(error), ...origin });+ },},);};diff --git a/site/src/cut/lib/projectLimit.ts b/site/src/cut/lib/projectLimit.tsindex a0dbcda7..83daf708 100644--- a/site/src/cut/lib/projectLimit.ts+++ b/site/src/cut/lib/projectLimit.ts@@ -41,6 +41,6 @@ export async function newProjectAllowed(client: QueryClient): Promise<boolean> {}track("project_limit_hit", { limit });- openUpgrade("projects");+ openUpgrade("projects", "project_limit");return false;}diff --git a/site/src/cut/lib/upgrade.ts b/site/src/cut/lib/upgrade.tsindex 714f81b5..7d20cd65 100644--- a/site/src/cut/lib/upgrade.ts+++ b/site/src/cut/lib/upgrade.ts@@ -3,18 +3,34 @@// raises it.export type UpgradeReason = "projects" | "credits" | "plans";-const listeners = new Set<(reason: UpgradeReason) => void>();+// The button or limit that raised the wall, for analytics: where in the app+// people meet the plans. The storage entries come from the storage wall.+export type UpgradeEntry =+ | "credits_pill"+ | "storage_meter"+ | "settings"+ | "generate_button"+ | "credits_link"+ | "credits_refused"+ | "project_limit"+ | "storage_pill"+ | "storage_refused"+ | "render_refused";++export type UpgradeRequest = { reason: UpgradeReason; entry: UpgradeEntry };++const listeners = new Set<(request: UpgradeRequest) => void>();/** True when a dialog is mounted to show the wall. A surface without one* (the ChatGPT card) says the limit in its own words. */-export function openUpgrade(reason: UpgradeReason): boolean {+export function openUpgrade(reason: UpgradeReason, entry: UpgradeEntry): boolean {for (const listener of listeners) {- listener(reason);+ listener({ reason, entry });}return listeners.size > 0;}-export function onUpgrade(handler: (reason: UpgradeReason) => void): () => void {+export function onUpgrade(handler: (request: UpgradeRequest) => void): () => void {listeners.add(handler);return () => {listeners.delete(handler);diff --git a/site/src/lib/analytics.ts b/site/src/lib/analytics.tsindex c84982c1..f0c32028 100644--- a/site/src/lib/analytics.ts+++ b/site/src/lib/analytics.ts@@ -4,11 +4,23 @@ import { useEffect } from "react";import type { PerfLogBatch } from "@/cut/lib/perfLog";import type { MainThreadSample, PerfSample } from "@/cut/lib/perfTrace";import type { ShortcutDecline } from "@/cut/lib/shortcutGate";+import type { UpgradeEntry } from "@/cut/lib/upgrade";import type {OnboardingRun,ReferralSource,} from "@/lib/onboarding/sequence";+// What the plans modal opened for: a limit hit, or the plans asked for.+type PlansReason = "projects" | "credits" | "storage" | "plans";++// Where a plan's checkout started: the plans modal, with what raised it and+// the button or limit that did; the onboarding's plans slide; or the storage+// grace banner on the projects home.+export type CheckoutOrigin =+ | { surface: "plans_dialog"; reason: PlansReason; entry: UpgradeEntry }+ | { surface: "onboarding" }+ | { surface: "grace_banner" };+// Every product analytics event, in one place. `track` checks the name and// its properties against this map at compile time, so call sites can't drift// from the list. Events with `void` properties take no second argument.@@ -24,6 +36,8 @@ export type AnalyticsEvents = {referralOther?: string;};onboarding_completed: { source: OnboardingRun; skipped: boolean; step: number };+ // The sequence's plans slide came up; intro as on the plans modal.+ onboarding_plans_shown: { source: OnboardingRun; intro: number };// Cut projects home.project_created: { source: "projects_home" | "sidebar" | "file_import" | "chatgpt_card" };folder_created: void;@@ -32,8 +46,11 @@ export type AnalyticsEvents = {// The top bar's credits pill.cut_credits_pill_clicked: { credits: number; dollars: number };cut_storage_upgrade_shown: { source: "quota-413" | "render" | "pill" };- // The upgrade wall at a free limit; intro is the open discount's percent, 0 for none.- upgrade_dialog_shown: { reason: "projects" | "credits" | "storage" | "plans"; pro: boolean; plan: string; intro: number };+ // The plans modal: shown, and closed without a checkout after `seconds` up.+ // entry is the button or limit that raised it; intro is the open discount's+ // percent, 0 for none.+ upgrade_dialog_shown: { reason: PlansReason; entry: UpgradeEntry; pro: boolean; plan: string; intro: number };+ upgrade_dialog_closed: { reason: PlansReason; entry: UpgradeEntry; plan: string; intro: number; seconds: number };project_limit_hit: { limit: number };cut_grace_banner_shown: void;// First exposure to an experiment variant; the same value rides every@@ -63,7 +80,11 @@ export type AnalyticsEvents = {subscribe_bonus_offered: { dollars: number };subscribe_bonus_checkout_started: { dollars: number; minutesLeft: number; source: "editor" | "settings" | "email" };// Billing (settings).- pro_checkout_started: { plan: string } | void;+ // A plan picked, the checkout that failed to start (error is the API's+ // code), and the trip back from Stripe or an in-place upgrade.+ pro_checkout_started: { plan: string } & CheckoutOrigin;+ pro_checkout_failed: { plan: string; error: string } & CheckoutOrigin;+ checkout_returned: { result: "success" | "cancelled" };billing_portal_opened: void;};