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 workspace: scoped shortcuts, autosave flush, narrow prompt bar, owner-aware actions
Claudecd5746024585
diff --git a/src/app/api/cinema/projects/[id]/items/route.ts b/src/app/api/cinema/projects/[id]/items/route.tsindex 7e73ca97..231293cf 100644--- a/src/app/api/cinema/projects/[id]/items/route.ts+++ b/src/app/api/cinema/projects/[id]/items/route.ts@@ -28,9 +28,10 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/cinema/proreturn handle(async () => {const { id } = await ctx.params;const b = await body(request, ItemsPatch, "Pick the takes to change");- if (b.folderId !== undefined) moveItems(id, b.ids, b.folderId);- if (b.favorite !== undefined) setFavorites(id, b.ids, b.favorite);- return Response.json({ ok: true });+ // Only this project's takes change; the counts say how many did.+ const moved = b.folderId !== undefined ? moveItems(id, b.ids, b.folderId) : 0;+ const liked = b.favorite !== undefined ? setFavorites(id, b.ids, b.favorite) : 0;+ return Response.json({ ok: true, moved, liked });});}diff --git a/src/components/cinema/autosave.ts b/src/components/cinema/autosave.tsnew file mode 100644index 00000000..584d0914--- /dev/null+++ b/src/components/cinema/autosave.ts@@ -0,0 +1,44 @@+/**+ * A debounced save that never drops the last edit: `schedule` saves a moment after the last change,+ * `flush` saves what's pending right away (on unmount, when the tab is hidden, when the page goes+ * away — then with `keepalive` so the request outlives the page). Pure, so it's tested without a DOM.+ */+export class Autosaver<T> {+ private pending: { value: T } | null = null;+ private timer: ReturnType<typeof setTimeout> | null = null;++ constructor(+ private save: (value: T, opts: { keepalive: boolean }) => void,+ private readonly delay: number,+ ) {}++ /** Swap in the latest save function (it closes over fresh props). */+ setSave(save: (value: T, opts: { keepalive: boolean }) => void): void {+ this.save = save;+ }++ schedule(value: T): void {+ this.pending = { value };+ if (this.timer) clearTimeout(this.timer);+ this.timer = setTimeout(() => this.flush(), this.delay);+ }++ flush(keepalive = false): void {+ if (this.timer) clearTimeout(this.timer);+ this.timer = null;+ const p = this.pending;+ this.pending = null;+ if (p) this.save(p.value, { keepalive });+ }++ /** Forget a pending save (the value was replaced from elsewhere). */+ cancel(): void {+ if (this.timer) clearTimeout(this.timer);+ this.timer = null;+ this.pending = null;+ }++ get dirty(): boolean {+ return this.pending !== null;+ }+}diff --git a/src/components/cinema/cinema-feed.tsx b/src/components/cinema/cinema-feed.tsxindex 8f1b48f9..67d7fea7 100644--- a/src/components/cinema/cinema-feed.tsx+++ b/src/components/cinema/cinema-feed.tsx@@ -2,10 +2,11 @@import {CalendarDays,- Check,Clapperboard,+ ExternalLink,Copy,Download,+ Eye,FastForward,FolderInput,Grid3x3,@@ -24,20 +25,24 @@ import {X,} from "lucide-react";import { useQueryClient } from "@tanstack/react-query";+import Link from "next/link";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 {+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ 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";@@ -49,7 +54,7 @@ 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";+import { foreign, useItemActions, type CinemaGeneration } from "./hooks";type Layout = "square" | "masonry" | "list";type TypeFilter = "all" | "image" | "video" | "audio";@@ -156,9 +161,16 @@ export interface FeedHandlers {onSaveElement: (g: CinemaGeneration, url: string, kind: "character" | "location") => void;}+/** A grid contact sheet and its tiles are one take: deleting any of them deletes the lot. */+export function deleteLabel(g: CinemaGeneration): string {+ const tiles = g.tiles?.length ?? (g.feature === "cinema-grid" && g.outputs.length > 1 ? g.outputs.length - 1 : 0);+ return tiles ? `Delete grid (sheet + ${tiles} tiles)` : "Delete take";+}+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;+ const elsewhere = foreign(u.g, projectId);return (<DropdownMenu><DropdownMenuTrigger asChild>@@ -171,7 +183,7 @@ function TileMenu({ u, folders, projectId, handlers, onDelete }: { u: Unit; fold<MoreHorizontal className="size-4" /></button></DropdownMenuTrigger>- <DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>+ <DropdownMenuContent align="end" className="w-56" onClick={(e) => e.stopPropagation()}><DropdownMenuItem onClick={() => handlers.onLoad(u.g)}><RotateCcw /> Load into prompt bar</DropdownMenuItem>@@ -208,7 +220,7 @@ function TileMenu({ u, folders, projectId, handlers, onDelete }: { u: Unit; fold</a></DropdownMenuItem>)}- <DropdownMenuItem onClick={() => void actions.favorite([u.g.id], !u.g.favorite)}>+ <DropdownMenuItem onClick={() => void actions.favorite([u.g.id], !u.g.favorite).catch((e) => toast.error((e as Error).message))}><Heart /> {u.g.favorite ? "Unlike" : "Like"}</DropdownMenuItem><DropdownMenuItem@@ -219,19 +231,36 @@ function TileMenu({ u, folders, projectId, handlers, onDelete }: { u: Unit; fold><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>+ {elsewhere ? (+ // Another project's take (My Generations): it moves within its own project.+ <DropdownMenuItem asChild>+ <Link href={`/cinema/${u.g.projectId}`}>+ <ExternalLink /> Open its project+ </Link>+ </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((n) => toast(n ? "Moved" : "That take isn't in this project", { duration: 1500 }))+ .catch((e) => toast.error((e as Error).message))+ }+ />+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ ))}<DropdownMenuSeparator /><DropdownMenuItem variant="destructive" onClick={() => onDelete([u.g.id])}>- <Trash2 /> Delete take+ <Trash2 /> {deleteLabel(u.g)}</DropdownMenuItem></DropdownMenuContent></DropdownMenu>@@ -274,7 +303,7 @@ function TileView({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))} />+ <FailedTile g={g} ratio={aspect} onRetry={() => void actions.retry(g).catch((e) => toast.error((e as Error).message))} />) : (<div className={cn("relative size-full", fit && "bg-muted")}>{/* Behind the video: visible until (or if) the browser can draw its first frame. */}@@ -332,44 +361,50 @@ function TileView({</div>);}- return (- <div- role={clickable ? "button" : undefined}- tabIndex={clickable ? 0 : undefined}- aria-label={clickable ? `${step ? `${step}: ` : ""}${promptOf(g)}` : undefined}- draggable={!u.tile}- onDragStart={(e) => e.dataTransfer.setData("application/x-cinema-takes", JSON.stringify(dragIds()))}+ // The tile opens (or, while selecting, toggles) through a real button laid over the media, next to+ // the checkbox and the action buttons rather than around them (no nested interactive controls).+ const overlay = (clickable || selecting) && (+ <button+ type="button"+ aria-label={selecting ? `${selected ? "Unselect" : "Select"}: ${promptOf(g)}` : `Open ${step ? `${step}: ` : ""}${promptOf(g)}`}+ aria-pressed={selecting ? selected : undefined}onClick={(e) => {if (selecting || e.metaKey || e.ctrlKey || e.shiftKey) onToggle(e.shiftKey);- else if (clickable) onOpen();+ else onOpen();}}onKeyDown={(e) => {- if (e.key === "Enter" && clickable) onOpen();- if (e.key === " ") {+ if (e.key === " " && !selecting) {e.preventDefault();onToggle(false);}}}+ className={cn("absolute inset-0 rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset", clickable && !selecting && "cursor-zoom-in")}+ />+ );+ return (+ <div+ draggable={!u.tile}+ onDragStart={(e) => e.dataTransfer.setData("application/x-cinema-takes", JSON.stringify(dragIds()))}className={cn(- "group/tile relative overflow-hidden rounded-xl bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring",+ "group/tile relative overflow-hidden rounded-xl bg-muted",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}+ {overlay}{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="pointer-events-none 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()}>+ <div className="pointer-events-auto flex shrink-0 items-center gap-0.5">{u.output?.kind === "video" && (<Tooltip><TooltipTrigger asChild>@@ -468,7 +503,6 @@ export function CinemaFeed({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());@@ -527,25 +561,60 @@ export function CinemaFeed({}, [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";+ // Delete moves to the Trash (the takes stay filed in their project): Undo puts them back.const del = async (list: string[]) => {- await actions.remove(list);setSelected(new Set());- toast(list.length > 1 ? `${list.length} takes deleted` : "Deleted", { duration: 1500 });+ try {+ await actions.remove(list);+ } catch (e) {+ toast.error((e as Error).message);+ return;+ }+ toast(list.length > 1 ? `${list.length} takes moved to Trash` : "Moved to Trash", {+ id: "cinema-trash",+ duration: 6000,+ action: { label: "Undo", onClick: () => void actions.restore(list).catch((e) => toast.error((e as Error).message)) },+ });};+ const own = live.filter((id) => !items.some((g) => g.id === id && foreign(g, projectId)));+ const layouts = [+ ["square", LayoutGrid, "Square"],+ ["masonry", Rows3, "Masonry"],+ ["list", List, "List"],+ ] as const;return (<div className="space-y-4"><div className="flex flex-wrap items-center gap-2">- <div className="min-w-0 flex-1">{title}</div>+ <div className="min-w-0 basis-full sm:basis-auto sm: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]) => (+ {/* Phones: layout, split and fit share one View menu so the toolbar fits on a line. */}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button type="button" className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary px-3 text-[12.5px] font-medium hover:bg-accent sm:hidden" aria-label="View options">+ <Eye className="size-3.5" /> View+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-52">+ <DropdownMenuLabel>Layout</DropdownMenuLabel>+ <DropdownMenuRadioGroup value={prefs.layout} onValueChange={(v) => setPrefs({ layout: v as Layout })}>+ {layouts.map(([id, Icon, label]) => (+ <DropdownMenuRadioItem key={id} value={id}>+ <Icon /> {label}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ <DropdownMenuSeparator />+ <DropdownMenuCheckboxItem checked={prefs.split} onCheckedChange={(split) => setPrefs({ split: !!split })}>+ Split by date+ </DropdownMenuCheckboxItem>+ <DropdownMenuCheckboxItem checked={prefs.fit} onCheckedChange={(fit) => setPrefs({ fit: !!fit })}>+ Fit previews (whole frame)+ </DropdownMenuCheckboxItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <div className="hidden h-8 rounded-full bg-muted p-0.5 sm:inline-flex" role="radiogroup" aria-label="Layout">+ {layouts.map(([id, Icon, label]) => (<Tooltip key={id}><TooltipTrigger asChild><button@@ -565,7 +634,7 @@ export function CinemaFeed({</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">+ <button type="button" aria-pressed={prefs.split} onClick={() => setPrefs({ split: !prefs.split })} className={cn("hidden size-8 place-items-center rounded-full sm:grid", 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>@@ -573,7 +642,7 @@ export function CinemaFeed({</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"}>+ <button type="button" aria-pressed={prefs.fit} onClick={() => setPrefs({ fit: !prefs.fit })} className={cn("hidden h-8 items-center rounded-full px-2.5 text-[12px] font-medium sm:inline-flex", 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>@@ -590,28 +659,38 @@ export function CinemaFeed({<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">+ <button+ type="button"+ onClick={() => void actions.favorite(live, !items.filter((g) => live.includes(g.id)).every((g) => g.favorite)).catch((e) => toast.error((e as Error).message))}+ 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">+ {own.length > 0 && (+ <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">+ {own.length < live.length && <DropdownMenuLabel className="text-[11.5px] font-normal text-muted-foreground">Takes from other projects stay where they are</DropdownMenuLabel>}+ <MoveToItems+ folders={folders}+ onMove={(f) =>+ void actions+ .move(own, f)+ .then((n) => {+ toast(`Moved ${n} take${n === 1 ? "" : "s"}`, { duration: 1500 });+ setSelected(new Set());+ })+ .catch((e) => toast.error((e as Error).message))+ }+ />+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ <button type="button" onClick={() => void del(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>@@ -647,7 +726,7 @@ export function CinemaFeed({projectId={projectId}folders={folders}handlers={handlers}- onDelete={(list) => setConfirm(list)}+ onDelete={(list) => void del(list)}dragIds={() => (selected.has(u.g.id) ? live : [u.g.id])}/>))}@@ -665,6 +744,7 @@ export function CinemaFeed({setOpen(null);// The viewer likes and deletes through /api/generations: pick those changes up.void qc.invalidateQueries({ queryKey: ["cinema", projectId, "items"] });+ void qc.invalidateQueries({ queryKey: ["cinema", "studio"] });}}onPrev={pos > 0 ? () => setOpen(viewable[pos - 1].key) : undefined}onNext={pos < viewable.length - 1 ? () => setOpen(viewable[pos + 1].key) : undefined}@@ -672,26 +752,6 @@ export function CinemaFeed({/>)}- <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.tsxindex aef1c98a..a35fc0c6 100644--- a/src/components/cinema/director-panel.tsx+++ b/src/components/cinema/director-panel.tsx@@ -402,6 +402,38 @@ const PRESET_LIGHT: Record<string, LightSource[]> = {"soft-cross": [{ direction: "front-left", color: "#fff6ea", brightness: 70, diffuse: 85 }, { direction: "right", color: "#dfe8ff", brightness: 45, diffuse: 85 }],};+const HEX = /^#[0-9a-f]{6}$/i;++/** A hex field that only hands on complete colours: "#ff" while typing stays local, and blur puts the last good one back. */+function HexInput({ value, onChange, label }: { value: string; onChange: (hex: string) => void; label: string }) {+ const [text, setText] = useState(value);+ const [shown, setShown] = useState(value);+ // The colour changed elsewhere (the picker, a preset): show it.+ if (value !== shown) {+ setShown(value);+ setText(value);+ }+ return (+ <Input+ value={text}+ onChange={(e) => {+ const raw = e.target.value.trim().slice(0, 7);+ const v = raw.startsWith("#") ? raw : `#${raw.slice(0, 6)}`;+ setText(v);+ if (HEX.test(v)) {+ setShown(v.toLowerCase());+ onChange(v.toLowerCase());+ }+ }}+ onBlur={() => setText(value)}+ spellCheck={false}+ aria-invalid={!HEX.test(text) || undefined}+ className="h-7 w-24 font-mono text-[12px]"+ aria-label={label}+ />+ );+}+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">@@ -444,15 +476,8 @@ function LightEditor({ light, index, onChange, onRemove }: { light: LightSource;</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`}- />+ <HexInput value={light.color} onChange={(color) => onChange({ ...light, color })} label={`Light ${index + 1} hex colour`} />+</div>{(["brightness", "diffuse"] as const).map((k) => (<div key={k} className="space-y-1">diff --git a/src/components/cinema/folder-sidebar.tsx b/src/components/cinema/folder-sidebar.tsxindex 1e933d7b..32d2753b 100644--- a/src/components/cinema/folder-sidebar.tsx+++ b/src/components/cinema/folder-sidebar.tsx@@ -1,8 +1,18 @@"use client";-import { ArrowDownAZ, AtSign, ChevronRight, Clock, Folder, FolderInput, FolderPlus, Heart, Home, Library, ListOrdered, MoreHorizontal, Pencil, Pin, PinOff, Search, Trash2 } from "lucide-react";+import { ArrowDown, ArrowDownAZ, ArrowUp, 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 {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";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";@@ -18,7 +28,8 @@ export const viewKey = (v: CinemaView) => (v.kind === "folder" ? `folder:${v.id}/** 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 type FolderSort = "manual" | "name" | "recent";+type Sort = FolderSort;export interface FolderNode extends CinemaFolder {children: FolderNode[];@@ -37,6 +48,24 @@ export function folderTree(folders: CinemaFolder[], sort: Sort = "manual"): Foldreturn build(null, 0);}+/**+ * Positions after moving `id` one step up (-1) or down (+1) among its siblings with the same pin+ * state (pinned folders always sort first). Only the folders whose position changes are returned;+ * tied positions (older folders) are spread out so the new order sticks.+ */+export function reorderFolders(siblings: Pick<CinemaFolder, "id" | "pinned" | "position">[], id: string, dir: -1 | 1): { id: string; position: number }[] {+ const me = siblings.find((s) => s.id === id);+ if (!me) return [];+ const group = siblings.filter((s) => s.pinned === me.pinned);+ const i = group.findIndex((s) => s.id === id);+ const j = i + dir;+ if (j < 0 || j >= group.length) return [];+ const order = group.map((s) => s.id);+ [order[i], order[j]] = [order[j], order[i]];+ const base = Math.min(...group.map((s) => s.position));+ return order.map((x, k) => ({ id: x, position: base + k })).filter((c) => group.find((s) => s.id === c.id)!.position !== c.position);+}+export function flattenTree(nodes: FolderNode[]): FolderNode[] {return nodes.flatMap((n) => [n, ...flattenTree(n.children)]);}@@ -78,6 +107,8 @@ export function MoveToItems({ folders, onMove, exclude }: { folders: CinemaFoldefunction FolderRow({node,+ siblings,+ sort,folders,view,setView,@@ -88,6 +119,9 @@ function FolderRow({onDropItems,}: {node: FolderNode;+ /** The folders next to this one, in the order shown (Move up / Move down). */+ siblings: FolderNode[];+ sort: Sort;folders: CinemaFolder[];view: CinemaView;setView: (v: CinemaView) => void;@@ -98,11 +132,17 @@ function FolderRow({onDropItems: (ids: string[], folderId: string) => void;}) {const actions = useFolderActions(projectId);+ const [confirmDelete, setConfirmDelete] = useState(false);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 group = siblings.filter((s) => s.pinned === node.pinned);+ const at = group.findIndex((s) => s.id === node.id);+ const reorder = (dir: -1 | 1) =>+ void Promise.all(reorderFolders(siblings, node.id, dir).map((c) => actions.update(c.id, { position: c.position }))).catch((e) => toast.error((e as Error).message));+ const parent = node.parentId ? folders.find((f) => f.id === node.parentId) : undefined;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));@@ -182,6 +222,16 @@ function FolderRow({<DropdownMenuItem onClick={() => void actions.update(node.id, { pinned: !node.pinned })}>{node.pinned ? <PinOff /> : <Pin />} {node.pinned ? "Unpin" : "Pin"}</DropdownMenuItem>+ {sort === "manual" && group.length > 1 && (+ <>+ <DropdownMenuItem disabled={at <= 0} onClick={() => reorder(-1)}>+ <ArrowUp /> Move up+ </DropdownMenuItem>+ <DropdownMenuItem disabled={at < 0 || at >= group.length - 1} onClick={() => reorder(1)}>+ <ArrowDown /> Move down+ </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) => (@@ -204,24 +254,43 @@ function FolderRow({</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");- })- }- >+ <DropdownMenuItem variant="destructive" onClick={() => setConfirmDelete(true)}><Trash2 /> Delete folder</DropdownMenuItem></DropdownMenuContent></DropdownMenu></div>+ <AlertDialog open={confirmDelete} onOpenChange={setConfirmDelete}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete “{node.name}”?</AlertDialogTitle>+ <AlertDialogDescription>+ Its takes{node.children.length ? " and subfolders" : ""} move up to {parent ? `“${parent.name}”` : "Home"}. No take is deleted.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() =>+ void actions+ .remove(node.id)+ .then(() => {+ if (active) setView(parent ? { kind: "folder", id: parent.id } : { kind: "home" });+ toast(`Folder deleted — its takes moved to ${parent ? parent.name : "Home"}`);+ })+ .catch((e) => toast.error((e as Error).message))+ }+ >+ Delete folder+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>{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} />+ <FolderRow key={c.id} node={c} siblings={node.children} sort={sort} folders={folders} view={view} setView={setView} open={open} toggle={toggle} counts={counts} projectId={projectId} onDropItems={onDropItems} />))}</ul>)}@@ -318,8 +387,22 @@ export function FolderSidebar({{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} />+ <FolderRow+ key={n.id}+ node={n}+ siblings={q ? [] : matches}+ sort={sort}+ 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>) : (diff --git a/src/components/cinema/hooks.ts b/src/components/cinema/hooks.tsindex 6765bb8a..6c1932ec 100644--- a/src/components/cinema/hooks.ts+++ b/src/components/cinema/hooks.ts@@ -1,12 +1,16 @@"use client";-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import type { CinemaFolder, CinemaGenerateInput, CinemaProject, CinemaTakeInfo, CinemaTile, DirectorMessage, DirectorSettings } from "@/lib/catalog/cinema";+import { useMutation, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";+import { useEffect, useState, useSyncExternalStore } from "react";+import type { CinemaFolder, CinemaGenerateInput, CinemaProject, CinemaTile, DirectorMessage, DirectorSettings } from "@/lib/catalog/cinema";import type { Generation } from "@/lib/catalog/types";+import { toStreamEvent } from "@/lib/generation-stream";+import { Autosaver } from "./autosave";+import { applyToTakes, type CinemaGeneration } from "./live";/** 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 type { CinemaGeneration };export interface ProjectView {project: CinemaProject;@@ -22,11 +26,71 @@ async function json<T>(res: Response): Promise<T> {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) }));+/** `keepalive` lets a save finish after the page is gone (tab closed, reload). */+const send = async <T,>(url: string, method: string, body?: unknown, keepalive = false) =>+ json<T>(await fetch(url, { method, keepalive, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }));const active = (g: Generation) => g.status === "queued" || g.status === "running";+// ---------------------------------------------------------------------------+// Live updates: one EventSource on GET /api/generations/stream for the workspace's lists. While it's+// connected the takes update in place and polling drops to a slow safety net.++const live = { es: null as EventSource | null, users: 0, connected: false, client: null as QueryClient | null, listeners: new Set<() => void>() };++function setConnected(v: boolean) {+ if (live.connected === v) return;+ live.connected = v;+ live.listeners.forEach((l) => l());+}++function applyEvent(qc: QueryClient, data: string, event: string) {+ const ev = toStreamEvent({ event, data });+ if (!ev) return;+ for (const q of qc.getQueryCache().findAll({ queryKey: ["cinema"] })) {+ const k = q.queryKey;+ if (!(k[2] === "items" || k[1] === "studio")) continue;+ const old = q.state.data as CinemaGeneration[] | undefined;+ const next = applyToTakes(old, ev);+ if (next !== old) qc.setQueryData(k, next);+ }+}++function useCinemaStream(): boolean {+ const qc = useQueryClient();+ useEffect(() => {+ live.client = qc;+ live.users++;+ if (!live.es && typeof EventSource !== "undefined") {+ const es = new EventSource("/api/generations/stream");+ es.onopen = () => setConnected(true);+ es.onerror = () => setConnected(false);+ for (const event of ["generation", "deleted"]) es.addEventListener(event, (m) => live.client && applyEvent(live.client, (m as MessageEvent<string>).data, event));+ live.es = es;+ }+ return () => {+ live.users--;+ if (live.users) return;+ live.es?.close();+ live.es = null;+ setConnected(false);+ };+ }, [qc]);+ return useSyncExternalStore(+ (cb) => {+ live.listeners.add(cb);+ return () => live.listeners.delete(cb);+ },+ () => live.connected,+ () => false,+ );+}++const pollEvery = (items: Generation[] | undefined, connected: boolean) => (items?.some(active) ? (connected ? 10_000 : 1500) : false);++// ---------------------------------------------------------------------------+// Queries+export function useCinemaProjects() {return useQuery({queryKey: ["cinema", "projects"],@@ -42,22 +106,24 @@ export function useCinemaProject(id: string) {});}-/** Every take in the project (folders are filtered in the browser); polls while anything renders. */+/** Every take in the project (folders are filtered in the browser); live, with polling as a fallback. */export function useCinemaItems(id: string) {+ const connected = useCinemaStream();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),+ refetchInterval: (q) => pollEvery(q.state.data, connected),});}-/** "My Generations": every Cinema Studio generation, in any project. */+/** "My Generations": every Cinema Studio generation, in any project (each with its projectId). */export function useStudioGenerations(id: string, enabled: boolean) {+ const connected = useCinemaStream();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),+ refetchInterval: (q) => pollEvery(q.state.data, connected),});}@@ -80,11 +146,17 @@ export interface ProjectPatch {pinned?: boolean;}+/** A patch plus `keepalive` for saves that must outlive the page (autosave on tab close). */+export type ProjectSave = ProjectPatch & { keepalive?: boolean };++const patchOf = ({ keepalive, ...patch }: ProjectSave): ProjectPatch => (void keepalive, patch);+export function useUpdateProject(id: string) {const qc = useQueryClient();return useMutation({- mutationFn: (patch: ProjectPatch) => send<CinemaProject>(`/api/cinema/projects/${id}`, "PATCH", patch),- onMutate: (patch) => {+ mutationFn: (save: ProjectSave) => send<CinemaProject>(`/api/cinema/projects/${id}`, "PATCH", patchOf(save), !!save.keepalive),+ onMutate: (save) => {+ const patch = patchOf(save);qc.setQueryData<ProjectView>(["cinema", id], (old) =>old ? { ...old, project: { ...old.project, ...patch, brief: { ...old.project.brief, ...patch.brief } } as CinemaProject } : old,);@@ -96,6 +168,30 @@ export function useUpdateProject(id: string) {});}+/**+ * A debounced autosave that never loses the last edit: it saves `delay` ms after the last change, and+ * right away when the component unmounts (a closed panel, a tab switch, leaving the page) or the+ * browser tab is hidden or closed (then with keepalive).+ */+export function useAutosave<T>(save: (value: T, opts: { keepalive: boolean }) => void, delay: number): Autosaver<T> {+ const [saver] = useState(() => new Autosaver(save, delay));+ useEffect(() => saver.setSave(save));+ useEffect(() => {+ const hide = () => {+ if (document.visibilityState === "hidden") saver.flush(true);+ };+ const exit = () => saver.flush(true);+ document.addEventListener("visibilitychange", hide);+ window.addEventListener("pagehide", exit);+ return () => {+ document.removeEventListener("visibilitychange", hide);+ window.removeEventListener("pagehide", exit);+ saver.flush();+ };+ }, [saver]);+ return saver;+}+export function useDeleteProject() {const qc = useQueryClient();return useMutation({@@ -130,35 +226,51 @@ export function useFolderActions(projectId: string) {};}+/** Whether a listed take belongs to another project (only "My Generations" shows those). */+export const foreign = (g: CinemaGeneration, projectId: string) => !!g.projectId && g.projectId !== projectId;++/**+ * Actions on takes. Likes and deletes go through the library (/api/generations/bulk) so they work+ * on any project's take; Delete moves to the Trash and comes with Undo. Moves are this project's+ * only; retries go to the project that owns the take.+ */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 keys = [["cinema", projectId, "items"], ["cinema", "studio"]];+ const patchLocal = (ids: string[], fn: (g: CinemaGeneration) => CinemaGeneration | null) => {+ for (const key of keys) 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: ["cinema"] });void qc.invalidateQueries({ queryKey: ["generations"] });+ void qc.invalidateQueries({ queryKey: ["library"] });+ void qc.invalidateQueries({ queryKey: ["library-facets"] });};+ const bulk = (action: "favorite" | "unfavorite" | "trash" | "restore", ids: string[]) => send<{ count: number }>("/api/generations/bulk", "POST", { action, ids });return {+ /** Move this project's takes to a folder; returns how many moved. */move: async (ids: string[], folderId: string | null) => {- patchLocal(ids, (g) => ({ ...g, folderId }));- await send(`/api/cinema/projects/${projectId}/items`, "PATCH", { ids, folderId }).finally(settle);+ patchLocal(ids, (g) => (foreign(g, projectId) ? g : { ...g, folderId }));+ return (await send<{ moved: number }>(`/api/cinema/projects/${projectId}/items`, "PATCH", { ids, folderId }).finally(settle)).moved;},favorite: async (ids: string[], favorite: boolean) => {patchLocal(ids, (g) => ({ ...g, favorite }));- await send(`/api/cinema/projects/${projectId}/items`, "PATCH", { ids, favorite }).finally(settle);+ await bulk(favorite ? "favorite" : "unfavorite", ids).finally(settle);},+ /** Move to the Trash (restore with `restore`): the takes stay filed in their project. */remove: async (ids: string[]) => {patchLocal(ids, () => null);- await send(`/api/cinema/projects/${projectId}/items`, "DELETE", { ids, deleteGenerations: true }).finally(settle);+ await bulk("trash", ids).finally(settle);+ },+ restore: async (ids: string[]) => {+ await bulk("restore", ids).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);+ retry: async (g: CinemaGeneration) => {+ await send(`/api/cinema/projects/${g.projectId ?? projectId}/items/${g.id}/retry`, "POST").finally(settle);},saveTiles: async (generationId: string, tiles: CinemaTile[]) => {await send(`/api/cinema/projects/${projectId}/items/${generationId}/tiles`, "PUT", { tiles });@@ -168,15 +280,17 @@ export function useItemActions(projectId: string) {}export type GenerateBody = { input: Omit<CinemaGenerateInput, "brief">; folderId: string | null };+export type GenerateResult = { items: Generation[]; folderId: string | null; plan: { notes: string[]; costUsd: number | null; outputs: number; modelId: string } };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),+ mutationFn: (body: GenerateBody) => send<GenerateResult>(`/api/cinema/projects/${projectId}/generate`, "POST", body),onSuccess: (res, body) => {- // New takes appear at once; polling takes over.+ // New takes appear at once (where the server filed them); the stream and polling take over.+ const folderId = res.folderId === undefined ? body.folderId : res.folderId;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,+ old ? [...res.items.map((g) => ({ ...g, folderId, projectId, 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] });},diff --git a/src/components/cinema/live.ts b/src/components/cinema/live.tsnew file mode 100644index 00000000..020dee7f--- /dev/null+++ b/src/components/cinema/live.ts@@ -0,0 +1,32 @@+import type { CinemaTakeInfo, CinemaTile } from "@/lib/catalog/cinema";+import type { Generation } from "@/lib/catalog/types";+import type { StreamEvent } from "@/lib/generation-stream";++/** A take as the workspace lists it: the generation plus where the project files it. */+export type CinemaGeneration = Generation & {+ folderId: string | null;+ tiles?: CinemaTile[];+ take?: CinemaTakeInfo;+ /** The project the take belongs to (set on every item; "My Generations" mixes projects). */+ projectId?: string | null;+};++/**+ * Apply one live event (GET /api/generations/stream) to a cached list of takes. Known takes are+ * updated in place, keeping what the project adds (its folder, tiles, take info): the stream's+ * folderId is the library's, not the scene's. Deleted or trashed takes leave the list. Unknown ids+ * are ignored (new takes arrive with the generate response). Returns the same array when nothing+ * changed, so React Query keeps every tile as it is.+ */+export function applyToTakes<T extends CinemaGeneration>(list: T[] | undefined, ev: StreamEvent): T[] | undefined {+ if (!list) return list;+ const id = ev.type === "deleted" ? ev.id : ev.generation.id;+ const at = list.findIndex((g) => g.id === id);+ if (at < 0) return list;+ if (ev.type === "deleted" || ev.generation.deletedAt) return list.filter((g) => g.id !== id);+ const old = list[at];+ if (old.updatedAt > ev.generation.updatedAt) return list;+ const next = list.slice();+ next[at] = { ...ev.generation, folderId: old.folderId, projectId: old.projectId, tiles: old.tiles, take: old.take } as T;+ return next;+}diff --git a/src/components/cinema/money.ts b/src/components/cinema/money.tsnew file mode 100644index 00000000..8a3b4841--- /dev/null+++ b/src/components/cinema/money.ts@@ -0,0 +1,11 @@+/**+ * Money spent or allowed (project spend, cost caps): "$0.00", "<$0.01", "$1.25". formatCost's+ * "Free" is for prices, not for what was spent. Kept apart from the catalog so the projects list+ * doesn't load it.+ */+export function formatUsd(usd: number | null | undefined): string {+ const v = usd ?? 0;+ if (v <= 0) return "$0.00";+ if (v < 0.01) return "<$0.01";+ return `$${v.toFixed(2)}`;+}diff --git a/src/components/cinema/palette-editor.tsx b/src/components/cinema/palette-editor.tsxindex ed4163d4..6ce2e9ed 100644--- a/src/components/cinema/palette-editor.tsx+++ b/src/components/cinema/palette-editor.tsx@@ -8,7 +8,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, Dimport { 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";+import { HARMONIES, harmonyPalette, hexToRgb, hslToHex, kmeans, rgbToHex, rgbToHsl, type Harmony, type RGB } from "./color-math";interface Point {/** 0–1 across the image. */@@ -188,72 +188,157 @@ function FromImage({ onColors }: { onColors: (hex: string[]) => void }) {const WHEEL_BASE = "#c0583a";+/** Where a hue (degrees, 0 = top, clockwise) and saturation (0–1) sit on the wheel, in % of its box. */+function wheelSpot(hue: number, sat: number): { left: string; top: string } {+ const a = (hue * Math.PI) / 180;+ const r = Math.max(0, Math.min(1, sat)) * 46;+ return { left: `${50 + r * Math.sin(a)}%`, top: `${50 - r * Math.cos(a)}%` };+}++/**+ * An HSL colour wheel: drag (or use the arrow keys on) the base handle to pick hue and saturation;+ * the harmony's other hues show as markers that turn with it.+ */+function HueWheel({ base, harmony, onBase }: { base: string; harmony: Harmony; onBase: (hex: string) => void }) {+ const ref = useRef<HTMLDivElement>(null);+ const [h, s, l] = rgbToHsl(hexToRgb(base));+ // Very dark or light bases pick at mid lightness, so the wheel still shows a change.+ const light = l < 0.2 || l > 0.8 ? 0.5 : l;+ const offsets = (HARMONIES.find((x) => x.id === harmony)?.offsets ?? [0]).filter((o) => o !== 0);+ const pick = (e: React.PointerEvent) => {+ const box = ref.current?.getBoundingClientRect();+ if (!box) return;+ const x = e.clientX - box.left - box.width / 2;+ const y = e.clientY - box.top - box.height / 2;+ const hue = ((Math.atan2(x, -y) * 180) / Math.PI + 360) % 360;+ const sat = Math.max(0.05, Math.min(1, Math.hypot(x, y) / ((box.width / 2) * 0.92)));+ onBase(hslToHex(hue, sat, light));+ };+ return (+ <div+ ref={ref}+ role="slider"+ tabIndex={0}+ aria-label="Base colour on the wheel (arrows: left/right hue, up/down saturation)"+ aria-valuemin={0}+ aria-valuemax={359}+ aria-valuenow={Math.round(h)}+ aria-valuetext={`Hue ${Math.round(h)}°, saturation ${Math.round(s * 100)}%`}+ onPointerDown={(e) => {+ e.currentTarget.setPointerCapture(e.pointerId);+ pick(e);+ }}+ onPointerMove={(e) => {+ if (e.buttons) pick(e);+ }}+ onKeyDown={(e) => {+ const step = e.shiftKey ? 15 : 5;+ const next =+ e.key === "ArrowRight" ? [h + step, s] : e.key === "ArrowLeft" ? [h - step, s] : e.key === "ArrowUp" ? [h, Math.min(1, s + 0.05)] : e.key === "ArrowDown" ? [h, Math.max(0.05, s - 0.05)] : null;+ if (!next) return;+ e.preventDefault();+ onBase(hslToHex(next[0], next[1], light));+ }}+ className="relative size-40 shrink-0 cursor-crosshair touch-none rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"+ style={{+ background:+ "radial-gradient(closest-side, hsl(0 0% 55%) 0%, hsl(0 0% 55% / 0) 100%), conic-gradient(from 0deg, hsl(0 80% 55%), hsl(60 80% 55%), hsl(120 80% 55%), hsl(180 80% 55%), hsl(240 80% 55%), hsl(300 80% 55%), hsl(360 80% 55%))",+ }}+ >+ {offsets.map((o) => (+ <span+ key={o}+ aria-hidden+ className="pointer-events-none absolute size-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-soft"+ style={{ ...wheelSpot(h + o, s), background: hslToHex(h + o, s, light) }}+ />+ ))}+ <span+ aria-hidden+ className="pointer-events-none absolute size-5 -translate-x-1/2 -translate-y-1/2 rounded-full border-[3px] border-white shadow-strong"+ style={{ ...wheelSpot(h, s), background: base }}+ />+ </div>+ );+}+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}+ <div className="flex flex-col items-center gap-4 sm:flex-row sm:items-start">+ <HueWheel+ base={/^#[0-9a-f]{6}$/i.test(base) ? base : WHEEL_BASE}+ harmony={harmony}+ onBase={(hex) => {+ setBase(hex);+ update(hex);+ }}+ />+ <div className="w-full min-w-0 flex-1 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={() => {- setHarmony(h.id);- update(base, h.id);+ 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);}}- 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>+ <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></div>);}-/** New palette: from an image (k-means in the browser, draggable sample points) or a colour-wheel harmony. */+/** 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}>diff --git a/src/components/cinema/project-settings.tsx b/src/components/cinema/project-settings.tsxindex 1c13a29e..510563f7 100644--- a/src/components/cinema/project-settings.tsx+++ b/src/components/cinema/project-settings.tsx@@ -20,7 +20,7 @@ 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 { formatUsd } from "./money";import { useCreateProject, useDeleteProject, useUpdateProject } from "./hooks";const MAX_DESC = 140;@@ -108,7 +108,7 @@ function ProjectForm({ project, spentUsd, onDone, onDeleted }: FormProps) {</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"}.` : ""}+ {project && spentUsd != null ? ` Spent so far ≈ ${formatUsd(spentUsd)}.` : ""}</p></div></div>diff --git a/src/components/cinema/projects-view.tsx b/src/components/cinema/projects-view.tsxindex cc6d7260..4bff1ba7 100644--- a/src/components/cinema/projects-view.tsx+++ b/src/components/cinema/projects-view.tsx@@ -11,7 +11,8 @@ 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 { formatUsd } from "./money";+import { timeAgo } from "@/lib/format";import { cn } from "@/lib/utils";import { useCinemaProjects, useUpdateProject } from "./hooks";import { ProjectDialog } from "./project-settings";@@ -61,8 +62,8 @@ function ProjectCard({ project, onSettings }: { project: CinemaProject; onSettin{project.stats?.spentUsd || project.costCapUsd != null ? (<span className="font-mono">{" "}- · ≈ {formatCost(project.stats?.spentUsd ?? 0) === "Free" ? "$0" : formatCost(project.stats?.spentUsd ?? 0)}- {project.costCapUsd != null ? ` of ${formatCost(project.costCapUsd) === "Free" ? "$0" : formatCost(project.costCapUsd)}` : ""}+ · ≈ {formatUsd(project.stats?.spentUsd)}+ {project.costCapUsd != null ? ` of ${formatUsd(project.costCapUsd)}` : ""}</span>) : null}</p>diff --git a/src/components/cinema/prompt-bar.tsx b/src/components/cinema/prompt-bar.tsxindex 89047068..4726b8de 100644--- a/src/components/cinema/prompt-bar.tsx+++ b/src/components/cinema/prompt-bar.tsx@@ -21,6 +21,7 @@ import {Maximize,Plus,RectangleHorizontal,+ SlidersHorizontal,Sparkles,UserRoundPlus,Video,@@ -30,7 +31,7 @@ import {X,} from "lucide-react";import { nanoid } from "nanoid";-import { useEffect, useMemo, useRef, useState } from "react";+import { useEffect, useId, 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";@@ -40,6 +41,7 @@ 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 { useEdgeFade } from "@/components/studio/use-edge-fade";import { uploadFile, useAssets, useStatus } from "@/lib/api";import { getModel } from "@/lib/catalog";import {@@ -66,6 +68,7 @@ import { CameraChip, EmotionChip, FilmSetupChip, LightingChip, PaletteChip } froimport { draftToInput, type BarAction, type CinemaDraft, type RefItem } from "./draft";import { useCinemaGenerate } from "./hooks";import { firstFrame, mediaDuration } from "./media";+import { formatUsd } from "./money";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";@@ -205,6 +208,9 @@ function RefThumb({ r, index, startFrame, onRemove }: { r: RefItem; index: numbe);}+/** "⌘" on Apple keyboards, "Ctrl" elsewhere (only rendered inside tooltips, i.e. in the browser). */+const modKey = () => (typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform) ? "⌘" : "Ctrl");+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). */@@ -358,7 +364,13 @@ export function PromptBar(props: PromptBarProps) {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);+ : refCheck ?? plan.blocker ?? (overCap ? `Over the project's ${formatUsd(costCapUsd)} limit (≈ ${formatUsd(spentUsd)} spent) — raise it in project settings` : undefined);+ // An empty bar needs no warning line (the placeholder says it); everything else is spelled out under the bar.+ const quietBlocker = !draft.prompt.trim() && !draft.refs.length && blocker === plan.blocker && /^Describe/.test(blocker ?? "");+ const blockerId = useId();+ const [directorRow, directorFade] = useEdgeFade<HTMLDivElement>();+ // Reference clips make the take reference-to-video: the first image is then a reference, not the start frame.+ const refMode = plan.steps.find((s) => s.key === "main")?.request.op === "ref2v";const video = draft.mode === "video";const action = input.action;const busy = generate.isPending || preparing;@@ -380,7 +392,11 @@ export function PromptBar(props: PromptBarProps) {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 }),+ onSuccess: (r) => {+ toast.success(r.items.length > 1 ? `${r.items.length} jobs queued` : "Queued", { duration: 1500 });+ // The scene was deleted meanwhile: say where the take went.+ if (folderId && r.folderId === null) toast(r.plan.notes[0] ?? "That scene was deleted, so the take is in Home", { duration: 4000 });+ },onError: (e) => toast.error((e as Error).message),},);@@ -389,10 +405,12 @@ export function PromptBar(props: PromptBarProps) {useEffect(() => {submitRef.current = submit;});- // ⌘/Ctrl+Enter generates from anywhere in the workspace (the prompt's own Enter already does).+ // ⌘/Ctrl+Enter generates from any field of the bar (onKeyDown below), and from the page when nothing+ // else has focus — never from a dialog, a sheet or another text field (Soul Cast, the brief, settings).useEffect(() => {const onKey = (e: KeyboardEvent) => {- if (e.defaultPrevented || e.key !== "Enter" || !(e.metaKey || e.ctrlKey)) return;+ if (e.defaultPrevented || e.key !== "Enter" || !(e.metaKey || e.ctrlKey) || e.isComposing) return;+ if (e.target !== document.body && e.target !== document.documentElement) return;e.preventDefault();void submitRef.current();};@@ -427,9 +445,95 @@ export function PromptBar(props: PromptBarProps) {? "Describe the scene – the whole grid shares it": "Describe your still – use @ to add characters & locations";+ // Secondary settings: inline on wide bars, in one Settings popover on narrow ones.+ const settingsItems: { label: string; node: React.ReactNode }[] = [+ {+ label: "Aspect ratio",+ node: <PickChip key="aspect" 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" ? [{ label: "Duration", node: <DurationChip key="duration" value={draft.duration} effective={effectiveDuration} onChange={(duration) => setDraft({ duration })} /> }] : []),+ {+ label: "Resolution",+ node: (+ <PickChip+ key="resolution"+ 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")+ ? [+ {+ label: video ? "Takes" : "Images",+ node: <PickChip key="batch" 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+ ? [+ {+ label: "Sound",+ node: (+ <Tooltip key="audio">+ <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"+ ? [+ {+ label: "Shots",+ node: (+ <PickChip+ key="multishot"+ 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")}+ />+ ),+ },+ ]+ : []),+ ];+ const settingsSummary = [+ draft.aspect[draft.mode],+ video && action !== "edit" ? `${effectiveDuration ?? draft.duration}s` : null,+ draft.resolution[draft.mode],+ draft.batch > 1 && action === "generate" ? `×${draft.batch}` : null,+ video && draft.multiShot.mode !== "off" && action === "generate" ? "Multi-shot" : null,+ ]+ .filter(Boolean)+ .join(" · ");+ // The live cost sits next to Generate at every width (short on narrow bars).+ const costShort = demo ? "Demo" : cost === 0 ? "Free" : cost != null ? `≈ ${formatCost(cost)}` : "≈ ?";+ const costLong = demo ? "Demo · free" : cost === 0 ? "Free" : cost != null ? `≈ ${formatCost(cost)}` : "Price unknown";+return (+<divclassName="group/composer @container 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"+ onKeyDown={(e) => {+ // Only the bar's own fields: React bubbles events from portals (the palette editor dialog, popovers) up here too.+ if (!e.currentTarget.contains(e.target as Node)) return;+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && !e.defaultPrevented && !e.nativeEvent.isComposing) {+ e.preventDefault();+ void submit();+ }+ }}onPaste={(e) => {const files = [...e.clipboardData.files];if (files.length) {@@ -481,7 +585,7 @@ export function PromptBar(props: PromptBarProps) {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) }))} />;+ return <RefThumb key={r.id} r={r} index={i} startFrame={r.kind === "image" && i === 0 && video && action === "generate" && !refMode} onRemove={() => setDraft((d) => ({ refs: d.refs.filter((x) => x.id !== r.id) }))} />;});})()}<AddRef onFiles={addRefs} onPick={(r) => setDraft((d) => ({ refs: [...d.refs, r] }))} />@@ -524,7 +628,9 @@ export function PromptBar(props: PromptBarProps) {)}{/* Director's Panel */}- <div className="scrollbar-none flex items-center gap-1.5 overflow-x-auto px-0.5 pb-1.5 @min-[760px]:flex-wrap @min-[760px]:overflow-visible">+ {/* Narrow bars scroll this row (with faded edges where more chips hide); wide ones wrap it. */}+ <div ref={directorRow} style={directorFade} className="scrollbar-none -mx-0.5 flex items-center gap-1.5 overflow-x-auto px-1 pb-1.5 @min-[760px]:flex-wrap @min-[760px]:overflow-visible" role="group" aria-label="Director's Panel">+<FilmSetupChip settings={settings} onChange={onSettings} mode={draft.mode} /><CameraChipsettings={settings}@@ -557,9 +663,10 @@ export function PromptBar(props: PromptBarProps) {</Tooltip></div>- {/* Generation settings */}+ {/* Generation settings. Narrow bars (phones, a bar squeezed by the side panel) wrap this row and+ fold the secondary settings into one Settings popover, so nothing hides off-screen. */}<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 @min-[760px]:flex-wrap @min-[760px]:overflow-visible">+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5"><Segmentedlabel="Mode"value={draft.mode}@@ -648,49 +755,45 @@ export function PromptBar(props: PromptBarProps) {/>)}- <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")}- />- )}+ <div className="hidden @min-[760px]:contents">{settingsItems.map((s) => s.node)}</div>+ <Popover>+ <PopoverTrigger asChild>+ <button type="button" className={cn(chip, chipIdle, "max-w-full @min-[760px]:hidden")} aria-label={`Settings: ${settingsSummary}`}>+ <SlidersHorizontal className="size-3.5 shrink-0" />+ <span className="truncate">{settingsSummary}</span>+ </button>+ </PopoverTrigger>+ <PopoverContent className="w-[min(92vw,320px)] space-y-1 p-2" align="start" side="top" collisionPadding={12}>+ <p className="px-1.5 pt-0.5 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">Settings</p>+ {settingsItems.map((s) => (+ <div key={s.label} className="flex items-center justify-between gap-3 rounded-lg px-1.5 py-1">+ <span className="text-[13px] text-muted-foreground">{s.label}</span>+ {s.node}+ </div>+ ))}+ </PopoverContent>+ </Popover></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>+ <span className={cn("mb-1.5 shrink-0 rounded-full px-2 py-0.5 font-mono text-[12px] tabular-nums", overCap ? "bg-destructive/10 text-destructive" : "bg-muted text-muted-foreground")}>+ <span className="@min-[520px]:hidden">{costShort}</span>+ <span className="hidden @min-[520px]:inline">{costLong}</span>+ </span>+ </TooltipTrigger>+ <TooltipContent>+ {demo ? "Demo mode: no key connected for this model, so takes are free placeholders" : cost === 0 ? "Runs on your own GPU" : "Estimated cost of this run, billed by the provider to your key"}+ </TooltipContent>+ </Tooltip><Tooltip><TooltipTrigger asChild><Buttonsize="icon"onClick={() => void submit()}disabled={busy}- aria-label="Generate"+ aria-label={plan.outputs > 1 ? `Generate ${plan.outputs}` : "Generate"}+ aria-disabled={!!blocker || undefined}+ aria-describedby={blocker ? blockerId : undefined}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" />}@@ -699,7 +802,7 @@ export function PromptBar(props: PromptBarProps) {<TooltipContent>{blocker ?? (<span className="flex items-center gap-1.5">- Generate{plan.outputs > 1 ? ` ${plan.outputs}` : ""} <Kbd>⌘</Kbd>+ Generate{plan.outputs > 1 ? ` ${plan.outputs}` : ""} <Kbd>{modKey()}</Kbd><Kbd>↵</Kbd></span>)}@@ -711,7 +814,12 @@ export function PromptBar(props: PromptBarProps) {{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>}+ {/* Why Generate can't run, in words (touch screens never see the tooltip). */}+ {blocker && (+ <p id={blockerId} className={cn("px-2 pt-1 text-[11.5px] leading-snug", quietBlocker ? "sr-only" : refCheck || overCap ? "text-destructive" : "text-muted-foreground")}>+ {blocker}+ </p>+ )}<span className="sr-only" aria-live="polite">{cost != null ? `Estimated cost ${demo ? "free in demo mode" : formatCost(cost)}` : ""}</span>diff --git a/src/components/cinema/side-panel.tsx b/src/components/cinema/side-panel.tsxindex 65ffbf0f..8dd94b12 100644--- a/src/components/cinema/side-panel.tsx+++ b/src/components/cinema/side-panel.tsx@@ -8,7 +8,7 @@ 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";+import { useAutosave, 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"];@@ -168,22 +168,25 @@ function DirectorChat({ projectId, onLoadShot, onBrief, promptText }: { projectI);}-/** The production's rules: tone, references, do's and don'ts. Prepended to every compiled prompt. */+/**+ * The production's rules: tone, references, do's and don'ts. Prepended to every compiled prompt.+ * Autosaves 0.7 s after typing stops, and at once when the panel closes, the tab switches to the+ * AI Director or the page goes away, so the last words are never lost.+ */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 saver = useAutosave<{ title: string; body: string }>((brief, { keepalive }) => {+ setState("saving");+ update.mutate({ brief, keepalive }, { onSuccess: () => setState("saved"), onError: (e) => (setState("dirty"), toast.error((e as Error).message)) });+ }, 700);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);+ saver.schedule({ title: t, body: b });};- 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">diff --git a/src/components/cinema/soul-builders.tsx b/src/components/cinema/soul-builders.tsxindex 66d8eff1..149e2313 100644--- a/src/components/cinema/soul-builders.tsx+++ b/src/components/cinema/soul-builders.tsx@@ -270,7 +270,21 @@ function SoulCast({ projectId, folderId, engine, context, brief, onOpenChange }:</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”" />+ <Textarea+ value={notes}+ onChange={(e) => setNotes(e.target.value.slice(0, 1000))}+ onKeyDown={(e) => {+ // ⌘/Ctrl+Enter makes the cast sheet (handled here, so the prompt bar behind the dialog never sees it).+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && !e.nativeEvent.isComposing) {+ e.preventDefault();+ if (!generate.isPending) run();+ }+ }}+ rows={2}+ className="resize-none text-[13px]"+ placeholder="e.g. “a retired safecracker with kind eyes and a nervous smile”"+ aria-label="Describe your character"+ /></div><div className="flex flex-wrap items-center gap-2 border-t pt-3"><Button variant="ghost" size="sm" onClick={() => setValues((v) => randomizeCast(v))}>@@ -350,11 +364,13 @@ function SoulLocation({ projectId, folderId, engine, settings, context, brief, ovalue={prompt}onChange={(e) => setPrompt(e.target.value.slice(0, 2500))}onKeyDown={(e) => {- if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && prompt.trim()) {+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && !e.nativeEvent.isComposing) {+ // Always handled here (even with an empty description), so it never reaches the prompt bar.e.preventDefault();- run();+ if (prompt.trim() && !generate.isPending) 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”"diff --git a/src/components/cinema/workspace.tsx b/src/components/cinema/workspace.tsxindex 22216a39..b6c28a23 100644--- a/src/components/cinema/workspace.tsx+++ b/src/components/cinema/workspace.tsx@@ -1,6 +1,6 @@"use client";-import { Bot, ChevronLeft, Clapperboard, Copy, FileText, Folder, FolderOpen, Heart, Library, MoreHorizontal, PanelLeft, Pin, PinOff, Settings2, Upload } from "lucide-react";+import { Bot, ChevronLeft, Clapperboard, Copy, FileText, Folder, FolderOpen, FolderTree, Heart, Library, MoreHorizontal, Pin, PinOff, Settings2, Upload } from "lucide-react";import { nanoid } from "nanoid";import Link from "next/link";import { useRouter } from "next/navigation";@@ -15,16 +15,16 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltipimport { 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 { rigError, type CinemaFolder, type DirectorSettings, type 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 { formatUsd } from "./money";+import { useAutosave, 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";@@ -169,15 +169,22 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaGconst 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);+ // Director settings save per project a moment after the last change, and at once when the+ // workspace goes away (another page, a closed tab): the last pick is never dropped.+ const settingsSaver = useAutosave<DirectorSettings>(+ (director, { keepalive }) => update.mutate({ director, keepalive }, { onError: (e) => toast.error((e as Error).message) }),+ 500,+ );+ // The last lighting the server would accept: a custom rig being edited into an invalid state isn't saved.+ const savedLighting = useRef(project.director.lighting ?? 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);+ const lighting = next.lighting ?? null;+ const invalid = lighting?.kind === "custom" && !!rigError(lighting.lights);+ if (!invalid) savedLighting.current = lighting;+ settingsSaver.schedule(invalid ? { ...next, lighting: savedLighting.current } : next);};- 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);@@ -332,19 +339,31 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaG</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>+ {/* Scenes (folders) open as a sheet below lg: a folder icon, unlike the app sidebar's panel icon next to it. */}+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ onClick={() => setFoldersOpen(true)}+ className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-lg px-2 text-[12.5px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground lg:hidden"+ aria-label="Scenes and folders"+ >+ <FolderTree className="size-4" /> <span className="hidden sm:inline">Scenes</span>+ </button>+ </TooltipTrigger>+ <TooltipContent>Scenes, favorites and elements</TooltipContent>+ </Tooltip><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 || project.costCapUsd != null ? ` · ≈ ${spentUsd > 0 ? formatCost(spentUsd) : "$0"} spent` : ""}- {project.costCapUsd != null ? ` of ${project.costCapUsd > 0 ? formatCost(project.costCapUsd) : "$0"}` : ""}+ {spentUsd > 0 || project.costCapUsd != null ? ` · ≈ ${formatUsd(spentUsd)} spent` : ""}+ {project.costCapUsd != null ? ` of ${formatUsd(project.costCapUsd)}` : ""}</p></div>- <EngineSwitch value={engine} onChange={setEngine} size="sm" />+ {/* Icons only on phones (labels from sm up), so the project name keeps its room. */}+ <EngineSwitch value={engine} onChange={setEngine} /><Tooltip><TooltipTrigger asChild><Buttondiff --git a/tests/cinema-client.test.ts b/tests/cinema-client.test.tsnew file mode 100644index 00000000..a7f1774b--- /dev/null+++ b/tests/cinema-client.test.ts@@ -0,0 +1,118 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { Autosaver } from "@/components/cinema/autosave";+import { reorderFolders } from "@/components/cinema/folder-sidebar";+import { applyToTakes, type CinemaGeneration } from "@/components/cinema/live";+import { formatUsd } from "@/components/cinema/money";++// The workspace's pure pieces: autosave that never drops the last edit, live updates of the takes,+// manual folder order and money formatting.++describe("Autosaver", () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ it("saves the last value once, a moment after the last change", () => {+ const save = vi.fn();+ const a = new Autosaver<string>(save, 700);+ a.schedule("a");+ vi.advanceTimersByTime(500);+ a.schedule("ab");+ vi.advanceTimersByTime(699);+ expect(save).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(save).toHaveBeenCalledExactlyOnceWith("ab", { keepalive: false });+ expect(a.dirty).toBe(false);+ });++ it("flushes a pending edit at once (unmount, panel closed, tab hidden) instead of dropping it", () => {+ const save = vi.fn();+ const a = new Autosaver<{ body: string }>(save, 700);+ a.schedule({ body: "Rain, neon, regret." });+ expect(a.dirty).toBe(true);+ a.flush(true); // the page is going away+ expect(save).toHaveBeenCalledExactlyOnceWith({ body: "Rain, neon, regret." }, { keepalive: true });+ vi.advanceTimersByTime(2000);+ a.flush();+ expect(save).toHaveBeenCalledTimes(1); // nothing pending: no second save+ });++ it("uses the latest save function and can forget a pending value", () => {+ const first = vi.fn();+ const second = vi.fn();+ const a = new Autosaver<number>(first, 100);+ a.schedule(1);+ a.setSave(second);+ vi.advanceTimersByTime(100);+ expect(first).not.toHaveBeenCalled();+ expect(second).toHaveBeenCalledWith(1, { keepalive: false });+ a.schedule(2);+ a.cancel();+ vi.advanceTimersByTime(100);+ expect(second).toHaveBeenCalledTimes(1);+ });+});++describe("live updates of the takes", () => {+ const take = (id: string, patch: Partial<CinemaGeneration> = {}): CinemaGeneration =>+ ({+ id,+ status: "running",+ updatedAt: 1,+ createdAt: 1,+ favorite: false,+ outputs: [],+ request: { feature: "cinema", modelId: "seedance-2-5" },+ folderId: "scene-1",+ projectId: "p1",+ take: { mode: "video", action: "generate", prompt: "rain" },+ ...patch,+ }) as CinemaGeneration;++ it("updates a known take in place and keeps the scene it's filed in", () => {+ const list = [take("a"), take("b")];+ const done = applyToTakes(list, { type: "generation", generation: { ...take("a"), status: "succeeded", updatedAt: 5, folderId: "library-folder", outputs: [{ url: "/api/files/a.mp4", kind: "video" }] } });+ expect(done).not.toBe(list);+ expect(done![0]).toMatchObject({ status: "succeeded", folderId: "scene-1", projectId: "p1", take: { prompt: "rain" } });+ expect(done![1]).toBe(list[1]);+ });++ it("ignores late events and unknown ids, and drops deleted or trashed takes", () => {+ const list = [take("a", { updatedAt: 9 }), take("b")];+ expect(applyToTakes(list, { type: "generation", generation: take("a", { updatedAt: 3, status: "failed" }) })).toBe(list);+ expect(applyToTakes(list, { type: "generation", generation: take("zzz") })).toBe(list);+ expect(applyToTakes(list, { type: "deleted", id: "b" })!.map((g) => g.id)).toEqual(["a"]);+ expect(applyToTakes(list, { type: "generation", generation: take("b", { updatedAt: 9, deletedAt: 9 }) })!.map((g) => g.id)).toEqual(["a"]);+ expect(applyToTakes(undefined, { type: "deleted", id: "a" })).toBeUndefined();+ });+});++describe("folder order", () => {+ const f = (id: string, position: number, pinned = false) => ({ id, position, pinned });++ it("swaps a folder with its neighbour among folders of the same pin state", () => {+ const siblings = [f("pin", 9, true), f("a", 0), f("b", 1), f("c", 2)];+ expect(reorderFolders(siblings, "b", -1)).toEqual([+ { id: "b", position: 0 },+ { id: "a", position: 1 },+ ]);+ expect(reorderFolders(siblings, "c", 1)).toEqual([]);+ expect(reorderFolders(siblings, "a", -1)).toEqual([]);+ expect(reorderFolders(siblings, "pin", 1)).toEqual([]);+ });++ it("spreads out tied positions so the new order sticks", () => {+ expect(reorderFolders([f("a", 3), f("b", 3), f("c", 3)], "c", -1)).toEqual([+ { id: "c", position: 4 },+ { id: "b", position: 5 },+ ]);+ });+});++describe("formatUsd", () => {+ it("prints spend and caps as money, never as “Free”", () => {+ expect(formatUsd(0)).toBe("$0.00");+ expect(formatUsd(null)).toBe("$0.00");+ expect(formatUsd(0.004)).toBe("<$0.01");+ expect(formatUsd(1.234)).toBe("$1.23");+ });+});diff --git a/tests/e2e/cinema-shortcuts.mjs b/tests/e2e/cinema-shortcuts.mjsnew file mode 100644index 00000000..6ac49625--- /dev/null+++ b/tests/e2e/cinema-shortcuts.mjs@@ -0,0 +1,123 @@+// Cinema Studio keyboard check: ⌘/Ctrl+Enter generates from the prompt bar only — never from a+// dialog, the side panel or another text field behind which the bar sits.+// Usage: node tests/e2e/cinema-shortcuts.mjs [appUrl] (app must be running; demo mode is fine).+// Exits 1 when a shortcut made a take it shouldn't have (or the prompt bar's didn't make one).+//+// Playwright and Chromium are found like tests/e2e/no-horizontal-scroll.mjs does.+import fs from "node:fs";+import path from "node:path";+import { createRequire } from "node:module";+import { fileURLToPath } from "node:url";++const app = (process.argv.slice(2).find((a) => !a.startsWith("--")) ?? "http://localhost:3000").replace(/\/$/, "");+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");++function loadPlaywright() {+ for (const from of [path.join(root, "package.json"), "/opt/node22/lib/node_modules/", "/opt/node-tools/node_modules/"]) {+ const req = createRequire(from);+ for (const name of ["playwright", "playwright-core"]) {+ try {+ return req(name);+ } catch {}+ }+ }+ throw new Error("Playwright not found: install playwright-core or run where the global install exists");+}++function chromiumPath() {+ if (process.env.CHROMIUM_PATH) return process.env.CHROMIUM_PATH;+ const dir = "/opt/pw-browsers";+ if (!fs.existsSync(dir)) return undefined;+ const newest = fs+ .readdirSync(dir)+ .filter((d) => /^chromium-\d+$/.test(d))+ .sort((a, b) => Number(b.split("-")[1]) - Number(a.split("-")[1]))[0];+ const exe = newest && path.join(dir, newest, "chrome-linux/chrome");+ return exe && fs.existsSync(exe) ? exe : undefined;+}++const { chromium } = loadPlaywright();+const browser = await chromium.launch({ executablePath: chromiumPath() });+const page = await (await browser.newContext({ viewport: { width: 1440, height: 900 } })).newPage();+const call = async (url, method = "GET", data) => {+ const r = await page.request.fetch(app + url, { method, headers: { "Content-Type": "application/json" }, data: data === undefined ? undefined : JSON.stringify(data) });+ return r.json();+};+const project = await call("/api/cinema/projects", "POST", { name: "Shortcut check" });+const takes = async () => (await call(`/api/cinema/projects/${project.id}/items`)).items;+const failures = [];+const check = async (label, act, expect) => {+ const before = await takes();+ await act();+ await page.waitForTimeout(2500);+ const made = (await takes()).filter((g) => !before.some((b) => b.id === g.id)).map((g) => g.feature);+ const ok = expect(made);+ console.log(`${ok ? "ok " : "FAIL"} ${label.padEnd(52)} made: ${made.join(", ") || "nothing"}`);+ if (!ok) failures.push(label);+};+const none = (made) => made.length === 0;++try {+ await page.goto(`${app}/cinema/${project.id}`, { waitUntil: "domcontentloaded", timeout: 120_000 });+ await page.waitForSelector("text=Your first shot", { timeout: 120_000 });+ await page.getByPlaceholder(/Describe your scene/).fill("A lighthouse in a storm");++ await check("Ctrl+Enter in the Soul Cast dialog makes a cast sheet", async () => {+ await page.getByRole("button", { name: "Soul Cast: build a character" }).click();+ await page.getByLabel("Describe your character").fill("kind eyes");+ await page.keyboard.press("Control+Enter");+ }, (made) => made.length > 0 && made.every((f) => f === "cinema-cast"));+ await page.keyboard.press("Escape");++ await check("Ctrl+Enter in an empty Soul Location dialog", async () => {+ await page.getByRole("button", { name: "Soul Location: build a location" }).click();+ await page.waitForSelector("text=Create location");+ await page.keyboard.press("Control+Enter");+ }, none);+ await page.keyboard.press("Escape");++ await check("Ctrl+Enter in the project brief", async () => {+ await page.getByRole("button", { name: "Project brief" }).first().click();+ await page.getByLabel("Brief", { exact: true }).fill("Rain and regret.");+ await page.keyboard.press("Control+Enter");+ }, none);++ await check("Ctrl+Enter in the AI Director box", async () => {+ await page.getByRole("tab", { name: "AI Director" }).click();+ await page.getByLabel("Message the AI Director").fill("Which lens for a close-up?");+ await page.keyboard.press("Control+Enter");+ }, none);+ await page.getByRole("button", { name: "Close panel" }).click();++ // The palette editor opens from a prompt-bar chip: its events bubble through React's tree to the bar.+ await check("Ctrl+Enter in the palette editor's name field", async () => {+ await page.getByRole("button", { name: "Color palette" }).click();+ await page.getByRole("button", { name: "New palette" }).click();+ await page.getByRole("tab", { name: "Color wheel" }).click();+ await page.getByPlaceholder("Enter palette name").fill("Dusk");+ await page.keyboard.press("Control+Enter");+ }, none);+ await page.keyboard.press("Escape");+ await page.keyboard.press("Escape");++ await check("Ctrl+Enter in Project settings", async () => {+ await page.getByRole("button", { name: "Project menu" }).click();+ await page.getByRole("menuitem", { name: "Project settings" }).click();+ await page.getByLabel("Spending limit").fill("5");+ await page.keyboard.press("Control+Enter");+ }, none);+ await page.keyboard.press("Escape");++ await check("Ctrl+Enter in the prompt bar makes a take", async () => {+ await page.getByPlaceholder(/Describe your scene/).click();+ await page.keyboard.press("Control+Enter");+ }, (made) => made.length === 1 && made[0] === "cinema");+} catch (e) {+ console.log(`FAIL ${e.message.split("\n")[0]}`);+ failures.push("run");+} finally {+ await call(`/api/cinema/projects/${project.id}`, "DELETE").catch(() => {});+ await browser.close();+}+console.log(failures.length ? `\n${failures.length} shortcut check(s) failed: ${failures.join("; ")}` : "\nAll shortcut checks passed.");+process.exit(failures.length ? 1 : 0);