Open source CapCut alternative.
TypeScript
fix(site): in-flight work shows on every side-panel tab
David Le450439daddac
diff --git a/site/src/cut/components/AudioPanel.tsx b/site/src/cut/components/AudioPanel.tsxindex 6c9e0528..a81744c1 100644--- a/site/src/cut/components/AudioPanel.tsx+++ b/site/src/cut/components/AudioPanel.tsx@@ -46,7 +46,7 @@ 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 { genPulseOverlay, useGenNotify } from "@/cut/lib/genNotify";+import { genPulseOverlay, useActiveWork, useGenNotify } from "@/cut/lib/genNotify";import { enrichAsset } from "@/cut/lib/media";import { waveGain } from "@/cut/lib/waveform";import { usePreviewAudio } from "@/cut/lib/previewAudio";@@ -168,7 +168,11 @@ function MusicGenerator({ projectId }: { projectId: string }) {1,(v) => typeof v === "number" && v >= 1 && v <= 4);- const [pending, setPending] = useState(0);+ // How many syntheses are in flight — several can run at once, so the button+ // stays live and this just drives the status row below it. The count lives in+ // the store, so a take started here keeps showing after a trip to another tab+ // and back; the panel unmounts and the work carries on.+ const pending = useActiveWork("audio", "music");// A sample dragged from the library onto the prompt box loads its prompt.const [dropActive, setDropActive] = useState(false);const droppedSample = (e: React.DragEvent) => {@@ -194,11 +198,10 @@ function MusicGenerator({ projectId }: { projectId: string }) {if (!text) return;setError(null);const n = takes;- setPending((p) => p + n);await Promise.all(Array.from({ length: n }, async () => {// Spins the Audio rail tile for the take's whole flight.- const settle = useGenNotify.getState().begin("audio");+ const settle = useGenNotify.getState().begin("audio", "music");try {const asset = await synthesizeMusic(projectId, text, { variant, instrumental });// A render can outlast the open project — the user may switch away@@ -216,7 +219,6 @@ function MusicGenerator({ projectId }: { projectId: string }) {} catch (e) {fail(e, "Music generation failed.");} finally {- setPending((p) => p - 1);settle();}})@@ -360,9 +362,9 @@ function VoiceGenerator({ projectId }: { projectId: string }) {const language = useSpeechLanguage();const [script, setScript] = useState("");const [direction, setDirection] = useState("");- // How many syntheses are in flight — several can run at once, so the button- // stays live and this just drives the status row below it.- const [pending, setPending] = useState(0);+ // 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);@@ -381,10 +383,9 @@ function VoiceGenerator({ projectId }: { projectId: string }) {const generate = async () => {const text = script.trim();if (!text) return;- setPending((p) => p + 1);// The Audio rail tile spins while this runs — the tab is often closed// before the voice lands.- const settle = useGenNotify.getState().begin("audio");+ const settle = useGenNotify.getState().begin("audio", "voice");setError(null);try {const playhead = playheadAt();@@ -416,7 +417,6 @@ function VoiceGenerator({ projectId }: { projectId: string }) {} catch (e) {fail(e, "Voice generation failed.");} finally {- setPending((p) => p - 1);settle();}};diff --git a/site/src/cut/components/ExportsDock.tsx b/site/src/cut/components/ExportsDock.tsxindex cae47b25..7aac4377 100644--- a/site/src/cut/components/ExportsDock.tsx+++ b/site/src/cut/components/ExportsDock.tsx@@ -19,6 +19,7 @@ import {beginExportPolling,endExportPolling,exportBackend,+ useExportRows,useExports,type ExportJob,type LocalRow,@@ -35,10 +36,6 @@ import { cn } from "@/lib/utils";* Cut app layout, above the per-project editor.*/export function ExportsDock() {- const jobs = useExports((s) => s.jobs);- const local = useExports((s) => s.local);- const dismissed = useExports((s) => s.dismissed);- const rendering = useExports((s) => s.rendering);const [collapsed, setCollapsed] = useState(false);// Poll the feed while the dock is mounted (i.e. the whole time the app is up).@@ -47,26 +44,16 @@ export function ExportsDock() {return endExportPolling;}, []);- const items = useMemo(() => {- const rank = (status: string) =>- status === "running" || status === "rendering"- ? 0- : status === "queued" || status === "preparing"- ? 1- : status === "done"- ? 2- : 3;- // A row this tab is rendering shows as its local row, which has the- // progress; the reserved job row behind it stays out of the dock.- const visible = jobs.filter((j) => !dismissed.includes(j.id) && !rendering.includes(j.id));- return [- ...visible.map((j) => ({ kind: "job" as const, data: j })),- ...local.map((r) => ({ kind: "local" as const, data: r })),- ].sort((a, b) => {- const dr = rank(a.data.status) - rank(b.data.status);- return dr !== 0 ? dr : (a.data.createdAt ?? 0) - (b.data.createdAt ?? 0);- });- }, [jobs, local, dismissed, rendering]);+ // Every project's work, assembled the same way the Media tab assembles one+ // project's (`useExportRows`). The dock is the notification, so its own X+ // list applies here: a hidden row keeps rendering and keeps its place in the+ // Media tab's Exports list, where the cancel lives.+ const dismissed = useExports((s) => s.dismissed);+ const all = useExportRows();+ const items = useMemo(+ () => all.filter((i) => !(i.kind === "job" && dismissed.includes(i.data.id))),+ [all, dismissed]+ );if (items.length === 0) return null;diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxindex 58b4b688..ab6a99f1 100644--- a/site/src/cut/components/SidePanel.tsx+++ b/site/src/cut/components/SidePanel.tsx@@ -44,7 +44,14 @@ import {import { useRefCopy } from "@/cut/lib/refCopy";import { RefDropZone } from "./RefDropZone";import { deleteExport, downloadProjectExport, revealExport } from "@/cut/lib/exportClient";-import { useExports, useWatchExportLands, type ExportJob } from "@/cut/lib/exportStore";+import {+ exportCancelable,+ exportInFlight,+ useExportRows,+ useExports,+ useWatchExportLands,+ type ExportRow,+} from "@/cut/lib/exportStore";import { useElapsed } from "@/cut/hooks/useElapsed";import { useInView } from "@/cut/hooks/useInView";import { useMediaFileSize } from "@/cut/hooks/useMediaFileSize";@@ -92,7 +99,14 @@ import { mediaUrl, TRANSITION_MAX } from "@/cut/lib/types";import { parseSecondsInput } from "@/cut/components/ScrubValue";import { ColorField } from "@/cut/components/ColorField";import { ValueSlider } from "@/cut/components/ValueSlider";-import { genPulseOverlay, isGenTab, useGenNotify, useGenPulse, useWatchGenTab } from "@/cut/lib/genNotify";+import {+ genPulseOverlay,+ isGenTab,+ useActiveWork,+ useGenNotify,+ useGenPulse,+ useWatchGenTab,+} from "@/cut/lib/genNotify";import { useGenerate, type GenerateJob } from "@/cut/lib/generate";import { CAPTION_LIMIT, normalizeTags } from "@/cut/lib/publish";import { useEditor } from "@/cut/lib/store";@@ -214,19 +228,17 @@ export function SidePanel({// store that owns that work: exports for Media, panel renders for// Video/Image, registered syntheses for Audio, the transcription pass for// Subtitles.- const exporting = useExports(- (s) =>- s.jobs.some(- (j) => j.projectId === projectId && (j.status === "queued" || j.status === "running")- ) || s.local.some((r) => r.projectId === projectId && r.status === "preparing")- );+ // Read through the same assembly the Media tab's own Exports list uses, so+ // the rail tile spins for exactly the work that list shows — a queued engine+ // job, and a render this tab is doing itself.+ const exporting = useExportRows(projectId).some(exportInFlight);const panelRendering = (s: { jobs: GenerateJob[] }, kind: GenerateJob["kind"]) =>s.jobs.some((j) => j.projectId === projectId && j.kind === kind && j.status === "running" && !j.chatId);const videoBusy = useGenerate((s) => panelRendering(s, "video"));const imageBusy = useGenerate((s) => panelRendering(s, "image"));- const audioBusy = useGenNotify((s) => s.active.audio.length > 0);+ const audioBusy = useActiveWork("audio") > 0;const subtitlesBusy = useEditor((s) => s.subtitleStatus === "running");const busy: Partial<Record<Tab, boolean>> = {media: exporting,@@ -553,12 +565,20 @@ function ExportPulse({ file }: { file: string }) {return pulse ? <div aria-hidden className={genPulseOverlay} /> : null;}-/** A queued or still-rendering export in the Exports list: spinner, live- * progress, and a cancel that stops the render (the dock's X only hides the- * notification). */-function ExportingRow({ job }: { job: ExportJob }) {- const elapsed = useElapsed(job.status === "running" ? job.startedAt ?? null : null);- const pct = Math.round(job.progress * 100);+/** An export still being worked on, in the Exports list: spinner, live+ * progress, and a cancel that stops it. This is the project's record of the+ * work, so an export hidden from the dock still has its row and its cancel+ * here. One row for both kinds of work — a job the engine or the render worker+ * owns, and a render this tab is doing itself, which is how a cloud or browser+ * project exports and which carries its progress on its own local row. */+function ExportingRow({ row }: { row: ExportRow }) {+ const { status } = row.data;+ const running = status === "running" || status === "rendering";+ const cancelable = exportCancelable(row);+ const startedAt = row.kind === "job" ? row.data.startedAt ?? null : row.data.createdAt;+ const elapsed = useElapsed(running ? startedAt : null);+ const progress = row.kind === "job" ? row.data.progress : (row.data.progress ?? 0);+ const pct = Math.round(progress * 100);return (<div className="relative flex w-full items-center gap-2.5 overflow-hidden rounded-lg border border-border p-1.5"><div className="grid h-11 w-[25px] shrink-0 place-items-center rounded-[4px] bg-muted">@@ -567,18 +587,24 @@ function ExportingRow({ job }: { job: ExportJob }) {<span className="min-w-0 flex-1"><span className="block truncate text-[11.5px] font-medium">Exporting…</span><span className="block text-[10.5px] text-muted-foreground tabular-nums">- {job.status === "running" ? `${pct}%${elapsed ? ` · ${elapsed}` : ""}` : "Queued"}+ {running+ ? `${pct}%${elapsed ? ` · ${elapsed}` : ""}`+ : status === "preparing"+ ? "Preparing…"+ : "Queued"}</span></span>- <Button- variant="ghost"- size="xs"- className="shrink-0 text-muted-foreground hover:text-destructive"- onClick={() => useExports.getState().cancel(job.id)}- >- Cancel- </Button>- {job.status === "running" && (+ {cancelable && (+ <Button+ variant="ghost"+ size="xs"+ className="shrink-0 text-muted-foreground hover:text-destructive"+ onClick={() => useExports.getState().cancel(row.data.id)}+ >+ Cancel+ </Button>+ )}+ {running && (<div className="absolute inset-x-0 bottom-0 h-0.5 bg-secondary"><divclassName="h-full bg-primary transition-[width] duration-300"@@ -681,16 +707,11 @@ function ProjectFilesPanel({.sort().join());- // This project's exports still in flight: queued/running jobs plus the brief- // client-only "preparing" window before the engine hands back a job id.- const exportJobs = useExports((s) => s.jobs);- const exportLocal = useExports((s) => s.local);- const exporting = exportJobs.filter(- (j) => j.projectId === projectId && (j.status === "queued" || j.status === "running")- );- const preparing = exportLocal.filter(- (r) => r.projectId === projectId && r.status === "preparing"- );+ // This project's exports still being worked on, assembled the way the dock+ // assembles every project's. A cloud or browser project renders in the tab,+ // and that render carries its progress on a local row; the engine's feed+ // alone showed nothing at all while it ran.+ const exporting = useExportRows(projectId).filter(exportInFlight);const readOnly = useEditor((s) => s.readOnly);// The whole panel takes drops: OS files import into this project and stay off// the timeline, and a project asset made elsewhere (a generation, a@@ -707,8 +728,18 @@ function ProjectFilesPanel({const [preview, setPreview] = useState<ExportItem | null>(null);const [deletingExport, setDeletingExport] = useState<ExportItem | null>(null);+ // Whatever is being worked on right now. When the last of it drops out — a+ // job settling, a tab-side render finishing — the folder has a new file in+ // it, so this is the second trigger for the re-read below. It covers the+ // paths the job feed alone misses: a render this tab did itself never passes+ // through a queued engine job.+ const exportingKey = exporting+ .map((r) => r.data.id)+ .sort()+ .join();+// Refresh the list on open, when the export dialog closes, and when a- // background render settles (done/error).+ // background render settles (done/error) or finishes in this tab.useEffect(() => {if (exportOpen) return;let alive = true;@@ -719,7 +750,7 @@ function ProjectFilesPanel({return () => {alive = false;};- }, [projectId, exportOpen, exportsSettled]);+ }, [projectId, exportOpen, exportsSettled, exportingKey]);const removeExport = async () => {const it = deletingExport;@@ -838,26 +869,12 @@ function ProjectFilesPanel({</Marquee>)}- {exports.length + exporting.length + preparing.length > 0 && (+ {exports.length + exporting.length > 0 && (<div className="mt-5 px-3.5"><div className="mb-2 text-[13px] font-semibold tracking-tight">Exports</div><div className="flex flex-col gap-1.5">- {preparing.map((r) => (- <div- key={r.id}- className="flex w-full items-center gap-2.5 rounded-lg border border-border p-1.5"- >- <div className="grid h-11 w-[25px] shrink-0 place-items-center rounded-[4px] bg-muted">- <Loader2 className="size-3.5 animate-spin text-primary" />- </div>- <span className="min-w-0 flex-1">- <span className="block truncate text-[11.5px] font-medium">Exporting…</span>- <span className="block text-[10.5px] text-muted-foreground">Preparing…</span>- </span>- </div>- ))}- {exporting.map((j) => (- <ExportingRow key={j.id} job={j} />+ {exporting.map((row) => (+ <ExportingRow key={row.data.id} row={row} />))}{exports.map((it) => (<divdiff --git a/site/src/cut/components/SubtitlesPanel.tsx b/site/src/cut/components/SubtitlesPanel.tsxindex cee7cf8c..031ad093 100644--- a/site/src/cut/components/SubtitlesPanel.tsx+++ b/site/src/cut/components/SubtitlesPanel.tsx@@ -20,6 +20,7 @@ import {} from "@/cut/lib/subtitles";import { useElapsed } from "@/cut/hooks/useElapsed";import { useCutCaps } from "@/cut/lib/backend/hooks";+import { useActiveWork, useGenNotify } from "@/cut/lib/genNotify";import { TIMELINE_H_MIN, useEditor } from "@/cut/lib/store";import { usePreviewSelector } from "@/cut/lib/playhead";import { PLATE_PAD_X, PLATE_PAD_Y, PLATE_RADIUS, plateFill } from "@/cut/lib/textRender";@@ -101,7 +102,15 @@ export function SubtitlesPanel() {};const translate = (fromLane: number) => {- void useEditor.getState().translateSubtitleTrack(fromLane).then(growTimeline);+ // Registered so the running panel knows which pass it is watching even+ // after the tab was closed and reopened — the local flag went with the+ // unmount and the wait then read as a transcription.+ const settle = useGenNotify.getState().begin("subtitles", "translate");+ void useEditor+ .getState()+ .translateSubtitleTrack(fromLane)+ .then(growTimeline)+ .finally(settle);};// A shared view reads the transcript; styling and generation stay the@@ -432,7 +441,9 @@ function EmptyState({const sources = Array.from({ length: subtitleLaneCount(subtitles) }, (_, i) => i).filter((i) => i !== lane && laneCues(subtitles, i).length > 0);- const [translating, setTranslating] = useState(false);+ // Which pass is running, read from the store: this component unmounts+ // whenever the user visits another tab.+ const translating = useActiveWork("subtitles", "translate") > 0;if (status === "running") {return (@@ -484,10 +495,7 @@ function EmptyState({{caps.transcribe && (<ButtonclassName="sub-generate w-full"- onClick={() => {- setTranslating(false);- onGenerate();- }}+ onClick={onGenerate}title="Transcribe your audio into plain captions, word for word"><Captions data-icon="inline-start" />@@ -503,10 +511,7 @@ function EmptyState({title={`Write this track by translating the ${laneLanguage(subtitles, i)} captions into ${LOCALES.find(([id]) => id === locale)?.[1] ?? locale}`}- onClick={() => {- setTranslating(true);- onTranslate(i);- }}+ onClick={() => onTranslate(i)}><Languages data-icon="inline-start" />Translate from {laneLanguage(subtitles, i)}diff --git a/site/src/cut/lib/exportStore.ts b/site/src/cut/lib/exportStore.tsindex fed5c675..a3d33b14 100644--- a/site/src/cut/lib/exportStore.ts+++ b/site/src/cut/lib/exportStore.ts@@ -1,6 +1,6 @@"use client";-import { useEffect, useRef } from "react";+import { useEffect, useMemo, useRef } from "react";import { create } from "zustand";import { engineOrigin, servedFromEngine } from "./api";import { getBackend, type CutBackend, type CutMode } from "./backend";@@ -306,6 +306,64 @@ export const useExports = create<ExportsState>((set, get) => ({},}));+/** One row a surface shows: an engine job, or a local row this tab owns. */+export type ExportRow =+ | { kind: "job"; data: ExportJob }+ | { kind: "local"; data: LocalRow };++/** Running first, then waiting, then what has settled. */+const statusRank = (status: string) =>+ status === "running" || status === "rendering"+ ? 0+ : status === "queued" || status === "preparing"+ ? 1+ : status === "done"+ ? 2+ : 3;++/**+ * Every export row a surface should show, in that order — the one assembly the+ * dock and the Media tab share, so the two never disagree about what is in+ * flight.+ *+ * A render this tab is doing itself appears once: the local row carries the+ * progress, and the reserved job row behind it is held back until the render+ * settles. Pass a projectId to narrow it to one project's work.+ *+ * Dismissal is left to the caller. `dismissed` is the dock's own hide list —+ * an X there on a still-running export silences the notification while the+ * render carries on — and the Media tab, which is the project's record of its+ * work and the only place with a cancel, keeps showing it.+ */+export function useExportRows(projectId?: string): ExportRow[] {+ const jobs = useExports((s) => s.jobs);+ const local = useExports((s) => s.local);+ const rendering = useExports((s) => s.rendering);+ return useMemo(() => {+ const mine = (x: { projectId: string }) => !projectId || x.projectId === projectId;+ return [+ ...jobs+ .filter((j) => mine(j) && !rendering.includes(j.id))+ .map((j) => ({ kind: "job" as const, data: j })),+ ...local.filter(mine).map((r) => ({ kind: "local" as const, data: r })),+ ].sort((a, b) => {+ const dr = statusRank(a.data.status) - statusRank(b.data.status);+ return dr !== 0 ? dr : (a.data.createdAt ?? 0) - (b.data.createdAt ?? 0);+ });+ }, [jobs, local, rendering, projectId]);+}++/** True while that row is still being worked on. */+export const exportInFlight = (row: ExportRow) => statusRank(row.data.status) <= 1;++/** Whether {@link ExportsState.cancel} can actually stop this row. A job is+ * cancelable through its backend, and a render this tab is doing itself+ * through the controller it holds. The seconds a local row spends handing the+ * cut to the engine ("preparing") hold no controller: that hand-off runs to+ * the job it creates, which is cancelable the moment it joins the feed. */+export const exportCancelable = (row: ExportRow) =>+ row.kind === "job" ? exportInFlight(row) : !!row.data.abort;+/** Badge the Media tab when one of this project's exports finishes in the* background: watch the engine feed for jobs newly turned done and report each* to the gen-notify store, keyed by file name so the export row can pulse.diff --git a/site/src/cut/lib/genNotify.ts b/site/src/cut/lib/genNotify.tsindex acc9cdda..15fa6ee0 100644--- a/site/src/cut/lib/genNotify.ts+++ b/site/src/cut/lib/genNotify.ts@@ -46,9 +46,11 @@ interface GenNotifyState {/** The just-opened tab's arrivals, pulsing until their timer clears them. */pulsing: Record<GenTab, string[]>;/** In-flight work registered per tab — the rail tile spins while a tab has- * entries. For work whose running state lives in no store of its own (audio- * syntheses); tabs with a job store (generate, exports, subtitles) are read- * directly by the rail. */+ * entries, and a panel reads its own share through {@link useActiveWork}.+ * This is where work whose running state lives in no store of its own goes+ * (the audio syntheses, which pass tells the subtitles panel what it is+ * waiting on); the tabs with a job feed of their own — Video, Image, Media —+ * are read from those feeds instead. */active: Record<GenTab, string[]>;/** The generate tab on screen; a completion here needs no badge or pulse —* the user watched the tile appear. */@@ -56,8 +58,10 @@ interface GenNotifyState {landed: (tab: GenTab, assetId: string) => void;/** Register a long task with its tab; call the returned function when it* settles. Settling after a project switch is a no-op — reset() already- * dropped the entry. */- begin: (tab: GenTab) => () => void;+ * dropped the entry. `job` names which of a tab's generators owns the work,+ * so a panel can count its own in flight ({@link useActiveWork}) and leave+ * the tab's other tasks out of it. */+ begin: (tab: GenTab, job?: string) => () => void;watch: (tab: GenTab | null) => void;endPulse: (tab: GenTab) => void;reset: () => void;@@ -72,8 +76,8 @@ export const useGenNotify = create<GenNotifyState>((set, get) => ({if (get().watching === tab) return; // watched live — no badge, no pulseset((s) => ({ unseen: { ...s.unseen, [tab]: [...s.unseen[tab], assetId] } }));},- begin: (tab) => {- const key = `w${workSeq++}`;+ begin: (tab, job) => {+ const key = `${job ?? ""}#w${workSeq++}`;set((s) => ({ active: { ...s.active, [tab]: [...s.active[tab], key] } }));return () =>set((s) =>@@ -101,6 +105,19 @@ export const useGenNotify = create<GenNotifyState>((set, get) => ({reset: () => set({ unseen: EMPTY, pulsing: EMPTY, active: EMPTY }),}));+/**+ * How many pieces of work a panel has in flight right now — the durable count,+ * held in this store, so a generator's "Generating…" row survives a trip to+ * another tab and back. Pass the `job`+ * name it registered under to count only its own; omit it for the tab's whole+ * load.+ */+export function useActiveWork(tab: GenTab, job?: string): number {+ return useGenNotify(+ (s) => s.active[tab].filter((k) => !job || k.startsWith(`${job}#`)).length+ );+}+/** Whether this finished tile is in its tab's fresh-arrival pulse. */export function useGenPulse(tab: GenTab, assetId?: string): boolean {return useGenNotify((s) => (assetId ? s.pulsing[tab].includes(assetId) : false));