Skip to content

Open source CapCut alternative.

TypeScript

feat(cut): cloud mode — backend seam, cloud projects, exports, LLM transcription [rebuild]

David Le36f0676c41d5
diff --git a/site/src/app/cut/app/p/[id]/page.tsx b/site/src/app/cut/app/p/[id]/page.tsx
index dae5751a..80c637eb 100644
--- a/site/src/app/cut/app/p/[id]/page.tsx
+++ b/site/src/app/cut/app/p/[id]/page.tsx
@@ -7,11 +7,18 @@ import { Editor } from "@/cut/components/Editor";
// Client-only: the id comes from the URL in the browser, so the hosted shell
// carries no server-rendered data. `from` and `folder` record which tab (and
// folder within it) opened the project so the editor's back button returns
-// there.
+// there; `src` is the project's residency (cloud when set).
function ProjectEditor() {
const { id } = useParams<{ id: string }>();
const params = useSearchParams();
- return <Editor projectId={id} from={params.get("from")} folder={params.get("folder")} />;
+ return (
+ <Editor
+ projectId={id}
+ from={params.get("from")}
+ folder={params.get("folder")}
+ src={params.get("src")}
+ />
+ );
}
export default function ProjectPage() {
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsx
index dd770932..44c0209f 100644
--- a/site/src/cut/components/AiPanel.tsx
+++ b/site/src/cut/components/AiPanel.tsx
@@ -40,7 +40,9 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import { apiFetch, apiUrl, engineReady } from "@/cut/lib/api";
+import { engineReady } from "@/cut/lib/api";
+import { apiFetch, apiUrl } from "@/cut/lib/backend";
+import { useCutCaps } from "@/cut/lib/backend/hooks";
import { buildAiContext } from "@/cut/lib/aiContext";
import { runAiTool } from "@/cut/lib/aiTools";
import { setAssetDragData } from "@/cut/lib/assetDrag";
@@ -424,6 +426,7 @@ function ChatSession({
}) {
const [input, setInput] = useState("");
const composerRef = useRef<HTMLTextAreaElement>(null);
+ const caps = useCutCaps();
// Live dictation → drops the finished transcript into the composer, appended
// after whatever the user had already typed.
const mic = useMicTranscription((text) =>
@@ -862,17 +865,19 @@ function ChatSession({
onSelect={onModelChange}
/>
<div className="flex-1" />
- <Button
- type="button"
- variant="ghost"
- size="sm"
- className="ai-mic text-muted-foreground"
- title="Dictate"
- disabled={busy}
- onClick={() => void mic.start()}
- >
- <Mic className="size-3.5" />
- </Button>
+ {caps.liveMic && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="ai-mic text-muted-foreground"
+ title="Dictate"
+ disabled={busy}
+ onClick={() => void mic.start()}
+ >
+ <Mic className="size-3.5" />
+ </Button>
+ )}
{busy ? (
<Button
variant="outline"
diff --git a/site/src/cut/components/AppSidebar.tsx b/site/src/cut/components/AppSidebar.tsx
index 63293067..55f4e81d 100644
--- a/site/src/cut/components/AppSidebar.tsx
+++ b/site/src/cut/components/AppSidebar.tsx
@@ -13,7 +13,7 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
-import { apiFetch } from "@/cut/lib/api";
+import { apiFetch, cutMode } from "@/cut/lib/backend";
import { track } from "@/lib/analytics";
import { NavUser } from "@/cut/components/NavUser";
import { homeHref, projectHref, tabForPath, useCutBase, type CutTab } from "@/cut/lib/nav";
@@ -43,7 +43,9 @@ export function AppSidebar() {
});
const project = (await res.json()) as ProjectSummary;
track("project_created", { source: "sidebar" });
- router.push(projectHref(base, project.id, tabForPath(pathname)));
+ // The sidebar creates on the globally bound backend, so the link carries
+ // that residency.
+ router.push(projectHref(base, project.id, tabForPath(pathname), null, cutMode()));
} finally {
setBusy(false);
}
diff --git a/site/src/cut/components/ConnectGate.tsx b/site/src/cut/components/ConnectGate.tsx
index 18c2053d..c44a651d 100644
--- a/site/src/cut/components/ConnectGate.tsx
+++ b/site/src/cut/components/ConnectGate.tsx
@@ -14,6 +14,8 @@ import {
engineProbe,
servedFromEngine,
} from "@/cut/lib/api";
+import { cutMode, setCutMode } from "@/cut/lib/backend";
+import { useWebMode, webModeEnabled } from "@/cut/lib/flags";
// Chrome gates a public https page's first fetch to 127.0.0.1 behind its
// Local Network Access prompt — "donkeycut.com wants to access other apps and
@@ -70,36 +72,69 @@ export function ConnectGate({ children }: { children: ReactNode }) {
const [needsAsk, setNeedsAsk] = useState(false);
const pass = useCallback(() => {
+ setCutMode("local");
engineGateOpen();
setGate("pass");
}, []);
+ // Web mode (the cut-web-mode flag): the app runs against the cloud backend,
+ // so a missing engine never walls the page — the gate still prefers the
+ // engine when it can probe without raising the browser ask, and otherwise
+ // passes straight through in cloud mode. The engine gate latch stays closed
+ // there; nothing in cloud mode touches loopback.
+ const passCloud = useCallback(() => {
+ setCutMode("cloud");
+ setGate("pass");
+ }, []);
+
const check = useCallback(async () => {
const forced = forcedGate();
if (forced) {
setNeedsAsk(forced === "ask" || forced === "connecting");
return setGate(forced === "ask" ? "install" : (forced as Gate));
}
+ const web = webModeEnabled();
const perm = await permissionState();
- if (perm === "denied") return setGate("blocked");
+ if (perm === "denied") {
+ if (web) passCloud();
+ else setGate("blocked");
+ return;
+ }
const quiet =
servedFromEngine() ||
perm === "granted" ||
(perm === null && localStorage.getItem(ACK_KEY) === "1");
setNeedsAsk(!quiet);
- if (!quiet) return setGate("install");
+ if (!quiet) {
+ if (web) passCloud();
+ else setGate("install");
+ return;
+ }
try {
await engineProbe();
pass();
} catch {
- setGate("install");
+ if (web) passCloud();
+ else setGate("install");
}
- }, [pass]);
+ }, [pass, passCloud]);
useEffect(() => {
void check();
}, [check]);
+ // The flag flips on the fly from the account menu: turning it on releases a
+ // gated page into cloud mode via a fresh check; turning it off while running
+ // on the cloud backend puts the gate back up on the local flow.
+ const webMode = useWebMode();
+ useEffect(() => {
+ const flip = webMode ? gate === "install" || gate === "blocked" : cutMode() === "cloud";
+ if (!flip) return;
+ if (!webMode) setCutMode("local");
+ const t = setTimeout(() => void check(), 0);
+ return () => clearTimeout(t);
+ }, [webMode, gate, check]);
+
// While waiting with a prompt-free path to loopback, keep probing so the
// page connects the moment the app starts.
useEffect(() => {
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index 71b54651..0cafedcc 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -2,9 +2,9 @@
import { useCallback, useEffect, useRef, useState } from "react";
import Link from "next/link";
-import { Clapperboard, Loader2 } from "lucide-react";
+import { Clapperboard, Loader2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
-import { apiFetch } from "@/cut/lib/api";
+import { apiFetch, setCutMode } from "@/cut/lib/backend";
import { renderPreviewProxy } from "@/cut/lib/exportClient";
import { fileZoneAt, hasRefDrag } from "@/cut/lib/assetRef";
import { enrichAsset, importFileToProject } from "@/cut/lib/media";
@@ -28,10 +28,12 @@ export function Editor({
projectId,
from,
folder,
+ src,
}: {
projectId: string;
from?: string | null;
folder?: string | null;
+ src?: string | null;
}) {
useEffect(() => installDevHooks(), []);
const back = backTarget(useCutBase(), from, folder);
@@ -48,10 +50,14 @@ export function Editor({
// panel, so collapse it and let the preview take the space.
const hasInspector = useEditor((s) => s.selection != null && s.selection.kind !== "cue");
const [importing, setImporting] = useState(0);
+ const [conflictReloaded, setConflictReloaded] = useState(false);
const dragDepth = useRef(0);
// Load the project document, then enrich assets (thumbs/waveforms) lazily.
+ // The link's ?src=cloud names a cloud-resident project; bind the backend
+ // before anything in the editor fetches.
useEffect(() => {
+ setCutMode(src === "cloud" ? "cloud" : "local");
void useEditor
.getState()
.loadProject(projectId)
@@ -61,6 +67,25 @@ export function Editor({
// 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, src]);
+
+ // A cloud save hit a newer stored version (another session's edits won).
+ // Take the newer doc through the ordinary load path — the GET returns it and
+ // rebinds the driver's version — and say so.
+ useEffect(() => {
+ const onConflict = (e: Event) => {
+ const detail = (e as CustomEvent<{ projectId: string }>).detail;
+ if (!detail || detail.projectId !== projectId) return;
+ void useEditor
+ .getState()
+ .loadProject(projectId)
+ .then(() => {
+ for (const asset of useEditor.getState().assets) void enrichAsset(asset);
+ });
+ setConflictReloaded(true);
+ };
+ window.addEventListener("cut-cloud-doc-conflict", onConflict);
+ return () => window.removeEventListener("cut-cloud-doc-conflict", onConflict);
}, [projectId]);
// Keep the project card's hover proxy fresh: rebuild it a few seconds after
@@ -434,6 +459,20 @@ export function Editor({
/>
)}
{exportOpen && <ExportDialog />}
+ {conflictReloaded && (
+ <div className="fixed top-14 left-1/2 z-50 flex -translate-x-1/2 items-center gap-1.5 rounded-full bg-foreground/90 py-1.5 pr-1.5 pl-3.5 text-background shadow-lg">
+ <span className="text-xs font-medium">Reloaded a newer version saved elsewhere.</span>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Dismiss"
+ className="rounded-full text-background hover:bg-background/15 hover:text-background"
+ onClick={() => setConflictReloaded(false)}
+ >
+ <X />
+ </Button>
+ </div>
+ )}
<Lightbox />
</div>
);
diff --git a/site/src/cut/components/ExportsDock.tsx b/site/src/cut/components/ExportsDock.tsx
index e345f534..987671d6 100644
--- a/site/src/cut/components/ExportsDock.tsx
+++ b/site/src/cut/components/ExportsDock.tsx
@@ -14,10 +14,12 @@ import {
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { useElapsed } from "@/cut/hooks/useElapsed";
+import type { CutMode } from "@/cut/lib/backend";
import { downloadExport, revealExport } from "@/cut/lib/exportClient";
import {
beginExportPolling,
endExportPolling,
+ exportBackend,
useExports,
type ExportJob,
type LocalRow,
@@ -127,11 +129,19 @@ function StatusIcon({ status }: { status: string }) {
return <CircleAlert className="size-4 shrink-0 text-destructive" />;
}
-function ProjectName({ projectId, name }: { projectId: string; name?: string }) {
+function ProjectName({
+ projectId,
+ name,
+ residency,
+}: {
+ projectId: string;
+ name?: string;
+ residency: CutMode;
+}) {
const base = useCutBase();
return (
<Link
- href={projectHref(base, projectId, "projects")}
+ href={projectHref(base, projectId, "projects", undefined, residency)}
className="block truncate text-xs font-medium hover:underline"
title={name || "Untitled"}
>
@@ -141,6 +151,10 @@ function ProjectName({ projectId, name }: { projectId: string; name?: string })
}
function ExportRow({ job }: { job: ExportJob }) {
+ // The job's own backend, not the globally bound one: the row must keep
+ // working after the app rebinds to the other residency.
+ const backend = exportBackend(job.residency);
+ const caps = backend.caps;
const elapsed = useElapsed(job.status === "running" ? job.startedAt ?? null : null);
const pct = Math.round(job.progress * 100);
@@ -157,7 +171,7 @@ function ExportRow({ job }: { job: ExportJob }) {
<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} />
+ <ProjectName projectId={job.projectId} name={job.projectName} residency={job.residency} />
<div
className={cn(
"truncate text-[11px] tabular-nums",
@@ -182,21 +196,25 @@ function ExportRow({ job }: { job: ExportJob }) {
<>
{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>
+ {caps.revealInFinder && (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Show in Finder"
+ title="Show in Finder"
+ onClick={() =>
+ void revealExport(job.projectId, job.outName!, backend).catch(() => {})
+ }
+ >
+ <FolderOpen />
+ </Button>
+ )}
<Button
variant="ghost"
size="icon-xs"
aria-label="Download again"
title="Download"
- onClick={() => downloadExport(job.id, job.outName!)}
+ onClick={() => downloadExport(job.id, job.outName!, backend)}
>
<Download />
</Button>
@@ -240,7 +258,7 @@ function LocalRowView({ row }: { row: LocalRow }) {
<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} />
+ <ProjectName projectId={row.projectId} name={row.projectName} residency={row.residency} />
<div
className={cn(
"truncate text-[11px]",
diff --git a/site/src/cut/components/MicDictation.tsx b/site/src/cut/components/MicDictation.tsx
index bf66f2d9..d5a0cc84 100644
--- a/site/src/cut/components/MicDictation.tsx
+++ b/site/src/cut/components/MicDictation.tsx
@@ -3,6 +3,7 @@
import { useEffect } from "react";
import { Check, Mic, X } from "lucide-react";
import { cn } from "@/lib/utils";
+import { useCutCaps } from "@/cut/lib/backend/hooks";
import { useMicTranscription, type MicController } from "@/cut/lib/micTranscribe";
import { LiveWaveform } from "./RecordDialog";
@@ -107,7 +108,9 @@ export function DictationControl({
buttonClassName?: string;
disabled?: boolean;
}) {
+ const caps = useCutCaps();
const mic = useMicTranscription((t) => onResult(appendTranscript(text, t)));
+ if (!caps.liveMic) return null;
return (
<>
{mic.state !== "idle" && (
diff --git a/site/src/cut/components/PlatformPreview.tsx b/site/src/cut/components/PlatformPreview.tsx
index 4df33f59..54de61b7 100644
--- a/site/src/cut/components/PlatformPreview.tsx
+++ b/site/src/cut/components/PlatformPreview.tsx
@@ -1,7 +1,7 @@
"use client";
import { useEffect, useRef, useState } from "react";
-import { apiUrl } from "@/cut/lib/api";
+import { apiUrl } from "@/cut/lib/backend";
import {
Bookmark,
Camera,
diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsx
index f064ec84..b12092ca 100644
--- a/site/src/cut/components/ProjectsHome.tsx
+++ b/site/src/cut/components/ProjectsHome.tsx
@@ -4,10 +4,12 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import {
Check,
+ Cloud,
Copy,
Film,
Folder,
FolderPlus,
+ Laptop,
LayoutGrid,
List,
Loader2,
@@ -43,20 +45,44 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
-import { apiFetch, apiUrl, engineLost } from "@/cut/lib/api";
+import { engineLost, engineOrigin, servedFromEngine } from "@/cut/lib/api";
+import { cloudBackend } from "@/cut/lib/backend/cloud";
+import { useCutMode } from "@/cut/lib/backend/hooks";
+import { localBackend } from "@/cut/lib/backend/local";
+import type { CutBackend, CutMode } from "@/cut/lib/backend/types";
+import { useWebMode, webModeEnabled } from "@/cut/lib/flags";
import { track } from "@/lib/analytics";
+import { authClient } from "@/lib/auth-client";
import { clearProjectThreads } from "@/cut/lib/chatThreads";
import { useGenerate } from "@/cut/lib/generate";
import { useGenScene } from "@/cut/lib/genScene";
-import { createProjectFromFile, isMediaFile } from "@/cut/lib/media";
+import { createProjectFromFile, isMediaFile, uploadProjectMediaTo } from "@/cut/lib/media";
import { homeHref, projectHref, useCutBase } from "@/cut/lib/nav";
import { formatTime } from "@/cut/lib/time";
-import { mediaUrl, type ProjectFolder, type ProjectSummary } from "@/cut/lib/types";
+import type { ProjectDoc, ProjectFolder, ProjectSummary } from "@/cut/lib/types";
import { cn } from "@/lib/utils";
import { buildDragGhost, FolderCrumb, FolderShelf, formatBytes, Marquee } from "./desktopFolders";
type View = "gallery" | "list";
+// Where a project lives: the engine on this Mac or the hosted cloud backend.
+// The home lists each residency it can reach as its own section, talking to
+// the backend objects directly — the global mode is only bound when a project
+// opens into the editor.
+type Residency = CutMode;
+
+const backendFor = (r: Residency): CutBackend => (r === "cloud" ? cloudBackend : localBackend);
+
+const RESIDENCY_LABEL: Record<Residency, string> = { local: "On this Mac", cloud: "Cloud" };
+
+type SectionData = {
+ projects: ProjectSummary[] | null;
+ folders: ProjectFolder[];
+ error: boolean;
+};
+
+const EMPTY_SECTION: SectionData = { projects: null, folders: [], error: false };
+
// A dragged selection is carried as a JSON array of project ids, so one drag can
// move a whole marquee-selected collection into a folder.
const PROJECT_MIME = "application/x-cut-project";
@@ -75,22 +101,52 @@ function formatDate(ts: number) {
});
}
+function ResidencyBadge({ residency, className }: { residency: Residency; className?: string }) {
+ const Icon = residency === "cloud" ? Cloud : Laptop;
+ return (
+ <span title={RESIDENCY_LABEL[residency]} className={className}>
+ <Icon className="size-3" />
+ </span>
+ );
+}
+
export function ProjectsHome() {
const router = useRouter();
const base = useCutBase();
- const [projects, setProjects] = useState<ProjectSummary[] | null>(null);
- const [folders, setFolders] = useState<ProjectFolder[]>([]);
+ const mode = useCutMode();
+ const webMode = useWebMode();
+ const { data: session } = authClient.useSession();
+ // Which backends this home lists. Engine presence is what the ConnectGate
+ // already resolved for this tab (same-origin page, or a memoized loopback
+ // origin) — never a fresh probe, which could raise the browser's
+ // local-network prompt.
+ const engineUp = servedFromEngine() || engineOrigin() !== "";
+ const residencies: Residency[] =
+ !webMode || !session ? ["local"] : engineUp ? ["local", "cloud"] : ["cloud"];
+ const dual = residencies.length > 1;
+ const r0 = residencies[0];
+
+ const [data, setData] = useState<Record<Residency, SectionData>>({
+ local: EMPTY_SECTION,
+ cloud: EMPTY_SECTION,
+ });
// The open folder lives in the URL (?folder=…) so project URLs can point
// back into it and the browser's back button steps folder → root.
const openFolder = useSearchParams().get("folder");
const [selected, setSelected] = useState<Set<string>>(new Set());
const [view, setView] = useState<View>("gallery");
const [createOpen, setCreateOpen] = useState(false);
- const [folderCreating, setFolderCreating] = useState(false);
- const [renaming, setRenaming] = useState<ProjectSummary | null>(null);
- const [deleting, setDeleting] = useState<ProjectSummary | null>(null);
+ const [folderCreating, setFolderCreating] = useState<Residency | null>(null);
+ const [renaming, setRenaming] = useState<{ project: ProjectSummary; residency: Residency } | null>(
+ null
+ );
+ const [deleting, setDeleting] = useState<{ project: ProjectSummary; residency: Residency } | null>(
+ null
+ );
const [name, setName] = useState("");
const [busy, setBusy] = useState(false);
+ // One line of feedback when a cross-residency duplicate fails.
+ const [dupError, setDupError] = useState<string | null>(null);
// A count of desktop files still uploading into fresh projects, plus whether an
// OS-file drag is hovering the surface (a depth counter tames enter/leave noise
// as the cursor crosses child tiles).
@@ -108,42 +164,74 @@ export function ProjectsHome() {
localStorage.setItem("cut-projects-view", v);
};
- const refresh = useCallback(async () => {
+ const refresh = useCallback(async (r: Residency) => {
+ const backend = backendFor(r);
try {
const [res, fres] = await Promise.all([
- apiFetch("/api/cut/projects"),
- apiFetch("/api/cut/projects/folders"),
+ backend.fetch("/api/cut/projects"),
+ backend.fetch("/api/cut/projects/folders"),
]);
if (!res.ok) throw new Error(String(res.status));
- setProjects((await res.json()) as ProjectSummary[]);
- setFolders(fres.ok ? ((await fres.json()) as ProjectFolder[]) : []);
+ const projects = (await res.json()) as ProjectSummary[];
+ const folders = fres.ok ? ((await fres.json()) as ProjectFolder[]) : [];
+ setData((prev) => ({ ...prev, [r]: { projects, folders, error: false } }));
} catch {
- // The engine on this Mac stopped answering; the ConnectGate takes the
- // screen back over until it returns.
- engineLost();
+ if (r === "local" && !webModeEnabled()) {
+ // The engine on this Mac stopped answering; the ConnectGate takes the
+ // screen back over until it returns.
+ engineLost();
+ return;
+ }
+ // One backend failing never takes down the other's section.
+ setData((prev) => ({ ...prev, [r]: { ...prev[r], error: true } }));
}
}, []);
- const createFolder = async (fname: string) => {
- const res = await apiFetch("/api/cut/projects/folders", {
+ const residencyKey = residencies.join(",");
+ useEffect(() => {
+ for (const r of residencyKey.split(",") as Residency[]) void refresh(r);
+ }, [residencyKey, refresh]);
+
+ // A section stuck on "Couldn't load these projects" heals itself: while any
+ // section is errored, retry its refresh every few seconds. A successful
+ // refresh clears the error, which changes the key and drops the interval.
+ const erroredKey = residencies.filter((r) => data[r].error).join(",");
+ useEffect(() => {
+ if (!erroredKey) return;
+ const id = setInterval(() => {
+ for (const r of erroredKey.split(",") as Residency[]) void refresh(r);
+ }, 3000);
+ return () => clearInterval(id);
+ }, [erroredKey, refresh]);
+
+ const createFolder = async (r: Residency, fname: string) => {
+ const res = await backendFor(r).fetch("/api/cut/projects/folders", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: fname }),
});
if (res.ok) {
const f = (await res.json()) as ProjectFolder;
- setFolders((prev) => [...prev, f]);
+ setData((prev) => ({ ...prev, [r]: { ...prev[r], folders: [...prev[r].folders, f] } }));
track("folder_created");
}
};
- const renameFolder = async (id: string, fname: string) => {
- setFolders((prev) => prev.map((f) => (f.id === id ? { ...f, name: fname } : f)));
- await apiFetch(`/api/cut/projects/folders/${id}`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name: fname }),
- }).catch(() => void refresh());
+ const renameFolder = async (r: Residency, id: string, fname: string) => {
+ setData((prev) => ({
+ ...prev,
+ [r]: {
+ ...prev[r],
+ folders: prev[r].folders.map((f) => (f.id === id ? { ...f, name: fname } : f)),
+ },
+ }));
+ await backendFor(r)
+ .fetch(`/api/cut/projects/folders/${id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ name: fname }),
+ })
+ .catch(() => void refresh(r));
};
// Open a folder (or the root, id null) by navigating, so the location is
@@ -153,49 +241,63 @@ export function ProjectsHome() {
router.push(homeHref(base, "projects", id));
};
- const deleteFolder = async (id: string) => {
- setFolders((prev) => prev.filter((f) => f.id !== id));
- setProjects((prev) => (prev ?? []).map((p) => (p.folderId === id ? { ...p, folderId: null } : p)));
+ const deleteFolder = async (r: Residency, id: string) => {
+ setData((prev) => ({
+ ...prev,
+ [r]: {
+ ...prev[r],
+ folders: prev[r].folders.filter((f) => f.id !== id),
+ projects: (prev[r].projects ?? []).map((p) =>
+ p.folderId === id ? { ...p, folderId: null } : p
+ ),
+ },
+ }));
if (openFolder === id) router.replace(homeHref(base, "projects"));
- await apiFetch(`/api/cut/projects/folders/${id}`, { method: "DELETE" }).catch(() => void refresh());
+ await backendFor(r)
+ .fetch(`/api/cut/projects/folders/${id}`, { method: "DELETE" })
+ .catch(() => void refresh(r));
};
// Move a collection of projects into a folder (or out to the root, folderId
- // null). Optimistic; reconciles from disk on any failure.
- const moveProjects = useCallback(
- async (ids: string[], folderId: string | null) => {
- if (ids.length === 0) return;
- const idset = new Set(ids);
- setProjects((prev) => (prev ?? []).map((p) => (idset.has(p.id) ? { ...p, folderId } : p)));
- setSelected(new Set());
- await Promise.all(
- ids.map((id) =>
- apiFetch(`/api/cut/projects/${id}/move`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ folderId }),
- })
- )
- ).catch(() => void refresh());
- },
- [refresh]
- );
-
- useEffect(() => {
- void refresh();
- }, [refresh]);
+ // null). Optimistic; reconciles from disk on any failure. A dragged
+ // selection can span sections, so a backend only ever moves its own.
+ const moveProjects = async (r: Residency, ids: string[], folderId: string | null) => {
+ const own = new Set((data[r].projects ?? []).map((p) => p.id));
+ const move = ids.filter((id) => own.has(id));
+ if (move.length === 0) return;
+ const idset = new Set(move);
+ setData((prev) => ({
+ ...prev,
+ [r]: {
+ ...prev[r],
+ projects: (prev[r].projects ?? []).map((p) =>
+ idset.has(p.id) ? { ...p, folderId } : p
+ ),
+ },
+ }));
+ setSelected(new Set());
+ await Promise.all(
+ move.map((id) =>
+ backendFor(r).fetch(`/api/cut/projects/${id}/move`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ folderId }),
+ })
+ )
+ ).catch(() => void refresh(r));
+ };
const create = async () => {
setBusy(true);
try {
- const res = await apiFetch("/api/cut/projects", {
+ const res = await backendFor(r0).fetch("/api/cut/projects", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: name.trim() || "Untitled", folderId: openFolder }),
});
const project = (await res.json()) as ProjectSummary;
track("project_created", { source: "projects_home" });
- router.push(projectHref(base, project.id, "projects", openFolder));
+ router.push(projectHref(base, project.id, "projects", openFolder, r0));
} finally {
setBusy(false);
}
@@ -203,19 +305,21 @@ export function ProjectsHome() {
// Make a new project in the folder that's open (root when none), then jump
// straight into it — no naming step.
- const newProjectHere = async (folderId: string | null = openFolder) => {
- const res = await apiFetch("/api/cut/projects", {
+ const newProjectHere = async (r: Residency, folderId: string | null = openFolder) => {
+ const res = await backendFor(r).fetch("/api/cut/projects", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Untitled", folderId }),
});
const project = (await res.json()) as ProjectSummary;
track("project_created", { source: "projects_home" });
- router.push(projectHref(base, project.id, "projects", folderId));
+ router.push(projectHref(base, project.id, "projects", folderId, r));
};
// Turn a batch of desktop files into projects filed under `folderId`. Each
// becomes its own project and pops into the grid the moment it's ready.
+ // File imports run on the globally bound backend, so they land in `mode`'s
+ // section.
const importFilesAsProjects = useCallback(
async (files: FileList | File[], folderId: string | null) => {
const media = Array.from(files).filter(isMediaFile);
@@ -230,33 +334,95 @@ export function ProjectsHome() {
} finally {
setImporting((n) => n - 1);
}
- await refresh();
+ await refresh(mode);
}
},
- [refresh]
+ [refresh, mode]
);
const rename = async () => {
if (!renaming) return;
setBusy(true);
try {
- await apiFetch(`/api/cut/projects/${renaming.id}`, {
+ await backendFor(renaming.residency).fetch(`/api/cut/projects/${renaming.project.id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name: name.trim() || renaming.name }),
+ body: JSON.stringify({ name: name.trim() || renaming.project.name }),
});
setRenaming(null);
- await refresh();
+ await refresh(renaming.residency);
} finally {
setBusy(false);
}
};
- const duplicate = async (p: ProjectSummary) => {
+ const duplicate = async (r: Residency, p: ProjectSummary) => {
setBusy(true);
try {
- await apiFetch(`/api/cut/projects/${p.id}/duplicate`, { method: "POST" });
- await refresh();
+ await backendFor(r).fetch(`/api/cut/projects/${p.id}/duplicate`, { method: "POST" });
+ await refresh(r);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ // Copy a project into the other residency: read the source doc, create the
+ // target project, move every media file's bytes across (in doc order — the
+ // fresh target dedupes only against names this copy already claimed), remap
+ // asset fileNames, then save the doc. A failure deletes the half-made copy.
+ const duplicateAcross = async (source: Residency, p: ProjectSummary) => {
+ const target: Residency = source === "cloud" ? "local" : "cloud";
+ const src = backendFor(source);
+ const dst = backendFor(target);
+ setDupError(null);
+ setBusy(true);
+ let created: string | null = null;
+ try {
+ const docRes = await src.fetch(`/api/cut/projects/${p.id}`);
+ if (!docRes.ok) throw new Error("Could not read the project.");
+ const doc = (await docRes.json()) as ProjectDoc;
+ const copyName = `${doc.name || p.name} copy`;
+ const createRes = await dst.fetch("/api/cut/projects", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ name: copyName }),
+ });
+ const summary = (await createRes.json()) as ProjectSummary;
+ if (!createRes.ok || !summary.id) throw new Error("Could not create the copy.");
+ created = summary.id;
+ const assets = Array.isArray(doc.assets) ? doc.assets : [];
+ const names = new Map<string, string>();
+ for (const a of assets) {
+ if (names.has(a.fileName)) continue;
+ const bytes = await src.fetch(
+ `/api/cut/projects/${p.id}/media/${encodeURIComponent(a.fileName)}`
+ );
+ if (!bytes.ok) throw new Error(`Could not read “${a.name}”.`);
+ names.set(
+ a.fileName,
+ await uploadProjectMediaTo(dst, summary.id, await bytes.blob(), a.fileName)
+ );
+ }
+ const copied: ProjectDoc = {
+ ...doc,
+ name: copyName,
+ folderId: null,
+ assets: assets.map((a) => ({ ...a, fileName: names.get(a.fileName) ?? a.fileName })),
+ };
+ const putRes = await dst.fetch(`/api/cut/projects/${summary.id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(copied),
+ });
+ if (!putRes.ok) throw new Error("Could not save the copy.");
+ await refresh(target);
+ } catch (e) {
+ if (created) {
+ void dst.fetch(`/api/cut/projects/${created}`, { method: "DELETE" }).catch(() => {});
+ }
+ setDupError(
+ e instanceof Error && e.message ? e.message : "Could not duplicate the project."
+ );
} finally {
setBusy(false);
}
@@ -265,9 +431,10 @@ export function ProjectsHome() {
const remove = async () => {
if (!deleting) return;
setBusy(true);
- const id = deleting.id;
+ const { project, residency } = deleting;
+ const id = project.id;
try {
- await apiFetch(`/api/cut/projects/${id}`, { method: "DELETE" });
+ await backendFor(residency).fetch(`/api/cut/projects/${id}`, { method: "DELETE" });
// The doc, media, and exports go with the folder on the server. Purge the
// client-side residue keyed to this project so nothing survives it: a live
// scene run, its in-flight renders, and its chat history (whose ids the
@@ -276,16 +443,25 @@ export function ProjectsHome() {
useGenerate.getState().cancelForOwner({ projectId: id });
clearProjectThreads(id);
setDeleting(null);
- await refresh();
+ await refresh(residency);
} finally {
setBusy(false);
}
};
- const all = projects ?? [];
- const shown = all.filter((p) => (p.folderId ?? null) === openFolder);
- const openFolderName = folders.find((f) => f.id === openFolder)?.name;
- const hasContent = all.length > 0 || folders.length > 0;
+ // Which section owns the open folder — in dual mode only that section shows.
+ const folderOwner: Residency | null = openFolder
+ ? (residencies.find((r) => data[r].folders.some((f) => f.id === openFolder)) ?? null)
+ : null;
+ const openFolderName = folderOwner
+ ? data[folderOwner].folders.find((f) => f.id === openFolder)?.name
+ : undefined;
+
+ const anySettled = residencies.some((r) => data[r].projects !== null || data[r].error);
+ const anyProjects = residencies.some((r) => (data[r].projects?.length ?? 0) > 0);
+ const hasContent = residencies.some(
+ (r) => (data[r].projects?.length ?? 0) > 0 || data[r].folders.length > 0
+ );
// Begin a project drag. Dragging a member of the current selection carries the
// whole selection; dragging anything else drags (and selects) just that item.
@@ -312,6 +488,211 @@ export function ProjectsHome() {
// PROJECT_MIME and are handled by the folder tiles and breadcrumb instead.
const isFileDrag = (e: React.DragEvent) => Array.from(e.dataTransfer.types).includes("Files");
+ const renderShelf = (r: Residency) => (
+ <FolderShelf
+ folders={data[r].folders}
+ mime={PROJECT_MIME}
+ creating={folderCreating === r}
+ onCreatingChange={(c) => setFolderCreating(c ? r : null)}
+ statOf={(id) => {
+ const items = (data[r].projects ?? []).filter((p) => (p.folderId ?? null) === id);
+ return { count: items.length, size: items.reduce((n, p) => n + (p.sizeBytes ?? 0), 0) };
+ }}
+ onOpen={gotoFolder}
+ onCreate={(n) => void createFolder(r, n)}
+ onRename={(id, n) => void renameFolder(r, id, n)}
+ onDelete={(id) => void deleteFolder(r, id)}
+ onDropIds={(ids, fid) => void moveProjects(r, ids, fid)}
+ // File imports run on the globally bound backend, so only its section's
+ // folders take file drops.
+ onDropFiles={r === mode ? (files, fid) => void importFilesAsProjects(files, fid) : undefined}
+ />
+ );
+
+ const renderGallery = (r: Residency, shown: ProjectSummary[]) => (
+ <Marquee
+ className={cn(
+ "grid grid-cols-[repeat(auto-fill,minmax(190px,1fr))] content-start gap-5",
+ dual ? "min-h-[20vh]" : "min-h-[42vh]"
+ )}
+ selected={selected}
+ setSelected={setSelected}
+ >
+ {shown.map((p) => (
+ <div
+ key={p.id}
+ data-sel-id={p.id}
+ className="group cursor-pointer"
+ draggable
+ onDragStart={(e) => onProjectDragStart(e, p)}
+ onClick={(e) => {
+ if (e.shiftKey || e.metaKey) {
+ e.preventDefault();
+ toggleSelect(p.id);
+ return;
+ }
+ router.push(projectHref(base, p.id, "projects", openFolder, r));
+ }}
+ >
+ {/* Vertical 9:16 tile — the project is mobile video, show it that way. */}
+ <div
+ className={cn(
+ "relative grid aspect-[9/16] place-items-center overflow-hidden rounded-2xl border bg-muted transition-shadow group-hover:shadow-[0_6px_28px_rgba(0,0,0,0.12)]",
+ selected.has(p.id) ? "border-[#0a84ff] ring-2 ring-[#0a84ff]" : "border-border"
+ )}
+ >
+ <CardPreview project={p} residency={r} />
+ <span className="absolute top-2 left-2 max-w-[70%] truncate rounded-lg bg-black/55 px-2 py-1 text-[11px] font-medium text-white backdrop-blur-sm">
+ {p.name}
+ </span>
+ {dual && (
+ <ResidencyBadge
+ residency={r}
+ className="absolute bottom-2 left-2 grid size-5 place-items-center rounded-md bg-black/65 text-white"
+ />
+ )}
+ <span className="absolute right-2 bottom-2 rounded-md bg-black/65 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums">
+ {formatTime(p.duration)}
+ </span>
+ <ProjectMenu
+ project={p}
+ className="absolute top-1.5 right-1.5 opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100"
+ folders={data[r].folders}
+ onRename={() => {
+ setName(p.name);
+ setRenaming({ project: p, residency: r });
+ }}
+ onDuplicate={() => void duplicate(r, p)}
+ duplicateTo={
+ dual
+ ? {
+ target: r === "cloud" ? "local" : "cloud",
+ run: () => void duplicateAcross(r, p),
+ }
+ : undefined
+ }
+ onMove={(folderId) => void moveProjects(r, [p.id], folderId)}
+ onDelete={() => setDeleting({ project: p, residency: r })}
+ />
+ </div>
+ <div className="mt-2 px-0.5 text-xs text-muted-foreground">
+ {formatBytes(p.sizeBytes ?? 0)} · edited {formatDate(p.updatedAt)}
+ </div>
+ </div>
+ ))}
+ </Marquee>
+ );
+
+ const renderList = (r: Residency, shown: ProjectSummary[]) => (
+ <div className="overflow-hidden rounded-xl border border-border bg-card">
+ <div className="grid grid-cols-[1fr_90px_70px_110px_40px] items-center gap-3 border-b border-border bg-muted/50 px-4 py-2 text-xs font-medium tracking-wide text-muted-foreground uppercase">
+ <span>Name</span>
+ <span>Length</span>
+ <span>Size</span>
+ <span>Edited</span>
+ <span />
+ </div>
+ {shown.map((p) => (
+ <div
+ key={p.id}
+ data-sel-id={p.id}
+ className={cn(
+ "group grid cursor-pointer grid-cols-[1fr_90px_70px_110px_40px] items-center gap-3 border-b border-border px-4 py-2.5 text-sm last:border-b-0 hover:bg-muted/50",
+ selected.has(p.id) && "bg-[#0a84ff]/10 hover:bg-[#0a84ff]/15"
+ )}
+ draggable
+ onDragStart={(e) => onProjectDragStart(e, p)}
+ onClick={(e) => {
+ if (e.shiftKey || e.metaKey) {
+ e.preventDefault();
+ toggleSelect(p.id);
+ return;
+ }
+ router.push(projectHref(base, p.id, "projects", openFolder, r));
+ }}
+ >
+ <span className="flex min-w-0 items-center gap-2.5">
+ <Film className="size-4 shrink-0 text-muted-foreground" />
+ <span className="truncate font-medium">{p.name}</span>
+ {dual && (
+ <ResidencyBadge residency={r} className="shrink-0 text-muted-foreground" />
+ )}
+ </span>
+ <span className="font-mono text-xs text-muted-foreground tabular-nums">
+ {formatTime(p.duration)}
+ </span>
+ <span className="text-xs text-muted-foreground tabular-nums">
+ {formatBytes(p.sizeBytes ?? 0)}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {formatDate(p.updatedAt)}
+ </span>
+ <ProjectMenu
+ project={p}
+ folders={data[r].folders}
+ onRename={() => {
+ setName(p.name);
+ setRenaming({ project: p, residency: r });
+ }}
+ onDuplicate={() => void duplicate(r, p)}
+ duplicateTo={
+ dual
+ ? {
+ target: r === "cloud" ? "local" : "cloud",
+ run: () => void duplicateAcross(r, p),
+ }
+ : undefined
+ }
+ onMove={(folderId) => void moveProjects(r, [p.id], folderId)}
+ onDelete={() => setDeleting({ project: p, residency: r })}
+ />
+ </div>
+ ))}
+ <button
+ type="button"
+ data-no-marquee
+ onClick={() => void newProjectHere(r)}
+ className="flex w-full items-center gap-2.5 px-4 py-2.5 text-sm font-medium text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground"
+ >
+ <Plus className="size-4" /> New project
+ </button>
+ </div>
+ );
+
+ const renderSection = (r: Residency) => {
+ const d = data[r];
+ const shown = (d.projects ?? []).filter((p) => (p.folderId ?? null) === openFolder);
+ return (
+ <section key={r} className="mb-8">
+ <h2 className="mb-3 text-sm font-semibold text-muted-foreground">{RESIDENCY_LABEL[r]}</h2>
+ {d.error ? (
+ <p className="py-6 text-sm text-muted-foreground">Couldn&rsquo;t load these projects.</p>
+ ) : d.projects === null ? (
+ <div className="grid place-items-center py-10 text-muted-foreground">
+ <Loader2 className="size-5 animate-spin" />
+ </div>
+ ) : (
+ <>
+ {openFolder === null && (d.folders.length > 0 || folderCreating === r) && renderShelf(r)}
+ {view === "gallery" ? renderGallery(r, shown) : renderList(r, shown)}
+ </>
+ )}
+ </section>
+ );
+ };
+
+ // Single-residency derivations, matching the pre-dual home exactly.
+ const soleData = data[r0];
+ const showHeader = dual ? anySettled : soleData.projects !== null && hasContent;
+ const dualSections = openFolder === null ? residencies : folderOwner ? [folderOwner] : [];
+
+ // Whole-surface file drops import on the globally bound backend; a folder
+ // another backend owns can't receive them, so those land at the root.
+ const surfaceDropFolder =
+ dual && openFolder && !data[mode].folders.some((f) => f.id === openFolder)
+ ? null
+ : openFolder;
+
return (
<div
className={cn(
@@ -343,7 +724,7 @@ export function ProjectsHome() {
e.preventDefault();
dragDepth.current = 0;
setFileOver(false);
- void importFilesAsProjects(e.dataTransfer.files, openFolder);
+ void importFilesAsProjects(e.dataTransfer.files, surfaceDropFolder);
}}
>
<div className="relative mx-auto w-full max-w-6xl px-10 py-9">
@@ -355,7 +736,7 @@ export function ProjectsHome() {
</span>
</div>
)}
- {projects && hasContent && (
+ {showHeader && (
<div className="mb-5 flex items-center justify-between">
{openFolder === null ? (
<h1 className="text-lg font-semibold tracking-tight">Projects</h1>
@@ -365,19 +746,50 @@ export function ProjectsHome() {
name={openFolderName ?? "Folder"}
mime={PROJECT_MIME}
onBack={() => gotoFolder(null)}
- onDropOut={(ids) => void moveProjects(ids, null)}
+ onDropOut={(ids) => void moveProjects(folderOwner ?? r0, ids, null)}
/>
)}
<div className="flex items-center gap-2">
- {openFolder === null && (
- <Button variant="outline" onClick={() => setFolderCreating(true)}>
- <FolderPlus data-icon="inline-start" /> New folder
+ {openFolder === null &&
+ (dual ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger render={<Button variant="outline" />}>
+ <FolderPlus data-icon="inline-start" /> New folder
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setFolderCreating("local")}>
+ <Laptop /> {RESIDENCY_LABEL.local}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setFolderCreating("cloud")}>
+ <Cloud /> {RESIDENCY_LABEL.cloud}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : (
+ <Button variant="outline" onClick={() => setFolderCreating(r0)}>
+ <FolderPlus data-icon="inline-start" /> New folder
+ </Button>
+ ))}
+ {dual && openFolder === null ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger render={<Button />}>
+ <Plus data-icon="inline-start" /> New project
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => void newProjectHere("local")}>
+ <Laptop /> {RESIDENCY_LABEL.local}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => void newProjectHere("cloud")}>
+ <Cloud /> {RESIDENCY_LABEL.cloud}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : (
+ <Button onClick={() => void newProjectHere(dual ? (folderOwner ?? "local") : r0)}>
+ <Plus data-icon="inline-start" /> New project
</Button>
)}
- <Button onClick={() => void newProjectHere()}>
- <Plus data-icon="inline-start" /> New project
- </Button>
- {projects.length > 0 && (
+ {anyProjects && (
<div className="flex rounded-lg border border-border bg-card p-0.5">
<Button
variant="ghost"
@@ -405,166 +817,62 @@ export function ProjectsHome() {
</div>
)}
- {projects && openFolder === null && (folders.length > 0 || folderCreating) && (
- <FolderShelf
- folders={folders}
- mime={PROJECT_MIME}
- creating={folderCreating}
- onCreatingChange={setFolderCreating}
- statOf={(id) => {
- const items = all.filter((p) => (p.folderId ?? null) === id);
- return { count: items.length, size: items.reduce((n, p) => n + (p.sizeBytes ?? 0), 0) };
- }}
- onOpen={gotoFolder}
- onCreate={createFolder}
- onRename={renameFolder}
- onDelete={deleteFolder}
- onDropIds={(ids, fid) => void moveProjects(ids, fid)}
- onDropFiles={(files, fid) => void importFilesAsProjects(files, fid)}
- />
- )}
+ {dupError && <p className="mb-4 text-sm text-destructive">{dupError}</p>}
- {projects === null ? (
- <div className="grid place-items-center py-24 text-muted-foreground">
- <Loader2 className="size-5 animate-spin" />
- </div>
- ) : !hasContent ? (
- <div className="grid min-h-[60vh] place-items-center">
- <div className="flex flex-col items-center gap-4 text-center">
- <div className="grid size-14 place-items-center rounded-2xl bg-muted">
- <Film className="size-7 text-muted-foreground" />
- </div>
- <h1 className="text-lg font-semibold tracking-tight">
- Create a new project to get started
- </h1>
- <Button
- onClick={() => {
- setName("");
- setCreateOpen(true);
- }}
- >
- <Plus data-icon="inline-start" /> New project
- </Button>
+ {dual ? (
+ !anySettled ? (
+ <div className="grid place-items-center py-24 text-muted-foreground">
+ <Loader2 className="size-5 animate-spin" />
</div>
- </div>
- ) : view === "gallery" ? (
- <Marquee
- className="grid min-h-[42vh] grid-cols-[repeat(auto-fill,minmax(190px,1fr))] content-start gap-5"
- selected={selected}
- setSelected={setSelected}
- >
- {shown.map((p) => (
- <div
- key={p.id}
- data-sel-id={p.id}
- className="group cursor-pointer"
- draggable
- onDragStart={(e) => onProjectDragStart(e, p)}
- onClick={(e) => {
- if (e.shiftKey || e.metaKey) {
- e.preventDefault();
- toggleSelect(p.id);
- return;
- }
- router.push(projectHref(base, p.id, "projects", openFolder));
- }}
- >
- {/* Vertical 9:16 tile — the project is mobile video, show it that way. */}
- <div
- className={cn(
- "relative grid aspect-[9/16] place-items-center overflow-hidden rounded-2xl border bg-muted transition-shadow group-hover:shadow-[0_6px_28px_rgba(0,0,0,0.12)]",
- selected.has(p.id) ? "border-[#0a84ff] ring-2 ring-[#0a84ff]" : "border-border"
- )}
- >
- <CardPreview project={p} />
- <span className="absolute top-2 left-2 max-w-[70%] truncate rounded-lg bg-black/55 px-2 py-1 text-[11px] font-medium text-white backdrop-blur-sm">
- {p.name}
- </span>
- <span className="absolute right-2 bottom-2 rounded-md bg-black/65 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums">
- {formatTime(p.duration)}
- </span>
- <ProjectMenu
- project={p}
- className="absolute top-1.5 right-1.5 opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100"
- folders={folders}
- onRename={() => {
- setName(p.name);
- setRenaming(p);
+ ) : (
+ dualSections.map(renderSection)
+ )
+ ) : (
+ <>
+ {soleData.projects !== null &&
+ openFolder === null &&
+ (soleData.folders.length > 0 || folderCreating === r0) &&
+ renderShelf(r0)}
+
+ {soleData.error ? (
+ <p className="py-24 text-center text-sm text-muted-foreground">
+ Couldn&rsquo;t load these projects.
+ </p>
+ ) : soleData.projects === null ? (
+ <div className="grid place-items-center py-24 text-muted-foreground">
+ <Loader2 className="size-5 animate-spin" />
+ </div>
+ ) : !hasContent ? (
+ <div className="grid min-h-[60vh] place-items-center">
+ <div className="flex flex-col items-center gap-4 text-center">
+ <div className="grid size-14 place-items-center rounded-2xl bg-muted">
+ <Film className="size-7 text-muted-foreground" />
+ </div>
+ <h1 className="text-lg font-semibold tracking-tight">
+ Create a new project to get started
+ </h1>
+ <Button
+ onClick={() => {
+ setName("");
+ setCreateOpen(true);
}}
- onDuplicate={() => void duplicate(p)}
- onMove={(folderId) => void moveProjects([p.id], folderId)}
- onDelete={() => setDeleting(p)}
- />
- </div>
- <div className="mt-2 px-0.5 text-xs text-muted-foreground">
- {formatBytes(p.sizeBytes ?? 0)} · edited {formatDate(p.updatedAt)}
+ >
+ <Plus data-icon="inline-start" /> New project
+ </Button>
</div>
</div>
- ))}
- </Marquee>
- ) : (
- <div className="overflow-hidden rounded-xl border border-border bg-card">
- <div className="grid grid-cols-[1fr_90px_70px_110px_40px] items-center gap-3 border-b border-border bg-muted/50 px-4 py-2 text-xs font-medium tracking-wide text-muted-foreground uppercase">
- <span>Name</span>
- <span>Length</span>
- <span>Size</span>
- <span>Edited</span>
- <span />
- </div>
- {shown.map((p) => (
- <div
- key={p.id}
- data-sel-id={p.id}
- className={cn(
- "group grid cursor-pointer grid-cols-[1fr_90px_70px_110px_40px] items-center gap-3 border-b border-border px-4 py-2.5 text-sm last:border-b-0 hover:bg-muted/50",
- selected.has(p.id) && "bg-[#0a84ff]/10 hover:bg-[#0a84ff]/15"
- )}
- draggable
- onDragStart={(e) => onProjectDragStart(e, p)}
- onClick={(e) => {
- if (e.shiftKey || e.metaKey) {
- e.preventDefault();
- toggleSelect(p.id);
- return;
- }
- router.push(projectHref(base, p.id, "projects", openFolder));
- }}
- >
- <span className="flex min-w-0 items-center gap-2.5">
- <Film className="size-4 shrink-0 text-muted-foreground" />
- <span className="truncate font-medium">{p.name}</span>
- </span>
- <span className="font-mono text-xs text-muted-foreground tabular-nums">
- {formatTime(p.duration)}
- </span>
- <span className="text-xs text-muted-foreground tabular-nums">
- {formatBytes(p.sizeBytes ?? 0)}
- </span>
- <span className="text-xs text-muted-foreground">
- {formatDate(p.updatedAt)}
- </span>
- <ProjectMenu
- project={p}
- folders={folders}
- onRename={() => {
- setName(p.name);
- setRenaming(p);
- }}
- onDuplicate={() => void duplicate(p)}
- onMove={(folderId) => void moveProjects([p.id], folderId)}
- onDelete={() => setDeleting(p)}
- />
- </div>
- ))}
- <button
- type="button"
- data-no-marquee
- onClick={() => void newProjectHere()}
- className="flex w-full items-center gap-2.5 px-4 py-2.5 text-sm font-medium text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground"
- >
- <Plus className="size-4" /> New project
- </button>
- </div>
+ ) : view === "gallery" ? (
+ renderGallery(
+ r0,
+ (soleData.projects ?? []).filter((p) => (p.folderId ?? null) === openFolder)
+ )
+ ) : (
+ renderList(
+ r0,
+ (soleData.projects ?? []).filter((p) => (p.folderId ?? null) === openFolder)
+ )
+ )}
+ </>
)}
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
@@ -618,7 +926,7 @@ export function ProjectsHome() {
<AlertDialog open={!!deleting} onOpenChange={(o) => !o && setDeleting(null)}>
<AlertDialogContent>
<AlertDialogHeader>
- <AlertDialogTitle>Delete “{deleting?.name}”?</AlertDialogTitle>
+ <AlertDialogTitle>Delete “{deleting?.project.name}”?</AlertDialogTitle>
<AlertDialogDescription>
This deletes the whole project folder, including its media files
and exports. This can’t be undone.
@@ -647,8 +955,11 @@ export function ProjectsHome() {
/** Card art: the actual edit (a rendered proxy) plays on hover; the poster is
* the first clip's real first frame. Falls back to the source when no proxy
* has been rendered yet. */
-function CardPreview({ project: p }: { project: ProjectSummary }) {
+function CardPreview({ project: p, residency }: { project: ProjectSummary; residency: Residency }) {
const videoRef = useRef<HTMLVideoElement>(null);
+ const backend = backendFor(residency);
+ const fileUrl = (file: string) =>
+ backend.url(`/api/cut/projects/${p.id}/media/${encodeURIComponent(file)}`);
if (!p.previewFile && !p.hasPreview) {
return (
@@ -665,7 +976,7 @@ function CardPreview({ project: p }: { project: ProjectSummary }) {
return (
// eslint-disable-next-line @next/next/no-img-element -- engine media file, not Next-optimizable
<img
- src={mediaUrl(p.id, p.previewFile!)}
+ src={fileUrl(p.previewFile!)}
alt=""
className="absolute inset-0 size-full object-cover"
/>
@@ -673,8 +984,8 @@ function CardPreview({ project: p }: { project: ProjectSummary }) {
}
const src = p.hasPreview
- ? apiUrl(`/api/cut/projects/${p.id}/preview`)
- : mediaUrl(p.id, p.previewFile!);
+ ? backend.url(`/api/cut/projects/${p.id}/preview`)
+ : fileUrl(p.previewFile!);
return (
<div
@@ -707,6 +1018,7 @@ function ProjectMenu({
folders,
onRename,
onDuplicate,
+ duplicateTo,
onMove,
onDelete,
}: {
@@ -715,6 +1027,8 @@ function ProjectMenu({
folders: ProjectFolder[];
onRename: () => void;
onDuplicate: () => void;
+ /** Cross-residency copy, when both residencies are live. */
+ duplicateTo?: { target: Residency; run: () => void };
onMove: (folderId: string | null) => void;
onDelete: () => void;
}) {
@@ -740,6 +1054,12 @@ function ProjectMenu({
<DropdownMenuItem onClick={onDuplicate}>
<Copy /> Duplicate
</DropdownMenuItem>
+ {duplicateTo && (
+ <DropdownMenuItem onClick={duplicateTo.run}>
+ {duplicateTo.target === "cloud" ? <Cloud /> : <Laptop />}{" "}
+ {duplicateTo.target === "cloud" ? "Duplicate to Cloud" : "Duplicate to this Mac"}
+ </DropdownMenuItem>
+ )}
{folders.length > 0 && (
<>
<DropdownMenuSeparator />
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index e98e31eb..46598383 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -23,7 +23,8 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import { apiFetch, apiUrl } from "@/cut/lib/api";
+import { apiFetch, apiUrl } from "@/cut/lib/backend";
+import { useCutCaps } from "@/cut/lib/backend/hooks";
import {
clearAssetDrag,
draggingLibrary,
@@ -565,6 +566,7 @@ function MediaPanel({
}
function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: string }) {
+ const caps = useCutCaps();
const [saved, setSaved] = useState(false);
// Number of timeline items that would be cascade-deleted; null = no prompt.
const [confirmUses, setConfirmUses] = useState<number | null>(null);
@@ -689,11 +691,13 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: string
<DropdownMenuItem onClick={saveToLibrary}>
<FolderPlus /> Save to library
</DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => void revealMedia(projectId, asset.fileName).catch(() => {})}
- >
- <FolderOpen /> Show in Finder
- </DropdownMenuItem>
+ {caps.revealInFinder && (
+ <DropdownMenuItem
+ onClick={() => void revealMedia(projectId, asset.fileName).catch(() => {})}
+ >
+ <FolderOpen /> Show in Finder
+ </DropdownMenuItem>
+ )}
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onClick={remove}>
<Trash2 /> Delete
diff --git a/site/src/cut/components/SubtitlesPanel.tsx b/site/src/cut/components/SubtitlesPanel.tsx
index 2dd19dc9..e1eacdd9 100644
--- a/site/src/cut/components/SubtitlesPanel.tsx
+++ b/site/src/cut/components/SubtitlesPanel.tsx
@@ -24,6 +24,7 @@ import {
trackLocale,
} from "@/cut/lib/subtitles";
import { useElapsed } from "@/cut/hooks/useElapsed";
+import { useCutCaps } from "@/cut/lib/backend/hooks";
import { TIMELINE_H_MIN, useEditor } from "@/cut/lib/store";
import { PLATE_PAD_X, PLATE_PAD_Y, PLATE_RADIUS, plateFill } from "@/cut/lib/textRender";
import {
@@ -71,6 +72,7 @@ function laneLanguage(subs: SubtitlesBlock, lane: number): string {
}
export function SubtitlesPanel() {
+ const caps = useCutCaps();
const subtitles = useEditor((s) => s.subtitles);
const lane = useEditor((s) => s.subtitleLane);
const status = useEditor((s) => s.subtitleStatus);
@@ -130,23 +132,25 @@ export function SubtitlesPanel() {
<EmptyState status={status} error={error} onGenerate={generate} onTranslate={translate} />
) : tab === "content" ? (
<>
- <div className="shrink-0 px-1.5">
- <Button
- variant="ghost"
- size="sm"
- className="sub-regenerate"
- title="Transcribe the cut again (replaces these captions — undoable)"
- disabled={status === "running"}
- onClick={generate}
- >
- {status === "running" ? (
- <Loader2 className="animate-spin" />
- ) : (
- <RefreshCw />
- )}
- Regenerate
- </Button>
- </div>
+ {caps.transcribe && (
+ <div className="shrink-0 px-1.5">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="sub-regenerate"
+ title="Transcribe the cut again (replaces these captions — undoable)"
+ disabled={status === "running"}
+ onClick={generate}
+ >
+ {status === "running" ? (
+ <Loader2 className="animate-spin" />
+ ) : (
+ <RefreshCw />
+ )}
+ Regenerate
+ </Button>
+ </div>
+ )}
<Transcript cues={activeCues} />
{status === "error" && error && (
<p className="sub-error shrink-0 border-t border-border px-4 py-2.5 text-[11px] leading-relaxed text-red-600">
@@ -401,6 +405,7 @@ function EmptyState({
onGenerate: () => void;
onTranslate: (fromLane: number) => void;
}) {
+ const caps = useCutCaps();
const subtitles = useEditor((s) => s.subtitles);
const lane = useEditor((s) => s.subtitleLane);
const locale = trackLocale(subtitles, lane);
@@ -457,34 +462,37 @@ function EmptyState({
</select>
<ChevronDown className="pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-muted-foreground" />
</div>
- <Button
- className="sub-generate w-full"
- onClick={() => {
- setTranslating(false);
- onGenerate();
- }}
- title="Transcribe your audio into plain captions, word for word"
- >
- <Captions data-icon="inline-start" />
- {status === "empty" || status === "error" ? "Try again" : "Generate subtitles"}
- </Button>
- {sources.map((i) => (
+ {caps.transcribe && (
<Button
- key={i}
- variant="outline"
- className="sub-translate w-full"
- title={`Write this track by translating the ${laneLanguage(subtitles, i)} captions into ${
- LOCALES.find(([id]) => id === locale)?.[1] ?? locale
- }`}
+ className="sub-generate w-full"
onClick={() => {
- setTranslating(true);
- onTranslate(i);
+ setTranslating(false);
+ onGenerate();
}}
+ title="Transcribe your audio into plain captions, word for word"
>
- <Languages data-icon="inline-start" />
- Translate from {laneLanguage(subtitles, i)}
+ <Captions data-icon="inline-start" />
+ {status === "empty" || status === "error" ? "Try again" : "Generate subtitles"}
</Button>
- ))}
+ )}
+ {caps.captionAi &&
+ sources.map((i) => (
+ <Button
+ key={i}
+ variant="outline"
+ className="sub-translate w-full"
+ title={`Write this track by translating the ${laneLanguage(subtitles, i)} captions into ${
+ LOCALES.find(([id]) => id === locale)?.[1] ?? locale
+ }`}
+ onClick={() => {
+ setTranslating(true);
+ onTranslate(i);
+ }}
+ >
+ <Languages data-icon="inline-start" />
+ Translate from {laneLanguage(subtitles, i)}
+ </Button>
+ ))}
</div>
);
}
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index df118505..77023131 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -1,6 +1,6 @@
"use client";
-import { apiFetch, apiJson } from "./api";
+import { apiFetch, apiJson, getBackend } from "./backend";
import { refFromAsset, refFromStockVideo, type AssetRef } from "./assetRef";
import { chatOwner, tagChatAsset } from "./chatAssets";
import { applyOwnership, useGenerate, type VideoAttempt, type VideoGenOptions } from "./generate";
@@ -18,7 +18,18 @@ import {
renameLibraryFolder,
saveAssetToLibrary,
} from "./library";
-import { enrichAsset, ensurePeaks, importImage, importStockVideo, importUrlMedia } from "./media";
+import {
+ captureFreezeFrame,
+ detectSilenceClientSide,
+ enrichAsset,
+ ensurePeaks,
+ importImage,
+ importStockVideo,
+ importUrlMedia,
+ makeContactSheetsClientSide,
+ makeStillSheetClientSide,
+ renderAudioSpanWav,
+} from "./media";
import { requestSidePanel, SIDE_PANEL_TABS, type SidePanelTab } from "./panelRequest";
import { blobToInlineAudio, refToInlineAudio, type InlineImage } from "./refMedia";
import { characterPrompt, stockTitle } from "./stock";
@@ -148,31 +159,50 @@ export async function runAiTool(
}
// A still is one sheet with no time axis.
if (asset.type === "image") {
- const res = await apiFetch(`/api/cut/projects/${projectId}/watch`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ file: asset.fileName, still: true }),
- });
- const body = await apiJson<WatchBody>(res);
- if (!res.ok) throw new ToolError(body.error ?? "Could not read the image.");
+ let body: WatchBody;
+ if (getBackend().kind === "cloud") {
+ body = await makeStillSheetClientSide(asset.url).catch((e) => {
+ throw new ToolError(e instanceof Error ? e.message : "Could not read the image.");
+ });
+ } else {
+ const res = await apiFetch(`/api/cut/projects/${projectId}/watch`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ file: asset.fileName, still: true }),
+ });
+ body = await apiJson<WatchBody>(res);
+ if (!res.ok) throw new ToolError(body.error ?? "Could not read the image.");
+ }
return {
images: body.sheets.map((sh) => sh.image),
source: { assetId: asset.id, name: asset.name },
note: "A still image — one frame, no time axis.",
};
}
- const res = await apiFetch(`/api/cut/projects/${projectId}/watch`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- file: asset.fileName,
+ let body: WatchBody;
+ if (getBackend().kind === "cloud") {
+ // Same defaults, clamps, and caps as the engine's watch handler.
+ body = await makeContactSheetsClientSide(asset.url, {
from,
...(to !== undefined ? { to } : {}),
...(isNum(input.interval_seconds) ? { interval: input.interval_seconds } : {}),
- }),
- });
- const body = await apiJson<WatchBody>(res);
- if (!res.ok) throw new ToolError(body.error ?? "Could not watch the video.");
+ }).catch((e) => {
+ throw new ToolError(e instanceof Error ? e.message : "Could not watch the video.");
+ });
+ } else {
+ const res = await apiFetch(`/api/cut/projects/${projectId}/watch`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ file: asset.fileName,
+ from,
+ ...(to !== undefined ? { to } : {}),
+ ...(isNum(input.interval_seconds) ? { interval: input.interval_seconds } : {}),
+ }),
+ });
+ body = await apiJson<WatchBody>(res);
+ if (!res.ok) throw new ToolError(body.error ?? "Could not watch the video.");
+ }
// The engine's ffmpeg has no text renderer; the cells get their source-
// time stamps here on a canvas. A sheet that fails to stamp rides plain —
// sheetFrames stays the authority either way.
@@ -216,23 +246,40 @@ export async function runAiTool(
case "detect_silence": {
const { projectId, asset, clip, speed, from, to } = resolveWatchRange(s, input);
if (asset.type === "image") throw new ToolError(`"${asset.name}" is an image — it has no audio.`);
- const res = await apiFetch(`/api/cut/projects/${projectId}/silence`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- file: asset.fileName,
- from,
- ...(to !== undefined ? { to } : {}),
- ...(isNum(input.threshold_db) ? { threshold_db: input.threshold_db } : {}),
- ...(isNum(input.min_silence) ? { min_silence: input.min_silence } : {}),
- }),
- });
interface SilenceBody {
silences: { start: number; end: number; duration: number }[];
error?: string;
}
- const body = await apiJson<SilenceBody>(res);
- if (!res.ok) throw new ToolError(body.error ?? "Could not scan for silence.");
+ let body: SilenceBody;
+ if (getBackend().kind === "cloud") {
+ // Same defaults and clamps as the engine's silence handler.
+ body = {
+ silences: await detectSilenceClientSide(asset.url, {
+ from,
+ ...(to !== undefined ? { to } : {}),
+ thresholdDb: clamp(isNum(input.threshold_db) ? input.threshold_db : -30, -90, 0),
+ minSilence: clamp(isNum(input.min_silence) ? input.min_silence : 0.35, 0.05, 10),
+ }).catch((e) => {
+ throw new ToolError(
+ e instanceof Error ? e.message : "Could not scan for silence."
+ );
+ }),
+ };
+ } else {
+ const res = await apiFetch(`/api/cut/projects/${projectId}/silence`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ file: asset.fileName,
+ from,
+ ...(to !== undefined ? { to } : {}),
+ ...(isNum(input.threshold_db) ? { threshold_db: input.threshold_db } : {}),
+ ...(isNum(input.min_silence) ? { min_silence: input.min_silence } : {}),
+ }),
+ });
+ body = await apiJson<SilenceBody>(res);
+ if (!res.ok) throw new ToolError(body.error ?? "Could not scan for silence.");
+ }
// Pre-map each silence's overlap with the clip's trimmed range onto the
// timeline so the model cuts on ready numbers.
const toTimeline = (t: number) =>
@@ -274,7 +321,7 @@ export async function runAiTool(
const wholeAudio = asset.type === "audio" && !clip && !isNum(input.from) && !isNum(input.to);
const inline = wholeAudio
? await refToInlineAudio(refFromAsset(asset))
- : await listenToSource(projectId, asset.fileName, from, to);
+ : await listenToSource(projectId, asset, from, to);
if (!inline)
throw new ToolError(
"That stretch is too long to listen to inline (≈12MB cap) — pass a narrower from/to."
@@ -599,31 +646,54 @@ export async function runAiTool(
const t = clamp(isNum(input.t) ? input.t : s.currentTime, 0, Math.max(0, total - 0.001));
const span = spans.find((sp) => t >= sp.start && t < sp.start + sp.len) ?? spans[spans.length - 1];
const srcTime = span.clip.in + (t - span.start);
- const res = await apiFetch(`/api/cut/projects/${projectId}/freeze`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- file: span.asset.fileName,
- srcTime,
- duration: isNum(input.duration) ? input.duration : 1,
- // Bake the still at the current project frame, framed exactly as
- // the preview shows it. Switching aspect later letterboxes this
- // still — capture a fresh one to re-fit.
- frame: { w: FRAME[s.aspect].w, h: FRAME[s.aspect].h },
- framing: {
- fit: span.clip.fit ?? "fit",
- panX: span.clip.panX ?? 0,
- panY: span.clip.panY ?? 0,
- },
- }),
- });
- const body = await apiJson<MediaAsset>(res);
- if (!res.ok) throw new ToolError(body.error ?? "Could not render the freeze frame.");
+ let body: MediaAsset;
+ if (getBackend().kind === "cloud") {
+ // No engine to bake a still video — grab the frame in the browser and
+ // store it as a project image; image clips carry their own length,
+ // sized below to the requested duration, mirroring the engine's
+ // /freeze clamps (default 1s, 0.5..10s).
+ const freezeDur = Math.min(10, Math.max(0.5, isNum(input.duration) ? input.duration : 1));
+ body = await captureFreezeFrame(projectId, span.asset.url, srcTime, freezeDur).catch(
+ (e) => {
+ throw new ToolError(
+ e instanceof Error ? e.message : "Could not render the freeze frame."
+ );
+ }
+ );
+ } else {
+ const res = await apiFetch(`/api/cut/projects/${projectId}/freeze`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ file: span.asset.fileName,
+ srcTime,
+ duration: isNum(input.duration) ? input.duration : 1,
+ // Bake the still at the current project frame, framed exactly as
+ // the preview shows it. Switching aspect later letterboxes this
+ // still — capture a fresh one to re-fit.
+ frame: { w: FRAME[s.aspect].w, h: FRAME[s.aspect].h },
+ framing: {
+ fit: span.clip.fit ?? "fit",
+ panX: span.clip.panX ?? 0,
+ panY: span.clip.panY ?? 0,
+ },
+ }),
+ });
+ const made = await apiJson<MediaAsset>(res);
+ if (!res.ok) throw new ToolError(made.error ?? "Could not render the freeze frame.");
+ body = made;
+ }
const asset: MediaAsset = { ...body, url: mediaUrl(projectId, body.fileName), origin: "freeze" };
const cur = useEditor.getState();
cur.addAsset(asset);
cur.addClipFromAsset(asset.id); // lands at the end, selected
const sel = useEditor.getState().selection;
+ // A cloud freeze is a still image, placed at the default image-clip
+ // length — resize it to the requested duration (the engine path bakes a
+ // video whose duration addClipFromAsset adopts on its own).
+ if (sel?.kind === "clip" && body.type === "image" && body.duration > 0) {
+ cur.updateClip(sel.id, { out: body.duration });
+ }
const index = clamp(isNum(input.index) ? Math.round(input.index) : 0, 0, useEditor.getState().clips.length - 1);
if (sel?.kind === "clip") cur.moveClip(sel.id, index);
void enrichAsset(asset);
@@ -1819,18 +1889,25 @@ function resolveWatchRange(
return { projectId, asset, clip, speed, from, to };
}
-/** Pull a source's audio track off the engine (video and audio alike) and
- * inline it for the model; null when the range clears the inline cap. */
+/** Pull a source's audio track off (video and audio alike) and inline it for
+ * the model; null when the range clears the inline cap. Local: the engine
+ * extracts mono AAC. Cloud: the browser renders the span to 16 kHz mono WAV. */
async function listenToSource(
projectId: string,
- fileName: string,
+ asset: MediaAsset,
from: number,
to: number | undefined,
): Promise<InlineImage | null> {
+ if (getBackend().kind === "cloud") {
+ const wav = await renderAudioSpanWav(asset.url, from, to).catch((e) => {
+ throw new ToolError(e instanceof Error ? e.message : "Could not read the audio.");
+ });
+ return blobToInlineAudio(wav);
+ }
const res = await apiFetch(`/api/cut/projects/${projectId}/audio`, {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ file: fileName, from, ...(to !== undefined ? { to } : {}) }),
+ body: JSON.stringify({ file: asset.fileName, from, ...(to !== undefined ? { to } : {}) }),
});
if (!res.ok) {
const body = await apiJson<{ error?: string }>(res).catch(() => ({ error: undefined }));
diff --git a/site/src/cut/lib/backend/cloud.ts b/site/src/cut/lib/backend/cloud.ts
new file mode 100644
index 00000000..d93352b6
--- /dev/null
+++ b/site/src/cut/lib/backend/cloud.ts
@@ -0,0 +1,103 @@
+// The cloud backend: hosted Cut APIs on the deployment itself, session-authed
+// (same-origin cookie; no `u=` param — the server derives the account from
+// the session). Routes mirror the engine's JSON shapes under /api/cut-cloud.
+// Media bytes ride presigned R2 URLs minted by those routes, not this
+// transport.
+import type { CutBackend } from "./types";
+
+const cloudPath = (path: string) => path.replace(/^\/api\/cut\//, "/api/cut-cloud/");
+
+// Cloud project docs are versioned for lost-write detection: GET hands the
+// current version out in a header, PUT sends it back as ?v= and gets the
+// incremented one in its body. The map lives in the transport so call sites
+// keep the engine's unversioned shapes.
+const docVersions = new Map<string, string>();
+
+// /projects/:id only — /projects/folders is the folder collection, not a doc.
+const PROJECT_DOC = /^\/api\/cut\/projects\/(?!folders$)([^/?]+)$/;
+
+async function cloudFetch(path: string, init?: RequestInit): Promise<Response> {
+ const doc = PROJECT_DOC.exec(path);
+ const method = (init?.method ?? "GET").toUpperCase();
+ if (!doc || (method !== "GET" && method !== "PUT")) return fetch(cloudPath(path), init);
+ const projectId = decodeURIComponent(doc[1]);
+
+ if (method === "GET") {
+ const res = await fetch(cloudPath(path), init);
+ const version = res.headers.get("x-cut-doc-version");
+ if (res.ok && version) docVersions.set(projectId, version);
+ return res;
+ }
+
+ // A PUT with no known version is the first save; it succeeds unconditionally.
+ const v = docVersions.get(projectId);
+ const res = await fetch(cloudPath(path) + (v ? `?v=${encodeURIComponent(v)}` : ""), init);
+ if (res.status === 409) {
+ const body = (await res
+ .clone()
+ .json()
+ .catch(() => null)) as { doc?: unknown; version?: number | string } | null;
+ if (body?.version !== undefined) docVersions.set(projectId, String(body.version));
+ window.dispatchEvent(
+ new CustomEvent("cut-cloud-doc-conflict", {
+ detail: { projectId, doc: body?.doc, version: body?.version },
+ })
+ );
+ } else if (res.ok) {
+ const body = (await res
+ .clone()
+ .json()
+ .catch(() => null)) as { version?: number | string } | null;
+ if (body?.version !== undefined) docVersions.set(projectId, String(body.version));
+ }
+ return res;
+}
+
+/** Batch-mint signed R2 GET URLs for a cloud project's media files. Returns
+ * fileName -> url; anything the mint misses keeps the /media route, whose 302
+ * serves the same bytes. */
+export async function fetchSignedMediaUrls(
+ projectId: string,
+ fileNames: string[]
+): Promise<Map<string, string>> {
+ const out = new Map<string, string>();
+ if (fileNames.length === 0) return out;
+ try {
+ const res = await cloudFetch("/api/cut/media/presign-get", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ items: fileNames.map((fileName) => ({ projectId, fileName })) }),
+ });
+ if (!res.ok) return out;
+ const body = (await res.json()) as { urls?: { fileName: string; url: string }[] };
+ for (const u of body.urls ?? []) out.set(u.fileName, u.url);
+ } catch {
+ // Signed URLs are an optimization; the route fallback still streams.
+ }
+ return out;
+}
+
+/** Friendly message for a presign 413 quota rejection, else null. */
+export function quotaErrorMessage(
+ status: number,
+ body: { error?: string } | null | undefined
+): string | null {
+ return status === 413 && body?.error === "storage_quota_exceeded"
+ ? "Cloud storage is full — free space in your projects or delete unused media."
+ : null;
+}
+
+export const cloudBackend: CutBackend = {
+ kind: "cloud",
+ caps: {
+ importUrl: true, // executed by the render worker
+ liveMic: true, // hosted LLM STT (lib/cloudTranscribe.ts)
+ transcribe: true, // hosted LLM STT (lib/cloudTranscribe.ts)
+ captionAi: false, // engine Claude-CLI one-shots; no hosted twin yet
+ localCliChat: false, // by design: those are the user's local logins
+ revealInFinder: false,
+ watch: true, // browser seek + canvas contact sheets (lib/media.ts)
+ },
+ fetch: (path, init) => cloudFetch(path, init),
+ url: (path) => cloudPath(path),
+};
diff --git a/site/src/cut/lib/backend/hooks.ts b/site/src/cut/lib/backend/hooks.ts
new file mode 100644
index 00000000..0f0b1046
--- /dev/null
+++ b/site/src/cut/lib/backend/hooks.ts
@@ -0,0 +1,15 @@
+// React bindings for the backend seam, kept out of ./index so the engine
+// binary (which compiles lib/types.ts → ./index) never bundles React.
+import { useSyncExternalStore } from "react";
+
+import { cutMode, getBackend, subscribeCutMode } from "./index";
+import type { CutCaps, CutMode } from "./types";
+
+export function useCutMode(): CutMode {
+ return useSyncExternalStore(subscribeCutMode, cutMode, () => "local" as const);
+}
+
+export function useCutCaps(): CutCaps {
+ useCutMode();
+ return getBackend().caps;
+}
diff --git a/site/src/cut/lib/backend/index.ts b/site/src/cut/lib/backend/index.ts
new file mode 100644
index 00000000..b17a87f8
--- /dev/null
+++ b/site/src/cut/lib/backend/index.ts
@@ -0,0 +1,46 @@
+// The backend seam: every Cut API call dispatches through the active backend.
+// The app runs local (the engine on this Mac) unless the ConnectGate put it in
+// cloud mode — web mode with no engine present, behind the `cut-web-mode`
+// flag. Call sites keep the exact apiFetch/apiUrl/apiJson shapes they always
+// had; only the import moved from ../api to this module.
+//
+// This module stays React-free: the engine binary compiles lib/types.ts, which
+// imports apiUrl from here. React hooks live in ./hooks.
+import { cloudBackend } from "./cloud";
+import { localBackend } from "./local";
+import type { CutBackend, CutCaps, CutMode } from "./types";
+
+export type { CutBackend, CutCaps, CutMode };
+export { apiJson } from "../api";
+
+let mode: CutMode = "local";
+const listeners = new Set<() => void>();
+
+/** Set by the ConnectGate before the app's data layer runs. */
+export function setCutMode(next: CutMode) {
+ if (mode === next) return;
+ mode = next;
+ listeners.forEach((l) => l());
+}
+
+export function cutMode(): CutMode {
+ return mode;
+}
+
+/** Subscription feed for ./hooks' useSyncExternalStore. */
+export function subscribeCutMode(onChange: () => void) {
+ listeners.add(onChange);
+ return () => {
+ listeners.delete(onChange);
+ };
+}
+
+export function getBackend(): CutBackend {
+ return mode === "cloud" ? cloudBackend : localBackend;
+}
+
+/** fetch() against the active backend. */
+export const apiFetch = (path: string, init?: RequestInit) => getBackend().fetch(path, init);
+
+/** Absolute-or-relative URL for a backend API path. */
+export const apiUrl = (path: string) => getBackend().url(path);
diff --git a/site/src/cut/lib/backend/local.ts b/site/src/cut/lib/backend/local.ts
new file mode 100644
index 00000000..ac4a6076
--- /dev/null
+++ b/site/src/cut/lib/backend/local.ts
@@ -0,0 +1,20 @@
+// The local backend: the engine on this Mac. A pass-through to the existing
+// engine transport in ../api, so request shapes are exactly what they were
+// before the backend seam existed.
+import { apiFetch, apiUrl } from "../api";
+import type { CutBackend } from "./types";
+
+export const localBackend: CutBackend = {
+ kind: "local",
+ caps: {
+ importUrl: true,
+ liveMic: true,
+ transcribe: true,
+ captionAi: true,
+ localCliChat: true,
+ revealInFinder: true,
+ watch: true,
+ },
+ fetch: (path, init) => apiFetch(path, init),
+ url: (path) => apiUrl(path),
+};
diff --git a/site/src/cut/lib/backend/types.ts b/site/src/cut/lib/backend/types.ts
new file mode 100644
index 00000000..14343c7a
--- /dev/null
+++ b/site/src/cut/lib/backend/types.ts
@@ -0,0 +1,35 @@
+// A Cut backend is where a project lives and executes: "local" is the engine
+// on this Mac (127.0.0.1, disk storage, native tools), "cloud" is the hosted
+// deployment (session auth, Postgres + R2). Both speak the same JSON route
+// shapes, so ordinary API calls dispatch through one transport; operations
+// whose contracts genuinely differ (uploads, export, transcription) branch on
+// the backend kind where they are implemented.
+export type CutMode = "local" | "cloud";
+
+// What the active backend can do. Components consult these to hide
+// affordances instead of feature-detecting or failing at call time.
+export type CutCaps = {
+ /** Import media from a URL (yt-dlp on the engine; render worker later). */
+ importUrl: boolean;
+ /** Live mic dictation (engine cut-stt --live). */
+ liveMic: boolean;
+ /** Timeline transcription (engine cut-stt; hosted LLM STT later). */
+ transcribe: boolean;
+ /** Caption AI: translate, rewrite, visual subtitles (engine Claude-CLI one-shots). */
+ captionAi: boolean;
+ /** Claude/Codex CLI chat providers (the user's own local logins). */
+ localCliChat: boolean;
+ /** Reveal a media file in Finder. */
+ revealInFinder: boolean;
+ /** AI "watch" filmstrip contact sheets (engine ffmpeg). */
+ watch: boolean;
+};
+
+export interface CutBackend {
+ kind: CutMode;
+ caps: CutCaps;
+ /** fetch() against this backend, preserving the engine route shapes. */
+ fetch(path: string, init?: RequestInit): Promise<Response>;
+ /** Absolute-or-relative URL for a backend API path (media src, downloads). */
+ url(path: string): string;
+}
diff --git a/site/src/cut/lib/cloudTranscribe.ts b/site/src/cut/lib/cloudTranscribe.ts
new file mode 100644
index 00000000..32590d78
--- /dev/null
+++ b/site/src/cut/lib/cloudTranscribe.ts
@@ -0,0 +1,298 @@
+"use client";
+
+// Hosted transcription. The cloud backend has no on-device speech engine, so
+// the browser does the audio work itself: render the timeline's audible mix
+// with an OfflineAudioContext (the same trims/speeds/volumes/crossfades the
+// engine's ffmpeg graph applies — see server/transcribe.ts), chunk it as
+// 16 kHz mono WAV, POST each chunk to the metered /transcribe route, then
+// stitch the returned cues back into timeline time and interpolate per-word
+// timings. Mic dictation reuses the same chunk/post/stitch core on a
+// MediaRecorder capture.
+
+import { apiFetch } from "./backend";
+import { mediaUrl, type SubtitleCue } from "./types";
+
+/** Mirror of the engine's TranscribeSpec (server/transcribe.ts) minus projectId. */
+export interface CloudTranscribeSpec {
+ duration: number;
+ locale?: string;
+ clips: {
+ file: string;
+ in: number;
+ out: number;
+ muted: boolean;
+ speed?: number;
+ /** Cross-dissolve overlap into the next clip, timeline seconds. */
+ transition?: number;
+ }[];
+ audio: { file: string; in: number; out: number; start: number; volume: number; speed?: number }[];
+}
+
+const RATE = 16000; // the wire format the hosted route expects
+const CHUNK_SECONDS = 90; // ~2.9MB of 16-bit mono PCM per chunk
+const OVERLAP_SECONDS = 3; // audio shared across chunk seams for stitching
+// A chunk quieter than this end to end carries no speech; skip the round-trip
+// (and its credit charge) — the engine path short-circuits silence the same way.
+const SILENCE_PEAK = 1e-3;
+
+const uid = () => crypto.randomUUID().slice(0, 8);
+const round = (n: number) => Math.round(n * 1000) / 1000;
+const speedOf = (s?: number) => (s && s > 0 ? s : 1);
+
+/** Timeline length of one spec clip: source span over speed. A gap spacer
+ * (no file) keeps its exact length — flooring it would land later cues late. */
+const clipDur = (c: CloudTranscribeSpec["clips"][number]) =>
+ c.file ? Math.max(0.1, (c.out - c.in) / speedOf(c.speed)) : Math.max(0, c.out - c.in);
+
+/** Render the cut's audible mix to a 16 kHz mono buffer, mirroring the engine's
+ * ffmpeg graph: clip audio folds sequentially with cross-dissolves overlapping
+ * (linear crossfade ≈ acrossfade's tri curve), soundtrack/voiceover items land
+ * at their absolute starts with their volumes, and speed rides playbackRate
+ * (pitch shifts where atempo would preserve it — timing, which is what cue
+ * placement needs, is identical). Returns null when nothing audible exists. */
+async function renderMix(projectId: string, spec: CloudTranscribeSpec): Promise<AudioBuffer | null> {
+ const ctx = new OfflineAudioContext(1, Math.max(1, Math.ceil(spec.duration * RATE)), RATE);
+ const files = [...new Set([...spec.clips, ...spec.audio].map((c) => c.file).filter(Boolean))];
+ const buffers = new Map<string, AudioBuffer>();
+ await Promise.all(
+ files.map(async (f) => {
+ try {
+ const res = await fetch(mediaUrl(projectId, f));
+ if (!res.ok) return;
+ buffers.set(f, await ctx.decodeAudioData(await res.arrayBuffer()));
+ } catch {
+ // No decodable audio stream (e.g. a silent video) — mixes as silence,
+ // like the engine's hasStream check.
+ }
+ })
+ );
+
+ const hasSpeechSource =
+ spec.clips.some((c) => !c.muted && buffers.has(c.file)) ||
+ spec.audio.some((a) => buffers.has(a.file));
+ if (!hasSpeechSource) return null;
+
+ // First pass: the timeline geometry of the sequential clip fold. Each
+ // cross-dissolve pulls the next clip back by the (clamped) overlap, exactly
+ // like the engine's acrossfade chain.
+ const geo = spec.clips.map((c) => ({ clip: c, at: 0, dur: clipDur(c), fadeIn: 0, fadeOut: 0 }));
+ let acc = 0;
+ geo.forEach((g, j) => {
+ const d =
+ j > 0 ? Math.min(spec.clips[j - 1].transition ?? 0, acc * 0.9, g.dur * 0.9) : 0;
+ const fade = d > 0.01 ? d : 0;
+ g.at = j === 0 ? 0 : acc - fade;
+ g.fadeIn = fade;
+ if (j > 0) geo[j - 1].fadeOut = fade;
+ acc = g.at + g.dur;
+ });
+
+ for (const g of geo) {
+ const c = g.clip;
+ const buf = !c.muted && c.file ? buffers.get(c.file) : undefined;
+ if (!buf) continue; // muted / silent clips and gap spacers only shape time
+ const src = ctx.createBufferSource();
+ src.buffer = buf;
+ src.playbackRate.value = speedOf(c.speed);
+ const gain = ctx.createGain();
+ if (g.fadeIn > 0) {
+ gain.gain.setValueAtTime(0, g.at);
+ gain.gain.linearRampToValueAtTime(1, g.at + g.fadeIn);
+ }
+ if (g.fadeOut > 0) {
+ gain.gain.setValueAtTime(1, g.at + g.dur - g.fadeOut);
+ gain.gain.linearRampToValueAtTime(0, g.at + g.dur);
+ }
+ src.connect(gain);
+ gain.connect(ctx.destination);
+ // start()'s offset/duration are source seconds; playbackRate stretches
+ // them onto the timeline, matching the engine's atrim + atempo.
+ src.start(g.at, Math.max(0, c.in), Math.max(0, c.out - c.in));
+ }
+
+ for (const a of spec.audio) {
+ const buf = buffers.get(a.file);
+ if (!buf) continue;
+ const src = ctx.createBufferSource();
+ src.buffer = buf;
+ src.playbackRate.value = speedOf(a.speed);
+ const gain = ctx.createGain();
+ gain.gain.value = a.volume;
+ src.connect(gain);
+ gain.connect(ctx.destination);
+ src.start(Math.max(0, a.start), Math.max(0, a.in), Math.max(0, a.out - a.in));
+ }
+
+ return ctx.startRendering();
+}
+
+/** 16-bit PCM WAV (RIFF) from mono 16 kHz float samples. */
+export function encodeWav(samples: Float32Array): Blob {
+ const data = new DataView(new ArrayBuffer(44 + samples.length * 2));
+ const ascii = (off: number, s: string) => {
+ for (let i = 0; i < s.length; i++) data.setUint8(off + i, s.charCodeAt(i));
+ };
+ ascii(0, "RIFF");
+ data.setUint32(4, 36 + samples.length * 2, true);
+ ascii(8, "WAVE");
+ ascii(12, "fmt ");
+ data.setUint32(16, 16, true);
+ data.setUint16(20, 1, true); // PCM
+ data.setUint16(22, 1, true); // mono
+ data.setUint32(24, RATE, true);
+ data.setUint32(28, RATE * 2, true);
+ data.setUint16(32, 2, true);
+ data.setUint16(34, 16, true);
+ ascii(36, "data");
+ data.setUint32(40, samples.length * 2, true);
+ for (let i = 0; i < samples.length; i++) {
+ const v = Math.max(-1, Math.min(1, samples[i]));
+ data.setInt16(44 + i * 2, v < 0 ? v * 0x8000 : v * 0x7fff, true);
+ }
+ return new Blob([data.buffer], { type: "audio/wav" });
+}
+
+function isSilent(samples: Float32Array): boolean {
+ for (let i = 0; i < samples.length; i++) {
+ if (Math.abs(samples[i]) > SILENCE_PEAK) return false;
+ }
+ return true;
+}
+
+interface WireCue {
+ start: number;
+ end: number;
+ text: string;
+}
+
+async function postChunk(
+ samples: Float32Array,
+ offset: number,
+ locale: string | undefined
+): Promise<WireCue[]> {
+ const form = new FormData();
+ form.append("audio", new File([encodeWav(samples)], "chunk.wav", { type: "audio/wav" }));
+ form.append("offset", String(round(offset)));
+ if (locale) form.append("locale", locale);
+ const res = await apiFetch("/api/cut/transcribe", { method: "POST", body: form });
+ const body = (await res.json().catch(() => null)) as
+ | { cues?: WireCue[]; error?: string; message?: string }
+ | null;
+ if (!res.ok) throw new Error(body?.message ?? body?.error ?? "Transcription failed.");
+ return (body?.cues ?? []).filter(
+ (c) =>
+ typeof c?.start === "number" &&
+ typeof c?.end === "number" &&
+ typeof c?.text === "string" &&
+ Number.isFinite(c.start) &&
+ Number.isFinite(c.end)
+ );
+}
+
+/** Proportional word timings inside a cue: split the text into words and
+ * distribute [start, end] by each word's share of the characters. */
+function interpolateWords(
+ text: string,
+ start: number,
+ end: number
+): { t0: number; t1: number; w: string }[] {
+ const parts = text.split(/\s+/).filter(Boolean);
+ const total = parts.reduce((n, w) => n + w.length, 0) || 1;
+ const span = Math.max(0, end - start);
+ let at = start;
+ return parts.map((w) => {
+ const d = (w.length / total) * span;
+ const word = { t0: round(at), t1: round(at + d), w };
+ at += d;
+ return word;
+ });
+}
+
+/** Chunk mono 16 kHz samples, transcribe each chunk, and stitch: cue times
+ * re-base by chunk offset, and in each 3s overlap the midpoint of the seam
+ * decides ownership — cues whose center falls in the earlier chunk's half are
+ * dropped from the later one (and vice versa), so seams never duplicate.
+ * Returns null when `isStale` trips mid-run. */
+async function transcribeSamples(
+ samples: Float32Array,
+ locale: string | undefined,
+ isStale?: () => boolean
+): Promise<SubtitleCue[] | null> {
+ const duration = samples.length / RATE;
+ const step = (CHUNK_SECONDS - OVERLAP_SECONDS) * RATE;
+ const cues: SubtitleCue[] = [];
+ for (let s = 0; s < samples.length; s += step) {
+ const slice = samples.subarray(s, Math.min(samples.length, s + CHUNK_SECONDS * RATE));
+ const offset = s / RATE;
+ const last = s + CHUNK_SECONDS * RATE >= samples.length;
+ if (isStale?.()) return null;
+ if (!isSilent(slice)) {
+ const chunk = await postChunk(slice, offset, locale);
+ if (isStale?.()) return null;
+ const from = s === 0 ? -Infinity : offset + OVERLAP_SECONDS / 2;
+ const to = last ? Infinity : offset + slice.length / RATE - OVERLAP_SECONDS / 2;
+ for (const c of chunk) {
+ const start = Math.max(0, Math.min(c.start + offset, duration));
+ const end = Math.max(0, Math.min(c.end + offset, duration));
+ const text = c.text.trim();
+ const mid = (start + end) / 2;
+ if (!text || end <= start || mid < from || mid >= to) continue;
+ cues.push({
+ id: uid(),
+ start: round(start),
+ end: round(end),
+ text,
+ words: interpolateWords(text, start, end),
+ });
+ }
+ }
+ if (last) break;
+ }
+ return cues.sort((a, b) => a.start - b.start);
+}
+
+/** Cloud twin of the engine transcribe job: render the spec's audible mix in
+ * the browser, transcribe it chunk by chunk, and return timeline-timed cues.
+ * Returns null when `isStale` trips (caller switched projects mid-run). */
+export async function cloudTranscribeSpec(
+ projectId: string,
+ spec: CloudTranscribeSpec,
+ isStale: () => boolean
+): Promise<SubtitleCue[] | null> {
+ if (spec.clips.length === 0 && spec.audio.length === 0) {
+ throw new Error("Add audio or video to the timeline first.");
+ }
+ const mix = await renderMix(projectId, spec);
+ if (isStale()) return null;
+ if (!mix) return []; // nothing audible — no speech, like the engine's short-circuit
+ return transcribeSamples(mix.getChannelData(0), spec.locale, isStale);
+}
+
+/** Transcribe a finished mic recording: decode it, downmix/resample to the
+ * wire format, run the chunk pipeline, and join the cue texts. */
+export async function cloudTranscribeRecording(blob: Blob, locale?: string): Promise<string> {
+ const bytes = await blob.arrayBuffer();
+ // Decode at the device rate, then resample/downmix through an offline
+ // render — decodeAudioData resamples to its context's rate, but the mono
+ // 16 kHz target length isn't known until after the decode.
+ const probe = new AudioContext();
+ let decoded: AudioBuffer;
+ try {
+ decoded = await probe.decodeAudioData(bytes);
+ } catch {
+ throw new Error("Could not read the recording's audio.");
+ } finally {
+ void probe.close().catch(() => {});
+ }
+ const ctx = new OfflineAudioContext(1, Math.max(1, Math.ceil(decoded.duration * RATE)), RATE);
+ const src = ctx.createBufferSource();
+ src.buffer = decoded;
+ src.connect(ctx.destination);
+ src.start();
+ const mono = (await ctx.startRendering()).getChannelData(0);
+ const cues = await transcribeSamples(mono, locale);
+ return (cues ?? [])
+ .map((c) => c.text)
+ .join(" ")
+ .trim();
+}
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index 72bd6ce4..c72d00eb 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -1,8 +1,10 @@
"use client";
-import { apiFetch, apiJson, apiUrl } from "./api";
+import { apiFetch, apiJson, getBackend, type CutBackend } from "./backend";
+import { quotaErrorMessage } from "./backend/cloud";
import { normalizeGrade } from "./colorGrade";
-import { clipSpeed, getClipSpans, overlayLayers, projectDuration, spanSequence } from "./store";
+import { putSigned } from "./media";
+import { clipSpeed, getClipSpans, overlayLayers, projectDuration, spanSequence, useEditor } from "./store";
import { captionStyle, cueOverlay, cueWordWindows, laneCues, subtitleLaneCount, trackPos } from "./subtitles";
import { renderOverlayPng } from "./textRender";
import { FRAME, overlayAnimStyle } from "./types";
@@ -106,8 +108,12 @@ export function formatSizeEstimate(bytes: number): string {
}
/** Reveal a rendered export in Finder (local engine only). */
-export async function revealExport(projectId: string, file: string) {
- await apiFetch(
+export async function revealExport(
+ projectId: string,
+ file: string,
+ backend: CutBackend = getBackend()
+) {
+ await backend.fetch(
`/api/cut/projects/${projectId}/exports/${encodeURIComponent(file)}/reveal`,
{ method: "POST" }
);
@@ -141,18 +147,26 @@ export interface ExportDoc {
}
-/** 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
- * the request. Shared by full exports and the low-res hover proxy. */
-async function buildExportForm(
+/** The neutral built cut: the engine spec plus the browser-rendered overlay
+ * PNGs. The local path serializes it to the engine's multipart form; the
+ * cloud path presigns the PNGs to R2 and posts the spec as JSON. */
+interface ExportPayload {
+ spec: object;
+ pngs: { name: string; blob: Blob }[];
+}
+
+/** Build the export spec + overlay PNGs from the cut. Media already lives in
+ * the project folder — the spec references it by file name; only overlay PNGs
+ * travel with the request. Shared by full exports and the low-res hover proxy. */
+async function buildExportPayload(
projectId: string,
doc: ExportDoc,
settings: ExportSettings,
target: "export" | "preview"
-): Promise<FormData> {
+): Promise<ExportPayload> {
const spans = getClipSpans(doc.clips, doc.assets);
const duration = projectDuration(doc);
- const form = new FormData();
+ const pngs: ExportPayload["pngs"] = [];
const assetById = new Map(doc.assets.map((a) => [a.id, a]));
// Overlay-only cuts (empty track 0) still export: track 0 becomes a black bed
// the length of the project and the overlays/soundtrack composite onto it —
@@ -302,7 +316,7 @@ async function buildExportForm(
if (o.start >= duration || !o.text.trim()) continue;
const png = await renderOverlayPng(o, settings.width, settings.height);
const key = `overlay_${i}.png`;
- form.append(key, png, key);
+ pngs.push({ name: key, blob: png });
overlays.push({ file: key, start: o.start, end: Math.min(o.end, duration) });
}
@@ -334,7 +348,7 @@ async function buildExportForm(
settings.height
);
const key = windows.length > 1 ? `sub_${lane}_${i}_${wi}.png` : `sub_${lane}_${i}.png`;
- form.append(key, png, key);
+ pngs.push({ name: key, blob: png });
captions.push({
file: key,
start: win.start,
@@ -351,13 +365,12 @@ async function buildExportForm(
const png = await new Promise<Blob>((resolve, reject) =>
blank.toBlob((b) => (b ? resolve(b) : reject(new Error("Could not render captions."))), "image/png")
);
- form.append("sub_blank.png", png, "sub_blank.png");
+ pngs.push({ name: "sub_blank.png", blob: png });
}
}
- form.append(
- "spec",
- JSON.stringify({
+ return {
+ spec: {
projectId,
target,
...settings,
@@ -369,21 +382,85 @@ async function buildExportForm(
overlayVideos,
overlays,
captions,
- })
- );
+ },
+ pngs,
+ };
+}
+
+/** Serialize a payload to the engine's multipart form: PNGs in render order,
+ * then the spec — the exact request shape from before the payload split. */
+function exportFormFromPayload({ spec, pngs }: ExportPayload): FormData {
+ const form = new FormData();
+ for (const p of pngs) form.append(p.name, p.blob, p.name);
+ form.append("spec", JSON.stringify(spec));
return form;
}
+/** Kick off an export on the given backend, returning the create response.
+ * The backend is captured when the export starts, so a job keeps rendering
+ * against its own backend even after the app rebinds to the other residency.
+ * Local: the engine's multipart form. Cloud: presign the overlay PNGs, PUT
+ * them straight to R2, then POST the JSON export body. */
+async function postExport(
+ projectId: string,
+ payload: ExportPayload,
+ outName: string,
+ backend: CutBackend
+): Promise<Response> {
+ if (backend.kind !== "cloud") {
+ return backend.fetch("/api/cut/export", { method: "POST", body: exportFormFromPayload(payload) });
+ }
+ const overlays: { name: string; key: string }[] = [];
+ if (payload.pngs.length > 0) {
+ const pre = await backend.fetch("/api/cut/export/presign", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ files: payload.pngs.map((p) => ({ name: p.name, bytes: p.blob.size })),
+ }),
+ });
+ const preBody = await apiJson<{ files?: { name: string; key: string; url: string }[] }>(pre);
+ if (!pre.ok || !preBody.files) {
+ throw new Error(
+ quotaErrorMessage(pre.status, preBody) ?? preBody.error ?? "Export failed to start."
+ );
+ }
+ const byName = new Map(preBody.files.map((f) => [f.name, f]));
+ await Promise.all(
+ payload.pngs.map(async (p) => {
+ const target = byName.get(p.name);
+ if (!target) throw new Error("Export failed to start.");
+ await putSigned(target.url, p.blob, "image/png");
+ })
+ );
+ for (const p of payload.pngs) overlays.push({ name: p.name, key: byName.get(p.name)!.key });
+ }
+ return backend.fetch("/api/cut/export", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ spec: payload.spec, overlays, projectId, outName }),
+ });
+}
+
+/** The cloud names the output client-side (the engine derives it from the
+ * project name itself, deduping on disk); mirror the engine's sanitize rule. */
+function exportOutName(): string {
+ const base =
+ useEditor.getState().projectName.replace(/[/\\:*?"<>|]/g, "").trim().slice(0, 60) || "export";
+ return `${base}.mp4`;
+}
+
/** Poll an export job to completion, reporting progress. Returns the file name. */
export async function pollExport(
jobId: string,
onProgress: (stage: string, ratio: number) => void,
- isCanceled: () => boolean = () => false
+ isCanceled: () => boolean = () => false,
+ backend: CutBackend = getBackend()
): Promise<string> {
for (;;) {
if (isCanceled()) throw new Error("Export canceled.");
await new Promise((r) => setTimeout(r, 400));
- const st = await apiFetch(`/api/cut/export/${jobId}`);
+ const st = await backend.fetch(`/api/cut/export/${jobId}`);
const status = await apiJson<{
status?: string;
progress?: number;
@@ -396,9 +473,9 @@ export async function pollExport(
}
/** Trigger a browser download of a finished export by job id. */
-export function downloadExport(jobId: string, outName: string) {
+export function downloadExport(jobId: string, outName: string, backend: CutBackend = getBackend()) {
const a = document.createElement("a");
- a.href = apiUrl(`/api/cut/export/${jobId}/file`);
+ a.href = backend.url(`/api/cut/export/${jobId}/file`);
a.download = outName;
document.body.appendChild(a);
a.click();
@@ -414,16 +491,17 @@ export async function createExportJob(
doc: ExportDoc,
settings: ExportSettings
): Promise<string> {
- const form = await buildExportForm(projectId, doc, settings, "export");
- const res = await apiFetch("/api/cut/export", { method: "POST", body: form });
+ const backend = getBackend(); // pinned: the payload build takes a while
+ const payload = await buildExportPayload(projectId, doc, settings, "export");
+ const res = await postExport(projectId, payload, exportOutName(), backend);
const body = await apiJson<{ id?: string }>(res);
if (!res.ok || !body.id) throw new Error(body.error ?? "Export failed to start.");
return body.id;
}
/** Cancel a running or queued export job by id. */
-export function cancelExportJob(jobId: string) {
- void apiFetch(`/api/cut/export/${jobId}`, { method: "DELETE" }).catch(() => {});
+export function cancelExportJob(jobId: string, backend: CutBackend = getBackend()) {
+ void backend.fetch(`/api/cut/export/${jobId}`, { method: "DELETE" }).catch(() => {});
}
/** Low-res proxy of the actual edit for the project card's hover preview.
@@ -431,16 +509,17 @@ export function cancelExportJob(jobId: string) {
* preview.mp4. Best-effort: silently no-ops if a slot is busy or there's no
* footage yet. */
export async function renderPreviewProxy(projectId: string, doc: ExportDoc, aspect: Aspect) {
+ const backend = getBackend(); // pinned: the proxy render outlives navigation
const [width, height] = aspect === "16:9" ? [640, 360] : [360, 640];
const settings: ExportSettings = { width, height, fps: 24, crf: 30, preset: "veryfast" };
- let form: FormData;
+ let res: Response;
try {
- form = await buildExportForm(projectId, doc, settings, "preview");
+ const payload = await buildExportPayload(projectId, doc, settings, "preview");
+ res = await postExport(projectId, payload, "preview.mp4", backend);
} catch {
return; // no clips yet
}
- const res = await apiFetch("/api/cut/export", { method: "POST", body: form });
const body = (await res.json().catch(() => ({}))) as { id?: string };
if (!res.ok || !body.id) return; // a slot was busy; try again later
- await pollExport(body.id, () => {}).catch(() => {});
+ await pollExport(body.id, () => {}, undefined, backend).catch(() => {});
}
diff --git a/site/src/cut/lib/exportStore.ts b/site/src/cut/lib/exportStore.ts
index cc06c97b..e5af1529 100644
--- a/site/src/cut/lib/exportStore.ts
+++ b/site/src/cut/lib/exportStore.ts
@@ -2,7 +2,11 @@
import { useEffect, useRef } from "react";
import { create } from "zustand";
-import { apiFetch } from "./api";
+import { engineOrigin, servedFromEngine } from "./api";
+import { getBackend, type CutBackend, type CutMode } from "./backend";
+import { cloudBackend } from "./backend/cloud";
+import { localBackend } from "./backend/local";
+import { webModeEnabled } from "./flags";
import {
cancelExportJob,
createExportJob,
@@ -16,6 +20,11 @@ import { useGenNotify } from "./genNotify";
// 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.
+//
+// With web mode on, local and cloud jobs can be in flight at once, so the
+// store reflects both backends' feeds; each row is tagged with the residency
+// it came from and every per-row action goes to that row's own backend — the
+// globally bound mode rebinds whenever a project of the other residency opens.
export interface ExportJob {
id: string;
@@ -28,6 +37,15 @@ export interface ExportJob {
/** Epoch ms the encode began (elapsed clock) and the job was created (order). */
startedAt?: number;
createdAt?: number;
+ /** Which backend's feed the row came from — stamped on merge, not sent by
+ * the server. */
+ residency: CutMode;
+}
+
+/** The backend a dock row lives on; per-row actions hit this, never the
+ * globally bound mode. */
+export function exportBackend(residency: CutMode): CutBackend {
+ return residency === "cloud" ? cloudBackend : localBackend;
}
/** A client-only dock row for the brief window before the engine has a job id:
@@ -41,6 +59,8 @@ export interface LocalRow {
status: "preparing" | "error";
error?: string;
createdAt: number;
+ /** The backend the export is starting on, captured when it was kicked off. */
+ residency: CutMode;
}
interface ExportsState {
@@ -75,7 +95,14 @@ export const useExports = create<ExportsState>((set, get) => ({
set((s) => ({
local: [
...s.local,
- { id: localId, projectId, projectName, status: "preparing", createdAt: Date.now() },
+ {
+ id: localId,
+ projectId,
+ projectName,
+ status: "preparing",
+ createdAt: Date.now(),
+ residency: getBackend().kind,
+ },
],
}));
try {
@@ -93,7 +120,8 @@ export const useExports = create<ExportsState>((set, get) => ({
},
cancel: (id) => {
- cancelExportJob(id);
+ const job = get().jobs.find((j) => j.id === id);
+ cancelExportJob(id, job ? exportBackend(job.residency) : undefined);
set((s) => ({
jobs: s.jobs.map((j) =>
j.id === id ? { ...j, status: "error", error: "Export canceled." } : j
@@ -124,18 +152,38 @@ export const useExports = create<ExportsState>((set, get) => ({
})),
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;
- }
- set((s) => ({
- jobs: list,
- dismissed: s.dismissed.filter((id) => list.some((j) => j.id === id)),
- }));
+ // One backend's feed, rows stamped with its residency; null on a hiccup so
+ // the caller keeps that backend's last good view.
+ const fetchFeed = async (backend: CutBackend): Promise<ExportJob[] | null> => {
+ try {
+ const res = await backend.fetch("/api/cut/export-jobs");
+ if (!res.ok) return null;
+ const list = (await res.json()) as ExportJob[];
+ return list.map((j) => ({ ...j, residency: backend.kind }));
+ } catch {
+ return null;
+ }
+ };
+ // Flag off: exactly the pre-seam behavior — the local feed only. Flag on,
+ // jobs of both residencies can run at once, so poll every plausible feed:
+ // local when an engine is actually reachable, cloud always.
+ const cloudOn = webModeEnabled();
+ const pollLocal = !cloudOn || engineOrigin() !== "" || servedFromEngine();
+ const [localRows, cloudRows] = await Promise.all([
+ pollLocal ? fetchFeed(localBackend) : Promise.resolve(null),
+ cloudOn ? fetchFeed(cloudBackend) : Promise.resolve(null),
+ ]);
+ set((s) => {
+ // A failed or skipped feed keeps its previous rows; only a fresh answer
+ // replaces that backend's slice.
+ const slice = (kind: CutMode, fresh: ExportJob[] | null) =>
+ fresh ?? s.jobs.filter((j) => j.residency === kind);
+ const jobs = [...slice("local", localRows), ...slice("cloud", cloudRows)];
+ return {
+ jobs,
+ dismissed: s.dismissed.filter((id) => jobs.some((j) => j.id === id)),
+ };
+ });
},
}));
diff --git a/site/src/cut/lib/genScene.ts b/site/src/cut/lib/genScene.ts
index 434f0248..e0894f2c 100644
--- a/site/src/cut/lib/genScene.ts
+++ b/site/src/cut/lib/genScene.ts
@@ -1,7 +1,7 @@
"use client";
import { create } from "zustand";
-import { apiFetch, apiJson } from "./api";
+import { apiFetch, apiJson } from "./backend";
import { useGenerate } from "./generate";
import { realSuite } from "./genvideo/adapters";
import { GEN_FPS, StoreEditorBridge } from "./genvideo/editorBridge";
diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.ts
index e2374355..c3ab68b0 100644
--- a/site/src/cut/lib/generate.ts
+++ b/site/src/cut/lib/generate.ts
@@ -2,7 +2,9 @@
import { useEffect } from "react";
import { create } from "zustand";
-import { apiFetch, apiJson } from "./api";
+import { getBackend, type CutBackend, type CutMode } from "./backend";
+import { cloudBackend } from "./backend/cloud";
+import { localBackend } from "./backend/local";
import type { AssetRef } from "./assetRef";
import { bytesFromBase64 } from "./bytes";
import { readThreadIds } from "./chatThreads";
@@ -10,12 +12,12 @@ import { composeGenPrompt, foldTextRefs } from "./composeGen";
import { stockAssetInDoc } from "./genvideo/docWriter";
import { cutAppBase } from "./hosts";
import { hostedPost } from "./hosted";
-import { enrichAsset, importFileToProject } from "./media";
+import { enrichAsset, importFileToProject, uploadProjectImage } from "./media";
import { refsToInlineImages, videoSafeInline, visualRefs, type InlineImage } from "./refMedia";
import { useGenNotify } from "./genNotify";
import { useImageGen } from "./imageGen";
import { useEditor } from "./store";
-import { mediaSlug, mediaUrl, type MediaAsset } from "./types";
+import { mediaSlug, type MediaAsset } from "./types";
import { videoModel } from "./videoModels";
import { walkLadder, type VideoAttempt } from "./videoLadder";
@@ -47,6 +49,10 @@ export interface GenerateJob {
* resumed caller re-adopts exactly its own in-flight job — never another
* shot's that happens to share a prompt. */
genKey?: string;
+ /** The backend the job started on. Landing work can outlive navigation into
+ * a project of the other residency, so every project write for this job pins
+ * here instead of reading the (rebound) global mode at land time. */
+ residency?: CutMode;
/** Which ladder rung landed the render (0-based index into the attempts) —
* how a caller knows whether its take rode an image anchor. */
rung?: number;
@@ -176,6 +182,11 @@ const VIDEO_DEADLINE_MS = 12 * 60_000;
const uid = () => crypto.randomUUID().slice(0, 8);
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+/** The backend a job's results land on: its pinned residency; jobs persisted
+ * before residency existed fall back to the active backend. */
+const jobBackend = (job: { residency?: CutMode }): CutBackend =>
+ job.residency === "cloud" ? cloudBackend : job.residency === "local" ? localBackend : getBackend();
+
/** Display name for the asset: the prompt, tidied and capped. */
const promptName = (prompt: string) => {
const line = prompt.trim().replace(/\s+/g, " ");
@@ -404,9 +415,9 @@ export const useGenerate = create<GenerateState>((set, get) => {
// store; a closed one records it in its persisted doc so nothing the render
// made is orphaned. Returns whether the OPEN project adopted it (badges and
// placement callbacks only make sense on screen).
- const adopt = (projectId: string, asset: MediaAsset): boolean => {
+ const adopt = (projectId: string, asset: MediaAsset, backend?: CutBackend): boolean => {
if (useEditor.getState().projectId !== projectId) {
- void stockAssetInDoc(projectId, asset).catch(() => {});
+ void stockAssetInDoc(projectId, asset, backend).catch(() => {});
return false;
}
useEditor.getState().addAsset(asset);
@@ -487,20 +498,22 @@ export const useGenerate = create<GenerateState>((set, get) => {
throw new Error("The provider returned no video.");
}
- const asset = await importFileToProject(job.projectId, file);
+ const backend = jobBackend(job);
+ const asset = await importFileToProject(job.projectId, file, backend);
if (!asset) throw new Error("Could not import the generated video.");
// The owner may have been deleted during the import (the file write is a
// round trip): drop the file we just wrote rather than leave it orphaned.
if (aborted()) {
- void apiFetch(
- `/api/cut/projects/${job.projectId}/media/${encodeURIComponent(asset.fileName)}`,
- { method: "DELETE" }
- ).catch(() => {});
+ void backend
+ .fetch(`/api/cut/projects/${job.projectId}/media/${encodeURIComponent(asset.fileName)}`, {
+ method: "DELETE",
+ })
+ .catch(() => {});
return;
}
asset.name = promptName(job.prompt);
applyOwnership(asset, job.chatId);
- if (adopt(job.projectId, asset)) {
+ if (adopt(job.projectId, asset, backend)) {
if (!job.chatId) useGenNotify.getState().landed("video", asset.id);
onDone?.(asset);
}
@@ -537,6 +550,7 @@ export const useGenerate = create<GenerateState>((set, get) => {
},
generateImage: (projectId, prompt, opts) => {
+ const backend = getBackend(); // pinned: the render outlives navigation
const job: GenerateJob = {
id: uid(),
projectId,
@@ -544,6 +558,7 @@ export const useGenerate = create<GenerateState>((set, get) => {
prompt,
startedAt: Date.now(),
status: "running",
+ residency: backend.kind,
...(opts?.chatId ? { chatId: opts.chatId } : {}),
};
set((s) => ({ jobs: [job, ...s.jobs] }));
@@ -573,38 +588,33 @@ export const useGenerate = create<GenerateState>((set, get) => {
const out = gen.outputs.find((o) => o.dataBase64);
if (!out?.dataBase64) throw new Error("The provider returned no image.");
- const form = new FormData();
- form.append(
- "file",
+ // Mark it generated so it surfaces in the generate panel; a stock
+ // image imported from a tile sends no origin (plain import).
+ const asset = await uploadProjectImage(
+ projectId,
new Blob([bytesFromBase64(out.dataBase64)], {
type: out.contentType ?? "image/png",
}),
- out.filename ?? "image.png"
+ out.filename ?? "image.png",
+ {
+ name: promptName(prompt),
+ origin: "generated",
+ failMessage: "Could not add the image to the project.",
+ backend,
+ }
);
- form.append("name", promptName(prompt));
- // Mark it generated so it surfaces in the generate panel; a stock
- // image imported from a tile sends no origin (plain import).
- form.append("origin", "generated");
- const baked = await apiFetch(`/api/cut/projects/${projectId}/image`, {
- method: "POST",
- body: form,
- });
- const body = await apiJson<MediaAsset>(baked);
- if (!baked.ok || !body.fileName) {
- throw new Error(body.error ?? "Could not add the image to the project.");
- }
- const asset: MediaAsset = { ...body, url: mediaUrl(projectId, body.fileName) };
// Owner deleted while the image rendered (cancelForOwner dropped the
// job): drop the baked file instead of adopting orphaned media.
if (cancelledJobs.has(job.id) || !get().jobs.some((j) => j.id === job.id)) {
- void apiFetch(
- `/api/cut/projects/${projectId}/media/${encodeURIComponent(body.fileName)}`,
- { method: "DELETE" }
- ).catch(() => {});
+ void backend
+ .fetch(`/api/cut/projects/${projectId}/media/${encodeURIComponent(asset.fileName)}`, {
+ method: "DELETE",
+ })
+ .catch(() => {});
return settled(job.id, job);
}
applyOwnership(asset, opts?.chatId);
- if (adopt(projectId, asset) && !opts?.chatId) {
+ if (adopt(projectId, asset, backend) && !opts?.chatId) {
useGenNotify.getState().landed("image", asset.id);
}
update(job.id, { status: "done", assetId: asset.id });
@@ -632,6 +642,7 @@ export const useGenerate = create<GenerateState>((set, get) => {
prompt: attempts[0]?.prompt ?? "",
startedAt: Date.now(),
status: "running",
+ residency: getBackend().kind, // pinned: the render outlives navigation
...(jobOpts?.chatId ? { chatId: jobOpts.chatId } : {}),
...(jobOpts?.genKey ? { genKey: jobOpts.genKey } : {}),
};
diff --git a/site/src/cut/lib/genvideo/docWriter.ts b/site/src/cut/lib/genvideo/docWriter.ts
index 918ece85..293944a5 100644
--- a/site/src/cut/lib/genvideo/docWriter.ts
+++ b/site/src/cut/lib/genvideo/docWriter.ts
@@ -14,7 +14,7 @@
* the doc is just the other end of the same contract.
*/
-import { apiFetch, apiJson } from "../api";
+import { apiFetch, apiJson, getBackend, type CutBackend } from "../backend";
import { storedAssets, useEditor } from "../store";
import { mediaUrl, SPEED_MIN } from "../types";
import type { AudioClip, MediaAsset, ProjectDoc, VideoClip } from "../types";
@@ -29,15 +29,18 @@ const chains = new Map<string, Promise<void>>();
* caller; the chain itself always continues. */
export function withProjectDoc(
projectId: string,
- mutate: (doc: ProjectDoc) => void
+ mutate: (doc: ProjectDoc) => void,
+ // Background writes can outlive navigation into a project of the other
+ // residency; callers that know their backend pin it here.
+ backend: CutBackend = getBackend()
): Promise<void> {
const prev = chains.get(projectId) ?? Promise.resolve();
const next = prev.then(async () => {
- const res = await apiFetch(`/api/cut/projects/${projectId}`);
+ const res = await backend.fetch(`/api/cut/projects/${projectId}`);
const doc = await apiJson<ProjectDoc>(res);
if (!res.ok) throw new Error(doc?.error ?? "Could not read the project.");
mutate(doc);
- const put = await apiFetch(`/api/cut/projects/${projectId}`, {
+ const put = await backend.fetch(`/api/cut/projects/${projectId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(doc),
@@ -75,12 +78,20 @@ export async function projectWriteMode(projectId: string): Promise<"store" | "do
/** Register a run-created asset in a closed project's doc (the open-project
* path stocks the store instead and autosave persists it). Idempotent. */
-export function stockAssetInDoc(projectId: string, asset: MediaAsset): Promise<void> {
- return withProjectDoc(projectId, (doc) => {
- if (!doc.assets.some((a) => a.id === asset.id)) {
- doc.assets.push(storedAssets([asset])[0]);
- }
- });
+export function stockAssetInDoc(
+ projectId: string,
+ asset: MediaAsset,
+ backend?: CutBackend
+): Promise<void> {
+ return withProjectDoc(
+ projectId,
+ (doc) => {
+ if (!doc.assets.some((a) => a.id === asset.id)) {
+ doc.assets.push(storedAssets([asset])[0]);
+ }
+ },
+ backend
+ );
}
/** A run's asset by id, wherever the user is: the live store when the run's
diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.ts
index d48461f3..a8fbfb5e 100644
--- a/site/src/cut/lib/library.ts
+++ b/site/src/cut/lib/library.ts
@@ -1,7 +1,7 @@
"use client";
-import { apiFetch, apiJson, apiUrl } from "./api";
-import { enrichAsset } from "./media";
+import { apiFetch, apiJson, apiUrl, getBackend } from "./backend";
+import { enrichAsset, presignedUpload, probeFileMeta } from "./media";
import { useEditor } from "./store";
import type { LibraryTemplate, MediaAsset, TemplateMedia, TemplateSaveInput } from "./types";
import { IMAGE_CLIP_SECONDS, mediaUrl } from "./types";
@@ -94,6 +94,27 @@ export async function moveLibraryItem(id: string, folderId: string | null): Prom
}
export async function uploadToLibrary(file: File): Promise<LibraryAsset> {
+ if (getBackend().kind === "cloud") {
+ // Presign -> direct R2 PUT -> complete, with the media probed here — the
+ // cloud can't cheaply probe an R2 object the way the engine probes disk.
+ // A file this browser can't decode would land as a zero-length asset it
+ // also couldn't preview, so reject it before any bytes go up.
+ const meta = await probeFileMeta(file).catch(() => null);
+ if (!meta || (meta.type !== "image" && !(meta.duration > 0))) {
+ throw new Error(
+ "This file can't be read in this browser, so it can't go in the cloud library. Import it in the Mac app instead."
+ );
+ }
+ const key = await presignedUpload("/api/cut/library/presign", file, file.name);
+ const res = await apiFetch("/api/cut/library/complete", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ key, meta: { name: file.name, ...meta } }),
+ });
+ const body = await apiJson<LibraryAsset>(res);
+ if (!res.ok) throw new Error(body.error ?? "Upload failed.");
+ return body;
+ }
const form = new FormData();
form.append("file", file, file.name);
const res = await apiFetch("/api/cut/library", { method: "POST", body: form });
diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.ts
index 549bae1a..b240b8ca 100644
--- a/site/src/cut/lib/media.ts
+++ b/site/src/cut/lib/media.ts
@@ -1,6 +1,8 @@
"use client";
-import { apiFetch, apiJson } from "./api";
+import { apiFetch, apiJson, getBackend, type CutBackend } from "./backend";
+import { quotaErrorMessage } from "./backend/cloud";
+import { encodeWav } from "./cloudTranscribe";
import { useEditor } from "./store";
import type { AssetType, AudioClip, MediaAsset, ProjectSummary, StoredAsset, VideoClip } from "./types";
import { IMAGE_CLIP_SECONDS, mediaUrl } from "./types";
@@ -92,11 +94,159 @@ export function isTextFile(file: File) {
return file.type.startsWith("text/") || /\.(txt|md|markdown|srt|vtt|csv|json)$/i.test(file.name);
}
+/** Presign a direct-to-R2 upload, PUT the bytes, and return the object key
+ * for the follow-up complete call. Shared by project media, the library, and
+ * export overlays; cloud backend only. */
+export async function presignedUpload(
+ presignPath: string,
+ file: Blob,
+ name: string,
+ backend: CutBackend = getBackend()
+): Promise<string> {
+ const mime = file.type || "application/octet-stream";
+ const res = await backend.fetch(presignPath, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ fileName: name, mime, bytes: file.size }),
+ });
+ const body = await apiJson<{ key?: string; url?: string }>(res);
+ if (!res.ok || !body.key || !body.url) {
+ throw new Error(quotaErrorMessage(res.status, body) ?? body.error ?? "Upload failed.");
+ }
+ await putSigned(body.url, file, mime);
+ return body.key;
+}
+
+/** PUT a blob to a presigned R2 URL. */
+export async function putSigned(url: string, file: Blob, mime?: string) {
+ const put = await fetch(url, {
+ method: "PUT",
+ headers: { "Content-Type": mime ?? (file.type || "application/octet-stream") },
+ body: file,
+ });
+ if (!put.ok) throw new Error("Upload failed.");
+}
+
+/** Upload raw media bytes into a project. Local: the engine's multipart POST,
+ * byte-identical to the pre-seam request. Cloud: presign -> direct R2 PUT ->
+ * complete. Returns the stored (deduped) file name. */
+export function uploadProjectMedia(projectId: string, file: Blob, name: string): Promise<string> {
+ return uploadProjectMediaTo(getBackend(), projectId, file, name);
+}
+
+/** `uploadProjectMedia` against an explicit backend — cross-residency copies
+ * upload to a backend that is not the globally bound one. */
+export async function uploadProjectMediaTo(
+ backend: CutBackend,
+ projectId: string,
+ file: Blob,
+ name: string
+): Promise<string> {
+ if (backend.kind !== "cloud") {
+ const form = new FormData();
+ form.append("file", file, name);
+ const res = await backend.fetch(`/api/cut/projects/${projectId}/media`, {
+ method: "POST",
+ body: form,
+ });
+ const body = await apiJson<{ fileName?: string }>(res);
+ if (!res.ok || !body.fileName) throw new Error(body.error ?? "Upload failed.");
+ return body.fileName;
+ }
+ const key = await presignedUpload(
+ `/api/cut/projects/${projectId}/media/presign`,
+ file,
+ name,
+ backend
+ );
+ const res = await backend.fetch(`/api/cut/projects/${projectId}/media/complete`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ key }),
+ });
+ const body = await apiJson<{ fileName?: string }>(res);
+ if (!res.ok || !body.fileName) throw new Error(body.error ?? "Upload failed.");
+ return body.fileName;
+}
+
+// The cloud /image mirror only takes inline multipart bodies below ~3.5MB;
+// larger images ride the presign path.
+const IMAGE_INLINE_MAX = 3 * 1024 * 1024;
+
+/** Store an image blob as a first-class project image asset. Local (and small
+ * cloud payloads): the engine's /image multipart route, byte-identical to the
+ * pre-seam request. Large cloud payloads: presign -> R2 PUT -> complete, with
+ * the dimensions probed here instead of by the server. */
+export async function uploadProjectImage(
+ projectId: string,
+ file: Blob,
+ fileName: string,
+ opts?: { name?: string; origin?: "generated"; failMessage?: string; backend?: CutBackend }
+): Promise<MediaAsset> {
+ // Callers whose work outlives navigation (finishing AI generations) pin the
+ // backend they started on; everyone else rides the active one.
+ const backend = opts?.backend ?? getBackend();
+ const failMessage = opts?.failMessage ?? "Could not add the image.";
+ if (backend.kind !== "cloud" || file.size < IMAGE_INLINE_MAX) {
+ const form = new FormData();
+ form.append("file", file, fileName);
+ if (opts?.name !== undefined) form.append("name", opts.name);
+ if (opts?.origin) form.append("origin", opts.origin);
+ const res = await backend.fetch(`/api/cut/projects/${projectId}/image`, {
+ method: "POST",
+ body: form,
+ });
+ const body = await apiJson<MediaAsset>(res);
+ if (!res.ok || !body.fileName) throw new Error(body.error ?? failMessage);
+ return { ...body, url: mediaUrl(projectId, body.fileName) };
+ }
+ const stored = await uploadProjectMediaTo(backend, projectId, file, fileName);
+ const url = mediaUrl(projectId, stored);
+ const dims = await loadImageMeta(url);
+ return {
+ id: uid(),
+ type: "image",
+ name: opts?.name?.trim() || fileName,
+ fileName: stored,
+ duration: 0,
+ width: dims.width,
+ height: dims.height,
+ ...(opts?.origin ? { origin: opts.origin } : {}),
+ url,
+ };
+}
+
+/** Probe a media file's kind/duration/dimensions in the browser via an object
+ * URL — for backends that can't probe server-side (cloud library complete). */
+export async function probeFileMeta(file: File): Promise<{
+ type: AssetType;
+ duration: number;
+ width?: number;
+ height?: number;
+}> {
+ const url = URL.createObjectURL(file);
+ try {
+ if (isImageFile(file) && !isVideoFile(file) && !isAudioFile(file)) {
+ const dims = await loadImageMeta(url);
+ return { type: "image", duration: 0, width: dims.width, height: dims.height };
+ }
+ if (isAudioFile(file) && !isVideoFile(file)) {
+ return { type: "audio", duration: await loadAudioDuration(url).catch(() => 0) };
+ }
+ const v = await loadVideoMeta(url);
+ if (v.videoWidth === 0) return { type: "audio", duration: v.duration };
+ return { type: "video", duration: v.duration, width: v.videoWidth, height: v.videoHeight };
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+}
+
/** Upload a raw file into the project folder, probe it, and return the asset.
* Thumbnails/waveform are filled in asynchronously via `enrichAsset`. */
export async function importFileToProject(
projectId: string,
- file: File
+ file: File,
+ backend: CutBackend = getBackend()
): Promise<MediaAsset | null> {
// MIME wins over extension: recordings are .webm for both video and audio.
const type: AssetType | null = file.type.startsWith("video/")
@@ -114,19 +264,12 @@ export async function importFileToProject(
: null;
if (!type) return null;
- const form = new FormData();
- form.append("file", file, file.name);
- const res = await apiFetch(`/api/cut/projects/${projectId}/media`, {
- method: "POST",
- body: form,
- });
- const body = await apiJson<{ fileName?: string }>(res);
- if (!res.ok || !body.fileName) throw new Error(body.error ?? "Upload failed.");
+ const fileName = await uploadProjectMediaTo(backend, projectId, file, file.name);
- const url = mediaUrl(projectId, body.fileName);
+ const url = mediaUrl(projectId, fileName);
const asset: MediaAsset = {
id: uid(),
- fileName: body.fileName,
+ fileName,
name: file.name,
type,
duration: 0,
@@ -185,18 +328,12 @@ export async function importImage(
const dl = await fetch(image.url);
if (!dl.ok) throw new Error("Could not read the image.");
const blob = await dl.blob();
- const form = new FormData();
- form.append("file", blob, image.url.split("/").pop() || "image.png");
- form.append("name", image.name);
- const res = await apiFetch(`/api/cut/projects/${projectId}/image`, {
- method: "POST",
- body: form,
+ const body = await uploadProjectImage(projectId, blob, image.url.split("/").pop() || "image.png", {
+ name: image.name,
});
- const body = await apiJson<MediaAsset>(res);
- if (!res.ok || !body.fileName) throw new Error(body.error ?? "Could not add the image.");
// A stock image lands on the timeline where the caller places it, not in the
// Media panel — tag it so it stays out.
- const asset: MediaAsset = { ...body, url: mediaUrl(projectId, body.fileName), origin: "stock" };
+ const asset: MediaAsset = { ...body, origin: "stock" };
useEditor.getState().addAsset(asset);
void enrichAsset(asset);
return asset;
@@ -256,12 +393,23 @@ export async function importUrlMedia(
projectId: string,
url: string
): Promise<{ assets: MediaAsset[]; text?: string }> {
- const res = await apiFetch(`/api/cut/projects/${projectId}/import-url`, {
+ // Pinned at start: the download can outlast navigation into a project of
+ // the other residency, and every poll must hit the backend the job started on.
+ const backend = getBackend();
+ const res = await backend.fetch(`/api/cut/projects/${projectId}/import-url`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url }),
});
- const body = await apiJson<{ files?: { fileName: string; title: string }[]; text?: string }>(res);
+ let body: { files?: { fileName: string; title: string }[]; text?: string; error?: string };
+ if (backend.kind === "cloud") {
+ // The cloud route is async: it answers {jobId} and a worker does the fetch.
+ const started = await apiJson<{ jobId?: string }>(res);
+ if (!res.ok || !started.jobId) throw new Error(started.error ?? "Could not import that URL.");
+ body = await pollImportUrlJob(started.jobId, backend);
+ } else {
+ body = await apiJson<{ files?: { fileName: string; title: string }[]; text?: string }>(res);
+ }
if (!res.ok || !body.files?.length) throw new Error(body.error ?? "Could not import that URL.");
const assets: MediaAsset[] = [];
for (const f of body.files) {
@@ -273,6 +421,42 @@ export async function importUrlMedia(
return { assets, text: body.text };
}
+/** Poll a cloud import-url job to completion (2s cadence, ~10 min cap) and
+ * return the engine-shaped {files, text} result. Fails only when the job
+ * itself says so — state "error", or the job gone (404) — or after several
+ * consecutive failed polls; a single dropped request keeps polling. */
+async function pollImportUrlJob(
+ jobId: string,
+ backend: CutBackend
+): Promise<{ files?: { fileName: string; title: string }[]; text?: string }> {
+ const deadline = Date.now() + 10 * 60 * 1000;
+ const MAX_STRIKES = 6;
+ let strikes = 0;
+ for (;;) {
+ if (Date.now() > deadline) throw new Error("Could not import that URL.");
+ await new Promise((r) => setTimeout(r, 2000));
+ let res: Response | null = null;
+ try {
+ res = await backend.fetch(`/api/cut/jobs/${jobId}`);
+ } catch {
+ // Network blip — a strike, counted below.
+ }
+ // The create call returned this job's id, so a 404 means it's gone.
+ if (res?.status === 404) throw new Error("Could not import that URL.");
+ if (!res?.ok) {
+ if (++strikes >= MAX_STRIKES) throw new Error("Could not import that URL.");
+ continue;
+ }
+ strikes = 0;
+ const job = await apiJson<{
+ state?: string;
+ result?: { files?: { fileName: string; title: string }[]; text?: string };
+ }>(res);
+ if (job.state === "error") throw new Error(job.error ?? "Could not import that URL.");
+ if (job.state === "done") return job.result ?? {};
+ }
+}
+
/** Build a runtime asset for a media file the engine already wrote into the
* project folder (freeze frames, AI generations, URL imports) — probe
* metadata, no upload. */
@@ -308,6 +492,234 @@ export async function assetFromProjectFile(
return asset;
}
+/** Cloud twin of the engine's freeze route: grab the source frame in the
+ * browser (seek + canvas at native resolution), store it as a PNG project
+ * image, and return the same asset shape the engine's freeze response has.
+ * `duration` (seconds) rides back on the asset so the caller can size the
+ * placed clip like the engine's baked still video; the stored image itself
+ * has no intrinsic length. */
+export async function captureFreezeFrame(
+ projectId: string,
+ sourceUrl: string,
+ srcTime: number,
+ duration = 0
+): Promise<MediaAsset> {
+ const v = await loadVideoMeta(sourceUrl);
+ await seekTo(v, Math.max(0, srcTime));
+ const canvas = document.createElement("canvas");
+ canvas.width = v.videoWidth;
+ canvas.height = v.videoHeight;
+ canvas.getContext("2d")!.drawImage(v, 0, 0);
+ v.removeAttribute("src");
+ v.load();
+ const blob = await new Promise<Blob | null>((r) => canvas.toBlob(r, "image/png"));
+ if (!blob) throw new Error("Could not render the freeze frame.");
+ const d = new Date();
+ const pad = (n: number) => String(n).padStart(2, "0");
+ const fileName = `freeze-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}-${uid().slice(0, 4)}.png`;
+ const asset = await uploadProjectImage(projectId, blob, fileName, {
+ failMessage: "Could not render the freeze frame.",
+ });
+ return duration > 0 ? { ...asset, duration } : asset;
+}
+
+const round2 = (n: number) => Math.round(n * 100) / 100;
+
+/** Cloud twin of the engine's silence route (ffmpeg silencedetect): decode the
+ * source's audio and scan 20ms RMS windows against the same dB threshold and
+ * minimum-duration rules. Times are absolute source seconds. */
+export async function detectSilenceClientSide(
+ sourceUrl: string,
+ opts: { from: number; to?: number; thresholdDb: number; minSilence: number }
+): Promise<{ start: number; end: number; duration: number }[]> {
+ const audio = await decodeAudio(sourceUrl);
+ if (!audio) throw new Error("This file has no audio track.");
+ const to = Math.min(opts.to ?? audio.duration, audio.duration);
+ const from = Math.max(0, Math.min(opts.from, to));
+ if (!(to > from)) return [];
+ const rate = audio.sampleRate;
+ const win = Math.max(1, Math.round(rate * 0.02));
+ const threshold = Math.pow(10, opts.thresholdDb / 20);
+ const channels = Array.from({ length: audio.numberOfChannels }, (_, c) =>
+ audio.getChannelData(c)
+ );
+ const first = Math.floor(from * rate);
+ const last = Math.min(audio.length, Math.ceil(to * rate));
+ const silences: { start: number; end: number; duration: number }[] = [];
+ let open: number | null = null;
+ const close = (endT: number) => {
+ if (open !== null && endT - open >= opts.minSilence) {
+ const start = round2(Math.max(from, open));
+ const end = round2(Math.min(to, endT));
+ if (end > start) silences.push({ start, end, duration: round2(end - start) });
+ }
+ open = null;
+ };
+ for (let s = first; s < last; s += win) {
+ const e = Math.min(last, s + win);
+ let sum = 0;
+ for (const ch of channels) {
+ for (let i = s; i < e; i++) sum += ch[i] * ch[i];
+ }
+ const rms = Math.sqrt(sum / ((e - s) * channels.length));
+ if (rms < threshold) {
+ if (open === null) open = s / rate;
+ } else {
+ close(s / rate);
+ }
+ }
+ close(to);
+ return silences;
+}
+
+/** Cloud twin of the engine's audio-extract route: render a span of the
+ * source's audio to 16 kHz mono WAV in the browser, for the AI to hear
+ * inline. An empty `to` runs to the end. */
+export async function renderAudioSpanWav(
+ sourceUrl: string,
+ from: number,
+ to: number | undefined
+): Promise<Blob> {
+ const audio = await decodeAudio(sourceUrl);
+ if (!audio) throw new Error("This file has no audio track.");
+ const end = Math.min(to ?? audio.duration, audio.duration);
+ const start = Math.max(0, Math.min(from, end));
+ const dur = end - start;
+ if (!(dur > 0)) throw new Error("from/to describe an empty range.");
+ const rate = 16000; // encodeWav's fixed sample rate
+ const ctx = new OfflineAudioContext(1, Math.max(1, Math.ceil(dur * rate)), rate);
+ const src = ctx.createBufferSource();
+ src.buffer = audio;
+ src.connect(ctx.destination);
+ src.start(0, start, dur);
+ return encodeWav((await ctx.startRendering()).getChannelData(0));
+}
+
+// The engine's contact-sheet geometry (server/frames.ts), mirrored exactly so
+// the tool's stampSheet lands each cell's time stamp in the same place in
+// both modes.
+const SHEET_GRID = 3; // cells per row and column
+const SHEET_CELL = 480; // cell long side, px
+const SHEET_GAP = 4; // tile margin and padding, px
+const SHEET_MAX = 4; // sheets per call
+const SHEET_QUALITY = 0.8; // jpeg encode
+
+export interface WatchSheets {
+ sheets: { image: string; frames: { t: number }[] }[];
+ layout: { grid: number; margin: number; padding: number };
+ sceneChanges: number[];
+ coveredTo: number;
+ truncated: boolean;
+}
+
+const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));
+
+// The engine scales with ffmpeg's scale=480:-2, which rounds the short side
+// to even; mirror it so cell geometry matches to the pixel.
+const cellDims = (w: number, h: number): [number, number] =>
+ w >= h
+ ? [SHEET_CELL, Math.max(2, 2 * Math.round((SHEET_CELL * h) / w / 2))]
+ : [Math.max(2, 2 * Math.round((SHEET_CELL * w) / h / 2)), SHEET_CELL];
+
+/** Cloud twin of the engine's watch route for a still image: one downscaled
+ * cell, no time axis. */
+export async function makeStillSheetClientSide(sourceUrl: string): Promise<WatchSheets> {
+ const img = new Image();
+ img.crossOrigin = "anonymous";
+ await new Promise<void>((resolve, reject) => {
+ img.onload = () => resolve();
+ img.onerror = () => reject(new Error("Could not read the image."));
+ img.src = sourceUrl;
+ });
+ if (img.naturalWidth === 0 || img.naturalHeight === 0)
+ throw new Error("Could not read the image.");
+ const [w, h] = cellDims(img.naturalWidth, img.naturalHeight);
+ const canvas = document.createElement("canvas");
+ canvas.width = w;
+ canvas.height = h;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) throw new Error("Could not read the image.");
+ ctx.imageSmoothingQuality = "high";
+ ctx.drawImage(img, 0, 0, w, h);
+ return {
+ sheets: [{ image: canvas.toDataURL("image/jpeg", SHEET_QUALITY), frames: [{ t: 0 }] }],
+ layout: { grid: 1, margin: 0, padding: 0 },
+ sceneChanges: [],
+ coveredTo: 0,
+ truncated: false,
+ };
+}
+
+/** Cloud twin of the engine's watch route: seek the source in the browser and
+ * tile downscaled frames into timestamped contact sheets, with the route's
+ * defaults, clamps, and per-call caps. Frames land on the steady interval
+ * only — scene detection needs a decoder — so sceneChanges stays empty and
+ * scene fields are omitted. */
+export async function makeContactSheetsClientSide(
+ sourceUrl: string,
+ opts: { from: number; to?: number; interval?: number }
+): Promise<WatchSheets> {
+ const v = await loadVideoMeta(sourceUrl);
+ try {
+ if (v.videoWidth === 0) throw new Error("Could not sample the video.");
+ const from = Math.max(0, opts.from);
+ const wanted = opts.to ?? v.duration;
+ if (opts.to === undefined && !(wanted > 0))
+ throw new Error("Could not read the media duration — pass to (seconds).");
+ if (!(wanted > from)) throw new Error("from/to describe an empty range.");
+ const to = Math.min(wanted, from + 600); // bound the work per call; callers resume from coveredTo
+ const interval =
+ opts.interval !== undefined
+ ? clamp(opts.interval, 0.5, 30)
+ : clamp((to - from) / 32, 2, 30);
+
+ const perSheet = SHEET_GRID * SHEET_GRID;
+ const times: number[] = [];
+ for (let t = from; t < to && times.length < SHEET_MAX * perSheet; t += interval)
+ times.push(round2(t));
+
+ const [cw, ch] = cellDims(v.videoWidth, v.videoHeight);
+ const sheetW = 2 * SHEET_GAP + SHEET_GRID * cw + (SHEET_GRID - 1) * SHEET_GAP;
+ const sheetH = 2 * SHEET_GAP + SHEET_GRID * ch + (SHEET_GRID - 1) * SHEET_GAP;
+ const sheets: WatchSheets["sheets"] = [];
+ for (let i = 0; i < times.length; i += perSheet) {
+ const chunk = times.slice(i, i + perSheet);
+ const canvas = document.createElement("canvas");
+ canvas.width = sheetW;
+ canvas.height = sheetH;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) throw new Error("Could not sample the video.");
+ ctx.fillStyle = "#000";
+ ctx.fillRect(0, 0, sheetW, sheetH);
+ ctx.imageSmoothingQuality = "high";
+ for (let j = 0; j < chunk.length; j++) {
+ await seekTo(v, chunk[j]);
+ const x = SHEET_GAP + (j % SHEET_GRID) * (cw + SHEET_GAP);
+ const y = SHEET_GAP + Math.floor(j / SHEET_GRID) * (ch + SHEET_GAP);
+ ctx.drawImage(v, x, y, cw, ch);
+ }
+ sheets.push({
+ image: canvas.toDataURL("image/jpeg", SHEET_QUALITY),
+ frames: chunk.map((t) => ({ t })),
+ });
+ }
+ const lastT = times.length > 0 ? times[times.length - 1] : from;
+ const capped = times.length >= SHEET_MAX * perSheet && lastT < to - interval;
+ // The per-call span bound is itself truncation — the caller asked for more.
+ const truncated = capped || to < wanted;
+ return {
+ sheets,
+ layout: { grid: SHEET_GRID, margin: SHEET_GAP, padding: SHEET_GAP },
+ sceneChanges: [],
+ coveredTo: capped ? lastT : to,
+ truncated,
+ };
+ } finally {
+ v.removeAttribute("src");
+ v.load();
+ }
+}
+
/** Generate filmstrip thumbnails / waveform peaks and merge them into the
* store. Safe to call repeatedly; skips assets that are already enriched. */
export async function enrichAsset(asset: MediaAsset) {
@@ -318,7 +730,7 @@ export async function enrichAsset(asset: MediaAsset) {
useEditor.getState().updateAsset(asset.id, { thumbs: [asset.url], thumbStep: IMAGE_CLIP_SECONDS });
}
} else if (asset.type === "video" && !asset.thumbs?.length) {
- const key = stripCacheKey(asset.url);
+ const key = stripCacheKey(useEditor.getState().projectId, asset.fileName);
const cached = await readCachedStrip(key, asset.duration);
if (cached) {
useEditor.getState().updateAsset(asset.id, { thumbs: cached.thumbs, thumbStep: cached.thumbStep });
@@ -393,7 +805,8 @@ export function loadAudioDuration(url: string): Promise<number> {
// on Retina (and when a tall timeline scales the row up).
const THUMB_H = 180;
-// Filmstrips persist in IndexedDB keyed by the media file's project path, so
+// Filmstrips persist in IndexedDB keyed by project + file name + thumbnail
+// geometry — not the URL, which churns on cloud signed-URL refreshes — so
// reopening a project paints clips from cache instead of re-seeking every
// video. Cache failures fall through to regeneration.
const STRIP_DB = "cut-filmstrips";
@@ -402,8 +815,8 @@ const STRIP_CAP = 500; // prune oldest beyond this many cached strips
type CachedStrip = { thumbs: string[]; thumbStep: number; duration: number; at: number };
-function stripCacheKey(url: string) {
- return new URL(url, window.location.href).pathname;
+function stripCacheKey(projectId: string | null, fileName: string) {
+ return `${projectId ?? ""}/${fileName}@${THUMB_H}`;
}
function openStripDb(): Promise<IDBDatabase> {
diff --git a/site/src/cut/lib/micTranscribe.ts b/site/src/cut/lib/micTranscribe.ts
index f6b9f81f..498b6b9a 100644
--- a/site/src/cut/lib/micTranscribe.ts
+++ b/site/src/cut/lib/micTranscribe.ts
@@ -1,12 +1,16 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
-import { apiFetch } from "./api";
+import { apiFetch, getBackend } from "./backend";
+import { cloudTranscribeRecording } from "./cloudTranscribe";
// Live dictation for the chat composer. The browser holds the mic permission,
// so it captures audio here and streams 16 kHz mono s16le PCM to the local
// engine, which runs it through Apple's on-device SpeechAnalyzer (see
// server/mic.ts + native/cut-stt.swift). The transcript never leaves the Mac.
+// On the cloud backend there is no engine: the mic records locally
+// (MediaRecorder) and one hosted transcription runs when the user confirms —
+// no live partials, so the composer shows "Listening…" while recording.
export type MicState = "idle" | "starting" | "recording" | "finishing";
@@ -52,6 +56,8 @@ export function useMicTranscription(onResult: (text: string) => void): MicContro
const [error, setError] = useState<string | null>(null);
const jobRef = useRef<string | null>(null);
+ const recorderRef = useRef<MediaRecorder | null>(null);
+ const recChunksRef = useRef<Blob[]>([]);
const streamRef = useRef<MediaStream | null>(null);
const ctxRef = useRef<AudioContext | null>(null);
const nodesRef = useRef<{ source: MediaStreamAudioSourceNode; processor: ScriptProcessorNode } | null>(null);
@@ -62,6 +68,20 @@ export function useMicTranscription(onResult: (text: string) => void): MicContro
const onResultRef = useRef(onResult);
onResultRef.current = onResult;
+ /** Stop and forget the cloud recorder (before its tracks stop). */
+ const discardRecorder = useCallback(() => {
+ const rec = recorderRef.current;
+ recorderRef.current = null;
+ recChunksRef.current = [];
+ if (rec && rec.state !== "inactive") {
+ try {
+ rec.stop();
+ } catch {
+ // Already stopping; nothing to discard.
+ }
+ }
+ }, []);
+
const teardownAudio = useCallback(() => {
if (feedTimer.current) clearInterval(feedTimer.current);
if (pollTimer.current) clearInterval(pollTimer.current);
@@ -119,6 +139,19 @@ export function useMicTranscription(onResult: (text: string) => void): MicContro
setError("Microphone access was blocked. Allow the microphone for this site, then try again.");
return;
}
+ if (getBackend().kind === "cloud") {
+ recChunksRef.current = [];
+ const rec = new MediaRecorder(media);
+ rec.ondataavailable = (e) => {
+ if (e.data.size > 0) recChunksRef.current.push(e.data);
+ };
+ rec.start(1000);
+ recorderRef.current = rec;
+ streamRef.current = media;
+ setStream(media);
+ setState("recording");
+ return;
+ }
try {
const res = await apiFetch("/api/cut/mic/start", {
method: "POST",
@@ -173,6 +206,31 @@ export function useMicTranscription(onResult: (text: string) => void): MicContro
}, [state, flush]);
const confirm = useCallback(async () => {
+ const rec = recorderRef.current;
+ if (rec) {
+ if (state !== "recording") return;
+ setState("finishing");
+ // Flush the recorder's tail, then transcribe the whole take in one go.
+ const blob = await new Promise<Blob>((resolve) => {
+ rec.onstop = () =>
+ resolve(new Blob(recChunksRef.current, { type: rec.mimeType || "audio/webm" }));
+ rec.stop();
+ });
+ recorderRef.current = null;
+ recChunksRef.current = [];
+ teardownAudio();
+ let text = "";
+ try {
+ text = await cloudTranscribeRecording(blob, navigator.language);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : "Transcription failed.");
+ }
+ setState("idle");
+ setPartial("");
+ const trimmed = text.trim();
+ if (trimmed) onResultRef.current(trimmed);
+ return;
+ }
const job = jobRef.current;
if (!job || state !== "recording") return;
setState("finishing");
@@ -206,20 +264,22 @@ export function useMicTranscription(onResult: (text: string) => void): MicContro
const job = jobRef.current;
jobRef.current = null;
if (job) void apiFetch(`/api/cut/mic/${job}/cancel`, { method: "POST" }).catch(() => {});
+ discardRecorder();
teardownAudio();
setState("idle");
setPartial("");
setError(null);
- }, [teardownAudio]);
+ }, [discardRecorder, teardownAudio]);
// Abandon a dictation if the composer unmounts mid-recording.
useEffect(() => {
return () => {
const job = jobRef.current;
if (job) void apiFetch(`/api/cut/mic/${job}/cancel`, { method: "POST" }).catch(() => {});
+ discardRecorder();
teardownAudio();
};
- }, [teardownAudio]);
+ }, [discardRecorder, teardownAudio]);
return { state, stream, partial, error, start, confirm, cancel };
}
diff --git a/site/src/cut/lib/nav.tsx b/site/src/cut/lib/nav.tsx
index 2b503992..4ef6a455 100644
--- a/site/src/cut/lib/nav.tsx
+++ b/site/src/cut/lib/nav.tsx
@@ -40,16 +40,19 @@ export function homeHref(base: string, tab: CutTab, folder?: string | null): str
/** Project editor URL that remembers the tab (and folder, when open) it was
* opened from. The default origin carries no query so the common URL stays
- * clean. */
+ * clean. Cloud-resident projects carry ?src=cloud so the editor binds the
+ * cloud backend before it loads; local links are unchanged. */
export function projectHref(
base: string,
id: string,
from: CutTab,
- folder?: string | null
+ folder?: string | null,
+ residency?: "local" | "cloud"
): string {
const params = new URLSearchParams();
if (from === "library") params.set("from", "library");
if (folder) params.set("folder", folder);
+ if (residency === "cloud") params.set("src", "cloud");
const qs = params.toString();
return `${base}/p/${id}${qs ? `?${qs}` : ""}`;
}
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 24e485c9..a0c9b384 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -25,7 +25,9 @@ import type {
} from "./types";
import type { VideoProject } from "./genvideo/types";
import { fillSlot } from "./genvideo/fillSlot";
-import { apiFetch, apiJson } from "./api";
+import { apiFetch, apiJson, getBackend } from "./backend";
+import { fetchSignedMediaUrls } from "./backend/cloud";
+import { cloudTranscribeSpec, type CloudTranscribeSpec } from "./cloudTranscribe";
import { trackLocale } from "./subtitles";
import { ANIM_STYLE_IDS, emptySubtitles, IMAGE_CLIP_SECONDS, LOOK_IDS, MAX_SUBTITLE_LANES, mediaUrl, migrateLegacyTransitions, SPEED_FLOOR, SPEED_MIN, TRANSITION_MAX } from "./types";
import { readTextStyle } from "./textStyle";
@@ -608,6 +610,15 @@ export function rippleInsert(
* null when the user switches projects mid-run. Throws user-facing errors.
* Shared with the brief-to-video transcribe adapter. */
export async function runTranscription(projectId: string, spec: object): Promise<SubtitleCue[] | null> {
+ // The hosted backend has no transcription job runner: the browser renders
+ // the audible mix itself and calls the metered cloud route chunk by chunk.
+ if (getBackend().kind === "cloud") {
+ return cloudTranscribeSpec(
+ projectId,
+ spec as CloudTranscribeSpec,
+ () => useEditor.getState().projectId !== projectId
+ );
+ }
const res = await apiFetch(`/api/cut/projects/${projectId}/transcribe`, {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -801,6 +812,12 @@ export const useEditor = create<EditorState>((baseSet, get) => {
...a,
url: mediaUrl(id, a.fileName),
}));
+ // Cloud media rides signed R2 URLs, batch-minted once per load; the
+ // /media route's 302 stays the fallback for anything the mint misses.
+ if (getBackend().kind === "cloud") {
+ const signed = await fetchSignedMediaUrls(id, assets.map((a) => a.fileName));
+ for (const a of assets) a.url = signed.get(a.fileName) ?? a.url;
+ }
// Older docs stored video track 0 packed (array order implied the
// position); bake explicit starts in once so every clip is free-placed.
const legacy = (doc.clips as LegacyClip[]).some((c) => typeof c.start !== "number");
@@ -2197,6 +2214,10 @@ export const useEditor = create<EditorState>((baseSet, get) => {
generateVisualSubtitles: async () => {
const s = get();
if (!s.projectId || s.subtitleStatus === "running") return;
+ if (!getBackend().caps.captionAi) {
+ set({ subtitleStatus: "error", subtitleError: "Not available in cloud mode yet." });
+ return;
+ }
const projectId = s.projectId;
const spans = getClipSpans(s.clips, s.assets);
if (spans.length === 0) {
@@ -2258,6 +2279,10 @@ export const useEditor = create<EditorState>((baseSet, get) => {
generateCaptions: async (style) => {
const s = get();
if (!s.projectId || s.subtitleStatus === "running") return;
+ if (!getBackend().caps.captionAi) {
+ set({ subtitleStatus: "error", subtitleError: "Not available in cloud mode yet." });
+ return;
+ }
const lane = s.subtitleLane;
const laneOf = (c: SubtitleCue) => c.lane ?? 0;
// Need cues first — transcribe if the active track hasn't been captioned.
@@ -2322,6 +2347,10 @@ export const useEditor = create<EditorState>((baseSet, get) => {
const s = get();
const lane = s.subtitleLane;
if (!s.projectId || s.subtitleStatus === "running" || fromLane === lane) return;
+ if (!getBackend().caps.captionAi) {
+ set({ subtitleStatus: "error", subtitleError: "Not available in cloud mode yet." });
+ return;
+ }
const laneOf = (c: SubtitleCue) => c.lane ?? 0;
const source = s.subtitles.cues.filter((c) => laneOf(c) === fromLane);
if (source.length === 0) return;
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index 91177219..acc4ddd8 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -1,4 +1,4 @@
-import { apiUrl } from "./api";
+import { apiUrl } from "./backend";
import type { VideoProject } from "./genvideo/types";
export type AssetType = "video" | "audio" | "image";