The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Cinema Studio workspace UI: projects, scenes, feed, prompt bar, Director's Panel, Soul Cast/Location, AI Director
Claude8aba59ed6cde
diff --git a/src/app/(studio)/cinema/[id]/page.tsx b/src/app/(studio)/cinema/[id]/page.tsxnew file mode 100644index 00000000..0f0ee7f3--- /dev/null+++ b/src/app/(studio)/cinema/[id]/page.tsx@@ -0,0 +1,18 @@+import type { Metadata } from "next";+import { Suspense } from "react";+import { CinemaWorkspace } from "@/components/cinema/workspace";++export const metadata: Metadata = { title: "Cinema Studio" };++async function Workspace({ params }: { params: PageProps<"/cinema/[id]">["params"] }) {+ const { id } = await params;+ return <CinemaWorkspace id={id} />;+}++export default function Page({ params }: PageProps<"/cinema/[id]">) {+ return (+ <Suspense fallback={null}>+ <Workspace params={params} />+ </Suspense>+ );+}diff --git a/src/app/(studio)/cinema/page.tsx b/src/app/(studio)/cinema/page.tsxnew file mode 100644index 00000000..be156618--- /dev/null+++ b/src/app/(studio)/cinema/page.tsx@@ -0,0 +1,8 @@+import type { Metadata } from "next";+import { CinemaProjects } from "@/components/cinema/projects-view";++export const metadata: Metadata = { title: "Cinema Studio" };++export default function Page() {+ return <CinemaProjects />;+}diff --git a/src/app/api/cinema/projects/[id]/generate/route.ts b/src/app/api/cinema/projects/[id]/generate/route.tsindex 42be38d7..aa618ca6 100644--- a/src/app/api/cinema/projects/[id]/generate/route.ts+++ b/src/app/api/cinema/projects/[id]/generate/route.ts@@ -9,6 +9,6 @@ export async function POST(request: Request, ctx: RouteContext<"/api/cinema/projreturn handle(async () => {const { id } = await ctx.params;const b = await body(request, GenerateBody, "That request isn't valid");- return Response.json(generateInProject(id, b.input as Parameters<typeof generateInProject>[1], b.folderId ?? null), { status: 201 });+ return Response.json(generateInProject(id, b.input, b.folderId ?? null), { status: 201 });});}diff --git a/src/app/api/cinema/projects/[id]/items/[generationId]/retry/route.ts b/src/app/api/cinema/projects/[id]/items/[generationId]/retry/route.tsnew file mode 100644index 00000000..a32f81a8--- /dev/null+++ b/src/app/api/cinema/projects/[id]/items/[generationId]/retry/route.ts@@ -0,0 +1,10 @@+import { retryItem } from "@/server/cinema";+import { handle } from "@/server/cinema-schemas";++/** Run a failed take again (same request, same folder). */+export async function POST(_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items/[generationId]/retry">) {+ return handle(async () => {+ const { id, generationId } = await ctx.params;+ return Response.json({ items: retryItem(id, generationId) }, { status: 201 });+ });+}diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsxindex cc5364b1..06492aa2 100644--- a/src/components/app-sidebar.tsx+++ b/src/components/app-sidebar.tsx@@ -74,6 +74,7 @@ const NAV = [{label: "Studios",items: [+ { href: "/cinema", label: "Cinema Studio", icon: Clapperboard },{ href: "/lipsync", label: "Lipsync & avatars", icon: Mic2 },{ href: "/motion-control", label: "Motion control", icon: PersonStanding },{ href: "/video-edit", label: "Edit video", icon: Scissors },diff --git a/src/components/cinema/camera-moves.tsx b/src/components/cinema/camera-moves.tsxnew file mode 100644index 00000000..94e67145--- /dev/null+++ b/src/components/cinema/camera-moves.tsx@@ -0,0 +1,195 @@+"use client";++import { ArrowDownAZ, Check, Hash, ListOrdered, X } from "lucide-react";+import { useMemo, useState } from "react";+import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { CAMERA_MOVES, moveBySlug, openCameraRoute, type CameraMove } from "@/lib/catalog/cinema";+import type { Engine } from "@/lib/catalog/types";+import { cn } from "@/lib/utils";++/** How the open engine drives a move (shown as a small badge in the picker). */+function routeBadge(m: CameraMove, engine: Engine): string | null {+ if (engine !== "open") return null;+ const r = openCameraRoute(m.slug, true);+ return r.via === "lora" ? "LoRA" : r.via === "fun-camera" ? "Fun Camera" : null;+}++export function MoveList({+ engine,+ selected,+ onPick,+ defaultQuery,+ autoFocus,+}: {+ engine: Engine;+ selected: string[];+ onPick: (slug: string) => void;+ /** What was typed after "#" in the prompt (the list mounts fresh each time the picker opens). */+ defaultQuery?: string;+ autoFocus?: boolean;+}) {+ const [sort, setSort] = useState<"default" | "name">("default");+ const [query, setQuery] = useState(defaultQuery ?? "");+ const moves = useMemo(() => (sort === "name" ? [...CAMERA_MOVES].sort((a, b) => a.name.localeCompare(b.name)) : CAMERA_MOVES), [sort]);+ return (+ <Command loop className="bg-transparent" filter={(value, search) => (value.toLowerCase().includes(search.toLowerCase()) ? 1 : 0)}>+ <div className="flex items-center gap-1 pr-1">+ <div className="min-w-0 flex-1">+ <CommandInput placeholder="Search camera moves…" value={query} onValueChange={setQuery} autoFocus={autoFocus} />+ </div>+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ onClick={() => setSort((s) => (s === "default" ? "name" : "default"))}+ className="grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground"+ aria-label={sort === "default" ? "Sort by name" : "Default order"}+ >+ {sort === "default" ? <ArrowDownAZ className="size-4" /> : <ListOrdered className="size-4" />}+ </button>+ </TooltipTrigger>+ <TooltipContent>{sort === "default" ? "Sort: Name (A–Z)" : "Sort: Default"}</TooltipContent>+ </Tooltip>+ </div>+ <CommandList className="max-h-[min(52vh,360px)]">+ <CommandEmpty>No camera moves match your search</CommandEmpty>+ <CommandGroup>+ {moves.map((m) => {+ const badge = routeBadge(m, engine);+ const n = selected.indexOf(m.slug);+ return (+ <CommandItem key={m.slug} value={`${m.name} ${m.slug} ${m.hint}`} onSelect={() => onPick(m.slug)} className="group/move items-start gap-2.5 py-2">+ <span className={cn("mt-0.5 grid size-6 shrink-0 place-items-center rounded-md text-[11px] font-semibold", n >= 0 ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground")}>+ {n >= 0 ? n + 1 : <Hash className="size-3" />}+ </span>+ <span className="min-w-0 flex-1">+ <span className="flex items-center gap-1.5 text-[13px] font-medium">+ {m.name}+ {badge && <span className="rounded-full bg-brand-faint px-1.5 py-px text-[10px] font-medium text-brand-text">{badge}</span>}+ </span>+ <span className="block text-[12px] leading-snug text-muted-foreground">{m.hint}</span>+ </span>+ <span className="mt-0.5 shrink-0 text-[11px] font-medium text-brand-text opacity-0 group-data-[selected=true]/move:opacity-100">Use</span>+ </CommandItem>+ );+ })}+ </CommandGroup>+ </CommandList>+ </Command>+ );+}++/** "#" picker: opens from the # button or when "#" is typed in the prompt; several moves per shot, in order. */+export function MovePicker({+ open,+ onOpenChange,+ engine,+ selected,+ onPick,+ initialQuery,+}: {+ open: boolean;+ onOpenChange: (o: boolean) => void;+ engine: Engine;+ selected: string[];+ onPick: (slug: string) => void;+ initialQuery?: string;+}) {+ const trigger = (+ <Tooltip>+ <TooltipTrigger asChild>+ <PopoverTrigger asChild>+ <button+ type="button"+ className={cn(+ "grid size-8 shrink-0 place-items-center rounded-full transition-colors",+ selected.length ? "bg-brand-faint text-brand-text hover:bg-brand-faint-hover" : "bg-secondary text-secondary-foreground hover:bg-accent",+ )}+ aria-label="Add a camera move"+ >+ <Hash className="size-3.5" />+ </button>+ </PopoverTrigger>+ </TooltipTrigger>+ <TooltipContent>Direct a camera move · type #</TooltipContent>+ </Tooltip>+ );+ return (+ <Popover open={open} onOpenChange={onOpenChange}>+ {trigger}+ <PopoverContent className="w-[min(92vw,400px)] p-0" align="start" side="top" collisionPadding={12}>+ <div className="border-b px-3 pt-3 pb-2">+ <p className="text-[13px] font-medium">Direct a camera move</p>+ <p className="text-[12px] text-muted-foreground">Adds to the prompt box, or type # there. Several per shot; order matters.</p>+ </div>+ <MoveList+ engine={engine}+ selected={selected}+ defaultQuery={initialQuery}+ autoFocus+ onPick={(slug) => {+ onPick(slug);+ onOpenChange(false);+ }}+ />+ </PopoverContent>+ </Popover>+ );+}++/** The shot's moves as ordered tags: drag or Alt+←/→ to reorder, × or Backspace to remove. */+export function MoveChips({ moves, onChange }: { moves: string[]; onChange: (m: string[]) => void }) {+ const [drag, setDrag] = useState<number | null>(null);+ if (!moves.length) return null;+ const move = (from: number, to: number) => {+ if (to < 0 || to >= moves.length || from === to) return;+ const next = [...moves];+ const [m] = next.splice(from, 1);+ next.splice(to, 0, m);+ onChange(next);+ };+ return (+ <div className="flex flex-wrap items-center gap-1.5 px-2 pb-1.5" role="list" aria-label="Camera moves, in order">+ {moves.map((slug, i) => {+ const m = moveBySlug(slug);+ return (+ <span+ key={`${slug}-${i}`}+ role="listitem"+ draggable+ onDragStart={(e) => {+ setDrag(i);+ e.dataTransfer.effectAllowed = "move";+ }}+ onDragOver={(e) => e.preventDefault()}+ onDrop={(e) => {+ e.preventDefault();+ if (drag !== null) move(drag, i);+ setDrag(null);+ }}+ tabIndex={0}+ onKeyDown={(e) => {+ if (e.altKey && e.key === "ArrowLeft") move(i, i - 1);+ else if (e.altKey && e.key === "ArrowRight") move(i, i + 1);+ else if (e.key === "Backspace" || e.key === "Delete") onChange(moves.filter((_, j) => j !== i));+ }}+ title={m?.hint}+ className="inline-flex h-7 cursor-grab items-center gap-1 rounded-full bg-brand-faint pr-1 pl-1.5 text-[12px] font-medium text-brand-text outline-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"+ >+ <span className="grid size-4 place-items-center rounded-full bg-primary text-[10px] text-primary-foreground">{i + 1}</span>#{m?.name ?? slug}+ <button type="button" onClick={() => onChange(moves.filter((_, j) => j !== i))} className="grid size-5 place-items-center rounded-full hover:bg-brand-faint-hover" aria-label={`Remove ${m?.name ?? slug}`}>+ <X className="size-3" />+ </button>+ </span>+ );+ })}+ {moves.length > 1 && (+ <span className="inline-flex items-center gap-1 text-[11px] text-muted-foreground">+ <Check className="size-3" /> runs in this order+ </span>+ )}+ </div>+ );+}diff --git a/src/components/cinema/cinema-feed.tsx b/src/components/cinema/cinema-feed.tsxnew file mode 100644index 00000000..efb2903e--- /dev/null+++ b/src/components/cinema/cinema-feed.tsx@@ -0,0 +1,687 @@+"use client";++import {+ CalendarDays,+ Check,+ Clapperboard,+ Copy,+ Download,+ FastForward,+ FolderInput,+ Grid3x3,+ Heart,+ ImagePlus,+ LayoutGrid,+ List,+ MapPin,+ MoreHorizontal,+ RotateCcw,+ Rows3,+ SlidersHorizontal,+ Trash2,+ UserRoundPlus,+ X,+} from "lucide-react";+import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";+import { toast } from "sonner";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { Checkbox } from "@/components/ui/checkbox";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Switch } from "@/components/ui/switch";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { FailedTile, MediaThumb, PendingTile, downloadName, tileRatio } from "@/components/studio/feed";+import { Viewer } from "@/components/studio/viewer";+import { getModel } from "@/lib/catalog";+import type { CinemaFolder } from "@/lib/catalog/cinema";+import type { Generation, OutputFile } from "@/lib/catalog/types";+import { formatCost, timeAgo } from "@/lib/format";+import { cn } from "@/lib/utils";+import { MoveToItems } from "./folder-sidebar";+import { useItemActions, type CinemaGeneration } from "./hooks";++type Layout = "square" | "masonry" | "list";+type TypeFilter = "all" | "image" | "video" | "audio";+type DateFilter = "all" | "today" | "7d" | "30d";+type StatusFilter = "all" | "liked" | "rendering" | "failed";++interface Prefs {+ layout: Layout;+ split: boolean;+ fit: boolean;+ type: TypeFilter;+ date: DateFilter;+ status: StatusFilter;+ hideFailed: boolean;+}++const DEFAULT_PREFS: Prefs = { layout: "square", split: true, fit: false, type: "all", date: "all", status: "all", hideFailed: false };+const PREFS_KEY = "fuobe.cinema.feed";+const prefListeners = new Set<() => void>();+let prefCache: { raw: string | null; value: Prefs } | null = null;++function readPrefs(): Prefs {+ try {+ const raw = localStorage.getItem(PREFS_KEY);+ if (prefCache?.raw === raw) return prefCache.value;+ const value = { ...DEFAULT_PREFS, ...(raw ? (JSON.parse(raw) as Partial<Prefs>) : {}) };+ prefCache = { raw, value };+ return value;+ } catch {+ return DEFAULT_PREFS;+ }+}++/** Feed layout and filters, remembered per viewer. */+function usePrefs(): [Prefs, (p: Partial<Prefs>) => void] {+ const prefs = useSyncExternalStore(+ (cb) => {+ prefListeners.add(cb);+ return () => prefListeners.delete(cb);+ },+ readPrefs,+ () => DEFAULT_PREFS,+ );+ const set = useCallback((p: Partial<Prefs>) => {+ try {+ localStorage.setItem(PREFS_KEY, JSON.stringify({ ...readPrefs(), ...p }));+ } catch {}+ prefListeners.forEach((l) => l());+ }, []);+ return [prefs, set];+}++/** One tile: a pending/failed take, one output of a take, or a tile cut from a grid sheet. */+interface Unit {+ key: string;+ g: CinemaGeneration;+ output?: OutputFile;+ index: number;+ tile?: { row: number; col: number };+}++const active = (g: Generation) => g.status === "queued" || g.status === "running";++function units(items: CinemaGeneration[]): Unit[] {+ const out: Unit[] = [];+ for (const g of items) {+ if (g.status !== "succeeded") {+ out.push({ key: g.id, g, index: 0 });+ continue;+ }+ // Open-source grids return the sheet first, then its tiles.+ const sheetTiles = g.feature === "cinema-grid" && g.outputs.length > 1;+ const outputs = sheetTiles ? g.outputs.slice(0, 1) : g.outputs;+ outputs.forEach((o, i) => out.push({ key: `${g.id}:${i}`, g, output: o, index: i }));+ const tiles = g.tiles?.length ? g.tiles.map((t) => ({ url: t.url, row: t.row, col: t.col })) : sheetTiles ? g.outputs.slice(1).map((o, i) => ({ url: o.url, row: -1, col: i })) : [];+ tiles.forEach((t, i) => out.push({ key: `${g.id}:t${i}`, g, output: { url: t.url, kind: "image" }, index: i, tile: { row: t.row, col: t.col } }));+ }+ return out;+}++function dayLabel(ts: number): string {+ const d = new Date(ts);+ const today = new Date();+ const start = (x: Date) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();+ const diff = Math.round((start(today) - start(d)) / 86_400_000);+ if (diff === 0) return "Today";+ if (diff === 1) return "Yesterday";+ return d.toLocaleDateString(undefined, { weekday: diff < 7 ? "long" : undefined, month: "short", day: "numeric", year: d.getFullYear() === today.getFullYear() ? undefined : "numeric" });+}++const promptOf = (g: CinemaGeneration) => g.take?.prompt?.trim() || g.request.prompt?.trim() || g.prompt || "Untitled";++const STEP_HINT: Record<string, string> = { "cinema-cast": "Cast", "cinema-location": "Location", "cinema-grid": "Grid" };++function Badge({ children, className }: { children: React.ReactNode; className?: string }) {+ return <span className={cn("inline-flex h-5 items-center rounded-full bg-black/50 px-1.5 text-[10.5px] font-medium text-white backdrop-blur", className)}>{children}</span>;+}++export interface FeedHandlers {+ onLoad: (g: CinemaGeneration) => void;+ onUseTake: (g: CinemaGeneration, o: OutputFile) => void;+ onAnimate: (url: string) => void;+ onReference: (url: string, kind: OutputFile["kind"]) => void;+ onSaveElement: (g: CinemaGeneration, url: string, kind: "character" | "location") => void;+}++function TileMenu({ u, folders, projectId, handlers, onDelete }: { u: Unit; folders: CinemaFolder[]; projectId: string; handlers: FeedHandlers; onDelete: (ids: string[]) => void }) {+ const actions = useItemActions(projectId);+ const o = u.output;+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ onClick={(e) => e.stopPropagation()}+ className="grid size-7 place-items-center rounded-lg text-white/90 transition-colors hover:bg-white/20 hover:text-white"+ aria-label="More actions"+ >+ <MoreHorizontal className="size-4" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>+ <DropdownMenuItem onClick={() => handlers.onLoad(u.g)}>+ <RotateCcw /> Load into prompt bar+ </DropdownMenuItem>+ {o?.kind === "image" && (+ <>+ <DropdownMenuItem onClick={() => handlers.onAnimate(o.url)}>+ <Clapperboard /> Animate (start frame)+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => handlers.onReference(o.url, "image")}>+ <ImagePlus /> Use as reference+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => handlers.onSaveElement(u.g, o.url, "character")}>+ <UserRoundPlus /> Save as character+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => handlers.onSaveElement(u.g, o.url, "location")}>+ <MapPin /> Save as location+ </DropdownMenuItem>+ </>+ )}+ {o?.kind === "video" && (+ <>+ <DropdownMenuItem onClick={() => handlers.onUseTake(u.g, o)}>+ <FastForward /> Extend or edit this take+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => handlers.onReference(o.url, "video")}>+ <ImagePlus /> Use as reference clip+ </DropdownMenuItem>+ </>+ )}+ {o && (+ <DropdownMenuItem asChild>+ <a href={`${o.url}?download=${encodeURIComponent(downloadName(u.g, o, u.index))}`}>+ <Download /> Download+ </a>+ </DropdownMenuItem>+ )}+ <DropdownMenuItem onClick={() => void actions.favorite([u.g.id], !u.g.favorite)}>+ <Heart /> {u.g.favorite ? "Unlike" : "Like"}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => {+ void navigator.clipboard.writeText(u.g.prompt ?? "");+ toast("Prompt copied");+ }}+ >+ <Copy /> Copy prompt+ </DropdownMenuItem>+ {!u.tile && (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <FolderInput /> Move to+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-72 overflow-y-auto">+ <MoveToItems folders={folders} onMove={(f) => void actions.move([u.g.id], f).then(() => toast("Moved", { duration: 1200 }))} />+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ )}+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" onClick={() => onDelete([u.g.id])}>+ <Trash2 /> Delete take+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++function TileView({+ u,+ layout,+ fit,+ selected,+ selecting,+ onToggle,+ onOpen,+ projectId,+ folders,+ handlers,+ onDelete,+ dragIds,+}: {+ u: Unit;+ layout: Layout;+ fit: boolean;+ selected: boolean;+ selecting: boolean;+ onToggle: (shift: boolean) => void;+ onOpen: () => void;+ projectId: string;+ folders: CinemaFolder[];+ handlers: FeedHandlers;+ onDelete: (ids: string[]) => void;+ dragIds: () => string[];+}) {+ const actions = useItemActions(projectId);+ const g = u.g;+ const ratio = u.tile ? 1 : tileRatio(g);+ const aspect = layout === "square" ? 1 : u.output?.kind === "audio" ? 1.6 : ratio;+ const step = u.tile ? `Tile ${u.tile.row >= 0 ? `${u.tile.row + 1}·${u.tile.col + 1}` : u.tile.col + 1}` : (g.request.step?.label ?? STEP_HINT[g.feature]);+ const media =+ active(g) ? (+ <PendingTile g={g} ratio={aspect} />+ ) : g.status !== "succeeded" ? (+ <FailedTile g={g} ratio={aspect} onRetry={() => void actions.retry(g.id).catch((e) => toast.error((e as Error).message))} />+ ) : (+ <div className={cn("size-full", fit && "bg-muted")}>+ <MediaThumb output={u.output!} className={fit ? "object-contain" : undefined} />+ </div>+ );+ const clickable = g.status === "succeeded";+ const checkbox = (+ <span+ className={cn(+ "absolute top-2 left-2 z-10 transition-opacity",+ selected || selecting ? "opacity-100" : "opacity-100 sm:opacity-0 sm:group-hover/tile:opacity-100 sm:group-focus-within/tile:opacity-100",+ )}+ onClick={(e) => {+ e.stopPropagation();+ onToggle(e.shiftKey);+ }}+ >+ <Checkbox checked={selected} aria-label={selected ? "Unselect" : "Select"} className="size-5 border-white/80 bg-black/30 shadow-soft data-[state=checked]:border-primary" />+ </span>+ );+ if (layout === "list") {+ return (+ <div+ className={cn("group/tile relative flex items-center gap-3 rounded-xl border p-2 transition-colors", selected ? "border-primary bg-brand-faint" : "hover:bg-accent")}+ draggable={!u.tile}+ onDragStart={(e) => e.dataTransfer.setData("application/x-cinema-takes", JSON.stringify(dragIds()))}+ >+ <Checkbox checked={selected} onCheckedChange={() => onToggle(false)} aria-label={selected ? "Unselect" : "Select"} className="ml-1 size-4" />+ <button+ type="button"+ onClick={(e) => (selecting || e.metaKey || e.ctrlKey ? onToggle(e.shiftKey) : clickable && onOpen())}+ className="relative aspect-video w-28 shrink-0 overflow-hidden rounded-lg bg-muted sm:w-36"+ aria-label="Open"+ >+ {g.status === "succeeded" ? <MediaThumb output={u.output!} className={fit ? "object-contain" : undefined} /> : <span className="absolute inset-0 grid place-items-center text-[11px] text-muted-foreground">{active(g) ? "Rendering…" : "Failed"}</span>}+ </button>+ <div className="min-w-0 flex-1">+ <p className="line-clamp-2 text-[13.5px] leading-snug">{promptOf(g)}</p>+ <p className="mt-0.5 flex flex-wrap gap-x-1.5 text-[11.5px] text-muted-foreground">+ {[step, getModel(g.modelId)?.name ?? g.modelId, g.provider === "mock" ? "Demo" : g.engine === "open" ? "Open source" : "Cloud", timeAgo(g.createdAt), g.costUsd ? formatCost(g.costUsd) : null, g.status === "failed" ? g.error : null]+ .filter(Boolean)+ .map((m, i) => (+ <span key={i} className={cn(i > 0 && "before:mr-1.5 before:content-['·']", m === g.error && "text-destructive")}>+ {m}+ </span>+ ))}+ </p>+ </div>+ {g.favorite && <Heart className="size-4 shrink-0 fill-highlight text-highlight" />}+ <div className="shrink-0 rounded-lg bg-foreground/70 [&_button]:text-white">+ <TileMenu u={u} folders={folders} projectId={projectId} handlers={handlers} onDelete={onDelete} />+ </div>+ </div>+ );+ }+ return (+ <div+ role={clickable ? "button" : undefined}+ tabIndex={clickable ? 0 : undefined}+ draggable={!u.tile}+ onDragStart={(e) => e.dataTransfer.setData("application/x-cinema-takes", JSON.stringify(dragIds()))}+ onClick={(e) => {+ if (selecting || e.metaKey || e.ctrlKey || e.shiftKey) onToggle(e.shiftKey);+ else if (clickable) onOpen();+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter" && clickable) onOpen();+ if (e.key === " ") {+ e.preventDefault();+ onToggle(false);+ }+ }}+ className={cn(+ "group/tile relative overflow-hidden rounded-xl bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring",+ layout === "masonry" && "mb-3 break-inside-avoid",+ clickable && "cursor-zoom-in",+ selected && "ring-2 ring-primary ring-offset-2 ring-offset-background",+ )}+ style={{ aspectRatio: aspect }}+ >+ {media}+ {checkbox}+ <div className="pointer-events-none absolute top-2 right-2 flex items-center gap-1">+ {g.favorite && <Heart className="size-4 fill-highlight text-highlight drop-shadow" />}+ </div>+ {g.status === "succeeded" && (+ <div className="absolute inset-x-0 bottom-0 flex items-end justify-between gap-1 bg-gradient-to-t from-black/65 to-transparent p-2 pt-8 opacity-100 transition-opacity sm:opacity-0 sm:group-focus-within/tile:opacity-100 sm:group-hover/tile:opacity-100">+ <div className="flex min-w-0 flex-wrap gap-1">+ {step && <Badge>{step}</Badge>}+ {u.output?.kind === "video" && g.request.params?.duration ? <Badge>{g.request.params.duration}s</Badge> : null}+ </div>+ <div className="flex shrink-0 items-center gap-0.5" onClick={(e) => e.stopPropagation()}>+ {u.output?.kind === "video" && (+ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" onClick={() => handlers.onUseTake(g, u.output!)} className="grid size-7 place-items-center rounded-lg text-white/90 hover:bg-white/20 hover:text-white" aria-label="Extend or edit this take">+ <FastForward className="size-4" />+ </button>+ </TooltipTrigger>+ <TooltipContent>Extend · Prequel · Edit</TooltipContent>+ </Tooltip>+ )}+ {u.output?.kind === "image" && (+ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" onClick={() => handlers.onAnimate(u.output!.url)} className="grid size-7 place-items-center rounded-lg text-white/90 hover:bg-white/20 hover:text-white" aria-label="Animate">+ <Clapperboard className="size-4" />+ </button>+ </TooltipTrigger>+ <TooltipContent>Animate: use as the start frame</TooltipContent>+ </Tooltip>+ )}+ <TileMenu u={u} folders={folders} projectId={projectId} handlers={handlers} onDelete={onDelete} />+ </div>+ </div>+ )}+ </div>+ );+}++function FilterChips({ prefs, setPrefs, nested, onNested }: { prefs: Prefs; setPrefs: (p: Partial<Prefs>) => void; nested?: boolean; onNested?: (v: boolean) => void }) {+ const n = [prefs.type !== "all", prefs.date !== "all", prefs.status !== "all", prefs.hideFailed].filter(Boolean).length;+ const group = <T extends string>(label: string, value: T, options: [T, string][], on: (v: T) => void) => (+ <div className="space-y-1">+ <p className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">{label}</p>+ <div className="flex flex-wrap gap-1">+ {options.map(([id, name]) => (+ <button key={id} type="button" onClick={() => on(id)} className={cn("h-7 rounded-full px-2.5 text-[12px] font-medium", value === id ? "bg-primary text-primary-foreground" : "bg-secondary hover:bg-accent")}>+ {name}+ </button>+ ))}+ </div>+ </div>+ );+ return (+ <Popover>+ <PopoverTrigger asChild>+ <button type="button" className={cn("inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-[12.5px] font-medium", n ? "bg-brand-faint text-brand-text" : "bg-secondary hover:bg-accent")} aria-label="Filters">+ <SlidersHorizontal className="size-3.5" /> Filters{n ? ` · ${n}` : ""}+ </button>+ </PopoverTrigger>+ <PopoverContent align="end" className="w-[min(92vw,320px)] space-y-3 p-3" collisionPadding={12}>+ {group("Type", prefs.type, [["all", "All types"], ["image", "Image"], ["video", "Video"], ["audio", "Audio"]], (type) => setPrefs({ type }))}+ {group("Date", prefs.date, [["all", "All period"], ["today", "Today"], ["7d", "Last 7 days"], ["30d", "Last 30 days"]], (date) => setPrefs({ date }))}+ {group("Status", prefs.status, [["all", "Any"], ["liked", "Liked"], ["rendering", "Rendering"], ["failed", "Failed"]], (status) => setPrefs({ status }))}+ <label className="flex items-center justify-between text-[13px]">+ Hide failed <Switch checked={prefs.hideFailed} onCheckedChange={(hideFailed) => setPrefs({ hideFailed })} />+ </label>+ {onNested && (+ <label className="flex items-center justify-between gap-3 text-[13px]">+ Include generations from nested folders <Switch checked={!!nested} onCheckedChange={onNested} />+ </label>+ )}+ {n > 0 && (+ <button type="button" onClick={() => setPrefs({ type: "all", date: "all", status: "all", hideFailed: false })} className="text-[12px] font-medium text-brand-text hover:underline">+ Clear filters+ </button>+ )}+ </PopoverContent>+ </Popover>+ );+}++export function CinemaFeed({+ projectId,+ items,+ folders,+ title,+ empty,+ handlers,+ nested,+ onNested,+ toolbarExtra,+}: {+ projectId: string;+ items: CinemaGeneration[];+ folders: CinemaFolder[];+ title: React.ReactNode;+ empty: React.ReactNode;+ handlers: FeedHandlers;+ nested?: boolean;+ onNested?: (v: boolean) => void;+ toolbarExtra?: React.ReactNode;+}) {+ const [prefs, setPrefs] = usePrefs();+ const actions = useItemActions(projectId);+ const [selected, setSelected] = useState<Set<string>>(new Set());+ const [anchor, setAnchor] = useState<string | null>(null);+ const [open, setOpen] = useState<string | null>(null);+ const [confirm, setConfirm] = useState<string[] | null>(null);+ // Date filters count from when the feed opened.+ const [now] = useState(() => Date.now());++ const filtered = useMemo(() => {+ const age = { today: 86_400_000, "7d": 7 * 86_400_000, "30d": 30 * 86_400_000 } as const;+ return items.filter((g) => {+ if (prefs.type !== "all" && !(g.outputs.some((o) => o.kind === prefs.type) || (g.status !== "succeeded" && g.kind === prefs.type))) return false;+ if (prefs.date === "today" && dayLabel(g.createdAt) !== "Today") return false;+ if (prefs.date !== "all" && prefs.date !== "today" && now - g.createdAt > age[prefs.date]) return false;+ if (prefs.status === "liked" && !g.favorite) return false;+ if (prefs.status === "rendering" && !active(g)) return false;+ if (prefs.status === "failed" && (g.status !== "failed" && g.status !== "canceled")) return false;+ if (prefs.hideFailed && (g.status === "failed" || g.status === "canceled")) return false;+ return true;+ });+ }, [items, prefs, now]);+ const all = useMemo(() => units(filtered), [filtered]);+ const viewable = all.filter((u) => u.g.status === "succeeded");+ const pos = open ? viewable.findIndex((u) => u.key === open) : -1;+ const ids = useMemo(() => [...new Set(all.map((u) => u.g.id))], [all]);+ const live = [...selected].filter((id) => ids.includes(id));+ const selecting = live.length > 0;++ // Esc unselects (Higgsfield: "Unselect All (Esc)").+ useEffect(() => {+ if (!selecting) return;+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape" && !(e.target as HTMLElement)?.closest("input,textarea,[role=dialog]")) setSelected(new Set());+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [selecting]);++ const toggle = (id: string, shift: boolean) => {+ setSelected((s) => {+ const next = new Set(s);+ if (shift && anchor) {+ const a = ids.indexOf(anchor);+ const b = ids.indexOf(id);+ for (const x of ids.slice(Math.min(a, b), Math.max(a, b) + 1)) next.add(x);+ } else if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ setAnchor(id);+ };++ const groups = useMemo(() => {+ if (!prefs.split) return [{ label: "", units: all }];+ const map = new Map<string, Unit[]>();+ for (const u of all) {+ const k = dayLabel(u.g.createdAt);+ map.set(k, [...(map.get(k) ?? []), u]);+ }+ return [...map.entries()].map(([label, us]) => ({ label, units: us }));+ }, [all, prefs.split]);++ const layoutCls = prefs.layout === "square" ? "grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4 2xl:grid-cols-5" : prefs.layout === "masonry" ? "columns-2 gap-3 sm:columns-3 lg:columns-4 2xl:columns-5" : "space-y-2";+ const del = async (list: string[]) => {+ await actions.remove(list);+ setSelected(new Set());+ toast(list.length > 1 ? `${list.length} takes deleted` : "Deleted", { duration: 1500 });+ };++ return (+ <div className="space-y-4">+ <div className="flex flex-wrap items-center gap-2">+ <div className="min-w-0 flex-1">{title}</div>+ {toolbarExtra}+ <div className="inline-flex h-8 rounded-full bg-muted p-0.5" role="radiogroup" aria-label="Layout">+ {(+ [+ ["square", LayoutGrid, "Square"],+ ["masonry", Rows3, "Masonry"],+ ["list", List, "List"],+ ] as const+ ).map(([id, Icon, label]) => (+ <Tooltip key={id}>+ <TooltipTrigger asChild>+ <button+ type="button"+ role="radio"+ aria-checked={prefs.layout === id}+ aria-label={label}+ onClick={() => setPrefs({ layout: id })}+ className={cn("grid w-8 place-items-center rounded-full", prefs.layout === id ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground")}+ >+ <Icon className="size-3.5" />+ </button>+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ ))}+ </div>+ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" aria-pressed={prefs.split} onClick={() => setPrefs({ split: !prefs.split })} className={cn("grid size-8 place-items-center rounded-full", prefs.split ? "bg-brand-faint text-brand-text" : "bg-secondary hover:bg-accent")} aria-label="Split by date">+ <CalendarDays className="size-3.5" />+ </button>+ </TooltipTrigger>+ <TooltipContent>Split by date</TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" aria-pressed={prefs.fit} onClick={() => setPrefs({ fit: !prefs.fit })} className={cn("inline-flex h-8 items-center rounded-full px-2.5 text-[12px] font-medium", prefs.fit ? "bg-brand-faint text-brand-text" : "bg-secondary hover:bg-accent")} aria-label={prefs.fit ? "Fit previews" : "Fill previews"}>+ <Grid3x3 className="mr-1 size-3.5" />+ {prefs.fit ? "Fit" : "Fill"}+ </button>+ </TooltipTrigger>+ <TooltipContent>{prefs.fit ? "Fit previews (whole frame)" : "Fill previews (cropped)"}</TooltipContent>+ </Tooltip>+ <FilterChips prefs={prefs} setPrefs={setPrefs} nested={nested} onNested={onNested} />+ </div>++ {selecting && (+ <div className="sticky top-2 z-20 flex flex-wrap items-center gap-1.5 rounded-full border bg-background/95 py-1 pr-1 pl-3 shadow-strong backdrop-blur animate-pop-in">+ <span className="text-[13px] font-medium">{live.length} selected</span>+ <button type="button" onClick={() => setSelected(new Set())} className="inline-flex h-7 items-center gap-1 rounded-full px-2 text-[12px] text-muted-foreground hover:bg-accent hover:text-foreground">+ <X className="size-3.5" /> Unselect all <kbd className="ml-0.5 font-mono text-[10px]">Esc</kbd>+ </button>+ <span className="flex-1" />+ <button type="button" onClick={() => void actions.favorite(live, !items.filter((g) => live.includes(g.id)).every((g) => g.favorite))} className="inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-[12.5px] font-medium hover:bg-accent">+ <Heart className="size-3.5" /> {items.filter((g) => live.includes(g.id)).every((g) => g.favorite) ? "Unlike" : "Like"}+ </button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button type="button" className="inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-[12.5px] font-medium hover:bg-accent">+ <FolderInput className="size-3.5" /> Move to+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="max-h-72 overflow-y-auto">+ <MoveToItems+ folders={folders}+ onMove={(f) =>+ void actions.move(live, f).then(() => {+ toast(`Moved ${live.length} take${live.length > 1 ? "s" : ""}`, { duration: 1500 });+ setSelected(new Set());+ })+ }+ />+ </DropdownMenuContent>+ </DropdownMenu>+ <button type="button" onClick={() => setConfirm(live)} className="inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-[12.5px] font-medium text-destructive hover:bg-destructive/10">+ <Trash2 className="size-3.5" /> Delete+ </button>+ </div>+ )}++ {!all.length ? (+ items.length ? (+ <p className="py-16 text-center text-[13px] text-muted-foreground">Nothing matches these filters.</p>+ ) : (+ empty+ )+ ) : (+ <div className="space-y-6">+ {groups.map((grp) => (+ <section key={grp.label || "all"} className="space-y-2.5">+ {grp.label && (+ <h3 className="flex items-center gap-2 text-[12px] font-medium text-muted-foreground">+ {grp.label}+ <span className="font-mono text-[11px] text-subtle-foreground">{grp.units.length}</span>+ </h3>+ )}+ <div className={layoutCls}>+ {grp.units.map((u) => (+ <TileView+ key={u.key}+ u={u}+ layout={prefs.layout}+ fit={prefs.fit}+ selected={selected.has(u.g.id)}+ selecting={selecting}+ onToggle={(shift) => toggle(u.g.id, shift)}+ onOpen={() => setOpen(u.key)}+ projectId={projectId}+ folders={folders}+ handlers={handlers}+ onDelete={(list) => setConfirm(list)}+ dragIds={() => (selected.has(u.g.id) ? live : [u.g.id])}+ />+ ))}+ </div>+ </section>+ ))}+ </div>+ )}++ {pos >= 0 && (+ <Viewer+ generation={{ ...viewable[pos].g, outputs: [viewable[pos].output!] }}+ index={0}+ onClose={() => setOpen(null)}+ onPrev={pos > 0 ? () => setOpen(viewable[pos - 1].key) : undefined}+ onNext={pos < viewable.length - 1 ? () => setOpen(viewable[pos + 1].key) : undefined}+ onReuse={(g) => handlers.onLoad(g as CinemaGeneration)}+ />+ )}++ <AlertDialog open={!!confirm} onOpenChange={(o) => !o && setConfirm(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{confirm && confirm.length > 1 ? `Delete ${confirm.length} takes?` : "Delete this take?"}</AlertDialogTitle>+ <AlertDialogDescription>They'll be removed from this project and your library, and can't be recovered.</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() => {+ if (confirm) void del(confirm);+ setConfirm(null);+ }}+ >+ <Check /> Delete+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );+}diff --git a/src/components/cinema/director-panel.tsx b/src/components/cinema/director-panel.tsxnew file mode 100644index 00000000..6843473b--- /dev/null+++ b/src/components/cinema/director-panel.tsx@@ -0,0 +1,623 @@+"use client";++import { ArrowDownAZ, Camera, Check, ChevronLeft, ChevronRight, Film, ListOrdered, Palette, Plus, Smile, Sun, Trash2, X } from "lucide-react";+import { useMemo, useState } from "react";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Input } from "@/components/ui/input";+import { Slider } from "@/components/ui/slider";+import { Switch } from "@/components/ui/switch";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import {+ APERTURES,+ CAMERA_BODIES,+ EMOTION_FAMILIES,+ ERAS,+ FOCAL_LENGTHS,+ GENRES,+ LENSES,+ LIGHTING_PRESETS,+ LIGHT_DIRECTIONS,+ MAX_LIGHTS,+ PALETTES,+ QUICK_LIGHT_DIRECTIONS,+ TEMPOS,+ emotionStep,+ optionName,+ paletteHex,+ paletteLabel,+ rigError,+ type CinemaMode,+ type DirectorOption,+ type DirectorSettings,+ type LightSource,+} from "@/lib/catalog/cinema";+import type { StudioElement } from "@/lib/catalog/elements";+import type { Engine } from "@/lib/catalog/types";+import { cn } from "@/lib/utils";+import { MoveChips, MoveList } from "./camera-moves";+import { PaletteEditor } from "./palette-editor";++type Patch = (p: Partial<DirectorSettings>) => void;++const chipCls = "inline-flex h-8 max-w-[260px] shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium transition-colors";++function DirectorChip({ icon: Icon, label, active, warn, children, ...rest }: { icon: typeof Film; label: string; active?: boolean; warn?: boolean; children?: React.ReactNode } & React.ComponentProps<"button">) {+ return (+ <button+ type="button"+ {...rest}+ className={cn(+ chipCls,+ active ? "bg-brand-faint text-brand-text hover:bg-brand-faint-hover" : "bg-secondary text-secondary-foreground hover:bg-accent",+ warn && "ring-1 ring-warning/60",+ )}+ >+ <Icon className="size-3.5 shrink-0" />+ <span className="truncate">{label}</span>+ {children}+ </button>+ );+}++function PanelHeader({ title, subtitle }: { title: string; subtitle: string }) {+ return (+ <div className="px-1 pb-2">+ <p className="text-[13px] font-medium">{title}</p>+ <p className="text-[12px] text-muted-foreground">{subtitle}</p>+ </div>+ );+}++/** Option cards in a grid: name and what it does; Auto first. */+function OptionGrid({ options, value, onChange, cols = 2 }: { options: DirectorOption[]; value: string | null | undefined; onChange: (slug: string | null) => void; cols?: 2 | 3 }) {+ return (+ <div className={cn("grid gap-1.5", cols === 3 ? "grid-cols-2 sm:grid-cols-3" : "grid-cols-1 sm:grid-cols-2")} role="radiogroup">+ {options.map((o) => {+ const sel = (value ?? null) === o.slug;+ return (+ <button+ key={o.name}+ type="button"+ role="radio"+ aria-checked={sel}+ onClick={() => onChange(o.slug)}+ className={cn(+ "flex flex-col items-start gap-0.5 rounded-lg border px-2.5 py-2 text-left transition-colors",+ sel ? "border-primary bg-brand-faint" : "hover:bg-accent",+ )}+ >+ <span className={cn("flex w-full items-center gap-1 text-[13px] font-medium", sel && "text-brand-text")}>+ {o.name}+ {sel && <Check className="ml-auto size-3.5" />}+ </span>+ <span className="text-[11.5px] leading-snug text-muted-foreground">{o.description}</span>+ </button>+ );+ })}+ </div>+ );+}++/** Film setup control: a carousel with Previous/Next arrows over one list (Higgsfield's pattern). */+function Carousel({ kind, title, subtitle, options, value, onChange, disabled }: { kind: string; title: string; subtitle: string; options: DirectorOption[]; value: string | null | undefined; onChange: (slug: string | null) => void; disabled?: string }) {+ const i = Math.max(0, options.findIndex((o) => o.slug === (value ?? null)));+ const cur = options[i];+ const step = (d: number) => onChange(options[(i + d + options.length) % options.length].slug);+ return (+ <div className={cn("rounded-xl border p-2.5", disabled && "opacity-50")}>+ <div className="flex items-center gap-2">+ <div className="min-w-0 flex-1">+ <p className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">{title}</p>+ <p className="text-[11.5px] text-muted-foreground">{subtitle}</p>+ </div>+ <button type="button" disabled={!!disabled} onClick={() => step(-1)} className="grid size-7 place-items-center rounded-full hover:bg-accent" aria-label={`Previous ${kind}`}>+ <ChevronLeft className="size-4" />+ </button>+ <span className="min-w-20 text-center font-heading text-[19px] leading-none">{cur.name}</span>+ <button type="button" disabled={!!disabled} onClick={() => step(1)} className="grid size-7 place-items-center rounded-full hover:bg-accent" aria-label={`Next ${kind}`}>+ <ChevronRight className="size-4" />+ </button>+ </div>+ <p className="mt-1.5 min-h-[2.4em] text-[12.5px] leading-snug">{disabled ?? cur.description}</p>+ <div className="mt-1.5 flex flex-wrap gap-1" role="radiogroup" aria-label={`Select ${kind}`}>+ {options.map((o) => (+ <button+ key={o.name}+ type="button"+ role="radio"+ aria-checked={o === cur}+ disabled={!!disabled}+ onClick={() => onChange(o.slug)}+ className={cn("h-6 rounded-full px-2 text-[12px] font-medium transition-colors", o === cur ? "bg-primary text-primary-foreground" : "bg-secondary hover:bg-accent")}+ >+ {o.name}+ </button>+ ))}+ </div>+ </div>+ );+}++export function FilmSetupChip({ settings, onChange, mode }: { settings: DirectorSettings; onChange: Patch; mode: CinemaMode }) {+ const parts = [settings.genre && optionName(GENRES, settings.genre), settings.era && optionName(ERAS, settings.era), mode === "video" && settings.tempo && optionName(TEMPOS, settings.tempo)].filter(Boolean);+ return (+ <Popover>+ <PopoverTrigger asChild>+ <DirectorChip icon={Film} label={parts.length ? parts.join(" · ") : "Film setup"} active={parts.length > 0} aria-label="Film setup" />+ </PopoverTrigger>+ <PopoverContent className="w-[min(92vw,460px)] space-y-2 p-3" align="start" side="top" collisionPadding={12}>+ <PanelHeader title="Film setup" subtitle="Genre, era and tempo: the conventions every shot follows" />+ <Carousel kind="genre" title="Genre" subtitle="Story conventions the model should follow" options={GENRES} value={settings.genre} onChange={(genre) => onChange({ genre })} />+ <Carousel kind="era" title="Era" subtitle="The period the film belongs to" options={ERAS} value={settings.era} onChange={(era) => onChange({ era })} />+ <Carousel+ kind="tempo"+ title="Tempo"+ subtitle="Pacing of the montage"+ options={TEMPOS}+ value={settings.tempo}+ onChange={(tempo) => onChange({ tempo })}+ disabled={mode === "image" ? "Tempo shapes video cuts; stills ignore it." : undefined}+ />+ </PopoverContent>+ </Popover>+ );+}++const CAMERA_TABS = [+ { id: "camera", label: "Camera" },+ { id: "lens", label: "Lens" },+ { id: "focal", label: "Focal length" },+ { id: "aperture", label: "Aperture" },+ { id: "movement", label: "Movement" },+] as const;++export function CameraChip({+ settings,+ onChange,+ mode,+ engine,+ moves,+ onMovesChange,+}: {+ settings: DirectorSettings;+ onChange: Patch;+ mode: CinemaMode;+ engine: Engine;+ moves: string[];+ onMovesChange: (m: string[]) => void;+}) {+ const [tab, setTab] = useState<(typeof CAMERA_TABS)[number]["id"]>("camera");+ const still = mode === "image";+ const missing = still && (!settings.camera || !settings.lens || !settings.focal);+ const parts = [+ settings.camera && optionName(CAMERA_BODIES, settings.camera),+ settings.lens && optionName(LENSES, settings.lens),+ settings.focal && optionName(FOCAL_LENGTHS, settings.focal),+ settings.aperture && optionName(APERTURES, settings.aperture).replace(/ .*/, ""),+ ].filter(Boolean);+ const required = (id: string) => still && ((id === "camera" && !settings.camera) || (id === "lens" && !settings.lens) || (id === "focal" && !settings.focal));+ return (+ <Popover>+ <Tooltip>+ <TooltipTrigger asChild>+ <PopoverTrigger asChild>+ <DirectorChip icon={Camera} label={parts.length ? parts.join(" · ") : "Camera"} active={parts.length > 0} warn={missing} aria-label="Camera settings" />+ </PopoverTrigger>+ </TooltipTrigger>+ {missing && <TooltipContent>Stills need a camera, lens and focal length</TooltipContent>}+ </Tooltip>+ <PopoverContent className="w-[min(94vw,540px)] p-3" align="start" side="top" collisionPadding={12}>+ <div className="scrollbar-none mb-3 flex gap-0.5 overflow-x-auto rounded-full bg-muted p-0.5" role="tablist">+ {CAMERA_TABS.filter((t) => t.id !== "movement" || mode === "video").map((t) => (+ <button+ key={t.id}+ role="tab"+ aria-selected={tab === t.id}+ onClick={() => setTab(t.id)}+ className={cn(+ "inline-flex h-7 shrink-0 items-center gap-1 rounded-full px-3 text-[12px] font-medium transition-colors",+ tab === t.id ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground",+ )}+ >+ {t.label}+ {required(t.id) && <span className="size-1.5 rounded-full bg-warning" aria-label="required" />}+ {t.id === "movement" && moves.length > 0 && <span className="font-mono text-[10px] text-brand-text">{moves.length}</span>}+ </button>+ ))}+ </div>+ <div className="max-h-[min(56vh,420px)] overflow-y-auto pr-0.5">+ {tab === "camera" && <OptionGrid options={CAMERA_BODIES} value={settings.camera} onChange={(camera) => onChange({ camera })} />}+ {tab === "lens" && <OptionGrid options={LENSES} value={settings.lens} onChange={(lens) => onChange({ lens })} />}+ {tab === "focal" && <OptionGrid options={FOCAL_LENGTHS} value={settings.focal} onChange={(focal) => onChange({ focal })} cols={3} />}+ {tab === "aperture" && <OptionGrid options={APERTURES} value={settings.aperture} onChange={(aperture) => onChange({ aperture })} />}+ {tab === "movement" && (+ <div className="-mx-1">+ <PanelHeader title="Direct a camera move" subtitle="Adds to the prompt box, or type # there. Several per shot; order matters." />+ <MoveChips moves={moves} onChange={onMovesChange} />+ <MoveList engine={engine} selected={moves} onPick={(slug) => onMovesChange([...moves, slug])} />+ </div>+ )}+ </div>+ {still && <p className="mt-2 text-[11.5px] text-muted-foreground">Cinematic stills need the camera, lens and focal length; the aperture is optional.</p>}+ </PopoverContent>+ </Popover>+ );+}++export function Swatches({ hex, className }: { hex: string[]; className?: string }) {+ return (+ <span className={cn("flex h-3 overflow-hidden rounded-full", className)} aria-hidden>+ {hex.map((h, i) => (+ <span key={i} className="h-full flex-1" style={{ background: h }} />+ ))}+ </span>+ );+}++export function PaletteChip({+ settings,+ onChange,+ engine,+ saved,+ onSave,+}: {+ settings: DirectorSettings;+ onChange: Patch;+ engine: Engine;+ saved: { name: string; hex: string[] }[];+ onSave: (p: { name: string; hex: string[] }[]) => void;+}) {+ const [q, setQ] = useState("");+ const [sort, setSort] = useState<"default" | "name">("default");+ const [editor, setEditor] = useState(false);+ const hex = paletteHex(settings.palette);+ const list = useMemo(() => {+ const ps = PALETTES.filter((p) => !q || p.name.toLowerCase().includes(q.toLowerCase()));+ return sort === "name" ? [...ps].sort((a, b) => a.name.localeCompare(b.name)) : ps;+ }, [q, sort]);+ const mine = saved.filter((p) => !q || p.name.toLowerCase().includes(q.toLowerCase()));+ const isSel = (kind: "preset" | "custom", key: string) =>+ settings.palette?.kind === kind && (kind === "preset" ? settings.palette.kind === "preset" && settings.palette.slug === key : settings.palette.kind === "custom" && settings.palette.name === key);+ return (+ <>+ <Popover>+ <PopoverTrigger asChild>+ <DirectorChip icon={Palette} label={paletteLabel(settings.palette) ?? "Color palette"} active={!!hex} aria-label="Color palette">+ {hex && <Swatches hex={hex} className="h-2.5 w-10 shrink-0" />}+ </DirectorChip>+ </PopoverTrigger>+ <PopoverContent className="w-[min(94vw,560px)] p-3" align="start" side="top" collisionPadding={12}>+ <PanelHeader title="Set up color palette" subtitle="Palette the color grade should follow" />+ <div className="mb-2 flex items-center gap-1.5">+ <Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search palettes…" className="h-8" aria-label="Search palettes" />+ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" onClick={() => setSort((s) => (s === "default" ? "name" : "default"))} className="grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Change sort">+ {sort === "default" ? <ArrowDownAZ className="size-4" /> : <ListOrdered className="size-4" />}+ </button>+ </TooltipTrigger>+ <TooltipContent>{sort === "default" ? "Sort: Name (A–Z)" : "Sort: Default"}</TooltipContent>+ </Tooltip>+ <button type="button" onClick={() => setEditor(true)} className="inline-flex h-8 shrink-0 items-center gap-1 rounded-lg bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent">+ <Plus className="size-3.5" /> New palette+ </button>+ </div>+ <div className="max-h-[min(50vh,380px)] space-y-2 overflow-y-auto pr-0.5">+ <div className="grid grid-cols-1 gap-1.5 sm:grid-cols-2">+ <button+ type="button"+ onClick={() => onChange({ palette: null })}+ className={cn("rounded-lg border px-2.5 py-2 text-left transition-colors", !settings.palette ? "border-primary bg-brand-faint" : "hover:bg-accent")}+ >+ <span className="text-[13px] font-medium">Auto</span>+ <span className="block text-[11.5px] text-muted-foreground">No palette: the prompt drives the grade</span>+ </button>+ {mine.map((p) => (+ <div key={`mine-${p.name}`} className={cn("group/pal relative rounded-lg border px-2.5 py-2 transition-colors", isSel("custom", p.name) ? "border-primary bg-brand-faint" : "hover:bg-accent")}>+ <button type="button" className="block w-full text-left" onClick={() => onChange({ palette: { kind: "custom", name: p.name, hex: p.hex } })}>+ <span className="flex items-center gap-1 text-[13px] font-medium">+ {p.name} <span className="rounded-full bg-secondary px-1.5 text-[10px] text-muted-foreground">yours</span>+ </span>+ <Swatches hex={p.hex} className="mt-1.5" />+ </button>+ <button+ type="button"+ onClick={() => onSave(saved.filter((x) => x !== p))}+ className="absolute top-1.5 right-1.5 grid size-6 place-items-center rounded-md text-muted-foreground opacity-100 hover:bg-accent hover:text-destructive sm:opacity-0 sm:group-hover/pal:opacity-100"+ aria-label={`Delete ${p.name}`}+ >+ <Trash2 className="size-3.5" />+ </button>+ </div>+ ))}+ {list.map((p) => (+ <button+ key={p.slug}+ type="button"+ onClick={() => onChange({ palette: { kind: "preset", slug: p.slug } })}+ className={cn("rounded-lg border px-2.5 py-2 text-left transition-colors", isSel("preset", p.slug) ? "border-primary bg-brand-faint" : "hover:bg-accent")}+ >+ <span className="flex items-center gap-1 text-[13px] font-medium">+ <span className="truncate">{p.name}</span>+ {isSel("preset", p.slug) && <Check className="ml-auto size-3.5 shrink-0 text-brand-text" />}+ </span>+ <Swatches hex={p.hex} className="mt-1.5" />+ </button>+ ))}+ </div>+ {!list.length && !mine.length && <p className="py-6 text-center text-[13px] text-muted-foreground">No palettes found</p>}+ </div>+ {engine === "open" && (+ <label className="mt-3 flex items-start justify-between gap-3 rounded-lg bg-muted px-3 py-2">+ <span>+ <span className="block text-[12.5px] font-medium">Lock the grade</span>+ <span className="block text-[11.5px] text-muted-foreground">Open source: recolour every take to the palette (palette transfer, runs on CPU)</span>+ </span>+ <Switch checked={settings.paletteLock !== false} onCheckedChange={(v) => onChange({ paletteLock: v })} aria-label="Lock the grade to the palette" />+ </label>+ )}+ </PopoverContent>+ </Popover>+ <PaletteEditor+ open={editor}+ onOpenChange={setEditor}+ onSave={(p) => {+ onSave([p, ...saved.filter((x) => x.name !== p.name)]);+ onChange({ palette: { kind: "custom", name: p.name, hex: p.hex } });+ }}+ />+ </>+ );+}++/** Where a light sits on a sphere: x/y from the direction words; "back" lights become a rim. */+function lightSpot(direction: string): { x: number; y: number; back: boolean } {+ const d = direction.split("-");+ return { x: 50 + (d.includes("left") ? -32 : d.includes("right") ? 32 : 0), y: 50 + (d.includes("top") ? -32 : d.includes("bottom") ? 32 : 0), back: d.includes("back") };+}++export function LightSphere({ lights, className }: { lights: LightSource[]; className?: string }) {+ const bg = lights+ .map((l) => {+ const s = lightSpot(l.direction);+ const size = 30 + l.diffuse * 0.4;+ const a = Math.round(25 + l.brightness * 0.75);+ return s.back+ ? `radial-gradient(circle at ${100 - s.x}% ${100 - s.y}%, transparent ${size + 10}%, color-mix(in oklab, ${l.color} ${a}%, transparent) ${size + 22}%, transparent ${size + 34}%)`+ : `radial-gradient(circle at ${s.x}% ${s.y}%, color-mix(in oklab, ${l.color} ${a}%, transparent), transparent ${size}%)`;+ })+ .join(", ");+ return <span className={cn("block aspect-square rounded-full bg-neutral-700", className)} style={{ backgroundImage: bg || undefined }} aria-hidden />;+}++const PRESET_LIGHT: Record<string, LightSource[]> = {+ silhouette: [{ direction: "back", color: "#fff4e0", brightness: 100, diffuse: 20 }],+ practicals: [{ direction: "front-bottom-left", color: "#ffb35c", brightness: 60, diffuse: 50 }, { direction: "right", color: "#ffd08a", brightness: 40, diffuse: 60 }],+ window: [{ direction: "left", color: "#e8f0ff", brightness: 85, diffuse: 45 }],+ "overhead-fall": [{ direction: "back-top", color: "#fff1dc", brightness: 75, diffuse: 80 }],+ "contre-jour": [{ direction: "back-top-right", color: "#ffd9a0", brightness: 100, diffuse: 70 }],+ "soft-cross": [{ direction: "front-left", color: "#fff6ea", brightness: 70, diffuse: 85 }, { direction: "right", color: "#dfe8ff", brightness: 45, diffuse: 85 }],+};++function LightEditor({ light, index, onChange, onRemove }: { light: LightSource; index: number; onChange: (l: LightSource) => void; onRemove?: () => void }) {+ return (+ <div className="space-y-2.5 rounded-xl border p-2.5">+ <div className="flex items-center gap-2">+ <span className="text-[12.5px] font-medium">Light {index + 1}</span>+ {onRemove && (+ <button type="button" onClick={onRemove} className="ml-auto inline-flex h-6 items-center gap-1 rounded-md px-1.5 text-[11.5px] text-muted-foreground hover:bg-accent hover:text-destructive">+ <X className="size-3" /> Remove light+ </button>+ )}+ </div>+ <div className="flex items-start gap-3">+ <LightSphere lights={[light]} className="size-16 shrink-0" />+ <div className="min-w-0 flex-1 space-y-1.5">+ <div className="flex flex-wrap gap-1">+ {QUICK_LIGHT_DIRECTIONS.map((d) => (+ <button+ key={d}+ type="button"+ onClick={() => onChange({ ...light, direction: d })}+ className={cn("h-6 rounded-full px-2 text-[11.5px] font-medium capitalize", light.direction === d ? "bg-primary text-primary-foreground" : "bg-secondary hover:bg-accent")}+ >+ {d}+ </button>+ ))}+ </div>+ <select+ value={light.direction}+ onChange={(e) => onChange({ ...light, direction: e.target.value })}+ className="h-7 w-full rounded-md border bg-background px-1.5 text-[12px] capitalize outline-none focus:border-primary"+ aria-label={`Light ${index + 1} direction`}+ >+ {LIGHT_DIRECTIONS.map((d) => (+ <option key={d} value={d}>+ {d.replace(/-/g, " ")}+ </option>+ ))}+ </select>+ </div>+ </div>+ <div className="flex items-center gap-2">+ <input type="color" value={light.color} onChange={(e) => onChange({ ...light, color: e.target.value })} className="size-7 shrink-0 cursor-pointer rounded-md border bg-transparent p-0.5" aria-label={`Light ${index + 1} colour`} />+ <Input+ value={light.color}+ onChange={(e) => {+ const v = e.target.value.trim();+ onChange({ ...light, color: v.startsWith("#") ? v.slice(0, 7) : `#${v.slice(0, 6)}` });+ }}+ className="h-7 w-24 font-mono text-[12px]"+ aria-label={`Light ${index + 1} hex colour`}+ />+ </div>+ {(["brightness", "diffuse"] as const).map((k) => (+ <div key={k} className="space-y-1">+ <div className="flex justify-between text-[11.5px] text-muted-foreground">+ <span className="capitalize">{k}</span>+ <span className="font-mono">{light[k]}</span>+ </div>+ <Slider value={[light[k]]} min={0} max={100} step={1} onValueChange={([v]) => onChange({ ...light, [k]: Math.round(v) })} aria-label={`Light ${index + 1} ${k}`} />+ </div>+ ))}+ </div>+ );+}++export function LightingChip({ settings, onChange }: { settings: DirectorSettings; onChange: Patch }) {+ const lighting = settings.lighting;+ const [tab, setTab] = useState<"presets" | "custom">(lighting?.kind === "custom" ? "custom" : "presets");+ const lights = lighting?.kind === "custom" ? lighting.lights : [];+ const err = lighting?.kind === "custom" ? rigError(lighting.lights) : null;+ const label = !lighting ? "Lighting" : lighting.kind === "preset" ? optionName(LIGHTING_PRESETS, lighting.slug) : `Custom · ${lights.length} light${lights.length === 1 ? "" : "s"}`;+ const setLights = (ls: LightSource[]) => onChange({ lighting: ls.length ? { kind: "custom", lights: ls } : null });+ return (+ <Popover>+ <PopoverTrigger asChild>+ <DirectorChip icon={Sun} label={label} active={!!lighting} aria-label="Lighting" />+ </PopoverTrigger>+ <PopoverContent className="w-[min(94vw,520px)] p-3" align="start" side="top" collisionPadding={12}>+ <PanelHeader title="Set up lighting" subtitle="Pick a scheme or place your own lights" />+ <div className="mb-3 inline-flex rounded-full bg-muted p-0.5" role="tablist">+ {(["presets", "custom"] as const).map((t) => (+ <button+ key={t}+ role="tab"+ aria-selected={tab === t}+ onClick={() => setTab(t)}+ className={cn("h-7 rounded-full px-3 text-[12px] font-medium", tab === t ? "bg-background shadow-soft" : "text-muted-foreground hover:text-foreground")}+ >+ {t === "presets" ? "Presets" : "Custom rig"}+ </button>+ ))}+ </div>+ <div className="max-h-[min(56vh,440px)] overflow-y-auto pr-0.5">+ {tab === "presets" ? (+ <div className="grid grid-cols-1 gap-1.5 sm:grid-cols-2" role="radiogroup">+ {[...LIGHTING_PRESETS].sort((a, b) => Number(!!a.slug) - Number(!!b.slug)).map((p) => {+ const sel = p.slug ? lighting?.kind === "preset" && lighting.slug === p.slug : !lighting;+ return (+ <button+ key={p.name}+ type="button"+ role="radio"+ aria-checked={sel}+ onClick={() => onChange({ lighting: p.slug ? { kind: "preset", slug: p.slug } : null })}+ className={cn("flex items-start gap-2.5 rounded-lg border px-2.5 py-2 text-left transition-colors", sel ? "border-primary bg-brand-faint" : "hover:bg-accent")}+ >+ <LightSphere lights={p.slug ? (PRESET_LIGHT[p.slug] ?? []) : [{ direction: "front-top", color: "#ffffff", brightness: 50, diffuse: 90 }]} className="mt-0.5 size-9 shrink-0" />+ <span className="min-w-0">+ <span className={cn("block text-[13px] font-medium", sel && "text-brand-text")}>{p.name}</span>+ <span className="block text-[11.5px] leading-snug text-muted-foreground">{p.description}</span>+ </span>+ </button>+ );+ })}+ </div>+ ) : (+ <div className="space-y-2">+ {lighting?.kind === "preset" && <p className="text-[12px] text-muted-foreground">A lighting preset and a custom rig are mutually exclusive — adding a light replaces “{optionName(LIGHTING_PRESETS, lighting.slug)}”.</p>}+ {lights.map((l, i) => (+ <LightEditor key={i} light={l} index={i} onChange={(nl) => setLights(lights.map((x, j) => (j === i ? nl : x)))} onRemove={() => setLights(lights.filter((_, j) => j !== i))} />+ ))}+ {lights.length < MAX_LIGHTS && (+ <button+ type="button"+ onClick={() => setLights([...lights, { direction: lights.length ? "right" : "front-top-left", color: lights.length ? "#9fb8ff" : "#ffd29a", brightness: lights.length ? 45 : 80, diffuse: 60 }])}+ className="flex w-full items-center justify-center gap-1.5 rounded-xl border border-dashed py-3 text-[12.5px] font-medium text-muted-foreground hover:border-primary hover:bg-brand-faint hover:text-brand-text"+ >+ <Plus className="size-3.5" /> Add light+ </button>+ )}+ {err && lights.length > 0 && <p className="text-[12px] text-destructive">{err}</p>}+ {lights.length > 0 && <LightSphere lights={lights} className="mx-auto size-24" />}+ </div>+ )}+ </div>+ </PopoverContent>+ </Popover>+ );+}++export function EmotionChip({ settings, onChange, characters }: { settings: DirectorSettings; onChange: Patch; characters: StudioElement[] }) {+ const emotions = settings.emotions ?? {};+ const active = characters.filter((c) => emotions[c.handle.toLowerCase()]);+ const first = active[0] ? emotionStep(emotions[active[0].handle.toLowerCase()]) : undefined;+ const set = (handle: string, v: { family: string; step: number } | null) => {+ const next = { ...emotions };+ if (v) next[handle.toLowerCase()] = v;+ else delete next[handle.toLowerCase()];+ onChange({ emotions: next });+ };+ return (+ <Popover>+ <PopoverTrigger asChild>+ <DirectorChip icon={Smile} label={first ? `${first.name}${active.length > 1 ? ` +${active.length - 1}` : ""}` : "Emotions"} active={active.length > 0} aria-label="Emotion wheel">+ {first && <span className="size-2.5 shrink-0 rounded-full" style={{ background: first.color }} />}+ </DirectorChip>+ </PopoverTrigger>+ <PopoverContent className="w-[min(94vw,480px)] p-3" align="start" side="top" collisionPadding={12}>+ <PanelHeader title="Emotion Wheel" subtitle="Give each @character a feeling; its intensity sets the words added after their name" />+ {!characters.length ? (+ <p className="rounded-lg bg-muted px-3 py-4 text-center text-[12.5px] text-muted-foreground">Mention a character with @ in the prompt to give them an emotion.</p>+ ) : (+ <div className="max-h-[min(56vh,440px)] space-y-3 overflow-y-auto pr-0.5">+ {characters.map((c) => {+ const cur = emotions[c.handle.toLowerCase()];+ const step = emotionStep(cur);+ return (+ <div key={c.id} className="space-y-1.5">+ <div className="flex items-center gap-2">+ <span className="grid size-6 place-items-center overflow-hidden rounded-full bg-muted" style={step ? { boxShadow: `0 0 0 2px ${step.color}` } : undefined}>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ {c.references[0] ? <img src={c.references[0]} alt="" className="size-full object-cover" /> : null}+ </span>+ <span className="text-[13px] font-medium">@{c.handle}</span>+ {step && <span className="truncate text-[12px] text-muted-foreground">{step.prompt}</span>}+ </div>+ <div className="flex flex-wrap gap-1">+ <button type="button" onClick={() => set(c.handle, null)} className={cn("h-7 rounded-full px-2.5 text-[12px] font-medium", !cur ? "bg-primary text-primary-foreground" : "bg-secondary hover:bg-accent")}>+ Neutral+ </button>+ {EMOTION_FAMILIES.map((f) => {+ const sel = cur?.family === f.name;+ return (+ <button+ key={f.name}+ type="button"+ onClick={() => set(c.handle, { family: f.name, step: cur?.family === f.name ? cur.step : 1 })}+ className={cn("inline-flex h-7 items-center gap-1.5 rounded-full border px-2.5 text-[12px] font-medium", sel ? "border-transparent text-white" : "hover:bg-accent")}+ style={sel ? { background: f.colors[cur!.step] } : undefined}+ >+ {!sel && <span className="size-2 rounded-full" style={{ background: f.colors[1] }} />}+ {f.name}+ </button>+ );+ })}+ </div>+ {cur && step && (+ <div className="flex gap-1 pl-0.5" role="radiogroup" aria-label={`${c.handle} intensity`}>+ {step.family.steps.map((s, i) => (+ <button+ key={s.name}+ type="button"+ role="radio"+ aria-checked={cur.step === i}+ onClick={() => set(c.handle, { family: cur.family, step: i })}+ className={cn("h-6 flex-1 rounded-md text-[11.5px] font-medium", cur.step === i ? "text-white" : "bg-secondary hover:bg-accent")}+ style={cur.step === i ? { background: step.family.colors[i] } : undefined}+ >+ {s.name} · {s.intensity}+ </button>+ ))}+ </div>+ )}+ </div>+ );+ })}+ </div>+ )}+ </PopoverContent>+ </Popover>+ );+}diff --git a/src/components/cinema/draft.ts b/src/components/cinema/draft.tsnew file mode 100644index 00000000..a4919019--- /dev/null+++ b/src/components/cinema/draft.ts@@ -0,0 +1,88 @@+import { DURATION, type CinemaAction, type CinemaGenerateInput, type CinemaMode, type DirectorSettings, type GridSize, type GridType } from "@/lib/catalog/cinema";+import type { Engine, MediaKind } from "@/lib/catalog/types";++/** The prompt bar's state (lifted into the workspace so the AI Director and tiles can fill it). */++export interface RefItem {+ id: string;+ /** /api/files URL once uploaded ("" while uploading). */+ ref: string;+ preview: string;+ kind: MediaKind;+ name?: string;+ uploading?: boolean;+ /** Seconds, for video/audio (measured in the browser). */+ duration?: number;+}++export type BarAction = Extract<CinemaAction, "generate" | "extend-forward" | "extend-backward" | "edit">;++export interface TakeSource {+ generationId: string;+ url: string;+ kind: "image" | "video";+ label: string;+}++export interface CinemaDraft {+ mode: CinemaMode;+ imageTool: "still" | "grid";+ prompt: string;+ moves: string[];+ refs: RefItem[];+ /** Model picked per mode and engine ("video:cloud" → "kling-3"). */+ models: Partial<Record<`${CinemaMode}:${Engine}`, string>>;+ duration: number;+ resolution: Record<CinemaMode, string>;+ aspect: Record<CinemaMode, string>;+ batch: number;+ audio: boolean;+ multiShot: { mode: "off" | "auto" | "manual"; shots: { prompt: string; duration: number }[] };+ grid: { size: GridSize; type: GridType };+ action: BarAction;+ source: TakeSource | null;+}++export const initialDraft = (): CinemaDraft => ({+ mode: "video",+ imageTool: "still",+ prompt: "",+ moves: [],+ refs: [],+ models: {},+ duration: DURATION.default,+ resolution: { video: "720p", image: "1K" },+ aspect: { video: "16:9", image: "16:9" },+ batch: 1,+ audio: true,+ multiShot: { mode: "off", shots: [] },+ grid: { size: "2x2", type: "freeform" },+ action: "generate",+ source: null,+});++/** The request body for /generate (and the input planCinema prices live). */+export function draftToInput(d: CinemaDraft, engine: Engine, settings: DirectorSettings, firstFrame?: string): Omit<CinemaGenerateInput, "brief"> {+ const ready = d.refs.filter((r) => r.ref && !r.uploading);+ const action = d.mode === "image" ? (d.imageTool === "grid" ? "grid" : "generate") : d.source?.kind === "video" ? d.action : "generate";+ return {+ engine,+ mode: d.mode,+ action,+ modelId: d.models[`${d.mode}:${engine}`],+ prompt: d.prompt,+ moves: d.mode === "video" ? d.moves : undefined,+ settings,+ images: ready.filter((r) => r.kind === "image").map((r) => r.ref),+ videos: ready.filter((r) => r.kind === "video").map((r) => r.ref),+ audios: ready.filter((r) => r.kind === "audio").map((r) => r.ref),+ duration: d.duration,+ resolution: d.resolution[d.mode],+ aspectRatio: d.aspect[d.mode],+ batch: d.batch,+ audio: d.audio,+ multiShot: d.mode === "video" && d.multiShot.mode !== "off" ? d.multiShot : undefined,+ source: d.source && action !== "generate" && action !== "grid" ? { url: d.source.url, kind: d.source.kind, ...(firstFrame ? { firstFrame } : {}) } : undefined,+ grid: action === "grid" ? d.grid : undefined,+ };+}diff --git a/src/components/cinema/elements-panel.tsx b/src/components/cinema/elements-panel.tsxnew file mode 100644index 00000000..5db45450--- /dev/null+++ b/src/components/cinema/elements-panel.tsx@@ -0,0 +1,87 @@+"use client";++import { AtSign, ExternalLink, MapPin, Plus, UserRoundPlus } from "lucide-react";+import Link from "next/link";+import { Button } from "@/components/ui/button";+import { Skeleton } from "@/components/ui/skeleton";+import { ELEMENT_ICONS } from "@/components/studio/prompt-input";+import { useElements } from "@/lib/api";+import { ELEMENT_KINDS, type StudioElement } from "@/lib/catalog/elements";++/** "My Elements": the characters, locations and props every shot can @mention. */+export function ElementsPanel({ onMention, onCast, onLocation }: { onMention: (el: StudioElement) => void; onCast: () => void; onLocation: () => void }) {+ const { data, isLoading } = useElements();+ const visual = (data ?? []).filter((e) => e.kind !== "voice");+ return (+ <div className="space-y-6">+ <div className="flex flex-wrap items-center gap-2">+ <h2 className="flex-1 font-heading text-[24px] leading-none">My Elements</h2>+ <Button variant="secondary" size="sm" onClick={onCast}>+ <UserRoundPlus /> New character+ </Button>+ <Button variant="secondary" size="sm" onClick={onLocation}>+ <MapPin /> New location+ </Button>+ <Button asChild variant="ghost" size="sm">+ <Link href="/elements?new=1">+ <Plus /> Upload an element+ </Link>+ </Button>+ </div>+ {isLoading ? (+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">+ {Array.from({ length: 5 }, (_, i) => (+ <Skeleton key={i} className="aspect-[3/4] rounded-xl" />+ ))}+ </div>+ ) : !visual.length ? (+ <div className="mx-auto max-w-md py-12 text-center">+ <div className="mx-auto grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">+ <AtSign className="size-5" />+ </div>+ <p className="mt-4 font-heading text-[22px]">No elements yet</p>+ <p className="mt-1 text-[13.5px] text-muted-foreground">Build a cast member with Soul Cast or a set with Soul Location, then type @ in any prompt to put them in the shot.</p>+ </div>+ ) : (+ ELEMENT_KINDS.filter((k) => k.kind !== "voice" && visual.some((e) => e.kind === k.kind)).map((k) => (+ <section key={k.kind} className="space-y-2.5">+ <h3 className="text-[12px] font-medium text-muted-foreground">{k.plural}</h3>+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">+ {visual+ .filter((e) => e.kind === k.kind)+ .map((el) => {+ const Icon = ELEMENT_ICONS[el.kind];+ return (+ <div key={el.id} className="group/el relative overflow-hidden rounded-xl border bg-card">+ <button type="button" onClick={() => onMention(el)} className="block w-full text-left outline-none focus-visible:ring-2 focus-visible:ring-ring" aria-label={`Add @${el.handle} to the prompt`}>+ <div className="aspect-[4/3] bg-muted">+ {el.references[0] ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={el.references[0]} alt="" loading="lazy" className="size-full object-cover" />+ ) : (+ <Icon className="m-auto mt-[22%] size-6 text-muted-foreground" />+ )}+ </div>+ <div className="p-2">+ <p className="truncate text-[13px] font-medium">{el.name}</p>+ <p className="truncate text-[11.5px] text-brand-text">@{el.handle}</p>+ </div>+ </button>+ <Link+ href={`/elements/${el.id}`}+ className="absolute top-1.5 right-1.5 grid size-7 place-items-center rounded-full bg-black/45 text-white opacity-100 backdrop-blur sm:opacity-0 sm:group-hover/el:opacity-100 focus-visible:opacity-100"+ aria-label={`Open ${el.name}`}+ >+ <ExternalLink className="size-3.5" />+ </Link>+ </div>+ );+ })}+ </div>+ </section>+ ))+ )}+ {visual.length > 0 && <p className="text-[12px] text-muted-foreground">Click an element to add it to the prompt.</p>}+ </div>+ );+}diff --git a/src/components/cinema/folder-sidebar.tsx b/src/components/cinema/folder-sidebar.tsxnew file mode 100644index 00000000..1e933d7b--- /dev/null+++ b/src/components/cinema/folder-sidebar.tsx@@ -0,0 +1,336 @@+"use client";++import { ArrowDownAZ, AtSign, ChevronRight, Clock, Folder, FolderInput, FolderPlus, Heart, Home, Library, ListOrdered, MoreHorizontal, Pencil, Pin, PinOff, Search, Trash2 } from "lucide-react";+import { useMemo, useState } from "react";+import { toast } from "sonner";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Input } from "@/components/ui/input";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { EMOTION_FAMILIES, type CinemaFolder } from "@/lib/catalog/cinema";+import { cn } from "@/lib/utils";+import { useFolderActions } from "./hooks";++/** Which feed the workspace shows. */+export type CinemaView = { kind: "home" } | { kind: "studio" } | { kind: "elements" } | { kind: "favorites" } | { kind: "folder"; id: string };++export const viewKey = (v: CinemaView) => (v.kind === "folder" ? `folder:${v.id}` : v.kind);++/** Folder swatches: the Emotion Wheel's mid tones, plus none. */+export const FOLDER_COLORS = EMOTION_FAMILIES.map((f) => f.colors[1]);++type Sort = "manual" | "name" | "recent";++export interface FolderNode extends CinemaFolder {+ children: FolderNode[];+ depth: number;+}++export function folderTree(folders: CinemaFolder[], sort: Sort = "manual"): FolderNode[] {+ const by = new Map<string | null, CinemaFolder[]>();+ for (const f of folders) {+ const parent = f.parentId && folders.some((x) => x.id === f.parentId) ? f.parentId : null;+ by.set(parent, [...(by.get(parent) ?? []), f]);+ }+ const order = (xs: CinemaFolder[]) =>+ [...xs].sort((a, b) => Number(b.pinned) - Number(a.pinned) || (sort === "name" ? a.name.localeCompare(b.name) : sort === "recent" ? b.updatedAt - a.updatedAt : a.position - b.position));+ const build = (parent: string | null, depth: number): FolderNode[] => order(by.get(parent) ?? []).map((f) => ({ ...f, depth, children: build(f.id, depth + 1) }));+ return build(null, 0);+}++export function flattenTree(nodes: FolderNode[]): FolderNode[] {+ return nodes.flatMap((n) => [n, ...flattenTree(n.children)]);+}++/** A folder's id and every folder nested in it. */+export function subtree(folders: CinemaFolder[], id: string): Set<string> {+ const out = new Set([id]);+ let grew = true;+ while (grew) {+ grew = false;+ for (const f of folders) {+ if (f.parentId && out.has(f.parentId) && !out.has(f.id)) {+ out.add(f.id);+ grew = true;+ }+ }+ }+ return out;+}++/** "Move to" submenu content: project root + every folder (indented). */+export function MoveToItems({ folders, onMove, exclude }: { folders: CinemaFolder[]; onMove: (folderId: string | null) => void; exclude?: Set<string> }) {+ const flat = flattenTree(folderTree(folders));+ return (+ <>+ <DropdownMenuItem onClick={() => onMove(null)}>+ <Home /> Project root+ </DropdownMenuItem>+ {flat+ .filter((f) => !exclude?.has(f.id))+ .map((f) => (+ <DropdownMenuItem key={f.id} onClick={() => onMove(f.id)} style={{ paddingLeft: 8 + f.depth * 14 }}>+ <Folder style={f.color ? { color: f.color } : undefined} /> {f.name}+ </DropdownMenuItem>+ ))}+ </>+ );+}++function FolderRow({+ node,+ folders,+ view,+ setView,+ open,+ toggle,+ counts,+ projectId,+ onDropItems,+}: {+ node: FolderNode;+ folders: CinemaFolder[];+ view: CinemaView;+ setView: (v: CinemaView) => void;+ open: Set<string>;+ toggle: (id: string) => void;+ counts: Map<string, number>;+ projectId: string;+ onDropItems: (ids: string[], folderId: string) => void;+}) {+ const actions = useFolderActions(projectId);+ const [renaming, setRenaming] = useState(false);+ const [name, setName] = useState(node.name);+ const [over, setOver] = useState(false);+ const active = view.kind === "folder" && view.id === node.id;+ const expanded = open.has(node.id);+ const commit = () => {+ setRenaming(false);+ if (name.trim() && name.trim() !== node.name) void actions.update(node.id, { name: name.trim() }).catch((e) => toast.error((e as Error).message));+ else setName(node.name);+ };+ return (+ <li>+ <div+ className={cn(+ "group/row flex h-8 items-center gap-1 rounded-lg pr-1 text-[13px] transition-colors",+ active ? "bg-sidebar-accent font-medium" : "hover:bg-accent",+ over && "bg-brand-faint ring-1 ring-primary",+ )}+ style={{ paddingLeft: 4 + node.depth * 14 }}+ onDragOver={(e) => {+ if (!e.dataTransfer.types.includes("application/x-cinema-takes")) return;+ e.preventDefault();+ setOver(true);+ }}+ onDragLeave={() => setOver(false)}+ onDrop={(e) => {+ setOver(false);+ const ids = e.dataTransfer.getData("application/x-cinema-takes");+ if (ids) onDropItems(JSON.parse(ids) as string[], node.id);+ }}+ >+ <button+ type="button"+ onClick={() => toggle(node.id)}+ className={cn("grid size-5 shrink-0 place-items-center rounded text-muted-foreground hover:text-foreground", !node.children.length && "invisible")}+ aria-label={expanded ? `Collapse ${node.name}` : `Expand ${node.name}`}+ aria-expanded={expanded}+ >+ <ChevronRight className={cn("size-3.5 transition-transform", expanded && "rotate-90")} />+ </button>+ {renaming ? (+ <Input+ value={name}+ autoFocus+ onChange={(e) => setName(e.target.value.slice(0, 60))}+ onBlur={commit}+ onKeyDown={(e) => {+ if (e.key === "Enter") commit();+ if (e.key === "Escape") {+ setName(node.name);+ setRenaming(false);+ }+ }}+ className="h-7 flex-1 px-1.5 text-[13px]"+ aria-label="Folder name"+ />+ ) : (+ <button type="button" onClick={() => setView({ kind: "folder", id: node.id })} onDoubleClick={() => setRenaming(true)} className="flex min-w-0 flex-1 items-center gap-1.5 text-left">+ <span className="size-2.5 shrink-0 rounded-full border" style={node.color ? { background: node.color, borderColor: node.color } : undefined} />+ <span className="truncate">{node.name}</span>+ {node.pinned && <Pin className="size-3 shrink-0 text-muted-foreground" />}+ </button>+ )}+ {!renaming && <span className="shrink-0 font-mono text-[10.5px] text-muted-foreground group-hover/row:hidden">{counts.get(node.id) || ""}</span>}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ className="hidden size-6 shrink-0 place-items-center rounded-md text-muted-foreground group-focus-within/row:grid group-hover/row:grid hover:bg-accent hover:text-foreground data-[state=open]:grid max-lg:grid"+ aria-label={`${node.name} actions`}+ >+ <MoreHorizontal className="size-3.5" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-52">+ <DropdownMenuItem onClick={() => setRenaming(true)}>+ <Pencil /> Rename+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => void actions.create({ name: "New scene", parentId: node.id }).then(() => !expanded && toggle(node.id))}>+ <FolderPlus /> New subfolder+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => void actions.update(node.id, { pinned: !node.pinned })}>+ {node.pinned ? <PinOff /> : <Pin />} {node.pinned ? "Unpin" : "Pin"}+ </DropdownMenuItem>+ <div className="flex flex-wrap gap-1 px-2 py-1.5" role="radiogroup" aria-label="Folder colour">+ <button type="button" onClick={() => void actions.update(node.id, { color: null })} className={cn("size-5 rounded-full border", !node.color && "ring-2 ring-primary ring-offset-1 ring-offset-popover")} aria-label="No colour" />+ {FOLDER_COLORS.map((c) => (+ <button+ key={c}+ type="button"+ onClick={() => void actions.update(node.id, { color: c })}+ className={cn("size-5 rounded-full", node.color === c && "ring-2 ring-primary ring-offset-1 ring-offset-popover")}+ style={{ background: c }}+ aria-label={`Colour ${c}`}+ />+ ))}+ </div>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <FolderInput /> Move to+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-72 overflow-y-auto">+ <MoveToItems folders={folders} exclude={subtree(folders, node.id)} onMove={(parentId) => void actions.update(node.id, { parentId }).catch((e) => toast.error((e as Error).message))} />+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ onClick={() =>+ void actions.remove(node.id).then(() => {+ if (active) setView({ kind: "home" });+ toast("Folder deleted — its takes moved up a level");+ })+ }+ >+ <Trash2 /> Delete folder+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ {expanded && node.children.length > 0 && (+ <ul>+ {node.children.map((c) => (+ <FolderRow key={c.id} node={c} folders={folders} view={view} setView={setView} open={open} toggle={toggle} counts={counts} projectId={projectId} onDropItems={onDropItems} />+ ))}+ </ul>+ )}+ </li>+ );+}++export function FolderSidebar({+ projectId,+ folders,+ view,+ setView,+ counts,+ onDropItems,+ className,+}: {+ projectId: string;+ folders: CinemaFolder[];+ view: CinemaView;+ setView: (v: CinemaView) => void;+ counts: { home: number; favorites: number; folders: Map<string, number> };+ onDropItems: (ids: string[], folderId: string) => void;+ className?: string;+}) {+ const actions = useFolderActions(projectId);+ const [q, setQ] = useState("");+ const [sort, setSort] = useState<Sort>("manual");+ const [open, setOpen] = useState<Set<string>>(() => new Set(folders.map((f) => f.id)));+ const tree = useMemo(() => folderTree(folders, sort), [folders, sort]);+ const matches = useMemo(() => (q ? flattenTree(tree).filter((f) => f.name.toLowerCase().includes(q.toLowerCase())).map((f) => ({ ...f, depth: 0, children: [] })) : tree), [tree, q]);+ const toggle = (id: string) => setOpen((s) => (s.has(id) ? new Set([...s].filter((x) => x !== id)) : new Set([...s, id])));+ const sections: { view: CinemaView; label: string; icon: typeof Home; count?: number }[] = [+ { view: { kind: "home" }, label: "Home", icon: Home, count: counts.home },+ { view: { kind: "studio" }, label: "My Generations", icon: Library },+ { view: { kind: "elements" }, label: "My Elements", icon: AtSign },+ { view: { kind: "favorites" }, label: "My Favorites", icon: Heart, count: counts.favorites },+ ];+ const newFolder = async () => {+ try {+ const f = await actions.create({ name: `Scene ${folders.filter((x) => !x.parentId).length + 1}` });+ setOpen((s) => new Set([...s, f.id]));+ setView({ kind: "folder", id: f.id });+ } catch (e) {+ toast.error((e as Error).message);+ }+ };+ return (+ <nav className={cn("flex min-h-0 flex-col gap-3 p-2", className)} aria-label="Project">+ <ul className="space-y-0.5">+ {sections.map((s) => {+ const active = viewKey(s.view) === viewKey(view);+ return (+ <li key={s.label}>+ <button+ type="button"+ onClick={() => setView(s.view)}+ className={cn("flex h-8 w-full items-center gap-2 rounded-lg px-2 text-[13px] transition-colors", active ? "bg-sidebar-accent font-medium" : "hover:bg-accent")}+ aria-current={active ? "page" : undefined}+ >+ <s.icon className="size-4 text-muted-foreground" />+ <span className="flex-1 text-left">{s.label}</span>+ {s.count ? <span className="font-mono text-[10.5px] text-muted-foreground">{s.count}</span> : null}+ </button>+ </li>+ );+ })}+ </ul>+ <div className="min-h-0 flex-1 space-y-1.5 overflow-y-auto">+ <div className="flex items-center gap-1 px-1">+ <span className="flex-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">Scenes</span>+ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" onClick={() => setSort((s) => (s === "manual" ? "name" : s === "name" ? "recent" : "manual"))} className="grid size-6 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Sort folders">+ {sort === "manual" ? <ListOrdered className="size-3.5" /> : sort === "name" ? <ArrowDownAZ className="size-3.5" /> : <Clock className="size-3.5" />}+ </button>+ </TooltipTrigger>+ <TooltipContent>Sort: {sort === "manual" ? "Manual" : sort === "name" ? "Name (A–Z)" : "Recently changed"}</TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" onClick={() => void newFolder()} className="grid size-6 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="New folder">+ <FolderPlus className="size-3.5" />+ </button>+ </TooltipTrigger>+ <TooltipContent>New folder (scene)</TooltipContent>+ </Tooltip>+ </div>+ {folders.length > 4 && (+ <div className="relative px-1">+ <Search className="pointer-events-none absolute top-1/2 left-3 size-3.5 -translate-y-1/2 text-muted-foreground" />+ <Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Find folder.." className="h-7 pl-7 text-[12.5px]" aria-label="Find folder" />+ </div>+ )}+ {folders.length ? (+ <ul className="space-y-0.5">+ {matches.map((n) => (+ <FolderRow key={n.id} node={n} folders={folders} view={view} setView={setView} open={q ? new Set() : open} toggle={toggle} counts={counts.folders} projectId={projectId} onDropItems={onDropItems} />+ ))}+ {q && !matches.length && <li className="px-2 py-2 text-[12px] text-muted-foreground">No folder with that name</li>}+ </ul>+ ) : (+ <button type="button" onClick={() => void newFolder()} className="mx-1 flex w-[calc(100%-0.5rem)] flex-col items-start gap-0.5 rounded-lg border border-dashed px-2.5 py-2 text-left text-[12px] text-muted-foreground hover:border-primary hover:bg-brand-faint hover:text-brand-text">+ <span className="flex items-center gap-1.5 font-medium">+ <FolderPlus className="size-3.5" /> New folder+ </span>+ Scenes, versions, deliverables — nest them as deep as you like.+ </button>+ )}+ </div>+ </nav>+ );+}diff --git a/src/components/cinema/hooks.ts b/src/components/cinema/hooks.tsnew file mode 100644index 00000000..6765bb8a--- /dev/null+++ b/src/components/cinema/hooks.ts@@ -0,0 +1,206 @@+"use client";++import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import type { CinemaFolder, CinemaGenerateInput, CinemaProject, CinemaTakeInfo, CinemaTile, DirectorMessage, DirectorSettings } from "@/lib/catalog/cinema";+import type { Generation } from "@/lib/catalog/types";++/** React Query hooks for /api/cinema/** (kept here, next to the workspace that uses them). */++export type CinemaGeneration = Generation & { folderId: string | null; tiles?: CinemaTile[]; take?: CinemaTakeInfo };++export interface ProjectView {+ project: CinemaProject;+ folders: CinemaFolder[];+ spentUsd: number;+ context: { higgsfield: boolean; cloudAllowed: boolean };+}++async function json<T>(res: Response): Promise<T> {+ if (res.status === 204) return undefined as T;+ const body = (await res.json().catch(() => ({}))) as T & { error?: string };+ if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);+ return body;+}++const send = async <T,>(url: string, method: string, body?: unknown) =>+ json<T>(await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }));++const active = (g: Generation) => g.status === "queued" || g.status === "running";++export function useCinemaProjects() {+ return useQuery({+ queryKey: ["cinema", "projects"],+ queryFn: async () => (await json<{ items: CinemaProject[] }>(await fetch("/api/cinema/projects"))).items,+ });+}++export function useCinemaProject(id: string) {+ return useQuery({+ queryKey: ["cinema", id],+ queryFn: async () => json<ProjectView>(await fetch(`/api/cinema/projects/${id}`)),+ retry: (n, e) => !/not found/i.test((e as Error).message) && n < 1,+ });+}++/** Every take in the project (folders are filtered in the browser); polls while anything renders. */+export function useCinemaItems(id: string) {+ return useQuery({+ queryKey: ["cinema", id, "items"],+ queryFn: async () => (await json<{ items: CinemaGeneration[] }>(await fetch(`/api/cinema/projects/${id}/items`))).items,+ refetchInterval: (q) => (q.state.data?.some(active) ? 1500 : false),+ });+}++/** "My Generations": every Cinema Studio generation, in any project. */+export function useStudioGenerations(id: string, enabled: boolean) {+ return useQuery({+ queryKey: ["cinema", "studio"],+ enabled,+ queryFn: async () => (await json<{ items: CinemaGeneration[] }>(await fetch(`/api/cinema/projects/${id}/items?scope=studio`))).items,+ refetchInterval: (q) => (q.state.data?.some(active) ? 1500 : false),+ });+}++export function useCreateProject() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (body: { name: string; description?: string | null; cover?: string | null; costCapUsd?: number | null }) => send<CinemaProject>("/api/cinema/projects", "POST", body),+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["cinema", "projects"] }),+ });+}++export interface ProjectPatch {+ name?: string;+ description?: string | null;+ cover?: string | null;+ costCapUsd?: number | null;+ director?: DirectorSettings;+ palettes?: CinemaProject["palettes"];+ brief?: { title?: string; body?: string };+ pinned?: boolean;+}++export function useUpdateProject(id: string) {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (patch: ProjectPatch) => send<CinemaProject>(`/api/cinema/projects/${id}`, "PATCH", patch),+ onMutate: (patch) => {+ qc.setQueryData<ProjectView>(["cinema", id], (old) =>+ old ? { ...old, project: { ...old.project, ...patch, brief: { ...old.project.brief, ...patch.brief } } as CinemaProject } : old,+ );+ },+ onSuccess: (project) => {+ qc.setQueryData<ProjectView>(["cinema", id], (old) => (old ? { ...old, project } : old));+ void qc.invalidateQueries({ queryKey: ["cinema", "projects"] });+ },+ });+}++export function useDeleteProject() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (id: string) => send<void>(`/api/cinema/projects/${id}`, "DELETE"),+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["cinema", "projects"] }),+ });+}++export function useFolderActions(projectId: string) {+ const qc = useQueryClient();+ const refresh = () => {+ void qc.invalidateQueries({ queryKey: ["cinema", projectId] });+ };+ return {+ create: async (body: { name: string; parentId?: string | null; color?: string | null }) => {+ const f = await send<CinemaFolder>(`/api/cinema/projects/${projectId}/folders`, "POST", body);+ refresh();+ return f;+ },+ update: async (folderId: string, patch: Partial<Pick<CinemaFolder, "name" | "color" | "pinned" | "parentId" | "position">>) => {+ qc.setQueryData<ProjectView>(["cinema", projectId], (old) => (old ? { ...old, folders: old.folders.map((f) => (f.id === folderId ? { ...f, ...patch } : f)) } : old));+ try {+ await send<CinemaFolder>(`/api/cinema/projects/${projectId}/folders/${folderId}`, "PATCH", patch);+ } finally {+ refresh();+ }+ },+ remove: async (folderId: string) => {+ await send<void>(`/api/cinema/projects/${projectId}/folders/${folderId}`, "DELETE");+ refresh();+ },+ };+}++export function useItemActions(projectId: string) {+ const qc = useQueryClient();+ const key = ["cinema", projectId, "items"];+ const patchLocal = (ids: string[], fn: (g: CinemaGeneration) => CinemaGeneration | null) =>+ qc.setQueryData<CinemaGeneration[]>(key, (old) => old?.map((g) => (ids.includes(g.id) ? fn(g) : g)).filter((g): g is CinemaGeneration => !!g));+ const settle = () => {+ void qc.invalidateQueries({ queryKey: key });+ void qc.invalidateQueries({ queryKey: ["cinema", "studio"] });+ void qc.invalidateQueries({ queryKey: ["generations"] });+ };+ return {+ move: async (ids: string[], folderId: string | null) => {+ patchLocal(ids, (g) => ({ ...g, folderId }));+ await send(`/api/cinema/projects/${projectId}/items`, "PATCH", { ids, folderId }).finally(settle);+ },+ favorite: async (ids: string[], favorite: boolean) => {+ patchLocal(ids, (g) => ({ ...g, favorite }));+ await send(`/api/cinema/projects/${projectId}/items`, "PATCH", { ids, favorite }).finally(settle);+ },+ remove: async (ids: string[]) => {+ patchLocal(ids, () => null);+ await send(`/api/cinema/projects/${projectId}/items`, "DELETE", { ids, deleteGenerations: true }).finally(settle);+ },+ cancel: async (g: Generation) => {+ patchLocal([g.id], (x) => ({ ...x, status: "canceled" }));+ await fetch(`/api/generations/${g.id}/cancel`, { method: "POST" }).finally(settle);+ },+ retry: async (generationId: string) => {+ await send(`/api/cinema/projects/${projectId}/items/${generationId}/retry`, "POST").finally(settle);+ },+ saveTiles: async (generationId: string, tiles: CinemaTile[]) => {+ await send(`/api/cinema/projects/${projectId}/items/${generationId}/tiles`, "PUT", { tiles });+ patchLocal([generationId], (g) => ({ ...g, tiles }));+ },+ };+}++export type GenerateBody = { input: Omit<CinemaGenerateInput, "brief">; folderId: string | null };++export function useCinemaGenerate(projectId: string) {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (body: GenerateBody) => send<{ items: Generation[]; plan: { notes: string[]; costUsd: number | null; outputs: number; modelId: string } }>(`/api/cinema/projects/${projectId}/generate`, "POST", body),+ onSuccess: (res, body) => {+ // New takes appear at once; polling takes over.+ qc.setQueryData<CinemaGeneration[]>(["cinema", projectId, "items"], (old) =>+ old ? [...res.items.map((g) => ({ ...g, folderId: body.folderId, take: { mode: body.input.mode, action: body.input.action, prompt: body.input.prompt, moves: body.input.moves } })), ...old] : old,+ );+ void qc.invalidateQueries({ queryKey: ["cinema", projectId] });+ },+ });+}++export function useDirectorChat(projectId: string) {+ const qc = useQueryClient();+ const key = ["cinema", projectId, "director"];+ const query = useQuery({+ queryKey: key,+ queryFn: async () => (await json<{ messages: DirectorMessage[] }>(await fetch(`/api/cinema/projects/${projectId}/director`))).messages,+ });+ const ask = useMutation({+ mutationFn: async (text: string) => (await send<{ messages: DirectorMessage[] }>(`/api/cinema/projects/${projectId}/director`, "POST", { text })).messages,+ onMutate: (text) => {+ qc.setQueryData<DirectorMessage[]>(key, (old) => [...(old ?? []), { id: `pending-${Date.now()}`, role: "user", text, createdAt: Date.now() }]);+ },+ onSuccess: (messages) => qc.setQueryData(key, messages),+ onError: () => void qc.invalidateQueries({ queryKey: key }),+ });+ const clear = async () => {+ qc.setQueryData(key, []);+ await send(`/api/cinema/projects/${projectId}/director`, "DELETE");+ };+ return { messages: query.data ?? [], loading: query.isLoading, ask, clear };+}diff --git a/src/components/cinema/media.ts b/src/components/cinema/media.tsnew file mode 100644index 00000000..af11a2a2--- /dev/null+++ b/src/components/cinema/media.ts@@ -0,0 +1,103 @@+"use client";++import { uploadFile } from "@/lib/api";+import { lineStats, tileRects } from "./grid-math";++/** Browser-side media helpers: durations, a take's first frame, cutting a grid sheet into tiles. */++const toBlob = (canvas: HTMLCanvasElement) => new Promise<Blob | null>((r) => canvas.toBlob(r, "image/png"));++/** Seconds of a video or audio file (NaN when the browser can't read it). */+export function mediaDuration(url: string, kind: "video" | "audio"): Promise<number> {+ return new Promise((resolve) => {+ const el = document.createElement(kind);+ const done = (v: number) => {+ el.removeAttribute("src");+ resolve(v);+ };+ const timer = setTimeout(() => done(NaN), 8000);+ el.preload = "metadata";+ el.onloadedmetadata = () => {+ clearTimeout(timer);+ done(Number.isFinite(el.duration) ? el.duration : NaN);+ };+ el.onerror = () => {+ clearTimeout(timer);+ done(NaN);+ };+ el.src = url;+ });+}++/**+ * The first frame of a video, uploaded as a PNG (prequels end on it; open-source edits restyle it).+ * Null when the browser can't decode the clip (the server then extracts it with fal's FFmpeg).+ */+export async function firstFrame(url: string): Promise<string | null> {+ try {+ const video = document.createElement("video");+ video.muted = true;+ video.playsInline = true;+ video.preload = "auto";+ const ready = new Promise<void>((resolve, reject) => {+ const t = setTimeout(() => reject(new Error("timeout")), 8000);+ video.onloadeddata = () => {+ video.currentTime = 0.04;+ };+ video.onseeked = () => {+ clearTimeout(t);+ resolve();+ };+ video.onerror = () => {+ clearTimeout(t);+ reject(new Error("decode"));+ };+ });+ video.src = url;+ await ready;+ if (!video.videoWidth) return null;+ const canvas = document.createElement("canvas");+ canvas.width = video.videoWidth;+ canvas.height = video.videoHeight;+ canvas.getContext("2d")!.drawImage(video, 0, 0);+ const blob = await toBlob(canvas);+ if (!blob) return null;+ return (await uploadFile(new File([blob], "first-frame.png", { type: "image/png" }))).url;+ } catch {+ return null;+ }+}++async function loadImage(url: string): Promise<HTMLImageElement> {+ const img = new Image();+ img.decoding = "async";+ img.src = url;+ await img.decode();+ return img;+}++/** Cut a contact sheet into rows × cols tiles (gutters detected, else an equal split) and upload each. */+export async function cutGrid(url: string, rows: number, cols: number): Promise<{ url: string; row: number; col: number }[]> {+ const img = await loadImage(url);+ const width = img.naturalWidth || 1024;+ const height = img.naturalHeight || 1024;+ const canvas = document.createElement("canvas");+ canvas.width = width;+ canvas.height = height;+ const ctx = canvas.getContext("2d", { willReadFrequently: true })!;+ ctx.drawImage(img, 0, 0, width, height);+ const data = ctx.getImageData(0, 0, width, height).data;+ const { rects } = tileRects(width, height, rows, cols, { x: lineStats(data, width, height, "x"), y: lineStats(data, width, height, "y") });+ const out: { url: string; row: number; col: number }[] = [];+ for (const r of rects) {+ const tile = document.createElement("canvas");+ tile.width = Math.max(1, r.w);+ tile.height = Math.max(1, r.h);+ tile.getContext("2d")!.drawImage(canvas, r.x, r.y, r.w, r.h, 0, 0, r.w, r.h);+ const blob = await toBlob(tile);+ if (!blob) throw new Error("Couldn't cut the sheet");+ const asset = await uploadFile(new File([blob], `tile-${r.row + 1}-${r.col + 1}.png`, { type: "image/png" }));+ out.push({ url: asset.url, row: r.row, col: r.col });+ }+ return out;+}diff --git a/src/components/cinema/palette-editor.tsx b/src/components/cinema/palette-editor.tsxnew file mode 100644index 00000000..ed4163d4--- /dev/null+++ b/src/components/cinema/palette-editor.tsx@@ -0,0 +1,354 @@+"use client";++import { ImageUp, Loader2, Plus, Shuffle, X } from "lucide-react";+import { useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Slider } from "@/components/ui/slider";+import { cn } from "@/lib/utils";+import { HARMONIES, harmonyPalette, hslToHex, kmeans, rgbToHex, type Harmony, type RGB } from "./color-math";++interface Point {+ /** 0–1 across the image. */+ x: number;+ y: number;+}++interface Sampled {+ url: string;+ width: number;+ height: number;+ data: Uint8ClampedArray;+}++const pixelAt = (img: Sampled, p: Point): RGB => {+ const x = Math.min(img.width - 1, Math.max(0, Math.round(p.x * (img.width - 1))));+ const y = Math.min(img.height - 1, Math.max(0, Math.round(p.y * (img.height - 1))));+ const o = (y * img.width + x) * 4;+ return [img.data[o], img.data[o + 1], img.data[o + 2]];+};++async function sampleImage(file: File): Promise<Sampled> {+ const url = URL.createObjectURL(file);+ const img = new Image();+ img.src = url;+ await img.decode();+ const scale = Math.min(1, 320 / Math.max(img.naturalWidth, img.naturalHeight));+ const width = Math.max(1, Math.round(img.naturalWidth * scale));+ const height = Math.max(1, Math.round(img.naturalHeight * scale));+ const canvas = document.createElement("canvas");+ canvas.width = width;+ canvas.height = height;+ const ctx = canvas.getContext("2d", { willReadFrequently: true })!;+ ctx.drawImage(img, 0, 0, width, height);+ return { url, width, height, data: ctx.getImageData(0, 0, width, height).data };+}++/** k-means centres, then a draggable sample point on the pixel closest to each one. */+function extract(img: Sampled, count: number): Point[] {+ const step = Math.max(1, Math.floor((img.width * img.height) / 5000));+ const px: RGB[] = [];+ const pos: Point[] = [];+ for (let i = 0; i < img.width * img.height; i += step) {+ const o = i * 4;+ px.push([img.data[o], img.data[o + 1], img.data[o + 2]]);+ pos.push({ x: (i % img.width) / Math.max(1, img.width - 1), y: Math.floor(i / img.width) / Math.max(1, img.height - 1) });+ }+ return kmeans(px, count).map((c) => {+ let best = 0;+ let bd = Infinity;+ px.forEach((p, i) => {+ const d = (p[0] - c.rgb[0]) ** 2 + (p[1] - c.rgb[1]) ** 2 + (p[2] - c.rgb[2]) ** 2;+ if (d < bd) {+ bd = d;+ best = i;+ }+ });+ return pos[best];+ });+}++function FromImage({ onColors }: { onColors: (hex: string[]) => void }) {+ const input = useRef<HTMLInputElement>(null);+ const box = useRef<HTMLDivElement>(null);+ const [img, setImg] = useState<Sampled | null>(null);+ const [points, setPoints] = useState<Point[]>([]);+ const [count, setCount] = useState(8);+ const [busy, setBusy] = useState(false);+ const [drag, setDrag] = useState<number | null>(null);++ const publish = (im: Sampled, ps: Point[]) => onColors(ps.map((p) => rgbToHex(pixelAt(im, p))));+ const load = async (f: File) => {+ if (!f.type.startsWith("image/")) return toast.error("Pick an image file");+ setBusy(true);+ try {+ const s = await sampleImage(f);+ const ps = extract(s, count);+ setImg(s);+ setPoints(ps);+ publish(s, ps);+ } catch {+ toast.error("Couldn't read that image. Try a PNG or JPEG.");+ } finally {+ setBusy(false);+ }+ };+ const move = (e: React.PointerEvent) => {+ if (drag === null || !img || !box.current) return;+ const r = box.current.getBoundingClientRect();+ const p = { x: Math.min(1, Math.max(0, (e.clientX - r.left) / r.width)), y: Math.min(1, Math.max(0, (e.clientY - r.top) / r.height)) };+ const next = points.map((q, i) => (i === drag ? p : q));+ setPoints(next);+ publish(img, next);+ };++ return (+ <div className="space-y-3">+ {!img ? (+ <button+ type="button"+ onClick={() => input.current?.click()}+ onDragOver={(e) => e.preventDefault()}+ onDrop={(e) => {+ e.preventDefault();+ const f = e.dataTransfer.files?.[0];+ if (f) void load(f);+ }}+ className="flex aspect-video w-full flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-border-strong text-[13px] text-muted-foreground transition-colors hover:border-primary hover:bg-brand-faint hover:text-brand-text"+ >+ {busy ? <Loader2 className="size-5 animate-spin" /> : <ImageUp className="size-5" />}+ {busy ? "Extracting colors from your image…" : "Drop an image or click to upload"}+ </button>+ ) : (+ <div+ ref={box}+ className="relative mx-auto max-h-[42vh] w-fit touch-none overflow-hidden rounded-xl"+ onPointerMove={move}+ onPointerUp={() => setDrag(null)}+ onPointerLeave={() => setDrag(null)}+ >+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={img.url} alt="" className="block max-h-[42vh] w-auto select-none" draggable={false} />+ {points.map((p, i) => (+ <button+ key={i}+ type="button"+ aria-label={`Sample point ${i + 1}`}+ onPointerDown={(e) => {+ e.preventDefault();+ (e.target as HTMLElement).setPointerCapture?.(e.pointerId);+ setDrag(i);+ }}+ className={cn("absolute size-5 -translate-x-1/2 -translate-y-1/2 cursor-grab rounded-full border-2 border-white shadow-strong active:cursor-grabbing", i === points.length - 1 && "size-6 ring-2 ring-primary")}+ style={{ left: `${p.x * 100}%`, top: `${p.y * 100}%`, background: rgbToHex(pixelAt(img, p)) }}+ />+ ))}+ </div>+ )}+ <div className="flex items-center gap-3">+ <span className="shrink-0 text-[12px] text-muted-foreground">Colours</span>+ <Slider+ value={[count]}+ min={3}+ max={12}+ step={1}+ onValueChange={([v]) => setCount(v)}+ onValueCommit={([v]) => {+ if (!img) return;+ const ps = extract(img, v);+ setPoints(ps);+ publish(img, ps);+ }}+ aria-label="Number of colours"+ />+ <span className="w-5 font-mono text-[12px]">{count}</span>+ {img && (+ <Button variant="ghost" size="sm" onClick={() => input.current?.click()}>+ Change image+ </Button>+ )}+ </div>+ {img && <p className="text-[11.5px] text-muted-foreground">Drag the sample points to pick colours; the largest ring is the main colour.</p>}+ <input+ ref={input}+ type="file"+ accept="image/*"+ hidden+ onChange={(e) => {+ const f = e.target.files?.[0];+ if (f) void load(f);+ e.target.value = "";+ }}+ />+ </div>+ );+}++const WHEEL_BASE = "#c0583a";++function ColorWheel({ onColors }: { onColors: (hex: string[]) => void }) {+ const [base, setBase] = useState(WHEEL_BASE);+ const [harmony, setHarmony] = useState<Harmony>("analogous");+ const [count, setCount] = useState(6);+ const update = (b = base, h = harmony, n = count) => onColors(harmonyPalette(b, h, n));+ return (+ <div className="space-y-3">+ <div className="flex items-center gap-2">+ <input type="color" value={base} onChange={(e) => {+ setBase(e.target.value);+ update(e.target.value);+ }} className="size-10 shrink-0 cursor-pointer rounded-lg border bg-transparent p-0.5" aria-label="Base colour" />+ <Input+ value={base}+ onChange={(e) => {+ const v = e.target.value.trim();+ setBase(v);+ if (/^#[0-9a-f]{6}$/i.test(v)) update(v);+ }}+ className="h-9 w-28 font-mono"+ aria-label="Base colour hex"+ />+ <Button+ variant="secondary"+ size="sm"+ onClick={() => {+ const b = hslToHex(Math.random() * 360, 0.35 + Math.random() * 0.45, 0.35 + Math.random() * 0.3);+ const h = HARMONIES[Math.floor(Math.random() * HARMONIES.length)].id;+ setBase(b);+ setHarmony(h);+ update(b, h);+ }}+ >+ <Shuffle /> Random+ </Button>+ </div>+ <div className="flex flex-wrap gap-1" role="radiogroup" aria-label="Harmony">+ {HARMONIES.map((h) => (+ <button+ key={h.id}+ type="button"+ role="radio"+ aria-checked={harmony === h.id}+ onClick={() => {+ setHarmony(h.id);+ update(base, h.id);+ }}+ className={cn("h-7 rounded-full px-2.5 text-[12px] font-medium", harmony === h.id ? "bg-primary text-primary-foreground" : "bg-secondary hover:bg-accent")}+ >+ {h.name}+ </button>+ ))}+ </div>+ <div className="flex items-center gap-3">+ <span className="shrink-0 text-[12px] text-muted-foreground">Colours</span>+ <Slider value={[count]} min={2} max={12} step={1} onValueChange={([v]) => {+ setCount(v);+ update(base, harmony, v);+ }} aria-label="Number of colours" />+ <span className="w-5 font-mono text-[12px]">{count}</span>+ </div>+ </div>+ );+}++/** New palette: from an image (k-means in the browser, draggable sample points) or a colour-wheel harmony. */+export function PaletteEditor({ open, onOpenChange, onSave }: { open: boolean; onOpenChange: (o: boolean) => void; onSave: (p: { name: string; hex: string[] }) => void }) {+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-[560px]">{open && <EditorBody onClose={() => onOpenChange(false)} onSave={onSave} />}</DialogContent>+ </Dialog>+ );+}++function EditorBody({ onClose, onSave }: { onClose: () => void; onSave: (p: { name: string; hex: string[] }) => void }) {+ const [tab, setTab] = useState<"image" | "wheel">("image");+ const [hex, setHex] = useState<string[]>([]);+ const [name, setName] = useState("");+ const [drag, setDrag] = useState<number | null>(null);+ const save = () => {+ if (!hex.length) return toast.error("Add some colours first");+ onSave({ name: name.trim() || `Palette ${new Date().toLocaleDateString(undefined, { month: "short", day: "numeric" })}`, hex });+ toast.success("Palette saved", { duration: 1500 });+ onClose();+ };+ return (+ <>+ <DialogHeader>+ <DialogTitle>New palette</DialogTitle>+ <DialogDescription>Pull colours from a frame you like, or build a harmony on the colour wheel.</DialogDescription>+ </DialogHeader>+ <div className="inline-flex w-fit rounded-full bg-muted p-0.5" role="tablist">+ {(+ [+ ["image", "From image"],+ ["wheel", "Color wheel"],+ ] as const+ ).map(([id, label]) => (+ <button+ key={id}+ role="tab"+ aria-selected={tab === id}+ onClick={() => {+ setTab(id);+ // The wheel starts from a harmony right away; the image tab waits for a picture.+ setHex(id === "wheel" ? harmonyPalette(WHEEL_BASE, "analogous", 6) : []);+ }} className={cn("h-7 rounded-full px-3 text-[12px] font-medium", tab === id ? "bg-background shadow-soft" : "text-muted-foreground")}>+ {label}+ </button>+ ))}+ </div>+ {tab === "image" ? <FromImage onColors={setHex} /> : <ColorWheel onColors={setHex} />}+ <div className="space-y-1.5">+ <p className="text-[12px] text-muted-foreground">{hex.length ? "Click a colour to change it, drag to reorder." : "Your colours appear here."}</p>+ <div className="flex flex-wrap items-center gap-1.5">+ {hex.map((h, i) => (+ <span+ key={`${h}-${i}`}+ draggable+ onDragStart={() => setDrag(i)}+ onDragOver={(e) => e.preventDefault()}+ onDrop={() => {+ if (drag === null || drag === i) return;+ const next = [...hex];+ const [x] = next.splice(drag, 1);+ next.splice(i, 0, x);+ setHex(next);+ setDrag(null);+ }}+ className="group/sw relative"+ >+ <label className="block size-9 cursor-pointer rounded-lg border shadow-soft" style={{ background: h }} title={h}>+ <input+ type="color"+ value={h}+ onChange={(e) => setHex(hex.map((x, j) => (j === i ? e.target.value : x)))}+ className="sr-only"+ aria-label={`Colour ${i + 1}`}+ />+ </label>+ <button+ type="button"+ onClick={() => setHex(hex.filter((_, j) => j !== i))}+ className="absolute -top-1.5 -right-1.5 grid size-4 place-items-center rounded-full bg-foreground text-background opacity-100 sm:opacity-0 sm:group-hover/sw:opacity-100"+ aria-label={`Remove colour ${i + 1}`}+ >+ <X className="size-2.5" />+ </button>+ </span>+ ))}+ {hex.length > 0 && hex.length < 12 && (+ <button type="button" onClick={() => setHex([...hex, hex[hex.length - 1]])} className="grid size-9 place-items-center rounded-lg border border-dashed text-muted-foreground hover:border-primary hover:text-brand-text" aria-label="Add colour">+ <Plus className="size-4" />+ </button>+ )}+ </div>+ </div>+ <DialogFooter className="gap-2 sm:items-center">+ <Input value={name} onChange={(e) => setName(e.target.value.slice(0, 60))} placeholder="Enter palette name" className="sm:max-w-60" onKeyDown={(e) => e.key === "Enter" && save()} />+ <Button onClick={save}>Save palette</Button>+ </DialogFooter>+ </>+ );+}diff --git a/src/components/cinema/project-settings.tsx b/src/components/cinema/project-settings.tsxnew file mode 100644index 00000000..1c13a29e--- /dev/null+++ b/src/components/cinema/project-settings.tsx@@ -0,0 +1,166 @@+"use client";++import { Loader2, Trash2 } from "lucide-react";+import { useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Textarea } from "@/components/ui/textarea";+import { MediaSlot, type SlotValue } from "@/components/studio/media-slot";+import type { CinemaProject } from "@/lib/catalog/cinema";+import { formatCost } from "@/lib/format";+import { useCreateProject, useDeleteProject, useUpdateProject } from "./hooks";++const MAX_DESC = 140;++interface FormProps {+ project?: CinemaProject;+ spentUsd?: number;+ onDone: (project?: CinemaProject) => void;+ onDeleted?: () => void;+}++/** New project / project settings: name, description (≤ 140), cover (16:9), cost cap. */+function ProjectForm({ project, spentUsd, onDone, onDeleted }: FormProps) {+ const create = useCreateProject();+ const update = useUpdateProject(project?.id ?? "");+ const del = useDeleteProject();+ const [name, setName] = useState(project?.name ?? "");+ const [description, setDescription] = useState(project?.description ?? "");+ const [cover, setCover] = useState<SlotValue | null>(project?.cover ? { ref: project.cover, preview: project.cover, kind: "image" } : null);+ const [cap, setCap] = useState(project?.costCapUsd != null ? String(project.costCapUsd) : "");+ const [confirm, setConfirm] = useState(false);+ const pending = create.isPending || update.isPending;+ const capValue = cap.trim() === "" ? null : Number(cap);+ const capBad = capValue !== null && (!Number.isFinite(capValue) || capValue < 0);++ const submit = () => {+ if (!name.trim()) return toast.error("Give the project a name");+ if (cover?.uploading) return toast.error("The cover is still uploading");+ if (capBad) return toast.error("The limit must be a positive amount in dollars");+ const body = { name: name.trim(), description: description.trim() || null, cover: cover?.ref || null, costCapUsd: capValue };+ if (project)+ update.mutate(body, {+ onSuccess: (p) => {+ toast.success("Saved", { duration: 1500 });+ onDone(p);+ },+ onError: (e) => toast.error((e as Error).message),+ });+ else create.mutate(body, { onSuccess: (p) => onDone(p), onError: (e) => toast.error((e as Error).message) });+ };++ return (+ <>+ <DialogHeader>+ <DialogTitle>{project ? "Project settings" : "New project"}</DialogTitle>+ <DialogDescription>Projects keep your generations, elements and chats together.</DialogDescription>+ </DialogHeader>+ <form+ className="space-y-4"+ onSubmit={(e) => {+ e.preventDefault();+ submit();+ }}+ >+ <div className="space-y-1.5">+ <Label htmlFor="cinema-name">Project name</Label>+ <Input id="cinema-name" value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. “Night Shift”" autoFocus maxLength={80} />+ </div>+ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <Label htmlFor="cinema-desc">Description</Label>+ <span className={`font-mono text-[11px] ${description.length > MAX_DESC - 10 ? "text-warning" : "text-muted-foreground"}`}>+ {description.length}/{MAX_DESC}+ </span>+ </div>+ <Textarea+ id="cinema-desc"+ value={description}+ onChange={(e) => setDescription(e.target.value.slice(0, MAX_DESC))}+ placeholder="A short summary shown on the project card"+ rows={2}+ className="resize-none"+ />+ </div>+ <div className="flex items-start gap-4">+ <div className="space-y-1.5">+ <Label>Cover</Label>+ <MediaSlot label="Cover · 16:9" kind="image" value={cover} onChange={setCover} size="lg" />+ </div>+ <div className="min-w-0 flex-1 space-y-1.5">+ <Label htmlFor="cinema-cap">Spending limit</Label>+ <div className="relative">+ <span className="pointer-events-none absolute top-1/2 left-2.5 -translate-y-1/2 text-[13px] text-muted-foreground">$</span>+ <Input id="cinema-cap" inputMode="decimal" value={cap} onChange={(e) => setCap(e.target.value.replace(/[^\d.]/g, ""))} placeholder="No limit" className="pl-6 font-mono" aria-invalid={capBad} />+ </div>+ <p className="text-[12px] leading-snug text-muted-foreground">+ An estimate guard: Generate stops before the project's estimated spend would pass it.+ {project && spentUsd != null ? ` Spent so far ≈ ${formatCost(spentUsd) || "$0"}.` : ""}+ </p>+ </div>+ </div>+ <DialogFooter className="items-center gap-2 sm:justify-between">+ {project && onDeleted ? (+ <Button type="button" variant="ghost" className="text-destructive hover:text-destructive" onClick={() => setConfirm(true)}>+ <Trash2 /> Delete project+ </Button>+ ) : (+ <span />+ )}+ <Button type="submit" disabled={pending}>+ {pending && <Loader2 className="animate-spin" />}+ {project ? "Save" : "Create project"}+ </Button>+ </DialogFooter>+ </form>+ {project && (+ <AlertDialog open={confirm} onOpenChange={setConfirm}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete “{project.name}”?</AlertDialogTitle>+ <AlertDialogDescription>Its folders, brief and Director chat are removed. The images and videos stay in your library.</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() =>+ del.mutate(project.id, {+ onSuccess: () => {+ toast("Project deleted");+ onDeleted?.();+ },+ onError: (e) => toast.error((e as Error).message),+ })+ }+ >+ Delete+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ )}+ </>+ );+}++export function ProjectDialog({ open, onOpenChange, ...props }: FormProps & { open: boolean; onOpenChange: (o: boolean) => void }) {+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-[520px]">{open && <ProjectForm {...props} />}</DialogContent>+ </Dialog>+ );+}diff --git a/src/components/cinema/projects-view.tsx b/src/components/cinema/projects-view.tsxnew file mode 100644index 00000000..a403f944--- /dev/null+++ b/src/components/cinema/projects-view.tsx@@ -0,0 +1,164 @@+"use client";++import { Clapperboard, Copy, ExternalLink, MoreHorizontal, Pin, PinOff, Plus, Settings2 } from "lucide-react";+import Link from "next/link";+import { useRouter } from "next/navigation";+import { useState } from "react";+import { toast } from "sonner";+import { PageShell } from "@/components/page-shell";+import { PageHeader } from "@/components/preset-gallery";+import { Button } from "@/components/ui/button";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Skeleton } from "@/components/ui/skeleton";+import type { CinemaProject } from "@/lib/catalog/cinema";+import { formatCost, timeAgo } from "@/lib/format";+import { cn } from "@/lib/utils";+import { useCinemaProjects, useUpdateProject } from "./hooks";+import { ProjectDialog } from "./project-settings";++/** A calm gradient for projects without a cover, stable per project. */+export function projectHue(id: string): number {+ let h = 0;+ for (const c of id) h = (h * 31 + c.charCodeAt(0)) % 360;+ return h;+}++function Cover({ project, className }: { project: CinemaProject; className?: string }) {+ const src = project.cover ?? project.stats?.cover;+ const hue = projectHue(project.id);+ if (src && /\.(mp4|webm|mov)(\?|$)/i.test(src))+ return <video src={`${src}#t=0.1`} muted playsInline preload="metadata" className={cn("size-full object-cover", className)} />;+ if (src)+ // eslint-disable-next-line @next/next/no-img-element+ return <img src={src} alt="" loading="lazy" className={cn("size-full object-cover", className)} />;+ return (+ <div className={cn("grid size-full place-items-center", className)} style={{ background: `linear-gradient(135deg, oklch(0.42 0.06 ${hue}), oklch(0.26 0.04 ${(hue + 40) % 360}))` }}>+ <Clapperboard className="size-7 text-white/70" />+ </div>+ );+}++function ProjectCard({ project, onSettings }: { project: CinemaProject; onSettings: () => void }) {+ const update = useUpdateProject(project.id);+ const href = `/cinema/${project.id}`;+ return (+ <div className="group/card relative animate-fade-up">+ <Link href={href} className="block rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <div className="relative aspect-video overflow-hidden rounded-xl bg-muted">+ <Cover project={project} className="transition-transform duration-300 ease-move group-hover/card:scale-[1.02]" />+ {project.pinned && (+ <span className="absolute top-2 left-2 grid size-7 place-items-center rounded-full bg-black/45 text-white backdrop-blur">+ <Pin className="size-3.5" />+ </span>+ )}+ </div>+ <div className="mt-2.5 min-w-0 px-0.5">+ <h3 className="truncate text-[15px] font-medium">{project.name}</h3>+ {project.description && <p className="mt-0.5 line-clamp-2 text-[13px] text-muted-foreground">{project.description}</p>}+ <p className="mt-1 text-[12px] text-muted-foreground">+ Updated {timeAgo(project.updatedAt)}+ {project.stats ? ` · ${project.stats.items} take${project.stats.items === 1 ? "" : "s"}` : ""}+ {project.stats?.spentUsd ? <span className="font-mono"> · ≈ {formatCost(project.stats.spentUsd)}</span> : null}+ {project.costCapUsd != null ? <span className="font-mono"> / {formatCost(project.costCapUsd) || "$0"}</span> : null}+ </p>+ </div>+ </Link>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ className="absolute top-2 right-2 grid size-8 place-items-center rounded-full bg-black/45 text-white opacity-100 backdrop-blur transition-opacity hover:bg-black/65 focus-visible:opacity-100 sm:opacity-0 sm:group-hover/card:opacity-100 data-[state=open]:opacity-100"+ aria-label={`${project.name} actions`}+ >+ <MoreHorizontal className="size-4" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => update.mutate({ pinned: !project.pinned })}>+ {project.pinned ? <PinOff /> : <Pin />} {project.pinned ? "Unpin" : "Pin"}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => window.open(href, "_blank")}>+ <ExternalLink /> Open in new tab+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => {+ void navigator.clipboard.writeText(new URL(href, window.location.origin).toString());+ toast("Link copied");+ }}+ >+ <Copy /> Copy link+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={onSettings}>+ <Settings2 /> Settings+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}++export function CinemaProjects() {+ const { data, isLoading } = useCinemaProjects();+ const router = useRouter();+ const [creating, setCreating] = useState(false);+ const [editing, setEditing] = useState<CinemaProject | null>(null);+ return (+ <PageShell wide>+ <PageHeader title="Cinema Studio" description="Direct films shot by shot: genre, camera, lens, palette and light, with characters and locations that stay the same.">+ <Button onClick={() => setCreating(true)}>+ <Plus /> New project+ </Button>+ </PageHeader>+ {isLoading ? (+ <div className="grid grid-cols-1 gap-x-5 gap-y-7 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">+ {Array.from({ length: 4 }, (_, i) => (+ <div key={i}>+ <Skeleton className="aspect-video rounded-xl" />+ <Skeleton className="mt-3 h-4 w-2/3" />+ <Skeleton className="mt-2 h-3 w-1/3" />+ </div>+ ))}+ </div>+ ) : !data?.length ? (+ <div className="mx-auto flex max-w-md flex-col items-center pt-[8vh] text-center">+ <div className="grid size-14 place-items-center rounded-2xl bg-brand-faint text-brand-text">+ <Clapperboard className="size-6" />+ </div>+ <h2 className="mt-5 font-heading text-[26px] leading-tight">Start your first production</h2>+ <p className="mt-2 text-[15px] text-muted-foreground">Projects keep your generations, elements, and chats together – create one to start.</p>+ <Button className="mt-6" onClick={() => setCreating(true)}>+ <Plus /> New project+ </Button>+ </div>+ ) : (+ <div className="grid grid-cols-1 gap-x-5 gap-y-7 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">+ {data.map((p) => (+ <ProjectCard key={p.id} project={p} onSettings={() => setEditing(p)} />+ ))}+ <button+ onClick={() => setCreating(true)}+ className="flex aspect-video flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-border-strong text-[13px] font-medium text-muted-foreground transition-colors hover:border-primary hover:bg-brand-faint hover:text-brand-text"+ >+ <Plus className="size-5" /> New project+ </button>+ </div>+ )}+ <ProjectDialog+ open={creating}+ onOpenChange={setCreating}+ onDone={(p) => {+ setCreating(false);+ if (p) router.push(`/cinema/${p.id}`);+ }}+ />+ <ProjectDialog+ open={!!editing}+ onOpenChange={(o) => !o && setEditing(null)}+ project={editing ?? undefined}+ spentUsd={editing?.stats?.spentUsd}+ onDone={() => setEditing(null)}+ onDeleted={() => setEditing(null)}+ />+ </PageShell>+ );+}diff --git a/src/components/cinema/prompt-bar.tsx b/src/components/cinema/prompt-bar.tsxnew file mode 100644index 00000000..06f04b73--- /dev/null+++ b/src/components/cinema/prompt-bar.tsx@@ -0,0 +1,677 @@+"use client";++import {+ ArrowLeftToLine,+ ArrowRightToLine,+ ArrowUp,+ AtSign,+ AudioLines,+ Check,+ ChevronDown,+ Clapperboard,+ Clock,+ Copy as CopyIcon,+ FileVideo,+ Grid2x2,+ ImageIcon,+ ImagePlus,+ Loader2,+ Lock,+ MapPin,+ Maximize,+ Plus,+ RectangleHorizontal,+ Sparkles,+ UserRoundPlus,+ Video,+ Volume2,+ VolumeX,+ Wand2,+ X,+} from "lucide-react";+import { nanoid } from "nanoid";+import { useEffect, useMemo, useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Kbd } from "@/components/ui/kbd";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Slider } from "@/components/ui/slider";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { PromptInput, ELEMENT_ICONS, type PromptInputHandle } from "@/components/studio/prompt-input";+import { ShotsEditor } from "@/components/studio/shots-editor";+import { uploadFile, useAssets, useStatus } from "@/lib/api";+import { getModel } from "@/lib/catalog";+import {+ BATCH,+ CINEMA_MODELS,+ DURATION,+ GRID_SIZES,+ GRID_TYPES,+ HIGGSFIELD_ONLY,+ IMAGE_ASPECTS,+ IMAGE_RESOLUTIONS,+ VIDEO_ASPECTS,+ VIDEO_RESOLUTIONS,+ checkReferences,+ planCinema,+ type DirectorSettings,+} from "@/lib/catalog/cinema";+import { findMentions, type StudioElement } from "@/lib/catalog/elements";+import type { Engine, MediaKind } from "@/lib/catalog/types";+import { formatCost } from "@/lib/format";+import { cn } from "@/lib/utils";+import { MoveChips, MovePicker } from "./camera-moves";+import { CameraChip, EmotionChip, FilmSetupChip, LightingChip, PaletteChip } from "./director-panel";+import { draftToInput, type BarAction, type CinemaDraft, type RefItem } from "./draft";+import { useCinemaGenerate } from "./hooks";+import { firstFrame, mediaDuration } from "./media";++const chip = "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium transition-colors";+const chipIdle = "bg-secondary text-secondary-foreground hover:bg-accent";+const chipOn = "bg-brand-faint text-brand-text hover:bg-brand-faint-hover";++function Segmented<T extends string>({ value, options, onChange, label }: { value: T; options: { id: T; label: string; icon?: typeof Video }[]; onChange: (v: T) => void; label: string }) {+ return (+ <div className="inline-flex h-8 shrink-0 rounded-full bg-muted p-0.5" role="radiogroup" aria-label={label}>+ {options.map((o) => (+ <button+ key={o.id}+ type="button"+ role="radio"+ aria-checked={value === o.id}+ onClick={() => onChange(o.id)}+ className={cn(+ "inline-flex items-center gap-1 rounded-full px-2.5 text-[12.5px] font-medium transition-colors",+ value === o.id ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground",+ )}+ >+ {o.icon && <o.icon className="size-3.5" />}+ {o.label}+ </button>+ ))}+ </div>+ );+}++function PickChip<T extends string | number>({ icon: Icon, label, value, options, onChange, format }: { icon: typeof Video; label: string; value: T; options: T[]; onChange: (v: T) => void; format?: (v: T) => string }) {+ const f = format ?? ((v: T) => String(v));+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button type="button" className={cn(chip, chipIdle)} aria-label={label}>+ <Icon className="size-3.5" />+ {f(value)}+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" side="top">+ <DropdownMenuLabel>{label}</DropdownMenuLabel>+ <DropdownMenuRadioGroup value={String(value)} onValueChange={(v) => onChange(options.find((o) => String(o) === v)!)}>+ {options.map((o) => (+ <DropdownMenuRadioItem key={String(o)} value={String(o)}>+ {f(o)}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++function DurationChip({ value, effective, onChange }: { value: number; effective?: number; onChange: (v: number) => void }) {+ return (+ <Popover>+ <PopoverTrigger asChild>+ <button type="button" className={cn(chip, chipIdle)} aria-label="Duration">+ <Clock className="size-3.5" />+ {effective && effective !== value ? (+ <span>+ <span className="text-muted-foreground line-through">{value}s</span> {effective}s+ </span>+ ) : (+ `${value}s`+ )}+ </button>+ </PopoverTrigger>+ <PopoverContent className="w-72 space-y-3 p-3" align="start" side="top" collisionPadding={12}>+ <div className="flex items-center justify-between">+ <p className="text-[13px] font-medium">Duration</p>+ <span className="font-mono text-[13px]">{value}s</span>+ </div>+ <Slider value={[value]} min={DURATION.min} max={DURATION.max} step={1} onValueChange={([v]) => onChange(v)} aria-label="Duration in seconds" />+ <div className="flex flex-wrap gap-1">+ {[4, 5, 8, 10, 15, 20, 30].map((d) => (+ <button key={d} type="button" onClick={() => onChange(d)} className={cn("h-6 rounded-full px-2 font-mono text-[11.5px]", value === d ? "bg-primary text-primary-foreground" : "bg-secondary hover:bg-accent")}>+ {d}s+ </button>+ ))}+ </div>+ {effective && effective !== value && <p className="text-[11.5px] text-muted-foreground">This model makes {effective}s clips — use Extend to make the scene longer.</p>}+ </PopoverContent>+ </Popover>+ );+}++function RefThumb({ r, index, startFrame, onRemove }: { r: RefItem; index: number; startFrame: boolean; onRemove: () => void }) {+ const kindLabel = r.kind === "image" ? `Image ${index + 1}` : r.kind === "video" ? `Video ${index + 1}` : `Audio ${index + 1}`;+ return (+ <div className="group/ref relative size-14 shrink-0 overflow-hidden rounded-xl border bg-muted" title={r.name ?? kindLabel}>+ {r.kind === "image" ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={r.preview} alt="" className="size-full object-cover" />+ ) : r.kind === "video" ? (+ <video src={`${r.preview}#t=0.1`} muted playsInline preload="metadata" className="size-full object-cover" />+ ) : (+ <span className="grid size-full place-items-center bg-brand-faint text-brand-text">+ <AudioLines className="size-5" />+ </span>+ )}+ <span className="absolute inset-x-0 bottom-0 truncate bg-gradient-to-t from-black/70 to-transparent px-1 pt-2 pb-0.5 text-[9.5px] font-medium text-white">+ {startFrame ? "Start frame" : kindLabel}+ {r.duration && Number.isFinite(r.duration) ? ` · ${Math.round(r.duration)}s` : ""}+ </span>+ {r.uploading && (+ <span className="absolute inset-0 grid place-items-center bg-background/60">+ <Loader2 className="size-4 animate-spin" />+ </span>+ )}+ <button type="button" onClick={onRemove} className="absolute top-0.5 right-0.5 grid size-5 place-items-center rounded-full bg-foreground/80 text-background" aria-label={`Remove ${kindLabel}`}>+ <X className="size-3" />+ </button>+ </div>+ );+}++const kindOf = (f: File): MediaKind => (f.type.startsWith("video/") ? "video" : f.type.startsWith("audio/") ? "audio" : "image");++/** Upload files into the reference tray (preview first, then the server URL; durations measured for clips). */+export function useAddRefs(setDraft: (fn: (d: CinemaDraft) => Partial<CinemaDraft>) => void) {+ return (files: FileList | File[]) => {+ for (const f of [...files]) {+ if (f.size > 200 * 1024 * 1024) {+ toast.error("That file's over 200 MB. Try a smaller one.");+ continue;+ }+ const id = nanoid(6);+ const kind = kindOf(f);+ const preview = URL.createObjectURL(f);+ setDraft((d) => ({ refs: [...d.refs, { id, ref: "", preview, kind, name: f.name, uploading: true }] }));+ if (kind === "video" || kind === "audio") void mediaDuration(preview, kind).then((duration) => setDraft((d) => ({ refs: d.refs.map((r) => (r.id === id ? { ...r, duration } : r)) })));+ uploadFile(f)+ .then((a) => setDraft((d) => ({ refs: d.refs.map((r) => (r.id === id ? { ...r, ref: a.url, preview: a.url, uploading: false } : r)) })))+ .catch((e) => {+ setDraft((d) => ({ refs: d.refs.filter((r) => r.id !== id) }));+ toast.error((e as Error).message || "Upload failed. Please try again.");+ });+ }+ };+}++function AddRef({ onFiles, onPick }: { onFiles: (f: FileList) => void; onPick: (r: RefItem) => void }) {+ const input = useRef<HTMLInputElement>(null);+ const [open, setOpen] = useState(false);+ const assets = useAssets(undefined, undefined);+ return (+ <Popover open={open} onOpenChange={setOpen}>+ <Tooltip>+ <TooltipTrigger asChild>+ <PopoverTrigger asChild>+ <button+ type="button"+ className="flex size-14 shrink-0 flex-col items-center justify-center gap-0.5 rounded-xl border border-dashed border-border-strong text-muted-foreground transition-colors hover:border-primary hover:bg-brand-faint hover:text-brand-text"+ aria-label="Add references"+ >+ <Plus className="size-4" />+ <span className="text-[10px] font-medium">Add</span>+ </button>+ </PopoverTrigger>+ </TooltipTrigger>+ <TooltipContent>Images, videos or audio as references · drop or paste anywhere</TooltipContent>+ </Tooltip>+ <PopoverContent className="w-[min(92vw,360px)] p-2" align="start" side="top" collisionPadding={12}>+ <button+ type="button"+ onClick={() => input.current?.click()}+ className="flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left text-[13px] font-medium hover:bg-accent"+ >+ <ImagePlus className="size-4" /> Upload images, videos or audio+ </button>+ <p className="px-2 pt-2 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">From your library</p>+ <div className="grid max-h-56 grid-cols-4 gap-1 overflow-y-auto">+ {(assets.data ?? []).slice(0, 40).map((a) => (+ <button+ key={a.id}+ type="button"+ onClick={() => {+ onPick({ id: nanoid(6), ref: a.url, preview: a.url, kind: a.kind, name: a.name ?? undefined });+ setOpen(false);+ }}+ className="relative aspect-square overflow-hidden rounded-md bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring"+ aria-label={`Use ${a.name ?? a.kind}`}+ >+ {a.kind === "image" ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={a.url} alt="" loading="lazy" className="size-full object-cover" />+ ) : a.kind === "video" ? (+ <video src={`${a.url}#t=0.1`} muted preload="metadata" className="size-full object-cover" />+ ) : (+ <AudioLines className="m-auto size-4 text-muted-foreground" />+ )}+ </button>+ ))}+ {!assets.isLoading && !assets.data?.length && <p className="col-span-4 px-2 py-3 text-[12px] text-muted-foreground">Nothing in your library yet.</p>}+ </div>+ <input+ ref={input}+ type="file"+ multiple+ accept="image/png,image/jpeg,image/webp,video/mp4,video/webm,video/quicktime,audio/mpeg,audio/wav,audio/x-wav,audio/ogg,audio/mp4"+ hidden+ onChange={(e) => {+ if (e.target.files?.length) onFiles(e.target.files);+ e.target.value = "";+ setOpen(false);+ }}+ />+ </PopoverContent>+ </Popover>+ );+}++export interface PromptBarProps {+ projectId: string;+ folderId: string | null;+ engine: Engine;+ draft: CinemaDraft;+ setDraft: (patch: Partial<CinemaDraft> | ((d: CinemaDraft) => Partial<CinemaDraft>)) => void;+ settings: DirectorSettings;+ onSettings: (patch: Partial<DirectorSettings>) => void;+ palettes: { name: string; hex: string[] }[];+ onPalettes: (p: { name: string; hex: string[] }[]) => void;+ context: { higgsfield: boolean; cloudAllowed: boolean };+ brief: string;+ spentUsd: number;+ costCapUsd: number | null;+ elements: StudioElement[];+ promptRef: React.RefObject<PromptInputHandle | null>;+ onCast: () => void;+ onLocation: () => void;+}++const ACTIONS: { id: BarAction; label: string; icon: typeof Video; hint: string }[] = [+ { id: "generate", label: "New take", icon: Sparkles, hint: "Use the selected take only as context" },+ { id: "extend-forward", label: "Extend", icon: ArrowRightToLine, hint: "Sequel: continue the take forward" },+ { id: "extend-backward", label: "Prequel", icon: ArrowLeftToLine, hint: "What happened just before the take" },+ { id: "edit", label: "Edit", icon: Wand2, hint: "Change something in the take (object, face, weather)" },+];++export function PromptBar(props: PromptBarProps) {+ const { projectId, folderId, engine, draft, setDraft, settings, onSettings, context, brief, spentUsd, costCapUsd, elements, promptRef } = props;+ const generate = useCinemaGenerate(projectId);+ const status = useStatus().data;+ const [movesOpen, setMovesOpen] = useState(false);+ const [preparing, setPreparing] = useState(false);+ const addRefs = useAddRefs((fn) => setDraft(fn));+ const input = useMemo(() => draftToInput(draft, engine, settings), [draft, engine, settings]);+ const plan = useMemo(() => planCinema({ ...input, brief }, context), [input, brief, context]);+ const model = plan.model;+ const mentions = useMemo(() => findMentions(draft.prompt, elements), [draft.prompt, elements]);+ const characters = mentions.filter((e) => e.kind === "character");+ const refCheck = checkReferences({+ images: draft.refs.filter((r) => r.kind === "image").length,+ videos: draft.refs.filter((r) => r.kind === "video").map((r) => r.duration ?? NaN),+ audios: draft.refs.filter((r) => r.kind === "audio").map((r) => r.duration ?? NaN),+ elements: mentions.length,+ });+ const demo = !!status && status.demoMode !== "off" && !model.routes.some((r) => status.providers[r.provider]?.configured);+ const cost = demo ? 0 : plan.costUsd;+ const overCap = costCapUsd != null && cost != null && cost > 0 && spentUsd + cost > costCapUsd + 1e-9;+ const uploading = draft.refs.some((r) => r.uploading);+ const blocker = uploading+ ? "Uploading…"+ : refCheck ?? plan.blocker ?? (overCap ? `Over the project's ${formatCost(costCapUsd)} limit (≈ ${formatCost(spentUsd)} spent) — raise it in project settings` : undefined);+ const video = draft.mode === "video";+ const action = input.action;+ const busy = generate.isPending || preparing;+ const effectiveDuration = plan.steps.find((s) => s.key === "main")?.request.params?.duration;++ const submit = async () => {+ if (busy) return;+ if (blocker) {+ toast.error(blocker);+ return;+ }+ let frame: string | undefined;+ const src = draft.source;+ if (src?.kind === "video" && (action === "extend-backward" || (action === "edit" && engine === "open"))) {+ setPreparing(true);+ frame = (await firstFrame(src.url)) ?? undefined;+ setPreparing(false);+ }+ generate.mutate(+ { input: draftToInput(draft, engine, settings, frame), folderId },+ {+ onSuccess: (r) => toast.success(r.items.length > 1 ? `${r.items.length} jobs queued` : "Queued", { duration: 1500 }),+ onError: (e) => toast.error((e as Error).message),+ },+ );+ };+ const submitRef = useRef(submit);+ useEffect(() => {+ submitRef.current = submit;+ });+ // ⌘/Ctrl+Enter generates from anywhere in the workspace (the prompt's own Enter already does).+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (e.defaultPrevented || e.key !== "Enter" || !(e.metaKey || e.ctrlKey)) return;+ e.preventDefault();+ void submitRef.current();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, []);++ const onPrompt = (v: string) => {+ // Typing "#" opens the camera-move picker (the # itself doesn't stay in the prompt).+ const el = document.activeElement as HTMLTextAreaElement | null;+ const caret = el?.tagName === "TEXTAREA" ? (el.selectionStart ?? v.length) : v.length;+ if (video && v.length === draft.prompt.length + 1 && v[caret - 1] === "#" && (caret === 1 || /\s/.test(v[caret - 2]))) {+ setDraft({ prompt: v.slice(0, caret - 1) + v.slice(caret) });+ setMovesOpen(true);+ return;+ }+ setDraft({ prompt: v });+ };++ const modelKey = `${draft.mode}:${engine}` as const;+ const modelList = CINEMA_MODELS[draft.mode][engine];+ const pickable = action === "generate" && !(draft.mode === "image" && draft.imageTool === "grid");+ const placeholder = video+ ? action === "edit"+ ? "Describe the change, e.g. “make it snow”, “replace the car with a horse”"+ : action === "extend-forward"+ ? "What happens next? (optional)"+ : action === "extend-backward"+ ? "What happened just before? (optional)"+ : "Describe your scene – use @ to add characters & locations, # for camera moves"+ : draft.imageTool === "grid"+ ? "Describe the scene – the whole grid shares it"+ : "Describe your still – use @ to add characters & locations";++ return (+ <div+ className="group/composer w-full rounded-[20px] border bg-background p-2.5 shadow-normal transition-[border-color,box-shadow] focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint sm:rounded-composer"+ onPaste={(e) => {+ const files = [...e.clipboardData.files];+ if (files.length) {+ e.preventDefault();+ addRefs(files);+ }+ }}+ >+ {/* Selected take: extend forward / backward or edit it */}+ {video && draft.source?.kind === "video" && (+ <div className="flex flex-wrap items-center gap-2 px-1 pb-2">+ <span className="relative h-9 w-14 shrink-0 overflow-hidden rounded-lg bg-muted">+ <video src={`${draft.source.url}#t=0.1`} muted playsInline preload="metadata" className="size-full object-cover" />+ </span>+ <span className="min-w-0 text-[12px] text-muted-foreground">+ <span className="block truncate font-medium text-foreground">{draft.source.label}</span>+ Selected take+ </span>+ <div className="scrollbar-none flex max-w-full gap-0.5 overflow-x-auto rounded-full bg-muted p-0.5" role="radiogroup" aria-label="What to do with the take">+ {ACTIONS.map((a) => (+ <Tooltip key={a.id}>+ <TooltipTrigger asChild>+ <button+ type="button"+ role="radio"+ aria-checked={draft.action === a.id}+ onClick={() => setDraft({ action: a.id })}+ className={cn(+ "inline-flex h-7 shrink-0 items-center gap-1 rounded-full px-2.5 text-[12px] font-medium",+ draft.action === a.id ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground",+ )}+ >+ <a.icon className="size-3.5" /> {a.label}+ </button>+ </TooltipTrigger>+ <TooltipContent>{a.hint}</TooltipContent>+ </Tooltip>+ ))}+ </div>+ <button type="button" onClick={() => setDraft({ source: null, action: "generate" })} className="ml-auto grid size-7 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Clear the selected take">+ <X className="size-3.5" />+ </button>+ </div>+ )}++ {/* References */}+ <div className="scrollbar-none flex items-center gap-2 overflow-x-auto px-1 pt-0.5 pb-2">+ {(() => {+ const n: Record<string, number> = {};+ return draft.refs.map((r) => {+ const i = (n[r.kind] = (n[r.kind] ?? -1) + 1);+ return <RefThumb key={r.id} r={r} index={i} startFrame={r.kind === "image" && i === 0 && video && action === "generate"} onRemove={() => setDraft((d) => ({ refs: d.refs.filter((x) => x.id !== r.id) }))} />;+ });+ })()}+ <AddRef onFiles={addRefs} onPick={(r) => setDraft((d) => ({ refs: [...d.refs, r] }))} />+ {!draft.refs.length && <span className="text-[12px] text-subtle-foreground">Start frame, references, clips or audio — or @ a character</span>}+ </div>++ {video && <MoveChips moves={draft.moves} onChange={(moves) => setDraft({ moves })} />}++ <PromptInput ref={promptRef} value={draft.prompt} onChange={onPrompt} onSubmit={() => void submit()} placeholder={placeholder} elements={elements} />++ {video && draft.multiShot.mode === "manual" && (+ <ShotsEditor+ model={model}+ shots={draft.multiShot.shots.length ? draft.multiShot.shots : [{ prompt: "", duration: 3 }]}+ onChange={(shots) => setDraft({ multiShot: shots ? { mode: "manual", shots } : { mode: "off", shots: [] } })}+ />+ )}++ {mentions.length > 0 && (+ <div className="flex flex-wrap items-center gap-1.5 px-2 pb-2">+ {mentions.map((el) => {+ const Icon = ELEMENT_ICONS[el.kind];+ const emo = settings.emotions?.[el.handle.toLowerCase()];+ return (+ <span key={el.id} className="inline-flex h-7 items-center gap-1.5 rounded-full border bg-background pr-2.5 pl-0.5 text-[12px] font-medium">+ <span className="grid size-6 place-items-center overflow-hidden rounded-full bg-muted">+ {el.references[0] ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={el.references[0]} alt="" className="size-full object-cover" />+ ) : (+ <Icon className="size-3.5" />+ )}+ </span>+ {el.name}+ {emo && <span className="text-[11px] text-muted-foreground">· {emo.family}</span>}+ </span>+ );+ })}+ </div>+ )}++ {/* Director's Panel */}+ <div className="scrollbar-none flex items-center gap-1.5 overflow-x-auto px-0.5 pb-1.5 sm:flex-wrap sm:overflow-visible">+ <FilmSetupChip settings={settings} onChange={onSettings} mode={draft.mode} />+ <CameraChip settings={settings} onChange={onSettings} mode={draft.mode} engine={engine} moves={draft.moves} onMovesChange={(moves) => setDraft({ moves })} />+ <PaletteChip settings={settings} onChange={onSettings} engine={engine} saved={props.palettes} onSave={props.onPalettes} />+ <LightingChip settings={settings} onChange={onSettings} />+ <EmotionChip settings={settings} onChange={onSettings} characters={characters} />+ </div>++ {/* Generation settings */}+ <div className="flex items-end gap-2">+ <div className="scrollbar-none flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto sm:flex-wrap sm:overflow-visible">+ <Segmented+ label="Mode"+ value={draft.mode}+ onChange={(mode) => setDraft({ mode })}+ options={[+ { id: "video", label: "Video", icon: Video },+ { id: "image", label: "Image", icon: ImageIcon },+ ]}+ />+ {!video && (+ <Segmented+ label="Image tool"+ value={draft.imageTool}+ onChange={(imageTool) => setDraft({ imageTool })}+ options={[+ { id: "still", label: "Still" },+ { id: "grid", label: "Grid", icon: Grid2x2 },+ ]}+ />+ )}+ {!video && draft.imageTool === "grid" && (+ <>+ <PickChip icon={Grid2x2} label="Grid size" value={draft.grid.size} options={GRID_SIZES.map((g) => g.id)} onChange={(size) => setDraft((d) => ({ grid: { ...d.grid, size } }))} format={(v) => GRID_SIZES.find((g) => g.id === v)!.name} />+ <PickChip icon={Clapperboard} label="Grid type" value={draft.grid.type} options={GRID_TYPES.map((g) => g.id)} onChange={(type) => setDraft((d) => ({ grid: { ...d.grid, type } }))} format={(v) => GRID_TYPES.find((g) => g.id === v)!.name} />+ </>+ )}++ {/* Model */}+ <DropdownMenu>+ <DropdownMenuTrigger asChild disabled={!pickable}>+ <button type="button" className={cn(chip, chipIdle, "max-w-[220px] disabled:opacity-100")} aria-label="Model">+ <Sparkles className="size-3.5 shrink-0" />+ <span className="truncate">{model.name}</span>+ {pickable && <ChevronDown className="size-3 shrink-0 opacity-60" />}+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" side="top" className="w-72">+ <DropdownMenuLabel>{engine === "open" ? "Open-source models" : "Cloud models"}</DropdownMenuLabel>+ {modelList.map((id) => {+ const m = getModel(id);+ if (!m) return null;+ const locked = HIGGSFIELD_ONLY.has(id) && !context.higgsfield;+ const sel = model.id === id;+ return (+ <DropdownMenuItem key={id} disabled={locked} onClick={() => setDraft((d) => ({ models: { ...d.models, [modelKey]: id } }))} className="items-start">+ <span className="mt-0.5 w-4">{sel && <Check className="size-3.5" />}</span>+ <span className="min-w-0 flex-1">+ <span className="flex items-center gap-1 text-[13px] font-medium">+ {m.name} {locked && <Lock className="size-3" />}+ </span>+ <span className="block text-[11.5px] leading-snug text-muted-foreground">{locked ? "Needs a Higgsfield key (Settings)" : m.tagline}</span>+ </span>+ </DropdownMenuItem>+ );+ })}+ <DropdownMenuSeparator />+ <p className="px-2 py-1.5 text-[11px] leading-snug text-muted-foreground">+ {engine === "open" ? "The Director is written into the prompt; camera moves use camera LoRAs or Wan Fun Camera where they exist." : "Cinema Studio 4.0 reads the Director natively; the others get it written into the prompt."}+ </p>+ </DropdownMenuContent>+ </DropdownMenu>++ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" onClick={() => promptRef.current?.startMention()} className={cn("grid size-8 shrink-0 place-items-center rounded-full", chipIdle)} aria-label="Add an element">+ <AtSign className="size-3.5" />+ </button>+ </TooltipTrigger>+ <TooltipContent>Add a character, location or prop · type @</TooltipContent>+ </Tooltip>+ {video && (+ <MovePicker+ open={movesOpen}+ onOpenChange={(o) => {+ setMovesOpen(o);+ if (!o) requestAnimationFrame(() => promptRef.current?.focus());+ }}+ engine={engine}+ selected={draft.moves}+ onPick={(slug) => setDraft((d) => ({ moves: [...d.moves, slug] }))}+ />+ )}++ <PickChip icon={RectangleHorizontal} label="Aspect ratio" value={draft.aspect[draft.mode]} options={video ? VIDEO_ASPECTS : IMAGE_ASPECTS} onChange={(v) => setDraft((d) => ({ aspect: { ...d.aspect, [d.mode]: v } }))} />+ {video && action !== "edit" && <DurationChip value={draft.duration} effective={effectiveDuration} onChange={(duration) => setDraft({ duration })} />}+ <PickChip+ icon={Maximize}+ label="Resolution"+ value={draft.resolution[draft.mode]}+ options={video ? VIDEO_RESOLUTIONS : IMAGE_RESOLUTIONS}+ onChange={(v) => setDraft((d) => ({ resolution: { ...d.resolution, [d.mode]: v } }))}+ />+ {action === "generate" && !(draft.mode === "image" && draft.imageTool === "grid") && (+ <PickChip icon={CopyIcon} label={video ? "Takes" : "Images"} value={draft.batch} options={Array.from({ length: BATCH.max }, (_, i) => i + 1)} onChange={(batch) => setDraft({ batch })} format={(v) => `×${v}`} />+ )}+ {video && model.options.audio === true && (+ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" onClick={() => setDraft((d) => ({ audio: !d.audio }))} className={cn(chip, draft.audio ? chipOn : chipIdle)} aria-pressed={draft.audio} aria-label="Audio">+ {draft.audio ? <Volume2 className="size-3.5" /> : <VolumeX className="size-3.5" />} Audio+ </button>+ </TooltipTrigger>+ <TooltipContent>{draft.audio ? "This generation will include generated audio." : "Silent take"}</TooltipContent>+ </Tooltip>+ )}+ {video && action === "generate" && (+ <PickChip+ icon={FileVideo}+ label="Multi-shot"+ value={draft.multiShot.mode}+ options={["off", "auto", "manual"]}+ onChange={(mode) => setDraft((d) => ({ multiShot: { mode, shots: mode === "manual" && !d.multiShot.shots.length ? [{ prompt: "", duration: 3 }, { prompt: "", duration: 3 }] : d.multiShot.shots } }))}+ format={(v) => (v === "off" ? "Single shot" : v === "auto" ? "Multi-shot · Auto" : "Multi-shot · Manual")}+ />+ )}+ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" onClick={props.onCast} className={cn(chip, chipIdle)} aria-label="Soul Cast: build a character">+ <UserRoundPlus className="size-3.5" /> Cast+ </button>+ </TooltipTrigger>+ <TooltipContent>Soul Cast: build an AI actor and save it as a character</TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" onClick={props.onLocation} className={cn(chip, chipIdle)} aria-label="Soul Location: build a location">+ <MapPin className="size-3.5" /> Location+ </button>+ </TooltipTrigger>+ <TooltipContent>Soul Location: keep every scene in the same world</TooltipContent>+ </Tooltip>+ </div>+ <span className={cn("hidden shrink-0 font-mono text-[12px] sm:inline", overCap ? "text-destructive" : "text-muted-foreground")}>+ {demo ? "Demo · free" : cost === 0 ? "Free" : cost != null ? `≈ ${formatCost(cost)}` : ""}+ </span>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ size="icon"+ onClick={() => void submit()}+ disabled={busy}+ aria-label="Generate"+ className={cn("size-10 shrink-0 rounded-full", blocker && "bg-muted text-subtle-foreground hover:bg-muted")}+ >+ {busy ? <Loader2 className="size-4 animate-spin" /> : <ArrowUp className="size-4" />}+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ {blocker ?? (+ <span className="flex items-center gap-1.5">+ Generate{plan.outputs > 1 ? ` ${plan.outputs}` : ""} <Kbd>⌘</Kbd>+ <Kbd>↵</Kbd>+ </span>+ )}+ </TooltipContent>+ </Tooltip>+ </div>+ {(plan.notes.length > 0 || preparing) && (+ <p className="px-2 pt-1.5 text-[11.5px] leading-snug text-muted-foreground">+ {preparing ? "Reading the take's first frame…" : plan.notes.slice(0, 3).join(" · ")}+ </p>+ )}+ {(blocker && !uploading && (refCheck || overCap)) && <p className="px-2 pt-1 text-[11.5px] text-destructive">{blocker}</p>}+ <span className="sr-only" aria-live="polite">+ {cost != null ? `Estimated cost ${demo ? "free in demo mode" : formatCost(cost)}` : ""}+ </span>+ </div>+ );+}diff --git a/src/components/cinema/side-panel.tsx b/src/components/cinema/side-panel.tsxnew file mode 100644index 00000000..65ffbf0f--- /dev/null+++ b/src/components/cinema/side-panel.tsx@@ -0,0 +1,275 @@+"use client";++import { ArrowUp, Bot, Check, ClipboardPaste, FileText, Loader2, Sparkles, Trash2, X } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { directorSummary, moveBySlug, type CinemaProject, type DirectorMessage, type DirectorSettings, type DirectorShot } from "@/lib/catalog/cinema";+import { cn } from "@/lib/utils";+import { useDirectorChat, useUpdateProject } from "./hooks";++const SUGGESTIONS = ["Write a script", "Generate an 8-shot storyboard for a sci-fi chase scene", "Create a 15-second cinematic perfume commercial"];++function ShotCard({ shot, onLoad }: { shot: DirectorShot; onLoad: (s: DirectorShot) => void }) {+ const look = directorSummary(shot.settings as DirectorSettings);+ return (+ <div className="space-y-1.5 rounded-xl border bg-background p-2.5">+ <div className="flex items-baseline justify-between gap-2">+ <p className="text-[13px] font-medium">{shot.title}</p>+ <span className="shrink-0 font-mono text-[11px] text-muted-foreground">{shot.duration}s</span>+ </div>+ <p className="text-[12.5px] leading-snug text-muted-foreground">{shot.prompt}</p>+ {(shot.moves.length > 0 || look.length > 0) && (+ <div className="flex flex-wrap gap-1">+ {shot.moves.map((m, i) => (+ <span key={`${m}-${i}`} className="rounded-full bg-brand-faint px-1.5 py-px text-[10.5px] font-medium text-brand-text">+ #{moveBySlug(m)?.name ?? m}+ </span>+ ))}+ {look.slice(0, 5).map((l) => (+ <span key={l} className="rounded-full bg-secondary px-1.5 py-px text-[10.5px] text-muted-foreground">+ {l}+ </span>+ ))}+ </div>+ )}+ <Button size="sm" variant="secondary" className="w-full" onClick={() => onLoad(shot)}>+ <ClipboardPaste /> Load into prompt bar+ </Button>+ </div>+ );+}++function Message({ m, onLoad, onBrief }: { m: DirectorMessage; onLoad: (s: DirectorShot) => void; onBrief: (b: string) => void }) {+ if (m.role === "user")+ return (+ <div className="flex justify-end">+ <p className="max-w-[85%] rounded-2xl rounded-br-md bg-secondary px-3 py-2 text-[13.5px] leading-snug whitespace-pre-wrap">{m.text}</p>+ </div>+ );+ return (+ <div className="space-y-2">+ <div className="flex items-start gap-2">+ <span className="mt-0.5 grid size-6 shrink-0 place-items-center rounded-full bg-brand-faint text-brand-text">+ <Bot className="size-3.5" />+ </span>+ <div className="min-w-0 flex-1">+ <p className="text-[13.5px] leading-relaxed whitespace-pre-wrap">{m.text}</p>+ {m.source === "offline" && <p className="mt-0.5 text-[11px] text-muted-foreground">Offline breakdown — connect Claude or Ollama in Settings for a smarter Director.</p>}+ </div>+ </div>+ {m.brief && (+ <div className="ml-8 space-y-2 rounded-xl border bg-background p-2.5">+ <p className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">Proposed brief</p>+ <p className="text-[12.5px] leading-snug whitespace-pre-wrap">{m.brief}</p>+ <Button size="sm" variant="secondary" className="w-full" onClick={() => onBrief(m.brief!)}>+ <FileText /> Use as project brief+ </Button>+ </div>+ )}+ {m.shots?.length ? (+ <div className="ml-8 space-y-2">+ {m.shots.map((s, i) => (+ <ShotCard key={i} shot={s} onLoad={onLoad} />+ ))}+ </div>+ ) : null}+ </div>+ );+}++function DirectorChat({ projectId, onLoadShot, onBrief, promptText }: { projectId: string; onLoadShot: (s: DirectorShot) => void; onBrief: (b: string) => void; promptText: string }) {+ const { messages, ask, clear } = useDirectorChat(projectId);+ const [text, setText] = useState("");+ const end = useRef<HTMLDivElement>(null);+ useEffect(() => {+ end.current?.scrollIntoView({ block: "end" });+ }, [messages.length, ask.isPending]);+ const send = (t = text) => {+ const v = t.trim();+ if (!v || ask.isPending) return;+ setText("");+ ask.mutate(v, { onError: (e) => toast.error((e as Error).message) });+ };+ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="min-h-0 flex-1 space-y-4 overflow-y-auto px-3 py-3">+ {!messages.length && (+ <div className="space-y-3 pt-4">+ <p className="font-heading text-[22px] leading-tight">Your AI Director</p>+ <p className="text-[13px] text-muted-foreground">Ask it to pick the camera, light the scene, write the prompt, or break a script into shots. It only proposes — nothing renders until you press Generate.</p>+ <div className="flex flex-col gap-1.5">+ {SUGGESTIONS.map((s) => (+ <button key={s} type="button" onClick={() => send(s)} className="rounded-xl border px-3 py-2 text-left text-[13px] transition-colors hover:bg-accent">+ {s}+ </button>+ ))}+ </div>+ </div>+ )}+ {messages.map((m) => (+ <Message key={m.id} m={m} onLoad={onLoadShot} onBrief={onBrief} />+ ))}+ {ask.isPending && (+ <div className="flex items-center gap-2 pl-1">+ <span className="grid size-6 place-items-center rounded-full bg-brand-faint text-brand-text">+ <Sparkles className="size-3.5" />+ </span>+ <span className="shimmer-text animate-shimmer-text text-[13px] font-medium">Directing…</span>+ </div>+ )}+ <div ref={end} />+ </div>+ <div className="border-t p-2.5">+ <div className="rounded-2xl border bg-background p-1.5 focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint">+ <textarea+ value={text}+ onChange={(e) => setText(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {+ e.preventDefault();+ send();+ }+ }}+ rows={2}+ placeholder="Ask AI Director anything, or paste a script"+ className="field-sizing-content max-h-40 min-h-10 w-full resize-none bg-transparent px-2 py-1 text-[13.5px] outline-none placeholder:text-subtle-foreground"+ aria-label="Message the AI Director"+ />+ <div className="flex items-center gap-1">+ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" onClick={() => setText((t) => (t ? `${t}\n${promptText}` : promptText))} disabled={!promptText.trim()} className="inline-flex h-7 items-center gap-1 rounded-full px-2 text-[11.5px] text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-40">+ <ClipboardPaste className="size-3.5" /> Get from prompt box+ </button>+ </TooltipTrigger>+ <TooltipContent>Paste the prompt bar's text here</TooltipContent>+ </Tooltip>+ {messages.length > 0 && (+ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" onClick={() => void clear()} className="grid size-7 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Clear the conversation">+ <Trash2 className="size-3.5" />+ </button>+ </TooltipTrigger>+ <TooltipContent>Clear the conversation</TooltipContent>+ </Tooltip>+ )}+ <Button size="icon" className="ml-auto size-8 rounded-full" onClick={() => send()} disabled={!text.trim() || ask.isPending} aria-label="Send">+ {ask.isPending ? <Loader2 className="animate-spin" /> : <ArrowUp />}+ </Button>+ </div>+ </div>+ <p className="px-1 pt-1.5 text-[10.5px] text-muted-foreground">LLMs can make mistakes. The Director only proposes; generating costs credits when you press Generate.</p>+ </div>+ </div>+ );+}++/** The production's rules: tone, references, do's and don'ts. Prepended to every compiled prompt. */+function Brief({ project }: { project: CinemaProject }) {+ const update = useUpdateProject(project.id);+ const [title, setTitle] = useState(project.brief.title);+ const [body, setBody] = useState(project.brief.body);+ const [state, setState] = useState<"saved" | "saving" | "dirty">("saved");+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);+ const save = (t: string, b: string) => {+ if (timer.current) clearTimeout(timer.current);+ setState("dirty");+ timer.current = setTimeout(() => {+ setState("saving");+ update.mutate({ brief: { title: t, body: b } }, { onSuccess: () => setState("saved"), onError: (e) => (setState("dirty"), toast.error((e as Error).message)) });+ }, 700);+ };+ useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []);+ return (+ <div className="flex min-h-0 flex-1 flex-col gap-2 p-3">+ <div className="flex items-center gap-2">+ <Input value={title} onChange={(e) => (setTitle(e.target.value), save(e.target.value, body))} placeholder="Brief title" className="h-9 font-heading text-[18px]" aria-label="Brief title" />+ <span className="flex shrink-0 items-center gap-1 text-[11.5px] text-muted-foreground" aria-live="polite">+ {state === "saving" ? <Loader2 className="size-3 animate-spin" /> : state === "saved" ? <Check className="size-3" /> : null}+ {state === "saving" ? "Saving…" : state === "saved" ? "Saved" : "Editing"}+ </span>+ </div>+ <textarea+ value={body}+ onChange={(e) => (setBody(e.target.value), save(title, e.target.value))}+ placeholder={"This brief is empty.\n\nSet the rules of the production: tone, references, do's and don'ts. Every prompt in this project — and the AI Director — works from it."}+ className="min-h-0 flex-1 resize-none rounded-xl border bg-background p-3 text-[13.5px] leading-relaxed outline-none placeholder:text-subtle-foreground focus:border-primary focus:ring-4 focus:ring-brand-faint"+ aria-label="Brief"+ />+ <p className="text-[11.5px] text-muted-foreground">Prepended to every prompt this project sends (trimmed to about 900 characters).</p>+ </div>+ );+}++export function SidePanel({+ project,+ tab,+ setTab,+ onClose,+ onLoadShot,+ promptText,+}: {+ project: CinemaProject;+ tab: "director" | "brief";+ setTab: (t: "director" | "brief") => void;+ onClose: () => void;+ onLoadShot: (s: DirectorShot) => void;+ promptText: string;+}) {+ const update = useUpdateProject(project.id);+ // A brief applied from the Director replaces what the editor shows.+ const [briefVersion, setBriefVersion] = useState(0);+ return (+ <div className="flex h-full min-h-0 flex-col">+ <div className="flex h-12 shrink-0 items-center gap-2 border-b px-2.5">+ <div className="inline-flex h-8 rounded-full bg-muted p-0.5" role="tablist">+ {(+ [+ ["director", "AI Director", Bot],+ ["brief", "Project brief", FileText],+ ] as const+ ).map(([id, label, Icon]) => (+ <button+ key={id}+ type="button"+ role="tab"+ aria-selected={tab === id}+ onClick={() => setTab(id)}+ className={cn("inline-flex items-center gap-1 rounded-full px-2.5 text-[12.5px] font-medium", tab === id ? "bg-background shadow-soft" : "text-muted-foreground hover:text-foreground")}+ >+ <Icon className="size-3.5" /> {label}+ </button>+ ))}+ </div>+ <button type="button" onClick={onClose} className="ml-auto grid size-8 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Close panel">+ <X className="size-4" />+ </button>+ </div>+ {tab === "director" ? (+ <DirectorChat+ projectId={project.id}+ onLoadShot={onLoadShot}+ promptText={promptText}+ onBrief={(b) =>+ update.mutate(+ { brief: { body: b } },+ {+ onSuccess: () => {+ setBriefVersion((v) => v + 1);+ toast.success("Brief updated", { duration: 1500, action: { label: "Open", onClick: () => setTab("brief") } });+ },+ onError: (e) => toast.error((e as Error).message),+ },+ )+ }+ />+ ) : (+ <Brief key={briefVersion} project={project} />+ )}+ </div>+ );+}diff --git a/src/components/cinema/soul-builders.tsx b/src/components/cinema/soul-builders.tsxnew file mode 100644index 00000000..fae2a9c6--- /dev/null+++ b/src/components/cinema/soul-builders.tsx@@ -0,0 +1,384 @@+"use client";++import { Check, Loader2, MapPin, RotateCcw, Shuffle, Sparkles, UserRoundPlus } from "lucide-react";+import { useRouter } from "next/navigation";+import { useMemo, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Slider } from "@/components/ui/slider";+import { Textarea } from "@/components/ui/textarea";+import { useSaveElement, useStatus } from "@/lib/api";+import {+ LOCATION_VIEWS,+ SOUL_CAST_FIELDS,+ SOUL_CAST_TABS,+ castDefaults,+ castName,+ castPrompt,+ directorSummary,+ planCinema,+ randomizeCast,+ visibleCast,+ type CastField,+ type CastValues,+ type DirectorSettings,+} from "@/lib/catalog/cinema";+import type { Engine, Generation } from "@/lib/catalog/types";+import { formatCost } from "@/lib/format";+import { cn } from "@/lib/utils";+import { useCinemaGenerate, useCinemaItems } from "./hooks";++interface BuilderProps {+ open: boolean;+ onOpenChange: (o: boolean) => void;+ projectId: string;+ folderId: string | null;+ engine: Engine;+ settings: DirectorSettings;+ context: { higgsfield: boolean; cloudAllowed: boolean };+ brief: string;+}++/** "${v}M" → "$250M", "{v}s" → "2020s", "{v}yo" → "35yo". */+const fmt = (f: CastField, v: string | number) => (f.format ? f.format.replace("{v}", String(v)) : String(v));++function Field({ f, values, set }: { f: CastField; values: CastValues; set: (patch: CastValues) => void }) {+ const v = values[f.key];+ const manualKey = `${f.key}_text`;+ return (+ <div className="space-y-2">+ <p className="text-[12.5px] font-medium">{f.question ?? f.label}</p>+ {f.kind === "ruler" ? (+ <div className="space-y-1.5 px-1">+ <div className="flex justify-between">+ <span className="text-[11.5px] text-muted-foreground">{f.key === "budget" ? "Budget in millions" : f.label}</span>+ <span className="font-mono text-[13px]">{v !== undefined ? fmt(f, v as string | number) : "—"}</span>+ </div>+ <Slider+ value={[Math.max(0, f.options.indexOf(v as string | number))]}+ min={0}+ max={f.options.length - 1}+ step={1}+ onValueChange={([i]) => set({ [f.key]: f.options[i] })}+ aria-label={f.label}+ />+ <div className="flex justify-between font-mono text-[10px] text-muted-foreground">+ <span>{fmt(f, f.options[0])}</span>+ <span>{fmt(f, f.options[f.options.length - 1])}</span>+ </div>+ </div>+ ) : (+ <div className="flex flex-wrap gap-1.5" role={f.kind === "multi" ? "group" : "radiogroup"} aria-label={f.label}>+ {f.options.map((o) => {+ const sel = f.kind === "multi" ? Array.isArray(v) && v.includes(String(o)) : v === o;+ return (+ <button+ key={String(o)}+ type="button"+ role={f.kind === "multi" ? "checkbox" : "radio"}+ aria-checked={sel}+ onClick={() => {+ if (f.kind === "multi") {+ const cur = Array.isArray(v) ? v : [];+ set({ [f.key]: sel ? cur.filter((x) => x !== o) : [...cur, String(o)] });+ } else set({ [f.key]: sel ? undefined : o });+ }}+ className={cn("inline-flex h-8 items-center gap-1 rounded-full border px-3 text-[12.5px] font-medium transition-colors", sel ? "border-primary bg-brand-faint text-brand-text" : "hover:bg-accent")}+ >+ {sel && <Check className="size-3" />}+ {String(o)}+ </button>+ );+ })}+ </div>+ )}+ {f.manual && (+ <Textarea+ value={String(values[manualKey] ?? "")}+ onChange={(e) => set({ [manualKey]: e.target.value.slice(0, 300) })}+ rows={2}+ className="resize-none text-[13px]"+ placeholder={f.key === "imperfections" ? "Describe any additional details. Max 300 characters." : f.key === "outfit" ? "Or describe the outfit…" : `Describe ${f.label.toLowerCase()} you want. Max 300 characters.`}+ aria-label={`${f.label}, in your words`}+ />+ )}+ </div>+ );+}++/** Generated variants of a builder run: pick one (or several) to save as an element. */+function Results({ items, picked, onPick }: { items: Generation[]; picked: string[]; onPick: (url: string) => void }) {+ if (!items.length) return null;+ return (+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">+ {items.flatMap((g) =>+ g.status === "succeeded"+ ? g.outputs.map((o) => (+ <button+ key={o.url}+ type="button"+ onClick={() => onPick(o.url)}+ className={cn("relative aspect-video overflow-hidden rounded-lg bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring", picked.includes(o.url) && "ring-2 ring-primary ring-offset-2 ring-offset-background")}+ aria-pressed={picked.includes(o.url)}+ aria-label="Pick this variant"+ >+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={o.url} alt="" className="size-full object-cover" />+ {picked.includes(o.url) && (+ <span className="absolute top-1.5 right-1.5 grid size-5 place-items-center rounded-full bg-primary text-primary-foreground">+ <Check className="size-3" />+ </span>+ )}+ </button>+ ))+ : [+ <div key={g.id} className="relative grid aspect-video place-items-center overflow-hidden rounded-lg bg-muted">+ {g.status === "failed" || g.status === "canceled" ? (+ <span className="px-2 text-center text-[11.5px] text-destructive">{g.error ?? "Couldn't generate this one"}</span>+ ) : (+ <>+ <div className="skeleton-sweep absolute inset-0 animate-skeleton" />+ <span className="shimmer-text relative animate-shimmer-text text-[12px] font-medium">{g.message ?? "Generating…"}</span>+ </>+ )}+ </div>,+ ],+ )}+ </div>+ );+}++function useBuilderRun(projectId: string) {+ const generate = useCinemaGenerate(projectId);+ const items = useCinemaItems(projectId).data;+ const [ids, setIds] = useState<string[]>([]);+ const results = useMemo(() => ids.map((id) => items?.find((g) => g.id === id)).filter((g): g is NonNullable<typeof g> => !!g), [ids, items]);+ return { generate, results, setIds };+}++function CostLabel({ plan, demoModel }: { plan: { costUsd: number | null }; demoModel: { routes: { provider: string }[] } }) {+ const status = useStatus().data;+ const demo = !!status && status.demoMode !== "off" && !demoModel.routes.some((r) => status.providers[r.provider]?.configured);+ return <span className="font-mono text-[12px] text-muted-foreground">{demo ? "Demo · free" : plan.costUsd === 0 ? "Free" : plan.costUsd != null ? `≈ ${formatCost(plan.costUsd)}` : ""}</span>;+}++function SaveElement({ kind, defaultName, picked, description, onSaved }: { kind: "character" | "location"; defaultName: string; picked: string[]; description: string; onSaved: () => void }) {+ const save = useSaveElement();+ const router = useRouter();+ const [name, setName] = useState(defaultName);+ if (!picked.length) return <p className="text-[12px] text-muted-foreground">Select an image variant to save it as {kind === "character" ? "a character" : "a location"}.</p>;+ return (+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center">+ <Input value={name} onChange={(e) => setName(e.target.value.slice(0, 60))} placeholder={kind === "character" ? "Character name" : "Location name"} className="sm:max-w-64" aria-label="Element name" />+ <Button+ disabled={save.isPending || !name.trim()}+ onClick={() =>+ save.mutate(+ { name: name.trim(), kind, description: description.slice(0, 500), references: picked.slice(0, 20) },+ {+ onSuccess: (el) => {+ toast.success(`Saved as @${el.handle}`, { action: { label: "Open", onClick: () => router.push(`/elements/${el.id}`) } });+ onSaved();+ },+ onError: (e) => toast.error((e as Error).message),+ },+ )+ }+ >+ {save.isPending ? <Loader2 className="animate-spin" /> : kind === "character" ? <UserRoundPlus /> : <MapPin />}+ Save as {kind === "character" ? "character" : "location"}+ </Button>+ </div>+ );+}++/** Soul Cast: an AI actor from the 17 casting fields → turnaround sheet → a character element. */+export function SoulCastDialog(props: BuilderProps) {+ return (+ <Dialog open={props.open} onOpenChange={props.onOpenChange}>+ <DialogContent className="max-h-[92svh] gap-3 overflow-y-auto sm:max-w-[720px]">{props.open && <SoulCast {...props} />}</DialogContent>+ </Dialog>+ );+}++function SoulCast({ projectId, folderId, engine, context, brief, onOpenChange }: BuilderProps) {+ const [values, setValues] = useState<CastValues>(castDefaults);+ const [tab, setTab] = useState(SOUL_CAST_TABS[0]);+ const [notes, setNotes] = useState("");+ const [batch, setBatch] = useState(2);+ const [picked, setPicked] = useState<string[]>([]);+ const { generate, results, setIds } = useBuilderRun(projectId);+ const visible = visibleCast(values);+ const input = { engine, mode: "image" as const, action: "cast" as const, prompt: notes, settings: {}, cast: visible, batch };+ const plan = planCinema({ ...input, brief }, context);+ const set = (patch: CastValues) => setValues((v) => ({ ...v, ...patch }));+ const fields = SOUL_CAST_FIELDS.filter((f) => f.tab === tab && (!f.when || f.when(values)));+ const run = () =>+ generate.mutate(+ { input, folderId },+ {+ onSuccess: (r) => {+ setIds(r.items.map((g) => g.id));+ setPicked([]);+ },+ onError: (e) => toast.error((e as Error).message),+ },+ );+ return (+ <>+ <DialogHeader>+ <DialogTitle className="font-heading text-[26px] font-normal">Build your cast</DialogTitle>+ <DialogDescription>Build your film's cast from scratch - genre, budget, appearance, and every detail in between.</DialogDescription>+ </DialogHeader>+ <div className="scrollbar-none -mx-1 flex gap-1 overflow-x-auto px-1 pb-1" role="tablist">+ {SOUL_CAST_TABS.map((t) => {+ const filled = SOUL_CAST_FIELDS.some((f) => f.tab === t && visible[f.key] !== undefined && !(f.default !== undefined && visible[f.key] === f.default));+ return (+ <button+ key={t}+ type="button"+ role="tab"+ aria-selected={tab === t}+ onClick={() => setTab(t)}+ className={cn("inline-flex h-8 shrink-0 items-center gap-1 rounded-full px-3 text-[12.5px] font-medium", tab === t ? "bg-primary text-primary-foreground" : "bg-secondary hover:bg-accent")}+ >+ {t}+ {filled && tab !== t && <span className="size-1.5 rounded-full bg-primary" />}+ </button>+ );+ })}+ </div>+ <div className="min-h-[200px] space-y-4">+ {fields.map((f) => (+ <Field key={f.key} f={f} values={values} set={set} />+ ))}+ </div>+ <div className="space-y-1.5">+ <p className="text-[12.5px] font-medium">Describe your character (optional)</p>+ <Textarea value={notes} onChange={(e) => setNotes(e.target.value.slice(0, 1000))} rows={2} className="resize-none text-[13px]" placeholder="e.g. “a retired safecracker with kind eyes and a nervous smile”" />+ </div>+ <div className="flex flex-wrap items-center gap-2 border-t pt-3">+ <Button variant="ghost" size="sm" onClick={() => setValues((v) => randomizeCast(v))}>+ <Shuffle /> Randomize+ </Button>+ <Button variant="ghost" size="sm" onClick={() => setValues(castDefaults())}>+ <RotateCcw /> Reset+ </Button>+ <div className="ml-auto flex items-center gap-2">+ <div className="inline-flex h-8 rounded-full bg-muted p-0.5" role="radiogroup" aria-label="Variants">+ {[1, 2, 3, 4].map((n) => (+ <button key={n} type="button" role="radio" aria-checked={batch === n} onClick={() => setBatch(n)} className={cn("w-8 rounded-full font-mono text-[12px]", batch === n ? "bg-background shadow-soft" : "text-muted-foreground")}>+ ×{n}+ </button>+ ))}+ </div>+ <CostLabel plan={plan} demoModel={plan.model} />+ <Button onClick={run} disabled={generate.isPending}>+ {generate.isPending ? <Loader2 className="animate-spin" /> : <Sparkles />} Generate character+ </Button>+ </div>+ </div>+ <p className="-mt-1 text-[11.5px] text-muted-foreground">+ {plan.model.name} · a turnaround sheet (front, three-quarter, profile, back and a close-up){engine === "open" ? " · open source" : ""}+ </p>+ {results.length > 0 && (+ <div className="space-y-3 border-t pt-3">+ <p className="text-[12.5px] font-medium">Select an image variant for your cast</p>+ <Results items={results} picked={picked} onPick={(u) => setPicked((p) => (p.includes(u) ? p.filter((x) => x !== u) : [u]))} />+ <SaveElement kind="character" defaultName={castName(visible)} picked={picked} description={castPrompt(visible, notes)} onSaved={() => onOpenChange(false)} />+ </div>+ )}+ </>+ );+}++/** Soul Location: describe a set → 16:9 empty establishing shots → a location element (plus extra views). */+export function SoulLocationDialog(props: BuilderProps) {+ return (+ <Dialog open={props.open} onOpenChange={props.onOpenChange}>+ <DialogContent className="max-h-[92svh] gap-3 overflow-y-auto sm:max-w-[680px]">{props.open && <SoulLocation {...props} />}</DialogContent>+ </Dialog>+ );+}++function SoulLocation({ projectId, folderId, engine, settings, context, brief, onOpenChange }: BuilderProps) {+ const [prompt, setPrompt] = useState("");+ const [batch, setBatch] = useState(2);+ const [picked, setPicked] = useState<string[]>([]);+ const { generate, results, setIds } = useBuilderRun(projectId);+ const input = { engine, mode: "image" as const, action: "location" as const, prompt, settings, batch };+ const plan = planCinema({ ...input, brief }, context);+ const look = directorSummary({ ...settings, genre: undefined, era: undefined, tempo: undefined, lighting: settings.lighting });+ const run = (extra?: { view: string; url: string }) =>+ generate.mutate(+ {+ input: extra ? { ...input, action: "location-view", view: extra.view, source: { url: extra.url, kind: "image" }, batch: 1 } : input,+ folderId,+ },+ {+ onSuccess: (r) => {+ setIds((ids) => (extra ? [...ids, ...r.items.map((g) => g.id)] : r.items.map((g) => g.id)));+ if (!extra) setPicked([]);+ },+ onError: (e) => toast.error((e as Error).message),+ },+ );+ return (+ <>+ <DialogHeader>+ <DialogTitle className="font-heading text-[26px] font-normal">Create location</DialogTitle>+ <DialogDescription>Keep every scene in the same world: build the set once, then @mention it in every shot.</DialogDescription>+ </DialogHeader>+ <div className="space-y-1.5">+ <p className="text-[12.5px] font-medium">Describe your location</p>+ <Textarea+ value={prompt}+ onChange={(e) => setPrompt(e.target.value.slice(0, 2500))}+ onKeyDown={(e) => {+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && prompt.trim()) {+ e.preventDefault();+ run();+ }+ }}+ rows={3}+ className="resize-none text-[13.5px]"+ placeholder="e.g. “a rain-soaked rooftop bar in Tokyo, neon signs, wet tiles, a single string of bulbs”"+ autoFocus+ />+ <p className="text-[11.5px] text-muted-foreground">{look.length ? `Uses the Director's ${look.join(", ")}.` : "Set a camera, lens and palette in the Director's Panel to shape the look."} 16:9, no people.</p>+ </div>+ <div className="flex flex-wrap items-center justify-end gap-2">+ <div className="inline-flex h-8 rounded-full bg-muted p-0.5" role="radiogroup" aria-label="Variants">+ {[1, 2, 3, 4].map((n) => (+ <button key={n} type="button" role="radio" aria-checked={batch === n} onClick={() => setBatch(n)} className={cn("w-8 rounded-full font-mono text-[12px]", batch === n ? "bg-background shadow-soft" : "text-muted-foreground")}>+ ×{n}+ </button>+ ))}+ </div>+ <CostLabel plan={plan} demoModel={plan.model} />+ <Button onClick={() => run()} disabled={generate.isPending || !prompt.trim()}>+ {generate.isPending ? <Loader2 className="animate-spin" /> : <Sparkles />} Generate location+ </Button>+ </div>+ {results.length > 0 && (+ <div className="space-y-3 border-t pt-3">+ <p className="text-[12.5px] font-medium">Pick the views to keep (several views make a stronger location)</p>+ <Results items={results} picked={picked} onPick={(u) => setPicked((p) => (p.includes(u) ? p.filter((x) => x !== u) : [...p, u]))} />+ {picked.length > 0 && (+ <div className="flex flex-wrap items-center gap-1.5">+ <span className="text-[12px] text-muted-foreground">Show the same location from another view:</span>+ {LOCATION_VIEWS.map((v) => (+ <button key={v.id} type="button" onClick={() => run({ view: v.id, url: picked[0] })} className="h-7 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent">+ {v.name}+ </button>+ ))}+ </div>+ )}+ <SaveElement kind="location" defaultName={prompt.split(/[,.]/)[0].replace(/^(an?|the)\s+/i, "").slice(0, 40) || "Location"} picked={picked} description={prompt} onSaved={() => onOpenChange(false)} />+ </div>+ )}+ </>+ );+}diff --git a/src/components/cinema/workspace.tsx b/src/components/cinema/workspace.tsxnew file mode 100644index 00000000..c91b5422--- /dev/null+++ b/src/components/cinema/workspace.tsx@@ -0,0 +1,466 @@+"use client";++import { Bot, ChevronLeft, Clapperboard, Copy, FileText, Folder, FolderOpen, Heart, Library, MoreHorizontal, PanelLeft, Pin, PinOff, Settings2, Upload } from "lucide-react";+import { nanoid } from "nanoid";+import Link from "next/link";+import { useRouter } from "next/navigation";+import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";+import { SidebarTrigger } from "@/components/ui/sidebar";+import { Skeleton } from "@/components/ui/skeleton";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { EngineSwitch } from "@/components/studio/engine-switch";+import type { PromptInputHandle } from "@/components/studio/prompt-input";+import { useElements, useEngine, useSaveElement } from "@/lib/api";+import type { CinemaFolder, DirectorSettings, DirectorShot } from "@/lib/catalog/cinema";+import type { StudioElement } from "@/lib/catalog/elements";+import type { OutputFile } from "@/lib/catalog/types";+import { formatCost } from "@/lib/format";+import { cn } from "@/lib/utils";+import { CinemaFeed, type FeedHandlers } from "./cinema-feed";+import { initialDraft, type CinemaDraft } from "./draft";+import { ElementsPanel } from "./elements-panel";+import { FolderSidebar, subtree, viewKey, type CinemaView } from "./folder-sidebar";+import { useCinemaItems, useCinemaProject, useItemActions, useStudioGenerations, useUpdateProject, type CinemaGeneration, type ProjectView } from "./hooks";+import { cutGrid } from "./media";+import { ProjectDialog } from "./project-settings";+import { PromptBar, useAddRefs } from "./prompt-bar";+import { SidePanel } from "./side-panel";+import { SoulCastDialog, SoulLocationDialog } from "./soul-builders";++function useMedia(query: string): boolean {+ return useSyncExternalStore(+ (cb) => {+ const m = window.matchMedia(query);+ m.addEventListener("change", cb);+ return () => m.removeEventListener("change", cb);+ },+ () => window.matchMedia(query).matches,+ () => false,+ );+}++/** Grid contact sheets are cut into tiles in the browser once, then saved with the take. */+const cutting = new Set<string>();+function useGridTiles(projectId: string, items: CinemaGeneration[]) {+ const actions = useItemActions(projectId);+ useEffect(() => {+ for (const g of items) {+ const sheet = g.outputs[0];+ if (g.feature !== "cinema-grid" || g.status !== "succeeded" || g.tiles?.length || g.outputs.length !== 1 || sheet?.kind !== "image" || cutting.has(g.id)) continue;+ cutting.add(g.id);+ const m = /(\d)×(\d) grid/.exec(g.prompt ?? "");+ const size = g.take?.grid?.size ?? (m ? `${m[1]}x${m[2]}` : "2x2");+ const n = Number(size[0]) || 2;+ void cutGrid(sheet.url, n, n)+ .then((tiles) => actions.saveTiles(g.id, tiles))+ .catch(() => toast.error("Couldn't cut the grid into tiles — open the sheet to use it whole"));+ }+ }, [items, actions]);+}++/** A name to start from when a still is saved as an element ("Rainy Rooftop Bar"). */+function nameFrom(prompt: string | undefined, fallback: string): string {+ const words = (prompt ?? "").replace(/@\S+/g, "").replace(/[^\p{L}\p{N}\s'-]/gu, " ").split(/\s+/).filter((w) => w.length > 2 && !/^(the|and|with|from|who|shot|wide|close|establishing|film|location)$/i.test(w));+ return words.slice(0, 3).map((w) => w[0].toUpperCase() + w.slice(1).toLowerCase()).join(" ") || fallback;+}++function folderPath(folders: CinemaFolder[], id: string): CinemaFolder[] {+ const out: CinemaFolder[] = [];+ let cur = folders.find((f) => f.id === id);+ while (cur && out.length < 12) {+ out.unshift(cur);+ cur = cur.parentId ? folders.find((f) => f.id === cur!.parentId) : undefined;+ }+ return out;+}++function Empty({ icon: Icon, title, text }: { icon: typeof Clapperboard; title: string; text: string }) {+ return (+ <div className="mx-auto flex max-w-md flex-col items-center py-[10vh] text-center">+ <div className="grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">+ <Icon className="size-5" />+ </div>+ <p className="mt-4 font-heading text-[22px] leading-tight">{title}</p>+ <p className="mt-1 text-[13.5px] text-muted-foreground">{text}</p>+ </div>+ );+}++export function CinemaWorkspace({ id }: { id: string }) {+ const project = useCinemaProject(id);+ const items = useCinemaItems(id);+ if (project.isLoading)+ return (+ <div className="flex h-svh flex-col">+ <div className="flex h-14 items-center gap-3 border-b px-4">+ <Skeleton className="h-6 w-48" />+ </div>+ <div className="flex flex-1">+ <div className="hidden w-60 space-y-2 border-r p-3 lg:block">+ {Array.from({ length: 5 }, (_, i) => (+ <Skeleton key={i} className="h-7" />+ ))}+ </div>+ <div className="grid flex-1 grid-cols-2 content-start gap-3 p-6 sm:grid-cols-4">+ {Array.from({ length: 8 }, (_, i) => (+ <Skeleton key={i} className="aspect-square rounded-xl" />+ ))}+ </div>+ </div>+ </div>+ );+ if (!project.data)+ return (+ <div className="flex h-svh flex-col">+ <div className="flex h-14 items-center px-3 md:hidden">+ <SidebarTrigger />+ </div>+ <div className="mx-auto max-w-sm pt-[18vh] text-center">+ <p className="font-heading text-[26px]">This project doesn't exist</p>+ <p className="mt-1 text-[14px] text-muted-foreground">It may have been deleted.</p>+ <Button asChild className="mt-5">+ <Link href="/cinema">All projects</Link>+ </Button>+ </div>+ </div>+ );+ return <Workspace data={project.data} items={items.data ?? []} loading={items.isLoading} />;+}++function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaGeneration[]; loading: boolean }) {+ const { project, folders, spentUsd, context } = data;+ const id = project.id;+ const router = useRouter();+ const [engine, setEngine] = useEngine();+ const [view, setView] = useState<CinemaView>({ kind: "home" });+ const [nested, setNested] = useState(true);+ const [draft, setDraftState] = useState<CinemaDraft>(initialDraft);+ const setDraft = (patch: Partial<CinemaDraft> | ((d: CinemaDraft) => Partial<CinemaDraft>)) => setDraftState((d) => ({ ...d, ...(typeof patch === "function" ? patch(d) : patch) }));+ const [settings, setSettings] = useState<DirectorSettings>(project.director);+ const update = useUpdateProject(id);+ const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);+ const onSettings = (patch: Partial<DirectorSettings>) => {+ const next = { ...settings, ...patch };+ setSettings(next);+ if (saveTimer.current) clearTimeout(saveTimer.current);+ // Persist per project, a moment after the last change.+ saveTimer.current = setTimeout(() => update.mutate({ director: next }, { onError: (e) => toast.error((e as Error).message) }), 500);+ };+ useEffect(() => () => void (saveTimer.current && clearTimeout(saveTimer.current)), []);+ const elements = useElements().data ?? [];+ const xl = useMedia("(min-width: 1280px)");+ const [panel, setPanel] = useState<"director" | "brief" | null>(null);+ const [foldersOpen, setFoldersOpen] = useState(false);+ const [castOpen, setCastOpen] = useState(false);+ const [locationOpen, setLocationOpen] = useState(false);+ const [settingsOpen, setSettingsOpen] = useState(false);+ const [dropping, setDropping] = useState(false);+ const promptRef = useRef<PromptInputHandle>(null);+ const studio = useStudioGenerations(id, view.kind === "studio");+ const actions = useItemActions(id);+ const saveElement = useSaveElement();+ const addRefs = useAddRefs((fn) => setDraft(fn));+ useGridTiles(id, items);++ const currentView: CinemaView = useMemo(() => (view.kind === "folder" && !folders.some((f) => f.id === view.id) ? { kind: "home" } : view), [view, folders]);+ const folderId = currentView.kind === "folder" ? currentView.id : null;+ const shown = useMemo(() => {+ switch (currentView.kind) {+ case "favorites":+ return items.filter((g) => g.favorite);+ case "studio":+ return studio.data ?? [];+ case "folder": {+ const set = nested ? subtree(folders, currentView.id) : new Set([currentView.id]);+ return items.filter((g) => g.folderId && set.has(g.folderId));+ }+ default:+ return items;+ }+ }, [currentView, items, studio.data, folders, nested]);+ const counts = useMemo(() => {+ const m = new Map<string, number>();+ for (const g of items) if (g.folderId) m.set(g.folderId, (m.get(g.folderId) ?? 0) + 1);+ return { home: items.length, favorites: items.filter((g) => g.favorite).length, folders: m };+ }, [items]);++ const focusPrompt = () => requestAnimationFrame(() => promptRef.current?.focus());+ const handlers: FeedHandlers = {+ onLoad: (g) => {+ const t = g.take;+ setDraft((d) => ({+ mode: t?.mode ?? (g.kind === "image" ? "image" : "video"),+ imageTool: t?.action === "grid" ? "grid" : "still",+ prompt: t?.prompt ?? g.request.prompt ?? "",+ moves: t?.moves ?? [],+ grid: t?.grid ?? d.grid,+ source: null,+ action: "generate",+ }));+ toast("Loaded into the prompt bar", { duration: 1500 });+ focusPrompt();+ },+ onUseTake: (g, o: OutputFile) => {+ setDraft({ mode: "video", source: { generationId: g.id, url: o.url, kind: "video", label: g.take?.prompt || g.request.prompt || "Take" }, action: "extend-forward" });+ focusPrompt();+ },+ onAnimate: (url) => {+ setDraft((d) => ({ mode: "video", source: null, action: "generate", refs: [{ id: nanoid(6), ref: url, preview: url, kind: "image" }, ...d.refs.filter((r) => r.ref !== url)] }));+ toast("Start frame set", { duration: 1500 });+ focusPrompt();+ },+ onReference: (url, kind) => {+ setDraft((d) => (d.refs.some((r) => r.ref === url) ? {} : { refs: [...d.refs, { id: nanoid(6), ref: url, preview: url, kind }] }));+ toast("Added to references", { duration: 1500 });+ },+ onSaveElement: (g, url, kind) =>+ saveElement.mutate(+ { name: nameFrom(g.take?.prompt ?? g.request.prompt, kind === "character" ? "New character" : "New location"), kind, references: [url] },+ {+ onSuccess: (el) => toast.success(`Saved as @${el.handle}`, { action: { label: "Open", onClick: () => router.push(`/elements/${el.id}`) } }),+ onError: (e) => toast.error((e as Error).message),+ },+ ),+ };+ const onLoadShot = (shot: DirectorShot) => {+ setDraft({ mode: "video", prompt: shot.prompt, moves: shot.moves, duration: shot.duration, source: null, action: "generate", multiShot: { mode: "off", shots: [] } });+ if (Object.keys(shot.settings).length) onSettings(shot.settings);+ toast("Shot loaded — review it, then press Generate", { duration: 2500 });+ if (!xl) setPanel(null);+ focusPrompt();+ };+ const mention = (el: StudioElement) => {+ setDraft((d) => ({ prompt: `${d.prompt.trim()}${d.prompt.trim() ? " " : ""}@${el.handle} ` }));+ focusPrompt();+ };++ const path = currentView.kind === "folder" ? folderPath(folders, currentView.id) : [];+ const title = (+ <div className="flex min-w-0 items-baseline gap-2">+ <h2 className="flex min-w-0 items-center gap-1.5 truncate font-heading text-[24px] leading-none">+ {currentView.kind === "folder" ? (+ path.map((f, i) => (+ <span key={f.id} className="flex min-w-0 items-center gap-1.5">+ {i > 0 && <span className="text-muted-foreground">/</span>}+ {i === path.length - 1 && <span className="size-2.5 shrink-0 rounded-full border" style={f.color ? { background: f.color, borderColor: f.color } : undefined} />}+ <button type="button" onClick={() => setView({ kind: "folder", id: f.id })} className={cn("truncate", i < path.length - 1 && "text-muted-foreground hover:text-foreground")}>+ {f.name}+ </button>+ </span>+ ))+ ) : currentView.kind === "studio" ? (+ "My Generations"+ ) : currentView.kind === "favorites" ? (+ "My Favorites"+ ) : (+ "Home"+ )}+ </h2>+ <span className="shrink-0 font-mono text-[12px] text-muted-foreground">{shown.length}</span>+ </div>+ );+ const empty =+ currentView.kind === "favorites" ? (+ <Empty icon={Heart} title="No favorites yet" text="Like your generations and they will appear here." />+ ) : currentView.kind === "studio" ? (+ <Empty icon={Library} title="No generations yet" text="Everything you make in Cinema Studio, in any project, shows up here." />+ ) : currentView.kind === "folder" ? (+ <Empty icon={FolderOpen} title="An empty scene" text="Describe a scene below and hit Generate — new takes land in this folder." />+ ) : (+ <Empty icon={Clapperboard} title="Your first shot" text="Start by describing a scene and pressing “Generate”. Set the genre, camera, palette and light in the Director's Panel." />+ );++ const sidebar = (+ <FolderSidebar+ projectId={id}+ folders={folders}+ view={currentView}+ setView={(v) => {+ setView(v);+ setFoldersOpen(false);+ }}+ counts={counts}+ onDropItems={(ids, f) => void actions.move(ids, f).then(() => toast(`Moved ${ids.length} take${ids.length > 1 ? "s" : ""}`, { duration: 1500 }))}+ className="h-full"+ />+ );+ const sidePanel = panel && (+ <SidePanel project={project} tab={panel} setTab={setPanel} onClose={() => setPanel(null)} onLoadShot={onLoadShot} promptText={draft.prompt} />+ );+ const builderProps = { projectId: id, folderId, engine, settings, context, brief: project.brief.body };++ return (+ <div className="flex h-svh min-w-0 flex-col md:h-[calc(100svh-0.5rem)]">+ <header className="flex h-14 shrink-0 items-center gap-1.5 border-b px-2 sm:gap-2 sm:px-4">+ <SidebarTrigger className="md:hidden" />+ <Tooltip>+ <TooltipTrigger asChild>+ <Link href="/cinema" className="hidden size-8 shrink-0 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground sm:grid" aria-label="All projects">+ <ChevronLeft className="size-4" />+ </Link>+ </TooltipTrigger>+ <TooltipContent>All projects</TooltipContent>+ </Tooltip>+ <button type="button" onClick={() => setFoldersOpen(true)} className="grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground lg:hidden" aria-label="Folders">+ <PanelLeft className="size-4" />+ </button>+ <div className="min-w-0 flex-1">+ <h1 className="truncate font-heading text-[20px] leading-tight sm:text-[22px]">{project.name}</h1>+ <p className="hidden truncate text-[11.5px] text-muted-foreground sm:block">+ Cinema Studio+ {project.description ? ` · ${project.description}` : ""}+ {spentUsd > 0 ? ` · ≈ ${formatCost(spentUsd)} spent` : ""}+ {project.costCapUsd != null ? ` of ${formatCost(project.costCapUsd) || "$0"}` : ""}+ </p>+ </div>+ <EngineSwitch value={engine} onChange={setEngine} size="sm" />+ <Tooltip>+ <TooltipTrigger asChild>+ <Button variant={panel === "director" ? "secondary" : "ghost"} size="sm" onClick={() => setPanel((p) => (p === "director" ? null : "director"))} aria-pressed={panel === "director"} className="shrink-0">+ <Bot /> <span className="hidden sm:inline">AI Director</span>+ </Button>+ </TooltipTrigger>+ <TooltipContent>Break a script into shots, pick the camera, write prompts</TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button variant={panel === "brief" ? "secondary" : "ghost"} size="icon-sm" onClick={() => setPanel((p) => (p === "brief" ? null : "brief"))} aria-pressed={panel === "brief"} aria-label="Project brief" className="shrink-0">+ <FileText />+ </Button>+ </TooltipTrigger>+ <TooltipContent>Project brief — prepended to every prompt</TooltipContent>+ </Tooltip>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="icon-sm" aria-label="Project menu" className="shrink-0">+ <MoreHorizontal />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => setSettingsOpen(true)}>+ <Settings2 /> Project settings+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => update.mutate({ pinned: !project.pinned })}>+ {project.pinned ? <PinOff /> : <Pin />} {project.pinned ? "Unpin project" : "Pin project"}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => {+ void navigator.clipboard.writeText(window.location.href);+ toast("Link copied");+ }}+ >+ <Copy /> Copy link+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem asChild>+ <Link href="/cinema">+ <Folder /> All projects+ </Link>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </header>++ <div className="flex min-h-0 flex-1">+ <aside className="hidden w-60 shrink-0 border-r bg-sidebar/40 lg:block">{sidebar}</aside>+ <main+ className="relative flex min-w-0 flex-1 flex-col"+ onDragOver={(e) => {+ if (!e.dataTransfer.types.includes("Files")) return;+ e.preventDefault();+ setDropping(true);+ }}+ onDragLeave={(e) => {+ if (e.currentTarget === e.target) setDropping(false);+ }}+ onDrop={(e) => {+ if (!e.dataTransfer.files.length) return;+ e.preventDefault();+ setDropping(false);+ addRefs(e.dataTransfer.files);+ }}+ >+ <div className="min-h-0 flex-1 overflow-y-auto px-3 pt-4 pb-6 sm:px-6">+ {currentView.kind === "elements" ? (+ <ElementsPanel onMention={mention} onCast={() => setCastOpen(true)} onLocation={() => setLocationOpen(true)} />+ ) : loading ? (+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">+ {Array.from({ length: 8 }, (_, i) => (+ <Skeleton key={i} className="aspect-square rounded-xl" />+ ))}+ </div>+ ) : (+ <CinemaFeed+ key={viewKey(currentView)}+ projectId={id}+ items={shown}+ folders={folders}+ title={title}+ empty={empty}+ handlers={handlers}+ nested={nested}+ onNested={currentView.kind === "folder" ? setNested : undefined}+ />+ )}+ </div>+ <div className="shrink-0 px-2 pb-[max(0.5rem,env(safe-area-inset-bottom))] sm:px-6 sm:pb-4">+ <div className="mx-auto max-w-[940px]">+ <PromptBar+ projectId={id}+ folderId={folderId}+ engine={engine}+ draft={draft}+ setDraft={setDraft}+ settings={settings}+ onSettings={onSettings}+ palettes={project.palettes}+ onPalettes={(palettes) => update.mutate({ palettes })}+ context={context}+ brief={project.brief.body}+ spentUsd={spentUsd}+ costCapUsd={project.costCapUsd}+ elements={elements}+ promptRef={promptRef}+ onCast={() => setCastOpen(true)}+ onLocation={() => setLocationOpen(true)}+ />+ </div>+ </div>+ {dropping && (+ <div className="pointer-events-none absolute inset-2 z-30 grid place-items-center rounded-2xl border-2 border-dashed border-primary bg-brand-faint/80 backdrop-blur-sm">+ <p className="flex items-center gap-2 text-[15px] font-medium text-brand-text">+ <Upload className="size-5" /> Drop files here to add them as references+ </p>+ </div>+ )}+ </main>+ {xl && panel && <aside className="w-[380px] shrink-0 border-l bg-sidebar/40">{sidePanel}</aside>}+ </div>++ <Sheet open={foldersOpen} onOpenChange={setFoldersOpen}>+ <SheetContent side="left" className="w-[min(86vw,320px)] gap-0 p-0">+ <SheetHeader className="border-b px-4 py-3">+ <SheetTitle className="font-heading text-[20px] font-normal">{project.name}</SheetTitle>+ <SheetDescription className="sr-only">Folders and sections of this project</SheetDescription>+ </SheetHeader>+ {sidebar}+ </SheetContent>+ </Sheet>+ <Sheet open={!xl && !!panel} onOpenChange={(o) => !o && setPanel(null)}>+ <SheetContent side="right" className="w-[min(100vw,420px)] gap-0 p-0 sm:max-w-[420px] [&>button]:hidden">+ <SheetTitle className="sr-only">{panel === "brief" ? "Project brief" : "AI Director"}</SheetTitle>+ <SheetDescription className="sr-only">Side panel</SheetDescription>+ {sidePanel}+ </SheetContent>+ </Sheet>++ <SoulCastDialog open={castOpen} onOpenChange={setCastOpen} {...builderProps} />+ <SoulLocationDialog open={locationOpen} onOpenChange={setLocationOpen} {...builderProps} />+ <ProjectDialog open={settingsOpen} onOpenChange={setSettingsOpen} project={project} spentUsd={spentUsd} onDone={() => setSettingsOpen(false)} onDeleted={() => router.push("/cinema")} />+ </div>+ );+}diff --git a/src/lib/catalog/cinema.ts b/src/lib/catalog/cinema.tsindex 74b9454d..ac356690 100644--- a/src/lib/catalog/cinema.ts+++ b/src/lib/catalog/cinema.ts@@ -140,6 +140,15 @@ export interface CinemaTile {col: number;}+/** What the user asked for when a take was made (the generation itself stores the compiled prompt). */+export interface CinemaTakeInfo {+ mode: CinemaMode;+ action: CinemaAction;+ prompt: string;+ moves?: string[];+ grid?: { size: GridSize; type: GridType };+}+/** A generation's membership in a project (and its folder = scene). */export interface CinemaItem {generationId: string;@@ -147,6 +156,7 @@ export interface CinemaItem {createdAt: number;/** Grid contact sheets: the tiles cut from it in the browser, saved as uploads. */tiles?: CinemaTile[];+ take?: CinemaTakeInfo;}/** One shot the AI Director proposes; "Load into prompt bar" copies it into the composer. */diff --git a/src/server/cinema-generate.ts b/src/server/cinema-generate.tsindex 48ae03f5..7762f709 100644--- a/src/server/cinema-generate.ts+++ b/src/server/cinema-generate.ts@@ -1,7 +1,17 @@import "server-only";import { nanoid } from "nanoid";import { getModel } from "@/lib/catalog";-import { SWATCH_PLACEHOLDER, planCinema, withPlaceholders, type CinemaContext, type CinemaGenerateInput, type CinemaPlan, type CinemaStep } from "@/lib/catalog/cinema";+import {+ SWATCH_PLACEHOLDER,+ planCinema,+ withPlaceholders,+ type CinemaContext,+ type CinemaGenerateInput,+ type CinemaPlan,+ type CinemaStep,+ type CinemaTakeInfo,+ type DirectorSettings,+} from "@/lib/catalog/cinema";import type { Generation, GenerationRequest } from "@/lib/catalog/types";import { CinemaError, addItems, getProject, spentUsd } from "./cinema";import { createGenerations, previewGeneration } from "./generations";@@ -39,8 +49,11 @@ export function swatchUrl(hex: string[]): string {return asset.url;}+/** A generate request from the workspace: the brief always comes from the project, the Director settings unless sent. */+export type CinemaRequest = Omit<CinemaGenerateInput, "settings" | "brief"> & { settings?: DirectorSettings };+/** The plan with this project's brief and (unless the request carries its own) Director settings. */-export function planForProject(projectId: string, input: CinemaGenerateInput): CinemaPlan {+export function planForProject(projectId: string, input: CinemaRequest): CinemaPlan {const project = getProject(projectId);if (!project) throw new CinemaError("Project not found", 404);return planCinema({ ...input, settings: input.settings ?? project.director, brief: project.brief.body }, cinemaContext());@@ -73,7 +86,7 @@ export interface CinemaRunResult {* Plan, check the project's cost cap, create the chained generations and record them in the project* (in `folderId`, the scene the user is looking at).*/-export function generateInProject(projectId: string, input: CinemaGenerateInput, folderId: string | null = null): CinemaRunResult {+export function generateInProject(projectId: string, input: CinemaRequest, folderId: string | null = null): CinemaRunResult {const project = getProject(projectId);if (!project) throw new CinemaError("Project not found", 404);const plan = planForProject(projectId, input);@@ -91,6 +104,13 @@ export function generateInProject(projectId: string, input: CinemaGenerateInput,}}+ const take: CinemaTakeInfo = {+ mode: input.mode,+ action: input.action,+ prompt: input.prompt.slice(0, 4000),+ ...(input.moves?.length ? { moves: input.moves } : {}),+ ...(input.action === "grid" && input.grid ? { grid: input.grid } : {}),+ };const batchId = nanoid(10);const made: Record<string, Generation[]> = {};const all: Generation[] = [];@@ -110,9 +130,9 @@ export function generateInProject(projectId: string, input: CinemaGenerateInput,}} catch (e) {// Keep what already started visible in the project, then report the step that failed.- if (all.length) addItems(projectId, all.map((g) => g.id), folderId);+ if (all.length) addItems(projectId, all.map((g) => g.id), folderId, take);throw new CinemaError((e as Error).message, 422);}- addItems(projectId, all.map((g) => g.id), folderId);+ addItems(projectId, all.map((g) => g.id), folderId, take);return { items: all, plan: { notes: plan.notes, costUsd: plan.costUsd, outputs: plan.outputs, modelId: plan.model.id } };}diff --git a/src/server/cinema.ts b/src/server/cinema.tsindex 8b1b6993..f3e6906a 100644--- a/src/server/cinema.ts+++ b/src/server/cinema.ts@@ -1,9 +1,9 @@import "server-only";import { nanoid } from "nanoid";-import type { CinemaFolder, CinemaItem, CinemaProject, CinemaTile, DirectorMessage, DirectorSettings } from "@/lib/catalog/cinema";+import type { CinemaFolder, CinemaItem, CinemaProject, CinemaTakeInfo, CinemaTile, DirectorMessage, DirectorSettings } from "@/lib/catalog/cinema";import type { Generation } from "@/lib/catalog/types";import { db } from "./db";-import { deleteGeneration, getGeneration, listGenerations } from "./generations";+import { createGenerations, deleteGeneration, getGeneration, listGenerations } from "./generations";/*** Cinema Studio projects: Director settings, brief and AI Director chat per project, nested folders@@ -91,8 +91,14 @@ const toFolder = (r: FolderRow): CinemaFolder => ({});const toItem = (r: ItemRow): CinemaItem => {- const meta = parse<{ tiles?: CinemaTile[] }>(r.meta_json, {});- return { generationId: r.generation_id, folderId: r.folder_id, createdAt: r.created_at, ...(meta.tiles?.length ? { tiles: meta.tiles } : {}) };+ const meta = parse<{ tiles?: CinemaTile[]; take?: CinemaTakeInfo }>(r.meta_json, {});+ return {+ generationId: r.generation_id,+ folderId: r.folder_id,+ createdAt: r.created_at,+ ...(meta.tiles?.length ? { tiles: meta.tiles } : {}),+ ...(meta.take ? { take: meta.take } : {}),+ };};/** A generation that still exists (soft-deleted rows from the Trash, when there is one, are left out). */@@ -262,7 +268,12 @@ export function descendants(projectId: string, folderId: string): Set<string> {let grew = true;while (grew) {grew = false;- for (const f of folders) if (f.parentId && out.has(f.parentId) && !out.has(f.id)) (out.add(f.id), (grew = true));+ for (const f of folders) {+ if (f.parentId && out.has(f.parentId) && !out.has(f.id)) {+ out.add(f.id);+ grew = true;+ }+ }}return out;}@@ -331,7 +342,7 @@ export function deleteFolder(projectId: string, id: string): void {// ---------------------------------------------------------------------------// Items: the project's generations-export type CinemaGeneration = Generation & { folderId: string | null; tiles?: CinemaTile[] };+export type CinemaGeneration = Generation & { folderId: string | null; tiles?: CinemaTile[]; take?: CinemaTakeInfo };export interface ItemQuery {/** A folder id; null = the project root only; undefined = everything in the project. */@@ -355,7 +366,7 @@ export function listItems(projectId: string, q: ItemQuery = {}): CinemaGeneratioif (!g) continue;if (q.favorites && !g.favorite) continue;const item = toItem(r);- out.push({ ...g, folderId: item.folderId, ...(item.tiles ? { tiles: item.tiles } : {}) });+ out.push({ ...g, folderId: item.folderId, ...(item.tiles ? { tiles: item.tiles } : {}), ...(item.take ? { take: item.take } : {}) });}return out.sort((a, b) => b.createdAt - a.createdAt);}@@ -370,12 +381,13 @@ export function listStudioGenerations(): CinemaGeneration[] {.map((g) => ({ ...g, folderId: folders.get(g.id) ?? null }));}-export function addItems(projectId: string, generationIds: string[], folderId: string | null = null): void {+export function addItems(projectId: string, generationIds: string[], folderId: string | null = null, take?: CinemaTakeInfo): void {requireProject(projectId);if (folderId) checkParent(projectId, folderId);const now = Date.now();- const ins = db().prepare("INSERT OR IGNORE INTO cinema_items (project_id, generation_id, folder_id, meta_json, created_at) VALUES (?, ?, ?, NULL, ?)");- db().transaction(() => generationIds.forEach((id, i) => ins.run(projectId, id, folderId, now + i)))();+ const meta = take ? JSON.stringify({ take }) : null;+ const ins = db().prepare("INSERT OR IGNORE INTO cinema_items (project_id, generation_id, folder_id, meta_json, created_at) VALUES (?, ?, ?, ?, ?)");+ db().transaction(() => generationIds.forEach((id, i) => ins.run(projectId, id, folderId, meta, now + i)))();touch(projectId);}@@ -406,6 +418,27 @@ export function setFavorites(projectId: string, generationIds: string[], favoritdb().transaction(() => generationIds.forEach((id) => up.run(favorite ? 1 : 0, Date.now(), id, projectId)))();}+/**+ * Run a failed or canceled take again, in the same folder. A chained step that already got its+ * inputs runs on its own; one whose earlier step failed needs that step retried first.+ */+export function retryItem(projectId: string, generationId: string): Generation[] {+ const r = db().prepare("SELECT * FROM cinema_items WHERE project_id = ? AND generation_id = ?").get(projectId, generationId) as ItemRow | undefined;+ const g = r ? liveGeneration(generationId) : null;+ if (!r || !g) throw new CinemaError("That take isn't in this project", 404);+ const req = { ...g.request };+ if (req.chain?.length || req.chainFrom) {+ const filled = req.chain?.every((c) => (c.slot === "images" || c.slot === "videos" ? (req.inputs?.[c.slot]?.length ?? 0) > 0 : c.slot === "prompt" ? !!req.prompt : !!req.inputs?.[c.slot]));+ if (!filled) throw new CinemaError("An earlier step of this take didn't finish — retry that one first", 422);+ delete req.chain;+ delete req.chainFrom;+ }+ const created = createGenerations(req, g.batchId ? { batchId: g.batchId } : {});+ const item = toItem(r);+ addItems(projectId, created.map((x) => x.id), item.folderId, item.take);+ return created;+}+export function setTiles(projectId: string, generationId: string, tiles: CinemaTile[]): CinemaItem {const r = db().prepare("SELECT * FROM cinema_items WHERE project_id = ? AND generation_id = ?").get(projectId, generationId) as ItemRow | undefined;if (!r) throw new CinemaError("That take isn't in this project", 404);