Skip to content

Open source CapCut alternative.

TypeScript

feat(site): share library folders and assets [rebuild]

David Le5b33da41f4aa
diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.md
index fea76f21..f6bc06d3 100644
--- a/docs/guides/backend-apis.md
+++ b/docs/guides/backend-apis.md
@@ -7,7 +7,7 @@ the site's own client views, signed in with a session cookie.
endpoint is a deliberate exception with a product reason — today only Better
Auth's own routes, the signature-verified Stripe and Resend webhooks, the
HMAC-token-verified one-click email unsubscribe and promotion button redirect,
-and a plain health check. Ship
+the token-authorized Cut project and library share viewers, and a plain health check. Ship
a handler without the wrapper and the endpoint is open to anyone.
## Authentication
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.md
index 9de9601a..f2f5d9cc 100644
--- a/docs/guides/cut/README.md
+++ b/docs/guides/cut/README.md
@@ -38,6 +38,8 @@ An export is the preview drawn again frame by frame into an MP4 by the same comp
A cloud project can be shared read-only by link, with the owner choosing which surfaces a viewer can open. The server filters the doc and its media to that set before anything leaves; the rail still shows every tab, and a withheld one sits locked with a hover note saying the view is read-only. A viewer can copy the shared project into their own account.
+Folders and assets use the project Share dialog for read-only public links or verified-email access; local items first become independent cloud copies. Folder access follows current contents; revocation blocks new requests immediately, while issued media URLs expire within two hours.
+
## The assistant
The chat drives everything the editor can do through typed tools, and every tool's schema and prompt text derive from the same constants the UI uses, so the catalog stays true. The assistant guide covers the harness, the tools, and the evals that hold the line.
diff --git a/site/prisma/Cut.prisma b/site/prisma/Cut.prisma
index 6d2dd14a..80c19a95 100644
--- a/site/prisma/Cut.prisma
+++ b/site/prisma/Cut.prisma
@@ -66,7 +66,7 @@ model CutFolder {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
- @@index([userId, scope])
+ @@index([userId, scope, parentId])
}
// One R2 object. Quota and orphan GC read from here: `pending` rows were
@@ -120,6 +120,7 @@ model CutLibraryAsset {
updatedAt DateTime @updatedAt
@@index([userId, createdAt])
+ @@index([userId, folderId, id])
}
model CutTemplate {
diff --git a/site/prisma/cut-library-sharing.prisma b/site/prisma/cut-library-sharing.prisma
new file mode 100644
index 00000000..26ff6ba0
--- /dev/null
+++ b/site/prisma/cut-library-sharing.prisma
@@ -0,0 +1,13 @@
+// Read-only links to a library folder tree or one asset.
+model CutLibraryShare {
+ id String @id
+ userId String
+ kind String
+ targetId String
+ access String @default("restricted")
+ emails Json @default("[]")
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@unique([userId, kind, targetId])
+}
diff --git a/site/src/app/cut/s/library/[token]/page.tsx b/site/src/app/cut/s/library/[token]/page.tsx
new file mode 100644
index 00000000..09617691
--- /dev/null
+++ b/site/src/app/cut/s/library/[token]/page.tsx
@@ -0,0 +1,12 @@
+import type { Metadata } from "next";
+import { Suspense } from "react";
+import { NoSessionReplay } from "@/app/_components/NoSessionReplay";
+import { SharedLibraryView } from "@/cut/components/SharedLibraryView";
+
+export const metadata: Metadata = {
+ title: "Shared library · Donkey Cut",
+ robots: { index: false, follow: false },
+};
+export default function SharedLibraryPage() {
+ return <><NoSessionReplay /><Suspense><SharedLibraryView /></Suspense></>;
+}
diff --git a/site/src/cut/components/LibraryShareDialog.tsx b/site/src/cut/components/LibraryShareDialog.tsx
new file mode 100644
index 00000000..ae1185c7
--- /dev/null
+++ b/site/src/cut/components/LibraryShareDialog.tsx
@@ -0,0 +1,60 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { Cloud, Loader2 } from "lucide-react";
+import { useQueryClient } from "@tanstack/react-query";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { ShareDialog } from "@/cut/components/ShareDialog";
+import { copyLibraryForSharing } from "@/cut/lib/libraryShareCopy";
+import { refetchLibrary } from "@/cut/lib/queries";
+import type { LibraryData } from "@/cut/lib/library";
+import type { LibraryShareTarget } from "@/cut/lib/librarySharing";
+import type { Residency } from "@/cut/lib/residency";
+
+type Props = {
+ target: LibraryShareTarget & { residency: Residency };
+ library: LibraryData;
+ onClose: () => void;
+ onCopied: (target: LibraryShareTarget) => void;
+};
+export function LibraryShareDialog({ target, library, onClose, onCopied }: Props) {
+ const [ready, setReady] = useState<LibraryShareTarget | null>(target.residency === "cloud" ? target : null);
+ const [copying, setCopying] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const started = useRef(false);
+ const mounted = useRef(true);
+ useEffect(() => {
+ mounted.current = true;
+ return () => { mounted.current = false; };
+ }, []);
+ const client = useQueryClient();
+ const copy = async () => {
+ if (started.current) return;
+ started.current = true;
+ setCopying(true);
+ setError(null);
+ try {
+ const landed = await copyLibraryForSharing(target, target.residency, library);
+ void refetchLibrary(client);
+ if (mounted.current) {
+ setReady(landed);
+ onCopied(landed);
+ }
+ } catch (e) {
+ if (mounted.current) setError(e instanceof Error ? e.message : "Could not copy to Cloud.");
+ } finally {
+ setCopying(false);
+ started.current = false;
+ }
+ };
+ if (ready) return <ShareDialog libraryTarget={ready} onClose={onClose} />;
+ return <Dialog open onOpenChange={(open) => { if (!open && !copying) onClose(); }}>
+ <DialogContent className="sm:max-w-sm" showCloseButton={!copying}>
+ <DialogHeader><DialogTitle>Share {target.kind}</DialogTitle></DialogHeader>
+ <p className="text-sm text-muted-foreground">Copy this {target.kind} to Cloud so people can open it while your device is offline. Share settings will apply to the cloud copy. Your local files stay here.</p>
+ {error && <p role="alert" className="text-sm text-destructive">{error}</p>}
+ <Button disabled={copying} onClick={() => void copy()}>{copying ? <Loader2 className="animate-spin" /> : <Cloud />}{copying ? "Copying to Cloud…" : "Copy to Cloud"}</Button>
+ </DialogContent>
+ </Dialog>;
+}
diff --git a/site/src/cut/components/LibraryView.tools.ts b/site/src/cut/components/LibraryView.tools.ts
index 2121f465..7a4ace18 100644
--- a/site/src/cut/components/LibraryView.tools.ts
+++ b/site/src/cut/components/LibraryView.tools.ts
@@ -8,7 +8,21 @@
import { bool, num, obj, str, type AiToolDef } from "@/cut/lib/aiToolDef";
+import { LIBRARY_SHARE_ACTIONS, LIBRARY_SHARE_KINDS, SHARE_ACCESS } from "@/cut/lib/librarySharing";
+
export const LIBRARY_TOOLS = [
+ {
+ name: "library_share",
+ description: "Manage a read-only link to a Library folder and all its descendants, or one asset. Get reads current settings; save replaces access and the email allowlist; remove revokes this link. Public access lets anyone with the link preview and download. Restricted access requires the owner or a signed-in invited email. Local items require copy_to_cloud:true on save; this creates an independent cloud copy and returns its target id. Use that returned id to manage its share. Share only when the user asks. Adding emails grants access; give the user the link to send.",
+ inputSchema: obj({
+ action: { type: "string", enum: [...LIBRARY_SHARE_ACTIONS] },
+ kind: { type: "string", enum: [...LIBRARY_SHARE_KINDS] },
+ id: str("Library folder or asset id from library_list"),
+ access: { type: "string", enum: [...SHARE_ACCESS] },
+ emails: { type: "array", items: { type: "string" }, description: "Complete invited email list for save" },
+ copy_to_cloud: bool("Copy a local item and its contents to Cloud before sharing"),
+ }, ["action", "kind", "id"]),
+ },
{
name: "library_list",
description:
diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsx
index 2830709f..4950f07f 100644
--- a/site/src/cut/components/LibraryView.tsx
+++ b/site/src/cut/components/LibraryView.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useRouter, useSearchParams } from "next/navigation";
import {
@@ -18,6 +18,7 @@ import {
Music,
Plus,
RotateCcw,
+ Share2,
Trash2,
Type,
Upload,
@@ -99,6 +100,8 @@ import {
RESIDENCY_LABEL,
type Residency,
} from "@/cut/lib/residency";
+import { LibraryShareDialog } from "@/cut/components/LibraryShareDialog";
+import type { LibraryShareTarget } from "@/cut/lib/librarySharing";
import { Lightbox } from "./Lightbox";
import { TabStatus } from "./TabStatus";
import { TemplateCard } from "./TemplateCard";
@@ -437,6 +440,12 @@ export function LibraryView() {
const [pending, setPending] = useState<Pending[]>([]);
// One drain bounds probe, decode, and transfer work across overlapping drops.
const uploadTail = useRef(Promise.resolve());
+ const [sharing, setSharing] = useState<(LibraryShareTarget & { residency: Residency }) | null>(null);
+ useLayoutEffect(() => () => setSharing(null), []);
+ const shareFolder = (id: string) => {
+ const folder = folders.find((f) => f.id === id);
+ if (folder && live(folder.residency)) setSharing({ kind: "folder", id, residency: folder.residency });
+ };
const [addOpen, setAddOpen] = useState(false);
const [url, setUrl] = useState("");
const [folderCreating, setFolderCreating] = useState(false);
@@ -945,6 +954,7 @@ export function LibraryView() {
/>
)}
<div className="flex items-center gap-2">
+ {openFolder && openOwner && <Button variant="outline" disabled={!live(openOwner)} onClick={() => shareFolder(openFolder)}><Share2 data-icon="inline-start" /> Share</Button>}
{(openFolder === null || newParent) && (
<Button variant="outline" onClick={() => setFolderCreating(true)}>
<FolderPlus data-icon="inline-start" /> New folder
@@ -992,6 +1002,7 @@ export function LibraryView() {
) : null;
}}
onOpen={gotoFolder}
+ onShare={shareFolder}
onCreate={async (name) => {
if (!live(newShelf)) return;
const f = await createLibraryFolder(name, newShelf, newParent);
@@ -1107,6 +1118,7 @@ export function LibraryView() {
<LibraryCard
key={a.id}
asset={a}
+ onShare={() => setSharing({ kind: "asset", id: a.id, residency: a.residency })}
area={a.type === "audio" ? audioArea : TILE_AREA}
selected={selected.has(a.id)}
dragGroup={pickedRun}
@@ -1190,6 +1202,11 @@ export function LibraryView() {
}}
finalFocus={false}
>
+ {ctxMenu.ids.length === 1 && <DropdownMenuItem onClick={() => {
+ const asset = shown.find((a) => a.id === ctxMenu.ids[0]);
+ if (asset && live(asset.residency)) setSharing({ kind: "asset", id: asset.id, residency: asset.residency });
+ setCtxMenu(null);
+ }}><Share2 /> Share</DropdownMenuItem>}
<DropdownMenuItem
variant="destructive"
onClick={() => {
@@ -1234,6 +1251,12 @@ export function LibraryView() {
</AlertDialogContent>
</AlertDialog>
+ {sharing && library.data && <LibraryShareDialog
+ key={`${sharing.kind}:${sharing.id}`}
+ target={sharing} library={library.data}
+ onClose={() => setSharing(null)}
+ onCopied={(target) => gotoFolder(target.kind === "folder" ? target.id : null)}
+ />}
<Lightbox />
<TabStatus />
</div>
@@ -1256,6 +1279,7 @@ export function LibraryCard({
onClick,
onDelete,
onUse,
+ onShare,
onDragStartExtra,
}: {
asset: LibraryAsset;
@@ -1279,6 +1303,7 @@ export function LibraryCard({
onClick?: (e: React.MouseEvent) => void;
onDelete?: () => void;
onUse?: () => void;
+ onShare?: () => void;
onDragStartExtra?: (e: React.DragEvent) => void;
}) {
// ⌘C over the card copies its mention token. A card inside the current
@@ -1582,6 +1607,7 @@ export function LibraryCard({
className="w-44"
onClick={(e) => e.stopPropagation()}
>
+ {onShare && <DropdownMenuItem disabled={offline} onClick={onShare}><Share2 /> Share</DropdownMenuItem>}
<DropdownMenuItem
onClick={() => downloadLibraryAsset(a)}
disabled={offline}
diff --git a/site/src/cut/components/ShareDialog.tsx b/site/src/cut/components/ShareDialog.tsx
index e3c4512e..971effca 100644
--- a/site/src/cut/components/ShareDialog.tsx
+++ b/site/src/cut/components/ShareDialog.tsx
@@ -17,33 +17,19 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Switch } from "@/components/ui/switch";
-import { apiFetch } from "@/cut/lib/backend";
+import { useQueryClient } from "@tanstack/react-query";
+import { useSharing, sharingKey } from "@/queries/sharing";
+import { requestSharing, type ShareResource } from "@/cut/lib/sharingClient";
+import { librarySharePath, shareEmailSchema, type ShareSettings as AccessSettings } from "@/cut/lib/librarySharing";
import { refreshShareCard, refreshShareLadder } from "@/cut/lib/exportClient";
import { useCutBase } from "@/cut/lib/nav";
import type { ShareFeatures } from "@/cut/lib/types";
-// Google-Docs-style sharing for a cloud project: invite people by email or
-// open the link to anyone, always read-only. The advanced switches opt extra
-// surfaces in; with all of them off a viewer gets the preview and timeline
-// only. Every change PUTs immediately — closing the dialog is done.
-//
-// The dialog renders its final layout on the first frame and disables the
-// controls until the fetch lands, so nothing reflows while it loads. The
-// "Stop sharing" slot keeps its space for the same reason: creating a share
-// by copying the link fills it in place.
+// One sharing dialog for projects, library folders, and assets. Changes save immediately.
-type ShareAccess = "restricted" | "public";
-
-/** What a share says, minus the identity the server assigns it. */
-interface ShareSettings {
- access: ShareAccess;
- emails: string[];
- features: ShareFeatures;
-}
-
-interface ShareState extends ShareSettings {
- id: string;
-}
+type ShareAccess = AccessSettings["access"];
+type ShareSettings = AccessSettings & { features: ShareFeatures };
+type ShareState = ShareSettings & { id: string };
const NO_FEATURES: ShareFeatures = {
chat: false,
@@ -61,24 +47,24 @@ const FEATURE_ROWS: { key: keyof ShareFeatures; label: string; hint: string }[]
{ key: "details", label: "Details", hint: "Caption, tags, and notes" },
];
-const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
-
/** The share link for a share id: the viewer route lives beside the app
* subtree, so the app base minus its /app segment is the share base. */
function shareLink(base: string, shareId: string): string {
return `${window.location.origin}${base.replace(/\/app$/, "")}/s/${shareId}`;
}
-export function ShareDialog({
- projectId,
- onClose,
-}: {
- projectId: string;
- onClose: () => void;
-}) {
+export function ShareDialog(props: ShareResource & { onClose: () => void }) {
+ const { onClose } = props;
+ const projectId = "projectId" in props ? props.projectId : null;
+ const libraryTarget = "libraryTarget" in props ? props.libraryTarget : null;
const base = useCutBase();
- const [loading, setLoading] = useState(true);
- const [share, setShare] = useState<ShareState | null>(null);
+ const client = useQueryClient();
+ const query = useSharing(props);
+ const loading = query.isPending || query.isFetching;
+ const share: ShareState | null = query.data?.share
+ ? { ...query.data.share, features: query.data.share.features ?? NO_FEATURES }
+ : null;
+ const setShare = (next: ShareState | null) => client.setQueryData(sharingKey(props), { share: next });
const [draft, setDraft] = useState("");
const [error, setError] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
@@ -88,63 +74,42 @@ export function ShareDialog({
// it; a failed save drops it back to what the server still holds.
const [pending, setPending] = useState<ShareSettings | null>(null);
const saveSeq = useRef(0);
+ const mutationBusy = useRef(false);
+ const shareId = share?.id;
useEffect(() => {
- let alive = true;
- void apiFetch(`/api/cut/projects/${projectId}/share`)
- .then((r) => (r.ok ? (r.json() as Promise<{ share: ShareState | null }>) : { share: null }))
- .then((body) => {
- if (!alive) return;
- // Opening the dialog is the moment before a link gets pasted
- // somewhere, so bring an existing share's preview card up to date with
- // the cut as it stands.
- // The card is a five-second render and can ride a dialog open. The
- // ladder cannot: it re-encodes the whole cut once per rung, so it waits
- // for the editor's own lull instead (Editor.tsx).
- if (body.share) refreshShareCard(projectId);
- setShare(body.share);
- setLoading(false);
- })
- .catch(() => {
- if (!alive) return;
- setError("Could not load sharing.");
- setLoading(false);
- });
- return () => {
- alive = false;
- };
- }, [projectId]);
+ if (projectId && shareId) refreshShareCard(projectId);
+ }, [projectId, shareId]);
/** PUT the next share state; the row is created on the first save. */
const save = async (next: ShareSettings): Promise<ShareState | null> => {
+ if (mutationBusy.current) return null;
+ mutationBusy.current = true;
const seq = ++saveSeq.current;
setPending(next);
setSaving(true);
setError(null);
try {
- const res = await apiFetch(`/api/cut/projects/${projectId}/share`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(next),
- });
- if (!res.ok) throw new Error();
- const body = (await res.json()) as { share: ShareState };
+ const body = await requestSharing(props, "PUT", next);
+ if (!body.share) throw new Error("Could not save sharing.");
+ const saved = { ...body.share, features: body.share.features ?? NO_FEATURES };
// Sharing for the first time: build the link's preview card now, so the
// first person to open the link sees the cut rather than a placeholder,
// and start the streaming ladder so the link is playable on a phone
// without waiting for the editor to close. This is the one interaction
// that earns a whole-cut render — it is the moment a link starts
// existing — and later saves leave it to the editor's lull.
- if (!share) {
+ if (!share && projectId) {
refreshShareCard(projectId);
void refreshShareLadder(projectId);
}
- setShare(body.share);
- return body.share;
+ if (seq === saveSeq.current) setShare(saved);
+ return saved;
} catch {
setError("Could not save sharing.");
return null;
} finally {
+ mutationBusy.current = false;
// Only the newest save owns the controls: an earlier response landing
// late leaves a rapid second toggle showing what was just clicked.
if (seq === saveSeq.current) {
@@ -164,7 +129,7 @@ export function ShareDialog({
const addEmail = () => {
const email = draft.trim().toLowerCase();
if (!email) return;
- if (!EMAIL_RE.test(email)) {
+ if (!shareEmailSchema.safeParse(email).success) {
setError("That doesn't look like an email address.");
return;
}
@@ -191,32 +156,41 @@ export function ShareDialog({
// the clipboard.
const target = share ?? (await save(current));
if (!target) return;
- await navigator.clipboard.writeText(shareLink(base, target.id));
- setCopied(true);
- setTimeout(() => setCopied(false), 1500);
+ try {
+ const link = libraryTarget
+ ? `${window.location.origin}${base.replace(/\/app$/, "")}${librarySharePath(target.id)}`
+ : shareLink(base, target.id);
+ await navigator.clipboard.writeText(link);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1500);
+ } catch {
+ setError("Could not copy the link. Try again.");
+ }
};
const removeShare = async () => {
+ if (mutationBusy.current) return;
+ mutationBusy.current = true;
setSaving(true);
setError(null);
try {
- const res = await apiFetch(`/api/cut/projects/${projectId}/share`, { method: "DELETE" });
- if (!res.ok) throw new Error();
+ await requestSharing(props, "DELETE");
setShare(null);
} catch {
setError("Could not remove the share.");
} finally {
+ mutationBusy.current = false;
setSaving(false);
}
};
- const busy = loading || saving;
+ const busy = loading || saving || query.isError;
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
- <DialogTitle>Share project</DialogTitle>
+ <DialogTitle>Share {libraryTarget?.kind ?? "project"}</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1.5">
@@ -227,7 +201,7 @@ export function ShareDialog({
className="w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] outline-none focus:border-ring disabled:opacity-60"
type="email"
placeholder="Invite by email, press Enter"
- disabled={loading}
+ disabled={busy}
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
@@ -246,6 +220,7 @@ export function ShareDialog({
>
{email}
<button
+ disabled={busy}
aria-label={`Remove ${email}`}
className="grid size-4 place-items-center rounded-full text-muted-foreground hover:bg-black/10 hover:text-foreground"
onClick={() => removeEmail(email)}
@@ -264,7 +239,7 @@ export function ShareDialog({
</span>
<DropdownMenu>
<DropdownMenuTrigger
- disabled={loading}
+ disabled={busy}
className="flex items-center gap-2 rounded-lg border border-input px-2.5 py-2 text-left text-[12.5px] transition-colors hover:border-ring disabled:opacity-60 disabled:hover:border-input"
>
{current.access === "public" ? (
@@ -313,7 +288,7 @@ export function ShareDialog({
</DropdownMenu>
</div>
- <details className="group">
+ {projectId ? <details className="group">
<summary className="cursor-pointer list-none text-[11px] font-medium tracking-wide text-muted-foreground uppercase select-none">
<span className="inline-flex items-center gap-1">
Also share
@@ -336,15 +311,22 @@ export function ShareDialog({
</span>
<Switch
checked={current.features[key]}
- disabled={loading}
+ disabled={busy}
onCheckedChange={(on) => setFeature(key, on)}
/>
</label>
))}
</div>
- </details>
+ </details> : (
+ <p className="text-[11px] leading-relaxed text-muted-foreground">
+ {libraryTarget?.kind === "folder"
+ ? "Viewers can browse and download this folder’s contents, including subfolders. Changes to the folder appear on the shared link."
+ : "Viewers can preview and download this asset."}
+ </p>
+ )}
- {error && <p className="text-sm text-red-600">{error}</p>}
+ {(error || query.error) && <p role="alert" className="text-sm text-red-600">{error ?? query.error?.message}</p>}
+ {query.isError && <Button variant="outline" onClick={() => void query.refetch()}>Try again</Button>}
</div>
<DialogFooter className="mt-1 flex-col gap-2 sm:flex-col">
<Button className="w-full" disabled={busy} onClick={() => void copyLink()}>
diff --git a/site/src/cut/components/SharedLibraryView.tsx b/site/src/cut/components/SharedLibraryView.tsx
new file mode 100644
index 00000000..7811a402
--- /dev/null
+++ b/site/src/cut/components/SharedLibraryView.tsx
@@ -0,0 +1,92 @@
+"use client";
+
+import Link from "next/link";
+import { useParams, useSearchParams } from "next/navigation";
+import { Download, Folder, Loader2, Type } from "lucide-react";
+import { buttonVariants } from "@/components/ui/button";
+import { useSharedLibrary } from "@/queries/sharing";
+import { ApiError } from "@/queries/apiClient";
+import { librarySharePath, type SharedLibraryAsset } from "@/cut/lib/librarySharing";
+import { authHrefFor } from "@/app/_components/landing/useAppEntryHref";
+import { useInView } from "@/cut/hooks/useInView";
+import { useCutBase } from "@/cut/lib/nav";
+
+function Asset({ asset, token }: { asset: SharedLibraryAsset; token: string }) {
+ const [ref, visible] = useInView<HTMLDivElement>();
+ const src = `/api/cut-shared/library/${encodeURIComponent(token)}/media/${encodeURIComponent(asset.id)}`;
+ return <div ref={ref} className="overflow-hidden rounded-xl border bg-background">
+ <div className="grid aspect-video place-items-center bg-muted">
+ {visible && (asset.type === "video"
+ ? <video aria-label={asset.name} controls playsInline preload="metadata" src={src} className="size-full object-contain" />
+ : asset.type === "audio"
+ ? <audio aria-label={asset.name} controls preload="none" src={src} className="w-full px-3" />
+ : asset.type === "image"
+ // eslint-disable-next-line @next/next/no-img-element -- Protected media resolves through the share access check.
+ ? <img alt={asset.name} src={src} loading="lazy" className="size-full object-contain" />
+ : <Type className="size-8 text-muted-foreground" />)}
+ </div>
+ <div className="flex items-center justify-between gap-3 p-3">
+ <span className="truncate text-sm font-medium" title={asset.name}>{asset.name}</span>
+ <a href={`${src}?download=1`} aria-label={`Download ${asset.name}`} className={buttonVariants({ variant: "ghost", size: "icon" })}><Download className="size-4" /></a>
+ </div>
+ </div>;
+}
+
+export function SharedLibraryView() {
+ const { token } = useParams<{ token: string }>();
+ const params = useSearchParams();
+ const folder = params.get("folder");
+ const offsetValue = Number(params.get("offset") ?? "0");
+ const offset = Number.isSafeInteger(offsetValue) && offsetValue >= 0 ? offsetValue : 0;
+ const query = useSharedLibrary(token, folder, offset);
+ const base = useCutBase();
+ const path = `${base.replace(/\/app$/, "")}${librarySharePath(token)}`;
+ const href = (id?: string | null, page = 0) => {
+ const p = new URLSearchParams();
+ if (id) p.set("folder", id);
+ if (page) p.set("offset", String(page));
+ return `${path}${p.size ? `?${p}` : ""}`;
+ };
+ const data = query.data;
+ const status = query.error instanceof ApiError ? query.error.status : 0;
+ return <main className="app-surface min-h-dvh bg-background font-system text-foreground">
+ <div className="mx-auto max-w-6xl px-5 py-9 sm:px-10">
+ <header className="mb-8 flex items-center justify-between gap-4">
+ <Link href={base} className="text-lg font-semibold">Donkey Cut</Link>
+ <span className="text-xs text-muted-foreground">Shared library · View only</span>
+ </header>
+ {query.isPending ? <div role="status" className="grid min-h-64 place-items-center"><Loader2 aria-label="Loading shared library" className="size-5 animate-spin" /></div>
+ : query.isError ? <div className="flex min-h-64 flex-col items-center justify-center gap-4 text-center">
+ <p role="alert" className="text-sm text-muted-foreground">{status === 401 ? "Sign in to view this share." : status === 403 ? "You don’t have access to this share. Ask the owner to invite you." : status === 404 ? "This share link is no longer available." : "Could not load this share."}</p>
+ {status === 401 || status === 403
+ ? <Link href={authHrefFor("/sign-in", href(folder, offset))} className={buttonVariants()}>Sign in</Link>
+ : status !== 404 && <button onClick={() => void query.refetch()} className={buttonVariants({ variant: "outline" })}>Try again</button>}
+ </div> : data && <>
+ <nav aria-label="Folder breadcrumb" className="mb-5 flex flex-wrap items-center gap-2 text-lg font-semibold">
+ {data.trail.length ? data.trail.map((f, i) => <span key={f.id} className="flex items-center gap-2">
+ {i > 0 && <span className="text-muted-foreground">/</span>}
+ {i === data.trail.length - 1 ? <span>{f.name}</span> : <Link href={href(f.id)} className="text-muted-foreground hover:text-foreground">{f.name}</Link>}
+ </span>) : <h1>{data.name}</h1>}
+ </nav>
+ {!!data.folders.length && <div className="mb-7 flex flex-wrap gap-2">
+ {data.folders.map((f) => <Link key={f.id} href={href(f.id)} className="flex w-24 flex-col gap-1 rounded-xl p-2 hover:bg-muted">
+ <Folder className="size-10 fill-[#8cc5ff] text-[#8cc5ff]" /><span className="line-clamp-2 text-xs font-medium">{f.name}</span>
+ </Link>)}
+ </div>}
+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
+ {data.assets.map((asset) => <Asset key={asset.id} asset={asset} token={token} />)}
+ </div>
+ {data.templates.map((t) => <section key={t.id} className="mt-5 rounded-xl border p-4">
+ <h2 className="mb-2 text-sm font-medium">{t.name}</h2>
+ <p className="mb-2 text-xs text-muted-foreground">Template media</p>
+ {t.files.map((f, i) => <a key={i} className="flex items-center gap-2 py-1 text-sm hover:underline" href={`/api/cut-shared/library/${encodeURIComponent(token)}/media/${encodeURIComponent(t.id)}?${new URLSearchParams({ template: t.id, file: f.fileName, download: "1" })}`}><Download className="size-3" />{f.name}</a>)}
+ </section>)}
+ {!data.folders.length && !data.assets.length && !data.templates.length && <p className="py-16 text-center text-sm text-muted-foreground">This folder is empty.</p>}
+ <nav aria-label="Pages" className="mt-6 flex justify-between">
+ {offset > 0 ? <Link href={href(folder)} className={buttonVariants({ variant: "outline" })}>First page</Link> : <span />}
+ {data.next !== null && <Link href={href(folder, data.next)} className={buttonVariants({ variant: "outline" })}>Next page</Link>}
+ </nav>
+ </>}
+ </div>
+ </main>;
+}
diff --git a/site/src/cut/components/desktopFolders.tsx b/site/src/cut/components/desktopFolders.tsx
index e332da18..1e50479a 100644
--- a/site/src/cut/components/desktopFolders.tsx
+++ b/site/src/cut/components/desktopFolders.tsx
@@ -1,7 +1,7 @@
"use client";
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { Folder, MoreHorizontal, Pencil, Trash2 } from "lucide-react";
+import { Folder, MoreHorizontal, Pencil, Share2, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
@@ -351,6 +351,7 @@ export function FolderShelf<F extends DeskFolder>({
onCreate,
onRename,
onDelete,
+ onShare,
onDropIds,
onDropFolders,
onDropFiles,
@@ -371,6 +372,7 @@ export function FolderShelf<F extends DeskFolder>({
onCreate?: (name: string) => void | Promise<void>;
onRename: (id: string, name: string) => void | Promise<void>;
onDelete: (id: string) => void | Promise<void>;
+ onShare?: (id: string) => void;
onDropIds: (ids: string[], folderId: string) => void;
/** Folders dropped onto a folder tile — filed inside it. */
onDropFolders?: (ids: string[], folderId: string) => void;
@@ -513,6 +515,7 @@ export function FolderShelf<F extends DeskFolder>({
<MoreHorizontal className="size-3.5" />
</DropdownMenuTrigger>
<DropdownMenuContent align="start" onClick={(e) => e.stopPropagation()}>
+ {onShare && <DropdownMenuItem onClick={() => onShare(f.id)}><Share2 /> Share</DropdownMenuItem>}
<DropdownMenuItem
onClick={() => {
setDraft(f.name);
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 2d301110..1ec5c96b 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -1,5 +1,10 @@
"use client";
+import { libraryShareTargetSchema, shareSettingsSchema, librarySharePath } from "@/cut/lib/librarySharing";
+import { requestSharing } from "@/cut/lib/sharingClient";
+import { copyLibraryForSharing } from "@/cut/lib/libraryShareCopy";
+import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";
+
import { GUIDE_IDS, guideFits, guidePreset, isGuideId, sanitizeGuideLines, type GuideId } from "./guides";
import {
ALL_EFFECT_IDS,
@@ -3196,6 +3201,34 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
};
},
+ library_share: async (_s, input) => {
+ const parsed = libraryShareTargetSchema.safeParse({ kind: input.kind, id: input.id });
+ if (!parsed.success) throw new ToolError("Pass a library folder or asset id and kind.");
+ const action = input.action;
+ if (action !== "get" && action !== "save" && action !== "remove") throw new ToolError("Unknown sharing action.");
+ const settings = action === "save" ? shareSettingsSchema.safeParse({ access: input.access, emails: input.emails }) : null;
+ if (settings && !settings.success) throw new ToolError("Save requires access and a valid email list.");
+ const library = await fetchLibrary();
+ let target = parsed.data;
+ const item = target.kind === "folder"
+ ? library.folders.find((f) => f.id === target.id)
+ : library.assets.find((a) => a.id === target.id);
+ if (!item) throw new ToolError("Library item not found.");
+ if (item.residency !== "cloud") {
+ if (action !== "save" || input.copy_to_cloud !== true)
+ throw new ToolError("Sharing a local item requires a cloud copy. Use save with copy_to_cloud:true.");
+ target = await copyLibraryForSharing(target, item.residency, library);
+ }
+ const result = await requestSharing({ libraryTarget: target },
+ action === "save" ? "PUT" : action === "remove" ? "DELETE" : "GET",
+ settings?.success ? settings.data : undefined).catch((error: unknown) => {
+ throw new ToolError(`Sharing failed for cloud ${target.kind} ${target.id}: ${error instanceof Error ? error.message : "Request failed."}`);
+ });
+ return { target, share: result.share ?? null,
+ ...(result.share ? { url: `${DONKEYCUT_CANONICAL}${librarySharePath(result.share.id)}` } : {}),
+ ...(action === "remove" ? { removed: true } : {}) };
+ },
+
library_list: async () => {
const lib = await fetchLibrary();
return {
diff --git a/site/src/cut/lib/libraryShareCopy.test.ts b/site/src/cut/lib/libraryShareCopy.test.ts
new file mode 100644
index 00000000..3aac4ac8
--- /dev/null
+++ b/site/src/cut/lib/libraryShareCopy.test.ts
@@ -0,0 +1,59 @@
+import { afterEach, describe, expect, spyOn, test } from "bun:test";
+import { localBackend } from "@/cut/lib/backend/local";
+import { browserBackend } from "@/cut/lib/backend/browser";
+import { cloudBackend } from "@/cut/lib/backend/cloud";
+import { copyLibraryForSharing } from "@/cut/lib/libraryShareCopy";
+import type { LibraryData } from "@/cut/lib/library";
+import type { Residency } from "@/cut/lib/residency";
+
+let cleanup = () => {};
+afterEach(() => cleanup());
+function setup(residency: Residency, failMove = false) {
+ const calls: { path: string; method: string; body: Record<string, unknown> }[] = [];
+ const reads: string[] = [];
+ const source = residency === "browser" ? browserBackend : localBackend;
+ const read = spyOn(source, "fetch").mockImplementation(async (path, init) => {
+ if (init?.method && init.method !== "GET") throw new Error("Source was modified");
+ reads.push(path);
+ return new Response(new Blob(["file"], { type: "audio/mpeg" }));
+ });
+ let serial = 0;
+ const cloud = spyOn(cloudBackend, "fetch").mockImplementation(async (path, init) => {
+ const body = typeof init?.body === "string" ? JSON.parse(init.body) as Record<string, unknown> : {};
+ calls.push({ path, method: init?.method ?? "GET", body });
+ if (path.endsWith("/presign")) return Response.json({ key: `key-${++serial}`, url: "https://upload.test/file" });
+ if (path.endsWith("/move") && failMove) return Response.json({ error: "Failed to file" }, { status: 500 });
+ return Response.json({ id: `cloud-${++serial}`, ...body });
+ });
+ const upload = spyOn(globalThis, "fetch").mockImplementation(async (input) => {
+ if (String(input) !== "https://upload.test/file") throw new Error("Unexpected network request");
+ return new Response(null, { status: 200 });
+ });
+ cleanup = () => { read.mockRestore(); cloud.mockRestore(); upload.mockRestore(); };
+ const data: LibraryData = {
+ folders: [{ id: "root", name: "Sounds", parentId: null, residency, createdAt: 0 }, { id: "child", name: "Music", parentId: "root", residency, createdAt: 0 }],
+ assets: [{ id: "asset", fileName: "beat.mp3", name: "Beat", type: "audio", duration: 1, addedAt: 0, folderId: "child", residency }, { id: "outside", fileName: "private.mp3", name: "Private", type: "audio", duration: 1, addedAt: 0, folderId: null, residency }],
+ templates: [],
+ };
+ return { calls, reads, data };
+}
+
+describe("library sharing cloud copies", () => {
+ for (const residency of ["local", "browser"] as const) {
+ test(`${residency} folder copies descendants and preserves the source`, async () => {
+ const { calls, reads, data } = setup(residency);
+ const target = await copyLibraryForSharing({ kind: "folder", id: "root" }, residency, data);
+ expect(target).toEqual({ kind: "folder", id: "cloud-1" });
+ expect(reads).toEqual(["/api/cut/library/media/beat.mp3"]);
+ expect(calls.filter((call) => call.path === "/api/cut/library/folders").map((call) => call.body.parentId)).toEqual([null, "cloud-1"]);
+ expect(calls.find((call) => call.path.endsWith("/move"))?.body.folderId).toBe("cloud-2");
+ expect(calls.some((call) => call.method === "DELETE")).toBe(false);
+ });
+ }
+ test("a failed copy removes its cloud assets and folders", async () => {
+ const { calls, data } = setup("local", true);
+ await expect(copyLibraryForSharing({ kind: "folder", id: "root" }, "local", data)).rejects.toThrow("Could not move item.");
+ const deletes = calls.filter((call) => call.method === "DELETE").map((call) => call.path);
+ expect(deletes).toEqual(["/api/cut/library/cloud-4", "/api/cut/library/folders/cloud-2", "/api/cut/library/folders/cloud-1"]);
+ });
+});
diff --git a/site/src/cut/lib/libraryShareCopy.ts b/site/src/cut/lib/libraryShareCopy.ts
new file mode 100644
index 00000000..2ddb288d
--- /dev/null
+++ b/site/src/cut/lib/libraryShareCopy.ts
@@ -0,0 +1,105 @@
+import { backendFor, type Residency } from "@/cut/lib/residency";
+import { cloudBackend } from "@/cut/lib/backend/cloud";
+import { presignedUpload } from "@/cut/lib/media";
+import {
+ createLibraryFolder, deleteFromLibrary, deleteLibraryFolder, deleteTemplate,
+ moveLibraryItem, type LibraryData, type LibraryAsset, type LibraryTemplateItem,
+} from "@/cut/lib/library";
+import type { LibraryShareTarget } from "@/cut/lib/librarySharing";
+
+async function uploadFile(residency: Residency, fileName: string) {
+ const response = await backendFor(residency).fetch(`/api/cut/library/media/${encodeURIComponent(fileName)}`);
+ if (!response.ok) throw new Error("Could not read the file for sharing.");
+ const blob = await response.blob();
+ return presignedUpload("/api/cut/library/presign", blob, fileName, cloudBackend);
+}
+
+/** A cloud copy is independent of the local shelf. Only a completed copy is shared. */
+export async function copyLibraryForSharing(
+ target: LibraryShareTarget,
+ residency: Residency,
+ library: LibraryData,
+): Promise<LibraryShareTarget> {
+ if (residency === "cloud") return target;
+ const assets: string[] = [];
+ const templates: string[] = [];
+ const folders: string[] = [];
+ const copyAsset = async (asset: LibraryAsset, folderId: string | null) => {
+ const key = await uploadFile(residency, asset.fileName);
+ const posterKey = asset.posterFile ? await uploadFile(residency, asset.posterFile) : undefined;
+ const response = await cloudBackend.fetch("/api/cut/library/complete", {
+ method: "POST", headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ key, posterKey, meta: {
+ name: asset.title || asset.name, type: asset.type, duration: asset.duration,
+ width: asset.width, height: asset.height, source: asset.source,
+ } }),
+ });
+ if (!response.ok) throw new Error("Could not copy the asset to Cloud.");
+ const landed = await response.json() as { id: string };
+ assets.push(landed.id);
+ if (folderId) await moveLibraryItem("cloud", landed.id, folderId);
+ return landed.id;
+ };
+ const copyTemplate = async (template: LibraryTemplateItem, folderId: string) => {
+ const keys: string[] = [];
+ for (const media of template.media) keys.push(await uploadFile(residency, media.fileName));
+ const response = await cloudBackend.fetch("/api/cut/library/templates/import", {
+ method: "POST", headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ...template, folderId, keys }),
+ });
+ if (!response.ok) throw new Error("Could not copy the template to Cloud.");
+ const landed = await response.json() as { id: string };
+ templates.push(landed.id);
+ };
+ try {
+ if (target.kind === "asset") {
+ const asset = library.assets.find((a) => a.id === target.id && a.residency === residency);
+ if (!asset) throw new Error("Asset not found.");
+ return { kind: "asset", id: await copyAsset(asset, null) };
+ }
+ const sourceFolders = library.folders.filter((f) => f.residency === residency);
+ const root = sourceFolders.find((f) => f.id === target.id);
+ if (!root) throw new Error("Folder not found.");
+ const group = <T,>(items: T[], parentOf: (item: T) => string | null) => {
+ const groups = new Map<string | null, T[]>();
+ for (const item of items) {
+ const parent = parentOf(item);
+ const children = groups.get(parent) ?? [];
+ children.push(item);
+ groups.set(parent, children);
+ }
+ return groups;
+ };
+ const folderChildren = group(sourceFolders, (f) => f.parentId ?? null);
+ const folderAssets = group(library.assets.filter((a) => a.residency === residency), (a) => a.folderId ?? null);
+ const folderTemplates = group(library.templates.filter((t) => t.residency === residency), (t) => t.folderId ?? null);
+ const todo = [{ folder: root, parent: null as string | null }];
+ const seen = new Set<string>();
+ let rootId = "";
+ for (let i = 0; i < todo.length; i++) {
+ const { folder, parent } = todo[i];
+ if (seen.has(folder.id)) throw new Error("This folder contains a cycle.");
+ seen.add(folder.id);
+ const copy = await createLibraryFolder(folder.name, "cloud", parent);
+ folders.push(copy.id);
+ if (!rootId) rootId = copy.id;
+ for (const asset of folderAssets.get(folder.id) ?? [])
+ await copyAsset(asset, copy.id);
+ for (const template of folderTemplates.get(folder.id) ?? [])
+ await copyTemplate(template, copy.id);
+ for (const child of folderChildren.get(folder.id) ?? []) todo.push({ folder: child, parent: copy.id });
+ }
+ return { kind: "folder", id: rootId };
+ } catch (error) {
+ const cleanup = await Promise.allSettled([
+ ...assets.map((id) => deleteFromLibrary("cloud", id)),
+ ...templates.map((id) => deleteTemplate("cloud", id)),
+ ]);
+ for (const id of folders.reverse()) {
+ cleanup.push(...await Promise.allSettled([deleteLibraryFolder("cloud", id)]));
+ }
+ if (cleanup.some((result) => result.status === "rejected"))
+ throw new Error("Copy failed. Some unshared copies remain in your Cloud library; remove them before retrying.");
+ throw error;
+ }
+}
diff --git a/site/src/cut/lib/librarySharing.ts b/site/src/cut/lib/librarySharing.ts
new file mode 100644
index 00000000..c87a0e94
--- /dev/null
+++ b/site/src/cut/lib/librarySharing.ts
@@ -0,0 +1,37 @@
+import { z } from "zod";
+
+export const LIBRARY_SHARE_KINDS = ["folder", "asset"] as const;
+export const SHARE_ACCESS = ["restricted", "public"] as const;
+export const LIBRARY_SHARE_ACTIONS = ["get", "save", "remove"] as const;
+export const shareEmailSchema = z.string().trim().toLowerCase().email().max(254);
+export const shareSettingsSchema = z.object({
+ access: z.enum(SHARE_ACCESS),
+ emails: z.array(shareEmailSchema).max(50)
+ .transform((emails) => [...new Set(emails)]),
+});
+export const libraryShareTargetSchema = z.object({
+ kind: z.enum(LIBRARY_SHARE_KINDS),
+ id: z.string().min(1).max(128),
+});
+export type LibraryShareTarget = z.infer<typeof libraryShareTargetSchema>;
+export type ShareSettings = z.infer<typeof shareSettingsSchema>;
+export type LibraryShareState = ShareSettings & { id: string };
+export type SharedLibraryAsset = {
+ id: string;
+ name: string;
+ type: "video" | "audio" | "image" | "font";
+ duration: number;
+ fileName: string;
+};
+export type SharedLibraryPage = {
+ name: string;
+ kind: LibraryShareTarget["kind"];
+ trail: { id: string; name: string }[];
+ folders: { id: string; name: string }[];
+ assets: SharedLibraryAsset[];
+ templates: { id: string; name: string; files: { name: string; fileName: string }[] }[];
+ next: number | null;
+};
+export const librarySharePath = (token: string) => `/s/library/${encodeURIComponent(token)}`;
+export const libraryShareApiPath = ({ kind, id }: LibraryShareTarget) =>
+ `/api/cut/library/shares/${kind}/${encodeURIComponent(id)}`;
diff --git a/site/src/cut/lib/sharingClient.ts b/site/src/cut/lib/sharingClient.ts
new file mode 100644
index 00000000..cc382736
--- /dev/null
+++ b/site/src/cut/lib/sharingClient.ts
@@ -0,0 +1,20 @@
+import { cloudBackend } from "@/cut/lib/backend/cloud";
+import { libraryShareApiPath, type LibraryShareTarget, type ShareSettings } from "@/cut/lib/librarySharing";
+import type { ShareFeatures } from "@/cut/lib/types";
+
+export type ShareResource = { projectId: string } | { libraryTarget: LibraryShareTarget };
+export type SharingSettings = ShareSettings & { features?: ShareFeatures };
+export type SharingState = SharingSettings & { id: string };
+export const shareEndpoint = (resource: ShareResource) => "projectId" in resource
+ ? `/api/cut/projects/${encodeURIComponent(resource.projectId)}/share`
+ : libraryShareApiPath(resource.libraryTarget);
+
+export async function requestSharing(resource: ShareResource, method = "GET", settings?: SharingSettings) {
+ const response = await cloudBackend.fetch(shareEndpoint(resource), {
+ method,
+ ...(settings ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify(settings) } : {}),
+ cache: "no-store",
+ });
+ if (!response.ok) throw new Error("Could not load or save sharing.");
+ return await response.json() as { share: SharingState | null };
+}
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index b0ed8416..a40e3357 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -389,6 +389,7 @@ The Library is shared across every project: folders, reusable assets, and templa
- library_list browses it; library_add copies an asset into the project (the import step "library"-scope attachments need); template_add re-materializes a template; save_template saves timeline items as one.
- Assets from the user's iOS app carry an origin: "camera" is a clip they recorded on their phone (their Camera Roll — "the video I shot on my phone" lives here), "inspiration" a reference saved into the Library's Inspiration folder. library_add imports either like any other asset. A camera clip's name is the clock it was shot on; its title, when it has one, was read off the clip itself and is what the user sees on the card — match a request like "the one about the launch" against the title.
- notes_list reads the user's synced notes (written on their phone or the Notes tab) with the folders they are filed in and the labels they carry — the place to look when they point at "my note", or name a folder or label, for a script, caption, or voiceover text.
+- library_share creates and manages public or email-restricted links to Library folders and assets. A folder link includes its subfolders and current contents. Local items are copied to Cloud before sharing; manage the returned cloud target id afterward. Viewers can preview and download.
- library_organize handles folders (create/rename/move/delete — folders nest, and a folder's parentId in library_list says where it sits), filing (move_asset), and deletes (permanent — explicit ask only).
- import_url reads any URL (TikTok, YouTube, Instagram, an X post or Article, a web page, direct links): a page comes back as its article text and its pictures, a post as its video or photos, and a source that is only words as sourceText alone. When the user asks for the sound alone — a song, a soundtrack — pass audio_only and the audio track lands as an audio asset. Media lands as a card in the chat with that text quoted beside it; the user drags a card to the timeline, Media, or the Library. Place it with add_clip only when they asked for it in the cut.
Attachments: media files dropped on the chat import into project media by themselves; library attachments wait for library_add.`,
diff --git a/site/src/cut/server/ai/headlessTools.ts b/site/src/cut/server/ai/headlessTools.ts
index 14f19ffd..107af31e 100644
--- a/site/src/cut/server/ai/headlessTools.ts
+++ b/site/src/cut/server/ai/headlessTools.ts
@@ -56,6 +56,7 @@ const PAGE_SESSION_TOOLS: ReadonlySet<string> = new Set([
"library_list",
"library_add",
"library_organize",
+ "library_share",
"notes_list",
"template_add",
"file_asset",
diff --git a/site/src/cut/server/cloud/library.ts b/site/src/cut/server/cloud/library.ts
index 05d9bb3e..217cee3f 100644
--- a/site/src/cut/server/cloud/library.ts
+++ b/site/src/cut/server/cloud/library.ts
@@ -84,10 +84,10 @@ async function takenLibraryNames(userId: string): Promise<Set<string>> {
return new Set(rows.map((r) => r.fileName));
}
-function assetView(
+export function assetView(
row: { id: string; folderId: string | null; meta: unknown; createdAt: Date },
obj: { fileName: string },
-): LibraryAsset {
+): LibraryAsset & { title?: string } {
const meta = (row.meta ?? {}) as AssetMeta;
return {
id: row.id,
@@ -105,7 +105,7 @@ function assetView(
};
}
-function templateView(row: {
+export function templateView(row: {
id: string;
name: string;
doc: unknown;
diff --git a/site/src/cut/server/cloud/libraryShareAccess.ts b/site/src/cut/server/cloud/libraryShareAccess.ts
new file mode 100644
index 00000000..af4566c6
--- /dev/null
+++ b/site/src/cut/server/cloud/libraryShareAccess.ts
@@ -0,0 +1,31 @@
+import type { ShareSettings } from "@/cut/lib/librarySharing";
+
+export function libraryShareAccess(
+ share: ShareSettings & { userId: string },
+ user: { id: string; email: string; emailVerified: boolean } | null,
+): 200 | 401 | 403 {
+ if (share.access === "public") return 200;
+ if (!user) return 401;
+ if (user.id === share.userId) return 200;
+ return user.emailVerified && share.emails.includes(user.email.trim().toLowerCase()) ? 200 : 403;
+}
+
+/** Walk only the requested folder's ancestors. Missing parents and cycles deny access. */
+export async function sharedFolderTrail(
+ rootId: string,
+ folderId: string,
+ read: (id: string) => Promise<{ id: string; name: string; parentId: string | null } | null>,
+): Promise<{ id: string; name: string }[] | null> {
+ const trail: { id: string; name: string }[] = [];
+ const seen = new Set<string>();
+ let id: string | null = folderId;
+ while (id && !seen.has(id)) {
+ seen.add(id);
+ const folder = await read(id);
+ if (!folder) return null;
+ trail.push({ id: folder.id, name: folder.name });
+ if (folder.id === rootId) return trail.reverse();
+ id = folder.parentId;
+ }
+ return null;
+}
diff --git a/site/src/cut/server/cloud/librarySharing.test.ts b/site/src/cut/server/cloud/librarySharing.test.ts
new file mode 100644
index 00000000..0df1a06b
--- /dev/null
+++ b/site/src/cut/server/cloud/librarySharing.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, mock, test } from "bun:test";
+import { prisma } from "@/lib/prisma";
+import { libraryShareAccess, sharedFolderTrail } from "@/cut/server/cloud/libraryShareAccess";
+import { createLibrarySharing } from "@/cut/server/cloud/librarySharing";
+import { shareSettingsSchema } from "@/cut/lib/librarySharing";
+
+const token = "abcdefghijklmnopqrstuvwx12345678";
+const now = new Date("2026-01-01");
+const share = { id: token, userId: "owner", kind: "folder", targetId: "root", access: "public", emails: [], createdAt: now, updatedAt: now };
+const folder = (id: string, parentId: string | null = null) => ({ id, name: id, parentId, userId: "owner", scope: "library", createdAt: now, updatedAt: now });
+const asset = { id: "asset", userId: "owner", folderId: "child", mediaObjectId: "object", meta: { name: "Sound.mp3", type: "audio" }, deletedAt: null, createdAt: now, updatedAt: now };
+const request = (method = "GET", body?: unknown) => new Request(`https://donkeycut.com/api/cut-shared/library/${token}`, { method, ...(body ? { body: JSON.stringify(body), headers: { "Content-Type": "application/json" } } : {}) });
+function harness() {
+ const rows = [folder("root"), folder("child", "root"), folder("sibling")];
+ const db = {
+ cutLibraryShare: {
+ findUnique: mock(async () => share as typeof share | null),
+ upsert: mock(async (args: unknown) => { void args; return share; }),
+ deleteMany: mock(async (args: unknown) => { void args; return { count: 1 }; }),
+ },
+ cutFolder: {
+ findFirst: mock(async (args: { where: { id: string; userId: string; scope: string } }) =>
+ rows.find((row) => row.id === args.where.id && row.userId === args.where.userId && row.scope === args.where.scope) ?? null),
+ findMany: mock(async (args: unknown) => { void args; return [folder("child", "root")]; }),
+ },
+ cutLibraryAsset: {
+ findFirst: mock(async (args: unknown) => { void args; return asset as typeof asset | null; }),
+ findMany: mock(async (args: unknown) => { void args; return [asset]; }),
+ },
+ cutTemplate: { findMany: mock(async () => []), findFirst: mock(async () => null) },
+ cutMediaObject: {
+ findFirst: mock(async (args: unknown) => { void args; return ({ id: "object", fileName: "sound.mp3", r2Key: "cut/owner/library/sound.mp3", updatedAt: now }); }),
+ findMany: mock(async () => [{ id: "object", fileName: "sound.mp3" }]),
+ },
+ };
+ const session = mock(async () => null);
+ const sign = mock((key: string, opts?: { version?: string; downloadName?: string }) => {
+ void opts;
+ return `https://media.test/${key}`;
+ });
+ const api = createLibrarySharing(db as unknown as typeof prisma, session, async () => 2, sign);
+ return { api, db, session, sign };
+}
+
+describe("library sharing", () => {
+ test("access requires public sharing, ownership, or a verified invited email", () => {
+ const settings = { userId: "owner", access: "restricted" as const, emails: ["[email protected]"] };
+ expect(libraryShareAccess(settings, null)).toBe(401);
+ expect(libraryShareAccess({ ...settings, access: "public" }, null)).toBe(200);
+ expect(libraryShareAccess(settings, { id: "owner", email: "[email protected]", emailVerified: false })).toBe(200);
+ expect(libraryShareAccess(settings, { id: "friend", email: "[email protected]", emailVerified: true })).toBe(200);
+ expect(libraryShareAccess(settings, { id: "friend", email: "[email protected]", emailVerified: false })).toBe(403);
+ expect(libraryShareAccess(settings, { id: "stranger", email: "[email protected]", emailVerified: true })).toBe(403);
+ expect(shareSettingsSchema.parse({ access: "restricted", emails: [" [email protected] ", "[email protected]"] }).emails).toEqual(["[email protected]"]);
+ expect(shareSettingsSchema.safeParse({ access: "public", emails: ["bad"] }).success).toBe(false);
+ expect(shareSettingsSchema.safeParse({ access: "typo", emails: [] }).success).toBe(false);
+ });
+ test("ancestry accepts descendants and rejects siblings, missing parents, and cycles", async () => {
+ const rows = [folder("root"), folder("child", "root"), folder("grandchild", "child"), folder("sibling"), folder("cycle", "cycle")];
+ const read = async (id: string) => rows.find((row) => row.id === id) ?? null;
+ expect(await sharedFolderTrail("root", "grandchild", read)).toEqual([{ id: "root", name: "root" }, { id: "child", name: "child" }, { id: "grandchild", name: "grandchild" }]);
+ for (const id of ["sibling", "missing", "cycle"]) expect(await sharedFolderTrail("root", id, read)).toBeNull();
+ });
+ test("revoked and malformed links cannot read media", async () => {
+ const { api, db } = harness();
+ const lookup = db.cutLibraryShare.findUnique.mockResolvedValue(null);
+ expect((await api.media(request(), "bad", "asset")).status).toBe(404);
+ expect(lookup).not.toHaveBeenCalled();
+ expect((await api.media(request(), token, "asset")).status).toBe(404);
+ });
+ test("restricted reads stop before content lookup without a session", async () => {
+ const { api, db } = harness();
+ db.cutLibraryShare.findUnique.mockResolvedValue({ ...share, access: "restricted" });
+ const contents = db.cutLibraryAsset.findFirst;
+ const response = await api.media(request(), token, "asset");
+ expect(response.status).toBe(401);
+ expect(response.headers.get("Cache-Control")).toBe("private, no-store");
+ expect(contents).not.toHaveBeenCalled();
+ });
+ test("an asset moved outside the tree loses folder-link access", async () => {
+ const { api, db } = harness();
+ db.cutLibraryAsset.findFirst.mockResolvedValue({ ...asset, folderId: "sibling" });
+ const media = db.cutMediaObject.findFirst;
+ expect((await api.media(request(), token, "asset")).status).toBe(404);
+ expect(media).not.toHaveBeenCalled();
+ });
+ test("a standalone link cannot access another asset", async () => {
+ const { api, db } = harness();
+ db.cutLibraryShare.findUnique.mockResolvedValue({ ...share, kind: "asset", targetId: "asset" });
+ expect((await api.media(request(), token, "other-asset")).status).toBe(404);
+ });
+ test("share changes require target ownership and validate settings", async () => {
+ const { api, db } = harness();
+ const write = db.cutLibraryShare.upsert;
+ expect((await api.manage(request("PUT", { access: "public", emails: [] }), "stranger", "folder", "root")).status).toBe(404);
+ expect((await api.manage(request("PUT", { access: "bad", emails: [] }), "owner", "folder", "root")).status).toBe(400);
+ expect(write).not.toHaveBeenCalled();
+ expect((await api.manage(request("PUT", { access: "restricted", emails: ["[email protected]"] }), "owner", "folder", "root")).status).toBe(200);
+ const args = write.mock.calls[0][0] as Parameters<typeof prisma.cutLibraryShare.upsert>[0];
+ expect(args.where).toEqual({ userId_kind_targetId: { userId: "owner", kind: "folder", targetId: "root" } });
+ expect(/^[A-Za-z0-9_-]{32}$/.test(args.create.id)).toBe(true);
+ expect(args.update.emails).toEqual(["[email protected]"]);
+ const remove = db.cutLibraryShare.deleteMany;
+ expect((await api.manage(request("DELETE"), "owner", "folder", "root")).status).toBe(200);
+ expect(remove.mock.calls[0][0]).toEqual({ where: { userId: "owner", kind: "folder", targetId: "root" } });
+ });
+ test("folder listings expose only their scoped page and omit owner metadata", async () => {
+ const { api, db } = harness();
+ const response = await api.list(request(), token);
+ expect(response.status).toBe(200);
+ const body = await response.json();
+ expect(body.name).toBe("root");
+ expect(body.assets).toEqual([{ id: "asset", name: "Sound.mp3", fileName: "sound.mp3", type: "audio", duration: 0 }]);
+ expect(db.cutLibraryAsset.findMany.mock.calls[0][0]).toMatchObject({ where: { userId: "owner", deletedAt: null, folderId: "root" }, take: 3 });
+ expect(JSON.stringify(body)).not.toContain("owner");
+ expect(response.headers.get("Cache-Control")).toBe("private, no-store");
+ });
+ test("deleted targets and sibling folder requests do not produce a listing", async () => {
+ const { api, db } = harness();
+ expect((await api.list(new Request(`${request().url}?folder=sibling`), token)).status).toBe(404);
+ db.cutFolder.findFirst.mockResolvedValue(null);
+ expect((await api.list(request(), token)).status).toBe(404);
+ expect(db.cutLibraryAsset.findMany).not.toHaveBeenCalled();
+ });
+
+ test("authorized media resolves the owner's complete object and preserves the download filename", async () => {
+ const { api, db, sign } = harness();
+ const response = await api.media(new Request(`${request().url}?download=1`), token, "asset");
+ expect(response.status).toBe(302);
+ expect(response.headers.get("Cache-Control")).toBe("private, no-store");
+ expect(sign.mock.calls[0]).toEqual(["cut/owner/library/sound.mp3", { version: String(now.getTime()), downloadName: "sound.mp3" }]);
+ expect(db.cutMediaObject.findFirst.mock.calls[0][0]).toEqual({ where: { userId: "owner", kind: "library", uploadState: "complete", id: "object" } });
+ db.cutLibraryAsset.findFirst.mockResolvedValue(null);
+ expect((await api.media(request(), token, "asset")).status).toBe(404);
+ });
+
+});
diff --git a/site/src/cut/server/cloud/librarySharing.ts b/site/src/cut/server/cloud/librarySharing.ts
new file mode 100644
index 00000000..b570c634
--- /dev/null
+++ b/site/src/cut/server/cloud/librarySharing.ts
@@ -0,0 +1,189 @@
+import { randomBytes } from "node:crypto";
+import { z } from "zod";
+import { auth } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import { getGlobalSetting } from "@/lib/config/effective";
+import {
+ libraryShareTargetSchema, shareSettingsSchema,
+ type LibraryShareTarget, type SharedLibraryPage,
+} from "@/cut/lib/librarySharing";
+import { libraryShareAccess, sharedFolderTrail } from "@/cut/server/cloud/libraryShareAccess";
+import { assetView, templateView } from "@/cut/server/cloud/library";
+import { mediaObjectUrl } from "@/cut/server/cloud/mediaCdn";
+
+const privateHeaders = { "Cache-Control": "private, no-store", Vary: "Cookie" };
+const err = (error: string, status: number) => Response.json({ error }, { status, headers: privateHeaders });
+const json = (body: unknown) => Response.json(body, { headers: privateHeaders });
+const tokenSchema = z.string().regex(/^[A-Za-z0-9_-]{32}$/);
+const querySchema = z.object({
+ folder: z.string().min(1).max(128).optional(),
+ offset: z.coerce.number().int().min(0).max(1000000).default(0),
+});
+
+export function createLibrarySharing(
+ db: Pick<typeof prisma, "cutFolder" | "cutLibraryAsset" | "cutLibraryShare" | "cutTemplate" | "cutMediaObject">,
+ getSession: (headers: Headers) => Promise<{ user: { id: string; email: string; emailVerified: boolean } } | null>,
+ getPageSize: () => Promise<number>,
+ signMedia: typeof mediaObjectUrl = mediaObjectUrl,
+) {
+ async function ownedTarget(userId: string, target: LibraryShareTarget) {
+ return target.kind === "folder"
+ ? db.cutFolder.findFirst({ where: { id: target.id, userId, scope: "library" } })
+ : db.cutLibraryAsset.findFirst({ where: { id: target.id, userId, deletedAt: null } });
+ }
+
+ const handlers = {
+ async manage(req: Request, userId: string, kind: string, id: string) {
+ const parsed = libraryShareTargetSchema.safeParse({ kind, id });
+ if (!parsed.success) return err("Invalid share target.", 400);
+ if (!(await ownedTarget(userId, parsed.data))) return err("Not found.", 404);
+ const where = { userId_kind_targetId: { userId, kind, targetId: id } };
+ if (req.method === "DELETE") {
+ await db.cutLibraryShare.deleteMany({ where: { userId, kind, targetId: id } });
+ return json({ ok: true });
+ }
+ if (req.method === "GET") {
+ const row = await db.cutLibraryShare.findUnique({ where });
+ return json({ share: row ? { id: row.id, ...shareSettingsSchema.parse(row) } : null });
+ }
+ const body = shareSettingsSchema.safeParse(await req.json().catch(() => null));
+ if (!body.success) return err("Invalid sharing settings.", 400);
+ const row = await db.cutLibraryShare.upsert({
+ where,
+ create: { id: randomBytes(24).toString("base64url"), userId, kind, targetId: id, ...body.data },
+ update: body.data,
+ });
+ return json({ share: { id: row.id, ...body.data } });
+ },
+
+ async list(req: Request, token: string) {
+ const resolved = await resolve(req, token);
+ if (resolved instanceof Response) return resolved;
+ const { share, target } = resolved;
+ const parsed = querySchema.safeParse(Object.fromEntries(new URL(req.url).searchParams));
+ if (!parsed.success) return err("Invalid folder page.", 400);
+ const { folder, offset } = parsed.data;
+ const pageSize = await getPageSize();
+ const readFolder = (id: string) => db.cutFolder.findFirst({
+ where: { id, userId: share.userId, scope: "library" },
+ select: { id: true, name: true, parentId: true },
+ });
+ const trail = target.kind === "folder"
+ ? await sharedFolderTrail(target.id, folder ?? target.id, readFolder)
+ : [];
+ if (!trail || (target.kind === "asset" && folder)) return err("Not found.", 404);
+ const folderId = trail.at(-1)?.id;
+ const [folders, assets, templates] = await Promise.all([
+ folderId ? db.cutFolder.findMany({
+ where: { userId: share.userId, scope: "library", parentId: folderId },
+ select: { id: true, name: true }, orderBy: { id: "asc" }, skip: offset, take: pageSize + 1,
+ }) : [],
+ db.cutLibraryAsset.findMany({
+ where: { userId: share.userId, deletedAt: null,
+ ...(target.kind === "asset" ? { id: target.id } : { folderId }) },
+ orderBy: { id: "asc" }, skip: offset, take: pageSize + 1,
+ }),
+ folderId ? db.cutTemplate.findMany({
+ where: { userId: share.userId, doc: { path: ["folderId"], equals: folderId } },
+ orderBy: { id: "asc" }, skip: offset, take: pageSize + 1,
+ }) : [],
+ ]);
+ const objects = await db.cutMediaObject.findMany({
+ where: { id: { in: assets.slice(0, pageSize).map((a) => a.mediaObjectId) },
+ userId: share.userId, kind: "library", uploadState: "complete" },
+ select: { id: true, fileName: true },
+ });
+ const byId = new Map(objects.map((o) => [o.id, o]));
+ const publicAssets = assets.slice(0, pageSize).flatMap((a) => {
+ const object = byId.get(a.mediaObjectId);
+ if (!object) return [];
+ const v = assetView(a, object);
+ return [{ id: v.id, name: v.title || v.name, fileName: v.fileName, type: v.type, duration: v.duration }];
+ });
+ const body: SharedLibraryPage = {
+ name: trail[0]?.name ?? publicAssets[0]?.name ?? "Shared asset",
+ kind: target.kind, trail, folders: folders.slice(0, pageSize).map(({ id, name }) => ({ id, name })), assets: publicAssets,
+ templates: templates.slice(0, pageSize).map((row) => {
+ const t = templateView(row);
+ return { id: t.id, name: t.name, files: t.media.map((m) => ({ name: m.name, fileName: m.fileName })) };
+ }),
+ next: [folders, assets, templates].some((rows) => rows.length > pageSize) ? offset + pageSize : null,
+ };
+ return json(body);
+ },
+
+ async media(req: Request, token: string, assetId: string) {
+ const resolved = await resolve(req, token);
+ if (resolved instanceof Response) return resolved;
+ const { share, target } = resolved;
+ if (!z.string().min(1).max(128).safeParse(assetId).success) return err("Not found.", 404);
+ const query = z.object({
+ template: z.string().min(1).max(128).optional(),
+ file: z.string().min(1).max(512).optional(),
+ download: z.enum(["1"]).optional(),
+ }).safeParse(Object.fromEntries(new URL(req.url).searchParams));
+ if (!query.success) return err("Invalid media request.", 400);
+ let folderId: string | null;
+ let fileName: string;
+ let mediaObjectId: string | undefined;
+ if (query.data.template) {
+ if (target.kind !== "folder" || query.data.template !== assetId) return err("Not found.", 404);
+ const row = await db.cutTemplate.findFirst({ where: { id: assetId, userId: share.userId } });
+ if (!row) return err("Not found.", 404);
+ const template = templateView(row);
+ const media = template.media.find((m) => m.fileName === query.data.file);
+ if (!media) return err("Not found.", 404);
+ folderId = template.folderId ?? null;
+ fileName = media.fileName;
+ } else {
+ if (target.kind === "asset" && target.id !== assetId) return err("Not found.", 404);
+ const row = await db.cutLibraryAsset.findFirst({
+ where: { id: assetId, userId: share.userId, deletedAt: null },
+ });
+ if (!row) return err("Not found.", 404);
+ folderId = row.folderId;
+ mediaObjectId = row.mediaObjectId;
+ fileName = "";
+ }
+ if (target.kind === "folder") {
+ if (!folderId || !(await sharedFolderTrail(target.id, folderId, (id) =>
+ db.cutFolder.findFirst({ where: { id, userId: share.userId, scope: "library" },
+ select: { id: true, name: true, parentId: true } })))) return err("Not found.", 404);
+ }
+ const object = await db.cutMediaObject.findFirst({
+ where: { userId: share.userId, kind: "library", uploadState: "complete",
+ ...(mediaObjectId ? { id: mediaObjectId } : { fileName }) },
+ });
+ if (!object) return err("Not found.", 404);
+ return new Response(null, { status: 302, headers: {
+ ...privateHeaders,
+ Location: signMedia(object.r2Key, {
+ version: String(object.updatedAt.getTime()),
+ ...(query.data.download ? { downloadName: object.fileName } : {}),
+ }),
+ } });
+ },
+ };
+
+ async function resolve(req: Request, token: string) {
+ if (!tokenSchema.safeParse(token).success) return err("Not found.", 404);
+ const share = await db.cutLibraryShare.findUnique({ where: { id: token } });
+ if (!share) return err("Not found.", 404);
+ const settings = shareSettingsSchema.safeParse(share);
+ const target = libraryShareTargetSchema.safeParse({ kind: share.kind, id: share.targetId });
+ if (!settings.success || !target.success) return err("Not found.", 404);
+ const session = share.access === "public" ? null : await getSession(req.headers);
+ const status = libraryShareAccess({ ...settings.data, userId: share.userId }, session?.user ?? null);
+ if (status !== 200) return err(status === 401 ? "Sign in to view this share." : "You don't have access to this share.", status);
+ if (!(await ownedTarget(share.userId, target.data))) return err("Not found.", 404);
+ return { share, target: target.data };
+ }
+
+ return handlers;
+}
+
+export const librarySharing = createLibrarySharing(
+ prisma,
+ (headers) => auth.api.getSession({ headers }),
+ async () => (await getGlobalSetting("librarySharing")).pageSize,
+);
diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.ts
index 55fd0b43..a3d55795 100644
--- a/site/src/cut/server/cloud/routes.ts
+++ b/site/src/cut/server/cloud/routes.ts
@@ -1,3 +1,4 @@
+import { librarySharing } from "@/cut/server/cloud/librarySharing";
// The hosted Cut API surface in one table, namespaced under /api/cut-cloud/*.
// The client's cloud driver rewrites /api/cut/X -> /api/cut-cloud/X, so paths
// mirror the engine table (http/routes.ts) with the cloud prefix, plus the
@@ -69,6 +70,9 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [
{ method: "POST", path: "/api/cut-cloud/projects/:id/convert", handler: (r, u, p) => jobsCloud.convert(u, p.id, r) },
{ method: "POST", path: "/api/cut-cloud/media/presign-get", handler: (r, u) => mediaCloud.presignGetBatch(u, r) },
+ { method: "GET", path: "/api/cut-cloud/library/shares/:kind/:id", handler: (r, u, p) => librarySharing.manage(r, u, p.kind, p.id) },
+ { method: "PUT", path: "/api/cut-cloud/library/shares/:kind/:id", handler: (r, u, p) => librarySharing.manage(r, u, p.kind, p.id) },
+ { method: "DELETE", path: "/api/cut-cloud/library/shares/:kind/:id", handler: (r, u, p) => librarySharing.manage(r, u, p.kind, p.id) },
{ method: "GET", path: "/api/cut-cloud/library", handler: (r, u) => libraryCloud.list(u, r) },
{ method: "POST", path: "/api/cut-cloud/library/presign", handler: (r, u) => libraryCloud.presign(u, r) },
{ method: "POST", path: "/api/cut-cloud/library/complete", handler: (r, u) => libraryCloud.complete(u, r) },
diff --git a/site/src/cut/server/cloud/sharedRoutes.ts b/site/src/cut/server/cloud/sharedRoutes.ts
index 40670be3..b913a6c5 100644
--- a/site/src/cut/server/cloud/sharedRoutes.ts
+++ b/site/src/cut/server/cloud/sharedRoutes.ts
@@ -1,3 +1,4 @@
+import { librarySharing } from "@/cut/server/cloud/librarySharing";
// The public shared-viewer API surface, namespaced under /api/cut-shared/*.
// Paths mirror the engine table after the token segment so the client's shared
// driver is a pure prefix rewrite of /api/cut/*. There is no auth wrapper:
@@ -14,6 +15,8 @@ interface SharedRoute extends RouteEntry {
}
const CUT_SHARED_ROUTES: SharedRoute[] = [
+ { method: "GET", path: "/api/cut-shared/library/:token", handler: (r, p) => librarySharing.list(r, p.token) },
+ { method: "GET", path: "/api/cut-shared/library/:token/media/:id", handler: (r, p) => librarySharing.media(r, p.token, p.id) },
{ method: "GET", path: "/api/cut-shared/:token", handler: (r, p) => sharedView.meta(p.token, r) },
{ method: "GET", path: "/api/cut-shared/:token/projects/:id", handler: (r, p) => sharedView.doc(p.token, p.id, r) },
{ method: "GET", path: "/api/cut-shared/:token/projects/:id/media/:file", handler: (r, p) => sharedView.serveMedia(p.token, p.id, p.file, r) },
diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.ts
index 5b702faa..01db42c9 100644
--- a/site/src/lib/config/registry.ts
+++ b/site/src/lib/config/registry.ts
@@ -31,6 +31,13 @@ function validTimeZone(zone: string): boolean {
}
export const SETTINGS = defineSettings({
+ librarySharing: {
+ schema: z.object({ pageSize: z.number().int().min(10).max(100) }).strict(),
+ default: { pageSize: 40 },
+ public: false,
+ title: "Shared library",
+ description: "Folders, assets, and templates returned per shared library page.",
+ },
promotionCreditOffer: {
schema: creditOfferTermsSchema.extend({ minimumAccountAgeDays: z.number().int().min(1).max(36500) }).strict(),
default: { dollars: 15, claimWindowDays: 3, expiresAfterDays: 28, claim: "link", minimumAccountAgeDays: 7 },
diff --git a/site/src/queries/sharing.ts b/site/src/queries/sharing.ts
new file mode 100644
index 00000000..5611b1c0
--- /dev/null
+++ b/site/src/queries/sharing.ts
@@ -0,0 +1,22 @@
+"use client";
+
+import { useQuery } from "@tanstack/react-query";
+import { requestSharing, shareEndpoint, type ShareResource } from "@/cut/lib/sharingClient";
+import { apiFetch } from "@/queries/apiClient";
+import type { SharedLibraryPage } from "@/cut/lib/librarySharing";
+
+export const sharingKey = (resource: ShareResource) => ["sharing", shareEndpoint(resource)] as const;
+export function useSharing(resource: ShareResource) {
+ return useQuery({ queryKey: sharingKey(resource), queryFn: () => requestSharing(resource), staleTime: 0, gcTime: 0, refetchOnWindowFocus: false, refetchOnReconnect: false });
+}
+export function useSharedLibrary(token: string, folder: string | null, offset: number) {
+ const params = new URLSearchParams({ offset: String(offset) });
+ if (folder) params.set("folder", folder);
+ return useQuery({
+ queryKey: ["shared-library", token, folder, offset],
+ queryFn: () => apiFetch<SharedLibraryPage>(`/api/cut-shared/library/${encodeURIComponent(token)}?${params}`, { cache: "no-store" }),
+ retry: false,
+ staleTime: 0,
+ gcTime: 0,
+ });
+}
diff --git a/site/src/types/bun-test.d.ts b/site/src/types/bun-test.d.ts
index 7d80a1b2..0e00d984 100644
--- a/site/src/types/bun-test.d.ts
+++ b/site/src/types/bun-test.d.ts
@@ -37,6 +37,7 @@ declare module "bun:test" {
}
export function expect(value: unknown): Matchers;
type Spy<T> = T extends (...args: infer Args) => infer Result ? {
+ mock: { calls: Args[] };
mockImplementation(fn: (...args: Args) => Result): Spy<T>;
mockReturnValue(value: Result): Spy<T>;
mockResolvedValue(value: Awaited<Result>): Spy<T>;
@@ -45,6 +46,7 @@ declare module "bun:test" {
export function spyOn<T extends object, K extends keyof T>(object: T, method: K): Spy<T[K]>;
/** Module mocking, for the tests that stand a dependency in. */
export const mock: {
+ <T extends (...args: never[]) => unknown>(fn: T): T & Spy<T>;
module(specifier: string, factory: () => unknown): void;
};
}