Skip to content

Open source CapCut alternative.

TypeScript

feat(site): wall free limits with an upgrade dialog

David Le830c7afa00cf
diff --git a/site/src/app/cut/app/(home)/layout.tsx b/site/src/app/cut/app/(home)/layout.tsx
index 570eea4e..21277025 100644
--- a/site/src/app/cut/app/(home)/layout.tsx
+++ b/site/src/app/cut/app/(home)/layout.tsx
@@ -3,6 +3,7 @@ import { Suspense } from "react";
import { AppSidebar } from "@/cut/components/AppSidebar";
import { ClaimCreditsDialog } from "@/cut/components/ClaimCreditsDialog";
import { StorageUpgradeDialog } from "@/cut/components/StorageUpgradeDialog";
+import { UpgradeDialog } from "@/cut/components/UpgradeDialog";
export default function HomeLayout({ children }: { children: React.ReactNode }) {
return (
@@ -12,6 +13,7 @@ export default function HomeLayout({ children }: { children: React.ReactNode })
{/* Every home surface uploads — projects, library — so the quota wall
answers from the layout rather than from each page. */}
<StorageUpgradeDialog />
+ <UpgradeDialog />
{/* A credit offer's email link lands on the home with ?claim=…; the
dialog reads the address, so it needs a boundary in the prerendered
shell. */}
diff --git a/site/src/clients/chatgpt/server/projects.ts b/site/src/clients/chatgpt/server/projects.ts
index 2c7136ea..c66d6961 100644
--- a/site/src/clients/chatgpt/server/projects.ts
+++ b/site/src/clients/chatgpt/server/projects.ts
@@ -2,6 +2,7 @@ import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
import { getCreditBalance } from "@/lib/credits/inference";
import { getActiveProSubscription } from "@/lib/billing/pro-subscription";
+import { cloudProjectsFull } from "@/lib/billing/project-limit-server";
import { isDonkeySuperUser } from "@/lib/super-user";
import { normalizeAspect, type ProjectDoc } from "@/cut/lib/types";
import { ADOPT_COMMAND, type AdoptedAsset } from "@/cut/lib/commandBatch";
@@ -431,6 +432,9 @@ export function projectTools(
requireEdit();
const frame = aspect ? normalizeAspect(aspect) : null;
if (aspect && !frame) throw new ProjectToolError('aspect must be "W:H", like "9:16" or "16:9".');
+ if (await cloudProjectsFull(identity.userId)) {
+ throw new ProjectToolError("This account is at its free project limit. Upgrade to Pro in Donkey Cut to make more projects.");
+ }
const now = Date.now();
const doc: ProjectDoc = {
version: 1,
diff --git a/site/src/cut/components/AppSidebar.tsx b/site/src/cut/components/AppSidebar.tsx
index a15f6935..c06bb1a1 100644
--- a/site/src/cut/components/AppSidebar.tsx
+++ b/site/src/cut/components/AppSidebar.tsx
@@ -23,6 +23,7 @@ import { NewProjectButton } from "@/cut/components/NewProjectButton";
import { NavUser } from "@/cut/components/NavUser";
import { homeHref, projectHref, tabForPath, useCutBase, type CutTab } from "@/cut/lib/nav";
import type { ProjectSummary } from "@/cut/lib/types";
+import { newProjectAllowed } from "@/cut/lib/projectLimit";
import { cn } from "@/lib/utils";
const NAV: { tab: CutTab; label: string; icon: typeof Clapperboard }[] = [
@@ -51,6 +52,10 @@ export function AppSidebar() {
const create = async (r: Residency) => {
setBusy(true);
try {
+ if (!(await newProjectAllowed(client))) {
+ setCreateIn(null);
+ return;
+ }
const res = await backendFor(r).fetch("/api/cut/projects", {
method: "POST",
headers: { "Content-Type": "application/json" },
diff --git a/site/src/cut/components/AudioPanel.tsx b/site/src/cut/components/AudioPanel.tsx
index 51b8fe88..a7f7a9c8 100644
--- a/site/src/cut/components/AudioPanel.tsx
+++ b/site/src/cut/components/AudioPanel.tsx
@@ -48,7 +48,7 @@ import { STOCK_MUSIC } from "@/cut/lib/stockMusicManifest";
import { stockAssetInDoc } from "@/cut/lib/genvideo/docWriter";
import { signInUrl, useSignedIn } from "@/cut/lib/generate";
import { HostedErrorText } from "./hostedError";
-import { CostTag, NOT_ENOUGH_CREDITS, useGenerateCost } from "./GenerateCost";
+import { CostTag, generateButton, NOT_ENOUGH_CREDITS, useGenerateCost } from "./GenerateCost";
import { musicMicros } from "@/lib/credits/price-sheet";
import { genPulseOverlay, useActiveWork, useGenNotify } from "@/cut/lib/genNotify";
import { enrichAsset } from "@/cut/lib/media";
@@ -228,6 +228,7 @@ function MusicGenerator({ projectId }: { projectId: string }) {
const variantLabel = MUSIC_VARIANTS.find((v) => v.id === variant) ?? MUSIC_VARIANTS[0];
// Every take renders a track at the length's flat price.
const cost = useGenerateCost((sheet) => musicMicros(sheet, variant, takes));
+ const button = generateButton(cost, () => void generate());
return (
<div className="music-generator flex flex-col gap-3.5">
@@ -311,9 +312,9 @@ function MusicGenerator({ projectId }: { projectId: string }) {
</div>
<Button
className="music-generate w-full"
- disabled={!prompt.trim() || signedOut || cost.short}
+ disabled={!prompt.trim() || signedOut || button.blocked}
title={!prompt.trim() ? "Describe the music above to generate" : undefined}
- onClick={() => void generate()}
+ onClick={button.onClick}
>
<Music data-icon="inline-start" />
{cost.short ? NOT_ENOUGH_CREDITS : "Generate music"}
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index c3ae41b5..4d611d5c 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -84,6 +84,7 @@ import { SidePanel } from "./SidePanel";
import { SpeedCurveStrip } from "./SpeedCurveStrip";
import { Timeline } from "./Timeline";
import { StorageUpgradeDialog } from "./StorageUpgradeDialog";
+import { UpgradeDialog } from "./UpgradeDialog";
import { TopBar } from "./TopBar";
import { ViewerTopBar } from "./ViewerTopBar";
@@ -1304,6 +1305,7 @@ export function Editor({
</div>
)}
{!chatgpt && <StorageUpgradeDialog />}
+ {!chatgpt && <UpgradeDialog />}
<Lightbox />
</div>
);
diff --git a/site/src/cut/components/EmbeddedNewProject.tsx b/site/src/cut/components/EmbeddedNewProject.tsx
index b1a123fd..19fc169a 100644
--- a/site/src/cut/components/EmbeddedNewProject.tsx
+++ b/site/src/cut/components/EmbeddedNewProject.tsx
@@ -2,12 +2,14 @@
import { useState } from "react";
import { useRouter } from "next/navigation";
+import { useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { cloudBackend } from "@/cut/lib/backend/cloud";
import { seedNewProjectDoc } from "@/cut/lib/docCache";
import { framedHref } from "@/cut/lib/hostBridge";
import { projectHref, useCutBase } from "@/cut/lib/nav";
+import { newProjectAllowed } from "@/cut/lib/projectLimit";
import { lastChosenAspect } from "@/cut/lib/store";
import type { ProjectSummary } from "@/cut/lib/types";
import { track } from "@/lib/analytics";
@@ -18,6 +20,7 @@ import { track } from "@/lib/analytics";
export function EmbeddedNewProject() {
const router = useRouter();
const base = useCutBase();
+ const client = useQueryClient();
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -25,6 +28,10 @@ export function EmbeddedNewProject() {
setBusy(true);
setError(null);
try {
+ // The card carries no upgrade wall, so the limit is said here.
+ if (!(await newProjectAllowed(client))) {
+ throw new Error("This account is at its free project limit. Upgrade to Pro in Donkey Cut to make more.");
+ }
const aspect = lastChosenAspect() ?? undefined;
const res = await cloudBackend.fetch("/api/cut/projects", {
method: "POST",
diff --git a/site/src/cut/components/GenerateCost.tsx b/site/src/cut/components/GenerateCost.tsx
index 0c71884a..ffa03ebb 100644
--- a/site/src/cut/components/GenerateCost.tsx
+++ b/site/src/cut/components/GenerateCost.tsx
@@ -1,14 +1,17 @@
"use client";
// The price of the next generation, shown on its Generate button before it
-// spends anything. A price above the balance disables the button; the 402 the
-// server would answer is the same check, in the same micros.
+// spends anything. A price above the balance disables the button, or, while
+// the out-of-credits upsell is on, turns it into the way to the upgrade wall;
+// the 402 the server would answer is the same check, in the same micros.
import { Zap } from "lucide-react";
import { useEnvironment } from "@/cut/lib/environment";
import { useSignedIn } from "@/cut/lib/generate";
+import { openUpgrade } from "@/cut/lib/upgrade";
import { creditMicrosToString, creditStringToMicros } from "@/lib/credits/amounts";
import { creditsFromDollars, formatCreditCount } from "@/lib/credits/format-credits";
import type { CreditPriceSheet } from "@/lib/credits/price-sheet";
+import { useAccountConfig } from "@/queries/accountConfig";
import { useCreditBalance, useCreditPriceSheet } from "@/queries/credits";
import { useLiveCreditBalance } from "./CreditsPill";
@@ -20,9 +23,11 @@ export type GenerateCost = {
credits: number | null;
/** The balance is read and falls short of the price. */
short: boolean;
+ /** Short, and the button opens the upgrade wall when pressed. */
+ walled: boolean;
};
-const UNPRICED: GenerateCost = { credits: null, short: false };
+const UNPRICED: GenerateCost = { credits: null, short: false, walled: false };
/** Prices one generation from the sheet, in micros; null leaves it unpriced.
* The ChatGPT card carries no credit readings, so the price stays off there. */
@@ -31,6 +36,7 @@ export function useGenerateCost(price: (sheet: CreditPriceSheet) => bigint | nul
const enabled = useSignedIn() === true && !chatgpt;
const sheet = useCreditPriceSheet({ enabled });
const balance = useCreditBalance({ enabled, freshness: "reuse" });
+ const config = useAccountConfig({ enabled });
useLiveCreditBalance();
if (!enabled || !sheet.data) {
return UNPRICED;
@@ -42,7 +48,17 @@ export function useGenerateCost(price: (sheet: CreditPriceSheet) => bigint | nul
}
const credits = creditsFromDollars(creditMicrosToString(micros), "up");
const short = balance.data ? creditStringToMicros(balance.data.balance) < micros : false;
- return { credits, short };
+ const walled = short && config.data?.settings.outOfCreditsUpsell.mode === "dialog";
+ return { credits, short, walled };
+}
+
+/** The Generate button's state: disabled when short with no wall to show,
+ * and pressing it opens the wall in place of generating when there is one. */
+export function generateButton(cost: GenerateCost, go: () => void): { blocked: boolean; onClick: () => void } {
+ return {
+ blocked: cost.short && !cost.walled,
+ onClick: cost.walled ? () => void openUpgrade("credits") : go,
+ };
}
/** The price beside the button label: "⚡ 1,318". */
diff --git a/site/src/cut/components/GeneratePanel.tsx b/site/src/cut/components/GeneratePanel.tsx
index db5ec4cb..21f94ce3 100644
--- a/site/src/cut/components/GeneratePanel.tsx
+++ b/site/src/cut/components/GeneratePanel.tsx
@@ -40,7 +40,7 @@ import { CopyHandlePill, MentionTextarea, RefChips } from "./AssetRefs";
import { DictationControl } from "./MicDictation";
import { GeneratedAssetMenu } from "./GeneratedAssetMenu";
import { HostedErrorText } from "./hostedError";
-import { CostTag, NOT_ENOUGH_CREDITS, useGenerateCost } from "./GenerateCost";
+import { CostTag, generateButton, NOT_ENOUGH_CREDITS, useGenerateCost } from "./GenerateCost";
import { cardIconButton } from "./iconButton";
import { PillSelect } from "./PillSelect";
import { ScrollArea } from "@/components/ui/scroll-area";
@@ -135,6 +135,8 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
useVideoGen.getState().openWith("");
};
+ const button = generateButton(cost, go);
+
return (
<>
<div className="flex h-12 shrink-0 items-center justify-between pr-2.5 pl-4">
@@ -270,8 +272,8 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
<Button
className="gen-go w-full shrink-0"
- disabled={!prompt.trim() || signedIn === false || cost.short}
- onClick={go}
+ disabled={!prompt.trim() || signedIn === false || button.blocked}
+ onClick={button.onClick}
>
<Sparkles data-icon="inline-start" />
{cost.short ? NOT_ENOUGH_CREDITS : "Generate video"}
diff --git a/site/src/cut/components/ImageGenPanel.tsx b/site/src/cut/components/ImageGenPanel.tsx
index 0d4ab546..10f9234b 100644
--- a/site/src/cut/components/ImageGenPanel.tsx
+++ b/site/src/cut/components/ImageGenPanel.tsx
@@ -31,7 +31,7 @@ import { cardIconButton } from "./iconButton";
import { PillSelect } from "./PillSelect";
import { GeneratedAssetMenu } from "./GeneratedAssetMenu";
import { HostedErrorText } from "./hostedError";
-import { CostTag, NOT_ENOUGH_CREDITS, useGenerateCost } from "./GenerateCost";
+import { CostTag, generateButton, NOT_ENOUGH_CREDITS, useGenerateCost } from "./GenerateCost";
import { ScrollArea } from "@/components/ui/scroll-area";
// The generate-image panel: an always-on column in the Image tab, sitting left
@@ -107,6 +107,8 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {
void useGenerate.getState().generateImage(projectId, text, { refs: all, aspect, resolution });
};
+ const button = generateButton(cost, go);
+
return (
<div ref={attachTarget} {...targetProps} className="relative flex min-h-0 flex-1 flex-col">
<div className="flex h-12 shrink-0 items-center pr-2.5 pl-4">
@@ -183,8 +185,8 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {
<Button
className="w-full shrink-0"
- disabled={!prompt.trim() || signedIn === false || cost.short}
- onClick={go}
+ disabled={!prompt.trim() || signedIn === false || button.blocked}
+ onClick={button.onClick}
>
<Sparkles data-icon="inline-start" />
{cost.short ? NOT_ENOUGH_CREDITS : "Generate image"}
diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsx
index 914ccc7a..2065ee01 100644
--- a/site/src/cut/components/ProjectsHome.tsx
+++ b/site/src/cut/components/ProjectsHome.tsx
@@ -74,6 +74,7 @@ import { useGenScene } from "@/cut/lib/genScene";
import { createProjectFromFile, isMediaFile } from "@/cut/lib/media";
import { dropLocalProjectCopy, localMediaUrl } from "@/cut/lib/mediaSync";
import { copyProjectAcross } from "@/cut/lib/projectCopy";
+import { newProjectAllowed } from "@/cut/lib/projectLimit";
import { homeHref, projectHref, useCutBase } from "@/cut/lib/nav";
import { daysUntil, formatDate, formatTime } from "@/cut/lib/time";
import {
@@ -480,6 +481,10 @@ export function ProjectsHome() {
// for a document we can describe in full.
const openNewProject = async (r: Residency, pname: string, folderId: string | null) => {
if (!live(r)) return;
+ if (!(await newProjectAllowed(client))) {
+ setCreateIn(null);
+ return;
+ }
// The frame the editor would open this project at is written into the doc
// at creation, so the card shows that shape before the editor's first save.
const aspect = lastChosenAspect() ?? undefined;
@@ -522,7 +527,11 @@ export function ProjectsHome() {
const media = Array.from(files).filter(isMediaFile);
if (media.length === 0) return;
setImporting((n) => n + media.length);
- for (const file of media) {
+ for (const [i, file] of media.entries()) {
+ if (!(await newProjectAllowed(client))) {
+ setImporting((n) => n - (media.length - i));
+ break;
+ }
try {
await createProjectFromFile(file, folderId);
track("project_created", { source: "file_import" });
@@ -534,7 +543,7 @@ export function ProjectsHome() {
await refresh(homeMode);
}
},
- [refresh, homeMode]
+ [refresh, homeMode, client]
);
const rename = async () => {
@@ -558,6 +567,7 @@ export function ProjectsHome() {
const duplicate = async (r: Residency, p: ProjectSummary) => {
if (!live(r)) return;
+ if (!(await newProjectAllowed(client))) return;
setBusy(true);
setDupError(null);
try {
diff --git a/site/src/cut/components/UpgradeDialog.tsx b/site/src/cut/components/UpgradeDialog.tsx
new file mode 100644
index 00000000..fff840e7
--- /dev/null
+++ b/site/src/cut/components/UpgradeDialog.tsx
@@ -0,0 +1,146 @@
+"use client";
+
+// The wall a free account meets at a paid limit: one project past the free
+// count, or a request that ran out of credits. Both sell Pro. A Pro account
+// that runs out is sent to buy credits.
+import { useEffect, useState } from "react";
+import { useRouter } from "next/navigation";
+import { FolderPlus, Loader2, Zap } from "lucide-react";
+
+import { CUT_PRO } from "@/app/cut/_components/landing/cutPricingPlans";
+import { introTerms, wallBanner } from "@/cut/components/IntroOffer";
+import { OfferButton, OfferDialog, OfferDismiss } from "@/cut/components/OfferDialog";
+import { useCutBase } from "@/cut/lib/nav";
+import { onOperationFailure } from "@/cut/lib/operationFailure";
+import { useUpgradeToPro } from "@/cut/lib/proUpgrade";
+import { onUpgrade, openUpgrade, type UpgradeReason } from "@/cut/lib/upgrade";
+import { track } from "@/lib/analytics";
+import { creditCountLabel, creditsPerDollar } from "@/lib/credits/format-credits";
+import { useAccountConfig } from "@/queries/accountConfig";
+import { useIntroOffer, useProSubscription } from "@/queries/billing";
+
+export function UpgradeDialog() {
+ const [reason, setReason] = useState<UpgradeReason | null>(null);
+ const config = useAccountConfig({ enabled: true });
+ const creditsMode = config.data?.settings.outOfCreditsUpsell.mode ?? "off";
+
+ useEffect(() => onUpgrade(setReason), []);
+
+ // A request refused for credits raises the wall while the setting asks for
+ // it; otherwise the inline notice where the request failed is the answer.
+ useEffect(() => {
+ if (creditsMode !== "dialog") {
+ return;
+ }
+ return onOperationFailure((failure) => {
+ if (failure.code === "insufficient_credits" || failure.code === "insufficient_credits_for_generation") {
+ openUpgrade("credits");
+ }
+ });
+ }, [creditsMode]);
+
+ if (!reason) {
+ return null;
+ }
+ return (
+ <OpenDialog
+ reason={reason}
+ projectLimit={config.data?.settings.freeProjectLimit.projects ?? null}
+ onClose={() => setReason(null)}
+ />
+ );
+}
+
+// Split so the billing reads only run while the dialog is up.
+function OpenDialog({
+ reason,
+ projectLimit,
+ onClose,
+}: {
+ reason: UpgradeReason;
+ projectLimit: number | null;
+ onClose: () => void;
+}) {
+ const pro = useProSubscription();
+ const isPro = pro.data?.isActive === true;
+ const intro = useIntroOffer({ enabled: pro.data?.isActive === false });
+ const upgrade = useUpgradeToPro();
+ const base = useCutBase();
+ const router = useRouter();
+ const ready = pro.isSuccess && (isPro || !intro.isPending);
+
+ useEffect(() => {
+ if (!ready) {
+ return;
+ }
+ track("upgrade_dialog_shown", { reason, pro: isPro, intro: intro.data?.percentOff ?? 0 });
+ }, [ready, reason, isPro, intro.data]);
+
+ // Held until the plan is known, so the card never opens on the wrong pitch.
+ if (!ready) {
+ return null;
+ }
+
+ const close = (open: boolean) => {
+ if (!open) {
+ onClose();
+ }
+ };
+
+ if (isPro) {
+ return (
+ <OfferDialog
+ open
+ onOpenChange={close}
+ banner="credits"
+ title="You're out of credits"
+ body="This month's Pro credits are spent. Buy more to keep generating."
+ cta={
+ <OfferButton
+ onClick={() => {
+ onClose();
+ router.push(`${base}/settings`);
+ }}
+ >
+ Buy credits
+ </OfferButton>
+ }
+ secondary={<OfferDismiss onClick={onClose}>Not now</OfferDismiss>}
+ />
+ );
+ }
+
+ const offer = intro.data ?? null;
+ const credits = creditCountLabel(CUT_PRO.monthlyDollars * creditsPerDollar);
+ const wall =
+ reason === "projects"
+ ? { icon: FolderPlus, title: "Upgrade to make more projects", body: projectsBody(projectLimit) }
+ : { icon: Zap, title: "You're out of credits", body: `Pro comes with ${credits} every month and 100 GB of cloud storage.` };
+
+ return (
+ <OfferDialog
+ open
+ onOpenChange={close}
+ banner={wallBanner(wall.icon, offer)}
+ closesAt={offer?.endsAt}
+ title={wall.title}
+ body={wall.body}
+ terms={offer ? introTerms(offer) : `Pro is ${CUT_PRO.price}.`}
+ cta={
+ <OfferButton disabled={upgrade.isPending} onClick={upgrade.start}>
+ {upgrade.isPending && <Loader2 className="animate-spin" data-icon="inline-start" />}
+ Upgrade to Pro
+ </OfferButton>
+ }
+ secondary={<OfferDismiss onClick={onClose}>Not now</OfferDismiss>}
+ />
+ );
+}
+
+/** What the free plan holds, as the projects wall says it. */
+function projectsBody(limit: number | null): string {
+ if (!limit) {
+ return "The free plan keeps your starter project. Pro makes as many as you need.";
+ }
+ return `The free plan keeps ${limit} project${limit === 1 ? "" : "s"} besides your starter. Pro makes as many as you need.`;
+}
diff --git a/site/src/cut/lib/projectLimit.ts b/site/src/cut/lib/projectLimit.ts
new file mode 100644
index 00000000..07ecef5b
--- /dev/null
+++ b/site/src/cut/lib/projectLimit.ts
@@ -0,0 +1,44 @@
+// The free plan's project limit, checked before any new project is made: the
+// projects home, the sidebar, a file dropped on the home, a duplicate, and
+// the ChatGPT card all ask here first. A move keeps the count, so it never
+// asks.
+import type { QueryClient } from "@tanstack/react-query";
+
+import { track } from "@/lib/analytics";
+import { countedProjects, projectLimitFull } from "@/lib/billing/project-limit";
+import { accountConfigQueryKey, fetchAccountConfig } from "@/queries/accountConfig";
+import { fetchProSubscription, proSubscriptionQueryKey } from "@/queries/billing";
+
+import { currentEngineUser } from "./api";
+import { listedProjectIds } from "./queries";
+import { openUpgrade } from "./upgrade";
+
+/** True when the account may make another project. When it may not, the
+ * upgrade wall is already up. */
+export async function newProjectAllowed(client: QueryClient): Promise<boolean> {
+ // Signed out, the projects are this browser's own and no plan applies.
+ const userId = currentEngineUser();
+ if (!userId) {
+ return true;
+ }
+
+ const config = await client.ensureQueryData({ queryKey: accountConfigQueryKey, queryFn: fetchAccountConfig });
+ const limit = config.settings.freeProjectLimit.projects;
+ if (limit === null) {
+ return true;
+ }
+
+ const pro = await client.ensureQueryData({ queryKey: proSubscriptionQueryKey, queryFn: fetchProSubscription });
+ if (pro.isActive) {
+ return true;
+ }
+
+ const ids = await listedProjectIds(client);
+ if (!projectLimitFull(countedProjects(ids, userId), limit)) {
+ return true;
+ }
+
+ track("project_limit_hit", { limit });
+ openUpgrade("projects");
+ return false;
+}
diff --git a/site/src/cut/lib/queries.ts b/site/src/cut/lib/queries.ts
index 0cb385e0..7e228407 100644
--- a/site/src/cut/lib/queries.ts
+++ b/site/src/cut/lib/queries.ts
@@ -151,6 +151,27 @@ export function useProjectsSection(r: Residency, { list, live }: { list: boolean
});
}
+/** The ids of every project the account holds on the shelves this browser
+ * knows, read from the listings the home already holds where it has them. A
+ * shelf it can only remember counts what it last listed; one that can't
+ * answer counts nothing. */
+export async function listedProjectIds(client: QueryClient): Promise<string[]> {
+ const live = availableResidencies();
+ const sections = await Promise.all(
+ listedResidencies().map(async (r) => {
+ if (live.includes(r)) {
+ return client.ensureQueryData({ queryKey: projectsKey(r), queryFn: () => fetchProjectsSection(r) }).catch(() => null);
+ }
+ const cached = client.getQueryData<ProjectsSection>(projectsKey(r));
+ if (cached) {
+ return cached;
+ }
+ return (await readSnapshot<ProjectsSection>(projectsSnapshotKey(r)))?.value ?? null;
+ })
+ );
+ return sections.flatMap((s) => s?.projects.map((p) => p.id) ?? []);
+}
+
/** How often a live library listing re-reads. Long enough that an open tab is
* cheap, short enough that a clip finishing its upload from the phone lands on
* screen while the user is still looking at the page. */
diff --git a/site/src/cut/lib/upgrade.ts b/site/src/cut/lib/upgrade.ts
new file mode 100644
index 00000000..40971e46
--- /dev/null
+++ b/site/src/cut/lib/upgrade.ts
@@ -0,0 +1,21 @@
+// The upgrade wall's signal: what a free account just ran into. The dialog
+// listens; anything that hits a paid limit raises it.
+export type UpgradeReason = "projects" | "credits";
+
+const listeners = new Set<(reason: UpgradeReason) => 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 {
+ for (const listener of listeners) {
+ listener(reason);
+ }
+ return listeners.size > 0;
+}
+
+export function onUpgrade(handler: (reason: UpgradeReason) => void): () => void {
+ listeners.add(handler);
+ return () => {
+ listeners.delete(handler);
+ };
+}
diff --git a/site/src/lib/analytics.ts b/site/src/lib/analytics.ts
index 16c636bf..098dca16 100644
--- a/site/src/lib/analytics.ts
+++ b/site/src/lib/analytics.ts
@@ -32,6 +32,9 @@ 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"; pro: boolean; intro: number };
+ project_limit_hit: { limit: number };
cut_grace_banner_shown: void;
// First exposure to an experiment variant; the same value rides every
// later event as a super property ($feature/<experiment>).
diff --git a/site/src/lib/billing/project-limit-server.ts b/site/src/lib/billing/project-limit-server.ts
new file mode 100644
index 00000000..ca4780bd
--- /dev/null
+++ b/site/src/lib/billing/project-limit-server.ts
@@ -0,0 +1,21 @@
+import { starterProjectId } from "@/cut/lib/starter";
+import { getActiveProSubscription } from "@/lib/billing/pro-subscription";
+import { contextForUser, getSetting } from "@/lib/config/effective";
+import { prisma } from "@/lib/prisma";
+
+import { projectLimitFull } from "./project-limit";
+
+/** Whether a free account's cloud projects fill its limit. The cloud is all a
+ * server can count; the page's gate counts every shelf. */
+export async function cloudProjectsFull(userId: string): Promise<boolean> {
+ const { projects: limit } = await getSetting("freeProjectLimit", await contextForUser(userId, null));
+ if (limit === null) {
+ return false;
+ }
+ if (await getActiveProSubscription(userId)) {
+ return false;
+ }
+
+ const counted = await prisma.cutProject.count({ where: { id: { not: starterProjectId(userId) }, userId } });
+ return projectLimitFull(counted, limit);
+}
diff --git a/site/src/lib/billing/project-limit.test.ts b/site/src/lib/billing/project-limit.test.ts
new file mode 100644
index 00000000..be57df2b
--- /dev/null
+++ b/site/src/lib/billing/project-limit.test.ts
@@ -0,0 +1,15 @@
+import { expect, test } from "bun:test";
+
+import { countedProjects, projectLimitFull } from "./project-limit";
+
+test("the starter project never counts", () => {
+ expect(countedProjects(["starter-u1", "a", "b"], "u1")).toBe(2);
+ expect(countedProjects(["starter-u2", "a"], "u1")).toBe(2);
+});
+
+test("null is no limit; a full limit leaves no room", () => {
+ expect(projectLimitFull(500, null)).toBe(false);
+ expect(projectLimitFull(0, 0)).toBe(true);
+ expect(projectLimitFull(1, 2)).toBe(false);
+ expect(projectLimitFull(2, 2)).toBe(true);
+});
diff --git a/site/src/lib/billing/project-limit.ts b/site/src/lib/billing/project-limit.ts
new file mode 100644
index 00000000..36cbfd5f
--- /dev/null
+++ b/site/src/lib/billing/project-limit.ts
@@ -0,0 +1,15 @@
+// The free plan's project limit, as the freeProjectLimit setting states it:
+// how many projects a free account holds besides its starter. Pure, so the
+// page's gate, the ChatGPT tool and the tests read one rule.
+import { starterProjectId } from "@/cut/lib/starter";
+
+/** How many of an account's projects count against the limit. */
+export function countedProjects(ids: string[], userId: string): number {
+ const starter = starterProjectId(userId);
+ return ids.filter((id) => id !== starter).length;
+}
+
+/** Whether `counted` projects leave no room under `limit`; null is no limit. */
+export function projectLimitFull(counted: number, limit: number | null): boolean {
+ return limit !== null && counted >= limit;
+}
diff --git a/site/src/lib/config/effective.ts b/site/src/lib/config/effective.ts
index f2ef5700..e71c5fea 100644
--- a/site/src/lib/config/effective.ts
+++ b/site/src/lib/config/effective.ts
@@ -43,14 +43,20 @@ export function countryFromHeaders(headers: Headers): string | null {
return raw && /^[A-Z]{2}$/.test(raw) ? raw : null;
}
-export async function contextFromRequest(request: DonkeyAuthenticatedRequest): Promise<ConfigContext> {
+export function contextFromRequest(request: DonkeyAuthenticatedRequest): Promise<ConfigContext> {
+ return contextForUser(request.donkey.userId, countryFromHeaders(request.headers));
+}
+
+/** The context for an account acting outside a page request, such as a
+ * ChatGPT tool call. */
+export async function contextForUser(userId: string, country: string | null): Promise<ConfigContext> {
const user = await prisma.user.findUnique({
- where: { id: request.donkey.userId },
+ where: { id: userId },
select: { createdAt: true },
});
return {
- userId: request.donkey.userId,
- country: countryFromHeaders(request.headers),
+ userId,
+ country,
createdAt: user?.createdAt ?? new Date(0),
hasAccount: user !== null,
};
diff --git a/site/src/queries/accountConfig.ts b/site/src/queries/accountConfig.ts
index 592ecf07..7e55a439 100644
--- a/site/src/queries/accountConfig.ts
+++ b/site/src/queries/accountConfig.ts
@@ -29,10 +29,12 @@ function parseAccountConfig(raw: unknown): AccountConfig {
// Fetched once per page load from the session gate. It never refetches on
// focus: a variant switching under someone mid-session is the one thing an
// experiment must not do.
+export const fetchAccountConfig = async () => parseAccountConfig(await apiFetch<unknown>("/api/account/config"));
+
export function useAccountConfig({ enabled }: { enabled: boolean }) {
return useQuery({
enabled,
- queryFn: async () => parseAccountConfig(await apiFetch<unknown>("/api/account/config")),
+ queryFn: fetchAccountConfig,
queryKey: accountConfigQueryKey,
refetchOnWindowFocus: false,
retry: false,