Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Assist studios: a dub that can't review dubs in one go (or says why); ads only reuse Assist's own kits

Claude6b779c089e7c
diff --git a/src/components/assist/transcript.tsx b/src/components/assist/transcript.tsx
index 26eb6266..3cd9229a 100644
--- a/src/components/assist/transcript.tsx
+++ b/src/components/assist/transcript.tsx
@@ -132,8 +132,8 @@ export function ApprovalCard({ item, live, onAnswer }: { item: Extract<AssistIte
<AppWindow className="mt-0.5 size-3.5 shrink-0" /> Opens in {item.opens.join(" and ")}, where you can keep working on it
</p>
) : null}
- {item.notes?.map((n) => (
- <p key={n} className="flex items-start gap-1.5">
+ {item.notes?.map((n, k) => (
+ <p key={k} className="flex items-start gap-1.5">
<Info className="mt-0.5 size-3.5 shrink-0" /> {n}
</p>
))}
diff --git a/src/lib/av/captions.ts b/src/lib/av/captions.ts
index af5d5833..51703ecf 100644
--- a/src/lib/av/captions.ts
+++ b/src/lib/av/captions.ts
@@ -127,11 +127,14 @@ export function lookFor(route: BurnRoute, look: CaptionLook): CaptionLook {
/** VEED's dynamic presets bill twice the basic rate. */
const VEED_DYNAMIC = new Set(["glass", "whisper", "glide2", "fusion", "glide", "terminal", "handwritten", "backdrop", "backdrop2"]);
-/** The burn's price per minute of video (USD), for the route's note; 0 on the open engine. */
-export function burnPricePerMinute(route: BurnRoute, style: string): number {
+/** VEED's translated subtitles add this per minute (its catalog note: "translation +$0.20/min"). */
+const VEED_TRANSLATION = 0.2;
+
+/** The burn's price per minute of video (USD), for the route's note; 0 on the open engine. `translated`: VEED also translates. */
+export function burnPricePerMinute(route: BurnRoute, style: string, translated = false): number {
if (route === "open") return 0;
if (route === "auto") return 0.03;
- return VEED_DYNAMIC.has(styleById(style).veed) ? 0.2 : 0.1;
+ return (VEED_DYNAMIC.has(styleById(style).veed) ? 0.2 : 0.1) + (translated ? VEED_TRANSLATION : 0);
}
/** What the style controls mean on this burner, in one line. */
diff --git a/src/lib/catalog/marketing.ts b/src/lib/catalog/marketing.ts
index 98880d94..1aa0df8c 100644
--- a/src/lib/catalog/marketing.ts
+++ b/src/lib/catalog/marketing.ts
@@ -65,6 +65,8 @@ export interface BrandKit extends BrandKitFields {
note?: string | null;
error?: string | null;
source: "website" | "manual";
+ /** "assist": made by Fuobe Assist from an ad brief (create_ads without a brand kit); Assist only reuses these. */
+ origin?: "assist";
productCount?: number;
/** Ads made for this brand (Ads Studio shelf). */
adCount?: number;
diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.ts
index a2d43f3a..30e581d4 100644
--- a/src/server/assist/agent.ts
+++ b/src/server/assist/agent.ts
@@ -939,7 +939,8 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {
const total = plans.some((p) => p.total === null) ? null : plans.reduce((n, p) => n + (p.total ?? 0), 0);
const summary = [...new Set(gated.map((g) => cardTitle(g.name, g.input)))].join(" · ");
const opens = [...new Set(plans.flatMap((p) => (p.studio ? [p.studio] : [])))];
- const notes = plans.flatMap((p) => (p.fallback ? [`${p.fallback}.`] : []));
+ // Two calls that fall back for the same reason say it once.
+ const notes = [...new Set(plans.flatMap((p) => (p.fallback ? [`${p.fallback}.`] : [])))];
const item = push(s, { role: "approval", summary, jobs, totalUsd: total, status: "pending", ...(opens.length && { opens }), ...(notes.length && { notes }) });
offlineNote();
s.pending = { approvalItemId: item.id, results, gated, order };
diff --git a/src/server/assist/studio-routes.ts b/src/server/assist/studio-routes.ts
index 474ed169..26e960bc 100644
--- a/src/server/assist/studio-routes.ts
+++ b/src/server/assist/studio-routes.ts
@@ -3,8 +3,9 @@ import fs from "node:fs";
import type { PlannedJob } from "@/lib/assist";
import { dubLanguageFor, facelessStyleFor, shortsPresetFor } from "@/lib/assist-studios";
import { BURN_MODELS, burnPricePerMinute, burnRequest, CAPTIONS_FEATURE, lookFor, OPEN_FONT_SIZE, styleById, transcribeRequest, type BurnRoute, type CaptionLook } from "@/lib/av/captions";
-import { DUB_STEP_MODELS, translateKey, type OneShotModel } from "@/lib/av/dub";
+import { DUB_STEP_MODELS, prepareSteps, translateKey, type OneShotModel } from "@/lib/av/dub";
import { getModel } from "@/lib/catalog";
+import { routesFor } from "@/lib/catalog/plan";
import { defaultSettings, genreInfo, PART_LABELS, type EpisodeAspect, type EpisodeSettings, type NarratorVoice, type StepPart } from "@/lib/catalog/faceless";
import { AD_RATIOS, emptyKit, type AdRatio, type BrandKit, type Product } from "@/lib/catalog/marketing";
import { lookFromPreset, SHORTS, SHORTS_MODELS, type ShortsLook } from "@/lib/catalog/shorts";
@@ -14,9 +15,10 @@ import { imageSize } from "@/lib/image-size";
import { clampLayers, decomposeCost, defaultLayers, TOOL_MODELS, TOOL_LABELS, type LayerJobInput } from "@/lib/layers";
import { createBatch, estimateBatch, listCreatives, type BatchInput } from "../ads";
import { createManualBrand, createProduct, DuplicateProductError, getBrand, getProduct, heuristicManualKit, listProducts, updateProduct } from "../brand";
-import { createPipeline, type PipelineStep } from "../chains";
+import { createPipeline, providerNames, type PipelineStep } from "../chains";
import { createDubSession, previewDub, videoLength, type CreateDubInput } from "../dub";
import { createChannel, createEpisode, estimateEpisode, listChannels } from "../faceless";
+import { chooseRoute } from "../generations";
import { createProject, deleteProject, FileUrl, jobSteps, startJob } from "../layers";
import { engineMode } from "../settings";
import { createSession, estimateWith, sourceInfo, type ShortsBody, type SourceInfo } from "../shorts";
@@ -240,7 +242,30 @@ const shortsRoute: StudioRoute<RestyleToolInput> = {
const ONE_SHOT_NAMES: Record<OneShotModel, string> = { "heygen-translate": "HeyGen Translate", "heygen-translate-fast": "HeyGen Translate Speed", "elevenlabs-dubbing": "ElevenLabs Dubbing" };
-function dubJob(i: DubToolInput, ctx: ToolContext): Checked<{ input: CreateDubInput; names: string[] }> {
+/**
+ * Why the review flow's first stage (voice, transcript, translations) can't start as one pipeline, or
+ * null: a step no provider can run, or a demo step among real ones, which createPipeline refuses (a
+ * fal key without Claude or Ollama: the translation would be a demo while the rest runs for real).
+ */
+function prepareProblem(input: Pick<CreateDubInput, "engine" | "video" | "source" | "targets">): string | null {
+ const modes: { label: string; needs: string; demo: boolean }[] = [];
+ for (const s of prepareSteps({ engine: input.engine, video: input.video, source: input.source, targets: input.targets })) {
+ const m = getModel(s.request.modelId);
+ if (!m || !s.request.op) continue;
+ const label = s.request.step?.label ?? s.key;
+ const needs = providerNames(m, s.request.op);
+ try {
+ modes.push({ label, needs, demo: chooseRoute(routesFor(m, s.request.op)).demo });
+ } catch {
+ return `${label} needs ${needs}`;
+ }
+ }
+ const demo = modes.find((x) => x.demo);
+ return demo && modes.some((x) => !x.demo) ? `${demo.label} would run as a demo (it needs ${demo.needs}) while the other steps run for real` : null;
+}
+
+/** `blocked`: the studio takes the call but can't start it (shown on the card, thrown on run); `notes` go on the card. */
+function dubJob(i: DubToolInput, ctx: ToolContext): Checked<{ input: CreateDubInput; names: string[]; notes: string[]; blocked?: string }> {
const engine = engineOf(ctx);
if (!i.video.startsWith("/api/files/")) return { problem: "Translate & dub works on videos saved in Fuobe (an upload or a result)" };
const asked = [...new Set(i.languages.map((l) => l.trim()).filter(Boolean))].slice(0, 4);
@@ -248,24 +273,41 @@ function dubJob(i: DubToolInput, ctx: ToolContext): Checked<{ input: CreateDubIn
const langs = asked.map((l) => ({ asked: l, lang: dubLanguageFor(l) }));
const unknown = langs.find((l) => !l.lang);
if (unknown) return { problem: `Translate & dub doesn't list ${unknown.asked}` };
- const review = i.review !== false;
- if (!review && engine === "open") return { problem: "Dubbing in one go is a cloud service; on the open engine Translate & dub reviews the lines first" };
- const model: OneShotModel | undefined = review ? undefined : i.lipsync === false ? "elevenlabs-dubbing" : "heygen-translate";
- const input: CreateDubInput = {
+ if (i.review === false && engine === "open") return { problem: "Dubbing in one go is a cloud service; on the open engine Translate & dub reviews the lines first" };
+ const oneShot: OneShotModel = i.lipsync === false ? "elevenlabs-dubbing" : "heygen-translate";
+ const base = {
engine,
- mode: review ? "steps" : "oneshot",
video: i.video,
title: fileTitle(i.video),
source: (i.source_language && dubLanguageFor(i.source_language)?.code) || "auto",
targets: [...new Set(langs.map((l) => l.lang!.code))],
- ...(model && { model }),
};
- try {
- previewDub(input);
- } catch (e) {
- return { problem: (e as Error).message };
+ const steps: CreateDubInput = { ...base, mode: "steps" };
+ const once: CreateDubInput = { ...base, mode: "oneshot", model: oneShot };
+ const names = langs.map((l) => l.lang!.name);
+ const priced = (input: CreateDubInput): string | null => {
+ try {
+ previewDub(input);
+ return null;
+ } catch (e) {
+ return (e as Error).message;
+ }
+ };
+ if (i.review === false) {
+ const problem = priced(once);
+ return problem ? { problem } : { input: once, names, notes: [] };
}
- return { input, names: langs.map((l) => l.lang!.name) };
+ const problem = priced(steps);
+ if (problem) return { problem };
+ // The review flow needs its first stage to run all for real (or all as a demo). When it can't and the
+ // review wasn't asked for outright, the cloud dubs in one go instead, still as a dub in the studio.
+ const why = prepareProblem(steps);
+ if (!why) return { input: steps, names, notes: [] };
+ const stuck = `Reviewing the lines can't start: ${why}`;
+ if (engine === "cloud" && i.review === undefined && !priced(once)) {
+ return { input: once, names, notes: [`${stuck} — so it dubs in one go with ${ONE_SHOT_NAMES[oneShot]} (connect it in Settings to review every line first)`] };
+ }
+ return { input: steps, names, notes: [], blocked: `${stuck} — connect it in Settings${engine === "cloud" ? ", or dub in one go (review: false)" : ", or turn on demo mode to try it all as a demo"}` };
}
const dubRoute: StudioRoute<DubToolInput> = {
@@ -273,10 +315,13 @@ const dubRoute: StudioRoute<DubToolInput> = {
page: modeHref("audio", "translate"),
refuse: (i, ctx) => problemOf(dubJob(i, ctx)),
plan: (i, ctx) => {
- const { input, names } = ok(dubJob(i, ctx));
+ const { input, names, notes, blocked } = ok(dubJob(i, ctx));
const price = previewDub(input);
const oneshot = input.mode === "oneshot";
const extra = price.unpriced.length ? ` · plus ${price.unpriced.join(" and ")} at the provider's own rate` : "";
+ const note = oneshot
+ ? `Dubbed in one go${input.model === "elevenlabs-dubbing" ? ", no lip re-sync" : ", lip-synced"}${extra}`
+ : `Transcribe and translate (${price.steps} steps)${extra} · then review every line and voice it in Translate & dub, priced there`;
const job: PlannedJob = {
tool: "dub_video",
modelId: input.model ?? DUB_STEP_MODELS[input.engine].translate,
@@ -287,15 +332,15 @@ const dubRoute: StudioRoute<DubToolInput> = {
count: input.targets.length,
costUsd: price.costUsd,
demo: price.demo,
- note: oneshot
- ? `Dubbed in one go${input.model === "elevenlabs-dubbing" ? ", no lip re-sync" : ", lip-synced"}${extra}`
- : `Transcribe and translate (${price.steps} steps)${extra} · then review every line and voice it in Translate & dub, priced there`,
+ note: [note, ...notes].join(" · "),
atomic: true,
+ ...(blocked && { error: blocked }),
};
return [job];
},
async run(i, ctx) {
- const { input } = ok(dubJob(i, ctx));
+ const { input, notes, blocked } = ok(dubJob(i, ctx));
+ if (blocked) throw new Error(blocked);
const s = createDubSession(input);
const steps = s.mode === "steps";
const ids = steps ? s.targets.map((c) => s.prepare?.[translateKey(c)]).filter((x): x is string => !!x) : Object.values(s.oneshot ?? {});
@@ -304,6 +349,8 @@ const dubRoute: StudioRoute<DubToolInput> = {
href: modeHref("audio", "translate", { dub: s.id }),
info: {
dub: s.id,
+ // Why it dubs in one go when the review was the default (tell the user).
+ ...(notes.length && { changed: notes.join(" ") }),
...(steps && {
next: `Once the translation is ready, the user reviews every line in Translate & dub and presses Voice${i.lipsync === false ? " (with Lip sync switched off)" : ""}; the dubbed video is made then.`,
}),
@@ -447,8 +494,9 @@ function adsJob(i: AdsToolInput, ctx: ToolContext): Checked<{ input: BatchInput;
const input: BatchInput = {
brandId: kit?.id ?? "draft",
engine,
- // Several formats need Fuobe's compositor (every ad in 1:1, 4:5 and 9:16); Higgsfield renders one format per ad.
- ...(ratios.length > 1 && { route: "fuobe" as const }),
+ // Several formats, or words to use as given, need Fuobe's compositor (every ad in 1:1, 4:5 and 9:16, its
+ // headline and call to action editable); Higgsfield renders one format per ad and writes its own copy into the picture.
+ ...((ratios.length > 1 || !!i.headline?.trim() || !!i.cta?.trim()) && { route: "fuobe" as const }),
items: [{ productId: draftProduct.id, count: Math.max(1, Math.min(8, i.count ?? 4)) }],
direction,
ratio: ratios[0] as AdRatio,
@@ -461,15 +509,24 @@ function adsJob(i: AdsToolInput, ctx: ToolContext): Checked<{ input: BatchInput;
return { input, brand: kit, product, draft: { brand: draftBrand, product: draftProduct }, name };
}
-/** The product the ads are for: the one named, else one made from the brief (a product of the same name gets the new photo). */
-function adsProduct(brandId: string, name: string, i: AdsToolInput): Product {
+const sameName = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase();
+
+/**
+ * The product the ads are for, made from the brief. A product of the same name already in the kit is
+ * used: in a kit Assist made, a new photo becomes its first; the user's own products are never changed
+ * (a new photo makes a second product of that name, as Ads Studio's "Create anyway" does).
+ */
+function adsProduct(brand: BrandKit, name: string, i: AdsToolInput): Product {
const images = i.product_image ? [i.product_image] : [];
try {
- return createProduct({ name, brandId, description: i.brief, images });
+ return createProduct({ name, brandId: brand.id, description: i.brief, images });
} catch (e) {
if (!(e instanceof DuplicateProductError)) throw e;
- const same = listProducts(brandId).find((p) => p.name.toLowerCase() === name.toLowerCase())!;
- return images.length ? (updateProduct(same.id, { images: [...images, ...same.images.filter((u) => !images.includes(u))] }) ?? same) : same;
+ const same = listProducts(brand.id).filter((p) => sameName(p.name, name));
+ const fits = same.find((p) => !images.length || p.images[0] === images[0]);
+ if (fits) return fits;
+ if (brand.origin === "assist" && same[0]) return updateProduct(same[0].id, { images: [...images, ...same[0].images.filter((u) => !images.includes(u))] }) ?? same[0];
+ return createProduct({ name, brandId: brand.id, description: i.brief, images }, { force: true });
}
}
@@ -501,10 +558,16 @@ const adsRoute: StudioRoute<AdsToolInput> = {
async run(i, ctx) {
const job = ok(adsJob(i, ctx));
// A brief without a brand kit gets one of its own, the way Ads Studio's "Describe your business" makes
- // it; the same product asked for again goes back to the kit it's in.
- const again = job.brand ? null : listProducts().find((p) => p.brandId && p.name.toLowerCase() === job.name.toLowerCase());
- const brand = job.brand ?? (again ? getBrand(again.brandId!) : null) ?? (await createManualBrand({ description: i.brief }));
- const product = job.product ?? adsProduct(brand.id, job.name, i);
+ // it (marked as Assist's); the same product asked for again goes back to that kit. The user's own
+ // kits are only used when named (brand_id).
+ const again = job.brand
+ ? null
+ : listProducts()
+ .filter((p) => p.brandId && sameName(p.name, job.name))
+ .map((p) => getBrand(p.brandId!))
+ .find((b): b is BrandKit => b?.origin === "assist" && b.status === "ready");
+ const brand = job.brand ?? again ?? (await createManualBrand({ description: i.brief, origin: "assist" }));
+ const product = job.product ?? adsProduct(brand, job.name, i);
const { batchId, run } = createBatch({ ...job.input, brandId: brand.id, items: [{ productId: product.id, count: job.input.items[0].count }] }, { headline: i.headline, cta: i.cta });
// The copy is written first (one LLM call), then each ad's picture starts: wait for that, not for the pictures.
let timer: ReturnType<typeof setTimeout> | undefined;
@@ -515,6 +578,8 @@ const adsRoute: StudioRoute<AdsToolInput> = {
href: `/ads/${brand.id}`,
info: {
brand: brand.id,
+ // The kit's name, to tell the user where the ads are (a kit made from the brief is named by it).
+ brandName: brand.name,
product: product.id,
batch: batchId,
ads: ads.map((c) => ({ headline: c.headline, cta: c.cta, status: c.status })),
@@ -592,8 +657,8 @@ const captionsRoute: StudioRoute<CaptionsToolInput> = {
refuse: (i, ctx) => problemOf(captionsJob(i, ctx)),
plan: (i, ctx) => {
const { steps, route, seconds } = ok(captionsJob(i, ctx));
- // The burn at the studio's own rate per minute (VEED's dynamic styles cost double).
- const burn = seconds && route !== "open" ? Math.round(burnPricePerMinute(route, CAPTION_LOOK.style) * (seconds / 60) * 1000) / 1000 : null;
+ // The burn at the studio's own rate per minute (VEED's dynamic styles cost double), plus VEED's translation when it translates.
+ const burn = seconds && route !== "open" ? Math.round(burnPricePerMinute(route, CAPTION_LOOK.style, route === "veed" && !!i.translate_to) * (seconds / 60) * 1000) / 1000 : null;
return planSteps("add_captions", steps).map((j) => (j.op === "captions" && burn !== null && !j.demo && !j.error ? { ...j, costUsd: burn } : j));
},
async run(i, ctx) {
diff --git a/src/server/assist/studio-tools.ts b/src/server/assist/studio-tools.ts
index 308464ba..1cc821e7 100644
--- a/src/server/assist/studio-tools.ts
+++ b/src/server/assist/studio-tools.ts
@@ -5,7 +5,9 @@ import type { PlannedJob } from "@/lib/assist";
import { getModel } from "@/lib/catalog";
import { routesFor } from "@/lib/catalog/plan";
import { FACELESS_STYLE_IDS, STYLES } from "@/lib/catalog/faceless";
+import { SHORTS_MODELS } from "@/lib/catalog/shorts";
import type { ChainSlot, Engine, GenerationRequest, Operation } from "@/lib/catalog/types";
+import { TOOL_MODELS } from "@/lib/layers";
import { createPipeline, type PipelineStep } from "../chains";
import { db } from "../db";
import { chooseRoute, createGenerations, outputKind, previewChained } from "../generations";
@@ -54,13 +56,23 @@ const LayersInput = z.object({
image: ref.describe("The image to split."),
layers: z.number().int().optional().describe("How many layers (2–8; the Layers studio starts at 8, Seedream decides how many it returns)."),
focus: z.string().optional().describe("What to separate, e.g. 'the person, the product, the headline text, the background'."),
- model_id: z.string().optional().describe("A layers model from search_models (task layers); default: the engine's best."),
+ model_id: z
+ .string()
+ .optional()
+ .describe(
+ `Layers' decomposition models: ${TOOL_MODELS.decompose.cloud.join(", ")} (cloud), ${TOOL_MODELS.decompose.open.join(", ")} (open source); default: the engine's first. Another model runs outside Layers, as a plain job in the Library.`,
+ ),
});
const RestyleInput = z.object({
video: ref.describe("The footage to restyle."),
style: z.string().describe("The new look, e.g. 'claymation, warm studio light' or 'anime, cel shading'."),
references: z.array(ref).optional().describe("Up to 4 style reference images."),
- model_id: z.string().optional().describe("A video-to-video model from search_models (task v2v)."),
+ model_id: z
+ .string()
+ .optional()
+ .describe(
+ `Shorts Studio's restyle models: ${SHORTS_MODELS.cloud.join(", ")} (cloud), ${SHORTS_MODELS.open.join(", ")} (open source); default: the engine's first. Another video-to-video model runs outside Shorts Studio, as a single job in the Library.`,
+ ),
});
const DubInput = z.object({
video: ref.describe("The video to dub."),
@@ -101,7 +113,10 @@ const AdsInput = z.object({
brief: z.string().describe("What the ads sell and to whom, with the offer or angle."),
product_image: ref.optional().describe("The product photo (keeps the real product in every ad)."),
count: z.number().int().optional().describe("How many different ads (1–8, default 4)."),
- aspect_ratios: z.array(z.string()).optional().describe("Formats for each ad: 1:1, 4:5 (default), 9:16, 16:9."),
+ aspect_ratios: z
+ .array(z.string())
+ .optional()
+ .describe("Ads Studio's formats: 1:1, 4:5 (default), 9:16 — there every ad comes in all three. 16:9 runs outside Ads Studio, as plain images in the Library."),
headline: z.string().optional().describe("A headline to use exactly; otherwise each ad gets its own."),
cta: z.string().optional().describe("Call to action, e.g. 'Shop now'."),
brand_id: z.string().optional().describe("A brand kit id from the Ads studio, when the user has one."),
@@ -548,7 +563,7 @@ const facelessEpisode = defineTool({
const createAds = defineTool({
name: "create_ads",
description:
- "Make a batch of different ad creatives (1–8) for a product: varied angles and layouts with a headline, body, call to action and the real product from its photo — a batch in Fuobe's Ads Studio, where every ad comes in 1:1, 4:5 and 9:16 with the brand's logo, colours and fonts, editable and downloadable. Without brand_id the ads go to a brand kit called “Assist”. Use it for 'ads for my product', 'a set of Meta ads', 'creatives to test'. Gated by the same approval card as generate.",
+ "Make a batch of different ad creatives (1–8) for a product: varied angles and layouts with a headline, body, call to action and the real product from its photo — a batch in Fuobe's Ads Studio, where every ad comes in 1:1, 4:5 and 9:16 with the brand's logo, colours and fonts, editable and downloadable. Without brand_id, a brand kit is made from the brief (as Ads Studio's “Describe your business” does, named after the business it describes) with a product named from the brief's first words; a later brief for a product of the same name goes back to that kit. The user's own kits are only used when you pass brand_id (and product_id), from the Ads studio. Use it for 'ads for my product', 'a set of Meta ads', 'creatives to test'. Gated by the same approval card as generate.",
schema: AdsInput,
gated: true,
title: (i) => `${Math.max(1, Math.min(8, i.count ?? 4))} ads: ${i.brief.slice(0, 50)}`,
diff --git a/src/server/brand.ts b/src/server/brand.ts
index 538c582c..dd530131 100644
--- a/src/server/brand.ts
+++ b/src/server/brand.ts
@@ -814,6 +814,7 @@ interface BrandRow {
interface StoredKit extends BrandKitFields {
source?: "website" | "manual";
+ origin?: "assist";
note?: string | null;
error?: string | null;
}
@@ -1118,8 +1119,8 @@ export function sellingPointsFrom(description: string | undefined): string[] {
.slice(0, 3);
}
-/** A manual kit from a description ("Describe your business") and optional product photos. */
-export async function createManualBrand(input: { description: string; name?: string; images?: string[]; colors?: string[] }): Promise<BrandKit> {
+/** A manual kit from a description ("Describe your business") and optional product photos. `origin`: who made it (Assist). */
+export async function createManualBrand(input: { description: string; name?: string; images?: string[]; colors?: string[]; origin?: "assist" }): Promise<BrandKit> {
const description = input.description.trim();
if (!description && !input.images?.length) throw new Error("Add a description or upload images");
const llm = description ? softFieldsFrom(parseJsonObject(await llmText(MANUAL_SYSTEM, `Business: ${description}`))) : {};
@@ -1130,6 +1131,7 @@ export async function createManualBrand(input: { description: string; name?: str
colors: colors.length ? colors : llm.colors?.length ? llm.colors : (heur.colors ?? []),
fonts: { heading: llm.fonts?.heading ?? heur.fonts?.heading, body: llm.fonts?.body ?? heur.fonts?.body },
source: "manual",
+ ...(input.origin && { origin: input.origin }),
};
const id = nanoid(10);
const now = Date.now();
diff --git a/src/server/chains.ts b/src/server/chains.ts
index a35776e4..e1ca4715 100644
--- a/src/server/chains.ts
+++ b/src/server/chains.ts
@@ -23,7 +23,8 @@ interface ModeStep {
op: Operation;
}
-const providerNames = (m: ModelDef, op: Operation) => [...new Set(routesFor(m, op).map((r) => (r.provider === "llm" ? "Claude or Ollama" : provider(r.provider).label)))].join(" or ");
+/** Who can run a model's operation, as Settings names them ("fal.ai", "Claude or Ollama"). */
+export const providerNames = (m: ModelDef, op: Operation) => [...new Set(routesFor(m, op).map((r) => (r.provider === "llm" ? "Claude or Ollama" : provider(r.provider).label)))].join(" or ");
/**
* A chain must not mix paid and demo steps: a demo join of paid clips (or a paid step fed a demo
diff --git a/src/server/dub.ts b/src/server/dub.ts
index 24127349..3aa2a741 100644
--- a/src/server/dub.ts
+++ b/src/server/dub.ts
@@ -96,16 +96,36 @@ export interface CreateDubInput {
duration?: number;
}
+/**
+ * Lengths read from stored files, by path, size and time: a dub (or an Assist call) is checked, priced
+ * and started, each asking for the length, and reading a 200 MB upload each time would block the server.
+ */
+const lengths = new Map<string, number | null>();
+
/** The source's length: its MP4/MOV header, else what the browser measured. The dubbed voice track is this long. */
export function videoLength(ref: string, measured?: number): number | undefined {
try {
if (ref.startsWith("/api/files/")) {
- const info = probeMedia(fs.readFileSync(absolutePath(decodeURIComponent(ref.slice("/api/files/".length)))));
- const d = info?.videoDuration ?? info?.duration;
- if (d && d > 0) return d;
+ const abs = absolutePath(decodeURIComponent(ref.slice("/api/files/".length)));
+ const st = fs.statSync(abs);
+ const key = `${abs}|${st.size}|${st.mtimeMs}`;
+ if (!lengths.has(key)) {
+ let d: number | null = null;
+ try {
+ const info = probeMedia(fs.readFileSync(abs));
+ const v = info?.videoDuration ?? info?.duration;
+ d = v && v > 0 ? v : null;
+ } catch {
+ // An unreadable header (WebM): what the browser measured.
+ }
+ lengths.set(key, d);
+ if (lengths.size > 64) lengths.delete(lengths.keys().next().value!);
+ }
+ const d = lengths.get(key);
+ if (d) return d;
}
} catch {
- // An unreadable header (WebM): what the browser measured.
+ // Gone: what the browser measured.
}
return measured && measured > 0 ? measured : undefined;
}
diff --git a/tests/assist-studio-routes.test.ts b/tests/assist-studio-routes.test.ts
index 3bb3618f..fe29bc3c 100644
--- a/tests/assist-studio-routes.test.ts
+++ b/tests/assist-studio-routes.test.ts
@@ -53,6 +53,21 @@ async function priced<T>(fn: () => T | Promise<T>): Promise<T> {
}
}
+/** Claude connected as the LLM (nothing is called while pricing). */
+async function withLlm<T>(fn: () => T | Promise<T>): Promise<T> {
+ setSetting("anthropicKey", "test-key");
+ setSetting("enhanceProvider", "auto");
+ try {
+ return await fn();
+ } finally {
+ setSetting("anthropicKey", "");
+ setSetting("enhanceProvider", "none");
+ }
+}
+
+type Est = { result: { structuredContent: { studio?: string; href?: string; fallback?: string; jobs: { error?: string }[] }; isError: boolean } };
+const estimate = async (tool: string, args: unknown) => (await rpc("tools/call", { name: "estimate_job", arguments: { tool, arguments: args } })) as Est;
+
const fixture = path.join(__dirname, "fixtures/shorts-12s.mp4");
let png = "";
let clip = "";
@@ -189,11 +204,11 @@ describe("Translate & dub", () => {
(await (await dubRoute.POST(new Request("http://x/api/dub?preview=1", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(b) }))).json()) as { costUsd: number; steps: number };
it("prices the first stage like the studio's preview, and one-go dubs too", async () => {
- const p = await priced(() => plan("dub_video", { video: clip, languages: ["Spanish", "German"] }));
- const route = await priced(() => preview({ engine: "cloud", mode: "steps", video: clip, targets: ["es", "de"] }));
+ const p = await withLlm(() => priced(() => plan("dub_video", { video: clip, languages: ["Spanish", "German"] })));
+ const route = await withLlm(() => priced(() => preview({ engine: "cloud", mode: "steps", video: clip, targets: ["es", "de"] })));
expect(p).toMatchObject({ studio: "Translate & dub", href: "/audio/translate" });
- // (The translation itself needs an LLM, which isn't connected here.)
- expect(p.jobs).toEqual([expect.objectContaining({ op: "translate", costUsd: route.costUsd, prompt: "Into Spanish, German", count: 2 })]);
+ expect(p.jobs).toEqual([expect.objectContaining({ op: "translate", costUsd: route.costUsd, prompt: "Into Spanish, German", count: 2, demo: false })]);
+ expect(p.jobs[0].error).toBeUndefined();
expect(route.costUsd).toBeGreaterThan(0);
expect(p.jobs[0].note).toMatch(/review every line and voice it in Translate & dub/);
const oneGo = await priced(() => plan("dub_video", { video: clip, languages: ["Spanish"], review: false }));
@@ -222,6 +237,40 @@ describe("Translate & dub", () => {
expect(gen(b.results[0])).toMatchObject({ modelId: "elevenlabs-dubbing", op: "dub" });
});
+ it("with a fal key but no Claude or Ollama, dubs in one go rather than plan a review that can't start", async () => {
+ // The review's translation would run as a demo among real steps, which createPipeline refuses.
+ const p = await priced(() => plan("dub_video", { video: clip, languages: ["Spanish"] }));
+ expect(p).toMatchObject({ studio: "Translate & dub", href: "/audio/translate" });
+ expect(p.jobs).toEqual([expect.objectContaining({ modelId: "heygen-translate", op: "dub", demo: false })]);
+ expect(p.jobs[0].error).toBeUndefined();
+ expect(p.jobs[0].note).toMatch(/Reviewing the lines can't start: Translate · Spanish would run as a demo \(it needs Claude or Ollama\).*dubs in one go with HeyGen Translate/);
+ expect((await priced(() => estimate("dub_video", { video: clip, languages: ["Spanish"] }))).result.isError).toBe(false);
+ // A review asked for outright isn't swapped: the card says why it can't start, and nothing is made.
+ const asked = await priced(() => plan("dub_video", { video: clip, languages: ["Spanish"], review: true }));
+ expect(asked.jobs[0].error).toMatch(/^Reviewing the lines can't start: Translate · Spanish would run as a demo.*connect it in Settings, or dub in one go \(review: false\)/);
+ expect((await priced(() => estimate("dub_video", { video: clip, languages: ["Spanish"], review: true }))).result.isError).toBe(true);
+ const before = dub.listDubSessions(100).length;
+ const out = await priced(() => run("dub_video", { video: clip, languages: ["Spanish"], review: true }));
+ expect(out).toMatchObject({ isError: true, content: expect.stringMatching(/Reviewing the lines can't start/) });
+ expect(dub.listDubSessions(100)).toHaveLength(before);
+ // With Claude connected too, the review runs as planned.
+ expect((await withLlm(() => priced(() => plan("dub_video", { video: clip, languages: ["Spanish"], review: true })))).jobs[0]).toMatchObject({ op: "translate", demo: false });
+ });
+
+ it("reads a video's length once, however often a call is checked and priced", () => {
+ const fresh = saveFile({ data: fs.readFileSync(fixture), contentType: "video/mp4", source: "upload", name: "read once.mp4" }).url;
+ const spy = vi.spyOn(fs, "readFileSync");
+ try {
+ for (let k = 0; k < 3; k++) {
+ expect(plan("dub_video", { video: fresh, languages: ["German"] }, "open").studio).toBe("Translate & dub");
+ expect(plan("add_captions", { video: fresh }, "open").studio).toBe("Captions");
+ }
+ expect(spy.mock.calls.filter(([f]) => String(f).endsWith(path.basename(fresh)))).toHaveLength(1);
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
it("falls back for a language the studio doesn't list", () => {
const p = plan("dub_video", { video: clip, languages: ["Klingon"] });
expect(p.fallback).toMatch(/doesn't list Klingon/);
@@ -286,7 +335,7 @@ describe("Ads Studio", () => {
expect(out.isError).toBeFalsy();
const b = body(out);
expect(b.href).toBe(`/ads/${b.brand}`);
- expect(brand.getBrand(b.brand)).toMatchObject({ source: "manual", status: "ready" });
+ expect(brand.getBrand(b.brand)).toMatchObject({ source: "manual", status: "ready", origin: "assist", name: b.brandName });
expect(brand.getProduct(b.product)).toMatchObject({ name: "Cold brew coffee for night owls", brandId: b.brand, images: [png] });
const creatives = ads.listCreatives({ brandId: b.brand, batchId: b.batch });
expect(creatives).toHaveLength(2);
@@ -299,6 +348,39 @@ describe("Ads Studio", () => {
expect([again.brand, again.product]).toEqual([b.brand, b.product]);
});
+ it("never takes over the user's own kits or changes their products", async () => {
+ const acme = await brand.createManualBrand({ description: "Acme makes running gear", name: "Acme" });
+ const shoes = brand.createProduct({ name: "Running shoes", brandId: acme.id });
+ const photo = saveFile({ data: encodePng({ width: 32, height: 32, data: Buffer.alloc(32 * 32 * 4, 90) }), contentType: "image/png", source: "upload", name: "shoe.png" }).url;
+ // No brand_id: a kit of Assist's own, even though Acme has a product of that name.
+ const b = body(await run("create_ads", { brief: "Running shoes, light and fast", product_image: photo, count: 1 }));
+ expect(b.brand).not.toBe(acme.id);
+ expect(brand.getBrand(b.brand)?.origin).toBe("assist");
+ expect(brand.getProduct(shoes.id)?.images).toEqual([]);
+ // Acme named: the ads are Acme's, and the new photo makes a second "Running shoes" rather than replacing Acme's.
+ const named = body(await run("create_ads", { brief: "Running shoes, light and fast", product_image: photo, brand_id: acme.id, count: 1 }));
+ expect(named.brand).toBe(acme.id);
+ expect(named.product).not.toBe(shoes.id);
+ expect(brand.getProduct(shoes.id)?.images).toEqual([]);
+ expect(brand.getProduct(named.product)).toMatchObject({ name: "Running shoes", brandId: acme.id, images: [photo] });
+ // The same photo again goes to that product; no photo, to the first of that name.
+ expect(body(await run("create_ads", { brief: "Running shoes", product_image: photo, brand_id: acme.id, count: 1 })).product).toBe(named.product);
+ expect(brand.listProducts(acme.id).filter((p) => p.name === "Running shoes")).toHaveLength(2);
+ });
+
+ it("keeps a given headline on Fuobe's compositor, even with a Higgsfield key", async () => {
+ setSetting("higgsfieldKey", "id:secret");
+ try {
+ const own = await priced(() => plan("create_ads", { brief: "Sneakers for city runs", aspect_ratios: ["4:5"] }));
+ expect(own.jobs[0].modelName).toBe("Higgsfield Ads Studio");
+ const fixed = await priced(() => plan("create_ads", { brief: "Sneakers for city runs", aspect_ratios: ["4:5"], headline: "Run the city" }));
+ expect(fixed.jobs[0].modelName).not.toBe("Higgsfield Ads Studio");
+ expect(fixed.jobs[0].note).toMatch(/each in 1:1, 4:5 and 9:16/);
+ } finally {
+ setSetting("higgsfieldKey", "");
+ }
+ });
+
it("falls back for formats it doesn't make", () => {
const p = plan("create_ads", { brief: "Sneakers", aspect_ratios: ["16:9"] });
expect(p.fallback).toMatch(/1:1, 4:5 and 9:16 ads \(not 16:9\)/);
@@ -313,6 +395,11 @@ describe("Captions", () => {
expect(p.jobs.map((j) => j.modelId)).toEqual(["scribe-v2", "auto-subtitle"]);
expect(p.jobs[1].costUsd).toBe(Math.round(burnPricePerMinute("auto", "clean") * (12 / 60) * 1000) / 1000);
expect(p.jobs[0].costUsd).toBeGreaterThan(0);
+ // VEED translating as it burns: its basic rate plus the translation's $0.20 a minute.
+ const translated = await priced(() => plan("add_captions", { video: clip, translate_to: "Spanish" }));
+ expect(translated.jobs).toEqual([expect.objectContaining({ modelId: "veed-subtitles", costUsd: Math.round(0.3 * (12 / 60) * 1000) / 1000 })]);
+ expect(burnPricePerMinute("veed", "clean", true)).toBeCloseTo(0.3);
+ expect(burnPricePerMinute("veed", "clean")).toBeCloseTo(0.1);
});
it("burns them in and opens the editor on the video with its lines", async () => {
@@ -349,7 +436,6 @@ describe("MCP", () => {
});
it("estimate_job says where the job opens, or why it runs in the Library", async () => {
- type Est = { result: { structuredContent: { studio?: string; href?: string; fallback?: string; jobs: unknown[] }; isError: boolean } };
const est = (await rpc("tools/call", { name: "estimate_job", arguments: { tool: "dub_video", arguments: { video: clip, languages: ["Spanish"] } } })) as Est;
expect(est.result.isError).toBe(false);
expect(est.result.structuredContent).toMatchObject({ studio: "Translate & dub", href: "/audio/translate" });
@@ -360,6 +446,14 @@ describe("MCP", () => {
expect(off.result.structuredContent.fallback).toMatch(/Library/);
});
+ it("tool arguments name what each studio takes", async () => {
+ const list = (await rpc("tools/list")) as { result: { tools: { name: string; inputSchema: { properties: Record<string, { description?: string; items?: unknown }> } }[] } };
+ const arg = (tool: string, key: string) => list.result.tools.find((t) => t.name === tool)!.inputSchema.properties[key].description ?? "";
+ expect(arg("restyle_footage", "model_id")).toMatch(/gemini-omni-flash.*oss-wan22-vace-restyle.*outside Shorts Studio/);
+ expect(arg("split_layers", "model_id")).toMatch(/seedream-5-layers.*oss-qwen-layered.*outside Layers/);
+ expect(arg("create_ads", "aspect_ratios")).toMatch(/16:9 runs outside Ads Studio/);
+ });
+
it("tools/call returns the job's page", async () => {
const r = (await rpc("tools/call", { name: "split_layers", arguments: { image: png } })) as { result: { content: { text: string }[]; isError: boolean } };
expect(r.result.isError).toBe(false);
@@ -391,9 +485,12 @@ describe("Assist chat", () => {
it("a call the studio can't take says why on the card", async () => {
const t = agent.createThread({ engine: "open", agent: "offline", autoApprove: false });
agent.addMessage(t.id, "A square tea episode");
- await agent.run(t.id, scripted(reply([use("u1", "faceless_episode", { scenes, style: "watercolour", aspect_ratio: "1:1" })], "tool_use")));
+ // Two square episodes in one turn: the reason is said once.
+ const square = { scenes, style: "watercolour", aspect_ratio: "1:1" };
+ await agent.run(t.id, scripted(reply([use("u1", "faceless_episode", square), use("u2", "faceless_episode", { ...square, title: "Again" })], "tool_use")));
const card = agent.getThread(t.id)!.thread.items.find((i) => i.role === "approval");
expect(card).toMatchObject({ notes: [expect.stringMatching(/16:9 and 9:16 episodes — so it runs as separate steps in your Library\./)] });
+ expect(card && "notes" in card ? card.notes : []).toHaveLength(1);
expect(card && "opens" in card ? card.opens : undefined).toBeUndefined();
});