The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Audio tools and Translate & dub: accounts run them on their own GPU or key
Adarsh82d216028f1a
diff --git a/docs/public-signup.md b/docs/public-signup.mdindex 86429275..dd2c068f 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -275,13 +275,8 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188the account's ComfyUI can't be reached, the run fails and says so. A cloud model, an AI helper orthe studio's local LLM is refused; "Enhance prompt" uses Fuobe's offline wording. Other tools(Canvas, Assist, Marketing…) answer 403 with `code: "own-gpu-tool"`, because they- plan with the studio's own AI helpers or keep projects of their own. So do the Audio hub's Split- soundtrack and Edit speech and Video tools → Remove dialogue (all `POST /api/audio-tools`), though their price- checks work, priced for the account's own GPU. Split soundtrack's, Edit speech's and Remove dialogue's pages say so up front ("Split- soundtrack isn't available here", "Edit speech isn't available here", "Remove dialogue isn't- available here"), with their upload and run off. Result menus don't offer Remove dialogue, Clean up- dialogue or Edit speech to a guest or an account, and Captions doesn't offer them "Fix this line"- (it opens Edit speech). Restore & colourise is left out of the Video tools tabs and the result menus for them.+ plan with the studio's own AI helpers or keep projects of their own. The Audio tools have their own routes (below).+ Restore & colourise is left out of the Video tools tabs and the result menus for them.A hosted model whose calls haven't yet passed a live run with a real key (`src/lib/catalog/hosted-untested.ts`:MiniMax H3 Max's lip sync, relight, insert, looks and Turbo, H3 Lite and HighSpeed, Vidu Q4, the Mureka songs andsong tools, MiniMax Music 3, ElevenLabs Music, Lyria 3.5, the hosted voice cleaners, Meshy retexture, Tripo P2,@@ -383,6 +378,23 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188owner's library answers 404. Katana's runs are its own projects (`GET /api/katana`, `GET`/`DELETE/api/katana/<id>`): up to 50, another account's or the owner's read as 404, deleted with the account. A guest getsthe sign-up card.+- **Audio tools.** An account runs Split soundtrack and Clean up dialogue, Video tools → Remove dialogue, Edit speech,+ Loop / extend, Join and Clean up voice (`POST /api/audio-tools`) the same way as Genjutsu's: every step on its own+ ComfyUI, or on its own fal.ai or Replicate key where a step is a cloud model, with only its own files, after the same+ checks, and a run counts once against its limits. Its price check is its own run's. Its stems, clean dialogue,+ edited speech and mixes are its own runs, to reopen in the mixer, open and download, and Export mix keeps the WAV as+ one of its runs (above). Edit speech runs on the account's own GPU only (AuK's files and a 24 GB card): its tab and+ page carry the "own setup" label (`audio:edit-speech`), and its upload and run ask an account without a GPU to+ connect one. Result menus offer Remove dialogue, Clean up dialogue and Edit speech, and Captions offers "Fix this line".+ A guest gets the sign-up card.+- **Translate & dub.** An account keeps dubs of its own (`GET`/`POST /api/dub`, `GET`/`PATCH`/`DELETE /api/dub/<id>`,+ `POST /api/dub/<id>/voice`): up to 50, in the account project store, deleted with the account. Another account's dub,+ or the owner's, reads as not found (404), and the owner's list never shows an account's. A dub (one shot on its own+ key, or step by step) and the voice of each language run the same way as Genjutsu's: every step on its own ComfyUI+ or key, with only its own video. Its translations run on its own GPU (Qwen3.5 4B, `oss-qwen35-translate`), never on+ 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.- **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/api/audio-tools/route.ts b/src/app/api/audio-tools/route.tsindex 47cd2480..2dfa5112 100644--- a/src/app/api/audio-tools/route.ts+++ b/src/app/api/audio-tools/route.ts@@ -1,7 +1,7 @@-import { AudioToolBody, AudioToolError, previewAudioTool, runAudioTool } from "@/server/audio-tools";+import { bodyTooBig, guestRun, onceForAccount, priceAsRun, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { AudioToolBody, AudioToolError, audioToolFiles, audioToolSteps, planAudioTool, previewAudioTool, runAudioTool, startAudioTool, type AudioToolPlan } from "@/server/audio-tools";import { connectRefusal } from "@/server/connect-refusal";import { ConnectComfyError } from "@/server/generations";-import { priceAs } from "@/server/visitor";/** What a field that doesn't check out means, in words the page shows. */const MESSAGES: Record<string, string> = {@@ -17,7 +17,9 @@ const MESSAGES: Record<string, string> = {* Audio → Loop / extend, Join, Split soundtrack (and its Clean up dialogue) and Clean up voice (and a split's mix put back on its video), and Video* tools → Remove dialogue, and Audio → Edit speech: start a run; `?preview=1` only plans and prices it.*/-async function post(request: Request) {+async function post(request: Request, preview: boolean) {+ const viewer = toolViewer(request);+ if (!preview && viewer.kind === "guest") return guestRun();const raw: unknown = await request.json().catch(() => null);const parsed = AudioToolBody.safeParse(raw);if (!parsed.success) {@@ -40,7 +42,24 @@ async function post(request: Request) {: (MESSAGES[path] ?? "Check the settings");return Response.json({ error: msg }, { status: 400 });}- const preview = new URL(request.url).searchParams.get("preview") === "1";+ if (!preview && viewer.kind === "account") {+ // An account's run: on its own GPU or key, with its own files, after the checks a studio run gets.+ const body = parsed.data;+ let planned: AudioToolPlan | null = null;+ return onceForAccount(+ viewer.account,+ "audio-tools",+ undefined,+ () =>+ runAccountTool(request, viewer.account, {+ tool: `audio-${body.tool}`,+ files: audioToolFiles(body),+ plan: () => audioToolSteps((planned = planAudioTool(body))),+ start: () => startAudioTool(planned!),+ }),+ ({ value, gpuWarning }) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201, headers: { "Cache-Control": "no-store" } }),+ );+ }try {if (preview) return Response.json(await previewAudioTool(parsed.data));return Response.json(await runAudioTool(parsed.data), { status: 201 });@@ -53,7 +72,16 @@ async function post(request: Request) {}}-/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */+/**+ * The owner runs as always. A signed-in account runs on its own GPU or its own fal.ai or Replicate key, and its price+ * check is its own run's (src/server/account-tool-run.ts priceAsRun); a guest's price check is the open engine's, and+ * its run gets the sign-up card.+ */export async function POST(request: Request) {- return priceAs(request, () => post(request));+ const preview = new URL(request.url).searchParams.get("preview") === "1";+ if (toolViewer(request).kind === "account") {+ const big = bodyTooBig(request);+ if (big) return big;+ }+ return preview ? priceAsRun(request, () => post(request, true)) : post(request, false);}diff --git a/src/app/api/dub/[id]/route.ts b/src/app/api/dub/[id]/route.tsindex 448a9df5..b565d079 100644--- a/src/app/api/dub/[id]/route.ts+++ b/src/app/api/dub/[id]/route.ts@@ -1,30 +1,48 @@import { connection } from "next/server";import { z } from "zod";+import { asViewer, guestRun, toolViewer } from "@/server/account-tool-run";import { CueSchema, deleteDubSession, dubView, getDubSession, saveDubDraft } from "@/server/dub";const Patch = z.object({ lang: z.string().min(2).max(12), cues: z.array(CueSchema).max(3000) });-export async function GET(_req: Request, ctx: RouteContext<"/api/dub/[id]">) {+const notFound = () => Response.json({ error: "Not found" }, { status: 404, headers: { "Cache-Control": "no-store" } });++/**+ * One dub: the owner's, or a signed-in account's own (src/server/dub.ts: another account's or the owner's reads as not+ * found). A guest has none: its read is not found and its change gets the sign-up card.+ */+export async function GET(request: Request, ctx: RouteContext<"/api/dub/[id]">) {await connection();const { id } = await ctx.params;- const s = getDubSession(id);- return s ? Response.json(dubView(s)) : Response.json({ error: "Not found" }, { status: 404 });+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return notFound();+ const view = asViewer(viewer, () => {+ const s = getDubSession(id);+ return s ? dubView(s) : null;+ });+ return view ? Response.json(view) : notFound();}/** Save the reviewed lines of one language. */export async function PATCH(request: Request, ctx: RouteContext<"/api/dub/[id]">) {const { id } = await ctx.params;+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return guestRun();const parsed = Patch.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Those lines can't be saved" }, { status: 400 });- try {- return Response.json(saveDubDraft(id, parsed.data.lang, parsed.data.cues));- } catch (e) {- return Response.json({ error: (e as Error).message }, { status: getDubSession(id) ? 422 : 404 });- }+ return asViewer(viewer, () => {+ try {+ return Response.json(saveDubDraft(id, parsed.data.lang, parsed.data.cues));+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: getDubSession(id) ? 422 : 404 });+ }+ });}-/** Forget the dub (its results stay in the Library). */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/dub/[id]">) {+/** Forget the dub (its results stay: in the Library, or an account's runs). */+export async function DELETE(request: Request, ctx: RouteContext<"/api/dub/[id]">) {const { id } = await ctx.params;- return deleteDubSession(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return guestRun();+ return asViewer(viewer, () => deleteDubSession(id)) ? new Response(null, { status: 204 }) : notFound();}diff --git a/src/app/api/dub/[id]/voice/route.ts b/src/app/api/dub/[id]/voice/route.tsindex f56e7fd7..225aae1c 100644--- a/src/app/api/dub/[id]/voice/route.ts+++ b/src/app/api/dub/[id]/voice/route.ts@@ -1,6 +1,6 @@import { z } from "zod";-import { CueSchema, getDubSession, previewVoiceDub, voiceDub } from "@/server/dub";-import { priceAs } from "@/server/visitor";+import { asViewer, bodyTooBig, guestRun, onceForAccount, priceAsRun, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { CueSchema, getDubSession, planVoiceDub, previewVoiceDub, startVoiceDub, voiceDub, voicePlanSteps, type VoicePlan } from "@/server/dub";const Body = z.object({lang: z.string().min(2).max(12),@@ -10,21 +10,50 @@ const Body = z.object({});/** Speak one language's reviewed lines in the cloned voice: the voice pipeline; `?preview=1` only prices it. */-async function post(request: Request, ctx: RouteContext<"/api/dub/[id]/voice">) {+async function post(request: Request, ctx: RouteContext<"/api/dub/[id]/voice">, preview: boolean) {const { id } = await ctx.params;+ const viewer = toolViewer(request);+ if (!preview && viewer.kind === "guest") return guestRun();const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Pick the language to voice" }, { status: 400 });- if (!getDubSession(id)) return Response.json({ error: "Not found" }, { status: 404 });+ // An account's own dub only (another's, or the owner's, reads as not found).+ const session = viewer.kind === "guest" ? null : asViewer(viewer, () => getDubSession(id));+ if (!session) return Response.json({ error: "Not found" }, { status: 404 });+ const opts = { cues: parsed.data.cues, lipsync: parsed.data.lipsync };+ if (!preview && viewer.kind === "account") {+ let plan: VoicePlan | null = null;+ return onceForAccount(+ viewer.account,+ `dub-voice:${id}`,+ undefined,+ () =>+ runAccountTool(request, viewer.account, {+ tool: "dub",+ // Its own video (the voice and the background are its own dub's first steps' results).+ files: [session.video],+ plan: () => voicePlanSteps((plan = planVoiceDub(id, parsed.data.lang, opts))),+ start: () => startVoiceDub(plan!),+ }),+ ({ value, gpuWarning }) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201, headers: { "Cache-Control": "no-store" } }),+ );+ }try {- const opts = { cues: parsed.data.cues, lipsync: parsed.data.lipsync };- if (new URL(request.url).searchParams.get("preview") === "1") return Response.json(previewVoiceDub(id, parsed.data.lang, opts));+ if (preview) return Response.json(previewVoiceDub(id, parsed.data.lang, opts));return Response.json(voiceDub(id, parsed.data.lang, opts), { status: 201 });} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}}-/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */+/**+ * The owner runs as always. A signed-in account voices its own dub on its own GPU or key, and its price check is its+ * own run's (src/server/account-tool-run.ts priceAsRun); a guest's run gets the sign-up card.+ */export async function POST(request: Request, ctx: RouteContext<"/api/dub/[id]/voice">) {- return priceAs(request, () => post(request, ctx));+ const preview = new URL(request.url).searchParams.get("preview") === "1";+ if (toolViewer(request).kind === "account") {+ const big = bodyTooBig(request);+ if (big) return big;+ }+ return preview ? priceAsRun(request, () => post(request, ctx, true)) : post(request, ctx, false);}diff --git a/src/app/api/dub/route.ts b/src/app/api/dub/route.tsindex 4a3c4d7a..5e04f889 100644--- a/src/app/api/dub/route.ts+++ b/src/app/api/dub/route.ts@@ -1,9 +1,10 @@import { connection } from "next/server";import { z } from "zod";import { ONE_SHOT_MODELS, VOICE_SPLIT_IDS, type VoiceSplit } from "@/lib/av/dub";-import { createDubSession, listDubSessions, previewDub } from "@/server/dub";+import { asViewer, bodyTooBig, guestRun, onceForAccount, priceAsRun, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { createDubSession, dubPlanSteps, dubRoomProblem, listDubSessions, planDub, previewDub, startDub, type DubPlan } from "@/server/dub";import { connectRefusal } from "@/server/connect-refusal";-import { priceAs } from "@/server/visitor";+import { ShortsError } from "@/server/shorts";const Body = z.object({engine: z.enum(["cloud", "open"]),@@ -19,22 +20,48 @@ const Body = z.object({voiceSplit: z.enum(VOICE_SPLIT_IDS as [VoiceSplit, ...VoiceSplit[]]).optional(),});-/** Recent dubs with the state of every step. */+/** Recent dubs with the state of every step: the owner's, or a signed-in account's own (a guest has none). */export async function GET(request: Request) {await connection();+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return Response.json({ items: [] }, { headers: { "Cache-Control": "no-store" } });const limit = Number(new URL(request.url).searchParams.get("limit") ?? 30);- return Response.json({ items: listDubSessions(Number.isFinite(limit) ? limit : 30) });+ return Response.json({ items: asViewer(viewer, () => listDubSessions(Number.isFinite(limit) ? limit : 30)) });}/** Start a dub: one-shot jobs (cloud) or the prepare pipeline (both engines); `?preview=1` only prices it. */-async function post(request: Request) {+async function post(request: Request, preview: boolean) {+ const viewer = toolViewer(request);+ if (!preview && viewer.kind === "guest") return guestRun();const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) {const first = parsed.error.issues[0];const msg = first?.path[0] === "video" ? "Add the video to translate" : first?.path[0] === "targets" ? "Pick up to 8 languages to dub into" : "Check the dub settings";return Response.json({ error: msg }, { status: 400 });}- const preview = new URL(request.url).searchParams.get("preview") === "1";+ if (!preview && viewer.kind === "account") {+ // An account's dub: on its own GPU or key, with its own video, after the checks a studio run gets. Its+ // translations run on its own GPU, never on this install's AI helper (src/server/dub.ts planDub).+ const input = parsed.data;+ let plan: DubPlan | null = null;+ return onceForAccount(+ viewer.account,+ "dub",+ undefined,+ () =>+ runAccountTool(request, viewer.account, {+ tool: "dub",+ files: [input.video],+ plan: () => {+ const full = dubRoomProblem();+ if (full) throw new ShortsError(full, 409);+ return dubPlanSteps((plan = planDub(input)));+ },+ start: () => startDub(plan!),+ }),+ ({ value, gpuWarning }) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201, headers: { "Cache-Control": "no-store" } }),+ );+ }try {if (preview) return Response.json(previewDub(parsed.data));return Response.json(createDubSession(parsed.data), { status: 201 });@@ -44,7 +71,16 @@ async function post(request: Request) {}}-/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */+/**+ * The owner runs as always. A signed-in account dubs on its own GPU or key, and its price check is its own run's+ * (src/server/account-tool-run.ts priceAsRun); a guest's price check is the open engine's, and its run gets the sign-up+ * card.+ */export async function POST(request: Request) {- return priceAs(request, () => post(request));+ const preview = new URL(request.url).searchParams.get("preview") === "1";+ if (toolViewer(request).kind === "account") {+ const big = bodyTooBig(request);+ if (big) return big;+ }+ return preview ? priceAsRun(request, () => post(request, true)) : post(request, false);}diff --git a/src/components/audio-tools/clean-dialogue-panel.tsx b/src/components/audio-tools/clean-dialogue-panel.tsxindex 7e6c7d22..d172f1fc 100644--- a/src/components/audio-tools/clean-dialogue-panel.tsx+++ b/src/components/audio-tools/clean-dialogue-panel.tsx@@ -50,7 +50,6 @@ const price = (p: { costUsd: number | null; demo: boolean } | undefined) =>export function CleanDialoguePanel({source,engine,- visitor,blocker,onMixer,}: {@@ -58,8 +57,7 @@ export function CleanDialoguePanel({source: CleanSource | null;/** The header's engine switch: your GPU (DBS) or the cloud (a hosted cleaner). */engine: Engine;- visitor: boolean;- /** Why nothing can run yet (no file, uploading, a visitor), in words. */+ /** Why nothing can run yet (no file, uploading), in words. */blocker: string | null;/** Switch to Split into stems (the mixer opens on the Clean dialogue preset). */onMixer: () => void;@@ -92,7 +90,7 @@ export function CleanDialoguePanel({: null,[source, engine, bed, quality, stereo, cleaner, remux],);- const settled = useSettled(visitor ? null : body);+ const settled = useSettled(body);const preview = useAudioToolPreview(settled);// While a change settles, the last answer is for other settings: say "Checking…" rather than its price.const p = settled === body ? preview.data : undefined;@@ -180,9 +178,7 @@ export function CleanDialoguePanel({)}<div className="flex flex-wrap items-center gap-3"><p className={cn("min-w-0 flex-1 text-[13px]", error && !blocker ? "text-destructive" : "text-muted-foreground")} aria-live="polite">- {visitor ? (- <span className="font-mono text-foreground">{openToolPrice(p, true)}</span>- ) : blocker ? (+ {blocker ? (blocker) : error ? (error@@ -197,7 +193,7 @@ export function CleanDialoguePanel({<span className="font-mono text-foreground">{price(p)}</span>)}</p>- <Button size="lg" className={cn("rounded-full", (blocker || error) && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={go} disabled={visitor || busy}>+ <Button size="lg" className={cn("rounded-full", (blocker || error) && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={go} disabled={busy}>{busy ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />} Clean it</Button></div>diff --git a/src/components/audio-tools/hooks.ts b/src/components/audio-tools/hooks.tsindex ac5f4230..e91ca905 100644--- a/src/components/audio-tools/hooks.ts+++ b/src/components/audio-tools/hooks.ts@@ -5,6 +5,7 @@ import { useEffect, useState } from "react";import type { AudioToolPreview } from "@/lib/av/audio-tools";import type { Engine, Generation } from "@/lib/catalog/types";import type { SpeechEffect } from "@/lib/speech-edit";+import { COMPUTER_KICK_EVENT } from "@/lib/api";import { responseError } from "@/lib/refusals";export type AudioToolBody =@@ -100,6 +101,10 @@ export function useAudioToolRun() {const qc = useQueryClient();return useMutation({mutationFn: (body: AudioToolBody) => post<{ batchId: string; result: Generation; items: Generation[] }>("/api/audio-tools", body),- onSuccess: () => void qc.invalidateQueries({ queryKey: ["generations"] }),+ onSuccess: () => {+ // The tab that runs this person's jobs on the ComfyUI on this computer (an account's "Your GPU") asks at once.+ window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));+ void qc.invalidateQueries({ queryKey: ["generations"] });+ },});}diff --git a/src/components/audio-tools/remove-dialogue-tool.tsx b/src/components/audio-tools/remove-dialogue-tool.tsxindex eaec405d..2c03118c 100644--- a/src/components/audio-tools/remove-dialogue-tool.tsx+++ b/src/components/audio-tools/remove-dialogue-tool.tsx@@ -37,13 +37,7 @@ import {import { Segmented } from "@/components/faceless/controls";import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";import { useGeneration } from "@/components/av/use-generation";-import { SelfHostNote } from "@/components/self-host-note";-import {- useAskBeforeUpload,- useEngine,- useGenerations,- useLikelyVisitor,-} from "@/lib/api";+import { useAskBeforeUpload, useEngine, useGenerations } from "@/lib/api";import {CLOUD_ONLY_REMOVE_PROBLEM,CLOUD_REMOVE_PROBLEM,@@ -104,12 +98,6 @@ const RUN_LABEL: Record<DialogueOutcome, string> = {const COPY ="Takes the talking out and keeps the music and sound effects. The picture stays exactly as it was.";-/**- * Why a guest or an account can't run it: POST /api/audio-tools answers them own-gpu-tool (docs/public-signup.md), so- * the page says so up front and its upload and run are off, instead of a run the server refuses.- */-const SELF_HOSTED = "Remove dialogue isn't available here";-/** ?video= from a result's "Remove dialogue", read once after hydration. */function useHandoff(take: (s: Source) => void) {useEffect(() => {@@ -133,7 +121,7 @@ function AddVideo({}: {onPick: (s: Source) => void;onUpdate: (next: (cur: Source | null) => Source | null) => void;- /** A visitor (the tool doesn't run here for them): nothing is uploaded or picked only to be refused. */+ /** Nothing is uploaded or picked. A guest is asked to sign up first, and an account with nothing to run on to connect its GPU. */disabled?: boolean;}) {const input = useRef<HTMLInputElement>(null);@@ -377,8 +365,6 @@ function ResultPanel({export function RemoveDialogueTool() {const [engine, setEngine, mode] = useEngine();- // A guest or an account: the run answers own-gpu-tool, so the page says so and the upload and run are off.- const visitor = useLikelyVisitor();const run = useAudioToolRun();const [source, setSource] = useState<Source | null>(null);const [outcome, setOutcome] = useState<DialogueOutcome>("no-dialogue");@@ -423,15 +409,13 @@ export function RemoveDialogueTool() {const picked: SplitQuality = quality ?? p?.hostPick ?? "fast";const cloudProblem =mode === "cloud" ? CLOUD_ONLY_REMOVE_PROBLEM : CLOUD_REMOVE_PROBLEM;- const blocker = visitor- ? SELF_HOSTED- : !source- ? "Add a video"- : source.uploading- ? "Uploading…"- : engine === "cloud"- ? cloudProblem- : null;+ const blocker = !source+ ? "Add a video"+ : source.uploading+ ? "Uploading…"+ : engine === "cloud"+ ? cloudProblem+ : null;const error = preview.error ? (preview.error as Error).message : null;const g = result.data;const busy =@@ -467,20 +451,12 @@ export function RemoveDialogueTool() {: null;return (- <ToolShell title="Video tools" selfHostedOnly>+ <ToolShell title="Video tools">{!source && (<ToolHerotitle="Remove dialogue"- subtitle={- visitor- ? COPY- : `${COPY} Runs on your ComfyUI with DBS (open source, 23 MB, CPU or GPU): free.`- }- >- {visitor && (- <SelfHostNote className="mt-3 max-w-xl">{SELF_HOSTED}.</SelfHostNote>- )}- </ToolHero>+ subtitle={`${COPY} Runs on your ComfyUI with DBS (open source, 23 MB, CPU or GPU): free.`}+ />)}<divclassName={cn(@@ -489,7 +465,7 @@ export function RemoveDialogueTool() {)}>{!source ? (- <AddVideo onPick={take} onUpdate={setSource} disabled={visitor} />+ <AddVideo onPick={take} onUpdate={setSource} />) : (<Paneltitle={@@ -651,13 +627,7 @@ export function RemoveDialogueTool() {)}aria-live="polite">- {visitor && engine !== "cloud" ? (- <>- <span className="font-mono text-foreground">- {openToolPrice(p, true)}- </span>- </>- ) : blocker && engine !== "cloud" ? (+ {blocker && engine !== "cloud" ? (blocker) : engine === "cloud" ? (mode === "cloud" ? (@@ -688,7 +658,7 @@ export function RemoveDialogueTool() {"bg-muted text-subtle-foreground hover:bg-muted",)}onClick={go}- disabled={busy || visitor}+ disabled={busy}>{busy ? (<Loader2 className="size-4 animate-spin" />diff --git a/src/components/audio-tools/speech-edit-tool.tsx b/src/components/audio-tools/speech-edit-tool.tsxindex dbded8f4..c7f7a8a4 100644--- a/src/components/audio-tools/speech-edit-tool.tsx+++ b/src/components/audio-tools/speech-edit-tool.tsx@@ -8,14 +8,14 @@ import { toast } from "sonner";import { Button } from "@/components/ui/button";import { Checkbox } from "@/components/ui/checkbox";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";-import { SelfHostNote } from "@/components/self-host-note";+import { OwnSetupChip, useOwnSetupPress, useOwnSetupViewer } from "@/components/own-setup";import { Feed } from "@/components/studio/feed";import { ACCEPT, kindOfFile, LibraryGrid, type SlotValue } from "@/components/studio/media-slot";import { VoiceRecorder } from "@/components/studio/voice-recorder";import { Segmented } from "@/components/faceless/controls";import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";import { useGeneration } from "@/components/av/use-generation";-import { useAskBeforeUpload, useCreateGeneration, useEngine, useGenerations, useLikelyVisitor } from "@/lib/api";+import { useAskBeforeUpload, useCreateGeneration, useEngine, useGenerations } from "@/lib/api";import { clock } from "@/lib/av/audio-tools";import type { Generation, OutputFile } from "@/lib/catalog/types";import type { Cue } from "@/lib/cues";@@ -54,8 +54,11 @@ import { uploadSource } from "./split-tool";const COPY = "Change a word without re-recording it, or how a line sounds: its pitch, pace, mood or noise. The new words come out in the same voice.";const SUBTITLE = `${COPY} Free, on your own GPU.`;-/** A guest or an account (public sign-up): the edit runs on a self-hosted Fuobe only (POST /api/audio-tools answers own-gpu-tool). */-const SELF_HOSTED = "Edit speech isn't available here";+/**+ * What Edit speech needs from a guest's or an account's own setup (src/lib/own-setup.ts): its own GPU with AuK's files+ * and 24 GB. A guest signs up first; an account without its own GPU connects one (a key doesn't run AuK).+ */+const OWN_SETUP = "audio:edit-speech";type Source = SlotValue & { kind: "audio" | "video"; duration?: number };type Mode = "words" | "sound";@@ -101,11 +104,14 @@ function useArrival(take: (s: Source, cues?: Cue[], line?: number) => void) {}, []);}-/** disabled: a visitor (the edit doesn't run here for them), so nothing is uploaded, recorded or picked only to be refused. */+/**+ * disabled: nothing is uploaded, recorded or picked. A guest is asked to sign up first, and an account without its own+ * GPU to connect one (the edit runs on a GPU only).+ */function AddMedia({ onPick, onUpdate, disabled }: { onPick: (s: Source) => void; onUpdate: (next: (cur: Source | null) => Source | null) => void; disabled?: boolean }) {const [over, setOver] = useState(false);const [picking, setPicking] = useState(false);- const askFirst = useAskBeforeUpload();+ const askFirst = useAskBeforeUpload({ gpuOnly: true });const inputId = useId();const take = (f: File | undefined) => {if (!f || disabled || askFirst()) return;@@ -260,7 +266,9 @@ function EffectOptions({ effect, onChange }: { effect: SpeechEffect; onChange: (export function SpeechEditTool() {const [engine, setEngine, mode] = useEngine();- const visitor = useLikelyVisitor();+ // A guest or an account: its own setup's label beside the title, and a press that asks for it first.+ const visitor = useOwnSetupViewer() !== null;+ const press = useOwnSetupPress();const create = useCreateGeneration();const run = useAudioToolRun();const [source, setSource] = useState<Source | null>(null);@@ -338,27 +346,25 @@ export function SpeechEditTool() {const p = preview.data;const error = preview.error ? (preview.error as Error).message : null;const cloudProblem = mode === "cloud" ? CLOUD_ONLY_SPEECH_EDIT_PROBLEM : CLOUD_SPEECH_EDIT_PROBLEM;- const blocker = visitor- ? SELF_HOSTED- : !source- ? "Add a recording"- : source.uploading- ? "Uploading…"- : engine === "cloud"- ? cloudProblem- : !cues- ? "Transcribe it first"- : view === "words" && !changes- ? "Change the words of a line"- : view === "sound" && !range- ? "Tick the lines to change"- : null;+ const blocker = !source+ ? "Add a recording"+ : source.uploading+ ? "Uploading…"+ : engine === "cloud"+ ? cloudProblem+ : !cues+ ? "Transcribe it first"+ : view === "words" && !changes+ ? "Change the words of a line"+ : view === "sound" && !range+ ? "Tick the lines to change"+ : null;const g = result.data;const busy = run.isPending || g?.status === "queued" || g?.status === "running" || onVideo.data?.status === "queued" || onVideo.data?.status === "running";const transcribing = create.isPending || t?.status === "queued" || t?.status === "running";const transcribe = () => {- if (!ready || visitor) return;+ if (!ready || !press(OWN_SETUP)) return;create.mutate({ feature: SPEECH_EDIT_FEATURE, modelId: "oss-qwen3-asr", engine: "open", op: "transcribe", inputs: ready.kind === "video" ? { video: ready.ref } : { audio: ready.ref }, title: `Transcript · ${baseName(ready)}` },{ onSuccess: (items) => setTranscriptId(items[0]?.id ?? null), onError: (e) => toastError(e) },@@ -367,6 +373,7 @@ export function SpeechEditTool() {const go = () => {if (blocker) return void toast(blocker);if (error) return void toast.error(error);+ if (!press(OWN_SETUP)) return;run.mutate(body!, {onSuccess: (r) => {const edit = r.items.find((x) => x.op === "speech-edit") ?? r.result;@@ -382,15 +389,15 @@ export function SpeechEditTool() {const warning = p && source?.kind === "video" ? p.notes.find((n) => /Lipsync/.test(n)) : undefined;return (- <ToolShell title="Audio" selfHostedOnly>+ <ToolShell title="Audio">{!source && (- <ToolHero title="Edit speech" subtitle={visitor ? COPY : SUBTITLE}>- {visitor && <SelfHostNote className="mt-3 max-w-xl">{SELF_HOSTED}.</SelfHostNote>}+ <ToolHero title="Edit speech" subtitle={SUBTITLE}>+ {visitor && <OwnSetupChip setup={OWN_SETUP} short={false} className="mt-3" />}</ToolHero>)}<div className={cn("mx-auto max-w-[860px] space-y-3", source ? "pt-4" : "mt-6")}>{!source ? (- <AddMedia onPick={(s) => take(s)} onUpdate={setSource} disabled={visitor} />+ <AddMedia onPick={(s) => take(s)} onUpdate={setSource} />) : (<SourcePanel source={source} onDuration={(duration) => setSource((s) => (s ? { ...s, duration } : s))} onRemove={clear} />)}@@ -413,7 +420,7 @@ export function SpeechEditTool() {<Panel title="1 · Transcribe"><div className="flex flex-wrap items-center gap-3"><p className="min-w-0 flex-1 text-[13px] text-muted-foreground">Fuobe writes down what was said, line by line, so you can change it like text. Free on your GPU.</p>- <Button className="rounded-full" onClick={transcribe} disabled={!ready || transcribing || visitor}>+ <Button className="rounded-full" onClick={transcribe} disabled={!ready || transcribing}>{transcribing ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />} Transcribe</Button></div>@@ -501,7 +508,7 @@ export function SpeechEditTool() {"Checking…")}</p>- <Button size="lg" className={cn("rounded-full", (blocker || error) && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={go} disabled={busy || visitor}>+ <Button size="lg" className={cn("rounded-full", (blocker || error) && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={go} disabled={busy}>{busy ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />} Edit speech</Button></div>diff --git a/src/components/audio-tools/split-tool.tsx b/src/components/audio-tools/split-tool.tsxindex a87fe93c..1ec5b06f 100644--- a/src/components/audio-tools/split-tool.tsx+++ b/src/components/audio-tools/split-tool.tsx@@ -15,8 +15,7 @@ import { ACCEPT, fileToSlot, kindOfFile, LibraryGrid, type SlotValue } from "@/cimport { Segmented } from "@/components/faceless/controls";import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";import { useGeneration } from "@/components/av/use-generation";-import { SelfHostNote } from "@/components/self-host-note";-import { useAskBeforeUpload, useEngine, useGenerations, useIsAccount, useLikelyVisitor } from "@/lib/api";+import { useAskBeforeUpload, useEngine, useGenerations, useIsAccount } from "@/lib/api";import {backgroundLowered,clock,@@ -147,7 +146,7 @@ export function uploadSource(f: File, kind: "audio" | "video", put: (s: Source));}-/** disabled: a visitor (the split doesn't run here for them), so nothing is uploaded or picked only to be refused. */+/** disabled: nothing is uploaded or picked. A guest is asked to sign up first, and an account with nothing to run on to connect its GPU. */function AddMedia({ onPick, onUpdate, disabled }: { onPick: (s: Source) => void; onUpdate: (next: (cur: Source | null) => Source | null) => void; disabled?: boolean }) {const input = useRef<HTMLInputElement>(null);const [over, setOver] = useState(false);@@ -673,11 +672,6 @@ function Mixer({ stems, source, engine, initial = ORIGINAL_MIX }: { stems: Stem[// ---------------------------------------------------------------------------// The tool-/**- * Why a guest or an account can't split: POST /api/audio-tools answers them own-gpu-tool (docs/public-signup.md), so the- * page says so up front and its upload and run are off, instead of a run the server refuses.- */-const SELF_HOSTED = "Split soundtrack isn't available here";/** Where the time estimate is for: the host's device when it said; else a CPU's, the figures the estimate then uses. */const onDevice = (device?: string) => (device === "cuda" ? "on your GPU" : device ? "on your CPU" : "on a CPU");@@ -696,7 +690,6 @@ function stemsOf(outputs: OutputFile[]): Stem[] {export function SplitSoundtrackTool() {const [engine, setEngine, mode] = useEngine();- const visitor = useLikelyVisitor();const run = useAudioToolRun();const [source, setSource] = useState<Source | null>(null);const [quality, setQuality] = useState<SplitQuality | null>(null);@@ -758,7 +751,7 @@ export function SplitSoundtrackTool() {const channels = p?.channels ?? source?.channels;const picked: SplitQuality = quality ?? p?.hostPick ?? "fast";const cloudProblem = mode === "cloud" ? CLOUD_ONLY_PROBLEM : CLOUD_SPLIT_PROBLEM;- const blocker = visitor ? SELF_HOSTED : !source ? "Add a soundtrack to split" : source.uploading ? "Uploading…" : engine === "cloud" ? cloudProblem : null;+ const blocker = !source ? "Add a soundtrack to split" : source.uploading ? "Uploading…" : engine === "cloud" ? cloudProblem : null;const error = preview.error ? (preview.error as Error).message : null;const go = () => {if (blocker) return void toast(blocker);@@ -776,14 +769,12 @@ export function SplitSoundtrackTool() {const stems = useMemo(() => (g?.status === "succeeded" ? stemsOf(g.outputs) : []), [g]);return (- <ToolShell title="Audio" selfHostedOnly>+ <ToolShell title="Audio">{!source && (<ToolHerotitle={goal === "clean" ? "Clean up dialogue" : "Split any soundtrack"}subtitle={goal === "clean" ? "Clear speech from a noisy or musical recording or video: the music and effects out from under it, or kept quietly." : "Dialogue, music and effects from a song, podcast, film clip or video, with a free live mixer."}- >- {visitor && <SelfHostNote className="mt-3 max-w-xl">{SELF_HOSTED}.</SelfHostNote>}- </ToolHero>+ />)}<div className={cn("mx-auto max-w-[860px] space-y-3", source ? "pt-4" : "mt-8")}><div className="flex min-w-0 flex-wrap items-center gap-2">@@ -798,7 +789,7 @@ export function SplitSoundtrackTool() {/></div>{!source ? (- <AddMedia onPick={take} onUpdate={setSource} disabled={visitor} />+ <AddMedia onPick={take} onUpdate={setSource} />) : (<SourcePanelsource={source}@@ -813,8 +804,7 @@ export function SplitSoundtrackTool() {<CleanDialoguePanelsource={ready ? { ref: ready.ref, kind: ready.kind, name: baseName(ready), duration: ready.duration, channels: ready.channels } : null}engine={engine}- visitor={visitor}- blocker={visitor ? SELF_HOSTED : !source ? "Add a soundtrack to clean" : source.uploading ? "Uploading…" : null}+ blocker={!source ? "Add a soundtrack to clean" : source.uploading ? "Uploading…" : null}onMixer={() => {setGoal("split");setMixPreset(mixPresetFor("split", true));@@ -877,11 +867,7 @@ export function SplitSoundtrackTool() {)}<div className="flex flex-wrap items-center gap-3"><p className={cn("min-w-0 flex-1 text-[13px]", error && !blocker ? "text-destructive" : "text-muted-foreground")} aria-live="polite">- {visitor && engine !== "cloud" ? (- <>- <span className="font-mono text-foreground">{openToolPrice(p, true)}</span>- </>- ) : blocker && engine !== "cloud" ? (+ {blocker && engine !== "cloud" ? (blocker) : engine === "cloud" ? (mode === "cloud" ? (@@ -900,7 +886,7 @@ export function SplitSoundtrackTool() {"Checking…")}</p>- <Button size="lg" className={cn("rounded-full", (blocker || error) && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={go} disabled={visitor || run.isPending || g?.status === "queued" || g?.status === "running"}>+ <Button size="lg" className={cn("rounded-full", (blocker || error) && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={go} disabled={run.isPending || g?.status === "queued" || g?.status === "running"}>{run.isPending || g?.status === "queued" || g?.status === "running" ? <Loader2 className="size-4 animate-spin" /> : <SlidersVertical className="size-4" />} Split it</Button></div>diff --git a/src/components/captions/captions-studio.tsx b/src/components/captions/captions-studio.tsxindex f847c10b..6ac5f284 100644--- a/src/components/captions/captions-studio.tsx+++ b/src/components/captions/captions-studio.tsx@@ -15,7 +15,7 @@ import { MediaDrop } from "@/components/av/media-drop";import { StepList } from "@/components/av/step-list";import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";import { useGeneration } from "@/components/av/use-generation";-import { useCreateGeneration, useEngine, useGenerations, useLikelyVisitor } from "@/lib/api";+import { useCreateGeneration, useEngine, useGenerations } from "@/lib/api";import { useVoiceFirstLive, useVoiceFirstShown, VoiceFirstSwitch } from "@/components/audio-tools/voice-first-switch";import { voiceFirstDefault } from "@/lib/av/voice-first";import { cueProblems } from "@/lib/av/cue-edit";@@ -145,8 +145,6 @@ export function CaptionsStudio() {function Editor({ video, restored, onReplace }: { video: SlotValue; restored: Saved | null; onReplace: (v: SlotValue | null) => void }) {const [engine, , mode] = useEngine();- // Fix this line opens Edit speech, which runs on a self-hosted Fuobe only: not offered to a guest or an account.- const visitor = useLikelyVisitor();const router = useRouter();const create = useCreateGeneration();const editor = useCueEditor(restored?.cues ?? []);@@ -282,7 +280,7 @@ function Editor({ video, restored, onReplace }: { video: SlotValue; restored: SaclassName="max-h-[60vh]"emptyHint="Transcribe the clip, import an .srt / .vtt, or write the lines yourself."/* Fix this line: change what was said in the clip itself (Edit speech, your GPU only). */- onFixLine={mode === "cloud" || visitor ? undefined : (i) => router.push(speechEditLink({ media: video.ref, kind: "video", name: video.name, cues, line: i }))}+ onFixLine={mode === "cloud" ? undefined : (i) => router.push(speechEditLink({ media: video.ref, kind: "video", name: video.name, cues, line: i }))}/></Panel>diff --git a/src/components/dub/dub-studio.tsx b/src/components/dub/dub-studio.tsxindex 262dec67..a3100d2e 100644--- a/src/components/dub/dub-studio.tsx+++ b/src/components/dub/dub-studio.tsx@@ -16,8 +16,7 @@ import { SourceLanguageSelect, TargetLanguages } from "@/components/av/language-import { MediaDrop } from "@/components/av/media-drop";import { StepList, type StepRow } from "@/components/av/step-list";import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";-import { SelfHostNote } from "@/components/self-host-note";-import { useEngine, useLikelyVisitor, useModelAccess } from "@/lib/api";+import { useEngine, useIsOwner, useModelAccess } from "@/lib/api";import { isPlaceholder } from "@/lib/demo-mode";import { keepOffered, offered } from "@/lib/model-access";import { cueProblems } from "@/lib/av/cue-edit";@@ -62,7 +61,9 @@ const SPLIT_LABEL: Record<VoiceSplit, string> = { dbs: "Keep music and effects",const ROUTE_LINE = {open: (split: VoiceSplit) =>`We separate the voice${split === "dbs" ? " from the music and effects" : ""}, translate every line for your review, speak it in the same voice and re-sync the lips.`,- cloud: "Cloud: ElevenLabs isolates the voice and Demucs lifts out the music and effects → Scribe v2 times the voice → Claude (or a local model) translates → you review → ElevenLabs speaks each line at its time and Chatterbox turns it into the speaker's voice → Sync Lipsync 3 → mixed back over the music and effects.",+ // A signed-in account's translations run on its own GPU (Qwen3.5 4B): src/server/dub.ts planDub.+ cloud: (owner: boolean) =>+ `Cloud: ElevenLabs isolates the voice and Demucs lifts out the music and effects → Scribe v2 times the voice → ${owner ? "Claude (or a local model)" : "Qwen3.5 on your GPU"} translates → you review → ElevenLabs speaks each line at its time and Chatterbox turns it into the speaker's voice → Sync Lipsync 3 → mixed back over the music and effects.`,};const STAGE: Record<DubStage, { label: string; tone: string }> = {@@ -100,7 +101,7 @@ export function DubStudio() {// A dub removed elsewhere (another tab) just closes.const open = sessions.data?.find((s) => s.id === openId);return (- <ToolShell title="Audio" selfHostedOnly>+ <ToolShell title="Audio">{open ? (<SessionView key={open.id} s={open} onBack={() => show(null)} />) : openId && sessions.isLoading ? (@@ -120,9 +121,8 @@ export function DubStudio() {function NewDub({ onStarted }: { onStarted: (id: string) => void }) {const [engine, , engineMode] = useEngine();- // A dub doesn't run on an account's own GPU or key yet (only the studios' generations do): said up front, and the- // upload and Translate are off, instead of a run the server refuses.- const visitor = useLikelyVisitor();+ // The note about DBS on your GPU is for the studio's own install with both engines.+ const owner = useIsOwner();const { create } = useDubActions();const [video, setVideo] = useState<SlotValue | null>(null);const [duration, setDuration] = useState<number | undefined>(undefined);@@ -152,7 +152,6 @@ function NewDub({ onStarted }: { onStarted: (id: string) => void }) {: null;const price = useDubPrice(body);const start = () => {- if (visitor) return;if (blocker || !body) return void toast(blocker, { id: "dub-blocker" });create.mutate({ ...body, title: video!.name?.replace(/\.[a-z0-9]+$/i, "") },@@ -169,12 +168,10 @@ function NewDub({ onStarted }: { onStarted: (id: string) => void }) {};return (<div className="pb-10">- <ToolHero title="Speak every language" subtitle="Translate the speech, keep the speaker's voice and re-sync the lips. Review every line before it's spoken.">- {visitor && <SelfHostNote className="mt-3 max-w-xl">Translate & dub isn't available here.</SelfHostNote>}- </ToolHero>+ <ToolHero title="Speak every language" subtitle="Translate the speech, keep the speaker's voice and re-sync the lips. Review every line before it's spoken." /><div className="mx-auto mt-8 max-w-[760px] space-y-3">- {/* A guest's or an account's video would be uploaded for a dub that can't start here. */}- <div inert={visitor} className={cn(visitor && "opacity-50")}>+ {/* A guest is asked to sign up before a video is added, and an account with nothing to run on to connect its GPU. */}+ <div><MediaDropkind="video"value={video}@@ -257,7 +254,7 @@ function NewDub({ onStarted }: { onStarted: (id: string) => void }) {<div className="mt-3 space-y-1 text-[12px] leading-snug text-muted-foreground"><p>Music and effects: Demucs. {MUSIC_MODEL_NOTE}.</p>{/* The note about your GPU is for the studio's own install with both engines, not a guest or an account. */}- {!visitor && engineMode === "both" && <p>{DBS_OPEN_ONLY_NOTE}.</p>}+ {owner && engineMode === "both" && <p>{DBS_OPEN_ONLY_NOTE}.</p>}</div>)}</Panel>@@ -285,11 +282,11 @@ function NewDub({ onStarted }: { onStarted: (id: string) => void }) {</Panel><div className="flex flex-col gap-3 pt-1 sm:flex-row sm:items-center"><p className="flex-1 text-[12px] leading-relaxed text-muted-foreground">- {oneShot ? `${ONE_SHOT[model].name} returns the finished video for each language.` : engine === "open" ? ROUTE_LINE.open(split) : ROUTE_LINE.cloud}+ {oneShot ? `${ONE_SHOT[model].name} returns the finished video for each language.` : engine === "open" ? ROUTE_LINE.open(split) : ROUTE_LINE.cloud(owner)}</p><div className="flex shrink-0 items-center gap-3 self-end sm:self-auto"><PriceNote price={price.data} loading={price.isFetching && !price.data} error={price.error as Error | null} hint={oneShot ? undefined : "Translating costs little; you'll see the voice's price before it speaks"} />- <Button size="lg" className={cn("shrink-0 rounded-full", blocker && "bg-muted text-muted-foreground hover:bg-muted")} onClick={start} disabled={create.isPending || visitor} aria-describedby={blocker ? "dub-blocker" : undefined}>+ <Button size="lg" className={cn("shrink-0 rounded-full", blocker && "bg-muted text-muted-foreground hover:bg-muted")} onClick={start} disabled={create.isPending} aria-describedby={blocker ? "dub-blocker" : undefined}>{create.isPending ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />}{oneShot ? "Dub it" : "Translate"}</Button>@@ -305,19 +302,15 @@ function NewDub({ onStarted }: { onStarted: (id: string) => void }) {);}-/**- * The price of the next step, next to its button: "≈ $8.13 + ElevenLabs v4", "Placeholder · free", "Free on your GPU" ("Self-hosted- * only" for a guest or an account: a dub doesn't run on their own GPU yet).- */+/** The price of the next step, next to its button: "≈ $8.13 + ElevenLabs v4", "Placeholder · free", "Free on your GPU". */function PriceNote({ price, loading, error, hint }: { price?: DubPrice; loading?: boolean; error?: Error | null; hint?: string }) {- const visitor = useLikelyVisitor();if (loading) return <Skeleton className="h-4 w-20" aria-label="Pricing" />;if (error) return <span className="max-w-[16rem] text-right text-[12px] leading-snug text-muted-foreground">{error.message}</span>;if (!price) return null;const extra = price.unpriced.length ? `${price.unpriced.join(" and ")} bill${price.unpriced.length === 1 ? "s" : ""} by the provider's own rate (per character or token).` : undefined;return (<span className="text-right text-[12px] leading-snug" title={[extra, hint].filter(Boolean).join(" ") || undefined}>- <span className="font-medium tabular-nums">{visitor && (price.demo || price.engine === "open") ? "Not available here" : priceLine(price)}</span>+ <span className="font-medium tabular-nums">{priceLine(price)}</span>{price.steps > 1 && <span className="block text-muted-foreground">{price.steps} steps</span>}</span>);diff --git a/src/components/dub/hooks.ts b/src/components/dub/hooks.tsindex 4d3b8044..de254c5f 100644--- a/src/components/dub/hooks.ts+++ b/src/components/dub/hooks.ts@@ -2,7 +2,7 @@import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { useEffect, useState } from "react";-import { useGenerationEvents } from "@/lib/api";+import { COMPUTER_KICK_EVENT, useGenerationEvents } from "@/lib/api";import type { DubPrice, DubSessionView, OneShotModel, VoiceSplit } from "@/lib/av/dub";import type { Cue } from "@/lib/cues";import type { Engine, Generation } from "@/lib/catalog/types";@@ -14,6 +14,12 @@ async function json<T>(res: Response): Promise<T> {return body;}+/**+ * A dub's steps started: 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.+ */+const kick = () => window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));+const active = (gs: Generation[]) => gs.some((g) => g.status === "queued" || g.status === "running");/** Recent dubs; refreshed when one of their steps changes on the live stream. */@@ -87,6 +93,7 @@ export function useDubActions() {const create = useMutation({mutationFn: async (body: NewDub) => json<DubSessionView>(await fetch("/api/dub", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })),onSuccess: (s) => {+ kick();put(s);void qc.invalidateQueries({ queryKey: ["generations"] });},@@ -105,6 +112,7 @@ export function useDubActions() {mutationFn: async ({ id, lang, cues, lipsync }: { id: string; lang: string; cues?: Cue[]; lipsync?: boolean }) =>json<DubSessionView>(await fetch(`/api/dub/${id}/voice`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ lang, cues, lipsync }) })),onSuccess: (s) => {+ kick();put(s);void qc.invalidateQueries({ queryKey: ["generations"] });},diff --git a/src/lib/av/dub.ts b/src/lib/av/dub.tsindex 15ebb246..6e9ac473 100644--- a/src/lib/av/dub.ts+++ b/src/lib/av/dub.ts@@ -153,6 +153,29 @@ export interface PrepareInput {title?: string;/** Open engine: the voice split (default DEFAULT_VOICE_SPLIT). The cloud ignores it. */voiceSplit?: VoiceSplit;+ /**+ * "gpu": the translations run on the asker's own ComfyUI (Qwen3.5 4B, GPU_TRANSLATE_MODEL), never on the install's+ * AI helper: a signed-in account's dub, on either engine. Default: the install's text model (DUB_STEP_MODELS).+ */+ translator?: "gpu";+ /** The video's length (seconds): how long a GPU translation may write. */+ seconds?: number;+}++/** The ComfyUI translator an account's dub uses (translate-qwen35-textgen): on its own GPU, timings kept. */+export const GPU_TRANSLATE_MODEL = "oss-qwen35-translate";++/**+ * The GPU translator's instruction: the transcript reaches it as the chained JSON list of timed lines, and its answer is+ * one "start-end: text" line per line, which the result reads back as timed lines.+ */+export const GPU_TRANSLATE_INSTRUCTION =+ 'The text below is a JSON list of subtitle lines. Each line has a "start" and an "end" time in seconds and its "text". Translate the text of every line into {language}. Write one line per item, in the same order, as start-end: translation, with the start and end numbers exactly as given (for example 0.5-2.75: translation). Keep each translation about as long as the original so it can be spoken in the same time. Output only those lines.\n\n';++/** How many tokens the GPU translator may write for a video this long (about 10 a second, within its limits). */+export function gpuTranslateTokens(seconds?: number): number {+ if (!seconds || !(seconds > 0)) return 8192;+ return Math.min(16_384, Math.max(2048, Math.ceil(seconds * 10)));}/** Step 1 (both engines): the voice to clone, the timed transcript and one translation per target language. */@@ -168,9 +191,13 @@ export function prepareSteps(o: PrepareInput): DubStep[] {chain: [{ slot: "prompt" }],request: {...base,- modelId: o.engine === "open" ? DUB_STEP_MODELS.open.translate : DUB_STEP_MODELS.cloud.translate,+ modelId: o.translator === "gpu" ? GPU_TRANSLATE_MODEL : o.engine === "open" ? DUB_STEP_MODELS.open.translate : DUB_STEP_MODELS.cloud.translate,op: "translate",- params: { targetLanguage: lang.name, ...(from && { sourceLanguage: from }) },+ params: {+ targetLanguage: lang.name,+ ...(from && { sourceLanguage: from }),+ ...(o.translator === "gpu" && { extra: { instruction: GPU_TRANSLATE_INSTRUCTION, maxTokens: gpuTranslateTokens(o.seconds) } }),+ },step: step(`Translate · ${lang.name}`, i, of),},});diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex 821a9ac6..df3168be 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -176,10 +176,11 @@ export function accountOwnRead(pathname: string): boolean {const ACCOUNT_CANVASES = /^\/api\/account\/canvases(\/[^/]+)?$/;/**- * The Library's counts, its Uploads (its stored files) and a zip of its runs (the Library's Download, a result's- * Download all, Shorts' Download parts): each route answers an account with its own only.+ * The Library's counts, its Uploads (its stored files), a zip of its runs (the Library's Download, a result's+ * Download all, Shorts' Download parts) and its own dubs (src/server/dub.ts): each route answers an account with its own+ * only.*/-const ACCOUNT_LISTS = new Set(["/api/generations/facets", "/api/assets", "/api/generations/zip"]);+const ACCOUNT_LISTS = new Set(["/api/generations/facets", "/api/assets", "/api/generations/zip", "/api/dub"]);/*** A signed-in account's zip of its own runs (/api/generations/zip; src/server/account-files.ts ACCOUNT_LIMITS): at most@@ -307,6 +308,10 @@ export const ACCOUNT_TOOL_RUNS: readonly RegExp[] = [/^\/api\/mixed-media(\/(preview|retry))?$/,/^\/api\/(turnaround|fly-around)$/,/^\/api\/katana(\/[^/]+\/retry)?$/,+ // Audio's tools (Split soundtrack, Clean up dialogue, Remove dialogue, Edit speech, Loop, Join, Clean up voice), and+ // Translate & dub: a dub, and voicing one language of the account's own dub (src/server/dub.ts).+ /^\/api\/audio-tools$/,+ /^\/api\/dub(\/[^/]+\/voice)?$/,];/**@@ -331,6 +336,9 @@ export const ACCOUNT_PROJECT_ROUTES: RegExp[] = [// Katana: its own runs (the list, one run, forgetting one), and how far its own Mixed Media render's frames are./^\/api\/katana(\/[^/]+)?$/,/^\/api\/mixed-media\/progress$/,+ // 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\/[^/]+$/,];export const accountProjectRoute = (pathname: string): boolean => ACCOUNT_PROJECT_ROUTES.some((r) => r.test(pathname));diff --git a/src/lib/hubs.ts b/src/lib/hubs.tsindex a1294c2e..a5331c42 100644--- a/src/lib/hubs.ts+++ b/src/lib/hubs.ts@@ -36,10 +36,10 @@ export const HUB_MODES: Record<HubKind, HubMode[]> = {{ id: "dialogue", label: "Dialogue" },{ id: "voice-change", label: "Voice change" },{ id: "design", label: "Design a voice" },- { id: "edit-speech", label: "Edit speech", selfHostedOnly: true },- { id: "translate", label: "Translate", selfHostedOnly: true },+ { id: "edit-speech", label: "Edit speech", ownSetup: "audio:edit-speech" },+ { id: "translate", label: "Translate" },{ id: "transcribe", label: "Transcribe" },- { id: "split", label: "Split soundtrack", selfHostedOnly: true },+ { id: "split", label: "Split soundtrack" },{ id: "sfx", label: "Sound effects" },{ id: "music", label: "Music" },{ id: "song", label: "Extend & remix", ownSetup: "mureka-extend" },@@ -51,7 +51,7 @@ export const HUB_MODES: Record<HubKind, HubMode[]> = {{ id: "matte", label: "Remove background" },{ id: "green-screen", label: "Green screen" },{ id: "remove-object", label: "Remove object" },- { id: "remove-dialogue", label: "Remove dialogue", selfHostedOnly: true },+ { id: "remove-dialogue", label: "Remove dialogue" },{ id: "remove-person", label: "Remove a person" },{ id: "evolution", label: "Evolution" },{ id: "restore", label: "Restore & colourise", ownerOnly: true, selfHostedOnly: true },diff --git a/src/lib/nav-model.ts b/src/lib/nav-model.tsindex 18f22add..175a8064 100644--- a/src/lib/nav-model.ts+++ b/src/lib/nav-model.ts@@ -731,10 +731,7 @@ export const STUDIO_SUBS: Readonly<Record<string, StudioSubs>> = {* Features a guest or an account may open but not run here (their pages say so up front, docs/public-signup.md): the* menus and the phone sheet link them for the owner only. Search and /studios still list them.*/-export const OWNER_RUNS: ReadonlySet<string> = new Set([- "audio-split",- "video-tools-remove-dialogue",-]);+export const OWNER_RUNS: ReadonlySet<string> = new Set<string>();/** The studio a feature lives under in the menus (Ads Studio under Marketing Studio). */const SUB_PARENT = new Map(Object.entries(STUDIO_SUBS).flatMap(([parent, s]) => s.ids.map((id) => [id, parent] as const)));diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.tsindex 5f60db3a..560b26fe 100644--- a/src/lib/output-actions.ts+++ b/src/lib/output-actions.ts@@ -116,7 +116,7 @@ export interface ActionContext {export const draftRenderPaid = (placeholders: boolean | undefined): string => (placeholders ? "" : " · paid");/** Hand-offs to tools a guest or an account can't open (they run on a self-hosted Fuobe only). */-const OWNER_ONLY_ACTIONS: ReadonlySet<OutputActionId> = new Set<OutputActionId>(["restore-video", "remove-dialogue", "clean-dialogue", "edit-speech"]);+const OWNER_ONLY_ACTIONS: ReadonlySet<OutputActionId> = new Set<OutputActionId>(["restore-video"]);const q = (url: string) => encodeURIComponent(url);diff --git a/src/server/audio-tools.ts b/src/server/audio-tools.tsindex 23814718..747d9b97 100644--- a/src/server/audio-tools.ts+++ b/src/server/audio-tools.ts@@ -8,6 +8,7 @@ import { CLOUD_ONLY_CLEAN_PROBLEM, missingReuse, NO_REUSE_PACK, planClean, planTimport type { Engine, Generation } from "@/lib/catalog/types";import { CLOUD_ONLY_SPEECH_EDIT_PROBLEM, EMOTIONS, PACES, PITCH_STEPS, planSpeechEdit, SPEECH_EDIT_MAX_SECONDS, VOLUME_STEPS } from "@/lib/speech-edit";import { lastGpuDevice } from "./account-gpu";+import type { ToolStep } from "./account-tool-run";import { createPipeline } from "./chains";import { ConnectComfyError, previewChained } from "./generations";import { comfyDbsModels, comfyDevice, comfyReuseModels, ownGpu } from "./providers/comfyui";@@ -207,7 +208,16 @@ function factsOf(url: string, gone = "That audio file is gone — add it again")return { ...(duration && { duration }), ...(info.channels && { channels: info.channels }), hasAudio: info.hasAudio };}-type AudioToolPlan = ToolPlan & { engine: Engine; split?: ClipFacts; headerChannels?: number };+export type AudioToolPlan = ToolPlan & { engine: Engine; split?: ClipFacts; headerChannels?: number };++/** Every file a request names (its clip, its clips, the mix and the video it goes on): an account's own, checked first. */+export function audioToolFiles(body: AudioToolRequest): string[] {+ if (body.tool === "join") return body.clips.map((c) => c.url);+ if (body.tool === "loop") return [body.audio];+ if (body.tool === "remux") return [body.video, body.audio];+ if (body.tool === "remove-dialogue") return [body.video];+ return [body.media];+}async function plan(body: AudioToolRequest): Promise<AudioToolPlan> {return planAudioTool(body);@@ -351,9 +361,23 @@ export async function previewAudioTool(body: AudioToolRequest): Promise<AudioTooreturn out;}+/**+ * A planned run's steps as an account's run checks them (src/server/account-tool-run.ts): each request with its chain,+ * and how many earlier steps it waits for.+ */+export function audioToolSteps(p: AudioToolPlan): ToolStep[] {+ return p.steps.map((s) => ({ request: s.chain ? { ...s.request, chain: s.chain } : s.request, deps: s.after?.length ?? 0 }));+}++export type AudioToolRun = { batchId: string; result: Generation; items: Generation[] };+/** Start a run: one batch; the last step's generation is the result. */-export async function runAudioTool(body: AudioToolRequest): Promise<{ batchId: string; result: Generation; items: Generation[] }> {- const p = await plan(body);+export async function runAudioTool(body: AudioToolRequest): Promise<AudioToolRun> {+ return startAudioTool(await plan(body));+}++/** Start a planned run (an account's, after its checks passed: inside asAccount). */+export function startAudioTool(p: AudioToolPlan): AudioToolRun {try {const run = createPipeline(p.steps.map((s) => ({ key: s.key, request: s.request, ...(s.after && { after: s.after }), ...(s.chain && { chain: s.chain }) })));return { batchId: run.batchId, result: run.byKey[p.steps[p.steps.length - 1].key], items: run.items };diff --git a/src/server/dub.ts b/src/server/dub.tsindex 6eb7cc68..443e6491 100644--- a/src/server/dub.ts+++ b/src/server/dub.ts@@ -20,12 +20,15 @@ import {} from "@/lib/av/dub";import { normalizeCues } from "@/lib/av/cue-edit";import { getModel } from "@/lib/catalog";-import type { Engine, Generation } from "@/lib/catalog/types";+import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";+import { ACCOUNT_PROJECT_LIMITS, createAccountProject, deleteAccountProject, getAccountProject, listAccountProjects, updateAccountProject } from "./account-projects";+import type { ToolStep } from "./account-tool-run";import { createPipeline } from "./chains";import { db } from "./db";import { cancelGeneration, createGenerations, getGeneration, previewChained } from "./generations";import { isOffered } from "./model-access";import { storedMedia } from "./storage";+import { tenantAccount } from "./tenant";/*** Translate & dub sessions. A session remembers the source video, the languages and which generations@@ -44,23 +47,61 @@ interface Row {updated_at: number;}-const toSession = (r: Row): DubSession => ({ ...(JSON.parse(r.data_json) as Omit<DubSession, "id" | "createdAt" | "updatedAt">), id: r.id, createdAt: r.created_at, updatedAt: r.updated_at });+type SessionData = Omit<DubSession, "id" | "createdAt" | "updatedAt">;++const toSession = (r: Row): DubSession => ({ ...(JSON.parse(r.data_json) as SessionData), id: r.id, createdAt: r.created_at, updatedAt: r.updated_at });++/**+ * A signed-in account's dubs (public sign-up) are its own projects (account-projects.ts, kind "dub"), never rows of the+ * owner's dub_sessions: inside the account's work (asAccount) every read and change names it, so another account's dub+ * or the owner's reads as not found. Its steps are its own runs (src/server/account-tool-run.ts).+ */+const DUB_KIND = "dub";++/** The session's data as it's stored (its id and times are the row's). */+function dataOf(s: DubSession): SessionData {+ const { id, createdAt, updatedAt, ...data } = s;+ void id;+ void createdAt;+ void updatedAt;+ return data;+}++/** A line in an account's list of dubs: what the list shows without reading the dub. */+const summaryOf = (s: DubSession) => ({ mode: s.mode, engine: s.engine, targets: s.targets });function save(s: DubSession): DubSession {- const { id, createdAt, ...data } = s;+ const data = dataOf(s);+ const account = tenantAccount();+ if (account) {+ const saved = updateAccountProject(account, DUB_KIND, s.id, { name: s.title, data, summary: summaryOf(s) });+ if (!saved) throw new Error("This dub no longer exists");+ return { ...s, updatedAt: saved.updatedAt };+ }const now = Date.now();- delete (data as Partial<DubSession>).updatedAt;db().prepare("INSERT INTO dub_sessions (id, data_json, created_at, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET data_json = excluded.data_json, updated_at = excluded.updated_at")- .run(id, JSON.stringify(data), createdAt, now);+ .run(s.id, JSON.stringify(data), s.createdAt, now);return { ...s, updatedAt: now };}export function getDubSession(id: string): DubSession | null {+ const account = tenantAccount();+ if (account) {+ const p = getAccountProject<SessionData>(account, DUB_KIND, id);+ return p ? { ...p.data, id: p.id, createdAt: p.createdAt, updatedAt: p.updatedAt } : null;+ }const r = db().prepare("SELECT * FROM dub_sessions WHERE id = ?").get(id) as Row | undefined;return r ? toSession(r) : null;}+/** An account has room for another dub (its projects of this kind): the words to say when it hasn't, else null. */+export function dubRoomProblem(): string | null {+ const account = tenantAccount();+ if (!account) return null;+ return listAccountProjects(account, DUB_KIND).length >= ACCOUNT_PROJECT_LIMITS.projects ? `You can keep up to ${ACCOUNT_PROJECT_LIMITS.projects} dubs. Delete one to make another.` : null;+}+/** Every generation id a session refers to. */function sessionIds(s: DubSession): string[] {return [@@ -81,7 +122,17 @@ export function dubView(s: DubSession): DubSessionView {}export function listDubSessions(limit = 30): DubSessionView[] {- const rows = db().prepare("SELECT * FROM dub_sessions ORDER BY updated_at DESC LIMIT ?").all(Math.max(1, Math.min(100, limit))) as Row[];+ const n = Math.max(1, Math.min(100, limit));+ const account = tenantAccount();+ if (account) {+ return listAccountProjects(account, DUB_KIND)+ .slice(0, n)+ .flatMap((p) => {+ const s = getDubSession(p.id);+ return s ? [dubView(s)] : [];+ });+ }+ const rows = db().prepare("SELECT * FROM dub_sessions ORDER BY updated_at DESC LIMIT ?").all(n) as Row[];return rows.map((r) => dubView(toSession(r)));}@@ -120,7 +171,18 @@ export function dubVoiceSplit(input: Pick<CreateDubInput, "engine" | "mode" | "vreturn input.engine === "open" && input.mode === "steps" ? pickVoiceSplit(input.voiceSplit, (id) => isOffered(id, "open")) : undefined;}-export function createDubSession(input: CreateDubInput): DubSessionView {+/** A dub planned, not started: the session it will be, and its one-shot jobs or its prepare pipeline. */+export interface DubPlan {+ base: DubSession;+ oneshot?: { model: OneShotModel; jobs: { lang: { code: string }; request: GenerationRequest }[] };+ steps?: DubStep[];+}++/**+ * Plan a dub. Inside a signed-in account's work its translations run on its own GPU (Qwen3.5 4B), never on this+ * install's AI helper (prepareSteps `translator`).+ */+export function planDub(input: CreateDubInput): DubPlan {if (input.mode === "oneshot" && input.engine === "open") throw new Error("One-shot dubbing is a cloud service — the open engine dubs step by step");const now = Date.now();const title = input.title?.trim().slice(0, 120) || "Dubbed video";@@ -142,26 +204,64 @@ export function createDubSession(input: CreateDubInput): DubSessionView {};if (input.mode === "oneshot") {const model = input.model ?? "heygen-translate";- const jobs = oneShotRequests({ model, video: input.video, source: input.source, targets: base.targets, title });+ return { base, oneshot: { model, jobs: oneShotRequests({ model, video: input.video, source: input.source, targets: base.targets, title }) } };+ }+ const gpu = tenantAccount() ? ({ translator: "gpu", seconds: duration } as const) : {};+ return { base, steps: prepareSteps({ engine: input.engine, video: input.video, source: input.source, targets: base.targets, title, voiceSplit, ...gpu }) };+}++/** A planned dub's requests as an account's run checks them (src/server/account-tool-run.ts). */+export function dubPlanSteps(p: DubPlan): ToolStep[] {+ if (p.oneshot) return p.oneshot.jobs.map((j) => ({ request: j.request }));+ return (p.steps ?? []).map(toolStep);+}++const toolStep = (st: DubStep): ToolStep => ({ request: st.chain ? { ...st.request, chain: st.chain } : st.request, deps: asList(st.after).length });++/**+ * Start a planned dub. An account's is kept as one of its own projects first (its id is the dub's), and forgotten+ * again when nothing could start.+ */+export function startDub(p: DubPlan): DubSessionView {+ const account = tenantAccount();+ let base = p.base;+ if (account) {+ const made = createAccountProject(account, DUB_KIND, { name: base.title, data: dataOf(base), summary: summaryOf(base) });+ base = { ...base, id: made.id, createdAt: made.createdAt, updatedAt: made.updatedAt };+ }+ const forget = () => account && deleteAccountProject(account, DUB_KIND, base.id);+ if (p.oneshot) {const oneshot: Record<string, string> = {};const made: Generation[] = [];try {- for (const j of jobs) {+ for (const j of p.oneshot.jobs) {const g = createGenerations(j.request, { batchId: base.batchId })[0];made.push(g);oneshot[j.lang.code] = g.id;}} catch (e) {+ // An account keeps the languages that started (it can open and stop them); with none, its dub is forgotten.+ if (account && made.length) save({ ...base, model: p.oneshot.model, oneshot });+ else forget();throw new Error(made.length ? `${(e as Error).message} (the other languages were started)` : (e as Error).message);}- return dubView(save({ ...base, model, oneshot }));+ return dubView(save({ ...base, model: p.oneshot.model, oneshot }));+ }+ let run: ReturnType<typeof createPipeline>;+ try {+ run = createPipeline(p.steps ?? [], { batchId: base.batchId });+ } catch (e) {+ forget();+ throw e;}- const steps = prepareSteps({ engine: input.engine, video: input.video, source: input.source, targets: base.targets, title, voiceSplit });- const run = createPipeline(steps, { batchId: base.batchId });const prepare = Object.fromEntries(Object.entries(run.byKey).map(([k, g]) => [k, g.id]));return dubView(save({ ...base, prepare }));}+export function createDubSession(input: CreateDubInput): DubSessionView {+ return startDub(planDub(input));+}+/** Save the reviewed lines of one language (nothing is spoken until voiceDub). */export function saveDubDraft(id: string, lang: string, cues: Cue[]): DubSessionView {const s = getDubSession(id);@@ -171,7 +271,7 @@ export function saveDubDraft(id: string, lang: string, cues: Cue[]): DubSessionV}/** The voice pipeline of one language, planned (not started): the steps and the session as it'll be saved. */-function planVoice(id: string, lang: string, opts: { cues?: Cue[]; lipsync?: boolean }): { s: DubSession; current: DubSession; steps: DubStep[]; lipsync: boolean } {+function planVoice(id: string, lang: string, opts: { cues?: Cue[]; lipsync?: boolean }): { s: DubSession; current: DubSession; steps: DubStep[]; lipsync: boolean; lang: string } {const s = getDubSession(id);if (!s) throw new Error("This dub no longer exists");if (s.mode !== "steps") throw new Error("This dub was made in one go — there's nothing to voice");@@ -187,12 +287,23 @@ function planVoice(id: string, lang: string, opts: { cues?: Cue[]; lipsync?: booif (!media.voice) throw new Error("The voice to clone is missing from the first step");const lipsync = opts.lipsync !== false;const steps = voiceSteps({ engine: s.engine, video: s.video, lang, cues, voiceRef: media.voice, background: media.background, lipsync, duration: s.duration ?? videoLength(s.video), title: s.title });- return { s, current, steps, lipsync };+ return { s, current, steps, lipsync, lang };}+export type VoicePlan = ReturnType<typeof planVoice>;++/** One language's voice pipeline planned, not started (an account's run checks its steps first: voicePlanSteps). */+export const planVoiceDub = (id: string, lang: string, opts: { cues?: Cue[]; lipsync?: boolean } = {}): VoicePlan => planVoice(id, lang, opts);++export const voicePlanSteps = (p: VoicePlan): ToolStep[] => p.steps.map(toolStep);+/** Speak the reviewed lines of one language: the voice pipeline. */export function voiceDub(id: string, lang: string, opts: { cues?: Cue[]; lipsync?: boolean } = {}): DubSessionView {- const { s, current, steps, lipsync } = planVoice(id, lang, opts);+ return startVoiceDub(planVoice(id, lang, opts));+}++/** Start a planned voice pipeline (an account's, inside asAccount after its checks). */+export function startVoiceDub({ s, current, steps, lipsync, lang }: VoicePlan): DubSessionView {const run = createPipeline(steps, { batchId: s.batchId });const ids = Object.fromEntries(Object.entries(run.byKey).map(([k, g]) => [k, g.id]));const voices = { ...s.voices, [lang]: [...(s.voices?.[lang] ?? []), { ids, at: Date.now(), lipsync }] };@@ -229,7 +340,9 @@ export function previewDub(input: CreateDubInput): DubPrice {const jobs = oneShotRequests({ model: input.model ?? "heygen-translate", video: input.video, source: input.source, targets });return priceSteps(input.engine, jobs.map((j, i) => ({ key: `dub:${i}`, request: j.request })), seconds);}- return priceSteps(input.engine, prepareSteps({ engine: input.engine, video: input.video, source: input.source, targets, voiceSplit: dubVoiceSplit(input) }), seconds);+ // An account's translations run on its own GPU (planDub), and are priced so.+ const gpu = tenantAccount() ? ({ translator: "gpu", seconds } as const) : {};+ return priceSteps(input.engine, prepareSteps({ engine: input.engine, video: input.video, source: input.source, targets, voiceSplit: dubVoiceSplit(input), ...gpu }), seconds);}/** What voicing one language would cost (POST /api/dub/[id]/voice?preview=1). */@@ -242,6 +355,8 @@ export function previewVoiceDub(id: string, lang: string, opts: { cues?: Cue[];export function deleteDubSession(id: string): boolean {const s = getDubSession(id);if (s) stopSteps(sessionIds(s));+ const account = tenantAccount();+ if (account) return deleteAccountProject(account, DUB_KIND, id);return db().prepare("DELETE FROM dub_sessions WHERE id = ?").run(id).changes > 0;}diff --git a/tests/account-audio.test.ts b/tests/account-audio.test.tsnew file mode 100644index 00000000..bbef4538--- /dev/null+++ b/tests/account-audio.test.ts@@ -0,0 +1,418 @@+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_WAV, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";++vi.setConfig({ testTimeout: 120_000 });+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++/**+ * The Audio tools and Translate & dub for a signed-in account (public sign-up): every step runs on the account's own+ * ComfyUI (a stand-in here) through the same generations every studio run makes, with only its own files; its dubs are+ * its own projects, and their translations run on its own GPU, never on the install's AI helper. A guest gets the+ * sign-up card; another account's dubs and runs and the owner's are never reached.+ */+const dir = tempDir("fuobe-account-audio-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";+process.env.FUOBE_PUBLIC_SIGNUP = "1";+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 ("owner-comfy.test"): recorded, so a test sees that nothing reached it.+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" && url.port !== "11434" && url.port !== "1234") 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;++const auth = await import("@/server/auth");+const toolsRoute = await import("@/app/api/audio-tools/route");+const exportRoute = await import("@/app/api/audio-tools/export/route");+const dubsRoute = await import("@/app/api/dub/route");+const dubRoute = await import("@/app/api/dub/[id]/route");+const voiceRoute = await import("@/app/api/dub/[id]/voice/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 { GPU_TRANSLATE_MODEL, reviewCues } = await import("@/lib/av/dub");+const { ensureRunner, getGeneration, listGenerations } = 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 { listDubSessions } = await import("@/server/dub");+const { purgeAccount } = await import("@/server/account-sweep");++const CLIP = fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4"));+// The words the stand-in's text steps write: a transcript (and a translation) as timed lines.+const LINES = "0.00-2.00: Hello there\n2.20-4.00: How are you";++let fake: FakeComfy;+let a = "";+let b = "";+let c = "";+const cookies: Record<string, string> = {};+beforeAll(async () => {+ fake = await startFakeComfy({ loras: [], delayMs: 0, graph: true, text: LINES });+ 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);+ // The runner's own start looks for the install's ComfyUI and local AI helper once: not part of any run.+ ensureRunner();+ await new Promise((r) => setTimeout(r, 300));+ fetched.length = 0;+});+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 = 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] }) },+ body: text,+ });+}+const get = (url: string, who?: string) => new Request(`http://localhost:3000${url}`, { headers: { host: "localhost:3000", ...(who && { cookie: cookies[who] }) } });+const ctx = (id: string) => ({ params: Promise.resolve({ id }) }) 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;+}++/** Tick the runner until the row is done (or the time is up). */+async function settle(id: string, ms = 60_000) {+ const end = Date.now() + ms;+ for (;;) {+ await globalThis.__fuobeRunner?.tick();+ const g = getGeneration(id, { includeDeleted: true });+ if (!g || (g.status !== "queued" && g.status !== "running") || Date.now() > end) return g;+ await new Promise((r) => setTimeout(r, 100));+ }+}++const prompts = () => fake.log.filter((e) => e.path === "/prompt").length;+const generationCount = () => (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;++/** Start an audio tool run as `who`; a LoRA its ComfyUI lacks is put there (the 409 names it), then it is sent again. */+async function tool(body: unknown, who: string): Promise<Response> {+ let r = await toolsRoute.POST(json("/api/audio-tools", "POST", body, who));+ if (r.status === 409 && (await r.clone().json()).code === "comfy_missing_model") {+ const j = (await r.json()) as { fix: { items: { file: string }[] } };+ fake.opts.loras = [...(fake.opts.loras ?? []), ...j.fix.items.map((i) => i.file)];+ for (const id of [a, b]) clearAccountLoras(id);+ r = await toolsRoute.POST(json("/api/audio-tools", "POST", body, who));+ }+ return r;+}++type Run = { batchId: string; result: { id: string }; items: { id: string; batchId: string | null }[] };++/** A run's every step: its own, on its own ComfyUI; nothing reached the install's ComfyUI or AI helper. */+async function ranAsOwn(r: Response, who: string) {+ expect(r.status, await r.clone().text()).toBe(201);+ const run = (await r.json()) as Run;+ expect(new Set(run.items.map((g) => g.batchId)).size).toBe(1);+ for (const g of run.items) {+ const row = getGeneration(g.id)!;+ expect(row.request.account, g.id).toBe(who);+ expect(row.provider, g.id).toBe("comfyui");+ }+ const done = await settle(run.result.id);+ expect(done?.status, done?.error ?? "").toBe("succeeded");+ for (const g of run.items) expect(getGeneration(g.id)!.status, g.id).toBe("succeeded");+ return { run, done: done! };+}++describe("the proxy opens the Audio tools and Translate & dub to accounts, and keeps the sign-up card for guests", () => {+ it("a guest gets the sign-up card on a run, a dub, a voice and a change to a dub; its price checks go through", async () => {+ for (const [p, m] of [+ ["/api/audio-tools", "POST"],+ ["/api/dub", "POST"],+ ["/api/dub/some-id/voice", "POST"],+ ["/api/dub/some-id", "PATCH"],+ ["/api/dub/some-id", "DELETE"],+ ["/api/audio-tools/export", "POST"],+ ] as const) {+ const r = viaProxy(p, m);+ expect(r.status, `${m} ${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/audio-tools?preview=1", "/api/dub?preview=1", "/api/dub/some-id/voice?preview=1"]) expect(passed(viaProxy(p, "POST")), p).toBe(true);+ // Its dubs list is empty; a dub is the owner's library (closed).+ expect(await viaProxy("/api/dub").json()).toEqual({ items: [] });+ expect(viaProxy("/api/dub/some-id").status).toBe(401);+ });++ it("an account with its own GPU reaches every route; one with neither a GPU nor a key is asked to connect one", async () => {+ for (const [p, m] of [+ ["/api/audio-tools", "POST"],+ ["/api/dub", "POST"],+ ["/api/dub/some-id/voice", "POST"],+ ["/api/dub", "GET"],+ ["/api/dub/some-id", "GET"],+ ["/api/dub/some-id", "PATCH"],+ ["/api/dub/some-id", "DELETE"],+ ] as const) {+ expect(passed(viaProxy(p, m, "a")), `${m} ${p}`).toBe(true);+ }+ for (const p of ["/api/audio-tools", "/api/dub", "/api/dub/some-id/voice"]) {+ const r = viaProxy(p, "POST", "c");+ expect(r.status, p).toBe(403);+ expect(r.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");+ expect((await r.json()).code).toBe("connect-gpu");+ }+ expect(access.ownGpuRun("POST", "/api/audio-tools")).toBe(true);+ expect(access.ownGpuRun("POST", "/api/dub/x/voice")).toBe(true);+ expect(access.ownGpuRun("GET", "/api/dub")).toBe(false);+ expect(access.accountProjectRoute("/api/dub/x")).toBe(true);+ expect(access.accountProjectRoute("/api/dub/x/voice")).toBe(false);+ });++ it("the routes refuse a guest themselves", async () => {+ expect((await toolsRoute.POST(json("/api/audio-tools", "POST", {}))).status).toBe(401);+ expect((await dubsRoute.POST(json("/api/dub", "POST", {}))).status).toBe(401);+ expect((await voiceRoute.POST(json("/api/dub/x/voice", "POST", {}), ctx("x"))).status).toBe(401);+ expect((await dubRoute.PATCH(json("/api/dub/x", "PATCH", {}), ctx("x"))).status).toBe(401);+ expect((await dubRoute.DELETE(get("/api/dub/x"), ctx("x"))).status).toBe(401);+ expect((await dubRoute.GET(get("/api/dub/x"), ctx("x"))).status).toBe(404);+ expect(await (await dubsRoute.GET(get("/api/dub"))).json()).toEqual({ items: [] });+ });+});++describe("an account runs the Audio tools on its own ComfyUI", () => {+ let clip = "";+ let split = "";+ beforeAll(async () => {+ clip = await upload("a", CLIP, "video/mp4", "scene.mp4");+ });++ it("prices a split for its own GPU, never as a demo", async () => {+ const r = await toolsRoute.POST(json("/api/audio-tools?preview=1", "POST", { tool: "split", engine: "open", media: clip, kind: "video" }, "a"));+ expect(r.status, await r.clone().text()).toBe(200);+ expect(((await r.json()) as { demo: boolean }).demo).toBe(false);+ });++ it("splits a soundtrack end to end: every step is its own, on its ComfyUI, and the stems are its own files", async () => {+ fake.log.length = 0;+ fetched.length = 0;+ const { run, done } = await ranAsOwn(await tool({ tool: "split", engine: "open", media: clip, kind: "video", name: "scene" }, "a"), a);+ split = run.result.id;+ expect(prompts()).toBe(run.items.length);+ expect(fetched.filter((u) => !u.endsWith("/system_stats"))).toEqual([]);+ const stems = done.outputs.filter((o) => o.kind === "audio");+ expect(stems.length).toBeGreaterThan(0);+ for (const o of stems) {+ expect(o.url).toMatch(/^\/api\/files\/outputs\//);+ expect((db().prepare("SELECT account_id FROM assets WHERE id = ?").get(o.assetId) as { account_id: string }).account_id).toBe(a);+ expect(passed(viaProxy(o.url, "GET", "a"))).toBe(true);+ expect(viaProxy(o.url, "GET", "b").status).toBe(403);+ }+ expect(passed(viaProxy(`/api/generations/${split}`, "GET", "a"))).toBe(true);+ expect(viaProxy(`/api/generations/${split}`, "GET", "b").status).toBe(403);+ expect(listGenerations({ features: [done.feature], account: a }).map((g) => g.id)).toContain(split);+ expect(listGenerations({ features: [done.feature], account: b })).toEqual([]);+ });++ it("cleans up dialogue, takes the dialogue out of a video and edits speech, each on its own ComfyUI", async () => {+ for (const body of [+ { tool: "clean-dialogue", engine: "open", media: clip, kind: "video", name: "scene" },+ { tool: "remove-dialogue", engine: "open", video: clip, name: "scene" },+ { tool: "speech-edit", engine: "open", media: clip, kind: "video", name: "scene", cues: [{ start: 0, end: 2, text: "Hello there" }], edited: ["Hello friend"] },+ ]) {+ fetched.length = 0;+ await ranAsOwn(await tool(body, "a"), a);+ expect(fetched.filter((u) => !u.endsWith("/system_stats")), body.tool).toEqual([]);+ }+ });++ it("keeps an exported mix as its own run, and puts it back on its own video", async () => {+ const q = new URLSearchParams({ offset: "0", last: "1", name: "scene · mix.wav" });+ const r = await exportRoute.POST(new Request(`http://localhost:3000/api/audio-tools/export?${q}`, { method: "POST", headers: { host: "localhost:3000", cookie: cookies.a, "content-type": "application/octet-stream", "content-length": String(TINY_WAV.length) }, body: new Uint8Array(TINY_WAV) }));+ expect(r.status, await r.clone().text()).toBe(201);+ const mix = (await r.json()) as { id: string; outputs: { url: string }[] };+ expect(getGeneration(mix.id)!.request.account).toBe(a);+ await ranAsOwn(await tool({ tool: "remux", engine: "open", video: clip, audio: mix.outputs[0].url, name: "scene" }, "a"), a);+ // Another account can't put A's mix on its video.+ const bClip = await upload("b", CLIP, "video/mp4", "b.mp4");+ const other = await tool({ tool: "remux", engine: "open", video: bClip, audio: mix.outputs[0].url }, "b");+ expect(other.status).toBe(403);+ expect((await other.json()).code).toBe("input-not-yours");+ });++ it("refuses another's file, the owner's file, a link, and an account with nothing to run on, before anything is made", async () => {+ const n = generationCount();+ const before = prompts();+ const theirs = await tool({ tool: "split", engine: "open", media: clip, kind: "video" }, "b");+ expect(theirs.status).toBe(403);+ expect((await theirs.json()).code).toBe("input-not-yours");+ const ownerClip = saveFile({ data: CLIP, contentType: "video/mp4", source: "upload", name: "owner.mp4" }).url;+ const owners = await tool({ tool: "remove-dialogue", engine: "open", video: ownerClip }, "a");+ expect(owners.status).toBe(403);+ expect((await tool({ tool: "split", engine: "open", media: "https://example.com/a.mp4", kind: "video" }, "a")).status).toBe(400);+ const own = runAsTenant({ kind: "account", id: c }, () => saveFile({ data: CLIP, contentType: "video/mp4", source: "upload", name: "c.mp4" }).url);+ const none = await tool({ tool: "split", engine: "open", media: own, kind: "video" }, "c");+ expect(none.status).toBe(403);+ expect(none.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");+ expect(generationCount()).toBe(n);+ expect(prompts()).toBe(before);+ });++ it("keeps the account's limits: runs going at once, and a body over a run's size", 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 (?, 'audio-split', 'oss-trim', 'open', 'comfyui', 'trim', 'audio', 'queued', ?, '[]', ?, ?)",+ );+ for (let i = 0; i < ACCOUNT_LIMITS.activeRuns; i++) add.run(`busy-${i}`, JSON.stringify({ feature: "audio-split", modelId: "oss-trim", account: a }), now, now);+ const r = await tool({ tool: "split", engine: "open", media: clip, kind: "video" }, "a");+ expect(r.status).toBe(429);+ expect((await r.json()).code).toBe(access.ACTIVE_RUNS_CODE);+ db().prepare("DELETE FROM generations WHERE id LIKE 'busy-%'").run();+ const big = new Request("http://localhost:3000/api/audio-tools", { method: "POST", headers: { host: "localhost:3000", cookie: cookies.a, "content-type": "application/json", "content-length": String(ACCOUNT_LIMITS.runBodyBytes + 1) }, body: "{}" });+ expect((await toolsRoute.POST(big)).status).toBe(413);+ });+});++describe("an account dubs a video on its own ComfyUI, and its dubs are its own", () => {+ let clip = "";+ let dub = "";+ beforeAll(async () => {+ clip = await upload("a", CLIP, "video/mp4", "talk.mp4");+ });++ it("prices a dub as its own run: the translation on its own GPU, free", async () => {+ const r = await dubsRoute.POST(json("/api/dub?preview=1", "POST", { engine: "open", mode: "steps", video: clip, targets: ["es"] }, "a"));+ expect(r.status, await r.clone().text()).toBe(200);+ const p = (await r.json()) as { demo: boolean; costUsd: number };+ expect(p.demo).toBe(false);+ expect(p.costUsd).toBe(0);+ });++ it("transcribes and translates on its own ComfyUI (never the AI helper), then voices a language end to end", async () => {+ fake.log.length = 0;+ fetched.length = 0;+ const r = await dubsRoute.POST(json("/api/dub", "POST", { engine: "open", mode: "steps", video: clip, targets: ["es"], title: "Talk" }, "a"));+ expect(r.status, await r.clone().text()).toBe(201);+ const s = (await r.json()) as { id: string; prepare: Record<string, string> };+ dub = s.id;+ // The account's own project; the owner's dub table never holds it.+ expect(store.getAccountProject(a, "dub", dub)).not.toBeNull();+ expect((db().prepare("SELECT COUNT(*) AS n FROM dub_sessions").get() as { n: number }).n).toBe(0);+ for (const id of Object.values(s.prepare)) {+ const g = getGeneration(id)!;+ expect(g.request.account).toBe(a);+ expect(g.provider).toBe("comfyui");+ expect((await settle(id))?.status, getGeneration(id)?.error ?? "").toBe("succeeded");+ }+ const translate = getGeneration(s.prepare["translate:es"])!;+ expect(translate.modelId).toBe(GPU_TRANSLATE_MODEL);+ // Its graph: the instruction names the language, and the transcript goes in as its timed lines (JSON).+ const graph = fake.log.map((e) => e.prompt).find((p) => Object.values(p ?? {}).some((n) => (n as { class_type?: string }).class_type === "TextGenerate"));+ const words = Object.values(graph ?? {}).find((n) => (n as { class_type?: string }).class_type === "StringConcatenate") as { inputs: { string_a: string; string_b: string } } | undefined;+ expect(words?.inputs.string_a).toMatch(/JSON list of subtitle lines[\s\S]*into Spanish/);+ expect(JSON.parse(words!.inputs.string_b)).toEqual([expect.objectContaining({ start: 0, end: 2, text: "Hello there" }), expect.objectContaining({ start: 2.2, end: 4, text: "How are you" })]);+ // The translator reads the transcript as its timed lines, and its answer is the lines to review.+ const view = (await (await dubRoute.GET(get(`/api/dub/${dub}`, "a"), ctx(dub))).json()) as Parameters<typeof reviewCues>[0];+ expect(reviewCues(view, "es")?.map((c) => c.text)).toEqual(["Hello there", "How are you"]);+ // Its reviewed lines are saved with its dub.+ const saved = await dubRoute.PATCH(json(`/api/dub/${dub}`, "PATCH", { lang: "es", cues: [{ start: 0, end: 2, text: "Hola" }, { start: 2.2, end: 4, text: "¿Qué tal?" }] }, "a"), ctx(dub));+ expect(saved.status, await saved.clone().text()).toBe(200);+ // The voice: every step its own, on its ComfyUI; the dubbed video is its own file.+ const v = await voiceRoute.POST(json(`/api/dub/${dub}/voice`, "POST", { lang: "es", lipsync: false }, "a"), ctx(dub));+ expect(v.status, await v.clone().text()).toBe(201);+ const voiced = (await v.json()) as { voices: Record<string, { ids: Record<string, string> }[]> };+ const ids = Object.values(voiced.voices.es[0].ids);+ for (const id of ids) {+ expect(getGeneration(id)!.request.account).toBe(a);+ expect(getGeneration(id)!.provider).toBe("comfyui");+ }+ for (const id of ids) expect((await settle(id))?.status, getGeneration(id)?.error ?? "").toBe("succeeded");+ expect(fetched.filter((u) => !u.endsWith("/system_stats"))).toEqual([]);+ const film = ids.map((id) => getGeneration(id)!).find((g) => g.outputs.some((o) => o.kind === "video"));+ expect(film?.outputs[0].url).toMatch(/^\/api\/files\/outputs\//);+ });++ it("another account and the owner never see, open, change, voice or forget it", async () => {+ const theirs = (await (await dubsRoute.GET(get("/api/dub", "b"))).json()) as { items: { id: string }[] };+ expect(theirs.items).toEqual([]);+ const mine = (await (await dubsRoute.GET(get("/api/dub", "a"))).json()) as { items: { id: string }[] };+ expect(mine.items.map((s) => s.id)).toEqual([dub]);+ expect((await dubRoute.GET(get(`/api/dub/${dub}`, "b"), ctx(dub))).status).toBe(404);+ expect((await dubRoute.PATCH(json(`/api/dub/${dub}`, "PATCH", { lang: "es", cues: [] }, "b"), ctx(dub))).status).toBe(404);+ expect((await voiceRoute.POST(json(`/api/dub/${dub}/voice`, "POST", { lang: "es" }, "b"), ctx(dub))).status).toBe(404);+ expect((await voiceRoute.POST(json(`/api/dub/${dub}/voice?preview=1`, "POST", { lang: "es" }, "b"), ctx(dub))).status).toBe(404);+ expect((await dubRoute.DELETE(get(`/api/dub/${dub}`, "b"), ctx(dub))).status).toBe(404);+ // The owner's list and the owner's reads are the owner's table only.+ expect(listDubSessions().map((s) => s.id)).not.toContain(dub);+ expect((await dubRoute.GET(get(`/api/dub/${dub}`, "owner"), ctx(dub))).status).toBe(404);+ // A's video in B's dub: refused before anything is made.+ const n = generationCount();+ const other = await dubsRoute.POST(json("/api/dub", "POST", { engine: "open", mode: "steps", video: clip, targets: ["es"] }, "b"));+ expect(other.status).toBe(403);+ expect((await other.json()).code).toBe("input-not-yours");+ expect(generationCount()).toBe(n);+ });++ it("asks an account with nothing to run on to connect its GPU, and keeps nothing", async () => {+ const own = runAsTenant({ kind: "account", id: c }, () => saveFile({ data: CLIP, contentType: "video/mp4", source: "upload", name: "c.mp4" }).url);+ const n = generationCount();+ const r = await dubsRoute.POST(json("/api/dub", "POST", { engine: "open", mode: "steps", video: own, targets: ["es"] }, "c"));+ expect(r.status).toBe(403);+ expect(r.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");+ expect(generationCount()).toBe(n);+ expect(store.listAccountProjects(c, "dub")).toEqual([]);+ });++ it("forgets its own dub, and its dubs go with the account", async () => {+ // A second dub, then the first forgotten.+ const r = await dubsRoute.POST(json("/api/dub", "POST", { engine: "open", mode: "steps", video: clip, targets: ["fr"] }, "a"));+ expect(r.status, await r.clone().text()).toBe(201);+ expect((await dubRoute.DELETE(get(`/api/dub/${dub}`, "a"), ctx(dub))).status).toBe(204);+ expect((await dubRoute.GET(get(`/api/dub/${dub}`, "a"), ctx(dub))).status).toBe(404);+ expect(store.listAccountProjects(a, "dub").length).toBe(1);+ await purgeAccount(a);+ expect(store.listAccountProjects(a, "dub")).toEqual([]);+ });+});diff --git a/tests/e2e/audio-accounts-live.mjs b/tests/e2e/audio-accounts-live.mjsnew file mode 100644index 00000000..e4295dd1--- /dev/null+++ b/tests/e2e/audio-accounts-live.mjs@@ -0,0 +1,134 @@+// The Audio tools and Translate & dub for visitors (a studio with a password and public sign-up, fuobe.com by default),+// through their routes and in a browser at a phone's and a desktop's width. A guest: the sign-up card on every run and+// change, an empty list of dubs, the price checks open, no "isn't available here" note, and the sign-up card when it+// adds a file. A signed-in account (a throwaway one this script makes and deletes): its own empty dubs, nobody else's+// dub (404), the pages' upload and run on, and the connect card when it has neither a GPU nor a key.+// No run is started (that needs the account's own GPU or key).+// Usage: node tests/e2e/audio-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(78)}${extra ? ` ${extra}` : ""}`);+ if (!ok) failures.push(label);+};++const PAGES = [+ { path: "/audio/split", name: "Split soundtrack", upload: /Upload audio or video/ },+ { path: "/video-tools/remove-dialogue", name: "Remove dialogue", upload: /Upload a video/ },+ { path: "/audio/edit-speech", name: "Edit speech", upload: /^Upload$/, label: "Runs on your own GPU · 24 GB" },+ { path: "/audio/translate", name: "Translate & dub", upload: /Upload a video/ },+];++/** 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(() => ({}));+ const dubs = await send("GET", "/api/dub");+ check(`${who}: its dubs are empty`, dubs.status() === 200 && JSON.stringify(await body(dubs)) === '{"items":[]}', String(dubs.status()));+ // A price check passes the sign-in gate (a file that isn't the asker's reads as gone: 422, never 401 or 403).+ const price = await send("POST", "/api/audio-tools?preview=1", { tool: "split", engine: "open", media: "/api/files/not-mine.wav", kind: "audio" });+ check(`${who}: Split's price check is open`, price.status() === 422, String(price.status()));+ const dubPrice = await send("POST", "/api/dub?preview=1", { engine: "open", mode: "steps", video: "/api/files/not-mine.mp4", targets: ["es"] });+ check(`${who}: a dub's price check is open`, dubPrice.status() !== 401 && dubPrice.status() !== 403, String(dubPrice.status()));+ if (who === "guest") {+ for (const [method, p] of [+ ["POST", "/api/audio-tools"],+ ["POST", "/api/dub"],+ ["POST", "/api/dub/nope/voice"],+ ["PATCH", "/api/dub/nope"],+ ["DELETE", "/api/dub/nope"],+ ]) {+ 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()));+ }+ const one = await send("GET", "/api/dub/nope");+ check("guest: a dub by id is closed", one.status() === 401, String(one.status()));+ return;+ }+ // The account reaches its routes, which answer with its own only.+ for (const [method, p, data] of [+ ["GET", "/api/dub/nope", undefined],+ ["PATCH", "/api/dub/nope", { lang: "es", cues: [] }],+ ["DELETE", "/api/dub/nope", undefined],+ ]) {+ const r = await send(method, p, data);+ check(`account: ${method} ${p} is not found`, r.status() === 404, String(r.status()));+ }+ // With neither a GPU nor a key of its own: the connect card, never "isn't available here".+ for (const [p, data] of [+ ["/api/audio-tools", { tool: "split", engine: "open", media: "/api/files/x.wav", kind: "audio" }],+ ["/api/dub", { engine: "open", mode: "steps", video: "/api/files/x.mp4", targets: ["es"] }],+ ["/api/dub/nope/voice", { lang: "es" }],+ ]) {+ const r = await send("POST", p, data);+ const j = await body(r);+ check(`account: POST ${p} asks to connect a GPU`, r.status() === 403 && j.code === "connect-gpu" && r.headers()["x-fuobe-connect-gpu"] === "1", `${r.status()} ${j.code ?? ""}`);+ }+}++const browser = await launch();+const email = `audio-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");+ const look = async (who) => {+ for (const width of [1440, 390]) {+ await page.setViewportSize({ width, height: width === 390 ? 844 : 1000 });+ for (const p of PAGES) {+ const at = `${who} ${width}: ${p.name}`;+ await page.goto(`${app}${p.path}`, { waitUntil: "load", timeout: 60_000 });+ await page.waitForTimeout(2500);+ check(`${at}: no "isn't available here" note`, (await page.getByText(/isn.t available here/).count()) === 0);+ check(`${at}: no price says "Not available here"`, (await page.getByText("Not available here").count()) === 0);+ const scroll = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);+ check(`${at}: no sideways scroll`, scroll <= 1, String(scroll));+ if (p.label) check(`${at}: its own-setup label shows`, (await page.getByText(p.label).count()) > 0);+ const upload = page.getByRole("button", { name: p.upload });+ check(`${at}: the upload is on`, (await upload.count()) > 0 && (await upload.first().isEnabled()));+ if (shots) await page.screenshot({ path: path.join(shots, `${who}-${width}-${p.path.replace(/\//g, "_")}.png`) });+ if (width !== 1440 || !(await upload.count())) continue;+ // Adding a file asks first: the sign-up card for a guest, the connect card for an account with no GPU or key.+ await upload.first().click();+ await page.waitForTimeout(1500);+ const card = who === "guest" ? /Create a free account/ : /Connect your GPU|your own files/;+ check(`${at}: the upload opens the ${who === "guest" ? "sign-up" : "connect"} card`, (await page.getByText(card).count()) > 0);+ if (shots) await page.screenshot({ path: path.join(shots, `${who}-${width}-${p.path.replace(/\//g, "_")}-card.png`) });+ await page.keyboard.press("Escape");+ await page.waitForTimeout(400);+ }+ }+ };+ await look("guest");++ // 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");+ await look("account");+ }+} 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, 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.tsindex c3bafb24..0cba55ab 100644--- a/tests/helpers/fake-comfy-runner.ts+++ b/tests/helpers/fake-comfy-runner.ts@@ -13,7 +13,8 @@* that many frames, node 3), `historyError` (/history answers HTTP 500 and then sends nothing), `uploadStatus` (the HTTP* 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).+ * `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).* This file runs under plain Node too: only erasable TypeScript.*/import http from "node:http";@@ -39,6 +40,46 @@ export interface FakeComfyOptions {text?: string;/** The history lists one video under each of these node ids instead of node 900 (a graph's declared outputs, e.g. a take and its master). */nodes?: string[];+ /**+ * The history answers for the graph that was sent: one file under each of its save nodes, as that node saves it (an+ * audio save node a WAV, SaveText the `text` words, a video combine an MP4, SaveImage a PNG, PreviewAny the words), so+ * a chain of steps (a soundtrack split into stems, its words, a mix) runs through.+ */+ graph?: boolean;+}++/** A tiny but real WAV (mono, 16-bit, 8 kHz, 0.1 s of silence). */+export const TINY_WAV: Buffer = (() => {+ const samples = 800;+ const b = Buffer.alloc(44 + samples * 2);+ b.write("RIFF", 0);+ b.writeUInt32LE(36 + samples * 2, 4);+ b.write("WAVEfmt ", 8);+ b.writeUInt32LE(16, 16);+ b.writeUInt16LE(1, 20);+ b.writeUInt16LE(1, 22);+ b.writeUInt32LE(8000, 24);+ b.writeUInt32LE(16000, 28);+ b.writeUInt16LE(2, 32);+ b.writeUInt16LE(16, 34);+ b.write("data", 36);+ b.writeUInt32LE(samples * 2, 40);+ return b;+})();++/** What a save node of the sent graph answers in the history (`graph`), by its class. */+function graphOutputs(prompt: Record<string, unknown> | undefined, text: string): Record<string, unknown> {+ const out: Record<string, unknown> = {};+ for (const [id, node] of Object.entries(prompt ?? {})) {+ const cls = String((node as { class_type?: unknown })?.class_type ?? "");+ const file = (ext: string, subfolder = "") => [{ filename: `fake_${id}_00001_.${ext}`, subfolder, type: "output" }];+ if (/^Save.*Audio|Audio.*Save|^SaveAudio/i.test(cls)) out[id] = { audio: file("wav") };+ else if (cls === "SaveText") out[id] = { text: [text], files: file("txt", "fuobe") };+ else if (cls === "PreviewAny") out[id] = { text: [text] };+ else if (/VideoCombine|^SaveVideo|^SaveWEBM|SaveAnimated/i.test(cls)) out[id] = { gifs: file("mp4") };+ else if (cls === "SaveImage") out[id] = { images: file("png") };+ }+ return out;}export interface FakeLogEntry {@@ -119,6 +160,7 @@ function uploadedBytes(body: Buffer, contentType: string): Buffer | undefined {export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<FakeComfy> {const log: FakeLogEntry[] = [];const jobs = new Map<string, number>();+ const graphs = new Map<string, Record<string, unknown> | undefined>();let lastUpload: Buffer | undefined;const server = http.createServer((req, res) => {const chunks: Buffer[] = [];@@ -161,6 +203,7 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<F}const id = opts.promptId ?? randomUUID();jobs.set(id, Date.now());+ graphs.set(id, entry.prompt);return json(200, { prompt_id: id, number: jobs.size, node_errors: {} });}if (p.startsWith("/history/")) {@@ -180,6 +223,7 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<Fif (started === undefined || Date.now() - started < (opts.delayMs ?? 0)) return json(200, {});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.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") } } } });@@ -215,6 +259,10 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<Fres.writeHead(200, { "content-type": "text/plain; charset=utf-8" });return res.end(opts.text ?? "");}+ if (name.endsWith(".wav")) {+ res.writeHead(200, { "content-type": "audio/wav" });+ return res.end(TINY_WAV);+ }if (name.endsWith(".exr")) {res.writeHead(200, { "content-type": "image/x-exr" });return res.end(Buffer.from("762f3101", "hex"));diff --git a/tests/next-steps.test.ts b/tests/next-steps.test.tsindex ec210378..b26b8f9a 100644--- a/tests/next-steps.test.ts+++ b/tests/next-steps.test.ts@@ -92,11 +92,11 @@ describe("Keep going with this", () => {expect(steps.every((s) => s.href.includes("video=%2Fapi%2Ffiles%2Fclip.mp4"))).toBe(true);});- it("splits a sounded clip's soundtrack, and offers Remove dialogue to the owner only", () => {+ it("splits a sounded clip's soundtrack, and offers Remove dialogue to everyone (an account runs it on its own GPU)", () => {const sounded = clip({ op: "lipsync", feature: "lipsync" });expect(ids(sounded)).toContain("split-soundtrack");expect(ids(sounded)).toContain("remove-dialogue");- expect(ids(sounded, { ...ALL_ADAPTERS, visitor: true })).not.toContain("remove-dialogue");+ expect(ids(sounded, { ...ALL_ADAPTERS, visitor: true })).toContain("remove-dialogue");expect(ids(sounded, { ...ALL_ADAPTERS, visitor: true })).not.toContain("restore-video");});diff --git a/tests/phone-nav.test.ts b/tests/phone-nav.test.tsindex b404c45a..4fa71052 100644--- a/tests/phone-nav.test.ts+++ b/tests/phone-nav.test.ts@@ -251,10 +251,8 @@ describe("the Studios sheet", () => {expect(words(sell)).toContain("Marketing Studio");const people = at("/", () => sheet({ group: "people" }));expect(pills(people)).toEqual(["From Reference", "Build from scratch", "From a description", "Motion transfer", "Character swap", "Object swap", "Restyle", "Insert", "From picture", "Finish"]);- // Pages that say "isn't available here" to a visitor, and the owner's own modes, aren't linked for them.- for (const w of ["Split soundtrack", "Remove dialogue"]) {- for (const g of LAUNCHER_GROUPS) expect(pills(at("/", () => sheet({ group: g.id }))), `${g.id}: ${w}`).not.toContain(w);- }+ // Split soundtrack and Remove dialogue run for visitors with an account (on their own GPU or key): linked too.+ for (const w of ["Split soundtrack", "Remove dialogue"]) expect(LAUNCHER_GROUPS.some((g) => pills(at("/", () => sheet({ group: g.id }))).includes(w)), w).toBe(true);// Cinema Studio's Blockout is linked for everyone (a guest is offered a free account on a run).const film = at("/", () => sheet({ group: "film" }));expect(pills(film)).toContain("Blockout");diff --git a/tests/public-signup-tools.test.ts b/tests/public-signup-tools.test.tsindex 9758e188..fa10549b 100644--- a/tests/public-signup-tools.test.ts+++ b/tests/public-signup-tools.test.ts@@ -110,15 +110,15 @@ describe("the proxy: PR #15's routes as main treats their kind", () => {process.env.FUOBE_PUBLIC_SIGNUP = "1";for (const p of ["/api/turnaround/estimate", "/api/turnaround?preview=1", "/api/audio-tools?preview=1"]) expect(passed(proxy(req(p, { method: "POST" }))), p).toBe(true);// Signing up wouldn't run these (an account's own GPU or key doesn't either): the account's answer, not the card.- for (const p of ["/api/audio-tools", "/api/marketing/runs", "/api/layers/l1/jobs", "/api/layout/plan"]) {+ for (const p of ["/api/marketing/runs", "/api/layers/l1/jobs", "/api/layout/plan"]) {const r = proxy(req(p, { method: "POST" }));expect(r.status, p).toBe(403);expect(r.headers.get(access.GUEST_HEADER), p).toBeNull();expect(await r.json(), p).toEqual({ error: access.OWN_GPU_TOOL_MESSAGE, code: "own-gpu-tool" });}- // The studios' runs, the tools an account runs on its own GPU (Shorts, Turnaround video, Katana), an upload and a save- // to the library: signing up is the next step there.- for (const p of ["/api/generations", "/api/shorts/sessions", "/api/turnaround", "/api/katana", "/api/media/probe", "/api/audio-tools/export?offset=0", "/api/canvases"]) {+ // The studios' runs, the tools an account runs on its own GPU (Shorts, Turnaround video, Katana, the Audio tools), an+ // upload and a save to the library: signing up is the next step there.+ for (const p of ["/api/generations", "/api/shorts/sessions", "/api/turnaround", "/api/katana", "/api/audio-tools", "/api/media/probe", "/api/audio-tools/export?offset=0", "/api/canvases"]) {const r = proxy(req(p, { method: "POST" }));expect(r.status, p).toBe(401);expect(r.headers.get(access.GUEST_HEADER), p).toBe("1");@@ -126,29 +126,29 @@ describe("the proxy: PR #15's routes as main treats their kind", () => {}});- it("gives an account the price checks, own-gpu-tool for the runs (a GPU wouldn't run them), and its own Export mix", async () => {+ it("gives an account the price checks, Connect your GPU for the Audio tools, and its own Export mix", async () => {process.env.FUOBE_PUBLIC_SIGNUP = "1";const cookie = auth.createSession(newAccount().id).value;for (const p of ["/api/turnaround/estimate", "/api/turnaround?preview=1", "/api/audio-tools?preview=1"]) expect(passed(proxy(req(p, { method: "POST", cookie }))), p).toBe(true);- for (const p of ["/api/audio-tools"]) {- const r = proxy(req(p, { method: "POST", cookie }));- expect(r.status, p).toBe(403);- expect(r.headers.get(access.CONNECT_GPU_HEADER), p).toBeNull();- expect((await r.json()).code, p).toBe("own-gpu-tool");- }+ // The Audio tools run on its own GPU or key (tests/account-audio.test.ts): with neither, it's asked to connect one.+ const tools = proxy(req("/api/audio-tools", { method: "POST", cookie }));+ expect(tools.status).toBe(403);+ expect(tools.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");+ expect((await tools.json()).code).toBe("connect-gpu");// The mix is kept as the account's own run (the route checks its room, run rate and the studio's checks), whatever the GPU.expect(passed(proxy(req("/api/audio-tools/export?offset=0", { method: "POST", cookie })))).toBe(true);});- it("runs an account's MOSS-Image on its own GPU (the studios' generations); the tools say own-gpu-tool", async () => {+ it("runs an account's MOSS-Image and the Audio tools on its own GPU; the other tools say own-gpu-tool", async () => {process.env.FUOBE_PUBLIC_SIGNUP = "1";const a = newAccount();const cookie = auth.createSession(a.id).value;auth.setAccountGpu(a.id, { url: "https://gpu.example" });expect(passed(proxy(req("/api/generations", { method: "POST", cookie })))).toBe(true);- // Turnaround video runs on its own GPU too (tests/account-video-tools.test.ts).+ // Turnaround video and the Audio tools run on its own GPU too (tests/account-video-tools.test.ts, account-audio.test.ts).expect(passed(proxy(req("/api/turnaround", { method: "POST", cookie })))).toBe(true);- for (const p of ["/api/audio-tools", "/api/layout/plan"]) {+ expect(passed(proxy(req("/api/audio-tools", { method: "POST", cookie })))).toBe(true);+ for (const p of ["/api/layout/plan"]) {const r = proxy(req(p, { method: "POST", cookie }));expect(r.status, p).toBe(403);expect(r.headers.get(access.CONNECT_GPU_HEADER), p).toBeNull();@@ -283,7 +283,7 @@ describe("the routes: a visitor's price is its own GPU's, and the owner's charac});describe("Clean up dialogue (DBS D5) on /api/audio-tools", () => {- it("prices a visitor's run on its own GPU, never a demo, only of its own file; the cloud cleaners use the install's keys, so a run is own-gpu-tool", async () => {+ it("prices a visitor's run on its own GPU, never a demo, only of its own file; a run without a GPU or key asks to connect one", async () => {process.env.FUOBE_PUBLIC_SIGNUP = "1";const who = newAccount();const cookie = auth.createSession(who.id).value;@@ -300,12 +300,12 @@ describe("Clean up dialogue (DBS D5) on /api/audio-tools", () => {expect(await owner.json()).toMatchObject({ steps: 1, demo: true });const run = proxy(req("/api/audio-tools", { method: "POST", cookie }));expect(run.status).toBe(403);- expect((await run.json()).code).toBe("own-gpu-tool");+ expect((await run.json()).code).toBe("connect-gpu");});});describe("Remove dialogue (DBS D2) on /api/audio-tools", () => {- it("prices a visitor's run on its own GPU, never a demo, and only of its own video; the run is own-gpu-tool at the proxy", async () => {+ it("prices a visitor's run on its own GPU, never a demo, and only of its own video; a run without a GPU or key asks to connect one", async () => {process.env.FUOBE_PUBLIC_SIGNUP = "1";const who = newAccount();const cookie = auth.createSession(who.id).value;@@ -323,13 +323,13 @@ describe("Remove dialogue (DBS D2) on /api/audio-tools", () => {expect(await owner.json()).toMatchObject({ steps: 2, demo: true });const run = proxy(req("/api/audio-tools", { method: "POST", cookie }));expect(run.status).toBe(403);- expect((await run.json()).code).toBe("own-gpu-tool");+ expect((await run.json()).code).toBe("connect-gpu");});});-describe("Split soundtrack's and Remove dialogue's pages tell a visitor up front (their runs are own-gpu-tool)", () => {+describe("Split soundtrack's, Remove dialogue's and Edit speech's pages are open to guests and accounts", () => {const src = (f: string) => fs.readFileSync(path.join(__dirname, "..", f), "utf8");- it("read 'Not available here', not 'Free', to a guest or an account", async () => {+ it("still say 'Not available here' only where a price function is asked to", async () => {const { openToolPrice } = await import("@/lib/av/split");expect(openToolPrice({ demo: false })).toBe("Free");expect(openToolPrice({ demo: true })).toBe("Placeholder · free");@@ -337,27 +337,23 @@ describe("Split soundtrack's and Remove dialogue's pages tell a visitor up frontfor (const p of [{ demo: false }, { demo: true }, undefined]) expect(openToolPrice(p, true)).toBe("Not available here");});- it("say it runs on a self-hosted Fuobe, and turn off the upload, the library pick and the run (as Remove object does)", () => {- for (const [file, tool] of [- ["src/components/audio-tools/split-tool.tsx", "Split soundtrack"],- ["src/components/audio-tools/remove-dialogue-tool.tsx", "Remove dialogue"],- // Edit speech's run is POST /api/audio-tools too (own-gpu-tool); its price line shows the blocker first.- ["src/components/audio-tools/speech-edit-tool.tsx", "Edit speech"],- ] as const) {+ it("carry no 'isn't available here' note, and ask a guest to sign up (an account to connect its GPU) before an upload", () => {+ for (const file of ["src/components/audio-tools/split-tool.tsx", "src/components/audio-tools/remove-dialogue-tool.tsx", "src/components/audio-tools/speech-edit-tool.tsx", "src/components/dub/dub-studio.tsx"]) {const page = src(file).replace(/\s+/g, " ");- expect(page).toContain("const visitor = useLikelyVisitor();");- expect(page).toContain(`const SELF_HOSTED = "${tool} isn't available here";`);- expect(page).toMatch(/blocker = visitor \? SELF_HOSTED/);- expect(page).toMatch(/\{visitor && (\( ?)?<SelfHostNote className="mt-3 max-w-xl">\{SELF_HOSTED\}\.<\/SelfHostNote> ?\)?\}/);- expect(page).toMatch(/<ToolShell title="[^"]+" selfHostedOnly>/);- expect(page).toMatch(/onUpdate=\{setSource\} disabled=\{visitor\}/);- // The upload button, From library, the hidden file input and the drop all honour it.- expect(page.match(/disabled=\{disabled\}/g)?.length).toBe(3);- expect(page).toMatch(/if \(!f \|\| disabled \|\| askFirst\(\)\) return;/);- expect(page).toMatch(/open=\{picking && !disabled\}/);- expect(page).toMatch(/disabled=\{(busy \|\| visitor|visitor \|\| run\.isPending)/);- if (tool !== "Edit speech") expect(page).toContain("openToolPrice(p, true)");+ expect(page, file).not.toContain("SelfHostNote");+ expect(page, file).not.toContain("useLikelyVisitor");+ expect(page, file).not.toContain("selfHostedOnly");+ expect(page, file).not.toMatch(/isn('|')t available here/);+ expect(page, file).not.toContain("openToolPrice(p, true)");+ }+ for (const file of ["src/components/audio-tools/split-tool.tsx", "src/components/audio-tools/remove-dialogue-tool.tsx", "src/components/audio-tools/speech-edit-tool.tsx"]) {+ expect(src(file).replace(/\s+/g, " "), file).toMatch(/if \(!f \|\| disabled \|\| askFirst\(\)\) return;/);}+ // Edit speech needs its own GPU (AuK, 24 GB): its own-setup label, and its runs ask for the GPU first.+ const speech = src("src/components/audio-tools/speech-edit-tool.tsx").replace(/\s+/g, " ");+ expect(speech).toContain('const OWN_SETUP = "audio:edit-speech";');+ expect(speech).toContain("useAskBeforeUpload({ gpuOnly: true })");+ expect(speech.match(/press\(OWN_SETUP\)/g)?.length).toBe(2);});});diff --git a/tests/regenerate-offered.test.ts b/tests/regenerate-offered.test.tsindex e3a2228c..e2b351f3 100644--- a/tests/regenerate-offered.test.ts+++ b/tests/regenerate-offered.test.ts@@ -79,25 +79,26 @@ describe("Regenerate while it is switched off", () => {});describe("tools a guest or an account can't open", () => {- it("leaves Restore & colourise and Remove dialogue out of a visitor's result menus, and keeps them for the owner", () => {+ it("leaves Restore & colourise out of a visitor's result menus, keeps it for the owner, and offers Remove dialogue to both", () => {const owner = ids(gen());expect(owner).toContain("restore-video");const visitor = ids(gen(), { visitor: true });expect(visitor).not.toContain("restore-video");- expect(visitor).not.toContain("remove-dialogue");+ // An account runs Remove dialogue on its own GPU (tests/account-audio.test.ts).+ expect(visitor).toContain("remove-dialogue");expect(ids(upload(), { visitor: true })).not.toContain("restore-video");});- it("leaves Clean up dialogue out of a visitor's result menus and keeps it for the owner; Remove a person is everyone's", () => {+ it("offers Remove a person and Clean up dialogue in a visitor's result menus, as the owner's", () => {// An uploaded clip gets both (a clip with sound).expect(ids(upload())).toEqual(expect.arrayContaining(["remove-person", "clean-dialogue"]));const visitor = ids(upload(), { visitor: true });- // An account runs Remove a person on its own GPU (tests/account-video-tools.test.ts); a guest signs up there.+ // An account runs both on its own GPU (tests/account-video-tools.test.ts, account-audio.test.ts); a guest signs up there.expect(visitor).toContain("remove-person");- expect(visitor).not.toContain("clean-dialogue");+ expect(visitor).toContain("clean-dialogue");});- it("leaves Restore & colourise's Video tools tab out for a visitor; Remove a person's tab is everyone's", () => {+ it("leaves Restore & colourise's Video tools tab out for a visitor; Remove a person's and Remove dialogue's tabs are everyone's", () => {const tabs = Object.fromEntries(HUB_MODES["video-tools"].map((m) => [m.id, m.ownerOnly ?? false]));expect(tabs).toMatchObject({ restore: true, "remove-person": false, "remove-dialogue": false, matte: false, evolution: false, "remove-object": false });});diff --git a/tests/speech-edit-server.test.ts b/tests/speech-edit-server.test.tsindex 7677cfc3..6d2ee23a 100644--- a/tests/speech-edit-server.test.ts+++ b/tests/speech-edit-server.test.ts@@ -128,16 +128,16 @@ describe("public sign-up", () => {let n = 0;const newAccount = () => auth.createAccount(`speech${++n}@example.com`, "long enough");- it("prices a visitor's edit on its own GPU, never a demo, and only of its own file; the run is own-gpu-tool for an account", async () => {+ it("prices a visitor's edit on its own GPU, never a demo, and only of its own file; an account without a GPU is asked to connect one", async () => {process.env.FUOBE_PUBLIC_SIGNUP = "1";auth.setPassword("install password");const who = newAccount();const cookie = auth.createSession(who.id).value;- // Through the sign-in proxy: the price check passes, the run is refused as a tool (it would use the studio's GPU).+ // Through the sign-in proxy: the price check passes; the run goes to its own GPU, and with none it's asked to connect one.expect(passed(proxy(req("/api/audio-tools?preview=1", cookie)))).toBe(true);const run = proxy(req("/api/audio-tools", cookie));expect(run.status).toBe(403);- expect((await run.json()).code).toBe("own-gpu-tool");+ expect((await run.json()).code).toBe("connect-gpu");// The owner's file answers a guest and an account as one that's gone.const owners = wav("owners.wav");for (const c of [undefined, cookie]) {@@ -185,9 +185,9 @@ describe("where Edit speech shows up", () => {expect(has(outputActions(g("music", "audio"), 0))).toBeUndefined();expect(has(outputActions(g("tts", "audio"), 0, { engineMode: "cloud" }))).toBeUndefined();expect(has(outputActions(g("lipsync", "video"), 0))?.href).toMatch(/^\/audio\/edit-speech\?video=/);- // A guest or an account (public sign-up) can't run it: the edit runs on a self-hosted Fuobe only.- expect(has(outputActions(g("tts", "audio"), 0, { visitor: true }))).toBeUndefined();- expect(has(outputActions(g("lipsync", "video"), 0, { visitor: true }))).toBeUndefined();+ // A guest or an account (public sign-up) gets it too: an account runs it on its own GPU.+ expect(has(outputActions(g("tts", "audio"), 0, { visitor: true }))?.href).toMatch(/^\/audio\/edit-speech\?audio=/);+ expect(has(outputActions(g("lipsync", "video"), 0, { visitor: true }))?.href).toMatch(/^\/audio\/edit-speech\?video=/);});it("has its model, licence and a row on the GPU pre-flight board", () => {