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
Marketing UI: kit progress, typed in/out times, @mentions, shared ad route, phone price
Claude2901ead04171
diff --git a/src/app/api/brands/[id]/chat/confirm/route.ts b/src/app/api/brands/[id]/chat/confirm/route.tsindex 7360292b..a8b1e7b1 100644--- a/src/app/api/brands/[id]/chat/confirm/route.ts+++ b/src/app/api/brands/[id]/chat/confirm/route.ts@@ -1,9 +1,10 @@import { after } from "next/server";import { z } from "zod";+import { AD_RATIOS } from "@/lib/catalog/marketing";import { confirmProposal } from "@/server/ads";import { failure, readBody } from "@/server/marketing";-const Body = z.object({ messageId: z.string().min(1).max(20), engine: z.enum(["cloud", "open"]), route: z.enum(["fuobe", "higgsfield"]).optional() });+const Body = z.object({ messageId: z.string().min(1).max(20), engine: z.enum(["cloud", "open"]), route: z.enum(["fuobe", "higgsfield"]).optional(), ratio: z.enum(AD_RATIOS).optional() });/** The user said yes to a chat proposal: the ads start rendering. */export async function POST(request: Request, ctx: RouteContext<"/api/brands/[id]/chat/confirm">) {@@ -11,7 +12,7 @@ export async function POST(request: Request, ctx: RouteContext<"/api/brands/[id]const body = await readBody(request, Body);if (body instanceof Response) return body;try {- const r = confirmProposal(id, body.messageId, body.engine, body.route);+ const r = confirmProposal(id, body.messageId, body.engine, body.route, body.ratio);after(() => r.run);return Response.json({ batchId: r.batchId, messages: r.chat }, { status: 201 });} catch (e) {diff --git a/src/app/api/marketing/runs/[id]/compose/route.ts b/src/app/api/marketing/runs/[id]/compose/route.tsindex 4a1b2bb1..8193c8c8 100644--- a/src/app/api/marketing/runs/[id]/compose/route.ts+++ b/src/app/api/marketing/runs/[id]/compose/route.ts@@ -1,7 +1,15 @@import { z } from "zod";import { failure, readBody, saveRunComposite } from "@/server/marketing";-const Body = z.object({ url: z.string().startsWith("/api/files/"), ratio: z.string().regex(/^\d+:\d+$/), text: z.string().max(1000).default("") });+const Body = z.object({+ url: z.string().startsWith("/api/files/"),+ ratio: z.string().regex(/^\d+:\d+$/),+ text: z.string().max(1000).default(""),+ /** The words as set (kept on the run, so "Edit text" opens with them). */+ overlay: z.object({ headline: z.string().max(140).optional(), body: z.string().max(400).optional(), cta: z.string().max(40).optional() }).optional(),+ /** Made by the browser on its own once the picture was ready (kept only if the run has none yet). */+ auto: z.boolean().optional(),+});/** Save an open-engine result with its words set in the browser (an uploaded PNG) to the Library. */export async function POST(request: Request, ctx: RouteContext<"/api/marketing/runs/[id]/compose">) {diff --git a/src/components/ads/ad-chat.tsx b/src/components/ads/ad-chat.tsxindex 9ac86d49..d8099ef4 100644--- a/src/components/ads/ad-chat.tsx+++ b/src/components/ads/ad-chat.tsx@@ -1,14 +1,17 @@"use client";-import { ArrowUp, AtSign, Check, Loader2, Sparkles, Trash2 } from "lucide-react";-import { useEffect, useRef, useState, useSyncExternalStore } from "react";+import { ArrowUp, AtSign, Check, Loader2, MoreHorizontal, Sparkles, Trash2, X } from "lucide-react";+import { useEffect, useId, useRef, useState, useSyncExternalStore } from "react";import { toast } from "sonner";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import type { BrandKit, Product } from "@/lib/catalog/marketing";import { formatCost } from "@/lib/format";import { cn } from "@/lib/utils";-import { useBrandChat, useEstimate, useStatusFlags, type ChatMessage } from "@/components/marketing/hooks";+import { useBrandChat, useEstimate, type ChatMessage } from "@/components/marketing/hooks";+import { insertMention, mentionMatches, mentionQuery } from "./mention";+import { RoutePicker, type AdRouteChoice } from "./new-ads";const NAME_KEY = "fuobe:first-name";const CHIPS = ["A lifestyle ad with the product in everyday use", "A clean studio shot with a bold headline", "A playful, colorful ad for social media"];@@ -42,12 +45,14 @@ function useFirstName(): [string, (n: string) => void] {];}-function Proposal({ msg, brand, products, engine, onConfirmed }: { msg: ChatMessage; brand: BrandKit; products: Product[]; engine: "cloud" | "open"; onConfirmed: (batchId: string) => void }) {+function Proposal({ msg, brand, products, engine, choice, onConfirmed }: { msg: ChatMessage; brand: BrandKit; products: Product[]; engine: "cloud" | "open"; choice: AdRouteChoice; onConfirmed: (batchId: string) => void }) {const { confirm } = useBrandChat(brand.id);- const { higgsfield } = useStatusFlags();const p = msg.proposal!;const total = p.items.reduce((n, i) => n + i.count, 0);- const est = useEstimate<{ costUsd: number | null; demo: boolean }>("/api/ads/estimate", msg.batchId ? null : { brandId: brand.id, engine, items: p.items, direction: p.direction, route: higgsfield && engine === "cloud" ? "higgsfield" : "fuobe" });+ // The same route as New ads (Higgsfield's one-shot ads only when that's what's picked there).+ const route = choice.route;+ const ratio = route === "higgsfield" ? choice.ratio : undefined;+ const est = useEstimate<{ costUsd: number | null; demo: boolean }>("/api/ads/estimate", msg.batchId ? null : { brandId: brand.id, engine, items: p.items, direction: p.direction, route, ratio });const names = p.items.map((i) => products.find((x) => x.id === i.productId)?.name).filter(Boolean);return (<div className="mt-2 rounded-xl border bg-background p-3">@@ -60,35 +65,54 @@ function Proposal({ msg, brand, products, engine, onConfirmed }: { msg: ChatMess<Check className="size-3.5" /> On their way to the grid</p>) : (- <button- type="button"- onClick={() =>- confirm.mutate(- { messageId: msg.id, engine, route: higgsfield && engine === "cloud" ? "higgsfield" : "fuobe" },- { onSuccess: (r) => (toast.success(`Generating ${total} ads`, { duration: 1500 }), onConfirmed(r.batchId)), onError: (e) => toast.error((e as Error).message) },- )- }- disabled={confirm.isPending}- className="mt-2 inline-flex h-8 items-center gap-1.5 rounded-full bg-primary px-3 text-[12px] font-medium text-primary-foreground hover:bg-primary/90"- >- {confirm.isPending ? <Loader2 className="size-3.5 animate-spin" /> : <Sparkles className="size-3.5" />}- Create {total} ads{est.data ? ` · ${est.data.demo ? "demo" : est.data.costUsd == null ? "" : `≈ ${formatCost(est.data.costUsd)}`}` : ""}- </button>+ <>+ {choice.available && (+ <div className="mt-2">+ <RoutePicker choice={choice} compact />+ </div>+ )}+ <button+ type="button"+ onClick={() =>+ confirm.mutate(+ { messageId: msg.id, engine, route, ratio },+ { onSuccess: (r) => (toast.success(`Generating ${total} ads`, { duration: 1500 }), onConfirmed(r.batchId)), onError: (e) => toast.error((e as Error).message) },+ )+ }+ disabled={confirm.isPending}+ className="mt-2 inline-flex h-8 items-center gap-1.5 rounded-full bg-primary px-3 text-[12px] font-medium text-primary-foreground hover:bg-primary/90"+ >+ {confirm.isPending ? <Loader2 className="size-3.5 animate-spin" /> : <Sparkles className="size-3.5" />}+ Create {total} ads{est.data ? ` · ${est.data.demo ? "demo" : est.data.costUsd == null ? "" : `≈ ${formatCost(est.data.costUsd)}`}` : ""}+ </button>+ </>)}</div>);}-/** The brand chat: ask for ads in plain words, @mention products, confirm what it proposes. */-export function AdChat({ brand, products, engine, onBatch, className }: { brand: BrandKit; products: Product[]; engine: "cloud" | "open"; onBatch: (batchId: string) => void; className?: string }) {+/**+ * The brand chat: ask for ads in plain words, @mention products, confirm what it proposes. Typing "@"+ * opens the product list without taking the focus: the typed name filters it, ↑↓ pick, Enter or Tab+ * puts "@Name" in place of what was typed. `onClose` (the phone sheet) adds a close button and moves+ * "Clear chat" into a menu, so the two never sit on top of each other.+ */+export function AdChat({ brand, products, engine, choice, onBatch, onClose, className }: { brand: BrandKit; products: Product[]; engine: "cloud" | "open"; choice: AdRouteChoice; onBatch: (batchId: string) => void; onClose?: () => void; className?: string }) {const { query, say, clear } = useBrandChat(brand.id);const [name, setName] = useFirstName();const [text, setText] = useState("");const [ph, setPh] = useState(0);- const [mention, setMention] = useState(false);+ const [caret, setCaret] = useState(0);+ const [menu, setMenu] = useState<"closed" | "typed" | "button">("closed");+ const [active, setActive] = useState(0);const box = useRef<HTMLTextAreaElement>(null);const list = useRef<HTMLDivElement>(null);+ const listId = useId();const messages = query.data ?? [];+ const typed = menu === "typed" ? mentionQuery(text, caret) : null;+ const open = menu === "button" || (menu === "typed" && !!typed);+ const matches = menu === "typed" ? mentionMatches(products, typed?.query ?? "") : products;+ const current = Math.min(active, Math.max(0, matches.length - 1));useEffect(() => {const t = setInterval(() => setPh((i) => (i + 1) % PLACEHOLDERS.length), 4000);return () => clearInterval(t);@@ -100,27 +124,62 @@ export function AdChat({ brand, products, engine, onBatch, className }: { brand:const v = t.trim();if (!v) return;setText("");+ setMenu("closed");say.mutate(v, { onError: (e) => toast.error((e as Error).message) });};const insert = (p: Product) => {- setText((t) => `${t}${t && !t.endsWith(" ") ? " " : ""}@${p.name} `);- setMention(false);- requestAnimationFrame(() => box.current?.focus());+ const at = box.current?.selectionStart ?? caret;+ const next = insertMention(text, menu === "typed" ? caret : at, p.name);+ setText(next.text);+ setCaret(next.caret);+ setMenu("closed");+ requestAnimationFrame(() => {+ box.current?.focus();+ box.current?.setSelectionRange(next.caret, next.caret);+ });+ };+ const follow = (el: HTMLTextAreaElement) => {+ const c = el.selectionStart ?? el.value.length;+ setCaret(c);+ if (mentionQuery(el.value, c)) setMenu((m) => (m === "button" ? m : "typed"));+ else setMenu((m) => (m === "typed" ? "closed" : m));};+ const optionId = (i: number) => `${listId}-o${i}`;return (<aside className={cn("flex min-h-0 flex-col rounded-2xl border bg-background", className)} aria-label="Brand chat"><div className="flex items-center justify-between gap-2 border-b px-4 py-3"><p className="text-[14px] font-semibold">Chat</p>- {messages.length > 0 && (- <Tooltip>- <TooltipTrigger asChild>- <button type="button" onClick={() => clear.mutate()} className="grid size-7 place-items-center rounded-full text-muted-foreground hover:bg-accent" aria-label="Clear chat">- <Trash2 className="size-3.5" />- </button>- </TooltipTrigger>- <TooltipContent>Clear chat</TooltipContent>- </Tooltip>- )}+ <div className="flex items-center gap-1">+ {messages.length > 0 &&+ (onClose ? (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button type="button" className="grid size-9 place-items-center rounded-full text-muted-foreground hover:bg-accent" aria-label="Chat options">+ <MoreHorizontal className="size-4" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem variant="destructive" onClick={() => clear.mutate()}>+ <Trash2 /> Clear chat+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ ) : (+ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" onClick={() => clear.mutate()} className="grid size-7 place-items-center rounded-full text-muted-foreground hover:bg-accent" aria-label="Clear chat">+ <Trash2 className="size-3.5" />+ </button>+ </TooltipTrigger>+ <TooltipContent>Clear chat</TooltipContent>+ </Tooltip>+ ))}+ {onClose && (+ <button type="button" onClick={onClose} className="grid size-9 place-items-center rounded-full text-muted-foreground hover:bg-accent" aria-label="Close the chat">+ <X className="size-4" />+ </button>+ )}+ </div></div><div ref={list} className="min-h-0 flex-1 space-y-3 overflow-y-auto px-4 py-4">{!messages.length && (@@ -150,7 +209,7 @@ export function AdChat({ brand, products, engine, onBatch, className }: { brand:<div key={m.id} className={cn("flex", m.role === "user" ? "justify-end" : "justify-start")}><div className={cn("max-w-[88%] rounded-2xl px-3 py-2 text-[13px] leading-relaxed", m.role === "user" ? "bg-brand-faint text-foreground" : "bg-muted")}><p className="whitespace-pre-wrap">{m.text}</p>- {m.role === "assistant" && m.proposal && <Proposal msg={m} brand={brand} products={products} engine={engine} onConfirmed={onBatch} />}+ {m.role === "assistant" && m.proposal && <Proposal msg={m} brand={brand} products={products} engine={engine} choice={choice} onConfirmed={onBatch} />}</div></div>))}@@ -169,9 +228,23 @@ export function AdChat({ brand, products, engine, onBatch, className }: { brand:value={text}onChange={(e) => {setText(e.target.value);- if (e.target.value.endsWith("@")) setMention(true);+ setActive(0);+ follow(e.target);}}+ onSelect={(e) => follow(e.currentTarget)}onKeyDown={(e) => {+ if (open && menu === "typed" && matches.length) {+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {+ e.preventDefault();+ setActive((current + (e.key === "ArrowDown" ? 1 : matches.length - 1)) % matches.length);+ return;+ }+ if ((e.key === "Enter" && !e.shiftKey) || e.key === "Tab") {+ e.preventDefault();+ insert(matches[current]);+ return;+ }+ }if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {e.preventDefault();sendText(text);@@ -180,29 +253,57 @@ export function AdChat({ brand, products, engine, onBatch, className }: { brand:rows={2}placeholder={PLACEHOLDERS[ph]}aria-label="Message"+ role="combobox"+ aria-autocomplete="list"+ aria-expanded={open && menu === "typed"}+ aria-controls={listId}+ aria-activedescendant={open && menu === "typed" && matches.length ? optionId(current) : undefined}className="w-full resize-none bg-transparent px-1.5 py-1 text-[13px] outline-none placeholder:text-subtle-foreground"/><div className="flex items-center justify-between">- <Popover open={mention} onOpenChange={setMention}>+ <Popover open={open} onOpenChange={(o) => setMenu(o ? "button" : "closed")}><PopoverTrigger asChild><button type="button" className="inline-flex h-7 items-center gap-1 rounded-full px-2 text-[12px] text-muted-foreground hover:bg-accent" aria-label="Mention a product"><AtSign className="size-3.5" /> Mention a product</button></PopoverTrigger>- <PopoverContent side="top" align="start" className="w-64 p-1" collisionPadding={12}>- {products.length ? (- products.map((p) => (- <button key={p.id} type="button" onClick={() => insert(p)} className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[13px] hover:bg-accent">- <span className="size-6 shrink-0 overflow-hidden rounded bg-muted">- {/* eslint-disable-next-line @next/next/no-img-element */}- {p.images[0] && <img src={p.images[0]} alt="" className="size-full object-cover" />}- </span>- <span className="truncate">{p.name}</span>- </button>- ))- ) : (- <p className="p-2 text-[12px] text-muted-foreground">No products yet.</p>- )}+ <PopoverContent+ side="top"+ align="start"+ className="w-64 p-1"+ collisionPadding={12}+ // Typing "@…" keeps the focus (and the typing) in the message box.+ onOpenAutoFocus={(e) => menu === "typed" && e.preventDefault()}+ onCloseAutoFocus={(e) => {+ e.preventDefault();+ box.current?.focus();+ }}+ onInteractOutside={(e) => e.target === box.current && e.preventDefault()}+ >+ <div id={listId} role="listbox" aria-label="Products">+ {matches.length ? (+ matches.map((p, i) => (+ <button+ key={p.id}+ id={optionId(i)}+ type="button"+ role="option"+ aria-selected={menu === "typed" && i === current}+ onMouseDown={(e) => menu === "typed" && e.preventDefault()}+ onClick={() => insert(p)}+ className={cn("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[13px] hover:bg-accent", menu === "typed" && i === current && "bg-accent")}+ >+ <span className="size-6 shrink-0 overflow-hidden rounded bg-muted">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ {p.images[0] && <img src={p.images[0]} alt="" className="size-full object-cover" />}+ </span>+ <span className="truncate">{p.name}</span>+ </button>+ ))+ ) : (+ <p className="p-2 text-[12px] text-muted-foreground">{products.length ? `No product matches “${typed?.query ?? ""}”.` : "No products yet."}</p>+ )}+ </div></PopoverContent></Popover><button type="button" onClick={() => sendText(text)} disabled={!text.trim() || say.isPending} className={cn("grid size-8 place-items-center rounded-full", text.trim() ? "bg-primary text-primary-foreground" : "bg-muted text-subtle-foreground")} aria-label="Send">diff --git a/src/components/ads/brand-workspace.tsx b/src/components/ads/brand-workspace.tsxindex 1ba81ec3..21a39878 100644--- a/src/components/ads/brand-workspace.tsx+++ b/src/components/ads/brand-workspace.tsx@@ -15,7 +15,7 @@ import { useBrand, useBrandActions, useCreatives } from "@/components/marketing/import { MarketingHeader, useMarketingEngine } from "@/components/marketing/shell";import { AdChat } from "./ad-chat";import { CreativeGrid } from "./creative-grid";-import { NewAds } from "./new-ads";+import { NewAds, useAdRoute } from "./new-ads";type Step = "kit" | "new" | "ads";@@ -45,7 +45,10 @@ export function BrandWorkspace({ brandId }: { brandId: string }) {const actions = useBrandActions(brandId);const [step, setStep] = useState<Step | null>(null);const [chat, setChat] = useState(false);+ const choice = useAdRoute(engine);const brand = view.data?.brand;+ // The chat works for any kit that isn't being researched (a canceled or failed research keeps what it found).+ const chatReady = !!brand && brand.status !== "researching";const products = view.data?.products ?? [];// First visit after the research: review the kit; with ads already made: the grid.const current: Step = step ?? (creatives.data?.length ? "ads" : brand?.status === "ready" && !products.length ? "kit" : creatives.isLoading ? "ads" : "kit");@@ -74,7 +77,8 @@ export function BrandWorkspace({ brandId }: { brandId: string }) {);}- const chatPanel = brand && <AdChat brand={brand} products={products} engine={engine} onBatch={() => (setStep("ads"), setChat(false))} className="h-full" />;+ const chatPanel = (inSheet: boolean) =>+ brand && <AdChat brand={brand} products={products} engine={engine} choice={choice} onBatch={() => (setStep("ads"), setChat(false))} onClose={inSheet ? () => setChat(false) : undefined} className="h-full" />;return (<div className="flex min-h-svh min-w-0 flex-col">@@ -84,7 +88,7 @@ export function BrandWorkspace({ brandId }: { brandId: string }) {engine={engine}onEngine={setEngine}right={- brand?.status === "ready" ? (+ chatReady ? (<Button variant="ghost" size="sm" className="xl:hidden" onClick={() => setChat(true)} aria-label="Open the brand chat"><MessageCircle /> <span className="hidden sm:inline">Chat</span></Button>@@ -146,7 +150,7 @@ export function BrandWorkspace({ brandId }: { brandId: string }) {<BrandKitForm key={brand.id} brand={brand} /></>)}- {current === "new" && <NewAds brand={brand} products={products} engine={engine} onCreated={() => setStep("ads")} />}+ {current === "new" && <NewAds brand={brand} products={products} engine={engine} choice={choice} onCreated={() => setStep("ads")} />}{current === "ads" &&(creatives.isLoading ? (<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">@@ -172,15 +176,15 @@ export function BrandWorkspace({ brandId }: { brandId: string }) {</>)}</main>- {brand?.status === "ready" && <div className="sticky top-28 hidden h-[calc(100svh-8rem)] w-[340px] shrink-0 xl:block">{chatPanel}</div>}+ {chatReady && <div className="sticky top-28 hidden h-[calc(100svh-8rem)] w-[340px] shrink-0 xl:block">{chatPanel(false)}</div>}</div><Sheet open={chat} onOpenChange={setChat}>- <SheetContent side="right" className="w-full gap-0 p-0 sm:max-w-md">+ <SheetContent side="right" showCloseButton={false} className="w-full gap-0 p-0 sm:max-w-md"><SheetHeader className="sr-only"><SheetTitle>Brand chat</SheetTitle><SheetDescription>Ask for ads in plain words</SheetDescription></SheetHeader>- <div className="h-full p-2">{chat && chatPanel}</div>+ <div className="h-full p-2">{chat && chatPanel(true)}</div></SheetContent></Sheet></div>diff --git a/src/components/ads/clip-range.tsx b/src/components/ads/clip-range.tsxindex d61e7da0..7bd83e60 100644--- a/src/components/ads/clip-range.tsx+++ b/src/components/ads/clip-range.tsx@@ -2,12 +2,55 @@import { Play, Scissors } from "lucide-react";import { useEffect, useRef, useState } from "react";-import { clampClip, initialClip, MULTIPLIER, type ClipRange as Range } from "@/lib/catalog/marketing";+import { clampClip, commitClipTime, initialClip, MULTIPLIER, parseClipTime, type ClipRange as Range } from "@/lib/catalog/marketing";import { cn } from "@/lib/utils";const r1 = (n: number) => Math.round(n * 10) / 10;const fmt = (s: number) => `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, "0")}`;+/**+ * An in/out time: what's typed stays as typed until Enter or leaving the field (then the range is+ * clamped), so "20" isn't cut to the 4 s minimum at its first digit. Arrow keys step 0.1 s at once;+ * Escape goes back to the current value.+ */+function TimeField({ label, value, max, onCommit }: { label: string; value: number; max: number; onCommit: (text: string) => void }) {+ const [text, setText] = useState<string | null>(null);+ const invalid = text != null && parseClipTime(text) == null;+ const commit = () => {+ if (text == null) return;+ setText(null);+ onCommit(text);+ };+ return (+ <label className="block">+ <span className="mb-1 block text-[11px] font-medium text-muted-foreground">{label}</span>+ <input+ type="text"+ inputMode="decimal"+ value={text ?? String(value)}+ onChange={(e) => setText(e.target.value)}+ onBlur={commit}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ commit();+ } else if (e.key === "Escape" && text != null) {+ e.preventDefault();+ setText(null);+ } else if (e.key === "ArrowUp" || e.key === "ArrowDown") {+ e.preventDefault();+ const base = parseClipTime(text ?? String(value)) ?? value;+ setText(null);+ onCommit(String(Math.min(max, Math.max(0, r1(base + (e.key === "ArrowUp" ? 0.1 : -0.1))))));+ }+ }}+ aria-invalid={invalid || undefined}+ className={cn("h-8 w-20 rounded-lg border bg-background px-2 font-mono text-[13px] tabular-nums outline-none focus:border-primary", invalid && "border-destructive")}+ />+ </label>+ );+}+/*** A plain in/out picker for the reference ad: the player, a bar showing the kept part, two time* fields and "set from the playhead" buttons. (A drop-in for a fuller trimmer later.)@@ -71,21 +114,15 @@ export function ClipRange({ src, duration, value, onChange, onDuration, onUnplay<div className="flex flex-wrap items-end gap-2">{(["start", "end"] as const).map((k) => (<div key={k} className="flex items-end gap-1">- <label className="block">- <span className="mb-1 block text-[11px] font-medium text-muted-foreground">{k === "start" ? "In (s)" : "Out (s)"}</span>- <input- type="number"- min={0}- max={r1(d)}- step={0.1}- value={range[k]}- onChange={(e) => {- const n = parseFloat(e.target.value);- if (Number.isFinite(n)) set(k, n);- }}- className="h-8 w-20 rounded-lg border bg-background px-2 font-mono text-[13px] tabular-nums outline-none focus:border-primary"- />- </label>+ <TimeField+ label={k === "start" ? "In (s)" : "Out (s)"}+ value={range[k]}+ max={r1(d)}+ onCommit={(text) => {+ const next = commitClipTime(text, range, d, k);+ if (next) onChange(next);+ }}+ /><button type="button" onClick={() => here(k)} className="inline-flex h-8 items-center gap-1 rounded-lg bg-secondary px-2 text-[12px] font-medium hover:bg-accent" title={`Set the ${k === "start" ? "in" : "out"} point at the playhead`}><Scissors className="size-3" /> {k === "start" ? "Set in here" : "Set out here"}</button>diff --git a/src/components/ads/creative-grid.tsx b/src/components/ads/creative-grid.tsxindex 994df45d..19ef5c18 100644--- a/src/components/ads/creative-grid.tsx+++ b/src/components/ads/creative-grid.tsx@@ -18,11 +18,18 @@ import { zipFiles } from "./zip";const layoutOf = (c: AdCreative, ratio: string) => (c.layout as AdLayout | null) ?? defaultLayout(ratio, c.position);+/** The formats a creative exists in: a baked (Higgsfield) ad only in the one it was rendered in. */+export const formatsOf = (c: Pick<AdCreative, "baked" | "ratio">): AdRatio[] => (c.baked ? [c.ratio ?? "4:5"] : [...AD_RATIOS]);++/** The format to export a creative in when the grid shows `ratio`. */+const exportRatio = (c: AdCreative, ratio: AdRatio): AdRatio => (formatsOf(c).includes(ratio) ? ratio : formatsOf(c)[0]);+function CreativeCard({ c, brand, ratio, product, n, onEdit }: { c: AdCreative; brand: BrandKit; ratio: AdRatio; product?: Product; n: number; onEdit: () => void }) {const { retry, remove } = useCreativeActions(brand.id);const ready = c.status === "ready" && !!c.image;const failed = c.status === "failed" || c.status === "canceled";const angle = AD_ANGLES.find((a) => a.id === c.angle)?.name;+ const own = exportRatio(c, ratio);return (<article className="group/ad min-w-0 animate-fade-up"><div className="relative">@@ -33,6 +40,7 @@ function CreativeCard({ c, brand, ratio, product, n, onEdit }: { c: AdCreative;) : (<div className="relative overflow-hidden rounded-xl bg-muted" style={{ aspectRatio: ratio.replace(":", " / ") }} />)}+ {ready && own !== ratio && <span className="pointer-events-none absolute bottom-2 left-2 rounded-full bg-black/55 px-2 py-0.5 text-[11px] font-medium text-white backdrop-blur">{own} only</span>}{!ready && (<div className={cn("absolute inset-0 flex flex-col justify-end rounded-xl p-3", failed ? "bg-background/85" : "bg-gradient-to-t from-background/90 via-background/30 to-transparent")}>{!failed && <div className="skeleton-sweep absolute inset-0 animate-skeleton rounded-xl" />}@@ -70,12 +78,14 @@ function CreativeCard({ c, brand, ratio, product, n, onEdit }: { c: AdCreative;<DropdownMenuItem onClick={onEdit}><Pencil /> Edit words and layout</DropdownMenuItem>- <DropdownMenuItem onClick={() => void downloadFormats({ brand: brand.name, product: product?.name, n }, [renderInput({ ratio, layout: layoutOf(c, ratio), text: c, brand, image: c.image, baked: c.baked })])}>- <Download /> Download {ratio}- </DropdownMenuItem>- <DropdownMenuItem onClick={() => void downloadFormats({ brand: brand.name, product: product?.name, n }, AD_RATIOS.map((r) => renderInput({ ratio: r, layout: layoutOf(c, r), text: c, brand, image: c.image, baked: c.baked })))}>- <FolderDown /> Download all formats+ <DropdownMenuItem onClick={() => void downloadFormats({ brand: brand.name, product: product?.name, n }, [renderInput({ ratio: own, layout: layoutOf(c, own), text: c, brand, image: c.image, baked: c.baked })])}>+ <Download /> Download {own}</DropdownMenuItem>+ {formatsOf(c).length > 1 && (+ <DropdownMenuItem onClick={() => void downloadFormats({ brand: brand.name, product: product?.name, n }, formatsOf(c).map((r) => renderInput({ ratio: r, layout: layoutOf(c, r), text: c, brand, image: c.image, baked: c.baked })))}>+ <FolderDown /> Download all formats+ </DropdownMenuItem>+ )}</>)}{failed && (@@ -107,7 +117,13 @@ export function CreativeGrid({ brand, products, creatives }: { brand: BrandKit;const shown = creatives.filter((c) => filter === "all" || c.productId === filter);const ready = shown.filter((c) => c.status === "ready" && c.image);const pending = creatives.filter((c) => c.status === "writing" || c.status === "queued" || c.status === "rendering").length;- const number = new Map(creatives.map((c, i) => [c.id, creatives.length - i]));+ // Ads are numbered in the order they were made: oldest batch first, and in a batch the order asked for.+ const number = useMemo(() => {+ const m = new Map<string, number>();+ let n = 0;+ for (const b of [...new Set(creatives.map((c) => c.batchId))].reverse()) for (const c of creatives) if (c.batchId === b) m.set(c.id, ++n);+ return m;+ }, [creatives]);const groups = split ? products.filter((p) => shown.some((c) => c.productId === p.id)).map((p) => ({ key: p.id, title: p.name, items: shown.filter((c) => c.productId === p.id) })) : [{ key: "all", title: "", items: shown }];const downloadAll = async () => {@@ -117,8 +133,10 @@ export function CreativeGrid({ brand, products, creatives }: { brand: BrandKit;try {const files = [];for (const c of ready) {- const blob = await exportPng(renderInput({ ratio, layout: layoutOf(c, ratio), text: c, brand, image: c.image, baked: c.baked }));- files.push({ name: exportName(brand.name, byId.get(c.productId ?? "")?.name, ratio, number.get(c.id) ?? 0), data: new Uint8Array(await blob.arrayBuffer()) });+ // A baked ad goes in the one format it was made in.+ const r = exportRatio(c, ratio);+ const blob = await exportPng(renderInput({ ratio: r, layout: layoutOf(c, r), text: c, brand, image: c.image, baked: c.baked }));+ files.push({ name: exportName(brand.name, byId.get(c.productId ?? "")?.name, r, number.get(c.id) ?? 0), data: new Uint8Array(await blob.arrayBuffer()) });}downloadBlob(new Blob([zipFiles(files) as BlobPart], { type: "application/zip" }), `${exportName(brand.name, undefined, ratio, ready.length).replace(/\.png$/, "")}-ads.zip`);toast.success("Downloaded", { id, duration: 1500 });@@ -177,7 +195,7 @@ export function CreativeGrid({ brand, products, creatives }: { brand: BrandKit;title={`${byId.get(editing.productId ?? "")?.name ?? brand.name} · ${AD_ANGLES.find((a) => a.id === editing.angle)?.name ?? "Ad"}`}image={editing.image}baked={editing.baked}- ratios={[ratio, ...AD_RATIOS.filter((r) => r !== ratio)]}+ ratios={editing.baked ? formatsOf(editing) : [ratio, ...AD_RATIOS.filter((r) => r !== ratio)]}initial={{ headline: editing.headline, body: editing.body, cta: editing.cta, layout: layoutOf(editing, ratio) }}brand={brand}productName={byId.get(editing.productId ?? "")?.name}diff --git a/src/components/ads/mention.ts b/src/components/ads/mention.tsnew file mode 100644index 00000000..fc7a28f2--- /dev/null+++ b/src/components/ads/mention.ts@@ -0,0 +1,31 @@+/**+ * @product mentions in the brand chat (pure text helpers, kept out of the component so they're tested):+ * the "@query" being typed before the caret, the products it matches, and the text after one is picked.+ */++/** The "@query" being typed just before the caret ("…for @Nig|"), or null when the caret isn't in one. */+export function mentionQuery(text: string, caret: number): { start: number; query: string } | null {+ const before = text.slice(0, Math.max(0, Math.min(caret, text.length)));+ const m = /(?:^|\s)@([^\s@]*)$/.exec(before);+ return m ? { start: before.length - m[1].length - 1, query: m[1] } : null;+}++/** Products whose name matches what's typed after "@" (names starting with it first). */+export function mentionMatches<P extends { name: string }>(products: P[], query: string): P[] {+ const q = query.trim().toLowerCase().replace(/_/g, " ");+ if (!q) return products;+ const hits = products.filter((p) => p.name.toLowerCase().includes(q));+ return [...hits.filter((p) => p.name.toLowerCase().startsWith(q)), ...hits.filter((p) => !p.name.toLowerCase().startsWith(q))];+}++/** The text with "@Name " for the picked product: in place of the "@query" being typed, else at the caret. */+export function insertMention(text: string, caret: number, name: string): { text: string; caret: number } {+ const at = Math.max(0, Math.min(caret, text.length));+ const q = mentionQuery(text, at);+ const start = q ? q.start : at;+ const before = text.slice(0, start);+ const after = text.slice(at);+ const pad = before && !/\s$/.test(before) ? " " : "";+ const tag = `${pad}@${name}${/^\s/.test(after) ? "" : " "}`;+ return { text: before + tag + after, caret: (before + tag).length };+}diff --git a/src/components/ads/new-ads.tsx b/src/components/ads/new-ads.tsxindex a93ca03f..18631cf4 100644--- a/src/components/ads/new-ads.tsx+++ b/src/components/ads/new-ads.tsx@@ -5,7 +5,7 @@ import { useMemo, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";import { AddFromLink, ProductCard, ProductDialog, UploadProductButton } from "@/components/brand/products";-import { AD_RATIOS, MAX_ADS_PER_PRODUCT, MAX_PRODUCTS_PER_RUN, type BrandKit, type Product } from "@/lib/catalog/marketing";+import { AD_RATIOS, MAX_ADS_PER_PRODUCT, MAX_PRODUCTS_PER_RUN, type AdRatio, type BrandKit, type Product } from "@/lib/catalog/marketing";import { formatCost } from "@/lib/format";import { cn } from "@/lib/utils";import { useCreativeActions, useEstimate, useProductActions, useStatusFlags } from "@/components/marketing/hooks";@@ -44,17 +44,65 @@ function Stepper({ value, onChange, label }: { value: number; onChange: (n: numb);}+/** Who makes a brand's ads: Fuobe (copy + visual + browser compositing) or Higgsfield's one-shot Ads Studio. */+export interface AdRouteChoice {+ /** Higgsfield's route is on offer (cloud engine, Higgsfield key set). */+ available: boolean;+ route: "fuobe" | "higgsfield";+ /** The one format Higgsfield renders per ad. */+ ratio: AdRatio;+ setRoute: (r: "fuobe" | "higgsfield") => void;+ setRatio: (r: AdRatio) => void;+}++/**+ * One route choice for New ads and the brand chat. It's derived from the status until the user picks,+ * so it doesn't freeze at "Fuobe" while the status is still loading.+ */+export function useAdRoute(engine: "cloud" | "open"): AdRouteChoice {+ const { higgsfield } = useStatusFlags();+ const [picked, setPicked] = useState<"fuobe" | "higgsfield" | null>(null);+ const [ratio, setRatio] = useState<AdRatio>("4:5");+ const available = engine === "cloud" && higgsfield;+ return { available, route: available ? (picked ?? "higgsfield") : "fuobe", ratio, setRoute: setPicked, setRatio };+}++/** The route radios (and Higgsfield's format), shared by New ads and a chat proposal. */+export function RoutePicker({ choice, compact }: { choice: AdRouteChoice; compact?: boolean }) {+ if (!choice.available) return null;+ return (+ <div className="flex flex-wrap items-center gap-2">+ {!compact && <span className="text-[12px] font-medium text-muted-foreground">Made by</span>}+ <div role="radiogroup" aria-label="Who makes the ads" className="inline-flex rounded-full bg-muted p-0.5">+ {(["higgsfield", "fuobe"] as const).map((r) => (+ <button key={r} type="button" role="radio" aria-checked={choice.route === r} onClick={() => choice.setRoute(r)} className={cn("h-7 rounded-full px-3 text-[12px] font-medium text-muted-foreground", choice.route === r && "bg-background text-foreground shadow-soft")}>+ {r === "higgsfield" ? (compact ? "Higgsfield" : "Higgsfield Ads Studio") : compact ? "Fuobe" : "Fuobe (your fonts, editable words)"}+ </button>+ ))}+ </div>+ {choice.route === "higgsfield" && (+ <div role="radiogroup" aria-label="Format" className="inline-flex rounded-full bg-muted p-0.5">+ {AD_RATIOS.map((r) => (+ <button key={r} type="button" role="radio" aria-checked={choice.ratio === r} onClick={() => choice.setRatio(r)} className={cn("h-7 rounded-full px-2.5 text-[12px] font-medium text-muted-foreground", choice.ratio === r && "bg-background text-foreground shadow-soft")}>+ {r}+ </button>+ ))}+ </div>+ )}+ {choice.route === "higgsfield" && !compact && <span className="text-[12px] text-muted-foreground">One format per ad, words drawn into the picture</span>}+ </div>+ );+}+/** Select products (≤10) → "How many ads to create?" (≤20 each, total price first) → Create. */-export function NewAds({ brand, products, engine, onCreated }: { brand: BrandKit; products: Product[]; engine: "cloud" | "open"; onCreated: (batchId: string) => void }) {+export function NewAds({ brand, products, engine, choice, onCreated }: { brand: BrandKit; products: Product[]; engine: "cloud" | "open"; choice: AdRouteChoice; onCreated: (batchId: string) => void }) {const { createBatch } = useCreativeActions(brand.id);const { remove } = useProductActions();- const { higgsfield } = useStatusFlags();const [selected, setSelected] = useState<string[]>(() => products.slice(0, MAX_PRODUCTS_PER_RUN).map((p) => p.id));const [counts, setCounts] = useState<Record<string, number>>({});const [editing, setEditing] = useState<Product | null>(null);- const [route, setRoute] = useState<"fuobe" | "higgsfield">(higgsfield && engine === "cloud" ? "higgsfield" : "fuobe");- const [ratio, setRatio] = useState<string>("4:5");- const effectiveRoute = engine === "open" || !higgsfield ? "fuobe" : route;+ const effectiveRoute = choice.route;+ const ratio = choice.ratio;const items = selected.filter((id) => products.some((p) => p.id === id)).map((productId) => ({ productId, count: counts[productId] ?? 4 }));const total = items.reduce((n, i) => n + i.count, 0);const body = useMemo(() => (items.length ? { brandId: brand.id, engine, route: effectiveRoute, items, ratio: effectiveRoute === "higgsfield" ? ratio : undefined } : null), [brand.id, engine, effectiveRoute, items, ratio]);@@ -114,7 +162,7 @@ export function NewAds({ brand, products, engine, onCreated }: { brand: BrandKit{items.length > 0 && (<section className="rounded-2xl border bg-background p-4 sm:p-5"><h3 className="text-[16px] font-semibold">How many ads to create?</h3>- <p className="text-[13px] text-muted-foreground">Each ad comes in 1:1, 4:5 and 9:16, with a headline, copy and a call to action.</p>+ <p className="text-[13px] text-muted-foreground">{effectiveRoute === "higgsfield" ? `Each ad comes in ${ratio}, made in one go by Higgsfield's Ads Studio.` : "Each ad comes in 1:1, 4:5 and 9:16, with a headline, copy and a call to action."}</p><ul className="mt-4 divide-y">{items.map((i) => {const p = products.find((x) => x.id === i.productId)!;@@ -130,25 +178,9 @@ export function NewAds({ brand, products, engine, onCreated }: { brand: BrandKit);})}</ul>- {engine === "cloud" && higgsfield && (- <div className="mt-4 flex flex-wrap items-center gap-2">- <span className="text-[12px] font-medium text-muted-foreground">Made by</span>- <div role="radiogroup" aria-label="Route" className="inline-flex rounded-full bg-muted p-0.5">- {(["higgsfield", "fuobe"] as const).map((r) => (- <button key={r} role="radio" aria-checked={route === r} onClick={() => setRoute(r)} className={cn("h-7 rounded-full px-3 text-[12px] font-medium text-muted-foreground", route === r && "bg-background text-foreground shadow-soft")}>- {r === "higgsfield" ? "Higgsfield Ads Studio" : "Fuobe (your fonts, editable words)"}- </button>- ))}- </div>- {route === "higgsfield" && (- <div role="radiogroup" aria-label="Format" className="inline-flex rounded-full bg-muted p-0.5">- {AD_RATIOS.map((r) => (- <button key={r} role="radio" aria-checked={ratio === r} onClick={() => setRatio(r)} className={cn("h-7 rounded-full px-2.5 text-[12px] font-medium text-muted-foreground", ratio === r && "bg-background text-foreground shadow-soft")}>- {r}- </button>- ))}- </div>- )}+ {choice.available && (+ <div className="mt-4">+ <RoutePicker choice={choice} /></div>)}<div className="mt-5 flex flex-wrap items-center justify-between gap-3 rounded-xl bg-muted/60 px-4 py-3">diff --git a/src/components/ads/render.ts b/src/components/ads/render.tsindex 4fd96dd9..bef54b22 100644--- a/src/components/ads/render.ts+++ b/src/components/ads/render.ts@@ -128,6 +128,16 @@ export function drawPlan(ctx: CanvasRenderingContext2D, plan: AdPlan, image: Canctx.restore();}+/** Fit a w×h picture inside a W×H frame without cropping, centred (a ±1 px difference fills the frame). */+export function containRect(w: number, h: number, W: number, H: number): { x: number; y: number; w: number; h: number } {+ const k = Math.min(W / w, H / h);+ let dw = w * k;+ let dh = h * k;+ if (Math.abs(dw - W) <= 1) dw = W;+ if (Math.abs(dh - H) <= 1) dh = H;+ return { x: (W - dw) / 2, y: (H - dh) / 2, w: dw, h: dh };+}+export interface RenderInput {ratio: AdRatio | string;layout: AdLayout;@@ -149,10 +159,13 @@ export async function renderAd(canvas: HTMLCanvasElement, input: RenderInput, scif (!ctx) return;ctx.setTransform(scale, 0, 0, scale, 0, 0);if (input.baked) {- const plan = planAd({ ratio: input.ratio, layout: "overlay", content: { headline: "" }, theme: input.theme, image: img ? { w: img.naturalWidth, h: img.naturalHeight } : null, measure: measureText });+ // The words are in the picture: show all of it (letterboxed in another format), never crop it.ctx.fillStyle = "#111";ctx.fillRect(0, 0, w, h);- if (img && plan.image) ctx.drawImage(img, plan.image.sx, plan.image.sy, plan.image.sw, plan.image.sh, 0, 0, w, h);+ if (img?.naturalWidth && img.naturalHeight) {+ const r = containRect(img.naturalWidth, img.naturalHeight, w, h);+ ctx.drawImage(img, r.x, r.y, r.w, r.h);+ }return;}const plan = planAd({diff --git a/src/components/brand/brand-kit-form.tsx b/src/components/brand/brand-kit-form.tsxindex 7c4eb21e..6f6964d2 100644--- a/src/components/brand/brand-kit-form.tsx+++ b/src/components/brand/brand-kit-form.tsx@@ -93,7 +93,7 @@ function Section({ title, hint, children }: { title: string; hint?: string; chil);}-function LogoField({ value, onChange }: { value?: string; onChange: (v?: string) => void }) {+export function LogoField({ value, onChange }: { value?: string; onChange: (v?: string) => void }) {const input = useRef<HTMLInputElement>(null);const [busy, setBusy] = useState(false);return (diff --git a/src/components/marketing/click-to-ad.tsx b/src/components/marketing/click-to-ad.tsxindex 2a75bc00..9462dff7 100644--- a/src/components/marketing/click-to-ad.tsx+++ b/src/components/marketing/click-to-ad.tsx@@ -5,14 +5,15 @@ import { Check, Clapperboard, Loader2, MousePointerClick, PenLine, RefreshCw, Spimport { useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";-import { areaCls, inputCls } from "@/components/brand/fields";+import { LogoField } from "@/components/brand/brand-kit-form";+import { areaCls, ColorList, inputCls } from "@/components/brand/fields";import { ImageList } from "@/components/brand/image-list";import { AddFromLink, priceText, ProductThumb, UploadProductButton } from "@/components/brand/products";import type { SlotValue } from "@/components/studio/media-slot";-import { AD_STYLES, KIT_LABELS, type MarketingRun, type Product, type RunEstimate } from "@/lib/catalog/marketing";+import { AD_STYLES, KIT_LABELS, type BrandKit, type MarketingRun, type Product, type RunEstimate } from "@/lib/catalog/marketing";import { formatCost } from "@/lib/format";import { cn } from "@/lib/utils";-import { addRuns, send, useBrand, useEstimate, useProductActions, useProducts } from "./hooks";+import { addRuns, send, useBrand, useEstimate, useProductActions, useProducts, useReadingProduct, useUpdateBrand } from "./hooks";import type { ModelInfo } from "./model-info";import { AvatarSlot, VoiceControl } from "./pickers";import { RunsList } from "./runs";@@ -58,12 +59,63 @@ function KitProgress() {const styleScene = (presenter: boolean, dark?: boolean) => (presenter ? "selfie" : dark ? "noir" : "orbit");+/**+ * The product kit's logo and colours, kept in the product's brand kit (made from the page when the link+ * was read) so they stay after a reload and reach the video prompts. Edits save to that kit.+ */+function KitBrand({ brand }: { brand: BrandKit }) {+ const update = useUpdateBrand(brand.id);+ const [colors, setColors] = useState(brand.colors);+ const [shown, setShown] = useState(brand.colors);+ if (shown !== brand.colors) {+ setShown(brand.colors);+ setColors(brand.colors);+ }+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);+ const pending = useRef<(() => void) | null>(null);+ const save = (patch: Partial<Pick<BrandKit, "logo" | "colors">>) => update.mutate(patch, { onError: (e) => toast.error((e as Error).message) });+ // Colours typed just before leaving the step still get saved.+ useEffect(() => {+ const t = timer;+ const p = pending;+ return () => {+ if (t.current) clearTimeout(t.current);+ p.current?.();+ };+ }, []);+ return (+ <div className="space-y-2.5 rounded-xl border p-3">+ <div className="flex items-center justify-between gap-2">+ <p className="text-[12px] font-medium text-muted-foreground">Logo and colours</p>+ <span className="text-[11px] text-subtle-foreground">{update.isPending ? "Saving…" : `In the ${brand.name} brand kit`}</span>+ </div>+ <LogoField value={brand.logo} onChange={(v) => save({ logo: v ?? "" })} />+ <ColorList+ value={colors}+ max={6}+ onChange={(v) => {+ setColors(v);+ if (timer.current) clearTimeout(timer.current);+ pending.current = () => save({ colors: v });+ timer.current = setTimeout(() => {+ pending.current?.();+ pending.current = null;+ }, 500);+ }}+ />+ <p className="text-[11px] text-muted-foreground">Used in the video's look. Ads Studio and Marketing Studio use this kit too.</p>+ </div>+ );+}+/** Click to Ad: product link → product kit → style → a 9:16 ad of up to 12 s with voiceover and captions. */export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {const qc = useQueryClient();const { engine, setEngine } = useMarketingEngine();const products = useProducts();- const { update, read } = useProductActions();+ const { update } = useProductActions();+ // The link is read by AddFromLink's own mutation: follow it by its key.+ const reading = useReadingProduct();const [productId, setProductId] = useState<string | null>(null);const [picked, setPicked] = useState<string[]>([]);const [brandBits, setBrandBits] = useState<{ logo?: string; colors: string[] } | null>(null);@@ -162,7 +214,7 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {<Step n={1} title="Your product" hint="Paste the product's own page, or pick one you saved." done={!!product}><AddFromLink limit={1} withBrand placeholder="https://yourshop.com/products/…" onAdded={(ps, extra) => ps[0] && choose(ps[0], extra.brand)} />- {read.isPending && <KitProgress />}+ {reading && <KitProgress />}<div className="mt-5"><div className="mb-2 flex items-center justify-between gap-2"><p className="text-[12px] font-medium text-muted-foreground">Or select your product</p>@@ -205,21 +257,24 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {</div></>)}- {(brandBits?.logo || brand?.logo || (brandBits?.colors.length ?? brand?.colors.length)) && (+ {brand ? (+ <KitBrand key={brand.id} brand={brand} />+ ) : (brandBits?.logo || brandBits?.colors.length) ? (+ // The page's bits while the product's brand kit loads.<div className="flex items-center gap-3 pt-1">- {(brandBits?.logo || brand?.logo) && (+ {brandBits?.logo && (<div className="checkerboard grid h-10 w-20 place-items-center overflow-hidden rounded-lg border">{/* eslint-disable-next-line @next/next/no-img-element */}- <img src={brandBits?.logo || brand?.logo} alt="Logo" className="max-h-full max-w-full object-contain p-1" />+ <img src={brandBits.logo} alt="Logo" className="max-h-full max-w-full object-contain p-1" /></div>)}<div className="flex gap-1">- {(brandBits?.colors.length ? brandBits.colors : (brand?.colors ?? [])).slice(0, 6).map((c) => (+ {(brandBits?.colors ?? []).slice(0, 6).map((c) => (<span key={c} className="size-5 rounded-full border" style={{ background: c }} title={c} />))}</div></div>- )}+ ) : null}</div><div className="min-w-0 space-y-3"><label className="block space-y-1.5">diff --git a/src/components/marketing/hooks.ts b/src/components/marketing/hooks.tsindex b411b42e..a5a762c7 100644--- a/src/components/marketing/hooks.ts+++ b/src/components/marketing/hooks.ts@@ -1,6 +1,6 @@"use client";-import { keepPreviousData, useMutation, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";+import { keepPreviousData, useIsMutating, useMutation, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";import { useEffect, useRef, useState } from "react";import { useGenerationEvents, useStatus } from "@/lib/api";import type { AdCreative, BrandKit, BrandKitFields, MarketingRun, Product, RunEstimate, RunFeature } from "@/lib/catalog/marketing";@@ -110,13 +110,20 @@ export function useProductActions() {update: useMutation({ mutationFn: ({ id, ...p }: ProductInput & { id: string }) => send<Product>(`/api/products/${id}`, "PATCH", p), onSuccess: done }),remove: useMutation({ mutationFn: (id: string) => send<void>(`/api/products/${id}`, "DELETE"), onSuccess: done }),read: useMutation({+ mutationKey: PRODUCT_READ,mutationFn: (b: { url: string; brandId?: string | null; limit?: number; withBrand?: boolean }) =>- send<{ products: Product[]; found: number; duplicate?: Product; message?: string; brand: { name?: string; logo?: string; colors: string[]; fonts: { heading?: string; body?: string } } }>("/api/products/read", "POST", b),+ send<{ products: Product[]; found: number; duplicate?: Product; message?: string; brandId?: string; brand: { name?: string; logo?: string; colors: string[]; fonts: { heading?: string; body?: string } } }>("/api/products/read", "POST", b),onSuccess: done,}),};}+/** The key of "read a product link" mutations, so a page can show progress for a read started elsewhere on it. */+export const PRODUCT_READ = ["product-read"] as const;++/** A product link is being read somewhere on the page (Click to Ad's "Building your product kit"). */+export const useReadingProduct = () => useIsMutating({ mutationKey: PRODUCT_READ }) > 0;+// ---------------------------------------------------------------------------// Runs (Marketing Studio, Click to Ad, Ad Multiplier)@@ -265,7 +272,7 @@ export function useBrandChat(brandId: string) {onError: () => void qc.invalidateQueries({ queryKey: key }),}),confirm: useMutation({- mutationFn: (b: { messageId: string; engine: "cloud" | "open"; route?: "fuobe" | "higgsfield" }) => send<{ batchId: string; messages: ChatMessage[] }>(`/api/brands/${brandId}/chat/confirm`, "POST", b),+ mutationFn: (b: { messageId: string; engine: "cloud" | "open"; route?: "fuobe" | "higgsfield"; ratio?: string }) => send<{ batchId: string; messages: ChatMessage[] }>(`/api/brands/${brandId}/chat/confirm`, "POST", b),onSuccess: (r) => {set(r.messages);void qc.invalidateQueries({ queryKey: ["ads", brandId] });diff --git a/src/components/marketing/marketing-studio.tsx b/src/components/marketing/marketing-studio.tsxindex e4dd399e..a7b52012 100644--- a/src/components/marketing/marketing-studio.tsx+++ b/src/components/marketing/marketing-studio.tsx@@ -1,7 +1,7 @@"use client";import { useQueryClient } from "@tanstack/react-query";-import { ArrowUp, ChevronDown, Image as ImageIcon, LayoutTemplate, Loader2, SlidersHorizontal, Type, Video, X } from "lucide-react";+import { ArrowUp, ChevronDown, Globe, Image as ImageIcon, LayoutTemplate, Loader2, SlidersHorizontal, Type, Video, X } from "lucide-react";import { useSearchParams } from "next/navigation";import { Suspense, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";import { toast } from "sonner";@@ -11,7 +11,7 @@ import { MediaSlot, type SlotValue } from "@/components/studio/media-slot";import { ResponsivePanel } from "@/components/studio/responsive-panel";import { BrandChip } from "@/components/brand/brand-dialog";import { inputCls } from "@/components/brand/fields";-import { FORMATS, formatModels, MAX_PROMPT, TEMPLATE_INDEX, type FormatId, type MarketingCategory, type MarketingTemplate, type RunEstimate } from "@/lib/catalog/marketing";+import { FORMATS, formatModels, looksLikeWebsite, MAX_PROMPT, openingAspect, TEMPLATE_INDEX, type FormatId, type MarketingCategory, type MarketingTemplate, type RunEstimate } from "@/lib/catalog/marketing";import { formatCost } from "@/lib/format";import { cn } from "@/lib/utils";import { addRuns, send, useBrands, useEstimate, useStatusFlags } from "./hooks";@@ -43,9 +43,11 @@ interface Draft {modelId?: string;voice?: string;voiceSample: SlotValue | null;+ /** SaaS motion: a website or social link to make the video about. */+ website: string;}-const BLANK: Draft = { format: "product-standalone", templateId: null, product: null, avatar: null, reference: null, hookId: null, settingId: null, prompt: "", headline: "", cta: "", aspectRatio: "3:4", batch: 1, voiceSample: null };+const BLANK: Draft = { format: "product-standalone", templateId: null, product: null, avatar: null, reference: null, hookId: null, settingId: null, prompt: "", headline: "", cta: "", aspectRatio: "3:4", batch: 1, voiceSample: null, website: "" };const BRAND_KEY = "fuobe:marketing-brand";const brandListeners = new Set<() => void>();@@ -83,7 +85,7 @@ function withTemplate(d: Draft, t: MarketingTemplate | null, format?: FormatId):...d,format: f.id,templateId: t?.id ?? null,- aspectRatio: f.aspectRatios.includes(t?.aspect ?? d.aspectRatio) ? (t?.aspect ?? d.aspectRatio) : f.defaultAspect,+ aspectRatio: openingAspect(d, t, f.id),duration: f.durations ? (t?.duration ?? f.durations.default) : undefined,batch: Math.min(d.batch, f.batch),hookId: f.hookAndSetting ? (t?.hook ?? null) : null,@@ -129,6 +131,7 @@ function SettingsPanel({ draft, set, models, higgsfield, engine }: { draft: Draf{f.durations && (<div><p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Length · {draft.duration}s</p>+ {f.pipeline === "ugc" && <p className="-mt-1 mb-1.5 text-[11px] text-subtle-foreground">The whole video: the script is sized to what's left after the hook and the product close-up</p>}<input type="range" min={f.durations.min} max={f.durations.max} step={1} value={draft.duration ?? f.durations.default} onChange={(e) => set({ duration: Number(e.target.value) })} aria-label="Length in seconds" className="w-full accent-[var(--primary)]" /><p className="mt-0.5 flex justify-between text-[11px] text-subtle-foreground"><span>{f.durations.min}s</span>@@ -194,6 +197,33 @@ function TextPanel({ draft, set, template }: { draft: Draft; set: (p: Partial<Dr);}+/** SaaS motion's "Website or social link" (one of prompt / product / website). */+function WebsitePanel({ draft, set }: { draft: Draft; set: (p: Partial<Draft>) => void }) {+ const [open, setOpen] = useState(false);+ const v = draft.website.trim();+ const bad = !!v && !looksLikeWebsite(v);+ return (+ <ResponsivePanel+ open={open}+ onOpenChange={setOpen}+ title="Website or social link"+ description="What the video is about when there's no product photo: your site or a social profile."+ trigger={+ <button type="button" className={cn(chipBase, v && !bad ? chipOn : chipIdle, "max-w-44")} aria-label={v ? `Website: ${v}` : "Add a website or social link"}>+ <Globe className="size-3.5" />+ <span className="truncate">{v ? v.replace(/^https?:\/\//i, "") : "Website"}</span>+ </button>+ }+ >+ <label className="block space-y-1.5">+ <span className="text-[12px] font-medium text-muted-foreground">Link</span>+ <input value={draft.website} onChange={(e) => set({ website: e.target.value })} maxLength={300} inputMode="url" placeholder="www.example.com" aria-invalid={bad || undefined} className={cn(inputCls, bad && "border-destructive")} />+ {bad && <span className="block text-[11px] text-destructive">Enter a valid website URL</span>}+ </label>+ </ResponsivePanel>+ );+}+function FormatChip({ draft, onFormat }: { draft: Draft; onFormat: (f: FormatId) => void }) {const [open, setOpen] = useState(false);const f = FORMATS[draft.format];@@ -285,11 +315,13 @@ export function MarketingStudio({ models }: { models: Record<string, ModelInfo>batch: draft.batch,voice: draft.voice,voiceSample: draft.voiceSample?.ref,+ website: f.oneOf?.includes("website") && looksLikeWebsite(draft.website) ? draft.website.trim() : undefined,}),[draft, engine, f, brandId],);const est = useEstimate<RunEstimate>("/api/marketing/estimate", draft.avatar?.uploading || draft.voiceSample?.uploading ? null : body);- const blocker = draft.product === null && f.product === "required" ? "Attach a product to generate" : est.data?.blocker;+ const badSite = !!f.oneOf?.includes("website") && !!draft.website.trim() && !looksLikeWebsite(draft.website);+ const blocker = draft.product === null && f.product === "required" ? "Attach a product to generate" : badSite ? "Enter a valid website URL" : est.data?.blocker;const cost = est.data && !est.data.blocker ? (est.data.demo ? "Demo · free" : est.data.costUsd == null ? "" : est.data.costUsd === 0 ? "Free" : `≈ ${formatCost(est.data.costUsd)}`) : "";const generate = async () => {@@ -425,6 +457,7 @@ export function MarketingStudio({ models }: { models: Record<string, ModelInfo>{f.hookAndSetting && <SettingPicker value={draft.settingId} onChange={(s) => set({ settingId: s })} />}{f.pipeline === "ugc" && <VoiceControl engine={engine} models={models} voice={draft.voice} sample={draft.voiceSample} onVoice={(v) => set({ voice: v })} onSample={(s) => set({ voiceSample: s })} />}{f.text && <TextPanel draft={draft} set={set} template={template} />}+ {f.oneOf?.includes("website") && <WebsitePanel draft={draft} set={set} />}{f.brandKit && <BrandChip value={brandId} onChange={pickBrand} />}<SettingsPanel draft={draft} set={set} models={models} higgsfield={higgsfield} engine={engine} /></div>@@ -444,8 +477,14 @@ export function MarketingStudio({ models }: { models: Record<string, ModelInfo><TooltipContent>{blocker ?? (template ? `Recreate template${cost ? ` · ${cost}` : ""}` : `Generate${cost ? ` · ${cost}` : ""}`)}</TooltipContent></Tooltip></div>- {est.data?.notes.length && !blocker ? <p className="truncate px-2 pt-1 text-[11px] text-muted-foreground">{est.data.notes[0]}</p> : null}- {blocker && <p className="px-2 pt-1 text-[11px] text-muted-foreground sm:hidden">{blocker}</p>}+ {est.data?.notes.length && !blocker ? <p className="hidden truncate px-2 pt-1 text-[11px] text-muted-foreground sm:block">{est.data.notes[0]}</p> : null}+ {/* Phones have no hover: the price (and what blocks Generate) sit under the composer. */}+ {(blocker || cost || est.data?.notes.length) && (+ <p className="flex min-w-0 items-baseline justify-between gap-2 px-2 pt-1 text-[11px] text-muted-foreground sm:hidden" aria-live="polite">+ <span className="min-w-0 truncate">{blocker ?? est.data?.notes[0] ?? ""}</span>+ {!blocker && cost && <span className="shrink-0 font-mono tabular-nums">{cost}</span>}+ </p>+ )}</div></div></div>diff --git a/src/components/marketing/runs.tsx b/src/components/marketing/runs.tsxindex 6ec0d8f4..e591fc87 100644--- a/src/components/marketing/runs.tsx+++ b/src/components/marketing/runs.tsx@@ -3,14 +3,14 @@import { useQueryClient } from "@tanstack/react-query";import { AlertCircle, Check, Circle, Download, Loader2, MoreHorizontal, Repeat2, Type, X } from "lucide-react";import dynamic from "next/dynamic";-import { useMemo, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import { Skeleton } from "@/components/ui/skeleton";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { MediaThumb } from "@/components/studio/result-media";-import { useGenerationActions } from "@/lib/api";-import { FORMATS, runStatus, type BrandKit, type MarketingRun, type RunFeature } from "@/lib/catalog/marketing";+import { uploadFile, useGenerationActions } from "@/lib/api";+import { FORMATS, overlayLayout, runStatus, type BrandKit, type MarketingRun, type RunFeature } from "@/lib/catalog/marketing";import type { Generation } from "@/lib/catalog/types";import { elapsed, formatCost, ratioValue, timeAgo } from "@/lib/format";import { cn } from "@/lib/utils";@@ -54,6 +54,33 @@ function runRatio(run: MarketingRun, g?: Generation): number {return ratioValue(ar && ar !== "auto" ? ar : undefined, g?.kind === "video" ? 9 / 16 : 3 / 4);}+/** The format the words are set in: the picture's own ratio. */+const composeRatio = (g?: Generation) => {+ const ar = g?.request.params?.aspectRatio;+ return ar && ar !== "auto" ? ar : "3:4";+};++const overlayText = (run: MarketingRun) => ({ headline: run.meta.overlay?.headline ?? "", body: run.meta.overlay?.body ?? "", cta: run.meta.overlay?.cta ?? "" });++/** An open-engine poster / ad whose picture is ready and whose words aren't set yet. */+function needsCompose(run: MarketingRun): boolean {+ if (run.engine !== "open" || !run.meta.overlay || run.meta.composed || runStatus(run).state !== "done") return false;+ return run.generations.some((g) => run.finalIds.includes(g.id) && g.outputs.some((o) => o.kind === "image"));+}++/** Set the run's words over its picture in the browser (brand fonts, logo, colours) and save it on the run. */+async function autoCompose(run: MarketingRun, brand: BrandKit | null): Promise<void> {+ const final = run.generations.find((g) => run.finalIds.includes(g.id));+ const image = final?.outputs.find((o) => o.kind === "image")?.url;+ if (!image) return;+ const [{ renderInput }, { exportPng }] = await Promise.all([import("@/components/ads/ad-editor"), import("@/components/ads/render")]);+ const ratio = composeRatio(final);+ const text = overlayText(run);+ const blob = await exportPng(renderInput({ ratio, layout: overlayLayout(run.meta.format), text, brand, image }));+ const asset = await uploadFile(new File([blob], `${run.title.replace(/[^\w-]+/g, "-").slice(0, 60) || "ad"}.png`, { type: "image/png" }));+ await send(`/api/marketing/runs/${run.id}/compose`, "POST", { url: asset.url, ratio, text: [text.headline, text.body, text.cta].filter(Boolean).join(" · "), overlay: run.meta.overlay ?? undefined, auto: true });+}+function RunCard({ run, brand, onOpen, onCompose }: { run: MarketingRun; brand?: BrandKit; onOpen: (g: Generation, i: number) => void; onCompose: (run: MarketingRun) => void }) {const qc = useQueryClient();const forget = useForgetRun(run.feature);@@ -70,6 +97,9 @@ function RunCard({ run, brand, onOpen, onCompose }: { run: MarketingRun; brand?:const ratio = runRatio(run, final);const format = run.meta.format ? FORMATS[run.meta.format] : null;const canCompose = run.engine === "open" && !!run.meta.overlay && status.state === "done" && outputs.some((x) => x.o.kind === "image");+ // The words are set in the browser right after the picture lands; the card shows that version.+ const composed = canCompose ? run.meta.composed : null;+ const setting = canCompose && !composed;const runAgain = () => {setAgain(true);send<{ runs: MarketingRun[] }>(`/api/marketing/runs/${run.id}/again`, "POST")@@ -83,11 +113,21 @@ function RunCard({ run, brand, onOpen, onCompose }: { run: MarketingRun; brand?:return (<article className="group/run min-w-0 animate-fade-up"><div className="relative">- {outputs.length ? (+ {composed ? (+ <button onClick={() => onCompose(run)} className="relative block w-full overflow-hidden rounded-xl bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring" style={{ aspectRatio: ratio }} aria-label={`Edit the text of ${run.title}`}>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={composed.url} alt="" className="size-full object-cover" loading="lazy" />+ </button>+ ) : outputs.length ? (<div className={cn("grid gap-1.5", outputs.length > 1 && "grid-cols-2")}>{outputs.slice(0, 4).map(({ g, o, i }) => (<button key={o.url} onClick={() => onOpen(g, i)} className="relative block overflow-hidden rounded-xl bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring" style={{ aspectRatio: ratio }} aria-label={`Open ${run.title}`}><MediaThumb output={o} g={g} />+ {setting && i === 0 && (+ <span className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/60 to-transparent px-2.5 pt-6 pb-2 text-left text-[12px] font-medium text-white">+ <span className="shimmer-text animate-shimmer-text">Setting your text…</span>+ </span>+ )}</button>))}</div>@@ -124,16 +164,23 @@ function RunCard({ run, brand, onOpen, onCompose }: { run: MarketingRun; brand?:</button></DropdownMenuTrigger><DropdownMenuContent align="end">+ {composed && (+ <DropdownMenuItem asChild>+ <a href={composed.url} download>+ <Download /> Download+ </a>+ </DropdownMenuItem>+ )}{outputs.map(({ o }, i) => (<DropdownMenuItem key={o.url} asChild><a href={o.url} download>- <Download /> Download{outputs.length > 1 ? ` ${i + 1}` : ""}+ <Download /> {composed ? "Download the picture without text" : `Download${outputs.length > 1 ? ` ${i + 1}` : ""}`}</a></DropdownMenuItem>))}{canCompose && (<DropdownMenuItem onClick={() => onCompose(run)}>- <Type /> Set your text+ <Type /> {composed ? "Edit text" : "Set your text"}</DropdownMenuItem>)}<DropdownMenuItem onClick={runAgain} disabled={again}>@@ -156,7 +203,7 @@ function RunCard({ run, brand, onOpen, onCompose }: { run: MarketingRun; brand?:</p>{canCompose && (<button onClick={() => onCompose(run)} className="mt-1.5 inline-flex h-7 items-center gap-1.5 rounded-full bg-brand-faint px-2.5 text-[12px] font-medium text-brand-text hover:bg-brand-faint-hover">- <Type className="size-3" /> Set your text+ <Type className="size-3" /> {composed ? "Edit text" : "Set your text"}</button>)}{steps.length > 1 && (@@ -179,6 +226,19 @@ export function RunsList({ feature, empty, limit }: { feature: RunFeature; emptyconst [open, setOpen] = useState<{ id: string; index: number } | null>(null);const [compose, setCompose] = useState<MarketingRun | null>(null);const list = useMemo(() => (limit ? runs.data?.slice(0, limit) : runs.data) ?? [], [runs.data, limit]);+ // Open posters and ads get their words set as soon as the picture lands (once per run; "Edit text" changes them).+ const qc = useQueryClient();+ const tried = useRef(new Set<string>());+ useEffect(() => {+ if (brands.isLoading) return;+ for (const r of list) {+ if (!needsCompose(r) || tried.current.has(r.id)) continue;+ tried.current.add(r.id);+ autoCompose(r, brands.data?.find((b) => b.id === r.meta.brandId) ?? null)+ .then(() => qc.invalidateQueries({ queryKey: ["marketing-runs", feature] }))+ .catch(() => undefined);+ }+ }, [list, brands.isLoading, brands.data, qc, feature]);const flat = useMemo(() => list.flatMap((r) => r.generations.filter((g) => r.finalIds.includes(g.id) && g.status === "succeeded").flatMap((g) => g.outputs.map((_, i) => ({ g, i })))), [list]);const pos = open ? flat.findIndex((f) => f.g.id === open.id && f.i === open.index) : -1;if (runs.isLoading)@@ -218,11 +278,12 @@ export function RunsList({ feature, empty, limit }: { feature: RunFeature; emptyonOpenChange={(o) => !o && setCompose(null)}title={compose.title}image={composeFinal.outputs.find((o) => o.kind === "image")?.url}- ratios={[composeFinal.request.params?.aspectRatio && composeFinal.request.params.aspectRatio !== "auto" ? composeFinal.request.params.aspectRatio : "3:4"]}- initial={{ headline: compose.meta.overlay?.headline ?? "", body: compose.meta.overlay?.body ?? "", cta: compose.meta.overlay?.cta ?? "", layout: compose.meta.format === "poster" ? "frame" : "overlay" }}+ ratios={[composeRatio(composeFinal)]}+ initial={{ ...overlayText(compose), layout: overlayLayout(compose.meta.format) }}brand={composeBrand}onSaveToLibrary={async (url, ratio, text) => {- await send(`/api/marketing/runs/${compose.id}/compose`, "POST", { url, ratio, text: [text.headline, text.body, text.cta].filter(Boolean).join(" · ") });+ await send(`/api/marketing/runs/${compose.id}/compose`, "POST", { url, ratio, text: [text.headline, text.body, text.cta].filter(Boolean).join(" · "), overlay: { headline: text.headline, body: text.body, cta: text.cta } });+ void qc.invalidateQueries({ queryKey: ["marketing-runs", compose.feature] });}}/>)}diff --git a/src/lib/catalog/marketing.ts b/src/lib/catalog/marketing.tsindex 989726a9..98880d94 100644--- a/src/lib/catalog/marketing.ts+++ b/src/lib/catalog/marketing.ts@@ -451,6 +451,30 @@ export const TEMPLATES: MarketingTemplate[] = [export const TEMPLATE_INDEX = new Map(TEMPLATES.map((x) => [x.id, x]));+/**+ * The shape a picked template (or format) opens in: the template's own, else the ratio in use while+ * the format stays the same, else the format's default (a UGC talking head opens 9:16, not the 3:4 of+ * the product shot picked before it).+ */+export function openingAspect(current: { format: FormatId; aspectRatio: string }, t: Pick<MarketingTemplate, "aspect"> | null | undefined, format: FormatId): string {+ const f = FORMATS[format];+ if (t?.aspect && f.aspectRatios.includes(t.aspect)) return t.aspect;+ if (format === current.format && f.aspectRatios.includes(current.aspectRatio)) return current.aspectRatio;+ return f.defaultAspect;+}++/** "www.example.com" → true: a web address the server accepts (a host with a dot, no spaces). */+export function looksLikeWebsite(s: string): boolean {+ const v = s.trim();+ if (!v || /\s/.test(v)) return false;+ try {+ const u = new URL(/^https?:\/\//i.test(v) ? v : `https://${v}`);+ return /^https?:$/.test(u.protocol) && u.hostname.includes(".") && !u.hostname.endsWith(".");+ } catch {+ return false;+ }+}+export function templatesFor(category: MarketingCategory | "all", media: "all" | "image" | "video"): MarketingTemplate[] {return TEMPLATES.filter((x) => {const f = FORMATS[x.format];@@ -610,6 +634,8 @@ export interface AdCreative extends AdConcept {image?: string | null;/** The visual already holds the text (Higgsfield Ads Studio): don't draw over it. */baked?: boolean;+ /** A baked creative's one format (Higgsfield renders a single ratio per ad). */+ ratio?: "1:1" | "4:5" | "9:16";layout?: string | null;engine: Engine;modelId: string;@@ -670,6 +696,25 @@ export function clampClip(r: ClipRange, duration: number, moved: "start" | "end"return { start: tenth(start), end: tenth(end) };}+/** A time typed into an in/out field: "12", "12.5", "12,5", "0:12.5" or "1:02" (seconds); null when it isn't one. */+export function parseClipTime(text: string): number | null {+ const t = text.trim().replace(",", ".");+ const m = /^(?:(\d+):)?(\d+(?:\.\d*)?|\.\d+)$/.exec(t);+ if (!m) return null;+ const s = (m[1] ? Number(m[1]) * 60 : 0) + Number(m[2]);+ return Number.isFinite(s) ? s : null;+}++/**+ * The range after the user finishes typing an in or out time (blur or Enter): the typed time is kept+ * and the other point follows (clampClip). Keystrokes before that don't move anything, so "20" isn't+ * clamped at its first digit.+ */+export function commitClipTime(text: string, range: ClipRange, duration: number, moved: "start" | "end"): ClipRange | null {+ const n = parseClipTime(text);+ return n == null ? null : clampClip({ ...range, [moved]: n }, duration, moved);+}+export interface MultiplierParts {mode: "prompt" | "sections";prompt?: string;@@ -884,6 +929,12 @@ export interface RunOverlay {cta?: string;}+/**+ * How the browser sets the words over an open-engine poster / ad / listing: posters framed on paper+ * (the words beside the picture), the rest over a soft shade at the bottom. The open prompt leaves room to match.+ */+export const overlayLayout = (format?: FormatId): "frame" | "overlay" => (format === "poster" ? "frame" : "overlay");+export interface MarketingRunMeta {format?: FormatId;templateId?: string;@@ -892,6 +943,8 @@ export interface MarketingRunMeta {styleId?: string;/** Open-engine text formats: the exact words the browser sets over the picture. */overlay?: RunOverlay | null;+ /** The picture with those words set (a Library generation), made in the browser once the picture is ready. */+ composed?: { id: string; url: string } | null;script?: string;mode?: "prompt" | "sections";notes?: string[];diff --git a/src/server/ads.ts b/src/server/ads.tsindex 3b81fffa..59852154 100644--- a/src/server/ads.ts+++ b/src/server/ads.ts@@ -405,6 +405,7 @@ function toCreative(r: CreativeRow): AdCreative {generationId: r.generation_id,image: s.image,baked: meta.route === "higgsfield",+ ...(meta.route === "higgsfield" && { ratio: (AD_RATIOS as readonly string[]).includes(meta.ratio ?? "") ? (meta.ratio as AdCreative["ratio"]) : "4:5" }),layout: r.layout,engine: meta.engine,modelId: meta.modelId,@@ -663,12 +664,12 @@ export async function chat(brandId: string, text: string): Promise<ChatMessage[]}/** The user said yes to a proposal: run it and remember the batch on the message. */-export function confirmProposal(brandId: string, messageId: string, engine: Engine, route?: "fuobe" | "higgsfield"): { batchId: string; run: Promise<void>; chat: ChatMessage[] } {+export function confirmProposal(brandId: string, messageId: string, engine: Engine, route?: "fuobe" | "higgsfield", ratio?: BatchInput["ratio"]): { batchId: string; run: Promise<void>; chat: ChatMessage[] } {const history = getChat(brandId);const msg = history.find((m) => m.id === messageId);if (!msg?.proposal) throw new AdsError("That suggestion is no longer available");if (msg.batchId) throw new AdsError("Those ads are already on their way");- const r = createBatch({ brandId, engine, route, items: msg.proposal.items, direction: msg.proposal.direction });+ const r = createBatch({ brandId, engine, route, items: msg.proposal.items, direction: msg.proposal.direction, ratio });const next = history.map((m) => (m.id === messageId ? { ...m, batchId: r.batchId } : m));saveChat(brandId, next);return { batchId: r.batchId, run: r.run, chat: next };diff --git a/src/server/marketing.ts b/src/server/marketing.tsindex 547f5e82..7f7f1323 100644--- a/src/server/marketing.ts+++ b/src/server/marketing.ts@@ -18,6 +18,7 @@ import {MULTIPLIER_MODELS,multiplierResolution,OPEN_SOUND_JOIN,+ overlayLayout,multiplierText,settingById,shotPlan,@@ -36,6 +37,7 @@ import {type Product,type RunEstimate,type RunFeature,+ type RunOverlay,} from "@/lib/catalog/marketing";import { routesFor } from "@/lib/catalog/plan";import { probeMedia } from "@/lib/media-probe";@@ -44,7 +46,7 @@ import { getBrand, getProduct } from "./brand";import { createPipeline, type PipelineStep } from "./chains";import { db } from "./db";import { llmText } from "./enhance";-import { createGenerations, listGenerations, previewChained, recordLocalGeneration } from "./generations";+import { createGenerations, getGeneration, listGenerations, previewChained, recordLocalGeneration } from "./generations";import { provider } from "./providers";import { engineMode } from "./settings";import { readRef } from "./storage";@@ -191,7 +193,11 @@ const KEEP_PRODUCT = "Keep the product exactly as in the reference photo: its sh/** The exact headline/CTA in a prompt (cloud models render text), or room left for the browser to set it (open). */function textLine(f: FormatDef, open: boolean, headline?: string, cta?: string, brand?: BrandKit | null): string {if (!f.text) return "";- if (open) return "Leave clean, uncluttered space at the top third for a headline; no text, letters, words or logos anywhere in the image";+ // Open results get the words set in the browser, in the layout overlayLayout() picks: the picture leaves room for it.+ if (open)+ return overlayLayout(f.id) === "frame"+ ? "No text, letters, words or logos anywhere in the image; the subject well composed with a little breathing room at the edges"+ : "Leave calm, uncluttered space in the lower third for a headline; no text, letters, words or logos anywhere in the image";const font = brand?.fonts.heading ? `set in a ${brand.fonts.heading}-style typeface` : "in bold, clean typography";return [headline && `The headline reads exactly “${headline}” ${font}`, cta && `a button that says exactly “${cta}”`, "spell every word exactly as written, no other text"].filter(Boolean).join(", ");}@@ -1088,12 +1094,20 @@ export async function rerun(id: string): Promise<MarketingRun[]> {return (await runMarketing(MarketingBody.parse(input))).runs;}-/** An open-engine poster/ad with its words set in the browser (an uploaded PNG), recorded in the Library. */-export function saveRunComposite(id: string, input: { url: string; ratio: string; text: string }) {+/**+ * An open-engine poster/ad with its words set in the browser (an uploaded PNG), recorded in the Library+ * and on the run (the card shows it). `auto`: the first composite the browser makes on its own once the+ * picture is ready; a run that has one already keeps it (no duplicate from a second tab).+ */+export function saveRunComposite(id: string, input: { url: string; ratio: string; text: string; overlay?: RunOverlay; auto?: boolean }) {const r = getRun(id);if (!r) throw new PlanError("Not found");+ if (input.auto && r.meta.composed) {+ const existing = getGeneration(r.meta.composed.id);+ if (existing) return existing;+ }const source = r.generations.find((g) => r.finalIds.includes(g.id))?.outputs.find((o) => o.kind === "image")?.url;- return recordLocalGeneration({+ const g = recordLocalGeneration({feature: r.feature,modelId: "local-ad-compose",op: "edit",@@ -1102,6 +1116,9 @@ export function saveRunComposite(id: string, input: { url: string; ratio: stringparams: { aspectRatio: input.ratio },output: { url: input.url, kind: "image", contentType: "image/png" },});+ const meta: MarketingRunMeta = { ...r.meta, composed: { id: g.id, url: input.url }, ...(input.overlay && { overlay: input.overlay }) };+ db().prepare("UPDATE marketing_runs SET meta_json = ? WHERE id = ?").run(JSON.stringify(meta), id);+ return g;}// ---------------------------------------------------------------------------diff --git a/tests/marketing-fixes.test.ts b/tests/marketing-fixes.test.tsindex 4fef8212..61ad82aa 100644--- a/tests/marketing-fixes.test.ts+++ b/tests/marketing-fixes.test.ts@@ -22,6 +22,8 @@ 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 mention = await import("@/components/ads/mention");+const render = await import("@/components/ads/render");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;@@ -300,6 +302,99 @@ describe("chat directions", () => {});});+describe("@product mentions in the chat box", () => {+ const products = [+ { id: "a", name: "Night Serum" },+ { id: "b", name: "Day Cream" },+ { id: "c", name: "Serum Duo" },+ ];+ it("find the '@query' being typed and filter by it", () => {+ expect(mention.mentionQuery("Make five playful ads for @", 27)).toEqual({ start: 26, query: "" });+ expect(mention.mentionQuery("ads for @Ser", 12)).toEqual({ start: 8, query: "Ser" });+ expect(mention.mentionQuery("mail me@home", 12)).toBeNull(); // not after a space+ expect(mention.mentionQuery("for @Night Serum now", 20)).toBeNull();+ expect(mention.mentionMatches(products, "ser").map((p) => p.id)).toEqual(["c", "a"]);+ expect(mention.mentionMatches(products, "")).toHaveLength(3);+ });+ it("replace the typed '@' (and query) with the product instead of appending", () => {+ const t = "Make five playful ads for @";+ expect(mention.insertMention(t, t.length, "Night Serum")).toEqual({ text: "Make five playful ads for @Night Serum ", caret: 39 });+ expect(mention.insertMention("ads for @Ni and more", 11, "Night Serum").text).toBe("ads for @Night Serum and more");+ // From the button, at the caret.+ expect(mention.insertMention("Make ads", 8, "Day Cream").text).toBe("Make ads @Day Cream ");+ // The result reads back cleanly offline.+ const msg = mention.insertMention(t, t.length, "Night Serum").text;+ expect(ads.offlineProposal(msg, products)).toEqual({ count: 5, productIds: ["a"], direction: "playful" });+ });+});++describe("in/out times in the Ad Multiplier", () => {+ it("don't move while typed; the range is clamped once the time is committed", () => {+ const range = { start: 12, end: 16 };+ // Typing "20" into Out: nothing is applied per keystroke, then 12–20 on Enter / blur.+ expect(cat.commitClipTime("20", range, 60, "end")).toEqual({ start: 12, end: 20 });+ expect(cat.commitClipTime("35", range, 60, "end")).toEqual({ start: 12, end: 35 });+ // Past the 30 s limit, the other point follows.+ expect(cat.commitClipTime("50", range, 60, "end")).toEqual({ start: 20, end: 50 });+ expect(cat.commitClipTime("0:45.5", { start: 20, end: 30 }, 60, "end")).toEqual({ start: 20, end: 45.5 });+ expect(cat.commitClipTime("abc", range, 60, "end")).toBeNull();+ expect(cat.parseClipTime("1:02")).toBe(62);+ expect(cat.parseClipTime("12,5")).toBe(12.5);+ expect(cat.parseClipTime(".5")).toBe(0.5);+ expect(cat.parseClipTime("")).toBeNull();+ });+});++describe("composer details", () => {+ it("a template opens in its own shape, else the format's when the format changes", () => {+ // Hero Headline (Ads) after a 3:4 product shot opens 4:5, the Ads default.+ expect(cat.openingAspect({ format: "product-standalone", aspectRatio: "3:4" }, cat.TEMPLATE_INDEX.get("ad-hero-headline"), "ads")).toBe("4:5");+ // A talking head after it opens 9:16.+ expect(cat.openingAspect({ format: "ads", aspectRatio: "3:4" }, cat.TEMPLATE_INDEX.get("ugc-honest-review"), "ugc-talking")).toBe("9:16");+ // Same format: the ratio in use stays.+ expect(cat.openingAspect({ format: "ads", aspectRatio: "1:1" }, cat.TEMPLATE_INDEX.get("ad-offer-burst"), "ads")).toBe("1:1");+ });+ it("checks a website or social link", () => {+ expect(cat.looksLikeWebsite("www.example.com")).toBe(true);+ expect(cat.looksLikeWebsite("https://instagram.com/acme")).toBe(true);+ expect(cat.looksLikeWebsite("acme")).toBe(false);+ expect(cat.looksLikeWebsite("my site.com")).toBe(false);+ });+ it("SaaS motion uses the brand kit's website when no link or product is given", () => {+ const b = { ...cat.emptyKit("Northbound"), id: "b1", website: "https://northbound.example/" } as import("@/lib/catalog/marketing").BrandKit;+ const plan = mk.planMarketing({ engine: "cloud", format: "motion-saas" }, { brand: b, higgsfield: false });+ expect(plan.steps[0].request.prompt).toMatch(/For the product at https:\/\/northbound\.example\//);+ expect(() => mk.planMarketing({ engine: "cloud", format: "motion-saas" }, { higgsfield: false })).toThrow(/website/);+ });+ it("open posters and ads ask for room where the words go", () => {+ const ad = mk.planMarketing({ engine: "open", format: "ads", templateId: "ad-hero-headline", productImages: [upload()] }, { higgsfield: false });+ expect(cat.overlayLayout("ads")).toBe("overlay");+ expect(ad.steps[0].request.prompt).toMatch(/lower third/);+ const poster = mk.planMarketing({ engine: "open", format: "poster", prompt: "A summer concert" }, { higgsfield: false });+ expect(cat.overlayLayout("poster")).toBe("frame");+ expect(poster.steps[0].request.prompt).not.toMatch(/third/);+ });+ it("keeps the browser's own composite on the run once (a second automatic one returns it)", () => {+ const plan = mk.planMarketing({ engine: "open", format: "poster", prompt: "A summer concert", headline: "Live at dusk" }, { higgsfield: false });+ const run = mk.launch(plan);+ expect(run.meta.overlay).toEqual({ headline: "Live at dusk" });+ const first = mk.saveRunComposite(run.id, { url: upload("c1.png"), ratio: "3:4", text: "Live at dusk", auto: true });+ const again = mk.saveRunComposite(run.id, { url: upload("c2.png"), ratio: "3:4", text: "Live at dusk", auto: true });+ expect(again.id).toBe(first.id);+ expect(mk.getRun(run.id)!.meta.composed).toEqual({ id: first.id, url: first.outputs[0].url });+ // An edit from "Edit text" replaces it and keeps the new words.+ const edited = mk.saveRunComposite(run.id, { url: upload("c3.png"), ratio: "3:4", text: "Tonight", overlay: { headline: "Tonight" } });+ expect(edited.id).not.toBe(first.id);+ expect(mk.getRun(run.id)!.meta).toMatchObject({ composed: { id: edited.id }, overlay: { headline: "Tonight" } });+ });++ it("baked ads are letterboxed, never cropped", () => {+ expect(render.containRect(1080, 1350, 1080, 1080)).toEqual({ x: 108, y: 0, w: 864, h: 1080 });+ expect(render.containRect(1080, 1350, 1080, 1350)).toEqual({ x: 0, y: 0, w: 1080, h: 1350 });+ expect(render.containRect(1080, 1351, 1080, 1350)).toMatchObject({ w: 1080, h: 1350 });+ });+});+describe("research progress", () => {it("never goes back while the writing-stage labels rotate", () => {const p = { index: cat.LLM_STAGE.from, startedAt: 0 };