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 Studio, Explainer and Content Factory: accounts make their own

Adarsha964d38d3f00
diff --git a/docs/public-signup.md b/docs/public-signup.md
index dd2c068f..d9dcb703 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -77,7 +77,8 @@ An account is signed in, but it sees the owner's studio as a guest does:
owner's results, files, uploads, folders, shares, projects (Layers, Cinema, Canvas, storyboards,
elements…) and Assist threads are hidden: the lists come back empty, and other reads answer 403.
Every change to them (create, rename, move, share, delete) answers 403 with `code: "library"`.
- Accounts have their own uploads and runs (below), and their own Cinema Studio projects.
+ Accounts have their own uploads and runs (below), their own Cinema Studio projects, and their own Faceless
+ channels, explainers and Content Factory series.
A Canvas Kinetic node renders in the owner's browser; keeping its run on the board
(`PUT /api/canvases/<id>/runs/<node>`) is a canvas change like any other (403 `library` for an account, 401
for a guest), and it takes only the owner's own finished Kinetic Motion results.
@@ -100,7 +101,8 @@ An account is signed in, but it sees the owner's studio as a guest does:
Storyboard, Elements, Faceless Studio, Content Factory, Explainer, Ads Studio, Click to Ad and
Marketing Studio show their ready-made starters the same way (`<studio>/start/<id>`); making one
(`POST /api/starters/<id>`) is the owner's, and an account gets 403 `library`, except Cinema Studio's
- ready films, which an account makes as its own project (a guest gets the sign-up card). A starter without its
+ ready films and Faceless Studio's ready channels, which an account makes as its own project (a guest gets the sign-up
+ card). Content Factory's and the Explainer's ready ones fill the composer for anyone. A starter without its
cover yet is the owner's only: its card, its words and its page (404 for anyone else). Storyboard's
ready stories with a cover also fill its composer for anyone (`/storyboard?starter=<id>`), and the
Library's "Make your first" row links to pages everyone can open.
@@ -395,6 +397,20 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188
the studio's AI helper, on either engine: a cloud step-by-step dub with a key and no GPU is asked to connect one. Its
reviewed lines are saved with its dub, and its dubbed videos are its own runs, to open and download. A guest gets the
sign-up card.
+- **Faceless Studio, the Explainer and Content Factory.** An account's channels (`/api/faceless/channels/**`), their
+ episodes (`/api/faceless/episodes/**`), its explainers (`/api/explainer`) and its series
+ (`/api/content-factory/series/**`) are its own (`src/server/account-projects.ts` kinds `faceless`, `explainer` and
+ `content-factory`; up to 50 of each, deleted with the account). Another account's, or the owner's, read as not found
+ (404), and the owner's lists never show an account's. Its scripts, episode plans, channel names, topic ideas and
+ document summaries are the offline writer's: never the studio's AI helper. A render, a retry, a timeline change, an
+ upscale, a channel avatar, a narrator sample and a reference clip's reading run on its own ComfyUI or its own fal.ai or
+ Replicate key, with only its own files, after the same checks as Genjutsu's (`src/server/account-tool-run.ts`); the
+ whole render is planned and checked before its first step starts, and a series' episodes render as one run. Writing a
+ script for review, a channel and a series made from a preset need no GPU or key. The server never fetches a link for
+ it: a channel's YouTube reference is kept as the link, and an explainer's link source and a series' TikTok or
+ Instagram link are the owner's (it attaches the file or uploads the clip). "Generate in Claude" (the studio's own MCP
+ server) and "Regenerate to 1080p" (held with Open-H3 Regenerate) aren't offered to it (403 `own-gpu-tool`). A guest
+ gets the sign-up card.
- **Files a run takes.** A run on your GPU takes only files you uploaded here, or your own results.
A link or a `data:` URI answers 400 with `code: "input-not-allowed"`, someone else's file 403
(`input-not-yours`), and a file that has expired 404 (`input-gone`, "That file has expired.
diff --git a/src/app/(studio)/content-factory/[id]/page.tsx b/src/app/(studio)/content-factory/[id]/page.tsx
index bae8eca4..00589c19 100644
--- a/src/app/(studio)/content-factory/[id]/page.tsx
+++ b/src/app/(studio)/content-factory/[id]/page.tsx
@@ -1,16 +1,17 @@
import type { Metadata } from "next";
+import { headers } from "next/headers";
import { notFound } from "next/navigation";
import { Suspense } from "react";
import { SeriesView } from "@/components/content-factory/series-view";
import { getModel } from "@/lib/catalog";
import { pickerData } from "@/lib/catalog/faceless";
-import { recordExists } from "@/server/records";
+import { recordFor } from "@/server/records";
export const metadata: Metadata = { title: "Series" };
async function Series({ params }: { params: PageProps<"/content-factory/[id]">["params"] }) {
const { id } = await params;
- if (!recordExists({ kind: "series", ids: [id] })) notFound();
+ if (!recordFor({ kind: "series", ids: [id] }, await headers())) notFound();
return <SeriesView id={id} voices={pickerData(getModel).voices} />;
}
diff --git a/src/app/(studio)/explainer/[id]/page.tsx b/src/app/(studio)/explainer/[id]/page.tsx
index 1a0b8ffe..d4173f5d 100644
--- a/src/app/(studio)/explainer/[id]/page.tsx
+++ b/src/app/(studio)/explainer/[id]/page.tsx
@@ -1,14 +1,15 @@
import type { Metadata } from "next";
+import { headers } from "next/headers";
import { notFound } from "next/navigation";
import { Suspense } from "react";
import { EpisodeView } from "@/components/faceless/episode-view";
-import { recordExists } from "@/server/records";
+import { recordFor } from "@/server/records";
export const metadata: Metadata = { title: "Explainer" };
async function Explainer({ params }: { params: PageProps<"/explainer/[id]">["params"] }) {
const { id } = await params;
- if (!recordExists({ kind: "explainer", ids: [id] })) notFound();
+ if (!recordFor({ kind: "explainer", ids: [id] }, await headers())) notFound();
return <EpisodeView id={id} backHref="/explainer" backLabel="Explainer" />;
}
diff --git a/src/app/(studio)/faceless/[id]/[episode]/page.tsx b/src/app/(studio)/faceless/[id]/[episode]/page.tsx
index 1e20d6dd..4ba653fb 100644
--- a/src/app/(studio)/faceless/[id]/[episode]/page.tsx
+++ b/src/app/(studio)/faceless/[id]/[episode]/page.tsx
@@ -1,14 +1,15 @@
import type { Metadata } from "next";
+import { headers } from "next/headers";
import { notFound } from "next/navigation";
import { Suspense } from "react";
import { EpisodeView } from "@/components/faceless/episode-view";
-import { recordExists } from "@/server/records";
+import { recordFor } from "@/server/records";
export const metadata: Metadata = { title: "Episode" };
async function Episode({ params }: { params: PageProps<"/faceless/[id]/[episode]">["params"] }) {
const { id, episode } = await params;
- if (!recordExists({ kind: "episode", ids: [id, episode] })) notFound();
+ if (!recordFor({ kind: "episode", ids: [id, episode] }, await headers())) notFound();
return <EpisodeView id={episode} backHref={`/faceless/${id}`} backLabel="Channel" />;
}
diff --git a/src/app/(studio)/faceless/[id]/new/page.tsx b/src/app/(studio)/faceless/[id]/new/page.tsx
index dabc05ce..ef064c02 100644
--- a/src/app/(studio)/faceless/[id]/new/page.tsx
+++ b/src/app/(studio)/faceless/[id]/new/page.tsx
@@ -1,17 +1,18 @@
import type { Metadata } from "next";
+import { headers } from "next/headers";
import { notFound } from "next/navigation";
import { Suspense } from "react";
import { EpisodeWizard } from "@/components/faceless/episode-wizard";
import { getModel } from "@/lib/catalog";
import { pickerData } from "@/lib/catalog/faceless";
import { facelessTopic } from "@/lib/starters/catalog";
-import { recordExists } from "@/server/records";
+import { recordFor } from "@/server/records";
export const metadata: Metadata = { title: "New episode" };
async function Wizard({ params, searchParams }: Pick<PageProps<"/faceless/[id]/new">, "params" | "searchParams">) {
const { id } = await params;
- if (!recordExists({ kind: "channel", ids: [id] })) notFound();
+ if (!recordFor({ kind: "channel", ids: [id] }, await headers())) notFound();
// A ready channel (?starter=<id>) opens with its first episode's topic written in.
const { starter } = await searchParams;
const topic = facelessTopic(typeof starter === "string" ? starter : undefined);
diff --git a/src/app/(studio)/faceless/[id]/page.tsx b/src/app/(studio)/faceless/[id]/page.tsx
index 4ddde4a9..6d037b62 100644
--- a/src/app/(studio)/faceless/[id]/page.tsx
+++ b/src/app/(studio)/faceless/[id]/page.tsx
@@ -1,16 +1,17 @@
import type { Metadata } from "next";
+import { headers } from "next/headers";
import { notFound } from "next/navigation";
import { Suspense } from "react";
import { ChannelView } from "@/components/faceless/channel-view";
import { getModel } from "@/lib/catalog";
import { pickerData } from "@/lib/catalog/faceless";
-import { recordExists } from "@/server/records";
+import { recordFor } from "@/server/records";
export const metadata: Metadata = { title: "Faceless channel" };
async function Channel({ params }: { params: PageProps<"/faceless/[id]">["params"] }) {
const { id } = await params;
- if (!recordExists({ kind: "channel", ids: [id] })) notFound();
+ if (!recordFor({ kind: "channel", ids: [id] }, await headers())) notFound();
return <ChannelView id={id} picker={pickerData(getModel)} />;
}
diff --git a/src/app/api/content-factory/estimate/route.ts b/src/app/api/content-factory/estimate/route.ts
index b74f9048..3706126d 100644
--- a/src/app/api/content-factory/estimate/route.ts
+++ b/src/app/api/content-factory/estimate/route.ts
@@ -1,7 +1,7 @@
import { z } from "zod";
+import { priceAsRun } from "@/server/account-tool-run";
import { BriefSchema, estimateSeries, handle, SeriesInputSchema } from "@/server/content-factory";
import { body } from "@/server/faceless";
-import { priceAs } from "@/server/visitor";
const Ask = SeriesInputSchema.extend({
seriesId: z.string().max(20).optional(),
@@ -9,12 +9,11 @@ const Ask = SeriesInputSchema.extend({
brief: BriefSchema.optional(),
});
-/** What the whole series would cost (one episode at the brief's pace × the episodes), and whether it runs as a demo. */
-async function post(request: Request) {
- return handle(async () => Response.json(estimateSeries(await body(request, Ask, "Those settings aren't valid"))));
-}
-
-/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+/**
+ * What the whole series would cost (one episode at the brief's pace × the episodes), and whether it runs as a demo. A
+ * visitor (public sign-up) gets the price of its run as it would go: an account's on its own GPU or its own key (with
+ * its own series' brief), a guest's on the open engine; never a demo (src/server/account-tool-run.ts priceAsRun).
+ */
export async function POST(request: Request) {
- return priceAs(request, () => post(request));
+ return priceAsRun(request, () => handle(async () => Response.json(estimateSeries(await body(request, Ask, "Those settings aren't valid")))));
}
diff --git a/src/app/api/content-factory/series/[id]/episodes/route.ts b/src/app/api/content-factory/series/[id]/episodes/route.ts
index ca852c22..c15b7503 100644
--- a/src/app/api/content-factory/series/[id]/episodes/route.ts
+++ b/src/app/api/content-factory/series/[id]/episodes/route.ts
@@ -1,6 +1,8 @@
import { z } from "zod";
import { MAX_EPISODES } from "@/lib/catalog/content-factory";
-import { addEpisodes, handle } from "@/server/content-factory";
+import { guestRun, toolViewer } from "@/server/account-tool-run";
+import { addEpisodes, handle, planAdd } from "@/server/content-factory";
+import { runSeries } from "@/server/content-factory-account";
import { body } from "@/server/faceless";
const More = z.object({
@@ -9,10 +11,17 @@ const More = z.object({
review: z.boolean().optional(),
});
-/** "Next episode": plan and start more episodes after the ones already made. */
+/**
+ * "Next episode": plan and start more episodes after the ones already made. An account's are planned and written first,
+ * then render on its own GPU or key as one run, after the checks a studio run gets; a guest signs up first.
+ */
export async function POST(request: Request, ctx: RouteContext<"/api/content-factory/series/[id]/episodes">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
return handle(async () => {
const { id } = await ctx.params;
- return Response.json(await addEpisodes(id, await body(request, More, "Say how many episodes to add")));
+ const input = await body(request, More, "Say how many episodes to add");
+ if (viewer.kind === "owner") return Response.json(await addEpisodes(id, input));
+ return runSeries(request, viewer.account, id, "add", !!input.review, () => planAdd(id, input));
}, request);
}
diff --git a/src/app/api/content-factory/series/[id]/generate/route.ts b/src/app/api/content-factory/series/[id]/generate/route.ts
index 2d7dc49c..b08bfcdb 100644
--- a/src/app/api/content-factory/series/[id]/generate/route.ts
+++ b/src/app/api/content-factory/series/[id]/generate/route.ts
@@ -1,13 +1,30 @@
import { z } from "zod";
-import { generateSeries, handle, SeriesInputSchema } from "@/server/content-factory";
+import { asViewer, bodyTooBig, guestRun, toolViewer } from "@/server/account-tool-run";
+import { generateSeries, handle, planGenerate, SeriesInputSchema } from "@/server/content-factory";
+import { runSeries } from "@/server/content-factory-account";
import { body } from "@/server/faceless";
+import { filesRefused, settingsFiles } from "@/server/faceless-account";
const Generate = SeriesInputSchema.extend({ review: z.boolean().optional() });
-/** "Generate here": plan the episodes, make the series' channel and start every episode. */
+/**
+ * "Generate here": plan the episodes, make the series' channel and start every episode. A signed-in account's series is
+ * planned and written first (the offline writer: no AI helper), then its episodes render on its own GPU or key as one
+ * run, after the checks a studio run gets (src/server/account-tool-run.ts); a guest signs up first.
+ */
export async function POST(request: Request, ctx: RouteContext<"/api/content-factory/series/[id]/generate">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const big = bodyTooBig(request);
+ if (big) return big;
+ }
return handle(async () => {
const { id } = await ctx.params;
- return Response.json(await generateSeries(id, await body(request, Generate, "Say what the video is about and pick the settings")));
+ const input = await body(request, Generate, "Say what the video is about and pick the settings");
+ if (viewer.kind === "owner") return Response.json(await asViewer(viewer, () => generateSeries(id, input)));
+ const refused = filesRefused(viewer.account.id, settingsFiles({ voice: input.voice ?? null }));
+ if (refused) return refused;
+ return runSeries(request, viewer.account, id, "generate", !!input.review, () => planGenerate(id, input));
}, request);
}
diff --git a/src/app/api/content-factory/series/[id]/read/route.ts b/src/app/api/content-factory/series/[id]/read/route.ts
index 9ee72ad2..d2d63e30 100644
--- a/src/app/api/content-factory/series/[id]/read/route.ts
+++ b/src/app/api/content-factory/series/[id]/read/route.ts
@@ -1,13 +1,24 @@
import { z } from "zod";
-import { handle, rereadSeries } from "@/server/content-factory";
+import { asViewer, guestRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { handle, rereadSeries, rereadSteps, seriesClip } from "@/server/content-factory";
import { body } from "@/server/faceless";
+import { planned } from "@/server/faceless-account";
const Read = z.object({ engine: z.enum(["cloud", "open"]) });
-/** Read the reference clip again (on either engine). */
+/**
+ * Read the reference clip again (on either engine). An account's runs on its own GPU or key, on its own clip, after the
+ * checks a studio run gets (src/server/account-tool-run.ts); a guest signs up first.
+ */
export async function POST(request: Request, ctx: RouteContext<"/api/content-factory/series/[id]/read">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
return handle(async () => {
const { id } = await ctx.params;
- return Response.json(await rereadSeries(id, (await body(request, Read, "Pick an engine")).engine));
+ const { engine } = await body(request, Read, "Pick an engine");
+ if (viewer.kind === "owner") return Response.json(await rereadSeries(id, engine));
+ const clip = asViewer(viewer, () => seriesClip(id));
+ const out = await runAccountTool(request, viewer.account, { tool: "content-factory", files: [clip], plan: () => planned(() => rereadSteps(id, engine)), start: () => rereadSeries(id, engine) });
+ return out.ok ? Response.json({ ...out.value, ...(out.gpuWarning && { gpuWarning: out.gpuWarning }) }) : out.response;
}, request);
}
diff --git a/src/app/api/content-factory/series/[id]/route.ts b/src/app/api/content-factory/series/[id]/route.ts
index 877e73b7..902222a4 100644
--- a/src/app/api/content-factory/series/[id]/route.ts
+++ b/src/app/api/content-factory/series/[id]/route.ts
@@ -1,31 +1,51 @@
import { connection } from "next/server";
import { z } from "zod";
+import { projectSavesLimited } from "@/server/account-projects";
+import { asViewer, guestRun, toolViewer } from "@/server/account-tool-run";
import { BriefSchema, deleteSeries, handle, seriesView, updateSeries } from "@/server/content-factory";
import { body } from "@/server/faceless";
const Patch = z.object({ brief: BriefSchema.optional(), name: z.string().max(60).optional() });
-/** The series: its reference, how far reading it has got, the brief, the plan and the episodes. */
-export async function GET(_req: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) {
+/**
+ * The series: its reference, how far reading it has got, the brief, the plan and the episodes. The owner's, or an
+ * account's own (another's, or the owner's, reads as not found).
+ */
+export async function GET(request: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) {
await connection();
- return handle(async () => Response.json(seriesView((await ctx.params).id)));
+ const viewer = toolViewer(request);
+ return handle(async () => {
+ const { id } = await ctx.params;
+ return Response.json(asViewer(viewer, () => seriesView(id)));
+ });
}
/** Edit the brief by hand, or rename the series. */
export async function PATCH(request: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const limited = projectSavesLimited(viewer.account.id);
+ if (limited) return limited;
+ }
return handle(async () => {
const { id } = await ctx.params;
- return Response.json(updateSeries(id, await body(request, Patch, "That brief isn't valid")));
+ const patch = await body(request, Patch, "That brief isn't valid");
+ return Response.json(asViewer(viewer, () => updateSeries(id, patch)));
}, request);
}
/**
- * Deletes the series and its channel, stopping what its episodes still render (finished videos stay in the Library).
- * `?draft=1` deletes only a draft that was never made (the composer moving on from a clip it was reading).
+ * Deletes the series and its channel, stopping what its episodes still render (finished videos stay in the Library, or
+ * in an account's runs). `?draft=1` deletes only a draft that was never made (the composer moving on from a clip it was
+ * reading).
*/
export async function DELETE(request: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
return handle(async () => {
- await deleteSeries((await ctx.params).id, { draftOnly: new URL(request.url).searchParams.get("draft") === "1" });
+ const { id } = await ctx.params;
+ await asViewer(viewer, () => deleteSeries(id, { draftOnly: new URL(request.url).searchParams.get("draft") === "1" }));
return new Response(null, { status: 204 });
}, request);
}
diff --git a/src/app/api/content-factory/series/route.ts b/src/app/api/content-factory/series/route.ts
index 0de5ba4b..6f24edc3 100644
--- a/src/app/api/content-factory/series/route.ts
+++ b/src/app/api/content-factory/series/route.ts
@@ -1,7 +1,10 @@
import { connection } from "next/server";
import { z } from "zod";
-import { createSeries, handle, listSeries, ReferenceSchema } from "@/server/content-factory";
+import { projectSavesLimited } from "@/server/account-projects";
+import { asViewer, guestRun, ownGpuTool, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { createSeries, handle, listSeries, makeSeries, prepareSeries, ReferenceSchema, seriesReadSteps, seriesReads, type PreparedSeries } from "@/server/content-factory";
import { body } from "@/server/faceless";
+import { planned } from "@/server/faceless-account";
const Create = z.object({
reference: ReferenceSchema.nullable(),
@@ -9,19 +12,38 @@ const Create = z.object({
prompt: z.string().max(2000).optional(),
});
-/** Series that have been made, newest first. */
-export async function GET() {
+/** Series that have been made, newest first: the owner's, or an account's own. */
+export async function GET(request: Request) {
await connection();
- return handle(() => Response.json({ items: listSeries() }));
+ const viewer = toolViewer(request);
+ return handle(() => Response.json({ items: asViewer(viewer, () => listSeries()) }));
}
/**
* A new series around a reference: an upload, a link (fetched only through the SSRF-safe fetch; 422 with
- * `needsUpload` when it gives no clip) or a preset. Reading a clip into a style brief starts straight away.
+ * `needsUpload` when it gives no clip) or a preset. Reading a clip into a style brief starts straight away. A signed-in
+ * account's series is its own, and reading its clip (its own upload: the server never fetches a link for an account)
+ * runs on its own GPU or key after the checks a studio run gets (src/server/account-tool-run.ts); a guest signs up first.
*/
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const limited = projectSavesLimited(viewer.account.id);
+ if (limited) return limited;
+ }
return handle(async () => {
const input = await body(request, Create, "Add a reference clip, a link or a preset");
- return Response.json(await createSeries(input), { status: 201 });
+ // An account uploads its clip (its composer offers no link): the server never fetches a link for it.
+ if (viewer.kind === "account" && input.reference?.kind === "link") return ownGpuTool();
+ if (viewer.kind === "owner" || !seriesReads(input)) return Response.json(await asViewer(viewer, () => createSeries(input)), { status: 201 });
+ let prepared: PreparedSeries | null = null;
+ const out = await runAccountTool(request, viewer.account, {
+ tool: "content-factory",
+ files: input.reference?.kind === "upload" ? [input.reference.url] : [],
+ plan: () => planned(async () => seriesReadSteps((prepared = await prepareSeries(input)))),
+ start: () => makeSeries(prepared!),
+ });
+ return out.ok ? Response.json({ ...out.value, ...(out.gpuWarning && { gpuWarning: out.gpuWarning }) }, { status: 201 }) : out.response;
}, request);
}
diff --git a/src/app/api/explainer/document/route.ts b/src/app/api/explainer/document/route.ts
index 261a728b..8f1e3c20 100644
--- a/src/app/api/explainer/document/route.ts
+++ b/src/app/api/explainer/document/route.ts
@@ -1,14 +1,23 @@
+import { asViewer, toolViewer } from "@/server/account-tool-run";
import { gateAsProxy, readFormWithin } from "@/server/direct-gate";
import { EngineSchema, FacelessError, handle, MAX_DOCUMENT_BYTES, readDocument } from "@/server/faceless";
+import { readsLimited } from "@/server/faceless-account";
/**
* A PDF or Word source (multipart: "file", "engine"): the text is read on the server and, when the
- * document is longer than the script writer reads, summarised. The file itself isn't kept.
+ * document is longer than the script writer reads, summarised. The file itself isn't kept. A signed-in account's is
+ * read for it (the beginning kept: no AI helper), within its hour's reads; a guest gets the sign-up card (the proxy's
+ * rules, run here).
*/
export async function POST(request: Request) {
// The proxy doesn't run on this route (a big form): its checks run here.
const denied = gateAsProxy(request);
if (denied) return denied;
+ const viewer = toolViewer(request);
+ if (viewer.kind === "account") {
+ const reads = readsLimited(viewer.account.id);
+ if (reads) return reads;
+ }
return handle(async () => {
const form = await readFormWithin(request, MAX_DOCUMENT_BYTES);
if (form === "too-big") throw new FacelessError(`That file is over ${MAX_DOCUMENT_BYTES / 1024 / 1024} MB — add the part that matters, or paste its text into the prompt`, 413);
@@ -16,6 +25,7 @@ export async function POST(request: Request) {
if (!(file instanceof File)) throw new FacelessError("Choose a PDF or a Word file (.docx)");
if (file.size > MAX_DOCUMENT_BYTES) throw new FacelessError(`${file.name} is over ${MAX_DOCUMENT_BYTES / 1024 / 1024} MB — add the part that matters, or paste its text into the prompt`, 413);
const engine = EngineSchema.safeParse(form?.get("engine"));
- return Response.json(await readDocument({ name: file.name, data: Buffer.from(await file.arrayBuffer()), type: file.type }, engine.success ? engine.data : "cloud"));
+ const data = Buffer.from(await file.arrayBuffer());
+ return Response.json(await asViewer(viewer, () => readDocument({ name: file.name, data, type: file.type }, engine.success ? engine.data : "cloud")));
}, request);
}
diff --git a/src/app/api/explainer/link/route.ts b/src/app/api/explainer/link/route.ts
index 5807a649..93a78582 100644
--- a/src/app/api/explainer/link/route.ts
+++ b/src/app/api/explainer/link/route.ts
@@ -1,10 +1,15 @@
import { z } from "zod";
+import { ownGpuTool, toolViewer } from "@/server/account-tool-run";
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. */
+/**
+ * A link source: the page is fetched (public addresses only) and summarised for the script writer. The owner's only: the
+ * server never fetches a link for an account (docs/public-signup.md), so an account attaches the file or pastes the text.
+ */
export async function POST(request: Request) {
+ if (toolViewer(request).kind !== "owner") return ownGpuTool();
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
index b9e0db4d..082cbd70 100644
--- a/src/app/api/explainer/route.ts
+++ b/src/app/api/explainer/route.ts
@@ -1,7 +1,10 @@
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";
+import { projectSavesLimited } from "@/server/account-projects";
+import { asViewer, bodyTooBig, guestRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { body, composeScript, createEpisode, draftGraph, FacelessError, graphToolSteps, handle, listEpisodes, SettingsSchema, SourceSchema } from "@/server/faceless";
+import { filesRefused, planned, settingsFiles, sourceFiles } from "@/server/faceless-account";
const Create = z.object({
prompt: z.string().max(MAX_TOPIC, "Prompt is too long (max 5000 characters)"),
@@ -11,20 +14,48 @@ const Create = z.object({
review: z.boolean().optional(),
});
-/** History: your explainers, newest first (`?q=` search, `?liked=1`). */
+/** History: your explainers, newest first (`?q=` search, `?liked=1`): the owner's, or an account's own. */
export async function GET(request: Request) {
await connection();
+ const viewer = toolViewer(request);
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 }) });
+ return Response.json({ items: asViewer(viewer, () => 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. */
+/**
+ * Explain something: the script is written from the prompt and sources, then rendered. A signed-in account's script is
+ * written at once (the offline writer: no AI helper), its sources' pictures must be its own, and its render runs on its
+ * own GPU or key after the checks a studio run gets (src/server/account-tool-run.ts); a guest signs up first.
+ */
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const big = bodyTooBig(request) ?? projectSavesLimited(viewer.account.id);
+ if (big) return big;
+ }
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 });
+ if (viewer.kind === "owner") {
+ const episode = createEpisode({ kind: "explainer", topic: input.prompt, sources: input.sources, settings: input.settings, autoRender: !input.review });
+ return Response.json(episode, { status: 201 });
+ }
+ const sources = input.sources ?? [];
+ const files = [...settingsFiles(input.settings), ...sourceFiles(sources)];
+ const refused = filesRefused(viewer.account.id, files);
+ if (refused) return refused;
+ if (!input.prompt.trim() && !sources.length) throw new FacelessError("Add a prompt, or attach a file or link");
+ const composed = await asViewer(viewer, () => composeScript({ kind: "explainer", channelId: null, topic: input.prompt.trim(), settings: input.settings, sources }, ""));
+ const ask = { kind: "explainer" as const, topic: input.prompt, sources, settings: input.settings, composed };
+ if (input.review) return Response.json(asViewer(viewer, () => createEpisode(ask)), { status: 201 });
+ const out = await runAccountTool(request, viewer.account, {
+ tool: "explainer",
+ files,
+ plan: () => planned(() => graphToolSteps(draftGraph({ kind: "explainer", title: composed.title ?? input.prompt, settings: input.settings, sources, script: composed }))),
+ start: () => createEpisode({ ...ask, autoRender: true }),
+ });
+ return out.ok ? Response.json({ ...out.value, ...(out.gpuWarning && { gpuWarning: out.gpuWarning }) }, { status: 201 }) : out.response;
}, request);
}
diff --git a/src/app/api/faceless/channels/[id]/avatar/route.ts b/src/app/api/faceless/channels/[id]/avatar/route.ts
index dcef2bf9..abc33588 100644
--- a/src/app/api/faceless/channels/[id]/avatar/route.ts
+++ b/src/app/api/faceless/channels/[id]/avatar/route.ts
@@ -1,9 +1,18 @@
-import { handle, makeAvatar } from "@/server/faceless";
+import { guestRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { avatarRequest, handle, makeAvatar } from "@/server/faceless";
+import { planned } from "@/server/faceless-account";
-/** Draw a channel avatar in the channel's style (one picture generation; it becomes the channel's picture when it's done). */
+/**
+ * Draw a channel avatar in the channel's style (one picture generation; it becomes the channel's picture when it's
+ * done). An account's runs on its own GPU or key, for its own channel, after the checks a studio run gets.
+ */
export async function POST(request: Request, ctx: RouteContext<"/api/faceless/channels/[id]/avatar">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
return handle(async () => {
const { id } = await ctx.params;
- return Response.json(makeAvatar(id), { status: 201 });
+ if (viewer.kind === "owner") return Response.json(makeAvatar(id), { status: 201 });
+ const run = await runAccountTool(request, viewer.account, { tool: "faceless", files: [], plan: () => planned(() => [{ request: avatarRequest(id) }]), start: () => makeAvatar(id) });
+ return run.ok ? Response.json({ ...run.value, ...(run.gpuWarning && { gpuWarning: run.gpuWarning }) }, { status: 201 }) : run.response;
}, request);
}
diff --git a/src/app/api/faceless/channels/[id]/route.ts b/src/app/api/faceless/channels/[id]/route.ts
index ed881229..53bcf95a 100644
--- a/src/app/api/faceless/channels/[id]/route.ts
+++ b/src/app/api/faceless/channels/[id]/route.ts
@@ -1,6 +1,9 @@
import { connection } from "next/server";
import { z } from "zod";
+import { projectSavesLimited } from "@/server/account-projects";
+import { asViewer, guestRun, toolViewer } from "@/server/account-tool-run";
import { body, deleteChannel, FacelessError, GenreSchema, getChannel, handle, listEpisodes, SettingsSchema, updateChannel } from "@/server/faceless";
+import { filesRefused, settingsFiles } from "@/server/faceless-account";
const Patch = z.object({
name: z.string().max(60).optional(),
@@ -11,30 +14,46 @@ const Patch = z.object({
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]">) {
+/** The channel with its episodes: the owner's, or an account's own (another's, or the owner's, reads as not found). */
+export async function GET(request: Request, ctx: RouteContext<"/api/faceless/channels/[id]">) {
await connection();
+ const viewer = toolViewer(request);
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 }) });
+ return asViewer(viewer, () => {
+ const channel = getChannel(id);
+ if (!channel) throw new FacelessError("Channel not found", 404);
+ return Response.json({ channel, episodes: listEpisodes({ channelId: id, limit: 200 }) });
+ });
});
}
+/** Rename it, change its idea or genre, its picture, its reference or its saved look. An account's pictures must be its own. */
export async function PATCH(request: Request, ctx: RouteContext<"/api/faceless/channels/[id]">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const limited = projectSavesLimited(viewer.account.id);
+ if (limited) return limited;
+ }
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));
+ if (viewer.kind === "account") {
+ const refused = filesRefused(viewer.account.id, [patch.avatarUrl, ...settingsFiles(patch.settings)]);
+ if (refused) return refused;
+ }
+ return Response.json(await asViewer(viewer, () => updateChannel(id, patch)));
}, request);
}
-/** Deletes the channel and its episodes, stopping what they still render (finished videos stay in the Library). */
+/** Deletes the channel and its episodes, stopping what they still render (finished videos stay in the Library, or in an account's runs). */
export async function DELETE(request: Request, ctx: RouteContext<"/api/faceless/channels/[id]">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
return handle(async () => {
const { id } = await ctx.params;
- await deleteChannel(id);
+ await asViewer(viewer, () => deleteChannel(id));
return new Response(null, { status: 204 });
}, request);
}
diff --git a/src/app/api/faceless/channels/route.ts b/src/app/api/faceless/channels/route.ts
index f6bb07ad..106eba75 100644
--- a/src/app/api/faceless/channels/route.ts
+++ b/src/app/api/faceless/channels/route.ts
@@ -1,6 +1,9 @@
import { connection } from "next/server";
import { z } from "zod";
-import { body, createChannel, EngineSchema, GenreSchema, handle, listChannels } from "@/server/faceless";
+import { projectSavesLimited } from "@/server/account-projects";
+import { asViewer, guestRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { avatarRequest, body, createChannel, EngineSchema, GenreSchema, handle, listChannels, makeAvatar } from "@/server/faceless";
+import { planned } from "@/server/faceless-account";
const Create = z.object({
idea: z.string().trim().min(1, "Describe the channel first").max(500, "Keep the channel idea under 500 characters"),
@@ -10,16 +13,36 @@ const Create = z.object({
name: z.string().max(60).optional(),
});
-/** Your channels, newest first, with episode counts and the latest finished episode. */
-export async function GET() {
+/** Your channels, newest first, with episode counts and the latest finished episode: the owner's, or an account's own. */
+export async function GET(request: Request) {
await connection();
- return handle(() => Response.json({ items: listChannels() }));
+ const viewer = toolViewer(request);
+ return handle(() => Response.json({ items: asViewer(viewer, () => listChannels()) }));
}
-/** Create a channel (its name is written for you when you don't give one). */
+/**
+ * Create a channel (its name is written for you when you don't give one). A signed-in account's is its own (a reference
+ * link is kept as it is: the server never fetches a link for an account); its avatar
+ * is a picture on its own GPU or key, made after that run's checks (without one, the channel shows its initials and
+ * "Draw an avatar"). A guest signs up first.
+ */
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const limited = projectSavesLimited(viewer.account.id);
+ if (limited) return limited;
+ }
return handle(async () => {
const input = await body(request, Create, "Describe the channel and pick a genre");
- return Response.json(await createChannel(input), { status: 201 });
+ if (viewer.kind === "owner") return Response.json(await createChannel(input), { status: 201 });
+ const channel = await asViewer(viewer, () => createChannel(input));
+ const avatar = await runAccountTool(request, viewer.account, {
+ tool: "faceless",
+ files: [],
+ plan: () => planned(() => [{ request: avatarRequest(channel.id) }]),
+ start: () => makeAvatar(channel.id),
+ });
+ return Response.json(avatar.ok ? { ...channel, avatarJob: avatar.value.id } : channel, { status: 201 });
}, request);
}
diff --git a/src/app/api/faceless/episodes/[id]/[action]/route.ts b/src/app/api/faceless/episodes/[id]/[action]/route.ts
index 89f4b908..88ff1e10 100644
--- a/src/app/api/faceless/episodes/[id]/[action]/route.ts
+++ b/src/app/api/faceless/episodes/[id]/[action]/route.ts
@@ -1,4 +1,7 @@
-import { episodeView, handle, regenerateEpisode, renderEpisode, retryEpisode, rewriteEpisode, undoChange, upscaleEpisode } from "@/server/faceless";
+import type { GenerationRequest } from "@/lib/catalog/types";
+import { asViewer, guestRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { episodeView, graphFiles, graphToolSteps, handle, regenerateEpisode, renderEpisode, renderGraph, retryEpisode, retryGraph, rewriteEpisode, undoChange, upscaleEpisode, upscaleToolSteps } from "@/server/faceless";
+import { planned } from "@/server/faceless-account";
const ACTIONS = {
/** Render the reviewed script. */
@@ -15,12 +18,50 @@ const ACTIONS = {
regenerate: regenerateEpisode,
} as const;
+type Action = keyof typeof ACTIONS;
+type Work = { steps: { request: GenerationRequest; deps: number }[]; files: string[] };
+
+/** What an account's action runs, for its run's checks (the others make nothing new: a rewrite is the offline writer's). */
+const RUNS: Partial<Record<Action, (id: string) => Work>> = {
+ render: (id) => {
+ const g = renderGraph(id);
+ return { steps: graphToolSteps(g), files: graphFiles(g) };
+ },
+ retry: (id) => {
+ const g = retryGraph(id);
+ return { steps: graphToolSteps(g), files: graphFiles(g) };
+ },
+ upscale: (id) => ({ steps: upscaleToolSteps(id), files: [] }),
+};
+
+/**
+ * An episode's action. A signed-in account's, on its own episode: a render, a retry and an upscale run on its own GPU or
+ * key after the checks a studio run gets (src/server/account-tool-run.ts); a guest signs up first.
+ */
export async function POST(request: Request, ctx: RouteContext<"/api/faceless/episodes/[id]/[action]">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
return handle(async () => {
const { id, action } = await ctx.params;
- const run = ACTIONS[action as keyof typeof ACTIONS];
+ const run = ACTIONS[action as Action];
if (!run) return Response.json({ error: "Not found" }, { status: 404 });
- run(id);
- return Response.json(episodeView(id));
+ if (viewer.kind === "owner") {
+ run(id);
+ return Response.json(episodeView(id));
+ }
+ const checked = RUNS[action as Action];
+ const work = checked ? asViewer(viewer, () => checked(id)) : null;
+ if (!checked || !work?.steps.length) {
+ // Nothing new to run (an undo, a rewrite, an upscale made or making already): the action as it is.
+ return Response.json(
+ asViewer(viewer, () => {
+ run(id);
+ return episodeView(id);
+ }),
+ );
+ }
+ const out = await runAccountTool(request, viewer.account, { tool: "faceless", files: work.files, plan: () => planned(() => checked(id).steps), start: () => run(id) });
+ if (!out.ok) return out.response;
+ return Response.json({ ...asViewer(viewer, () => episodeView(id)), ...(out.gpuWarning && { gpuWarning: out.gpuWarning }) });
}, request);
}
diff --git a/src/app/api/faceless/episodes/[id]/change/route.ts b/src/app/api/faceless/episodes/[id]/change/route.ts
index cfa5422d..7203735d 100644
--- a/src/app/api/faceless/episodes/[id]/change/route.ts
+++ b/src/app/api/faceless/episodes/[id]/change/route.ts
@@ -1,16 +1,27 @@
-import { applyChange, body, ChangeSchema, episodeView, handle, previewChange } from "@/server/faceless";
+import { asViewer, guestRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { applyChange, body, ChangeSchema, changeGraph, episodeView, graphFiles, graphToolSteps, handle, previewChange } from "@/server/faceless";
+import { planned } from "@/server/faceless-account";
/**
* 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).
+ * the mix and the subtitles, or the narration). An account's change runs on its own GPU or key, after the checks a
+ * studio run gets (src/server/account-tool-run.ts).
*/
export async function POST(request: Request, ctx: RouteContext<"/api/faceless/episodes/[id]/change">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
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 });
+ if (!c.apply) return Response.json(asViewer(viewer, () => previewChange(id, c)));
+ if (viewer.kind === "owner") {
+ applyChange(id, c);
+ return Response.json(episodeView(id), { status: 201 });
+ }
+ const graph = asViewer(viewer, () => changeGraph(id, c));
+ const out = await runAccountTool(request, viewer.account, { tool: "faceless", files: graphFiles(graph), plan: () => planned(() => graphToolSteps(changeGraph(id, c))), start: () => applyChange(id, c) });
+ if (!out.ok) return out.response;
+ return Response.json({ ...asViewer(viewer, () => episodeView(id)), ...(out.gpuWarning && { gpuWarning: out.gpuWarning }) }, { status: 201 });
}, request);
}
diff --git a/src/app/api/faceless/episodes/[id]/route.ts b/src/app/api/faceless/episodes/[id]/route.ts
index 44d0aaaa..dd630c4e 100644
--- a/src/app/api/faceless/episodes/[id]/route.ts
+++ b/src/app/api/faceless/episodes/[id]/route.ts
@@ -1,6 +1,9 @@
import { connection } from "next/server";
import { z } from "zod";
+import { projectSavesLimited } from "@/server/account-projects";
+import { asViewer, guestRun, toolViewer } from "@/server/account-tool-run";
import { BlockSchema, body, deleteEpisode, episodeView, handle, SettingsSchema, updateEpisode } from "@/server/faceless";
+import { filesRefused, settingsFiles } from "@/server/faceless-account";
const Patch = z.object({
title: z.string().max(120).optional(),
@@ -9,30 +12,47 @@ const Patch = z.object({
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]">) {
+/** The episode with every step's generation, its progress, spend and estimate: the owner's, or an account's own. */
+export async function GET(request: Request, ctx: RouteContext<"/api/faceless/episodes/[id]">) {
await connection();
+ const viewer = toolViewer(request);
return handle(async () => {
const { id } = await ctx.params;
- return Response.json(episodeView(id));
+ return Response.json(asViewer(viewer, () => episodeView(id)));
});
}
-/** Rename, like, or (before rendering) edit the script and settings. */
+/** Rename, like, or (before rendering) edit the script and settings. An account's files must be its own. */
export async function PATCH(request: Request, ctx: RouteContext<"/api/faceless/episodes/[id]">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const limited = projectSavesLimited(viewer.account.id);
+ if (limited) return limited;
+ }
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));
+ if (viewer.kind === "account") {
+ const refused = filesRefused(viewer.account.id, settingsFiles(patch.settings));
+ if (refused) return refused;
+ }
+ return Response.json(
+ asViewer(viewer, () => {
+ updateEpisode(id, patch);
+ return episodeView(id);
+ }),
+ );
}, request);
}
-/** Deletes the episode and stops what it still renders (its finished videos stay in the Library). */
+/** Deletes the episode and stops what it still renders (its finished videos stay in the Library, or in an account's runs). */
export async function DELETE(request: Request, ctx: RouteContext<"/api/faceless/episodes/[id]">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
return handle(async () => {
const { id } = await ctx.params;
- await deleteEpisode(id);
+ await asViewer(viewer, () => deleteEpisode(id));
return new Response(null, { status: 204 });
}, request);
}
diff --git a/src/app/api/faceless/episodes/route.ts b/src/app/api/faceless/episodes/route.ts
index 00e3becf..fc4394aa 100644
--- a/src/app/api/faceless/episodes/route.ts
+++ b/src/app/api/faceless/episodes/route.ts
@@ -2,7 +2,10 @@ import { connection } from "next/server";
import { z } from "zod";
import { CF_LENGTH_VALUES } from "@/lib/catalog/content-factory";
import { FACELESS_LENGTHS, MAX_SCRIPT, MAX_TOPIC } from "@/lib/catalog/faceless";
-import { body, createEpisode, FacelessError, getChannel, handle, listEpisodes, SettingsSchema } from "@/server/faceless";
+import { projectSavesLimited } from "@/server/account-projects";
+import { asViewer, guestRun, toolViewer } from "@/server/account-tool-run";
+import { body, composeScript, createEpisode, FacelessError, getChannel, handle, listEpisodes, SettingsSchema } from "@/server/faceless";
+import { filesRefused, settingsFiles } from "@/server/faceless-account";
const Create = z.object({
channelId: z.string().max(40),
@@ -13,22 +16,45 @@ const Create = z.object({
saveLook: z.boolean().optional(),
});
-/** Episodes, newest first (`?channel=` for one channel). */
+/** Episodes, newest first (`?channel=` for one channel): the owner's, or an account's own. */
export async function GET(request: Request) {
await connection();
+ const viewer = toolViewer(request);
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 }) });
+ return Response.json({ items: asViewer(viewer, () => 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. */
+/**
+ * A new episode: the script is written (or your pasted script split into scenes) in the background, then it waits for
+ * your review. An account's is written at once, in its own channel, with only its own files; it renders on its own GPU
+ * or key once it is reviewed (the render route's checks). A guest signs up first.
+ */
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const limited = projectSavesLimited(viewer.account.id);
+ if (limited) return limited;
+ }
return handle(async () => {
const input = await body(request, Create, "Pick a topic and the video settings");
- // A Content Factory channel (its settings carry a style brief) also makes 30-second episodes.
- const lengths = getChannel(input.channelId)?.settings.brief ? CF_LENGTH_VALUES : FACELESS_LENGTHS;
- if (!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, saveLook: input.saveLook }), { status: 201 });
+ if (viewer.kind === "account") {
+ const refused = filesRefused(viewer.account.id, settingsFiles(input.settings));
+ if (refused) return refused;
+ }
+ return asViewer(viewer, async () => {
+ // A Content Factory channel (its settings carry a style brief) also makes 30-second episodes.
+ const channel = getChannel(input.channelId);
+ if (!channel) throw new FacelessError("Channel not found", 404);
+ const lengths = channel.settings.brief ? CF_LENGTH_VALUES : FACELESS_LENGTHS;
+ if (!lengths.includes(input.settings.length)) throw new FacelessError("Choose one of the offered video lengths");
+ const ask = { kind: "faceless" as const, channelId: input.channelId, topic: input.topic, script: input.script, settings: input.settings, saveLook: input.saveLook };
+ if (viewer.kind === "owner") return Response.json(createEpisode(ask), { status: 201 });
+ if (!input.topic.trim() && !input.script?.trim()) throw new FacelessError("Add a topic, or bring your own script");
+ const composed = await composeScript({ kind: "faceless", channelId: input.channelId, topic: input.topic.trim(), settings: input.settings, sources: [] }, input.script?.trim() ?? "");
+ return Response.json(createEpisode({ ...ask, composed }), { status: 201 });
+ });
}, request);
}
diff --git a/src/app/api/faceless/estimate/route.ts b/src/app/api/faceless/estimate/route.ts
index e71be54b..e969a284 100644
--- a/src/app/api/faceless/estimate/route.ts
+++ b/src/app/api/faceless/estimate/route.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
+import { priceAsRun } from "@/server/account-tool-run";
import { BlockSchema, body, estimateEpisode, GenreSchema, handle, SettingsSchema } from "@/server/faceless";
-import { priceAs } from "@/server/visitor";
const Ask = z.object({
kind: z.enum(["faceless", "explainer"]),
@@ -9,12 +9,11 @@ const Ask = z.object({
genre: GenreSchema.optional(),
});
-/** What an episode would cost (by part), whether it runs as a demo, and what's in the way. */
-async function post(request: Request) {
- return handle(async () => Response.json(estimateEpisode(await body(request, Ask, "Those settings aren't valid"))));
-}
-
-/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+/**
+ * What an episode would cost (by part), whether it runs as a demo, and what's in the way. A visitor (public sign-up)
+ * gets the price of its run as it would go: an account's on its own GPU or its own key, a guest's on the open engine;
+ * never a demo (src/server/account-tool-run.ts priceAsRun).
+ */
export async function POST(request: Request) {
- return priceAs(request, () => post(request));
+ return priceAsRun(request, () => 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
index e52918e6..bf59d853 100644
--- a/src/app/api/faceless/topics/route.ts
+++ b/src/app/api/faceless/topics/route.ts
@@ -1,4 +1,5 @@
import { z } from "zod";
+import { asViewer, guestRun, toolViewer } from "@/server/account-tool-run";
import { body, EngineSchema, GenreSchema, getChannel, handle, suggestTopics } from "@/server/faceless";
const Ask = z.object({
@@ -10,14 +11,21 @@ const Ask = z.object({
round: z.number().int().min(0).max(50).optional(),
});
-/** 4–6 episode topics for a channel (the install's LLM, or templates offline). */
+/**
+ * 4–6 episode topics for a channel (the install's LLM, or templates offline). An account's are the offline ones, for
+ * its own channel; a guest signs up first.
+ */
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
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 }));
+ return asViewer(viewer, async () => {
+ 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 }));
+ });
}, request);
}
diff --git a/src/app/api/faceless/voices/preview/route.ts b/src/app/api/faceless/voices/preview/route.ts
index 79078880..7fdf4a44 100644
--- a/src/app/api/faceless/voices/preview/route.ts
+++ b/src/app/api/faceless/voices/preview/route.ts
@@ -1,12 +1,24 @@
import { z } from "zod";
-import { body, handle, voicePreview } from "@/server/faceless";
+import { asViewer, guestRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { body, handle, voicePreview, voicePreviewPlan } from "@/server/faceless";
+import { planned } from "@/server/faceless-account";
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. */
+/**
+ * A short sample of a premade narrator voice: one speech generation, reused once it exists. An account's is its own
+ * (on its own key, after the checks a studio run gets), reused for it only; a guest signs up first.
+ */
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
return handle(async () => {
const { id } = await body(request, Ask, "Pick a voice");
- return Response.json(voicePreview({ kind: "preset", id }));
+ const voice = { kind: "preset" as const, id };
+ if (viewer.kind === "owner") return Response.json(voicePreview(voice));
+ const p = asViewer(viewer, () => voicePreviewPlan(voice));
+ if ("made" in p) return Response.json(p.made);
+ const out = await runAccountTool(request, viewer.account, { tool: "faceless", files: [], plan: () => planned(() => [{ request: p.request }]), start: () => voicePreview(voice) });
+ return out.ok ? Response.json(out.value) : out.response;
}, request);
}
diff --git a/src/app/api/starters/[id]/route.ts b/src/app/api/starters/[id]/route.ts
index 78aeb2d9..e54404a6 100644
--- a/src/app/api/starters/[id]/route.ts
+++ b/src/app/api/starters/[id]/route.ts
@@ -10,16 +10,17 @@ const Body = z.object({ engine: z.enum(["cloud", "open"]).default("cloud") });
/**
* The owner's "Use template" on a ready-made starter: makes it (a channel set up for its first episode, a brand kit with
- * its product) and answers `{ href }`, where it opens. A signed-in account makes Cinema Studio's ready films only, each
- * as its own project (src/server/cinema.ts); the rest are saved to the owner's library (403 for an account). A guest
- * signs up first.
+ * its product) and answers `{ href }`, where it opens. A signed-in account makes Cinema Studio's ready films and Faceless
+ * Studio's ready channels, each as its own project (src/server/cinema.ts, faceless.ts); the rest are saved to the
+ * owner's library (403 for an account). A guest signs up first.
*/
export async function POST(request: Request, { params }: RouteContext<"/api/starters/[id]">) {
const { id } = await params;
const viewer = toolViewer(request);
if (viewer.kind === "guest") return guestRun();
if (viewer.kind === "account") {
- if (getStarter(id)?.seed.kind !== "cinema") return Response.json({ error: LIBRARY_MESSAGE, code: "library" }, { status: 403 });
+ const kind = getStarter(id)?.seed.kind;
+ if (kind !== "cinema" && kind !== "faceless") return Response.json({ error: LIBRARY_MESSAGE, code: "library" }, { status: 403 });
const limited = projectSavesLimited(viewer.account.id);
if (limited) return limited;
}
diff --git a/src/components/content-factory/home.tsx b/src/components/content-factory/home.tsx
index dd7a6915..a9db718e 100644
--- a/src/components/content-factory/home.tsx
+++ b/src/components/content-factory/home.tsx
@@ -15,11 +15,10 @@ import { EngineSwitch } from "@/components/studio/engine-switch";
import { Segmented, usd } from "@/components/faceless/controls";
import { NarratorChip } from "@/components/faceless/narrator";
import { StyleArt } from "@/components/faceless/style-art";
-import { SelfHostNote } from "@/components/self-host-note";
import { StarterParam } from "@/components/starters/starter-param";
import { StarterSection, useStarters } from "@/components/starters/starter-section";
import { useEdgeFade } from "@/components/studio/use-edge-fade";
-import { uploadFile, useEngine, useHydrated, useIsOwner, useLikelyVisitor } from "@/lib/api";
+import { uploadFile, useAskBeforeUpload, useEngine, useHydrated, useIsOwner } from "@/lib/api";
import {
ANIMATION_STYLES,
CF_LENGTHS,
@@ -95,8 +94,9 @@ export function ContentFactoryHome({ voices, starters: given = [], fills: givenF
const [example, setExample] = useState(0);
// The estimate's problem (no narrator voice yet…) is a hint until Generate is pressed.
const [tried, setTried] = useState(false);
- // A series doesn't run on an account's own GPU yet (only the studios' generations do): said here, not after Generate.
- const visitor = useLikelyVisitor();
+ // A clip of your own: a guest is asked to sign up first, and an account with neither its own GPU nor its own key to
+ // connect one (reading it runs there).
+ const askFirst = useAskBeforeUpload();
const [exampleRow, exampleFade] = useEdgeFade<HTMLDivElement>();
const file = useRef<HTMLInputElement>(null);
const promptRef = useRef<HTMLTextAreaElement>(null);
@@ -218,7 +218,7 @@ export function ContentFactoryHome({ voices, starters: given = [], fills: givenF
// One run at a time: a second Enter (or click) before the first request has re-rendered would plan, make and bill it twice.
const submitting = useRef(false);
const submit = async () => {
- if (submitting.current || visitor) return;
+ if (submitting.current) return;
setTried(true);
if (blocker) {
toast(blocker, { id: "cf-blocker" });
@@ -266,10 +266,10 @@ export function ContentFactoryHome({ voices, starters: given = [], fills: givenF
options={[
{ value: "here", label: "Generate here", hint: "Fuobe makes the episodes now" },
// Handing the brief to Claude Code needs Fuobe's own MCP server: the owner's.
- ...(visitor ? [] : [{ value: "claude" as const, label: "Generate in Claude", hint: "Copy a prompt for Claude Code with Fuobe's MCP server" }]),
+ ...(!owner ? [] : [{ value: "claude" as const, label: "Generate in Claude", hint: "Copy a prompt for Claude Code with Fuobe's MCP server" }]),
]}
/>
- <span className="text-[12px] text-muted-foreground">{mode === "claude" ? "Claude writes them and runs Fuobe over MCP" : visitor ? "Makes the episodes now" : engine === "open" ? "Makes the episodes now, on your ComfyUI" : "Makes the episodes now, with your providers"}</span>
+ <span className="text-[12px] text-muted-foreground">{mode === "claude" ? "Claude writes them and runs Fuobe over MCP" : engine === "open" ? "Makes the episodes now, on your ComfyUI" : "Makes the episodes now, with your providers"}</span>
</div>
{/* The reference: the brief every episode follows */}
@@ -289,35 +289,36 @@ export function ContentFactoryHome({ voices, starters: given = [], fills: givenF
<ReferenceCard reference={{ kind: "preset", presetId: preset.id, title: `Preset: ${preset.name}` }} analysis={null} styleId={preset.brief.styleId} />
) : null}
<div className="flex flex-wrap items-center gap-1.5">
- {/* A guest's or an account's clip would be uploaded and read for a series that can't start here. */}
<button
type="button"
- onClick={() => file.current?.click()}
- disabled={uploading || create.isPending || visitor}
+ onClick={() => askFirst() || file.current?.click()}
+ disabled={uploading || create.isPending}
className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary px-3 text-[13px] font-medium hover:bg-accent disabled:opacity-60"
>
{uploading ? <Loader2 className="size-3.5 animate-spin" /> : <Upload className="size-3.5" />}
{uploading ? "Uploading…" : view?.reference?.url ? "Change video" : "Add a video"}
</button>
- <button
- type="button"
- onClick={() => setLinkOpen((v) => !v)}
- disabled={visitor}
- aria-expanded={linkOpen && !visitor}
- aria-controls={ids.link}
- className={cn("inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium disabled:opacity-60", linkOpen && !visitor ? "bg-brand-faint text-brand-text" : "bg-secondary hover:bg-accent")}
- >
- <Link2 className="size-3.5" /> TikTok or Instagram link
- </button>
+ {/* A link is fetched by the studio's server: the owner's. A visitor adds the clip itself. */}
+ {owner && (
+ <button
+ type="button"
+ onClick={() => setLinkOpen((v) => !v)}
+ aria-expanded={linkOpen}
+ aria-controls={ids.link}
+ className={cn("inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium disabled:opacity-60", linkOpen ? "bg-brand-faint text-brand-text" : "bg-secondary hover:bg-accent")}
+ >
+ <Link2 className="size-3.5" /> TikTok or Instagram link
+ </button>
+ )}
<a href="#presets" className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary px-3 text-[13px] font-medium hover:bg-accent">
<Sparkles className="size-3.5" /> Presets
</a>
<span className="text-[12px] text-muted-foreground">
- {engine === "open" ? (visitor ? "We study the clip's pacing and look" : "Reading a clip is free (Gemma 4 on your ComfyUI)") : perMinute > 0 ? `Reading a clip costs about ${usd(perMinute)} a minute` : "Reading a clip makes a free placeholder"}
+ {engine === "open" ? "Reading a clip is free (Gemma 4 on your ComfyUI)" : perMinute > 0 ? `Reading a clip costs about ${usd(perMinute)} a minute` : "Reading a clip makes a free placeholder"}
</span>
<input ref={file} type="file" accept="video/mp4,video/quicktime,video/webm,.mp4,.mov,.m4v,.webm" hidden onChange={(e) => (void onFile(e.target.files?.[0]), (e.target.value = ""))} />
</div>
- {linkOpen && !visitor && (
+ {linkOpen && owner && (
<div id={ids.link} className="space-y-1.5 rounded-2xl bg-muted/60 p-2.5">
<form
className="flex min-w-0 items-center gap-2"
@@ -469,20 +470,15 @@ export function ContentFactoryHome({ voices, starters: given = [], fills: givenF
Review scripts first
</label>
)}
- <Button onClick={() => void submit()} disabled={busy || visitor} className="ml-auto h-9 rounded-full px-4">
+ <Button onClick={() => void submit()} disabled={busy} className="ml-auto h-9 rounded-full px-4">
{busy ? <Loader2 className="animate-spin" /> : mode === "here" ? <ArrowRight /> : <Bot />}
{busy ? "Planning your episodes…" : mode === "here" ? (episodes > 1 ? `Generate ${episodes} episodes` : "Generate") : "Get the prompt"}
</Button>
</div>
- {visitor ? (
- <SelfHostNote className="mt-2">Content Factory isn&apos;t available here.</SelfHostNote>
- ) : (
- mode === "here" &&
- est?.error && (
- <p role={tried ? "alert" : undefined} className={cn("mt-2 text-[12px]", tried ? "text-destructive" : "text-muted-foreground")}>
- {est.error}
- </p>
- )
+ {mode === "here" && est?.error && (
+ <p role={tried ? "alert" : undefined} className={cn("mt-2 text-[12px]", tried ? "text-destructive" : "text-muted-foreground")}>
+ {est.error}
+ </p>
)}
{blocker && prompt.trim() && (
<p className="mt-2 text-[12px] text-muted-foreground" aria-live="polite">
diff --git a/src/components/content-factory/hooks.ts b/src/components/content-factory/hooks.ts
index 7ca0bd0c..9b2b8e22 100644
--- a/src/components/content-factory/hooks.ts
+++ b/src/components/content-factory/hooks.ts
@@ -4,6 +4,7 @@ import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tansta
import type { ClaudePrompt, SeriesCard, SeriesEstimate, SeriesSettings, SeriesView, StyleBrief } from "@/lib/catalog/content-factory";
import type { NarratorVoice } from "@/lib/catalog/faceless";
import type { Engine } from "@/lib/catalog/types";
+import { COMPUTER_KICK_EVENT } from "@/lib/api";
import { responseError } from "@/lib/refusals";
import { useDebounced } from "@/components/faceless/hooks";
@@ -25,8 +26,16 @@ async function json<T>(res: Response): Promise<T> {
return body;
}
-const send = async <T,>(url: string, method: string, body?: unknown) =>
- json<T>(await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }));
+/** POSTs that only ask (a price, a message): nothing runs. */
+const ASKS = /\/(estimate|claude)$/;
+
+const send = async <T,>(url: string, method: string, body?: unknown) => {
+ const out = await json<T>(await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }));
+ // A run may have started (a render, a reading, a picture): the tab that runs this person's jobs on the ComfyUI on this
+ // computer (an account's "Your GPU") asks for them at once, as after a studio run.
+ if (method === "POST" && !ASKS.test(url) && !(url.endsWith("/change") && !(body as { apply?: boolean } | undefined)?.apply)) window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));
+ return out;
+};
export type ReferenceInput = { kind: "upload"; url: string; title?: string } | { kind: "link"; link: string } | { kind: "preset"; presetId: string };
diff --git a/src/components/content-factory/parts.tsx b/src/components/content-factory/parts.tsx
index 15d7ca20..71e154f3 100644
--- a/src/components/content-factory/parts.tsx
+++ b/src/components/content-factory/parts.tsx
@@ -25,7 +25,6 @@ import {
} from "@/lib/catalog/content-factory";
import { formatLength } from "@/lib/catalog/faceless";
import type { Engine } from "@/lib/catalog/types";
-import { useLikelyVisitor } from "@/lib/api";
import { copyText } from "@/lib/clipboard";
import { templateCover } from "@/lib/template-covers";
import { cn } from "@/lib/utils";
@@ -297,15 +296,13 @@ export function PresetTile({ p, on, tabStop, onPick }: { p: StylePreset; on: boo
// The price
/**
- * "≈ $4.20 · 3 episodes × $1.40" / "Placeholder · free" / "Free · your GPU", with the research's pricing note. A guest or an
- * account reads "Not available here" for the open engine: a series doesn't run on their own GPU yet.
+ * "≈ $4.20 · 3 episodes × $1.40" / "Placeholder · free" / "Free · your GPU", with the research's pricing note.
*/
export function SeriesPriceLine({ data, loading, engine, className }: { data: SeriesEstimate | undefined; loading?: boolean; engine: Engine; className?: string }) {
- const visitor = useLikelyVisitor();
if (!data) return <span className={cn("inline-flex items-center gap-1.5 font-mono text-[12px] text-muted-foreground", className)}>{loading && <Loader2 className="size-3 animate-spin" />}Estimating…</span>;
const p = data.price;
const each = p.episodes > 1 ? ` · ${p.episodes} × ${usd(p.perEpisode)}` : "";
- const price = visitor && (data.demo || engine === "open") ? "Not available here" : data.demo ? "Placeholder · free" : engine === "open" ? "Free · your GPU" : `≈ ${usd(p.total)}${p.unknown ? "+" : ""}${each}`;
+ const price = data.demo ? "Placeholder · free" : engine === "open" ? "Free · your GPU" : `≈ ${usd(p.total)}${p.unknown ? "+" : ""}${each}`;
return (
<span className={cn("inline-flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5", className)}>
<Popover>
@@ -317,7 +314,7 @@ export function SeriesPriceLine({ data, loading, engine, className }: { data: Se
</PopoverTrigger>
<PopoverContent className="w-72 p-3 text-[13px]" collisionPadding={12}>
<p className="font-medium">How the price works</p>
- <p className="mt-1 text-[12px] text-muted-foreground">{data.demo ? "Some steps aren't connected, so this run makes placeholder results." : engine === "open" ? (visitor ? "Content Factory isn't available here." : "Every step runs on your own ComfyUI, free.") : PRICE_NOTE}</p>
+ <p className="mt-1 text-[12px] text-muted-foreground">{data.demo ? "Some steps aren't connected, so this run makes placeholder results." : engine === "open" ? "Every step runs on your own ComfyUI, free." : PRICE_NOTE}</p>
{!data.demo && engine === "cloud" && p.episodes > 1 && (
<p className="mt-2 font-mono text-[12px] tabular-nums">
{p.episodes} episodes × {usd(p.perEpisode)} = {usd(p.total)}
diff --git a/src/components/explainer/explainer-studio.tsx b/src/components/explainer/explainer-studio.tsx
index 545f2cb8..078e6e5e 100644
--- a/src/components/explainer/explainer-studio.tsx
+++ b/src/components/explainer/explainer-studio.tsx
@@ -15,10 +15,9 @@ import { EngineSwitch } from "@/components/studio/engine-switch";
import { grabFrames } from "@/components/restore/hooks";
import { OldFootageOffer } from "@/components/restore/old-footage";
import { fileToSlot } from "@/components/studio/media-slot";
-import { SelfHostNote } from "@/components/self-host-note";
import { StarterParam } from "@/components/starters/starter-param";
import { StarterSection, useStarters } from "@/components/starters/starter-section";
-import { useEngine, useIsOwner, useLikelyVisitor } from "@/lib/api";
+import { useAskBeforeUpload, useEngine, useIsOwner } from "@/lib/api";
import {
ANIMATION_MODES,
AUTO_SECONDS,
@@ -158,8 +157,9 @@ export function ExplainerStudio({ picker, starters: given = [], fills: givenFill
const { starters, fills } = useStarters("explainer", given, givenFills);
const router = useRouter();
const [engine, setEngine] = useEngine();
- // An explainer doesn't run on an account's own GPU yet (only the studios' generations do): said here, not after Generate.
- const visitor = useLikelyVisitor();
+ // Files of your own: a guest is asked to sign up first, and an account with neither its own GPU nor its own key to
+ // connect one (an explainer renders there).
+ const askFirst = useAskBeforeUpload();
// The estimate's problem (no narrator voice yet…) is a hint until Generate is pressed.
const [tried, setTried] = useState(false);
const genre = genreInfo("education");
@@ -291,7 +291,6 @@ export function ExplainerStudio({ picker, starters: given = [], fills: givenFill
};
const generate = () => {
- if (visitor) return;
setTried(true);
if (!prompt.trim() && !sources.length) return void toast("Add a prompt, or attach a file or link", { id: "faceless-blocker" });
if (manualBad) return void toast("Duration must be Auto or a whole number of seconds between 15 and 600", { id: "faceless-blocker" });
@@ -314,7 +313,7 @@ export function ExplainerStudio({ picker, starters: given = [], fills: givenFill
<header className="max-md:sticky top-chrome z-20 flex h-14 items-center gap-2 bg-background/85 px-4 backdrop-blur sm:px-6">
<h1 className="truncate font-heading text-[22px] leading-none">Explainer</h1>
<div className="ml-auto">
- <EngineSwitch value={engine} onChange={setEngine} selfHostedOnly />
+ <EngineSwitch value={engine} onChange={setEngine} />
</div>
<PhoneNavButton />
</header>
@@ -366,12 +365,13 @@ export function ExplainerStudio({ picker, starters: given = [], fills: givenFill
))}
<button
type="button"
- onClick={() => (sources.length >= MAX_SOURCES ? toast("Up to 3 sources per video — remove one to add another") : file.current?.click())}
+ onClick={() => (sources.length >= MAX_SOURCES ? toast("Up to 3 sources per video — remove one to add another") : askFirst() || file.current?.click())}
className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary px-3 text-[13px] font-medium hover:bg-accent"
>
<Paperclip className="size-3.5" /> Attach a file
</button>
- <LinkPopover engine={engine} disabled={sources.length >= MAX_SOURCES} onAdd={(s) => setSources((xs) => [...xs, s].slice(0, MAX_SOURCES))} />
+ {/* A link is read by the studio's server: the owner's. A visitor attaches the file or pastes the words. */}
+ {owner && <LinkPopover engine={engine} disabled={sources.length >= MAX_SOURCES} onAdd={(s) => setSources((xs) => [...xs, s].slice(0, MAX_SOURCES))} />}
<input
ref={file}
type="file"
@@ -452,11 +452,10 @@ export function ExplainerStudio({ picker, starters: given = [], fills: givenFill
<div className="mt-3 flex flex-wrap items-center gap-3">
<EstimateLine data={estimate.data} loading={estimate.isFetching} engine={engine} className="min-w-0 flex-1" quiet={!tried} />
- <Button onClick={generate} disabled={create.isPending || visitor} className="rounded-full">
+ <Button onClick={generate} disabled={create.isPending} className="rounded-full">
{create.isPending ? <Loader2 className="animate-spin" /> : <Sparkles />} Generate
</Button>
</div>
- {visitor && <SelfHostNote className="mt-2">Explainer videos aren&apos;t available here.</SelfHostNote>}
</div>
<ol className="mt-6 grid gap-2 sm:grid-cols-3 lg:grid-cols-1" aria-label="How it works">
diff --git a/src/components/faceless/controls.tsx b/src/components/faceless/controls.tsx
index d1d60738..3e425dbc 100644
--- a/src/components/faceless/controls.tsx
+++ b/src/components/faceless/controls.tsx
@@ -7,7 +7,6 @@ import { Switch } from "@/components/ui/switch";
import { radioKeys, radioTab } from "@/components/studio/radio-keys";
import { formatLength, PART_LABELS, type EstimateResult, type StepPart } from "@/lib/catalog/faceless";
import type { Engine } from "@/lib/catalog/types";
-import { useLikelyVisitor } from "@/lib/api";
import { cn } from "@/lib/utils";
/** A segmented control (Liner style: muted track, white thumb), keyboard like a radio group. */
@@ -78,14 +77,13 @@ export const usd = (n: number) => (n >= 10 ? `$${n.toFixed(0)}` : `$${n.toFixed(
/**
* "≈ $7.02" / "Placeholder · free" / "Free · your GPU", with what it's made of in a popover. quiet: the estimate's problem (no
- * narrator voice yet…) is a plain hint, not a warning: nothing has been asked of the visitor yet. A guest or an account
- * reads "Not available here" for the open engine: Faceless and Explainer don't run on their own GPU yet.
+ * narrator voice yet…) is a plain hint, not a warning: nothing has been asked of the visitor yet. The open engine runs on
+ * the viewer's own GPU (an account's own ComfyUI), free.
*/
export function EstimateLine({ data, loading, engine, className, quiet }: { data: EstimateResult | undefined; loading?: boolean; engine: Engine; className?: string; quiet?: boolean }) {
const [open, setOpen] = useState(false);
- const visitor = useLikelyVisitor();
if (!data) return <span className={cn("inline-flex items-center gap-1.5 font-mono text-[12px] text-muted-foreground", className)}>{loading && <Loader2 className="size-3 animate-spin" />}Estimating…</span>;
- const price = visitor && (data.demo || engine === "open") ? "Not available here" : data.demo ? "Placeholder · free" : engine === "open" ? "Free · your GPU" : `≈ ${usd(data.estimate.total)}${data.estimate.unknown ? "+" : ""}`;
+ const price = data.demo ? "Placeholder · free" : engine === "open" ? "Free · your GPU" : `≈ ${usd(data.estimate.total)}${data.estimate.unknown ? "+" : ""}`;
const parts = Object.entries(data.estimate.parts).filter(([, v]) => (v ?? 0) > 0) as [StepPart, number][];
const notes = !data.error ? (data.notes ?? []) : [];
return (
diff --git a/src/components/faceless/episode-view.tsx b/src/components/faceless/episode-view.tsx
index 37163d98..dae905e5 100644
--- a/src/components/faceless/episode-view.tsx
+++ b/src/components/faceless/episode-view.tsx
@@ -56,7 +56,7 @@ import {
type StepView,
} from "@/lib/catalog/faceless";
import type { Generation } from "@/lib/catalog/types";
-import { useEngineMode, useIsVisitor } from "@/lib/api";
+import { useEngineMode } from "@/lib/api";
import { FACELESS_REGEN_COPY } from "@/lib/catalog/faceless";
import { timeAgo } from "@/lib/format";
import { downloadHref, downloadName } from "@/lib/library";
@@ -223,8 +223,6 @@ const PART_OPTIONS: { value: ChangePart; label: string }[] = [
/** Change the selected scenes: describe the change, see what re-runs and the price, apply or discard. */
function SceneEditor({ view, scenes, onClose, onOpen }: { view: View; scenes: SceneRow[]; onClose: () => void; onOpen: (g: Generation) => void }) {
const ep = view.episode;
- // A guest or an account: the open engine runs on a self-hosted Fuobe only (not on their own GPU yet).
- const visitor = useIsVisitor();
const [part, setPart] = useState<ChangePart>("picture");
const [instruction, setInstruction] = useState("");
const [lines, setLines] = useState<string[]>(() => scenes.map((s) => s.narration));
@@ -351,7 +349,7 @@ function SceneEditor({ view, scenes, onClose, onOpen }: { view: View; scenes: Sc
: preview.isError
? (preview.error as Error).message
: preview.data
- ? `Re-renders ${preview.data.labels.length} step${preview.data.labels.length === 1 ? "" : "s"} (${stepWords(preview.data.labels)})${preview.data.retime ? ", plus any scene whose timing moves" : ""} · ${preview.data.demo ? "Placeholder · free" : ep.settings.engine === "open" ? (visitor ? "Not available here" : "Free · your GPU") : preview.data.costUsd === null ? "price unknown" : `≈ ${usd(preview.data.costUsd)}${preview.data.retime ? "+" : ""}`}`
+ ? `Re-renders ${preview.data.labels.length} step${preview.data.labels.length === 1 ? "" : "s"} (${stepWords(preview.data.labels)})${preview.data.retime ? ", plus any scene whose timing moves" : ""} · ${preview.data.demo ? "Placeholder · free" : ep.settings.engine === "open" ? "Free · your GPU" : preview.data.costUsd === null ? "price unknown" : `≈ ${usd(preview.data.costUsd)}${preview.data.retime ? "+" : ""}`}`
: "Pricing…"}
</p>
<Button variant="ghost" onClick={discard} disabled={!draft}>
diff --git a/src/components/faceless/episode-wizard.tsx b/src/components/faceless/episode-wizard.tsx
index 1e0a60b8..beefa91c 100644
--- a/src/components/faceless/episode-wizard.tsx
+++ b/src/components/faceless/episode-wizard.tsx
@@ -11,7 +11,7 @@ import { Skeleton } from "@/components/ui/skeleton";
import { NotFoundState } from "@/components/empty-state";
import { EngineSwitch } from "@/components/studio/engine-switch";
import { radioKeys, radioTab } from "@/components/studio/radio-keys";
-import { useEngine } from "@/lib/api";
+import { useEngine, useIsOwner } from "@/lib/api";
import {
defaultVoice,
FACELESS_STYLE_IDS,
@@ -70,6 +70,8 @@ export function EpisodeWizard({ channelId, picker, initialTopic }: { channelId:
const [step, setStep] = useState<1 | 2>(1);
const [topics, setTopics] = useState<TopicIdea[] | null>(null);
const [offline, setOffline] = useState(false);
+ // Suggestions written offline say how to get fresher ones: the studio's AI helper, which only its owner sets up.
+ const owner = useIsOwner();
const [round, setRound] = useState(0);
const [loadingTopics, setLoadingTopics] = useState(false);
const [picked, setPicked] = useState<string | null>(null);
@@ -211,7 +213,7 @@ export function EpisodeWizard({ channelId, picker, initialTopic }: { channelId:
<section aria-label="Topic suggestions" className="space-y-3">
<div className="flex flex-wrap items-center justify-between gap-2">
- <p className={cn("text-[13px] text-muted-foreground", loadingTopics && "shimmer-text animate-shimmer-text")}>{loadingTopics ? "Writing topic suggestions…" : offline ? "Suggestions written offline — connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings for fresher ones." : "Tick one, or write your own below."}</p>
+ <p className={cn("text-[13px] text-muted-foreground", loadingTopics && "shimmer-text animate-shimmer-text")}>{loadingTopics ? "Writing topic suggestions…" : offline && owner ? "Suggestions written offline — connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings for fresher ones." : "Tick one, or write your own below."}</p>
<Button
variant="outline"
size="sm"
diff --git a/src/components/faceless/faceless-home.tsx b/src/components/faceless/faceless-home.tsx
index f5ba97d2..2ef3840e 100644
--- a/src/components/faceless/faceless-home.tsx
+++ b/src/components/faceless/faceless-home.tsx
@@ -9,10 +9,9 @@ import { PhoneNavButton } from "@/components/nav/phone-nav-button";
import { Skeleton } from "@/components/ui/skeleton";
import { EngineSwitch } from "@/components/studio/engine-switch";
import { radioKeys, radioTab } from "@/components/studio/radio-keys";
-import { SelfHostNote } from "@/components/self-host-note";
import { useEdgeFade } from "@/components/studio/use-edge-fade";
import { StarterSection, useStarters } from "@/components/starters/starter-section";
-import { useEngine, useIsOwner, useLikelyVisitor } from "@/lib/api";
+import { useEngine, useIsOwner } from "@/lib/api";
import { GENRE_IDEAS, GENRES, MAX_IDEA, MAX_SCRIPT, wordCount, youtubeKind, YOUTUBE_ERROR, type FacelessGenre } from "@/lib/catalog/faceless";
import { starterShown, type StarterCardData } from "@/lib/starters/types";
import { cn } from "@/lib/utils";
@@ -47,8 +46,6 @@ export function FacelessHome({ starters: given = [] }: { starters?: StarterCardD
const g = GENRES.find((x) => x.id === genre)!;
const [genreRow, genreFade] = useEdgeFade<HTMLDivElement>();
const [ideaRow, ideaFade] = useEdgeFade<HTMLDivElement>();
- // A channel doesn't run on an account's own GPU yet (only the studios' generations do): said here, not after Next.
- const visitor = useLikelyVisitor();
const owner = useIsOwner();
const hasChannels = !!channels.data?.length;
// Until the viewer is known to be the owner, only starters with their real cover show (StarterSection).
@@ -61,7 +58,6 @@ export function FacelessHome({ starters: given = [] }: { starters?: StarterCardD
};
const submit = () => {
- if (visitor) return;
if (!idea.trim()) return void toast("Describe the channel first", { id: "faceless-blocker" });
if (!checkRef(reference)) return;
create.mutate(
@@ -85,7 +81,7 @@ export function FacelessHome({ starters: given = [] }: { starters?: StarterCardD
<header className="max-md:sticky top-chrome z-20 flex h-14 items-center gap-2 bg-background/85 px-4 backdrop-blur sm:px-6">
<h1 className="truncate font-heading text-[22px] leading-none">Faceless Studio</h1>
<div className="ml-auto">
- <EngineSwitch value={engine} onChange={setEngine} selfHostedOnly />
+ <EngineSwitch value={engine} onChange={setEngine} />
</div>
<PhoneNavButton />
</header>
@@ -189,7 +185,7 @@ export function FacelessHome({ starters: given = [] }: { starters?: StarterCardD
setScript({ name: f.name, text });
}}
/>
- <Button onClick={submit} disabled={create.isPending || visitor} className="ml-auto h-9 rounded-full px-4">
+ <Button onClick={submit} disabled={create.isPending} className="ml-auto h-9 rounded-full px-4">
{create.isPending ? <Loader2 className="animate-spin" /> : <ArrowRight />}
{create.isPending ? "Creating…" : "Next"}
</Button>
@@ -199,7 +195,6 @@ export function FacelessHome({ starters: given = [] }: { starters?: StarterCardD
{refError}
</p>
)}
- {visitor && <SelfHostNote className="px-1 pt-2">Faceless channels aren&apos;t available here.</SelfHostNote>}
</div>
</div>
diff --git a/src/components/faceless/hooks.ts b/src/components/faceless/hooks.ts
index d87f5354..7e0828bf 100644
--- a/src/components/faceless/hooks.ts
+++ b/src/components/faceless/hooks.ts
@@ -2,7 +2,7 @@
import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useRef, useState } from "react";
-import { useGenerationEvents } from "@/lib/api";
+import { COMPUTER_KICK_EVENT, useGenerationEvents } from "@/lib/api";
import type {
ChangePart,
ChangePreview,
@@ -30,8 +30,16 @@ async function json<T>(res: Response): Promise<T> {
return body;
}
-const send = async <T,>(url: string, method: string, body?: unknown) =>
- json<T>(await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }));
+/** POSTs that only ask (a price, topic ideas, a page read): nothing runs. */
+const ASKS = /\/(estimate|topics|link)$/;
+
+const send = async <T,>(url: string, method: string, body?: unknown) => {
+ const out = await json<T>(await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }));
+ // A run may have started (a render, a reading, a picture): the tab that runs this person's jobs on the ComfyUI on this
+ // computer (an account's "Your GPU") asks for them at once, as after a studio run.
+ if (method === "POST" && !ASKS.test(url) && !(url.endsWith("/change") && !(body as { apply?: boolean } | undefined)?.apply)) window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));
+ return out;
+};
const inFlight = (s: string) => s === "writing" || s === "rendering";
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index df3168be..790473a3 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -339,6 +339,15 @@ export const ACCOUNT_PROJECT_ROUTES: RegExp[] = [
// Translate & dub: one of its own dubs (open it, save its reviewed lines, forget it). Its list is ACCOUNT_LISTS', and
// starting one is a tool run (ACCOUNT_TOOL_RUNS), so its price check is counted as every other.
/^\/api\/dub\/[^/]+$/,
+ // Faceless Studio, the Explainer and Content Factory: their own channels, episodes, explainers and series, their topic
+ // ideas, documents and narrator samples, and their runs (renders, retries, changes, upscales, avatars, readings), each
+ // checked by the route on its own GPU or key (src/server/faceless.ts, content-factory.ts). "Generate in Claude" isn't
+ // here (it hands the brief to the studio's own MCP server), nor "Regenerate to 1080p" (held with Open-H3 Regenerate),
+ // nor reading a link (the server never fetches a link for an account: it uploads the file or pastes the words).
+ /^\/api\/faceless\/(channels(\/[^/]+(\/avatar)?)?|episodes(\/[^/]+(\/(render|retry|rewrite|undo|upscale|change))?)?|topics|voices\/preview)$/,
+ /^\/api\/explainer(\/document)?$/,
+ /^\/api\/content-factory\/series(\/[^/]+(\/(episodes|generate|read))?)?$/,
+ /^\/api\/starters\/faceless\.[^/]+$/,
];
export const accountProjectRoute = (pathname: string): boolean => ACCOUNT_PROJECT_ROUTES.some((r) => r.test(pathname));
diff --git a/src/lib/starters/types.ts b/src/lib/starters/types.ts
index 592c53d0..565d81c9 100644
--- a/src/lib/starters/types.ts
+++ b/src/lib/starters/types.ts
@@ -131,7 +131,8 @@ export const starterHref = (s: Pick<StarterCardData, "id" | "surface"> & { use?:
export const starterShown = (s: Pick<StarterCardData, "cover">, visitor: boolean) => !visitor || !!s.cover;
/**
- * Surfaces whose starters a visitor makes too: a signed-in account's Cinema film is its own project (a guest is offered a
- * free account first). Elsewhere a starter is saved to the owner's library, so only the owner makes it.
+ * Surfaces whose starters a visitor makes too: a signed-in account's Cinema film and Faceless channel are its own
+ * projects, and a ready series or explainer fills its own composer (a guest is offered a free account first). Elsewhere
+ * a starter is saved to the owner's library, so only the owner makes it.
*/
-export const VISITOR_MAKES: ReadonlySet<StarterSurface> = new Set<StarterSurface>(["cinema"]);
+export const VISITOR_MAKES: ReadonlySet<StarterSurface> = new Set<StarterSurface>(["cinema", "faceless", "content-factory", "explainer"]);
diff --git a/src/server/account-projects.ts b/src/server/account-projects.ts
index a9fd5ac4..de344b0a 100644
--- a/src/server/account-projects.ts
+++ b/src/server/account-projects.ts
@@ -196,6 +196,28 @@ export function accountProjectsWith(kind: string, field: string): { id: string;
.all(kindOf(kind)) as { id: string; accountId: string }[];
}
+/**
+ * Which account keeps a project of that kind with this id, or null (nobody's: the owner's row, or none). For a tool whose
+ * rows live in its own tables under the project's id (Faceless channels, Content Factory series…), so a row that is an
+ * account's is never read as the owner's.
+ */
+export function accountProjectOwner(kind: string, id: string): string | null {
+ const r = store().prepare("SELECT account_id FROM account_projects WHERE id = ? AND kind = ?").get(id, kindOf(kind)) as { account_id: string } | undefined;
+ return r?.account_id ?? null;
+}
+
+/**
+ * The ids of one account's projects of a kind (or, with no account, of every account's), as a subquery for
+ * `column IN (…)`: an account's list reads its own rows only, and the owner's leaves every account's out.
+ */
+export function accountProjectIds(kind: string, accountId?: string): { sql: string; args: string[] } {
+ store();
+ const k = kindOf(kind);
+ return accountId
+ ? { sql: "SELECT id FROM account_projects WHERE kind = ? AND account_id = ?", args: [k, accountId] }
+ : { sql: "SELECT id FROM account_projects WHERE kind = ?", args: [k] };
+}
+
/** Every project of an account, when the account is deleted. */
export function deleteAccountProjects(accountId: string): number {
return store().prepare("DELETE FROM account_projects WHERE account_id = ?").run(accountId).changes;
diff --git a/src/server/account-sweep.ts b/src/server/account-sweep.ts
index 6f697564..ab345ae7 100644
--- a/src/server/account-sweep.ts
+++ b/src/server/account-sweep.ts
@@ -5,6 +5,8 @@ import { RETENTION_MS, runAccountDeletedHooks } from "./account-files";
import { deleteAccountCanvases } from "./account-canvas";
import { deleteAccountProjects } from "./account-projects";
import { deleteAccountCinema } from "./cinema";
+import { deleteAccountSeries } from "./content-factory";
+import { deleteAccountFaceless } from "./faceless";
import { clearAccountLoras } from "./account-loras";
import { accountById, deleteAccount, readAccountIds, setAccountDisabled } from "./auth";
import { strayAccountIds } from "./auth-store";
@@ -49,6 +51,8 @@ export async function purgeAccount(id: string): Promise<{ runs: number; files: n
deleteAccountCanvases(id);
// A tool's own rows under its projects go before the projects themselves.
deleteAccountCinema(id);
+ deleteAccountSeries(id);
+ deleteAccountFaceless(id);
deleteAccountProjects(id);
await runAccountDeletedHooks(id);
return { runs, files: files.length };
diff --git a/src/server/content-factory-account.ts b/src/server/content-factory-account.ts
new file mode 100644
index 00000000..92d4d4f1
--- /dev/null
+++ b/src/server/content-factory-account.ts
@@ -0,0 +1,39 @@
+import "server-only";
+import { projectRefsProblem } from "./account-projects";
+import { runAccountTool } from "./account-tool-run";
+import type { Account } from "./auth";
+import { claimSeries, seriesRunFiles, seriesRunSteps, startSeriesRun, type SeriesRun } from "./content-factory";
+import { planned } from "./faceless-account";
+import { asAccount } from "./generations";
+import { ShortsError } from "./shorts";
+
+/**
+ * A signed-in account's "Generate here" or "Next episode" on its own series (public sign-up). The run is planned first,
+ * as the account: the episodes' titles and scripts (the offline writer's) and every step their renders run. Its
+ * episodes render as one run on its own GPU or key, after the checks a studio run gets (src/server/account-tool-run.ts).
+ * With `review` they're written and wait for review instead: nothing renders yet, so there's no run to check. One run
+ * at a time per series (claimSeries).
+ */
+export async function runSeries(request: Request, account: Account, id: string, kind: SeriesRun["kind"], review: boolean, plan: () => Promise<SeriesRun>): Promise<Response> {
+ const release = claimSeries(id, kind);
+ try {
+ if (review) return Response.json(await asAccount(account.id, async () => startSeriesRun(await plan())));
+ let run: SeriesRun | null = null;
+ const out = await runAccountTool(request, account, {
+ tool: "content-factory",
+ files: [],
+ plan: () =>
+ planned(async () => {
+ run = await plan();
+ // Every file its episodes read (a narrator's sample, style pictures) must be its own.
+ const problem = projectRefsProblem(account.id, { files: seriesRunFiles(run) });
+ if (problem) throw new ShortsError(problem.error, problem.status);
+ return seriesRunSteps(run);
+ }),
+ start: () => startSeriesRun(run!),
+ });
+ return out.ok ? Response.json({ ...out.value, ...(out.gpuWarning && { gpuWarning: out.gpuWarning }) }) : out.response;
+ } finally {
+ release();
+ }
+}
diff --git a/src/server/content-factory.ts b/src/server/content-factory.ts
index 9fa18ee3..7dbdd2ec 100644
--- a/src/server/content-factory.ts
+++ b/src/server/content-factory.ts
@@ -40,14 +40,36 @@ import {
type SeriesView,
type StyleBrief,
} from "@/lib/catalog/content-factory";
-import { genreInfo, pickerData, type ChannelSettings, type EpisodeSettings, type NarratorVoice, type TimedText } from "@/lib/catalog/faceless";
+import { genreInfo, pickerData, type ChannelSettings, type EpisodeScript, type EpisodeSettings, type FacelessGenre, type GraphStep, type NarratorVoice, type TimedText } from "@/lib/catalog/faceless";
import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
import { probeMedia } from "@/lib/media-probe";
+import { AccountProjectError, accountProjectIds, accountProjectOwner, deleteAccountProject } from "./account-projects";
import { authEnabled } from "./auth";
import { db } from "./db";
import { llmText, llmTextBackend, type LlmImage } from "./enhance";
-import { askLlm, createChannel, createEpisode, deleteChannel, estimateEpisode, FacelessError, getChannel, handle as facelessHandle, listEpisodes, VoiceSchema } from "./faceless";
-import { cancelGeneration, createGenerations, getGeneration, previewGeneration } from "./generations";
+import {
+ ACCOUNT_CLOUD_ENGINE,
+ askLlm,
+ composeScript,
+ createChannel,
+ createEpisode,
+ deleteChannel,
+ draftGraph,
+ dropRowId,
+ estimateEpisode,
+ FacelessError,
+ forViewer,
+ getChannel,
+ graphFiles,
+ graphToolSteps,
+ handle as facelessHandle,
+ listEpisodes,
+ newRowId,
+ viewerScope,
+ VoiceSchema,
+} from "./faceless";
+import { accountRun, AccountRunError, asAccount, cancelGeneration, createGenerations, getGeneration, previewGeneration } from "./generations";
+import { tenant, tenantAccount } from "./tenant";
import type { JsonSpec } from "./llm";
import { fetchRemote, RemoteFetchError } from "./remote-fetch";
import { engineMode } from "./settings";
@@ -90,6 +112,12 @@ const BRIEF_SCHEMA: JsonSpec = {
* Whatever can't be read (demo mode, no LLM, an answer that isn't a brief) gives way to the offline brief
* from the clip's shape, length and narration pace, with a note that says so.
*
+ * Whose series (public sign-up): the owner's, or a signed-in account's own project (account-projects.ts kind
+ * "content-factory") under the row's id, read and changed only inside its own work (tenant.ts asAccount). An account's
+ * reading runs on its own GPU (Gemma 4) or its own key (the transcript; the brief is then written from the clip's
+ * shape and pace, never by the install's AI helper), and its series' plans and scripts are the offline writer's.
+ * Everything a run of an account's would make is planned first and checked (src/server/account-tool-run.ts).
+ *
* The step generations live in the generations table (they survive restarts); the brief is written by
* whoever reads the series first once they're done (seriesView), in this process.
*/
@@ -123,7 +151,14 @@ interface SeriesRow {
updated_at: number;
}
-const seriesRow = (id: string) => db().prepare("SELECT * FROM content_series WHERE id = ?").get(id) as SeriesRow | undefined;
+/** An account's series, as its own project kind (account-projects.ts). */
+export const SERIES_KIND = "content-factory";
+
+/** A series of whoever the work is for: the owner's, or an account's own (another's reads as none). */
+const seriesRow = (id: string) => {
+ const r = db().prepare("SELECT * FROM content_series WHERE id = ?").get(id) as SeriesRow | undefined;
+ return r && forViewer(accountProjectOwner(SERIES_KIND, id)) ? r : undefined;
+};
const dataOf = (r: SeriesRow) => JSON.parse(r.data_json) as SeriesData;
function mustRow(id: string): SeriesRow {
@@ -175,11 +210,27 @@ function pruneSeries(): void {
.all() as SeriesRow[];
for (const r of [...drafts, ...orphans]) {
if (running().has(r.id)) continue;
- for (const g of Object.values(dataOf(r).analysis?.steps ?? {})) void cancelGeneration(g).catch(() => {});
+ // An account's series: its reading steps are stopped as its own work, and its project goes with the row.
+ const owner = accountProjectOwner(SERIES_KIND, r.id);
+ const stop = () => {
+ for (const g of Object.values(dataOf(r).analysis?.steps ?? {})) void cancelGeneration(g).catch(() => {});
+ };
+ if (owner) asAccount(owner, stop);
+ else stop();
db().prepare("DELETE FROM content_series WHERE id = ?").run(r.id);
+ if (owner) deleteAccountProject(owner, SERIES_KIND, r.id);
}
}
+/**
+ * When an account is deleted (account-sweep.ts purgeAccount, before its projects go, with its channels): its series.
+ * Its runs are deleted with the account.
+ */
+export function deleteAccountSeries(accountId: string): void {
+ const ids = accountProjectIds(SERIES_KIND, accountId);
+ db().prepare(`DELETE FROM content_series WHERE id IN (${ids.sql})`).run(...ids.args);
+}
+
// ---------------------------------------------------------------------------
// The reference: an upload, a link (fetched through the SSRF-safe fetchRemote), or a preset
@@ -240,6 +291,8 @@ async function readLink(raw: string): Promise<SeriesReference> {
const checked = referenceLink(raw);
if ("error" in checked) throw new FacelessError(checked.error);
const { url, platform } = checked;
+ // The server never fetches a link for an account (docs/public-signup.md): it uploads the clip.
+ if (tenant()) throw new NeedsUpload(noMediaMessage(platform));
// YouTube never hands its files out; a page from the platforms may (an og:video), so they're tried.
if (platform === "youtube") throw new NeedsUpload(noMediaMessage(platform));
const ref: SeriesReference = { kind: "link", link: url, platform };
@@ -310,7 +363,10 @@ const STEP_LABEL = { frames: "Reference frames", transcript: "Reference transcri
const engineAllowed = (engine: Engine) => engineMode() === "both" || engineMode() === engine;
function checkEngine(engine: Engine): void {
- if (!engineAllowed(engine)) throw new FacelessError(engine === "open" ? "This install is set to paid cloud APIs only (Settings → Engine mode)" : "This install is set to open source only (Settings → Engine mode)");
+ if (engineAllowed(engine)) return;
+ // An account's engine mode is open source only until it adds a key of its own.
+ if (tenant()) throw new FacelessError(ACCOUNT_CLOUD_ENGINE, 422);
+ throw new FacelessError(engine === "open" ? "This install is set to paid cloud APIs only (Settings → Engine mode)" : "This install is set to open source only (Settings → Engine mode)");
}
function request(ref: SeriesReference, key: keyof typeof STEP_LABEL, r: Omit<GenerationRequest, "feature">): GenerationRequest {
@@ -325,13 +381,44 @@ export function frameInterval(seconds: number | undefined, fps: number | undefin
return Math.max(1, Math.min(300, Math.round((secs * rate) / frames)));
}
+/**
+ * The step generations one read of the clip makes. An account's on the cloud engine is the transcript only: its brief is
+ * written from the clip's shape and narration pace (the frames are for the install's AI helper, which an account's work
+ * never uses).
+ */
+function readRequests(ref: Pick<SeriesReference, "url" | "title" | "seconds" | "fps">, engine: Engine): Partial<Record<keyof typeof STEP_LABEL, GenerationRequest>> {
+ const r = ref as SeriesReference;
+ if (engine === "open") {
+ return { brief: request(r, "brief", { modelId: "oss-reference-brief", op: "write", inputs: { video: ref.url }, params: { duration: Math.min(OPEN_REFERENCE_SECONDS, ref.seconds ?? OPEN_REFERENCE_SECONDS) } }) };
+ }
+ return {
+ // JPEG, not fal's default PNG: a full-HD PNG frame can weigh 3 MB, and Claude takes 32 MB a request.
+ ...(!tenant() && { frames: request(r, "frames", { modelId: "extract-frames", op: "extract-frames", inputs: { video: ref.url }, params: { frameInterval: frameInterval(ref.seconds, ref.fps), extra: { output_format: "jpg", quality: 80 } } }) }),
+ transcript: request(r, "transcript", { modelId: "scribe-v2", op: "transcribe", inputs: { video: ref.url }, params: { ...(ref.seconds && { duration: ref.seconds, sourceDuration: ref.seconds }) } }),
+ };
+}
+
+/**
+ * Before an account's clip is fetched or read: every step a read on this engine makes must run on its own GPU or key
+ * (a stand-in clip stands for the one not fetched yet). Refused with the account's answer (Connect your GPU, Add your key).
+ */
+function assertAccountReads(engine: Engine): void {
+ const account = tenantAccount();
+ if (!account) return;
+ checkEngine(engine);
+ for (const r of Object.values(readRequests({ url: "/api/files/estimate.mp4", seconds: 30 }, engine))) {
+ const own = accountRun(account, previewGeneration(r).route.provider, "submit");
+ if ("error" in own) throw new AccountRunError(own);
+ }
+}
+
/** The step generations for one read of the clip (none can start: the offline brief, with why). */
function startSteps(ref: SeriesReference, engine: Engine): { steps: SeriesAnalysis["steps"]; costUsd: number | null; demo: boolean; error?: string } {
const steps: SeriesAnalysis["steps"] = {};
let cost = 0;
let demo = false;
const errors: string[] = [];
- const run = (key: keyof typeof STEP_LABEL, r: GenerationRequest) => {
+ for (const [key, r] of Object.entries(readRequests(ref, engine)) as [keyof typeof STEP_LABEL, GenerationRequest][]) {
try {
const p = previewGeneration(r);
const g = createGenerations(r)[0];
@@ -339,15 +426,10 @@ function startSteps(ref: SeriesReference, engine: Engine): { steps: SeriesAnalys
cost += p.costUsd ?? 0;
demo ||= p.demo;
} catch (e) {
+ // An account's run was checked step by step: one that can't start now stops it (the route says why).
+ if (tenantAccount()) throw e;
errors.push((e as Error).message);
}
- };
- if (engine === "open") {
- run("brief", request(ref, "brief", { modelId: "oss-reference-brief", op: "write", inputs: { video: ref.url }, params: { duration: Math.min(OPEN_REFERENCE_SECONDS, ref.seconds ?? OPEN_REFERENCE_SECONDS) } }));
- } else {
- // JPEG, not fal's default PNG: a full-HD PNG frame can weigh 3 MB, and Claude takes 32 MB a request.
- run("frames", request(ref, "frames", { modelId: "extract-frames", op: "extract-frames", inputs: { video: ref.url }, params: { frameInterval: frameInterval(ref.seconds, ref.fps), extra: { output_format: "jpg", quality: 80 } } }));
- run("transcript", request(ref, "transcript", { modelId: "scribe-v2", op: "transcribe", inputs: { video: ref.url }, params: { ...(ref.seconds && { duration: ref.seconds, sourceDuration: ref.seconds }) } }));
}
return { steps, costUsd: engine === "open" ? 0 : Math.round(cost * 1000) / 1000, demo, ...(errors.length && !Object.keys(steps).length && { error: errors[0] }) };
}
@@ -457,6 +539,8 @@ async function writeBrief(id: string): Promise<void> {
note = demo
? "Demo brief — connect fal and Claude in Settings to read the clip for real. This one comes from the clip's shape and length."
: `The clip couldn't be read (${framesGen?.error ?? wordsGen?.error ?? "no frames or words came back"}). This brief comes from its shape and length — read it again to retry.`;
+ } else if (tenant()) {
+ // An account's brief: from the clip's shape, length and narration pace (the install's AI helper isn't its own).
} else if (!llmTextBackend()) {
offline = true;
note = "No LLM is connected (Settings → AI helper), so this brief comes from the clip's shape, length and narration pace.";
@@ -539,24 +623,73 @@ export function seriesView(id: string): SeriesView {
}
/** A new series around a reference (reading starts straight away), a preset (its brief is ready), or nothing yet. */
-export async function createSeries(input: { reference: ReferenceInput | null; engine: Engine; prompt?: string }): Promise<SeriesView> {
+export async function createSeries(input: SeriesCreate): Promise<SeriesView> {
+ return makeSeries(await prepareSeries(input));
+}
+
+export interface SeriesCreate {
+ reference: ReferenceInput | null;
+ engine: Engine;
+ prompt?: string;
+}
+
+/** A new series' reference, resolved (a link fetched and kept, an upload read): nothing of the series is made yet. */
+export interface PreparedSeries extends SeriesCreate {
+ resolved: SeriesReference | null;
+}
+
+/** Whether making this series reads a clip (an upload or a link): an account's is then a run of its own. */
+export const seriesReads = (input: SeriesCreate) => !!input.reference && input.reference.kind !== "preset";
+
+/**
+ * The reference resolved, before the series is made. An account's link is fetched only once every step that reads it
+ * can run on its own GPU or key.
+ */
+export async function prepareSeries(input: SeriesCreate): Promise<PreparedSeries> {
checkEngine(input.engine);
+ if (seriesReads(input)) assertAccountReads(input.engine);
+ return { ...input, resolved: input.reference ? await resolveReference(input.reference) : null };
+}
+
+/** The reading steps making this series starts (an account's run is checked with them first). */
+export function seriesReadSteps(p: PreparedSeries): { request: GenerationRequest; deps: number }[] {
+ return p.resolved?.url ? Object.values(readRequests(p.resolved, p.engine)).map((request) => ({ request, deps: 0 })) : [];
+}
+
+/** Make the series, and start reading its clip. */
+export function makeSeries(p: PreparedSeries): SeriesView {
pruneSeries();
- const reference = input.reference ? await resolveReference(input.reference) : null;
- const id = nanoid(10);
+ const reference = p.resolved;
+ const id = newRowId(SERIES_KIND, reference?.title ?? "Series");
const now = Date.now();
const preset = reference?.kind === "preset" ? getPreset(reference.presetId) : undefined;
- const data: SeriesData = { name: null, prompt: input.prompt?.trim().slice(0, MAX_PROMPT) ?? "", reference, analysis: null, brief: preset ? preset.brief : null, settings: null, plan: [] };
- if (preset) data.analysis = { engine: input.engine, status: "ready", steps: {}, costUsd: 0 };
- db().prepare("INSERT INTO content_series (id, channel_id, data_json, created_at, updated_at) VALUES (?, NULL, ?, ?, ?)").run(id, JSON.stringify(data), now, now);
+ const data: SeriesData = { name: null, prompt: p.prompt?.trim().slice(0, MAX_PROMPT) ?? "", reference, analysis: null, brief: preset ? preset.brief : null, settings: null, plan: [] };
+ if (preset) data.analysis = { engine: p.engine, status: "ready", steps: {}, costUsd: 0 };
+ try {
+ db().prepare("INSERT INTO content_series (id, channel_id, data_json, created_at, updated_at) VALUES (?, NULL, ?, ?, ?)").run(id, JSON.stringify(data), now, now);
+ } catch (e) {
+ dropRowId(SERIES_KIND, id);
+ throw e;
+ }
if (reference?.url) {
- data.analysis = beginAnalysis(id, reference, input.engine);
+ data.analysis = beginAnalysis(id, reference, p.engine);
if (data.analysis.status === "ready") data.brief = offlineBrief({ seconds: reference.seconds, width: reference.width, height: reference.height, title: reference.title });
save(id, data);
}
return seriesView(id);
}
+/** What "Read again" would start (an account's run is checked with it first). */
+export function rereadSteps(id: string, engine: Engine): { request: GenerationRequest; deps: number }[] {
+ checkEngine(engine);
+ const d = dataOf(mustRow(id));
+ if (!d.reference?.url) throw new FacelessError("This series has no clip to read — add one first");
+ return Object.values(readRequests(d.reference, engine)).map((request) => ({ request, deps: 0 }));
+}
+
+/** The clip a series reads: an account's must be its own file. */
+export const seriesClip = (id: string): string | null => dataOf(mustRow(id)).reference?.url ?? null;
+
/** Read the reference again (after an offline brief, a failure, or on the other engine). */
export async function rereadSeries(id: string, engine: Engine): Promise<SeriesView> {
checkEngine(engine);
@@ -608,11 +741,13 @@ export async function deleteSeries(id: string, o: { draftOnly?: boolean } = {}):
for (const g of Object.values(d.analysis?.steps ?? {})) void cancelGeneration(g).catch(() => {});
if (r.channel_id && getChannel(r.channel_id)) await deleteChannel(r.channel_id);
db().prepare("DELETE FROM content_series WHERE id = ?").run(id);
+ dropRowId(SERIES_KIND, id);
}
-/** Series that have been made (drafts that never ran stay out of the list). */
+/** Series that have been made (drafts that never ran stay out of the list): whoever the work is for's own. */
export function listSeries(): SeriesCard[] {
- const rows = db().prepare("SELECT * FROM content_series WHERE channel_id IS NOT NULL ORDER BY updated_at DESC LIMIT 100").all() as SeriesRow[];
+ const scope = viewerScope("id", SERIES_KIND);
+ const rows = db().prepare(`SELECT * FROM content_series WHERE channel_id IS NOT NULL AND ${scope.sql} ORDER BY updated_at DESC LIMIT 100`).all(...scope.args) as SeriesRow[];
return rows.flatMap((r) => {
const channel = getChannel(r.channel_id!);
if (!channel) return [];
@@ -688,7 +823,7 @@ function analysisPerMinute(engine: Engine): number {
const frames = previewGeneration({ feature: "content-factory", modelId: "extract-frames", op: "extract-frames", inputs: { video: "/api/files/estimate.mp4" }, params: { frameInterval: 90 } });
const words = previewGeneration({ feature: "content-factory", modelId: "scribe-v2", op: "transcribe", inputs: { video: "/api/files/estimate.mp4" }, params: { duration: 60, sourceDuration: 60 } });
if (frames.demo && words.demo) return 0;
- return briefCostUsd({ seconds: 60, framesUsd: frames.costUsd ?? 0, transcribePerMinute: words.costUsd ?? 0, claude: llmTextBackend() === "claude" });
+ return briefCostUsd({ seconds: 60, framesUsd: tenant() ? 0 : (frames.costUsd ?? 0), transcribePerMinute: words.costUsd ?? 0, claude: llmTextBackend() === "claude" });
} catch {
return 0;
}
@@ -741,31 +876,100 @@ async function planEpisodes(o: { prompt: string; settings: SeriesSettings; brief
const COULDNT_PLAN = "Couldn't plan your episodes. You weren't charged, so it's safe to try again.";
-function startEpisodes(o: { channelId: string; prompt: string; plan: SeriesEpisodePlan[]; earlier: string[]; settings: EpisodeSettings; review: boolean; series: boolean }): string[] {
+/** One episode of a series run, planned: its topic, its title, and (an account's) its script composed already. */
+interface PlannedEpisode {
+ topic: string;
+ title?: string;
+ composed?: EpisodeScript;
+}
+
+/**
+ * One "Generate here" or "Next episode", planned before anything is made: the episodes' titles and topics, and for an
+ * account its episodes' scripts (the offline writer's) and every step their renders run, so its run is checked first.
+ */
+export interface SeriesRun {
+ id: string;
+ /** "generate" makes the series' channel; "add" adds to it. */
+ kind: "generate" | "add";
+ prompt: string;
+ settings: EpisodeSettings;
+ genre: FacelessGenre;
+ review: boolean;
+ /** The series' episode plans (and, for "generate", its name) to save. */
+ plan: { name: string | null; episodes: SeriesEpisodePlan[] };
+ /** "generate": the series' settings and the channel it makes. */
+ seriesSettings?: SeriesSettings;
+ channel?: { settings: ChannelSettings };
+ /** "add": the series' channel. */
+ channelId?: string;
+ episodes: PlannedEpisode[];
+ /** An account's: every step its episodes render (none with `review`: nothing renders yet). */
+ graphs: GraphStep[][];
+}
+
+/** The planned episodes: their topics (each one knows the titles before it) and, for an account, their scripts. */
+async function planned(o: { prompt: string; plan: SeriesEpisodePlan[]; earlier: string[]; settings: EpisodeSettings; genre: FacelessGenre; series: boolean }): Promise<PlannedEpisode[]> {
const titles = [...o.earlier];
- const ids: string[] = [];
- o.plan.forEach((ep) => {
+ const out: PlannedEpisode[] = [];
+ for (const ep of o.plan) {
const topic = episodeTopic(o.prompt, ep, { number: titles.length + 1, earlier: titles, series: o.series });
- const made = createEpisode({ kind: "faceless", channelId: o.channelId, topic, settings: o.settings, autoRender: !o.review, saveLook: false, ...(o.series && { title: ep.title }) });
- ids.push(made.id);
+ // An account's script is written now (offline: no AI helper), so the run that renders it is checked as it will run.
+ const composed = tenantAccount() ? await composeScript({ kind: "faceless", channelId: null, topic, settings: o.settings, sources: [], genre: o.genre }, "") : undefined;
+ out.push({ topic, ...(o.series && { title: ep.title }), ...(composed && { composed }) });
titles.push(ep.title);
- });
- return ids;
+ }
+ return out;
}
+/** An account's episodes' graphs, for its run's checks (none with `review`). */
+function plannedGraphs(run: Pick<SeriesRun, "episodes" | "settings" | "genre" | "review">): GraphStep[][] {
+ if (!tenantAccount() || run.review) return [];
+ return run.episodes.map((e) => draftGraph({ kind: "faceless", title: e.title ?? e.topic, settings: run.settings, script: e.composed!, genre: run.genre }));
+}
+
+/** Every step an account's series run renders, as one run (its episodes share a batch). */
+export const seriesRunSteps = (run: SeriesRun) => run.graphs.flatMap(graphToolSteps);
+
+/** The files an account's series run reads (its narrator's sample, its style pictures): all must be its own. */
+export const seriesRunFiles = (run: SeriesRun) => [...new Set(run.graphs.flatMap(graphFiles))];
+
+/** Create the planned episodes in the channel; an account's render at once with their composed scripts, as one batch. */
+function startEpisodes(o: { channelId: string; settings: EpisodeSettings; review: boolean; episodes: PlannedEpisode[] }): string[] {
+ const batchId = tenantAccount() && !o.review ? nanoid(10) : undefined;
+ return o.episodes.map(
+ (e) =>
+ createEpisode({
+ kind: "faceless",
+ channelId: o.channelId,
+ topic: e.topic,
+ settings: o.settings,
+ autoRender: !o.review,
+ saveLook: false,
+ ...(e.title && { title: e.title }),
+ ...(e.composed && { composed: e.composed }),
+ ...(batchId && { batchId }),
+ }).id,
+ );
+}
+
+/** One "Generate here" or "Next episode" at a time per series (see claim). */
+export const claimSeries = (id: string, kind: SeriesRun["kind"]) => claim(id, kind === "generate" ? "This series is being made — a moment" : "Episodes are being added to this series — a moment");
+
/** "Generate here": plan the episodes, make the series' channel, and start every episode (rendered straight after its script unless `review`). */
export async function generateSeries(id: string, input: SeriesInput & { review?: boolean }): Promise<SeriesView> {
const r = mustRow(id);
if (r.channel_id) throw new FacelessError("This series is made — add episodes from its page", 409);
- const release = claim(id, "This series is being made — a moment");
+ const release = claimSeries(id, "generate");
try {
- return await generateClaimed(id, input);
+ return await startSeriesRun(await planGenerate(id, input));
} finally {
release();
}
}
-async function generateClaimed(id: string, input: SeriesInput & { review?: boolean }): Promise<SeriesView> {
+/** "Generate here", planned (nothing is made). */
+export async function planGenerate(id: string, input: SeriesInput & { review?: boolean }): Promise<SeriesRun> {
+ if (mustRow(id).channel_id) throw new FacelessError("This series is made — add episodes from its page", 409);
checkEngine(input.settings.engine);
const prompt = input.prompt.trim();
if (!prompt) throw new FacelessError("Say what the video is about");
@@ -774,47 +978,34 @@ async function generateClaimed(id: string, input: SeriesInput & { review?: boole
const est = estimateEpisode({ kind: "faceless", settings, genre: input.settings.genre });
if (est.error) throw new FacelessError(est.error);
const count = Math.max(1, Math.min(MAX_EPISODES, Math.round(input.settings.episodes)));
- let plan: { name: string | null; episodes: SeriesEpisodePlan[] };
- let channelId: string;
+ let plan: SeriesRun["plan"];
try {
plan = await planEpisodes({ prompt, settings: input.settings, brief, count, previous: [] });
- const channelSettings: ChannelSettings = {
- engine: settings.engine,
- styleId: settings.styleId,
- styleRefs: [],
- voice: settings.voice,
- aspect: settings.aspect,
- subtitles: settings.subtitles,
- music: settings.music,
- animation: settings.animation,
- length: settings.length,
- ...(settings.brief && { brief: settings.brief }),
- };
- const channel = await createChannel({ idea: prompt, genre: input.settings.genre, engine: settings.engine, ...(plan.name && { name: plan.name }), avatar: false, settings: channelSettings });
- channelId = channel.id;
} catch (e) {
if (e instanceof FacelessError) throw e;
throw new FacelessError(COULDNT_PLAN, 500);
}
- // Seen as made from here on (a second click gets "This series is made"); a brief edited meanwhile is kept.
- patch(id, (cur) => ({ ...cur, name: plan.name, prompt, settings: { ...input.settings, episodes: count }, plan: plan.episodes }), channelId);
- const ids = startEpisodes({ channelId, prompt, plan: plan.episodes, earlier: [], settings, review: !!input.review, series: count > 1 });
- patch(id, (cur) => ({ ...cur, episodeIds: ids }));
- return seriesView(id);
-}
-
-/** "Next episode": plan more after the ones already made, the first one following what the user says happens in it. */
-export async function addEpisodes(id: string, input: { count: number; next?: string; review?: boolean }): Promise<SeriesView> {
- mustRow(id);
- const release = claim(id, "Episodes are being added to this series — a moment");
- try {
- return await addClaimed(id, input);
- } finally {
- release();
- }
+ const channelSettings: ChannelSettings = {
+ engine: settings.engine,
+ styleId: settings.styleId,
+ styleRefs: [],
+ voice: settings.voice,
+ aspect: settings.aspect,
+ subtitles: settings.subtitles,
+ music: settings.music,
+ animation: settings.animation,
+ length: settings.length,
+ ...(settings.brief && { brief: settings.brief }),
+ };
+ const genre = input.settings.genre;
+ const review = !!input.review;
+ const episodes = await planned({ prompt, plan: plan.episodes, earlier: [], settings, genre, series: count > 1 });
+ const run = { id, kind: "generate" as const, prompt, settings, genre, review, plan, seriesSettings: { ...input.settings, episodes: count }, channel: { settings: channelSettings }, episodes };
+ return { ...run, graphs: plannedGraphs(run) };
}
-async function addClaimed(id: string, input: { count: number; next?: string; review?: boolean }): Promise<SeriesView> {
+/** "Next episode", planned (nothing is made). */
+export async function planAdd(id: string, input: { count: number; next?: string; review?: boolean }): Promise<SeriesRun> {
const r = mustRow(id);
const d = dataOf(r);
const channel = r.channel_id ? getChannel(r.channel_id) : null;
@@ -828,13 +1019,52 @@ async function addClaimed(id: string, input: { count: number; next?: string; rev
const more = await planEpisodes({ prompt: d.prompt, settings: d.settings, brief: d.brief, count, previous, next: input.next }).catch(() => {
throw new FacelessError(COULDNT_PLAN, 500);
});
- const ids = startEpisodes({ channelId: channel.id, prompt: d.prompt, plan: more.episodes, earlier: previous, settings, review: !!input.review, series: true });
+ const genre = d.settings.genre;
+ const review = !!input.review;
+ const episodes = await planned({ prompt: d.prompt, plan: more.episodes, earlier: previous, settings, genre, series: true });
+ const run = { id, kind: "add" as const, prompt: d.prompt, settings, genre, review, plan: more, channelId: channel.id, episodes };
+ return { ...run, graphs: plannedGraphs(run) };
+}
+
+/** Make what a series run planned: the channel ("generate"), the episodes, and the series' record of them. */
+export async function startSeriesRun(run: SeriesRun): Promise<SeriesView> {
+ const r = mustRow(run.id);
+ if (run.kind === "generate") {
+ if (r.channel_id) throw new FacelessError("This series is made — add episodes from its page", 409);
+ let channelId: string;
+ try {
+ const made = await createChannel({ idea: run.prompt, genre: run.genre, engine: run.settings.engine, ...(run.plan.name && { name: run.plan.name }), avatar: false, settings: run.channel!.settings });
+ channelId = made.id;
+ } catch (e) {
+ if (e instanceof FacelessError || e instanceof AccountProjectError) throw e;
+ throw new FacelessError(COULDNT_PLAN, 500);
+ }
+ // Seen as made from here on (a second click gets "This series is made"); a brief edited meanwhile is kept.
+ patch(run.id, (cur) => ({ ...cur, name: run.plan.name, prompt: run.prompt, settings: run.seriesSettings!, plan: run.plan.episodes }), channelId);
+ const ids = startEpisodes({ channelId, settings: run.settings, review: run.review, episodes: run.episodes });
+ patch(run.id, (cur) => ({ ...cur, episodeIds: ids }));
+ return seriesView(run.id);
+ }
+ const channelId = run.channelId!;
+ if (r.channel_id !== channelId || !getChannel(channelId)) throw new FacelessError("Make the series first", 409);
+ const ids = startEpisodes({ channelId, settings: run.settings, review: run.review, episodes: run.episodes });
// Read again before writing: a brief edited while the episodes were planned is kept.
- patch(id, (cur) => {
- const plan = [...cur.plan, ...more.episodes];
- return { ...cur, plan, settings: { ...(cur.settings ?? d.settings!), episodes: plan.length }, episodeIds: [...(cur.episodeIds ?? []), ...ids] };
+ patch(run.id, (cur) => {
+ const plan = [...cur.plan, ...run.plan.episodes];
+ return { ...cur, plan, settings: { ...(cur.settings ?? dataOf(r).settings!), episodes: plan.length }, episodeIds: [...(cur.episodeIds ?? []), ...ids] };
});
- return seriesView(id);
+ return seriesView(run.id);
+}
+
+/** "Next episode": plan more after the ones already made, the first one following what the user says happens in it. */
+export async function addEpisodes(id: string, input: { count: number; next?: string; review?: boolean }): Promise<SeriesView> {
+ mustRow(id);
+ const release = claimSeries(id, "add");
+ try {
+ return await startSeriesRun(await planAdd(id, input));
+ } finally {
+ release();
+ }
}
// ---------------------------------------------------------------------------
diff --git a/src/server/faceless-account.ts b/src/server/faceless-account.ts
new file mode 100644
index 00000000..477deaf9
--- /dev/null
+++ b/src/server/faceless-account.ts
@@ -0,0 +1,47 @@
+import "server-only";
+import type { EpisodeSettings, ExplainerSource } from "@/lib/catalog/faceless";
+import { AccountProjectError, projectRefsProblem } from "./account-projects";
+import { FacelessError } from "./faceless";
+import { hit } from "./rate";
+import { ShortsError } from "./shorts";
+
+/**
+ * The account side of the routes of Faceless Studio, the Explainer and Content Factory (public sign-up). A signed-in
+ * account's channels, episodes, explainers and series are its own (src/server/faceless.ts, content-factory.ts), and
+ * every render, reading or picture of its runs on its own GPU or key after the checks a studio run gets
+ * (src/server/account-tool-run.ts runAccountTool). These are the small pieces its routes share.
+ */
+
+/** A plan's refusal keeps its status through runAccountTool (it keeps a ShortsError's, and answers 422 for the rest). */
+export async function planned<T>(fn: () => T | Promise<T>): Promise<T> {
+ try {
+ return await fn();
+ } catch (e) {
+ if (e instanceof FacelessError || e instanceof AccountProjectError) throw new ShortsError(e.message, e.status);
+ throw e;
+ }
+}
+
+/** The files an episode's (or a channel's) settings name: its style pictures, its narrator's sample, its music clip. */
+export function settingsFiles(s?: Partial<Pick<EpisodeSettings, "styleRefs" | "voice" | "bedClip" | "sourceImages">> | null): string[] {
+ if (!s) return [];
+ return [...(s.styleRefs ?? []), ...(s.voice?.kind === "sample" ? [s.voice.url] : []), ...(s.bedClip ? [s.bedClip.url] : []), ...(s.sourceImages ?? [])];
+}
+
+/** The pictures an explainer's sources name. */
+export const sourceFiles = (sources?: ExplainerSource[]): string[] => (sources ?? []).flatMap((s) => (s.kind === "image" ? [s.url] : []));
+
+/** An account's request that names a file that isn't its own (or one of Fuobe's published examples): its answer, or null. */
+export function filesRefused(accountId: string, files: (string | null | undefined)[]): Response | null {
+ const problem = projectRefsProblem(accountId, { files: files.filter((f): f is string => !!f) });
+ return problem ? Response.json({ error: problem.error, code: problem.code }, { status: problem.status, headers: { "Cache-Control": "no-store" } }) : null;
+}
+
+/** Documents an account has read for it in an hour (an explainer's PDF or Word source). */
+export const READS_PER_HOUR = 30;
+
+/** An account's document read past its hour: 429, or null. */
+export function readsLimited(accountId: string): Response | null {
+ const rate = hit(`faceless-read:${accountId}`, READS_PER_HOUR, 60 * 60_000);
+ return rate.ok ? null : Response.json({ error: "You've added a lot of files this hour. Try again later." }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS) } });
+}
diff --git a/src/server/faceless.ts b/src/server/faceless.ts
index 4b7121c2..8a026da2 100644
--- a/src/server/faceless.ts
+++ b/src/server/faceless.ts
@@ -87,13 +87,14 @@ import { routesFor } from "@/lib/catalog/plan";
import { pricingAt } from "@/lib/catalog/promo";
import { REGEN_COPY, REGEN_OFFERED } from "@/lib/catalog/regenerate";
import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
+import { AccountProjectError, accountProjectIds, accountProjectOwner, createAccountProject, deleteAccountProject } from "./account-projects";
import { DocxError, docxText } from "./assist/docx";
import { PdfError, pdfText } from "./assist/pdf";
import { db } from "./db";
import { listElements } from "./elements";
import { connectRefusal } from "./connect-refusal";
import { createPipeline } from "./chains";
-import { cancelGeneration, chooseRoute, ConnectComfyError, createGenerations, getGeneration, previewChained } from "./generations";
+import { asAccount, cancelGeneration, chooseRoute, ConnectComfyError, createGenerations, getGeneration, previewChained } from "./generations";
import { provider } from "./providers";
import type { JsonSpec } from "./llm";
import { llmBackends, probeLocal } from "./providers/llm";
@@ -101,6 +102,7 @@ import { fetchRemote } from "./remote-fetch";
import { engineMode, getSetting } from "./settings";
import { fileUrl, saveFile } from "./storage";
import { firstOn, offeredModel } from "./model-access";
+import { tenant, tenantAccount } from "./tenant";
/**
* Faceless Studio and the Explainer on the server: channels (genre, saved style, narrator, aspect,
@@ -117,6 +119,13 @@ import { firstOn, offeredModel } from "./model-access";
*
* 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.
+ *
+ * Whose channels and episodes (public sign-up): the owner's, or a signed-in account's own. An account's channel and its
+ * explainers are its own projects in account-projects.ts (kinds "faceless" and "explainer") under the row's id; a
+ * channel's episodes are its channel's. Every read and change here is for whoever the work is for (tenant.ts asAccount):
+ * an account reaches only its own (another's, or the owner's, reads as not found) and the owner's lists never hold an
+ * account's. An account's work never uses the install's AI helper (its scripts, names, topics and summaries are the
+ * offline writer's) or its elements; its renders run on its own GPU or key (src/server/account-tool-run.ts).
*/
export class FacelessError extends Error {
@@ -199,7 +208,60 @@ function updateEpisodeRow(id: string, fields: Partial<EpisodeRow>): void {
.run({ ...fields, __now: Date.now(), __id: id });
}
-const episodeRow = (id: string) => db().prepare("SELECT * FROM faceless_episodes WHERE id = ?").get(id) as EpisodeRow | undefined;
+// ---------------------------------------------------------------------------
+// Whose rows (see the header)
+
+/** An account's channel, and an account's explainer, as its own project kinds (account-projects.ts). */
+export const CHANNEL_KIND = "faceless";
+export const EXPLAINER_KIND = "explainer";
+
+/** Whether the work is a guest's (a visitor's price check): a guest has no channels or episodes. */
+const guestWork = () => tenant()?.kind === "guest";
+
+/** A new row's id: the owner's as before; an account's is its own project's (its limit of them counts). */
+export function newRowId(kind: string, name: string): string {
+ const account = tenantAccount();
+ return account ? createAccountProject(account, kind, { name, data: {} }).id : nanoid(10);
+}
+
+/** An account's project made for a row that then couldn't be stored: let go of it. */
+export function dropRowId(kind: string, id: string): void {
+ const account = tenantAccount();
+ if (account) deleteAccountProject(account, kind, id);
+}
+
+/** Whose a channel is: an account's id, or null for the owner's. */
+export const channelOwner = (id: string): string | null => accountProjectOwner(CHANNEL_KIND, id);
+
+/** Whose an episode is: its channel's, or (an explainer) its own project's. */
+export const episodeOwner = (r: { id: string; channel_id: string | null }): string | null => (r.channel_id ? channelOwner(r.channel_id) : accountProjectOwner(EXPLAINER_KIND, r.id));
+
+/** Whether a row whose owner this is belongs to whoever the work is for: an account its own, the owner never an account's. */
+export const forViewer = (owner: string | null): boolean => !guestWork() && owner === (tenantAccount() ?? null);
+
+/** `column IN / NOT IN (…)`: the rows of one kind that are whoever the work is for (a guest's: none). */
+export function viewerScope(column: string, kind: string): { sql: string; args: unknown[] } {
+ if (guestWork()) return { sql: "0", args: [] };
+ const account = tenantAccount();
+ const ids = accountProjectIds(kind, account);
+ return { sql: account ? `${column} IN (${ids.sql})` : `${column} NOT IN (${ids.sql})`, args: ids.args };
+}
+
+/** The episodes that are whoever the work is for: an account's channels' and its explainers; the owner's, none of those. */
+function episodeScope(): { sql: string; args: unknown[] } {
+ if (guestWork()) return { sql: "0", args: [] };
+ const account = tenantAccount();
+ const channels = accountProjectIds(CHANNEL_KIND, account);
+ const explainers = accountProjectIds(EXPLAINER_KIND, account);
+ return account
+ ? { sql: `(channel_id IN (${channels.sql}) OR (channel_id IS NULL AND id IN (${explainers.sql})))`, args: [...channels.args, ...explainers.args] }
+ : { sql: `((channel_id IS NULL OR channel_id NOT IN (${channels.sql})) AND id NOT IN (${explainers.sql}))`, args: [...channels.args, ...explainers.args] };
+}
+
+const episodeRow = (id: string) => {
+ const r = db().prepare("SELECT * FROM faceless_episodes WHERE id = ?").get(id) as EpisodeRow | undefined;
+ return r && forViewer(episodeOwner(r)) ? r : undefined;
+};
function mustEpisode(id: string): FacelessEpisode {
const r = episodeRow(id);
@@ -229,6 +291,8 @@ const TOPICS_TIMEOUT_MS = 25_000;
/** 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, o: AskOptions = {}): Promise<string | null> {
+ // An account's work, or a visitor's price check, never uses the install's AI helper: the offline wording is used.
+ if (tenant()) return null;
if (getSetting("demoMode") === "on") return null;
// A text model switched off in Settings → Models & licences gives way to the offline wording, like no LLM at all.
const found = getModel(ENGINE_MODELS[engine].write);
@@ -282,10 +346,14 @@ function refreshAvatar(r: ChannelRow): ChannelRow {
return next;
}
-const channelRow = (id: string) => db().prepare("SELECT * FROM faceless_channels WHERE id = ?").get(id) as ChannelRow | undefined;
+const channelRow = (id: string) => {
+ const r = db().prepare("SELECT * FROM faceless_channels WHERE id = ?").get(id) as ChannelRow | undefined;
+ return r && forViewer(channelOwner(id)) ? r : undefined;
+};
export function listChannels(): FacelessChannel[] {
- const rows = (db().prepare("SELECT * FROM faceless_channels ORDER BY updated_at DESC").all() as ChannelRow[]).map(refreshAvatar);
+ const scope = viewerScope("id", CHANNEL_KIND);
+ const rows = (db().prepare(`SELECT * FROM faceless_channels WHERE ${scope.sql} ORDER BY updated_at DESC`).all(...scope.args) as ChannelRow[]).map(refreshAvatar);
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]),
);
@@ -304,11 +372,15 @@ export function getChannel(id: string): FacelessChannel | null {
return r ? toChannel(refreshAvatar(r)) : null;
}
-/** Title and thumbnail of a YouTube link (oEmbed, through the SSRF-safe fetch); the thumbnail is saved as an upload. */
+/**
+ * Title and thumbnail of a YouTube link (oEmbed, through the SSRF-safe fetch); the thumbnail is saved as an upload. An
+ * account's is kept as the plain link: the server never fetches a link for an account (docs/public-signup.md).
+ */
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 };
+ if (tenant()) return ref;
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 };
@@ -345,9 +417,10 @@ export async function createChannel(input: { idea: string; genre: FacelessGenre;
const reference = input.reference?.trim() ? await readReference(input.reference) : null;
const given = input.name?.trim().slice(0, 60) || null;
const now = Date.now();
+ const firstName = given ?? channelName(idea);
const row: ChannelRow = {
- id: nanoid(10),
- name: given ?? channelName(idea),
+ id: newRowId(CHANNEL_KIND, firstName),
+ name: firstName,
idea: idea.slice(0, 500),
genre: input.genre,
avatar_url: null,
@@ -357,9 +430,14 @@ export async function createChannel(input: { idea: string; genre: FacelessGenre;
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);
+ try {
+ db()
+ .prepare(`INSERT INTO faceless_channels (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)
+ .run(row);
+ } catch (e) {
+ dropRowId(CHANNEL_KIND, row.id);
+ throw e;
+ }
const job = (async () => {
if (!given) {
const answer = await askLlm(input.engine, NAME_SYSTEM, `Channel idea: ${idea}\nGenre: ${genreInfo(input.genre).label}`, { timeoutMs: NAME_TIMEOUT_MS });
@@ -368,8 +446,9 @@ export async function createChannel(input: { idea: string; genre: FacelessGenre;
}
try {
// avatar: false (Assist's channel) leaves the initials and the "Draw an avatar" button; Content Factory
- // series show their reference instead (no picture to pay for).
- if (input.avatar !== false && channelRow(row.id)) makeAvatar(row.id);
+ // series show their reference instead (no picture to pay for). An account's avatar is a run on its own GPU or
+ // key, started by the route after that run's checks (src/app/api/faceless/channels).
+ if (input.avatar !== false && !tenantAccount() && channelRow(row.id)) makeAvatar(row.id);
} catch {
// No picture model can run right now: the channel shows its initials, and "Draw an avatar" is there.
}
@@ -413,25 +492,44 @@ export async function deleteChannel(id: string): Promise<void> {
db().prepare("DELETE FROM faceless_episodes WHERE channel_id = ?").run(id);
db().prepare("DELETE FROM faceless_channels WHERE id = ?").run(id);
})();
+ dropRowId(CHANNEL_KIND, id);
await Promise.all(stops);
}
+/**
+ * When an account is deleted (account-sweep.ts purgeAccount, before its projects go): its channels, their episodes and
+ * its explainers. Its runs are deleted with the account.
+ */
+export function deleteAccountFaceless(accountId: string): void {
+ const channels = accountProjectIds(CHANNEL_KIND, accountId);
+ const explainers = accountProjectIds(EXPLAINER_KIND, accountId);
+ db().transaction(() => {
+ db().prepare(`DELETE FROM faceless_episodes WHERE channel_id IN (${channels.sql}) OR (channel_id IS NULL AND id IN (${explainers.sql}))`).run(...channels.args, ...explainers.args);
+ db().prepare(`DELETE FROM faceless_channels WHERE id IN (${channels.sql})`).run(...channels.args);
+ })();
+}
+
/** A channel avatar in the channel's style (one picture generation); it becomes the channel's picture when it's done. */
export function makeAvatar(id: string): Generation {
+ const [g] = createGenerations(avatarRequest(id));
+ db().prepare("UPDATE faceless_channels SET avatar_job = ? WHERE id = ?").run(g.id, id);
+ return g;
+}
+
+/** The avatar's one picture generation, as makeAvatar creates it (an account's run is checked with it first). */
+export function avatarRequest(id: string): GenerationRequest {
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({
+ return {
feature: "faceless-avatar",
modelId: ENGINE_MODELS[engine].still,
// The words name only what the picture shows (the open still model draws any words it is given, and reads no negatives).
prompt: `A round channel avatar for a YouTube channel about ${subjectOf(c.idea) || c.name}: one bold, simple pictorial emblem, centred on a plain background. Style: ${style.look}.`,
params: { aspectRatio: "1:1", numOutputs: 1 },
title: `${c.name} · avatar`,
- });
- db().prepare("UPDATE faceless_channels SET avatar_job = ? WHERE id = ?").run(g.id, id);
- return g;
+ };
}
// ---------------------------------------------------------------------------
@@ -475,11 +573,22 @@ export interface EpisodeInput {
blocks?: Partial<ScriptBlock>[];
/** The title before the script names it (a series' planned episode title). */
title?: string;
+ /**
+ * A script composed already (composeScript): an account's, written before its run is checked, so what renders is
+ * what was checked. No writer runs; it's ready to review, or renders at once with autoRender.
+ */
+ composed?: EpisodeScript;
+ /** The render's batch: an account's series renders its episodes as one run. */
+ batchId?: string;
}
+/** An account's episode on the cloud engine without a key of its own (its engine mode is open source only). */
+export const ACCOUNT_CLOUD_ENGINE = "Add a fal.ai or Replicate key to make this on the cloud engine, or switch to open source to make it on your GPU.";
+
function cleanSettings(s: EpisodeSettings): EpisodeSettings {
const mode = engineMode();
if (mode !== "both" && s.engine !== mode) {
+ if (tenant()) throw new FacelessError(ACCOUNT_CLOUD_ENGINE, 422);
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 {
@@ -493,7 +602,8 @@ function cleanSettings(s: EpisodeSettings): EpisodeSettings {
export function createEpisode(input: EpisodeInput): FacelessEpisode {
const topic = input.topic.trim();
const pasted = input.script?.trim() ?? "";
- const written = input.blocks ? normalizeBlocks(input.blocks) : null;
+ const composed = input.composed ?? null;
+ const written = composed ? normalizeBlocks(composed.blocks) : input.blocks ? normalizeBlocks(input.blocks) : null;
if (!topic && !pasted && !input.sources?.length && !written?.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 || (written && narrationText(written).length > MAX_SCRIPT)) throw new FacelessError("That script is too long to narrate. Shorten it and try again.");
if (written && !written.length) throw new FacelessError("The script has no scenes yet");
@@ -503,9 +613,12 @@ export function createEpisode(input: EpisodeInput): FacelessEpisode {
const sources = (input.sources ?? []).slice(0, MAX_SOURCES);
settings.sourceImages = sources.filter((s): s is Extract<ExplainerSource, { kind: "image" }> => s.kind === "image").map((s) => s.url);
const now = Date.now();
- const title = (input.title?.trim() || topic || pasted || written?.[0]?.narration || "").replace(/\s+/g, " ").slice(0, input.title ? 120 : 80) || "Untitled episode";
+ const named = composed?.title?.trim() || input.title?.trim();
+ const title = (named || topic || pasted || written?.[0]?.narration || "").replace(/\s+/g, " ").slice(0, named ? 120 : 80) || "Untitled episode";
+ const script: EpisodeScript = composed ? { ...composed, blocks: written! } : written ? { blocks: written, source: "ai" } : { blocks: [], source: pasted ? "pasted" : "ai" };
const row: EpisodeRow = {
- id: nanoid(10),
+ // An explainer of an account's is its own project (a channel's episodes are their channel's).
+ id: channel ? nanoid(10) : newRowId(EXPLAINER_KIND, title),
channel_id: channel?.id ?? null,
kind: input.kind,
title,
@@ -513,7 +626,7 @@ export function createEpisode(input: EpisodeInput): FacelessEpisode {
status: written ? "review" : "writing",
error: null,
settings_json: JSON.stringify(settings),
- script_json: JSON.stringify((written ? { blocks: written, source: "ai" } : { blocks: [], source: pasted ? "pasted" : "ai" }) satisfies EpisodeScript),
+ script_json: JSON.stringify(script),
plan_json: null,
sources_json: JSON.stringify(sources),
favorite: 0,
@@ -521,9 +634,14 @@ export function createEpisode(input: EpisodeInput): FacelessEpisode {
updated_at: now,
};
const first = channel ? !(db().prepare("SELECT 1 FROM faceless_episodes WHERE channel_id = ? LIMIT 1").get(channel.id) as unknown) : false;
- db()
- .prepare(`INSERT INTO faceless_episodes (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)
- .run(row);
+ try {
+ db()
+ .prepare(`INSERT INTO faceless_episodes (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)
+ .run(row);
+ } catch (e) {
+ if (!channel) dropRowId(EXPLAINER_KIND, row.id);
+ throw e;
+ }
if (channel && (input.saveLook ?? first)) {
void updateChannel(channel.id, {
settings: {
@@ -543,14 +661,16 @@ export function createEpisode(input: EpisodeInput): FacelessEpisode {
if (written) {
if (!input.autoRender) return toEpisode(row);
try {
- return renderEpisode(row.id);
+ return renderEpisode(row.id, input.batchId);
} catch (e) {
// The script is there: show it with what's in the way, as a written script that can't render does.
updateEpisodeRow(row.id, { status: "review", error: (e as Error).message });
return mustEpisode(row.id);
}
}
- startWriting(row.id, pasted, !!input.autoRender);
+ // An account's render starts only after its run's checks (src/server/account-tool-run.ts), with a script composed
+ // first: one written here waits for review.
+ startWriting(row.id, pasted, !!input.autoRender && !tenant());
return toEpisode(row);
}
@@ -581,9 +701,20 @@ function startWriting(id: string, pasted: string, autoRender: boolean): Promise<
/** Wait for a script that's being written (tests, and the API's `?wait=1`). */
export const scriptWritten = (id: string) => writing().get(id)?.job ?? Promise.resolve();
-async function writeScript(id: string, pasted: string, signal: AbortSignal): Promise<void> {
- const ep = mustEpisode(id);
- const genre = genreInfo(ep.channelId ? (getChannel(ep.channelId)?.genre ?? "education") : "education");
+/** What the script writer reads: the episode as it is (or will be) stored. */
+export type ScriptAsk = Pick<FacelessEpisode, "kind" | "channelId" | "topic" | "settings" | "sources"> & {
+ /** The channel's genre, for an episode whose channel isn't made yet (an account's series, composed before its run). */
+ genre?: FacelessGenre;
+};
+
+/**
+ * A script for an episode: the engine's LLM when it answers, else the offline writer (a pasted script is split into scenes
+ * and its pictures planned). An account's is always the offline writer's (askLlm), without the install's notes about its
+ * AI helper, and never names the owner's elements.
+ */
+export async function composeScript(ep: ScriptAsk, pasted: string, signal?: AbortSignal): Promise<EpisodeScript> {
+ const visitor = !!tenant();
+ const genre = genreInfo(ep.genre ?? (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);
@@ -592,7 +723,7 @@ async function writeScript(id: string, pasted: string, signal: AbortSignal): Pro
const sceneSecs = s.brief?.sceneSeconds ? Math.max(4, Math.min(10, Math.round(s.brief.sceneSeconds))) : 10;
const scenes = s.brief?.sceneSeconds && !auto ? Math.max(1, Math.round(s.length / sceneSecs)) : blockCount(auto ? AUTO_SECONDS : s.length);
const handles = new Set(s.elements.map((h) => h.toLowerCase()));
- const elements = listElements()
+ const elements = (visitor ? [] : 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, SOURCE_CHARS)}`] : x.kind === "link" ? [`${x.title ?? x.url} (${x.url}): ${x.text.slice(0, SOURCE_CHARS)}`] : []));
@@ -606,7 +737,7 @@ async function writeScript(id: string, pasted: string, signal: AbortSignal): Pro
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 a local model (Ollama, LM Studio or Unsloth Studio) in Settings for better scenes." }),
+ ...(!visuals && !visitor && { offline: true, note: failure ? `Pictures planned offline (${failure}).` : "Pictures planned from your words — connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings for better scenes." }),
};
} else {
const topic = ep.topic || textSources[0]?.slice(0, 300) || "this topic";
@@ -632,9 +763,15 @@ async function writeScript(id: string, pasted: string, signal: AbortSignal): Pro
// The offline beats run about 10 s each: a brief's shorter scenes would overshoot the length, so middle beats go.
if (s.brief?.sceneSeconds && !auto) while (blocks.length > 1 && totalSeconds(blocks) > s.length * 1.15) blocks.splice(Math.floor(blocks.length / 2), 1);
if (elements.length) for (const b of blocks) b.visual = `${b.visual}, with ${elements.map((e) => `@${e.handle}`).join(" and ")}`;
- script = { source: "ai", blocks, offline: true, note: failure ? `${OFFLINE_NOTE} (${failure})` : OFFLINE_NOTE };
+ script = visitor ? { source: "ai", blocks } : { source: "ai", blocks, offline: true, note: failure ? `${OFFLINE_NOTE} (${failure})` : OFFLINE_NOTE };
}
}
+ return script;
+}
+
+async function writeScript(id: string, pasted: string, signal: AbortSignal): Promise<void> {
+ const ep = mustEpisode(id);
+ const script = await composeScript(ep, pasted, signal);
if (signal.aborted || !episodeRow(id)) return;
updateEpisodeRow(id, {
status: "review",
@@ -689,6 +826,7 @@ export async function deleteEpisode(id: string): Promise<void> {
const ep = mustEpisode(id);
const stops = stopEpisode(ep);
db().prepare("DELETE FROM faceless_episodes WHERE id = ?").run(id);
+ if (!ep.channelId) dropRowId(EXPLAINER_KIND, id);
await Promise.all(stops);
}
@@ -902,8 +1040,8 @@ function advance(ep: FacelessEpisode): FacelessEpisode {
return mustEpisode(ep.id);
}
-/** Start the render: the whole graph is checked first, then stage one (pictures, narration, its timing) starts. */
-export function renderEpisode(id: string): FacelessEpisode {
+/** The episode ready to render and its whole graph, checked (nothing is created). */
+function renderable(id: string): { ready: FacelessEpisode; blocks: ScriptBlock[]; graph: GraphStep[] } {
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);
@@ -913,7 +1051,75 @@ export function renderEpisode(id: string): FacelessEpisode {
const ready = { ...ep, script: { ...ep.script, blocks } };
const graph = buildGraph(ready, blocks);
validate(graph);
- const batchId = nanoid(10);
+ return { ready, blocks, graph };
+}
+
+/**
+ * A graph's steps as an account's run is checked with them (src/server/account-tool-run.ts ToolStep): each request with
+ * its chain, waiting for as many earlier steps as it names. Every step of the graph, so every provider it reaches, its
+ * words and its files are checked before the first one starts.
+ */
+export function graphToolSteps(graph: GraphStep[]): { request: GenerationRequest; deps: number }[] {
+ return graph.map((s) => ({ request: { ...s.request, ...(s.chain && { chain: s.chain }) }, deps: s.after?.length ?? 0 }));
+}
+
+/** The files a graph's steps read (uploads and results): an account's must all be its own. */
+export function graphFiles(graph: GraphStep[]): string[] {
+ const files = new Set<string>();
+ for (const s of graph) {
+ for (const v of Object.values(s.request.inputs ?? {})) for (const x of Array.isArray(v) ? v : [v]) if (typeof x === "string" && x) files.add(x);
+ }
+ return [...files];
+}
+
+/** What "Render" would run (an account's run is checked with it first). */
+export const renderGraph = (id: string): GraphStep[] => renderable(id).graph;
+
+/** The settings an episode is stored with: its picture sources set from the explainer's image sources. */
+function storedSettings(settings: EpisodeSettings, sources: ExplainerSource[]): EpisodeSettings {
+ const s = cleanSettings(settings);
+ s.sourceImages = sources.slice(0, MAX_SOURCES).filter((x): x is Extract<ExplainerSource, { kind: "image" }> => x.kind === "image").map((x) => x.url);
+ return s;
+}
+
+/**
+ * The graph an episode that isn't made yet would render with this script: an account's explainer or series episode,
+ * checked before anything is made. `genre`: the channel's (one that's made in the same run isn't there yet).
+ */
+export function draftGraph(input: { kind: "faceless" | "explainer"; channelId?: string | null; title: string; settings: EpisodeSettings; sources?: ExplainerSource[]; script: EpisodeScript; genre?: FacelessGenre }): GraphStep[] {
+ const blocks = normalizeBlocks(input.script.blocks);
+ if (!blocks.length) throw new FacelessError("The script has no scenes yet");
+ const ep: FacelessEpisode = {
+ id: "draft",
+ channelId: input.channelId ?? null,
+ kind: input.kind,
+ title: input.title,
+ topic: "",
+ status: "review",
+ error: null,
+ settings: storedSettings(input.settings, input.sources ?? []),
+ script: { ...input.script, blocks },
+ plan: null,
+ sources: [],
+ favorite: false,
+ createdAt: 0,
+ updatedAt: 0,
+ };
+ let graph: GraphStep[];
+ try {
+ graph = buildEpisodeGraph({ ...graphInput(ep, blocks), ...(input.genre && { genre: genreInfo(input.genre) }) }, getModel);
+ } catch (e) {
+ if (e instanceof FacelessError || e instanceof ConnectComfyError) throw e;
+ throw new FacelessError((e as Error).message, 422);
+ }
+ validate(graph);
+ return graph;
+}
+
+/** Start the render: the whole graph is checked first, then stage one (pictures, narration, its timing) starts. */
+export function renderEpisode(id: string, batch?: string): FacelessEpisode {
+ const { ready, graph } = renderable(id);
+ const batchId = batch ?? nanoid(10);
const { ids, awaiting } = launch(ready, graph, {}, graph.map((s) => s.key), batchId);
const plan: EpisodePlan = { batchId, ids, awaiting, changes: [] };
updateEpisodeRow(id, { status: "rendering", error: null, plan_json: JSON.stringify(plan), script_json: JSON.stringify(ready.script) });
@@ -978,6 +1184,19 @@ export interface ChangeInput {
narration?: string[];
}
+/** What "Retry" would run, at most (an account's run is checked with it first): the episode's graph as it renders now. */
+export function retryGraph(id: string): GraphStep[] {
+ const ep = mustEpisode(id);
+ return ep.plan ? currentGraph(ep) : renderGraph(id);
+}
+
+/** The steps a change would run (an account's run is checked with them first). */
+export function changeGraph(id: string, c: ChangeInput): GraphStep[] {
+ const { graph, plan } = changed(mustEpisode(id), c);
+ const rerun = new Set(plan.rerun);
+ return graph.filter((s) => rerun.has(s.key));
+}
+
/** The blocks, picture edits and graph a change would render, and the steps it touches. */
function changed(ep: FacelessEpisode, c: ChangeInput) {
if (!ep.plan) throw new FacelessError("Render the episode first", 409);
@@ -1119,26 +1338,37 @@ function upscaleOffer(ep: FacelessEpisode, seconds: number): EpisodeView["upscal
/** "Upscale to 1080p": one upscale step on the finished film, offered as the download once it's done. */
export function upscaleEpisode(id: string): FacelessEpisode {
const ep = mustEpisode(id);
- const modelId = ENGINE_MODELS[ep.settings.engine].upscale;
- if (!modelId) throw new FacelessError("This engine has no video upscaler", 422);
- const final = finalOf(ep);
- if (!ep.plan || !final) throw new FacelessError("Wait for the episode to finish first", 409);
- const had = ep.plan.upscaled ? getGeneration(ep.plan.upscaled) : null;
- if (had && had.status !== "failed" && had.status !== "canceled") return ep;
+ const up = upscaleStep(ep);
+ if (!up) return ep;
let g: Generation;
try {
- [g] = createGenerations(
- { feature: ep.kind, modelId, op: "upscale-video", params: { resolution: "1080p" }, chain: [{ slot: "video" }], title: `${ep.title} · 1080p`, batchTitle: ep.title, step: { label: "Upscale to 1080p", index: 0, of: 1 } },
- { batchId: ep.plan.batchId, dependsOn: final.id },
- );
+ [g] = createGenerations(up.request, { batchId: ep.plan!.batchId, dependsOn: up.final.id });
} catch (e) {
if (e instanceof ConnectComfyError) throw e;
throw new FacelessError((e as Error).message, 422);
}
- updateEpisodeRow(id, { plan_json: JSON.stringify({ ...ep.plan, upscaled: g.id } satisfies EpisodePlan) });
+ updateEpisodeRow(id, { plan_json: JSON.stringify({ ...ep.plan!, upscaled: g.id } satisfies EpisodePlan) });
return mustEpisode(id);
}
+/** The upscale step on the finished film, or null when one is made or making already. */
+function upscaleStep(ep: FacelessEpisode): { request: GenerationRequest; final: Generation } | null {
+ const modelId = ENGINE_MODELS[ep.settings.engine].upscale;
+ if (!modelId) throw new FacelessError("This engine has no video upscaler", 422);
+ const final = finalOf(ep);
+ if (!ep.plan || !final) throw new FacelessError("Wait for the episode to finish first", 409);
+ const had = ep.plan.upscaled ? getGeneration(ep.plan.upscaled) : null;
+ if (had && had.status !== "failed" && had.status !== "canceled") return null;
+ const request: GenerationRequest = { feature: ep.kind, modelId, op: "upscale-video", params: { resolution: "1080p" }, chain: [{ slot: "video" }], title: `${ep.title} · 1080p`, batchTitle: ep.title, step: { label: "Upscale to 1080p", index: 0, of: 1 } };
+ return { request, final };
+}
+
+/** What "Upscale to 1080p" would run (an account's run is checked with it first): nothing when it's made or making. */
+export function upscaleToolSteps(id: string): { request: GenerationRequest; deps: number }[] {
+ const up = upscaleStep(mustEpisode(id));
+ return up ? [{ request: up.request, deps: 1 }] : [];
+}
+
// ---------------------------------------------------------------------------
// Regenerate to 1080p (open engine)
@@ -1259,7 +1489,10 @@ function sweep(): void {
const rows = db().prepare("SELECT * FROM faceless_episodes WHERE status = 'rendering' AND plan_json LIKE '%\"awaiting\":true%'").all() as EpisodeRow[];
for (const r of rows) {
try {
- settle(toEpisode(r));
+ // An account's episode goes on as its own work: its steps stamped as its runs, on its own GPU or key.
+ const owner = episodeOwner(r);
+ if (owner) asAccount(owner, () => settle(toEpisode(r)));
+ else settle(toEpisode(r));
} catch (e) {
console.warn(`[faceless] couldn't continue ${r.id}: ${(e as Error).message}`);
}
@@ -1356,8 +1589,10 @@ function toCard(r: EpisodeRow): EpisodeCard {
}
export function listEpisodes(o: { channelId?: string; kind?: "faceless" | "explainer"; q?: string; liked?: boolean; limit?: number }): EpisodeCard[] {
- const where: string[] = [];
- const args: unknown[] = [];
+ // Whoever the work is for: an account's own episodes, or the owner's.
+ const scope = episodeScope();
+ const where: string[] = [scope.sql];
+ const args: unknown[] = [...scope.args];
if (o.channelId) {
where.push("channel_id = ?");
args.push(o.channelId);
@@ -1373,7 +1608,7 @@ export function listEpisodes(o: { channelId?: string; kind?: "faceless" | "expla
args.push(`%${q}%`, `%${q}%`);
}
const rows = db()
- .prepare(`SELECT * FROM faceless_episodes ${where.length ? `WHERE ${where.join(" AND ")}` : ""} ORDER BY created_at DESC LIMIT ?`)
+ .prepare(`SELECT * FROM faceless_episodes 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);
}
@@ -1455,18 +1690,27 @@ function notesFor(settings: EpisodeSettings, seconds: number): { notes?: string[
/** A short sample of a premade narrator (one cheap speech generation, reused once made). */
export function voicePreview(voice: NarratorVoice & { kind: "preset" }): Generation {
+ const p = voicePreviewPlan(voice);
+ return "made" in p ? p.made : createGenerations(p.request)[0];
+}
+
+/**
+ * The narrator sample made before (only the asker's own: an account's, or the owner's), or the one speech generation that
+ * makes it (an account's run is checked with it first).
+ */
+export function voicePreviewPlan(voice: NarratorVoice & { kind: "preset" }): { made: Generation } | { request: GenerationRequest } {
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",
+ "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 COALESCE(json_extract(g.request_json, '$.account'), '') = ? AND g.status IN ('queued', 'running', 'succeeded') ORDER BY g.created_at DESC LIMIT 1",
)
- .get(modelId, v.id) as { id: string } | undefined;
+ .get(modelId, v.id, tenantAccount() ?? "") 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];
+ if (found) return { made: found };
+ return { request: { feature: "faceless-voice", modelId, op: "tts", prompt: previewLine(v.name), params: { voice: v.id }, title: `${v.name} · narrator sample` } };
}
const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
@@ -1654,7 +1898,7 @@ export async function handle(fn: () => Promise<Response> | Response, request?: R
try {
return await fn();
} catch (e) {
- if (e instanceof FacelessError) return Response.json({ error: e.message }, { status: e.status });
+ if (e instanceof FacelessError || e instanceof AccountProjectError) return Response.json({ error: e.message }, { status: e.status });
if (e instanceof ConnectComfyError) return (request && connectRefusal(e, request)) || Response.json({ error: e.message }, { status: 422 });
console.error("[faceless]", e);
return Response.json({ error: (e as Error).message || "Something went wrong" }, { status: 500 });
diff --git a/src/server/records.ts b/src/server/records.ts
index e6aa3874..59c0aab7 100644
--- a/src/server/records.ts
+++ b/src/server/records.ts
@@ -1,6 +1,6 @@
import "server-only";
import type { RecordRef } from "@/lib/record-pages";
-import { getAccountProject } from "./account-projects";
+import { accountProjectOwner, getAccountProject } from "./account-projects";
import { requestAccount } from "./auth";
import { db } from "./db";
@@ -35,7 +35,20 @@ export function recordExists(ref: RecordRef): boolean {
}
/** Record pages a tool keeps per account (public sign-up): the project kind it keeps them as (account-projects.ts). */
-const ACCOUNT_KINDS: Partial<Record<RecordRef["kind"], string>> = { shorts: "shorts", cinema: "cinema", "swap-project": "swap" };
+const ACCOUNT_KINDS: Partial<Record<RecordRef["kind"], string>> = {
+ shorts: "shorts",
+ cinema: "cinema",
+ "swap-project": "swap",
+ // Faceless channels, their episodes (the channel is the project), explainers and Content Factory series: their rows
+ // live in the tool's own tables under the project's id (src/server/faceless.ts, content-factory.ts).
+ channel: "faceless",
+ episode: "faceless",
+ explainer: "explainer",
+ series: "content-factory",
+};
+
+/** Kinds whose rows share the tool's table with the owner's: the project only says whose a row is. */
+const SHARED_TABLE = new Set<RecordRef["kind"]>(["channel", "episode", "explainer", "series"]);
/**
* For a signed-in account: whether the record a page names is one of its own, on a page a tool keeps per account (null:
@@ -45,7 +58,7 @@ export function accountRecordExists(ref: RecordRef, accountId: string): boolean
const kind = ACCOUNT_KINDS[ref.kind];
if (!kind) return null;
try {
- return !!getAccountProject(accountId, kind, ref.ids[0]);
+ return !!getAccountProject(accountId, kind, ref.ids[0]) && (!SHARED_TABLE.has(ref.kind) || recordExists(ref));
} catch {
return true;
}
@@ -54,5 +67,9 @@ export function accountRecordExists(ref: RecordRef, accountId: string): boolean
/** recordExists for whoever asks (a page's request headers): an account's own on a page kept per account. */
export function recordFor(ref: RecordRef, headers: Headers): boolean {
const account = requestAccount({ headers } as Request);
- return (account && accountRecordExists(ref, account.id)) ?? recordExists(ref);
+ if (account) return accountRecordExists(ref, account.id) ?? recordExists(ref);
+ // The owner's page never opens an account's row of a shared table.
+ const kind = ACCOUNT_KINDS[ref.kind];
+ if (kind && SHARED_TABLE.has(ref.kind) && accountProjectOwner(kind, ref.ids[0])) return false;
+ return recordExists(ref);
}
diff --git a/src/server/starters.ts b/src/server/starters.ts
index b2da5e89..cd79a3b1 100644
--- a/src/server/starters.ts
+++ b/src/server/starters.ts
@@ -9,6 +9,7 @@ import { adoptSample } from "./canvas-samples";
import { appendChat, createProject, getChat, listItems, listProjects, updateProject } from "./cinema";
import { createElement, listElements } from "./elements";
import { createChannel, listChannels, updateChannel } from "./faceless";
+import { tenantAccount } from "./tenant";
/**
* The owner's "Use template" on a starter that is made here (POST /api/starters/<id>): a Cinema Studio project with its
@@ -17,8 +18,9 @@ import { createChannel, listChannels, updateChannel } from "./faceless";
* fills a composer (Assist, Storyboard, Content Factory, Explainer) or links to one (the Library's) is opened, not made.
*
* Guests get 401 and accounts 403 "library" before this runs (LIBRARY_CHANGES in src/lib/guest-access.ts): a starter
- * is saved to the owner's library. The one exception is a Cinema Studio film for a signed-in account: made inside its
- * own work (asAccount), it is that account's own project (src/server/cinema.ts reads and makes the asker's projects).
+ * is saved to the owner's library. The exceptions are a Cinema Studio film and a Faceless channel for a signed-in
+ * account: made inside its own work (asAccount), each is that account's own project (src/server/cinema.ts and
+ * faceless.ts read and make the asker's own).
*/
export class StarterError extends Error {
@@ -122,8 +124,9 @@ export async function createFromStarter(id: string, engine: Engine): Promise<{ h
return { href: "/elements", id: el.id, note };
}
if (seed.kind === "faceless") {
- // On the open engine the narrator clones a voice: the starter's own sample, while it is published.
- const voice = engine === "open" ? narrator(s) : undefined;
+ // On the open engine the narrator clones a voice: the starter's own sample, while it is published. That copy is the
+ // studio's file: an account's channel (made inside its own work) picks its own narrator in its first episode.
+ const voice = engine === "open" && !tenantAccount() ? narrator(s) : undefined;
// The channel made before from this starter (same name and idea) opens again, rather than a second one.
const known = listChannels().find((c) => c.name === seed.channel.name && c.idea === seed.channel.idea);
const channel = known
diff --git a/tests/account-content.test.ts b/tests/account-content.test.ts
new file mode 100644
index 00000000..5dd26032
--- /dev/null
+++ b/tests/account-content.test.ts
@@ -0,0 +1,706 @@
+import fs from "node:fs";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";
+import { tempDir } from "./helpers/temp-dir";
+
+vi.setConfig({ testTimeout: 180_000 });
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {}, after: () => {} }));
+
+/**
+ * Faceless Studio, the Explainer and Content Factory for a signed-in account (public sign-up): its channels, episodes,
+ * explainers and series are its own (account-projects.ts kinds "faceless", "explainer", "content-factory"), its scripts
+ * are the offline writer's (never the studio's AI helper), and every render and reading runs on its own ComfyUI (a
+ * stand-in here) through the same generations every studio run makes, with only its own files. A guest gets the
+ * sign-up card; another account's and the owner's are never reached.
+ */
+const dir = tempDir("fuobe-account-content-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+// The studio's own AI helper: recorded, so a test sees that an account's scripts never reach it.
+process.env.OLLAMA_URL = "http://owner-llm.test:11434";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;
+delete process.env.FUOBE_HOSTED_RUNS;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+// Plain fetch is the install's own ComfyUI or AI helper: recorded, so a test sees that nothing reached them.
+const realFetch = globalThis.fetch;
+const fetched: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = new URL(String(input instanceof Request ? input.url : input));
+ if (url.hostname === "127.0.0.1") return realFetch(input, init);
+ fetched.push(url.toString());
+ if (url.host !== "owner-comfy.test:8188") return new Response("not stubbed", { status: 599 });
+ if (url.pathname === "/system_stats") return Response.json({ system: { comfyui_version: "owner", ram_total: 1 }, devices: [] });
+ return Response.json({});
+}) as typeof fetch;
+// The runner's start lists the AI helper's models once (/api/tags): a status read, never a request with anyone's words.
+const reachedOwner = () => fetched.filter((u) => !u.endsWith("/system_stats") && !u.endsWith("/api/tags"));
+
+const auth = await import("@/server/auth");
+const channelsRoute = await import("@/app/api/faceless/channels/route");
+const channelRoute = await import("@/app/api/faceless/channels/[id]/route");
+const avatarRoute = await import("@/app/api/faceless/channels/[id]/avatar/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 topicsRoute = await import("@/app/api/faceless/topics/route");
+const voicesRoute = await import("@/app/api/faceless/voices/preview/route");
+const facelessEstimate = await import("@/app/api/faceless/estimate/route");
+const explainerRoute = await import("@/app/api/explainer/route");
+const documentRoute = await import("@/app/api/explainer/document/route");
+const seriesListRoute = await import("@/app/api/content-factory/series/route");
+const seriesRoute = await import("@/app/api/content-factory/series/[id]/route");
+const generateRoute = await import("@/app/api/content-factory/series/[id]/generate/route");
+const moreRoute = await import("@/app/api/content-factory/series/[id]/episodes/route");
+const readRoute = await import("@/app/api/content-factory/series/[id]/read/route");
+const cfEstimate = await import("@/app/api/content-factory/estimate/route");
+const startersRoute = await import("@/app/api/starters/[id]/route");
+const uploadsRoute = await import("@/app/api/uploads/route");
+const gpuRoute = await import("@/app/api/account/gpu/route");
+const { proxy } = await import("@/proxy");
+const access = await import("@/lib/guest-access");
+const { defaultSettings, genreInfo } = await import("@/lib/catalog/faceless");
+const faceless = await import("@/server/faceless");
+const { getGeneration } = await import("@/server/generations");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { clearAccountLoras } = await import("@/server/account-loras");
+const { saveFile } = await import("@/server/storage");
+const { runAsTenant } = await import("@/server/tenant");
+const { ACCOUNT_LIMITS } = await import("@/server/account-files");
+const store = await import("@/server/account-projects");
+const { recordFor } = await import("@/server/records");
+const { purgeAccount } = await import("@/server/account-sweep");
+const { provider } = await import("@/server/providers");
+// The studio's AI helper (the "llm" provider every script, name, topic and summary would go through): never asked for an account.
+const llmAsked = vi.spyOn(provider("llm"), "submit");
+
+const CLIP = fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4"));
+
+/** 12 s of a quiet tone: a narrator's sample (open-source narration clones a voice from 10–60 s of it). */
+const VOICE = (() => {
+ const rate = 16000;
+ const n = rate * 12;
+ 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 * 180 * i) / rate) * 4000), 44 + i * 2);
+ return buf;
+})();
+
+let fake: FakeComfy;
+let a = "";
+let b = "";
+let c = "";
+const cookies: Record<string, string> = {};
+const voices: Record<string, string> = {};
+beforeAll(async () => {
+ fake = await startFakeComfy({ loras: [], delayMs: 0, mixed: true });
+ globalThis.__fuobeTestGpuPort = fake.port;
+ auth.setPassword("install password");
+ for (const [k, email] of [
+ ["a", "[email protected]"],
+ ["b", "[email protected]"],
+ ["c", "[email protected]"],
+ ] as const) {
+ const id = auth.createAccount(email, "long enough").id;
+ cookies[k] = `${auth.SESSION_COOKIE}=${auth.createSession(id).value}`;
+ if (k === "a") a = id;
+ if (k === "b") b = id;
+ if (k === "c") c = id;
+ }
+ cookies.owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+ // A and B link their own ComfyUI; C has neither a GPU nor a key.
+ for (const who of ["a", "b"]) expect((await gpuRoute.PUT(json("/api/account/gpu", "PUT", { url: fake.url }, who))).status).toBe(200);
+ for (const who of ["a", "b"]) voices[who] = await upload(who, VOICE, "audio/wav", "narrator.wav");
+});
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestGpuPort = undefined;
+ globalThis.__fuobeTestDiskFree = undefined;
+ await fake.close();
+});
+beforeEach(() => {
+ resetRates();
+ for (const id of [a, b]) clearAccountLoras(id);
+});
+
+function json(url: string, method: string, body?: unknown, who?: string): Request {
+ const text = body === undefined ? "" : JSON.stringify(body);
+ return new Request(`http://localhost:3000${url}`, {
+ method,
+ headers: { host: "localhost:3000", "content-type": "application/json", "content-length": String(Buffer.byteLength(text)), ...(who && { cookie: cookies[who] }) },
+ ...(method !== "GET" && method !== "HEAD" && text && { body: text }),
+ });
+}
+const params = <T extends Record<string, string>>(p: T) => ({ params: Promise.resolve(p) }) as never;
+
+const viaProxy = (url: string, method = "GET", who?: string) =>
+ proxy(new NextRequest(`http://localhost:3000${url}`, { method, headers: { host: "localhost:3000", ...(who && { cookie: cookies[who] }), ...(method !== "GET" && { "content-type": "application/json" }) }, ...(method !== "GET" && { body: "{}" }) }));
+const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";
+
+async function upload(who: string, data: Buffer, type: string, name: string): Promise<string> {
+ const r = await uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: { host: "localhost:3000", cookie: cookies[who], "content-type": type, "x-file-name": name, "content-length": String(data.length) }, body: new Uint8Array(data) }));
+ expect(r.status, await r.clone().text()).toBe(201);
+ return ((await r.json()) as { url: string }).url;
+}
+
+/** Send a run; a LoRA its ComfyUI lacks is put there (the 409 names it), then it is sent again. */
+async function run(send: () => Promise<Response>): Promise<Response> {
+ let r = await send();
+ for (let i = 0; i < 3 && r.status === 409; i++) {
+ const j = (await r.clone().json()) as { code: string; fix?: { items: { file: string }[] } };
+ if (j.code !== "comfy_missing_model" || !j.fix) break;
+ fake.opts.loras = [...(fake.opts.loras ?? []), ...j.fix.items.map((x) => x.file)];
+ for (const id of [a, b]) clearAccountLoras(id);
+ r = await send();
+ }
+ return r;
+}
+
+/** An open-engine, 20-second explainer in still pictures, narrated by the account's own sample. */
+const explainerSettings = (who: string, extra: Record<string, unknown> = {}) => ({
+ ...defaultSettings("open", genreInfo("education"), { explainer: true }),
+ length: 20,
+ auto: false,
+ animation: "frames" as const,
+ music: false,
+ subtitles: false,
+ styleRefs: [],
+ elements: [],
+ voice: { kind: "sample", url: voices[who], name: "Narrator" },
+ ...extra,
+});
+
+interface EpisodeViewBody {
+ episode: { id: string; status: string; error: string | null; title: string; channelId: string | null; script: { blocks: unknown[]; offline?: boolean; note?: string }; plan: { batchId: string; ids: Record<string, string> } | null };
+ final: { id: string; outputs: { url: string }[] } | null;
+}
+
+const readEpisode = (id: string, who?: string) => episodeRoute.GET(json(`/api/faceless/episodes/${id}`, "GET", undefined, who), params({ id }));
+
+/** Tick the runner and read the episode (its first look after stage one starts stage two) until it is done or failed. */
+async function settleEpisode(id: string, who: string, ms = 90_000): Promise<EpisodeViewBody> {
+ const end = Date.now() + ms;
+ for (;;) {
+ await globalThis.__fuobeRunner?.tick();
+ const v = (await (await readEpisode(id, who)).json()) as EpisodeViewBody;
+ if (v.episode.status === "done" || v.episode.status === "failed" || Date.now() > end) return v;
+ await new Promise((r) => setTimeout(r, 100));
+ }
+}
+
+const accountOf = (gid: string) => getGeneration(gid, { includeDeleted: true })?.request.account;
+const count = () => (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
+const h = (who: string) => new Headers({ host: "localhost:3000", ...(cookies[who] && { cookie: cookies[who] }) });
+
+describe("the proxy opens the three tools to accounts, and keeps the sign-up card for guests", () => {
+ const CHANGES = [
+ ["POST", "/api/faceless/channels"],
+ ["PATCH", "/api/faceless/channels/ch1"],
+ ["DELETE", "/api/faceless/channels/ch1"],
+ ["POST", "/api/faceless/channels/ch1/avatar"],
+ ["POST", "/api/faceless/episodes"],
+ ["PATCH", "/api/faceless/episodes/ep1"],
+ ["DELETE", "/api/faceless/episodes/ep1"],
+ ["POST", "/api/faceless/episodes/ep1/render"],
+ ["POST", "/api/faceless/episodes/ep1/retry"],
+ ["POST", "/api/faceless/episodes/ep1/upscale"],
+ ["POST", "/api/faceless/episodes/ep1/change"],
+ ["POST", "/api/faceless/topics"],
+ ["POST", "/api/faceless/voices/preview"],
+ ["POST", "/api/explainer"],
+ ["POST", "/api/content-factory/series"],
+ ["PATCH", "/api/content-factory/series/s1"],
+ ["DELETE", "/api/content-factory/series/s1"],
+ ["POST", "/api/content-factory/series/s1/generate"],
+ ["POST", "/api/content-factory/series/s1/episodes"],
+ ["POST", "/api/content-factory/series/s1/read"],
+ ["POST", "/api/starters/faceless.boat-hotels"],
+ ] as const;
+
+ it("a guest gets the sign-up card on every change, empty lists, and nobody's channel, episode or series", async () => {
+ for (const [method, p] of CHANGES) {
+ const r = viaProxy(p, method);
+ expect(r.status, `${method} ${p}`).toBe(401);
+ expect(r.headers.get(access.GUEST_HEADER), p).toBe("1");
+ expect((await r.json()).error).toBe(access.GUEST_RUN_MESSAGE);
+ }
+ for (const p of ["/api/faceless/channels", "/api/faceless/episodes", "/api/explainer", "/api/content-factory/series"]) expect(await viaProxy(p).json(), p).toEqual({ items: [] });
+ for (const p of ["/api/faceless/channels/ch1", "/api/faceless/episodes/ep1", "/api/content-factory/series/s1"]) expect(viaProxy(p).status, p).toBe(401);
+ // Price checks stay open to everyone.
+ for (const p of ["/api/faceless/estimate", "/api/content-factory/estimate"]) expect(passed(viaProxy(p, "POST")), p).toBe(true);
+ // The explainer's document route makes the proxy's checks itself: a guest is asked to sign up.
+ const form = new FormData();
+ form.append("file", new File(["hello"], "notes.pdf", { type: "application/pdf" }));
+ const doc = await documentRoute.POST(new Request("http://localhost:3000/api/explainer/document", { method: "POST", headers: { host: "localhost:3000" }, body: form }));
+ expect(doc.status).toBe(401);
+ expect(doc.headers.get(access.GUEST_HEADER)).toBe("1");
+ });
+
+ it("an account reaches its own routes (the routes scope them); handing a brief to Claude stays the owner's", async () => {
+ for (const [method, p] of [...CHANGES, ["GET", "/api/faceless/channels"], ["GET", "/api/faceless/channels/ch1"], ["GET", "/api/faceless/episodes/ep1"], ["GET", "/api/explainer"], ["GET", "/api/content-factory/series/s1"]] as const) {
+ expect(passed(viaProxy(p, method, "a")), `${method} ${p}`).toBe(true);
+ }
+ const claude = viaProxy("/api/content-factory/claude", "POST", "a");
+ expect(claude.status).toBe(403);
+ expect((await claude.json()).code).toBe("own-gpu-tool");
+ // The server never fetches a link for an account (or a guest): an explainer's link source is the owner's.
+ for (const who of [undefined, "a"]) {
+ const link = viaProxy("/api/explainer/link", "POST", who);
+ expect(link.status, who).toBe(403);
+ expect((await link.json()).code).toBe("own-gpu-tool");
+ }
+ // "Regenerate to 1080p" stays held with Open-H3 Regenerate, for everyone.
+ const regen = viaProxy("/api/faceless/episodes/ep1/regenerate", "POST", "a");
+ expect(regen.status).toBe(403);
+ expect((await regen.json()).code).toBe("own-gpu-tool");
+ });
+
+ it("the routes refuse a guest themselves", async () => {
+ for (const [name, r] of [
+ ["channel", () => channelsRoute.POST(json("/api/faceless/channels", "POST", {}))],
+ ["episode", () => episodesRoute.POST(json("/api/faceless/episodes", "POST", {}))],
+ ["render", () => actionRoute.POST(json("/api/faceless/episodes/e/render", "POST"), params({ id: "e", action: "render" }))],
+ ["change", () => changeRoute.POST(json("/api/faceless/episodes/e/change", "POST", {}), params({ id: "e" }))],
+ ["explainer", () => explainerRoute.POST(json("/api/explainer", "POST", {}))],
+ ["series", () => seriesListRoute.POST(json("/api/content-factory/series", "POST", {}))],
+ ["generate", () => generateRoute.POST(json("/api/content-factory/series/s/generate", "POST", {}), params({ id: "s" }))],
+ ["topics", () => topicsRoute.POST(json("/api/faceless/topics", "POST", {}))],
+ ] as const) {
+ const res = await r();
+ expect(res.status, name).toBe(401);
+ expect(res.headers.get(access.GUEST_HEADER), name).toBe("1");
+ }
+ });
+});
+
+describe("Explainer: an account's explainers are its own and render on its own GPU", () => {
+ let id = "";
+ let view: EpisodeViewBody;
+
+ it("asks an account with neither a GPU nor a key to connect one, before anything is made", async () => {
+ const n = count();
+ const own = runAsTenant({ kind: "account", id: c }, () => saveFile({ data: VOICE, contentType: "audio/wav", source: "upload", name: "c.wav" }).url);
+ const r = await explainerRoute.POST(json("/api/explainer", "POST", { prompt: "How bees make honey", settings: { ...explainerSettings("a"), voice: { kind: "sample", url: own } } }, "c"));
+ expect(r.status, await r.clone().text()).toBe(403);
+ expect(r.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");
+ expect(count()).toBe(n);
+ expect(store.listAccountProjects(c, "explainer")).toEqual([]);
+ });
+
+ it("prices it for its own GPU, never as a demo", async () => {
+ const r = await facelessEstimate.POST(json("/api/faceless/estimate", "POST", { kind: "explainer", settings: explainerSettings("a") }, "a"));
+ expect(r.status, await r.clone().text()).toBe(200);
+ expect(((await r.json()) as { demo: boolean }).demo).toBe(false);
+ });
+
+ it("writes the script offline and renders it end to end: every step its own, on its ComfyUI", async () => {
+ fake.log.length = 0;
+ fetched.length = 0;
+ const r = await run(() => explainerRoute.POST(json("/api/explainer", "POST", { prompt: "How bees make honey", settings: explainerSettings("a") }, "a")));
+ expect(r.status, await r.clone().text()).toBe(201);
+ id = ((await r.json()) as { id: string }).id;
+ view = await settleEpisode(id, "a");
+ expect(view.episode.status, view.episode.error ?? "").toBe("done");
+ // The offline writer's script, with no note about the studio's AI helper.
+ expect(view.episode.script.blocks.length).toBeGreaterThan(0);
+ expect(view.episode.script.offline).toBeFalsy();
+ expect(view.episode.script.note).toBeUndefined();
+ expect(llmAsked).not.toHaveBeenCalled();
+ const gens = Object.values(view.episode.plan!.ids);
+ expect(gens.length).toBeGreaterThan(3);
+ for (const g of gens) {
+ expect(accountOf(g), g).toBe(a);
+ expect(getGeneration(g)?.status, `${g} ${getGeneration(g)?.modelId} ${getGeneration(g)?.error ?? ""}`).toBe("succeeded");
+ }
+ // One run: its steps share a batch; every step went to its own ComfyUI; nothing reached the studio's ComfyUI or AI helper.
+ expect(new Set(gens.map((g) => getGeneration(g)!.batchId)).size).toBe(1);
+ expect(fake.log.filter((e) => e.path === "/prompt").length).toBe(gens.length);
+ expect(reachedOwner()).toEqual([]);
+ // The explainer is the account's own project; the finished video is its own file, and it downloads.
+ expect(store.getAccountProject(a, "explainer", id)).not.toBeNull();
+ const out = view.final!.outputs[0].url;
+ expect(passed(viaProxy(out, "GET", "a"))).toBe(true);
+ expect(viaProxy(out, "GET", "b").status).toBe(403);
+ });
+
+ it("reopens it: its history lists it, and its page opens for it alone", async () => {
+ const list = (await (await explainerRoute.GET(json("/api/explainer", "GET", undefined, "a"))).json()) as { items: { id: string; status: string }[] };
+ expect(list.items.map((e) => e.id)).toEqual([id]);
+ expect(list.items[0].status).toBe("done");
+ expect(passed(viaProxy(`/explainer/${id}`, "GET", "a"))).toBe(true);
+ expect(viaProxy(`/explainer/${id}`, "GET", "b").status).toBe(404);
+ expect(recordFor({ kind: "explainer", ids: [id] }, h("a"))).toBe(true);
+ expect(recordFor({ kind: "explainer", ids: [id] }, h("b"))).toBe(false);
+ expect(recordFor({ kind: "explainer", ids: [id] }, h("owner"))).toBe(false);
+ });
+
+ it("another account and the owner never see, open, change or run it", async () => {
+ for (const who of ["b", "owner"]) {
+ const list = (await (await explainerRoute.GET(json("/api/explainer", "GET", undefined, who))).json()) as { items: { id: string }[] };
+ expect(list.items.map((e) => e.id), who).not.toContain(id);
+ }
+ fake.log.length = 0;
+ expect((await readEpisode(id, "b")).status).toBe(404);
+ expect((await readEpisode(id, "owner")).status).toBe(404);
+ for (const action of ["render", "retry", "upscale", "rewrite", "undo"]) {
+ expect((await actionRoute.POST(json(`/api/faceless/episodes/${id}/${action}`, "POST", undefined, "b"), params({ id, action }))).status, action).toBe(404);
+ }
+ expect((await changeRoute.POST(json(`/api/faceless/episodes/${id}/change`, "POST", { blocks: ["x"], part: "motion", instruction: "zoom", apply: true }, "b"), params({ id }))).status).toBe(404);
+ expect((await episodeRoute.PATCH(json(`/api/faceless/episodes/${id}`, "PATCH", { title: "mine" }, "b"), params({ id }))).status).toBe(404);
+ expect((await episodeRoute.DELETE(json(`/api/faceless/episodes/${id}`, "DELETE", undefined, "b"), params({ id }))).status).toBe(404);
+ expect(fake.log.some((e) => e.path === "/prompt")).toBe(false);
+ // A's narrator in B's explainer: refused before anything is planned or sent.
+ const r = await explainerRoute.POST(json("/api/explainer", "POST", { prompt: "Tides", settings: explainerSettings("a") }, "b"));
+ expect(r.status).toBe(403);
+ expect((await r.json()).code).toBe("input-not-yours");
+ });
+
+ it("never reaches the owner's explainers", async () => {
+ const owner = faceless.createEpisode({ kind: "explainer", topic: "The owner's explainer", settings: { ...explainerSettings("a"), voice: null }, blocks: [{ narration: "One.", visual: "A field" }] });
+ expect((await readEpisode(owner.id, "a")).status).toBe(404);
+ const list = (await (await explainerRoute.GET(json("/api/explainer", "GET", undefined, "a"))).json()) as { items: { id: string }[] };
+ expect(list.items.map((e) => e.id)).not.toContain(owner.id);
+ expect((await actionRoute.POST(json(`/api/faceless/episodes/${owner.id}/render`, "POST", undefined, "a"), params({ id: owner.id, action: "render" }))).status).toBe(404);
+ expect((await episodeRoute.DELETE(json(`/api/faceless/episodes/${owner.id}`, "DELETE", undefined, "a"), params({ id: owner.id }))).status).toBe(404);
+ expect(recordFor({ kind: "explainer", ids: [owner.id] }, h("a"))).toBe(false);
+ // The owner still has it.
+ expect((await readEpisode(owner.id, "owner")).status).toBe(200);
+ });
+
+ it("writes one for review first, then renders it from the review", async () => {
+ const n = count();
+ const r = await explainerRoute.POST(json("/api/explainer", "POST", { prompt: "Why the sky is blue", settings: explainerSettings("a"), review: true }, "a"));
+ expect(r.status, await r.clone().text()).toBe(201);
+ const ep = (await r.json()) as { id: string; status: string };
+ expect(ep.status).toBe("review");
+ expect(count()).toBe(n);
+ const go = await run(() => actionRoute.POST(json(`/api/faceless/episodes/${ep.id}/render`, "POST", undefined, "a"), params({ id: ep.id, action: "render" })));
+ expect(go.status, await go.clone().text()).toBe(200);
+ const v = await settleEpisode(ep.id, "a");
+ expect(v.episode.status, v.episode.error ?? "").toBe("done");
+ for (const g of Object.values(v.episode.plan!.ids)) expect(accountOf(g)).toBe(a);
+ });
+
+ it("a change from the timeline runs on its own GPU, after its checks", async () => {
+ const blocks = (await (await readEpisode(id, "a")).json()) as { scenes: { id: string }[] };
+ const scene = blocks.scenes[0].id;
+ const preview = await changeRoute.POST(json(`/api/faceless/episodes/${id}/change`, "POST", { blocks: [scene], part: "picture", instruction: "make it night" }, "a"), params({ id }));
+ expect(preview.status, await preview.clone().text()).toBe(200);
+ const before = count();
+ const r = await run(() => changeRoute.POST(json(`/api/faceless/episodes/${id}/change`, "POST", { blocks: [scene], part: "picture", instruction: "make it night", apply: true }, "a"), params({ id })));
+ expect(r.status, await r.clone().text()).toBe(201);
+ expect(count()).toBeGreaterThan(before);
+ const v = await settleEpisode(id, "a");
+ expect(v.episode.status, v.episode.error ?? "").toBe("done");
+ for (const g of Object.values(v.episode.plan!.ids)) expect(accountOf(g)).toBe(a);
+ });
+});
+
+describe("Faceless Studio: an account's channels and episodes are its own", () => {
+ let channel = "";
+ let episode = "";
+
+ it("makes a channel of its own, with an avatar drawn on its own GPU", async () => {
+ fake.log.length = 0;
+ fetched.length = 0;
+ const r = await channelsRoute.POST(json("/api/faceless/channels", "POST", { idea: "Strange hotels on the water", genre: "education", engine: "open" }, "a"));
+ expect(r.status, await r.clone().text()).toBe(201);
+ const ch = (await r.json()) as { id: string; name: string; avatarJob: string | null };
+ channel = ch.id;
+ expect(store.getAccountProject(a, "faceless", channel)).not.toBeNull();
+ expect(ch.avatarJob).toBeTruthy();
+ expect(accountOf(ch.avatarJob!)).toBe(a);
+ expect(fake.log.filter((e) => e.path === "/prompt").length).toBeLessThanOrEqual(1);
+ expect(reachedOwner()).toEqual([]);
+ const list = (await (await channelsRoute.GET(json("/api/faceless/channels", "GET", undefined, "a"))).json()) as { items: { id: string }[] };
+ expect(list.items.map((x) => x.id)).toEqual([channel]);
+ });
+
+ it("an account without a GPU or key still makes its channel; its avatar waits for one", async () => {
+ const n = count();
+ const r = await channelsRoute.POST(json("/api/faceless/channels", "POST", { idea: "Tiny museums", genre: "history", engine: "open" }, "c"));
+ expect(r.status).toBe(201);
+ const ch = (await r.json()) as { id: string; avatarJob: string | null };
+ expect(ch.avatarJob).toBeNull();
+ expect(count()).toBe(n);
+ const draw = await avatarRoute.POST(json(`/api/faceless/channels/${ch.id}/avatar`, "POST", undefined, "c"), params({ id: ch.id }));
+ expect(draw.status).toBe(403);
+ expect(draw.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");
+ });
+
+ it("suggests topics offline and writes the episode's script offline: the studio's AI helper is never asked", async () => {
+ fetched.length = 0;
+ const t = await topicsRoute.POST(json("/api/faceless/topics", "POST", { channelId: channel, engine: "open" }, "a"));
+ expect(t.status, await t.clone().text()).toBe(200);
+ expect(((await t.json()) as { topics: unknown[] }).topics.length).toBeGreaterThan(2);
+ const r = await episodesRoute.POST(json("/api/faceless/episodes", "POST", { channelId: channel, topic: "A hotel on a frozen lake", settings: { ...explainerSettings("a"), length: 60, auto: undefined } }, "a"));
+ expect(r.status, await r.clone().text()).toBe(201);
+ const ep = (await r.json()) as { id: string; status: string; script: { blocks: unknown[]; offline?: boolean } };
+ episode = ep.id;
+ expect(ep.status).toBe("review");
+ expect(ep.script.blocks.length).toBeGreaterThan(0);
+ expect(ep.script.offline).toBeFalsy();
+ expect(reachedOwner()).toEqual([]);
+ expect(llmAsked).not.toHaveBeenCalled();
+ });
+
+ it("renders the episode on its own GPU, and its channel page lists it", async () => {
+ fake.log.length = 0;
+ fetched.length = 0;
+ const r = await run(() => actionRoute.POST(json(`/api/faceless/episodes/${episode}/render`, "POST", undefined, "a"), params({ id: episode, action: "render" })));
+ expect(r.status, await r.clone().text()).toBe(200);
+ const v = await settleEpisode(episode, "a");
+ expect(v.episode.status, v.episode.error ?? "").toBe("done");
+ const gens = Object.values(v.episode.plan!.ids);
+ for (const g of gens) expect(accountOf(g)).toBe(a);
+ expect(reachedOwner()).toEqual([]);
+ const page = (await (await channelRoute.GET(json(`/api/faceless/channels/${channel}`, "GET", undefined, "a"), params({ id: channel }))).json()) as { episodes: { id: string }[] };
+ expect(page.episodes.map((e) => e.id)).toEqual([episode]);
+ expect(passed(viaProxy(`/faceless/${channel}/${episode}`, "GET", "a"))).toBe(true);
+ expect(viaProxy(`/faceless/${channel}/${episode}`, "GET", "b").status).toBe(404);
+ expect(recordFor({ kind: "episode", ids: [channel, episode] }, h("a"))).toBe(true);
+ expect(recordFor({ kind: "channel", ids: [channel] }, h("b"))).toBe(false);
+ expect(recordFor({ kind: "channel", ids: [channel] }, h("owner"))).toBe(false);
+ });
+
+ it("another account and the owner never see, change or add to its channel", async () => {
+ for (const who of ["b", "owner"]) {
+ const list = (await (await channelsRoute.GET(json("/api/faceless/channels", "GET", undefined, who))).json()) as { items: { id: string }[] };
+ expect(list.items.map((x) => x.id), who).not.toContain(channel);
+ const eps = (await (await episodesRoute.GET(json("/api/faceless/episodes", "GET", undefined, who))).json()) as { items: { id: string }[] };
+ expect(eps.items.map((x) => x.id), who).not.toContain(episode);
+ }
+ expect((await channelRoute.GET(json(`/api/faceless/channels/${channel}`, "GET", undefined, "b"), params({ id: channel }))).status).toBe(404);
+ expect((await channelRoute.PATCH(json(`/api/faceless/channels/${channel}`, "PATCH", { name: "mine" }, "b"), params({ id: channel }))).status).toBe(404);
+ expect((await channelRoute.DELETE(json(`/api/faceless/channels/${channel}`, "DELETE", undefined, "b"), params({ id: channel }))).status).toBe(404);
+ expect((await avatarRoute.POST(json(`/api/faceless/channels/${channel}/avatar`, "POST", undefined, "b"), params({ id: channel }))).status).toBe(404);
+ const add = await episodesRoute.POST(json("/api/faceless/episodes", "POST", { channelId: channel, topic: "Mine now", settings: { ...explainerSettings("b"), length: 60, auto: undefined } }, "b"));
+ expect(add.status).toBe(404);
+ // A picture of A's as B's channel picture: refused.
+ const pic = await upload("a", TINY_PNG, "image/png", "avatar.png");
+ const own = await channelsRoute.POST(json("/api/faceless/channels", "POST", { idea: "Night trains", genre: "education", engine: "open" }, "b"));
+ const bChannel = ((await own.json()) as { id: string }).id;
+ const steal = await channelRoute.PATCH(json(`/api/faceless/channels/${bChannel}`, "PATCH", { avatarUrl: pic }, "b"), params({ id: bChannel }));
+ expect(steal.status).toBe(403);
+ // A's own picture as its own channel's: fine.
+ const mine = await channelRoute.PATCH(json(`/api/faceless/channels/${channel}`, "PATCH", { avatarUrl: pic, name: "Water hotels" }, "a"), params({ id: channel }));
+ expect(mine.status, await mine.clone().text()).toBe(200);
+ expect(((await mine.json()) as { name: string }).name).toBe("Water hotels");
+ });
+
+ it("never reaches the owner's channels", async () => {
+ const owner = await faceless.createChannel({ idea: "The owner's channel", genre: "education", engine: "open", name: "Owner TV", avatar: false });
+ expect((await channelRoute.GET(json(`/api/faceless/channels/${owner.id}`, "GET", undefined, "a"), params({ id: owner.id }))).status).toBe(404);
+ expect((await channelRoute.DELETE(json(`/api/faceless/channels/${owner.id}`, "DELETE", undefined, "a"), params({ id: owner.id }))).status).toBe(404);
+ const add = await episodesRoute.POST(json("/api/faceless/episodes", "POST", { channelId: owner.id, topic: "Mine", settings: { ...explainerSettings("a"), length: 60, auto: undefined } }, "a"));
+ expect(add.status).toBe(404);
+ const list = (await (await channelsRoute.GET(json("/api/faceless/channels", "GET", undefined, "owner"))).json()) as { items: { id: string }[] };
+ expect(list.items.map((x) => x.id)).toEqual([owner.id]);
+ });
+
+ it("a ready channel is made as its own", async () => {
+ const r = await startersRoute.POST(json("/api/starters/faceless.boat-hotels", "POST", { engine: "open" }, "a"), params({ id: "faceless.boat-hotels" }));
+ expect(r.status, await r.clone().text()).toBe(201);
+ const href = ((await r.json()) as { href: string }).href;
+ const id = /^\/faceless\/([^/]+)\/new/.exec(href)![1];
+ expect(store.getAccountProject(a, "faceless", id)).not.toBeNull();
+ expect(store.getAccountProject(b, "faceless", id)).toBeNull();
+ });
+
+ it("a narrator sample on its own key only (no key: the card that adds one)", async () => {
+ const n = count();
+ const r = await voicesRoute.POST(json("/api/faceless/voices/preview", "POST", { id: "rachel" }, "a"));
+ expect([400, 403]).toContain(r.status);
+ expect(count()).toBe(n);
+ });
+
+ it("deletes its channel and the channel's episodes", async () => {
+ const r = await channelRoute.DELETE(json(`/api/faceless/channels/${channel}`, "DELETE", undefined, "a"), params({ id: channel }));
+ expect(r.status).toBe(204);
+ expect(store.getAccountProject(a, "faceless", channel)).toBeNull();
+ expect(db().prepare("SELECT 1 FROM faceless_episodes WHERE channel_id = ?").get(channel)).toBeUndefined();
+ expect((await readEpisode(episode, "a")).status).toBe(404);
+ });
+});
+
+describe("Content Factory: an account's series are its own", () => {
+ let clip = "";
+ let series = "";
+
+ beforeAll(async () => {
+ clip = await upload("a", CLIP, "video/mp4", "reference.mp4");
+ });
+
+ const ask = (who: string, extra: Record<string, unknown> = {}) => ({
+ prompt: "Three hotels you can only reach by boat",
+ settings: { engine: "open", length: 30, episodes: 2, animation: "frame-by-frame", genre: "education", aspect: "9:16" },
+ voice: { kind: "sample", url: voices[who], name: "Narrator" },
+ subtitles: false,
+ music: false,
+ ...extra,
+ });
+
+ async function settleSeries(id: string, who: string, ms = 60_000): Promise<{ analysis: { status: string; offline?: boolean; note?: string } | null; brief: unknown; episodes: { id: string; status: string }[]; channel: { id: string } | null }> {
+ const end = Date.now() + ms;
+ for (;;) {
+ await globalThis.__fuobeRunner?.tick();
+ const v = (await (await seriesRoute.GET(json(`/api/content-factory/series/${id}`, "GET", undefined, who), params({ id }))).json()) as Awaited<ReturnType<typeof settleSeries>>;
+ if (v.analysis?.status !== "reading" || Date.now() > end) return v;
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ }
+
+ it("reads its own clip into a brief on its own GPU", async () => {
+ fake.log.length = 0;
+ fetched.length = 0;
+ const r = await run(() => seriesListRoute.POST(json("/api/content-factory/series", "POST", { reference: { kind: "upload", url: clip }, engine: "open" }, "a")));
+ expect(r.status, await r.clone().text()).toBe(201);
+ series = ((await r.json()) as { id: string }).id;
+ expect(store.getAccountProject(a, "content-factory", series)).not.toBeNull();
+ const v = await settleSeries(series, "a");
+ expect(v.analysis?.status).toBe("ready");
+ expect(v.brief).toBeTruthy();
+ for (const e of fake.log.filter((x) => x.path === "/prompt")) expect(e.prompt).toBeTruthy();
+ expect(fake.log.filter((x) => x.path === "/prompt").length).toBe(1);
+ expect(reachedOwner()).toEqual([]);
+ });
+
+ it("never fetches a link for an account: it uploads the clip", async () => {
+ fetched.length = 0;
+ const r = await seriesListRoute.POST(json("/api/content-factory/series", "POST", { reference: { kind: "link", link: "https://www.tiktok.com/@someone/video/123" }, engine: "open" }, "a"));
+ expect(r.status).toBe(403);
+ expect(fetched).toEqual([]);
+ // A channel's YouTube reference is kept as the link, never fetched.
+ const ch = await channelsRoute.POST(json("/api/faceless/channels", "POST", { idea: "Calm trains", genre: "education", engine: "open", reference: "https://www.youtube.com/@calmtrains" }, "b"));
+ expect(ch.status, await ch.clone().text()).toBe(201);
+ expect(((await ch.json()) as { reference: { url: string; title?: string } }).reference).toMatchObject({ url: "https://www.youtube.com/@calmtrains" });
+ expect(fetched).toEqual([]);
+ });
+
+ it("refuses another account's clip, and reading for an account with no GPU or key", async () => {
+ const steal = await seriesListRoute.POST(json("/api/content-factory/series", "POST", { reference: { kind: "upload", url: clip }, engine: "open" }, "b"));
+ expect(steal.status).toBe(403);
+ const n = count();
+ const own = runAsTenant({ kind: "account", id: c }, () => saveFile({ data: CLIP, contentType: "video/mp4", source: "upload", name: "c.mp4" }).url);
+ const r = await seriesListRoute.POST(json("/api/content-factory/series", "POST", { reference: { kind: "upload", url: own }, engine: "open" }, "c"));
+ expect(r.status).toBe(403);
+ expect(r.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");
+ expect(count()).toBe(n);
+ expect(store.listAccountProjects(c, "content-factory")).toEqual([]);
+ });
+
+ it("prices the series for its own GPU", async () => {
+ const r = await cfEstimate.POST(json("/api/content-factory/estimate", "POST", { ...ask("a"), seriesId: series }, "a"));
+ expect(r.status, await r.clone().text()).toBe(200);
+ expect(((await r.json()) as { demo: boolean }).demo).toBe(false);
+ });
+
+ it("generates its episodes as one run on its own GPU, in a channel of its own", async () => {
+ fake.log.length = 0;
+ fetched.length = 0;
+ const r = await run(() => generateRoute.POST(json(`/api/content-factory/series/${series}/generate`, "POST", ask("a"), "a"), params({ id: series })));
+ expect(r.status, await r.clone().text()).toBe(200);
+ const v = (await r.json()) as { made: boolean; channel: { id: string }; episodes: { id: string }[] };
+ expect(v.made).toBe(true);
+ expect(v.episodes.length).toBe(2);
+ expect(store.getAccountProject(a, "faceless", v.channel.id)).not.toBeNull();
+ const batches = new Set<string>();
+ for (const e of v.episodes) {
+ const ev = await settleEpisode(e.id, "a");
+ expect(ev.episode.status, ev.episode.error ?? "").toBe("done");
+ for (const g of Object.values(ev.episode.plan!.ids)) {
+ expect(accountOf(g)).toBe(a);
+ batches.add(getGeneration(g)!.batchId!);
+ }
+ }
+ // Its episodes render as one run.
+ expect(batches.size).toBe(1);
+ expect(reachedOwner()).toEqual([]);
+ const list = (await (await seriesListRoute.GET(json("/api/content-factory/series", "GET", undefined, "a"))).json()) as { items: { id: string; episodes: number }[] };
+ expect(list.items.map((s) => s.id)).toEqual([series]);
+ expect(list.items[0].episodes).toBe(2);
+ expect(passed(viaProxy(`/content-factory/${series}`, "GET", "a"))).toBe(true);
+ expect(viaProxy(`/content-factory/${series}`, "GET", "b").status).toBe(404);
+ });
+
+ it("adds an episode for review: written, nothing renders yet", async () => {
+ const n = count();
+ const r = await moreRoute.POST(json(`/api/content-factory/series/${series}/episodes`, "POST", { count: 1, next: "A floating spa", review: true }, "a"), params({ id: series }));
+ expect(r.status, await r.clone().text()).toBe(200);
+ const v = (await r.json()) as { episodes: { id: string; status: string }[] };
+ expect(v.episodes.length).toBe(3);
+ expect(v.episodes.filter((e) => e.status === "review").length).toBe(1);
+ expect(count()).toBe(n);
+ });
+
+ it("another account and the owner never see, change or run it", async () => {
+ for (const who of ["b", "owner"]) {
+ const list = (await (await seriesListRoute.GET(json("/api/content-factory/series", "GET", undefined, who))).json()) as { items: { id: string }[] };
+ expect(list.items.map((s) => s.id), who).not.toContain(series);
+ expect((await seriesRoute.GET(json(`/api/content-factory/series/${series}`, "GET", undefined, who), params({ id: series }))).status, who).toBe(404);
+ }
+ fake.log.length = 0;
+ expect((await seriesRoute.PATCH(json(`/api/content-factory/series/${series}`, "PATCH", { name: "mine" }, "b"), params({ id: series }))).status).toBe(404);
+ expect((await moreRoute.POST(json(`/api/content-factory/series/${series}/episodes`, "POST", { count: 1 }, "b"), params({ id: series }))).status).toBe(404);
+ expect((await readRoute.POST(json(`/api/content-factory/series/${series}/read`, "POST", { engine: "open" }, "b"), params({ id: series }))).status).toBe(404);
+ expect((await seriesRoute.DELETE(json(`/api/content-factory/series/${series}`, "DELETE", undefined, "b"), params({ id: series }))).status).toBe(404);
+ expect(fake.log.some((e) => e.path === "/prompt")).toBe(false);
+ expect(store.getAccountProject(a, "content-factory", series)).not.toBeNull();
+ });
+
+ it("a series from a preset for an account with no GPU or key: made, but its run asks for one first", async () => {
+ const r = await seriesListRoute.POST(json("/api/content-factory/series", "POST", { reference: { kind: "preset", presetId: "what-if" }, engine: "open" }, "c"));
+ expect(r.status, await r.clone().text()).toBe(201);
+ const id = ((await r.json()) as { id: string }).id;
+ const n = count();
+ const sample = runAsTenant({ kind: "account", id: c }, () => saveFile({ data: VOICE, contentType: "audio/wav", source: "upload", name: "c.wav" }).url);
+ const g = await generateRoute.POST(json(`/api/content-factory/series/${id}/generate`, "POST", { ...ask("a"), voice: { kind: "sample", url: sample } }, "c"), params({ id }));
+ expect(g.status, await g.clone().text()).toBe(403);
+ expect(g.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");
+ // The cloud engine without a key of its own: said plainly (no studio settings named).
+ const cloud = await generateRoute.POST(json(`/api/content-factory/series/${id}/generate`, "POST", { ...ask("a"), voice: null, settings: { ...ask("a").settings, engine: "cloud" } }, "c"), params({ id }));
+ expect(cloud.status).toBe(422);
+ expect((await cloud.json()).error).toBe(faceless.ACCOUNT_CLOUD_ENGINE);
+ expect(count()).toBe(n);
+ expect(store.listAccountProjects(c, "faceless").length).toBe(1);
+ });
+});
+
+describe("an account's limits, and its deletion", () => {
+ it("keeps runs going at once", async () => {
+ const now = Date.now();
+ const add = db().prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'explainer', 'oss-chatterbox', 'open', 'comfyui', 'tts', 'audio', 'queued', ?, '[]', ?, ?)",
+ );
+ for (let i = 0; i < ACCOUNT_LIMITS.activeRuns; i++) add.run(`busy-content-${i}`, JSON.stringify({ feature: "explainer", modelId: "oss-chatterbox", account: b }), now, now);
+ const r = await explainerRoute.POST(json("/api/explainer", "POST", { prompt: "Volcanoes", settings: explainerSettings("b") }, "b"));
+ expect(r.status).toBe(429);
+ expect((await r.json()).code).toBe(access.ACTIVE_RUNS_CODE);
+ db().prepare("DELETE FROM generations WHERE id LIKE 'busy-content-%'").run();
+ });
+
+ it("goes with the account: its channels, episodes, explainers and series", async () => {
+ await purgeAccount(a);
+ for (const kind of ["faceless", "explainer", "content-factory"]) expect(store.listAccountProjects(a, kind), kind).toEqual([]);
+ const left = db().prepare("SELECT COUNT(*) AS n FROM faceless_episodes e WHERE e.kind = 'explainer' AND e.channel_id IS NULL AND e.title = 'How bees make honey'").get() as { n: number };
+ expect(left.n).toBe(0);
+ expect((db().prepare("SELECT COUNT(*) AS n FROM content_series").get() as { n: number }).n).toBeGreaterThan(0);
+ });
+});
diff --git a/tests/account-keys-isolation.test.ts b/tests/account-keys-isolation.test.ts
index dc677204..3f4f35e3 100644
--- a/tests/account-keys-isolation.test.ts
+++ b/tests/account-keys-isolation.test.ts
@@ -429,7 +429,7 @@ describe("routing for an account", () => {
it("text steps, the AI helpers, 3D and the other tools stay closed to an account with a key", async () => {
expect(gens.accountRun(A, "llm")).toMatchObject({ code: "own-gpu-tool" });
const at = (url: string) => proxy(new NextRequest(`http://localhost:3000${url}`, { method: "POST", headers: { cookie: cookies.A }, body: "{}" }));
- for (const url of ["/api/assist", "/api/enhance", "/api/shorts", "/api/faceless/episodes"]) {
+ for (const url of ["/api/assist", "/api/enhance", "/api/shorts", "/api/content-factory/claude", "/api/explainer/link"]) {
const r = at(url);
expect(r.status, url).toBe(403);
}
diff --git a/tests/e2e/content-accounts-live.mjs b/tests/e2e/content-accounts-live.mjs
new file mode 100644
index 00000000..f7882cf5
--- /dev/null
+++ b/tests/e2e/content-accounts-live.mjs
@@ -0,0 +1,215 @@
+// Faceless Studio, the Explainer and Content Factory for visitors (a studio with a password and public sign-up, fuobe.com
+// by default), through their routes and in a browser at phone and desktop widths. A guest: the sign-up card on every
+// change, empty lists, the price checks open, no "isn't available here" note, and the sign-up card when it attaches a
+// file or adds a clip. A signed-in account (a throwaway one this script makes and deletes): its own channel, episode,
+// explainer and series made, reopened and deleted; nobody else's (404); its renders ask for its own GPU or key first;
+// links, "Generate in Claude" and "Regenerate to 1080p" not offered; the pages' buttons on.
+// No render is started (that needs the account's own GPU or key).
+// Usage: node tests/e2e/content-accounts-live.mjs [appUrl] [--shots <dir>] Exits 1 on a failed check.
+import fs from "node:fs";
+import path from "node:path";
+import crypto from "node:crypto";
+import { launch } from "./_browser.mjs";
+
+const argv = process.argv.slice(2);
+const flag = (k) => (argv.includes(k) ? argv[argv.indexOf(k) + 1] : undefined);
+const app = (argv.find((a, i) => !a.startsWith("--") && argv[i - 1] !== "--shots") ?? "https://fuobe.com").replace(/\/$/, "");
+const shots = flag("--shots");
+if (shots) fs.mkdirSync(shots, { recursive: true });
+
+const failures = [];
+const check = (label, ok, extra = "") => {
+ console.log(`${ok ? "ok " : "FAIL"} ${label.padEnd(76)}${extra ? ` ${extra}` : ""}`);
+ if (!ok) failures.push(label);
+};
+
+const settings = { engine: "open", length: 20, animation: "frames", aspect: "16:9", subtitles: false, music: false, styleId: "editorial-motion-graphics", styleRefs: [], voice: null, elements: [], auto: false };
+const seriesAsk = { prompt: "Three hotels you can only reach by boat", settings: { engine: "open", length: 30, episodes: 1, animation: "frame-by-frame", genre: "education", aspect: "9:16" }, voice: null, subtitles: false, music: false };
+
+/** The route checks, as a guest (`req`: a context's request, signed out) or as the account (signed in). */
+async function routes(req, who) {
+ const send = (method, p, data) => req.fetch(`${app}${p}`, { method, headers: { origin: app, "content-type": "application/json" }, ...(data !== undefined && { data }) });
+ const body = async (r) => r.json().catch(() => ({}));
+ for (const p of ["/api/faceless/channels", "/api/faceless/episodes", "/api/explainer", "/api/content-factory/series"]) {
+ const r = await send("GET", p);
+ check(`${who}: ${p} lists nothing yet`, r.status() === 200 && JSON.stringify(await body(r)) === '{"items":[]}', String(r.status()));
+ }
+ const price = await send("POST", "/api/faceless/estimate", { kind: "explainer", settings });
+ const e = await body(price);
+ check(`${who}: the explainer's price check works, never as a demo`, price.status() === 200 && e.demo === false, `${price.status()} ${JSON.stringify(e).slice(0, 80)}`);
+ const cf = await send("POST", "/api/content-factory/estimate", { ...seriesAsk, presetId: "what-if" });
+ check(`${who}: the series' price check works`, cf.status() === 200 && (await body(cf)).demo === false, String(cf.status()));
+ for (const p of ["/faceless/nope-not-a-channel", "/explainer/nope-not-an-explainer", "/content-factory/nope-not-a-series"]) {
+ const r = await send("GET", p);
+ check(`${who}: ${p} is a 404`, r.status() === 404, String(r.status()));
+ }
+ for (const p of ["/api/explainer/link", "/api/content-factory/claude", "/api/faceless/episodes/nope/regenerate"]) {
+ const r = await send("POST", p, {});
+ check(`${who}: ${p} isn't offered`, r.status() === 403 && (await body(r)).code === "own-gpu-tool", String(r.status()));
+ }
+ if (who === "guest") {
+ for (const [method, p] of [
+ ["POST", "/api/faceless/channels"],
+ ["POST", "/api/faceless/episodes"],
+ ["POST", "/api/faceless/episodes/nope/render"],
+ ["POST", "/api/faceless/topics"],
+ ["DELETE", "/api/faceless/channels/nope"],
+ ["POST", "/api/explainer"],
+ ["POST", "/api/content-factory/series"],
+ ["POST", "/api/content-factory/series/nope/generate"],
+ ["POST", "/api/starters/faceless.boat-hotels"],
+ ]) {
+ const r = await send(method, p, {});
+ check(`guest: ${method} ${p} asks to sign up`, r.status() === 401 && r.headers()["x-fuobe-guest"] === "1", String(r.status()));
+ }
+ for (const p of ["/api/faceless/channels/nope", "/api/faceless/episodes/nope", "/api/content-factory/series/nope"]) {
+ const r = await send("GET", p);
+ check(`guest: ${p} is closed`, r.status() === 401, String(r.status()));
+ }
+ return;
+ }
+ // The account reaches its routes, which answer with its own only.
+ for (const p of ["/api/faceless/channels/nope", "/api/faceless/episodes/nope", "/api/content-factory/series/nope"]) {
+ const r = await send("GET", p);
+ check(`account: ${p} (none of its own) is not found`, r.status() === 404, String(r.status()));
+ }
+ // Its own channel: made, reopened, an episode written offline, its render asks for its own GPU or key first.
+ const ch = await send("POST", "/api/faceless/channels", { idea: "Strange hotels on the water", genre: "education", engine: "open" });
+ const channel = await body(ch);
+ check("account: makes a channel of its own", ch.status() === 201 && !!channel.id, String(ch.status()));
+ if (channel.id) {
+ const list = await body(await send("GET", "/api/faceless/channels"));
+ check("account: its channels list it", list.items?.length === 1 && list.items[0].id === channel.id);
+ const ep = await send("POST", "/api/faceless/episodes", { channelId: channel.id, topic: "A hotel on a frozen lake", settings: { ...settings, length: 60, auto: undefined } });
+ const episode = await body(ep);
+ check("account: writes an episode (offline, for review)", ep.status() === 201 && episode.status === "review" && episode.script?.blocks?.length > 0, `${ep.status()} ${episode.status}`);
+ if (episode.id) {
+ const one = await send("GET", `/api/faceless/episodes/${episode.id}`);
+ check("account: reopens its episode", one.status() === 200, String(one.status()));
+ const page = await send("GET", `/faceless/${channel.id}/${episode.id}`);
+ check("account: its episode's page opens", page.status() === 200, String(page.status()));
+ const render = await send("POST", `/api/faceless/episodes/${episode.id}/render`, {});
+ check("account: its render asks for its own GPU or key first", render.status() === 403 && ["connect-gpu", "add-key"].includes((await body(render)).code), String(render.status()));
+ }
+ const del = await send("DELETE", `/api/faceless/channels/${channel.id}`);
+ check("account: deletes its channel", del.status() === 204, String(del.status()));
+ }
+ // Its own explainer, written for review.
+ const ex = await send("POST", "/api/explainer", { prompt: "Why the sky is blue", settings, review: true });
+ const explainer = await body(ex);
+ check("account: writes an explainer for review", ex.status() === 201 && explainer.status === "review", `${ex.status()} ${explainer.status}`);
+ if (explainer.id) {
+ const page = await send("GET", `/explainer/${explainer.id}`);
+ check("account: its explainer's page opens", page.status() === 200, String(page.status()));
+ const render = await send("POST", `/api/faceless/episodes/${explainer.id}/render`, {});
+ check("account: the explainer's render asks for its own GPU or key first", render.status() === 403, String(render.status()));
+ const del = await send("DELETE", `/api/faceless/episodes/${explainer.id}`);
+ check("account: deletes its explainer", del.status() === 204, String(del.status()));
+ }
+ // Its own series from a preset (no clip to read).
+ const s = await send("POST", "/api/content-factory/series", { reference: { kind: "preset", presetId: "what-if" }, engine: "open" });
+ const series = await body(s);
+ check("account: makes a series from a preset", s.status() === 201 && !!series.id, String(s.status()));
+ if (series.id) {
+ const one = await send("GET", `/api/content-factory/series/${series.id}`);
+ check("account: reopens its series", one.status() === 200, String(one.status()));
+ const gen = await send("POST", `/api/content-factory/series/${series.id}/generate`, seriesAsk);
+ check("account: Generate reaches its route (no narrator yet: it says so)", gen.status() >= 400 && gen.status() < 500 && gen.status() !== 401, String(gen.status()));
+ const del = await send("DELETE", `/api/content-factory/series/${series.id}`);
+ check("account: deletes its series", del.status() === 204, String(del.status()));
+ }
+}
+
+/** One page's checks at one width. */
+async function look(page, who, width) {
+ const tag = `${who} @${width}`;
+ const shot = async (name) => shots && (await page.screenshot({ path: path.join(shots, `${name}-${who}-${width}.png`), fullPage: false }));
+ const card = who === "guest" ? /Create a free account/ : /Connect your GPU|your own files/;
+ const notes = ["Faceless channels aren't available here", "Explainer videos aren't available here", "Content Factory isn't available here", "Not available here"];
+ const noNotes = async (name) => {
+ let found = 0;
+ for (const n of notes) found += await page.getByText(n).count();
+ check(`${tag}: ${name} shows no "not available" note`, found === 0);
+ };
+
+ await page.goto(`${app}/faceless`, { waitUntil: "load", timeout: 60_000 });
+ await page.waitForTimeout(3000);
+ await noNotes("/faceless");
+ const next = page.getByRole("button", { name: /^Next$/ });
+ check(`${tag}: Faceless's Next is on`, (await next.count()) > 0 && (await next.first().isEnabled()));
+ check(`${tag}: /faceless has no sideways scroll`, await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1));
+ await shot("faceless");
+
+ await page.goto(`${app}/explainer`, { waitUntil: "load", timeout: 60_000 });
+ await page.waitForTimeout(3000);
+ await noNotes("/explainer");
+ const generate = page.getByRole("button", { name: /^Generate$/ });
+ check(`${tag}: the Explainer's Generate is on`, (await generate.count()) > 0 && (await generate.first().isEnabled()));
+ check(`${tag}: the Explainer offers no link source`, (await page.getByRole("button", { name: "Paste a link" }).count()) === 0);
+ check(`${tag}: /explainer has no sideways scroll`, await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1));
+ await shot("explainer");
+ const attach = page.getByRole("button", { name: "Attach a file" });
+ check(`${tag}: Attach a file is offered`, (await attach.count()) > 0 && (await attach.first().isEnabled()));
+ if (await attach.count()) {
+ await attach.first().click();
+ await page.waitForTimeout(1500);
+ check(`${tag}: Attach a file opens the ${who === "guest" ? "sign-up" : "connect"} card`, (await page.getByText(card).count()) > 0);
+ await shot("explainer-attach");
+ await page.keyboard.press("Escape");
+ await page.waitForTimeout(400);
+ }
+
+ await page.goto(`${app}/content-factory`, { waitUntil: "load", timeout: 60_000 });
+ await page.waitForTimeout(3000);
+ await noNotes("/content-factory");
+ check(`${tag}: Content Factory offers no link (the clip is added)`, (await page.getByRole("button", { name: /TikTok or Instagram link/ }).count()) === 0);
+ check(`${tag}: Content Factory offers no "Generate in Claude"`, (await page.getByText("Generate in Claude").count()) === 0);
+ const go = page.getByRole("button", { name: /^Generate/ });
+ check(`${tag}: Content Factory's Generate is on`, (await go.count()) > 0 && (await go.first().isEnabled()));
+ check(`${tag}: /content-factory has no sideways scroll`, await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1));
+ await shot("content-factory");
+ const add = page.getByRole("button", { name: /Add a video/ });
+ if (await add.count()) {
+ await add.first().click();
+ await page.waitForTimeout(1500);
+ check(`${tag}: Add a video opens the ${who === "guest" ? "sign-up" : "connect"} card`, (await page.getByText(card).count()) > 0);
+ await shot("content-factory-add");
+ await page.keyboard.press("Escape");
+ await page.waitForTimeout(400);
+ } else check(`${tag}: Add a video is offered`, false);
+}
+
+const browser = await launch();
+const email = `content-ui-${crypto.randomBytes(5).toString("hex")}@example.com`;
+const password = crypto.randomBytes(18).toString("base64url");
+let signedUp = false;
+const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
+try {
+ const page = await context.newPage();
+ await routes(page.request, "guest");
+ for (const width of [390, 1440]) {
+ await page.setViewportSize({ width, height: width === 390 ? 844 : 1000 });
+ await look(page, "guest", width);
+ }
+ // A throwaway account (signed in in this browser), then the same checks.
+ const res = await page.request.post(`${app}/api/auth/signup`, { data: { email, password }, headers: { origin: app } });
+ signedUp = res.ok();
+ check("signed up a throwaway account", signedUp, String(res.status()));
+ if (signedUp) {
+ await routes(page.request, "account");
+ for (const width of [390, 1440]) {
+ await page.setViewportSize({ width, height: width === 390 ? 844 : 1000 });
+ await look(page, "account", width);
+ }
+ }
+} finally {
+ if (signedUp) {
+ const page = context.pages()[0];
+ const del = await page.request.delete(`${app}/api/auth/me`, { data: { password }, headers: { origin: app } });
+ console.log(`deleted the throwaway account: ${del.status()}`);
+ check("deleted the throwaway account", del.status() === 204 || del.ok(), String(del.status()));
+ }
+ await browser.close();
+}
+console.log(failures.length ? `${failures.length} failed` : "all ok");
+process.exit(failures.length ? 1 : 0);
diff --git a/tests/helpers/fake-comfy-runner.ts b/tests/helpers/fake-comfy-runner.ts
index 0cba55ab..4c25f71c 100644
--- a/tests/helpers/fake-comfy-runner.ts
+++ b/tests/helpers/fake-comfy-runner.ts
@@ -14,7 +14,8 @@
* status /upload/image answers, e.g. 500 to fail every upload), `refuseClass` (/prompt answers "not in list" for a graph with
* a node of that class), `echo` (an image output is the last picture uploaded, so a result lines up with its photo),
* `text` (a SaveText output, node 5: the history carries the words and /view serves them as the .txt file), `graph`
- * (outputs under the sent graph's own save nodes: audio as a WAV, SaveText as `text`, so a chain of steps runs through).
+ * (outputs under the sent graph's own save nodes: audio as a WAV, SaveText as `text`, so a chain of steps runs through), `mixed` (every
+ * job answers a clip, a picture, a sound and a text, so each step of a chained tool takes the kind it reads).
* This file runs under plain Node too: only erasable TypeScript.
*/
import http from "node:http";
@@ -46,6 +47,8 @@ export interface FakeComfyOptions {
* a chain of steps (a soundtrack split into stems, its words, a mix) runs through.
*/
graph?: boolean;
+ /** Every job answers a clip, a picture, a sound (a WAV) and a text (`text`, or "Done."): a chained tool's steps each take their kind. */
+ mixed?: boolean;
}
/** A tiny but real WAV (mono, 16-bit, 8 kHz, 0.1 s of silence). */
@@ -106,6 +109,27 @@ export const TINY_PNG = Buffer.from(
"hex",
);
+/** Half a second of a quiet 220 Hz tone: a real 16 kHz mono WAV (a narrator's sample, a narration, a music bed). */
+export const TONE_WAV: Buffer = (() => {
+ 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) * 3000), 44 + i * 2);
+ return buf;
+})();
+
/** A one-triangle binary glTF 2 (a GLB the server's 3D finish can read). */
export const TINY_GLB: Buffer = (() => {
const bin = Buffer.alloc(36);
@@ -224,6 +248,15 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<F
const done = { status: { completed: true, status_str: "success" } };
const list = (n: number, ext: string) => Array.from({ length: n }, (_, i) => ({ filename: `fake_${String(i + 1).padStart(5, "0")}_.${ext}`, subfolder: "", type: "output" }));
if (opts.graph) return json(200, { [id]: { ...done, outputs: graphOutputs(graphs.get(id), opts.text ?? "") } });
+ if (opts.mixed) {
+ const text = opts.text ?? "Done.";
+ return json(200, {
+ [id]: {
+ ...done,
+ outputs: { "900": { gifs: list(1, "mp4") }, "901": { images: list(1, "png") }, "902": { audio: list(1, "wav") }, "903": { text: [text], files: [{ filename: "fake_00001_.txt", subfolder: "fuobe", type: "output" }] } },
+ },
+ });
+ }
if (opts.layers) return json(200, { [id]: { ...done, outputs: { "60": { images: list(opts.layers, "png") } } } });
if (opts.text !== undefined) return json(200, { [id]: { ...done, outputs: { "5": { text: [opts.text], files: [{ filename: "fake_00001_.txt", subfolder: "fuobe", type: "output" }] } } } });
if (opts.frames) return json(200, { [id]: { ...done, outputs: { "5": { gifs: list(1, "mp4") }, "3": { images: list(opts.frames, "exr") } } } });
@@ -257,11 +290,11 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<F
const name = url.searchParams.get("filename") ?? "";
if (name.endsWith(".txt")) {
res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
- return res.end(opts.text ?? "");
+ return res.end(opts.text ?? (opts.mixed ? "Done." : ""));
}
if (name.endsWith(".wav")) {
res.writeHead(200, { "content-type": "audio/wav" });
- return res.end(TINY_WAV);
+ return res.end(opts.mixed ? TONE_WAV : TINY_WAV);
}
if (name.endsWith(".exr")) {
res.writeHead(200, { "content-type": "image/x-exr" });
diff --git a/tests/public-signup.test.ts b/tests/public-signup.test.ts
index 3f0be02f..e1416944 100644
--- a/tests/public-signup.test.ts
+++ b/tests/public-signup.test.ts
@@ -222,7 +222,8 @@ describe("accounts never run on the owner's keys or GPU", () => {
"/api/layers/l1/jobs",
"/api/enhance",
"/api/brands/b1/chat",
- "/api/faceless/episodes/e1/render",
+ // Faceless, Explainer and Content Factory runs go to their routes (tests/account-content.test.ts); handing a brief
+ // to Claude stays the owner's.
"/api/content-factory/claude",
// A run route that ignores ?preview=1 isn't a price check.
"/api/faceless/episodes/e1/estimate",
diff --git a/tests/regenerate-held.test.ts b/tests/regenerate-held.test.ts
index f3595336..4e9911de 100644
--- a/tests/regenerate-held.test.ts
+++ b/tests/regenerate-held.test.ts
@@ -53,8 +53,9 @@ afterAll(() => {
globalThis.__fuobeTestDiskFree = undefined;
});
+/** The owner's request (a guest is asked to sign up first; an account's own channels: tests/account-content.test.ts). */
const json = (method: string, body?: unknown) =>
- new Request("http://x/api", { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
+ new Request("http://x/api", { method, headers: { "Content-Type": "application/json", cookie: owner }, body: body === undefined ? undefined : JSON.stringify(body) });
const params = <T extends Record<string, string>>(p: T) => ({ params: Promise.resolve(p) }) as never;
const clip = (accountId?: string) => saveFile({ data: TINY_MP4, contentType: "video/mp4", source: "upload", name: "clip.mp4", ...(accountId && { accountId }) }).url;
const count = () => (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
diff --git a/tests/request-body-limits.test.ts b/tests/request-body-limits.test.ts
index 6c31a519..634349a9 100644
--- a/tests/request-body-limits.test.ts
+++ b/tests/request-body-limits.test.ts
@@ -71,13 +71,14 @@ describe("M-3: the proxy holds at most a few MB of any request body", () => {
it("each of those routes refuses a guest, an account and another website as the proxy would", async () => {
for (const r of BIG) {
// Assist and the tools an account's own GPU doesn't run give a guest the account's answer (403): signing up
- // wouldn't let it in. A run's finish and a save to the library offer to sign up (401).
- expect((await r.call(form(r.path))).status, `${r.name}: guest`).toBe(["finish", "mix export"].includes(r.name) ? 401 : 403);
+ // wouldn't let it in. A run's finish, a save to the library and an explainer's document offer to sign up (401).
+ expect((await r.call(form(r.path))).status, `${r.name}: guest`).toBe(["finish", "mix export", "explainer document"].includes(r.name) ? 401 : 403);
expect((await r.call(form(r.path, { cookie: owner, headers: { origin: "http://evil.example" } }))).status, `${r.name}: cross-site`).toBe(403);
}
- // An account: its own Export mix passes the proxy's rules (the route then reads the WAV: a form isn't one), and its own
+ // An account: its own Export mix and an explainer's document pass the proxy's rules (the route then reads the WAV or the
+ // document: a PNG isn't one), and its own
// run's finish does too, but "g1" isn't its own.
- for (const r of BIG) expect((await r.call(form(r.path, { cookie: account }))).status, `${r.name}: account`).toBe(r.name === "mix export" ? 415 : 403);
+ for (const r of BIG) expect((await r.call(form(r.path, { cookie: account }))).status, `${r.name}: account`).toBe(["mix export", "explainer document"].includes(r.name) ? 415 : 403);
});
it("each lets the owner through to the route's own checks", async () => {