Skip to content

Open source CapCut alternative.

TypeScript

feat(site): show both library shelves in one Cut listing

David Le1849c4bd6b98
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.md
index b52f1d77..7b33aefb 100644
--- a/docs/guides/cut/README.md
+++ b/docs/guides/cut/README.md
@@ -32,8 +32,12 @@ Web mode makes Cut usable in any browser on any OS with nothing installed. It sh
Every client call goes through a backend seam (`site/src/cut/lib/backend/`): the local driver is the engine transport unchanged, and the cloud driver rewrites the same paths to `/api/cut-cloud/*` with the session cookie. Residency is per project — the home screen lists "On this Mac" and "Cloud" sections, each served by its own driver, and opening a project binds the editor to that project's backend. Capability flags on the driver hide what a backend can't do, so components never feature-detect.
+The library is the exception, because it is a shelf rather than a place: it lists every residency the browser can reach at once — the Mac's when an engine has answered, the cloud's when web mode is on — as one listing, newest first, with a badge saying which shelf each item is on. So a cloud project can pull a clip off this Mac, and a local project can pull one out of the cloud. Each item's own shelf answers for it: previews, renames, and deletes go to the backend it came from, and folders belong to one shelf, so items file only into folders beside them. Adding to a project is the one crossing: on the project's own shelf the server copies the file without the bytes leaving it, and off it the browser carries them down and back up.
+
Cloud projects store their doc in Postgres (versioned; a stale autosave 409s and the editor reloads the newer copy) and media in R2: uploads go direct from the browser on presigned URLs (the hosted functions never see the bytes), playback streams on signed range URLs, and a flat per-user quota is enforced at presign time. That quota is visible rather than implicit: a free account editing a cloud project sees what it has used in the editor's top bar, and a presign rejected for space opens an upgrade offer wherever it happened instead of a bare error. The same slot carries the countdown when a subscription is set to cancel, and clicking it opens the billing portal.
+A dropped file does not wait for that upload. Because a presign claims the stored name before any bytes move, and the browser can read the file it was handed, an import is measured, named, and placed on the timeline in the same moment it is dropped — playing from the local copy, filmstrip and all — while the bytes go out behind the editor. The saved document is what keeps this honest: an import still uploading is left out of it, along with the clips that use it, so a tab closed mid-upload leaves nothing to reopen broken, and the asset and its clips join the document the moment the upload lands. Export waits on the same line, since a render reads the saved document.
+
Storage a subscription paid for outlives the subscription for a while: when Pro ends and the account still holds more than the free tier, it keeps everything for thirty days, warned in the editor and on the projects home. After that the daily sweep brings it back under the cap — least-recently-updated projects first, then the oldest library assets, stopping the moment it fits — so what survives is the recent work, and an account already under the cap is never touched.
A cloud project can be shared read-only, Google-Docs style: the editor's Share dialog invites specific emails (viewers sign in) or opens the link to anyone (no sign-in), and switches opt extra surfaces in — chat, media, AI generations, subtitles, details — on top of the always-shared preview and timeline. The share row's id is the link token, so revoking deletes the link. Viewers ride a third backend driver against `/api/cut-shared/<token>/*`, a deliberately public API surface (the one exception to session auth on the cloud side): the server resolves access per request, filters the doc to the shared surfaces before it leaves, and refuses media outside that filter, so hiding is enforced by the backend rather than the client. A public share's reads are cached at the edge for a lifetime that tracks how long the owner has been idle — a doc saved seconds ago is served near-live, one untouched for an hour is served from cache for minutes — and the same number is handed back as the viewer's poll interval, so a link a crowd opens costs a handful of origin requests rather than one per viewer per tick. A restricted share's reads depend on the viewer's session, so they are never cached. A shared project's media is served from Cloudflare's edge rather than presigned against R2's S3 endpoint, which nothing caches: a Worker holding a private bucket binding checks a short token the hosted API mints, then answers from cache keyed on the object alone. Dropping the token from the cache key is what makes the token affordable to keep short — every viewer and every re-mint share one cached copy — and a short token is what makes unsharing mean something, since a presigned URL is a bearer credential nothing can withdraw before it expires. Owner-side editing still presigns R2 directly, where the URLs are minted on fixed windows so a browser can reuse bytes across reloads. A shared link unfurls with the project's own card: the render worker derives a first-frame still and a five-second animation from the opening of the cut, the page's metadata points at them through a URL carrying the doc version, and a project with no card yet gets a drawn one. Viewers poll the doc version on an interval the server picks — shared views trail live edits, they don't stream them — and a "Copy project" action duplicates everything the share exposes — the filtered doc, its media, and the chat threads when chat is shared — server-side into the viewer's own account and quota. Copies queue rather than run in the request: each request writes a job row and publishes it to a Cloudflare Queue whose serial consumer executes one copy at a time, so a burst of copy requests can't stampede storage; the client polls the job for the outcome. An owner duplicating their own cloud project from the dashboard rides the same queue. Exports, hover-preview proxies, share cards, and URL imports run on the render worker — a container (`site/src/cut/worker/`) that claims job rows from Postgres, reuses the engine's exact ffmpeg pipeline against R2, and reports progress back through the rows the client polls. Transcription and mic dictation call a hosted, credit-metered route that has Gemini produce cue-level timestamps from browser-rendered audio chunks; word timings are interpolated within each cue. The assistant offers its Gemini models (which already run entirely in the page); the Claude/Codex CLI providers stay app-only because they are the user's local logins.
diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsx
index d9bfc318..e4dfdea6 100644
--- a/site/src/cut/components/LibraryView.tsx
+++ b/site/src/cut/components/LibraryView.tsx
@@ -4,8 +4,10 @@ import { useCallback, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useRouter, useSearchParams } from "next/navigation";
import {
+ Cloud,
FolderOpen,
FolderPlus,
+ Laptop,
Link as LinkIcon,
Loader2,
Plus,
@@ -50,6 +52,12 @@ import {
type LibraryAsset,
type LibraryData,
} from "@/cut/lib/library";
+import {
+ activeResidency,
+ availableResidencies,
+ RESIDENCY_LABEL,
+ type Residency,
+} from "@/cut/lib/residency";
import { TemplateCard } from "./TemplateCard";
import { homeHref, useCutBase } from "@/cut/lib/nav";
import { useRevealFlash } from "@/cut/lib/refReveal";
@@ -63,6 +71,23 @@ import { buildDragGhost, FolderCrumb, FolderShelf, Marquee } from "./desktopFold
// marquee-selected collection can be dropped onto a folder at once.
const LIBRARY_MOVE_MIME = "application/x-cut-library-move";
+/** Which shelf an item sits on, on its card. The library merges both, so the
+ * badge is how you tell a clip on this Mac from one in the cloud. */
+export function ShelfBadge({
+ 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 LibraryView() {
const router = useRouter();
const base = useCutBase();
@@ -95,26 +120,36 @@ export function LibraryView() {
const [fileOver, setFileOver] = useState(false);
const dragDepth = useRef(0);
- const renameTpl = async (id: string, name: string) => {
+ // Every mutation goes to the shelf its item sits on; only new items need a
+ // destination, and that is the folder they land in, or the bound backend.
+ const shelfOf = (id: string): Residency | null =>
+ all.find((a) => a.id === id)?.residency ??
+ templates.find((t) => t.id === id)?.residency ??
+ null;
+ const shelfForNew = (folderId: string | null) =>
+ (folderId ? folders.find((f) => f.id === folderId)?.residency : null) ?? activeResidency();
+
+ const renameTpl = async (r: Residency, id: string, name: string) => {
patch((d) => ({ ...d, templates: d.templates.map((t) => (t.id === id ? { ...t, name } : t)) }));
- await renameTemplate(id, name).catch(() => void reload());
+ await renameTemplate(r, id, name).catch(() => void reload());
};
- const removeTpl = async (id: string) => {
+ const removeTpl = async (r: Residency, id: string) => {
patch((d) => ({ ...d, templates: d.templates.filter((t) => t.id !== id) }));
- await deleteTemplate(id).catch(() => void reload());
+ await deleteTemplate(r, id).catch(() => void reload());
};
// Upload a batch into `folderId` (the open folder by default — folder tiles
// pass their own id when files are dropped straight onto them).
const upload = async (files: FileList | File[], folderId: string | null = openFolder) => {
const list = Array.from(files).filter(isMediaFile);
+ const residency = shelfForNew(folderId);
setUploading((n) => n + list.length);
for (const file of list) {
try {
- const asset = await uploadToLibrary(file);
+ const asset = await uploadToLibrary(file, residency);
if (folderId) {
- await moveLibraryItem(asset.id, folderId).catch(() => {});
+ await moveLibraryItem(residency, asset.id, folderId).catch(() => {});
asset.folderId = folderId;
}
patch((d) => ({ ...d, assets: [asset, ...d.assets] }));
@@ -131,11 +166,12 @@ export function LibraryView() {
if (!value || importing) return;
setImporting(true);
setUrlError(null);
+ const residency = shelfForNew(openFolder);
try {
- const imported = await importUrlToLibrary(value);
+ const imported = await importUrlToLibrary(value, residency);
if (openFolder) {
for (const asset of imported) {
- await moveLibraryItem(asset.id, openFolder).catch(() => {});
+ await moveLibraryItem(residency, asset.id, openFolder).catch(() => {});
asset.folderId = openFolder;
}
}
@@ -151,11 +187,11 @@ export function LibraryView() {
const remove = async () => {
if (!deleting) return;
- const id = deleting.id;
+ const { id, residency } = deleting;
setDeleting(null);
patch((d) => ({ ...d, assets: d.assets.filter((a) => a.id !== id) }));
try {
- await deleteFromLibrary(id);
+ await deleteFromLibrary(residency, id);
} catch {
void reload();
}
@@ -168,16 +204,25 @@ export function LibraryView() {
router.push(homeHref(base, "library", id));
};
+ // A folder belongs to one shelf, so a drag that spans both files only the
+ // items already on that folder's shelf; the rest stay where they are.
const moveItems = async (ids: string[], folderId: string | null) => {
- if (ids.length === 0) return;
- const idset = new Set(ids);
+ const target = folderId ? folders.find((f) => f.id === folderId)?.residency : null;
+ const moving = ids
+ .map((id) => ({ id, residency: shelfOf(id) }))
+ .filter((x): x is { id: string; residency: Residency } => !!x.residency)
+ .filter((x) => !target || x.residency === target);
+ if (moving.length === 0) return;
+ const idset = new Set(moving.map((x) => x.id));
patch((d) => ({
...d,
assets: d.assets.map((a) => (idset.has(a.id) ? { ...a, folderId } : a)),
templates: d.templates.map((t) => (idset.has(t.id) ? { ...t, folderId } : t)),
}));
setSelected(new Set());
- await Promise.all(ids.map((id) => moveLibraryItem(id, folderId))).catch(() => void reload());
+ await Promise.all(
+ moving.map((x) => moveLibraryItem(x.residency, x.id, folderId))
+ ).catch(() => void reload());
};
// Carry the current selection (or just this card) as a folder-move payload,
@@ -198,6 +243,7 @@ export function LibraryView() {
}
};
+ const bothShelves = availableResidencies().length > 1;
const shown = all.filter((a) => (a.folderId ?? null) === openFolder);
const shownTemplates = templates.filter((t) => (t.folderId ?? null) === openFolder);
const openFolderName = folders.find((f) => f.id === openFolder)?.name;
@@ -292,19 +338,27 @@ export function LibraryView() {
all.filter((a) => (a.folderId ?? null) === id).length +
templates.filter((t) => (t.folderId ?? null) === id).length,
})}
+ badgeOf={(id) => {
+ const r = folders.find((f) => f.id === id)?.residency;
+ return bothShelves && r ? <ShelfBadge residency={r} /> : null;
+ }}
onOpen={gotoFolder}
onCreate={async (name) => {
- const f = await createLibraryFolder(name);
+ const f = await createLibraryFolder(name, activeResidency());
patch((d) => ({ ...d, folders: [...d.folders, f] }));
}}
onRename={async (id, name) => {
+ const r = folders.find((f) => f.id === id)?.residency;
+ if (!r) return;
patch((d) => ({
...d,
folders: d.folders.map((f) => (f.id === id ? { ...f, name } : f)),
}));
- await renameLibraryFolder(id, name).catch(() => void reload());
+ await renameLibraryFolder(r, id, name).catch(() => void reload());
}}
onDelete={async (id) => {
+ const r = folders.find((f) => f.id === id)?.residency;
+ if (!r) return;
patch((d) => ({
folders: d.folders.filter((f) => f.id !== id),
assets: d.assets.map((a) => (a.folderId === id ? { ...a, folderId: null } : a)),
@@ -313,7 +367,7 @@ export function LibraryView() {
),
}));
if (openFolder === id) router.replace(homeHref(base, "library"));
- await deleteLibraryFolder(id).catch(() => void reload());
+ await deleteLibraryFolder(r, id).catch(() => void reload());
}}
onDropIds={(ids, fid) => void moveItems(ids, fid)}
onDropFiles={(files, fid) => void upload(files, fid)}
@@ -326,14 +380,14 @@ export function LibraryView() {
<TemplateCard
key={t.id}
template={t}
- mediaSrc={libraryMediaUrl}
- dragScope="library"
+ mediaSrc={(f) => libraryMediaUrl(f, t.residency)}
+ drag={{ scope: "library", template: t }}
onDragStartExtra={(e) => {
e.dataTransfer.setData(LIBRARY_MOVE_MIME, JSON.stringify([t.id]));
e.dataTransfer.effectAllowed = "copyMove";
}}
- onRename={(name) => void renameTpl(t.id, name)}
- onDelete={() => void removeTpl(t.id)}
+ onRename={(name) => void renameTpl(t.residency, t.id, name)}
+ onDelete={() => void removeTpl(t.residency, t.id)}
/>
))}
</div>
@@ -476,6 +530,9 @@ export function LibraryCard({
}) {
const videoRef = useRef<HTMLVideoElement>(null);
const { flash, attachReveal } = useRevealFlash("library", a.id);
+ // With one shelf reachable, every card is on it — the badge would say
+ // nothing.
+ const bothShelves = availableResidencies().length > 1;
// Each card is a real media element, so the source waits until the tile has
// been scrolled near: a large library would otherwise pull every file's
// metadata across the network the moment the page opened.
@@ -517,7 +574,7 @@ export function LibraryCard({
<video
crossOrigin={MEDIA_CORS}
ref={videoRef}
- src={`${libraryMediaUrl(a.fileName)}#t=${posterT}`}
+ src={`${libraryMediaUrl(a.fileName, a.residency)}#t=${posterT}`}
muted
loop
playsInline
@@ -527,10 +584,10 @@ export function LibraryCard({
)
) : a.type === "image" ? (
// eslint-disable-next-line @next/next/no-img-element -- library media file, not Next-optimizable
- <img crossOrigin={MEDIA_CORS} src={libraryMediaUrl(a.fileName)} alt={a.name} loading="lazy" className="size-full object-cover" />
+ <img crossOrigin={MEDIA_CORS} src={libraryMediaUrl(a.fileName, a.residency)} alt={a.name} loading="lazy" className="size-full object-cover" />
) : (
<AudioCardFace
- url={libraryMediaUrl(a.fileName)}
+ url={libraryMediaUrl(a.fileName, a.residency)}
duration={a.duration}
// On hover the + button takes the pill's corner.
durationClassName={!!onUse && "transition-opacity group-hover:opacity-0"}
@@ -558,6 +615,16 @@ export function LibraryCard({
<Plus className="size-3.5" />
</button>
)}
+ {bothShelves && (
+ <ShelfBadge
+ residency={a.residency}
+ className={cn(
+ "absolute top-2 right-2 text-white/85 transition-opacity",
+ // The delete button takes this corner on hover.
+ onDelete && "group-hover:opacity-0"
+ )}
+ />
+ )}
<div className="absolute top-1.5 right-1.5 flex gap-1 opacity-0 group-hover:opacity-100">
{onDelete && (
<Button
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index 3950546c..5cc85955 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -60,10 +60,12 @@ import {
saveTemplate,
type LibraryAsset,
type LibraryFolder,
+ type LibraryTemplateItem,
} from "@/cut/lib/library";
+import { activeResidency, availableResidencies, type Residency } from "@/cut/lib/residency";
import { retryUpload } from "@/cut/lib/importQueue";
import { revealMedia } from "@/cut/lib/media";
-import { mediaUrl, TRANSITION_MAX, type LibraryTemplate } from "@/cut/lib/types";
+import { mediaUrl, TRANSITION_MAX } from "@/cut/lib/types";
import { genPulseOverlay, isGenTab, useGenNotify, useGenPulse, useWatchGenTab } from "@/cut/lib/genNotify";
import { CAPTION_LIMIT, normalizeTags } from "@/cut/lib/publish";
import { useEditor } from "@/cut/lib/store";
@@ -84,7 +86,7 @@ import { SampleLibrary } from "./StockMusicPanel";
import { StockVideosPanel } from "./StockVideosPanel";
import { STOCK_MUSIC } from "@/cut/lib/stockMusicManifest";
import { STOCK_VIDEOS } from "@/cut/lib/stockVideoManifest";
-import { LibraryCard } from "./LibraryView";
+import { LibraryCard, ShelfBadge } from "./LibraryView";
// Drag a library clip onto a folder tile to file it (side panel, single card).
const LIBRARY_MOVE_MIME = "application/x-cut-library-move";
@@ -518,7 +520,7 @@ function MediaPanel({
key={t.id}
template={t}
mediaSrc={(f) => mediaUrl(projectId, f)}
- dragScope="project"
+ drag={{ scope: "project", template: t }}
addTitle="Add to timeline"
onAdd={() => addProjectTemplateToTimeline(projectId, t)}
onRename={(name) => useEditor.getState().renameTemplate(t.id, name)}
@@ -905,7 +907,7 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: string
function LibraryPanel({ projectId }: { projectId: string }) {
const [assets, setAssets] = useState<LibraryAsset[] | null>(null);
const [folders, setFolders] = useState<LibraryFolder[]>([]);
- const [templates, setTemplates] = useState<LibraryTemplate[]>([]);
+ const [templates, setTemplates] = useState<LibraryTemplateItem[]>([]);
const [openFolder, setOpenFolder] = useLocalPref<string | null>(
"cut-library-folder",
null,
@@ -936,14 +938,14 @@ function LibraryPanel({ projectId }: { projectId: string }) {
if (a) setOpenFolder(a.folderId ?? null);
});
- const removeTemplate = async (id: string) => {
+ const removeTemplate = async (r: Residency, id: string) => {
setTemplates((prev) => prev.filter((t) => t.id !== id));
- await deleteTemplate(id).catch(() => void reload());
+ await deleteTemplate(r, id).catch(() => void reload());
};
- const commitTemplateRename = async (id: string, name: string) => {
+ const commitTemplateRename = async (r: Residency, id: string, name: string) => {
setTemplates((prev) => prev.map((t) => (t.id === id ? { ...t, name } : t)));
- await renameTemplate(id, name).catch(() => void reload());
+ await renameTemplate(r, id, name).catch(() => void reload());
};
useEffect(() => {
@@ -952,21 +954,31 @@ function LibraryPanel({ projectId }: { projectId: string }) {
const remove = async () => {
if (!deleting) return;
- const id = deleting.id;
+ const { id, residency } = deleting;
setAssets((prev) => (prev ?? []).filter((a) => a.id !== id));
setDeleting(null);
try {
- await deleteFromLibrary(id);
+ await deleteFromLibrary(residency, id);
} catch {
// Server delete failed; pull a fresh list so the UI stays truthful.
void reload();
}
};
+ // Every item carries its shelf; a folder belongs to one, so an item only
+ // files into a folder on the same shelf.
+ const shelfOf = (id: string): Residency | null =>
+ (assets ?? []).find((a) => a.id === id)?.residency ??
+ templates.find((t) => t.id === id)?.residency ??
+ null;
+
const move = async (id: string, folderId: string | null) => {
+ const residency = shelfOf(id);
+ if (!residency) return;
+ if (folderId && folders.find((f) => f.id === folderId)?.residency !== residency) return;
setAssets((prev) => (prev ?? []).map((a) => (a.id === id ? { ...a, folderId } : a)));
setTemplates((prev) => prev.map((t) => (t.id === id ? { ...t, folderId } : t)));
- await moveLibraryItem(id, folderId).catch(() => void reload());
+ await moveLibraryItem(residency, id, folderId).catch(() => void reload());
};
// Let a clip be dragged onto a folder tile to file it (alongside the timeline
@@ -978,6 +990,7 @@ function LibraryPanel({ projectId }: { projectId: string }) {
};
const all = assets ?? [];
+ const bothShelves = availableResidencies().length > 1;
const shown = all.filter((a) => (a.folderId ?? null) === openFolder);
const shownTemplates = templates.filter((t) => (t.folderId ?? null) === openFolder);
const openFolderName = folders.find((f) => f.id === openFolder)?.name;
@@ -1009,12 +1022,20 @@ function LibraryPanel({ projectId }: { projectId: string }) {
all.filter((a) => (a.folderId ?? null) === id).length +
templates.filter((t) => (t.folderId ?? null) === id).length,
})}
+ badgeOf={(id) => {
+ const r = folders.find((f) => f.id === id)?.residency;
+ return bothShelves && r ? <ShelfBadge residency={r} /> : null;
+ }}
onOpen={(id) => setOpenFolder(id)}
onRename={async (id, name) => {
+ const r = folders.find((f) => f.id === id)?.residency;
+ if (!r) return;
setFolders((prev) => prev.map((f) => (f.id === id ? { ...f, name } : f)));
- await renameLibraryFolder(id, name).catch(() => void reload());
+ await renameLibraryFolder(r, id, name).catch(() => void reload());
}}
onDelete={async (id) => {
+ const r = folders.find((f) => f.id === id)?.residency;
+ if (!r) return;
setFolders((prev) => prev.filter((f) => f.id !== id));
setAssets((prev) =>
(prev ?? []).map((a) => (a.folderId === id ? { ...a, folderId: null } : a))
@@ -1023,17 +1044,20 @@ function LibraryPanel({ projectId }: { projectId: string }) {
prev.map((t) => (t.folderId === id ? { ...t, folderId: null } : t))
);
if (openFolder === id) setOpenFolder(null);
- await deleteLibraryFolder(id).catch(() => void reload());
+ await deleteLibraryFolder(r, id).catch(() => void reload());
}}
onDropIds={(ids, fid) => ids.forEach((id) => void move(id, fid))}
onRefDrop={(ref, fid) => {
// Project media dropped on a folder tile (a Media card or a
// timeline clip): save it to the library, filed in that folder.
+ // The copy lands on the project's own shelf, so a folder on the
+ // other one can't take it.
if (ref.scope !== "project") return;
+ if (folders.find((f) => f.id === fid)?.residency !== activeResidency()) return;
const asset = useEditor.getState().assets.find((a) => a.id === ref.id);
if (!asset) return;
void saveAssetToLibrary(projectId, asset)
- .then((saved) => moveLibraryItem(saved.id, fid))
+ .then((saved) => moveLibraryItem(saved.residency, saved.id, fid))
.then(() => void reload())
.catch(() => {});
}}
@@ -1047,21 +1071,21 @@ function LibraryPanel({ projectId }: { projectId: string }) {
<TemplateCard
key={t.id}
template={t}
- mediaSrc={libraryMediaUrl}
- dragScope="library"
+ mediaSrc={(f) => libraryMediaUrl(f, t.residency)}
+ drag={{ scope: "library", template: t }}
onDragStartExtra={(e) => {
e.dataTransfer.setData(LIBRARY_MOVE_MIME, JSON.stringify([t.id]));
e.dataTransfer.effectAllowed = "copyMove";
}}
addTitle="Add to this project"
onAdd={() => void addTemplateToProject(projectId, t)}
- onRename={(name) => void commitTemplateRename(t.id, name)}
- onDelete={() => void removeTemplate(t.id)}
+ onRename={(name) => void commitTemplateRename(t.residency, t.id, name)}
+ onDelete={() => void removeTemplate(t.residency, t.id)}
onRefDrop={(r) => {
if (r.scope !== "project") return;
const asset = useEditor.getState().assets.find((a) => a.id === r.id);
if (!asset) return;
- void addAssetToLibraryTemplate(projectId, t.id, asset)
+ void addAssetToLibraryTemplate(projectId, t, asset)
.then((updated) =>
setTemplates((prev) => prev.map((x) => (x.id === updated.id ? updated : x)))
)
diff --git a/site/src/cut/components/TemplateCard.tsx b/site/src/cut/components/TemplateCard.tsx
index d80cedb7..4f62074c 100644
--- a/site/src/cut/components/TemplateCard.tsx
+++ b/site/src/cut/components/TemplateCard.tsx
@@ -26,6 +26,7 @@ import {
clearAssetDrag,
setCardDragImage,
setTemplateDragData,
+ type TemplateDrag,
} from "@/cut/lib/assetDrag";
import { MEDIA_CORS } from "@/cut/lib/mediaCors";
import { useAssetDrop, type AssetRef } from "@/cut/lib/assetRef";
@@ -36,7 +37,7 @@ import { cn } from "@/lib/utils";
/** A template row card: name and parts, a "…" menu (Rename / extras / Delete)
* and an optional "+" action, both revealed on hover. Rename swaps the name
- * into an inline input. With `dragScope` set the card drags like any other
+ * into an inline input. With `drag` set the card drags like any other
* item — onto the timeline, or onto the Media/Library rail tiles. Clicking the
* card expands it to preview what's inside: each clip, sound, and title, plus
* a caption count. Hovering a video/image row floats a live preview (video
@@ -45,7 +46,7 @@ import { cn } from "@/lib/utils";
export function TemplateCard({
template: t,
mediaSrc,
- dragScope,
+ drag,
onAdd,
addTitle,
onRename,
@@ -57,8 +58,8 @@ export function TemplateCard({
template: LibraryTemplate;
/** Resolve a template media file to a playable URL (project or library). */
mediaSrc: (fileName: string) => string;
- /** Where this card lives; makes it draggable with a template payload. */
- dragScope?: "project" | "library";
+ /** The payload this card drags; omit to make it undraggable. */
+ drag?: TemplateDrag;
/** The "+" action; omit to drop the button (e.g. no open project). */
onAdd?: () => void;
addTitle?: string;
@@ -130,13 +131,13 @@ export function TemplateCard({
{...(onRefDrop ? refDrop.targetProps : {})}
className={cn(
"group flex flex-col rounded-lg border border-border bg-background px-2.5 py-1.5",
- dragScope ? "cursor-grab active:cursor-grabbing" : "cursor-pointer",
+ drag ? "cursor-grab active:cursor-grabbing" : "cursor-pointer",
onRefDrop && refDrop.active && "border-primary bg-primary/10",
)}
- draggable={!!dragScope}
+ draggable={!!drag}
onDragStart={(e) => {
- if (!dragScope) return;
- setTemplateDragData(e, dragScope, t);
+ if (!drag) return;
+ setTemplateDragData(e, drag);
onDragStartExtra?.(e);
setCardDragImage(e, e.currentTarget);
}}
diff --git a/site/src/cut/components/desktopFolders.tsx b/site/src/cut/components/desktopFolders.tsx
index eeb2f72b..877f1786 100644
--- a/site/src/cut/components/desktopFolders.tsx
+++ b/site/src/cut/components/desktopFolders.tsx
@@ -208,6 +208,7 @@ export function FolderCrumb({
export function FolderShelf<F extends DeskFolder>({
folders,
statOf,
+ badgeOf,
mime,
onOpen,
onCreate,
@@ -222,6 +223,9 @@ export function FolderShelf<F extends DeskFolder>({
}: {
folders: F[];
statOf: (id: string) => { count: number; size?: number };
+ /** Small marker beside the item count — where the library says which shelf
+ * a folder is on. */
+ badgeOf?: (id: string) => React.ReactNode;
mime: string;
onOpen: (id: string) => void;
onCreate?: (name: string) => void | Promise<void>;
@@ -369,9 +373,10 @@ export function FolderShelf<F extends DeskFolder>({
/>
<div className="min-w-0 flex-1">
<div className="truncate text-xs font-medium">{f.name}</div>
- <div className="text-[10px] text-muted-foreground tabular-nums">
+ <div className="flex items-center gap-1 text-[10px] text-muted-foreground tabular-nums">
{s.count} {s.count === 1 ? "item" : "items"}
{s.size != null ? ` · ${formatBytes(s.size)}` : ""}
+ {badgeOf?.(f.id)}
</div>
</div>
{menu}
@@ -387,9 +392,10 @@ export function FolderShelf<F extends DeskFolder>({
<span className="mt-0.5 line-clamp-2 max-w-full text-xs font-medium leading-tight">
{f.name}
</span>
- <span className="text-[10px] text-muted-foreground tabular-nums">
+ <span className="flex items-center gap-1 text-[10px] text-muted-foreground tabular-nums">
{s.count}
{s.size != null ? ` · ${formatBytes(s.size)}` : ""}
+ {badgeOf?.(f.id)}
</span>
{menu}
</div>
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 5c438c14..1cde473e 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -1221,6 +1221,13 @@ export async function runAiTool(
}
case "library_organize": {
+ // The library spans both shelves, so every id is resolved against the
+ // current listing to find the backend that owns it.
+ const lib = await fetchLibrary();
+ const folderShelf = (id: string) => lib.folders.find((f) => f.id === id)?.residency;
+ const itemShelf = (id: string) =>
+ lib.assets.find((a) => a.id === id)?.residency ??
+ lib.templates.find((t) => t.id === id)?.residency;
switch (String(input.action ?? "")) {
case "create_folder": {
const name = String(input.name ?? "").trim();
@@ -1231,25 +1238,43 @@ export async function runAiTool(
case "rename_folder": {
const name = String(input.name ?? "").trim();
if (!name) throw new ToolError("A folder name is required.");
- await renameLibraryFolder(String(input.folder_id ?? ""), name);
+ const id = String(input.folder_id ?? "");
+ const r = folderShelf(id);
+ if (!r) throw new ToolError(`No library folder with id ${id}.`);
+ await renameLibraryFolder(r, id, name);
return { renamed: true, name };
}
case "delete_folder": {
- await deleteLibraryFolder(String(input.folder_id ?? ""));
+ const id = String(input.folder_id ?? "");
+ const r = folderShelf(id);
+ if (!r) throw new ToolError(`No library folder with id ${id}.`);
+ await deleteLibraryFolder(r, id);
return { deleted: true, note: "Its assets moved to the Library root." };
}
case "move_asset": {
const folderId =
typeof input.folder_id === "string" && input.folder_id ? input.folder_id : null;
- await moveLibraryItem(String(input.id ?? ""), folderId);
+ const id = String(input.id ?? "");
+ const r = itemShelf(id);
+ if (!r) throw new ToolError(`No library item with id ${id}.`);
+ if (folderId && folderShelf(folderId) !== r) {
+ throw new ToolError("That folder is on the other library shelf.");
+ }
+ await moveLibraryItem(r, id, folderId);
return { moved: true, folderId };
}
case "delete_asset": {
- await deleteFromLibrary(String(input.id ?? ""));
+ const id = String(input.id ?? "");
+ const r = lib.assets.find((a) => a.id === id)?.residency;
+ if (!r) throw new ToolError(`No library asset with id ${id}.`);
+ await deleteFromLibrary(r, id);
return { deleted: true };
}
case "delete_template": {
- await deleteTemplate(String(input.id ?? ""));
+ const id = String(input.id ?? "");
+ const r = lib.templates.find((t) => t.id === id)?.residency;
+ if (!r) throw new ToolError(`No library template with id ${id}.`);
+ await deleteTemplate(r, id);
return { deleted: true };
}
default:
diff --git a/site/src/cut/lib/assetDrag.ts b/site/src/cut/lib/assetDrag.ts
index d407b762..513a1191 100644
--- a/site/src/cut/lib/assetDrag.ts
+++ b/site/src/cut/lib/assetDrag.ts
@@ -2,7 +2,7 @@
import type React from "react";
import { clearRefDrag, refFromAsset, refFromLibrary, setRefDragData } from "./assetRef";
-import type { LibraryAsset } from "./library";
+import type { LibraryAsset, LibraryTemplateItem } from "./library";
import { useEditor } from "./store";
import type { LibraryTemplate } from "./types";
@@ -62,19 +62,21 @@ export function draggedLibraryId(e: React.DragEvent | DragEvent): string | null
}
/** A template dragged from the Media panel (project scope) or the Library
- * panel (library scope), so the rail tiles can move it the other way. */
+ * panel (library scope), so the rail tiles can move it the other way. A
+ * library template carries the shelf it sits on; a project one lives in the
+ * open project and needs no residency. */
export const TEMPLATE_MIME = "application/x-cut-template";
-let inFlightTemplate: { scope: "project" | "library"; template: LibraryTemplate } | null = null;
+export type TemplateDrag =
+ | { scope: "project"; template: LibraryTemplate }
+ | { scope: "library"; template: LibraryTemplateItem };
-export function setTemplateDragData(
- e: React.DragEvent,
- scope: "project" | "library",
- template: LibraryTemplate
-) {
- e.dataTransfer.setData(TEMPLATE_MIME, template.id);
+let inFlightTemplate: TemplateDrag | null = null;
+
+export function setTemplateDragData(e: React.DragEvent, drag: TemplateDrag) {
+ e.dataTransfer.setData(TEMPLATE_MIME, drag.template.id);
e.dataTransfer.effectAllowed = "copy";
- inFlightTemplate = { scope, template };
+ inFlightTemplate = drag;
}
/** The template drag in flight, readable during `dragover`. */
diff --git a/site/src/cut/lib/assetRef.ts b/site/src/cut/lib/assetRef.ts
index 013525f8..c86e3946 100644
--- a/site/src/cut/lib/assetRef.ts
+++ b/site/src/cut/lib/assetRef.ts
@@ -62,7 +62,7 @@ export const refFromLibrary = (a: LibraryAsset): AssetRef => ({
id: a.id,
name: a.name,
kind: a.type,
- url: libraryMediaUrl(a.fileName),
+ url: libraryMediaUrl(a.fileName, a.residency),
duration: a.duration,
});
diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.ts
index a8fbfb5e..62edf71c 100644
--- a/site/src/cut/lib/library.ts
+++ b/site/src/cut/lib/library.ts
@@ -1,7 +1,13 @@
"use client";
-import { apiFetch, apiJson, apiUrl, getBackend } from "./backend";
-import { enrichAsset, presignedUpload, probeFileMeta } from "./media";
+import { apiJson, getBackend } from "./backend";
+import { enrichAsset, presignedUpload, probeFileMeta, uploadProjectMediaTo } from "./media";
+import {
+ activeResidency,
+ availableResidencies,
+ backendFor,
+ type Residency,
+} from "./residency";
import { useEditor } from "./store";
import type { LibraryTemplate, MediaAsset, TemplateMedia, TemplateSaveInput } from "./types";
import { IMAGE_CLIP_SECONDS, mediaUrl } from "./types";
@@ -24,53 +30,95 @@ export interface LibraryAsset {
addedAt: number;
folderId?: string | null;
source?: LibrarySource;
+ /** Which shelf this came off. Stamped on arrival — the servers each answer
+ * for themselves and don't know the other exists. */
+ residency: Residency;
}
export interface LibraryFolder {
id: string;
name: string;
createdAt: number;
+ residency: Residency;
}
+/** A template as the library lists it: the stored doc plus the shelf it sits
+ * on, so its media resolve against the right backend. */
+export type LibraryTemplateItem = LibraryTemplate & { residency: Residency };
+
export interface LibraryData {
assets: LibraryAsset[];
folders: LibraryFolder[];
- templates: LibraryTemplate[];
+ templates: LibraryTemplateItem[];
}
-export const libraryMediaUrl = (fileName: string) =>
- apiUrl(`/api/cut/library/media/${encodeURIComponent(fileName)}`);
+export const libraryMediaUrl = (fileName: string, residency: Residency) =>
+ backendFor(residency).url(`/api/cut/library/media/${encodeURIComponent(fileName)}`);
-export async function fetchLibrary(): Promise<LibraryData> {
- const res = await apiFetch("/api/cut/library");
+async function fetchLibraryFrom(r: Residency): Promise<LibraryData> {
+ const res = await backendFor(r).fetch("/api/cut/library");
if (!res.ok) throw new Error("Could not load the library.");
- return (await res.json()) as LibraryData;
+ const data = (await res.json()) as LibraryData;
+ return {
+ assets: (data.assets ?? []).map((a) => ({ ...a, residency: r })),
+ folders: (data.folders ?? []).map((f) => ({ ...f, residency: r })),
+ templates: (data.templates ?? []).map((t) => ({ ...t, residency: r })),
+ };
+}
+
+/**
+ * The whole shelf: every reachable residency's library in one listing, newest
+ * first. A residency that fails is left out rather than failing the read — one
+ * unreachable half never hides the other; only both failing is an error.
+ */
+export async function fetchLibrary(): Promise<LibraryData> {
+ const rs = availableResidencies();
+ const parts = await Promise.all(rs.map((r) => fetchLibraryFrom(r).catch(() => null)));
+ const got = parts.filter((p): p is LibraryData => p !== null);
+ if (got.length === 0) throw new Error("Could not load the library.");
+ const byNewest = <T extends { addedAt: number }>(items: T[]) =>
+ [...items].sort((a, b) => b.addedAt - a.addedAt);
+ return {
+ assets: byNewest(got.flatMap((p) => p.assets)),
+ folders: got.flatMap((p) => p.folders).sort((a, b) => a.createdAt - b.createdAt),
+ templates: byNewest(got.flatMap((p) => p.templates)),
+ };
}
-export async function importUrlToLibrary(url: string): Promise<LibraryAsset[]> {
- const res = await apiFetch("/api/cut/library/import-url", {
+export async function importUrlToLibrary(
+ url: string,
+ residency: Residency = activeResidency()
+): Promise<LibraryAsset[]> {
+ const res = await backendFor(residency).fetch("/api/cut/library/import-url", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url }),
});
const body = await apiJson<LibraryAsset[]>(res);
if (!res.ok) throw new Error(body.error ?? "Could not import that URL.");
- return body;
+ return (Array.isArray(body) ? body : []).map((a) => ({ ...a, residency }));
}
-export async function createLibraryFolder(name: string): Promise<LibraryFolder> {
- const res = await apiFetch("/api/cut/library/folders", {
+export async function createLibraryFolder(
+ name: string,
+ residency: Residency = activeResidency()
+): Promise<LibraryFolder> {
+ const res = await backendFor(residency).fetch("/api/cut/library/folders", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
});
const body = await apiJson<LibraryFolder>(res);
if (!res.ok) throw new Error(body.error ?? "Could not create folder.");
- return body;
+ return { ...body, residency };
}
-export async function renameLibraryFolder(id: string, name: string): Promise<void> {
- const res = await apiFetch(`/api/cut/library/folders/${id}`, {
+export async function renameLibraryFolder(
+ residency: Residency,
+ id: string,
+ name: string
+): Promise<void> {
+ const res = await backendFor(residency).fetch(`/api/cut/library/folders/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
@@ -78,14 +126,22 @@ export async function renameLibraryFolder(id: string, name: string): Promise<voi
if (!res.ok) throw new Error("Could not rename folder.");
}
-export async function deleteLibraryFolder(id: string): Promise<void> {
- const res = await apiFetch(`/api/cut/library/folders/${id}`, { method: "DELETE" });
+export async function deleteLibraryFolder(residency: Residency, id: string): Promise<void> {
+ const res = await backendFor(residency).fetch(`/api/cut/library/folders/${id}`, {
+ method: "DELETE",
+ });
if (!res.ok) throw new Error("Could not delete folder.");
}
-/** File a library item — an asset or a template — into a folder (`null` ungroups). */
-export async function moveLibraryItem(id: string, folderId: string | null): Promise<void> {
- const res = await apiFetch("/api/cut/library/move", {
+/** File a library item — an asset or a template — into a folder on its own
+ * shelf (`null` ungroups). Folders don't span residencies: a cloud item can't
+ * move into a folder that lives on the Mac. */
+export async function moveLibraryItem(
+ residency: Residency,
+ id: string,
+ folderId: string | null
+): Promise<void> {
+ const res = await backendFor(residency).fetch("/api/cut/library/move", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id, folderId }),
@@ -93,8 +149,12 @@ export async function moveLibraryItem(id: string, folderId: string | null): Prom
if (!res.ok) throw new Error("Could not move item.");
}
-export async function uploadToLibrary(file: File): Promise<LibraryAsset> {
- if (getBackend().kind === "cloud") {
+export async function uploadToLibrary(
+ file: File,
+ residency: Residency = activeResidency()
+): Promise<LibraryAsset> {
+ const backend = backendFor(residency);
+ if (residency === "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
@@ -105,52 +165,76 @@ export async function uploadToLibrary(file: File): Promise<LibraryAsset> {
"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", {
+ const key = await presignedUpload("/api/cut/library/presign", file, file.name, backend);
+ const res = await backend.fetch("/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;
+ return { ...body, residency };
}
const form = new FormData();
form.append("file", file, file.name);
- const res = await apiFetch("/api/cut/library", { method: "POST", body: form });
+ const res = await backend.fetch("/api/cut/library", { method: "POST", body: form });
const body = await apiJson<LibraryAsset>(res);
if (!res.ok) throw new Error(body.error ?? "Upload failed.");
- return body;
+ return { ...body, residency };
}
-export async function deleteFromLibrary(id: string) {
- const res = await apiFetch(`/api/cut/library/${id}`, { method: "DELETE" });
+export async function deleteFromLibrary(residency: Residency, id: string) {
+ const res = await backendFor(residency).fetch(`/api/cut/library/${id}`, { method: "DELETE" });
if (!res.ok) throw new Error("Could not delete.");
}
+/** Land one library file in the open project and return its stored name.
+ *
+ * On the project's own shelf the server does the copy without the bytes ever
+ * reaching the browser. Off it — a cloud project reaching for a clip on this
+ * Mac, or the reverse — neither server can see the other, so the bytes come
+ * down here and go back up into the project. */
+async function copyLibraryFileToProject(
+ projectId: string,
+ residency: Residency,
+ fileName: string,
+ assetId?: string
+): Promise<string> {
+ const target = getBackend();
+ if (assetId && residency === target.kind) {
+ const res = await target.fetch("/api/cut/library/use", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ assetId, projectId }),
+ });
+ const body = await apiJson<{ fileName?: string }>(res);
+ if (!res.ok || !body.fileName) throw new Error(body.error ?? "Could not add from library.");
+ return body.fileName;
+ }
+ const bytes = await backendFor(residency).fetch(
+ `/api/cut/library/media/${encodeURIComponent(fileName)}`
+ );
+ if (!bytes.ok) throw new Error("Could not read that library file.");
+ return uploadProjectMediaTo(target, projectId, await bytes.blob(), fileName);
+}
+
/** Copy a library asset into the open project's media and register it, without
* placing it on the timeline. Callers choose where it lands. */
export async function importLibraryAsset(
projectId: string,
lib: LibraryAsset
): Promise<MediaAsset> {
- const res = await apiFetch("/api/cut/library/use", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ assetId: lib.id, projectId }),
- });
- const body = await apiJson<{ fileName?: string }>(res);
- if (!res.ok || !body.fileName) throw new Error(body.error ?? "Could not add from library.");
+ const fileName = await copyLibraryFileToProject(projectId, lib.residency, lib.fileName, lib.id);
const asset: MediaAsset = {
id: crypto.randomUUID().slice(0, 8),
- fileName: body.fileName,
+ fileName,
name: lib.name,
type: lib.type,
duration: lib.duration,
width: lib.width,
height: lib.height,
- url: mediaUrl(projectId, body.fileName),
+ url: mediaUrl(projectId, fileName),
};
useEditor.getState().addAsset(asset);
// Generate filmstrip thumbnails / waveform peaks so the clip renders like any
@@ -171,35 +255,45 @@ export async function addLibraryAssetToProject(
return asset;
}
-/** Save the current timeline selection as a by-reference template. */
+/** Save the current timeline selection as a by-reference template. It lands on
+ * the project's own shelf: the server copies the media straight across. */
export async function saveTemplate(
projectId: string,
input: TemplateSaveInput
-): Promise<LibraryTemplate> {
- const res = await apiFetch("/api/cut/library/templates", {
+): Promise<LibraryTemplateItem> {
+ const residency = activeResidency();
+ const res = await backendFor(residency).fetch("/api/cut/library/templates", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ projectId, ...input }),
});
const body = await apiJson<LibraryTemplate>(res);
if (!res.ok) throw new Error(body.error ?? "Could not save the template.");
- return body;
+ return { ...body, residency };
}
/** Append a project asset to a library template as one more part at its end:
- * the engine copies the file into the library and returns the updated
- * template. */
+ * the server copies the file into the library and returns the updated
+ * template. Same-shelf only — the copy happens server-side, where neither
+ * backend can see the other's project media. */
export async function addAssetToLibraryTemplate(
projectId: string,
- templateId: string,
+ template: LibraryTemplateItem,
asset: MediaAsset
-): Promise<LibraryTemplate> {
+): Promise<LibraryTemplateItem> {
+ if (template.residency !== getBackend().kind) {
+ throw new Error(
+ template.residency === "cloud"
+ ? "That template is in the cloud; this project isn't."
+ : "That template is on this Mac; this project isn't."
+ );
+ }
const len = asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration;
const part =
asset.type === "audio"
? { audio: { in: 0, out: len, volume: 1 } }
: { layer: { in: 0, out: len, muted: false, track: 1, asClip: true } };
- const res = await apiFetch(`/api/cut/library/templates/${templateId}/add`, {
+ const res = await getBackend().fetch(`/api/cut/library/templates/${template.id}/add`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
@@ -218,11 +312,15 @@ export async function addAssetToLibraryTemplate(
});
const body = await apiJson<LibraryTemplate>(res);
if (!res.ok) throw new Error(body.error ?? "Could not add to the template.");
- return body;
+ return { ...body, residency: template.residency };
}
-export async function renameTemplate(id: string, name: string): Promise<void> {
- const res = await apiFetch(`/api/cut/library/templates/${id}`, {
+export async function renameTemplate(
+ residency: Residency,
+ id: string,
+ name: string
+): Promise<void> {
+ const res = await backendFor(residency).fetch(`/api/cut/library/templates/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
@@ -230,31 +328,52 @@ export async function renameTemplate(id: string, name: string): Promise<void> {
if (!res.ok) throw new Error("Could not rename the template.");
}
-export async function deleteTemplate(id: string): Promise<void> {
- const res = await apiFetch(`/api/cut/library/templates/${id}`, { method: "DELETE" });
+export async function deleteTemplate(residency: Residency, id: string): Promise<void> {
+ const res = await backendFor(residency).fetch(`/api/cut/library/templates/${id}`, {
+ method: "DELETE",
+ });
if (!res.ok) throw new Error("Could not delete the template.");
}
+/** Land a template's media in the open project, in `template.media` order, and
+ * return the stored file names. On the project's own shelf one call does the
+ * whole copy server-side; off it each file rides through the browser. */
+async function copyTemplateMediaToProject(
+ projectId: string,
+ template: LibraryTemplateItem
+): Promise<TemplateMedia[]> {
+ if (template.residency === getBackend().kind) {
+ const res = await getBackend().fetch(`/api/cut/library/templates/${template.id}/use`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ projectId }),
+ });
+ const body = await apiJson<{ media?: TemplateMedia[] }>(res);
+ if (!res.ok || !body.media) throw new Error(body.error ?? "Could not add the template.");
+ return body.media;
+ }
+ const out: TemplateMedia[] = [];
+ for (const m of template.media) {
+ const fileName = await copyLibraryFileToProject(projectId, template.residency, m.fileName);
+ out.push({ ...m, fileName });
+ }
+ return out;
+}
+
/** Copy a template's media into the open project and re-materialize its clips,
* overlays, and captions at the playhead — everything editable, nothing baked. */
export async function addTemplateToProject(
projectId: string,
- template: LibraryTemplate,
+ template: LibraryTemplateItem,
at?: number
): Promise<void> {
- const res = await apiFetch(`/api/cut/library/templates/${template.id}/use`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ projectId }),
- });
- const body = await apiJson<{ media?: TemplateMedia[] }>(res);
- if (!res.ok || !body.media) throw new Error(body.error ?? "Could not add the template.");
+ const media = await copyTemplateMediaToProject(projectId, template);
const s = useEditor.getState();
- // Each returned media file (in template.media order) becomes a project asset;
+ // Each copied media file (in template.media order) becomes a project asset;
// the layer/audio media indices resolve against this array. Enrichment gives
// the new clips their filmstrip thumbnails and waveform peaks.
- const assetIds = body.media.map((m) => {
+ const assetIds = media.map((m) => {
const asset: MediaAsset = {
id: crypto.randomUUID().slice(0, 8),
fileName: m.fileName,
@@ -277,19 +396,13 @@ export async function addTemplateToProject(
* Nothing is placed on the timeline. */
export async function importTemplateToProject(
projectId: string,
- template: LibraryTemplate
+ template: LibraryTemplateItem
): Promise<void> {
- const res = await apiFetch(`/api/cut/library/templates/${template.id}/use`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ projectId }),
- });
- const body = await apiJson<{ media?: TemplateMedia[] }>(res);
- if (!res.ok || !body.media) throw new Error(body.error ?? "Could not add the template.");
+ const media = await copyTemplateMediaToProject(projectId, template);
useEditor.getState().addTemplate({
name: template.name,
duration: template.duration,
- media: body.media,
+ media,
layers: template.layers,
audio: template.audio,
texts: template.texts,
@@ -326,14 +439,19 @@ export function addProjectTemplateToTimeline(
useEditor.getState().insertTemplate(template, assetIds, at ?? useEditor.getState().currentTime);
}
-/** Copy a project asset into the shared library for reuse. */
-export async function saveAssetToLibrary(projectId: string, asset: MediaAsset) {
- const res = await apiFetch("/api/cut/library/save", {
+/** Copy a project asset into the shared library for reuse. It lands on the
+ * project's own shelf, where the server can copy the bytes itself. */
+export async function saveAssetToLibrary(
+ projectId: string,
+ asset: MediaAsset
+): Promise<LibraryAsset> {
+ const residency = activeResidency();
+ const res = await backendFor(residency).fetch("/api/cut/library/save", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ projectId, fileName: asset.fileName, name: asset.name }),
});
const body = await apiJson<LibraryAsset>(res);
if (!res.ok) throw new Error(body.error ?? "Could not save to library.");
- return body;
+ return { ...body, residency };
}
diff --git a/site/src/cut/lib/queries.ts b/site/src/cut/lib/queries.ts
index 5c838570..2483beb1 100644
--- a/site/src/cut/lib/queries.ts
+++ b/site/src/cut/lib/queries.ts
@@ -20,28 +20,24 @@ import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-quer
import { useEffect } from "react";
import { engineLost } from "./api";
-import { getBackend } from "./backend";
-import { cloudBackend } from "./backend/cloud";
-import { localBackend } from "./backend/local";
import { useCutMode } from "./backend/hooks";
-import type { CutBackend, CutMode } from "./backend/types";
import { readSnapshot, snapshotKey, writeSnapshot } from "./cache";
import { webModeEnabled } from "./flags";
import { fetchLibrary, type LibraryData } from "./library";
+import { availableResidencies, backendFor, type Residency } from "./residency";
import type { ProjectFolder, ProjectSummary } from "./types";
-/** Where a project lives: the engine on this Mac, or the hosted cloud
- * backend. ("shared" is a view of someone else's project, never a residency
- * of yours, so it never lists here.) */
-export type Residency = "local" | "cloud";
-
-export const backendFor = (r: Residency): CutBackend =>
- r === "cloud" ? cloudBackend : localBackend;
+export { backendFor };
+export type { Residency };
export type ProjectsSection = { projects: ProjectSummary[]; folders: ProjectFolder[] };
export const projectsKey = (r: Residency) => ["cut", "projects", r] as const;
-export const libraryKey = (mode: CutMode) => ["cut", "library", mode] as const;
+/** The library listing spans every reachable residency, so the set itself is
+ * the cache key — connecting the engine mid-session widens the shelf rather
+ * than repainting a stale half of it. */
+export const libraryScope = () => availableResidencies().join("+");
+export const libraryKey = (scope: string) => ["cut", "library", scope] as const;
/**
* Paint the last answer we stored while the live one is in flight. The
@@ -111,21 +107,25 @@ export function useProjectsSection(r: Residency, enabled: boolean) {
});
}
-/** The library of the backend the app is currently bound to. */
+/** The user's whole shelf: every reachable residency's library, merged. */
export function useLibrary() {
- const mode = useCutMode();
+ // Not read for the query itself — the backend binding decides which
+ // residencies are reachable, so a mode change re-keys and re-reads.
+ useCutMode();
const client = useQueryClient();
+ const scope = libraryScope();
+ const snap = snapshotKey(scope, "library");
useEffect(
- () => seedFromSnapshot<LibraryData>(client, libraryKey(mode), snapshotKey(mode, "library")),
- [client, mode]
+ () => seedFromSnapshot<LibraryData>(client, libraryKey(scope), snap),
+ [client, scope, snap]
);
return useQuery<LibraryData>({
- queryKey: libraryKey(mode),
+ queryKey: libraryKey(scope),
queryFn: async () => {
const data = await fetchLibrary();
- writeSnapshot(snapshotKey(mode, "library"), data);
+ writeSnapshot(snap, data);
return data;
},
staleTime: 0,
@@ -148,14 +148,14 @@ export function patchProjects(
if (next) writeSnapshot(snapshotKey(r, "projects"), next);
}
-/** The library's equivalent. Keyed on the active backend, which is the only
- * one the library view ever shows. */
+/** The library's equivalent. Its items carry their own residency, so one
+ * merged listing is patched however the mutation asks. */
export function patchLibrary(client: QueryClient, fn: (prev: LibraryData) => LibraryData) {
- const mode = getBackend().kind;
- const next = client.setQueryData<LibraryData>(libraryKey(mode), (prev) =>
+ const scope = libraryScope();
+ const next = client.setQueryData<LibraryData>(libraryKey(scope), (prev) =>
prev ? fn(prev) : prev
);
- if (next) writeSnapshot(snapshotKey(mode, "library"), next);
+ if (next) writeSnapshot(snapshotKey(scope, "library"), next);
}
/** Pull a residency's listing again — for the changes only the server can
@@ -165,5 +165,5 @@ export function refetchProjects(client: QueryClient, r: Residency) {
}
export function refetchLibrary(client: QueryClient) {
- return client.invalidateQueries({ queryKey: libraryKey(getBackend().kind) });
+ return client.invalidateQueries({ queryKey: libraryKey(libraryScope()) });
}
diff --git a/site/src/cut/lib/residency.ts b/site/src/cut/lib/residency.ts
index ebeb6322..ed6a7c8b 100644
--- a/site/src/cut/lib/residency.ts
+++ b/site/src/cut/lib/residency.ts
@@ -4,11 +4,56 @@
// engine — when one is already connected; loopback is never probed here, so
// the browser's local-network ask can't fire — is asked whether it owns the
// id, and a miss means the project is cloud-resident.
+//
+// A project opens into one residency. The library is the other way around: it
+// is the user's shelf, and both halves of it are theirs, so every surface that
+// shows the library shows every residency this browser can reach — a cloud
+// project can still pull a clip off this Mac's disk, and a local project can
+// still pull one out of the cloud.
import { engineOrigin, servedFromEngine } from "./api";
+import { cutMode } from "./backend";
+import { cloudBackend } from "./backend/cloud";
import { localBackend } from "./backend/local";
-import type { CutMode } from "./backend/types";
+import type { CutBackend, CutMode } from "./backend/types";
import { webModeEnabled } from "./flags";
+/** Where a piece of the user's own data lives. ("shared" is a view of someone
+ * else's cloud project, never a residency of yours, so it never lists here.) */
+export type Residency = "local" | "cloud";
+
+export const backendFor = (r: Residency): CutBackend =>
+ r === "cloud" ? cloudBackend : localBackend;
+
+export const RESIDENCY_LABEL: Record<Residency, string> = {
+ local: "On this Mac",
+ cloud: "Cloud",
+};
+
+/**
+ * The residencies this browser can talk to right now.
+ *
+ * The engine counts only once it has actually answered — the ConnectGate
+ * resolved its origin, or the page is served by it. Probing here could raise
+ * the browser's local-network prompt, and calling the engine before the gate
+ * opens would hang on its latch. The cloud counts whenever web mode is on;
+ * without the flag there is no hosted half to read.
+ */
+export function availableResidencies(): Residency[] {
+ const out: Residency[] = [];
+ if (servedFromEngine() || engineOrigin() !== "") out.push("local");
+ if (webModeEnabled()) out.push("cloud");
+ // Neither resolved yet: fall back to whatever the app is bound to, so a
+ // caller always has one backend to ask.
+ if (out.length === 0) out.push(activeResidency());
+ return out;
+}
+
+/** The residency the app is bound to: where a new library upload lands, and
+ * where the open project lives. A shared view reads the local shelf. */
+export function activeResidency(): Residency {
+ return cutMode() === "cloud" ? "cloud" : "local";
+}
+
export async function resolveProjectMode(projectId: string): Promise<CutMode> {
if (!webModeEnabled()) return "local";
if (!servedFromEngine() && !engineOrigin()) return "cloud";