Skip to content

Open source CapCut alternative.

TypeScript

feat(site): play a shared project on a phone

David Lefc96144d2e67
diff --git a/site/package-lock.json b/site/package-lock.json
index 52b14e76..b1ee1303 100644
--- a/site/package-lock.json
+++ b/site/package-lock.json
@@ -37,6 +37,7 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"defuddle": "^0.18.1",
+ "hls.js": "^1.6.16",
"linkedom": "^0.18.12",
"lucide-react": "^1.23.0",
"next": "16.2.6",
@@ -8740,6 +8741,12 @@
"hermes-estree": "0.25.1"
}
},
+ "node_modules/hls.js": {
+ "version": "1.6.16",
+ "resolved": "https://registry.npmjs.org/hls.js/-/hls.js-1.6.16.tgz",
+ "integrity": "sha512-VSIRpLfRwlAAdGL4wiTucx2ScRipo0ed1FBatWkyt832jC4CReKstga6yIhYVwGu9LOBjuX9wzmRMeQdBJtzEA==",
+ "license": "Apache-2.0"
+ },
"node_modules/hono": {
"version": "4.12.19",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.19.tgz",
diff --git a/site/package.json b/site/package.json
index 99d4ee12..1c71243d 100644
--- a/site/package.json
+++ b/site/package.json
@@ -50,6 +50,7 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"defuddle": "^0.18.1",
+ "hls.js": "^1.6.16",
"linkedom": "^0.18.12",
"lucide-react": "^1.23.0",
"next": "16.2.6",
diff --git a/site/src/app/cut/s/[token]/SharedProjectView.tsx b/site/src/app/cut/s/[token]/SharedProjectView.tsx
index 29247473..a1847c04 100644
--- a/site/src/app/cut/s/[token]/SharedProjectView.tsx
+++ b/site/src/app/cut/s/[token]/SharedProjectView.tsx
@@ -6,6 +6,8 @@ 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 { MobileShare } from "@/cut/components/share/MobileShare";
+import { useIsNarrow } from "@/cut/hooks/useIsNarrow";
import { bindCutMode } from "@/cut/lib/backend";
import { bindSharedBackend } from "@/cut/lib/backend/shared";
import { holdThreadsInMemory } from "@/cut/lib/chatThreads";
@@ -22,7 +24,7 @@ import { authClient } from "@/lib/auth-client";
type Gate =
| { state: "loading" }
- | { state: "ready"; projectId: string }
+ | { state: "ready"; projectId: string; name: string; features: ShareFeatures }
| { state: "signin" }
| { state: "denied" }
| { state: "missing" };
@@ -31,6 +33,7 @@ export function SharedProject() {
const { token } = useParams<{ token: string }>();
const [gate, setGate] = useState<Gate>({ state: "loading" });
const { data: session } = authClient.useSession();
+ const narrow = useIsNarrow();
useEffect(() => {
let alive = true;
@@ -40,12 +43,21 @@ export function SharedProject() {
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 };
+ const meta = (await res.json()) as {
+ projectId: string;
+ name?: string;
+ features: ShareFeatures;
+ };
bindSharedBackend(token);
bindCutMode("shared");
holdThreadsInMemory();
useEditor.getState().setSharedView(meta.features);
- setGate({ state: "ready", projectId: meta.projectId });
+ setGate({
+ state: "ready",
+ projectId: meta.projectId,
+ name: meta.name ?? "Untitled",
+ features: meta.features,
+ });
})
.catch(() => alive && setGate({ state: "missing" }));
return () => {
@@ -53,11 +65,26 @@ export function SharedProject() {
};
}, [token]);
- if (gate.state === "ready") return <Editor projectId={gate.projectId} viewer />;
+ // A phone gets the player, not the editor. The choice is made here rather
+ // than in CSS because the editor starts a decoder per clip the moment it
+ // mounts, which is the cost a narrow screen cannot pay — so the render waits
+ // for `narrow` to be known rather than guessing and correcting.
+ if (gate.state === "ready" && narrow !== null) {
+ return narrow ? (
+ <MobileShare
+ token={token}
+ projectId={gate.projectId}
+ name={gate.name}
+ features={gate.features}
+ />
+ ) : (
+ <Editor projectId={gate.projectId} viewer />
+ );
+ }
- if (gate.state === "loading") {
+ if (gate.state === "loading" || gate.state === "ready") {
return (
- <div className="grid h-screen place-items-center text-muted-foreground">
+ <div className="grid h-[100dvh] place-items-center text-muted-foreground">
<Loader2 className="size-5 animate-spin" />
</div>
);
@@ -69,7 +96,7 @@ export function SharedProject() {
};
return (
- <div className="grid h-screen place-items-center">
+ <div className="grid h-[100dvh] 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" ? (
@@ -97,8 +124,11 @@ export function SharedProject() {
}
export function SharedProjectView() {
+ // Dynamic viewport units, not h-screen: on a phone the browser's own chrome
+ // slides in and out, and 100vh measures the tallest state — so the bottom of
+ // a fixed-height page sits under the toolbar for most of a visit.
return (
- <div className="h-screen bg-white font-system text-foreground antialiased">
+ <div className="h-[100dvh] bg-white font-system text-foreground antialiased">
<Suspense>
<SharedProject />
</Suspense>
diff --git a/site/src/cut/components/share/BottomSheet.tsx b/site/src/cut/components/share/BottomSheet.tsx
new file mode 100644
index 00000000..058eaaa8
--- /dev/null
+++ b/site/src/cut/components/share/BottomSheet.tsx
@@ -0,0 +1,71 @@
+"use client";
+
+import { useEffect } from "react";
+import { X } from "lucide-react";
+import { Button } from "@/components/ui/button";
+
+/**
+ * A panel that rises from the bottom of the screen.
+ *
+ * On a phone this is what the editor's side panels become. They are fixed-width
+ * columns in a row of columns, which is a shape a narrow screen has no room
+ * for; a sheet gives the same content the full width and leaves the video
+ * visible above it.
+ *
+ * Height is capped rather than fixed so a short panel stays short, and the body
+ * scrolls inside the sheet so the page behind it never does.
+ */
+export function BottomSheet({
+ title,
+ open,
+ onClose,
+ children,
+}: {
+ title: string;
+ open: boolean;
+ onClose: () => void;
+ children: React.ReactNode;
+}) {
+ useEffect(() => {
+ if (!open) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") onClose();
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [open, onClose]);
+
+ if (!open) return null;
+
+ return (
+ <div className="fixed inset-0 z-50 flex flex-col justify-end">
+ <button
+ type="button"
+ aria-label="Close"
+ className="absolute inset-0 bg-black/50"
+ onClick={onClose}
+ />
+ <div
+ role="dialog"
+ aria-modal="true"
+ aria-label={title}
+ className="relative flex max-h-[75dvh] flex-col rounded-t-2xl border-t border-border bg-card shadow-2xl"
+ >
+ {/* A grab handle reads as "this can be dismissed" on touch, where there
+ is no cursor to hint it. */}
+ <div className="flex justify-center pt-2 pb-1">
+ <div className="h-1 w-9 rounded-full bg-muted-foreground/30" />
+ </div>
+ <div className="flex items-center justify-between px-4 pb-2">
+ <h2 className="text-sm font-medium">{title}</h2>
+ <Button variant="ghost" size="icon-sm" aria-label="Close" onClick={onClose}>
+ <X />
+ </Button>
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 pb-[max(1rem,env(safe-area-inset-bottom))]">
+ {children}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/site/src/cut/components/share/HlsVideo.tsx b/site/src/cut/components/share/HlsVideo.tsx
new file mode 100644
index 00000000..e97316cc
--- /dev/null
+++ b/site/src/cut/components/share/HlsVideo.tsx
@@ -0,0 +1,130 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+
+/** How many fatal errors playback may recover from before it is treated as
+ * broken. A real network blip resolves in one or two; anything past this is a
+ * permanent failure wearing a transient error's clothes. */
+const MAX_RECOVERIES = 3;
+
+/**
+ * A `<video>` playing an HLS master playlist.
+ *
+ * Safari and iOS play HLS natively, so they get the URL directly and hls.js
+ * never loads — attaching it there would replace a well-tuned platform player
+ * with a worse one. Everywhere else (Chrome and Android have no native HLS)
+ * hls.js is imported on demand, so its weight lands only on the browsers that
+ * need it and never on the initial page.
+ */
+export function HlsVideo({
+ src,
+ poster,
+ className,
+ onError,
+ onPlaying,
+}: {
+ src: string;
+ poster?: string;
+ className?: string;
+ onError?: () => void;
+ /** Fires once playback is actually running, so a caller can avoid replacing
+ * a video someone is watching. */
+ onPlaying?: () => void;
+}) {
+ const ref = useRef<HTMLVideoElement>(null);
+ const [failed, setFailed] = useState(false);
+ // Held in a ref so the effect below does not depend on it. A caller passing an
+ // inline arrow — the normal way to write this — would otherwise hand over a
+ // new function every render and tear down and rebuild the player each time.
+ const onErrorRef = useRef(onError);
+ useEffect(() => {
+ onErrorRef.current = onError;
+ }, [onError]);
+
+ useEffect(() => {
+ const video = ref.current;
+ if (!video) return;
+ setFailed(false);
+ let live = true;
+
+ const giveUp = () => {
+ if (!live) return;
+ live = false;
+ setFailed(true);
+ onErrorRef.current?.();
+ };
+
+ // Native HLS. Checked before loading the library so Safari/iOS take this
+ // path — canPlayType answers for the platform player, not for hls.js.
+ if (video.canPlayType("application/vnd.apple.mpegurl")) {
+ // The platform player reports through the element, and this is the only
+ // channel it has: without it an expired token 403s every segment, the
+ // video stalls on a black frame, and nothing upstream ever learns that
+ // playback died.
+ video.addEventListener("error", giveUp);
+ video.src = src;
+ return () => {
+ live = false;
+ video.removeEventListener("error", giveUp);
+ };
+ }
+
+ let destroy: (() => void) | undefined;
+ void import("hls.js").then(({ default: Hls }) => {
+ if (!live || !ref.current) return;
+ if (!Hls.isSupported()) {
+ // Neither native nor MSE: nothing left to try.
+ giveUp();
+ return;
+ }
+ const hls = new Hls({
+ // The ladder's own rung choice is the point of streaming here; cap how
+ // far ahead it buffers so a phone on cellular does not pull minutes of
+ // a long cut it may never watch.
+ maxBufferLength: 30,
+ maxMaxBufferLength: 60,
+ });
+ // Recovery is bounded. Each kind of fatal error has a documented retry,
+ // so a dropped segment reconnects instead of ending playback — but an
+ // error that is permanent rather than transient (an expired token, a
+ // ladder swept out from under the viewer) repeats forever, and retrying
+ // it without a budget pins the phone in a request loop against the edge
+ // and never reaches the failure the viewer needs to see.
+ let recoveries = 0;
+ hls.on(Hls.Events.ERROR, (_e, data) => {
+ if (!data.fatal) return;
+ const recoverable =
+ data.type === Hls.ErrorTypes.NETWORK_ERROR || data.type === Hls.ErrorTypes.MEDIA_ERROR;
+ if (!recoverable || recoveries >= MAX_RECOVERIES) {
+ hls.destroy();
+ giveUp();
+ return;
+ }
+ recoveries++;
+ if (data.type === Hls.ErrorTypes.NETWORK_ERROR) hls.startLoad();
+ else hls.recoverMediaError();
+ });
+ hls.loadSource(src);
+ hls.attachMedia(ref.current);
+ destroy = () => hls.destroy();
+ });
+
+ return () => {
+ live = false;
+ destroy?.();
+ };
+ }, [src]);
+
+ return (
+ <video
+ ref={ref}
+ poster={poster}
+ controls
+ playsInline
+ preload="metadata"
+ className={className}
+ onPlaying={onPlaying}
+ aria-label={failed ? "Video unavailable" : undefined}
+ />
+ );
+}
diff --git a/site/src/cut/components/share/MobileShare.tsx b/site/src/cut/components/share/MobileShare.tsx
new file mode 100644
index 00000000..9ac88f8e
--- /dev/null
+++ b/site/src/cut/components/share/MobileShare.tsx
@@ -0,0 +1,456 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { Clapperboard, FileText, Images, Loader2, MessageSquare, Captions } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import type { ProjectDoc, ShareFeatures, StoredAsset } from "@/cut/lib/types";
+import { BottomSheet } from "./BottomSheet";
+import { HlsVideo } from "./HlsVideo";
+
+/**
+ * The share as a phone should see it: the cut playing as one video, with the
+ * shared surfaces reachable as sheets.
+ *
+ * It deliberately does not mount the editor. The editor plays a project by
+ * compositing it live — a video decoder per clip, painted to a canvas — which
+ * is the right design on a desktop and the wrong one on a phone, where the
+ * decoders alone would exhaust what the device will give a tab. Here the cut
+ * arrives already flattened, as an adaptive stream, so the phone decodes one
+ * video at the rung its network can carry.
+ */
+
+type StreamState =
+ | { state: "loading" }
+ | { state: "ready"; url: string }
+ /** No ladder to play yet, so the project's flattened proxy stands in: lower
+ * resolution and one fixed bitrate, but watchable. The poll keeps running
+ * underneath and swaps in the real stream the moment it exists. */
+ | { state: "proxy"; url: string }
+ | { state: "preparing" }
+ | { state: "failed" };
+
+type SheetId = "details" | "subtitles" | "media" | "chat";
+
+/** First gap before re-asking for the stream. The low rungs publish well before
+ * the last, so a viewer who opens a link mid-render usually waits seconds. */
+const STREAM_POLL_MS = 5000;
+/** Ceiling on the backoff, so a long render is still picked up promptly. */
+const MAX_STREAM_POLL_MS = 60_000;
+/** After this many tries the viewer keeps whatever they have. Roughly ten
+ * minutes of asking with the backoff above — past that, a ladder is not coming
+ * on this visit and a reload is the honest way to find out otherwise. */
+const MAX_STREAM_POLLS = 12;
+
+export function MobileShare({
+ token,
+ projectId,
+ name,
+ features,
+}: {
+ token: string;
+ projectId: string;
+ name: string;
+ features: ShareFeatures;
+}) {
+ const api = useCallback(
+ (path: string) => `/api/cut-shared/${encodeURIComponent(token)}${path}`,
+ [token]
+ );
+ const [stream, setStream] = useState<StreamState>({ state: "loading" });
+ const [doc, setDoc] = useState<ProjectDoc | null>(null);
+ const [sheet, setSheet] = useState<SheetId | null>(null);
+ const onStreamError = useCallback(() => setStream({ state: "failed" }), []);
+ // Whether playback has begun, so the poll knows not to replace a video the
+ // viewer is watching; a ref rather than state because changing it must not
+ // re-render the element it is guarding.
+ const startedRef = useRef(false);
+ // Whether the flattened proxy has already failed for this share, so the poll
+ // stops offering it again.
+ const proxyFailedRef = useRef(false);
+
+ // A ladder may still be rendering when a link is opened, and a share made
+ // before ladders existed has none until its owner next edits the project.
+ // Either way the viewer gets the flattened proxy rather than a spinner, and
+ // the poll swaps in the real stream when it lands.
+ //
+ // A server error takes the same path deliberately: a viewer is not the right
+ // place to report a broken deployment, and it is not hidden — the stream
+ // route logs the reason and a ladder render that cannot record itself fails
+ // its job outright. Only a 200 that carries no URL is terminal, since asking
+ // again could not answer differently.
+ //
+ // The poll backs off and eventually stops. A link whose project will never
+ // have a ladder would otherwise ask forever, and /stream is deliberately
+ // uncached — so a link a crowd opens would put a steady origin-plus-database
+ // request per viewer per tick behind it, which is the stampede the rest of
+ // the share design exists to avoid.
+ useEffect(() => {
+ let alive = true;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let attempt = 0;
+ const proxyUrl = api(`/projects/${projectId}/preview`);
+ // Fall back to the proxy, unless it has already failed for this share —
+ // re-entering it then would remount a broken <video>, which errors straight
+ // back to "preparing" and flickers between the two forever.
+ const fallBack = () => {
+ setStream(
+ proxyFailedRef.current ? { state: "preparing" } : { state: "proxy", url: proxyUrl }
+ );
+ again();
+ };
+ const again = () => {
+ if (attempt >= MAX_STREAM_POLLS) return;
+ const delay = Math.min(
+ MAX_STREAM_POLL_MS,
+ STREAM_POLL_MS * Math.pow(2, Math.max(0, attempt - 1))
+ );
+ attempt++;
+ timer = setTimeout(poll, delay);
+ };
+ const poll = async () => {
+ try {
+ const res = await fetch(api(`/projects/${projectId}/stream`));
+ if (!alive) return;
+ if (res.ok) {
+ const body = (await res.json()) as { url?: string };
+ if (body.url) {
+ // Never yank a video the viewer is already watching. Swapping the
+ // element mid-playback restarts the cut at zero with no
+ // explanation; the better stream is worth having on the next load,
+ // not at the cost of the sitting they are in.
+ if (startedRef.current) return;
+ return setStream({ state: "ready", url: body.url });
+ }
+ return setStream({ state: "failed" });
+ }
+ fallBack();
+ } catch {
+ if (!alive) return;
+ fallBack();
+ }
+ };
+ void poll();
+ return () => {
+ alive = false;
+ if (timer) clearTimeout(timer);
+ };
+ }, [api, projectId]);
+
+ // The doc backs every sheet. It is small next to the media it describes, and
+ // the server has already filtered it to what this share offers.
+ useEffect(() => {
+ let alive = true;
+ void fetch(api(`/projects/${projectId}`))
+ .then((r) => (r.ok ? (r.json() as Promise<ProjectDoc>) : null))
+ .then((d) => alive && setDoc(d))
+ .catch(() => {});
+ return () => {
+ alive = false;
+ };
+ }, [api, projectId]);
+
+ const sheets = useMemo(() => {
+ const out: { id: SheetId; label: string; icon: React.ReactNode }[] = [];
+ if (features.details) out.push({ id: "details", label: "Details", icon: <FileText /> });
+ if (features.subtitles) out.push({ id: "subtitles", label: "Transcript", icon: <Captions /> });
+ if (features.media || features.genai) {
+ out.push({ id: "media", label: "Media", icon: <Images /> });
+ }
+ if (features.chat) out.push({ id: "chat", label: "Chat", icon: <MessageSquare /> });
+ return out;
+ }, [features]);
+
+ return (
+ <div className="flex h-[100dvh] flex-col bg-background">
+ <header className="flex items-center gap-2 px-4 pt-[max(0.75rem,env(safe-area-inset-top))] pb-3">
+ <Clapperboard className="size-4 shrink-0 text-muted-foreground" />
+ <h1 className="truncate text-sm font-medium">{name}</h1>
+ </header>
+
+ <div className="flex min-h-0 flex-1 items-center justify-center bg-black">
+ {stream.state === "ready" ? (
+ <HlsVideo
+ src={stream.url}
+ className="max-h-full max-w-full"
+ onError={onStreamError}
+ onPlaying={() => (startedRef.current = true)}
+ />
+ ) : stream.state === "proxy" ? (
+ // The endpoint redirects to the media edge, so the element can hold
+ // the path directly. It 404s on its own when the project has no proxy
+ // — or when the share hides Subtitles and this render has them burned
+ // in — which is the case that shows "preparing".
+ <video
+ src={stream.url}
+ controls
+ playsInline
+ preload="metadata"
+ className="max-h-full max-w-full"
+ onPlaying={() => (startedRef.current = true)}
+ onError={() => {
+ proxyFailedRef.current = true;
+ setStream({ state: "preparing" });
+ }}
+ />
+ ) : (
+ <div className="flex flex-col items-center gap-3 px-8 text-center">
+ {stream.state === "failed" ? (
+ <p className="text-sm text-white/70">This project can&apos;t be played right now.</p>
+ ) : (
+ <>
+ <Loader2 className="size-5 animate-spin text-white/70" />
+ <p className="text-sm text-white/70">
+ {stream.state === "preparing"
+ ? "Getting this project ready to play…"
+ : "Loading…"}
+ </p>
+ </>
+ )}
+ </div>
+ )}
+ </div>
+
+ {sheets.length > 0 && (
+ <nav className="flex shrink-0 justify-around border-t border-border px-2 pt-2 pb-[max(0.5rem,env(safe-area-inset-bottom))]">
+ {sheets.map((s) => (
+ <Button
+ key={s.id}
+ variant="ghost"
+ className="h-auto flex-col gap-1 px-4 py-2 text-[11px] font-normal"
+ onClick={() => setSheet(s.id)}
+ >
+ {s.icon}
+ {s.label}
+ </Button>
+ ))}
+ </nav>
+ )}
+
+ <BottomSheet
+ title={sheets.find((s) => s.id === sheet)?.label ?? ""}
+ open={sheet !== null}
+ onClose={() => setSheet(null)}
+ >
+ {sheet === "details" && <DetailsSheet doc={doc} />}
+ {sheet === "subtitles" && <SubtitlesSheet doc={doc} />}
+ {sheet === "media" && <MediaSheet api={api} projectId={projectId} doc={doc} />}
+ {sheet === "chat" && <ChatSheet api={api} projectId={projectId} />}
+ </BottomSheet>
+ </div>
+ );
+}
+
+function Empty({ children }: { children: React.ReactNode }) {
+ return <p className="py-6 text-center text-sm text-muted-foreground">{children}</p>;
+}
+
+function DetailsSheet({ doc }: { doc: ProjectDoc | null }) {
+ if (!doc) return <Empty>Loading…</Empty>;
+ const notes = doc.notes;
+ const publish = doc.publish;
+ const links = notes?.links?.filter(Boolean) ?? [];
+ if (!notes?.text && !notes?.publishedAt && links.length === 0 && !publish?.caption) {
+ return <Empty>No details shared.</Empty>;
+ }
+ return (
+ <div className="flex flex-col gap-4 pb-2 text-sm">
+ {publish?.caption && (
+ <section className="flex flex-col gap-1">
+ <h3 className="text-xs font-medium text-muted-foreground">Caption</h3>
+ <p className="whitespace-pre-wrap">{publish.caption}</p>
+ </section>
+ )}
+ {notes?.publishedAt && (
+ <section className="flex flex-col gap-1">
+ <h3 className="text-xs font-medium text-muted-foreground">Published</h3>
+ <p>{notes.publishedAt}</p>
+ </section>
+ )}
+ {notes?.text && (
+ <section className="flex flex-col gap-1">
+ <h3 className="text-xs font-medium text-muted-foreground">Notes</h3>
+ <p className="whitespace-pre-wrap">{notes.text}</p>
+ </section>
+ )}
+ {links.length > 0 && (
+ <section className="flex flex-col gap-1">
+ <h3 className="text-xs font-medium text-muted-foreground">Links</h3>
+ {links.map((l) => (
+ <a
+ key={l}
+ href={l}
+ target="_blank"
+ rel="noreferrer noopener"
+ className="truncate text-primary underline"
+ >
+ {l}
+ </a>
+ ))}
+ </section>
+ )}
+ </div>
+ );
+}
+
+/** Seconds as m:ss — the transcript's only timestamp format, since a cut long
+ * enough to need hours still reads fine counting minutes. */
+function stamp(seconds: number): string {
+ const s = Math.max(0, Math.floor(seconds));
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
+}
+
+function SubtitlesSheet({ doc }: { doc: ProjectDoc | null }) {
+ if (!doc) return <Empty>Loading…</Empty>;
+ const cues = doc.subtitles?.cues ?? [];
+ if (cues.length === 0) return <Empty>No transcript shared.</Empty>;
+ return (
+ <ul className="flex flex-col gap-2 pb-2 text-sm">
+ {cues.map((cue, i) => (
+ <li key={i} className="flex gap-3">
+ <span className="shrink-0 pt-px font-mono text-xs text-muted-foreground tabular-nums">
+ {stamp(cue.start)}
+ </span>
+ <span>{cue.text}</span>
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+function MediaSheet({
+ api,
+ projectId,
+ doc,
+}: {
+ api: (path: string) => string;
+ projectId: string;
+ doc: ProjectDoc | null;
+}) {
+ const [urls, setUrls] = useState<Record<string, string>>({});
+ // Only assets a clip does not already use: the cut itself is the video above,
+ // so this lists what the share adds to it.
+ const assets = useMemo(() => {
+ if (!doc) return [];
+ const used = new Set([
+ ...(doc.clips ?? []).map((c) => c.assetId),
+ ...(doc.audioClips ?? []).map((c) => c.assetId),
+ ]);
+ return (doc.assets ?? []).filter((a) => !used.has(a.id) && a.type !== "audio");
+ }, [doc]);
+
+ useEffect(() => {
+ if (assets.length === 0) return;
+ let alive = true;
+ void fetch(api("/media/presign-get"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ items: assets.map((a) => ({ projectId, fileName: a.fileName })),
+ }),
+ })
+ .then((r) => (r.ok ? (r.json() as Promise<{ urls?: { fileName: string; url: string }[] }>) : null))
+ .then((body) => {
+ if (!alive || !body?.urls) return;
+ setUrls(Object.fromEntries(body.urls.map((u) => [u.fileName, u.url])));
+ })
+ .catch(() => {});
+ return () => {
+ alive = false;
+ };
+ }, [api, projectId, assets]);
+
+ if (!doc) return <Empty>Loading…</Empty>;
+ if (assets.length === 0) return <Empty>No media shared.</Empty>;
+ return (
+ <div className="grid grid-cols-3 gap-2 pb-2">
+ {assets.map((a) => (
+ <MediaTile key={a.id} asset={a} url={urls[a.fileName]} />
+ ))}
+ </div>
+ );
+}
+
+function MediaTile({ asset, url }: { asset: StoredAsset; url?: string }) {
+ return (
+ <figure className="flex flex-col gap-1">
+ <div className="aspect-square overflow-hidden rounded-md bg-muted">
+ {url ? (
+ asset.type === "image" ? (
+ <img src={url} alt={asset.name} loading="lazy" className="size-full object-cover" />
+ ) : (
+ // Metadata only, and a fragment so the poster frame is a real frame
+ // rather than black: a grid of autoloading videos would pull the
+ // whole panel's bytes on a phone.
+ <video
+ src={`${url}#t=0.1`}
+ preload="metadata"
+ muted
+ playsInline
+ className="size-full object-cover"
+ />
+ )
+ ) : null}
+ </div>
+ <figcaption className="truncate text-[11px] text-muted-foreground">{asset.name}</figcaption>
+ </figure>
+ );
+}
+
+/** A chat thread as the share stores it — the fields this read-only view needs
+ * out of the payload the editor round-trips. Messages are AI SDK `UIMessage`s,
+ * so their text lives in `parts` rather than on the message itself. */
+interface SharedThread {
+ id?: string;
+ title?: string;
+ messages?: { role?: string; parts?: { type?: string; text?: string }[] }[];
+}
+
+/** The readable text of one message: its text parts, joined. Tool calls and
+ * attachments are other part types and are left out — this is a transcript of
+ * the conversation, not a replay of the run. */
+function messageText(m: NonNullable<SharedThread["messages"]>[number]): string {
+ return (m.parts ?? [])
+ .map((p) => (p.type === "text" ? (p.text ?? "") : ""))
+ .join("")
+ .trim();
+}
+
+function ChatSheet({ api, projectId }: { api: (path: string) => string; projectId: string }) {
+ const [threads, setThreads] = useState<SharedThread[] | null>(null);
+ useEffect(() => {
+ let alive = true;
+ void fetch(api(`/projects/${projectId}/chats`))
+ .then((r) => (r.ok ? (r.json() as Promise<SharedThread[]>) : []))
+ .then((t) => alive && setThreads(Array.isArray(t) ? t : []))
+ .catch(() => alive && setThreads([]));
+ return () => {
+ alive = false;
+ };
+ }, [api, projectId]);
+
+ if (threads === null) return <Empty>Loading…</Empty>;
+ // Emptiness is decided on what will actually render, not on the message
+ // count: a thread of nothing but tool calls has messages and no readable
+ // text, and counting those would open a blank sheet instead of saying so.
+ const shown = threads
+ .flatMap((t) => t.messages ?? [])
+ .map((m) => ({ role: m.role, text: messageText(m) }))
+ .filter((m) => m.text.length > 0);
+ if (shown.length === 0) return <Empty>No chat shared.</Empty>;
+ return (
+ <ul className="flex flex-col gap-3 pb-2 text-sm">
+ {shown.map((m, i) => (
+ <li
+ key={i}
+ className={
+ m.role === "user"
+ ? "ml-6 rounded-lg bg-muted px-3 py-2 whitespace-pre-wrap"
+ : "mr-6 whitespace-pre-wrap"
+ }
+ >
+ {m.text}
+ </li>
+ ))}
+ </ul>
+ );
+}
diff --git a/site/src/cut/hooks/useIsNarrow.ts b/site/src/cut/hooks/useIsNarrow.ts
new file mode 100644
index 00000000..799274ca
--- /dev/null
+++ b/site/src/cut/hooks/useIsNarrow.ts
@@ -0,0 +1,33 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+/** Below this the editor cannot lay out: its shell alone floors at 900px of
+ * fixed chrome before the preview canvas gets a pixel. */
+export const NARROW_MAX_WIDTH = 900;
+
+/**
+ * Whether the viewport is too narrow for the editor — null until known.
+ *
+ * The site's styling rule is to branch on Tailwind's responsive variants rather
+ * than a media-query hook, and that holds wherever the question is how
+ * something looks. This one decides what MOUNTS: the editor's playback builds a
+ * video decoder per clip, so hiding it with a class would still start every
+ * decode on a phone that cannot afford one. That has to be a JS branch.
+ *
+ * The null state is why the return type is not a plain boolean. A hook that
+ * guessed false first would mount the editor for a frame on a phone, which is
+ * exactly the cost this exists to avoid — the guess is not free the way a
+ * mis-guessed CSS class would be. Callers wait it out instead.
+ */
+export function useIsNarrow(): boolean | null {
+ const [narrow, setNarrow] = useState<boolean | null>(null);
+ useEffect(() => {
+ const query = window.matchMedia(`(max-width: ${NARROW_MAX_WIDTH - 1}px)`);
+ const sync = () => setNarrow(query.matches);
+ sync();
+ query.addEventListener("change", sync);
+ return () => query.removeEventListener("change", sync);
+ }, []);
+ return narrow;
+}