Open source CapCut alternative.
TypeScript
feat(site): share cloud projects read-only with a link or email invites
David Le6e4dc323537c
diff --git a/site/prisma/Cut.prisma b/site/prisma/Cut.prismaindex 6bdbcf40..0916ce0c 100644--- a/site/prisma/Cut.prisma+++ b/site/prisma/Cut.prisma@@ -18,6 +18,24 @@ model CutProject {@@index([userId, updatedAt])}+// A read-only share of one cloud project. The row id doubles as the link+// token: deleting the row kills the link, and re-sharing mints a fresh URL+// without moving the project. For a public share the token is the only gate,+// so share.ts always supplies a cryptographically random id (the cuid()+// default is a fallback only, never the token an attacker would see).+model CutProjectShare {+ id String @id @default(cuid()) // link token (random, set in share.ts)+ projectId String @unique+ userId String // owner; content queries and R2 keys resolve under this id+ access String @default("restricted") // restricted | public+ emails Json @default("[]") // lowercased invitee emails+ features Json @default("{}") // { chat, media, genai, subtitles, details } booleans+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([userId])+}+model CutFolder {id String @id @default(cuid())userId Stringdiff --git a/site/src/app/cut/s/[token]/page.tsx b/site/src/app/cut/s/[token]/page.tsxnew file mode 100644index 00000000..2cbbe7fd--- /dev/null+++ b/site/src/app/cut/s/[token]/page.tsx@@ -0,0 +1,105 @@+"use client";++import { Suspense, useEffect, useState } from "react";+import { useParams } from "next/navigation";+import { Clapperboard, Loader2 } from "lucide-react";+import { authHrefFor } from "@/app/_components/landing/useAppEntryHref";+import { Button } from "@/components/ui/button";+import { Editor } from "@/cut/components/Editor";+import { setCutMode } from "@/cut/lib/backend";+import { bindSharedBackend } from "@/cut/lib/backend/shared";+import { useEditor } from "@/cut/lib/store";+import type { ShareFeatures } from "@/cut/lib/types";+import { authClient } from "@/lib/auth-client";++// The read-only share view. This route sits beside the app subtree on purpose:+// /cut/app is session-gated (RequireSession) and engine-gated (ConnectGate),+// and a public share link must open with neither. The share meta fetch is the+// access check — the server answers 401 (sign in), 403 (not invited), or 404+// (no such share) — and on success the page binds the shared backend and+// mounts the editor in viewer mode.++type Gate =+ | { state: "loading" }+ | { state: "ready"; projectId: string }+ | { state: "signin" }+ | { state: "denied" }+ | { state: "missing" };++function SharedProject() {+ const { token } = useParams<{ token: string }>();+ const [gate, setGate] = useState<Gate>({ state: "loading" });+ const { data: session } = authClient.useSession();++ useEffect(() => {+ let alive = true;+ void fetch(`/api/cut-shared/${encodeURIComponent(token)}`)+ .then(async (res) => {+ if (!alive) return;+ if (res.status === 401) return setGate({ state: "signin" });+ if (res.status === 403) return setGate({ state: "denied" });+ if (!res.ok) return setGate({ state: "missing" });+ const meta = (await res.json()) as { projectId: string; features: ShareFeatures };+ bindSharedBackend(token);+ setCutMode("shared");+ useEditor.getState().setSharedView(meta.features);+ setGate({ state: "ready", projectId: meta.projectId });+ })+ .catch(() => alive && setGate({ state: "missing" }));+ return () => {+ alive = false;+ };+ }, [token]);++ if (gate.state === "ready") return <Editor projectId={gate.projectId} viewer />;++ if (gate.state === "loading") {+ return (+ <div className="grid h-screen place-items-center text-muted-foreground">+ <Loader2 className="size-5 animate-spin" />+ </div>+ );+ }++ const signIn = () => {+ const here = window.location.pathname + window.location.search;+ window.location.href = authHrefFor("/sign-in", here);+ };++ return (+ <div className="grid h-screen place-items-center">+ <div className="flex max-w-sm flex-col items-center gap-3 text-center">+ <Clapperboard className="size-7 text-muted-foreground" />+ {gate.state === "signin" ? (+ <>+ <p className="text-sm text-muted-foreground">+ This project is shared with specific people — sign in to see if+ that's you.+ </p>+ <Button onClick={signIn}>Sign in</Button>+ </>+ ) : gate.state === "denied" ? (+ <p className="text-sm text-muted-foreground">+ You don't have access to this project+ {session?.user.email ? ` as ${session.user.email}` : ""}. Ask the+ owner to invite you.+ </p>+ ) : (+ <p className="text-sm text-muted-foreground">+ This share link isn't active anymore.+ </p>+ )}+ </div>+ </div>+ );+}++export default function SharedProjectPage() {+ return (+ <div className="min-h-screen bg-white font-system text-foreground antialiased">+ <Suspense>+ <SharedProject />+ </Suspense>+ </div>+ );+}diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsxindex d2ca3bff..8dc73f53 100644--- a/site/src/cut/components/AiPanel.tsx+++ b/site/src/cut/components/AiPanel.tsx@@ -232,6 +232,7 @@ export function AiPanel({}) {const [info, setInfo] = useState<ModelsInfo | null>(null);const caps = useCutCaps();+ const readOnly = useEditor((s) => s.readOnly);const signedIn = useSignedIn();const [model, setModel] = useState<string>(() =>typeof window === "undefined"@@ -263,6 +264,16 @@ export function AiPanel({};}, [projectId]);+ // A shared view opens on the owner's newest thread — the viewer has no chat+ // of their own to resume. Derived, so the fallback holds until the viewer+ // explicitly opens another thread from the list.+ const sessionThread = useMemo(() => {+ if (!readOnly || !chatsReady) return activeChat;+ const list = readThreads(projectId);+ if (list.length === 0 || list.some((t) => t.id === activeChat)) return activeChat;+ return list[0].id;+ }, [readOnly, chatsReady, projectId, activeChat]);+useEffect(() => {// The models probe asks the engine which CLIs are installed; without the// localCliChat cap there is no engine to ask (mergedInfo synthesizes the@@ -350,15 +361,17 @@ export function AiPanel({><History /></Button>- <Button- variant="ghost"- size="sm"- className="ai-new-thread"- title="New chat"- onClick={newChat}- >- <Plus />- </Button>+ {!readOnly && (+ <Button+ variant="ghost"+ size="sm"+ className="ai-new-thread"+ title="New chat"+ onClick={newChat}+ >+ <Plus />+ </Button>+ )}<Button variant="ghost" size="sm" title="Close (⌘J)" onClick={onClose}><X /></Button>@@ -407,6 +420,7 @@ export function AiPanel({minute: "2-digit",})}</span>+ {!readOnly && (<spanrole="button"aria-label="Delete thread"@@ -419,6 +433,7 @@ export function AiPanel({><Trash2 className="size-3.5" /></span>+ )}</button>)))}@@ -429,9 +444,9 @@ export function AiPanel({{chatsReady && (<ChatSession- key={activeChat}+ key={sessionThread}projectId={projectId}- threadId={activeChat}+ threadId={sessionThread}info={mergedInfo}model={model}onModelChange={selectModel}@@ -459,6 +474,7 @@ function ChatSession({const [input, setInput] = useState("");const composerRef = useRef<HTMLTextAreaElement>(null);const caps = useCutCaps();+ const readOnly = useEditor((s) => s.readOnly);// Live dictation → drops the finished transcript into the composer, appended// after whatever the user had already typed.const mic = useMicTranscription((text) =>@@ -838,6 +854,7 @@ function ChatSession({</div></div>+ {!readOnly && (<div className="shrink-0 px-2.5 pb-2.5"><div className="relative">{outOfCredits && (@@ -950,6 +967,7 @@ function ChatSession({</p>)}</div>+ )}</div>);}diff --git a/site/src/cut/components/AudioPanel.tsx b/site/src/cut/components/AudioPanel.tsxindex 320bfc40..9da3a2cd 100644--- a/site/src/cut/components/AudioPanel.tsx+++ b/site/src/cut/components/AudioPanel.tsx@@ -87,6 +87,7 @@ export function AudioPanel({sub: "voice" | "music";onSub: (v: "voice" | "music") => void;}) {+ const readOnly = useEditor((s) => s.readOnly);// The app-wide preview player: starting a clip stops the last one, here or// on a chat audio card. Leaving the tab silences only this panel's own// preview — a chat card's playback belongs to the chat, which is still on@@ -113,7 +114,7 @@ export function AudioPanel({<div className="flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto px-3.5 pb-4">{sub === "voice" ? (<>- <VoiceGenerator projectId={projectId} />+ {!readOnly && <VoiceGenerator projectId={projectId} />}<ProjectAudioprojectId={projectId}importing={importing}@@ -123,7 +124,7 @@ export function AudioPanel({</>) : (<>- <MusicGenerator projectId={projectId} />+ {!readOnly && <MusicGenerator projectId={projectId} />}<ProjectMusic projectId={projectId} onTogglePlay={togglePlay} playingUrl={playingUrl} /></>)}diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex 1e420310..f1fda554 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -24,15 +24,20 @@ import { Preview } from "./Preview";import { SidePanel } from "./SidePanel";import { Timeline } from "./Timeline";import { TopBar } from "./TopBar";+import { ViewerTopBar } from "./ViewerTopBar";export function Editor({projectId,from,folder,+ viewer = false,}: {projectId: string;from?: string | null;folder?: string | null;+ /** Read-only share view: the share page bound the shared backend and put+ * the store in read-only mode before mounting. */+ viewer?: boolean;}) {useEffect(() => installDevHooks(), []);const back = backTarget(useCutBase(), from, folder);@@ -44,22 +49,31 @@ export function Editor({const stale = useEditor((s) => s.projectId) !== projectId;const exportOpen = useEditor((s) => s.exportOpen);const aiOpen = useEditor((s) => s.aiOpen);+ const sharedFeatures = useEditor((s) => s.sharedFeatures);// The inspector only earns its column when the selection has a panel to// show; otherwise (nothing selected, or a subtitle cue) it is an empty white// panel, so collapse it and let the preview take the space.- const hasInspector = useEditor((s) => s.selection != null && s.selection.kind !== "cue");+ const hasInspector = useEditor(+ (s) => !s.readOnly && s.selection != null && s.selection.kind !== "cue"+ );const [importing, setImporting] = useState(0);const [conflictReloaded, setConflictReloaded] = useState(false);+ const [shareGone, setShareGone] = useState(false);const dragDepth = useRef(0);// Load the project document, then enrich assets (thumbs/waveforms) lazily.// Residency is a fact about the project, not the link: resolve where the id// lives (residency.ts) and bind the backend before anything else fetches.+ // A share view skips that — its page bound the shared backend already.useEffect(() => {let alive = true;- void resolveProjectMode(projectId).then((mode) => {+ const bind = viewer+ ? Promise.resolve()+ : resolveProjectMode(projectId).then((mode) => {+ if (alive) setCutMode(mode);+ });+ void bind.then(() => {if (!alive) return;- setCutMode(mode);void useEditor.getState().loadProject(projectId)@@ -73,12 +87,46 @@ export function Editor({return () => {alive = false;};- }, [projectId]);+ }, [projectId, viewer]);++ // Delayed follow of the owner's edits: poll the doc version every 10s and+ // reload on change, keeping the playhead. A 401/403/404 means the share was+ // revoked or narrowed — stop and say so.+ useEffect(() => {+ if (!viewer) return;+ let last: string | null = null;+ let stopped = false;+ const tick = async () => {+ if (stopped || document.hidden) return;+ try {+ const res = await apiFetch(`/api/cut/projects/${projectId}`, { method: "HEAD" });+ if ([401, 403, 404].includes(res.status)) {+ stopped = true;+ setShareGone(true);+ return;+ }+ if (!res.ok) return;+ const version = res.headers.get("x-cut-doc-version");+ if (version && last && version !== last) {+ const at = useEditor.getState().currentTime;+ await useEditor.getState().loadProject(projectId);+ for (const asset of useEditor.getState().assets) void enrichAsset(asset);+ useEditor.getState().seek(at);+ }+ if (version) last = version;+ } catch {+ // Transient network failure — the next tick retries.+ }+ };+ const timer = setInterval(() => void tick(), 10_000);+ return () => clearInterval(timer);+ }, [viewer, projectId]);// A cloud save hit a newer stored version (another session's edits won).// Take the newer doc through the ordinary load path — the GET returns it and// rebinds the driver's version — and say so.useEffect(() => {+ if (viewer) return;const onConflict = (e: Event) => {const detail = (e as CustomEvent<{ projectId: string }>).detail;if (!detail || detail.projectId !== projectId) return;@@ -92,11 +140,12 @@ export function Editor({};window.addEventListener("cut-cloud-doc-conflict", onConflict);return () => window.removeEventListener("cut-cloud-doc-conflict", onConflict);- }, [projectId]);+ }, [projectId, viewer]);// Keep the project card's hover proxy fresh: rebuild it a few seconds after// the cut settles. Best-effort and single-flight; skips when there's no cut.useEffect(() => {+ if (viewer) return;let timer: ReturnType<typeof setTimeout> | null = null;let rendering = false;const render = async () => {@@ -158,10 +207,11 @@ export function Editor({unsub();if (timer) clearTimeout(timer);};- }, [projectId]);+ }, [projectId, viewer]);// Autosave: debounce document changes into PUT /api/cut/projects/<id>.useEffect(() => {+ if (viewer) return;let timer: ReturnType<typeof setTimeout> | null = null;let last = serializeDoc(useEditor.getState());let lastName = useEditor.getState().projectName;@@ -244,7 +294,7 @@ export function Editor({unsub();if (timer) clearTimeout(timer);};- }, [projectId]);+ }, [projectId, viewer]);const importFiles = useCallback(async (@@ -291,6 +341,7 @@ export function Editor({// with `Files` too, so internal drags — which always carry the ref MIME —// are filtered out; dragging a stock tile never lights the drop hints.useEffect(() => {+ if (viewer) return;const isFileDrag = (e: DragEvent) =>!!e.dataTransfer?.types.includes("Files") && !hasRefDrag(e);// "media" when the drag carries at least one video/audio/image (the@@ -356,7 +407,7 @@ export function Editor({window.removeEventListener("dragleave", leave);window.removeEventListener("drop", drop);};- }, [importFiles]);+ }, [importFiles, viewer]);// Keyboard shortcuts.useEffect(() => {@@ -376,6 +427,19 @@ export function Editor({const s = useEditor.getState();if (s.exportOpen || document.querySelector('[data-slot="dialog-content"]')) return;+ // A read-only view keeps playback keys; everything that edits is out.+ if (s.readOnly) {+ const allowed =+ e.code === "Space" ||+ e.key === "ArrowLeft" ||+ e.key === "ArrowRight" ||+ e.key === "Escape" ||+ ((e.metaKey || e.ctrlKey) &&+ e.key.toLowerCase() === "j" &&+ s.sharedFeatures?.chat === true);+ if (!allowed) return;+ }+if (e.code === "Space" && !controlFocused) {e.preventDefault();if (!s.playing && s.currentTime >= projectDuration(s) - 0.01) s.seek(0);@@ -441,16 +505,27 @@ export function Editor({);}+ const anySidePanel = sharedFeatures+ ? sharedFeatures.media || sharedFeatures.genai || sharedFeatures.subtitles || sharedFeatures.details+ : true;+return (<div className="flex h-screen min-w-[900px] overflow-hidden"><div className="grid min-w-0 flex-1 grid-rows-[46px_minmax(0,1fr)_auto]">- <TopBar onImport={importFiles} from={from} folder={folder} uploading={importing} />+ {viewer ? (+ <ViewerTopBar />+ ) : (+ <TopBar onImport={importFiles} from={from} folder={folder} uploading={importing} />+ )}<divclassName={`grid min-h-0 ${hasInspector ? "grid-cols-[auto_minmax(0,1fr)_272px]" : "grid-cols-[auto_minmax(0,1fr)]"}`}>- <SidePanel projectId={projectId} onImport={importFiles} importing={importing > 0} />+ {anySidePanel && (+ <SidePanel projectId={projectId} onImport={importFiles} importing={importing > 0} />+ )}+ {!anySidePanel && <div />}<div className="grid min-h-0 min-w-0"><Preview /></div>@@ -458,7 +533,7 @@ export function Editor({</div><Timeline /></div>- {aiOpen && (+ {aiOpen && (!viewer || sharedFeatures?.chat) && (<AiPanelkey={projectId}projectId={projectId}@@ -466,6 +541,11 @@ export function Editor({/>)}{exportOpen && <ExportDialog />}+ {shareGone && (+ <div className="fixed top-14 left-1/2 z-50 -translate-x-1/2 rounded-full bg-foreground/90 px-3.5 py-1.5 text-xs font-medium text-background shadow-lg">+ This share is no longer available.+ </div>+ )}{conflictReloaded && (<div className="fixed top-14 left-1/2 z-50 flex -translate-x-1/2 items-center gap-1.5 rounded-full bg-foreground/90 py-1.5 pr-1.5 pl-3.5 text-background shadow-lg"><span className="text-xs font-medium">Reloaded a newer version saved elsewhere.</span>diff --git a/site/src/cut/components/GeneratePanel.tsx b/site/src/cut/components/GeneratePanel.tsxindex 73716831..82eded33 100644--- a/site/src/cut/components/GeneratePanel.tsx+++ b/site/src/cut/components/GeneratePanel.tsx@@ -49,6 +49,7 @@ const ASPECT_WORD: Record<VideoAspect, string> = {};export function GenerateVideoPanel({ projectId }: { projectId: string }) {+ const readOnly = useEditor((s) => s.readOnly);const signedIn = useSignedIn();const allJobs = useGenerate((s) => s.jobs);// Panel renders only — a chat- or scene-owned job lives on its chat card.@@ -112,6 +113,7 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {{...targetProps}className="relative flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto px-3.5 pb-4">+ {!readOnly && (<>{/* Composer: the character and attached references ride inside theinput box, above the prompt — same shape as the image panel, whichalso highlights this box while a drag hovers the panel. */}@@ -220,6 +222,7 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {Renders take a minute or two. Keep editing while it runs.</p>)}+ </>)}{jobs.length > 0 && (<div className="flex flex-col gap-1.5">diff --git a/site/src/cut/components/ImageGenPanel.tsx b/site/src/cut/components/ImageGenPanel.tsxindex 148ab6f8..5beba71d 100644--- a/site/src/cut/components/ImageGenPanel.tsx+++ b/site/src/cut/components/ImageGenPanel.tsx@@ -57,6 +57,7 @@ function pixelDims(aspect: ImageAspect, resolution: ImageResolution): string {export function ImageGenPanel({ projectId }: { projectId: string }) {const { prompt, aspect, resolution, refs } = useImageGen();+ const readOnly = useEditor((s) => s.readOnly);const signedIn = useSignedIn();const candidates = useRefCandidates();const allJobs = useGenerate((s) => s.jobs);@@ -102,6 +103,7 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {</div><div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto px-3.5 pb-4">+ {!readOnly && (<>{/* Composer: attached references ride as little image thumbnails insidethe input box, above the prompt (Claude-style). */}<div@@ -178,6 +180,7 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {to continue.</p>)}+ </>)}{/* Generations in flight (or failed): a finished asset drops into thelist below, so only the transient states row here. Several can rundiff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsxindex 261998b6..fe61157c 100644--- a/site/src/cut/components/ProjectsHome.tsx+++ b/site/src/cut/components/ProjectsHome.tsx@@ -46,10 +46,10 @@ import {} from "@/components/ui/dropdown-menu";import { Input } from "@/components/ui/input";import { engineLost, engineOrigin, servedFromEngine } from "@/cut/lib/api";-import { cloudBackend } from "@/cut/lib/backend/cloud";+import { cloudBackend, quotaErrorMessage } from "@/cut/lib/backend/cloud";import { useCutMode } from "@/cut/lib/backend/hooks";import { localBackend } from "@/cut/lib/backend/local";-import type { CutBackend, CutMode } from "@/cut/lib/backend/types";+import type { CutBackend } from "@/cut/lib/backend/types";import { useWebMode, webModeEnabled } from "@/cut/lib/flags";import { track } from "@/lib/analytics";import { authClient } from "@/lib/auth-client";@@ -69,8 +69,9 @@ type View = "gallery" | "list";// Where a project lives: the engine on this Mac or the hosted cloud backend.// The home lists each residency it can reach as its own section, talking to// the backend objects directly — the global mode is only bound when a project-// opens into the editor.-type Residency = CutMode;+// opens into the editor. (The "shared" mode is a view of someone else's+// project, never a residency of yours.)+type Residency = "local" | "cloud";const backendFor = (r: Residency): CutBackend => (r === "cloud" ? cloudBackend : localBackend);@@ -115,6 +116,8 @@ export function ProjectsHome() {const router = useRouter();const base = useCutBase();const mode = useCutMode();+ // The home never runs in shared mode; anything non-cloud lists as local.+ const homeMode: Residency = mode === "cloud" ? "cloud" : "local";const webMode = useWebMode();const { data: session } = authClient.useSession();// Which backends this home lists. Engine presence is what the ConnectGate@@ -335,10 +338,10 @@ export function ProjectsHome() {} finally {setImporting((n) => n - 1);}- await refresh(mode);+ await refresh(homeMode);}},- [refresh, mode]+ [refresh, homeMode]);const rename = async () => {@@ -359,9 +362,38 @@ export function ProjectsHome() {const duplicate = async (r: Residency, p: ProjectSummary) => {setBusy(true);+ setDupError(null);try {- await backendFor(r).fetch(`/api/cut/projects/${p.id}/duplicate`, { method: "POST" });+ const res = await backendFor(r).fetch(`/api/cut/projects/${p.id}/duplicate`, {+ method: "POST",+ });+ const body = (await res.json().catch(() => null)) as+ | { jobId?: string; error?: string }+ | null;+ if (!res.ok) {+ throw new Error(+ quotaErrorMessage(res.status, body) ?? body?.error ?? "Could not duplicate the project."+ );+ }+ // Cloud duplicates queue (copies drain one at a time); poll until this+ // one lands. The engine answers with the finished summary instead.+ if (body?.jobId) {+ for (;;) {+ await new Promise((done) => setTimeout(done, 2000));+ const st = await backendFor(r).fetch(`/api/cut/copy-jobs/${body.jobId}`);+ if (!st.ok) throw new Error("Could not duplicate the project.");+ const job = (await st.json()) as { state: string; error?: string };+ if (job.state === "done") break;+ if (job.state === "error") {+ throw new Error(job.error || "Could not duplicate the project.");+ }+ }+ }await refresh(r);+ } catch (e) {+ setDupError(+ e instanceof Error && e.message ? e.message : "Could not duplicate the project."+ );} finally {setBusy(false);}@@ -650,7 +682,7 @@ export function ProjectsHome() {// Whole-surface file drops import on the globally bound backend; a folder// another backend owns can't receive them, so those land at the root.const surfaceDropFolder =- dual && openFolder && !data[mode].folders.some((f) => f.id === openFolder)+ dual && openFolder && !data[homeMode].folders.some((f) => f.id === openFolder)? null: openFolder;diff --git a/site/src/cut/components/ShareDialog.tsx b/site/src/cut/components/ShareDialog.tsxnew file mode 100644index 00000000..adc7fee8--- /dev/null+++ b/site/src/cut/components/ShareDialog.tsx@@ -0,0 +1,340 @@+"use client";++import { useEffect, useState } from "react";+import { Check, ChevronDown, Globe, Link as LinkIcon, Loader2, Lock, X } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Switch } from "@/components/ui/switch";+import { apiFetch } from "@/cut/lib/backend";+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.++type ShareAccess = "restricted" | "public";++interface ShareState {+ id: string;+ access: ShareAccess;+ emails: string[];+ features: ShareFeatures;+}++const NO_FEATURES: ShareFeatures = {+ chat: false,+ media: false,+ genai: false,+ subtitles: false,+ details: false,+};++const FEATURE_ROWS: { key: keyof ShareFeatures; label: string; hint: string }[] = [+ { key: "chat", label: "Chat", hint: "AI chat threads and their cards" },+ { key: "media", label: "Media", hint: "Uploaded files beyond the timeline" },+ { key: "genai", label: "AI generations", hint: "Generated video, image, and audio" },+ { key: "subtitles", label: "Subtitles", hint: "The transcript panel" },+ { 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;+}) {+ const base = useCutBase();+ const [loading, setLoading] = useState(true);+ const [share, setShare] = useState<ShareState | null>(null);+ const [draft, setDraft] = useState("");+ const [error, setError] = useState<string | null>(null);+ const [copied, setCopied] = useState(false);+ const [saving, setSaving] = useState(false);++ 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;+ setShare(body.share);+ setLoading(false);+ })+ .catch(() => {+ if (!alive) return;+ setError("Could not load sharing.");+ setLoading(false);+ });+ return () => {+ alive = false;+ };+ }, [projectId]);++ /** PUT the next share state; the row is created on the first save. */+ const save = async (next: {+ access: ShareAccess;+ emails: string[];+ features: ShareFeatures;+ }): Promise<ShareState | null> => {+ 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 };+ setShare(body.share);+ return body.share;+ } catch {+ setError("Could not save sharing.");+ return null;+ } finally {+ setSaving(false);+ }+ };++ const current: Omit<ShareState, "id"> & { id?: string } = share ?? {+ access: "restricted",+ emails: [],+ features: NO_FEATURES,+ };++ const addEmail = () => {+ const email = draft.trim().toLowerCase();+ if (!email) return;+ if (!EMAIL_RE.test(email)) {+ setError("That doesn't look like an email address.");+ return;+ }+ setDraft("");+ setError(null);+ if (current.emails.includes(email)) return;+ void save({ ...current, emails: [...current.emails, email] });+ };++ const removeEmail = (email: string) => {+ void save({ ...current, emails: current.emails.filter((e) => e !== email) });+ };++ const setAccess = (access: ShareAccess) => {+ if (access !== current.access) void save({ ...current, access });+ };++ const setFeature = (key: keyof ShareFeatures, on: boolean) => {+ void save({ ...current, features: { ...current.features, [key]: on } });+ };++ const copyLink = async () => {+ // The first copy creates the share, so the link works the moment it's on+ // 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);+ };++ const removeShare = async () => {+ setSaving(true);+ setError(null);+ try {+ const res = await apiFetch(`/api/cut/projects/${projectId}/share`, { method: "DELETE" });+ if (!res.ok) throw new Error();+ setShare(null);+ } catch {+ setError("Could not remove the share.");+ } finally {+ setSaving(false);+ }+ };++ return (+ <Dialog open onOpenChange={(open) => !open && onClose()}>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>Share project</DialogTitle>+ </DialogHeader>+ {loading ? (+ <div className="grid h-32 place-items-center text-muted-foreground">+ <Loader2 className="size-4 animate-spin" />+ </div>+ ) : (+ <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-1.5">+ <span className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">+ People+ </span>+ <input+ className="w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] outline-none focus:border-ring"+ type="email"+ placeholder="Invite by email, press Enter"+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ addEmail();+ }+ }}+ />+ {current.emails.length > 0 && (+ <div className="flex flex-wrap gap-1">+ {current.emails.map((email) => (+ <span+ key={email}+ className="inline-flex items-center gap-1 rounded-full bg-muted py-0.5 pr-1 pl-2 text-[11.5px]"+ >+ {email}+ <button+ 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)}+ >+ <X className="size-2.5" />+ </button>+ </span>+ ))}+ </div>+ )}+ </div>++ <div className="flex flex-col gap-1.5">+ <span className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">+ General access+ </span>+ <DropdownMenu>+ <DropdownMenuTrigger 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">+ {current.access === "public" ? (+ <Globe className="size-4 text-muted-foreground" />+ ) : (+ <Lock className="size-4 text-muted-foreground" />+ )}+ <span className="min-w-0 flex-1">+ <span className="block font-medium">+ {current.access === "public" ? "Anyone with the link" : "Restricted"}+ </span>+ <span className="block text-[11px] text-muted-foreground">+ {current.access === "public"+ ? "Anyone can view — no sign-in needed"+ : "Only people you invite can view, signed in"}+ </span>+ </span>+ <ChevronDown className="size-3.5 text-muted-foreground" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-72">+ <DropdownMenuItem onClick={() => setAccess("restricted")}>+ <Lock />+ <span className="flex-1">+ Restricted+ <span className="block text-[10.5px] text-muted-foreground">+ Only people you invite can view, signed in+ </span>+ </span>+ {current.access === "restricted" && (+ <Check className="size-3.5 text-muted-foreground" />+ )}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => setAccess("public")}>+ <Globe />+ <span className="flex-1">+ Anyone with the link+ <span className="block text-[10.5px] text-muted-foreground">+ Anyone can view — no sign-in needed+ </span>+ </span>+ {current.access === "public" && (+ <Check className="size-3.5 text-muted-foreground" />+ )}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>++ <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+ <ChevronDown className="size-3 transition-transform group-open:rotate-180" />+ </span>+ </summary>+ <p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">+ Viewers always get the preview and timeline, read-only. Switch+ on anything else they should see.+ </p>+ <div className="mt-1 flex flex-col">+ {FEATURE_ROWS.map(({ key, label, hint }) => (+ <label+ key={key}+ className="flex min-h-9 cursor-pointer items-center justify-between gap-2.5"+ >+ <span className="text-[13px]">+ {label}+ <span className="block text-[10.5px] text-muted-foreground">{hint}</span>+ </span>+ <Switch+ checked={current.features[key]}+ onCheckedChange={(on) => setFeature(key, on)}+ />+ </label>+ ))}+ </div>+ </details>++ {error && <p className="text-sm text-red-600">{error}</p>}+ </div>+ )}+ {!loading && (+ <DialogFooter className="mt-1 flex-col gap-2 sm:flex-col">+ <Button className="w-full" disabled={saving} onClick={() => void copyLink()}>+ {copied ? (+ <>+ <Check data-icon="inline-start" /> Copied+ </>+ ) : (+ <>+ <LinkIcon data-icon="inline-start" /> Copy link+ </>+ )}+ </Button>+ {share && (+ <Button+ variant="ghost"+ className="w-full text-muted-foreground hover:text-destructive"+ disabled={saving}+ onClick={() => void removeShare()}+ >+ Stop sharing+ </Button>+ )}+ </DialogFooter>+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxindex adee7837..323a0256 100644--- a/site/src/cut/components/SidePanel.tsx+++ b/site/src/cut/components/SidePanel.tsx@@ -109,11 +109,29 @@ export function SidePanel({onImport: (files: FileList | File[]) => void;importing: boolean;}) {+ // A shared view shows only the surfaces the share opted in; the Library is+ // the viewer's own cross-project shelf and never appears there.+ const sharedFeatures = useEditor((s) => s.sharedFeatures);+ const visibleTabs = !sharedFeatures+ ? TABS+ : TABS.filter(({ id }) =>+ id === "media"+ ? sharedFeatures.media+ : id === "video" || id === "image" || id === "audio"+ ? sharedFeatures.genai+ : id === "subtitles"+ ? sharedFeatures.subtitles+ : id === "publish"+ ? sharedFeatures.details+ : false+ );// `null` collapses the panel: clicking the active tab unselects it, leaving// just the icon rail so the video canvas takes the freed width.- const [tab, setTab] = useLocalPref<Tab | null>("cut-side-tab", "media", (v) =>+ const [tabPref, setTab] = useLocalPref<Tab | null>("cut-side-tab", "media", (v) =>v === null || TABS.some((t) => t.id === v));+ // The remembered tab may be hidden in this share; fall back to collapsed.+ const tab = tabPref !== null && !visibleTabs.some((t) => t.id === tabPref) ? null : tabPref;// The Audio tab's Voice/Music sub-tab lives here so the Music sub-tab can lay// out as two columns — the generator plus the sample library — like Image/Video.const [audioSub, setAudioSub] = useLocalPref<"voice" | "music">(@@ -179,7 +197,7 @@ export function SidePanel({tab !== null && "border-r border-border")}>- {TABS.map(({ id, label, icon: Icon }) => {+ {visibleTabs.map(({ id, label, icon: Icon }, tabIndex) => {// The open tab never badges — its completions are already on screen.const unseenCount = isGenTab(id) && id !== tab ? unseen[id].length : 0;const tileClass =@@ -242,7 +260,7 @@ export function SidePanel({return (<Fragment key={id}>{/* Soft breaks between the file tabs, the AI-generate tabs, and the finishing tabs. */}- {(id === "video" || id === "subtitles") && (+ {(id === "video" || id === "subtitles") && tabIndex > 0 && (<div aria-hidden className="my-1 h-px w-8 shrink-0 bg-border" />)}{id === "media" || id === "library" ? (@@ -266,22 +284,30 @@ export function SidePanel({// the stock reference browser on the right. Clicking a stock tile loads// its prompt into the generate panel beside it.<>- <div className="flex w-[252px] min-h-0 shrink-0 flex-col border-r border-border">+ <div+ className={cn(+ "flex w-[252px] min-h-0 shrink-0 flex-col",+ !sharedFeatures && "border-r border-border"+ )}+ >{tab === "image" ? (<ImageGenPanel projectId={projectId} />) : (<GenerateVideoPanel projectId={projectId} />)}</div>- {/* Video browses wider: 16:9 clip tiles need the room. */}- <div- className={cn(- "flex min-h-0 shrink-0 flex-col",- tab === "image" ? "w-[264px]" : "w-[340px]"- )}- >- {tab === "image" ? <StockImagesPanel /> : <StockVideosPanel />}- </div>+ {/* Video browses wider: 16:9 clip tiles need the room. A shared view+ shows only the project's own generations — no stock browsing. */}+ {!sharedFeatures && (+ <div+ className={cn(+ "flex min-h-0 shrink-0 flex-col",+ tab === "image" ? "w-[264px]" : "w-[340px]"+ )}+ >+ {tab === "image" ? <StockImagesPanel /> : <StockVideosPanel />}+ </div>+ )}</>) : tab === "audio" ? (// Music is two columns like the generate tabs — the generator on the@@ -290,7 +316,7 @@ export function SidePanel({<divclassName={cn("flex w-[264px] min-h-0 shrink-0 flex-col",- audioSub === "music" && STOCK_MUSIC.length > 0 && "border-r border-border"+ !sharedFeatures && audioSub === "music" && STOCK_MUSIC.length > 0 && "border-r border-border")}><AudioPanel@@ -300,7 +326,7 @@ export function SidePanel({onSub={setAudioSub}/></div>- {audioSub === "music" && STOCK_MUSIC.length > 0 && (+ {!sharedFeatures && audioSub === "music" && STOCK_MUSIC.length > 0 && (<div className="flex w-[340px] min-h-0 shrink-0 flex-col"><SampleLibrary projectId={projectId} /></div>@@ -410,6 +436,7 @@ function MediaPanel({const preparing = exportLocal.filter((r) => r.projectId === projectId && r.status === "preparing");+ const readOnly = useEditor((s) => s.readOnly);const inputRef = useRef<HTMLInputElement>(null);const [exports, setExports] = useState<ExportItem[]>([]);const [preview, setPreview] = useState<ExportItem | null>(null);@@ -456,22 +483,24 @@ function MediaPanel({) : undefined}/>- <div className="px-3.5 pb-3">- <Button variant="outline" className="w-full" onClick={() => inputRef.current?.click()}>- <Upload data-icon="inline-start" /> Upload- </Button>- <input- ref={inputRef}- type="file"- accept="video/*,audio/*"- multiple- hidden- onChange={(e) => {- if (e.target.files?.length) onImport(e.target.files);- e.target.value = "";- }}- />- </div>+ {!readOnly && (+ <div className="px-3.5 pb-3">+ <Button variant="outline" className="w-full" onClick={() => inputRef.current?.click()}>+ <Upload data-icon="inline-start" /> Upload+ </Button>+ <input+ ref={inputRef}+ type="file"+ accept="video/*,audio/*"+ multiple+ hidden+ onChange={(e) => {+ if (e.target.files?.length) onImport(e.target.files);+ e.target.value = "";+ }}+ />+ </div>+ )}<div className="min-h-0 flex-1 overflow-y-auto pb-3.5">{templates.length > 0 && (@@ -1098,6 +1127,7 @@ function ProjectFadeRow({ label, value, onChange }: {}function PublishPanel() {+ const readOnly = useEditor((s) => s.readOnly);const publish = useEditor((s) => s.publish);const setPublish = useEditor((s) => s.setPublish);const notes = useEditor((s) => s.notes);@@ -1113,19 +1143,21 @@ function PublishPanel() {<><PanelHead title="Details" /><div className="flex min-h-0 flex-col gap-4 overflow-y-auto px-3.5 pb-4">- <div className="flex flex-col gap-1.5">- <SectionTitle>Video</SectionTitle>- <ProjectFadeRow- label="Fade in"- value={fadeIn}- onChange={(v) => useEditor.getState().setProjectFade({ fadeIn: v })}- />- <ProjectFadeRow- label="Fade out"- value={fadeOut}- onChange={(v) => useEditor.getState().setProjectFade({ fadeOut: v })}- />- </div>+ {!readOnly && (+ <div className="flex flex-col gap-1.5">+ <SectionTitle>Video</SectionTitle>+ <ProjectFadeRow+ label="Fade in"+ value={fadeIn}+ onChange={(v) => useEditor.getState().setProjectFade({ fadeIn: v })}+ />+ <ProjectFadeRow+ label="Fade out"+ value={fadeOut}+ onChange={(v) => useEditor.getState().setProjectFade({ fadeOut: v })}+ />+ </div>+ )}<div className="flex flex-col gap-1.5"><div className="flex items-center justify-between">@@ -1136,6 +1168,7 @@ function PublishPanel() {className="publish-caption min-h-[110px] w-full resize-y rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] leading-relaxed outline-none focus:border-ring"placeholder={"What's happening in this video?\n\nHooks read best in the first line."}value={publish.caption}+ readOnly={readOnly}onChange={(e) => setPublish({ caption: e.target.value })}/></div>@@ -1149,6 +1182,7 @@ function PublishPanel() {className="publish-tags w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] outline-none focus:border-ring"placeholder="fyp howto cut"value={publish.tags}+ readOnly={readOnly}onChange={(e) => setPublish({ tags: e.target.value })}/>{tagsLine && (@@ -1174,6 +1208,7 @@ function PublishPanel() {className="publish-sound w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] outline-none focus:border-ring"placeholder="My track — artist"value={publish.soundTitle}+ readOnly={readOnly}onChange={(e) => setPublish({ soundTitle: e.target.value })}/><p className="text-[11px] leading-relaxed text-muted-foreground">@@ -1190,6 +1225,7 @@ function PublishPanel() {type="date"className="notes-date rounded-lg border border-input bg-transparent px-2 py-1 text-[12px] outline-none focus:border-ring"value={notes.publishedAt}+ disabled={readOnly}onChange={(e) => setNotes({ publishedAt: e.target.value })}/></label>@@ -1197,12 +1233,14 @@ function PublishPanel() {className="notes-links min-h-[54px] w-full resize-y rounded-lg border border-input bg-transparent px-2.5 py-2 font-mono text-[11.5px] leading-relaxed outline-none focus:border-ring"placeholder={"Links, one per line\nhttps://tiktok.com/…"}value={notes.links.join("\n")}+ readOnly={readOnly}onChange={(e) => setNotes({ links: e.target.value.split("\n") })}/><textareaclassName="notes-text min-h-[70px] w-full resize-y rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] leading-relaxed outline-none focus:border-ring"placeholder="Anything worth remembering about this cut…"value={notes.text}+ readOnly={readOnly}onChange={(e) => setNotes({ text: e.target.value })}/></div>diff --git a/site/src/cut/components/SubtitlesPanel.tsx b/site/src/cut/components/SubtitlesPanel.tsxindex 3f62eb91..19cfe614 100644--- a/site/src/cut/components/SubtitlesPanel.tsx+++ b/site/src/cut/components/SubtitlesPanel.tsx@@ -73,6 +73,7 @@ function laneLanguage(subs: SubtitlesBlock, lane: number): string {export function SubtitlesPanel() {const caps = useCutCaps();+ const readOnly = useEditor((s) => s.readOnly);const subtitles = useEditor((s) => s.subtitles);const lane = useEditor((s) => s.subtitleLane);const status = useEditor((s) => s.subtitleStatus);@@ -96,6 +97,25 @@ export function SubtitlesPanel() {void useEditor.getState().translateSubtitleTrack(fromLane).then(growTimeline);};+ // A shared view reads the transcript; styling and generation stay the+ // owner's.+ if (readOnly) {+ return (+ <>+ <div className="flex h-12 shrink-0 items-center pl-4">+ <span className="text-sm font-semibold tracking-tight">Subtitles</span>+ </div>+ {hasCues ? (+ <Transcript cues={activeCues} />+ ) : (+ <p className="px-4 text-[11px] leading-relaxed text-muted-foreground">+ No subtitles yet.+ </p>+ )}+ </>+ );+ }+return (<><div className="flex h-12 shrink-0 items-center justify-between pr-2.5 pl-4">diff --git a/site/src/cut/components/TopBar.tsx b/site/src/cut/components/TopBar.tsxindex dbe4af73..0548777b 100644--- a/site/src/cut/components/TopBar.tsx+++ b/site/src/cut/components/TopBar.tsx@@ -2,7 +2,7 @@import { useState } from "react";import Link from "next/link";-import { Check, ChevronDown, ChevronLeft, Cloud, Ellipsis, Loader2, Mic, Monitor, Smartphone, Sparkles, Upload, Video } from "lucide-react";+import { Check, ChevronDown, ChevronLeft, Cloud, Ellipsis, Loader2, Mic, Monitor, Share2, Smartphone, Sparkles, Upload, Video } from "lucide-react";import { Button } from "@/components/ui/button";import {Dialog,@@ -27,6 +27,7 @@ import { useEditor } from "@/cut/lib/store";import { ASPECT_LABEL, type Aspect } from "@/cut/lib/types";import { cn } from "@/lib/utils";import { RecordDialog, type RecordMode } from "./RecordDialog";+import { ShareDialog } from "./ShareDialog";export function TopBar({onImport,@@ -61,6 +62,7 @@ export function TopBar({// Cloud imports are real uploads worth reporting; local imports are instant// disk copies, so the flag-off surface stays exactly as it was.const cloudUploading = uploading > 0 && cutMode === "cloud";+ const [shareOpen, setShareOpen] = useState(false);const [moveOpen, setMoveOpen] = useState(false);const [moving, setMoving] = useState(false);const [moveProgress, setMoveProgress] = useState<string | null>(null);@@ -213,29 +215,41 @@ export function TopBar({</span></div><div className="flex items-center gap-2">+ {cutMode === "cloud" && (+ <Button+ variant="ghost"+ size="sm"+ aria-label="Share"+ title="Share"+ onClick={() => setShareOpen(true)}+ >+ <Share2 data-icon="inline-start" /> Share+ </Button>+ )}<Button- variant="ghost"size="sm"- className="ai-toggle"- aria-label="Chat"- title="Chat (⌘J)"+ disabled={!hasClips}onClick={() => {const s = useEditor.getState();- s.setAiOpen(!s.aiOpen);+ s.setPlaying(false);+ s.setExportOpen(true);}}>- <Sparkles data-icon="inline-start" /> Chat+ <Upload data-icon="inline-start" /> Export</Button>+ <div aria-hidden className="h-4 w-px bg-border" /><Button+ variant="ghost"size="sm"- disabled={!hasClips}+ className="ai-toggle"+ aria-label="Chat"+ title="Chat (⌘J)"onClick={() => {const s = useEditor.getState();- s.setPlaying(false);- s.setExportOpen(true);+ s.setAiOpen(!s.aiOpen);}}>- <Upload data-icon="inline-start" /> Export+ <Sparkles data-icon="inline-start" /> Chat</Button>{canMoveToCloud && (<DropdownMenu>@@ -259,6 +273,12 @@ export function TopBar({</DropdownMenu>)}</div>+ {shareOpen && (+ <ShareDialog+ projectId={useEditor.getState().projectId ?? ""}+ onClose={() => setShareOpen(false)}+ />+ )}{moveOpen && (<Dialog open onOpenChange={(open) => !open && !moving && setMoveOpen(false)}><DialogContent className="sm:max-w-sm">diff --git a/site/src/cut/components/ViewerTopBar.tsx b/site/src/cut/components/ViewerTopBar.tsxnew file mode 100644index 00000000..21bc0a06--- /dev/null+++ b/site/src/cut/components/ViewerTopBar.tsx@@ -0,0 +1,118 @@+"use client";++import { useState } from "react";+import { Copy, Loader2, Sparkles } from "lucide-react";+import { authHrefFor } from "@/app/_components/landing/useAppEntryHref";+import { Button } from "@/components/ui/button";+import { apiFetch } from "@/cut/lib/backend";+import { quotaErrorMessage } from "@/cut/lib/backend/cloud";+import { enableWebMode } from "@/cut/lib/flags";+import { projectHref, useCutBase } from "@/cut/lib/nav";+import { useEditor } from "@/cut/lib/store";+import { authClient } from "@/lib/auth-client";++// Chrome for the read-only share view: logo, project name, a "View only"+// chip, and the viewer's two actions — open the shared chat (when the share+// includes it) and copy the project into their own account. Copying needs a+// session: signed-out clicks route through sign-in with this share URL as the+// callback.+export function ViewerTopBar() {+ const base = useCutBase();+ const projectName = useEditor((s) => s.projectName);+ const chatShared = useEditor((s) => s.sharedFeatures?.chat === true);+ const { data: session } = authClient.useSession();+ const [copying, setCopying] = useState(false);+ const [copyError, setCopyError] = useState<string | null>(null);++ const copyProject = async () => {+ if (!session) {+ const here = window.location.pathname + window.location.search;+ window.location.href = authHrefFor("/sign-in", here);+ return;+ }+ setCopying(true);+ setCopyError(null);+ try {+ const res = await apiFetch("/api/cut/copy", { method: "POST" });+ const body = (await res.json().catch(() => null)) as+ | { jobId?: string; error?: string }+ | null;+ if (!res.ok || !body?.jobId) {+ throw new Error(+ quotaErrorMessage(res.status, body) ?? body?.error ?? "Could not copy the project."+ );+ }+ // Copies drain through a queue one at a time; poll the job until this+ // one lands.+ for (;;) {+ await new Promise((r) => setTimeout(r, 2000));+ const st = await apiFetch(`/api/cut/copy/${body.jobId}`);+ if (!st.ok) throw new Error("Could not copy the project.");+ const job = (await st.json()) as {+ state: string;+ newProjectId?: string;+ error?: string;+ };+ if (job.state === "done" && job.newProjectId) {+ // The copy is a cloud project, so cloud editing must be on for+ // this account before the editor opens it.+ await enableWebMode();+ window.location.href = projectHref(base, job.newProjectId, "projects");+ return;+ }+ if (job.state === "error") throw new Error(job.error ?? "Could not copy the project.");+ }+ } catch (e) {+ setCopyError(e instanceof Error ? e.message : "Could not copy the project.");+ setCopying(false);+ }+ };++ return (+ <header className="relative flex items-center justify-between border-b border-border bg-card pr-3 pl-3">+ <div className="flex min-w-0 items-center gap-1">+ <span className="grid size-[22px] shrink-0 place-items-center">+ <img+ src="/donkey-logo.svg"+ alt="Donkey"+ width={22}+ height={22}+ className="block h-full w-full object-contain"+ />+ </span>+ <span className="ml-1.5 max-w-64 truncate px-2 py-1 text-sm font-medium tracking-tight">+ {projectName}+ </span>+ <span className="ml-1 rounded-full border border-border px-2 py-0.5 text-[10.5px] font-medium text-muted-foreground">+ View only+ </span>+ </div>+ <div className="flex items-center gap-2">+ {copyError && <span className="max-w-72 truncate text-xs text-destructive">{copyError}</span>}+ {chatShared && (+ <Button+ variant="ghost"+ size="sm"+ className="ai-toggle"+ aria-label="Chat"+ title="Chat (⌘J)"+ onClick={() => {+ const s = useEditor.getState();+ s.setAiOpen(!s.aiOpen);+ }}+ >+ <Sparkles data-icon="inline-start" /> Chat+ </Button>+ )}+ <Button size="sm" disabled={copying} onClick={() => void copyProject()}>+ {copying ? (+ <Loader2 className="animate-spin" data-icon="inline-start" />+ ) : (+ <Copy data-icon="inline-start" />+ )}+ {copying ? "Copying…" : "Copy project"}+ </Button>+ </div>+ </header>+ );+}diff --git a/site/src/cut/lib/backend/cloud.ts b/site/src/cut/lib/backend/cloud.tsindex d5f3989f..564569ea 100644--- a/site/src/cut/lib/backend/cloud.ts+++ b/site/src/cut/lib/backend/cloud.ts@@ -53,9 +53,11 @@ async function cloudFetch(path: string, init?: RequestInit): Promise<Response> {return res;}-/** Batch-mint signed R2 GET URLs for a cloud project's media files. Returns- * fileName -> url; anything the mint misses keeps the /media route, whose 302- * serves the same bytes. */+/** Batch-mint signed R2 GET URLs for a cloud or shared project's media files.+ * Returns fileName -> url; anything the mint misses keeps the /media route,+ * whose 302 serves the same bytes. Dispatches through the active backend so+ * the shared driver's token prefix applies; lazy import because ./index+ * imports this module. */export async function fetchSignedMediaUrls(projectId: string,fileNames: string[]@@ -63,7 +65,8 @@ export async function fetchSignedMediaUrls(const out = new Map<string, string>();if (fileNames.length === 0) return out;try {- const res = await cloudFetch("/api/cut/media/presign-get", {+ const { apiFetch } = await import("./index");+ const res = await apiFetch("/api/cut/media/presign-get", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ items: fileNames.map((fileName) => ({ projectId, fileName })) }),diff --git a/site/src/cut/lib/backend/index.ts b/site/src/cut/lib/backend/index.tsindex b17a87f8..f33c6115 100644--- a/site/src/cut/lib/backend/index.ts+++ b/site/src/cut/lib/backend/index.ts@@ -8,6 +8,7 @@// imports apiUrl from here. React hooks live in ./hooks.import { cloudBackend } from "./cloud";import { localBackend } from "./local";+import { sharedBackend } from "./shared";import type { CutBackend, CutCaps, CutMode } from "./types";export type { CutBackend, CutCaps, CutMode };@@ -36,7 +37,7 @@ export function subscribeCutMode(onChange: () => void) {}export function getBackend(): CutBackend {- return mode === "cloud" ? cloudBackend : localBackend;+ return mode === "cloud" ? cloudBackend : mode === "shared" ? sharedBackend : localBackend;}/** fetch() against the active backend. */diff --git a/site/src/cut/lib/backend/shared.ts b/site/src/cut/lib/backend/shared.tsnew file mode 100644index 00000000..03c35c4e--- /dev/null+++ b/site/src/cut/lib/backend/shared.ts@@ -0,0 +1,30 @@+// The shared backend: a read-only view of someone else's cloud project,+// reached through the public /api/cut-shared/<token>/* surface. The token is+// the share link's id; the viewer page binds it before the editor mounts.+// Reads only — the viewer never PUTs, so there is no version map here.+import type { CutBackend } from "./types";++let token = "";++/** Bind the share link token before setCutMode("shared"). */+export function bindSharedBackend(next: string) {+ token = next;+}++const sharedPath = (path: string) =>+ path.replace(/^\/api\/cut\//, `/api/cut-shared/${encodeURIComponent(token)}/`);++export const sharedBackend: CutBackend = {+ kind: "shared",+ caps: {+ importUrl: false,+ liveMic: false,+ transcribe: false,+ captionAi: false,+ localCliChat: false,+ revealInFinder: false,+ watch: false,+ },+ fetch: (path, init) => fetch(sharedPath(path), init),+ url: (path) => sharedPath(path),+};diff --git a/site/src/cut/lib/backend/types.ts b/site/src/cut/lib/backend/types.tsindex 14343c7a..b57dc2d0 100644--- a/site/src/cut/lib/backend/types.ts+++ b/site/src/cut/lib/backend/types.ts@@ -1,10 +1,11 @@// A Cut backend is where a project lives and executes: "local" is the engine// on this Mac (127.0.0.1, disk storage, native tools), "cloud" is the hosted-// deployment (session auth, Postgres + R2). Both speak the same JSON route-// shapes, so ordinary API calls dispatch through one transport; operations-// whose contracts genuinely differ (uploads, export, transcription) branch on-// the backend kind where they are implemented.-export type CutMode = "local" | "cloud";+// deployment (session auth, Postgres + R2), and "shared" is a read-only view+// of another account's cloud project through a share link. All speak the same+// JSON route shapes, so ordinary API calls dispatch through one transport;+// operations whose contracts genuinely differ (uploads, export,+// transcription) branch on the backend kind where they are implemented.+export type CutMode = "local" | "cloud" | "shared";// What the active backend can do. Components consult these to hide// affordances instead of feature-detecting or failing at call time.diff --git a/site/src/cut/lib/chatCloud.ts b/site/src/cut/lib/chatCloud.tsindex 5715e65b..de59bd15 100644--- a/site/src/cut/lib/chatCloud.ts+++ b/site/src/cut/lib/chatCloud.ts@@ -18,7 +18,9 @@ const seeded = new Map<string, Promise<void>>();* projects; memoized per project, but a network failure clears the memo so* the next panel mount retries. */export function ensureCloudThreads(projectId: string): Promise<void> {- if (cutMode() !== "cloud") return Promise.resolve();+ // Shared viewers seed too (read-only); saves and deletes below stay+ // cloud-only, so a viewer never writes back.+ if (cutMode() === "local") return Promise.resolve();let p = seeded.get(projectId);if (!p) {p = seedThreads(projectId).catch(() => {diff --git a/site/src/cut/lib/genScene.ts b/site/src/cut/lib/genScene.tsindex e0894f2c..abcfc038 100644--- a/site/src/cut/lib/genScene.ts+++ b/site/src/cut/lib/genScene.ts@@ -99,6 +99,9 @@ useEditor.subscribe((s, prev) => {// mounts. loadProject flips `loaded` false→true in the same set() that// fills genvideo, so the edge fires once per open.if (!s.loaded || prev.loaded || !s.projectId) return;+ // A shared view shows the owner's persisted run as data only — never+ // adopt or resume it (resuming would render on the viewer's account).+ if (s.readOnly) return;const live = orchestrators.get(s.projectId);if (live && !live.isAborted && !isTerminal(statusFor(live.project))) {// The run is still working: its clips loaded as ordinary content — re-markdiff --git a/site/src/cut/lib/laneTracks.ts b/site/src/cut/lib/laneTracks.tsindex 9b6f6430..b2ab59ee 100644--- a/site/src/cut/lib/laneTracks.ts+++ b/site/src/cut/lib/laneTracks.ts@@ -366,6 +366,8 @@ export function startLaneMove<V = unknown>((ui.visStart ?? self.start) +(e.clientX - e.currentTarget.getBoundingClientRect().left) / ui.pps;s.seek(grabTime);+ // A read-only view: the click selects and seeks; the drag never starts.+ if (s.readOnly) return;s.pushHistory();const start0 = self.start;@@ -588,6 +590,7 @@ export function startLaneTrim() {settleSnapBack();const s = useEditor.getState();+ if (s.readOnly) return;const ad = ADAPTERS[kind];const raw0 = ad.raws(s).find((r) => ad.view(r).id === id);if (!raw0) return;diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex b014ffb8..b6013c97 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -12,6 +12,7 @@ import type {ProjectDoc,RenderRecord,Selection,+ ShareFeatures,StoredAsset,SubtitleCue,SubtitlesBlock,@@ -100,6 +101,11 @@ export interface EditorState {loaded: boolean;loadError: string | null;saveState: SaveState;+ /** Read-only shared view: the set wrapper strips doc-mutating writes, so+ * every edit path is inert by construction. View state stays live. */+ readOnly: boolean;+ /** The share's opted-in surfaces; null outside a shared view. */+ sharedFeatures: ShareFeatures | null;assets: MediaAsset[];/** Every video clip, on any track. Tracks number 0..N bottom-up: track 0@@ -156,6 +162,8 @@ export interface EditorState {loadProject: (id: string) => Promise<void>;setProjectName: (name: string) => void;setSaveState: (s: SaveState) => void;+ /** Enter read-only shared mode; call before loadProject. */+ setSharedView: (features: ShareFeatures) => void;setAspect: (a: Aspect) => void;/** Set the whole-video fade in/out (seconds; 0 clears). Like the aspect,@@ -648,6 +656,28 @@ export async function runTranscription(projectId: string, spec: object): Promise}}+// Doc-mutating state: in a read-only shared view the set wrapper drops these+// keys from every write, so edit paths anywhere in the app become no-ops.+// Hydration (loadProject, the shared-view poll) escapes via `hydrating`.+const DOC_KEYS = [+ "projectName",+ "saveState",+ "assets",+ "clips",+ "audioClips",+ "overlays",+ "templates",+ "aspect",+ "fadeIn",+ "fadeOut",+ "publish",+ "notes",+ "subtitles",+ "genvideo",+ "renders",+] as const;+let hydrating = false;+export const useEditor = create<EditorState>((baseSet, get) => {// Every write that touches clips grounds the stack, so the spine invariant// holds by construction — across deletes, drops, undo, and doc loads.@@ -658,7 +688,11 @@ export const useEditor = create<EditorState>((baseSet, get) => {replace?: boolean) =>baseSet((prev) => {- const next = typeof partial === "function" ? partial(prev) : partial;+ let next = typeof partial === "function" ? partial(prev) : partial;+ if (prev.readOnly && !hydrating) {+ next = { ...next };+ for (const k of DOC_KEYS) delete (next as Record<string, unknown>)[k];+ }return next.clips ? { ...next, clips: groundTracks(next.clips) } : next;}, replace as false | undefined);@@ -743,6 +777,8 @@ export const useEditor = create<EditorState>((baseSet, get) => {loaded: false,loadError: null,saveState: "saved",+ readOnly: false,+ sharedFeatures: null,assets: [],clips: [],@@ -781,6 +817,7 @@ export const useEditor = create<EditorState>((baseSet, get) => {// stale, and the loaded clips are ordinary, fully-undoable content.genClipIds.clear();genAudioIds.clear();+ hydrating = true;set({projectId: id,loaded: false,@@ -807,6 +844,7 @@ export const useEditor = create<EditorState>((baseSet, get) => {genvideo: undefined,renders: [],});+ hydrating = false;// A background scene run may still be writing this project's doc — drain// its queued writes so the load never reads a half-written doc. Ordering// matters: projectId is set (loaded false) BEFORE this await, so a write@@ -823,9 +861,10 @@ export const useEditor = create<EditorState>((baseSet, get) => {...a,url: mediaUrl(id, a.fileName),}));- // Cloud media rides signed R2 URLs, batch-minted once per load; the- // /media route's 302 stays the fallback for anything the mint misses.- if (getBackend().kind === "cloud") {+ // Cloud and shared media ride signed R2 URLs, batch-minted once per+ // load; the /media route's 302 stays the fallback for anything the+ // mint misses.+ if (getBackend().kind !== "local") {const signed = await fetchSignedMediaUrls(id, assets.map((a) => a.fileName));for (const a of assets) a.url = signed.get(a.fileName) ?? a.url;}@@ -857,6 +896,7 @@ export const useEditor = create<EditorState>((baseSet, get) => {// Docs saved when edge transition styles existed convert them into the// equivalent clip animations.const merged = migrateLegacyTransitions(lifted);+ hydrating = true;set({projectName: doc.name,assets,@@ -893,11 +933,14 @@ export const useEditor = create<EditorState>((baseSet, get) => {});} catch (err) {set({ loadError: err instanceof Error ? err.message : String(err) });+ } finally {+ hydrating = false;}},setProjectName: (name) => set({ projectName: name }),setSaveState: (s) => set({ saveState: s }),+ setSharedView: (features) => set({ readOnly: true, sharedFeatures: features }),// Clone so each persist yields a fresh top-level reference: the orchestrator// mutates one project object in place, and autosave detects a genvideo change@@ -1064,10 +1107,31 @@ export const useEditor = create<EditorState>((baseSet, get) => {return { assets: [...s.assets, asset], ...(guess ? { aspect: guess } : {}) };}),- updateAsset: (id, patch) =>+ updateAsset: (id, patch) => {+ // A read-only view still takes runtime enrichment (signed URLs,+ // filmstrips, waveforms) — decorative fields only; doc fields stay+ // stripped with every other edit.+ if (get().readOnly) {+ const runtime: Partial<MediaAsset> = {};+ if (patch.url !== undefined) runtime.url = patch.url;+ if (patch.thumbs !== undefined) runtime.thumbs = patch.thumbs;+ if (patch.thumbStep !== undefined) runtime.thumbStep = patch.thumbStep;+ if (patch.peaks !== undefined) runtime.peaks = patch.peaks;+ if (Object.keys(runtime).length === 0) return;+ hydrating = true;+ try {+ set((s) => ({+ assets: s.assets.map((a) => (a.id === id ? { ...a, ...runtime } : a)),+ }));+ } finally {+ hydrating = false;+ }+ return;+ }set((s) => ({assets: s.assets.map((a) => (a.id === id ? { ...a, ...patch } : a)),- })),+ }));+ },removeAsset: (id) => {const st = get();diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex 51297a83..c48285a5 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -649,6 +649,16 @@ export interface ClipSpan {}/** The document persisted as project.json inside each project folder. */+/** Which optional surfaces a project share exposes to viewers. Playback+ * (preview + timeline) is always shared; these opt the rest in. */+export interface ShareFeatures {+ chat: boolean;+ media: boolean;+ genai: boolean;+ subtitles: boolean;+ details: boolean;+}+export interface ProjectDoc {version: 1;name: string;diff --git a/site/src/cut/server/cloud/share.ts b/site/src/cut/server/cloud/share.tsnew file mode 100644index 00000000..ec383b5b--- /dev/null+++ b/site/src/cut/server/cloud/share.ts@@ -0,0 +1,98 @@+// Owner-side management of a cloud project's share. One row per project+// (CutProjectShare); the row id is the link token viewers open. Viewer-side+// reads live in sharedView.ts.+import { randomBytes } from "node:crypto";+import type { ShareFeatures } from "@/cut/lib/types";+import { prisma } from "@/lib/prisma";+import { getProject } from "./projects";+import { caught, err } from "./util";++export type ShareAccess = "restricted" | "public";+export type { ShareFeatures };++const FEATURE_KEYS = ["chat", "media", "genai", "subtitles", "details"] as const;+const MAX_EMAILS = 50;+const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;++/** The share id is the link token, and for a public share it is the only+ * gate — so it must be unguessable, not a sequential/fingerprinted cuid. 24+ * random bytes (~192 bits) base64url. */+function newShareToken(): string {+ return randomBytes(24).toString("base64url");+}++export function normalizeFeatures(raw: unknown): ShareFeatures {+ const src = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};+ return Object.fromEntries(FEATURE_KEYS.map((k) => [k, src[k] === true])) as unknown as ShareFeatures;+}++/** Lowercased, deduped, email-shaped list — or null when the input is not a+ * valid list. */+export function normalizeEmails(raw: unknown): string[] | null {+ if (!Array.isArray(raw) || raw.length > MAX_EMAILS) return null;+ const emails = new Set<string>();+ for (const item of raw) {+ if (typeof item !== "string") return null;+ const email = item.trim().toLowerCase();+ if (!EMAIL_RE.test(email) || email.length > 254) return null;+ emails.add(email);+ }+ return [...emails];+}++type ShareRow = {+ id: string;+ projectId: string;+ userId: string;+ access: string;+ emails: unknown;+ features: unknown;+};++const shareJson = (row: ShareRow) => ({+ id: row.id,+ access: (row.access === "public" ? "public" : "restricted") as ShareAccess,+ emails: normalizeEmails(row.emails) ?? [],+ features: normalizeFeatures(row.features),+});++export const shareCloud = {+ async get(userId: string, projectId: string) {+ if (!(await getProject(userId, projectId))) return err("Project not found.", 404);+ const row = await prisma.cutProjectShare.findUnique({ where: { projectId } });+ return Response.json({ share: row && row.userId === userId ? shareJson(row) : null });+ },++ async put(userId: string, projectId: string, req: Request) {+ try {+ if (!(await getProject(userId, projectId))) return err("Project not found.", 404);+ const body = (await req.json()) as {+ access?: unknown;+ emails?: unknown;+ features?: unknown;+ };+ const access = body.access === "public" ? "public" : "restricted";+ const emails = normalizeEmails(body.emails ?? []);+ if (!emails) return err("Bad email list.", 400);+ const features = normalizeFeatures(body.features);+ const data = { access, emails, features: { ...features } };+ const row = await prisma.cutProjectShare.upsert({+ where: { projectId },+ create: { id: newShareToken(), projectId, userId, ...data },+ update: data,+ });+ return Response.json({ share: shareJson(row) });+ } catch (e) {+ return caught(e, "Could not save the share.");+ }+ },++ async remove(userId: string, projectId: string) {+ try {+ await prisma.cutProjectShare.deleteMany({ where: { projectId, userId } });+ return Response.json({ ok: true });+ } catch (e) {+ return caught(e, "Could not remove the share.");+ }+ },+};diff --git a/site/src/cut/server/cloud/sharedView.ts b/site/src/cut/server/cloud/sharedView.tsnew file mode 100644index 00000000..0ce282ae--- /dev/null+++ b/site/src/cut/server/cloud/sharedView.ts@@ -0,0 +1,197 @@+// Viewer-side reads of a shared cloud project. Every handler resolves the+// share token first, then reads the OWNER's rows and presigns the owner's R2+// keys — the viewer's session (if any) only ever gates access. The server is+// the content boundary: the filtered doc and the media allowlist are what+// decide which bytes a viewer can reach; the client's tab hiding is+// presentation only. Copying a share lives in copyQueue.ts.+import type { ProjectDoc, StoredAsset } from "@/cut/lib/types";+import { auth } from "@/lib/auth";+import { prisma } from "@/lib/prisma";+import { presignGet, projectMediaKey } from "./r2";+import { normalizeEmails, normalizeFeatures, type ShareFeatures } from "./share";+import { caught, decodeFileParam, err, redirect } from "./util";++const PRESIGN_GET_BATCH_MAX = 500;++export type ShareRow = NonNullable<+ Awaited<ReturnType<typeof prisma.cutProjectShare.findUnique>>+>;++interface ShareView {+ share: ShareRow;+ features: ShareFeatures;+}++/** Resolve who may see this share: the row must exist, and a restricted share+ * additionally needs a signed-in viewer who is the owner or an invitee.+ * Returns the error Response to send when access fails. */+export async function resolveShare(token: string, req: Request): Promise<ShareView | Response> {+ if (!token || token.length > 64) return err("Share not found.", 404);+ const share = await prisma.cutProjectShare.findUnique({ where: { id: token } });+ if (!share) return err("Share not found.", 404);+ const features = normalizeFeatures(share.features);+ if (share.access === "public") return { share, features };+ const session = await auth.api.getSession({ headers: req.headers });+ if (!session?.user) return err("Sign in to view this project.", 401);+ const email = session.user.email?.toLowerCase() ?? "";+ const invited = (normalizeEmails(share.emails) ?? []).includes(email);+ if (session.user.id !== share.userId && !invited) {+ return err("You don't have access to this project.", 403);+ }+ return { share, features };+}++async function ownerProject(share: ShareRow) {+ return prisma.cutProject.findFirst({ where: { id: share.projectId, userId: share.userId } });+}++/** The asset set a viewer may see: everything playback needs (referenced by a+ * clip), plus each optional surface's assets when that surface is shared.+ * Untagged assets belong to the Media panel; origin-tagged ones to the+ * generate panels; chat-tagged ones to chat. The Library is never shared. */+function allowedAssets(doc: ProjectDoc, features: ShareFeatures): StoredAsset[] {+ const assets = Array.isArray(doc.assets) ? doc.assets : [];+ const referenced = new Set<string>([+ ...(Array.isArray(doc.clips) ? doc.clips : []).map((c) => c.assetId),+ ...(Array.isArray(doc.audioClips) ? doc.audioClips : []).map((c) => c.assetId),+ ]);+ return assets.filter((a) => {+ if (referenced.has(a.id)) return true;+ if (a.chatId) return features.chat;+ if (a.origin) return features.genai;+ return features.media;+ });+}++export function filterDocForShare(doc: ProjectDoc, features: ShareFeatures): ProjectDoc {+ const filtered: ProjectDoc = {+ ...doc,+ assets: allowedAssets(doc, features),+ templates: undefined,+ folderId: null,+ ui: undefined,+ publish: features.details ? doc.publish : undefined,+ notes: features.details ? doc.notes : undefined,+ genvideo: features.genai ? doc.genvideo : undefined,+ renders: features.chat ? doc.renders : undefined,+ // The transcript ships only when Subtitles is shared: the cue text and+ // word timings are content, so a hidden panel is not enough — the doc+ // itself must not carry them. Without it the viewer's playback shows no+ // burned-in captions either, which is the point of the toggle.+ subtitles: features.subtitles ? doc.subtitles : undefined,+ };+ return filtered;+}++async function allowedFileNames(share: ShareRow, features: ShareFeatures): Promise<Set<string>> {+ const row = await ownerProject(share);+ if (!row) return new Set();+ return new Set(allowedAssets(row.doc as unknown as ProjectDoc, features).map((a) => a.fileName));+}++export const sharedView = {+ async meta(token: string, req: Request) {+ const view = await resolveShare(token, req);+ if (view instanceof Response) return view;+ const row = await ownerProject(view.share);+ if (!row) return err("Share not found.", 404);+ return Response.json({+ projectId: view.share.projectId,+ name: row.name,+ access: view.share.access,+ features: view.features,+ });+ },++ async doc(token: string, id: string, req: Request) {+ const view = await resolveShare(token, req);+ if (view instanceof Response) return view;+ if (id !== view.share.projectId) return err("Project not found.", 404);+ // The viewer's 10s change-poll is a HEAD that only reads the version+ // header. Serve it from a version-only select instead of reading and+ // filtering the whole doc every tick.+ if (req.method === "HEAD") {+ const meta = await prisma.cutProject.findFirst({+ where: { id: view.share.projectId, userId: view.share.userId },+ select: { version: true },+ });+ if (!meta) return err("Project not found.", 404);+ return new Response(null, { headers: { "x-cut-doc-version": String(meta.version) } });+ }+ const row = await ownerProject(view.share);+ if (!row) return err("Project not found.", 404);+ return Response.json(filterDocForShare(row.doc as unknown as ProjectDoc, view.features), {+ headers: { "x-cut-doc-version": String(row.version) },+ });+ },++ async serveMedia(token: string, id: string, file: string, req: Request) {+ try {+ const view = await resolveShare(token, req);+ if (view instanceof Response) return view;+ if (id !== view.share.projectId) return err("Project not found.", 404);+ const fileName = decodeFileParam(file);+ const allowed = await allowedFileNames(view.share, view.features);+ if (!allowed.has(fileName)) return err("Media not found.", 404);+ return redirect(await presignGet(projectMediaKey(view.share.userId, id, fileName)));+ } catch (e) {+ return caught(e, "Bad request.", 400);+ }+ },++ async presignGetBatch(token: string, req: Request) {+ try {+ const view = await resolveShare(token, req);+ if (view instanceof Response) return view;+ const { items } = (await req.json()) as {+ items?: { projectId?: string; fileName?: string }[];+ };+ if (!Array.isArray(items)) return err("items is required.", 400);+ if (items.length > PRESIGN_GET_BATCH_MAX) return err("Too many items.", 400);+ const allowed = await allowedFileNames(view.share, view.features);+ const urls = await Promise.all(+ items+ .filter(+ (i) =>+ i.projectId === view.share.projectId &&+ typeof i.fileName === "string" &&+ allowed.has(i.fileName)+ )+ .map(async (i) => ({+ projectId: i.projectId!,+ fileName: i.fileName!,+ url: await presignGet(projectMediaKey(view.share.userId, i.projectId!, i.fileName!)),+ }))+ );+ return Response.json({ urls });+ } catch (e) {+ return caught(e, "Could not sign the media URLs.");+ }+ },++ async chats(token: string, id: string, req: Request) {+ const view = await resolveShare(token, req);+ if (view instanceof Response) return view;+ if (id !== view.share.projectId || !view.features.chat) return err("Not found.", 404);+ const rows = await prisma.cutChatThread.findMany({+ where: { userId: view.share.userId, projectId: id },+ orderBy: { updatedAt: "desc" },+ select: { data: true },+ });+ return Response.json(rows.map((r) => r.data));+ },++ async preview(token: string, id: string, req: Request) {+ try {+ const view = await resolveShare(token, req);+ if (view instanceof Response) return view;+ if (id !== view.share.projectId) return err("Not found.", 404);+ const row = await ownerProject(view.share);+ if (!row?.previewKey) return new Response("Not found.", { status: 404 });+ return redirect(await presignGet(row.previewKey));+ } catch (e) {+ return caught(e, "Bad request.", 400);+ }+ },++};