Open source CapCut alternative.
TypeScript
feat(site): per-account feature flags with self-serve settings UI
David Lee66c80bc7fd3
diff --git a/site/prisma/FeatureFlags.prisma b/site/prisma/FeatureFlags.prismanew file mode 100644index 00000000..63937a42--- /dev/null+++ b/site/prisma/FeatureFlags.prisma@@ -0,0 +1,14 @@+// Per-account feature flags, self-serve from the account settings. Known flag+// ids and their copy live in code (src/lib/feature-flags.ts); rows exist only+// for flags a user has touched.++model UserFeatureFlag {+ id String @id @default(cuid())+ userId String+ flag String+ enabled Boolean @default(false)+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@unique([userId, flag])+}diff --git a/site/src/app/api/account/feature-flags/route.ts b/site/src/app/api/account/feature-flags/route.tsnew file mode 100644index 00000000..c5114128--- /dev/null+++ b/site/src/app/api/account/feature-flags/route.ts@@ -0,0 +1,40 @@+import { NextResponse } from "next/server";++import {+ withDonkeyAuth,+ type DonkeyAuthenticatedRequest,+} from "@/lib/donkey-api-auth";+import { ACCOUNT_FEATURE_FLAGS, isKnownFeatureFlag } from "@/lib/feature-flags";+import { prisma } from "@/lib/prisma";++// The signed-in account's feature flags: the full registry with each flag's+// enabled state. Rows exist only for flags the user has touched.+export const GET = withDonkeyAuth(async (request: DonkeyAuthenticatedRequest) => {+ const rows = await prisma.userFeatureFlag.findMany({+ where: { userId: request.donkey.userId },+ });+ const enabled = new Map(rows.map((r) => [r.flag, r.enabled]));+ return NextResponse.json({+ flags: ACCOUNT_FEATURE_FLAGS.map((f) => ({+ ...f,+ enabled: enabled.get(f.id) ?? false,+ })),+ });+});++export const PUT = withDonkeyAuth(async (request: DonkeyAuthenticatedRequest) => {+ const body = (await request.json().catch(() => null)) as {+ flag?: string;+ enabled?: boolean;+ } | null;+ if (!body?.flag || typeof body.enabled !== "boolean" || !isKnownFeatureFlag(body.flag)) {+ return NextResponse.json({ error: "Unknown flag." }, { status: 400 });+ }+ const userId = request.donkey.userId;+ await prisma.userFeatureFlag.upsert({+ where: { userId_flag: { userId, flag: body.flag } },+ create: { userId, flag: body.flag, enabled: body.enabled },+ update: { enabled: body.enabled },+ });+ return NextResponse.json({ ok: true, flag: body.flag, enabled: body.enabled });+});diff --git a/site/src/app/cut/app/(home)/settings/SettingsHeader.tsx b/site/src/app/cut/app/(home)/settings/SettingsHeader.tsxindex 99bfe401..5165299c 100644--- a/site/src/app/cut/app/(home)/settings/SettingsHeader.tsx+++ b/site/src/app/cut/app/(home)/settings/SettingsHeader.tsx@@ -14,6 +14,12 @@ const SECTIONS = [description: "Your AI generation usage this billing period.",pinned: false,},+ {+ suffix: "/settings/flags",+ title: "Feature flags",+ description: "Early features you can turn on for your account.",+ pinned: true,+ },{suffix: "/settings",title: "Billing",diff --git a/site/src/app/cut/app/(home)/settings/flags/page.tsx b/site/src/app/cut/app/(home)/settings/flags/page.tsxnew file mode 100644index 00000000..67a03603--- /dev/null+++ b/site/src/app/cut/app/(home)/settings/flags/page.tsx@@ -0,0 +1,73 @@+"use client";++import { useEffect, useState } from "react";++import { Switch } from "@/components/ui/switch";+import { applyWebModeLocal } from "@/cut/lib/flags";++type FlagRow = { id: string; title: string; description: string; enabled: boolean };++// Self-serve account feature flags. The account is the source of truth; the+// Cut client mirrors "cut-web-mode" locally so the editor reacts to a flip+// without a reload.+export default function CutFeatureFlagsPage() {+ const [flags, setFlags] = useState<FlagRow[] | null>(null);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let alive = true;+ void fetch("/api/account/feature-flags")+ .then(async (res) => {+ if (!res.ok) throw new Error();+ const body = (await res.json()) as { flags: FlagRow[] };+ if (alive) setFlags(body.flags);+ })+ .catch(() => {+ if (alive) setError("Couldn't load your feature flags.");+ });+ return () => {+ alive = false;+ };+ }, []);++ const toggle = (id: string, enabled: boolean) => {+ setFlags((cur) => cur?.map((f) => (f.id === id ? { ...f, enabled } : f)) ?? cur);+ if (id === "cut-web-mode") applyWebModeLocal(enabled);+ void fetch("/api/account/feature-flags", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ flag: id, enabled }),+ }).then((res) => {+ if (res.ok) return;+ // The account write failed; put the switch (and the mirror) back.+ setFlags((cur) => cur?.map((f) => (f.id === id ? { ...f, enabled: !enabled } : f)) ?? cur);+ if (id === "cut-web-mode") applyWebModeLocal(!enabled);+ setError("Couldn't save that change — try again.");+ });+ };++ return (+ <div className="max-w-2xl space-y-6 pb-9">+ <div className="rounded-xl border bg-card p-5">+ {error && <p className="mb-3 text-sm text-red-600">{error}</p>}+ {!flags && !error && <p className="text-sm text-muted-foreground">Loading…</p>}+ {flags?.map((f, i) => (+ <div key={f.id} className={i > 0 ? "mt-4 border-t pt-4" : undefined}>+ <label className="flex items-start justify-between gap-6">+ <span className="min-w-0">+ <span className="block text-sm font-medium">{f.title}</span>+ <span className="mt-0.5 block text-sm text-muted-foreground">+ {f.description}+ </span>+ </span>+ <Switch+ checked={f.enabled}+ onCheckedChange={(v) => toggle(f.id, v === true)}+ />+ </label>+ </div>+ ))}+ </div>+ </div>+ );+}diff --git a/site/src/cut/components/NavUser.tsx b/site/src/cut/components/NavUser.tsxindex bf19aaf1..6b6e0836 100644--- a/site/src/cut/components/NavUser.tsx+++ b/site/src/cut/components/NavUser.tsx@@ -1,7 +1,7 @@"use client";import { useRouter } from "next/navigation";-import { ChartColumn, CreditCard, EllipsisVertical, LogOut } from "lucide-react";+import { ChartColumn, CreditCard, EllipsisVertical, Flag, LogOut } from "lucide-react";import {DropdownMenu,DropdownMenuContent,@@ -79,6 +79,9 @@ export function NavUser() {<DropdownMenuItem onClick={() => router.push(`${base}/settings/usage`)}><ChartColumn /> Usage</DropdownMenuItem>+ <DropdownMenuItem onClick={() => router.push(`${base}/settings/flags`)}>+ <Flag /> Feature flags+ </DropdownMenuItem><DropdownMenuSeparator /><DropdownMenuItem onClick={signOut}><LogOut /> Log outdiff --git a/site/src/cut/components/RequireSession.tsx b/site/src/cut/components/RequireSession.tsxindex 472626a8..8b4dc189 100644--- a/site/src/cut/components/RequireSession.tsx+++ b/site/src/cut/components/RequireSession.tsx@@ -4,6 +4,7 @@ import { useEffect, type ReactNode } from "react";import { signInHrefFor } from "@/app/_components/landing/useAppEntryHref";import { setEngineUser } from "@/cut/lib/api";+import { syncAccountFlags } from "@/cut/lib/flags";import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";import { useAppLoaded } from "@/lib/analytics";import { authClient } from "@/lib/auth-client";@@ -33,6 +34,14 @@ export function RequireSession({ children }: { children: ReactNode }) {useAppLoaded("cut", session?.user);+ // The web-mode flag lives on the account; refresh the local mirror once the+ // session is known so a grant (or revoke) from another device takes effect+ // on the next load here.+ const userId = session?.user.id;+ useEffect(() => {+ if (userId) void syncAccountFlags();+ }, [userId]);+useEffect(() => {if (!signedOut) return;const here = window.location.pathname + window.location.search;diff --git a/site/src/cut/lib/flags.ts b/site/src/cut/lib/flags.tsnew file mode 100644index 00000000..4b1efab4--- /dev/null+++ b/site/src/cut/lib/flags.ts@@ -0,0 +1,53 @@+// Cut's web-mode flag is an ACCOUNT feature flag ("cut-web-mode"), enabled per+// user in the account settings' Feature flags section. localStorage only+// mirrors the server value so reads stay synchronous; RequireSession refreshes+// the mirror from the account on every app load, and the settings page updates+// it when the user flips the switch. Reads go through useSyncExternalStore so+// every component — and every other tab, via the storage event — reacts to a+// change immediately.+import { useSyncExternalStore } from "react";++const WEB_MODE_KEY = "cut-web-mode";+const FLAG_EVENT = "cut-flags-changed";++export function webModeEnabled(): boolean {+ if (typeof window === "undefined") return false;+ return localStorage.getItem(WEB_MODE_KEY) === "1";+}++/** Update the local mirror (this tab reacts immediately, other tabs via the+ * storage event). The account value is written by the settings page's PUT;+ * this never calls the server. */+export function applyWebModeLocal(on: boolean) {+ if (on) localStorage.setItem(WEB_MODE_KEY, "1");+ else localStorage.removeItem(WEB_MODE_KEY);+ window.dispatchEvent(new Event(FLAG_EVENT));+}++/** Refresh the mirror from the signed-in account's flags. Errors keep the+ * current mirror — a transient fetch failure must not flip the editor's+ * backend out from under the user. */+export async function syncAccountFlags() {+ try {+ const res = await fetch("/api/account/feature-flags");+ if (!res.ok) return;+ const body = (await res.json()) as { flags?: { id: string; enabled: boolean }[] };+ const webMode = body.flags?.find((f) => f.id === WEB_MODE_KEY);+ if (webMode && webMode.enabled !== webModeEnabled()) applyWebModeLocal(webMode.enabled);+ } catch {+ // Offline or hosted API unreachable; the mirror stands.+ }+}++function subscribe(onChange: () => void) {+ window.addEventListener(FLAG_EVENT, onChange);+ window.addEventListener("storage", onChange);+ return () => {+ window.removeEventListener(FLAG_EVENT, onChange);+ window.removeEventListener("storage", onChange);+ };+}++export function useWebMode(): boolean {+ return useSyncExternalStore(subscribe, webModeEnabled, () => false);+}diff --git a/site/src/lib/feature-flags.ts b/site/src/lib/feature-flags.tsnew file mode 100644index 00000000..f962277d--- /dev/null+++ b/site/src/lib/feature-flags.ts@@ -0,0 +1,20 @@+// The registry of account feature flags. A flag ships here first; the account+// settings page renders this list and the API accepts only these ids.++export type AccountFeatureFlag = {+ id: string;+ title: string;+ description: string;+};++export const ACCOUNT_FEATURE_FLAGS: AccountFeatureFlag[] = [+ {+ id: "cut-web-mode",+ title: "Cloud mode (beta)",+ description:+ "Edit in any browser on any OS with no install: projects stored in the cloud, exports rendered by a cloud worker. The Mac app keeps running everything locally.",+ },+];++export const isKnownFeatureFlag = (id: string) =>+ ACCOUNT_FEATURE_FLAGS.some((f) => f.id === id);