Open source CapCut alternative.
TypeScript
feat(site): show Cut cloud storage and offer the upgrade where it runs out
David Le3c390b7d36af
diff --git a/site/src/app/cut/app/(home)/layout.tsx b/site/src/app/cut/app/(home)/layout.tsxindex 517cc839..8da75a7f 100644--- a/site/src/app/cut/app/(home)/layout.tsx+++ b/site/src/app/cut/app/(home)/layout.tsx@@ -1,10 +1,14 @@import { AppSidebar } from "@/cut/components/AppSidebar";+import { StorageUpgradeDialog } from "@/cut/components/StorageUpgradeDialog";export default function HomeLayout({ children }: { children: React.ReactNode }) {return (<div className="flex h-screen bg-background"><AppSidebar /><main className="min-w-0 flex-1 overflow-y-auto">{children}</main>+ {/* Every home surface uploads — projects, library — so the quota wall+ answers from the layout rather than from each page. */}+ <StorageUpgradeDialog /></div>);}diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex 9d584e57..83997b67 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -24,6 +24,7 @@ import { Lightbox } from "./Lightbox";import { Preview } from "./Preview";import { SidePanel } from "./SidePanel";import { Timeline } from "./Timeline";+import { StorageUpgradeDialog } from "./StorageUpgradeDialog";import { TopBar } from "./TopBar";import { ViewerTopBar } from "./ViewerTopBar";@@ -608,6 +609,7 @@ export function Editor({</Button></div>)}+ <StorageUpgradeDialog /><Lightbox /></div>);diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsxindex 62d7a7cf..b9104826 100644--- a/site/src/cut/components/ProjectsHome.tsx+++ b/site/src/cut/components/ProjectsHome.tsx@@ -47,19 +47,20 @@ import {import { Input } from "@/components/ui/input";import { engineLost, engineOrigin, servedFromEngine } from "@/cut/lib/api";import { cloudBackend, quotaErrorMessage } from "@/cut/lib/backend/cloud";-import { useCutMode } from "@/cut/lib/backend/hooks";+import { useCloudUsage, useCutMode } from "@/cut/lib/backend/hooks";import { localBackend } from "@/cut/lib/backend/local";import type { CutBackend } from "@/cut/lib/backend/types";import { useWebMode, webModeEnabled } from "@/cut/lib/flags";import { track } from "@/lib/analytics";import { authClient } from "@/lib/auth-client";+import { useStartCheckout } from "@/queries/billing";import { clearProjectThreads } from "@/cut/lib/chatThreads";import { useGenerate } from "@/cut/lib/generate";import { useGenScene } from "@/cut/lib/genScene";import { createProjectFromFile, isMediaFile } from "@/cut/lib/media";import { copyProjectAcross } from "@/cut/lib/projectCopy";import { homeHref, projectHref, useCutBase } from "@/cut/lib/nav";-import { formatTime } from "@/cut/lib/time";+import { daysUntil, formatTime } from "@/cut/lib/time";import type { ProjectFolder, ProjectSummary } from "@/cut/lib/types";import { cn } from "@/lib/utils";import { buildDragGhost, FolderCrumb, FolderShelf, formatBytes, Marquee } from "./desktopFolders";@@ -112,6 +113,51 @@ function ResidencyBadge({ residency, className }: { residency: Residency; classN);}+/** After a Pro plan ends, an over-cap account has a countdown before the daily+ * sweep reclaims its oldest projects. Say so where the projects are. */+function GraceBanner({ enabled }: { enabled: boolean }) {+ // A deletion deadline moves once a day; one read per visit is plenty.+ const usage = useCloudUsage(enabled, { poll: false });+ const checkout = useStartCheckout();+ const base = useCutBase();+ const grace = usage.data?.grace;+ const shown = useRef(false);+ useEffect(() => {+ if (grace && !shown.current) {+ shown.current = true;+ track("cut_grace_banner_shown");+ }+ }, [grace]);+ if (!grace) return null;+ const days = daysUntil(grace.deadline);+ return (+ <div className="mb-4 flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">+ <span className="text-destructive">+ Your Pro plan ended and you’re over the free storage limit. Your oldest cloud projects+ will be deleted {days === 0 ? "today" : `in ${days} day${days === 1 ? "" : "s"}`} unless you+ upgrade or free {formatBytes(grace.overBytes)}.+ </span>+ <Button+ variant="link"+ size="sm"+ className="h-auto p-0"+ disabled={checkout.isPending}+ onClick={async () => {+ track("pro_checkout_started");+ try {+ const { url } = await checkout.mutateAsync("pro");+ window.location.assign(url);+ } catch {+ window.location.assign(`${base}/settings`);+ }+ }}+ >+ Upgrade to Pro+ </Button>+ </div>+ );+}+export function ProjectsHome() {const router = useRouter();const base = useCutBase();@@ -785,6 +831,8 @@ export function ProjectsHome() {</div>)}+ <GraceBanner enabled={residencies.includes("cloud")} />+{dupError && <p className="mb-4 text-sm text-destructive">{dupError}</p>}{!anySettled ? (diff --git a/site/src/cut/components/StoragePill.tsx b/site/src/cut/components/StoragePill.tsxnew file mode 100644index 00000000..a66ffb3e--- /dev/null+++ b/site/src/cut/components/StoragePill.tsx@@ -0,0 +1,85 @@+"use client";++// The top bar's subscription surface for cloud projects, one slot with two+// mutually exclusive faces: free accounts see their storage usage (click →+// upgrade dialog); a Pro set to cancel sees the days it has left (click →+// Stripe portal, where Resume lives).+import { Loader2 } from "lucide-react";+import { useCloudUsage, useCutMode } from "@/cut/lib/backend/hooks";+import { openStorageUpgrade } from "@/cut/lib/storageQuota";+import { daysUntil } from "@/cut/lib/time";+import { track } from "@/lib/analytics";+import { cn } from "@/lib/utils";+import { useOpenBillingPortal, useProSubscription } from "@/queries/billing";+import { formatBytes } from "./desktopFolders";++const PILL =+ "flex items-center gap-1.5 rounded-full border border-border bg-card px-3 py-1.5 text-xs font-medium shadow-xs transition-colors";++export function StoragePill() {+ const cloud = useCutMode() === "cloud";+ if (!cloud) return null;+ return <CloudStoragePill />;+}++function CloudStoragePill() {+ const pro = useProSubscription();+ // The meter has to move as media lands, so this reader is the polling one.+ const usage = useCloudUsage(pro.data?.isActive === false, { poll: true });+ const portal = useOpenBillingPortal();++ if (!pro.data) return null;++ if (pro.data.isActive) {+ const end = pro.data.cancelAtPeriodEnd ? pro.data.currentPeriodEnd : null;+ if (!end) return null;+ const days = daysUntil(end);+ return (+ <button+ className={cn(PILL, "text-muted-foreground hover:text-foreground")}+ title="Resume your subscription"+ disabled={portal.isPending}+ onClick={async () => {+ track("billing_portal_opened");+ try {+ const { url } = await portal.mutateAsync();+ window.location.assign(url);+ } catch {+ // Portal unavailable — leave the pill as-is.+ }+ }}+ >+ {portal.isPending && <Loader2 className="size-3 animate-spin" />}+ Pro · {days === 0 ? "ends today" : `ends in ${days} day${days === 1 ? "" : "s"}`}+ </button>+ );+ }++ const u = usage.data;+ if (!u || u.quotaBytes === null) return null;+ const frac = u.bytes / u.quotaBytes;+ return (+ <button+ className={cn(+ PILL,+ frac >= 1+ ? "text-destructive"+ : frac >= 0.8+ ? "text-amber-600 dark:text-amber-500"+ : "text-muted-foreground hover:text-foreground"+ )}+ title="Cloud storage"+ onClick={() => {+ track("cut_storage_pill_clicked");+ openStorageUpgrade({+ bytes: u.bytes,+ quotaBytes: u.quotaBytes ?? undefined,+ source: "pill",+ grace: u.grace,+ });+ }}+ >+ {formatBytes(u.bytes)} of {formatBytes(u.quotaBytes)}+ </button>+ );+}diff --git a/site/src/cut/components/StorageUpgradeDialog.tsx b/site/src/cut/components/StorageUpgradeDialog.tsxnew file mode 100644index 00000000..12113bd6--- /dev/null+++ b/site/src/cut/components/StorageUpgradeDialog.tsx@@ -0,0 +1,117 @@+"use client";++// The storage-quota wall's face: opens when an upload is rejected for space+// anywhere in the app, or when the top bar's pill is clicked, and sells the+// Pro storage tier — or just explains, when the account already has it.+import { useEffect, useState } from "react";+import { Loader2 } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { useCutBase } from "@/cut/lib/nav";+import {+ clearStorageQuotaWall,+ onStorageQuota,+ type StorageQuotaDetail,+} from "@/cut/lib/storageQuota";+import { daysUntil } from "@/cut/lib/time";+import { track } from "@/lib/analytics";+import { useProSubscription, useStartCheckout } from "@/queries/billing";+import { formatBytes } from "./desktopFolders";++export function StorageUpgradeDialog() {+ const [detail, setDetail] = useState<StorageQuotaDetail | null>(null);++ useEffect(+ () =>+ onStorageQuota((d) => {+ setDetail(d);+ track("cut_storage_upgrade_shown", { source: d.source });+ }),+ []+ );++ const close = () => {+ setDetail(null);+ clearStorageQuotaWall();+ };++ if (!detail) return null;+ return <OpenDialog detail={detail} onClose={close} />;+}++// Split so the billing query only runs while the dialog is up.+function OpenDialog({ detail, onClose }: { detail: StorageQuotaDetail; onClose: () => void }) {+ const pro = useProSubscription();+ const checkout = useStartCheckout();+ const base = useCutBase();+ const isPro = pro.data?.isActive === true;++ const used =+ detail.bytes !== undefined && detail.quotaBytes !== undefined+ ? `You've used ${formatBytes(detail.bytes)} of ${formatBytes(detail.quotaBytes)}.`+ : null;+ const graceDays = detail.grace ? daysUntil(detail.grace.deadline) : null;++ const upgrade = async () => {+ track("pro_checkout_started");+ try {+ const { url } = await checkout.mutateAsync("pro");+ window.location.assign(url);+ } catch {+ // Checkout can't start (an unconfigured plan 404s); the billing page+ // carries the same subscribe action, so send them there rather than+ // leaving the button dead.+ window.location.assign(`${base}/settings`);+ }+ };++ return (+ <Dialog open onOpenChange={(open) => !open && onClose()}>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>+ {detail.source === "quota-413" ? "Cloud storage is full" : "Cloud storage"}+ </DialogTitle>+ </DialogHeader>+ <div className="space-y-2 text-sm text-muted-foreground">+ {used && <p>{used}</p>}+ {detail.grace && graceDays !== null && (+ <p className="text-destructive">+ Your Pro plan ended. Your oldest cloud projects will be deleted{" "}+ {graceDays === 0 ? "today" : `in ${graceDays} day${graceDays === 1 ? "" : "s"}`}{" "}+ unless you upgrade or free {formatBytes(detail.grace.overBytes)}.+ </p>+ )}+ <p>+ {isPro+ ? "Free up space by deleting projects or media you no longer need."+ : "Pro includes 50 GB of cloud storage, or free up space by deleting media."}+ </p>+ </div>+ <DialogFooter className="mt-2">+ {isPro ? (+ <Button className="w-full" onClick={onClose}>+ OK+ </Button>+ ) : (+ <div className="flex w-full flex-col gap-2">+ <Button className="w-full" disabled={checkout.isPending} onClick={() => void upgrade()}>+ {checkout.isPending && <Loader2 className="animate-spin" data-icon="inline-start" />}+ Upgrade to Pro+ </Button>+ <Button variant="ghost" className="w-full" onClick={onClose}>+ Not now+ </Button>+ </div>+ )}+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/site/src/cut/components/TopBar.tsx b/site/src/cut/components/TopBar.tsxindex b180c0a2..190793dc 100644--- a/site/src/cut/components/TopBar.tsx+++ b/site/src/cut/components/TopBar.tsx@@ -1,7 +1,8 @@"use client";-import { useState } from "react";+import { useEffect, useRef, useState } from "react";import Link from "next/link";+import { useQueryClient } from "@tanstack/react-query";import { Check, ChevronDown, ChevronLeft, Cloud, Loader2, Mic, Monitor, Ratio, Share2, Smartphone, Sparkles, Square, Upload, Video } from "lucide-react";import { Button } from "@/components/ui/button";import {@@ -18,7 +19,7 @@ import {DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import { cloudBackend } from "@/cut/lib/backend/cloud";-import { useCutMode } from "@/cut/lib/backend/hooks";+import { cloudUsageQueryKey, useCutMode } from "@/cut/lib/backend/hooks";import { localBackend } from "@/cut/lib/backend/local";import { useWebMode } from "@/cut/lib/flags";import { backTarget, projectHref, useCutBase } from "@/cut/lib/nav";@@ -29,6 +30,7 @@ import { ASPECT_PRESETS, aspectLabel, aspectOrientation, normalizeAspect, parseRimport { cn } from "@/lib/utils";import { RecordDialog, type RecordMode } from "./RecordDialog";import { ShareDialog } from "./ShareDialog";+import { StoragePill } from "./StoragePill";function AspectIcon({ aspect, className }: { aspect: Aspect; className?: string }) {const o = aspectOrientation(aspect);@@ -125,6 +127,16 @@ export function TopBar({// Cloud imports are real uploads worth reporting; local imports are instant// disk copies, so the flag-off surface stays exactly as it was.const cloudUploading = uploading > 0 && cutMode === "cloud";+ // Uploads settle in bursts; refresh the storage pill's number when a burst+ // ends. Only the settling edge counts — on mount nothing has landed yet.+ const queryClient = useQueryClient();+ const wasUploading = useRef(false);+ useEffect(() => {+ if (wasUploading.current && !cloudUploading) {+ void queryClient.invalidateQueries({ queryKey: cloudUsageQueryKey });+ }+ wasUploading.current = cloudUploading;+ }, [cloudUploading, queryClient]);const [shareOpen, setShareOpen] = useState(false);const [moveOpen, setMoveOpen] = useState(false);const [moving, setMoving] = useState(false);@@ -340,6 +352,7 @@ export function TopBar({</span></div><div className="flex items-center gap-2">+ <StoragePill />{cutMode === "cloud" && (<Buttonvariant="ghost"diff --git a/site/src/cut/lib/backend/cloud.ts b/site/src/cut/lib/backend/cloud.tsindex 9332cc3d..f3f4badc 100644--- a/site/src/cut/lib/backend/cloud.ts+++ b/site/src/cut/lib/backend/cloud.ts@@ -3,6 +3,7 @@// the session). Routes mirror the engine's JSON shapes under /api/cut-cloud.// Media bytes ride presigned R2 URLs minted by those routes, not this// transport.+import { emitStorageQuota } from "../storageQuota";import type { CutBackend } from "./types";const cloudPath = (path: string) => path.replace(/^\/api\/cut\//, "/api/cut-cloud/");@@ -100,14 +101,16 @@ export async function fetchSignedMediaUrls(return out;}-/** Friendly message for a presign 413 quota rejection, else null. */+/** Friendly message for a presign 413 quota rejection, else null. Also raises+ * the storage-quota wall so the upgrade dialog opens wherever the rejection+ * happened — this inline string stays as the terse fallback next to it. */export function quotaErrorMessage(status: number,- body: { error?: string } | null | undefined+ body: { error?: string; bytes?: number; quotaBytes?: number } | null | undefined): string | null {- return status === 413 && body?.error === "storage_quota_exceeded"- ? "Cloud storage is full — free space in your projects or delete unused media."- : null;+ if (status !== 413 || body?.error !== "storage_quota_exceeded") return null;+ emitStorageQuota({ bytes: body?.bytes, quotaBytes: body?.quotaBytes, source: "quota-413" });+ return "Cloud storage is full.";}export const cloudBackend: CutBackend = {diff --git a/site/src/cut/lib/backend/hooks.ts b/site/src/cut/lib/backend/hooks.tsindex 0f0b1046..2a54d98e 100644--- a/site/src/cut/lib/backend/hooks.ts+++ b/site/src/cut/lib/backend/hooks.ts@@ -1,5 +1,6 @@// React bindings for the backend seam, kept out of ./index so the engine// binary (which compiles lib/types.ts → ./index) never bundles React.+import { useQuery } from "@tanstack/react-query";import { useSyncExternalStore } from "react";import { cutMode, getBackend, subscribeCutMode } from "./index";@@ -13,3 +14,30 @@ export function useCutCaps(): CutCaps {useCutMode();return getBackend().caps;}++export const cloudUsageQueryKey = ["cut", "cloud-usage"] as const;++export type CloudUsage = {+ bytes: number;+ /** null = unlimited. */+ quotaBytes: number | null;+ /** Present when the account's Pro ended and it holds more than the free cap:+ * the sweep reclaims storage after `deadline` unless `overBytes` is freed. */+ grace?: { deadline: string; overBytes: number };+};++/** The account's cloud storage usage — cloud-only by construction, so it hits+ * the hosted route directly on the session cookie. `poll` is for the editor's+ * live meter; readers that only need the number once should leave it off. */+export function useCloudUsage(enabled: boolean, opts?: { poll?: boolean }) {+ return useQuery<CloudUsage>({+ enabled,+ queryKey: cloudUsageQueryKey,+ queryFn: async () => {+ const res = await fetch("/api/cut-cloud/usage");+ if (!res.ok) throw new Error(`usage ${res.status}`);+ return (await res.json()) as CloudUsage;+ },+ ...(opts?.poll ? { refetchInterval: 60_000 } : {}),+ });+}diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.tsindex 48517b48..8e145a45 100644--- a/site/src/cut/lib/media.ts+++ b/site/src/cut/lib/media.ts@@ -197,7 +197,9 @@ export async function uploadProjectImage(body: form,});const body = await apiJson<MediaAsset>(res);- if (!res.ok || !body.fileName) throw new Error(body.error ?? failMessage);+ if (!res.ok || !body.fileName) {+ throw new Error(quotaErrorMessage(res.status, body) ?? body.error ?? failMessage);+ }return { ...body, url: mediaUrl(projectId, body.fileName) };}const stored = await uploadProjectMediaTo(backend, projectId, file, fileName);diff --git a/site/src/cut/lib/storageQuota.ts b/site/src/cut/lib/storageQuota.tsnew file mode 100644index 00000000..a5c8006e--- /dev/null+++ b/site/src/cut/lib/storageQuota.ts@@ -0,0 +1,40 @@+// The storage-quota wall: one contract shared by the code that hits the limit+// (the cloud transport's 413 handler) and the dialog that offers the upgrade.+// It lives in lib so the React-free transport can raise it.++export type StorageQuotaDetail = {+ bytes?: number;+ quotaBytes?: number;+ source: "quota-413" | "pill";+ grace?: { deadline: string; overBytes: number };+};++const EVENT = "cut-storage-quota";++// A rejected upload rejects once per file, and every file in the batch is over+// the same limit. The first one raises the wall; the rest are the same event,+// so they stay quiet until the user has answered it.+let walled = false;++export function emitStorageQuota(detail: StorageQuotaDetail): void {+ if (typeof window === "undefined" || walled) return;+ walled = true;+ window.dispatchEvent(new CustomEvent(EVENT, { detail }));+}++/** Open the dialog from a deliberate click, past any standing wall. */+export function openStorageUpgrade(detail: StorageQuotaDetail): void {+ walled = false;+ emitStorageQuota(detail);+}++/** Called when the dialog closes: the next rejection is news again. */+export function clearStorageQuotaWall(): void {+ walled = false;+}++export function onStorageQuota(handler: (detail: StorageQuotaDetail) => void): () => void {+ const listener = (e: Event) => handler((e as CustomEvent<StorageQuotaDetail>).detail);+ window.addEventListener(EVENT, listener);+ return () => window.removeEventListener(EVENT, listener);+}diff --git a/site/src/cut/lib/time.ts b/site/src/cut/lib/time.tsindex 0f3fa7d7..f304819d 100644--- a/site/src/cut/lib/time.ts+++ b/site/src/cut/lib/time.ts@@ -1,3 +1,9 @@+/** Whole days left until an ISO timestamp, floored at zero — anything inside+ * the last day reads as 0, so "today" means today. */+export function daysUntil(iso: string): number {+ return Math.max(0, Math.floor((new Date(iso).getTime() - Date.now()) / 86_400_000));+}+/** Elapsed wall-clock as "m:ss" — 63400ms -> "1:03". */export function formatElapsed(ms: number) {const t = Math.max(0, Math.floor(ms / 1000));diff --git a/site/src/lib/analytics.ts b/site/src/lib/analytics.tsindex 5581ca34..4e15e2a1 100644--- a/site/src/lib/analytics.ts+++ b/site/src/lib/analytics.ts@@ -22,6 +22,10 @@ export type AnalyticsEvents = {// Cut projects home.project_created: { source: "projects_home" | "sidebar" | "file_import" };folder_created: void;+ // Cut cloud storage limits.+ cut_storage_pill_clicked: void;+ cut_storage_upgrade_shown: { source: "quota-413" | "pill" };+ cut_grace_banner_shown: void;// Billing (settings).pro_checkout_started: void;billing_portal_opened: void;