Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Content Factory: the studio — a reference, a brief, "Make a video about…", episodes, here or in Claude

Claude4d1d4008648b
diff --git a/src/app/(studio)/content-factory/[id]/page.tsx b/src/app/(studio)/content-factory/[id]/page.tsx
new file mode 100644
index 00000000..93de4f3a
--- /dev/null
+++ b/src/app/(studio)/content-factory/[id]/page.tsx
@@ -0,0 +1,20 @@
+import type { Metadata } from "next";
+import { Suspense } from "react";
+import { SeriesView } from "@/components/content-factory/series-view";
+import { getModel } from "@/lib/catalog";
+import { pickerData } from "@/lib/catalog/faceless";
+
+export const metadata: Metadata = { title: "Series" };
+
+async function Series({ params }: { params: PageProps<"/content-factory/[id]">["params"] }) {
+ const { id } = await params;
+ return <SeriesView id={id} voices={pickerData(getModel).voices} />;
+}
+
+export default function Page({ params }: PageProps<"/content-factory/[id]">) {
+ return (
+ <Suspense fallback={null}>
+ <Series params={params} />
+ </Suspense>
+ );
+}
diff --git a/src/app/(studio)/content-factory/page.tsx b/src/app/(studio)/content-factory/page.tsx
new file mode 100644
index 00000000..d0e8d307
--- /dev/null
+++ b/src/app/(studio)/content-factory/page.tsx
@@ -0,0 +1,10 @@
+import type { Metadata } from "next";
+import { ContentFactoryHome } from "@/components/content-factory/home";
+import { getModel } from "@/lib/catalog";
+import { pickerData } from "@/lib/catalog/faceless";
+
+export const metadata: Metadata = { title: "Content Factory" };
+
+export default function Page() {
+ return <ContentFactoryHome voices={pickerData(getModel).voices} />;
+}
diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsx
index d78ed3b5..b743d7b0 100644
--- a/src/components/app-sidebar.tsx
+++ b/src/components/app-sidebar.tsx
@@ -11,6 +11,7 @@ import {
Layers,
Layers2,
Crop,
+ Factory,
FastForward,
Brush,
AudioLines,
@@ -134,6 +135,7 @@ const NAV: NavGroupDef[] = [
{ href: "/fashion-factory", label: "Fashion Factory", icon: Shirt },
{ href: "/character-sheet", label: "Character Sheet", icon: UserRoundCog },
{ href: "/faceless", label: "Faceless Studio", icon: Tv },
+ { href: "/content-factory", label: "Content Factory", icon: Factory },
{ href: "/explainer", label: "Explainer", icon: Presentation },
{ href: "/lipsync", label: "Lipsync & avatars", icon: Mic2 },
{ href: "/motion-control", label: "Motion control", icon: PersonStanding },
diff --git a/src/components/content-factory/home.tsx b/src/components/content-factory/home.tsx
new file mode 100644
index 00000000..93965bfa
--- /dev/null
+++ b/src/components/content-factory/home.tsx
@@ -0,0 +1,538 @@
+"use client";
+
+import { ArrowRight, Bot, Film, Link2, Loader2, Minus, Plus, Sparkles, Upload } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useEffect, useId, useRef, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { SidebarTrigger } from "@/components/ui/sidebar";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Switch } from "@/components/ui/switch";
+import { MediaThumb } from "@/components/studio/feed";
+import { EngineSwitch } from "@/components/studio/engine-switch";
+import { Segmented, usd } from "@/components/faceless/controls";
+import { NarratorChip } from "@/components/faceless/narrator";
+import { StyleArt } from "@/components/faceless/style-art";
+import { uploadFile, useEngine, useHydrated } from "@/lib/api";
+import {
+ ANIMATION_STYLES,
+ CF_LENGTHS,
+ getPreset,
+ IDEA_EXAMPLES,
+ MAX_EPISODES,
+ MAX_PROMPT,
+ PLATFORM_NOTE,
+ referenceLink,
+ type AnimationStyleId,
+ type SeriesCard,
+} from "@/lib/catalog/content-factory";
+import { GENRES, type EpisodeAspect, type FacelessGenre, type NarratorVoice, type PickerData } from "@/lib/catalog/faceless";
+import { cn } from "@/lib/utils";
+import { ApiError, useCreateSeries, useGenerateSeries, useRereadSeries, useSeries, useSeriesEstimate, useSeriesList, useUpdateSeries, type SeriesAsk } from "./hooks";
+import { BriefCard, ClaudeDialog, PresetGrid, ReferenceCard, SeriesPriceLine } from "./parts";
+
+/** The clip being read stays in the composer across reloads (this browser only). */
+const DRAFT_KEY = "fuobe.content-factory.draft";
+const DEFAULT_PRESET = "what-if";
+
+const readDraft = () => {
+ try {
+ return localStorage.getItem(DRAFT_KEY);
+ } catch {
+ return null;
+ }
+};
+const writeDraft = (id: string | null) => {
+ try {
+ if (id) localStorage.setItem(DRAFT_KEY, id);
+ else localStorage.removeItem(DRAFT_KEY);
+ } catch {}
+};
+
+const STEPS = [
+ { icon: Film, title: "Pick a style", text: "Upload a short you love, paste its link, or start from a trending preset." },
+ { icon: Sparkles, title: "Get its brief", text: "Pacing, shots, captions, music mood, hook and narrator — read from the clip." },
+ { icon: Bot, title: "Make the series", text: "Say what it's about, how long and how many episodes. Here, or in Claude." },
+];
+
+function chipTrigger(className?: string) {
+ return cn("h-8 max-w-full gap-1 rounded-full border-0 bg-secondary px-3 text-[13px] font-medium shadow-none hover:bg-accent dark:bg-secondary dark:hover:bg-accent", className);
+}
+
+export function ContentFactoryHome({ voices }: { voices: PickerData["voices"] }) {
+ const router = useRouter();
+ const [engine, setEngine] = useEngine();
+ const [mode, setMode] = useState<"here" | "claude">("here");
+ const [presetId, setPresetId] = useState<string>(DEFAULT_PRESET);
+ // The series being read: picked in this visit, else the draft from an earlier one (this browser).
+ const [picked, setSeriesId] = useState<string | null | undefined>(undefined);
+ const [prompt, setPrompt] = useState("");
+ const [genre, setGenre] = useState<FacelessGenre>("storytelling");
+ const [animation, setAnimation] = useState<AnimationStyleId>("fully-animated");
+ const [length, setLength] = useState(30);
+ const [episodes, setEpisodes] = useState(1);
+ const [aspect, setAspect] = useState<EpisodeAspect>("9:16");
+ const [voice, setVoice] = useState<NarratorVoice | undefined>(undefined);
+ const [review, setReview] = useState(false);
+ const [linkOpen, setLinkOpen] = useState(false);
+ const [link, setLink] = useState("");
+ const [linkError, setLinkError] = useState<{ message: string; upload: boolean } | null>(null);
+ const [uploading, setUploading] = useState(false);
+ const [claudeOpen, setClaudeOpen] = useState(false);
+ const [example, setExample] = useState(0);
+ const file = useRef<HTMLInputElement>(null);
+ const promptRef = useRef<HTMLTextAreaElement>(null);
+ const ids = { prompt: useId(), link: useId(), voice: useId() };
+
+ const hydrated = useHydrated();
+ const candidate = picked !== undefined ? picked : hydrated ? readDraft() : null;
+ const series = useSeries(candidate);
+ // A draft that's gone (or already made) is let go.
+ const gone = !!series.error || !!series.data?.channel;
+ const seriesId = gone ? null : candidate;
+ const create = useCreateSeries();
+ const generate = useGenerateSeries();
+ const reread = useRereadSeries();
+ const updateBrief = useUpdateSeries();
+ const list = useSeriesList();
+
+ useEffect(() => {
+ if (gone) writeDraft(null);
+ }, [gone]);
+
+ const view = seriesId ? series.data : undefined;
+ const preset = getPreset(view?.reference?.presetId ?? presetId);
+ const brief = view ? view.brief : (preset?.brief ?? null);
+ const reading = view?.analysis?.status === "reading";
+ const examples = brief?.topics.length ? brief.topics : IDEA_EXAMPLES;
+
+ // A new brief brings its own look: the animation style, the shape (and a preset its genre).
+ const briefKey = view ? `${view.id}:${view.analysis?.status}:${view.analysis?.engine}` : presetId;
+ const [adopted, setAdopted] = useState<string | null>(null);
+ if (brief && !reading && adopted !== briefKey) {
+ setAdopted(briefKey);
+ setAnimation(brief.animation);
+ setAspect(brief.aspect);
+ if (!view && preset) setGenre(preset.genre);
+ }
+
+ // The examples under the prompt rotate while it's empty.
+ useEffect(() => {
+ if (prompt) return;
+ const t = setInterval(() => setExample((i) => i + 1), 3500);
+ return () => clearInterval(t);
+ }, [prompt]);
+
+ const ask: SeriesAsk = { prompt: prompt.trim(), settings: { engine, length, episodes, animation, genre, aspect }, ...(voice && { voice }) };
+ const source = seriesId ? { seriesId } : { presetId };
+ const estimate = useSeriesEstimate({ ...ask, prompt: ask.prompt || "estimate", ...source });
+ const perMinute = estimate.data?.analysisPerMinute ?? 0;
+
+ const choosePreset = (id: string) => {
+ setPresetId(id);
+ setSeriesId(null);
+ writeDraft(null);
+ setLinkError(null);
+ };
+
+ const startSeries = (reference: Parameters<typeof create.mutate>[0]["reference"]) =>
+ create.mutateAsync({ reference, engine }).then((v) => {
+ setSeriesId(v.id);
+ writeDraft(v.id);
+ setLinkOpen(false);
+ setLink("");
+ setLinkError(null);
+ return v;
+ });
+
+ const onFile = async (f: File | undefined) => {
+ if (!f) return;
+ if (!/^video\//.test(f.type) && !/\.(mp4|mov|m4v|webm)$/i.test(f.name)) return void toast.error("Add a video clip (MP4, MOV or WebM)");
+ setUploading(true);
+ try {
+ const asset = await uploadFile(f);
+ await startSeries({ kind: "upload", url: asset.url, title: f.name });
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setUploading(false);
+ }
+ };
+
+ const fetchLink = () => {
+ const checked = referenceLink(link);
+ if ("error" in checked) return setLinkError({ message: checked.error, upload: false });
+ startSeries({ kind: "link", link: checked.url }).catch((e: Error) => setLinkError({ message: e.message, upload: e instanceof ApiError && e.needsUpload }));
+ };
+
+ const blocker = !prompt.trim() ? "Say what the video is about" : reading ? "The reference is still being read — a moment" : !brief ? "Add a reference or pick a preset" : null;
+
+ const submit = async () => {
+ if (blocker) {
+ toast(blocker, { id: "cf-blocker" });
+ if (!prompt.trim()) promptRef.current?.focus();
+ return;
+ }
+ if (mode === "claude") return setClaudeOpen(true);
+ try {
+ // A preset becomes a series of its own (kept as the draft, so a retry doesn't make another).
+ const id = seriesId ?? (await startSeries({ kind: "preset", presetId })).id;
+ await generate.mutateAsync({ id, ...ask, review });
+ writeDraft(null);
+ router.push(`/content-factory/${id}`);
+ } catch (e) {
+ toast.error((e as Error).message);
+ }
+ };
+
+ const busy = create.isPending || generate.isPending;
+ const est = estimate.data;
+
+ return (
+ <div className="flex min-h-svh min-w-0 flex-col">
+ <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">
+ <SidebarTrigger className="md:hidden" />
+ <h1 className="truncate font-heading text-[22px] leading-none">Content Factory</h1>
+ <div className="ml-auto">
+ <EngineSwitch value={engine} onChange={setEngine} />
+ </div>
+ </header>
+ <div className="mx-auto w-full max-w-[1240px] min-w-0 flex-1 space-y-12 px-3 pb-16 sm:px-6">
+ <div className="mx-auto max-w-[780px] pt-[5vh] text-center sm:pt-[8vh]">
+ <h2 className="font-heading text-display text-balance">Faceless shorts in the style of a video you love</h2>
+ <p className="mx-auto mt-2 max-w-[600px] text-body text-muted-foreground">Show it a reference, say what to make, and get a whole series: script, narrator, pictures, motion, music and captions that follow the same pacing and look.</p>
+
+ <div className="mt-7 rounded-[20px] border bg-background p-3 text-left shadow-soft transition-[border-color,box-shadow] focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint sm:rounded-composer sm:p-4">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <Segmented
+ label="Generate with"
+ value={mode}
+ onChange={setMode}
+ options={[
+ { value: "here", label: "Generate here", hint: "Fuobe makes the episodes now" },
+ { value: "claude", label: "Generate in Claude", hint: "Copy a prompt for Claude Code with Fuobe's MCP server" },
+ ]}
+ />
+ <span className="text-[12px] text-muted-foreground">{mode === "claude" ? "Claude writes them and runs Fuobe over MCP" : engine === "open" ? "Makes the episodes now, on your ComfyUI" : "Makes the episodes now, with your providers"}</span>
+ </div>
+
+ {/* The reference: the brief every episode follows */}
+ <div className="mt-3 space-y-2">
+ {view?.reference ? (
+ <ReferenceCard
+ reference={view.reference}
+ analysis={view.analysis}
+ styleId={view.brief?.styleId ?? "colorful-3d"}
+ onClear={() => choosePreset(DEFAULT_PRESET)}
+ onReread={() => reread.mutate({ id: view.id, engine }, { onError: (e) => toast.error((e as Error).message) })}
+ rereading={reread.isPending}
+ />
+ ) : seriesId && series.isLoading ? (
+ <Skeleton className="h-[72px] rounded-2xl" />
+ ) : preset ? (
+ <ReferenceCard reference={{ kind: "preset", presetId: preset.id, title: `Preset: ${preset.name}` }} analysis={null} styleId={preset.brief.styleId} />
+ ) : null}
+ <div className="flex flex-wrap items-center gap-1.5">
+ <button
+ type="button"
+ onClick={() => file.current?.click()}
+ disabled={uploading || create.isPending}
+ className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary px-3 text-[13px] font-medium hover:bg-accent disabled:opacity-60"
+ >
+ {uploading ? <Loader2 className="size-3.5 animate-spin" /> : <Upload className="size-3.5" />}
+ {uploading ? "Uploading…" : view?.reference?.url ? "Change video" : "Add a video"}
+ </button>
+ <button
+ type="button"
+ onClick={() => setLinkOpen((v) => !v)}
+ aria-expanded={linkOpen}
+ aria-controls={ids.link}
+ className={cn("inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium", linkOpen ? "bg-brand-faint text-brand-text" : "bg-secondary hover:bg-accent")}
+ >
+ <Link2 className="size-3.5" /> TikTok or Instagram link
+ </button>
+ <a href="#presets" className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary px-3 text-[13px] font-medium hover:bg-accent">
+ <Sparkles className="size-3.5" /> Presets
+ </a>
+ <span className="text-[12px] text-muted-foreground">
+ {engine === "open" ? "Reading a clip is free (Gemma 4 on your ComfyUI)" : perMinute > 0 ? `Reading a clip costs about ${usd(perMinute)} a minute` : "Reading a clip runs as a free demo"}
+ </span>
+ <input ref={file} type="file" accept="video/mp4,video/quicktime,video/webm,.mp4,.mov,.m4v,.webm" hidden onChange={(e) => (void onFile(e.target.files?.[0]), (e.target.value = ""))} />
+ </div>
+ {linkOpen && (
+ <div id={ids.link} className="space-y-1.5 rounded-2xl bg-muted/60 p-2.5">
+ <form
+ className="flex min-w-0 items-center gap-2"
+ onSubmit={(e) => {
+ e.preventDefault();
+ fetchLink();
+ }}
+ >
+ <label htmlFor={`${ids.link}-in`} className="sr-only">
+ Link to a TikTok, Instagram reel or video file
+ </label>
+ <input
+ id={`${ids.link}-in`}
+ value={link}
+ onChange={(e) => {
+ setLink(e.target.value);
+ setLinkError(null);
+ }}
+ inputMode="url"
+ placeholder="https://www.tiktok.com/@…/video/…"
+ aria-invalid={!!linkError}
+ aria-describedby={`${ids.link}-note${linkError ? ` ${ids.link}-err` : ""}`}
+ className="h-9 min-w-0 flex-1 rounded-full border bg-background px-3 text-[13px] outline-none focus:border-primary"
+ />
+ <Button type="submit" size="sm" className="h-9 shrink-0 rounded-full" disabled={!link.trim() || create.isPending}>
+ {create.isPending ? <Loader2 className="animate-spin" /> : null}
+ {create.isPending ? "Fetching…" : "Use"}
+ </Button>
+ </form>
+ {linkError && (
+ <div id={`${ids.link}-err`} role="alert" className="flex flex-wrap items-center gap-2 text-[12px] text-destructive">
+ <span className="min-w-0">{linkError.message}</span>
+ {linkError.upload && (
+ <Button type="button" variant="secondary" size="sm" className="h-7 rounded-full" onClick={() => file.current?.click()}>
+ <Upload /> Upload the clip
+ </Button>
+ )}
+ </div>
+ )}
+ <p id={`${ids.link}-note`} className="text-[11px] leading-snug text-muted-foreground">
+ {PLATFORM_NOTE}
+ </p>
+ </div>
+ )}
+ </div>
+
+ <label htmlFor={ids.prompt} className="mt-3 block px-1 text-[12px] font-medium text-muted-foreground">
+ Make a video about…
+ </label>
+ <textarea
+ id={ids.prompt}
+ ref={promptRef}
+ value={prompt}
+ maxLength={MAX_PROMPT}
+ onChange={(e) => setPrompt(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ void submit();
+ }
+ }}
+ rows={2}
+ placeholder={`${examples[example % examples.length]}…`}
+ className="mt-1 w-full resize-none bg-transparent px-1 text-body leading-relaxed outline-none [field-sizing:content] placeholder:text-subtle-foreground"
+ />
+ <div className="scrollbar-none -mx-1 flex gap-1.5 overflow-x-auto px-1 pb-1">
+ {examples.slice(0, 5).map((ex) => (
+ <button key={ex} type="button" onClick={() => setPrompt(ex)} className="h-7 shrink-0 rounded-full bg-secondary px-2.5 text-[12px] text-secondary-foreground hover:bg-accent">
+ {ex}
+ </button>
+ ))}
+ </div>
+
+ <div className="mt-2 flex flex-wrap items-center gap-1.5 border-t pt-3">
+ <Select value={genre} onValueChange={(v) => setGenre(v as FacelessGenre)}>
+ <SelectTrigger aria-label="Genre" className={chipTrigger()}>
+ <SelectValue>{GENRES.find((g) => g.id === genre)?.label}</SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {GENRES.map((g) => (
+ <SelectItem key={g.id} value={g.id}>
+ <span className="flex flex-col">
+ <span>{g.label}</span>
+ <span className="text-[12px] text-muted-foreground">{g.hint}</span>
+ </span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Select value={animation} onValueChange={(v) => setAnimation(v as AnimationStyleId)}>
+ <SelectTrigger aria-label="Animation style" className={chipTrigger()}>
+ <SelectValue>{ANIMATION_STYLES.find((a) => a.id === animation)?.label}</SelectValue>
+ </SelectTrigger>
+ <SelectContent className="max-w-[min(92vw,380px)]">
+ {ANIMATION_STYLES.map((a) => (
+ <SelectItem key={a.id} value={a.id}>
+ <span className="flex flex-col whitespace-normal">
+ <span>{a.label}</span>
+ <span className="text-[12px] leading-snug text-muted-foreground">{engine === "open" ? a.openCopy : a.copy}</span>
+ </span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Select value={String(length)} onValueChange={(v) => setLength(Number(v))}>
+ <SelectTrigger aria-label="Length of each episode" className={chipTrigger()}>
+ <SelectValue>{CF_LENGTHS.find((l) => l.value === length)?.label}</SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {CF_LENGTHS.map((l) => (
+ <SelectItem key={l.value} value={String(l.value)}>
+ {l.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <div role="group" aria-label="Episodes" className="inline-flex h-8 items-center rounded-full bg-secondary">
+ <button type="button" onClick={() => setEpisodes((n) => Math.max(1, n - 1))} disabled={episodes <= 1} className="grid size-8 place-items-center rounded-full hover:bg-accent disabled:opacity-40" aria-label="Fewer episodes">
+ <Minus className="size-3.5" />
+ </button>
+ <span className="min-w-[5.5rem] text-center text-[13px] font-medium tabular-nums" aria-live="polite">
+ {episodes} episode{episodes === 1 ? "" : "s"}
+ </span>
+ <button type="button" onClick={() => setEpisodes((n) => Math.min(MAX_EPISODES, n + 1))} disabled={episodes >= MAX_EPISODES} className="grid size-8 place-items-center rounded-full hover:bg-accent disabled:opacity-40" aria-label="More episodes">
+ <Plus className="size-3.5" />
+ </button>
+ </div>
+ <Select value={aspect} onValueChange={(v) => setAspect(v as EpisodeAspect)}>
+ <SelectTrigger aria-label="Shape" className={chipTrigger()}>
+ <SelectValue>{aspect === "9:16" ? "9:16" : "16:9"}</SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="9:16">Vertical 9:16 · TikTok, Reels, Shorts</SelectItem>
+ <SelectItem value="16:9">Horizontal 16:9 · YouTube</SelectItem>
+ </SelectContent>
+ </Select>
+ {mode === "here" && <NarratorChip engine={engine} voices={voices} value={voice ?? null} onChange={setVoice} />}
+ </div>
+
+ <div className="mt-3 flex flex-wrap items-center gap-x-3 gap-y-2">
+ {mode === "here" ? (
+ <SeriesPriceLine data={est} loading={estimate.isFetching} engine={engine} className="min-w-0 flex-1 basis-56" />
+ ) : (
+ <p className="min-w-0 flex-1 basis-56 text-[12px] text-muted-foreground">Claude prices every episode with your providers and asks before it runs.</p>
+ )}
+ {mode === "here" && (
+ <label className="inline-flex cursor-pointer items-center gap-2 text-[12px] text-muted-foreground">
+ <Switch checked={review} onCheckedChange={setReview} aria-label="Review each script before it renders" />
+ Review scripts first
+ </label>
+ )}
+ <Button onClick={() => void submit()} disabled={busy} className="ml-auto h-9 rounded-full px-4">
+ {busy ? <Loader2 className="animate-spin" /> : mode === "here" ? <ArrowRight /> : <Bot />}
+ {busy ? "Planning your episodes…" : mode === "here" ? (episodes > 1 ? `Generate ${episodes} episodes` : "Generate") : "Get the prompt"}
+ </Button>
+ </div>
+ {mode === "here" && est?.error && (
+ <p role="alert" className="mt-2 text-[12px] text-destructive">
+ {est.error}
+ </p>
+ )}
+ {blocker && prompt.trim() && (
+ <p className="mt-2 text-[12px] text-muted-foreground" aria-live="polite">
+ {blocker}
+ </p>
+ )}
+ </div>
+
+ {brief && !reading && (
+ <BriefCard
+ className="mt-4"
+ brief={brief}
+ note={view?.analysis?.note}
+ saving={updateBrief.isPending}
+ onSave={async (b) => {
+ try {
+ // A preset's brief, edited, becomes a series of its own.
+ const id = seriesId ?? (await startSeries({ kind: "preset", presetId })).id;
+ await updateBrief.mutateAsync({ id, brief: b });
+ } catch (e) {
+ toast.error((e as Error).message);
+ }
+ }}
+ />
+ )}
+ </div>
+
+ <section id="presets" aria-labelledby="presets-title" className="scroll-mt-16 space-y-4">
+ <div>
+ <h2 id="presets-title" className="font-heading text-[24px]">
+ Pick a trending style to start from
+ </h2>
+ <p className="text-[13px] text-muted-foreground">Ready-made briefs from formats that do well — nothing to read, so nothing to pay for.</p>
+ </div>
+ <PresetGrid value={view ? (view.reference?.presetId ?? null) : presetId} onPick={(p) => choosePreset(p.id)} />
+ </section>
+
+ <section aria-labelledby="series-title" className="space-y-4">
+ <h2 id="series-title" className="font-heading text-[24px]">
+ My series
+ </h2>
+ {list.isLoading ? (
+ <div className="grid grid-cols-2 gap-x-4 gap-y-6 sm:grid-cols-3 lg:grid-cols-5">
+ {Array.from({ length: 5 }, (_, i) => (
+ <Skeleton key={i} className="aspect-[4/5] rounded-xl" />
+ ))}
+ </div>
+ ) : list.data?.length ? (
+ <div className="grid grid-cols-2 gap-x-4 gap-y-6 sm:grid-cols-3 lg:grid-cols-5">
+ {list.data.map((s) => (
+ <SeriesTile key={s.id} s={s} />
+ ))}
+ </div>
+ ) : (
+ <div className="flex flex-col items-center rounded-2xl border border-dashed px-6 py-10 text-center">
+ <div className="grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">
+ <Film className="size-5" />
+ </div>
+ <p className="mt-3 font-heading text-[22px]">No series yet</p>
+ <p className="mt-1 max-w-sm text-[13px] text-muted-foreground">Pick a style above and say what to make: every episode lands here, and in Faceless Studio as a channel.</p>
+ </div>
+ )}
+ </section>
+
+ <section aria-label="How it works" className="grid gap-3 sm:grid-cols-3">
+ {STEPS.map((s, i) => (
+ <div key={s.title} className="flex gap-3 rounded-2xl bg-muted/50 p-4">
+ <span className="grid size-9 shrink-0 place-items-center rounded-xl bg-background text-brand-text shadow-soft">
+ <s.icon className="size-4" />
+ </span>
+ <div className="min-w-0">
+ <p className="text-[13px] font-medium">
+ {i + 1}. {s.title}
+ </p>
+ <p className="mt-0.5 text-[12px] leading-snug text-muted-foreground">{s.text}</p>
+ </div>
+ </div>
+ ))}
+ </section>
+ </div>
+ <ClaudeDialog open={claudeOpen} onOpenChange={setClaudeOpen} ask={claudeOpen ? { ...ask, ...source } : null} />
+ </div>
+ );
+}
+
+function SeriesTile({ s }: { s: SeriesCard }) {
+ const picture = s.poster?.outputs.find((o) => o.kind === "image");
+ return (
+ <Link href={`/content-factory/${s.id}`} className="group/card block min-w-0 animate-fade-up rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <div className={cn("relative overflow-hidden rounded-xl bg-muted", s.aspect === "9:16" ? "aspect-[4/5]" : "aspect-video")}>
+ {picture ? (
+ <MediaThumb output={picture} className="transition-transform duration-300 ease-move group-hover/card:scale-[1.02]" />
+ ) : s.thumbnail ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={s.thumbnail} alt="" className="size-full object-cover" />
+ ) : (
+ <StyleArt styleId={s.styleId} className="opacity-90" />
+ )}
+ {s.rendering > 0 && (
+ <span className="absolute bottom-2 left-2 inline-flex items-center gap-1 rounded-full bg-black/55 px-2 py-0.5 text-[11px] font-medium text-white backdrop-blur">
+ <Loader2 className="size-3 animate-spin" /> {s.rendering} in progress
+ </span>
+ )}
+ </div>
+ <div className="mt-2 min-w-0 px-0.5">
+ <h3 className="truncate text-[14px] font-medium">{s.name}</h3>
+ <p className="truncate text-[12px] text-muted-foreground">
+ {s.episodes} episode{s.episodes === 1 ? "" : "s"}
+ {s.done ? ` · ${s.done} done` : ""}
+ </p>
+ </div>
+ </Link>
+ );
+}
diff --git a/src/components/content-factory/hooks.ts b/src/components/content-factory/hooks.ts
new file mode 100644
index 00000000..fe0d75ef
--- /dev/null
+++ b/src/components/content-factory/hooks.ts
@@ -0,0 +1,125 @@
+"use client";
+
+import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import type { SeriesCard, SeriesEstimate, SeriesSettings, SeriesView, StyleBrief } from "@/lib/catalog/content-factory";
+import type { NarratorVoice } from "@/lib/catalog/faceless";
+import type { Engine } from "@/lib/catalog/types";
+import { useDebounced } from "@/components/faceless/hooks";
+
+/** React Query hooks for /api/content-factory/** (kept next to the views that use them). */
+
+export class ApiError extends Error {
+ constructor(
+ message: string,
+ readonly needsUpload = false,
+ ) {
+ super(message);
+ }
+}
+
+async function json<T>(res: Response): Promise<T> {
+ if (res.status === 204) return undefined as T;
+ const body = (await res.json().catch(() => ({}))) as T & { error?: string; needsUpload?: boolean };
+ if (!res.ok) throw new ApiError(body.error ?? `Request failed (${res.status})`, !!body.needsUpload);
+ 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) }));
+
+export type ReferenceInput = { kind: "upload"; url: string; title?: string } | { kind: "link"; link: string } | { kind: "preset"; presetId: string };
+
+/** What the composer sends for a price, a run or the Claude message. */
+export interface SeriesAsk {
+ prompt: string;
+ settings: SeriesSettings;
+ voice?: NarratorVoice | null;
+ subtitles?: boolean;
+ music?: boolean;
+}
+
+const inFlight = (v: SeriesView) => v.analysis?.status === "reading" || v.episodes.some((e) => e.status === "writing" || e.status === "rendering");
+
+export function useSeriesList() {
+ return useQuery({
+ queryKey: ["content-factory", "series"],
+ queryFn: async () => (await json<{ items: SeriesCard[] }>(await fetch("/api/content-factory/series"))).items,
+ refetchInterval: (q) => (q.state.data?.some((s) => s.rendering > 0) ? 5000 : false),
+ });
+}
+
+export function useSeries(id: string | null) {
+ return useQuery({
+ queryKey: ["content-factory", "series", id],
+ enabled: !!id,
+ queryFn: async () => json<SeriesView>(await fetch(`/api/content-factory/series/${id}`)),
+ retry: (n, e) => !/not found/i.test((e as Error).message) && n < 1,
+ refetchInterval: (q) => {
+ const d = q.state.data;
+ if (!d) return false;
+ return d.analysis?.status === "reading" ? 1200 : inFlight(d) ? 3000 : false;
+ },
+ });
+}
+
+/** Put a fresh view in the cache (so the page shows it without a refetch). */
+function useSetView() {
+ const qc = useQueryClient();
+ return (v: SeriesView) => {
+ qc.setQueryData(["content-factory", "series", v.id], v);
+ void qc.invalidateQueries({ queryKey: ["content-factory", "series"], exact: true });
+ };
+}
+
+export function useCreateSeries() {
+ const set = useSetView();
+ return useMutation({
+ mutationFn: (b: { reference: ReferenceInput | null; engine: Engine; prompt?: string }) => send<SeriesView>("/api/content-factory/series", "POST", b),
+ onSuccess: set,
+ });
+}
+
+export function useRereadSeries() {
+ const set = useSetView();
+ return useMutation({ mutationFn: ({ id, engine }: { id: string; engine: Engine }) => send<SeriesView>(`/api/content-factory/series/${id}/read`, "POST", { engine }), onSuccess: set });
+}
+
+export function useUpdateSeries() {
+ const set = useSetView();
+ return useMutation({ mutationFn: ({ id, ...b }: { id: string; brief?: StyleBrief; name?: string }) => send<SeriesView>(`/api/content-factory/series/${id}`, "PATCH", b), onSuccess: set });
+}
+
+export function useGenerateSeries() {
+ const set = useSetView();
+ return useMutation({ mutationFn: ({ id, ...b }: SeriesAsk & { id: string; review?: boolean }) => send<SeriesView>(`/api/content-factory/series/${id}/generate`, "POST", b), onSuccess: set });
+}
+
+export function useAddEpisodes(id: string) {
+ const set = useSetView();
+ return useMutation({ mutationFn: (b: { count: number; next?: string; review?: boolean }) => send<SeriesView>(`/api/content-factory/series/${id}/episodes`, "POST", b), onSuccess: set });
+}
+
+export function useDeleteSeries() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (id: string) => send<void>(`/api/content-factory/series/${id}`, "DELETE"),
+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["content-factory"] }),
+ });
+}
+
+export function useSeriesEstimate(input: (SeriesAsk & { seriesId?: string; presetId?: string }) | null) {
+ const key = input && JSON.stringify(input);
+ const debounced = useDebounced(key, 300);
+ const q = useQuery({
+ queryKey: ["content-factory", "estimate", debounced],
+ enabled: !!debounced,
+ queryFn: async () => send<SeriesEstimate>("/api/content-factory/estimate", "POST", JSON.parse(debounced!)),
+ placeholderData: keepPreviousData,
+ staleTime: 20_000,
+ retry: false,
+ });
+ return { data: q.data, error: q.error as Error | null, isFetching: q.isFetching || key !== debounced };
+}
+
+export const claudePrompt = (b: SeriesAsk & { seriesId?: string; presetId?: string }) =>
+ send<{ message: string; bytes: number; needsToken: boolean }>("/api/content-factory/claude", "POST", b);
diff --git a/src/components/content-factory/parts.tsx b/src/components/content-factory/parts.tsx
new file mode 100644
index 00000000..0d4c3931
--- /dev/null
+++ b/src/components/content-factory/parts.tsx
@@ -0,0 +1,378 @@
+"use client";
+
+import { AlertTriangle, Check, Copy, Film, Info, Loader2, Pencil, RotateCcw, Sparkles, Terminal, X } from "lucide-react";
+import Link from "next/link";
+import { useQuery } from "@tanstack/react-query";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { StyleArt } from "@/components/faceless/style-art";
+import { usd } from "@/components/faceless/controls";
+import { radioKeys, radioTab } from "@/components/studio/radio-keys";
+import {
+ briefLines,
+ mcpCommand,
+ PLATFORM_LABEL,
+ PRESETS,
+ type SeriesAnalysis,
+ type SeriesEstimate,
+ type SeriesReference,
+ type StyleBrief,
+ type StylePreset,
+} from "@/lib/catalog/content-factory";
+import { formatLength } from "@/lib/catalog/faceless";
+import type { Engine } from "@/lib/catalog/types";
+import { copyText } from "@/lib/clipboard";
+import { cn } from "@/lib/utils";
+import { claudePrompt, type SeriesAsk } from "./hooks";
+
+/** The research's pricing line (Higgsfield settles the cost once the video is made; Fuobe's providers do too). */
+export const PRICE_NOTE = "Final cost depends on video complexity and is settled once your video is generated. It may be slightly higher or lower than shown.";
+
+async function copy(text: string, what: string) {
+ if (await copyText(text)) toast.success(`${what} copied`);
+ else toast.error("Couldn't copy — select the text and copy it yourself");
+}
+
+// ---------------------------------------------------------------------------
+// The reference
+
+/** "TikTok · 0:42 · 9:16" */
+function referenceMeta(ref: SeriesReference): string {
+ const shape = ref.width && ref.height ? (ref.width > ref.height ? "16:9" : ref.width < ref.height ? "9:16" : "1:1") : null;
+ return [ref.kind === "preset" ? "Preset style" : ref.platform ? PLATFORM_LABEL[ref.platform] : "Your clip", ref.seconds ? formatLength(ref.seconds) : null, shape].filter(Boolean).join(" · ");
+}
+
+/** The reference in the composer or on the series page: its picture, what it is, and how reading it is going. */
+export function ReferenceCard({
+ reference,
+ analysis,
+ styleId,
+ onClear,
+ onReread,
+ rereading,
+ className,
+}: {
+ reference: SeriesReference;
+ analysis: SeriesAnalysis | null;
+ styleId: string;
+ onClear?: () => void;
+ onReread?: () => void;
+ rereading?: boolean;
+ className?: string;
+}) {
+ const reading = analysis?.status === "reading";
+ return (
+ <div className={cn("flex min-w-0 items-center gap-3 rounded-2xl bg-muted/60 p-2 pr-3", className)}>
+ <div className="relative size-14 shrink-0 overflow-hidden rounded-xl bg-muted">
+ {reference.thumbnail ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={reference.thumbnail} alt="" className="size-full object-cover" />
+ ) : reference.url ? (
+ <>
+ <Film className="absolute inset-0 m-auto size-5 text-muted-foreground" aria-hidden />
+ <video src={`${reference.url}#t=0.5`} muted playsInline preload="metadata" className="relative size-full object-cover" aria-hidden />
+ </>
+ ) : (
+ <StyleArt styleId={styleId} />
+ )}
+ {reading && (
+ <span className="absolute inset-0 grid place-items-center bg-black/35 text-white">
+ <Loader2 className="size-4 animate-spin" />
+ </span>
+ )}
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-[13px] font-medium">{reference.title || (reference.kind === "link" ? reference.link : "Reference clip")}</p>
+ <p className="truncate text-[12px] text-muted-foreground">{referenceMeta(reference)}</p>
+ <p className="mt-0.5 text-[12px]" role="status" aria-live="polite">
+ {reading ? (
+ <span className="text-muted-foreground">{analysis?.stage ?? "Reading the style…"}</span>
+ ) : analysis?.status === "failed" ? (
+ <span className="inline-flex items-center gap-1 text-destructive">
+ <AlertTriangle className="size-3 shrink-0" /> {analysis.error ?? "Couldn't read it"}
+ </span>
+ ) : analysis?.offline ? (
+ <span className="inline-flex items-center gap-1">
+ <Info className="size-3 shrink-0 text-warning" /> Rough brief — see its note
+ </span>
+ ) : (
+ <span className="inline-flex items-center gap-1">
+ <Check className="size-3 shrink-0 text-success" /> {reference.kind === "preset" ? "Ready to use" : "Style brief ready"}
+ </span>
+ )}
+ </p>
+ </div>
+ {onReread && reference.url && !reading && (
+ <Button variant="ghost" size="sm" className="shrink-0 rounded-full" onClick={onReread} disabled={rereading} aria-label="Read the clip again">
+ {rereading ? <Loader2 className="animate-spin" /> : <RotateCcw />}
+ <span className="hidden sm:inline">Read again</span>
+ </Button>
+ )}
+ {onClear && (
+ <button type="button" onClick={onClear} className="grid size-8 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Change reference">
+ <X className="size-4" />
+ </button>
+ )}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// The brief
+
+type EditableKey = "format" | "hook" | "pacing" | "look";
+const EDITABLE: { key: EditableKey; label: string }[] = [
+ { key: "format", label: "Format" },
+ { key: "hook", label: "Hook (first 3 seconds)" },
+ { key: "pacing", label: "Pacing" },
+ { key: "look", label: "Look of every picture" },
+];
+
+/** What every episode follows: format, hook, pacing, shots, narrator, music and captions — with the reading's note, and an editor. */
+export function BriefCard({ brief, note, onSave, saving, className }: { brief: StyleBrief; note?: string; onSave?: (b: StyleBrief) => void; saving?: boolean; className?: string }) {
+ const [draft, setDraft] = useState<StyleBrief | null>(null);
+ const id = useId();
+ return (
+ <section aria-labelledby={`${id}-t`} className={cn("rounded-2xl border bg-background p-4 text-left", className)}>
+ <div className="flex items-center gap-2">
+ <Sparkles className="size-4 shrink-0 text-brand-text" />
+ <h3 id={`${id}-t`} className="text-[14px] font-medium">
+ Style brief
+ </h3>
+ <span className="text-[12px] text-muted-foreground">every episode follows it</span>
+ {onSave && !draft && (
+ <Button variant="ghost" size="sm" className="ml-auto h-7 rounded-full" onClick={() => setDraft(brief)}>
+ <Pencil /> Edit
+ </Button>
+ )}
+ </div>
+ {note && (
+ <p className="mt-2 flex items-start gap-1.5 rounded-lg bg-warning/10 px-2.5 py-2 text-[12px] text-foreground">
+ <Info className="mt-0.5 size-3.5 shrink-0 text-warning" />
+ <span className="min-w-0">{note}</span>
+ </p>
+ )}
+ {draft ? (
+ <form
+ className="mt-3 space-y-2.5"
+ onSubmit={(e) => {
+ e.preventDefault();
+ onSave?.(draft);
+ setDraft(null);
+ }}
+ >
+ {EDITABLE.map((f) => (
+ <label key={f.key} className="block">
+ <span className="text-[12px] font-medium text-muted-foreground">{f.label}</span>
+ <textarea
+ value={draft[f.key]}
+ maxLength={f.key === "look" ? 600 : 400}
+ rows={2}
+ onChange={(e) => setDraft({ ...draft, [f.key]: e.target.value })}
+ className="mt-1 w-full resize-none rounded-lg border bg-background px-2.5 py-1.5 text-[13px] leading-snug outline-none [field-sizing:content] focus:border-primary"
+ />
+ </label>
+ ))}
+ <label className="block">
+ <span className="text-[12px] font-medium text-muted-foreground">Narrator</span>
+ <input
+ value={draft.voice.tone}
+ maxLength={200}
+ onChange={(e) => setDraft({ ...draft, voice: { ...draft.voice, tone: e.target.value } })}
+ className="mt-1 h-9 w-full rounded-lg border bg-background px-2.5 text-[13px] outline-none focus:border-primary"
+ />
+ </label>
+ <label className="block">
+ <span className="text-[12px] font-medium text-muted-foreground">Music</span>
+ <input
+ value={draft.music.mood}
+ maxLength={300}
+ onChange={(e) => setDraft({ ...draft, music: { ...draft.music, mood: e.target.value } })}
+ className="mt-1 h-9 w-full rounded-lg border bg-background px-2.5 text-[13px] outline-none focus:border-primary"
+ />
+ </label>
+ <div className="flex justify-end gap-2 pt-1">
+ <Button type="button" variant="ghost" size="sm" onClick={() => setDraft(null)}>
+ Cancel
+ </Button>
+ <Button type="submit" size="sm" disabled={saving}>
+ {saving && <Loader2 className="animate-spin" />} Save brief
+ </Button>
+ </div>
+ </form>
+ ) : (
+ <ul className="mt-3 grid gap-x-6 gap-y-1.5 text-[13px] leading-snug sm:grid-cols-2">
+ {[...briefLines(brief), `Look: ${brief.look}`].map((l) => {
+ const [k, ...v] = l.split(": ");
+ return (
+ <li key={l} className="min-w-0">
+ <span className="text-muted-foreground">{k}:</span> {v.join(": ")}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </section>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Presets ("Pick a trending style to start from")
+
+export function PresetGrid({ value, onPick }: { value: string | null; onPick: (p: StylePreset) => void }) {
+ const picked = PRESETS.some((p) => p.id === value);
+ return (
+ <div role="radiogroup" aria-label="Preset styles" onKeyDown={radioKeys} className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
+ {PRESETS.map((p, i) => {
+ const on = value === p.id;
+ return (
+ <button
+ key={p.id}
+ type="button"
+ role="radio"
+ aria-checked={on}
+ tabIndex={radioTab(picked ? on : i === 0)}
+ onClick={() => onPick(p)}
+ className={cn(
+ "group/preset relative min-w-0 overflow-hidden rounded-2xl border bg-background text-left transition-[box-shadow,border-color] outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ on ? "border-primary ring-2 ring-brand-faint" : "hover:border-border-strong",
+ )}
+ >
+ <div className="relative aspect-[4/3] w-full overflow-hidden">
+ <StyleArt styleId={p.brief.styleId} className="transition-transform duration-300 ease-move group-hover/preset:scale-[1.04]" />
+ <span className="absolute bottom-2 left-2 rounded-full bg-black/50 px-2 py-0.5 text-[11px] font-medium text-white backdrop-blur">{p.brief.aspect === "9:16" ? "Vertical" : "Horizontal"}</span>
+ {on && (
+ <span className="absolute top-2 right-2 grid size-6 place-items-center rounded-full bg-primary text-primary-foreground shadow-soft">
+ <Check className="size-3.5" />
+ </span>
+ )}
+ </div>
+ <div className="p-3">
+ <p className="truncate text-[14px] font-medium">{p.name}</p>
+ <p className="mt-0.5 line-clamp-2 text-[12px] leading-snug text-muted-foreground">{p.tagline}</p>
+ <p className="mt-2 text-[12px] font-medium text-brand-text">{on ? "In use" : "Use as reference"}</p>
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// The price
+
+/** "≈ $4.20 · 3 episodes × $1.40" / "Demo · free" / "Free · your GPU", with the research's pricing note. */
+export function SeriesPriceLine({ data, loading, engine, className }: { data: SeriesEstimate | undefined; loading?: boolean; engine: Engine; className?: string }) {
+ if (!data) return <span className={cn("inline-flex items-center gap-1.5 font-mono text-[12px] text-muted-foreground", className)}>{loading && <Loader2 className="size-3 animate-spin" />}Estimating…</span>;
+ const p = data.price;
+ const each = p.episodes > 1 ? ` · ${p.episodes} × ${usd(p.perEpisode)}` : "";
+ const price = data.demo ? "Demo · free" : engine === "open" ? "Free · your GPU" : `≈ ${usd(p.total)}${p.unknown ? "+" : ""}${each}`;
+ return (
+ <span className={cn("inline-flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5", className)}>
+ <Popover>
+ <PopoverTrigger asChild>
+ <button type="button" className={cn("inline-flex items-center gap-1 font-mono text-[12px] text-foreground tabular-nums hover:underline", loading && "opacity-60")}>
+ {price}
+ {loading ? <Loader2 className="size-3 animate-spin text-muted-foreground" /> : <Info className="size-3 text-muted-foreground" />}
+ </button>
+ </PopoverTrigger>
+ <PopoverContent className="w-72 p-3 text-[13px]" collisionPadding={12}>
+ <p className="font-medium">How the price works</p>
+ <p className="mt-1 text-[12px] text-muted-foreground">{data.demo ? "Nothing is connected for some steps, so this runs as a free demo with placeholder results." : engine === "open" ? "Every step runs on your own ComfyUI: no fees." : PRICE_NOTE}</p>
+ {!data.demo && engine === "cloud" && p.episodes > 1 && (
+ <p className="mt-2 font-mono text-[12px] tabular-nums">
+ {p.episodes} episodes × {usd(p.perEpisode)} = {usd(p.total)}
+ </p>
+ )}
+ {data.notes?.map((n) => (
+ <p key={n} className="mt-2 border-t pt-2 text-[12px] text-muted-foreground">
+ {n}
+ </p>
+ ))}
+ </PopoverContent>
+ </Popover>
+ <span className="font-mono text-[12px] text-muted-foreground tabular-nums">
+ {formatLength(data.seconds)} · {data.scenes} scene{data.scenes === 1 ? "" : "s"} each
+ </span>
+ </span>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// "Generate in Claude": the claude mcp add line and the message, with copy buttons (nothing is sent anywhere)
+
+function CodeBox({ text, label, wrap, className }: { text: string; label: string; wrap?: boolean; className?: string }) {
+ return (
+ <div className={cn("relative rounded-xl bg-muted", className)}>
+ <pre tabIndex={0} aria-label={label} className={cn("max-h-64 overflow-auto p-3 pr-12 font-mono text-[11px] leading-relaxed outline-none focus-visible:ring-2 focus-visible:ring-ring", wrap ? "whitespace-pre-wrap" : "whitespace-pre")}>
+ {text}
+ </pre>
+ <button type="button" onClick={() => void copy(text, label)} className="absolute top-2 right-2 grid size-8 place-items-center rounded-lg bg-background text-muted-foreground shadow-soft hover:text-foreground" aria-label={`Copy ${label.toLowerCase()}`}>
+ <Copy className="size-3.5" />
+ </button>
+ </div>
+ );
+}
+
+export function ClaudeDialog({ open, onOpenChange, ask }: { open: boolean; onOpenChange: (v: boolean) => void; ask: (SeriesAsk & { seriesId?: string; presetId?: string }) | null }) {
+ const key = ask && JSON.stringify(ask);
+ const q = useQuery({ queryKey: ["content-factory", "claude", key], enabled: open && !!key, queryFn: () => claudePrompt(JSON.parse(key!)), retry: false, staleTime: 60_000 });
+ const out = q.data ?? null;
+ const error = q.error ? (q.error as Error).message : null;
+ const [origin] = useState(() => (typeof window === "undefined" ? "http://localhost:3000" : window.location.origin));
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-h-[90svh] overflow-y-auto sm:max-w-[640px]">
+ <DialogHeader>
+ <DialogTitle>Generate in Claude</DialogTitle>
+ <DialogDescription>Claude plans and writes the episodes, then makes them with Fuobe through its MCP server. It prices each one and asks you before it spends anything.</DialogDescription>
+ </DialogHeader>
+ <ol className="min-w-0 space-y-4 text-[13px]">
+ <li className="min-w-0 space-y-1.5">
+ <p className="font-medium">
+ <span className="text-muted-foreground">1.</span> Connect Fuobe to Claude Code (once)
+ </p>
+ <CodeBox text={mcpCommand(origin, !!out?.needsToken)} label="Command" />
+ {out?.needsToken && (
+ <p className="text-[12px] text-muted-foreground">
+ This studio has a password: create a token in{" "}
+ <Link href="/settings#security" className="underline underline-offset-2">
+ Settings → Security
+ </Link>{" "}
+ and put it in place of fuobe_…
+ </p>
+ )}
+ </li>
+ <li className="min-w-0 space-y-1.5">
+ <p className="font-medium">
+ <span className="text-muted-foreground">2.</span> Paste this into a new Claude chat
+ </p>
+ {error ? (
+ <p role="alert" className="flex items-start gap-1.5 text-[12px] text-destructive">
+ <AlertTriangle className="mt-0.5 size-3.5 shrink-0" /> {error}
+ </p>
+ ) : out ? (
+ <CodeBox text={out.message} label="Prompt" wrap />
+ ) : (
+ <div className="flex h-24 items-center justify-center gap-2 rounded-xl bg-muted text-[12px] text-muted-foreground">
+ <Loader2 className="size-4 animate-spin" /> Writing the prompt…
+ </div>
+ )}
+ </li>
+ </ol>
+ <div className="flex flex-wrap items-center justify-between gap-2 pt-1">
+ <p className="flex items-center gap-1.5 text-[12px] text-muted-foreground">
+ <Terminal className="size-3.5 shrink-0" /> Nothing is sent from here.
+ </p>
+ <Button disabled={!out} onClick={() => out && void copy(out.message, "Prompt")}>
+ <Copy /> Copy prompt
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/content-factory/series-view.tsx b/src/components/content-factory/series-view.tsx
new file mode 100644
index 00000000..78c85d1f
--- /dev/null
+++ b/src/components/content-factory/series-view.tsx
@@ -0,0 +1,239 @@
+"use client";
+
+import { ArrowLeft, Loader2, Minus, Plus, Trash2, Tv } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import { SidebarTrigger } from "@/components/ui/sidebar";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Switch } from "@/components/ui/switch";
+import { EpisodeTile } from "@/components/faceless/cards";
+import { voiceLabel } from "@/components/faceless/narrator";
+import { animationStyle, CF_LENGTHS, MAX_EPISODES } from "@/lib/catalog/content-factory";
+import { genreInfo, type PickerData } from "@/lib/catalog/faceless";
+import { BriefCard, ReferenceCard, SeriesPriceLine } from "./parts";
+import { useAddEpisodes, useDeleteSeries, useSeries, useSeriesEstimate, useUpdateSeries } from "./hooks";
+
+function Chip({ children }: { children: React.ReactNode }) {
+ return <span className="inline-flex h-7 max-w-full items-center truncate rounded-full bg-secondary px-2.5 text-[12px] font-medium text-secondary-foreground">{children}</span>;
+}
+
+export function SeriesView({ id, voices }: { id: string; voices: PickerData["voices"] }) {
+ const router = useRouter();
+ const { data: s, isLoading, error } = useSeries(id);
+ const more = useAddEpisodes(id);
+ const del = useDeleteSeries();
+ const update = useUpdateSeries();
+ const [next, setNext] = useState("");
+ const [count, setCount] = useState(1);
+ const [review, setReview] = useState(false);
+ const [confirm, setConfirm] = useState(false);
+ const nextId = useId();
+
+ const channel = s?.channel ?? null;
+ const settings = s?.settings ?? null;
+ const estimate = useSeriesEstimate(
+ s && settings && channel
+ ? { prompt: s.prompt, settings: { ...settings, engine: channel.settings.engine, episodes: count }, voice: channel.settings.voice, seriesId: s.id, subtitles: channel.settings.subtitles, music: channel.settings.music }
+ : null,
+ );
+
+ const header = (
+ <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">
+ <SidebarTrigger className="md:hidden" />
+ <Link href="/content-factory" className="inline-flex min-w-0 items-center gap-1.5 text-[13px] text-muted-foreground hover:text-foreground">
+ <ArrowLeft className="size-4 shrink-0" /> <span className="truncate">Content Factory</span>
+ </Link>
+ </header>
+ );
+
+ if (error || (s && !channel)) {
+ return (
+ <div className="flex min-h-svh min-w-0 flex-col">
+ {header}
+ <div className="mx-auto w-full max-w-[640px] px-3 pt-16 text-center sm:px-6">
+ <h1 className="font-heading text-[28px]">{error ? "Series not found" : "This series hasn't been made yet"}</h1>
+ <p className="mt-2 text-[14px] text-muted-foreground">{error ? "It may have been deleted." : "Its reference is in the Content Factory composer: say what it's about and generate it there."}</p>
+ <Button asChild className="mt-6 rounded-full">
+ <Link href="/content-factory">Open Content Factory</Link>
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
+ const style = settings ? animationStyle(settings.animation) : null;
+ const engine = channel?.settings.engine ?? "cloud";
+
+ return (
+ <div className="flex min-h-svh min-w-0 flex-col">
+ {header}
+ <div className="mx-auto w-full max-w-[1240px] min-w-0 flex-1 space-y-8 px-3 pb-16 sm:px-6">
+ {isLoading || !s || !channel || !settings ? (
+ <div className="space-y-4 pt-6">
+ <Skeleton className="h-9 w-72 max-w-full" />
+ <Skeleton className="h-4 w-96 max-w-full" />
+ <div className="grid grid-cols-2 gap-4 pt-6 sm:grid-cols-3 lg:grid-cols-5">
+ {Array.from({ length: 5 }, (_, i) => (
+ <Skeleton key={i} className="aspect-[4/5] rounded-xl" />
+ ))}
+ </div>
+ </div>
+ ) : (
+ <>
+ <section className="flex flex-wrap items-start gap-4 pt-6">
+ <div className="min-w-0 flex-1 basis-72">
+ <h1 className="font-heading text-[32px] leading-tight text-balance">{s.name ?? channel.name}</h1>
+ {s.prompt.trim().toLowerCase() !== (s.name ?? channel.name).trim().toLowerCase() && <p className="mt-1 line-clamp-3 text-[14px] text-muted-foreground">{s.prompt}</p>}
+ <div className="mt-3 flex flex-wrap gap-1.5">
+ <Chip>{genreInfo(settings.genre).label}</Chip>
+ <Chip>{style?.label}</Chip>
+ <Chip>{CF_LENGTHS.find((l) => l.value === settings.length)?.label ?? `${settings.length} s`} each</Chip>
+ <Chip>{settings.aspect === "9:16" ? "Vertical 9:16" : "Horizontal 16:9"}</Chip>
+ <Chip>{voiceLabel(channel.settings.voice, voices, engine)}</Chip>
+ <Chip>{engine === "open" ? "Open source" : "Cloud"}</Chip>
+ </div>
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ <Button asChild variant="secondary" className="rounded-full">
+ <Link href={`/faceless/${channel.id}`}>
+ <Tv /> Open in Faceless Studio
+ </Link>
+ </Button>
+ <Button variant="ghost" size="icon" className="rounded-full text-muted-foreground hover:text-destructive" onClick={() => setConfirm(true)} aria-label="Delete series">
+ <Trash2 />
+ </Button>
+ </div>
+ </section>
+
+ <div className="grid gap-4 lg:grid-cols-[minmax(0,2fr)_minmax(0,3fr)]">
+ {s.reference && <ReferenceCard reference={s.reference} analysis={s.analysis} styleId={channel.settings.styleId} className="h-fit" />}
+ {s.brief && (
+ <BriefCard
+ brief={s.brief}
+ note={s.analysis?.note}
+ saving={update.isPending}
+ onSave={(b) => update.mutate({ id: s.id, brief: b }, { onSuccess: () => toast("Saved — episodes you add from now on follow it"), onError: (e) => toast.error((e as Error).message) })}
+ />
+ )}
+ </div>
+
+ <section aria-labelledby="episodes-title" className="space-y-4">
+ <h2 id="episodes-title" className="font-heading text-[24px]">
+ Episodes
+ </h2>
+ <ol className="grid grid-cols-2 gap-x-4 gap-y-6 sm:grid-cols-3 lg:grid-cols-5">
+ {s.episodes.map((ep, i) => (
+ <li key={ep.id} className="min-w-0">
+ <p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Episode {i + 1}</p>
+ <EpisodeTile ep={ep} href={`/faceless/${channel.id}/${ep.id}`} />
+ </li>
+ ))}
+ </ol>
+ </section>
+
+ <section aria-labelledby="next-title" className="max-w-[760px] rounded-2xl border bg-background p-4 shadow-soft">
+ <h2 id="next-title" className="text-[15px] font-medium">
+ Next episode
+ </h2>
+ <label htmlFor={nextId} className="mt-1 block text-[12px] text-muted-foreground">
+ What happens in the next episode? Leave it empty and the story simply carries on.
+ </label>
+ <textarea
+ id={nextId}
+ value={next}
+ maxLength={1000}
+ rows={2}
+ onChange={(e) => setNext(e.target.value)}
+ placeholder={s.plan.length ? `After “${s.plan[s.plan.length - 1].title}”…` : "What happens next…"}
+ className="mt-2 w-full resize-none rounded-xl border bg-background px-3 py-2 text-[14px] leading-relaxed outline-none [field-sizing:content] focus:border-primary"
+ />
+ <div className="mt-3 flex flex-wrap items-center gap-x-3 gap-y-2">
+ <div role="group" aria-label="Episodes to add" className="inline-flex h-8 items-center rounded-full bg-secondary">
+ <button type="button" onClick={() => setCount((n) => Math.max(1, n - 1))} disabled={count <= 1} className="grid size-8 place-items-center rounded-full hover:bg-accent disabled:opacity-40" aria-label="Fewer episodes">
+ <Minus className="size-3.5" />
+ </button>
+ <span className="min-w-[5.5rem] text-center text-[13px] font-medium tabular-nums" aria-live="polite">
+ {count} episode{count === 1 ? "" : "s"}
+ </span>
+ <button type="button" onClick={() => setCount((n) => Math.min(MAX_EPISODES, n + 1))} disabled={count >= MAX_EPISODES} className="grid size-8 place-items-center rounded-full hover:bg-accent disabled:opacity-40" aria-label="More episodes">
+ <Plus className="size-3.5" />
+ </button>
+ </div>
+ <SeriesPriceLine data={estimate.data} loading={estimate.isFetching} engine={engine} className="min-w-0 flex-1 basis-48" />
+ <label className="inline-flex cursor-pointer items-center gap-2 text-[12px] text-muted-foreground">
+ <Switch checked={review} onCheckedChange={setReview} aria-label="Review each script before it renders" />
+ Review scripts first
+ </label>
+ <Button
+ className="ml-auto h-9 rounded-full px-4"
+ disabled={more.isPending}
+ onClick={() =>
+ more.mutate(
+ { count, next: next.trim() || undefined, review },
+ {
+ onSuccess: () => {
+ setNext("");
+ toast(count === 1 ? "Next episode started" : `${count} episodes started`);
+ },
+ onError: (e) => toast.error((e as Error).message),
+ },
+ )
+ }
+ >
+ {more.isPending ? <Loader2 className="animate-spin" /> : <Plus />}
+ {more.isPending ? "Planning…" : count === 1 ? "Add episode" : `Add ${count} episodes`}
+ </Button>
+ </div>
+ {estimate.data?.error && (
+ <p role="alert" className="mt-2 text-[12px] text-destructive">
+ {estimate.data.error}
+ </p>
+ )}
+ </section>
+
+ <AlertDialog open={confirm} onOpenChange={setConfirm}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete “{s.name ?? channel.name}”?</AlertDialogTitle>
+ <AlertDialogDescription>
+ The series, its channel and its {s.episodes.length} episode{s.episodes.length === 1 ? "" : "s"} are removed, and anything still rendering stops. Finished videos stay in your Library.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() =>
+ del.mutate(s.id, {
+ onSuccess: () => {
+ toast("Series deleted");
+ router.push("/content-factory");
+ },
+ onError: (e) => toast.error((e as Error).message),
+ })
+ }
+ >
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/src/server/faceless.ts b/src/server/faceless.ts
index d4776730..408510d8 100644
--- a/src/server/faceless.ts
+++ b/src/server/faceless.ts
@@ -592,6 +592,8 @@ async function writeScript(id: string, pasted: string, signal: AbortSignal): Pro
script = { source: "ai", title: parsed.title ?? undefined, blocks: parsed.blocks };
} else {
const blocks = offlineScript(topic, ep.kind === "explainer" ? "education" : genre.id, scenes);
+ // The offline beats run about 10 s each: a brief's shorter scenes would overshoot the length, so middle beats go.
+ if (s.brief?.sceneSeconds && !auto) while (blocks.length > 1 && totalSeconds(blocks) > s.length * 1.15) blocks.splice(Math.floor(blocks.length / 2), 1);
if (elements.length) for (const b of blocks) b.visual = `${b.visual}, with ${elements.map((e) => `@${e.handle}`).join(" and ")}`;
script = { source: "ai", blocks, offline: true, note: failure ? `${OFFLINE_NOTE} (${failure})` : OFFLINE_NOTE };
}
diff --git a/tests/content-factory-api.test.ts b/tests/content-factory-api.test.ts
index ad063fdf..d0a68542 100644
--- a/tests/content-factory-api.test.ts
+++ b/tests/content-factory-api.test.ts
@@ -172,6 +172,10 @@ describe("prices, Generate here and Next episode", () => {
expect(ep.settings).toMatchObject({ length: 30, animation: "frames", aspect: "9:16", brief: { sceneSeconds: expect.any(Number) } });
expect(ep.topic).toMatch(/^Episode 1 of the series “The lost city of Ys”/);
expect(faceless.episodeView(v.episodes[2].id).episode.topic).toMatch(/Earlier episodes: .+; .+\./);
+ // The offline writer keeps a 30-second episode near 30 s, even at the brief's faster pace.
+ await faceless.scriptWritten(v.episodes[0].id);
+ const written = faceless.episodeView(v.episodes[0].id).episode;
+ expect(written.script.blocks.reduce((n, b) => n + b.seconds, 0)).toBeLessThanOrEqual(30 * 1.15);
// A second click doesn't make it twice.
expect((await generateRoute.POST(json("POST", { prompt: "The lost city of Ys", settings }), params({ id: series.id }))).status).toBe(409);
// GET handlers start with connection(), which needs a request scope: read through the server module.