The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Click to Ad: the ad can end on a logo card, on both engines
Claudeb04193cd4c78
diff --git a/src/lib/catalog/marketing.ts b/src/lib/catalog/marketing.tsindex 854967c0..faaa5f5f 100644--- a/src/lib/catalog/marketing.ts+++ b/src/lib/catalog/marketing.ts@@ -1,4 +1,4 @@-import type { Engine, Generation } from "./types";+import type { ChainSlot, Engine, Generation, GenerationRequest } from "./types";/*** Marketing Studio, Ads Studio, Ad Multiplier and Click to Ad: the shared catalog (formats,@@ -581,6 +581,114 @@ export const styleById = (id?: string | null) => AD_STYLES.find((s) => s.id ===/** Click to Ad makes a 9:16 ad of at most 12 seconds. */export const CLICK_TO_AD = { aspect: "9:16", maxSeconds: 12, shots: 3 } as const;+// ---------------------------------------------------------------------------+// The logo end card a Click to Ad video ends on++/**+ * The card is drawn in the browser (brand colour, logo, product name, CTA; components/marketing/end-card.ts)+ * at the ad's 9:16 size, then held for 2–3 s: a gentle push-in on the cloud (fal image-to-video, zoom 1 → 1.05),+ * a still on the open engine. Without a drawn card the cloud puts the logo on the brand colour itself.+ */+export const END_CARD = { seconds: 2.5, minSeconds: 2, maxSeconds: 3, zoomTo: 1.05, fps: 24, size: { w: 720, h: 1280 }, cta: "Shop now" } as const;++export const END_CARD_MODELS = {+ cloud: { art: "overlay-image", clip: "ken-burns", join: "join-clips" },+ open: { append: "oss-append-endcard", clip: "oss-still-to-clip", join: "oss-join-sound1" },+} as const;++export interface EndCardStep {+ key: string;+ label: string;+ request: GenerationRequest;+ after?: string[];+ chain?: ChainSlot[];+}++export interface EndCardInput {+ engine: Engine;+ /** The step whose clip the card follows (the finished ad). */+ ad: string;+ /** The card the page drew (/api/files/…). */+ card?: string;+ /** Cloud, no drawn card: the brand-colour background and the logo overlay-image puts on it. */+ background?: string;+ logo?: string;+ seconds?: number;+ feature: string;+ title: string;+ aspectRatio: string;+ resolution?: string;+ /**+ * Open engine: who encoded the ad. video-append-endcard copies the ad's packets and only takes clips ComfyUI+ * encoded (every open step does); others get still-to-clip + the join that keeps the first clip's sound.+ */+ adEncodedBy?: "comfyui" | "other";+}++/**+ * The steps that make the end card and put it after the ad, and the key of the finished video. Cloud:+ * [overlay-image: the logo on the brand colour →] ken-burns (zoom 1 → 1.05) → merge-videos after the ad.+ * Open: video-append-endcard (the ad's sound kept, padded with silence under the card), or still-to-clip ++ * oss-join-sound1 for a clip the open engine didn't make.+ */+export function endCardSteps(o: EndCardInput): { steps: EndCardStep[]; final: string } {+ const seconds = Math.max(END_CARD.minSeconds, Math.min(END_CARD.maxSeconds, o.seconds ?? END_CARD.seconds));+ const result = { feature: o.feature, title: o.title, batchTitle: o.title };+ const helper = { feature: `${o.feature}-step` };+ if (o.engine === "open") {+ if (!o.card) throw new Error("The open engine needs the end card drawn on the page — turn End card off, or make the ad from Click to Ad");+ const M = END_CARD_MODELS.open;+ if ((o.adEncodedBy ?? "comfyui") === "comfyui") {+ return {+ final: "endcard",+ steps: [+ {+ key: "endcard",+ label: "End card",+ request: { ...result, modelId: M.append, op: "concat", prompt: o.title, inputs: { images: [o.card] }, params: { duration: seconds } },+ after: [o.ad],+ chain: [{ slot: "video" }],+ },+ ],+ };+ }+ return {+ final: "endcard",+ steps: [+ { key: "endcardClip", label: "End card", request: { ...helper, modelId: M.clip, op: "still-motion", inputs: { images: [o.card] }, params: { duration: seconds, fps: 25, aspectRatio: o.aspectRatio, ...(o.resolution && { resolution: o.resolution }) } } },+ {+ key: "endcard",+ label: "Adding the end card",+ request: { ...result, modelId: M.join, op: "concat", prompt: o.title, params: { aspectRatio: o.aspectRatio, ...(o.resolution && { resolution: o.resolution }) } },+ after: [o.ad, "endcardClip"],+ chain: [{ slot: "videos" }, { slot: "videos" }],+ },+ ],+ };+ }+ const M = END_CARD_MODELS.cloud;+ const steps: EndCardStep[] = [];+ if (!o.card) {+ if (!o.background || !o.logo) throw new Error("Add a logo to the brand kit for the end card, or turn End card off");+ steps.push({ key: "endcardArt", label: "End card", request: { ...helper, modelId: M.art, op: "overlay", inputs: { images: [o.background, o.logo] }, params: { position: { x: 0.5, y: 0.45 }, scale: 1 } } });+ }+ const move = { duration: seconds, fps: END_CARD.fps, zoomFrom: 1, zoomTo: END_CARD.zoomTo, panFrom: { x: 0.5, y: 0.5 }, panTo: { x: 0.5, y: 0.5 }, easing: "ease-in-out" as const };+ steps.push({+ key: "endcardClip",+ label: "End card motion",+ request: { ...helper, modelId: M.clip, op: "still-motion", ...(o.card ? { inputs: { images: [o.card] } } : {}), params: move },+ ...(o.card ? {} : { after: ["endcardArt"], chain: [{ slot: "images" as const }] }),+ });+ steps.push({+ key: "endcard",+ label: "Adding the end card",+ request: { ...result, modelId: M.join, op: "concat", prompt: o.title, params: { aspectRatio: o.aspectRatio } },+ after: [o.ad, "endcardClip"],+ chain: [{ slot: "videos" }, { slot: "videos" }],+ });+ return { steps, final: "endcard" };+}+// ---------------------------------------------------------------------------// Ads Studio@@ -913,6 +1021,8 @@ export interface MarketingRunMeta {notes?: string[];/** What the run was made from, so "Run again" can repeat it. */input?: Record<string, unknown>;+ /** Click to Ad: the logo end card it ends on (the card the page drew; null: the kit's logo on its colour). */+ endCard?: string | null;}export interface MarketingRun {diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.tsindex 0f7de344..e46767d3 100644--- a/src/lib/catalog/models.ts+++ b/src/lib/catalog/models.ts@@ -1469,6 +1469,31 @@ const local: ModelDef[] = [defaults: { aspectRatio: "9:16", resolution: "480p" },hidden: true,}),+ // Click to Ad's logo end card (r4/marketing-mixed): core nodes, no model, CPU.+ o({+ id: "oss-append-endcard",+ name: "Append end card",+ vendor: "ComfyUI",+ family: "utility",+ kind: "video",+ tagline: "Ends an ad on a still (its logo card) and keeps the ad's sound; the ad's picture is copied, not re-encoded · CPU",+ routes: [comfy("concat", "video-append-endcard", "the ad (inputs.video) + the card (images[0]) at the ad's own size and frame rate; only for clips the open engine made")],+ options: { maxImages: 1, promptless: true },+ defaults: { duration: 2.5 },+ hidden: true,+ }),+ o({+ id: "oss-still-to-clip",+ name: "Still to clip",+ vendor: "ComfyUI",+ family: "utility",+ kind: "video",+ tagline: "Holds a still (an end card) for a few seconds, with a silent sound track · no model, CPU",+ routes: [comfy("still-motion", "still-to-clip", "centre-cropped to the clip size; joined after clips the open engine didn't make")],+ options: { aspectRatios: VID_AR, resolutions: ["480p", "720p", "1080p"], maxImages: 1, promptless: true },+ defaults: { aspectRatio: "9:16", resolution: "480p", duration: 2.5 },+ hidden: true,+ }),o({id: "oss-join-sound2",name: "Join clips (keep the second clip's sound)",diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.tsindex 46f2b694..039a8a26 100644--- a/src/lib/catalog/plan.ts+++ b/src/lib/catalog/plan.ts@@ -392,7 +392,9 @@ export function missingInputs(op: Operation, req: Pick<GenerationRequest, "inputconst i = req.inputs ?? {};if (n.images && (i.images?.length ?? 0) < n.images) return n.msg;if (n.video && !i.video) return n.msg;- if (n.videos && (i.videos?.length ?? 0) < n.videos) return n.msg;+ // A join may also be one clip and a still appended after it (an ad and its end card).+ const clips = (i.videos?.length ?? 0) + (op === "concat" && i.video && i.images?.length ? 2 : 0);+ if (n.videos && clips < n.videos) return n.msg;if (n.audio && !i.audio) return n.msg;if (n.audios && (i.audios?.length ?? 0) < n.audios) return n.msg;if (n.endImage && !i.endImage) return n.msg;diff --git a/src/lib/comfy.ts b/src/lib/comfy.tsindex edaaf34b..ae40af38 100644--- a/src/lib/comfy.ts+++ b/src/lib/comfy.ts@@ -582,6 +582,32 @@ export function dropVhsAudio(wf: ComfyWorkflow): ComfyWorkflow {}return out;}+/**+ * A silent clip read by core LoadAudio (video-append-endcard reads the ad's sound from the same upload): LoadAudio+ * stops with "No audio stream found in the file". The loaders go, with the sound nodes fed only by them (the card's+ * silence and the AudioConcat), and the inputs of the picture nodes that took that sound (ConcatenateVideo's+ * complete_audio), so the result has no sound track. `loaders` are the LoadAudio node ids; `keep` the output nodes.+ */+export function dropLoadedSound(wf: ComfyWorkflow, loaders: string[], keep: string[]): ComfyWorkflow {+ const gone = new Set(loaders.filter((id) => wf[id]?.class_type === "LoadAudio"));+ if (!gone.size) return wf;+ const out = cloneWorkflow(wf);+ const isSound = (cls: string) => /audio/i.test(cls) && !/video/i.test(cls);+ for (let grew = true; grew; ) {+ grew = false;+ for (const [id, n] of Object.entries(out)) {+ if (gone.has(id) || !isSound(n.class_type)) continue;+ if (Object.values(n.inputs).some((v) => isLinkValue(v) && gone.has(v[0]))) {+ gone.add(id);+ grew = true;+ }+ }+ }+ for (const n of Object.values(out)) for (const [k, v] of Object.entries(n.inputs)) if (isLinkValue(v) && gone.has(v[0])) delete n.inputs[k];+ for (const id of gone) delete out[id];+ return dropUnused(out, keep);+}+/** Codes people use that Whisper spells differently. */const WHISPER_ALIASES: Record<string, string> = { fil: "tl", jv: "jw", iw: "he", nb: "no", zh_hans: "zh" };diff --git a/src/server/marketing.ts b/src/server/marketing.tsindex 7f7f1323..118982f0 100644--- a/src/server/marketing.ts+++ b/src/server/marketing.ts@@ -7,6 +7,8 @@ import {brandLine,CLICK_TO_AD,cueLines,+ END_CARD,+ endCardSteps,estimateCues,fitScript,FORMATS,@@ -49,7 +51,8 @@ import { llmText } from "./enhance";import { createGenerations, getGeneration, listGenerations, previewChained, recordLocalGeneration } from "./generations";import { provider } from "./providers";import { engineMode } from "./settings";-import { readRef } from "./storage";+import { encodePng } from "./png";+import { readRef, saveFile } from "./storage";/*** Marketing Studio (templates → product shots, posters, ads, product motion, UGC presenters),@@ -104,6 +107,11 @@ export const ClickToAdBody = z.object({voice: z.string().max(80).optional(),voiceSample: FILE.optional(),avatar: FILE.optional(),+ /**+ * End on the brand: a logo card after the ad, held 2–3 s. `image` is the card the page drew (brand colour,+ * logo, product name, CTA); without it the cloud puts the kit's logo on its main colour (the open engine needs it).+ */+ endCard: z.object({ image: FILE.optional(), seconds: z.number().min(END_CARD.minSeconds).max(END_CARD.maxSeconds).optional() }).optional(),});export type ClickToAdInput = z.infer<typeof ClickToAdBody>;@@ -645,7 +653,48 @@ export function clickToAdSeconds(engine: Engine, presenter: boolean): { voice: nreturn { voice: Math.max(4, Math.min(CLICK_TO_AD.maxSeconds, shots.reduce((a, b) => a + b, 0)) - 0.6), broll: 0 };}-export function planClickToAd(input: ClickToAdInput, ctx: { product: Product; brand?: BrandKit | null; script: string }): RunPlan {+/** A raster logo overlay-image can place (an SVG can't be read there), else undefined. */+const rasterLogo = (brand?: BrandKit | null) => (brand?.logo && !isSvg(brand.logo) ? brand.logo : undefined);++/**+ * The ad, then its logo end card: the ad's last step becomes a helper and the card's join is the result+ * (endCardSteps: cloud ken-burns + merge-videos, open video-append-endcard).+ */+function withEndCard(plan: RunPlan, input: ClickToAdInput, ctx: { brand?: BrandKit | null; background?: string }): RunPlan {+ if (!input.endCard) return plan;+ const ad = plan.finals[0];+ const card = endCardSteps({+ engine: plan.engine,+ ad,+ card: input.endCard.image,+ background: ctx.background,+ logo: rasterLogo(ctx.brand),+ seconds: input.endCard.seconds,+ feature: plan.feature,+ title: plan.title,+ aspectRatio: CLICK_TO_AD.aspect,+ resolution: input.quality ?? "480p",+ });+ const steps = plan.steps.map((s) => {+ if (s.key !== ad) return s;+ const request = { ...s.request, feature: `${plan.feature}-step` };+ delete request.title;+ return { ...s, request };+ });+ const seconds = Math.max(END_CARD.minSeconds, Math.min(END_CARD.maxSeconds, input.endCard.seconds ?? END_CARD.seconds));+ const notes = [...plan.notes, `Ends on your logo card for ${seconds} s${input.endCard.image ? "" : " (the kit's logo on its main colour)"}`];+ return { ...plan, steps: [...steps, ...card.steps], finals: [card.final], meta: { ...plan.meta, endCard: input.endCard.image ?? null }, notes };+}++export function planClickToAd(input: ClickToAdInput, ctx: { product: Product; brand?: BrandKit | null; script: string; background?: string }): RunPlan {+ try {+ return withEndCard(planAd(input, ctx), input, ctx);+ } catch (e) {+ throw e instanceof PlanError ? e : new PlanError((e as Error).message);+ }+}++function planAd(input: ClickToAdInput, ctx: { product: Product; brand?: BrandKit | null; script: string }): RunPlan {const style = styleById(input.styleId);if (!style) throw new PlanError("Pick a style");const images = input.images?.length ? input.images : ctx.product.images;@@ -1023,7 +1072,17 @@ export function estimateClickToAd(input: ClickToAdInput): RunEstimate {const ctx = context({ productId: input.productId });const presenter = input.presenter ?? styleById(input.styleId)?.presenter ?? false;const script = input.script?.trim() || Array(wordBudget(clickToAdSeconds(input.engine, presenter).voice)).fill("word").join(" ");- return estimatePlan(planClickToAd(input, { product: ctx.product!, brand: ctx.brand, script }));+ return estimatePlan(planClickToAd(input, { product: ctx.product!, brand: ctx.brand, script, background: "/api/files/placeholder.png" }));+}++/** The end card's background when the page drew none: the kit's main colour at the card's size (cloud: the logo goes on it). */+function cardBackground(brand?: BrandKit | null): string {+ const hex = brand?.colors.find((c) => /^#[0-9a-f]{6}$/i.test(c)) ?? "#141414";+ const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16));+ const { w, h } = END_CARD.size;+ const data = Buffer.alloc(w * h * 4);+ for (let i = 0; i < data.length; i += 4) data.set([r, g, b, 255], i);+ return saveFile({ data: encodePng({ width: w, height: h, data }), contentType: "image/png", source: "generation", name: "end-card-background.png" }).url;}export async function clickToAdScript(input: Pick<ClickToAdInput, "engine" | "productId" | "styleId" | "presenter" | "instructions">): Promise<{ script: string; by: "llm" | "rules"; seconds: number }> {@@ -1040,7 +1099,10 @@ export async function runClickToAd(input: ClickToAdInput): Promise<{ run: Marketconst presenter = input.presenter ?? styleById(input.styleId)?.presenter ?? false;const seconds = clickToAdSeconds(input.engine, presenter).voice;const script = input.script?.trim() ? fitScript(input.script, seconds) : (await clickToAdScript(input)).script;- const plan = planClickToAd(input, { product: ctx.product, brand: ctx.brand, script });+ // Checked first with a stand-in, so a plan that can't run writes no file.+ const fallback = input.endCard && !input.endCard.image && input.engine === "cloud";+ if (fallback) planClickToAd(input, { product: ctx.product, brand: ctx.brand, script, background: "/api/files/placeholder.png" });+ const plan = planClickToAd(input, { product: ctx.product, brand: ctx.brand, script, background: fallback ? cardBackground(ctx.brand) : undefined });estimatePlan(plan);return { run: launch(plan, { ...input, script }), script };}diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex b807e535..92ab659f 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -12,6 +12,7 @@ import {bypassReference,computeDimensions,computeFrames,+ dropLoadedSound,dropVhsAudio,expandCaptionWorkflow,explainComfyError,@@ -724,6 +725,12 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,values.width = Math.max(multiple, Math.floor((dims.width * k) / multiple) * multiple);values.height = Math.max(multiple, Math.floor((dims.height * k) / multiple) * multiple);}+ // An end card appended to an ad (video-append-endcard): the card is encoded at the ad's own size and frame rate,+ // so the ad's packets are copied as they are. Only the ad's header knows them.+ if (manifest.id === "video-append-endcard") {+ if (!clip?.width || !clip.height || !clip.fps) throw new ProviderError("Couldn't read the ad's size and frame rate, so the end card can't be added");+ Object.assign(values, { width: clip.width, height: clip.height, fps: Math.round(clip.fps * 1000) / 1000 });+ }if (b.frames && span) values.frames = computeFrames(span, fps, Number(d.frameStep ?? 4), manifest.limits?.maxFrames);// Lip re-sync runs as long as the new voice; a voice past the frame cap is refused, not cut.const voiceLength = ctx.op === "lipsync" && b.frames && !span ? ctx.media?.(String(values.audio ?? ""))?.duration : undefined;@@ -907,7 +914,11 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,if (finish.dropSound) for (const n of Object.values(wf)) if (n.class_type === "CreateVideo") delete n.inputs.audio;// VHS meta-batch: a manager of its own per job (a stale one loses frames), and no sound link for a silent clip.wf = tagMetaBatch(wf, ctx.generationId);- if (clip && !clip.hasAudio && clip.hasVideo) wf = dropVhsAudio(wf);+ if (clip && !clip.hasAudio && clip.hasVideo) {+ wf = dropVhsAudio(wf);+ // Core LoadAudio reading the clip's own sound (the end card's ad): no sound, no sound track.+ wf = dropLoadedSound(wf, (b.video ?? []).filter((t) => t.input === "audio").map((t) => t.node), outputIds);+ }if (manifest.expand === "captions") {if (!cues.length) throw new ProviderError("No timed captions to burn in. Transcribe the clip first, or write lines like “0.00-2.40: Hello there”");try {diff --git a/tests/marketing-endcard.test.ts b/tests/marketing-endcard.test.tsnew file mode 100644index 00000000..9dc32f60--- /dev/null+++ b/tests/marketing-endcard.test.ts@@ -0,0 +1,190 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import type { BrandKit, Product } from "@/lib/catalog/marketing";+import type { Generation, GenInput } from "@/lib/catalog/types";+import type { ComfyWorkflow, ManifestWorkflow } from "@/lib/comfy";+import type { MediaInfo } from "@/lib/media-probe";++// Click to Ad's logo end card (r4/marketing-mixed): the plan per engine (cloud ken-burns + merge-videos,+// open video-append-endcard or still-to-clip + the sound-keeping join), how it hangs off the ad, a demo run,+// and the two open workflows bound through the ComfyUI provider.++vi.setConfig({ testTimeout: 90_000 });++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-endcard-"));+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 gens = await import("@/server/generations");+const { saveFile } = await import("@/server/storage");+const { prepareWorkflow } = await import("@/server/providers/comfyui");+const { getModel } = await import("@/lib/catalog");+const { END_CARD, END_CARD_MODELS, endCardSteps } = await import("@/lib/catalog/marketing");++beforeAll(() => setSetting("demoMode", "auto"));+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(400, 7)]);+const upload = (name = "p.png") => saveFile({ data: PNG, contentType: "image/png", name, source: "upload" }).url;+const product = (): Product => ({ id: "p1", brandId: null, name: "Barrier Cream", sellingPoints: ["Calms red skin overnight"], images: [upload()], createdAt: 0, updatedAt: 0 });+const kit = (over: Partial<BrandKit> = {}): BrandKit =>+ ({ id: "b1", name: "Dermaco", colors: ["#c1121f", "#fdf0d5"], fonts: {}, values: [], aesthetics: [], tone: [], sellingPoints: [], competitors: [], socials: [], images: [], details: [], status: "ready", source: "manual", createdAt: 0, updatedAt: 0, ...over }) as BrandKit;+const SCRIPT = "Okay so this cream fixed my skin in a week and I am not even joking about it at all honestly.";++async function settle(id: string, ms = 80_000): Promise<Generation> {+ const end = Date.now() + ms;+ for (;;) {+ const g = gens.getGeneration(id)!;+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;+ if (Date.now() > end) throw new Error(`timed out: ${g.status} ${g.message}`);+ await new Promise((r) => setTimeout(r, 250));+ }+}++describe("the end card's steps per engine", () => {+ const base = { ad: "captions", feature: "click-to-ad", title: "Clean Minimal · Barrier Cream", aspectRatio: "9:16", resolution: "480p" };++ it("uses real, hidden models", () => {+ for (const id of [...Object.values(END_CARD_MODELS.cloud), ...Object.values(END_CARD_MODELS.open)]) expect(getModel(id), id).toBeDefined();+ for (const id of ["overlay-image", "ken-burns", "oss-append-endcard", "oss-still-to-clip"]) expect(getModel(id)!.hidden, id).toBe(true);+ expect(getModel("oss-append-endcard")!.routes).toEqual([expect.objectContaining({ op: "concat", provider: "comfyui", endpoint: "video-append-endcard" })]);+ expect(getModel("oss-still-to-clip")!.routes).toEqual([expect.objectContaining({ op: "still-motion", provider: "comfyui", endpoint: "still-to-clip" })]);+ });++ it("cloud: the drawn card → a 2.5 s push-in (zoom 1 → 1.05) → merge-videos after the ad", () => {+ const { steps, final } = endCardSteps({ ...base, engine: "cloud", card: "/api/files/card.png" });+ expect(final).toBe("endcard");+ expect(steps.map((s) => s.key)).toEqual(["endcardClip", "endcard"]);+ expect(steps[0].request).toMatchObject({+ feature: "click-to-ad-step",+ modelId: "ken-burns",+ op: "still-motion",+ inputs: { images: ["/api/files/card.png"] },+ params: { duration: 2.5, fps: 24, zoomFrom: 1, zoomTo: 1.05, easing: "ease-in-out" },+ });+ expect(steps[1]).toMatchObject({ after: ["captions", "endcardClip"], chain: [{ slot: "videos" }, { slot: "videos" }], request: { feature: "click-to-ad", title: base.title, modelId: "join-clips", op: "concat" } });+ });++ it("cloud without a drawn card: overlay-image puts the logo on the brand colour first", () => {+ const { steps } = endCardSteps({ ...base, engine: "cloud", background: "/api/files/bg.png", logo: "/api/files/logo.png", seconds: 9 });+ expect(steps.map((s) => s.key)).toEqual(["endcardArt", "endcardClip", "endcard"]);+ expect(steps[0].request).toMatchObject({ modelId: "overlay-image", op: "overlay", inputs: { images: ["/api/files/bg.png", "/api/files/logo.png"] }, params: { position: { x: 0.5, y: 0.45 }, scale: 1 } });+ expect(steps[1]).toMatchObject({ after: ["endcardArt"], chain: [{ slot: "images" }], request: { params: { duration: 3 } } });+ expect(steps[1].request.inputs).toBeUndefined();+ expect(() => endCardSteps({ ...base, engine: "cloud" })).toThrow(/Add a logo to the brand kit/);+ });++ it("open: the card appended to the ad keeping its sound, or still-to-clip + the join that keeps the first clip's sound", () => {+ const own = endCardSteps({ ...base, engine: "open", card: "/api/files/card.png", seconds: 1 });+ expect(own.steps).toHaveLength(1);+ expect(own.steps[0]).toMatchObject({+ key: "endcard",+ after: ["captions"],+ chain: [{ slot: "video" }],+ request: { feature: "click-to-ad", title: base.title, modelId: "oss-append-endcard", op: "concat", inputs: { images: ["/api/files/card.png"] }, params: { duration: 2 } },+ });+ const foreign = endCardSteps({ ...base, engine: "open", card: "/api/files/card.png", adEncodedBy: "other" });+ expect(foreign.steps.map((s) => s.request.modelId)).toEqual(["oss-still-to-clip", "oss-join-sound1"]);+ expect(foreign.steps[0].request.params).toMatchObject({ duration: END_CARD.seconds, fps: 25, aspectRatio: "9:16", resolution: "480p" });+ expect(foreign.steps[1]).toMatchObject({ after: ["captions", "endcardClip"], request: { feature: "click-to-ad", params: { aspectRatio: "9:16", resolution: "480p" } } });+ expect(() => endCardSteps({ ...base, engine: "open" })).toThrow(/needs the end card drawn on the page/);+ });+});++describe("Click to Ad with an end card", () => {+ it("ends the product-only ad on the card: captions become a helper, the card's join is the result", () => {+ const card = upload("card.png");+ const plan = mk.planClickToAd({ engine: "cloud", productId: "p1", styleId: "clean-minimal", endCard: { image: card } }, { product: product(), script: SCRIPT });+ expect(plan.finals).toEqual(["endcard"]);+ const by = Object.fromEntries(plan.steps.map((s) => [s.key, s]));+ expect(by.captions.request.feature).toBe("click-to-ad-step");+ expect(by.captions.request.title).toBeUndefined();+ expect(by.endcard).toMatchObject({ after: ["captions", "endcardClip"], request: { feature: "click-to-ad", title: plan.title } });+ expect(plan.meta.endCard).toBe(card);+ expect(plan.notes).toContain("Ends on your logo card for 2.5 s");+ // Prices: the card's two fal steps are about free; every step is valid.+ const est = mk.estimatePlan(plan);+ expect(est.steps.map((s) => s.key).slice(-2)).toEqual(["endcardClip", "endcard"]);+ });++ it("no card asked for: the plan is as before", () => {+ const plan = mk.planClickToAd({ engine: "cloud", productId: "p1", styleId: "clean-minimal" }, { product: product(), script: SCRIPT });+ expect(plan.finals).toEqual(["captions"]);+ expect(plan.steps.some((s) => s.key.startsWith("endcard"))).toBe(false);+ });++ it("cloud, no drawn card: the kit's raster logo on the background; an SVG logo can't be placed", () => {+ const logo = upload("logo.png");+ const plan = mk.planClickToAd({ engine: "cloud", productId: "p1", styleId: "clean-minimal", endCard: {} }, { product: product(), brand: kit({ logo }), script: SCRIPT, background: "/api/files/bg.png" });+ expect(plan.steps.find((s) => s.key === "endcardArt")!.request.inputs).toEqual({ images: ["/api/files/bg.png", logo] });+ expect(plan.notes.join(" ")).toMatch(/the kit's logo on its main colour/);+ expect(() => mk.planClickToAd({ engine: "cloud", productId: "p1", styleId: "clean-minimal", endCard: {} }, { product: product(), brand: kit({ logo: "/api/files/logo.svg" }), script: SCRIPT, background: "/api/files/bg.png" })).toThrow(+ /Add a logo to the brand kit for the end card, or turn End card off/,+ );+ });++ it("open: appended after the presenter film (ComfyUI-encoded), and needs the drawn card", () => {+ const card = upload("card.png");+ const plan = mk.planClickToAd({ engine: "open", productId: "p1", styleId: "simple-ugc", voiceSample: upload("v.png"), endCard: { image: card, seconds: 3 } }, { product: product(), script: SCRIPT });+ expect(plan.finals).toEqual(["endcard"]);+ expect(plan.steps.find((s) => s.key === "film")!.request.feature).toBe("click-to-ad-step");+ expect(plan.steps.at(-1)).toMatchObject({ key: "endcard", after: ["film"], request: { modelId: "oss-append-endcard", inputs: { images: [card] }, params: { duration: 3 } } });+ mk.estimatePlan(plan);+ expect(() => mk.planClickToAd({ engine: "open", productId: "p1", styleId: "simple-ugc", voiceSample: upload("v.png"), endCard: {} }, { product: product(), script: SCRIPT })).toThrow(mk.PlanError);+ });++ it("runs end to end on the demo provider (open: the ad, then the card appended)", async () => {+ const card = upload("card.png");+ const plan = mk.planClickToAd({ engine: "open", productId: "p1", styleId: "clean-minimal", voiceSample: upload("v.png"), endCard: { image: card } }, { product: product(), script: SCRIPT });+ const run = mk.launch(plan);+ expect(run.finalIds).toHaveLength(1);+ const final = await settle(run.finalIds[0]);+ expect(final, final.error ?? "").toMatchObject({ status: "succeeded", modelId: "oss-append-endcard", feature: "click-to-ad", kind: "video" });+ const captions = mk.getRun(run.id)!.generations.find((g) => g.modelId === "oss-captions-burnin")!;+ expect(final.request.inputs).toMatchObject({ video: captions.outputs[0].url, images: [card] });+ });+});++describe("the open end-card workflows through the ComfyUI provider", () => {+ async function prepare(id: string, input: GenInput, op: "concat" | "still-motion", media: Record<string, MediaInfo> = {}) {+ return prepareWorkflow(id, { seed: 7, ...input }, { generationId: "gen1", op, upload: async (_d, _t, name) => `up_${name}`, media: (name) => media[name], serverRam: async () => undefined });+ }+ const at = (wf: ComfyWorkflow, m: ManifestWorkflow, key: string) => (m.bindings[key] ?? []).map((t) => wf[t.node].inputs[t.input]);+ const ad = (hasAudio: boolean): MediaInfo => ({ container: "mp4", hasVideo: true, hasAudio, duration: 12, videoDuration: 12, width: 480, height: 848, fps: 25 });++ it("video-append-endcard: the ad's own size and frame rate, the card's seconds, the ad read twice (picture and sound)", async () => {+ const { workflow: wf, manifest: m } = await prepare("video-append-endcard", { video: "ad.mp4", images: ["card.png"], duration: 2.5 }, "concat", { "ad.mp4": ad(true) });+ expect(at(wf, m, "video")).toEqual(["ad.mp4", "ad.mp4"]);+ expect(at(wf, m, "image")).toEqual(["card.png"]);+ expect([at(wf, m, "width"), at(wf, m, "height"), at(wf, m, "fps"), at(wf, m, "duration")]).toEqual([[480], [848], [25], [2.5]]);+ expect(wf["14"].inputs.complete_audio).toEqual(["13", 0]);+ expect(at(wf, m, "filenamePrefix")).toEqual(["fuobe/gen1"]);+ });++ it("a silent ad: no LoadAudio, no padding, no complete_audio (the result has no sound track)", async () => {+ const { workflow: wf } = await prepare("video-append-endcard", { video: "ad.mp4", images: ["card.png"], duration: 2 }, "concat", { "ad.mp4": ad(false) });+ for (const id of ["2", "12", "13"]) expect(wf[id], id).toBeUndefined();+ expect(wf["14"].inputs.complete_audio).toBeUndefined();+ expect(wf["14"].inputs["videos.video0"]).toEqual(["1", 0]);+ expect(Object.keys(wf).sort()).toEqual(["1", "10", "11", "14", "15", "3", "4", "5", "6", "7", "8", "9"]);+ });++ it("refuses an ad whose size and frame rate it can't read", async () => {+ await expect(prepare("video-append-endcard", { video: "ad.mp4", images: ["card.png"] }, "concat")).rejects.toThrow(/Couldn't read the ad's size and frame rate/);+ });++ it("still-to-clip: the card at the clip size for its seconds", async () => {+ const { workflow: wf, manifest: m } = await prepare("still-to-clip", { images: ["card.png"], aspectRatio: "9:16", resolution: "480p", duration: 2.5, fps: 25 }, "still-motion");+ expect(at(wf, m, "image")).toEqual(["card.png"]);+ expect([at(wf, m, "duration"), at(wf, m, "fps")]).toEqual([[2.5], [25]]);+ const [w] = at(wf, m, "width") as number[];+ const [h] = at(wf, m, "height") as number[];+ expect(w % 2 + (h % 2)).toBe(0);+ expect(h / w).toBeCloseTo(16 / 9, 1);+ });+});