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
Content Factory: one Generate at a time, frames that fit one Claude request, and Claude told the engine it runs on
Claude94add4c0f7d7
diff --git a/src/app/api/content-factory/series/[id]/route.ts b/src/app/api/content-factory/series/[id]/route.tsindex a7186ab6..2f57b7ed 100644--- a/src/app/api/content-factory/series/[id]/route.ts+++ b/src/app/api/content-factory/series/[id]/route.ts@@ -19,10 +19,13 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/content-fa});}-/** Deletes the series and its channel, stopping what its episodes still render (finished videos stay in the Library). */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) {+/**+ * Deletes the series and its channel, stopping what its episodes still render (finished videos stay in the Library).+ * `?draft=1` deletes only a draft that was never made (the composer moving on from a clip it was reading).+ */+export async function DELETE(request: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) {return handle(async () => {- await deleteSeries((await ctx.params).id);+ await deleteSeries((await ctx.params).id, { draftOnly: new URL(request.url).searchParams.get("draft") === "1" });return new Response(null, { status: 204 });});}diff --git a/src/components/content-factory/home.tsx b/src/components/content-factory/home.tsxindex 93965bfa..d9841cd4 100644--- a/src/components/content-factory/home.tsx+++ b/src/components/content-factory/home.tsx@@ -30,7 +30,7 @@ import {} 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 { ApiError, discardDraft, 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). */@@ -90,7 +90,7 @@ export function ContentFactoryHome({ voices }: { voices: PickerData["voices"] })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 gone = !!series.error || !!series.data?.made;const seriesId = gone ? null : candidate;const create = useCreateSeries();const generate = useGenerateSeries();@@ -127,10 +127,17 @@ export function ContentFactoryHome({ voices }: { voices: PickerData["voices"] })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 });+ // Priced again when the clip's brief comes in or is edited, not only when a setting changes.+ const estimate = useSeriesEstimate({ ...ask, prompt: ask.prompt || "estimate", ...source }, view ? `${view.analysis?.status ?? "none"}:${view.updatedAt}` : undefined);const perMinute = estimate.data?.analysisPerMinute ?? 0;+ /** The draft being left (another clip, a preset, X): reading it stops, so it stops billing, and its row goes. */+ const leaveDraft = (next?: string) => {+ if (seriesId && seriesId !== next) discardDraft(seriesId);+ };+const choosePreset = (id: string) => {+ leaveDraft();setPresetId(id);setSeriesId(null);writeDraft(null);@@ -139,6 +146,7 @@ export function ContentFactoryHome({ voices }: { voices: PickerData["voices"] })const startSeries = (reference: Parameters<typeof create.mutate>[0]["reference"]) =>create.mutateAsync({ reference, engine }).then((v) => {+ leaveDraft(v.id);setSeriesId(v.id);writeDraft(v.id);setLinkOpen(false);@@ -169,13 +177,17 @@ export function ContentFactoryHome({ voices }: { voices: PickerData["voices"] })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;+ // One run at a time: a second Enter (or click) before the first request has re-rendered would plan, make and bill it twice.+ const submitting = useRef(false);const submit = async () => {+ if (submitting.current) return;if (blocker) {toast(blocker, { id: "cf-blocker" });if (!prompt.trim()) promptRef.current?.focus();return;}if (mode === "claude") return setClaudeOpen(true);+ submitting.current = 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;@@ -184,6 +196,8 @@ export function ContentFactoryHome({ voices }: { voices: PickerData["voices"] })router.push(`/content-factory/${id}`);} catch (e) {toast.error((e as Error).message);+ } finally {+ submitting.current = false;}};@@ -405,7 +419,7 @@ export function ContentFactoryHome({ voices }: { voices: PickerData["voices"] }){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>+ <p className="min-w-0 flex-1 basis-56 text-[12px] text-muted-foreground">Claude prices every episode and asks before it runs.</p>)}{mode === "here" && (<label className="inline-flex cursor-pointer items-center gap-2 text-[12px] text-muted-foreground">diff --git a/src/components/content-factory/hooks.ts b/src/components/content-factory/hooks.tsindex fe0d75ef..e3b77805 100644--- a/src/components/content-factory/hooks.ts+++ b/src/components/content-factory/hooks.ts@@ -1,7 +1,7 @@"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 { ClaudePrompt, 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";@@ -62,12 +62,13 @@ export function useSeries(id: string | null) {});}-/** Put a fresh view in the cache (so the page shows it without a refetch). */+/** Put a fresh view in the cache (so the page shows it without a refetch); its brief may price differently now. */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 });+ void qc.invalidateQueries({ queryKey: ["content-factory", "estimate"] });};}@@ -107,11 +108,15 @@ export function useDeleteSeries() {});}-export function useSeriesEstimate(input: (SeriesAsk & { seriesId?: string; presetId?: string }) | null) {+/**+ * The series' price. `rev` names the brief it's priced on (the series' reading state and last change), so a+ * brief that's read or edited is priced again even when none of the settings changed.+ */+export function useSeriesEstimate(input: (SeriesAsk & { seriesId?: string; presetId?: string }) | null, rev?: string) {const key = input && JSON.stringify(input);const debounced = useDebounced(key, 300);const q = useQuery({- queryKey: ["content-factory", "estimate", debounced],+ queryKey: ["content-factory", "estimate", debounced, rev ?? null],enabled: !!debounced,queryFn: async () => send<SeriesEstimate>("/api/content-factory/estimate", "POST", JSON.parse(debounced!)),placeholderData: keepPreviousData,@@ -121,5 +126,9 @@ export function useSeriesEstimate(input: (SeriesAsk & { seriesId?: string; presereturn { 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);+export const claudePrompt = (b: SeriesAsk & { seriesId?: string; presetId?: string }) => send<ClaudePrompt>("/api/content-factory/claude", "POST", b);++/** Let go of a draft the composer moved away from: its reading stops (and stops billing), and its row goes. */+export function discardDraft(id: string): void {+ void fetch(`/api/content-factory/series/${id}?draft=1`, { method: "DELETE" }).catch(() => {});+}diff --git a/src/components/content-factory/parts.tsx b/src/components/content-factory/parts.tsxindex 0d4c3931..ff55a071 100644--- a/src/components/content-factory/parts.tsx+++ b/src/components/content-factory/parts.tsx@@ -298,6 +298,7 @@ export function SeriesPriceLine({ data, loading, engine, className }: { data: Se<span className="font-mono text-[12px] text-muted-foreground tabular-nums">{formatLength(data.seconds)} · {data.scenes} scene{data.scenes === 1 ? "" : "s"} each</span>+ {data.briefPending && <span className="text-[12px] text-muted-foreground">· priced again once the clip is read</span>}</span>);}@@ -349,8 +350,26 @@ export function ClaudeDialog({ open, onOpenChange, ask }: { open: boolean; onOpe</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+ <span className="text-muted-foreground">2.</span> Paste this into Claude Code</p>+ {out?.engineNote && (+ <p className="flex items-start gap-1.5 rounded-lg bg-warning/10 px-2.5 py-2 text-[12px]">+ <Info className="mt-0.5 size-3.5 shrink-0 text-warning" />+ <span className="min-w-0">{out.engineNote}</span>+ </p>+ )}+ {out && out.parts > 1 && (+ <p className="flex items-start gap-1.5 text-[12px] text-muted-foreground">+ <Film className="mt-0.5 size-3.5 shrink-0" />+ <span className="min-w-0">+ Each episode comes out as {out.parts} videos of about {formatLength(out.partSeconds)}: Fuobe's faceless_episode tool makes up to 8 scenes a call. Put them together with{" "}+ <Link href="/video-tools/join" className="underline underline-offset-2">+ Video tools → Join clips+ </Link>+ .+ </span>+ </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}diff --git a/src/components/content-factory/series-view.tsx b/src/components/content-factory/series-view.tsxindex 78c85d1f..1097c358 100644--- a/src/components/content-factory/series-view.tsx+++ b/src/components/content-factory/series-view.tsx@@ -48,6 +48,7 @@ export function SeriesView({ id, voices }: { id: string; voices: PickerData["vois && 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,+ s ? String(s.updatedAt) : undefined,);const header = (@@ -60,15 +61,39 @@ export function SeriesView({ id, voices }: { id: string; voices: PickerData["voi);if (error || (s && !channel)) {+ // Made, but its channel was deleted in Faceless Studio (its episodes went with it): only deleting is left.+ const orphan = !error && !!s?.made;+ const removeOrphan = () =>+ s &&+ del.mutate(s.id, {+ onSuccess: () => {+ toast("Series deleted");+ router.push("/content-factory");+ },+ onError: (e) => toast.error((e as Error).message),+ });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>+ <h1 className="font-heading text-[28px]">{error ? "Series not found" : orphan ? "This series' channel was deleted" : "This series hasn't been made yet"}</h1>+ <p className="mt-2 text-[14px] text-muted-foreground">+ {error+ ? "It may have been deleted."+ : orphan+ ? "Its channel and episodes were deleted in Faceless Studio, so nothing more can be made here. Start a new series from the same reference in Content Factory."+ : "Its reference is in the Content Factory composer: say what it's about and generate it there."}+ </p>+ <div className="mt-6 flex flex-wrap justify-center gap-2">+ {orphan && (+ <Button variant="secondary" className="rounded-full" onClick={removeOrphan} disabled={del.isPending}>+ {del.isPending ? <Loader2 className="animate-spin" /> : <Trash2 />} Delete series+ </Button>+ )}+ <Button asChild className="rounded-full">+ <Link href="/content-factory">Open Content Factory</Link>+ </Button>+ </div></div></div>);diff --git a/src/lib/catalog/content-factory.ts b/src/lib/catalog/content-factory.tsindex 17920cb7..9bc45076 100644--- a/src/lib/catalog/content-factory.ts+++ b/src/lib/catalog/content-factory.ts@@ -196,6 +196,10 @@ function text(v: unknown, max = 400): string {const clampNum = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, n));const round1 = (n: number) => Math.round(n * 10) / 10;+/** A narrator's pace a brief can carry (words a minute); the brief editor's schema accepts a little more either side. */+export const MIN_WPM = 80;+export const MAX_WPM = 260;+/** "2–3 s" → 2.5, "about 4 seconds" → 4, "fast" → 2.5; null when it says nothing about time. */export function secondsFrom(v: unknown): number | null {if (typeof v === "number" && Number.isFinite(v) && v > 0) return v;@@ -349,7 +353,7 @@ export function normalizeBrief(raw: unknown, base: StyleBrief = defaultBrief()):const wpm = Number(text(field(voiceRaw, "words_per_minute", "wordsPerMinute", "wpm", "pace", "speed")).match(/\d+/)?.[0] ?? NaN);const tone = text([field(voiceRaw, "tone", "style", "delivery"), field(voiceRaw, "voice", "gender", "character")].filter((x) => x !== undefined), 160) || base.voice.tone;const language = text(field(voiceRaw, "language", "lang"), 40);- voice = { tone, ...(Number.isFinite(wpm) && wpm >= 80 && wpm <= 260 && { wordsPerMinute: Math.round(wpm) }), ...(language && { language }) };+ voice = { tone, ...(Number.isFinite(wpm) && wpm >= MIN_WPM && wpm <= MAX_WPM && { wordsPerMinute: Math.round(wpm) }), ...(language && { language }) };} else voice = { tone: text(voiceRaw, 160) || base.voice.tone };const musicRaw = field(root, "music", "soundtrack", "background_music", "audio", "sound");@@ -422,7 +426,9 @@ export function speechRate(cues: TimedText[]): number | null {export function offlineBrief(o: { seconds?: number; width?: number; height?: number; cues?: TimedText[]; title?: string } = {}): StyleBrief {const aspect: EpisodeAspect = o.width && o.height ? (o.width > o.height ? "16:9" : "9:16") : "9:16";const b = defaultBrief({ aspect });- const wpm = o.cues ? speechRate(o.cues) : null;+ // A rap or a sped-up voice reads faster than any narrator speaks: kept within what a brief can say (and save).+ const rate = o.cues ? speechRate(o.cues) : null;+ const wpm = rate === null ? null : clampNum(rate, MIN_WPM, MAX_WPM);const long = (o.seconds ?? 0) > 90;return {...b,@@ -990,6 +996,30 @@ export function mcpCommand(origin: string, needsToken: boolean): string {return `claude mcp add --transport http fuobe ${origin.replace(/\/+$/, "")}/api/mcp${needsToken ? ' --header "Authorization: Bearer fuobe_…"' : ""}`;}+export interface ClaudePlan {+ /** Seconds of narration a scene carries in the message. */+ sceneSeconds: number;+ /** What the brief's own pace would give a scene (shorter when the tool's 8 scenes don't cover the episode). */+ briefSceneSeconds: number;+ scenes: number;+ /** faceless_episode calls (separate videos) per episode. */+ parts: number;+ perPart: number;+ partSeconds: number;+}++/**+ * How an episode fits faceless_episode, which takes up to 8 scenes a call: scenes are lengthened first (up to+ * 10 s, the tool's own scene length), then a longer episode is made as parts, one call (one video) each.+ */+export function claudePlan(o: { length: number; brief: StyleBrief; animation: AnimationStyleId }): ClaudePlan {+ const briefSceneSeconds = sceneSecondsFor(animationStyle(o.animation), o.brief.shotSeconds);+ const sceneSeconds = Math.min(BLOCK_SECONDS, Math.max(briefSceneSeconds, Math.round(o.length / TOOL_MAX_SCENES)));+ const scenes = Math.max(2, scenesFor(o.length, sceneSeconds));+ const parts = Math.ceil(scenes / TOOL_MAX_SCENES);+ return { sceneSeconds, briefSceneSeconds, scenes, parts, perPart: Math.max(2, Math.ceil(scenes / parts)), partSeconds: Math.round(o.length / parts) };+}+export function claudeMessage(o: {prompt: string;brief: StyleBrief;@@ -998,16 +1028,15 @@ export function claudeMessage(o: {animation: AnimationStyleId;genre: GenreInfo;aspect: EpisodeAspect;+ /** The engine Fuobe's MCP server runs on (Settings → Engine mode), not the composer's switch. */engine: Engine;voice?: string | null;+ /** On the open engine: the narrator's recording (a /api/files/ URL), so Claude needn't ask for one. */+ voiceSample?: string | null;reference?: string | null;}): string {const style = animationStyle(o.animation);- // The tool takes up to 8 scenes: longer scenes first (up to 10 s each), then the episode in parts.- const sceneSecs = Math.min(BLOCK_SECONDS, Math.max(sceneSecondsFor(style, o.brief.shotSeconds), Math.round(o.length / TOOL_MAX_SCENES)));- const scenes = scenesFor(o.length, sceneSecs);- const parts = Math.ceil(scenes / TOOL_MAX_SCENES);- const perPart = Math.max(2, Math.ceil(scenes / parts));+ const { sceneSeconds: sceneSecs, briefSceneSeconds, scenes, parts, perPart, partSeconds } = claudePlan(o);const styleId = getStyle(o.brief.styleId).id;const words = wordsFor(sceneSecs);const look = `${getStyle(o.brief.styleId).look}. ${o.brief.look}`;@@ -1026,14 +1055,23 @@ export function claudeMessage(o: {"How to make it:",`1. Load the faceless-video skill (load_skill "faceless-video").`,n > 1 ? `2. Plan ${n} episode titles that build on each other, and show them to me.` : "2. Pick a specific, clickable title.",- `3. For each episode write ${Math.max(2, scenes)} scenes: narration of at most ${words} words each (about ${sceneSecs} s spoken), the first one a hook as the brief says, and a visual for each in the look above. ${style.writer}`,+ `3. For each episode write ${scenes} scenes: narration of at most ${words} words each (about ${sceneSecs} s spoken), the first one a hook as the brief says, and a visual for each in the look above. ${style.writer}`,+ sceneSecs > briefSceneSeconds+ ? ` Scenes run about ${sceneSecs} s here, longer than the brief's cuts (about ${o.brief.shotSeconds} s a shot), so that faceless_episode's ${TOOL_MAX_SCENES} scenes a call cover more of the episode: give every visual a camera move or a change of view so it keeps the brief's pace.`+ : null,parts > 1- ? ` faceless_episode takes up to ${TOOL_MAX_SCENES} scenes a call, so make each episode as ${parts} parts of about ${perPart} scenes (“Part 1”, “Part 2”…), one call per part.`- : "",+ ? ` faceless_episode makes one video of up to ${TOOL_MAX_SCENES} scenes a call, so each episode comes out as ${parts} parts of about ${perPart} scenes (about ${formatLength(partSeconds)} each), one call per part, titled “<episode title> — Part 1”, “— Part 2”…. Tell me this before I approve anything, and when they're done list each episode's parts in order: Join clips in Fuobe's Video tools puts them together into one video.`+ : null,`4. Price each ${parts > 1 ? "part" : "episode"} with estimate_job (tool "faceless_episode") and wait for my OK before running anything.`,- `5. Run faceless_episode once per ${parts > 1 ? "part" : "episode"} with style_id "${styleId}", style "${look.replace(/"/g, "'").slice(0, 600)}", aspect_ratio "${o.aspect}"${o.voice ? ` and voice "${o.voice}"` : ""}, then follow it with check_generations and give me the links when they're done.`,- o.engine === "open" ? "The open-source engine clones the narrator's voice: ask me for a 10–60 s voice sample (voice_sample) before running." : "",- ].filter((l, i, all) => l !== "" || (all[i - 1] !== "" && i > 0));+ `5. Run faceless_episode once per ${parts > 1 ? "part" : "episode"} with style_id "${styleId}", style "${look.replace(/"/g, "'").slice(0, 600)}", aspect_ratio "${o.aspect}"${o.engine === "open" ? (o.voiceSample ? ` and voice_sample "${o.voiceSample}"` : "") : o.voice ? ` and voice "${o.voice}"` : ""}, then follow it with check_generations and give me the links when they're done.`,+ o.engine === "open"+ ? o.voiceSample+ ? "Fuobe runs this on the open-source engine (my ComfyUI): no fees, and the narration clones the voice sample above."+ : "Fuobe runs this on the open-source engine (my ComfyUI), which clones the narrator's voice: ask me for a 10–60 s voice sample (voice_sample) before running."+ : null,+ ]+ .filter((l): l is string => l !== null)+ .filter((l, i, all) => l !== "" || (all[i - 1] !== "" && i > 0));let out = lines.join("\n");// Within Higgsfield's 64 KB cap (a very long prompt is cut, never the instructions).while (new TextEncoder().encode(out).length > MAX_CLAUDE_MESSAGE) out = out.replace(/Make a video about: ([\s\S]*?)\n/, (_m, p: string) => `Make a video about: ${p.slice(0, Math.floor(p.length * 0.8))}…\n`);@@ -1097,6 +1135,8 @@ export interface SeriesView {/** The planned episodes (titles), in order. */plan: SeriesEpisodePlan[];channel: FacelessChannel | null;+ /** "Generate here" has made it (its channel may since have been deleted in Faceless Studio: then channel is null). */+ made: boolean;episodes: EpisodeCard[];createdAt: number;updatedAt: number;@@ -1118,6 +1158,20 @@ export interface SeriesCard {updatedAt: number;}+/** What the "Generate in Claude" dialog shows (POST /api/content-factory/claude). */+export interface ClaudePrompt {+ message: string;+ bytes: number;+ needsToken: boolean;+ /** The engine Claude's runs use: Fuobe's MCP server follows Settings → Engine mode (cloud unless it's "open source only"). */+ engine: Engine;+ /** Said in the dialog when that isn't the composer's engine. */+ engineNote?: string;+ /** How each episode reaches faceless_episode (8 scenes a call): more than one part means separate videos. */+ parts: number;+ partSeconds: number;+}+export interface SeriesEstimate {price: SeriesPrice;demo: boolean;@@ -1128,4 +1182,6 @@ export interface SeriesEstimate {notes?: string[];/** What reading a 1-minute reference costs on this engine (shown before an upload). */analysisPerMinute: number;+ /** The reference is still being read: priced from its length and shape, and priced again once its brief is in. */+ briefPending?: boolean;}diff --git a/src/server/content-factory.ts b/src/server/content-factory.tsindex 7074d753..eb9b7584 100644--- a/src/server/content-factory.ts+++ b/src/server/content-factory.ts@@ -8,6 +8,7 @@ import {briefRequest,CF_LENGTH_VALUES,claudeMessage,+ claudePlan,episodeTopic,getPreset,MAX_BRIEF_FRAMES,@@ -28,6 +29,7 @@ import {seriesSettings,SERIES_SYSTEM,type AnimationStyleId,+ type ClaudePrompt,type ReferencePlatform,type SeriesAnalysis,type SeriesCard,@@ -113,16 +115,48 @@ function save(id: string, data: SeriesData, channelId?: string | null): void {else db().prepare("UPDATE content_series SET data_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(data), now, id);}-/** Change a series' data in place (a re-read, so a brief written meanwhile isn't lost). */-function patch(id: string, fn: (d: SeriesData) => SeriesData | void): SeriesData | null {+/** Change a series' data in place (a re-read, so a brief written or edited meanwhile isn't lost). */+function patch(id: string, fn: (d: SeriesData) => SeriesData | void, channelId?: string | null): SeriesData | null {const r = seriesRow(id);if (!r) return null;const d = dataOf(r);const next = fn(d) ?? d;- save(id, next);+ save(id, next, channelId);return next;}+declare global {+ var __fuobeContentRuns: Set<string> | undefined;+}+/** Series a "Generate here" or "Next episode" is planning or starting right now (this process). */+const running = () => (globalThis.__fuobeContentRuns ??= new Set<string>());++/**+ * One run at a time per series, claimed before anything awaits: planning asks the LLM for up to 25 s, and a+ * second click (or Enter) meanwhile would otherwise make a second channel and bill every episode twice.+ */+function claim(id: string, busy: string): () => void {+ if (running().has(id)) throw new FacelessError(busy, 409);+ running().add(id);+ return () => void running().delete(id);+}++/** Drafts are kept this long (the composer's clip across reloads); "Generate here" makes them series. */+const DRAFT_MS = 3 * 24 * 60 * 60 * 1000;++/** Old drafts that never ran, and series whose channel was deleted in Faceless Studio (their episodes went with it). */+function pruneSeries(): void {+ const drafts = db().prepare("SELECT * FROM content_series WHERE channel_id IS NULL AND updated_at < ?").all(Date.now() - DRAFT_MS) as SeriesRow[];+ const orphans = db()+ .prepare("SELECT s.* FROM content_series s LEFT JOIN faceless_channels c ON c.id = s.channel_id WHERE s.channel_id IS NOT NULL AND c.id IS NULL")+ .all() as SeriesRow[];+ for (const r of [...drafts, ...orphans]) {+ if (running().has(r.id)) continue;+ for (const g of Object.values(dataOf(r).analysis?.steps ?? {})) void cancelGeneration(g).catch(() => {});+ db().prepare("DELETE FROM content_series WHERE id = ?").run(r.id);+ }+}+// ---------------------------------------------------------------------------// The reference: an upload, a link (fetched through the SSRF-safe fetchRemote), or a preset@@ -145,14 +179,37 @@ async function saveClip(data: Buffer, contentType: string, name: string): Promisreturn { url, seconds: round1(facts.seconds), width: facts.width, height: facts.height, fps: round1(facts.fps) };}+/** What a fetched clip really is (its bytes over the server's word): MP4, MOV or WebM, with a file name to match. */+export function clipType(data: Buffer, said = ""): { contentType: string; name: string } {+ const head = data.subarray(0, 64);+ if (head.length >= 4 && head.readUInt32BE(0) === 0x1a45dfa3) return { contentType: "video/webm", name: "reference.webm" };+ if (head.length >= 12 && head.toString("latin1", 4, 8) === "ftyp" && head.toString("latin1", 8, 12) === "qt ") return { contentType: "video/quicktime", name: "reference.mov" };+ if (head.length >= 8 && head.toString("latin1", 4, 8) === "ftyp") return { contentType: "video/mp4", name: "reference.mp4" };+ if (said === "video/webm") return { contentType: said, name: "reference.webm" };+ if (said === "video/quicktime") return { contentType: said, name: "reference.mov" };+ return { contentType: "video/mp4", name: "reference.mp4" };+}+/** A video behind a link, or null when the answer isn't one. */-async function fetchClip(url: string): Promise<Buffer | null> {+async function fetchClip(url: string): Promise<{ data: Buffer; contentType: string; name: string } | null> {const res = await fetchRemote(url, { maxBytes: MAX_CLIP_BYTES, timeoutMs: 90_000 });const type = res.contentType?.split(";")[0].trim().toLowerCase() ?? "";- if (VIDEO_TYPE.test(type) || (type === "application/octet-stream" && clipFacts(res.data).seconds)) return res.data;+ if (VIDEO_TYPE.test(type) || (type === "application/octet-stream" && clipFacts(res.data).seconds)) return { data: res.data, ...clipType(res.data, type) };return null;}+/** The file name in a link's path, as a title ("my%20clip.mp4" → "my clip.mp4"); a malformed escape is kept as written. */+export function linkTitle(url: string): string | undefined {+ const raw = new URL(url).pathname.split("/").pop() ?? "";+ let name = raw;+ try {+ name = decodeURIComponent(raw);+ } catch {+ // "%E0%A4%A" isn't UTF-8: the raw name still says which clip it was.+ }+ return name.slice(0, 120) || undefined;+}+const FETCH_FAILED = "Fuobe couldn't fetch that link. Check it opens in a private window, or upload the clip instead.";/** A pasted link → the clip saved here, with the page's title and picture (fetched only through fetchRemote). */@@ -165,18 +222,22 @@ async function readLink(raw: string): Promise<SeriesReference> {const ref: SeriesReference = { kind: "link", link: url, platform };try {if (platform === "direct") {+ const title = linkTitle(url);const clip = await fetchClip(url);if (!clip) throw new NeedsUpload(noMediaMessage(platform));- return { ...ref, ...(await saveClip(clip, "video/mp4", "reference.mp4")), title: decodeURIComponent(new URL(url).pathname.split("/").pop() ?? "").slice(0, 120) || undefined };+ return { ...ref, ...(await saveClip(clip.data, clip.contentType, clip.name)), ...(title && { title }) };}const page = await fetchRemote(url, { maxBytes: 3 * 1024 * 1024, timeoutMs: 15_000 });const type = page.contentType?.split(";")[0].trim().toLowerCase() ?? "";- if (VIDEO_TYPE.test(type)) return { ...ref, ...(await saveClip(page.data, type, "reference.mp4")) };+ if (VIDEO_TYPE.test(type)) {+ const t = clipType(page.data, type);+ return { ...ref, ...(await saveClip(page.data, t.contentType, t.name)) };+ }const media = pageMedia(page.data.toString("utf8"), page.url);if (!media.video) throw new NeedsUpload(noMediaMessage(platform));const clip = await fetchClip(media.video);if (!clip) throw new NeedsUpload(noMediaMessage(platform));- const saved = await saveClip(clip, "video/mp4", "reference.mp4");+ const saved = await saveClip(clip.data, clip.contentType, clip.name);let thumbnail: string | undefined;if (media.image) {try {@@ -261,7 +322,8 @@ function startSteps(ref: SeriesReference, engine: Engine): { steps: SeriesAnalysif (engine === "open") {run("brief", request(ref, "brief", { modelId: "oss-reference-brief", op: "write", inputs: { video: ref.url }, params: { duration: Math.min(OPEN_REFERENCE_SECONDS, ref.seconds ?? OPEN_REFERENCE_SECONDS) } }));} else {- run("frames", request(ref, "frames", { modelId: "extract-frames", op: "extract-frames", inputs: { video: ref.url }, params: { frameInterval: frameInterval(ref.seconds, ref.fps) } }));+ // JPEG, not fal's default PNG: a full-HD PNG frame can weigh 3 MB, and Claude takes 32 MB a request.+ run("frames", request(ref, "frames", { modelId: "extract-frames", op: "extract-frames", inputs: { video: ref.url }, params: { frameInterval: frameInterval(ref.seconds, ref.fps), extra: { output_format: "jpg", quality: 80 } } }));run("transcript", request(ref, "transcript", { modelId: "scribe-v2", op: "transcribe", inputs: { video: ref.url }, params: { ...(ref.seconds && { duration: ref.seconds, sourceDuration: ref.seconds }) } }));}return { steps, costUsd: engine === "open" ? 0 : Math.round(cost * 1000) / 1000, demo, ...(errors.length && !Object.keys(steps).length && { error: errors[0] }) };@@ -297,6 +359,22 @@ export function spread<T>(list: T[], n: number): T[] {const IMAGE_TYPE = /^image\/(jpeg|png|gif|webp)$/;+/** Claude takes images of up to 5 MB each (as base64, 4/3 of the file) in a request of up to 32 MB. */+export const MAX_FRAME_BYTES = 3_750_000;+/** All the frames of one request together, as files: about 20 MB as base64, well inside the request limit. */+export const FRAME_BUDGET_BYTES = 15_000_000;++/** The frames that fit the request: none over the per-image limit, then fewer (still spread over the clip) until they fit the budget. */+export function fitFrames<T extends { data: Buffer }>(frames: T[], budget = FRAME_BUDGET_BYTES, each = MAX_FRAME_BYTES): T[] {+ const ok = frames.filter((f) => f.data.length <= each);+ const total = (list: T[]) => list.reduce((n, f) => n + f.data.length, 0);+ for (let n = ok.length; n > 0; n--) {+ const picked = spread(ok, n);+ if (total(picked) <= budget) return picked;+ }+ return [];+}+async function framesOf(g: Generation | null): Promise<LlmImage[]> {if (g?.status !== "succeeded") return [];const outs = g.outputs.filter((o) => o.kind === "image" && !o.meta?.demo);@@ -308,12 +386,12 @@ async function framesOf(g: Generation | null): Promise<LlmImage[]> {for (const o of picked) {try {const f = await readRef(o.url);- if (IMAGE_TYPE.test(f.contentType) && f.data.length <= 4.5 * 1024 * 1024) images.push({ data: f.data, contentType: f.contentType });+ if (IMAGE_TYPE.test(f.contentType)) images.push({ data: f.data, contentType: f.contentType });} catch {// A frame that can't be read is left out.}}- return images;+ return fitFrames(images);}async function writeBrief(id: string): Promise<void> {@@ -424,6 +502,7 @@ function toView(r: SeriesRow, d: SeriesData): SeriesView {settings: d.settings,plan: d.plan,channel,+ made: !!r.channel_id,episodes: channel ? inOrder(listEpisodes({ channelId: channel.id, limit: 200 }), d.episodeIds ?? []) : [],createdAt: r.created_at,updatedAt: r.updated_at,@@ -438,6 +517,7 @@ export function seriesView(id: string): SeriesView {/** A new series around a reference (reading starts straight away), a preset (its brief is ready), or nothing yet. */export async function createSeries(input: { reference: ReferenceInput | null; engine: Engine; prompt?: string }): Promise<SeriesView> {checkEngine(input.engine);+ pruneSeries();const reference = input.reference ? await resolveReference(input.reference) : null;const id = nanoid(10);const now = Date.now();@@ -495,8 +575,11 @@ export function updateSeries(id: string, p: { brief?: StyleBrief; name?: stringreturn seriesView(id);}-export async function deleteSeries(id: string): Promise<void> {+/** Deletes a series with its channel; `draftOnly` (the composer letting go of a clip) leaves a made series alone. */+export async function deleteSeries(id: string, o: { draftOnly?: boolean } = {}): Promise<void> {const r = mustRow(id);+ if (running().has(id)) throw new FacelessError("Its episodes are being planned — delete it once they've started", 409);+ if (o.draftOnly && r.channel_id) return;const d = dataOf(r);for (const g of Object.values(d.analysis?.steps ?? {})) void cancelGeneration(g).catch(() => {});if (r.channel_id && getChannel(r.channel_id)) await deleteChannel(r.channel_id);@@ -592,11 +675,16 @@ export function estimateSeries(input: SeriesInput & { seriesId?: string; presetIconst s = input.settings;const perMinute = analysisPerMinute(s.engine);let brief: StyleBrief;+ let pending = false;try {brief = briefFor(input);} catch {- // No reference yet: price the default look, so the composer always shows a price.- brief = getPreset("what-if")!.brief;+ const row = input.seriesId ? seriesRow(input.seriesId) : undefined;+ const d = row ? dataOf(row) : null;+ pending = d?.analysis?.status === "reading";+ // Still reading: what the clip's length and shape already say (the price comes again with the brief).+ // No reference yet: the default look, so the composer always shows a price.+ brief = pending && d?.reference ? offlineBrief({ seconds: d.reference.seconds, width: d.reference.width, height: d.reference.height }) : getPreset("what-if")!.brief;}const settings = episodeSettings(input, brief);const est = estimateEpisode({ kind: "faceless", settings, genre: s.genre });@@ -608,6 +696,7 @@ export function estimateSeries(input: SeriesInput & { seriesId?: string; presetI...(est.error && { error: est.error }),...(est.notes && { notes: est.notes }),analysisPerMinute: perMinute,+ ...(pending && { briefPending: true }),};}@@ -644,7 +733,15 @@ function startEpisodes(o: { channelId: string; prompt: string; plan: SeriesEpisoexport async function generateSeries(id: string, input: SeriesInput & { review?: boolean }): Promise<SeriesView> {const r = mustRow(id);if (r.channel_id) throw new FacelessError("This series is made — add episodes from its page", 409);- const d = dataOf(r);+ const release = claim(id, "This series is being made — a moment");+ try {+ return await generateClaimed(id, input);+ } finally {+ release();+ }+}++async function generateClaimed(id: string, input: SeriesInput & { review?: boolean }): Promise<SeriesView> {checkEngine(input.settings.engine);const prompt = input.prompt.trim();if (!prompt) throw new FacelessError("Say what the video is about");@@ -675,16 +772,25 @@ export async function generateSeries(id: string, input: SeriesInput & { review?:if (e instanceof FacelessError) throw e;throw new FacelessError(COULDNT_PLAN, 500);}- // Seen as made from here on (a second click gets "This series is made").- const next = { ...d, name: plan.name, prompt, settings: { ...input.settings, episodes: count }, plan: plan.episodes };- save(id, next, channelId);+ // Seen as made from here on (a second click gets "This series is made"); a brief edited meanwhile is kept.+ patch(id, (cur) => ({ ...cur, name: plan.name, prompt, settings: { ...input.settings, episodes: count }, plan: plan.episodes }), channelId);const ids = startEpisodes({ channelId, prompt, plan: plan.episodes, earlier: [], settings, review: !!input.review, series: count > 1 });- save(id, { ...next, episodeIds: ids });+ patch(id, (cur) => ({ ...cur, episodeIds: ids }));return seriesView(id);}/** "Next episode": plan more after the ones already made, the first one following what the user says happens in it. */export async function addEpisodes(id: string, input: { count: number; next?: string; review?: boolean }): Promise<SeriesView> {+ mustRow(id);+ const release = claim(id, "Episodes are being added to this series — a moment");+ try {+ return await addClaimed(id, input);+ } finally {+ release();+ }+}++async function addClaimed(id: string, input: { count: number; next?: string; review?: boolean }): Promise<SeriesView> {const r = mustRow(id);const d = dataOf(r);const channel = r.channel_id ? getChannel(r.channel_id) : null;@@ -699,22 +805,41 @@ export async function addEpisodes(id: string, input: { count: number; next?: strthrow new FacelessError(COULDNT_PLAN, 500);});const ids = startEpisodes({ channelId: channel.id, prompt: d.prompt, plan: more.episodes, earlier: previous, settings, review: !!input.review, series: true });- save(id, { ...d, plan: [...d.plan, ...more.episodes], settings: { ...d.settings, episodes: d.plan.length + more.episodes.length }, episodeIds: [...(d.episodeIds ?? []), ...ids] });+ // Read again before writing: a brief edited while the episodes were planned is kept.+ patch(id, (cur) => {+ const plan = [...cur.plan, ...more.episodes];+ return { ...cur, plan, settings: { ...(cur.settings ?? d.settings!), episodes: plan.length }, episodeIds: [...(cur.episodeIds ?? []), ...ids] };+ });return seriesView(id);}// ---------------------------------------------------------------------------// "Generate in Claude"-export function claudePrompt(input: SeriesInput & { seriesId?: string; presetId?: string; voiceName?: string }): { message: string; bytes: number; needsToken: boolean } {+/** The engine Fuobe's MCP tools run on (src/server/mcp.ts: the cloud unless the install is open source only). */+const mcpEngine = (): Engine => (engineMode() === "open" ? "open" : "cloud");++export function claudePrompt(input: SeriesInput & { seriesId?: string; presetId?: string }): ClaudePrompt {const brief = briefFor(input);const s = input.settings;const d = input.seriesId ? dataOf(mustRow(input.seriesId)) : null;const ref = d?.reference;const reference = ref && ref.kind !== "preset" ? `${ref.title ? `“${ref.title}”` : "clip"}${ref.platform ? ` (${PLATFORM_LABEL[ref.platform as ReferencePlatform]})` : ""}` : null;- const voice = input.voice?.kind === "preset" ? input.voice.id : null;- const message = claudeMessage({ prompt: input.prompt, brief, length: s.length, episodes: s.episodes, animation: s.animation as AnimationStyleId, genre: genreInfo(s.genre), aspect: s.aspect, engine: s.engine, voice, reference });- return { message, bytes: new TextEncoder().encode(message).length, needsToken: authEnabled() };+ const engine = mcpEngine();+ const voice = engine === "cloud" && input.voice?.kind === "preset" ? input.voice.id : null;+ const voiceSample = engine === "open" && input.voice?.kind === "sample" ? input.voice.url : null;+ const animation = s.animation as AnimationStyleId;+ const message = claudeMessage({ prompt: input.prompt, brief, length: s.length, episodes: s.episodes, animation, genre: genreInfo(s.genre), aspect: s.aspect, engine, voice, voiceSample, reference });+ const plan = claudePlan({ length: s.length, brief, animation });+ const engineNote =+ s.engine === engine+ ? undefined+ : engine === "open"+ ? "Claude's runs use the open-source engine (your ComfyUI): this install is set to Open source only."+ : engineMode() === "both"+ ? "Claude's runs use the cloud engine and your paid providers, not your GPU: Fuobe's MCP server follows Settings → Engine mode, which is set to both. Set it to Open source only to run them on your ComfyUI, or use Generate here."+ : "Claude's runs use the cloud engine and your paid providers: this install is set to paid cloud APIs only.";+ return { message, bytes: new TextEncoder().encode(message).length, needsToken: authEnabled(), engine, ...(engineNote && { engineNote }), parts: plan.parts, partSeconds: plan.partSeconds };}// ---------------------------------------------------------------------------diff --git a/tests/content-factory-api.test.ts b/tests/content-factory-api.test.tsindex d0a68542..904f4f9c 100644--- a/tests/content-factory-api.test.ts+++ b/tests/content-factory-api.test.ts@@ -2,7 +2,7 @@ import fs from "node:fs";import os from "node:os";import path from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";-import type { SeriesEstimate, SeriesView } from "@/lib/catalog/content-factory";+import { offlineBrief, type SeriesEstimate, type SeriesView } from "@/lib/catalog/content-factory";// Content Factory's server (r4/content-factory): references (an upload, a link through the guard and the// SSRF-safe fetch, a preset), reading them into a brief on both engines (demo mode here), prices, "Generate@@ -101,6 +101,8 @@ describe("reading a clip into a brief", () => {const words = getGeneration(v.analysis!.steps.transcript!)!;expect(frames.request).toMatchObject({ feature: "content-factory", modelId: "extract-frames", op: "extract-frames" });expect(frames.request.params?.frameInterval).toBeGreaterThanOrEqual(1);+ // JPEG frames: fal's default PNG runs to 3 MB a full-HD frame, past what one Claude request takes.+ expect(frames.request.params?.extra).toMatchObject({ output_format: "jpg", quality: 80 });expect(words.request).toMatchObject({ modelId: "scribe-v2", op: "transcribe" });const ready = await readied(v.id);expect(ready.analysis).toMatchObject({ status: "ready", offline: true, note: expect.stringMatching(/^Demo brief/) });@@ -123,6 +125,58 @@ describe("reading a clip into a brief", () => {await readied(v.id);}, 90_000);+ it("Claude gets the frames that fit one request: none over 5 MB as base64, all within the budget, still spread over the clip", () => {+ const f = (bytes: number) => ({ data: Buffer.alloc(bytes) });+ const total = (l: { data: Buffer }[]) => l.reduce((n, x) => n + x.data.length, 0);+ // 20 noisy full-HD PNG frames (3.07 MB each, 61 MB in all) would be an 82 MB request.+ const png = Array.from({ length: 20 }, () => f(3_070_000));+ const fit = cf.fitFrames(png);+ expect(total(fit)).toBeLessThanOrEqual(cf.FRAME_BUDGET_BYTES);+ expect(fit).toHaveLength(4);+ expect(fit[0]).toBe(png[0]);+ expect(fit.at(-1)).toBe(png[19]);+ expect((cf.FRAME_BUDGET_BYTES / 3) * 4).toBeLessThan(32 * 1024 * 1024 * 0.7);+ expect(Math.ceil(cf.MAX_FRAME_BYTES / 3) * 4).toBeLessThanOrEqual(5_000_000);+ // JPEG frames all fit; one too big for Claude is left out.+ expect(cf.fitFrames(Array.from({ length: 20 }, () => f(400_000)))).toHaveLength(20);+ expect(cf.fitFrames([f(4_500_000), f(300_000)])).toHaveLength(1);+ });++ it("while the clip is read, the price comes from its length and shape, and says it comes again", async () => {+ const v: SeriesView = await (await seriesRoute.POST(json("POST", { reference: { kind: "upload", url: clip() }, engine: "cloud" }))).json();+ expect(v.analysis?.status).toBe("reading");+ const during: SeriesEstimate = await (await estimateRoute.POST(json("POST", { prompt: "x", settings, seriesId: v.id }))).json();+ expect(during.briefPending).toBe(true);+ await readied(v.id);+ const after: SeriesEstimate = await (await estimateRoute.POST(json("POST", { prompt: "x", settings, seriesId: v.id }))).json();+ expect(after.briefPending).toBeUndefined();+ expect(after.scenes).toBe(during.scenes);+ }, 90_000);++ it("a draft the composer leaves is deleted (its reading stops); a made series is never deleted as a draft", async () => {+ const v: SeriesView = await (await seriesRoute.POST(json("POST", { reference: { kind: "upload", url: clip() }, engine: "cloud" }))).json();+ const del = (id: string, draft: boolean) => oneRoute.DELETE(new Request(`http://x/api${draft ? "?draft=1" : ""}`, { method: "DELETE" }), params({ id }));+ expect((await del(v.id, true)).status).toBe(204);+ expect(() => cf.seriesView(v.id)).toThrow(/not found/);+ const made: SeriesView = await (await seriesRoute.POST(json("POST", { reference: { kind: "preset", presetId: "what-if" }, engine: "cloud" }))).json();+ await cf.generateSeries(made.id, { prompt: "What if cats ruled the world", settings: { ...settings, episodes: 1 } });+ expect((await del(made.id, true)).status).toBe(204);+ expect(view(made.id).made).toBe(true);+ expect((await del(made.id, false)).status).toBe(204);+ expect(() => cf.seriesView(made.id)).toThrow(/not found/);+ }, 90_000);++ it("knows a link's clip by its bytes, and keeps a malformed file name as written", () => {+ const head = (brand: string) => Buffer.concat([Buffer.from([0, 0, 0, 24]), Buffer.from(`ftyp${brand}`), Buffer.alloc(16)]);+ expect(cf.clipType(head("isom"), "application/octet-stream")).toEqual({ contentType: "video/mp4", name: "reference.mp4" });+ expect(cf.clipType(head("qt "), "video/mp4")).toEqual({ contentType: "video/quicktime", name: "reference.mov" });+ expect(cf.clipType(Buffer.from([0x1a, 0x45, 0xdf, 0xa3, 0x9f, 0x42, 0x86, 0x81]), "video/mp4")).toEqual({ contentType: "video/webm", name: "reference.webm" });+ expect(cf.clipType(Buffer.from("????????"), "video/webm")).toEqual({ contentType: "video/webm", name: "reference.webm" });+ expect(cf.linkTitle("https://cdn.example.com/clips/my%20clip.mp4")).toBe("my clip.mp4");+ expect(cf.linkTitle("https://cdn.example.com/clip%E0%A4%A.mp4")).toBe("clip%E0%A4%A.mp4");+ expect(cf.linkTitle("https://cdn.example.com/")).toBeUndefined();+ });+it("the frame interval asks for about a frame a second, at most 20 over the clip", () => {expect(cf.frameInterval(10, 30)).toBe(30);expect(cf.frameInterval(60, 30)).toBe(90);@@ -205,6 +259,45 @@ describe("prices, Generate here and Next episode", () => {expect((await res.json()).error).toMatch(/reference or pick a preset/);});+ it("one Generate at a time: a second one while the first plans gets 409, and only one channel is made", async () => {+ const s: SeriesView = await (await seriesRoute.POST(json("POST", { reference: { kind: "preset", presetId: "countdown" }, engine: "cloud" }))).json();+ const channels = faceless.listChannels().length;+ const input = { prompt: "Inventions that happened by accident", settings };+ const both = await Promise.allSettled([cf.generateSeries(s.id, input), cf.generateSeries(s.id, input)]);+ expect(both.map((r) => r.status).sort()).toEqual(["fulfilled", "rejected"]);+ const refused = both.find((r): r is PromiseRejectedResult => r.status === "rejected")!.reason as InstanceType<typeof faceless.FacelessError>;+ expect(refused.status).toBe(409);+ expect(faceless.listChannels().length).toBe(channels + 1);+ expect(view(s.id).episodes).toHaveLength(3);+ // Next episode twice at once: one runs, and the plan keeps every episode it made.+ const more = await Promise.allSettled([cf.addEpisodes(s.id, { count: 1 }), cf.addEpisodes(s.id, { count: 1 })]);+ expect(more.map((r) => r.status).sort()).toEqual(["fulfilled", "rejected"]);+ const v = view(s.id);+ expect(v.plan).toHaveLength(4);+ expect(v.episodes.map((e) => e.title)).toEqual(v.plan.map((p) => p.title));+ });++ it("a brief edited while episodes are planned is kept", async () => {+ const s: SeriesView = await (await seriesRoute.POST(json("POST", { reference: { kind: "preset", presetId: "tiny-worlds" }, engine: "cloud" }))).json();+ const run = cf.generateSeries(s.id, { prompt: "A day in a paper city", settings });+ cf.updateSeries(s.id, { brief: { ...s.brief!, hook: "Open inside a matchbox" } });+ const v = await run;+ expect(v.brief?.hook).toBe("Open inside a matchbox");+ expect(v.plan).toHaveLength(3);+ });++ it("a series whose channel was deleted in Faceless Studio says so, and the next new series clears it away", async () => {+ const s: SeriesView = await (await seriesRoute.POST(json("POST", { reference: { kind: "preset", presetId: "myth-retold" }, engine: "cloud" }))).json();+ const made = await cf.generateSeries(s.id, { prompt: "Prometheus steals fire", settings: { ...settings, episodes: 1 } });+ await faceless.deleteChannel(made.channel!.id);+ expect(view(s.id)).toMatchObject({ made: true, channel: null });+ expect(cf.listSeries().some((c) => c.id === s.id)).toBe(false);+ // Generating it again can't work: it says so instead of making a second channel.+ await expect(cf.generateSeries(s.id, { prompt: "x", settings })).rejects.toMatchObject({ status: 409 });+ await seriesRoute.POST(json("POST", { reference: { kind: "preset", presetId: "what-if" }, engine: "cloud" }));+ expect(() => cf.seriesView(s.id)).toThrow(/not found/);+ });+it("deletes the series with its channel", async () => {const channelId = view(series.id).channel!.id;expect((await oneRoute.DELETE(json("DELETE"), params({ id: series.id }))).status).toBe(204);@@ -226,9 +319,39 @@ describe("Generate in Claude", () => {expect((await claudeRoute.POST(json("POST", { prompt: " ", settings, seriesId: s.id }))).status).toBe(400);});+ it("writes the message for the engine Claude's runs use (Settings → Engine mode), and says when that isn't the composer's", async () => {+ const s: SeriesView = await (await seriesRoute.POST(json("POST", { reference: { kind: "preset", presetId: "dark-history" }, engine: "cloud" }))).json();+ const ask = (body: object) => claudeRoute.POST(json("POST", { prompt: "The town that vanished", settings, seriesId: s.id, ...body })).then((r) => r.json());+ // "Both": Fuobe's MCP server runs on the cloud, whatever the composer's switch says.+ const open = await ask({ settings: { ...settings, engine: "open" }, voice: { kind: "sample", url: "/api/files/me.wav" } });+ expect(open).toMatchObject({ engine: "cloud", engineNote: expect.stringMatching(/cloud engine and your paid providers/) });+ expect(open.message).not.toMatch(/open-source engine|voice_sample "/);+ expect((await ask({})).engineNote).toBeUndefined();+ // A 5-minute episode comes out as parts, and the dialog says how many.+ expect(await ask({ settings: { ...settings, length: 300 } })).toMatchObject({ parts: 4, partSeconds: 75 });+ setSetting("engineMode", "open");+ try {+ const onlyOpen = await ask({ settings: { ...settings, engine: "open" }, voice: { kind: "sample", url: "/api/files/me.wav" } });+ expect(onlyOpen.engine).toBe("open");+ expect(onlyOpen.engineNote).toBeUndefined();+ expect(onlyOpen.message).toContain('voice_sample "/api/files/me.wav"');+ } finally {+ setSetting("engineMode", "both");+ }+ });+it("edits the brief by hand", async () => {const s: SeriesView = await (await seriesRoute.POST(json("POST", { reference: { kind: "preset", presetId: "what-if" }, engine: "cloud" }))).json();const res = await oneRoute.PATCH(json("PATCH", { brief: { ...s.brief!, hook: "Start on the punchline" } }), params({ id: s.id }));expect(((await res.json()) as SeriesView).brief?.hook).toBe("Start on the punchline");});++ it("saves an edited offline brief read from a fast talker (its pace within the editor's limits)", async () => {+ const s: SeriesView = await (await seriesRoute.POST(json("POST", { reference: { kind: "preset", presetId: "what-if" }, engine: "cloud" }))).json();+ const fast = Array.from({ length: 3 }, (_, i) => ({ start: i * 2, end: i * 2 + 2, text: "one two three four five six seven eight nine ten eleven twelve" }));+ const brief = { ...offlineBrief({ cues: fast }), hook: "Straight in" };+ const res = await oneRoute.PATCH(json("PATCH", { brief }), params({ id: s.id }));+ expect(res.status).toBe(200);+ expect(((await res.json()) as SeriesView).brief?.voice.wordsPerMinute).toBe(260);+ });});diff --git a/tests/content-factory.test.ts b/tests/content-factory.test.tsindex afdfcf1d..145b8e8f 100644--- a/tests/content-factory.test.ts+++ b/tests/content-factory.test.ts@@ -8,10 +8,13 @@ import {briefLook,CF_LENGTH_VALUES,claudeMessage,+ claudePlan,defaultBrief,episodeTopic,MAX_CLAUDE_MESSAGE,+ MAX_WPM,mcpCommand,+ MIN_WPM,noMediaMessage,offlineBrief,offlineSeries,@@ -165,6 +168,18 @@ describe("offline brief", () => {expect(offlineBrief().aspect).toBe("9:16");expect(speechRate([{ start: 0, end: 1, text: "hi" }])).toBeNull();});++ it("keeps a rap's or a sped-up voice's pace within what a brief can carry (and the brief editor can save)", () => {+ const fast = Array.from({ length: 3 }, (_, i) => ({ start: i * 2, end: i * 2 + 2, text: "one two three four five six seven eight nine ten eleven twelve" }));+ expect(speechRate(fast)).toBe(360);+ expect(offlineBrief({ cues: fast }).voice).toMatchObject({ wordsPerMinute: MAX_WPM, tone: expect.stringMatching(/fast/i) });+ const slow = [+ { start: 0, end: 10, text: "one two three four five six" },+ { start: 10, end: 20, text: "seven eight nine ten eleven twelve" },+ ];+ expect(speechRate(slow)).toBe(36);+ expect(offlineBrief({ cues: slow }).voice.wordsPerMinute).toBe(MIN_WPM);+ });});describe("the reference link guard", () => {@@ -367,6 +382,29 @@ describe("Generate in Claude", () => {expect(claudeMessage({ ...base, length: 30 })).not.toContain("parts of");});+ it("says when scenes run longer than the brief's cuts, and that a long episode comes out as parts to join", () => {+ const dark = PRESETS.find((p) => p.id === "dark-history")!.brief;+ expect(claudePlan({ length: 300, brief: dark, animation: "frame-by-frame" })).toEqual({ sceneSeconds: 10, briefSceneSeconds: 7, scenes: 30, parts: 4, perPart: 8, partSeconds: 75 });+ const long = claudeMessage({ ...base, brief: dark, animation: "frame-by-frame", length: 300 });+ expect(long).toMatch(/Scenes run about 10 s here, longer than the brief's cuts \(about 5 s a shot\)/);+ expect(long).toMatch(/each episode comes out as 4 parts of about 8 scenes \(about 1:15 each\)/);+ expect(long).toMatch(/Tell me this before I approve anything[\s\S]*Join clips in Fuobe's Video tools/);+ expect(long).not.toMatch(/\n$|\n\n\n/);+ // At the brief's own pace nothing is stretched or split.+ const short = claudeMessage({ ...base, brief: dark, animation: "frame-by-frame", length: 30 });+ expect(short).not.toContain("longer than the brief's cuts");+ expect(short).not.toContain("Join clips");+ expect(claudePlan({ length: 30, brief: dark, animation: "frame-by-frame" })).toMatchObject({ sceneSeconds: 7, parts: 1 });+ });++ it("on the open engine passes the narrator's recording instead of asking for one", () => {+ const m = claudeMessage({ ...base, engine: "open", voice: "JBFqnCBsd6RMkjVDRZzb", voiceSample: "/api/files/narrator.wav" });+ expect(m).toContain('voice_sample "/api/files/narrator.wav"');+ expect(m).not.toContain('voice "JBFqnCBsd6RMkjVDRZzb"');+ expect(m).not.toMatch(/ask me for a 10–60 s voice sample/);+ expect(m).toContain(ANIMATION_STYLES[0].openCopy);+ });+it("stays within 64 KB however long the prompt is", () => {const m = claudeMessage({ ...base, prompt: "flying cars ".repeat(20_000) });expect(new TextEncoder().encode(m).length).toBeLessThanOrEqual(MAX_CLAUDE_MESSAGE);