Skip to content

Open source CapCut alternative.

TypeScript

feat(site): app-wide Cut exports dock across projects and tabs

David Le6f78908b7681
diff --git a/site/src/app/cut/app/layout.tsx b/site/src/app/cut/app/layout.tsx
index db692b0b..1e7e8595 100644
--- a/site/src/app/cut/app/layout.tsx
+++ b/site/src/app/cut/app/layout.tsx
@@ -2,6 +2,7 @@ import type { ReactNode } from "react";
import { AppSurfaceBackground } from "@/app/app/_components/AppSurfaceBackground";
import { ConnectGate } from "@/cut/components/ConnectGate";
+import { ExportsDock } from "@/cut/components/ExportsDock";
import { RequireSession } from "@/cut/components/RequireSession";
// The Cut app (projects home, library, editor) renders on the same white
@@ -19,7 +20,11 @@ export default function CutAppLayout({ children }: { children: ReactNode }) {
<div className="min-h-screen bg-white font-system text-foreground antialiased">
<AppSurfaceBackground />
<RequireSession>
- <ConnectGate>{children}</ConnectGate>
+ <ConnectGate>
+ {children}
+ {/* App-wide: exports keep showing as you move between projects. */}
+ <ExportsDock />
+ </ConnectGate>
</RequireSession>
</div>
);
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index 0a0f9862..71b54651 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -6,7 +6,6 @@ import { Clapperboard, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { apiFetch } from "@/cut/lib/api";
import { renderPreviewProxy } from "@/cut/lib/exportClient";
-import { useExport } from "@/cut/lib/exportStore";
import { fileZoneAt, hasRefDrag } from "@/cut/lib/assetRef";
import { enrichAsset, importFileToProject } from "@/cut/lib/media";
// Side-effect import: registers the brief-to-video resume subscription, so a
@@ -18,7 +17,6 @@ import { projectDuration, serializeDoc, storedAssets, useEditor } from "@/cut/li
import type { MediaAsset } from "@/cut/lib/types";
import { AiPanel } from "./AiPanel";
import { ExportDialog } from "./ExportDialog";
-import { ExportStatus } from "./ExportStatus";
import { Inspector } from "./Inspector";
import { Lightbox } from "./Lightbox";
import { Preview } from "./Preview";
@@ -60,8 +58,9 @@ export function Editor({
.then(() => {
for (const asset of useEditor.getState().assets) void enrichAsset(asset);
});
- // Rejoin an export that's still rendering (e.g. after a reload).
- void useExport.getState().reconnect(projectId);
+ // An export still rendering after a reload rejoins on its own: the app-wide
+ // exports dock polls the engine's job feed, so it reappears with no per-
+ // project reconnect here.
}, [projectId]);
// Keep the project card's hover proxy fresh: rebuild it a few seconds after
@@ -435,7 +434,6 @@ export function Editor({
/>
)}
{exportOpen && <ExportDialog />}
- <ExportStatus />
<Lightbox />
</div>
);
diff --git a/site/src/cut/components/ExportDialog.tsx b/site/src/cut/components/ExportDialog.tsx
index 264b21a3..f964c313 100644
--- a/site/src/cut/components/ExportDialog.tsx
+++ b/site/src/cut/components/ExportDialog.tsx
@@ -1,7 +1,6 @@
"use client";
import { useMemo, useState } from "react";
-import { Check } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -10,7 +9,6 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
-import { useElapsed } from "@/cut/hooks/useElapsed";
import {
EXPORT_PRESETS,
estimateExportBytes,
@@ -18,10 +16,13 @@ import {
originalSettings,
presetSettings,
} from "@/cut/lib/exportClient";
-import { useExport } from "@/cut/lib/exportStore";
+import { useExports } from "@/cut/lib/exportStore";
import { projectDuration, useEditor } from "@/cut/lib/store";
import { cn } from "@/lib/utils";
+// Just a launcher: pick a preset, hand the cut to the engine, and close. Every
+// export — progress, queue position, the finished file — is tracked in the
+// app-wide exports dock, so starting one never blocks starting another.
export function ExportDialog() {
const setExportOpen = useEditor((s) => s.setExportOpen);
const aspect = useEditor((s) => s.aspect);
@@ -32,11 +33,6 @@ export function ExportDialog() {
() => projectDuration({ clips, audioClips }),
[clips, audioClips]
);
- const status = useExport((s) => s.status);
- const ratio = useExport((s) => s.ratio);
- const startedAt = useExport((s) => s.startedAt);
- const elapsed = useElapsed(status === "running" ? startedAt : null);
- const error = useExport((s) => s.error);
// "Original" leads: sized from the footage on the timeline, so it is always
// the highest option. The fixed presets follow, flipped to the aspect.
const presets = useMemo(
@@ -58,142 +54,68 @@ export function ExportDialog() {
);
const [presetId, setPresetId] = useState("original");
- // Closing never cancels a running render — clicking outside (or Esc) just
- // dismisses the dialog and the render keeps going in the background, tracked
- // by the status chip. Only Cancel stops it. A finished/failed export is
- // cleared on close.
- const close = () => {
- if (useExport.getState().status !== "running") useExport.getState().dismiss();
- setExportOpen(false);
- };
-
const run = () => {
const s = useEditor.getState();
if (!s.projectId) return;
const settings = (presets.find((p) => p.id === presetId) ?? presets[0]).settings;
- useExport.getState().start(s.projectId, {
- assets: s.assets,
- clips: s.clips,
- audioClips: s.audioClips,
- overlays: s.overlays,
- subtitles: s.subtitles,
- fadeIn: s.fadeIn,
- fadeOut: s.fadeOut,
- }, settings);
+ void useExports.getState().start(
+ s.projectId,
+ {
+ assets: s.assets,
+ clips: s.clips,
+ audioClips: s.audioClips,
+ overlays: s.overlays,
+ subtitles: s.subtitles,
+ fadeIn: s.fadeIn,
+ fadeOut: s.fadeOut,
+ },
+ settings,
+ s.projectName
+ );
+ setExportOpen(false); // the dock takes it from here
};
return (
- <Dialog open onOpenChange={(o) => !o && close()}>
+ <Dialog open onOpenChange={(o) => !o && setExportOpen(false)}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
<DialogTitle>Export</DialogTitle>
</DialogHeader>
- {status === "idle" && (
- <>
- <div className="flex flex-col gap-2" role="radiogroup" aria-label="Export preset">
- {presets.map((p) => (
- <button
- key={p.id}
- role="radio"
- aria-checked={presetId === p.id}
- className={cn(
- "flex items-center gap-3 rounded-lg border border-border bg-background px-3 py-2.5 text-left transition-colors hover:border-input",
- presetId === p.id && "border-primary bg-primary/10"
- )}
- onClick={() => setPresetId(p.id)}
- >
- <span className="flex min-w-0 flex-col items-start">
- <span className="text-sm font-medium">{p.label}</span>
- <span className="text-xs text-muted-foreground">
- {p.settings.width} × {p.settings.height} · {p.detail}
- </span>
- </span>
- <span className="ml-auto shrink-0 text-xs tabular-nums text-muted-foreground">
- {formatSizeEstimate(estimateExportBytes(p.settings, duration))}
- </span>
- </button>
- ))}
- </div>
- <DialogFooter>
- <Button className="w-full" onClick={run}>
- Export video
- </Button>
- </DialogFooter>
- </>
- )}
-
- {status === "running" && (
- <>
- <div className="pt-1">
- <div className="h-1.5 overflow-hidden rounded-full bg-secondary">
- <div
- className="h-full rounded-full bg-primary transition-[width] duration-300"
- style={{ width: `${Math.round(ratio * 100)}%` }}
- />
- </div>
- <div className="mt-2.5 flex justify-end text-xs text-muted-foreground">
- <span className="font-mono tabular-nums">
- {Math.round(ratio * 100)}%{elapsed ? ` · ${elapsed}` : ""}
+ <div className="flex flex-col gap-2" role="radiogroup" aria-label="Export preset">
+ {presets.map((p) => (
+ <button
+ key={p.id}
+ role="radio"
+ aria-checked={presetId === p.id}
+ className={cn(
+ "flex items-center gap-3 rounded-lg border border-border bg-background px-3 py-2.5 text-left transition-colors hover:border-input",
+ presetId === p.id && "border-primary bg-primary/10"
+ )}
+ onClick={() => setPresetId(p.id)}
+ >
+ <span className="flex min-w-0 flex-col items-start">
+ <span className="text-sm font-medium">{p.label}</span>
+ <span className="text-xs text-muted-foreground">
+ {p.settings.width} × {p.settings.height} · {p.detail}
</span>
- </div>
- <p className="mt-3 text-center text-xs text-muted-foreground">
- Rendering in the background. You can keep editing, or close this
- to hide it and it keeps going.
- </p>
- </div>
- <DialogFooter className="py-2 sm:justify-center">
- <Button
- variant="ghost"
- size="sm"
- className="text-xs text-muted-foreground"
- onClick={() => {
- useExport.getState().cancel();
- setExportOpen(false);
- }}
- >
- Cancel export
- </Button>
- </DialogFooter>
- </>
- )}
-
- {status === "done" && (
- <>
- <div className="flex flex-col items-center pt-2 text-center">
- <span className="mb-3 grid size-11 place-items-center rounded-full bg-[#30d158] text-[#04180b]">
- <Check className="size-5" />
</span>
- <div className="text-sm text-muted-foreground">
- Saved into the project's exports folder and downloaded.
- </div>
- </div>
- <DialogFooter>
- <Button className="w-full" onClick={close}>
- Done
- </Button>
- </DialogFooter>
- </>
- )}
+ <span className="ml-auto shrink-0 text-xs tabular-nums text-muted-foreground">
+ {formatSizeEstimate(estimateExportBytes(p.settings, duration))}
+ </span>
+ </button>
+ ))}
+ </div>
- {status === "error" && (
- <>
- <div>
- <div className="mb-2 text-sm font-medium text-destructive">
- Export didn't finish
- </div>
- <pre className="max-h-36 overflow-auto rounded-lg border border-border bg-background p-2.5 font-mono text-[10.5px] leading-relaxed break-words whitespace-pre-wrap text-muted-foreground select-text">
- {error}
- </pre>
- </div>
- <DialogFooter>
- <Button variant="ghost" onClick={close}>
- Close
- </Button>
- <Button onClick={() => useExport.getState().dismiss()}>Try again</Button>
- </DialogFooter>
- </>
- )}
+ <DialogFooter className="flex-col gap-2 sm:flex-col">
+ <Button className="w-full" onClick={run}>
+ Export video
+ </Button>
+ <p className="text-center text-[11px] text-muted-foreground">
+ Renders in the background. You can keep editing, open another project,
+ or export more — each shows in the corner.
+ </p>
+ </DialogFooter>
</DialogContent>
</Dialog>
);
diff --git a/site/src/cut/components/ExportStatus.tsx b/site/src/cut/components/ExportStatus.tsx
deleted file mode 100644
index 293f0555..00000000
--- a/site/src/cut/components/ExportStatus.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-"use client";
-
-import { Check, FolderOpen, Loader2, X } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { useElapsed } from "@/cut/hooks/useElapsed";
-import { revealExport } from "@/cut/lib/exportClient";
-import { useExport } from "@/cut/lib/exportStore";
-import { useEditor } from "@/cut/lib/store";
-
-/** A small floating chip that tracks a background export after the dialog is
- * closed, so the render keeps going and the result is still one click away. */
-export function ExportStatus() {
- const status = useExport((s) => s.status);
- const ratio = useExport((s) => s.ratio);
- const outName = useExport((s) => s.outName);
- const projectId = useExport((s) => s.projectId);
- const startedAt = useExport((s) => s.startedAt);
- const exportOpen = useEditor((s) => s.exportOpen);
- const elapsed = useElapsed(status === "running" ? startedAt : null);
-
- // The dialog owns the UI while it's open.
- if (exportOpen || status === "idle") return null;
-
- return (
- <div className="fixed right-4 bottom-4 z-50 flex items-center gap-2.5 rounded-xl border border-border bg-card px-3 py-2 shadow-lg">
- {status === "running" && (
- <>
- <Loader2 className="size-4 animate-spin text-primary" />
- <span className="text-xs font-medium">
- Exporting…{" "}
- <span className="tabular-nums text-muted-foreground">
- {Math.round(ratio * 100)}%{elapsed ? ` · ${elapsed}` : ""}
- </span>
- </span>
- <Button
- variant="ghost"
- size="icon-xs"
- aria-label="Cancel export"
- onClick={() => useExport.getState().cancel()}
- >
- <X />
- </Button>
- </>
- )}
- {status === "done" && (
- <>
- <span className="grid size-5 place-items-center rounded-full bg-[#30d158] text-[#04180b]">
- <Check className="size-3" />
- </span>
- <span className="text-xs font-medium">Export ready</span>
- {projectId && outName && (
- <Button
- variant="ghost"
- size="icon-xs"
- aria-label="Show in Finder"
- title="Show in Finder"
- onClick={() => void revealExport(projectId, outName).catch(() => {})}
- >
- <FolderOpen />
- </Button>
- )}
- <Button
- variant="ghost"
- size="icon-xs"
- aria-label="Dismiss"
- onClick={() => useExport.getState().dismiss()}
- >
- <X />
- </Button>
- </>
- )}
- {status === "error" && (
- <>
- <span className="text-xs font-medium text-destructive">Export failed</span>
- <Button
- variant="ghost"
- size="icon-xs"
- aria-label="Dismiss"
- onClick={() => useExport.getState().dismiss()}
- >
- <X />
- </Button>
- </>
- )}
- </div>
- );
-}
diff --git a/site/src/cut/components/ExportsDock.tsx b/site/src/cut/components/ExportsDock.tsx
new file mode 100644
index 00000000..8ca8f55b
--- /dev/null
+++ b/site/src/cut/components/ExportsDock.tsx
@@ -0,0 +1,252 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import Link from "next/link";
+import {
+ Check,
+ ChevronDown,
+ CircleAlert,
+ Clock,
+ Download,
+ FolderOpen,
+ Loader2,
+ X,
+} from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { useElapsed } from "@/cut/hooks/useElapsed";
+import { downloadExport, revealExport } from "@/cut/lib/exportClient";
+import {
+ beginExportPolling,
+ endExportPolling,
+ useExports,
+ type ExportJob,
+ type LocalRow,
+} from "@/cut/lib/exportStore";
+import { projectHref, useCutBase } from "@/cut/lib/nav";
+import { cn } from "@/lib/utils";
+
+/**
+ * The app-wide exports dock: one card pinned to the bottom-right that shows
+ * every export across every project, live in every tab. It mirrors the engine's
+ * job feed, so a render started in one project keeps showing while you open
+ * another, exports queued past the running cap show their place in line, and a
+ * finished file is one click from Finder or a re-download. Mounted once in the
+ * 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 [collapsed, setCollapsed] = useState(false);
+
+ // Poll the feed while the dock is mounted (i.e. the whole time the app is up).
+ useEffect(() => {
+ beginExportPolling();
+ return endExportPolling;
+ }, []);
+
+ const items = useMemo(() => {
+ const rank = (status: string) =>
+ status === "running" ? 0 : status === "queued" || status === "preparing" ? 1 : status === "done" ? 2 : 3;
+ const visible = jobs.filter((j) => !dismissed.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]);
+
+ if (items.length === 0) return null;
+
+ const running = items.filter((i) => i.data.status === "running").length;
+ const waiting = items.filter(
+ (i) => i.data.status === "queued" || i.data.status === "preparing"
+ ).length;
+ const multi = items.length > 1;
+
+ return (
+ <div className="fixed right-4 bottom-4 z-50 w-72 overflow-hidden rounded-xl border border-border bg-card shadow-lg">
+ {multi && (
+ <div className="flex items-center gap-2 px-3 py-2">
+ <span className="text-xs font-semibold">Exports</span>
+ <span className="flex-1 truncate text-[11px] text-muted-foreground tabular-nums">
+ {[running && `${running} running`, waiting && `${waiting} queued`]
+ .filter(Boolean)
+ .join(" · ") || `${items.length} done`}
+ </span>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label={collapsed ? "Expand exports" : "Collapse exports"}
+ onClick={() => setCollapsed((c) => !c)}
+ >
+ <ChevronDown className={cn("transition-transform", !collapsed && "rotate-180")} />
+ </Button>
+ </div>
+ )}
+ {!collapsed && (
+ <div className="max-h-[min(60vh,22rem)] divide-y divide-border overflow-y-auto">
+ {items.map((it) =>
+ it.kind === "job" ? (
+ <ExportRow key={it.data.id} job={it.data} />
+ ) : (
+ <LocalRowView key={it.data.id} row={it.data} />
+ )
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function StatusIcon({ status }: { status: string }) {
+ if (status === "running" || status === "preparing")
+ return <Loader2 className="size-4 shrink-0 animate-spin text-primary" />;
+ if (status === "queued") return <Clock className="size-4 shrink-0 text-muted-foreground" />;
+ if (status === "done")
+ return (
+ <span className="grid size-4 shrink-0 place-items-center rounded-full bg-[#30d158] text-[#04180b]">
+ <Check className="size-2.5" />
+ </span>
+ );
+ return <CircleAlert className="size-4 shrink-0 text-destructive" />;
+}
+
+function ProjectName({ projectId, name }: { projectId: string; name?: string }) {
+ const base = useCutBase();
+ return (
+ <Link
+ href={projectHref(base, projectId, "projects")}
+ className="block truncate text-xs font-medium hover:underline"
+ title={name || "Untitled"}
+ >
+ {name || "Untitled"}
+ </Link>
+ );
+}
+
+function ExportRow({ job }: { job: ExportJob }) {
+ const elapsed = useElapsed(job.status === "running" ? job.startedAt ?? null : null);
+ const pct = Math.round(job.progress * 100);
+
+ const sub =
+ job.status === "running"
+ ? `${pct}%${elapsed ? ` · ${elapsed}` : ""}`
+ : job.status === "queued"
+ ? "Queued"
+ : job.status === "done"
+ ? "Ready"
+ : job.error || "Export failed";
+
+ return (
+ <div className="relative flex items-center gap-2.5 px-3 py-2">
+ <StatusIcon status={job.status} />
+ <div className="min-w-0 flex-1">
+ <ProjectName projectId={job.projectId} name={job.projectName} />
+ <div
+ className={cn(
+ "truncate text-[11px] tabular-nums",
+ job.status === "error" ? "text-destructive" : "text-muted-foreground"
+ )}
+ >
+ {sub}
+ </div>
+ </div>
+ <div className="flex items-center">
+ {(job.status === "running" || job.status === "queued") && (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Cancel export"
+ onClick={() => useExports.getState().cancel(job.id)}
+ >
+ <X />
+ </Button>
+ )}
+ {job.status === "done" && (
+ <>
+ {job.outName && (
+ <>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Show in Finder"
+ title="Show in Finder"
+ onClick={() => void revealExport(job.projectId, job.outName!).catch(() => {})}
+ >
+ <FolderOpen />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Download again"
+ title="Download"
+ onClick={() => downloadExport(job.id, job.outName!)}
+ >
+ <Download />
+ </Button>
+ </>
+ )}
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Dismiss"
+ onClick={() => useExports.getState().dismiss(job.id)}
+ >
+ <X />
+ </Button>
+ </>
+ )}
+ {job.status === "error" && (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Dismiss"
+ onClick={() => useExports.getState().dismiss(job.id)}
+ >
+ <X />
+ </Button>
+ )}
+ </div>
+ {job.status === "running" && (
+ <div className="absolute inset-x-0 bottom-0 h-0.5 bg-secondary">
+ <div
+ className="h-full bg-primary transition-[width] duration-300"
+ style={{ width: `${pct}%` }}
+ />
+ </div>
+ )}
+ </div>
+ );
+}
+
+function LocalRowView({ row }: { row: LocalRow }) {
+ return (
+ <div className="flex items-center gap-2.5 px-3 py-2">
+ <StatusIcon status={row.status} />
+ <div className="min-w-0 flex-1">
+ <ProjectName projectId={row.projectId} name={row.projectName} />
+ <div
+ className={cn(
+ "truncate text-[11px]",
+ row.status === "error" ? "text-destructive" : "text-muted-foreground"
+ )}
+ >
+ {row.status === "preparing" ? "Preparing…" : row.error || "Couldn't start export"}
+ </div>
+ </div>
+ {row.status === "error" && (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Dismiss"
+ onClick={() => useExports.getState().dismiss(row.id)}
+ >
+ <X />
+ </Button>
+ )}
+ </div>
+ );
+}
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index fc3fad36..6405c6d1 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -29,7 +29,7 @@ import {
import type { AssetRef } from "@/cut/lib/assetRef";
import { RefDropZone } from "./RefDropZone";
import { deleteExport, revealExport } from "@/cut/lib/exportClient";
-import { useExport } from "@/cut/lib/exportStore";
+import { useExports } from "@/cut/lib/exportStore";
import {
addAssetToLibraryTemplate,
addLibraryAssetToProject,
@@ -330,7 +330,15 @@ function MediaPanel({
// A render that finishes in the background (dialog closed) drops a new file in
// the exports folder; re-read the list when it lands so it shows without a
// manual refresh.
- const exportStatus = useExport((s) => s.status);
+ // Refetch the finished-file list whenever an export for this project settles
+ // (its file lands in the exports folder). Counting settled jobs gives a value
+ // that changes exactly on that transition.
+ const exportsSettled = useExports(
+ (s) =>
+ s.jobs.filter(
+ (j) => j.projectId === projectId && (j.status === "done" || j.status === "error")
+ ).length
+ );
const inputRef = useRef<HTMLInputElement>(null);
const [exports, setExports] = useState<ExportItem[]>([]);
const [preview, setPreview] = useState<ExportItem | null>(null);
@@ -348,7 +356,7 @@ function MediaPanel({
return () => {
alive = false;
};
- }, [projectId, exportOpen, exportStatus]);
+ }, [projectId, exportOpen, exportsSettled]);
const removeExport = async () => {
const it = deletingExport;
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index b45c3042..5aeae8c3 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -138,10 +138,6 @@ export interface ExportDoc {
fadeOut?: number;
}
-export interface ExportHandle {
- cancel: () => void;
- done: Promise<{ outName: string }>;
-}
/** Build the export FormData from the cut. Media already lives in the project
* folder — the spec references it by file name; only overlay PNGs travel with
@@ -391,37 +387,25 @@ export function downloadExport(jobId: string, outName: string) {
a.remove();
}
-export function startExport(
+/** Build the cut and hand it to the engine, returning the new job id. Progress,
+ * cancel, download, and the finished-file actions are all driven from the
+ * engine's job feed by the exports dock — this only kicks the render off, so it
+ * returns the moment the job is queued and never blocks on the encode. */
+export async function createExportJob(
projectId: string,
doc: ExportDoc,
- settings: ExportSettings,
- onProgress: (stage: string, ratio: number) => void
-): ExportHandle {
- let jobId: string | null = null;
- let canceled = false;
-
- const done = (async () => {
- onProgress("Preparing", 0);
- const form = await buildExportForm(projectId, doc, settings, "export");
- onProgress("Starting encoder", 0);
- const res = await apiFetch("/api/cut/export", { method: "POST", body: form });
- const body = await apiJson<{ id?: string }>(res);
- if (!res.ok || !body.id) throw new Error(body.error ?? "Export failed to start.");
- jobId = body.id;
-
- const outName = await pollExport(jobId, onProgress, () => canceled);
- onProgress("Done", 1);
- downloadExport(jobId, outName);
- return { outName };
- })();
+ settings: ExportSettings
+): Promise<string> {
+ const form = await buildExportForm(projectId, doc, settings, "export");
+ const res = await apiFetch("/api/cut/export", { method: "POST", body: form });
+ const body = await apiJson<{ id?: string }>(res);
+ if (!res.ok || !body.id) throw new Error(body.error ?? "Export failed to start.");
+ return body.id;
+}
- return {
- done,
- cancel: () => {
- canceled = true;
- if (jobId) void apiFetch(`/api/cut/export/${jobId}`, { method: "DELETE" });
- },
- };
+/** Cancel a running or queued export job by id. */
+export function cancelExportJob(jobId: string) {
+ void apiFetch(`/api/cut/export/${jobId}`, { method: "DELETE" }).catch(() => {});
}
/** Low-res proxy of the actual edit for the project card's hover preview.
diff --git a/site/src/cut/lib/exportStore.ts b/site/src/cut/lib/exportStore.ts
index 2560bba0..ab07d630 100644
--- a/site/src/cut/lib/exportStore.ts
+++ b/site/src/cut/lib/exportStore.ts
@@ -3,100 +3,167 @@
import { create } from "zustand";
import { apiFetch } from "./api";
import {
+ cancelExportJob,
+ createExportJob,
downloadExport,
- pollExport,
- startExport,
type ExportDoc,
- type ExportHandle,
type ExportSettings,
} from "./exportClient";
-// The current export, held outside the dialog so it keeps running (and stays
-// visible) after the dialog closes. One export at a time is plenty here.
+// Exports are tracked app-wide, not per-open-project. The engine holds every
+// export job in one process-global registry, so this store is a thin reflection
+// of that feed: every tab polls the same list and shows the same queue, and
+// starting an export in one project while another still renders just adds a row.
+// The dock (ExportsDock) renders it; the engine does the queueing.
-type Status = "idle" | "running" | "done" | "error";
-
-interface ExportState {
- status: Status;
- stage: string;
- ratio: number;
- /** Epoch ms when this export started (or was rejoined) — the running chip
- * and dialog show a ticking elapsed from it. */
- startedAt: number | null;
+export interface ExportJob {
+ id: string;
+ projectId: string;
+ projectName?: string;
+ status: "queued" | "running" | "done" | "error";
+ progress: number; // 0..1
outName?: string;
error?: string;
- projectId: string | null;
- handle: ExportHandle | null;
- start: (projectId: string, doc: ExportDoc, settings: ExportSettings) => void;
- cancel: () => void;
- dismiss: () => void;
- /** After a reopen or reload, rejoin an export still running for a project. */
- reconnect: (projectId: string) => Promise<void>;
+ /** Epoch ms the encode began (elapsed clock) and the job was created (order). */
+ startedAt?: number;
+ createdAt?: number;
+}
+
+/** A client-only dock row for the brief window before the engine has a job id:
+ * while the cut is being built and uploaded ("preparing"), or when that failed
+ * before a job ever existed ("error"). Kept apart from the engine feed so a
+ * poll tick never clears it. */
+export interface LocalRow {
+ id: string;
+ projectId: string;
+ projectName?: string;
+ status: "preparing" | "error";
+ error?: string;
+ createdAt: number;
+}
+
+// Jobs this tab started, so this tab (and only this tab) auto-downloads them
+// when they finish — the same one-download-per-export the single export gave.
+// Other tabs still see the job and can download it by hand from the dock.
+const ownDownloads = new Set<string>();
+
+interface ExportsState {
+ /** The engine's export feed, reflected verbatim on each poll. */
+ jobs: ExportJob[];
+ /** Rows that don't have an engine job yet (preparing / start error). */
+ local: LocalRow[];
+ /** Finished/failed engine jobs the user cleared from this tab's dock. */
+ dismissed: string[];
+ /** Build the cut and hand it to the engine; the dock tracks it from there. */
+ start: (
+ projectId: string,
+ doc: ExportDoc,
+ settings: ExportSettings,
+ projectName?: string
+ ) => Promise<void>;
+ cancel: (id: string) => void;
+ dismiss: (id: string) => void;
+ /** One poll of the engine feed. */
+ refresh: () => Promise<void>;
}
-export const useExport = create<ExportState>((set, get) => ({
- status: "idle",
- stage: "",
- ratio: 0,
- startedAt: null,
- projectId: null,
- handle: null,
+export const useExports = create<ExportsState>((set, get) => ({
+ jobs: [],
+ local: [],
+ dismissed: [],
- start: (projectId, doc, settings) => {
- get().handle?.cancel();
- set({
- status: "running",
- stage: "Preparing",
- ratio: 0,
- startedAt: Date.now(),
- error: undefined,
- outName: undefined,
- projectId,
- });
- const handle = startExport(projectId, doc, settings, (stage, ratio) => set({ stage, ratio }));
- set({ handle });
- handle.done
- .then(({ outName }) => set({ status: "done", outName, ratio: 1, handle: null }))
- .catch((err: unknown) =>
- set({
- status: "error",
- error: err instanceof Error ? err.message : String(err),
- handle: null,
- })
- );
+ start: async (projectId, doc, settings, projectName) => {
+ const localId = `local-${crypto.randomUUID().slice(0, 8)}`;
+ set((s) => ({
+ local: [
+ ...s.local,
+ { id: localId, projectId, projectName, status: "preparing", createdAt: Date.now() },
+ ],
+ }));
+ try {
+ const jobId = await createExportJob(projectId, doc, settings);
+ ownDownloads.add(jobId);
+ set((s) => ({ local: s.local.filter((r) => r.id !== localId) }));
+ void get().refresh(); // show the queued job now, not on the next tick
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ set((s) => ({
+ local: s.local.map((r) =>
+ r.id === localId ? { ...r, status: "error", error: msg } : r
+ ),
+ }));
+ }
},
- cancel: () => {
- get().handle?.cancel();
- set({ status: "idle", handle: null, ratio: 0, stage: "" });
+ cancel: (id) => {
+ cancelExportJob(id);
+ ownDownloads.delete(id);
+ set((s) => ({
+ jobs: s.jobs.map((j) =>
+ j.id === id ? { ...j, status: "error", error: "Export canceled." } : j
+ ),
+ }));
+ void get().refresh();
},
- dismiss: () =>
- set({ status: "idle", ratio: 0, stage: "", error: undefined, outName: undefined }),
+ dismiss: (id) =>
+ set((s) => ({
+ local: s.local.filter((r) => r.id !== id),
+ dismissed: s.jobs.some((j) => j.id === id)
+ ? [...new Set([...s.dismissed, id])]
+ : s.dismissed,
+ })),
- reconnect: async (projectId) => {
- if (get().status === "running") return;
- const list = (await apiFetch(`/api/cut/projects/${projectId}/export-jobs`)
- .then((r) => (r.ok ? r.json() : []))
- .catch(() => [])) as { id: string; status: string; progress: number; outName?: string }[];
- const running = list.find((j) => j.status === "running");
- if (!running) return;
- // The true start predates the rejoin; counting from here still shows time
- // moving, which is the point of the clock.
- set({
- status: "running",
- stage: "Rendering",
- ratio: running.progress,
- startedAt: Date.now(),
- projectId,
- });
- pollExport(running.id, (stage, ratio) => set({ stage, ratio }))
- .then((outName) => {
- downloadExport(running.id, outName);
- set({ status: "done", outName, ratio: 1 });
- })
- .catch((err: unknown) =>
- set({ status: "error", error: err instanceof Error ? err.message : String(err) })
- );
+ refresh: async () => {
+ let list: ExportJob[];
+ try {
+ const res = await apiFetch("/api/cut/export-jobs");
+ if (!res.ok) return; // engine hiccup — keep the last good view
+ list = (await res.json()) as ExportJob[];
+ } catch {
+ return;
+ }
+ for (const j of list) {
+ const settled = j.status === "done" || j.status === "error";
+ if (j.status === "done" && j.outName && ownDownloads.has(j.id)) {
+ downloadExport(j.id, j.outName);
+ }
+ if (settled) ownDownloads.delete(j.id);
+ }
+ set((s) => ({
+ jobs: list,
+ dismissed: s.dismissed.filter((id) => list.some((j) => j.id === id)),
+ }));
},
}));
+
+// The dock is mounted app-wide, so polling runs the whole time the Cut app is
+// open. It quickens while work is in flight and idles between exports.
+let pollTimer: ReturnType<typeof setTimeout> | null = null;
+let mounts = 0;
+
+export function beginExportPolling() {
+ mounts++;
+ if (pollTimer !== null) return;
+ const tick = async () => {
+ await useExports.getState().refresh();
+ if (mounts === 0) {
+ pollTimer = null;
+ return;
+ }
+ const s = useExports.getState();
+ const active =
+ s.local.length > 0 ||
+ s.jobs.some((j) => j.status === "queued" || j.status === "running");
+ pollTimer = setTimeout(tick, active ? 700 : 3000);
+ };
+ pollTimer = setTimeout(tick, 0);
+}
+
+export function endExportPolling() {
+ mounts = Math.max(0, mounts - 1);
+ if (mounts === 0 && pollTimer !== null) {
+ clearTimeout(pollTimer);
+ pollTimer = null;
+ }
+}