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.

Faceless/Explainer server: channels, episodes, render pipeline, timeline changes, API

Claudec62e0583240d
diff --git a/src/app/api/explainer/link/route.ts b/src/app/api/explainer/link/route.ts
new file mode 100644
index 00000000..fad633f4
--- /dev/null
+++ b/src/app/api/explainer/link/route.ts
@@ -0,0 +1,12 @@
+import { z } from "zod";
+import { body, EngineSchema, handle, summarizeLink } from "@/server/faceless";
+
+const Ask = z.object({ url: z.string().url("Paste a full link, starting with https://").max(2000), engine: EngineSchema });
+
+/** A link source: the page is fetched (public addresses only) and summarised for the script writer. */
+export async function POST(request: Request) {
+ return handle(async () => {
+ const { url, engine } = await body(request, Ask, "Paste a link – article, page");
+ return Response.json(await summarizeLink(url, engine));
+ });
+}
diff --git a/src/app/api/explainer/route.ts b/src/app/api/explainer/route.ts
new file mode 100644
index 00000000..aad9ea88
--- /dev/null
+++ b/src/app/api/explainer/route.ts
@@ -0,0 +1,30 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { MAX_TOPIC } from "@/lib/catalog/faceless";
+import { body, createEpisode, handle, listEpisodes, SettingsSchema, SourceSchema } from "@/server/faceless";
+
+const Create = z.object({
+ prompt: z.string().max(MAX_TOPIC, "Prompt is too long (max 5000 characters)"),
+ sources: z.array(SourceSchema).max(3, "Up to 3 sources per video — remove one to add another").optional(),
+ settings: SettingsSchema,
+ /** Show the script for review before rendering (default: render straight away). */
+ review: z.boolean().optional(),
+});
+
+/** History: your explainers, newest first (`?q=` search, `?liked=1`). */
+export async function GET(request: Request) {
+ await connection();
+ return handle(() => {
+ const p = new URL(request.url).searchParams;
+ return Response.json({ items: listEpisodes({ kind: "explainer", q: p.get("q") ?? undefined, liked: p.get("liked") === "1", limit: 200 }) });
+ });
+}
+
+/** Explain something: the script is written from the prompt and sources, then rendered. */
+export async function POST(request: Request) {
+ return handle(async () => {
+ const input = await body(request, Create, "Add a prompt, or attach a file or link");
+ const episode = createEpisode({ kind: "explainer", topic: input.prompt, sources: input.sources, settings: input.settings, autoRender: !input.review });
+ return Response.json(episode, { status: 201 });
+ });
+}
diff --git a/src/app/api/faceless/channels/[id]/avatar/route.ts b/src/app/api/faceless/channels/[id]/avatar/route.ts
new file mode 100644
index 00000000..4d90b502
--- /dev/null
+++ b/src/app/api/faceless/channels/[id]/avatar/route.ts
@@ -0,0 +1,9 @@
+import { handle, makeAvatar } from "@/server/faceless";
+
+/** Draw a channel avatar in the channel's style (one picture generation; PATCH avatarUrl with it when it's done). */
+export async function POST(_req: Request, ctx: RouteContext<"/api/faceless/channels/[id]/avatar">) {
+ return handle(async () => {
+ const { id } = await ctx.params;
+ return Response.json(makeAvatar(id), { status: 201 });
+ });
+}
diff --git a/src/app/api/faceless/channels/[id]/route.ts b/src/app/api/faceless/channels/[id]/route.ts
new file mode 100644
index 00000000..f2e8deaa
--- /dev/null
+++ b/src/app/api/faceless/channels/[id]/route.ts
@@ -0,0 +1,40 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { body, deleteChannel, FacelessError, GenreSchema, getChannel, handle, listEpisodes, SettingsSchema, updateChannel } from "@/server/faceless";
+
+const Patch = z.object({
+ name: z.string().max(60).optional(),
+ idea: z.string().max(500).optional(),
+ genre: GenreSchema.optional(),
+ avatarUrl: z.string().startsWith("/api/files/").max(500).nullable().optional(),
+ reference: z.string().max(500).nullable().optional(),
+ settings: SettingsSchema.pick({ engine: true, styleId: true, styleRefs: true, voice: true, aspect: true, subtitles: true, music: true, animation: true, length: true }).partial().optional(),
+});
+
+/** The channel with its episodes. */
+export async function GET(_req: Request, ctx: RouteContext<"/api/faceless/channels/[id]">) {
+ await connection();
+ return handle(async () => {
+ const { id } = await ctx.params;
+ const channel = getChannel(id);
+ if (!channel) throw new FacelessError("Channel not found", 404);
+ return Response.json({ channel, episodes: listEpisodes({ channelId: id, limit: 200 }) });
+ });
+}
+
+export async function PATCH(request: Request, ctx: RouteContext<"/api/faceless/channels/[id]">) {
+ return handle(async () => {
+ const { id } = await ctx.params;
+ const patch = await body(request, Patch, "Those channel settings aren't valid");
+ return Response.json(await updateChannel(id, patch));
+ });
+}
+
+/** Deletes the channel and its episodes (their videos stay in the Library). */
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/faceless/channels/[id]">) {
+ return handle(async () => {
+ const { id } = await ctx.params;
+ deleteChannel(id);
+ return new Response(null, { status: 204 });
+ });
+}
diff --git a/src/app/api/faceless/channels/route.ts b/src/app/api/faceless/channels/route.ts
new file mode 100644
index 00000000..84522075
--- /dev/null
+++ b/src/app/api/faceless/channels/route.ts
@@ -0,0 +1,25 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { body, createChannel, EngineSchema, GenreSchema, handle, listChannels } from "@/server/faceless";
+
+const Create = z.object({
+ idea: z.string().trim().min(1, "Describe the channel first").max(500, "Keep the channel idea under 500 characters"),
+ genre: GenreSchema,
+ engine: EngineSchema,
+ reference: z.string().max(500).optional(),
+ name: z.string().max(60).optional(),
+});
+
+/** Your channels, newest first, with episode counts and the latest finished episode. */
+export async function GET() {
+ await connection();
+ return handle(() => Response.json({ items: listChannels() }));
+}
+
+/** Create a channel (its name is written for you when you don't give one). */
+export async function POST(request: Request) {
+ return handle(async () => {
+ const input = await body(request, Create, "Describe the channel and pick a genre");
+ return Response.json(await createChannel(input), { status: 201 });
+ });
+}
diff --git a/src/app/api/faceless/episodes/[id]/[action]/route.ts b/src/app/api/faceless/episodes/[id]/[action]/route.ts
new file mode 100644
index 00000000..faa7aee8
--- /dev/null
+++ b/src/app/api/faceless/episodes/[id]/[action]/route.ts
@@ -0,0 +1,22 @@
+import { episodeView, handle, renderEpisode, retryEpisode, rewriteEpisode, undoChange } from "@/server/faceless";
+
+const ACTIONS = {
+ /** Render the reviewed script. */
+ render: renderEpisode,
+ /** Redo the failed steps and what waited on them. */
+ retry: retryEpisode,
+ /** Write the script again. */
+ rewrite: rewriteEpisode,
+ /** Go back to the version before the last change. */
+ undo: undoChange,
+} as const;
+
+export async function POST(_req: Request, ctx: RouteContext<"/api/faceless/episodes/[id]/[action]">) {
+ return handle(async () => {
+ const { id, action } = await ctx.params;
+ const run = ACTIONS[action as keyof typeof ACTIONS];
+ if (!run) return Response.json({ error: "Not found" }, { status: 404 });
+ run(id);
+ return Response.json(episodeView(id));
+ });
+}
diff --git a/src/app/api/faceless/episodes/[id]/change/route.ts b/src/app/api/faceless/episodes/[id]/change/route.ts
new file mode 100644
index 00000000..6a9307c4
--- /dev/null
+++ b/src/app/api/faceless/episodes/[id]/change/route.ts
@@ -0,0 +1,16 @@
+import { applyChange, body, ChangeSchema, episodeView, handle, previewChange } from "@/server/faceless";
+
+/**
+ * The timeline editor: `{ blocks, part, instruction | narration }` returns what the change re-runs and its
+ * price; with `apply: true` it re-runs those steps (that block's picture or clips, the joins after it,
+ * the mix and the subtitles, or the narration).
+ */
+export async function POST(request: Request, ctx: RouteContext<"/api/faceless/episodes/[id]/change">) {
+ return handle(async () => {
+ const { id } = await ctx.params;
+ const c = await body(request, ChangeSchema, "Pick a scene and describe the change");
+ if (!c.apply) return Response.json(previewChange(id, c));
+ applyChange(id, c);
+ return Response.json(episodeView(id), { status: 201 });
+ });
+}
diff --git a/src/app/api/faceless/episodes/[id]/route.ts b/src/app/api/faceless/episodes/[id]/route.ts
new file mode 100644
index 00000000..4950e09e
--- /dev/null
+++ b/src/app/api/faceless/episodes/[id]/route.ts
@@ -0,0 +1,38 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { BlockSchema, body, deleteEpisode, episodeView, handle, SettingsSchema, updateEpisode } from "@/server/faceless";
+
+const Patch = z.object({
+ title: z.string().max(120).optional(),
+ favorite: z.boolean().optional(),
+ blocks: z.array(BlockSchema).min(1, "Keep at least one scene").max(80, "Up to 80 scenes").optional(),
+ settings: SettingsSchema.partial().optional(),
+});
+
+/** The episode with every step's generation, its progress, spend and estimate. */
+export async function GET(_req: Request, ctx: RouteContext<"/api/faceless/episodes/[id]">) {
+ await connection();
+ return handle(async () => {
+ const { id } = await ctx.params;
+ return Response.json(episodeView(id));
+ });
+}
+
+/** Rename, like, or (before rendering) edit the script and settings. */
+export async function PATCH(request: Request, ctx: RouteContext<"/api/faceless/episodes/[id]">) {
+ return handle(async () => {
+ const { id } = await ctx.params;
+ const patch = await body(request, Patch, "Those changes aren't valid");
+ updateEpisode(id, patch);
+ return Response.json(episodeView(id));
+ });
+}
+
+/** Deletes the episode (its videos stay in the Library). */
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/faceless/episodes/[id]">) {
+ return handle(async () => {
+ const { id } = await ctx.params;
+ deleteEpisode(id);
+ return new Response(null, { status: 204 });
+ });
+}
diff --git a/src/app/api/faceless/episodes/route.ts b/src/app/api/faceless/episodes/route.ts
new file mode 100644
index 00000000..8764aab9
--- /dev/null
+++ b/src/app/api/faceless/episodes/route.ts
@@ -0,0 +1,29 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { FACELESS_LENGTHS, MAX_SCRIPT, MAX_TOPIC } from "@/lib/catalog/faceless";
+import { body, createEpisode, FacelessError, handle, listEpisodes, SettingsSchema } from "@/server/faceless";
+
+const Create = z.object({
+ channelId: z.string().max(40),
+ topic: z.string().max(MAX_TOPIC, "Keep the topic under 5,000 characters"),
+ script: z.string().max(MAX_SCRIPT, "That script is too long to narrate. Shorten it and try again.").optional(),
+ settings: SettingsSchema,
+});
+
+/** Episodes, newest first (`?channel=` for one channel). */
+export async function GET(request: Request) {
+ await connection();
+ return handle(() => {
+ const p = new URL(request.url).searchParams;
+ return Response.json({ items: listEpisodes({ channelId: p.get("channel") ?? undefined, kind: "faceless", q: p.get("q") ?? undefined, limit: 200 }) });
+ });
+}
+
+/** A new episode: the script is written (or your pasted script split into scenes) in the background, then it waits for your review. */
+export async function POST(request: Request) {
+ return handle(async () => {
+ const input = await body(request, Create, "Pick a topic and the video settings");
+ if (!FACELESS_LENGTHS.includes(input.settings.length)) throw new FacelessError("Choose one of the offered video lengths");
+ return Response.json(createEpisode({ kind: "faceless", channelId: input.channelId, topic: input.topic, script: input.script, settings: input.settings }), { status: 201 });
+ });
+}
diff --git a/src/app/api/faceless/estimate/route.ts b/src/app/api/faceless/estimate/route.ts
new file mode 100644
index 00000000..d69688fa
--- /dev/null
+++ b/src/app/api/faceless/estimate/route.ts
@@ -0,0 +1,14 @@
+import { z } from "zod";
+import { BlockSchema, body, estimateEpisode, GenreSchema, handle, SettingsSchema } from "@/server/faceless";
+
+const Ask = z.object({
+ kind: z.enum(["faceless", "explainer"]),
+ settings: SettingsSchema,
+ blocks: z.array(BlockSchema).max(80).optional(),
+ genre: GenreSchema.optional(),
+});
+
+/** What an episode would cost (by part), whether it runs as a demo, and what's in the way. */
+export async function POST(request: Request) {
+ return handle(async () => Response.json(estimateEpisode(await body(request, Ask, "Those settings aren't valid"))));
+}
diff --git a/src/app/api/faceless/topics/route.ts b/src/app/api/faceless/topics/route.ts
new file mode 100644
index 00000000..0111dd4c
--- /dev/null
+++ b/src/app/api/faceless/topics/route.ts
@@ -0,0 +1,23 @@
+import { z } from "zod";
+import { body, EngineSchema, GenreSchema, getChannel, handle, suggestTopics } from "@/server/faceless";
+
+const Ask = z.object({
+ idea: z.string().trim().min(1).max(500).optional(),
+ channelId: z.string().max(40).optional(),
+ genre: GenreSchema.optional(),
+ engine: EngineSchema,
+ avoid: z.array(z.string().max(200)).max(30).optional(),
+ round: z.number().int().min(0).max(50).optional(),
+});
+
+/** 4–6 episode topics for a channel (the install's LLM, or templates offline). */
+export async function POST(request: Request) {
+ return handle(async () => {
+ const q = await body(request, Ask, "Describe the channel first");
+ const channel = q.channelId ? getChannel(q.channelId) : null;
+ const idea = q.idea ?? channel?.idea;
+ if (!idea) return Response.json({ error: "Describe the channel first" }, { status: 400 });
+ const reference = channel?.reference ? [channel.reference.title, channel.reference.author].filter(Boolean).join(" by ") || undefined : undefined;
+ return Response.json(await suggestTopics({ idea, genre: q.genre ?? channel?.genre ?? "education", engine: q.engine, avoid: q.avoid, round: q.round, reference }));
+ });
+}
diff --git a/src/app/api/faceless/voices/preview/route.ts b/src/app/api/faceless/voices/preview/route.ts
new file mode 100644
index 00000000..e1a101e2
--- /dev/null
+++ b/src/app/api/faceless/voices/preview/route.ts
@@ -0,0 +1,12 @@
+import { z } from "zod";
+import { body, handle, voicePreview } from "@/server/faceless";
+
+const Ask = z.object({ id: z.string().min(1).max(80) });
+
+/** A short sample of a premade narrator voice: one speech generation, reused once it exists. */
+export async function POST(request: Request) {
+ return handle(async () => {
+ const { id } = await body(request, Ask, "Pick a voice");
+ return Response.json(voicePreview({ kind: "preset", id }));
+ });
+}
diff --git a/src/lib/catalog/faceless.ts b/src/lib/catalog/faceless.ts
index bb655246..c23ee4ae 100644
--- a/src/lib/catalog/faceless.ts
+++ b/src/lib/catalog/faceless.ts
@@ -1,5 +1,5 @@
import { estimateCost } from "./plan";
-import type { ChainSlot, Engine, GenerationRequest, ModelDef } from "./types";
+import type { ChainSlot, Engine, Generation, GenerationRequest, ModelDef } from "./types";
/*
* Faceless Studio and the Explainer: the data and the pure planning shared by the browser (wizard,
@@ -366,6 +366,8 @@ export interface EpisodeSettings {
resolution?: string;
/** Reference images that show the subject (Explainer sources). */
sourceImages?: string[];
+ /** Explainer "Auto": the script decides the length. */
+ auto?: boolean;
}
export interface ScriptBlock {
@@ -1189,6 +1191,7 @@ export function subjectOf(idea: string): string {
.trim()
.replace(/[.!?]+$/, "")
.replace(/^(a |an |my )?(youtube )?channel\s+(about|with|on|for|of)\s+/i, "")
+ .replace(/^(please\s+)?(explain|describe|tell (me|us) about|show (me|us)|teach (me|us)( about)?)\s+(to (me|us|kids)\s+)?/i, "")
.replace(/^(about|on)\s+/i, "")
.trim();
return s || "your subject";
@@ -1346,12 +1349,12 @@ export function parseScript(text: string): ParsedScript | null {
const BEATS: Record<FacelessGenre, { narration: string; visual: string }[]> = {
education: [
- { narration: "Have you ever wondered how {s} actually works? In the next few minutes, it will all make sense.", visual: "An intriguing establishing picture of {s}, seen from a surprising angle" },
- { narration: "Let's start with the basics: what {s} is, and why it matters more than you might think.", visual: "A simple diagram-like picture introducing {s}" },
- { narration: "Here is the first key idea. Once you see it, the rest of {s} starts to click.", visual: "A close-up that highlights the first key part of {s}" },
+ { narration: "Today's question: {s}. In the next few minutes, it will all make sense.", visual: "An intriguing establishing picture about {s}, seen from a surprising angle" },
+ { narration: "Let's start with the basics, and why this matters more than you might think.", visual: "A simple diagram-like picture introducing {s}" },
+ { narration: "Here is the first key idea. Once you see it, the rest starts to click.", visual: "A close-up that highlights the first key part of {s}" },
{ narration: "Now add the second piece. This is where most people get confused, so let's slow down.", visual: "Two parts of {s} side by side, showing how they connect" },
- { narration: "Put together, these pieces explain something you see every day.", visual: "An everyday scene where {s} is quietly at work" },
- { narration: "And here's a surprising fact about {s} that even experts find fascinating.", visual: "A dramatic, surprising view related to {s}" },
+ { narration: "Put together, these pieces explain something you see every day.", visual: "An everyday scene connected to {s}" },
+ { narration: "So that's the answer, in a nutshell. Now you know more than most people do.", visual: "A satisfying wide picture that sums up {s}" },
],
history: [
{ narration: "This is the story of {s}, and it begins long before most people think.", visual: "A sweeping historical landscape where the story of {s} begins" },
@@ -1446,3 +1449,140 @@ export function defaultSettings(engine: Engine, genre: GenreInfo, o: { explainer
/** A short line the narrator reads for a voice preview. */
export const previewLine = (name: string) => `Hi, I'm ${name}. I'll be narrating your episode — here's how I sound.`;
+
+// ---------------------------------------------------------------------------
+// What the API sends (shared by the server module and the client hooks)
+
+export interface ChannelReference {
+ url: string;
+ kind: "channel" | "video" | "playlist";
+ title?: string;
+ author?: string;
+ /** The link's thumbnail, saved as an upload (offered as a style reference). */
+ thumbnail?: string;
+}
+
+/** Saved on the channel so every episode looks and sounds the same. */
+export type ChannelSettings = Pick<EpisodeSettings, "engine" | "styleId" | "styleRefs" | "voice" | "aspect" | "subtitles" | "music" | "animation" | "length">;
+
+export interface FacelessChannel {
+ id: string;
+ name: string;
+ idea: string;
+ genre: FacelessGenre;
+ avatarUrl: string | null;
+ reference: ChannelReference | null;
+ settings: ChannelSettings;
+ createdAt: number;
+ updatedAt: number;
+ /** Lists: how many episodes, and the newest finished one's poster. */
+ episodes?: number;
+ cover?: Generation | null;
+}
+
+export type EpisodeStatus = "writing" | "write-failed" | "review" | "rendering" | "done" | "failed";
+
+export interface EpisodeScript {
+ title?: string;
+ blocks: ScriptBlock[];
+ /** Written without an LLM (a demo-quality draft), and why. */
+ offline?: boolean;
+ note?: string;
+ source: "ai" | "pasted";
+}
+
+/** A source the Explainer read: an image (a reference for the pictures), a document's text, or a summarised link. */
+export type ExplainerSource = { kind: "image"; url: string; name?: string } | { kind: "text"; name: string; text: string } | { kind: "link"; url: string; title?: string; text: string };
+
+export interface EpisodeChange {
+ at: number;
+ blocks: string[];
+ part: ChangePart;
+ instruction: string;
+ costUsd: number | null;
+}
+
+export type StillEdits = Record<string, { source: string; instruction: string }>;
+
+export interface EpisodePlan {
+ batchId: string;
+ /** Step key → the generation that made it (the current version). */
+ ids: Record<string, string>;
+ /** Picture edits the current version was made with. */
+ stillEdits?: StillEdits;
+ /** The version before the last change (Undo). */
+ previous?: { ids: Record<string, string>; blocks: ScriptBlock[]; stillEdits?: StillEdits };
+ /** The last finished film, shown while a change renders. */
+ lastFinal?: string;
+ changes: EpisodeChange[];
+}
+
+export interface FacelessEpisode {
+ id: string;
+ channelId: string | null;
+ kind: "faceless" | "explainer";
+ title: string;
+ topic: string;
+ status: EpisodeStatus;
+ error: string | null;
+ settings: EpisodeSettings;
+ script: EpisodeScript;
+ plan: EpisodePlan | null;
+ sources: ExplainerSource[];
+ favorite: boolean;
+ createdAt: number;
+ updatedAt: number;
+}
+
+export interface StepView {
+ key: string;
+ part: StepPart;
+ block?: number;
+ label: string;
+ generation: Generation | null;
+}
+
+export interface EpisodeView {
+ episode: FacelessEpisode;
+ channel: FacelessChannel | null;
+ steps: StepView[];
+ final: Generation | null;
+ /** The previous finished film while a change renders. */
+ previousFinal: Generation | null;
+ /** 0–1 over every step. */
+ progress: number;
+ /** What the current version cost so far, and the render's estimate. */
+ spentUsd: number;
+ estimate: CostBreakdown | null;
+}
+
+/** One item in the Explainer's history or a channel's episode list. */
+export interface EpisodeCard {
+ id: string;
+ channelId: string | null;
+ kind: "faceless" | "explainer";
+ title: string;
+ status: EpisodeStatus;
+ styleId: string;
+ aspect: EpisodeAspect;
+ seconds: number;
+ favorite: boolean;
+ poster: Generation | null;
+ progress: number;
+ createdAt: number;
+}
+
+export interface EstimateResult {
+ estimate: CostBreakdown;
+ demo: boolean;
+ seconds: number;
+ blocks: number;
+ error?: string;
+}
+
+export interface ChangePreview {
+ rerun: string[];
+ labels: string[];
+ costUsd: number | null;
+ demo: boolean;
+}
diff --git a/src/server/db.ts b/src/server/db.ts
index 73575c8d..796053f9 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -175,6 +175,37 @@ const MIGRATIONS: string[] = [
edited_at INTEGER
);
CREATE INDEX IF NOT EXISTS canvases_updated ON canvases(updated_at DESC);`,
+ // Faceless Studio channels (genre, saved style / voice / aspect / subtitles) and episodes (Faceless and Explainer: script, render plan).
+ `CREATE TABLE IF NOT EXISTS faceless_channels (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ idea TEXT NOT NULL,
+ genre TEXT NOT NULL,
+ avatar_url TEXT,
+ reference_json TEXT,
+ settings_json TEXT NOT NULL,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS faceless_channels_updated ON faceless_channels(updated_at DESC);
+ CREATE TABLE IF NOT EXISTS faceless_episodes (
+ id TEXT PRIMARY KEY,
+ channel_id TEXT,
+ kind TEXT NOT NULL,
+ title TEXT NOT NULL,
+ topic TEXT NOT NULL,
+ status TEXT NOT NULL,
+ error TEXT,
+ settings_json TEXT NOT NULL,
+ script_json TEXT NOT NULL,
+ plan_json TEXT,
+ sources_json TEXT,
+ favorite INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS faceless_episodes_channel ON faceless_episodes(channel_id, created_at DESC);
+ CREATE INDEX IF NOT EXISTS faceless_episodes_kind ON faceless_episodes(kind, created_at DESC);`,
];
declare global {
diff --git a/src/server/faceless.ts b/src/server/faceless.ts
new file mode 100644
index 00000000..46730304
--- /dev/null
+++ b/src/server/faceless.ts
@@ -0,0 +1,1079 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { z } from "zod";
+import { getModel } from "@/lib/catalog";
+import {
+ AUTO_SECONDS,
+ blockCount,
+ buildEpisodeGraph,
+ changedKeys,
+ channelName,
+ defaultSettings,
+ ENGINE_MODELS,
+ estimateGraph,
+ finalKey,
+ genreInfo,
+ getStyle,
+ MAX_SCRIPT,
+ narrationText,
+ normalizeBlocks,
+ OFFLINE_NOTE,
+ offlineScript,
+ offlineTopics,
+ parseScript,
+ parseTopics,
+ parseVisuals,
+ placeholderBlocks,
+ planRerun,
+ planRetry,
+ previewLine,
+ scriptBrief,
+ scriptSystem,
+ splitScript,
+ topicsBrief,
+ topicsSystem,
+ totalSeconds,
+ visualsBrief,
+ visualsSystem,
+ wordsFor,
+ youtubeKind,
+ YOUTUBE_ERROR,
+ type ChangePart,
+ type ChangePreview,
+ type ChannelReference,
+ type ChannelSettings,
+ type EpisodeCard,
+ type EpisodePlan,
+ type EpisodeScript,
+ type EpisodeSettings,
+ type EpisodeStatus,
+ type EpisodeView,
+ type EstimateResult,
+ type ExplainerSource,
+ type FacelessChannel,
+ type FacelessEpisode,
+ type FacelessGenre,
+ type GraphInput,
+ type GraphStep,
+ type NarratorVoice,
+ type ScriptBlock,
+ type StillEdits,
+ type TopicIdea,
+} from "@/lib/catalog/faceless";
+import { routesFor } from "@/lib/catalog/plan";
+import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
+import { createPipeline } from "./chains";
+import { db } from "./db";
+import { listElements } from "./elements";
+import { cancelGeneration, chooseRoute, createGenerations, getGeneration, previewChained } from "./generations";
+import { provider } from "./providers";
+import { llmBackends, probeOllama } from "./providers/llm";
+import { fetchRemote } from "./remote-fetch";
+import { engineMode, getSetting } from "./settings";
+import { fileUrl, saveFile } from "./storage";
+
+/**
+ * Faceless Studio and the Explainer on the server: channels (genre, saved style, narrator, aspect,
+ * subtitles), episodes (topic → script → review → render), the render itself as chained generations
+ * (createPipeline over the graph from src/lib/catalog/faceless.ts), retries, block changes from the
+ * timeline editor (re-run that block's steps and everything after them) with Undo, voice previews,
+ * topic suggestions, link summaries and estimates.
+ *
+ * Writing a script runs in this process (the install's LLM through the "llm" provider, or the offline
+ * writer); a restart while it writes leaves the episode "write-failed" with a Try again. Rendering lives
+ * in the generations table, so it survives restarts like any chained job.
+ */
+
+export class FacelessError extends Error {
+ constructor(
+ message: string,
+ readonly status = 400,
+ ) {
+ super(message);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Rows
+
+interface ChannelRow {
+ id: string;
+ name: string;
+ idea: string;
+ genre: string;
+ avatar_url: string | null;
+ reference_json: string | null;
+ settings_json: string;
+ created_at: number;
+ updated_at: number;
+}
+
+interface EpisodeRow {
+ id: string;
+ channel_id: string | null;
+ kind: "faceless" | "explainer";
+ title: string;
+ topic: string;
+ status: EpisodeStatus;
+ error: string | null;
+ settings_json: string;
+ script_json: string;
+ plan_json: string | null;
+ sources_json: string | null;
+ favorite: number;
+ created_at: number;
+ updated_at: number;
+}
+
+const toChannel = (r: ChannelRow): FacelessChannel => ({
+ id: r.id,
+ name: r.name,
+ idea: r.idea,
+ genre: genreInfo(r.genre).id,
+ avatarUrl: r.avatar_url,
+ reference: r.reference_json ? (JSON.parse(r.reference_json) as ChannelReference) : null,
+ settings: JSON.parse(r.settings_json) as ChannelSettings,
+ createdAt: r.created_at,
+ updatedAt: r.updated_at,
+});
+
+const toEpisode = (r: EpisodeRow): FacelessEpisode => ({
+ id: r.id,
+ channelId: r.channel_id,
+ kind: r.kind,
+ title: r.title,
+ topic: r.topic,
+ status: r.status,
+ error: r.error,
+ settings: JSON.parse(r.settings_json) as EpisodeSettings,
+ script: JSON.parse(r.script_json) as EpisodeScript,
+ plan: r.plan_json ? (JSON.parse(r.plan_json) as EpisodePlan) : null,
+ sources: r.sources_json ? (JSON.parse(r.sources_json) as ExplainerSource[]) : [],
+ favorite: !!r.favorite,
+ createdAt: r.created_at,
+ updatedAt: r.updated_at,
+});
+
+function updateEpisodeRow(id: string, fields: Partial<EpisodeRow>): void {
+ const keys = Object.keys(fields);
+ if (!keys.length) return;
+ db()
+ .prepare(`UPDATE faceless_episodes SET ${keys.map((k) => `${k} = @${k}`).join(", ")}, updated_at = @__now WHERE id = @__id`)
+ .run({ ...fields, __now: Date.now(), __id: id });
+}
+
+const episodeRow = (id: string) => db().prepare("SELECT * FROM faceless_episodes WHERE id = ?").get(id) as EpisodeRow | undefined;
+
+function mustEpisode(id: string): FacelessEpisode {
+ const r = episodeRow(id);
+ if (!r) throw new FacelessError("Episode not found", 404);
+ return toEpisode(r);
+}
+
+// ---------------------------------------------------------------------------
+// The LLM (the install's own: Claude or Ollama for the cloud engine, Ollama only for the open one)
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+/** One answer from the engine's text model, or null (no LLM, AI helper off, demo mode on, or it failed: `onError` hears why). */
+export async function askLlm(engine: Engine, system: string, user: string, onError?: (msg: string) => void): Promise<string | null> {
+ if (getSetting("demoMode") === "on") return null;
+ const model = getModel(ENGINE_MODELS[engine].write);
+ const route = model?.routes.find((r) => r.op === "write");
+ if (!model || !route) return null;
+ await probeOllama();
+ if (!llmBackends(route).length) return null;
+ const llm = provider("llm");
+ try {
+ const { externalId } = await llm.submit({ generationId: `faceless_${nanoid(6)}`, model, route, input: { prompt: user, extra: { system } } });
+ const ctx = { externalId, meta: {}, route, model, createdAt: Date.now() };
+ const deadline = Date.now() + 8 * 60_000;
+ while (Date.now() < deadline) {
+ await sleep(350);
+ const r = await llm.poll(ctx);
+ if (r.state === "succeeded") return r.outputs[0]?.text?.trim() || null;
+ if (r.state === "failed") {
+ onError?.(r.error);
+ return null;
+ }
+ }
+ await llm.cancel?.(ctx);
+ onError?.("The LLM took too long");
+ } catch (e) {
+ onError?.((e as Error).message);
+ }
+ return null;
+}
+
+// ---------------------------------------------------------------------------
+// Channels
+
+const ChannelDefaults = (engine: Engine, genre: FacelessGenre): ChannelSettings => {
+ const s = defaultSettings(engine, genreInfo(genre));
+ return { engine, styleId: s.styleId, styleRefs: [], voice: s.voice, aspect: s.aspect, subtitles: s.subtitles, music: s.music, animation: s.animation, length: s.length };
+};
+
+export function listChannels(): FacelessChannel[] {
+ const rows = db().prepare("SELECT * FROM faceless_channels ORDER BY updated_at DESC").all() as ChannelRow[];
+ const counts = new Map(
+ (db().prepare("SELECT channel_id, COUNT(*) AS n FROM faceless_episodes WHERE channel_id IS NOT NULL GROUP BY channel_id").all() as { channel_id: string; n: number }[]).map((r) => [r.channel_id, r.n]),
+ );
+ return rows.map((r) => {
+ const c = toChannel(r);
+ const done = db().prepare("SELECT * FROM faceless_episodes WHERE channel_id = ? AND status = 'done' ORDER BY updated_at DESC LIMIT 1").get(r.id) as EpisodeRow | undefined;
+ return { ...c, episodes: counts.get(r.id) ?? 0, cover: done ? finalOf(toEpisode(done)) : null };
+ });
+}
+
+export function getChannel(id: string): FacelessChannel | null {
+ const r = db().prepare("SELECT * FROM faceless_channels WHERE id = ?").get(id) as ChannelRow | undefined;
+ return r ? toChannel(r) : null;
+}
+
+/** Title and thumbnail of a YouTube link (oEmbed, through the SSRF-safe fetch); the thumbnail is saved as an upload. */
+async function readReference(url: string): Promise<ChannelReference> {
+ const kind = youtubeKind(url);
+ if (!kind) throw new FacelessError(YOUTUBE_ERROR);
+ const ref: ChannelReference = { url: url.trim(), kind };
+ try {
+ const res = await fetchRemote(`https://www.youtube.com/oembed?format=json&url=${encodeURIComponent(ref.url)}`, { maxBytes: 256 * 1024, timeoutMs: 8000 });
+ const j = JSON.parse(res.data.toString("utf8")) as { title?: string; author_name?: string; thumbnail_url?: string };
+ ref.title = j.title?.slice(0, 200);
+ ref.author = j.author_name?.slice(0, 120);
+ if (j.thumbnail_url) {
+ const img = await fetchRemote(j.thumbnail_url, { maxBytes: 4 * 1024 * 1024, timeoutMs: 8000 });
+ const type = img.contentType?.startsWith("image/") ? img.contentType : "image/jpeg";
+ ref.thumbnail = saveFile({ data: img.data, contentType: type, name: "reference-thumbnail.jpg", source: "upload" }).url;
+ }
+ } catch {
+ // Saved as a plain link: the look can't be matched without the thumbnail, the script still gets the link.
+ }
+ return ref;
+}
+
+export async function createChannel(input: { idea: string; genre: FacelessGenre; engine: Engine; reference?: string; name?: string }): Promise<FacelessChannel> {
+ const idea = input.idea.trim();
+ if (!idea) throw new FacelessError("Describe the channel first");
+ const reference = input.reference?.trim() ? await readReference(input.reference) : null;
+ let name = input.name?.trim() || null;
+ if (!name) {
+ const answer = await askLlm(
+ input.engine,
+ "You name YouTube channels. Reply with the name only: 2–4 words, memorable, no quotes, no emoji.",
+ `Channel idea: ${idea}\nGenre: ${genreInfo(input.genre).label}`,
+ );
+ name = answer?.split("\n")[0].replace(/^["'“”]+|["'“”.]+$/g, "").trim().slice(0, 60) || null;
+ }
+ const now = Date.now();
+ const row: ChannelRow = {
+ id: nanoid(10),
+ name: name || channelName(idea),
+ idea: idea.slice(0, 500),
+ genre: input.genre,
+ avatar_url: null,
+ reference_json: reference ? JSON.stringify(reference) : null,
+ settings_json: JSON.stringify(ChannelDefaults(input.engine, input.genre)),
+ created_at: now,
+ updated_at: now,
+ };
+ db()
+ .prepare(`INSERT INTO faceless_channels (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)
+ .run(row);
+ return toChannel(row);
+}
+
+export async function updateChannel(
+ id: string,
+ patch: { name?: string; idea?: string; genre?: FacelessGenre; avatarUrl?: string | null; reference?: string | null; settings?: Partial<ChannelSettings> },
+): Promise<FacelessChannel> {
+ const cur = getChannel(id);
+ if (!cur) throw new FacelessError("Channel not found", 404);
+ const fields: Partial<ChannelRow> = {};
+ if (patch.name !== undefined) fields.name = patch.name.trim().slice(0, 60) || cur.name;
+ if (patch.idea !== undefined) fields.idea = patch.idea.trim().slice(0, 500) || cur.idea;
+ if (patch.genre) fields.genre = patch.genre;
+ if (patch.avatarUrl !== undefined) fields.avatar_url = patch.avatarUrl;
+ if (patch.reference !== undefined) fields.reference_json = patch.reference ? JSON.stringify(await readReference(patch.reference)) : null;
+ if (patch.settings) fields.settings_json = JSON.stringify({ ...cur.settings, ...patch.settings });
+ const keys = Object.keys(fields);
+ if (keys.length) {
+ db()
+ .prepare(`UPDATE faceless_channels SET ${keys.map((k) => `${k} = @${k}`).join(", ")}, updated_at = @__now WHERE id = @__id`)
+ .run({ ...fields, __now: Date.now(), __id: id });
+ }
+ return getChannel(id)!;
+}
+
+/** Deletes the channel and its episodes; their videos stay in the Library. */
+export function deleteChannel(id: string): void {
+ if (!getChannel(id)) throw new FacelessError("Channel not found", 404);
+ db().transaction(() => {
+ db().prepare("DELETE FROM faceless_episodes WHERE channel_id = ?").run(id);
+ db().prepare("DELETE FROM faceless_channels WHERE id = ?").run(id);
+ })();
+}
+
+/** A channel avatar in the channel's style (one picture generation). */
+export function makeAvatar(id: string): Generation {
+ const c = getChannel(id);
+ if (!c) throw new FacelessError("Channel not found", 404);
+ const style = getStyle(c.settings.styleId);
+ const engine = c.settings.engine;
+ const [g] = createGenerations({
+ feature: "faceless-avatar",
+ modelId: ENGINE_MODELS[engine].still,
+ prompt: `A round channel avatar for a YouTube channel called “${c.name}” (${c.idea}): one bold, simple central emblem, centred on a plain background. Style: ${style.look}. No text or letters.`,
+ params: { aspectRatio: "1:1", numOutputs: 1 },
+ title: `${c.name} · avatar`,
+ });
+ return g;
+}
+
+// ---------------------------------------------------------------------------
+// Topics
+
+export async function suggestTopics(input: { idea: string; genre: FacelessGenre; engine: Engine; avoid?: string[]; count?: number; round?: number; reference?: string }): Promise<{ topics: TopicIdea[]; offline: boolean }> {
+ const count = Math.max(4, Math.min(6, input.count ?? 5));
+ const genre = genreInfo(input.genre);
+ const answer = await askLlm(input.engine, topicsSystem, topicsBrief({ idea: input.idea, genre, count, avoid: input.avoid, reference: input.reference }));
+ const topics = answer ? parseTopics(answer).slice(0, count) : [];
+ if (topics.length >= 3) return { topics, offline: false };
+ return { topics: offlineTopics(input.idea, genre.id, count, (input.round ?? 0) * count), offline: true };
+}
+
+// ---------------------------------------------------------------------------
+// Episodes: create, write, review
+
+declare global {
+ var __fuobeFacelessWriting: Map<string, Promise<void>> | undefined;
+}
+const writing = () => (globalThis.__fuobeFacelessWriting ??= new Map<string, Promise<void>>());
+
+export interface EpisodeInput {
+ kind: "faceless" | "explainer";
+ channelId?: string | null;
+ topic: string;
+ settings: EpisodeSettings;
+ /** A pasted script (skips the writer). */
+ script?: string;
+ sources?: ExplainerSource[];
+ /** Explainer: render as soon as the script is written (no review step). */
+ autoRender?: boolean;
+}
+
+function cleanSettings(s: EpisodeSettings): EpisodeSettings {
+ const mode = engineMode();
+ if (mode !== "both" && s.engine !== mode) {
+ throw new FacelessError(mode === "open" ? "This install is set to open source only (Settings → Engine mode)" : "This install is set to paid cloud APIs only (Settings → Engine mode)");
+ }
+ return {
+ ...s,
+ styleRefs: s.styleRefs.slice(0, 3),
+ elements: [...new Set(s.elements)].slice(0, 8),
+ length: Math.max(15, Math.min(600, Math.round(s.length))),
+ };
+}
+
+export function createEpisode(input: EpisodeInput): FacelessEpisode {
+ const topic = input.topic.trim();
+ const pasted = input.script?.trim() ?? "";
+ if (!topic && !pasted && !input.sources?.length) throw new FacelessError(input.kind === "explainer" ? "Add a prompt, or attach a file or link" : "Add a topic, or bring your own script");
+ if (pasted.length > MAX_SCRIPT) throw new FacelessError("That script is too long to narrate. Shorten it and try again.");
+ const channel = input.channelId ? getChannel(input.channelId) : null;
+ if (input.channelId && !channel) throw new FacelessError("Channel not found", 404);
+ const settings = cleanSettings(input.settings);
+ const sources = (input.sources ?? []).slice(0, 3);
+ settings.sourceImages = sources.filter((s): s is Extract<ExplainerSource, { kind: "image" }> => s.kind === "image").map((s) => s.url);
+ const now = Date.now();
+ const title = (topic || pasted).replace(/\s+/g, " ").slice(0, 80) || "Untitled episode";
+ const row: EpisodeRow = {
+ id: nanoid(10),
+ channel_id: channel?.id ?? null,
+ kind: input.kind,
+ title,
+ topic: topic.slice(0, 5000),
+ status: "writing",
+ error: null,
+ settings_json: JSON.stringify(settings),
+ script_json: JSON.stringify({ blocks: [], source: pasted ? "pasted" : "ai" } satisfies EpisodeScript),
+ plan_json: null,
+ sources_json: JSON.stringify(sources),
+ favorite: 0,
+ created_at: now,
+ updated_at: now,
+ };
+ db()
+ .prepare(`INSERT INTO faceless_episodes (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)
+ .run(row);
+ if (channel) {
+ // The channel remembers the latest look and voice.
+ void updateChannel(channel.id, {
+ settings: { engine: settings.engine, styleId: settings.styleId, styleRefs: settings.styleRefs, voice: settings.voice, aspect: settings.aspect, subtitles: settings.subtitles, music: settings.music, animation: settings.animation, length: settings.length },
+ });
+ }
+ startWriting(row.id, pasted, !!input.autoRender);
+ return toEpisode(row);
+}
+
+/** Write (or split) the script in the background; the episode moves to review, or straight to rendering. */
+function startWriting(id: string, pasted: string, autoRender: boolean): Promise<void> {
+ const job = (async () => {
+ try {
+ await writeScript(id, pasted);
+ } catch (e) {
+ updateEpisodeRow(id, { status: "write-failed", error: (e as Error).message || "Couldn't write the script" });
+ return;
+ }
+ if (!autoRender) return;
+ try {
+ renderEpisode(id);
+ } catch (e) {
+ // The script is there: show it with what's in the way (a missing voice, an engine that isn't connected).
+ updateEpisodeRow(id, { status: "review", error: (e as Error).message });
+ }
+ })().finally(() => writing().delete(id));
+ writing().set(id, job);
+ return job;
+}
+
+/** Wait for a script that's being written (tests, and the API's `?wait=1`). */
+export const scriptWritten = (id: string) => writing().get(id) ?? Promise.resolve();
+
+async function writeScript(id: string, pasted: string): Promise<void> {
+ const ep = mustEpisode(id);
+ const genre = genreInfo(ep.channelId ? (getChannel(ep.channelId)?.genre ?? "education") : "education");
+ const channel = ep.channelId ? getChannel(ep.channelId) : null;
+ const s = ep.settings;
+ const style = getStyle(s.styleId);
+ const auto = ep.kind === "explainer" && s.auto;
+ const scenes = blockCount(auto ? AUTO_SECONDS : s.length);
+ const handles = new Set(s.elements.map((h) => h.toLowerCase()));
+ const elements = listElements()
+ .filter((e) => e.kind !== "voice" && handles.has(e.handle.toLowerCase()))
+ .map((e) => ({ handle: e.handle, kind: e.kind, description: e.description }));
+ const textSources = ep.sources.flatMap((x) => (x.kind === "text" ? [`${x.name}: ${x.text.slice(0, 6000)}`] : x.kind === "link" ? [`${x.title ?? x.url} (${x.url}): ${x.text.slice(0, 6000)}`] : []));
+ let failure = "";
+ const onError = (m: string) => (failure = m);
+ let script: EpisodeScript;
+ if (pasted) {
+ const blocks = splitScript(pasted);
+ const answer = await askLlm(s.engine, visualsSystem, visualsBrief(blocks, style.name, ep.topic || pasted.slice(0, 200)), onError);
+ const visuals = answer ? parseVisuals(answer, blocks.length) : null;
+ script = {
+ source: "pasted",
+ blocks: visuals ? blocks.map((b, i) => ({ ...b, visual: visuals[i].visual, motion: visuals[i].motion || b.motion })) : blocks,
+ ...(!visuals && { offline: true, note: failure ? `Pictures planned offline (${failure}).` : "Pictures planned from your words — connect Claude or Ollama in Settings for better scenes." }),
+ };
+ } else {
+ const topic = ep.topic || textSources[0]?.slice(0, 300) || "this topic";
+ const brief = scriptBrief({
+ topic,
+ genre: ep.kind === "explainer" ? { ...genre, label: "Explainer", hint: "Explain it clearly to someone new to it", tone: genre.tone } : genre,
+ scenes,
+ wordsPerScene: wordsFor(10),
+ channel: channel ? `${channel.name} — ${channel.idea}` : undefined,
+ styleName: style.name,
+ elements,
+ reference: channel?.reference ? [channel.reference.title, channel.reference.author && `by ${channel.reference.author}`].filter(Boolean).join(" ") || channel.reference.url : undefined,
+ sources: textSources,
+ auto,
+ });
+ const answer = await askLlm(s.engine, scriptSystem, brief, onError);
+ const parsed = answer ? parseScript(answer) : null;
+ if (parsed?.blocks.length) {
+ script = { source: "ai", title: parsed.title ?? undefined, blocks: parsed.blocks };
+ } else {
+ const blocks = offlineScript(topic, ep.kind === "explainer" ? "education" : genre.id, scenes);
+ 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 };
+ }
+ }
+ if (!episodeRow(id)) return;
+ updateEpisodeRow(id, {
+ status: "review",
+ error: null,
+ title: (script.title || ep.title).slice(0, 120),
+ script_json: JSON.stringify(script),
+ });
+}
+
+/** Write the script again (after a failure, or for a fresh draft). */
+export function rewriteEpisode(id: string): FacelessEpisode {
+ const ep = mustEpisode(id);
+ if (ep.status === "rendering" || ep.status === "done") throw new FacelessError("This episode is already rendered — change scenes in the timeline instead", 409);
+ if (writing().has(id)) return ep;
+ updateEpisodeRow(id, { status: "writing", error: null });
+ startWriting(id, ep.script.source === "pasted" ? ep.script.blocks.map((b) => b.narration).join(" ") : "", false);
+ return mustEpisode(id);
+}
+
+export function updateEpisode(id: string, patch: { title?: string; favorite?: boolean; blocks?: Partial<ScriptBlock>[]; settings?: Partial<EpisodeSettings> }): FacelessEpisode {
+ const ep = mustEpisode(id);
+ const fields: Partial<EpisodeRow> = {};
+ if (patch.title !== undefined) fields.title = patch.title.trim().slice(0, 120) || ep.title;
+ if (patch.favorite !== undefined) fields.favorite = patch.favorite ? 1 : 0;
+ if (patch.blocks || patch.settings) {
+ if (ep.status !== "review" && ep.status !== "write-failed") throw new FacelessError("The script can only change before the episode renders — use the timeline editor", 409);
+ if (patch.blocks) {
+ const blocks = normalizeBlocks(patch.blocks);
+ if (narrationText(blocks).length > MAX_SCRIPT) throw new FacelessError("That script is too long to narrate. Shorten it and try again.");
+ fields.script_json = JSON.stringify({ ...ep.script, blocks });
+ fields.status = "review";
+ }
+ if (patch.settings) fields.settings_json = JSON.stringify(cleanSettings({ ...ep.settings, ...patch.settings }));
+ }
+ updateEpisodeRow(id, fields);
+ return mustEpisode(id);
+}
+
+export function deleteEpisode(id: string): void {
+ mustEpisode(id);
+ db().prepare("DELETE FROM faceless_episodes WHERE id = ?").run(id);
+}
+
+// ---------------------------------------------------------------------------
+// Rendering
+
+/**
+ * A voice to clone when an open-source narrator has no sample and the narration would only run as a
+ * demo anyway (no ComfyUI): a short tone saved once, so demo mode stays clickable end to end.
+ */
+function demoVoice(): string {
+ const found = db().prepare("SELECT rel_path FROM assets WHERE name = 'fuobe-demo-voice.wav' LIMIT 1").get() as { rel_path: string } | undefined;
+ if (found) return fileUrl(found.rel_path);
+ const rate = 16000;
+ const n = rate * 2;
+ const buf = Buffer.alloc(44 + n * 2);
+ buf.write("RIFF", 0);
+ buf.writeUInt32LE(36 + n * 2, 4);
+ buf.write("WAVEfmt ", 8);
+ buf.writeUInt32LE(16, 16);
+ buf.writeUInt16LE(1, 20);
+ buf.writeUInt16LE(1, 22);
+ buf.writeUInt32LE(rate, 24);
+ buf.writeUInt32LE(rate * 2, 28);
+ buf.writeUInt16LE(2, 32);
+ buf.writeUInt16LE(16, 34);
+ buf.write("data", 36);
+ buf.writeUInt32LE(n * 2, 40);
+ for (let i = 0; i < n; i++) buf.writeInt16LE(Math.round(Math.sin((2 * Math.PI * 220 * i) / rate) * 0.2 * 32767 * Math.min(1, i / 800, (n - i) / 800)), 44 + i * 2);
+ return saveFile({ data: buf, contentType: "audio/wav", name: "fuobe-demo-voice.wav", source: "upload" }).url;
+}
+
+/** Whether a model's operation would run as a demo right now. */
+function runsAsDemo(modelId: string, op: GenerationRequest["op"]): boolean {
+ const m = getModel(modelId);
+ if (!m || !op) return true;
+ try {
+ return chooseRoute(routesFor(m, op)).demo;
+ } catch {
+ return false;
+ }
+}
+
+function graphInput(ep: FacelessEpisode, blocks = ep.script.blocks, stillEdits?: StillEdits): GraphInput {
+ const genre = genreInfo(ep.channelId ? getChannel(ep.channelId)?.genre : "education");
+ const s = ep.settings;
+ const narration = ENGINE_MODELS[s.engine].narration;
+ let fallbackVoice: string | undefined;
+ if (s.engine === "open" && s.voice?.kind !== "sample") {
+ if (!runsAsDemo(narration, "tts")) throw new FacelessError("Pick the narrator's voice: record or upload 10–60 s of speech, or use one of your saved voices (open-source narration clones a voice)");
+ fallbackVoice = demoVoice();
+ }
+ return { feature: ep.kind, title: ep.title, genre, settings: s, blocks, stillEdits, fallbackVoice };
+}
+
+function buildGraph(ep: FacelessEpisode, blocks = ep.script.blocks, stillEdits?: StillEdits): GraphStep[] {
+ try {
+ return buildEpisodeGraph(graphInput(ep, blocks, stillEdits), getModel);
+ } catch (e) {
+ if (e instanceof FacelessError) throw e;
+ throw new FacelessError((e as Error).message, 422);
+ }
+}
+
+/**
+ * Cloud episodes with a music bed are mixed by the open mixer (the cloud soundtrack tool takes one
+ * track): it must run the way the rest does.
+ */
+function checkMusicMix(ep: FacelessEpisode, graph: GraphStep[]): void {
+ if (ep.settings.engine !== "cloud" || !ep.settings.music) return;
+ const mix = graph.find((s) => s.key === "mix")!;
+ if (engineMode() === "cloud") throw new FacelessError("A music bed is mixed under the voice by the open-source mixer, and this install is set to cloud APIs only — turn music off", 422);
+ const mixDemo = runsAsDemo(mix.request.modelId, "mux");
+ const videoDemo = runsAsDemo(graph.find((s) => s.part === "clip")!.request.modelId, "i2v");
+ if (mixDemo && !videoDemo) throw new FacelessError("A music bed is mixed under the voice by ComfyUI (the cloud soundtrack tool takes one track) — start ComfyUI, or turn music off", 422);
+}
+
+function toPipelineSteps(graph: GraphStep[]) {
+ return graph.map((s) => ({ key: s.key, request: { ...s.request, step: s.request.step ?? { label: s.label, index: 0, of: 1 } }, after: s.after, chain: s.chain }));
+}
+
+/** Start the render: every step as a chained generation (validated as a whole before anything is created). */
+export function renderEpisode(id: string): FacelessEpisode {
+ const ep = mustEpisode(id);
+ if (ep.status === "writing") throw new FacelessError("The script is still being written", 409);
+ if (ep.status === "rendering") throw new FacelessError("This episode is already rendering", 409);
+ if (ep.plan) throw new FacelessError(ep.status === "done" ? "This episode is done — change scenes in the timeline" : "This episode already rendered — use Retry", 409);
+ const blocks = normalizeBlocks(ep.script.blocks);
+ if (!blocks.length) throw new FacelessError("The script has no scenes yet");
+ const ready = { ...ep, script: { ...ep.script, blocks } };
+ const graph = buildGraph(ready, blocks);
+ checkMusicMix(ready, graph);
+ let pipeline: ReturnType<typeof createPipeline>;
+ try {
+ pipeline = createPipeline(toPipelineSteps(graph));
+ } catch (e) {
+ throw new FacelessError((e as Error).message, 422);
+ }
+ const plan: EpisodePlan = {
+ batchId: pipeline.batchId,
+ ids: Object.fromEntries(Object.entries(pipeline.byKey).map(([k, g]) => [k, g.id])),
+ changes: [],
+ };
+ updateEpisodeRow(id, { status: "rendering", error: null, plan_json: JSON.stringify(plan), script_json: JSON.stringify(ready.script) });
+ return mustEpisode(id);
+}
+
+/**
+ * Create the `rerun` steps of a graph again, waiting on the new ones or on the current generations of
+ * the steps that are kept. Everything is previewed first, so a bad step creates nothing.
+ */
+function relaunch(graph: GraphStep[], ids: Record<string, string>, rerun: string[], batchId: string): Record<string, string> {
+ const todo = new Set(rerun);
+ const steps = graph.filter((s) => todo.has(s.key));
+ for (const s of graph) if (!todo.has(s.key) && !ids[s.key]) throw new FacelessError(`“${s.label}” has no result to reuse — try again`, 409);
+ const previews = steps.map((s) => {
+ try {
+ return { key: s.key, label: s.label, ...previewChained({ ...s.request, ...(s.chain && { chain: s.chain }) }, s.after?.length ?? 0) };
+ } catch (e) {
+ throw new FacelessError(`${s.label}: ${(e as Error).message}`, 422);
+ }
+ });
+ const demo = previews.find((p) => p.demo);
+ const real = previews.find((p) => !p.demo);
+ if (demo && real) throw new FacelessError(`${demo.label} would run as a demo (${demo.model.name} isn't connected) while ${real.label} runs for real — connect it in Settings, or turn on demo mode`, 422);
+ const next = { ...ids };
+ const made: Generation[] = [];
+ try {
+ for (const s of steps) {
+ const after = s.after ?? [];
+ const [g] = createGenerations({ ...s.request, ...(s.chain && { chain: s.chain }), step: s.request.step ?? { label: s.label, index: 0, of: 1 } }, { batchId, ...(after.length && { dependsOn: after.map((k) => next[k]) }) });
+ next[s.key] = g.id;
+ made.push(g);
+ }
+ } catch (e) {
+ for (const g of made) void cancelGeneration(g.id);
+ throw new FacelessError((e as Error).message, 422);
+ }
+ return next;
+}
+
+const statusMap = (ids: Record<string, string>) =>
+ Object.fromEntries(Object.entries(ids).map(([k, id]) => [k, getGeneration(id)?.status])) as Record<string, string | undefined>;
+
+/** Redo the steps that failed (and what waited on them); finished steps are kept. */
+export function retryEpisode(id: string): FacelessEpisode {
+ const ep = mustEpisode(id);
+ if (!ep.plan) return renderEpisode(id);
+ const graph = buildGraph(ep, ep.script.blocks, ep.plan.stillEdits);
+ const status = statusMap(ep.plan.ids);
+ if (Object.values(status).some((s) => s === "queued" || s === "running")) {
+ // Steps still waiting on a failed one fail on the runner's next tick; retry those too.
+ const live = graph.filter((s) => status[s.key] === "queued" || status[s.key] === "running");
+ if (live.some((s) => !s.after?.length || s.after.some((a) => status[a] !== "failed" && status[a] !== "canceled"))) throw new FacelessError("Still rendering — retry once it stops", 409);
+ }
+ const plan = planRetry(graph, Object.fromEntries(Object.entries(status).map(([k, v]) => [k, v === "queued" || v === "running" ? "failed" : v])));
+ if (!plan.rerun.length) return ep;
+ for (const k of plan.rerun) if (ep.plan.ids[k]) void cancelGeneration(ep.plan.ids[k]);
+ const ids = relaunch(graph, ep.plan.ids, plan.rerun, ep.plan.batchId);
+ updateEpisodeRow(id, { status: "rendering", error: null, plan_json: JSON.stringify({ ...ep.plan, ids } satisfies EpisodePlan) });
+ return mustEpisode(id);
+}
+
+// ---------------------------------------------------------------------------
+// The timeline editor
+
+export interface ChangeInput {
+ blocks: string[];
+ part: ChangePart;
+ /** Picture / motion: what to change. */
+ instruction?: string;
+ /** Narration: the block's new lines (one per block). */
+ narration?: string[];
+}
+
+/** The blocks, picture edits and graph a change would render. */
+function changed(ep: FacelessEpisode, c: ChangeInput) {
+ if (!ep.plan) throw new FacelessError("Render the episode first", 409);
+ const ids = c.blocks.filter((b) => ep.script.blocks.some((x) => x.id === b));
+ if (!ids.length) throw new FacelessError("Pick a scene to change");
+ const instruction = c.instruction?.trim() ?? "";
+ let blocks = ep.script.blocks;
+ const stillEdits: StillEdits = { ...ep.plan.stillEdits };
+ if (c.part === "narration") {
+ if (!c.narration || c.narration.length !== ids.length || c.narration.some((n) => !n.trim())) throw new FacelessError("Write the new lines for each scene");
+ // The block keeps its length (its clips are reused); lines that no longer fit are flagged in the editor.
+ blocks = blocks.map((b) => (ids.includes(b.id) ? { ...b, narration: c.narration![ids.indexOf(b.id)].replace(/\s+/g, " ").trim() } : b));
+ } else {
+ if (!instruction) throw new FacelessError(c.part === "picture" ? "Describe what to change in the picture" : "Describe the new movement");
+ if (c.part === "motion") blocks = blocks.map((b) => (ids.includes(b.id) ? { ...b, motion: instruction } : b));
+ if (c.part === "picture") {
+ for (const b of ids) {
+ const still = getGeneration(ep.plan.ids[`still-${b}`] ?? "");
+ const source = still?.status === "succeeded" ? still.outputs.find((o) => o.kind === "image")?.url : undefined;
+ if (source) stillEdits[b] = { source, instruction };
+ else delete stillEdits[b];
+ }
+ // A picture that never rendered is made again from its description plus the change.
+ blocks = blocks.map((b) => (ids.includes(b.id) && !stillEdits[b.id] ? { ...b, visual: `${b.visual}. ${instruction}` } : b));
+ }
+ }
+ const graph = buildGraph(ep, blocks, stillEdits);
+ return { graph, blocks, stillEdits, plan: planRerun(graph, changedKeys(graph, ids, c.part)), ids };
+}
+
+export function previewChange(id: string, c: ChangeInput): ChangePreview {
+ const ep = mustEpisode(id);
+ const { graph, plan } = changed(ep, c);
+ const est = estimateGraph(graph, getModel, plan.rerun);
+ const demo = plan.rerun.some((k) => {
+ const s = graph.find((x) => x.key === k)!;
+ try {
+ return previewChained({ ...s.request, ...(s.chain && { chain: s.chain }) }, s.after?.length ?? 0).demo;
+ } catch {
+ return false;
+ }
+ });
+ return { rerun: plan.rerun, labels: plan.rerun.map((k) => graph.find((s) => s.key === k)!.label), costUsd: est.unknown ? null : est.total, demo };
+}
+
+/** Re-run what the change touches (that block's steps, the joins after it, the mix, the subtitles); Undo keeps the version before. */
+export function applyChange(id: string, c: ChangeInput): FacelessEpisode {
+ const ep = mustEpisode(id);
+ if (ep.status === "rendering") throw new FacelessError("Wait for the current render to finish before changing scenes", 409);
+ const { graph, blocks, stillEdits, plan, ids } = changed(ep, c);
+ const est = estimateGraph(graph, getModel, plan.rerun);
+ const next = relaunch(graph, ep.plan!.ids, plan.rerun, ep.plan!.batchId);
+ const final = getGeneration(ep.plan!.ids[finalKey(graph)] ?? "");
+ const updated: EpisodePlan = {
+ ...ep.plan!,
+ ids: next,
+ stillEdits,
+ previous: { ids: ep.plan!.ids, blocks: ep.script.blocks, stillEdits: ep.plan!.stillEdits },
+ lastFinal: final?.status === "succeeded" ? final.id : ep.plan!.lastFinal,
+ changes: [...ep.plan!.changes, { at: Date.now(), blocks: ids, part: c.part, instruction: c.part === "narration" ? (c.narration ?? []).join(" / ") : (c.instruction ?? ""), costUsd: est.unknown ? null : est.total }].slice(-50),
+ };
+ updateEpisodeRow(id, { status: "rendering", error: null, plan_json: JSON.stringify(updated), script_json: JSON.stringify({ ...ep.script, blocks }) });
+ return mustEpisode(id);
+}
+
+/** Back to the version before the last change (its generations are still there; nothing is refunded). */
+export function undoChange(id: string): FacelessEpisode {
+ const ep = mustEpisode(id);
+ const prev = ep.plan?.previous;
+ if (!prev) throw new FacelessError("Nothing to undo", 409);
+ for (const [k, gid] of Object.entries(ep.plan!.ids)) if (prev.ids[k] !== gid) void cancelGeneration(gid);
+ const plan: EpisodePlan = { ...ep.plan!, ids: prev.ids, stillEdits: prev.stillEdits, previous: undefined, lastFinal: undefined };
+ updateEpisodeRow(id, { status: "rendering", plan_json: JSON.stringify(plan), script_json: JSON.stringify({ ...ep.script, blocks: prev.blocks }) });
+ return mustEpisode(id);
+}
+
+// ---------------------------------------------------------------------------
+// Reading
+
+function finalOf(ep: FacelessEpisode): Generation | null {
+ if (!ep.plan) return null;
+ const key = ep.plan.ids.captions ? "captions" : "mix";
+ const g = getGeneration(ep.plan.ids[key] ?? "");
+ return g?.status === "succeeded" ? g : null;
+}
+
+/** The episode's status from its generations (saved when it changes). */
+function settle(ep: FacelessEpisode, gens: Map<string, Generation | null>): EpisodeStatus {
+ if (ep.status === "writing" && !writing().has(ep.id)) {
+ // A restart while the script was being written.
+ updateEpisodeRow(ep.id, { status: "write-failed", error: "Interrupted while writing the script — try again" });
+ return "write-failed";
+ }
+ if (!ep.plan || ep.status === "writing" || ep.status === "write-failed" || ep.status === "review") return ep.status;
+ const list = Object.entries(ep.plan.ids).map(([k, id]) => [k, gens.get(id) ?? null] as const);
+ const final = list.find(([k]) => k === (ep.plan!.ids.captions ? "captions" : "mix"))?.[1];
+ const active = list.some(([, g]) => g && (g.status === "queued" || g.status === "running"));
+ const broken = list.find(([, g]) => !g || g.status === "failed" || g.status === "canceled");
+ const status: EpisodeStatus = final?.status === "succeeded" ? "done" : !active && broken ? "failed" : "rendering";
+ const error = status === "failed" ? (broken?.[1]?.error ?? "A step was deleted — retry to make it again") : null;
+ if (status !== ep.status || error !== ep.error) updateEpisodeRow(ep.id, { status, error });
+ return status;
+}
+
+const stepProgress = (g: Generation | null) => (!g ? 0 : g.status === "succeeded" ? 1 : g.status === "running" ? Math.max(0.05, Math.min(0.95, g.progress ?? 0.1)) : 0);
+
+export function episodeView(id: string): EpisodeView {
+ const ep = mustEpisode(id);
+ const gens = new Map<string, Generation | null>();
+ for (const gid of Object.values(ep.plan?.ids ?? {})) gens.set(gid, getGeneration(gid));
+ const status = settle(ep, gens);
+ const current = { ...ep, status, error: status === ep.status ? ep.error : (episodeRow(id)?.error ?? null) };
+ let graph: GraphStep[] = [];
+ try {
+ if (current.script.blocks.length) graph = buildEpisodeGraph({ ...graphInputSafe(current), blocks: current.script.blocks, stillEdits: ep.plan?.stillEdits }, getModel);
+ } catch {
+ graph = [];
+ }
+ const steps = graph.map((s) => ({ key: s.key, part: s.part, block: s.block, label: s.label, generation: ep.plan?.ids[s.key] ? (gens.get(ep.plan.ids[s.key]) ?? null) : null }));
+ const final = finalOf(current);
+ const previousFinal = !final && ep.plan?.lastFinal ? getGeneration(ep.plan.lastFinal) : null;
+ const spent = [...gens.values()].reduce((n, g) => n + (g && g.status !== "failed" && g.status !== "canceled" ? (g.costUsd ?? 0) : 0), 0);
+ return {
+ episode: current,
+ channel: current.channelId ? getChannel(current.channelId) : null,
+ steps,
+ final,
+ previousFinal: previousFinal?.status === "succeeded" ? previousFinal : null,
+ progress: steps.length && ep.plan ? steps.reduce((n, s) => n + stepProgress(s.generation), 0) / steps.length : 0,
+ spentUsd: Math.round(spent * 100) / 100,
+ estimate: graph.length ? estimateGraph(graph, getModel) : null,
+ };
+}
+
+/** The graph input for reading (never throws for a missing open voice: the view just shows the plan). */
+function graphInputSafe(ep: FacelessEpisode): GraphInput {
+ try {
+ return graphInput(ep);
+ } catch {
+ return { feature: ep.kind, title: ep.title, genre: genreInfo(ep.channelId ? getChannel(ep.channelId)?.genre : "education"), settings: ep.settings, blocks: ep.script.blocks, fallbackVoice: "/api/files/placeholder.wav" };
+ }
+}
+
+function toCard(r: EpisodeRow): EpisodeCard {
+ const ep = toEpisode(r);
+ const ids = Object.values(ep.plan?.ids ?? {});
+ const gens = new Map(ids.map((id) => [id, getGeneration(id)] as const));
+ const status = ep.plan ? settle(ep, gens) : settle(ep, new Map());
+ const final = ep.plan ? (gens.get(ep.plan.ids.captions ?? ep.plan.ids.mix ?? "") ?? null) : null;
+ // A still from the first scene stands in until the film is done.
+ const firstStill = ep.plan ? (gens.get(ep.plan.ids[`still-${ep.script.blocks[0]?.id}`] ?? "") ?? null) : null;
+ const poster = final?.status === "succeeded" ? final : firstStill?.status === "succeeded" ? firstStill : null;
+ return {
+ id: ep.id,
+ channelId: ep.channelId,
+ kind: ep.kind,
+ title: ep.title,
+ status,
+ styleId: ep.settings.styleId,
+ aspect: ep.settings.aspect,
+ seconds: totalSeconds(ep.script.blocks) || ep.settings.length,
+ favorite: ep.favorite,
+ poster,
+ progress: ids.length ? [...gens.values()].reduce((n, g) => n + stepProgress(g ?? null), 0) / ids.length : 0,
+ createdAt: ep.createdAt,
+ };
+}
+
+export function listEpisodes(o: { channelId?: string; kind?: "faceless" | "explainer"; q?: string; liked?: boolean; limit?: number }): EpisodeCard[] {
+ const where: string[] = [];
+ const args: unknown[] = [];
+ if (o.channelId) {
+ where.push("channel_id = ?");
+ args.push(o.channelId);
+ }
+ if (o.kind) {
+ where.push("kind = ?");
+ args.push(o.kind);
+ }
+ if (o.liked) where.push("favorite = 1");
+ const q = o.q?.trim();
+ if (q) {
+ where.push("(title LIKE ? OR topic LIKE ?)");
+ args.push(`%${q}%`, `%${q}%`);
+ }
+ const rows = db()
+ .prepare(`SELECT * FROM faceless_episodes ${where.length ? `WHERE ${where.join(" AND ")}` : ""} ORDER BY created_at DESC LIMIT ?`)
+ .all(...args, Math.max(1, Math.min(o.limit ?? 60, 200))) as EpisodeRow[];
+ return rows.map(toCard);
+}
+
+// ---------------------------------------------------------------------------
+// Estimates, voices, links
+
+/** What an episode would cost and whether it would run as a demo, before or after the script exists. */
+export function estimateEpisode(input: { kind: "faceless" | "explainer"; settings: EpisodeSettings; blocks?: Partial<ScriptBlock>[]; genre?: FacelessGenre }): EstimateResult {
+ const settings = { ...input.settings, styleRefs: input.settings.styleRefs.slice(0, 3) };
+ const blocks = input.blocks?.length ? normalizeBlocks(input.blocks) : placeholderBlocks(settings.auto ? AUTO_SECONDS : settings.length);
+ const seconds = totalSeconds(blocks);
+ const fake: FacelessEpisode = {
+ id: "estimate",
+ channelId: null,
+ kind: input.kind,
+ title: "Estimate",
+ topic: "",
+ status: "review",
+ error: null,
+ settings,
+ script: { blocks, source: "ai" },
+ plan: null,
+ sources: [],
+ favorite: false,
+ createdAt: 0,
+ updatedAt: 0,
+ };
+ let graph: GraphStep[];
+ try {
+ graph = buildEpisodeGraph({ ...graphInputSafe(fake), genre: genreInfo(input.genre) }, getModel);
+ } catch (e) {
+ return { estimate: { total: 0, parts: {}, unknown: true }, demo: true, seconds, blocks: blocks.length, error: (e as Error).message };
+ }
+ let error: string | undefined;
+ let demo = false;
+ try {
+ cleanSettings(settings);
+ checkMusicMix(fake, graph);
+ if (settings.engine === "open" && settings.voice?.kind !== "sample" && !runsAsDemo(ENGINE_MODELS.open.narration, "tts")) {
+ error = "Pick the narrator's voice: record or upload 10–60 s of speech, or use one of your saved voices";
+ }
+ } catch (e) {
+ error = (e as Error).message;
+ }
+ // Every distinct model once is enough to know the mode (and to catch a step the install can't run).
+ const seen = new Set<string>();
+ for (const s of graph) {
+ const k = `${s.request.modelId}:${s.part}`;
+ if (seen.has(k)) continue;
+ seen.add(k);
+ try {
+ const p = previewChained({ ...s.request, ...(s.chain && { chain: s.chain }) }, s.after?.length ?? 0);
+ demo ||= p.demo;
+ } catch (e) {
+ error ??= `${s.label}: ${(e as Error).message}`;
+ }
+ }
+ return { estimate: estimateGraph(graph, getModel), demo, seconds, blocks: blocks.length, ...(error && { error }) };
+}
+
+/** A short sample of a premade narrator (one cheap speech generation, reused once made). */
+export function voicePreview(voice: NarratorVoice & { kind: "preset" }): Generation {
+ const modelId = ENGINE_MODELS.cloud.narration;
+ const model = getModel(modelId)!;
+ const v = model.options.voices?.find((x) => x.id === voice.id);
+ if (!v) throw new FacelessError("Unknown voice");
+ const existing = db()
+ .prepare(
+ "SELECT g.id FROM generations g LEFT JOIN generation_trash t ON t.generation_id = g.id WHERE t.deleted_at IS NULL AND g.feature = 'faceless-voice' AND g.model_id = ? AND json_extract(g.request_json, '$.params.voice') = ? AND g.status IN ('queued', 'running', 'succeeded') ORDER BY g.created_at DESC LIMIT 1",
+ )
+ .get(modelId, v.id) as { id: string } | undefined;
+ const found = existing && getGeneration(existing.id);
+ if (found) return found;
+ return createGenerations({ feature: "faceless-voice", modelId, op: "tts", prompt: previewLine(v.name), params: { voice: v.id }, title: `${v.name} · narrator sample` })[0];
+}
+
+const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
+
+/** Readable text of an HTML page: title plus paragraphs, scripts and styles dropped. */
+export function pageText(html: string): { title: string | null; text: string } {
+ const title = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html)?.[1] ?? /<meta[^>]+property=["']og:title["'][^>]+content=["']([^"']+)/i.exec(html)?.[1] ?? null;
+ const body = html
+ .replace(/<(head|script|style|noscript|svg|nav|footer|header|form)[\s\S]*?<\/\1>/gi, " ")
+ .replace(/<br\s*\/?>|<\/(p|div|li|h[1-6]|section|article|tr)>/gi, "\n")
+ .replace(/<[^>]+>/g, " ")
+ .replace(/&(#\d+|#x[\da-f]+|\w+);/gi, (m, e: string) =>
+ e.startsWith("#x") ? String.fromCodePoint(parseInt(e.slice(2), 16)) : e.startsWith("#") ? String.fromCodePoint(Number(e.slice(1))) : (ENTITIES[e.toLowerCase()] ?? m),
+ )
+ .split("\n")
+ .map((l) => l.replace(/\s+/g, " ").trim())
+ .filter((l) => l.length > 2)
+ .join("\n");
+ const decode = (s: string) => s.replace(/&(\w+);/g, (m, e: string) => ENTITIES[e.toLowerCase()] ?? m).replace(/\s+/g, " ").trim();
+ return { title: title ? decode(title) : null, text: body };
+}
+
+/** A link source for the Explainer: fetched with the SSRF-safe fetch, then summarised for the writer. */
+export async function summarizeLink(url: string, engine: Engine): Promise<Extract<ExplainerSource, { kind: "link" }>> {
+ let res: Awaited<ReturnType<typeof fetchRemote>>;
+ try {
+ res = await fetchRemote(url, { maxBytes: 5 * 1024 * 1024, timeoutMs: 15_000 });
+ } catch (e) {
+ throw new FacelessError((e as Error).message || "Couldn't open that link", 422);
+ }
+ const type = res.contentType ?? "";
+ if (!/^text\/|html|xml|json/.test(type)) throw new FacelessError("That link isn't a web page or text — upload the file instead", 422);
+ const raw = res.data.toString("utf8");
+ const { title, text } = /html|xml/.test(type) ? pageText(raw) : { title: null, text: raw };
+ if (text.length < 40) throw new FacelessError("That page has no readable text", 422);
+ const summary = await askLlm(
+ engine,
+ "You summarise web pages for a video script writer. Reply with the key facts, numbers, names and explanations as short plain sentences (at most 250 words). No preamble.",
+ `Page: ${title ?? url}\n\n${text.slice(0, 24_000)}`,
+ );
+ return { kind: "link", url: res.url, title: title?.slice(0, 160), text: (summary ?? text).slice(0, 6000) };
+}
+
+// ---------------------------------------------------------------------------
+// Request schemas and the route helper (src/app/api/faceless/**, src/app/api/explainer/**)
+
+const FileUrl = z.string().startsWith("/api/files/").max(500);
+export const VoiceSchema = z.union([
+ z.object({ kind: z.literal("preset"), id: z.string().min(1).max(80), name: z.string().max(80).optional() }),
+ z.object({ kind: z.literal("sample"), url: FileUrl, name: z.string().max(120).optional() }),
+]);
+export const GenreSchema = z.enum(["education", "history", "kids", "storytelling"]);
+export const EngineSchema = z.enum(["cloud", "open"]);
+
+export const SettingsSchema = z.object({
+ engine: EngineSchema,
+ length: z.number().int().min(15).max(600),
+ animation: z.enum(["animated", "frames"]),
+ aspect: z.enum(["16:9", "9:16"]),
+ subtitles: z.boolean(),
+ music: z.boolean(),
+ styleId: z.string().min(1).max(60),
+ styleRefs: z.array(FileUrl).max(3, "Up to 3 style references"),
+ voice: VoiceSchema.nullable(),
+ elements: z.array(z.string().max(60)).max(8),
+ videoModel: z.string().max(60).optional(),
+ resolution: z.string().max(10).optional(),
+ auto: z.boolean().optional(),
+});
+
+export const BlockSchema = z.object({
+ id: z.string().max(40).optional(),
+ narration: z.string().max(2000),
+ visual: z.string().max(1200),
+ motion: z.string().max(400).optional(),
+ seconds: z.number().optional(),
+});
+
+export const SourceSchema = z.union([
+ z.object({ kind: z.literal("image"), url: FileUrl, name: z.string().max(200).optional() }),
+ z.object({ kind: z.literal("text"), name: z.string().max(200), text: z.string().min(1).max(20_000) }),
+ z.object({ kind: z.literal("link"), url: z.string().url().max(2000), title: z.string().max(200).optional(), text: z.string().min(1).max(8000) }),
+]);
+
+export const ChangeSchema = z.object({
+ blocks: z.array(z.string().max(40)).min(1).max(12),
+ part: z.enum(["picture", "motion", "narration"]),
+ instruction: z.string().max(1000).optional(),
+ narration: z.array(z.string().max(2000)).max(12).optional(),
+ apply: z.boolean().optional(),
+});
+
+/** Parse a JSON body; a schema's own message (e.g. "Up to 3 style references") wins over the generic one. */
+export async function body<S extends z.ZodType>(request: Request, schema: S, message: string): Promise<z.infer<S>> {
+ const parsed = schema.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) {
+ const custom = parsed.error.issues.find((i) => i.message && !/^(Invalid|Expected|Too|Unrecognized)/.test(i.message))?.message;
+ throw new FacelessError(custom ?? message, 400);
+ }
+ return parsed.data;
+}
+
+/** Turn thrown errors into the API's `{ error }` responses. */
+export async function handle(fn: () => Promise<Response> | Response): Promise<Response> {
+ try {
+ return await fn();
+ } catch (e) {
+ if (e instanceof FacelessError) return Response.json({ error: e.message }, { status: e.status });
+ console.error("[faceless]", e);
+ return Response.json({ error: (e as Error).message || "Something went wrong" }, { status: 500 });
+ }
+}
diff --git a/tests/faceless-api.test.ts b/tests/faceless-api.test.ts
new file mode 100644
index 00000000..eb2d1b0f
--- /dev/null
+++ b/tests/faceless-api.test.ts
@@ -0,0 +1,299 @@
+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 { EpisodeSettings, EpisodeView, FacelessChannel, FacelessEpisode } from "@/lib/catalog/faceless";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-faceless-"));
+process.env.FUOBE_DATA_DIR = dir;
+// Nothing listens: open models run on the demo provider, and there's no LLM (the offline writer runs).
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const gens = await import("@/server/generations");
+const faceless = await import("@/server/faceless");
+const channelsRoute = await import("@/app/api/faceless/channels/route");
+const channelRoute = await import("@/app/api/faceless/channels/[id]/route");
+const topicsRoute = await import("@/app/api/faceless/topics/route");
+const episodesRoute = await import("@/app/api/faceless/episodes/route");
+const episodeRoute = await import("@/app/api/faceless/episodes/[id]/route");
+const actionRoute = await import("@/app/api/faceless/episodes/[id]/[action]/route");
+const changeRoute = await import("@/app/api/faceless/episodes/[id]/change/route");
+const estimateRoute = await import("@/app/api/faceless/estimate/route");
+const voiceRoute = await import("@/app/api/faceless/voices/preview/route");
+const explainerRoute = await import("@/app/api/explainer/route");
+const linkRoute = await import("@/app/api/explainer/link/route");
+
+beforeAll(() => {
+ setSetting("demoMode", "auto");
+ setSetting("enhanceProvider", "none");
+});
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const json = (method: string, body?: unknown) =>
+ new Request("http://x/api", { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
+const params = <T extends Record<string, string>>(p: T) => ({ params: Promise.resolve(p) });
+
+const cloud: EpisodeSettings = {
+ engine: "cloud",
+ length: 60,
+ animation: "animated",
+ aspect: "16:9",
+ subtitles: true,
+ music: false,
+ styleId: "editorial-motion-graphics",
+ styleRefs: [],
+ voice: { kind: "preset", id: "Xb7hH8MSUJpSbSDYk0k2" },
+ elements: [],
+};
+const open: EpisodeSettings = { ...cloud, engine: "open", music: true, voice: null, aspect: "9:16", animation: "frames" };
+
+async function view(id: string): Promise<EpisodeView> {
+ // GET handlers start with connection(), which needs a request scope: read through the server module.
+ return JSON.parse(JSON.stringify(faceless.episodeView(id)));
+}
+
+/** Wait for an episode to finish rendering (demo jobs: a few seconds per step). */
+async function settled(id: string, ms = 90_000): Promise<EpisodeView> {
+ const until = Date.now() + ms;
+ for (;;) {
+ const v = await view(id);
+ if (v.episode.status === "done" || v.episode.status === "failed") return v;
+ if (Date.now() > until) throw new Error(`timed out: ${v.episode.status} ${Math.round(v.progress * 100)}%`);
+ await new Promise((r) => setTimeout(r, 500));
+ }
+}
+
+let channel: FacelessChannel;
+
+describe("Faceless channels and topics", () => {
+ it("creates a channel with a written name, lists it, and saves its look", async () => {
+ const res = await channelsRoute.POST(json("POST", { idea: "Channel about the rise and fall of empires", genre: "history", engine: "cloud" }));
+ expect(res.status).toBe(201);
+ channel = await res.json();
+ expect(channel).toMatchObject({ name: "The Rise and Fall of Empires", genre: "history", settings: { styleId: "watercolor-chronicle", voice: { kind: "preset", id: "JBFqnCBsd6RMkjVDRZzb" }, aspect: "16:9", subtitles: true } });
+ expect(faceless.listChannels().map((c) => c.id)).toContain(channel.id);
+ expect((await channelsRoute.POST(json("POST", { idea: "", genre: "history", engine: "cloud" }))).status).toBe(400);
+ const bad = await channelsRoute.POST(json("POST", { idea: "x", genre: "history", engine: "cloud", reference: "https://vimeo.com/1" }));
+ expect(bad.status).toBe(400);
+ expect((await bad.json()).error).toBe("That does not look like a YouTube channel, video or playlist link.");
+ const patched = await (await channelRoute.PATCH(json("PATCH", { name: "Empires", settings: { aspect: "9:16" } }), params({ id: channel.id }))).json();
+ expect(patched).toMatchObject({ name: "Empires", settings: { aspect: "9:16", styleId: "watercolor-chronicle" } });
+ expect((await channelRoute.PATCH(json("PATCH", { name: "x" }), params({ id: "nope" }))).status).toBe(404);
+ });
+
+ it("suggests 4–6 topics offline, and new ones on the next round", async () => {
+ const first = await (await topicsRoute.POST(json("POST", { channelId: channel.id, engine: "cloud" }))).json();
+ expect(first.offline).toBe(true);
+ expect(first.topics.length).toBeGreaterThanOrEqual(4);
+ expect(first.topics.length).toBeLessThanOrEqual(6);
+ expect(first.topics[0].title).toMatch(/rise and fall of empires/i);
+ const next = await (await topicsRoute.POST(json("POST", { channelId: channel.id, engine: "cloud", round: 1 }))).json();
+ expect(next.topics[0].title).not.toBe(first.topics[0].title);
+ });
+});
+
+describe("Episodes", () => {
+ it("validates lengths, topics and scripts", async () => {
+ const bad = await episodesRoute.POST(json("POST", { channelId: channel.id, topic: "x", settings: { ...cloud, length: 90 } }));
+ expect((await bad.json()).error).toBe("Choose one of the offered video lengths");
+ const empty = await episodesRoute.POST(json("POST", { channelId: channel.id, topic: " ", settings: cloud }));
+ expect((await empty.json()).error).toBe("Add a topic, or bring your own script");
+ const long = await episodesRoute.POST(json("POST", { channelId: channel.id, topic: "x", script: "word ".repeat(2500), settings: cloud }));
+ expect((await long.json()).error).toBe("That script is too long to narrate. Shorten it and try again.");
+ const refs = await episodesRoute.POST(json("POST", { channelId: channel.id, topic: "x", settings: { ...cloud, styleRefs: ["/api/files/a.png", "/api/files/b.png", "/api/files/c.png", "/api/files/d.png"] } }));
+ expect((await refs.json()).error).toBe("Up to 3 style references");
+ });
+
+ it("splits a pasted script into scenes for review, and edits them before rendering", async () => {
+ const script = "The Roman Empire did not fall in a day. For centuries it stretched from Britain to Egypt. Then, slowly, the cracks began to show. Armies grew expensive, borders grew long, and emperors came and went. By 476, the western half was gone.";
+ const res = await episodesRoute.POST(json("POST", { channelId: channel.id, topic: "How Rome fell", script, settings: cloud }));
+ expect(res.status).toBe(201);
+ const ep: FacelessEpisode = await res.json();
+ expect(ep.status).toBe("writing");
+ await faceless.scriptWritten(ep.id);
+ const v = await view(ep.id);
+ expect(v.episode.status).toBe("review");
+ expect(v.episode.script).toMatchObject({ source: "pasted", offline: true });
+ expect(v.episode.script.blocks.map((b) => b.narration).join(" ")).toBe(script);
+ expect(v.episode.script.blocks.every((b) => b.seconds <= 10 && b.visual)).toBe(true);
+ // Review: edit a scene; a scene with too many words is split.
+ const blocks = v.episode.script.blocks.map((b, i) => (i === 0 ? { ...b, narration: `${b.narration} ${"and it kept going on ".repeat(8)}` } : b));
+ const edited: EpisodeView = await (await episodeRoute.PATCH(json("PATCH", { blocks, title: "Rome, slowly" }), params({ id: ep.id }))).json();
+ expect(edited.episode.title).toBe("Rome, slowly");
+ expect(edited.episode.script.blocks.length).toBeGreaterThan(v.episode.script.blocks.length);
+ expect(edited.episode.script.blocks.every((b) => b.seconds <= 10)).toBe(true);
+ expect(edited.steps.filter((s) => s.part === "still")).toHaveLength(edited.episode.script.blocks.length);
+ expect(edited.estimate!.total).toBeGreaterThan(0);
+ // The channel remembers the look and voice of its latest episode.
+ expect(faceless.listEpisodes({ channelId: channel.id }).map((e) => e.id)).toContain(ep.id);
+ expect(faceless.getChannel(channel.id)!.settings.aspect).toBe("16:9");
+ });
+
+ it("estimates by engine and mode, and says what's in the way", async () => {
+ const est = async (s: EpisodeSettings) => (await estimateRoute.POST(json("POST", { kind: "faceless", settings: s }))).json();
+ const animated = await est(cloud);
+ const frames = await est({ ...cloud, animation: "frames" });
+ expect(animated.demo).toBe(true);
+ expect(animated.blocks).toBe(6);
+ expect(animated.estimate.parts.clip).toBeCloseTo(6, 5);
+ expect(frames.estimate.total).toBeLessThan(animated.estimate.total);
+ const openEst = await est(open);
+ expect(openEst.estimate.total).toBe(0);
+ expect(openEst.error).toBeUndefined();
+ // Cloud music needs the open mixer; with everything on the demo provider it still runs.
+ expect((await est({ ...cloud, music: true })).error).toBeUndefined();
+ setSetting("engineMode", "cloud");
+ try {
+ expect((await est({ ...cloud, music: true })).error).toMatch(/turn music off/);
+ expect((await est(open)).error).toMatch(/cloud APIs only/);
+ } finally {
+ setSetting("engineMode", "both");
+ }
+ });
+
+ it(
+ "renders end to end in demo mode on both engines, then re-runs one scene, undoes it and retries a failure",
+ async () => {
+ const make = async (settings: EpisodeSettings, topic: string) => {
+ const ep: FacelessEpisode = await (await episodesRoute.POST(json("POST", { channelId: channel.id, topic, settings }))).json();
+ await faceless.scriptWritten(ep.id);
+ const v = await view(ep.id);
+ expect(v.episode.status).toBe("review");
+ expect(v.episode.script).toMatchObject({ source: "ai", offline: true });
+ expect(v.episode.script.blocks).toHaveLength(6);
+ const r = await actionRoute.POST(json("POST"), params({ id: ep.id, action: "render" }));
+ expect(r.status).toBe(200);
+ return ep.id;
+ };
+ const cloudId = await make(cloud, "Why Rome split in two");
+ const openId = await make(open, "The fall of Byzantium");
+ expect((await actionRoute.POST(json("POST"), params({ id: cloudId, action: "render" }))).status).toBe(409);
+
+ const rendering = await view(openId);
+ expect(rendering.episode.status).toBe("rendering");
+ // Open, frame by frame: 12 shots, folded joins, the demo voice cloned, music, timed captions.
+ const ids = rendering.episode.plan!.ids;
+ // A 10-second scene is two 5-second Wan shots; short scenes are one.
+ const clips = Object.keys(ids).filter((k) => k.startsWith("clip-"));
+ expect(clips.length).toBeGreaterThan(6);
+ expect(clips).toHaveLength(rendering.steps.filter((s) => s.part === "clip").length);
+ expect(Object.keys(ids)).toEqual(expect.arrayContaining(["join", "join-1-1", "narration", "music", "mix", "words", "captions"]));
+ const narration = gens.getGeneration(ids.narration)!;
+ expect(narration.request.inputs?.voiceAudio).toMatch(/^\/api\/files\/uploads\/.+\.wav$/);
+ expect(gens.getGeneration(ids["clip-" + rendering.episode.script.blocks[0].id + "-1"])!.request.prompt).toMatch(/still illustration/);
+
+ const [doneCloud, doneOpen] = await Promise.all([settled(cloudId), settled(openId)]);
+ for (const v of [doneCloud, doneOpen]) {
+ expect(v.episode.status).toBe("done");
+ expect(v.final?.status).toBe("succeeded");
+ expect(v.final?.outputs[0].kind).toBe("video");
+ expect(v.progress).toBe(1);
+ expect(v.steps.every((s) => s.generation?.status === "succeeded")).toBe(true);
+ }
+ expect(doneOpen.final!.op).toBe("captions");
+ expect(doneOpen.final!.request.title).toBe(doneOpen.episode.title);
+
+ // Timeline editor: change scene 3's picture.
+ const target = doneCloud.episode.script.blocks[2].id;
+ const before = doneCloud.episode.plan!.ids;
+ const preview = await (await changeRoute.POST(json("POST", { blocks: [target], part: "picture", instruction: "make it night" }), params({ id: cloudId }))).json();
+ expect(preview.rerun).toEqual([`still-${target}`, `clip-${target}-1`, "join", "mix", "captions"]);
+ expect(preview.costUsd).toBeGreaterThan(0.3);
+ expect(preview.demo).toBe(true);
+ const applied = await changeRoute.POST(json("POST", { blocks: [target], part: "picture", instruction: "make it night", apply: true }), params({ id: cloudId }));
+ expect(applied.status).toBe(201);
+ const changing: EpisodeView = await applied.json();
+ expect(changing.episode.status).toBe("rendering");
+ const after = changing.episode.plan!.ids;
+ expect(after[`still-${target}`]).not.toBe(before[`still-${target}`]);
+ expect(after[`still-${doneCloud.episode.script.blocks[0].id}`]).toBe(before[`still-${doneCloud.episode.script.blocks[0].id}`]);
+ expect(after.narration).toBe(before.narration);
+ expect(gens.getGeneration(after[`still-${target}`])!.request).toMatchObject({ op: "edit", inputs: { images: [doneCloud.steps.find((s) => s.key === `still-${target}`)!.generation!.outputs[0].url] } });
+ expect(changing.previousFinal?.id).toBe(before.captions);
+ expect(changing.episode.plan!.changes).toHaveLength(1);
+
+ // A narration change re-voices the whole voice-over and re-mixes; the pictures are kept.
+ const voice = await (await changeRoute.POST(json("POST", { blocks: [doneOpen.episode.script.blocks[2].id], part: "narration", narration: ["Night fell over the city."] }), params({ id: openId }))).json();
+ expect(voice.rerun).toEqual(["narration", "mix", "words", "captions"]);
+
+ // Retry (meanwhile, on the open episode): a step that fails takes what waits on it down; Retry redoes only those.
+ const failing = await view(openId);
+ const clipKey = failing.steps.find((s) => s.key.startsWith(`clip-${failing.episode.script.blocks[1].id}-`))!.key;
+ await changeRoute.POST(json("POST", { blocks: [failing.episode.script.blocks[1].id], part: "motion", instruction: "a slow zoom out", apply: true }), params({ id: openId }));
+ const mid = await view(openId);
+ expect(mid.episode.plan!.ids[clipKey]).not.toBe(failing.episode.plan!.ids[clipKey]);
+ expect(mid.episode.plan!.ids[`still-${failing.episode.script.blocks[1].id}`]).toBe(failing.episode.plan!.ids[`still-${failing.episode.script.blocks[1].id}`]);
+ await gens.cancelGeneration(mid.episode.plan!.ids[clipKey]);
+
+ const [changed, failed] = await Promise.all([settled(cloudId), settled(openId)]);
+ expect(changed.episode.status).toBe("done");
+ expect(changed.final!.id).toBe(after.captions);
+ // Undo goes back to the version before.
+ const undone: EpisodeView = await (await actionRoute.POST(json("POST"), params({ id: cloudId, action: "undo" }))).json();
+ expect(undone.episode.plan!.ids).toEqual(before);
+ expect((await settled(cloudId)).final!.id).toBe(before.captions);
+
+ expect(failed.episode.status).toBe("failed");
+ expect(failed.episode.error).toBeTruthy();
+ const retried: EpisodeView = await (await actionRoute.POST(json("POST"), params({ id: openId, action: "retry" }))).json();
+ expect(retried.episode.status).toBe("rendering");
+ expect(retried.episode.plan!.ids[clipKey]).not.toBe(mid.episode.plan!.ids[clipKey]);
+ expect(retried.episode.plan!.ids.narration).toBe(mid.episode.plan!.ids.narration);
+ // The redone clip runs (what follows it is the same chain the first render ran).
+ const redone = retried.episode.plan!.ids[clipKey];
+ for (let i = 0; i < 60 && gens.getGeneration(redone)!.status !== "succeeded"; i++) await new Promise((r) => setTimeout(r, 500));
+ expect(gens.getGeneration(redone)!.status).toBe("succeeded");
+ },
+ 300_000,
+ );
+});
+
+describe("Explainer", () => {
+ it("renders straight from a prompt and a document, lists history and likes", async () => {
+ const res = await explainerRoute.POST(
+ json("POST", {
+ prompt: "Explain how dinosaurs went extinct, for kids",
+ sources: [{ kind: "text", name: "notes.txt", text: "An asteroid hit Chicxulub 66 million years ago." }],
+ settings: { ...cloud, length: 30, styleId: "pixel-art" },
+ }),
+ );
+ expect(res.status).toBe(201);
+ const ep: FacelessEpisode = await res.json();
+ await faceless.scriptWritten(ep.id);
+ const v = await view(ep.id);
+ expect(v.episode.kind).toBe("explainer");
+ expect(v.episode.status).toBe("rendering");
+ expect(v.episode.script.blocks).toHaveLength(3);
+ expect(v.steps.find((s) => s.part === "still")!.generation!.request.prompt).toMatch(/16-bit pixel art/);
+ expect(faceless.listEpisodes({ kind: "explainer", q: "dinosaurs" }).map((c) => c.id)).toEqual([ep.id]);
+ expect(faceless.listEpisodes({ kind: "faceless", q: "dinosaurs" })).toEqual([]);
+ await episodeRoute.PATCH(json("PATCH", { favorite: true }), params({ id: ep.id }));
+ expect(faceless.listEpisodes({ kind: "explainer", liked: true })).toHaveLength(1);
+ // Validation the research names.
+ const many = await explainerRoute.POST(json("POST", { prompt: "x", sources: Array.from({ length: 4 }, (_, i) => ({ kind: "text", name: `${i}`, text: "t" })), settings: cloud }));
+ expect((await many.json()).error).toBe("Up to 3 sources per video — remove one to add another");
+ const none = await explainerRoute.POST(json("POST", { prompt: "", settings: cloud }));
+ expect((await none.json()).error).toBe("Add a prompt, or attach a file or link");
+ });
+
+ it("refuses links to this machine (SSRF-safe fetch)", async () => {
+ const res = await linkRoute.POST(json("POST", { url: "http://127.0.0.1:9/secret", engine: "cloud" }));
+ expect(res.status).toBe(422);
+ expect((await res.json()).error).toMatch(/won't fetch/);
+ expect(faceless.pageText("<html><head><title>Tides &amp; you</title><script>x()</script></head><body><p>The moon pulls.</p><p>Twice a day.</p></body></html>")).toEqual({
+ title: "Tides & you",
+ text: "The moon pulls.\nTwice a day.",
+ });
+ });
+
+ it("makes one voice preview per narrator and reuses it", async () => {
+ const a = await (await voiceRoute.POST(json("POST", { id: "JBFqnCBsd6RMkjVDRZzb" }))).json();
+ const b = await (await voiceRoute.POST(json("POST", { id: "JBFqnCBsd6RMkjVDRZzb" }))).json();
+ expect(a.id).toBe(b.id);
+ expect(a).toMatchObject({ feature: "faceless-voice", op: "tts", modelId: "elevenlabs-v4" });
+ expect(a.request.prompt).toMatch(/I'm George/);
+ expect((await voiceRoute.POST(json("POST", { id: "nobody" }))).status).toBe(400);
+ });
+});