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.

Marketing planners: voiced open films, scripts that keep the CTA, kits from product links

Claudeed50686bf9ec
diff --git a/src/app/api/ads/multiplier/estimate/route.ts b/src/app/api/ads/multiplier/estimate/route.ts
index 2610f6ed..a8d6f938 100644
--- a/src/app/api/ads/multiplier/estimate/route.ts
+++ b/src/app/api/ads/multiplier/estimate/route.ts
@@ -4,7 +4,7 @@ export async function POST(request: Request) {
const body = await readBody(request, MultiplierBody, "Add a reference video to recreate");
if (body instanceof Response) return body;
try {
- return Response.json(estimateMultiplier(body));
+ return Response.json(await estimateMultiplier(body));
} catch (e) {
return Response.json({ costUsd: null, demo: false, steps: [], notes: [], runs: 0, blocker: (e as Error).message });
}
diff --git a/src/app/api/ads/multiplier/route.ts b/src/app/api/ads/multiplier/route.ts
index a84e96eb..f6125701 100644
--- a/src/app/api/ads/multiplier/route.ts
+++ b/src/app/api/ads/multiplier/route.ts
@@ -5,7 +5,7 @@ export async function POST(request: Request) {
const body = await readBody(request, MultiplierBody, "Add a reference video to recreate");
if (body instanceof Response) return body;
try {
- return Response.json({ runs: runMultiplier(body) }, { status: 201 });
+ return Response.json({ runs: await runMultiplier(body) }, { status: 201 });
} catch (e) {
return failure(e);
}
diff --git a/src/components/brand/research-progress.tsx b/src/components/brand/research-progress.tsx
index 2d8e8730..28b9a125 100644
--- a/src/components/brand/research-progress.tsx
+++ b/src/components/brand/research-progress.tsx
@@ -4,7 +4,7 @@ import { Loader2, Sparkles } from "lucide-react";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
-import { researchLabel, RESEARCH_LABELS, type BrandKit } from "@/lib/catalog/marketing";
+import { researchLabel, researchProgress, type BrandKit } from "@/lib/catalog/marketing";
/** The clock, ticking every `every` ms (rotating labels). */
function useNow(every: number) {
@@ -25,7 +25,7 @@ export function ResearchLabel({ progress }: { progress: BrandKit["progress"] })
/** "Usually takes about a minute": Higgsfield's rotating research labels, a progress bar and Cancel. */
export function ResearchProgress({ brand, onCancel, canceling }: { brand: BrandKit; onCancel?: () => void; canceling?: boolean }) {
const now = useNow(700);
- const { index, label } = researchLabel(brand.progress, now);
+ const { label } = researchLabel(brand.progress, now);
const host = brand.website ? new URL(brand.website).hostname.replace(/^www\./, "") : brand.name;
return (
<div role="status" aria-live="polite" className="mx-auto w-full max-w-md text-center">
@@ -34,7 +34,7 @@ export function ResearchProgress({ brand, onCancel, canceling }: { brand: BrandK
</div>
<h2 className="mt-5 font-heading text-[26px] leading-tight">Researching {host}</h2>
<p className="mt-1 text-[14px] text-muted-foreground">Usually takes about a minute. You can leave this page — it keeps going.</p>
- <Progress value={((index + 1) / RESEARCH_LABELS.length) * 100} className="mt-6 h-1.5" aria-label="Research progress" />
+ <Progress value={researchProgress(brand.progress, now)} className="mt-6 h-1.5" aria-label="Research progress" />
<p key={label} className="mt-3 animate-fade-up text-[13px] font-medium">
<span className="shimmer-text animate-shimmer-text">{label}…</span>
</p>
diff --git a/src/lib/catalog/marketing.ts b/src/lib/catalog/marketing.ts
index ef384828..989726a9 100644
--- a/src/lib/catalog/marketing.ts
+++ b/src/lib/catalog/marketing.ts
@@ -124,6 +124,19 @@ export function researchLabel(p: Pick<BrandProgress, "index" | "startedAt"> | nu
return { index: i, label: RESEARCH_LABELS[i] };
}
+/**
+ * How far the research is (0–100) for the bar: the server's own step, eased forward over time during
+ * the writing stage so it keeps moving — and never goes back while the labels rotate.
+ */
+export function researchProgress(p: Pick<BrandProgress, "index" | "startedAt"> | null | undefined, now: number, settle = 25_000): number {
+ const total = RESEARCH_LABELS.length;
+ if (!p) return (1 / total) * 100;
+ const at = ((Math.min(p.index, total - 1) + 1) / total) * 100;
+ if (p.index < LLM_STAGE.from || p.index > LLM_STAGE.to) return at;
+ const end = ((LLM_STAGE.to + 1) / total) * 100;
+ return at + (end - at) * (1 - Math.exp(-Math.max(0, now - p.startedAt) / settle));
+}
+
/** Click to Ad's product-kit labels. */
export const KIT_LABELS = ["Connecting to website", "Extracting product images", "Finding brand colors", "Locating logo", "Processing details", "Finalizing product kit"] as const;
@@ -704,14 +717,33 @@ export const WORDS_PER_SECOND = 2.5;
export const wordBudget = (seconds: number) => Math.max(6, Math.round(seconds * WORDS_PER_SECOND));
-/** Trim a script to its word budget at a sentence end when possible. */
+const wordsIn = (s: string) => s.split(" ").filter(Boolean).length;
+
+/**
+ * Trim a script to its word budget at sentence ends. The closing sentence (the call to action) stays
+ * when it takes at most half the budget: sentences give way from the middle, never the end.
+ */
export function fitScript(script: string, seconds: number): string {
const max = wordBudget(seconds);
- const words = script.replace(/\s+/g, " ").trim().split(" ").filter(Boolean);
- if (words.length <= max) return words.join(" ");
- const cut = words.slice(0, max).join(" ");
- const end = Math.max(cut.lastIndexOf(". "), cut.lastIndexOf("! "), cut.lastIndexOf("? "));
- return end > cut.length * 0.5 ? cut.slice(0, end + 1) : `${cut.replace(/[,;:\s]+$/, "")}.`;
+ const text = script.replace(/\s+/g, " ").trim();
+ if (wordsIn(text) <= max) return text;
+ const sentences = (text.match(/[^.!?]+(?:[.!?]+["”’']?|$)/g) ?? [text]).map((s) => s.trim()).filter(Boolean);
+ const last = sentences.length > 1 ? sentences[sentences.length - 1] : null;
+ const tail = last && wordsIn(last) <= max / 2 ? last : null;
+ const room = max - (tail ? wordsIn(tail) : 0);
+ const head: string[] = [];
+ let used = 0;
+ for (const s of tail ? sentences.slice(0, -1) : sentences) {
+ if (used + wordsIn(s) > room) break;
+ head.push(s);
+ used += wordsIn(s);
+ }
+ if (!head.length || used < room * 0.5) {
+ // The opening sentence alone runs past the budget: cut it at a word.
+ const cut = (tail ? sentences.slice(0, -1).join(" ") : text).split(" ").slice(0, room).join(" ").replace(/[,;:\s]+$/, "");
+ head.splice(0, head.length, /[.!?]$/.test(cut) ? cut : `${cut}.`);
+ }
+ return [...head, ...(tail ? [tail] : [])].join(" ");
}
export interface Cue {
@@ -822,6 +854,12 @@ export const UGC_MODELS = {
open: { voice: "oss-chatterbox", still: "oss-qwen-edit", talk: "oss-infinitetalk", clip: "oss-wan22-14b-fast", captions: "oss-captions-burnin", join: "oss-join-clips", mux: "oss-mux", trim: "oss-trim", frame: "oss-extract-frame" },
} as const;
+/**
+ * Open joins that keep one clip's own sound (oss-join-clips drops every soundtrack): the first clip's
+ * from the start, or the second clip's starting where the first ends (a silent hook before the voice).
+ */
+export const OPEN_SOUND_JOIN = { first: "oss-join-sound1", second: "oss-join-sound2" } as const;
+
/** The models the Ad Multiplier can recreate with, per engine (the first that's usable is the default). */
export const MULTIPLIER_MODELS: Record<Engine, ModelChoice[]> = {
cloud: [
diff --git a/src/server/ads.ts b/src/server/ads.ts
index b7dbc803..3b81fffa 100644
--- a/src/server/ads.ts
+++ b/src/server/ads.ts
@@ -21,6 +21,7 @@ import { db } from "./db";
import { llmText } from "./enhance";
import { createGenerations, getGeneration, previewGeneration, recordLocalGeneration } from "./generations";
import { provider } from "./providers";
+import { llmBackends } from "./providers/llm";
import { engineMode } from "./settings";
/**
@@ -284,7 +285,8 @@ export function estimateBatch(input: BatchInput): BatchEstimate {
perAd,
costUsd: perAd === null ? null : Math.round((perAd * total + copy * input.items.length) * 1000) / 1000,
demo: p.demo,
- copyBy: copy > 0 || p.demo ? "llm" : "rules",
+ // Who writes the words: an LLM this install can reach (as llmText picks one), else the rules.
+ copyBy: route === "fuobe" && llmBackends({ endpoint: "claude" }).length ? "llm" : "rules",
};
}
@@ -423,18 +425,21 @@ function settle(rows: CreativeRow[]): CreativeRow[] {
}
export function listCreatives(o: { brandId: string; batchId?: string; productId?: string; limit?: number }): AdCreative[] {
- const where = ["brand_id = ?"];
+ const where = ["c.brand_id = ?"];
const args: unknown[] = [o.brandId];
if (o.batchId) {
- where.push("batch_id = ?");
+ where.push("c.batch_id = ?");
args.push(o.batchId);
}
if (o.productId) {
- where.push("product_id = ?");
+ where.push("c.product_id = ?");
args.push(o.productId);
}
+ // Newest batch first; inside a batch, in the order the ads were asked for (product by product).
const rows = db()
- .prepare(`SELECT * FROM ad_creatives WHERE ${where.join(" AND ")} ORDER BY created_at DESC, position ASC LIMIT ?`)
+ .prepare(
+ `SELECT c.* FROM ad_creatives c LEFT JOIN ad_batches b ON b.id = c.batch_id WHERE ${where.join(" AND ")} ORDER BY COALESCE(b.created_at, c.created_at) DESC, c.batch_id, c.position ASC LIMIT ?`,
+ )
.all(...args, Math.min(1000, o.limit ?? 400)) as CreativeRow[];
return settle(rows).map(toCreative);
}
@@ -559,10 +564,21 @@ export function offlineProposal(text: string, products: Pick<Product, "id" | "na
direction = direction
.replace(/\b(please|can you|could you|make|create|generate|write|me|some)\b/gi, " ")
.replace(/\bfor (?:my|our|the|this) products?\b/gi, " ")
+ // A stray "@" (or an @mention that names no product) is not part of the direction.
+ .replace(/(?:\b(?:for|of|with|featuring)\s+)?(?<!\S)@\S*/gi, " ")
.replace(/\s+([,.!?])/g, "$1")
.replace(/^[\s,.:;-]+|[\s,.:;-]+$/g, "")
.replace(/\s+/g, " ")
.trim();
+ // …nor a word left dangling once the products are gone ("playful for").
+ for (let prev = ""; prev !== direction; ) {
+ prev = direction;
+ direction = direction
+ .replace(/(?:^|\s+)(?:for|of|with|featuring|about|to|on|and|the|a|an)$/i, "")
+ .replace(/^and\b\s*/i, "")
+ .replace(/^[\s,.:;-]+|[\s,.:;-]+$/g, "")
+ .trim();
+ }
return { count, productIds: ids, direction };
}
diff --git a/src/server/brand.ts b/src/server/brand.ts
index 51da1e62..2af945f2 100644
--- a/src/server/brand.ts
+++ b/src/server/brand.ts
@@ -334,7 +334,26 @@ function offerOf(v: unknown): { price: number | null; currency: string | null }
return { price: priceOf(o.price ?? o.lowPrice ?? (o.priceSpecification as Json | undefined)?.price), currency: str(o.priceCurrency) || null };
}
-const stripHtml = (s: string, max = 600) => clean(strip(s), max);
+/** Text from HTML with its line breaks kept (list items and paragraphs stay apart for selling points). */
+const stripHtml = (s: string, max = 600) =>
+ strip(s)
+ .split("\n")
+ .map((line) => line.replace(/\s+/g, " ").trim())
+ .filter(Boolean)
+ .join("\n")
+ .slice(0, max)
+ .trim();
+
+/** Like clean(), but keeps line breaks (a product description's bullet lines). */
+const cleanLines = (s: string | undefined | null, max = 2000) =>
+ s
+ ? decodeEntities(s)
+ .split(/\r?\n/)
+ .map((line) => line.replace(/\s+/g, " ").trim())
+ .filter(Boolean)
+ .join("\n")
+ .slice(0, max)
+ : "";
/** Products in JSON-LD (Product, ProductGroup, and Products inside an ItemList). */
export function jsonLdProducts(blocks: Json[], base: string): ProductDraft[] {
@@ -1200,7 +1219,7 @@ function insertProduct(p: Omit<ProductDraft, "images"> & { sellingPoints?: strin
id,
brandId,
clean(p.name, 140) || "Untitled product",
- clean(p.description, 2000) || null,
+ cleanLines(p.description, 2000) || null,
p.price ?? null,
p.currency ? clean(p.currency, 8) : null,
clean(p.audience, 300) || null,
@@ -1251,7 +1270,7 @@ export function updateProduct(id: string, patch: Partial<ProductInput>): Product
const next = {
brand_id: patch.brandId !== undefined ? patch.brandId : p.brandId,
name: patch.name !== undefined ? clean(patch.name, 140) || p.name : p.name,
- description: patch.description !== undefined ? clean(patch.description, 2000) || null : (p.description ?? null),
+ description: patch.description !== undefined ? cleanLines(patch.description, 2000) || null : (p.description ?? null),
price: patch.price !== undefined ? patch.price : (p.price ?? null),
currency: patch.currency !== undefined ? (patch.currency ? clean(patch.currency, 8) : null) : (p.currency ?? null),
audience: patch.audience !== undefined ? clean(patch.audience, 300) || null : (p.audience ?? null),
@@ -1282,9 +1301,60 @@ export interface LinkRead {
duplicate?: Product;
/** Brand bits the page carries: Click to Ad's product kit shows the logo and colours. */
brand: { name?: string; logo?: string; colors: string[]; fonts: { heading?: string; body?: string } };
+ /** The brand kit the products were added to (the site's own kit when read with its brand). */
+ brandId?: string;
message?: string;
}
+const siteHost = (url: string | undefined) => {
+ try {
+ return url ? new URL(url).hostname.replace(/^www\./, "").toLowerCase() : "";
+ } catch {
+ return "";
+ }
+};
+
+/**
+ * The brand kit for a product page's site: the kit whose website is on the same host (missing logo,
+ * colours and fonts filled from the page), else a new ready kit made from what the page showed.
+ */
+export function kitForSite(pageUrl: string, bits: LinkRead["brand"]): BrandKit {
+ const host = siteHost(pageUrl);
+ const existing = listBrands().find((b) => b.status !== "researching" && siteHost(b.website) === host);
+ if (existing) {
+ const patch: Partial<BrandKitFields> = {};
+ if (!existing.logo && bits.logo) patch.logo = bits.logo;
+ if (!existing.colors.length && bits.colors.length) patch.colors = bits.colors;
+ if (!existing.fonts.heading && !existing.fonts.body && (bits.fonts.heading || bits.fonts.body)) patch.fonts = bits.fonts;
+ return Object.keys(patch).length ? (updateBrand(existing.id, patch) ?? existing) : existing;
+ }
+ const website = new URL(pageUrl).origin + "/";
+ const name = clean(bits.name, 80) || hostName(host);
+ const kit: StoredKit = {
+ ...emptyKit(name),
+ website,
+ logo: bits.logo,
+ colors: bits.colors.filter(isHex).slice(0, 8),
+ fonts: { heading: bits.fonts.heading, body: bits.fonts.body },
+ source: "website",
+ note: `Made from a product page on ${host}. Run the research for the rest of the brand kit (tone, audience, values…).`,
+ };
+ const id = nanoid(10);
+ const now = Date.now();
+ db()
+ .prepare("INSERT INTO brand_kits (id, name, website, status, progress_json, kit_json, chat_json, created_at, updated_at) VALUES (?, ?, ?, 'ready', NULL, ?, '[]', ?, ?)")
+ .run(id, name, website, JSON.stringify(kit), now, now);
+ return getBrand(id)!;
+}
+
+/** What Click to Ad shows for a kit: its own logo, colours and fonts, else the page's. */
+const kitBits = (kit: BrandKit, page: LinkRead["brand"]): LinkRead["brand"] => ({
+ name: kit.name,
+ logo: kit.logo ?? page.logo,
+ colors: kit.colors.length ? kit.colors : page.colors,
+ fonts: kit.fonts.heading || kit.fonts.body ? kit.fonts : page.fonts,
+});
+
/**
* Add products from a link ("Add product from link", Click to Ad): Shopify's product JSON when the
* store is Shopify, else JSON-LD / OpenGraph on the page. Images are downloaded into the library.
@@ -1311,6 +1381,25 @@ export async function readProductLink(input: { url: string; brandId?: string | n
if (!drafts.length) throw new Error("Paste the product's link — a description alone is not enough.");
const limit = Math.max(1, input.limit ?? 1);
const facts = input.withBrand ? parseSite(page.text, page.url) : null;
+ // The page's brand bits (Click to Ad's product kit), read before the products so they can join that brand's kit.
+ let brand: LinkRead["brand"] = { colors: [], fonts: {} };
+ if (facts) {
+ const sheets = (await pool(facts.stylesheets.slice(0, 3), 3, (s) => fetchText(s, 2 * 1024 * 1024, 10_000))).filter((x): x is NonNullable<typeof x> => !!x).map((x) => x.text);
+ const css = [...facts.inlineCss, ...sheets];
+ const logo = facts.svgLogo
+ ? saveFile({ data: Buffer.from(facts.svgLogo), contentType: "image/svg+xml", name: `${facts.host}-logo.svg`, source: "upload" }).url
+ : await firstSaved(facts.logos, { allowSvg: true, minBytes: 300 });
+ const f = extractFonts(page.text, css);
+ brand = { name: facts.organization?.name ?? facts.name, logo: logo ?? undefined, colors: extractColors(css, facts.themeColor), fonts: { heading: f.heading, body: f.body } };
+ }
+ // A product read with its brand (and no brand chosen) joins the kit for that site, made now if there's none,
+ // so the logo and colours stay with the product and reach every flow that uses it.
+ const kit = facts && !brandId ? kitForSite(page.url, brand) : null;
+ const owner = brandId ?? kit?.id ?? null;
+ if (kit) {
+ const dup = listProducts(kit.id).find((p) => p.url === url || p.url === page.url);
+ if (dup) return { products: [], found: 1, duplicate: dup, brand: kitBits(kit, brand), brandId: kit.id, message: `«${dup.name}» is already among ${kit.name}'s products.` };
+ }
const llm = softFieldsFrom(
parseJsonObject(
await llmText(
@@ -1326,23 +1415,14 @@ export async function readProductLink(input: { url: string; brandId?: string | n
for (const d of drafts.slice(0, limit)) {
const soft = llm.products?.find((x) => x.name.toLowerCase() === d.name.toLowerCase());
const pics = (await pool(d.images.slice(0, 5), 4, (u) => saveRemoteImage(u))).filter((x): x is string => !!x);
- products.push(insertProduct({ ...d, audience: soft?.audience, sellingPoints: soft?.sellingPoints?.length ? soft.sellingPoints : sellingPointsFrom(d.description) }, brandId, pics));
- }
- let brand: LinkRead["brand"] = { colors: [], fonts: {} };
- if (facts) {
- const sheets = (await pool(facts.stylesheets.slice(0, 3), 3, (s) => fetchText(s, 2 * 1024 * 1024, 10_000))).filter((x): x is NonNullable<typeof x> => !!x).map((x) => x.text);
- const css = [...facts.inlineCss, ...sheets];
- const logo = facts.svgLogo
- ? saveFile({ data: Buffer.from(facts.svgLogo), contentType: "image/svg+xml", name: `${facts.host}-logo.svg`, source: "upload" }).url
- : await firstSaved(facts.logos, { allowSvg: true, minBytes: 300 });
- const f = extractFonts(page.text, css);
- brand = { name: facts.organization?.name ?? facts.name, logo: logo ?? undefined, colors: extractColors(css, facts.themeColor), fonts: { heading: f.heading, body: f.body } };
+ products.push(insertProduct({ ...d, audience: soft?.audience, sellingPoints: soft?.sellingPoints?.length ? soft.sellingPoints : sellingPointsFrom(d.description) }, owner, pics));
}
const found = drafts.length;
return {
products,
found,
- brand,
+ brand: kit ? kitBits(getBrand(kit.id) ?? kit, brand) : brand,
+ brandId: owner ?? undefined,
message: found > products.length ? `Found ${found} products on that page and added the first ${products.length}. Paste a product's own link to add another.` : undefined,
};
} finally {
diff --git a/src/server/marketing.ts b/src/server/marketing.ts
index 0614a8e5..547f5e82 100644
--- a/src/server/marketing.ts
+++ b/src/server/marketing.ts
@@ -17,6 +17,7 @@ import {
MULTIPLIER,
MULTIPLIER_MODELS,
multiplierResolution,
+ OPEN_SOUND_JOIN,
multiplierText,
settingById,
shotPlan,
@@ -37,6 +38,7 @@ import {
type RunFeature,
} from "@/lib/catalog/marketing";
import { routesFor } from "@/lib/catalog/plan";
+import { probeMedia } from "@/lib/media-probe";
import type { ChainSlot, Engine, GenerationRequest, ModelDef, Operation } from "@/lib/catalog/types";
import { getBrand, getProduct } from "./brand";
import { createPipeline, type PipelineStep } from "./chains";
@@ -45,6 +47,7 @@ import { llmText } from "./enhance";
import { createGenerations, listGenerations, previewChained, recordLocalGeneration } from "./generations";
import { provider } from "./providers";
import { engineMode } from "./settings";
+import { readRef } from "./storage";
/**
* Marketing Studio (templates → product shots, posters, ads, product motion, UGC presenters),
@@ -179,7 +182,8 @@ const fill = (s: string, product?: Product | null, brand?: BrandKit | null) =>
function productLine(p?: Product | null): string {
if (!p) return "";
const pts = p.sellingPoints.slice(0, 2).join("; ");
- return `The product is ${p.name}${p.description ? ` — ${p.description.slice(0, 160)}` : ""}${pts ? ` (${pts})` : ""}`;
+ const about = p.description?.replace(/\s+/g, " ").trim().slice(0, 160);
+ return `The product is ${p.name}${about ? ` — ${about}` : ""}${pts ? ` (${pts})` : ""}`;
}
const KEEP_PRODUCT = "Keep the product exactly as in the reference photo: its shape, proportions, label, logo, text and colours";
@@ -212,10 +216,11 @@ export function planMarketing(input: MarketingInput, ctx: PlanContext): RunPlan
const productImages = input.productImages?.length ? input.productImages : (product?.images ?? []);
const hasProduct = productImages.length > 0;
const prompt = input.prompt?.trim() ?? "";
+ const website = input.website?.trim() || brand?.website || "";
// Required inputs, in Higgsfield's words.
if (f.product === "required" && !hasProduct) throw new PlanError(product ? `${product.name} has no images` : "Attach a product to generate");
if (f.oneOf?.length) {
- const has = { product: hasProduct, avatar: !!input.avatar, prompt: !!prompt, website: !!(input.website?.trim() || brand?.website) };
+ const has = { product: hasProduct, avatar: !!input.avatar, prompt: !!prompt, website: !!website };
if (!f.oneOf.some((k) => has[k])) {
throw new PlanError(f.id === "product-with-model" ? "Attach reference or product" : f.id === "poster" ? "Add a prompt or a product" : "Add a prompt, a product or a website");
}
@@ -309,7 +314,7 @@ export function planMarketing(input: MarketingInput, ctx: PlanContext): RunPlan
const aspect = nearestAspect(input.aspectRatio ?? f.defaultAspect, model.options.aspectRatios);
const refs = [...productImages.slice(0, 1), ...(input.reference ? [input.reference] : [])];
const motionText = (extra?: string) =>
- join(tpl ? fill(tpl.prompt, product, brand) : "A polished product commercial", extra, productLine(product), hasProduct && "The product stays exactly as in the first frame: same shape, label and colours", prompt, brandText, !hasProduct && input.website && `For the product at ${input.website}`);
+ join(tpl ? fill(tpl.prompt, product, brand) : "A polished product commercial", extra, productLine(product), hasProduct && "The product stays exactly as in the first frame: same shape, label and colours", prompt, brandText, !hasProduct && website && `For the product at ${website}`);
const base = { feature, modelId, params: { aspectRatio: aspect } as GenerationRequest["params"] };
// Open models make a few seconds per clip: longer motion is several shots from the product photo, joined.
const shots = open ? shotPlan(want, model.options.durations) : [snapDuration(want, model.options.durations)];
@@ -493,10 +498,23 @@ function planPresenter(p: PresenterPlan): RunPlan {
clips.push("broll");
}
if (clips.length > 1) {
+ // The open join keeps one clip's own sound: the captioned presenter's voice, after the hook when there is one
+ // (oss-join-clips drops every soundtrack and plays the 25 fps presenter at the hook's 16 fps).
+ const joinId = open ? (p.hook ? OPEN_SOUND_JOIN.second : OPEN_SOUND_JOIN.first) : M.join;
+ const joiner = need(joinId);
steps.push({
key: "film",
label: "Final video",
- request: { feature: p.feature, modelId: M.join, op: "concat", prompt: p.title, params: { aspectRatio: nearestAspect(aspect, need(M.join).options.aspectRatios) }, chain: clips.map(() => ({ slot: "videos" as const })), title: p.title, batchTitle: p.title },
+ request: {
+ feature: p.feature,
+ modelId: joinId,
+ op: "concat",
+ prompt: p.title,
+ params: { aspectRatio: nearestAspect(aspect, joiner.options.aspectRatios), ...(open && { resolution: nearestRes(p.quality ?? "480p", joiner) }) },
+ chain: clips.map(() => ({ slot: "videos" as const })),
+ title: p.title,
+ batchTitle: p.title,
+ },
after: clips,
});
} else {
@@ -504,7 +522,6 @@ function planPresenter(p: PresenterPlan): RunPlan {
c.request = { ...c.request, feature: p.feature, title: p.title, batchTitle: p.title };
}
if (open) p.notes.push("Open captions are timed from the script at a natural speaking pace");
- if (open && clips.length > 1) p.notes.push("The open-source join keeps the picture; the hook and close-up play without the voiceover");
p.meta.script = p.script;
return { feature: p.feature, engine: p.engine, title: p.title, steps, finals: [steps[steps.length - 1].key === "film" ? "film" : "captions"], meta: p.meta, notes: p.notes };
}
@@ -527,15 +544,61 @@ export interface ScriptInput {
language?: string;
}
-/** A natural script from facts alone, for installs with no LLM. */
+const countWords = (t: string) => t.split(/\s+/).filter(Boolean).length;
+const capitalize = (t: string) => t.charAt(0).toUpperCase() + t.slice(1);
+
+/** Words that tell the writer what to do ("mention", "highlight…"), dropped when the line is spoken as is. */
+const DIRECTIVE = String.raw`(?:mention|highlight|say|talk about|focus on|emphasi[sz]e|include|add|stress|call out|point out|note|tell (?:them|people|viewers))`;
+
+/**
+ * Custom-script instructions as lines the presenter can say: "highlight eco-friendly materials,
+ * mention free shipping over $40" → ["Eco-friendly materials.", "Free shipping over $40."].
+ */
+export function spokenInstructions(text: string | undefined): string[] {
+ if (!text?.trim()) return [];
+ return text
+ .split(new RegExp(String.raw`[;\n]+|,\s*(?:and\s+)?(?=${DIRECTIVE}\b)|\s+and\s+(?=${DIRECTIVE}\b)`, "i"))
+ .map((part) =>
+ part
+ .trim()
+ .replace(new RegExp(String.raw`^(?:please\s+)?(?:(?:make sure|be sure) (?:to|you)\s+)?${DIRECTIVE}(?:\s+that)?\s+`, "i"), "")
+ .replace(/[.!?,;:\s]+$/, ""),
+ )
+ .filter(Boolean)
+ .map((part) => `${capitalize(part)}.`);
+}
+
+/**
+ * A natural script from facts alone, for installs with no LLM, built to the word budget by priority:
+ * the call to action and the instructions always stay, the opener shortens, and selling points fill
+ * what's left — the middle gives way, never the end.
+ */
export function heuristicScript(s: ScriptInput): string {
+ const budget = wordBudget(s.seconds);
const name = s.product?.name ?? s.brand?.name ?? "this";
- const points = [...(s.product?.sellingPoints ?? []), ...(s.brand?.sellingPoints ?? [])].map(sentence).filter(Boolean);
- const opener = s.hook ? `Okay, that was not how I planned to start this, but I have to tell you about ${name}.` : `I didn't expect ${name} to become part of my every day, but here we are.`;
- const body = points.length ? points.slice(0, 2).map((p, i) => (i === 0 ? `First, ${p.charAt(0).toLowerCase()}${p.slice(1)}.` : `And ${p.charAt(0).toLowerCase()}${p.slice(1)}.`)).join(" ") : `It just works, it looks great, and it makes my day a little easier.`;
- const extra = s.instructions ? `${sentence(s.instructions)}.` : "";
- const close = s.brand?.website ? `Go check out ${s.brand.name} — link's in my bio.` : `Honestly? Go try it for yourself.`;
- return fitScript([opener, body, extra, close].filter(Boolean).join(" "), s.seconds);
+ const found = [...(s.product?.sellingPoints ?? []), ...(s.brand?.sellingPoints ?? [])].map(sentence).filter(Boolean);
+ const points = (found.length ? found : ["It just works, it looks great, and it makes my day a little easier"]).slice(0, 2).map((p) => `${capitalize(p)}.`);
+ // Longest first; the last of each list is the shortest form.
+ const openers = s.hook
+ ? [`Okay, that was not how I planned to start this, but I have to tell you about ${name}.`, `Okay, I have to tell you about ${name}.`, `Meet ${name}.`]
+ : [`I didn't expect ${name} to become part of my every day, but here we are.`, `I didn't expect to love ${name} this much.`, `Meet ${name}.`];
+ const closes = s.brand?.website ? [`Go check out ${s.brand.name} — link's in my bio.`, "Link's in my bio."] : ["Honestly? Go try it for yourself.", "Go try it today."];
+ let instructions = spokenInstructions(s.instructions);
+ let opener = openers[openers.length - 1];
+ let close = closes[closes.length - 1];
+ const used = () => countWords([opener, ...instructions, close].join(" "));
+ if (used() > budget) {
+ // Instructions longer than the ad: keep their first words, still ending on the call to action.
+ const room = Math.max(1, budget - countWords(opener) - countWords(close));
+ const words = instructions.join(" ").split(/\s+/).slice(0, room).join(" ").replace(/[,;:.!?\s]+$/, "");
+ instructions = words ? [`${words}.`] : [];
+ if (used() > budget) opener = "";
+ }
+ close = closes.find((c) => countWords([opener, ...instructions, c].join(" ")) <= budget) ?? close;
+ if (opener) opener = openers.find((o) => countWords([o, ...instructions, close].join(" ")) <= budget) ?? opener;
+ const middle: string[] = [];
+ for (const p of points) if (countWords([opener, ...instructions, ...middle, p, close].join(" ")) <= budget) middle.push(p);
+ return [opener, ...instructions, ...middle, close].filter(Boolean).join(" ");
}
/** The words the presenter says: the LLM when one is set up, else the heuristic. Always within the word budget. */
@@ -663,7 +726,16 @@ export function multiplierModel(input: Pick<MultiplierInput, "engine" | "modelId
return need(id);
}
-export function planMultiplier(input: MultiplierInput, ctx: { higgsfield: boolean; extractFrame?: boolean }): RunPlan {
+export interface MultiplierContext {
+ higgsfield: boolean;
+ extractFrame?: boolean;
+ /** The reference has a soundtrack (null or missing: its header couldn't be read). */
+ referenceSound?: boolean | null;
+ /** The reference's shape ("9:16"), from its header. */
+ referenceAspect?: string;
+}
+
+export function planMultiplier(input: MultiplierInput, ctx: MultiplierContext): RunPlan {
const open = input.engine === "open";
const start = Math.max(0, input.start ?? 0);
const end = Math.min(input.duration, input.end ?? input.duration);
@@ -707,7 +779,11 @@ export function planMultiplier(input: MultiplierInput, ctx: { higgsfield: boolea
},
after: src.after,
});
- if (!trimmed) {
+ if (ctx.referenceSound === false) {
+ // A silent reference: nothing to lay back on.
+ const edit = steps[steps.length - 1];
+ edit.request = { ...edit.request, feature: "ad-multiplier", title, batchTitle: title };
+ } else if (!trimmed) {
steps.push({ key: "sound", label: "Original sound", request: { feature: "ad-multiplier", modelId: M.mux, op: "mux", inputs: { audio: input.video }, title, batchTitle: title }, after: ["edit"], chain: [{ slot: "video" }] });
} else {
notes.push("Wan Animate makes the picture only; use the whole clip to keep its original sound");
@@ -744,7 +820,8 @@ export function planMultiplier(input: MultiplierInput, ctx: { higgsfield: boolea
const title = [input.hook != null && "New hook", input.cta != null && "New CTA"].filter(Boolean).join(" + ");
const frameModel = getModel(M.frame);
const canExtract = !!frameModel && (ctx.extractFrame ?? true);
- const clipParams = { duration: snapDuration(4, clipModel.options.durations), ...(clipModel.options.audio && { generateAudio: true }), resolution: nearestRes(resolution, clipModel) };
+ const clipAspect = nearestAspect(ctx.referenceAspect, clipModel.options.aspectRatios);
+ const clipParams = { duration: snapDuration(4, clipModel.options.durations), ...(clipModel.options.audio && { generateAudio: true }), resolution: nearestRes(resolution, clipModel), ...(clipAspect && { aspectRatio: clipAspect }) };
const order: string[] = [];
if (input.hook != null) {
const start = input.firstFrame ?? images[0];
@@ -774,17 +851,30 @@ export function planMultiplier(input: MultiplierInput, ctx: { higgsfield: boolea
}
order.push("cta");
}
- const joiner = need(M.join);
+ // The open join keeps the reference's own sound (after the new hook when there is one); a reference whose
+ // header couldn't be read goes through the plain join, which keeps the picture only.
+ const keepSound = open && !!ctx.referenceSound;
+ const joiner = need(keepSound ? (input.hook != null ? OPEN_SOUND_JOIN.second : OPEN_SOUND_JOIN.first) : M.join);
const stepKeys = order.filter((k) => k !== "original");
// The original goes in as an input; its place among the chained clips follows from position first/last.
const chain: ChainSlot[] = stepKeys.map((k) => ({ slot: "videos" as const, position: order.indexOf(k) < order.indexOf("original") ? ("first" as const) : ("last" as const) }));
steps.push({
key: "film",
label: "Final video",
- request: { feature: "ad-multiplier", modelId: joiner.id, op: "concat", prompt: title, inputs: trimmed ? undefined : { videos: [input.video] }, chain, title, batchTitle: title },
+ request: {
+ feature: "ad-multiplier",
+ modelId: joiner.id,
+ op: "concat",
+ prompt: title,
+ inputs: trimmed ? undefined : { videos: [input.video] },
+ ...(keepSound && { params: { aspectRatio: nearestAspect(ctx.referenceAspect, joiner.options.aspectRatios) ?? "auto", resolution: nearestRes(resolution, joiner) } }),
+ chain,
+ title,
+ batchTitle: title,
+ },
after: stepKeys,
});
- if (open) notes.push("The open-source join keeps the picture; the joined ad plays without sound");
+ if (open && ctx.referenceSound == null) notes.push("This clip's soundtrack couldn't be read here, so the joined ad keeps the picture only");
return { feature: "ad-multiplier", engine: input.engine, title, steps, finals: ["film"], meta, notes };
}
@@ -878,13 +968,28 @@ function context(input: { productId?: string; brandId?: string }) {
return { product, brand, higgsfield: higgsfieldReady() };
}
-const presenterSeconds = (input: MarketingInput) => input.duration ?? FORMATS[input.format].durations?.default ?? 15;
+/** The shortest talking part a UGC film gets, however short the length asked for. */
+const MIN_TALK_SECONDS = 5;
+
+/**
+ * Seconds the presenter talks in a UGC film: the length asked for minus the hook clip before it and
+ * the product close-up after it, so the whole film comes out about as long as the Length setting.
+ */
+export function presenterSeconds(input: MarketingInput, ctx: { product?: Product | null }): number {
+ const f = FORMATS[input.format];
+ const want = input.duration ?? f.durations?.default ?? 15;
+ const tpl = input.templateId ? TEMPLATE_INDEX.get(input.templateId) : undefined;
+ const shot = snapDuration(4, need(UGC_MODELS[input.engine].clip).options.durations);
+ const hook = f.hookAndSetting && hookById(input.hookId === undefined ? tpl?.hook : input.hookId);
+ const broll = !!(input.productImages?.length || ctx.product?.images.length);
+ return Math.max(MIN_TALK_SECONDS, want - (hook ? shot : 0) - (broll ? shot : 0));
+}
/** Marketing Studio: price a run (a stand-in script of the right length for UGC; no LLM call). */
export function estimateMarketing(input: MarketingInput): RunEstimate {
const ctx = context(input);
const f = FORMATS[input.format];
- const script = f.pipeline === "ugc" ? input.script?.trim() || Array(wordBudget(presenterSeconds(input))).fill("word").join(" ") : undefined;
+ const script = f.pipeline === "ugc" ? input.script?.trim() || Array(wordBudget(presenterSeconds(input, ctx))).fill("word").join(" ") : undefined;
const runs = f.pipeline === "image" ? 1 : Math.min(input.batch ?? 1, f.batch);
return estimatePlan(planMarketing(input, { ...ctx, script }), runs);
}
@@ -896,9 +1001,10 @@ export async function runMarketing(input: MarketingInput): Promise<{ runs: Marke
let script: string | undefined;
if (f.pipeline === "ugc") {
const hook = hookById(input.hookId === undefined ? tpl?.hook : input.hookId);
+ const seconds = presenterSeconds(input, ctx);
script = input.script?.trim()
- ? fitScript(input.script, presenterSeconds(input))
- : (await writeScript({ product: ctx.product, brand: ctx.brand, seconds: presenterSeconds(input), hook: hook?.prompt, angle: tpl?.prompt, instructions: input.prompt })).script;
+ ? fitScript(input.script, seconds)
+ : (await writeScript({ product: ctx.product, brand: ctx.brand, seconds, hook: hook?.prompt, angle: tpl?.prompt, instructions: input.prompt })).script;
}
const plan = planMarketing(input, { ...ctx, script });
const runs = f.pipeline === "image" ? 1 : Math.min(input.batch ?? 1, f.batch);
@@ -933,13 +1039,40 @@ export async function runClickToAd(input: ClickToAdInput): Promise<{ run: Market
return { run: launch(plan, { ...input, script }), script };
}
-export function estimateMultiplier(input: MultiplierInput): RunEstimate {
- const plan = planMultiplier(input, { higgsfield: higgsfieldReady() });
+declare global {
+ var __fuobeClipFacts: Map<string, { sound: boolean | null; aspect?: string }> | undefined;
+}
+const clipFacts = () => (globalThis.__fuobeClipFacts ??= new Map());
+
+/** Whether a stored clip has a soundtrack, and its shape, from the file's own header (cached per file). */
+export async function referenceFacts(ref: string): Promise<{ sound: boolean | null; aspect?: string }> {
+ const cache = clipFacts();
+ const hit = cache.get(ref);
+ if (hit) return hit;
+ let facts: { sound: boolean | null; aspect?: string } = { sound: null };
+ try {
+ const info = probeMedia(new Uint8Array((await readRef(ref)).data));
+ if (info?.hasVideo) facts = { sound: info.hasAudio, aspect: info.width && info.height ? nearestAspect(`${info.width}:${info.height}`, ["9:16", "4:5", "3:4", "1:1", "4:3", "16:9", "21:9"]) : undefined };
+ } catch {
+ // Not readable here: the plan falls back to what works without knowing.
+ }
+ if (cache.size > 200) cache.clear();
+ cache.set(ref, facts);
+ return facts;
+}
+
+async function multiplierContext(input: MultiplierInput): Promise<MultiplierContext> {
+ const facts = await referenceFacts(input.video);
+ return { higgsfield: higgsfieldReady(), referenceSound: facts.sound, referenceAspect: facts.aspect };
+}
+
+export async function estimateMultiplier(input: MultiplierInput): Promise<RunEstimate> {
+ const plan = planMultiplier(input, await multiplierContext(input));
return estimatePlan(plan, input.versions ?? 1);
}
-export function runMultiplier(input: MultiplierInput): MarketingRun[] {
- const plan = planMultiplier(input, { higgsfield: higgsfieldReady() });
+export async function runMultiplier(input: MultiplierInput): Promise<MarketingRun[]> {
+ const plan = planMultiplier(input, await multiplierContext(input));
estimatePlan(plan);
return Array.from({ length: input.versions ?? 1 }, () => launch(plan, { ...input, versions: 1 }));
}
@@ -951,7 +1084,7 @@ export async function rerun(id: string): Promise<MarketingRun[]> {
const input = r.meta.input;
if (!input) throw new PlanError("This run can't be repeated — start it again from the form");
if (r.feature === "click-to-ad") return [(await runClickToAd(ClickToAdBody.parse(input))).run];
- if (r.feature === "ad-multiplier") return runMultiplier(MultiplierBody.parse(input));
+ if (r.feature === "ad-multiplier") return await runMultiplier(MultiplierBody.parse(input));
return (await runMarketing(MarketingBody.parse(input))).runs;
}
diff --git a/tests/marketing-api.test.ts b/tests/marketing-api.test.ts
index e264abba..8998d15e 100644
--- a/tests/marketing-api.test.ts
+++ b/tests/marketing-api.test.ts
@@ -191,8 +191,12 @@ describe("brand kits", () => {
const again = await (await readRoute.POST(json("POST", { url: `${origin}/products/barrier-cream`, brandId }))).json();
expect(again.duplicate.name).toBe("Barrier Cream");
+ // Read with its brand (Click to Ad), the product joins the site's own kit — here the researched one, which has it already.
const shop = await (await readRoute.POST(json("POST", { url: `${origin}/products/maple-pecan-granola`, withBrand: true }))).json();
- expect(shop.products[0]).toMatchObject({ name: "Maple Pecan Granola", price: 12.5, brandId: null });
+ expect(shop.brandId).toBe(brandId);
+ expect(shop.duplicate).toMatchObject({ name: "Maple Pecan Granola", price: 12.5, brandId });
+ expect(shop.brand).toMatchObject({ name: "Ember & Oat", logo: expect.stringMatching(/^\/api\/files\//) });
+ expect(brand.listProducts(brandId).filter((x) => x.name === "Maple Pecan Granola")).toHaveLength(1);
const coll = await (await readRoute.POST(json("POST", { url: `${origin}/collections/skin`, limit: 2 }))).json();
expect(coll.products.map((p: { name: string }) => p.name)).toEqual(["Night Serum", "Day Cream"]);
@@ -202,10 +206,26 @@ describe("brand kits", () => {
const patched = await (await productRoute.PATCH(json("PATCH", { audience: "Sensitive skin", url: "dewtheory.example/cream" }), params({ id: p.id }))).json();
expect(patched).toMatchObject({ audience: "Sensitive skin", url: "https://dewtheory.example/cream" });
const unassigned = await (await productsRoute.GET(json("GET", undefined, "http://x/api/products?brand=none"))).json();
- expect(unassigned.items.map((x: { name: string }) => x.name)).toEqual(expect.arrayContaining(["Maple Pecan Granola", "Night Serum"]));
+ expect(unassigned.items.map((x: { name: string }) => x.name)).toEqual(expect.arrayContaining(["Night Serum", "Day Cream"]));
expect((await productRoute.DELETE(json("DELETE"), params({ id: p.id }))).status).toBe(204);
});
+ it("keeps a product page's logo and colours in the site's brand kit (made once, then matched by host)", () => {
+ const bits = { name: "Dew Theory", logo: upload("logo.png"), colors: ["#112233", "#445566"], fonts: { heading: "Fraunces" } };
+ const made = brand.kitForSite("https://www.dewtheory.example/products/barrier-cream", bits);
+ expect(made).toMatchObject({ name: "Dew Theory", website: "https://www.dewtheory.example/", status: "ready", logo: bits.logo, colors: bits.colors, fonts: { heading: "Fraunces" } });
+ expect(made.note).toMatch(/Made from a product page on dewtheory\.example/);
+ const again = brand.kitForSite("https://dewtheory.example/products/night-serum", { colors: ["#ffffff"], fonts: {} });
+ expect(again.id).toBe(made.id);
+ expect(again.colors).toEqual(bits.colors); // the kit's own colours win
+ // The kit reaches Click to Ad's video prompts through the product's brand.
+ const p = brand.createProduct({ name: "Barrier Cream", brandId: made.id, images: [upload()] });
+ const plan = mk.planClickToAd({ engine: "cloud", productId: p.id, styleId: "clean-minimal" }, { product: p, brand: brand.getBrand(made.id), script: "One two three four five six seven eight." });
+ expect(plan.meta.brandId).toBe(made.id);
+ expect(plan.steps.find((s) => s.key === "shot1")!.request.prompt).toMatch(/Brand: Dew Theory.*#112233/);
+ brand.deleteBrand(made.id);
+ });
+
it("plans Marketing Studio runs per format and engine", () => {
const b = brand.getBrand(brandId)!;
const product = brand.listProducts(brandId)[0];
diff --git a/tests/marketing-fixes.test.ts b/tests/marketing-fixes.test.ts
new file mode 100644
index 00000000..4fef8212
--- /dev/null
+++ b/tests/marketing-fixes.test.ts
@@ -0,0 +1,316 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+/**
+ * The review fixes of the marketing suite: open joins keep the voice, plans with a Higgsfield key,
+ * offline scripts that keep the call to action and the instructions, chat directions without "@"
+ * leftovers, a research bar that never goes back, and the sound-keeping join workflows bound for real.
+ */
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-marketing-fixes-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const mk = await import("@/server/marketing");
+const ads = await import("@/server/ads");
+const brand = await import("@/server/brand");
+const { saveFile } = await import("@/server/storage");
+const { prepareWorkflow, loadManifest } = await import("@/server/providers/comfyui");
+const cat = await import("@/lib/catalog/marketing");
+const { getModel } = await import("@/lib/catalog");
+
+const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(4000, 7)]);
+const upload = (name = "p.png") => saveFile({ data: PNG, contentType: "image/png", name, source: "upload" }).url;
+
+/** A tiny MP4 header: ftyp + moov with one video trak (and an audio trak when `sound`), enough for probeMedia. */
+function mp4(sound: boolean, w = 1080, h = 1920): Buffer {
+ const box = (type: string, ...body: Buffer[]) => {
+ const data = Buffer.concat(body);
+ const head = Buffer.alloc(8);
+ head.writeUInt32BE(8 + data.length);
+ head.write(type, 4, "latin1");
+ return Buffer.concat([head, data]);
+ };
+ const mvhd = (() => {
+ const b = Buffer.alloc(100);
+ b.writeUInt32BE(1000, 12); // timescale
+ b.writeUInt32BE(8000, 16); // 8 s
+ return box("mvhd", b);
+ })();
+ const trak = (handler: "vide" | "soun") => {
+ const hdlr = Buffer.alloc(24);
+ hdlr.write(handler, 8, "latin1");
+ const tkhd = Buffer.alloc(84);
+ if (handler === "vide") {
+ tkhd.writeUInt32BE(0x10000, 40); // identity matrix (not rotated)
+ tkhd.writeUInt32BE(0x10000, 56);
+ tkhd.writeUInt32BE(w << 16, 76);
+ tkhd.writeUInt32BE(h << 16, 80);
+ }
+ const mdhd = Buffer.alloc(24);
+ mdhd.writeUInt32BE(1000, 12);
+ mdhd.writeUInt32BE(8000, 16);
+ return box("trak", box("tkhd", tkhd), box("mdia", box("mdhd", mdhd), box("hdlr", hdlr)));
+ };
+ const ftyp = box("ftyp", Buffer.from("isom\0\0\0\0isomiso2mp41", "latin1"));
+ return Buffer.concat([ftyp, box("moov", mvhd, trak("vide"), ...(sound ? [trak("soun")] : []))]);
+}
+const clip = (sound: boolean, w?: number, h?: number) => saveFile({ data: mp4(sound, w, h), contentType: "video/mp4", name: sound ? "ad.mp4" : "silent.mp4", source: "upload" }).url;
+
+beforeAll(() => {
+ setSetting("demoMode", "auto");
+ setSetting("enhanceProvider", "none");
+});
+afterAll(() => {
+ setSetting("higgsfieldKey", "");
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
+const product = (over: Partial<import("@/lib/catalog/marketing").Product> = {}): import("@/lib/catalog/marketing").Product => ({
+ id: "p1",
+ brandId: null,
+ name: "Barrier Cream",
+ sellingPoints: ["Calms red, reactive skin overnight", "Fragrance-free and vegan"],
+ images: [upload()],
+ createdAt: 0,
+ updatedAt: 0,
+ ...over,
+});
+const SCRIPT = "Okay so this cream fixed my skin in a week and I am not even joking about it at all honestly.";
+
+// ---------------------------------------------------------------------------
+
+describe("open joins keep the voice", () => {
+ const filmOf = (plan: import("@/server/marketing").RunPlan) => plan.steps.find((s) => s.key === "film")!;
+
+ it("UGC with a hook: the presenter's own sound starts after the silent hook (sound of clip 2)", () => {
+ const plan = mk.planMarketing(
+ { engine: "open", format: "ugc-talking", templateId: "ugc-honest-review", hookId: "camera-bump", voiceSample: upload("v.png") },
+ { product: product(), higgsfield: false, script: SCRIPT },
+ );
+ const film = filmOf(plan);
+ expect(plan.finals).toEqual(["film"]);
+ expect(film.request.modelId).toBe(cat.OPEN_SOUND_JOIN.second);
+ // Clip order: hook, the captioned (voiced) presenter, the product close-up.
+ expect(film.after).toEqual(["hook", "captions", "broll"]);
+ // The voiced clip carries the TTS: talk takes the voice, captions take talk (and keep its sound).
+ expect(plan.steps.find((s) => s.key === "talk")!.after).toEqual(["still", "voice"]);
+ expect(plan.steps.find((s) => s.key === "captions")!.after).toEqual(["talk"]);
+ expect(getModel(film.request.modelId)!.routes[0].endpoint).toBe("video-concat-sound2-{n}");
+ expect(plan.notes.join(" ")).not.toMatch(/without the voiceover|without sound/);
+ });
+
+ it("UGC without a hook and Click to Ad's presenter: the first clip's sound from the start", () => {
+ const ugc = mk.planMarketing({ engine: "open", format: "ugc-talking", hookId: null, voiceSample: upload("v.png") }, { product: product(), higgsfield: false, script: SCRIPT });
+ expect(filmOf(ugc).request.modelId).toBe(cat.OPEN_SOUND_JOIN.first);
+ expect(filmOf(ugc).after).toEqual(["captions", "broll"]);
+ const c2a = mk.planClickToAd({ engine: "open", productId: "p1", styleId: "simple-ugc", voiceSample: upload("v.png"), quality: "720p" }, { product: product(), script: SCRIPT });
+ expect(filmOf(c2a).request).toMatchObject({ modelId: cat.OPEN_SOUND_JOIN.first, params: { aspectRatio: "9:16", resolution: "720p" } });
+ expect(filmOf(c2a).after).toEqual(["captions", "broll"]);
+ // Cloud keeps fal's merge (it keeps the clips' audio).
+ const cloud = mk.planClickToAd({ engine: "cloud", productId: "p1", styleId: "simple-ugc" }, { product: product(), script: SCRIPT });
+ expect(filmOf(cloud).request.modelId).toBe("join-clips");
+ });
+
+ it("Click to Ad product-only: joined first, the voice muxed on after the join, captions last", () => {
+ const plan = mk.planClickToAd({ engine: "open", productId: "p1", styleId: "clean-minimal", voiceSample: upload("v.png") }, { product: product(), script: SCRIPT });
+ const keys = plan.steps.map((s) => s.key);
+ expect(keys.indexOf("mux")).toBeGreaterThan(keys.indexOf("film"));
+ expect(plan.steps.find((s) => s.key === "mux")!.after).toEqual(["film", "voice"]);
+ expect(plan.finals).toEqual(["captions"]);
+ });
+
+ it("Ad Multiplier hook / CTA: the reference's own sound when it has one, the plain join otherwise", () => {
+ const base = { engine: "open" as const, video: upload("ref.png"), duration: 12, mode: "sections" as const, quality: "1080p" as const, firstFrame: upload("f.png"), lastFrame: upload("l.png") };
+ const both = mk.planMultiplier({ ...base, hook: "Wait", cta: "Shop" }, { higgsfield: false, referenceSound: true, referenceAspect: "9:16" });
+ const film = filmOf(both);
+ expect(film.request).toMatchObject({ modelId: cat.OPEN_SOUND_JOIN.second, inputs: { videos: [base.video] }, params: { aspectRatio: "9:16", resolution: "720p" } });
+ expect(both.steps.find((s) => s.key === "hook")!.request.params).toMatchObject({ aspectRatio: "9:16" });
+ const ctaOnly = mk.planMultiplier({ ...base, hook: null, cta: "Shop" }, { higgsfield: false, referenceSound: true });
+ expect(filmOf(ctaOnly).request.modelId).toBe(cat.OPEN_SOUND_JOIN.first);
+ const silent = mk.planMultiplier({ ...base, hook: "Wait", cta: null }, { higgsfield: false, referenceSound: false });
+ expect(filmOf(silent).request.modelId).toBe("oss-join-clips");
+ expect(silent.notes).toEqual([]);
+ const unknown = mk.planMultiplier({ ...base, hook: "Wait", cta: null }, { higgsfield: false });
+ expect(filmOf(unknown).request.modelId).toBe("oss-join-clips");
+ expect(unknown.notes.join(" ")).toMatch(/soundtrack couldn't be read/);
+ });
+
+ it("Ad Multiplier prompt mode: no 'Original sound' step for a silent reference", () => {
+ const base = { engine: "open" as const, video: upload("ref.png"), duration: 12, mode: "prompt" as const, quality: "720p" as const, images: [upload("star.png")], prompt: "Recreate with @image_1" };
+ expect(mk.planMultiplier(base, { higgsfield: false, referenceSound: true }).steps.map((s) => s.key)).toEqual(["edit", "sound"]);
+ const silent = mk.planMultiplier(base, { higgsfield: false, referenceSound: false });
+ expect(silent.steps.map((s) => s.key)).toEqual(["edit"]);
+ expect(silent.steps[0].request).toMatchObject({ feature: "ad-multiplier", title: silent.title });
+ });
+
+ it("reads the reference's sound and shape from its header (cached per file)", async () => {
+ expect(await mk.referenceFacts(clip(true))).toEqual({ sound: true, aspect: "9:16" });
+ expect(await mk.referenceFacts(clip(false, 1920, 1080))).toEqual({ sound: false, aspect: "16:9" });
+ expect(await mk.referenceFacts(upload("not-a-video.png"))).toEqual({ sound: null });
+ // Through the estimate: a voiced 9:16 reference keeps its sound on the open join.
+ const est = await mk.estimateMultiplier({ engine: "open", video: clip(true), duration: 8, mode: "sections", hook: "Wait", cta: null, quality: "720p", firstFrame: upload("f.png") });
+ expect(est.steps.find((s) => s.key === "film")!.modelId).toBe(cat.OPEN_SOUND_JOIN.second);
+ });
+});
+
+describe("the sound-keeping join workflows", () => {
+ it("are in the library, validated, and bind every clip, the size and the frame rate", async () => {
+ const byId = new Map(loadManifest().workflows.map((w) => [w.id, w]));
+ for (const id of ["video-concat-sound1-2", "video-concat-sound1-3", "video-concat-sound2-2", "video-concat-sound2-3"]) {
+ expect(byId.get(id)?.validated, id).toBe(true);
+ expect(byId.get(id)?.defaults.fps, id).toBe(25);
+ }
+ const res = await prepareWorkflow("video-concat-sound2-{n}", { videos: ["hook.mp4", "talk.mp4", "broll.mp4"], aspectRatio: "9:16", resolution: "480p" }, { generationId: "g1", op: "concat", upload: async (_d, _t, n) => n });
+ expect(res.manifest.id).toBe("video-concat-sound2-3");
+ const wf = res.workflow;
+ expect([wf["1"].inputs.video, wf["4"].inputs.video, wf["7"].inputs.video]).toEqual(["hook.mp4", "talk.mp4", "broll.mp4"]);
+ // Every clip is resampled to the film's rate; clip 1's length is the silence before clip 2's sound.
+ expect([wf["1"].inputs.force_rate, wf["4"].inputs.force_rate, wf["7"].inputs.force_rate, wf["21"].inputs.fps]).toEqual([25, 25, 25, 25]);
+ expect(wf["31"].inputs.duration).toEqual(["30", 2]);
+ expect(wf["32"].inputs).toMatchObject({ audio1: ["31", 0], audio2: ["4", 2], direction: "after" });
+ expect(wf["21"].inputs.audio).toEqual(["32", 0]);
+ const { width, height } = wf["2"].inputs as { width: number; height: number };
+ expect(width / height).toBeCloseTo(9 / 16, 1);
+ expect(wf["22"].inputs.filename_prefix).toBe("fuobe/g1");
+ const first = await prepareWorkflow("video-concat-sound1-{n}", { videos: ["talk.mp4", "broll.mp4"], aspectRatio: "9:16" }, { generationId: "g2", op: "concat", upload: async (_d, _t, n) => n });
+ expect(first.manifest.id).toBe("video-concat-sound1-2");
+ expect(first.workflow["21"].inputs.audio).toEqual(["1", 2]);
+ });
+});
+
+// ---------------------------------------------------------------------------
+
+describe("plans with a Higgsfield key", () => {
+ it("Ads Studio goes one-shot through Higgsfield's ads-studio; the Multiplier defaults to Seedance 2.5 edit", () => {
+ setSetting("higgsfieldKey", "key:secret");
+ try {
+ expect(ads.batchRoute({ engine: "cloud" })).toBe("higgsfield");
+ expect(ads.batchRoute({ engine: "cloud", route: "fuobe" })).toBe("fuobe");
+ expect(ads.batchRoute({ engine: "open", route: "higgsfield" })).toBe("fuobe");
+ const kit = brand.kitForSite("https://hf.example/p/1", { name: "HF Brand", colors: ["#123456"], fonts: {} });
+ const req = ads.higgsfieldRequest(product(), kit, "9:16", "winter sale", 3);
+ expect(req).toMatchObject({ modelId: "ads-studio", op: "edit", params: { aspectRatio: "9:16", numOutputs: 1 } });
+ expect(req.prompt).toMatch(/Direction: winter sale/);
+ const model = mk.multiplierModel({ engine: "cloud" }, true);
+ expect(model.id).toBe("seedance-2-5");
+ const plan = mk.planMultiplier({ engine: "cloud", video: upload("ref.png"), duration: 10, mode: "prompt", quality: "720p" }, { higgsfield: true });
+ expect(plan.steps[0].request).toMatchObject({ modelId: "seedance-2-5", op: "v2v" });
+ expect(model.routes.some((r) => r.op === "v2v" && r.provider === "higgsfield")).toBe(true);
+ expect(plan.notes.join(" ")).not.toMatch(/connect a Higgsfield key/);
+ brand.deleteBrand(kit.id);
+ } finally {
+ setSetting("higgsfieldKey", "");
+ }
+ expect(ads.batchRoute({ engine: "cloud" })).toBe("fuobe");
+ expect(mk.multiplierModel({ engine: "cloud" }, false).id).toBe("kling-o3");
+ });
+
+ it("says the rules write the copy when no LLM is reachable", () => {
+ const kit = brand.kitForSite("https://copy.example/p/1", { name: "Copy Co", colors: [], fonts: {} });
+ const p = brand.createProduct({ name: "Mug", brandId: kit.id, images: [upload()] });
+ const est = ads.estimateBatch({ brandId: kit.id, engine: "cloud", items: [{ productId: p.id, count: 2 }] });
+ expect(est.demo).toBe(true);
+ expect(est.copyBy).toBe("rules");
+ brand.deleteBrand(kit.id);
+ });
+
+ it("lists a batch's ads in the order they were asked for, newest batch first", async () => {
+ const kit = brand.kitForSite("https://order.example/p/1", { name: "Order Co", colors: [], fonts: {} });
+ const a = brand.createProduct({ name: "First", brandId: kit.id, images: [upload()] });
+ const b = brand.createProduct({ name: "Second", brandId: kit.id, images: [upload()] });
+ const one = ads.createBatch({ brandId: kit.id, engine: "open", items: [{ productId: a.id, count: 2 }, { productId: b.id, count: 1 }] });
+ await one.run;
+ await new Promise((r) => setTimeout(r, 5));
+ const two = ads.createBatch({ brandId: kit.id, engine: "open", items: [{ productId: b.id, count: 1 }] });
+ await two.run;
+ const list = ads.listCreatives({ brandId: kit.id });
+ expect(list.map((c) => [c.batchId, c.productId, c.position])).toEqual([
+ [two.batchId, b.id, 0],
+ [one.batchId, a.id, 0],
+ [one.batchId, a.id, 1],
+ [one.batchId, b.id, 2],
+ ]);
+ brand.deleteBrand(kit.id);
+ });
+});
+
+// ---------------------------------------------------------------------------
+
+describe("offline scripts keep the call to action and the instructions", () => {
+ const p = product({ name: "Barrier Cream" });
+ const words = (s: string) => s.split(/\s+/).filter(Boolean).length;
+
+ it.each([8, 11.4, 12, 15])("at %s s", (seconds) => {
+ const s = mk.heuristicScript({ product: p, seconds, instructions: "mention free shipping over $40" });
+ expect(words(s)).toBeLessThanOrEqual(cat.wordBudget(seconds));
+ expect(s).toContain("Free shipping over $40.");
+ expect(s).toMatch(/(Go try it for yourself|Go try it today)\.$/);
+ expect(s).not.toMatch(/Honestly\?$/);
+ });
+
+ it("ends on the brand's link when it has a website, and trims long instructions instead of the end", () => {
+ const b = { ...cat.emptyKit("Dew Theory"), website: "https://dew.example/" } as import("@/lib/catalog/marketing").BrandKit;
+ expect(mk.heuristicScript({ product: p, brand: b, seconds: 12 })).toMatch(/link's in my bio\.$/i);
+ const long = mk.heuristicScript({ product: p, seconds: 8, instructions: "say that it is fragrance free and vegan and made with ceramides and oat extract and that dermatologists helped make it for reactive skin" });
+ expect(words(long)).toBeLessThanOrEqual(cat.wordBudget(8));
+ expect(long).toMatch(/Go try it today\.$/);
+ expect(long).toMatch(/It is fragrance free/);
+ });
+
+ it("turns instructions into lines to say", () => {
+ expect(mk.spokenInstructions("highlight eco-friendly materials, mention free shipping")).toEqual(["Eco-friendly materials.", "Free shipping."]);
+ expect(mk.spokenInstructions("it saved my 7 a.m. meetings")).toEqual(["It saved my 7 a.m. meetings."]);
+ expect(mk.spokenInstructions("Please mention that it ships free; focus on the scent")).toEqual(["It ships free.", "The scent."]);
+ expect(mk.spokenInstructions(" ")).toEqual([]);
+ });
+
+ it("fitScript drops middle sentences before the closing call to action", () => {
+ const s = "This is the opening line about the cream. Here is a long middle sentence that goes on and on about texture. Another middle bit. Shop now at the link.";
+ const out = cat.fitScript(s, 6); // 15 words
+ expect(out.endsWith("Shop now at the link.")).toBe(true);
+ expect(out.split(" ").length).toBeLessThanOrEqual(15);
+ expect(out.startsWith("This is the opening line")).toBe(true);
+ // Fits already: unchanged.
+ expect(cat.fitScript("Short and sweet.", 8)).toBe("Short and sweet.");
+ });
+
+ it("sizes a UGC script to the talking part: the length minus the hook and the close-up", () => {
+ const shot = cat.snapDuration(4, getModel(cat.UGC_MODELS.cloud.clip)!.options.durations);
+ expect(mk.presenterSeconds({ engine: "cloud", format: "ugc-talking", duration: 20, hookId: "camera-bump" }, { product: product() })).toBe(20 - 2 * shot);
+ expect(mk.presenterSeconds({ engine: "cloud", format: "ugc-talking", duration: 20, hookId: null }, { product: null })).toBe(20);
+ expect(mk.presenterSeconds({ engine: "cloud", format: "tiktok", duration: 8, hookId: "camera-bump" }, { product: product() })).toBe(5);
+ });
+});
+
+describe("chat directions", () => {
+ const products = [
+ { id: "a", name: "Night Serum" },
+ { id: "b", name: "Day Cream" },
+ ];
+ it("drop a stray '@' and the words left dangling by a mention", () => {
+ expect(ads.offlineProposal("Make five playful ads for @ @Night Serum", products)).toEqual({ count: 5, productIds: ["a"], direction: "playful" });
+ expect(ads.offlineProposal("Make 2 ads for @Nght with a holiday theme", products)).toEqual({ count: 2, productIds: [], direction: "with a holiday theme" });
+ expect(ads.offlineProposal("3 bold ads of @Day Cream and @Night Serum", products)?.direction).toBe("bold");
+ expect(ads.offlineProposal("Make 4 ads for @Night Serum with a holiday theme", products)?.direction).toBe("with a holiday theme");
+ });
+});
+
+describe("research progress", () => {
+ it("never goes back while the writing-stage labels rotate", () => {
+ const p = { index: cat.LLM_STAGE.from, startedAt: 0 };
+ let last = 0;
+ for (let t = 0; t < 120_000; t += 700) {
+ const v = cat.researchProgress(p, t);
+ expect(v).toBeGreaterThanOrEqual(last);
+ last = v;
+ }
+ expect(last).toBeLessThan(cat.researchProgress({ index: 11, startedAt: 0 }, 0));
+ expect(cat.researchProgress({ index: 0, startedAt: 0 }, 0)).toBeCloseTo(100 / cat.RESEARCH_LABELS.length);
+ expect(cat.researchProgress(null, 0)).toBeGreaterThan(0);
+ });
+});
diff --git a/tests/marketing-scrape.test.ts b/tests/marketing-scrape.test.ts
index a2d4d06d..0449d6c8 100644
--- a/tests/marketing-scrape.test.ts
+++ b/tests/marketing-scrape.test.ts
@@ -113,7 +113,9 @@ describe("products", () => {
images: ["https://emberandoat.example/cdn/shop/products/maple-pecan.jpg", "https://cdn.example-shop.com/maple-pecan-2.jpg"],
brand: "Ember & Oat",
});
- expect(ps[0].description).toBe("Crunchy clusters of organic oats, Oregon pecans and dark maple syrup. Vegan and gluten-free Only 6 grams of sugar per serving");
+ // List items stay on their own lines, so each becomes its own selling point.
+ expect(ps[0].description).toBe("Crunchy clusters of organic oats, Oregon pecans and dark maple syrup.\nVegan and gluten-free\nOnly 6 grams of sugar per serving");
+ expect(sellingPointsFrom(ps[0].description)).toEqual(["Crunchy clusters of organic oats, Oregon pecans and dark maple syrup", "Vegan and gluten-free", "Only 6 grams of sugar per serving"]);
expect(ps[1].price).toBe(9);
// A single product's JSON (/products/<handle>.json) has the same shape under "product".
expect(shopifyProducts({ product: { title: "One", images: [] } }, "https://x.example")[0].name).toBe("One");