Skip to content

Open source CapCut alternative.

TypeScript

feat(site): Media panel folders [rebuild]

David Le61d7c7336dd6
diff --git a/site/src/components/ui/dropdown-menu.tsx b/site/src/components/ui/dropdown-menu.tsx
index eb054113..9e0bd2f8 100644
--- a/site/src/components/ui/dropdown-menu.tsx
+++ b/site/src/components/ui/dropdown-menu.tsx
@@ -36,12 +36,15 @@ function DropdownMenuContent({
alignOffset = 0,
side = "bottom",
sideOffset = 4,
+ anchor,
className,
...props
}: MenuPrimitive.Popup.Props &
Pick<
MenuPrimitive.Positioner.Props,
- "align" | "alignOffset" | "side" | "sideOffset"
+ // `anchor` detaches the menu from its trigger — a controlled menu opened
+ // at the pointer (a right-click) anchors to a virtual point.
+ "align" | "alignOffset" | "side" | "sideOffset" | "anchor"
>) {
return (
<MenuPrimitive.Portal>
@@ -51,6 +54,7 @@ function DropdownMenuContent({
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
+ anchor={anchor}
{...stayInMenu}
>
<MenuPrimitive.Popup
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index dcbaf2e2..320a19b6 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -597,6 +597,7 @@ export function Editor({
docOverlays(s.overlays) !== (last.overlays as unknown) ||
s.transitions !== lastBars ||
s.templates !== (last.templates as unknown) ||
+ s.mediaFolders !== (last.mediaFolders as unknown) ||
s.subtitles !== (last.subtitles as unknown) ||
s.aspect !== last.aspect ||
s.fadeIn !== (last.fadeIn ?? 0) ||
@@ -669,6 +670,9 @@ export function Editor({
* when every one of them is busy there — what a paste means by "here".
* Without it the file takes track 0's next free slot. */
atFirstFit?: boolean;
+ /** Media folder the import files into — the one open in the Media
+ * panel when the upload started. */
+ folderId?: string;
}
) => {
const list = Array.from(files);
@@ -694,6 +698,7 @@ export function Editor({
// but never in the Media panel (reserved for user imports).
if (opts?.origin) asset.origin = opts.origin;
if (opts?.name) asset.name = opts.name;
+ if (opts?.folderId) asset.folderId = opts.folderId;
const s = useEditor.getState();
// Probing, naming and (for a pasted frame) rendering all outlive a
// project switch. The asset was prepared against `projectId` and its
diff --git a/site/src/cut/components/SidePanel.tools.ts b/site/src/cut/components/SidePanel.tools.ts
index ff8adaf8..b8a04401 100644
--- a/site/src/cut/components/SidePanel.tools.ts
+++ b/site/src/cut/components/SidePanel.tools.ts
@@ -45,6 +45,25 @@ export const SIDE_PANEL_TOOLS = [
max_height: num("Cap the output height in pixels (e.g. 1080); omit to keep the source size"),
}, ["asset_ids"]),
},
+ {
+ name: "media_organize",
+ description:
+ "Organize the Media panel's Project Files with folders (this project only; the shared Library has library_organize): create_folder / rename_folder / delete_folder (a deleted folder's files drop back to the top level), move_asset files user-imported media into a folder (omit folder_id for the top level). Folders and each asset's folderId are in `media` / `mediaFolders` from get_state. create_folder can take asset_ids to file into the new folder in the same call.",
+ inputSchema: obj({
+ action: {
+ type: "string",
+ enum: ["create_folder", "rename_folder", "delete_folder", "move_asset"],
+ description: "The organize operation",
+ },
+ name: str("Folder name (create_folder, rename_folder)"),
+ folder_id: str("Media folder id (rename_folder, delete_folder, move_asset destination — omit for the top level)"),
+ asset_ids: {
+ type: "array",
+ items: { type: "string" },
+ description: "Project asset ids to file (move_asset; optional on create_folder)",
+ },
+ }, ["action"]),
+ },
{
name: "delete_asset",
description:
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index 16c93adc..c7e7b8ef 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -137,6 +137,9 @@ import { SubTabs } from "./SubTabs";
// Drag a library clip onto a folder tile to file it (side panel, single card).
const LIBRARY_MOVE_MIME = "application/x-cut-library-move";
+// A Project Files selection dragged onto a folder tile or the crumb: the
+// payload is the picked asset ids, so one drop files the whole selection.
+const MEDIA_MOVE_MIME = "application/x-cut-media-move";
import { PlatformPreviewDialog, type ExportItem } from "./PlatformPreview";
import { SubtitlesPanel } from "./SubtitlesPanel";
@@ -160,7 +163,7 @@ export function SidePanel({
importing,
}: {
projectId: string;
- onImport: (files: FileList | File[], opts?: { mediaOnly?: boolean }) => void;
+ onImport: (files: FileList | File[], opts?: { mediaOnly?: boolean; folderId?: string }) => void;
importing: boolean;
}) {
// A shared view shows only the surfaces the share opted in; the Library is
@@ -626,7 +629,7 @@ function MediaPanel({
importing,
}: {
projectId: string;
- onImport: (files: FileList | File[], opts?: { mediaOnly?: boolean }) => void;
+ onImport: (files: FileList | File[], opts?: { mediaOnly?: boolean; folderId?: string }) => void;
importing: boolean;
}) {
// A shared view shows only the project's own files — the Library is the
@@ -662,7 +665,14 @@ function MediaPanel({
</div>
)}
{view === "project" ? (
- <ProjectFilesPanel projectId={projectId} onImport={onImport} importing={importing} />
+ <ProjectFilesPanel
+ // Which folder is open is remembered per project and read once, at
+ // mount, so the panel starts fresh when another project opens.
+ key={projectId}
+ projectId={projectId}
+ onImport={onImport}
+ importing={importing}
+ />
) : (
<LibraryPanel projectId={projectId} />
)}
@@ -676,7 +686,7 @@ function ProjectFilesPanel({
importing,
}: {
projectId: string;
- onImport: (files: FileList | File[], opts?: { mediaOnly?: boolean }) => void;
+ onImport: (files: FileList | File[], opts?: { mediaOnly?: boolean; folderId?: string }) => void;
importing: boolean;
}) {
const caps = useCutCaps();
@@ -686,11 +696,43 @@ function ProjectFilesPanel({
// Fonts are project assets (their bytes live in media/) but they belong to
// the text inspector's font menu, never the Media grid.
const assets = useEditor((s) => s.assets).filter((a) => a.origin == null && a.type !== "font");
+ // The panel's folders, plus which one is open; the grid shows the open
+ // folder's files, or the unfiled ones at the root.
+ const folders = useEditor((s) => s.mediaFolders);
+ // Folders are the project's own, so which one is open is remembered under
+ // the project's own key: opening a second project leaves the first one's
+ // place standing.
+ const [storedFolder, setOpenFolder] = useLocalPref<string | null>(
+ `cut-media-folder:${projectId}`,
+ null,
+ (v) => v === null || typeof v === "string"
+ );
+ // A remembered folder may have been deleted since — here or on another
+ // machine. Once the doc is in, an id no folder answers for reads as the
+ // root, without writing that back over what is remembered.
+ const projectLoaded = useEditor((s) => s.loaded);
+ const openFolder =
+ storedFolder !== null && projectLoaded && !folders.some((f) => f.id === storedFolder)
+ ? null
+ : storedFolder;
+ const shown = assets.filter((a) => (a.folderId ?? null) === openFolder);
// Which tiles are picked, so a sweep or a ⇧-click can hand the timeline a
// run of media in one drag. Anything that leaves the grid leaves the pick.
- const { picked, setPicked, pick } = useTilePicks(assets.map((a) => a.id));
+ const { picked, setPicked, pick } = useTilePicks(shown.map((a) => a.id));
// Built once for the whole grid; each card hands the same array on.
const pickedIds = [...picked];
+ // The name field of a folder being made: [] from the empty-space menu, the
+ // picked ids when the selection menu starts one — those file into the
+ // folder the moment its name is committed.
+ const [creatingIds, setCreatingIds] = useState<string[] | null>(null);
+ // The right-click menu at the cursor: `ids` carries the selection it acts
+ // on, null means the empty-space menu (just "New folder").
+ const [ctxMenu, setCtxMenu] = useState<{ x: number; y: number; ids: string[] | null } | null>(
+ null
+ );
+ // A selection delete that would also take timeline clips waits on this
+ // confirm; ids whose media is unused delete without one.
+ const [deletingIds, setDeletingIds] = useState<string[] | null>(null);
const templates = useEditor((s) => s.templates);
const exportOpen = useEditor((s) => s.exportOpen);
// A render that finishes in the background (dialog closed) drops a new file in
@@ -720,10 +762,17 @@ function ProjectFilesPanel({
// recording) dropped here moves into Media. It lights up for both.
const { active: dropActive, attachTarget, targetProps } = useAssetDrop(
(ref) => {
+ // Filed straight into the open folder, so the drop lands where the eye is.
if (ref.scope === "project")
- useEditor.getState().updateAsset(ref.id, { origin: undefined, chatId: undefined });
+ useEditor.getState().updateAsset(ref.id, {
+ origin: undefined,
+ chatId: undefined,
+ folderId: openFolder ?? undefined,
+ });
},
- readOnly ? undefined : (files) => onImport(files, { mediaOnly: true })
+ readOnly
+ ? undefined
+ : (files) => onImport(files, { mediaOnly: true, folderId: openFolder ?? undefined })
);
const inputRef = useRef<HTMLInputElement>(null);
const [exports, setExports] = useState<ExportItem[]>([]);
@@ -771,6 +820,41 @@ function ProjectFilesPanel({
if (preview && !list.some((e) => e.file === preview.file)) setPreview(null);
};
+ // The selection menu's delete: unused media goes straight away; media on
+ // the timeline waits on the confirm below, which names what goes with it.
+ const removeMany = (ids: string[]) => {
+ const s = useEditor.getState();
+ const gone = new Set(ids);
+ const uses =
+ s.clips.filter((c) => gone.has(c.assetId)).length +
+ s.audioClips.filter((c) => gone.has(c.assetId)).length;
+ if (uses > 0) setDeletingIds(ids);
+ else for (const id of ids) s.removeAsset(id);
+ };
+
+ // Right-click: over a card, the selection menu (the card joins the pick if
+ // it wasn't in it); over empty panel space at the root, the New-folder menu.
+ const onPanelContextMenu = (e: React.MouseEvent) => {
+ if (readOnly) return;
+ const t = e.target as HTMLElement;
+ // Controls, folder tiles, and the crumb keep their own menus and clicks.
+ if (t.closest("button,a,input,textarea,[role='button'],[role='menuitem'],[data-no-marquee]"))
+ return;
+ const card = t.closest<HTMLElement>("[data-sel-id]");
+ if (card) {
+ const id = card.dataset.selId!;
+ if (!shown.some((a) => a.id === id)) return;
+ e.preventDefault();
+ const ids = picked.has(id) ? [id, ...pickedIds.filter((x) => x !== id)] : [id];
+ if (!picked.has(id)) setPicked(new Set([id]));
+ setCtxMenu({ x: e.clientX, y: e.clientY, ids });
+ return;
+ }
+ if (openFolder !== null) return;
+ e.preventDefault();
+ setCtxMenu({ x: e.clientX, y: e.clientY, ids: null });
+ };
+
return (
<div
ref={attachTarget}
@@ -787,6 +871,7 @@ function ProjectFilesPanel({
dropActive &&
"rounded-xl bg-[#0a84ff]/5 outline-2 outline-dashed outline-offset-[-4px] outline-[#0a84ff]/60"
)}
+ onContextMenu={onPanelContextMenu}
>
{/* An export in flight spins on the Media rail tile, not here. */}
{!readOnly && (
@@ -801,15 +886,65 @@ function ProjectFilesPanel({
multiple
hidden
onChange={(e) => {
- if (e.target.files?.length) onImport(e.target.files);
+ if (e.target.files?.length)
+ onImport(e.target.files, { folderId: openFolder ?? undefined });
e.target.value = "";
}}
/>
</div>
)}
- <ScrollArea className="min-h-0 flex-1" contentClassName="pb-3.5">
- {templates.length > 0 && (
+ {openFolder !== null && (
+ <div className="flex h-9 shrink-0 items-center px-2 pb-1.5">
+ <FolderCrumb
+ className="text-sm"
+ root="Project Files"
+ name={folders.find((f) => f.id === openFolder)?.name ?? "Folder"}
+ mime={MEDIA_MOVE_MIME}
+ onBack={() => setOpenFolder(null)}
+ onDropOut={(ids) => useEditor.getState().moveAssetsToMediaFolder(ids, null)}
+ />
+ </div>
+ )}
+ {openFolder === null && (folders.length > 0 || creatingIds !== null) && (
+ <div className="shrink-0 px-3.5">
+ <FolderShelf
+ rows
+ folders={readOnly ? folders.map((f) => ({ ...f, locked: true })) : folders}
+ mime={MEDIA_MOVE_MIME}
+ statOf={(id) => ({ count: assets.filter((a) => a.folderId === id).length })}
+ onOpen={(id) => setOpenFolder(id)}
+ onCreate={(name) => {
+ useEditor.getState().addMediaFolder(name, creatingIds ?? undefined);
+ }}
+ onRename={(id, name) => useEditor.getState().renameMediaFolder(id, name)}
+ onDelete={(id) => useEditor.getState().removeMediaFolder(id)}
+ onDropIds={(ids, fid) => useEditor.getState().moveAssetsToMediaFolder(ids, fid)}
+ onDropFiles={
+ readOnly
+ ? undefined
+ : (files, fid) => onImport(files, { mediaOnly: true, folderId: fid })
+ }
+ onRefDrop={(ref, fid) => {
+ // Media made elsewhere — a generation, a recording, a timeline
+ // clip's asset — dropped on a folder tile joins Media filed there.
+ if (ref.scope !== "project") return;
+ useEditor.getState().updateAsset(ref.id, {
+ origin: undefined,
+ chatId: undefined,
+ folderId: fid,
+ });
+ }}
+ creating={creatingIds !== null}
+ onCreatingChange={(c) => {
+ if (!c) setCreatingIds(null);
+ }}
+ />
+ </div>
+ )}
+
+ <ScrollArea className="min-h-0 flex-1" contentClassName="pt-1 pb-3.5">
+ {openFolder === null && templates.length > 0 && (
<div className="flex flex-col gap-1.5 px-3.5 pb-3">
{templates.map((t) => (
<TemplateCard
@@ -833,15 +968,21 @@ function ProjectFilesPanel({
))}
</div>
)}
- {assets.length === 0 && !importing ? (
- <div className="px-2 py-7 text-center text-xs leading-relaxed text-balance text-muted-foreground">
- <div className="mb-3 flex justify-center gap-3.5">
- <Film className="size-5" />
- <Music className="size-5" />
+ {shown.length === 0 && !importing ? (
+ openFolder !== null ? (
+ <div className="px-3.5 py-6 text-center text-xs text-muted-foreground">
+ Empty folder
</div>
- Drop videos, audio and images assets here. They are only available in
- this project.
- </div>
+ ) : assets.length === 0 && folders.length === 0 ? (
+ <div className="px-2 py-7 text-center text-xs leading-relaxed text-balance text-muted-foreground">
+ <div className="mb-3 flex justify-center gap-3.5">
+ <Film className="size-5" />
+ <Music className="size-5" />
+ </div>
+ Drop videos, audio and images assets here. They are only available in
+ this project.
+ </div>
+ ) : null
) : (
<Marquee
scope="self"
@@ -850,14 +991,15 @@ function ProjectFilesPanel({
selected={picked}
setSelected={setPicked}
>
- {assets.map((a) => (
+ {shown.map((a) => (
<AssetCard
key={a.id}
asset={a}
projectId={projectId}
selected={picked.has(a.id)}
- onSelect={(e) => pick(e, a.id, assets.map((x) => x.id))}
+ onSelect={(e) => pick(e, a.id, shown.map((x) => x.id))}
dragGroup={pickedIds}
+ onDragLanded={() => setPicked(new Set())}
/>
))}
{importing && (
@@ -871,7 +1013,7 @@ function ProjectFilesPanel({
</Marquee>
)}
- {exports.length + exporting.length > 0 && (
+ {openFolder === null && exports.length + exporting.length > 0 && (
<div className="mt-5 px-3.5">
<div className="mb-2 text-[13px] font-semibold tracking-tight">Exports</div>
<div className="flex flex-col gap-1.5">
@@ -981,6 +1123,88 @@ function ProjectFilesPanel({
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
+
+ {/* The right-click menu: the same dropdown the cards' "…" button uses,
+ anchored to the pointer. */}
+ <DropdownMenu open={ctxMenu !== null} onOpenChange={(o) => !o && setCtxMenu(null)}>
+ {ctxMenu && (
+ <DropdownMenuContent
+ className="w-48"
+ sideOffset={0}
+ anchor={{
+ getBoundingClientRect: () => new DOMRect(ctxMenu.x, ctxMenu.y, 0, 0),
+ }}
+ // No focus return on close — there is no trigger to go back to,
+ // and reclaiming focus would blur the folder-name field the "New
+ // folder" items open, whose blur cancels the creation.
+ finalFocus={false}
+ >
+ {ctxMenu.ids === null ? (
+ <DropdownMenuItem
+ onClick={() => {
+ setCreatingIds([]);
+ setCtxMenu(null);
+ }}
+ >
+ <FolderPlus /> New folder
+ </DropdownMenuItem>
+ ) : (
+ <>
+ <DropdownMenuItem
+ onClick={() => {
+ // The name field opens on the root shelf; the picked ids
+ // file into the folder when the name is committed.
+ setCreatingIds(ctxMenu.ids);
+ setOpenFolder(null);
+ setCtxMenu(null);
+ }}
+ >
+ <FolderPlus /> New folder
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => {
+ removeMany(ctxMenu.ids!);
+ setCtxMenu(null);
+ }}
+ >
+ <Trash2 /> Delete
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ )}
+ </DropdownMenu>
+
+ <AlertDialog open={deletingIds !== null} onOpenChange={(o) => !o && setDeletingIds(null)}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {deletingIds !== null && deletingIds.length > 1
+ ? `Remove ${deletingIds.length} files from the project?`
+ : "Remove this file from the project?"}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ Timeline clips made from them are removed too.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ className="bg-destructive/10 text-destructive hover:bg-destructive/20"
+ onClick={(e) => {
+ e.preventDefault();
+ const s = useEditor.getState();
+ for (const id of deletingIds ?? []) s.removeAsset(id);
+ setDeletingIds(null);
+ }}
+ >
+ Remove
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</div>
);
}
@@ -1024,6 +1248,7 @@ function AssetCard({
selected,
onSelect,
dragGroup,
+ onDragLanded,
}: {
asset: MediaAsset;
projectId: string;
@@ -1034,6 +1259,8 @@ function AssetCard({
onSelect?: (e: React.MouseEvent) => void;
/** Everything picked right now, so dragging one card drags them all. */
dragGroup?: string[];
+ /** A drop that landed leaves nothing to keep picked. */
+ onDragLanded?: () => void;
}) {
const caps = useCutCaps();
const [saved, setSaved] = useState(false);
@@ -1097,7 +1324,15 @@ function AssetCard({
onClick={onSelect}
onDragStart={(e) => {
setAssetDragData(e, asset.id, dragGroup);
- setObjectDragImage(e);
+ // The same selection as a folder-move payload, so a folder tile or
+ // the crumb can take the drop; the ghost gathers the picked cards
+ // into one stack under the cursor, counted.
+ const ids =
+ selected && dragGroup?.includes(asset.id)
+ ? [asset.id, ...dragGroup.filter((x) => x !== asset.id)]
+ : [asset.id];
+ e.dataTransfer.setData(MEDIA_MOVE_MIME, JSON.stringify(ids));
+ setObjectDragImage(e, ids.length, ids, onDragLanded);
}}
onDragEnd={clearAssetDrag}
onMouseEnter={() => {
@@ -1441,7 +1676,7 @@ function LibraryPanel({ projectId }: { projectId: string }) {
const ids = picked.has(a.id) ? [a.id, ...[...picked].filter((id) => id !== a.id)] : [a.id];
e.dataTransfer.setData(LIBRARY_MOVE_MIME, JSON.stringify(ids));
e.dataTransfer.effectAllowed = "copyMove";
- setObjectDragImage(e);
+ setObjectDragImage(e, ids.length, ids, () => setPicked(new Set()));
};
const bothShelves = availableResidencies().length > 1;
@@ -1600,7 +1835,7 @@ function LibraryPanel({ projectId }: { projectId: string }) {
</div>
) : null
) : (
- <ScrollArea className="min-h-0 flex-1" contentClassName="pb-3.5">
+ <ScrollArea className="min-h-0 flex-1" contentClassName="pt-1 pb-3.5">
<Marquee
scope="self"
rootClassName="relative min-h-full px-3.5"
diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.ts
index e4d12fae..acb00d02 100644
--- a/site/src/cut/lib/aiContext.ts
+++ b/site/src/cut/lib/aiContext.ts
@@ -250,12 +250,18 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
.filter((a) => a.type === "font")
.map((a) => ({ id: uploadedFontId(a.id), label: a.name })),
],
+ // The Media panel's folders, when the project has any; each filed asset
+ // carries its folderId below (media_organize moves them).
+ ...(s.mediaFolders.length > 0
+ ? { mediaFolders: s.mediaFolders.map((f) => ({ id: f.id, name: f.name })) }
+ : {}),
media: shownAssets.map((a) => ({
id: a.id,
name: a.name,
type: a.type,
duration: r(a.duration),
...(a.origin ? { origin: a.origin } : {}),
+ ...(a.folderId != null ? { folderId: a.folderId } : {}),
// Source spans whose frame map exists (persisted with the project):
// distinct-moment times and cut candidates recorded by an earlier watch
// or by the background sweep. The map aims a watch — it is not seen
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 105326d1..98f3775b 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -2968,6 +2968,53 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
throw new ToolError('`to` must be "media" or "library".');
},
+ media_organize: (s, input) => {
+ const folderOf = (id: string) => {
+ const f = s.mediaFolders.find((x) => x.id === id);
+ if (!f) throw new ToolError(`No Media folder with id ${id}.`);
+ return f;
+ };
+ const assetIds = () => {
+ const ids = Array.isArray(input.asset_ids) ? input.asset_ids.map(String) : [];
+ for (const id of ids) requireItem(s.assets, id, "project asset");
+ return ids;
+ };
+ switch (String(input.action ?? "")) {
+ case "create_folder": {
+ const name = String(input.name ?? "").trim();
+ if (!name) throw new ToolError("A folder name is required.");
+ const ids = assetIds();
+ const folderId = s.addMediaFolder(name, ids);
+ return { folderId, name, ...(ids.length > 0 ? { filed: ids.length } : {}) };
+ }
+ case "rename_folder": {
+ const name = String(input.name ?? "").trim();
+ if (!name) throw new ToolError("A folder name is required.");
+ const f = folderOf(String(input.folder_id ?? ""));
+ s.renameMediaFolder(f.id, name);
+ return { renamed: true, name };
+ }
+ case "delete_folder": {
+ const f = folderOf(String(input.folder_id ?? ""));
+ s.removeMediaFolder(f.id);
+ return { deleted: true, note: "Its files moved to the Media panel's top level." };
+ }
+ case "move_asset": {
+ const folderId =
+ typeof input.folder_id === "string" && input.folder_id
+ ? folderOf(input.folder_id).id
+ : null;
+ const ids = assetIds();
+ if (ids.length === 0)
+ throw new ToolError("asset_ids is required — the media to file.");
+ s.moveAssetsToMediaFolder(ids, folderId);
+ return { moved: ids.length, folderId };
+ }
+ default:
+ throw new ToolError(`Unknown action "${String(input.action)}".`);
+ }
+ },
+
convert_media: async (s, input) => {
const projectId = s.projectId;
if (!projectId) throw new ToolError("No project open.");
diff --git a/site/src/cut/lib/backend/browser/router.ts b/site/src/cut/lib/backend/browser/router.ts
index a55a9206..be61da42 100644
--- a/site/src/cut/lib/backend/browser/router.ts
+++ b/site/src/cut/lib/backend/browser/router.ts
@@ -91,6 +91,7 @@ async function putProject(req: Request, id: string): Promise<Response> {
: existing.overlayClips,
overlays: Array.isArray(body.overlays) ? body.overlays : existing.overlays,
templates: Array.isArray(body.templates) ? body.templates : existing.templates,
+ mediaFolders: Array.isArray(body.mediaFolders) ? body.mediaFolders : existing.mediaFolders,
aspect: normalizeAspect(body.aspect) ?? existing.aspect,
fadeIn: typeof body.fadeIn === "number" ? body.fadeIn : existing.fadeIn,
fadeOut: typeof body.fadeOut === "number" ? body.fadeOut : existing.fadeOut,
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index bc9bd9b2..bb7809e4 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -22,6 +22,7 @@ import type {
ClipSpan,
LibraryTemplate,
MediaAsset,
+ MediaFolder,
Overlay,
OverlayKind,
OverlayPatch,
@@ -206,6 +207,15 @@ export const PPS_MIN = 0.01;
export const PPS_MAX = 800;
const clampPps = (v: number) =>
Number.isFinite(v) ? Math.max(PPS_MIN, Math.min(PPS_MAX, v)) : 60;
+/** An asset filed into a Media folder. The Media panel shows what the user put
+ * there — assets with no `origin` — so filing a created clip (a render, a
+ * voiceover, a recording) is also its move out of the place that made it. */
+const filedInMedia = (a: MediaAsset, folderId: string | null): MediaAsset => ({
+ ...a,
+ folderId: folderId ?? undefined,
+ origin: undefined,
+ chatId: undefined,
+});
/** Tallest the timeline may grow: the window height less room for the top bar
* and a usable preview. The constant covers code running without a window. */
export const timelineHMax = () =>
@@ -686,6 +696,16 @@ export interface EditorState {
addTemplate: (input: TemplateSaveInput) => LibraryTemplate;
renameTemplate: (id: string, name: string) => void;
removeTemplate: (id: string) => void;
+ /** The Media panel's folders (ProjectDoc.mediaFolders). Like the asset
+ * list, they sit outside the undo history. */
+ mediaFolders: MediaFolder[];
+ /** Create a Media folder, filing `assetIds` into it; returns the new id. */
+ addMediaFolder: (name: string, assetIds?: string[]) => string;
+ renameMediaFolder: (id: string, name: string) => void;
+ /** Delete a Media folder; its assets drop back to the panel's top level. */
+ removeMediaFolder: (id: string) => void;
+ /** File assets into a Media folder (null = back to the top level). */
+ moveAssetsToMediaFolder: (ids: string[], folderId: string | null) => void;
/** Append a project asset to a template as one more part at its end. */
addAssetToTemplate: (templateId: string, assetId: string) => void;
select: (sel: Selection) => void;
@@ -1191,6 +1211,7 @@ const DOC_KEYS = [
"audioClips",
"overlays",
"templates",
+ "mediaFolders",
"aspect",
"fadeIn",
"fadeOut",
@@ -1545,6 +1566,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
audioClips: [],
overlays: [],
templates: [],
+ mediaFolders: [],
aspect: lastChosenAspect() ?? "9:16",
aspectTouched: lastChosenAspect() !== null,
fadeIn: 0,
@@ -1594,6 +1616,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
audioClips: [],
overlays: [],
templates: [],
+ mediaFolders: [],
aspect: lastChosenAspect() ?? "9:16",
aspectTouched: lastChosenAspect() !== null,
fadeIn: 0,
@@ -1960,6 +1983,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
audioClips: merged.audioClips,
overlays: withLooks.overlays,
templates: doc.templates ?? [],
+ mediaFolders: doc.mediaFolders ?? [],
aspect: normalizeAspect(doc.aspect) ?? lastChosenAspect() ?? "9:16",
aspectTouched: doc.aspect !== undefined || lastChosenAspect() !== null,
fadeIn: doc.fadeIn ?? 0,
@@ -3662,6 +3686,42 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
removeTemplate: (id) => set({ templates: get().templates.filter((t) => t.id !== id) }),
+ addMediaFolder: (name, assetIds) => {
+ const folder: MediaFolder = {
+ id: crypto.randomUUID().slice(0, 10),
+ name,
+ createdAt: Date.now(),
+ };
+ const file = new Set(assetIds ?? []);
+ set((s) => ({
+ mediaFolders: [...s.mediaFolders, folder],
+ ...(file.size > 0
+ ? { assets: s.assets.map((a) => (file.has(a.id) ? filedInMedia(a, folder.id) : a)) }
+ : {}),
+ }));
+ return folder.id;
+ },
+
+ renameMediaFolder: (id, name) =>
+ set((s) => ({
+ mediaFolders: s.mediaFolders.map((f) => (f.id === id ? { ...f, name } : f)),
+ })),
+
+ removeMediaFolder: (id) =>
+ set((s) => ({
+ mediaFolders: s.mediaFolders.filter((f) => f.id !== id),
+ assets: s.assets.map((a) =>
+ a.folderId === id ? { ...a, folderId: undefined } : a
+ ),
+ })),
+
+ moveAssetsToMediaFolder: (ids, folderId) => {
+ const move = new Set(ids);
+ set((s) => ({
+ assets: s.assets.map((a) => (move.has(a.id) ? filedInMedia(a, folderId) : a)),
+ }));
+ },
+
addAssetToTemplate: (templateId, assetId) => {
const s = get();
const t = s.templates.find((x) => x.id === templateId);
@@ -4896,7 +4956,7 @@ export const docOverlays = (() => {
export function storedAssets(assets: MediaAsset[]): StoredAsset[] {
return assets
.filter((a) => !tabOnlyUpload(a))
- .map(({ id, fileName, name, type, duration, width, height, origin, chatId, language, watch, speech, beats, sceneCuts }) => ({
+ .map(({ id, fileName, name, type, duration, width, height, origin, chatId, folderId, language, watch, speech, beats, sceneCuts }) => ({
id,
fileName,
name,
@@ -4906,6 +4966,7 @@ export function storedAssets(assets: MediaAsset[]): StoredAsset[] {
...(height !== undefined ? { height } : {}),
...(origin !== undefined ? { origin } : {}),
...(chatId !== undefined ? { chatId } : {}),
+ ...(folderId != null ? { folderId } : {}),
...(language !== undefined ? { language } : {}),
...(watch !== undefined ? { watch } : {}),
...(speech !== undefined ? { speech } : {}),
@@ -4923,6 +4984,7 @@ export function serializeDoc(s: {
audioClips: AudioClip[];
overlays: Overlay[];
templates: LibraryTemplate[];
+ mediaFolders: MediaFolder[];
aspect: Aspect;
fadeIn: number;
fadeOut: number;
@@ -4944,6 +5006,7 @@ export function serializeDoc(s: {
// serialize byte-identical to the pre-union shape.
overlays: docOverlays(s.overlays),
templates: s.templates,
+ mediaFolders: s.mediaFolders,
aspect: s.aspect,
fadeIn: s.fadeIn,
fadeOut: s.fadeOut,
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index 54545aef..e32e086c 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -204,6 +204,17 @@ export interface StoredAsset {
/** For origin "chat": the chat thread that made it. Deleting that thread
* deletes the assets it still owns (see chatAssets.ts). */
chatId?: string;
+ /** Media panel folder this file is filed in (see ProjectDoc.mediaFolders);
+ * absent/null = the panel's top level. */
+ folderId?: string | null;
+}
+
+/** A folder in the Media panel's Project Files view — a flat, project-local
+ * grouping of user imports; assets point at one via `folderId`. */
+export interface MediaFolder {
+ id: string;
+ name: string;
+ createdAt: number;
}
/** Most labels one note may wear. Both clients hold the line at this — the
@@ -1410,6 +1421,8 @@ export interface ProjectDoc {
/** Templates saved in this project (their media reference project files by
* name). Adding one to the shared Library copies its media out. */
templates?: LibraryTemplate[];
+ /** The Media panel's folders; assets file into them via their `folderId`. */
+ mediaFolders?: MediaFolder[];
/** Which project folder this belongs to (null/absent = ungrouped). */
folderId?: string | null;
/** In-progress or finished brief-to-video run (genvideo). Persisted so a
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 175b3b69..eebbee6d 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -370,6 +370,7 @@ How to decide the details the user left open. Make the call, apply it, and state
Project media (\`media\` in editor_state) is every file in the open project. The Media panel shows the user's own imports — assets with no origin tag; created media (origin generated, voiceover, stock, chat, freeze, recording) lives where it was made until filed away.
- add_clip / add_overlay_video place a project asset on the timeline; listen_audio plays an asset's sound to you — an audio asset, or a video/clip's own track; watch_video is the visual sibling.
- file_asset moves a created asset into Media (to:"media", clears its origin) or copies any asset into the Library (to:"library").
+- media_organize keeps the Media panel's own folders (\`mediaFolders\` in editor_state, per project): create/rename/delete a folder, move_asset to file media into one — filing a created asset also moves it into Media, like dropping its card on a folder tile.
- delete_asset removes an asset from the project plus its timeline clips; the media does not come back with undo, so only on an explicit ask, and say what went with it.
- convert_media rewrites project media as MP4 (H.264/AAC) in place, one call for a whole list of asset ids. Reach for it when footage plays black or shows a format warning — phone HEVC, ProRes, raw PCM sound — and whenever someone asks for mp4 files. That ask is usually files dropped straight on this chat: convert them and each one is on its own card in the thread, converted, ready to download or drag onto the timeline — close by saying they're on their cards. An asset that came from the Media panel stays there. Streams that already fit are copied, so most .mov files convert in seconds, and a file that is already H.264/AAC MP4 comes back untouched (say so instead of claiming a conversion); max_height shrinks an oversized source at the same time. Clips already cut from the asset keep playing. It runs on whichever machine already holds the bytes — this Mac, the render worker, or the tab — and works with no editor tab attached; when nothing available can decode the source the error names the fix (the Mac app, another browser, or moving the project to the cloud), so report it and move on.
The Library is shared across every project: folders, reusable assets, and templates — a template is a saved arrangement (clips, overlays, titles, captions, by reference) that comes back editable.
diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.ts
index 82b2a8b7..225f1f29 100644
--- a/site/src/cut/server/cloud/projects.ts
+++ b/site/src/cut/server/cloud/projects.ts
@@ -202,6 +202,7 @@ export const projectsCloud = {
: existing.overlayClips,
overlays: Array.isArray(body.overlays) ? body.overlays : existing.overlays,
templates: Array.isArray(body.templates) ? body.templates : existing.templates,
+ mediaFolders: Array.isArray(body.mediaFolders) ? body.mediaFolders : existing.mediaFolders,
aspect: normalizeAspect(body.aspect) ?? existing.aspect,
fadeIn: typeof body.fadeIn === "number" ? body.fadeIn : existing.fadeIn,
fadeOut: typeof body.fadeOut === "number" ? body.fadeOut : existing.fadeOut,
diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.ts
index aa069bda..14d6055a 100644
--- a/site/src/cut/server/http/projects.ts
+++ b/site/src/cut/server/http/projects.ts
@@ -127,6 +127,7 @@ export const projectsApi = {
: existing.overlayClips,
overlays: Array.isArray(body.overlays) ? body.overlays : existing.overlays,
templates: Array.isArray(body.templates) ? body.templates : existing.templates,
+ mediaFolders: Array.isArray(body.mediaFolders) ? body.mediaFolders : existing.mediaFolders,
aspect: normalizeAspect(body.aspect) ?? existing.aspect,
fadeIn: typeof body.fadeIn === "number" ? body.fadeIn : existing.fadeIn,
fadeOut: typeof body.fadeOut === "number" ? body.fadeOut : existing.fadeOut,