Open source CapCut alternative.
TypeScript
fix(site): one line when credits run short [rebuild]
David Lef0a5b6f8c596
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsxindex 5920b813..99edd552 100644--- a/site/src/cut/components/AiPanel.tsx+++ b/site/src/cut/components/AiPanel.tsx@@ -1255,7 +1255,7 @@ function ChatSession({><TriangleAlert className="size-3 shrink-0" /><span>- No credits left —{" "}+ Insufficient credits —{" "}<span className="font-medium underline">reload credits</span></span></a>diff --git a/site/src/cut/components/AudioPanel.tsx b/site/src/cut/components/AudioPanel.tsxindex a81744c1..b9260a97 100644--- a/site/src/cut/components/AudioPanel.tsx+++ b/site/src/cut/components/AudioPanel.tsx@@ -45,7 +45,8 @@ import { draggingRef, hasRefDrag } from "@/cut/lib/assetRef";import { useMusicGen } from "@/cut/lib/musicGen";import { STOCK_MUSIC } from "@/cut/lib/stockMusicManifest";import { stockAssetInDoc } from "@/cut/lib/genvideo/docWriter";-import { creditsUrl, signInUrl, useSignedIn } from "@/cut/lib/generate";+import { signInUrl, useSignedIn } from "@/cut/lib/generate";+import { HostedErrorText } from "./hostedError";import { genPulseOverlay, useActiveWork, useGenNotify } from "@/cut/lib/genNotify";import { enrichAsset } from "@/cut/lib/media";import { waveGain } from "@/cut/lib/waveform";@@ -53,7 +54,7 @@ import { usePreviewAudio } from "@/cut/lib/previewAudio";import { useEditor } from "@/cut/lib/store";import { playheadAt } from "@/cut/lib/playhead";import { formatTime } from "@/cut/lib/time";-import { NoCreditsError, synthesizeSpeech } from "@/cut/lib/tts";+import { synthesizeSpeech } from "@/cut/lib/tts";import { useLocalPref } from "@/cut/lib/uiState";import { DUCK_DEFAULT } from "@/cut/lib/voiceover";import { useSpeakerVoice, useSpeechLanguage, VoicePicker } from "@/cut/components/VoicePicker";@@ -181,13 +182,9 @@ function MusicGenerator({ projectId }: { projectId: string }) {if (ref?.scope !== "stock" || ref.kind !== "audio") return undefined;return STOCK_MUSIC.find((s) => s.id === ref.id);};- const [error, setError] = useState<{ text: string; credits?: boolean } | null>(null);+ const [error, setError] = useState<{ text: string } | null>(null);const fail = (e: unknown, fallback: string) =>- setError(- e instanceof Error- ? { text: e.message, credits: e instanceof NoCreditsError }- : { text: fallback }- );+ setError({ text: e instanceof Error ? e.message : fallback });// Music runs on the user's Donkey account, like image/video/voiceover.const signedOut = useSignedIn() === false;@@ -336,20 +333,7 @@ function MusicGenerator({ projectId }: { projectId: string }) {) : (error && (<p className="music-error text-[11px] leading-relaxed text-red-600">- {error.text}- {error.credits && (- <>- {" "}- <a- className="font-medium underline hover:no-underline"- href={creditsUrl()}- target="_blank"- rel="noreferrer"- >- Add credits- </a>- </>- )}+ <HostedErrorText error={error.text} /></p>))}@@ -365,15 +349,9 @@ function VoiceGenerator({ projectId }: { projectId: string }) {// In-flight count read from the store, so the status row survives the panel// unmounting when the user changes tabs.const pending = useActiveWork("audio", "voice");- // `credits` marks a failure caused by an empty balance, which renders with a- // link to buy more.- const [error, setError] = useState<{ text: string; credits?: boolean } | null>(null);+ const [error, setError] = useState<{ text: string } | null>(null);const fail = (e: unknown, fallback: string) =>- setError(- e instanceof Error- ? { text: e.message, credits: e instanceof NoCreditsError }- : { text: fallback }- );+ setError({ text: e instanceof Error ? e.message : fallback });const directionInput = useRef<HTMLTextAreaElement>(null);// Voiceovers run on the user's Donkey account, like image/video generation.const signedOut = useSignedIn() === false;@@ -536,20 +514,7 @@ function VoiceGenerator({ projectId }: { projectId: string }) {) : (error && (<p className="voice-error text-[11px] leading-relaxed text-red-600">- {error.text}- {error.credits && (- <>- {" "}- <a- className="font-medium underline hover:no-underline"- href={creditsUrl()}- target="_blank"- rel="noreferrer"- >- Add credits- </a>- </>- )}+ <HostedErrorText error={error.text} /></p>))}diff --git a/site/src/cut/components/SceneCard.tsx b/site/src/cut/components/SceneCard.tsxindex 6036be8e..7e816263 100644--- a/site/src/cut/components/SceneCard.tsx+++ b/site/src/cut/components/SceneCard.tsx@@ -15,7 +15,7 @@ import { useHoverPlay } from "../hooks/useHoverPlay";import { refFromAsset, type AssetRef } from "../lib/assetRef";import { lightboxItemFromRef, useLightbox } from "../lib/lightbox";import { formatDuration, useGenScene, type SceneRun } from "../lib/genScene";-import { NO_CREDITS_MESSAGE } from "../lib/generate";+import { NO_CREDITS_MESSAGE } from "../lib/credits";import { GEN_FPS } from "../lib/genvideo/editorBridge";import { useEditor } from "../lib/store";import { formatTime } from "../lib/time";@@ -98,14 +98,15 @@ export function SceneCard({ threadId }: { threadId: string }) {const hasFrames = run.shots.some((sh) => sh.clip || sh.startKeyframe);// Shots that couldn't be rendered as video and are holding a still instead.const stillCount = run.shots.filter((sh) => sh.status === "failed").length;- // Any shot stopped by an empty balance: the summary names the cause (the- // composer's credits tab carries the reload link).- const creditsOut = run.shots.some(- (sh) => sh.status === "failed" && sh.error === NO_CREDITS_MESSAGE- );// Why they held: the first failed shot's own error, so the notice names the- // cause instead of stating that something failed.- const stillReason = run.shots.find((sh) => sh.status === "failed" && sh.error)?.error;+ // cause instead of stating that something failed. A shot stopped by the+ // balance wins the summary even when a later one failed for its own reason —+ // it is the one the user can act on.+ const creditsReason = run.shots.find(+ (sh) => sh.status === "failed" && sh.error === NO_CREDITS_MESSAGE+ )?.error;+ const stillReason =+ creditsReason ?? run.shots.find((sh) => sh.status === "failed" && sh.error)?.error;// Elapsed clock: planning counts from the run start, rendering from approval;// it stops at the end. Hidden while waiting for the user at the gate.const clockAnchor = run.status === "planning" ? run.startedAt : run.renderStartedAt ?? run.startedAt;@@ -198,8 +199,8 @@ export function SceneCard({ threadId }: { threadId: string }) {<span>{stillCount} of {run.shots.length} shot{run.shots.length === 1 ? "" : "s"} held astill —{" "}- {creditsOut || stillReason ? (- <HostedErrorText error={creditsOut ? NO_CREDITS_MESSAGE : stillReason!} link={false} />+ {stillReason ? (+ <HostedErrorText error={stillReason} link={false} />) : ("video generation failed")}diff --git a/site/src/cut/components/VoicePicker.tsx b/site/src/cut/components/VoicePicker.tsxindex bc495d78..c2ed45f3 100644--- a/site/src/cut/components/VoicePicker.tsx+++ b/site/src/cut/components/VoicePicker.tsx@@ -9,10 +9,11 @@ import {DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import { SectionTitle } from "@/cut/components/SectionTitle";-import { creditsUrl, signInUrl, useSignedIn } from "@/cut/lib/generate";+import { signInUrl, useSignedIn } from "@/cut/lib/generate";+import { HostedErrorText } from "./hostedError";import { useGenNotify } from "@/cut/lib/genNotify";import { useEditor, type EditorState } from "@/cut/lib/store";-import { NoCreditsError, renderSpeechClip, resolveLanguage, resolveVoice } from "@/cut/lib/tts";+import { renderSpeechClip, resolveLanguage, resolveVoice } from "@/cut/lib/tts";import {SPEECH_VOICES,VOICE_SAMPLE_TEXT,@@ -298,7 +299,7 @@ export function GenerateSubtitlesAudio({const language = useSpeechLanguage();const signedOut = useSignedIn() === false;const [busy, setBusy] = useState(false);- const [error, setError] = useState<{ text: string; credits?: boolean } | null>(null);+ const [error, setError] = useState<{ text: string } | null>(null);const cueCount = useEditor((s) => scopedCueIds(s, selectCueIds).length);const hasVideo = useEditor((s) => s.clips.length > 0);@@ -333,11 +334,9 @@ export function GenerateSubtitlesAudio({});useGenNotify.getState().landed("audio", asset.id);} catch (e) {- setError(- e instanceof Error- ? { text: e.message, credits: e instanceof NoCreditsError }- : { text: "Voice generation failed." }- );+ setError({+ text: e instanceof Error ? e.message : "Voice generation failed.",+ });} finally {setBusy(false);settle();@@ -374,20 +373,7 @@ export function GenerateSubtitlesAudio({) : (error && (<p className="voice-error text-[11px] leading-relaxed text-red-600">- {error.text}- {error.credits && (- <>- {" "}- <a- className="font-medium underline hover:no-underline"- href={creditsUrl()}- target="_blank"- rel="noreferrer"- >- Add credits- </a>- </>- )}+ <HostedErrorText error={error.text} /></p>))}diff --git a/site/src/cut/components/hostedError.tsx b/site/src/cut/components/hostedError.tsxindex 896de2e6..a2410f78 100644--- a/site/src/cut/components/hostedError.tsx+++ b/site/src/cut/components/hostedError.tsx@@ -1,16 +1,20 @@-import { creditsUrl, NO_CREDITS_MESSAGE } from "@/cut/lib/generate";+import { NO_CREDITS_MESSAGE } from "@/cut/lib/credits";+import { creditsUrl } from "@/cut/lib/generate";+import { useOutOfCredits } from "@/cut/lib/hosted";-/** A hosted-inference error message (chat reply or generation tile). An- * empty-balance failure reads "No credits left, reload here" with the credits- * link inline; any other error (or a missing message) renders as plain text.- * Surfaces inside the chat panel pass `link={false}` — there the composer's- * credits tab carries the reload link, so the messages stay plain. */+/** A hosted-inference error message (chat reply or generation tile). A balance+ * failure reads "Insufficient credits, reload here" with the credits link+ * inline; any other error (or a missing message) renders as plain text.+ * Surfaces inside the chat panel pass `link={false}` and lean on the composer's+ * credits tab for the link — but that tab only rises for an empty balance, so a+ * balance merely short of one generation keeps its link here. */export function HostedErrorText({ error, link = true }: { error?: string; link?: boolean }) {+ const tabCarriesLink = useOutOfCredits((s) => s.out);if (error === NO_CREDITS_MESSAGE) {- if (!link) return <>{NO_CREDITS_MESSAGE}</>;+ if (!link && tabCarriesLink) return <>{NO_CREDITS_MESSAGE}</>;return (<>- No credits left,{" "}+ {error},{" "}<aclassName="font-medium underline hover:no-underline"href={creditsUrl()}diff --git a/site/src/cut/lib/audioGen.ts b/site/src/cut/lib/audioGen.tsindex 4bb042be..c6b77c8e 100644--- a/site/src/cut/lib/audioGen.ts+++ b/site/src/cut/lib/audioGen.ts@@ -1,6 +1,7 @@"use client";import { bytesFromBase64 } from "./bytes";+import { NO_CREDITS_MESSAGE } from "./credits";import { hostedPost } from "./hosted";import { importFileToProject } from "./media";import { NoCreditsError } from "./tts";@@ -32,7 +33,7 @@ async function readError(res: Response, fallback: string): Promise<string> {const message = [body?.message, body?.error].find((v): v is string => typeof v === "string" && v.length > 0);- if (res.status === 402) return message ?? "Not enough Donkey credits — top up to continue.";+ if (res.status === 402) return NO_CREDITS_MESSAGE;// The provider's own error (`details.message`) names the actual rejection (a// filtered prompt, a timeout); the top-level message is generic.const detail = body?.details?.message;diff --git a/site/src/cut/lib/credits.ts b/site/src/cut/lib/credits.tsnew file mode 100644index 00000000..6a6b3194--- /dev/null+++ b/site/src/cut/lib/credits.ts@@ -0,0 +1,4 @@+/** What every Cut surface says when the balance can't cover the work — an empty+ * account, or one holding less than this generation's price. The hosted routes+ * answer 402 either way, and each surface pairs this with a link to reload. */+export const NO_CREDITS_MESSAGE = "Insufficient credits";diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.tsindex b6f3ed4f..161af5eb 100644--- a/site/src/cut/lib/generate.ts+++ b/site/src/cut/lib/generate.ts@@ -16,6 +16,7 @@ import {stockAssetInDoc,upsertRenderInDoc,} from "./genvideo/docWriter";+import { NO_CREDITS_MESSAGE } from "./credits";import { CUT_APP_BASE } from "./nav";import { hostedFetch, hostedPost } from "./hosted";import { enrichAsset, importFileToProject, uploadProjectImage } from "./media";@@ -224,11 +225,6 @@ export function signInUrl(): string {return `/sign-in?callbackURL=${encodeURIComponent(window.location.href)}`;}-/** Shown for any 402 (empty balance) across chat and generation tiles. The- * chat error box and the job tiles match this text to swap in a "reload here"- * credits link, so keep it and those call sites in sync. */-export const NO_CREDITS_MESSAGE = "No credits left";-/** Cut's billing page, where credits are bought. Linked from any generation* error caused by an empty balance. */export function creditsUrl(): string {@@ -689,8 +685,8 @@ export const useGenerate = create<GenerateState>((set, get) => {// The next rung is a fresh submission: drop the dead rung's poll// payload so a reload can't resume a render that already failed.onRungFailed: () => update(job.id, { poll: undefined }),- // An empty balance fails every rung identically — stop there so- // a broke render fails fast, not once per rung.+ // The balance fails every rung identically — stop there so a+ // render nobody can pay for fails fast, not once per rung.fatal: (error) => error === NO_CREDITS_MESSAGE,});diff --git a/site/src/cut/lib/genvideo/adapters/text.ts b/site/src/cut/lib/genvideo/adapters/text.tsindex f19b45a4..1a3c5dc6 100644--- a/site/src/cut/lib/genvideo/adapters/text.ts+++ b/site/src/cut/lib/genvideo/adapters/text.ts@@ -16,7 +16,7 @@import { geminiModelRoles } from "@/lib/inference/gemini-models";import { hostedPost } from "../../hosted";-import { NO_CREDITS_MESSAGE } from "../../generate";+import { NO_CREDITS_MESSAGE } from "../../credits";import { secToFrame, type RawShot } from "../coverage";import { wordsInRange, type BreakdownRole, type ScriptRole, type StyleRole } from "../capabilities";import { refImageParts, type InlineImagePart } from "./refImages";diff --git a/site/src/cut/lib/hosted.ts b/site/src/cut/lib/hosted.tsindex 1b94e6cb..b470e9fc 100644--- a/site/src/cut/lib/hosted.ts+++ b/site/src/cut/lib/hosted.ts@@ -14,9 +14,9 @@ const CLIENT_ID = "donkey-cut";const OUT_KEY = "cut-credits-out";/** Whether the account balance is known to be empty: the last hosted call- * bounced with a 402. Set and cleared by `hostedPost` — the single chokepoint- * for hosted calls — and persisted so a reload keeps the composer's credits- * tab up until a call goes through again. */+ * bounced with a 402 that named no price. Set and cleared by `hostedPost` — the+ * single chokepoint for hosted calls — and persisted so a reload keeps the+ * composer's credits tab up until a call goes through again. */export const useOutOfCredits = create<{ out: boolean }>(() => ({out: typeof window !== "undefined" && safeRead() === "1",}));@@ -39,8 +39,22 @@ function setOut(out: boolean) {}}-function noteBalance(res: Response) {- if (res.status === 402 || res.ok) setOut(res.status === 402);+async function noteBalance(res: Response) {+ if (res.ok) {+ setOut(false);+ return;+ }+ if (res.status !== 402) return;+ // Two kinds of 402. An empty balance stops everything hosted and takes the+ // page out; a balance merely short of one flat-priced generation stops that+ // generation while chat and the metered calls keep working, so it leaves the+ // flag alone and the tile carries the message. The body is a few bytes and+ // the caller still gets an unread stream.+ const body = (await res+ .clone()+ .json()+ .catch(() => null)) as { error?: unknown } | null;+ if (body?.error !== "insufficient_credits_for_generation") setOut(true);}// One re-check in flight at a time; focus/visibility events can fire together.@@ -127,6 +141,6 @@ export const hostedPost = async (path: string, body: unknown, signal?: AbortSignbody: payload,signal,});- noteBalance(res);+ await noteBalance(res);return res;};diff --git a/site/src/cut/lib/pi/prodDeps.ts b/site/src/cut/lib/pi/prodDeps.tsindex c895d5ec..129d67b3 100644--- a/site/src/cut/lib/pi/prodDeps.ts+++ b/site/src/cut/lib/pi/prodDeps.ts@@ -5,7 +5,8 @@ import { AI_SKILL_INDEX, AI_SKILLS } from "@/cut/server/ai/catalog";import { buildAiContext } from "../aiContext";import { runAiTool } from "../aiTools";import { normalizeRef } from "../assetRef";-import { NO_CREDITS_MESSAGE, useGenerate } from "../generate";+import { NO_CREDITS_MESSAGE } from "../credits";+import { useGenerate } from "../generate";import { hostedPost } from "../hosted";import { refsToParts } from "../refMedia";import type { CutAgentDeps } from "./cutAgent";diff --git a/site/src/cut/lib/pi/serverDeps.ts b/site/src/cut/lib/pi/serverDeps.tsindex e6a88082..0987dbc8 100644--- a/site/src/cut/lib/pi/serverDeps.ts+++ b/site/src/cut/lib/pi/serverDeps.ts@@ -3,7 +3,7 @@ import { AI_SKILL_INDEX, AI_SKILLS } from "@/cut/server/ai/catalog";import { buildAiContext } from "../aiContext";import { MEDIA_RUNTIME_TOOLS, runAiTool, UI_TOOLS } from "../aiTools";import { normalizeRef } from "../assetRef";-import { NO_CREDITS_MESSAGE } from "../generate";+import { NO_CREDITS_MESSAGE } from "../credits";import { hostedPost } from "../hosted";import { bindHeadlessSession, type HeadlessSession } from "../headless/bind";import { headlessRuntime } from "../headless/runtime";diff --git a/site/src/cut/lib/tts.ts b/site/src/cut/lib/tts.tsindex 73b8f89f..ed0a1451 100644--- a/site/src/cut/lib/tts.ts+++ b/site/src/cut/lib/tts.ts@@ -2,6 +2,7 @@import { geminiModels } from "@/lib/inference/gemini-models";import { bytesFromBase64 } from "./bytes";+import { NO_CREDITS_MESSAGE } from "./credits";import { hostedPost } from "./hosted";import { importFileToProject } from "./media";import { mediaSlug, type MediaAsset } from "./types";@@ -198,7 +199,7 @@ async function readError(res: Response, fallback: string): Promise<string> {const message = [body?.message, body?.error].find((v): v is string => typeof v === "string" && v.length > 0);- if (res.status === 402) return message ?? "Not enough Donkey credits — top up to continue.";+ if (res.status === 402) return NO_CREDITS_MESSAGE;// The provider's own error (`details.message`) names the actual rejection// ("input too long", a rate limit, …); the top-level message is generic.const detail = body?.details?.message;