Open source CapCut alternative.
TypeScript
feat(site): credits readout in the Cut top bar with an account toggle
David Lee069ef9676ca
diff --git a/site/src/app/cut/app/(home)/settings/profile/EditorSection.tsx b/site/src/app/cut/app/(home)/settings/profile/EditorSection.tsxnew file mode 100644index 00000000..1e265e2d--- /dev/null+++ b/site/src/app/cut/app/(home)/settings/profile/EditorSection.tsx@@ -0,0 +1,43 @@+"use client";++import { Switch } from "@/components/ui/switch";+import { useAccountFlags, useSetAccountFlag } from "@/queries/featureFlags";++// Editor preferences that belong to the account, so they follow the user to+// every browser: what the top bar shows, and whatever joins it later.+export function EditorSection() {+ const set = useSetAccountFlag();+ const prefs = useAccountFlags().data?.filter((f) => f.group === "editor");++ if (!prefs?.length) return null;++ return (+ <div className="rounded-xl border bg-card p-5">+ <div className="text-sm font-medium">Editor</div>+ <div className="mt-4 border-t pt-4">+ {prefs.map((pref, i) => (+ <div key={pref.id} className={i > 0 ? "mt-4 border-t pt-4" : undefined}>+ <div className="flex items-start justify-between gap-6">+ <span className="min-w-0">+ <span className="block text-sm font-medium">{pref.title}</span>+ <span className="mt-0.5 block text-sm text-muted-foreground">+ {pref.description}+ </span>+ </span>+ <Switch+ aria-label={pref.title}+ checked={pref.enabled}+ onCheckedChange={(v) => set.mutate({ flag: pref.id, enabled: v === true })}+ />+ </div>+ </div>+ ))}+ {set.isError && (+ <p className="mt-3 text-sm text-red-600">+ Couldn't save that change — try again.+ </p>+ )}+ </div>+ </div>+ );+}diff --git a/site/src/app/cut/app/(home)/settings/profile/FeatureFlagsSection.tsx b/site/src/app/cut/app/(home)/settings/profile/FeatureFlagsSection.tsxindex 493192aa..5996a8a5 100644--- a/site/src/app/cut/app/(home)/settings/profile/FeatureFlagsSection.tsx+++ b/site/src/app/cut/app/(home)/settings/profile/FeatureFlagsSection.tsx@@ -8,8 +8,8 @@ import { useAccountFlags, useSetAccountFlag } from "@/queries/featureFlags";// account like everything else here. With no flags shipping there is nothing to// say, so the section isn't there at all.export function FeatureFlagsSection() {- const { data: flags } = useAccountFlags();const set = useSetAccountFlag();+ const flags = useAccountFlags().data?.filter((f) => f.group === "early");if (!flags?.length) return null;diff --git a/site/src/app/cut/app/(home)/settings/profile/page.tsx b/site/src/app/cut/app/(home)/settings/profile/page.tsxindex 84c08377..8cf53c80 100644--- a/site/src/app/cut/app/(home)/settings/profile/page.tsx+++ b/site/src/app/cut/app/(home)/settings/profile/page.tsx@@ -4,6 +4,7 @@ import { useState } from "react";import { Pencil } from "lucide-react";import { AvatarDialog } from "@/app/cut/app/(home)/settings/profile/AvatarDialog";+import { EditorSection } from "@/app/cut/app/(home)/settings/profile/EditorSection";import { EmailSection } from "@/app/cut/app/(home)/settings/profile/EmailSection";import { FeatureFlagsSection } from "@/app/cut/app/(home)/settings/profile/FeatureFlagsSection";import { Button } from "@/components/ui/button";@@ -122,6 +123,8 @@ export default function CutProfilePage() {</div></div>+ <EditorSection />+<EmailSection /><FeatureFlagsSection />diff --git a/site/src/cut/components/CreditsPill.tsx b/site/src/cut/components/CreditsPill.tsxnew file mode 100644index 00000000..0a0ec455--- /dev/null+++ b/site/src/cut/components/CreditsPill.tsx@@ -0,0 +1,126 @@+"use client";++// The top bar's balance: what the account can still spend on hosted work —+// chat, generation, voice — so a session can be planned around it. Reads as a+// number and leads to the billing page.+import { useEffect } from "react";+import Link from "next/link";+import { useQueryClient } from "@tanstack/react-query";+import { Coins } from "lucide-react";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/components/ui/tooltip";+import { useEngineUser } from "@/cut/lib/backend/hooks";+import { useHostedBalance } from "@/cut/lib/hosted";+import { useCutBase } from "@/cut/lib/nav";+import { track } from "@/lib/analytics";+import { formatUsd } from "@/lib/credits/format-usd";+import { CREDITS_PILL_FLAG } from "@/lib/feature-flags";+import { creditBalanceQueryKey, useCreditBalance, type CreditBalance } from "@/queries/credits";+import { useAccountFlags } from "@/queries/featureFlags";++// The number sits in the bar as muted text; the pill's border and fill come+// up under the pointer, where they say it can be clicked.+const PILL =+ "flex cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-full border border-transparent px-3 py-1.5 text-xs font-medium tabular-nums text-muted-foreground transition-colors hover:border-border hover:bg-card hover:shadow-xs";++/** A hosted call that answered with no balance was charged after its+ * response left; the re-read waits for the charge to land. */+const SETTLE_DELAY_MS = 1500;++/** The bar's reading of a balance: cents while there is less than $10, where+ * each one changes what the next generation can be, and whole dollars past+ * that, where they are noise. A round amount drops the ".00" either way. */+export function compactUsd(dollars: number): string {+ const cents = Math.round(dollars * 100);+ const showCents = dollars < 10 && cents % 100 !== 0;+ return dollars.toLocaleString("en-US", {+ currency: "USD",+ style: "currency",+ minimumFractionDigits: showCents ? 2 : 0,+ maximumFractionDigits: showCents ? 2 : 0,+ });+}++export function CreditsPill() {+ const user = useEngineUser();+ // Mounted above the account check so the hook order is stable; idle until+ // there is an account whose preference to read.+ const flags = useAccountFlags({ enabled: Boolean(user) });+ const shown = flags.data?.some((f) => f.id === CREDITS_PILL_FLAG && f.enabled) ?? false;+ if (!user || !shown) return null;+ return <BalancePill />;+}++function BalancePill() {+ const base = useCutBase();+ const queryClient = useQueryClient();+ const balance = useCreditBalance();+ const reported = useHostedBalance((s) => s.balance);+ const settled = useHostedBalance((s) => s.settled);++ // A charged call reported the balance it left: that is the balance, with no+ // request to make.+ useEffect(() => {+ if (reported === null) return;+ queryClient.setQueryData<CreditBalance>(creditBalanceQueryKey, (prev) =>+ prev ? { ...prev, balance: reported } : prev+ );+ }, [reported, queryClient]);+ // A call that answered without one: re-read once its charge has landed.+ // Only the count moving matters; the mount value is whatever the page has+ // done so far.+ useEffect(() => {+ if (settled === 0) return;+ const id = setTimeout(+ () => void queryClient.invalidateQueries({ queryKey: creditBalanceQueryKey }),+ SETTLE_DELAY_MS+ );+ return () => clearTimeout(id);+ }, [settled, queryClient]);+ // Background work — renders, cloud jobs — charges without a call from this+ // tab, and a top-up happens on another page; a slow poll keeps the number+ // honest between them, and a focus refetch catches the trip back from billing.+ useEffect(() => {+ const id = setInterval(() => {+ if (document.visibilityState !== "visible") return;+ void queryClient.invalidateQueries({ queryKey: creditBalanceQueryKey });+ }, 60_000);+ const onFocus = () => void queryClient.invalidateQueries({ queryKey: creditBalanceQueryKey });+ window.addEventListener("focus", onFocus);+ return () => {+ clearInterval(id);+ window.removeEventListener("focus", onFocus);+ };+ }, [queryClient]);++ if (!balance.data) return null;+ const dollars = Number.parseFloat(balance.data.balance) || 0;+ const message =+ dollars > 0+ ? `${formatUsd(balance.data.balance)} credits remaining`+ : "No credits left";+ return (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger+ render={+ <Link+ href={`${base}/settings`}+ aria-label={`Credits: ${compactUsd(dollars)}`}+ onClick={() => track("cut_credits_pill_clicked", { dollars })}+ className={PILL}+ />+ }+ >+ <Coins className="size-3.5" />+ {compactUsd(dollars)}+ </TooltipTrigger>+ <TooltipContent side="bottom">{message}</TooltipContent>+ </Tooltip>+ </TooltipProvider>+ );+}diff --git a/site/src/cut/components/TopBar.tsx b/site/src/cut/components/TopBar.tsxindex 43995df9..0ae23812 100644--- a/site/src/cut/components/TopBar.tsx+++ b/site/src/cut/components/TopBar.tsx@@ -36,6 +36,7 @@ import { projectDuration, useEditor } from "@/cut/lib/store";import { useLocalPref } from "@/cut/lib/uiState";import { ASPECT_PRESETS, aspectLabel, aspectOrientation, normalizeAspect, parseRatio, type Aspect } from "@/cut/lib/types";import { cn } from "@/lib/utils";+import { CreditsPill } from "./CreditsPill";import { RecordDialog, type RecordMode } from "./RecordDialog";import { ShareDialog } from "./ShareDialog";import { StoragePill } from "./StoragePill";@@ -73,8 +74,8 @@ export function TopBar({const [draft, setDraft] = useState("");const [recordMode, setRecordMode] = useState<RecordMode | null>(null);// The right-hand actions step down as the bar tightens: full labels →- // icon-only Share/Cloud/Export → everything in a … menu. The storage pill- // never folds. Which step fits is measured against hidden copies of the+ // icon-only Share/Cloud/Export → everything in a … menu. The credits and+ // storage pills never fold. Which step fits is measured against hidden copies of the// full and compact rows, because the visible row can't report a width it// isn't showing. Every measured box is content-sized — none of them depend// on the chosen step — so the measurement can't feed back into itself.@@ -374,7 +375,6 @@ export function TopBar({<Upload data-icon={compact ? undefined : "inline-start"} />{!compact && "Export"}</Button>- <div aria-hidden className="h-4 w-px bg-border" /><Buttonvariant={aiOpen ? "default" : "outline"}size="sm"@@ -614,7 +614,8 @@ export function TopBar({sight. Clipping would only shave the focus ring off the lastbutton. */}<div className="flex shrink-0 items-center gap-2 pr-3">- <div ref={pillRef} className="flex items-center">+ <div ref={pillRef} className="flex items-center gap-2">+ <CreditsPill /><StoragePill /></div><div className="relative flex items-center">diff --git a/site/src/lib/analytics.ts b/site/src/lib/analytics.tsindex b0a5f769..02a7ed75 100644--- a/site/src/lib/analytics.ts+++ b/site/src/lib/analytics.ts@@ -27,6 +27,8 @@ export type AnalyticsEvents = {folder_created: void;// Cut cloud storage limits.cut_storage_pill_clicked: void;+ // The top bar's credits pill.+ cut_credits_pill_clicked: { dollars: number };cut_storage_upgrade_shown: { source: "quota-413" | "pill" };cut_grace_banner_shown: void;// Preview timing from an account that turned diagnostics on, one summary perdiff --git a/site/src/lib/feature-flags.ts b/site/src/lib/feature-flags.tsindex 49b02ef7..790265e3 100644--- a/site/src/lib/feature-flags.ts+++ b/site/src/lib/feature-flags.ts@@ -1,21 +1,34 @@-// 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.+// The registry of account flags. A flag ships here first; the account settings+// page renders this list and the API accepts only these ids. `group` decides+// which settings section a flag sits in: an editor preference everyone has, or+// an early feature an account opts into.export type AccountFeatureFlag = {id: string;title: string;description: string;+ group: "editor" | "early";/** The state an account with no row of its own gets. A flag that has shipped* to everyone defaults on and the switch becomes an opt-out. */defaultEnabled: boolean;};+export const CREDITS_PILL_FLAG = "editor_credits_pill";+export const ACCOUNT_FEATURE_FLAGS: AccountFeatureFlag[] = [+ {+ id: CREDITS_PILL_FLAG,+ title: "Show credits in the editor",+ description: "Your remaining balance in the editor's top bar.",+ group: "editor",+ defaultEnabled: true,+ },{id: "preview_diagnostics",title: "Share diagnostics",description:"Help us diagnose playback issues. Your video, audio, and project stay in your browser.",+ group: "early",defaultEnabled: false,},];diff --git a/site/src/queries/featureFlags.ts b/site/src/queries/featureFlags.tsindex 5cd36ecf..aa394e02 100644--- a/site/src/queries/featureFlags.ts+++ b/site/src/queries/featureFlags.ts@@ -10,11 +10,15 @@ export type AccountFlag = {id: string;title: string;description: string;+ group: "editor" | "early";enabled: boolean;};-export function useAccountFlags() {+// `enabled` is for the signed-out case: the editor's top bar mounts this above+// its own account check, and the route answers 401 without a session.+export function useAccountFlags(options?: { enabled?: boolean }) {return useQuery({+ enabled: options?.enabled ?? true,queryFn: async () => {const body = await apiFetch<{ flags: AccountFlag[] }>("/api/account/feature-flags",