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
Ready-made starters for Faceless, Content Factory, Explainer and the ad studios
Adarsh5ffaa1e1e8f6
diff --git a/docs/public-signup.md b/docs/public-signup.mdindex f5695ae0..043854f9 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -70,7 +70,10 @@ An account is signed in, but it sees the owner's studio as a guest does:owner's Library, with or without a GPU. Accounts have their own uploads and runs (below), but noprojects yet.Canvas shows its ready boards to guests and accounts as read-only pages (`/canvas/start/<id>`):- what goes in, the steps and what comes out. Only the owner makes boards.+ what goes in, the steps and what comes out. Only the owner makes boards. Faceless Studio, Content+ Factory, Explainer, Ads Studio, Click to Ad and Marketing Studio show their ready-made starters the+ same way (`<studio>/start/<id>`); making one (`POST /api/starters/<id>`) is the owner's, and an+ account gets 403 `library`.- **Settings, keys and tokens are the owner's.** Changing settings or model switches, the password,API tokens, Public sign-up, LoRA downloads, Assist connectors and the MCP endpoint answer 403 foran account.diff --git a/scripts/eval/lib/template-covers.mjs b/scripts/eval/lib/template-covers.mjsindex 61fba30e..0f5e8d14 100644--- a/scripts/eval/lib/template-covers.mjs+++ b/scripts/eval/lib/template-covers.mjs@@ -18,7 +18,7 @@ export const TEMPLATE_MANIFEST = path.join(REPO_DIR, "src", "lib", "template-covexport const PEAKS_FILE = path.join(REPO_DIR, "src", "lib", "preset-peaks.generated.ts");/** The tile groups, as the manifest's keys start (`<group>/<tile id>`) and the folders under previews/templates/ are named. */-export const TEMPLATE_GROUPS = ["marketing", "fashion", "photodump", "shorts", "mixed-media", "canvas", "content-factory", "explainer", "soul", "influencer", "examples"];+export const TEMPLATE_GROUPS = ["marketing", "fashion", "photodump", "shorts", "mixed-media", "canvas", "content-factory", "explainer", "soul", "influencer", "examples", "starters"];/** At most this many frames per tile: the cover and up to five more (a contact sheet's 2x2, a carousel's slides, an example storyboard). */const MAX_FRAMES = 6;diff --git a/src/app/(studio)/ads/page.tsx b/src/app/(studio)/ads/page.tsxindex 2e4649ba..deb7d7f4 100644--- a/src/app/(studio)/ads/page.tsx+++ b/src/app/(studio)/ads/page.tsx@@ -1,9 +1,10 @@import type { Metadata } from "next";import { AdsHome } from "@/components/ads/ads-home";import { exampleRow } from "@/lib/examples/catalog";+import { starterCards } from "@/lib/starters/catalog";export const metadata: Metadata = { title: "Ads Studio" };export default function Page() {- return <AdsHome examples={exampleRow("suite:ads")} />;+ return <AdsHome examples={exampleRow("suite:ads")} starters={starterCards("ads")} />;}diff --git a/src/app/(studio)/ads/start/[id]/page.tsx b/src/app/(studio)/ads/start/[id]/page.tsxnew file mode 100644index 00000000..3d1b1104--- /dev/null+++ b/src/app/(studio)/ads/start/[id]/page.tsx@@ -0,0 +1,14 @@+import type { Metadata } from "next";+import { starterMetadata, starterParams, StarterRoute } from "@/components/starters/starter-route";++export function generateStaticParams() {+ return starterParams("ads");+}++export function generateMetadata({ params }: PageProps<"/ads/start/[id]">): Promise<Metadata> {+ return starterMetadata("ads", params);+}++export default function Page({ params }: PageProps<"/ads/start/[id]">) {+ return <StarterRoute surface="ads" params={params} />;+}diff --git a/src/app/(studio)/content-factory/page.tsx b/src/app/(studio)/content-factory/page.tsxindex d0e8d307..9ca19a88 100644--- a/src/app/(studio)/content-factory/page.tsx+++ b/src/app/(studio)/content-factory/page.tsx@@ -2,9 +2,10 @@ import type { Metadata } from "next";import { ContentFactoryHome } from "@/components/content-factory/home";import { getModel } from "@/lib/catalog";import { pickerData } from "@/lib/catalog/faceless";+import { starterCards, starterFills } from "@/lib/starters/catalog";export const metadata: Metadata = { title: "Content Factory" };export default function Page() {- return <ContentFactoryHome voices={pickerData(getModel).voices} />;+ return <ContentFactoryHome voices={pickerData(getModel).voices} starters={starterCards("content-factory")} fills={starterFills("content-factory")} />;}diff --git a/src/app/(studio)/content-factory/start/[id]/page.tsx b/src/app/(studio)/content-factory/start/[id]/page.tsxnew file mode 100644index 00000000..205c0c82--- /dev/null+++ b/src/app/(studio)/content-factory/start/[id]/page.tsx@@ -0,0 +1,14 @@+import type { Metadata } from "next";+import { starterMetadata, starterParams, StarterRoute } from "@/components/starters/starter-route";++export function generateStaticParams() {+ return starterParams("content-factory");+}++export function generateMetadata({ params }: PageProps<"/content-factory/start/[id]">): Promise<Metadata> {+ return starterMetadata("content-factory", params);+}++export default function Page({ params }: PageProps<"/content-factory/start/[id]">) {+ return <StarterRoute surface="content-factory" params={params} />;+}diff --git a/src/app/(studio)/explainer/page.tsx b/src/app/(studio)/explainer/page.tsxindex 928c26f1..d5bf1de3 100644--- a/src/app/(studio)/explainer/page.tsx+++ b/src/app/(studio)/explainer/page.tsx@@ -2,9 +2,10 @@ import type { Metadata } from "next";import { ExplainerStudio } from "@/components/explainer/explainer-studio";import { getModel } from "@/lib/catalog";import { pickerData } from "@/lib/catalog/faceless";+import { starterCards, starterFills } from "@/lib/starters/catalog";export const metadata: Metadata = { title: "Explainer" };export default function Page() {- return <ExplainerStudio picker={pickerData(getModel)} />;+ return <ExplainerStudio picker={pickerData(getModel)} starters={starterCards("explainer")} fills={starterFills("explainer")} />;}diff --git a/src/app/(studio)/explainer/start/[id]/page.tsx b/src/app/(studio)/explainer/start/[id]/page.tsxnew file mode 100644index 00000000..19b6ba16--- /dev/null+++ b/src/app/(studio)/explainer/start/[id]/page.tsx@@ -0,0 +1,14 @@+import type { Metadata } from "next";+import { starterMetadata, starterParams, StarterRoute } from "@/components/starters/starter-route";++export function generateStaticParams() {+ return starterParams("explainer");+}++export function generateMetadata({ params }: PageProps<"/explainer/start/[id]">): Promise<Metadata> {+ return starterMetadata("explainer", params);+}++export default function Page({ params }: PageProps<"/explainer/start/[id]">) {+ return <StarterRoute surface="explainer" params={params} />;+}diff --git a/src/app/(studio)/faceless/[id]/new/page.tsx b/src/app/(studio)/faceless/[id]/new/page.tsxindex cf0470a9..dabc05ce 100644--- a/src/app/(studio)/faceless/[id]/new/page.tsx+++ b/src/app/(studio)/faceless/[id]/new/page.tsx@@ -4,20 +4,24 @@ import { Suspense } from "react";import { EpisodeWizard } from "@/components/faceless/episode-wizard";import { getModel } from "@/lib/catalog";import { pickerData } from "@/lib/catalog/faceless";+import { facelessTopic } from "@/lib/starters/catalog";import { recordExists } from "@/server/records";export const metadata: Metadata = { title: "New episode" };-async function Wizard({ params }: { params: PageProps<"/faceless/[id]/new">["params"] }) {+async function Wizard({ params, searchParams }: Pick<PageProps<"/faceless/[id]/new">, "params" | "searchParams">) {const { id } = await params;if (!recordExists({ kind: "channel", ids: [id] })) notFound();- return <EpisodeWizard channelId={id} picker={pickerData(getModel)} />;+ // A ready channel (?starter=<id>) opens with its first episode's topic written in.+ const { starter } = await searchParams;+ const topic = facelessTopic(typeof starter === "string" ? starter : undefined);+ return <EpisodeWizard channelId={id} picker={pickerData(getModel)} initialTopic={topic} />;}-export default function Page({ params }: PageProps<"/faceless/[id]/new">) {+export default function Page({ params, searchParams }: PageProps<"/faceless/[id]/new">) {return (<Suspense fallback={null}>- <Wizard params={params} />+ <Wizard params={params} searchParams={searchParams} /></Suspense>);}diff --git a/src/app/(studio)/faceless/page.tsx b/src/app/(studio)/faceless/page.tsxindex df7c90d6..e776323d 100644--- a/src/app/(studio)/faceless/page.tsx+++ b/src/app/(studio)/faceless/page.tsx@@ -1,8 +1,9 @@import type { Metadata } from "next";import { FacelessHome } from "@/components/faceless/faceless-home";+import { starterCards } from "@/lib/starters/catalog";export const metadata: Metadata = { title: "Faceless Studio" };export default function Page() {- return <FacelessHome />;+ return <FacelessHome starters={starterCards("faceless")} />;}diff --git a/src/app/(studio)/faceless/start/[id]/page.tsx b/src/app/(studio)/faceless/start/[id]/page.tsxnew file mode 100644index 00000000..8759c696--- /dev/null+++ b/src/app/(studio)/faceless/start/[id]/page.tsx@@ -0,0 +1,14 @@+import type { Metadata } from "next";+import { starterMetadata, starterParams, StarterRoute } from "@/components/starters/starter-route";++export function generateStaticParams() {+ return starterParams("faceless");+}++export function generateMetadata({ params }: PageProps<"/faceless/start/[id]">): Promise<Metadata> {+ return starterMetadata("faceless", params);+}++export default function Page({ params }: PageProps<"/faceless/start/[id]">) {+ return <StarterRoute surface="faceless" params={params} />;+}diff --git a/src/app/(studio)/marketing/click-to-ad/page.tsx b/src/app/(studio)/marketing/click-to-ad/page.tsxindex 304a49cc..258e74ad 100644--- a/src/app/(studio)/marketing/click-to-ad/page.tsx+++ b/src/app/(studio)/marketing/click-to-ad/page.tsx@@ -1,9 +1,10 @@import type { Metadata } from "next";import { ClickToAd } from "@/components/marketing/click-to-ad";import { marketingModelInfo } from "@/components/marketing/model-info";+import { starterCards } from "@/lib/starters/catalog";export const metadata: Metadata = { title: "Click to Ad" };export default function Page() {- return <ClickToAd models={marketingModelInfo()} />;+ return <ClickToAd models={marketingModelInfo()} starters={starterCards("click-to-ad")} />;}diff --git a/src/app/(studio)/marketing/click-to-ad/start/[id]/page.tsx b/src/app/(studio)/marketing/click-to-ad/start/[id]/page.tsxnew file mode 100644index 00000000..bf52ad4e--- /dev/null+++ b/src/app/(studio)/marketing/click-to-ad/start/[id]/page.tsx@@ -0,0 +1,14 @@+import type { Metadata } from "next";+import { starterMetadata, starterParams, StarterRoute } from "@/components/starters/starter-route";++export function generateStaticParams() {+ return starterParams("click-to-ad");+}++export function generateMetadata({ params }: PageProps<"/marketing/click-to-ad/start/[id]">): Promise<Metadata> {+ return starterMetadata("click-to-ad", params);+}++export default function Page({ params }: PageProps<"/marketing/click-to-ad/start/[id]">) {+ return <StarterRoute surface="click-to-ad" params={params} />;+}diff --git a/src/app/(studio)/marketing/page.tsx b/src/app/(studio)/marketing/page.tsxindex 97ed0eb7..d7fd844f 100644--- a/src/app/(studio)/marketing/page.tsx+++ b/src/app/(studio)/marketing/page.tsx@@ -1,9 +1,10 @@import type { Metadata } from "next";import { MarketingStudio } from "@/components/marketing/marketing-studio";import { marketingModelInfo } from "@/components/marketing/model-info";+import { starterCards } from "@/lib/starters/catalog";export const metadata: Metadata = { title: "Marketing Studio" };export default function Page() {- return <MarketingStudio models={marketingModelInfo()} />;+ return <MarketingStudio models={marketingModelInfo()} starters={starterCards("marketing")} />;}diff --git a/src/app/(studio)/marketing/start/[id]/page.tsx b/src/app/(studio)/marketing/start/[id]/page.tsxnew file mode 100644index 00000000..98c0a6e1--- /dev/null+++ b/src/app/(studio)/marketing/start/[id]/page.tsx@@ -0,0 +1,14 @@+import type { Metadata } from "next";+import { starterMetadata, starterParams, StarterRoute } from "@/components/starters/starter-route";++export function generateStaticParams() {+ return starterParams("marketing");+}++export function generateMetadata({ params }: PageProps<"/marketing/start/[id]">): Promise<Metadata> {+ return starterMetadata("marketing", params);+}++export default function Page({ params }: PageProps<"/marketing/start/[id]">) {+ return <StarterRoute surface="marketing" params={params} />;+}diff --git a/src/app/api/starters/[id]/route.ts b/src/app/api/starters/[id]/route.tsnew file mode 100644index 00000000..c8c5892a--- /dev/null+++ b/src/app/api/starters/[id]/route.ts@@ -0,0 +1,21 @@+import { z } from "zod";+import { createFromStarter, StarterError } from "@/server/starters";++const Body = z.object({ engine: z.enum(["cloud", "open"]).default("cloud") });++/**+ * The owner's "Use template" on a ready-made starter: makes it (a channel set up for its first episode, a brand kit with+ * its product) and answers `{ href }`, where it opens. Guests get 401 and accounts 403 before this runs (LIBRARY_CHANGES).+ */+export async function POST(request: Request, { params }: RouteContext<"/api/starters/[id]">) {+ const { id } = await params;+ const parsed = Body.safeParse(await request.json().catch(() => ({})));+ if (!parsed.success) return Response.json({ error: "Pick an engine" }, { status: 400 });+ try {+ return Response.json(await createFromStarter(id, parsed.data.engine), { status: 201 });+ } catch (e) {+ // A studio's own refusal (an engine this install doesn't use, a missing photo) keeps its status.+ const status = e instanceof StarterError ? e.status : ((e as { status?: number }).status ?? 400);+ return Response.json({ error: (e as Error).message || "That starter couldn't be made" }, { status });+ }+}diff --git a/src/components/ads/ads-home.tsx b/src/components/ads/ads-home.tsxindex ba912617..5aaccec2 100644--- a/src/components/ads/ads-home.tsx+++ b/src/components/ads/ads-home.tsx@@ -10,12 +10,14 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTriggeimport { Skeleton } from "@/components/ui/skeleton";import { BrandStart } from "@/components/brand/brand-dialog";import { SelfHostNote } from "@/components/self-host-note";+import { StarterSection } from "@/components/starters/starter-section";import { ExampleRow } from "@/components/studio/example-row";-import { useIsVisitor } from "@/lib/api";+import { useIsOwner, useIsVisitor } from "@/lib/api";import { ResearchLabel } from "@/components/brand/research-progress";import type { BrandKit } from "@/lib/catalog/marketing";import { timeAgo } from "@/lib/format";import type { ExampleRowData } from "@/lib/examples/types";+import { starterShown, type StarterCardData } from "@/lib/starters/types";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";import { useBrandActions, useBrands } from "@/components/marketing/hooks";@@ -100,14 +102,21 @@ function DeleteBrand({ brand, onClose }: { brand: BrandKit | null; onClose: () =/*** Ads Studio home: start from a website (or by hand), and the brand shelf.* examples: "More to try" (exampleRow(), from the page), while there are no brands of one's own.+ * starters: the ready brand kits (src/lib/starters/catalog.ts), first while there are no brands, one row under them after.*/-export function AdsHome({ examples }: { examples?: ExampleRowData | null }) {+export function AdsHome({ examples, starters = [] }: { examples?: ExampleRowData | null; starters?: StarterCardData[] }) {const router = useRouter();const { engine, setEngine } = useMarketingEngine();const brands = useBrands();const [deleting, setDeleting] = useState<BrandKit | null>(null);// A brand is saved to the studio's library, which is its owner's: a guest or an account is told so, not given the form.const visitor = useIsVisitor();+ const owner = useIsOwner();+ const hasBrands = !!brands.data?.length;+ const readyShown = starters.some((s) => starterShown(s, !owner));+ // A "More to try" tile that is a shown starter's own example (the same photo) isn't shown twice.+ const ownExamples = new Set(starters.flatMap((s) => (starterShown(s, !owner) && s.tryIn ? [s.tryIn.example] : [])));+ const moreToTry = examples && { ...examples, cards: examples.cards.filter((c) => !ownExamples.has(c.id)) };return (<div className="flex min-h-content min-w-0 flex-col"><MarketingHeader title="Ads Studio" active="ads" engine={engine} onEngine={setEngine} />@@ -124,35 +133,41 @@ export function AdsHome({ examples }: { examples?: ExampleRowData | null }) {</div></section>- {examples && (visitor || (brands.isSuccess && !brands.data.length)) && <ExampleRow row={examples} className="mt-12" />}+ {!brands.isLoading && !hasBrands && <StarterSection starters={starters} className="mt-12" />}- <section className="mt-14">- <div className="mb-4 flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between sm:gap-3">- <h2 className="font-heading text-[24px] whitespace-nowrap">Your brands</h2>- <span className="text-[12px] text-muted-foreground">Every brand gets its own research, products and ads</span>- </div>- {brands.isLoading ? (- <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">- {Array.from({ length: 3 }, (_, i) => (- <Skeleton key={i} className="aspect-[4/3] rounded-2xl" />- ))}- </div>- ) : brands.data?.length ? (- <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">- {brands.data.map((b) => (- <BrandCard key={b.id} brand={b} onDelete={() => setDeleting(b)} />- ))}+ {!!moreToTry?.cards.length && (visitor || (brands.isSuccess && !brands.data.length)) && <ExampleRow row={moreToTry} className="mt-12" />}++ {(brands.isLoading || hasBrands || !readyShown) && (+ <section className="mt-14">+ <div className="mb-4 flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between sm:gap-3">+ <h2 className="font-heading text-[24px] whitespace-nowrap">Your brands</h2>+ <span className="text-[12px] text-muted-foreground">Every brand gets its own research, products and ads</span></div>- ) : (- <div className="rounded-2xl border border-dashed px-6 py-12 text-center">- <div className="mx-auto grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">- <Target className="size-5" />+ {brands.isLoading ? (+ <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">+ {Array.from({ length: 3 }, (_, i) => (+ <Skeleton key={i} className="aspect-[4/3] rounded-2xl" />+ ))}</div>- <p className="mt-4 text-[15px] font-medium">No brands yet</p>- {!visitor && <p className="mt-1 text-[13px] text-muted-foreground">Paste a link or create one manually to get started.</p>}- </div>- )}- </section>+ ) : brands.data?.length ? (+ <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">+ {brands.data.map((b) => (+ <BrandCard key={b.id} brand={b} onDelete={() => setDeleting(b)} />+ ))}+ </div>+ ) : (+ <div className="rounded-2xl border border-dashed px-6 py-12 text-center">+ <div className="mx-auto grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">+ <Target className="size-5" />+ </div>+ <p className="mt-4 text-[15px] font-medium">No brands yet</p>+ {!visitor && <p className="mt-1 text-[13px] text-muted-foreground">Paste a link or create one manually to get started.</p>}+ </div>+ )}+ </section>+ )}++ {hasBrands && <StarterSection starters={starters} row className="mt-12" />}<section className="mt-12 grid gap-4 md:grid-cols-2"><Link href="/ads/multiplier" className={cn("group flex items-center gap-4 rounded-2xl border bg-background p-4 transition-shadow hover:shadow-soft")}>diff --git a/src/components/canvas/node-icon.tsx b/src/components/canvas/node-icon.tsxindex 78f901d0..6ef456aa 100644--- a/src/components/canvas/node-icon.tsx+++ b/src/components/canvas/node-icon.tsx@@ -40,6 +40,8 @@ import {ZoomIn,type LucideIcon,Box,+ Music,+ Shirt,} from "lucide-react";export const ICONS: Record<string, LucideIcon> = {@@ -82,6 +84,9 @@ export const ICONS: Record<string, LucideIcon> = {Building2,Fish,Dog,+ // Outfit lookbook, music video+ Shirt,+ Music,};/** A node type's or template's icon, by lucide name. */diff --git a/src/components/content-factory/home.tsx b/src/components/content-factory/home.tsxindex 9d33e7cc..59930cde 100644--- a/src/components/content-factory/home.tsx+++ b/src/components/content-factory/home.tsx@@ -3,7 +3,7 @@import { ArrowRight, Bot, Film, Link2, Loader2, Minus, Plus, Sparkles, Upload } from "lucide-react";import Link from "next/link";import { useRouter } from "next/navigation";-import { useEffect, useId, useRef, useState } from "react";+import { Suspense, useEffect, useId, useRef, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";@@ -16,8 +16,10 @@ import { Segmented, usd } from "@/components/faceless/controls";import { NarratorChip } from "@/components/faceless/narrator";import { StyleArt } from "@/components/faceless/style-art";import { SelfHostNote } from "@/components/self-host-note";+import { StarterParam } from "@/components/starters/starter-param";+import { StarterSection } from "@/components/starters/starter-section";import { useEdgeFade } from "@/components/studio/use-edge-fade";-import { uploadFile, useEngine, useHydrated, useLikelyVisitor } from "@/lib/api";+import { uploadFile, useEngine, useHydrated, useIsOwner, useLikelyVisitor } from "@/lib/api";import {ANIMATION_STYLES,CF_LENGTHS,@@ -31,6 +33,7 @@ import {type SeriesCard,} from "@/lib/catalog/content-factory";import { GENRES, type EpisodeAspect, type FacelessGenre, type NarratorVoice, type PickerData } from "@/lib/catalog/faceless";+import { starterShown, type StarterCardData, type StarterFill } from "@/lib/starters/types";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";import { ApiError, discardDraft, useCreateSeries, useGenerateSeries, useRereadSeries, useSeries, useSeriesEstimate, useSeriesList, useUpdateSeries, type SeriesAsk } from "./hooks";@@ -64,7 +67,11 @@ function chipTrigger(className?: string) {return cn("h-8 max-w-full gap-1 rounded-full border-0 bg-secondary px-3 text-[13px] font-medium shadow-none hover:bg-accent dark:bg-secondary dark:hover:bg-accent", className);}-export function ContentFactoryHome({ voices }: { voices: PickerData["voices"] }) {+/**+ * starters: the ready series (src/lib/starters/catalog.ts), right under the composer while you have none, one row under+ * yours after; fills: what each one puts in the composer.+ */+export function ContentFactoryHome({ voices, starters = [], fills = {} }: { voices: PickerData["voices"]; starters?: StarterCardData[]; fills?: Record<string, StarterFill> }) {const router = useRouter();const [engine, setEngine] = useEngine();const [mode, setMode] = useState<"here" | "claude">("here");@@ -105,6 +112,9 @@ export function ContentFactoryHome({ voices }: { voices: PickerData["voices"] })const reread = useRereadSeries();const updateBrief = useUpdateSeries();const list = useSeriesList();+ const owner = useIsOwner();+ const hasSeries = !!list.data?.length;+ const readyShown = starters.some((s) => starterShown(s, !owner));useEffect(() => {if (gone) writeDraft(null);@@ -183,6 +193,21 @@ export function ContentFactoryHome({ voices }: { voices: PickerData["voices"] })startSeries({ kind: "link", link: checked.url }).catch((e: Error) => setLinkError({ message: e.message, upload: e instanceof ApiError && e.needsUpload }));};+ /** A ready series in the composer: its trending style, its idea, its length; the style brings its own look. */+ const fill = (id: string) => {+ const f = fills[id];+ if (f?.kind !== "content-factory") return;+ choosePreset(f.presetId);+ setPrompt(f.prompt);+ setLength(f.length);+ setEpisodes(f.episodes);+ setMode("here");+ requestAnimationFrame(() => {+ promptRef.current?.scrollIntoView({ block: "center", behavior: "smooth" });+ promptRef.current?.focus({ preventScroll: true });+ });+ };+const blocker = !prompt.trim() ? "Say what the video is about" : reading ? "The reference is still being read — a moment" : !brief ? "Add a reference or pick a preset" : null;// One run at a time: a second Enter (or click) before the first request has re-rendered would plan, make and bill it twice.@@ -480,6 +505,8 @@ export function ContentFactoryHome({ voices }: { voices: PickerData["voices"] }))}</div>+ {!list.isLoading && !hasSeries && <StarterSection starters={starters} onFill={fill} />}+<section id="presets" aria-labelledby="presets-title" className="scroll-mt-16 space-y-4"><div><h2 id="presets-title" className="font-heading text-[24px]">@@ -490,32 +517,36 @@ export function ContentFactoryHome({ voices }: { voices: PickerData["voices"] })<PresetGrid value={view ? (view.reference?.presetId ?? null) : presetId} onPick={(p) => choosePreset(p.id)} /></section>- <section aria-labelledby="series-title" className="space-y-4">- <h2 id="series-title" className="font-heading text-[24px]">- My series- </h2>- {list.isLoading ? (- <div className="grid grid-cols-2 gap-x-4 gap-y-6 sm:grid-cols-3 lg:grid-cols-5">- {Array.from({ length: 5 }, (_, i) => (- <Skeleton key={i} className="aspect-[4/5] rounded-xl" />- ))}- </div>- ) : list.data?.length ? (- <div className="grid grid-cols-2 gap-x-4 gap-y-6 sm:grid-cols-3 lg:grid-cols-5">- {list.data.map((s) => (- <SeriesTile key={s.id} s={s} />- ))}- </div>- ) : (- <div className="flex flex-col items-center rounded-2xl border border-dashed px-6 py-10 text-center">- <div className="grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">- <Film className="size-5" />+ {(list.isLoading || hasSeries || !readyShown) && (+ <section aria-labelledby="series-title" className="space-y-4">+ <h2 id="series-title" className="font-heading text-[24px]">+ My series+ </h2>+ {list.isLoading ? (+ <div className="grid grid-cols-2 gap-x-4 gap-y-6 sm:grid-cols-3 lg:grid-cols-5">+ {Array.from({ length: 5 }, (_, i) => (+ <Skeleton key={i} className="aspect-[4/5] rounded-xl" />+ ))}</div>- <p className="mt-3 font-heading text-[22px]">No series yet</p>- <p className="mt-1 max-w-sm text-[13px] text-muted-foreground">Pick a style above and say what to make: every episode lands here, and in Faceless Studio as a channel.</p>- </div>- )}- </section>+ ) : list.data?.length ? (+ <div className="grid grid-cols-2 gap-x-4 gap-y-6 sm:grid-cols-3 lg:grid-cols-5">+ {list.data.map((s) => (+ <SeriesTile key={s.id} s={s} />+ ))}+ </div>+ ) : (+ <div className="flex flex-col items-center rounded-2xl border border-dashed px-6 py-10 text-center">+ <div className="grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">+ <Film className="size-5" />+ </div>+ <p className="mt-3 font-heading text-[22px]">No series yet</p>+ <p className="mt-1 max-w-sm text-[13px] text-muted-foreground">Pick a style above and say what to make: every episode lands here, and in Faceless Studio as a channel.</p>+ </div>+ )}+ </section>+ )}++ {hasSeries && <StarterSection starters={starters} onFill={fill} row />}<section aria-label="How it works" className="grid gap-3 sm:grid-cols-3">{STEPS.map((s, i) => (@@ -533,6 +564,9 @@ export function ContentFactoryHome({ voices }: { voices: PickerData["voices"] })))}</section></div>+ <Suspense fallback={null}>+ <StarterParam onStarter={fill} />+ </Suspense><ClaudeDialog open={claudeOpen} onOpenChange={setClaudeOpen} ask={claudeOpen ? { ...ask, ...source } : null} /></div>);diff --git a/src/components/explainer/explainer-studio.tsx b/src/components/explainer/explainer-studio.tsxindex f0256a94..8e999ff7 100644--- a/src/components/explainer/explainer-studio.tsx+++ b/src/components/explainer/explainer-studio.tsx@@ -2,7 +2,7 @@import { Download, FileText, Image as ImageIcon, Link2, Loader2, Paperclip, Search, Settings2, Sparkles, X } from "lucide-react";import { useRouter } from "next/navigation";-import { useId, useRef, useState } from "react";+import { Suspense, useId, useRef, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";@@ -16,7 +16,9 @@ import { grabFrames } from "@/components/restore/hooks";import { OldFootageOffer } from "@/components/restore/old-footage";import { fileToSlot } from "@/components/studio/media-slot";import { SelfHostNote } from "@/components/self-host-note";-import { useEngine, useLikelyVisitor } from "@/lib/api";+import { StarterParam } from "@/components/starters/starter-param";+import { StarterSection } from "@/components/starters/starter-section";+import { useEngine, useIsOwner, useLikelyVisitor } from "@/lib/api";import {ANIMATION_MODES,AUTO_SECONDS,@@ -35,6 +37,7 @@ import {type ExplainerSource,type PickerData,} from "@/lib/catalog/faceless";+import { starterShown, type StarterCardData, type StarterFill } from "@/lib/starters/types";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";import { EpisodeTile } from "../faceless/cards";@@ -145,8 +148,12 @@ function LinkPopover({ engine, disabled, onAdd }: { engine: EpisodeSettings["eng);}-/** Higgsfield Explainer's form: a style, what to explain, up to 3 sources, the format; plus your history. */-export function ExplainerStudio({ picker }: { picker: PickerData }) {+/**+ * Higgsfield Explainer's form: a style, what to explain, up to 3 sources, the format; plus your history.+ * starters: the ready explainers (src/lib/starters/catalog.ts), where the history is while it's empty, one row under it+ * after; fills: what each one puts in the form.+ */+export function ExplainerStudio({ picker, starters = [], fills = {} }: { picker: PickerData; starters?: StarterCardData[]; fills?: Record<string, StarterFill> }) {const router = useRouter();const [engine, setEngine] = useEngine();// An explainer doesn't run on an account's own GPU yet (only the studios' generations do): said here, not after Generate.@@ -170,6 +177,27 @@ export function ExplainerStudio({ picker }: { picker: PickerData }) {const history = useExplainers({ q, liked: tab === "liked" });const like = useLikeEpisode();const promptId = useId();+ const promptRef = useRef<HTMLTextAreaElement>(null);+ const owner = useIsOwner();+ const readyShown = starters.some((s) => starterShown(s, !owner));+ const noHistory = !history.isLoading && !history.data?.length && tab === "all" && !q;++ /** A ready explainer in the form: its topic, style, length, shape and narrator. */+ const fill = (id: string) => {+ const f = fills[id];+ if (f?.kind !== "explainer") return;+ setPrompt(f.prompt);+ set({ styleId: f.styleId, aspect: f.aspect, ...(f.voice && { voice: { kind: "preset" as const, id: f.voice } }) });+ if (f.duration === "auto" || EXPLAINER_DURATIONS.some((d) => d.value === f.duration)) setDuration(String(f.duration));+ else {+ setDuration("manual");+ setManual(String(f.duration));+ }+ requestAnimationFrame(() => {+ promptRef.current?.scrollIntoView({ block: "center", behavior: "smooth" });+ promptRef.current?.focus({ preventScroll: true });+ });+ };const manualSecs = Math.round(Number(manual));const manualBad = duration === "manual" && (!Number.isInteger(Number(manual)) || manualSecs < EXPLAINER_MIN || manualSecs > EXPLAINER_MAX);@@ -309,6 +337,7 @@ export function ExplainerStudio({ picker }: { picker: PickerData }) {</label><textareaid={promptId}+ ref={promptRef}value={prompt}maxLength={MAX_TOPIC}onChange={(e) => setPrompt(e.target.value)}@@ -442,8 +471,9 @@ export function ExplainerStudio({ picker }: { picker: PickerData }) {</ol></section>- <section aria-labelledby="history-title" className="min-w-0 space-y-4">- <div className="flex flex-wrap items-center gap-2">+ {/* While there is no history yet, the ready explainers stand in its place, without its tabs and search. */}+ <section aria-labelledby={noHistory && readyShown ? "starters-title" : "history-title"} className="min-w-0 space-y-4">+ <div className={cn("flex flex-wrap items-center gap-2", noHistory && readyShown && "hidden")}><h2 id="history-title" className="mr-auto font-heading text-[24px]">History</h2>@@ -473,6 +503,8 @@ export function ExplainerStudio({ picker }: { picker: PickerData }) {<EpisodeTile key={ep.id} ep={ep} href={`/explainer/${ep.id}`} onLike={() => like.mutate({ id: ep.id, favorite: !ep.favorite })} />))}</div>+ ) : noHistory && readyShown ? (+ <StarterSection starters={starters} onFill={fill} narrow />) : (<div className="flex flex-col items-center rounded-2xl border border-dashed px-6 py-12 text-center"><div className="grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">{tab === "liked" ? <ImageIcon className="size-5" /> : <Sparkles className="size-5" />}</div>@@ -480,9 +512,13 @@ export function ExplainerStudio({ picker }: { picker: PickerData }) {<p className="mt-1 max-w-sm text-[13px] text-muted-foreground">{tab === "liked" ? "Like an explainer to keep it here." : "Pick a style, say what to explain, and press Generate."}</p></div>)}+ {!!history.data?.length && tab === "all" && !q && <StarterSection starters={starters} onFill={fill} headingLevel="h3" narrow row className="pt-6" />}</section></div>+ <Suspense fallback={null}>+ <StarterParam onStarter={fill} />+ </Suspense><Sheet open={stylesOpen} onOpenChange={setStylesOpen}>{/* The Sheet's own width is set for its side (data-[side=right]:…): only the same variant overrides it. */}<SheetContent className="overflow-y-auto data-[side=right]:w-full data-[side=right]:sm:max-w-[640px]">diff --git a/src/components/faceless/episode-wizard.tsx b/src/components/faceless/episode-wizard.tsxindex 9f159a44..cfad96a6 100644--- a/src/components/faceless/episode-wizard.tsx+++ b/src/components/faceless/episode-wizard.tsx@@ -58,8 +58,11 @@ function Steps({ step }: { step: 1 | 2 }) {);}-/** New episode: a topic (suggested or your own), the video settings and the script source; then the script is written for review. */-export function EpisodeWizard({ channelId, picker }: { channelId: string; picker: PickerData }) {+/**+ * New episode: a topic (suggested or your own), the video settings and the script source; then the script is written for review.+ * initialTopic: a ready channel's first topic (its starter), in "Or write your own".+ */+export function EpisodeWizard({ channelId, picker, initialTopic }: { channelId: string; picker: PickerData; initialTopic?: string }) {const router = useRouter();const { data, error } = useChannel(channelId);const [engine, setEngine] = useEngine();@@ -70,7 +73,7 @@ export function EpisodeWizard({ channelId, picker }: { channelId: string; pickerconst [round, setRound] = useState(0);const [loadingTopics, setLoadingTopics] = useState(false);const [picked, setPicked] = useState<string | null>(null);- const [own, setOwn] = useState("");+ const [own, setOwn] = useState(initialTopic ?? "");const [scriptMode, setScriptMode] = useState<"ai" | "pasted">("ai");const [script, setScript] = useState("");const [draft, setDraft] = useState<EpisodeSettings | null>(null);diff --git a/src/components/faceless/faceless-home.tsx b/src/components/faceless/faceless-home.tsxindex d75e7537..ab675c86 100644--- a/src/components/faceless/faceless-home.tsx+++ b/src/components/faceless/faceless-home.tsx@@ -11,8 +11,10 @@ import { EngineSwitch } from "@/components/studio/engine-switch";import { radioKeys, radioTab } from "@/components/studio/radio-keys";import { SelfHostNote } from "@/components/self-host-note";import { useEdgeFade } from "@/components/studio/use-edge-fade";-import { useEngine, useLikelyVisitor } from "@/lib/api";+import { StarterSection } from "@/components/starters/starter-section";+import { useEngine, useIsOwner, useLikelyVisitor } from "@/lib/api";import { GENRE_IDEAS, GENRES, MAX_IDEA, MAX_SCRIPT, wordCount, youtubeKind, YOUTUBE_ERROR, type FacelessGenre } from "@/lib/catalog/faceless";+import { starterShown, type StarterCardData } from "@/lib/starters/types";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";import { ChannelCard, EmptyChannels } from "./cards";@@ -27,7 +29,8 @@ const STEPS = [{ icon: Wand2, title: "Review and render", text: "Edit the script scene by scene, render, then fix any scene in the timeline." },];-export function FacelessHome() {+/** starters: the ready channels (src/lib/starters/catalog.ts): first while you have no channels, one row under yours after. */+export function FacelessHome({ starters = [] }: { starters?: StarterCardData[] }) {const router = useRouter();const [engine, setEngine] = useEngine();const [genre, setGenre] = useState<FacelessGenre>("education");@@ -45,6 +48,10 @@ export function FacelessHome() {const [ideaRow, ideaFade] = useEdgeFade<HTMLDivElement>();// A channel doesn't run on an account's own GPU yet (only the studios' generations do): said here, not after Next.const visitor = useLikelyVisitor();+ const owner = useIsOwner();+ const hasChannels = !!channels.data?.length;+ // Until the viewer is known to be the owner, only starters with their real cover show (StarterSection).+ const readyShown = starters.some((s) => starterShown(s, !owner));const checkRef = (v: string) => {const bad = v.trim() && !youtubeKind(v);@@ -195,29 +202,35 @@ export function FacelessHome() {</div></div>- <section aria-labelledby="channels-title" className="space-y-4">- <h2 id="channels-title" className="font-heading text-[24px]">- My channels- </h2>- {channels.isLoading ? (- <div className="grid grid-cols-1 gap-x-5 gap-y-7 sm:grid-cols-2 lg:grid-cols-4">- {Array.from({ length: 4 }, (_, i) => (- <div key={i}>- <Skeleton className="aspect-video rounded-xl" />- <Skeleton className="mt-3 h-4 w-2/3" />- </div>- ))}- </div>- ) : channels.data?.length ? (- <div className="grid grid-cols-1 gap-x-5 gap-y-7 sm:grid-cols-2 lg:grid-cols-4">- {channels.data.map((c) => (- <ChannelCard key={c.id} channel={c} />- ))}- </div>- ) : (- <EmptyChannels />- )}- </section>+ {!channels.isLoading && !hasChannels && <StarterSection starters={starters} />}++ {(channels.isLoading || hasChannels || !readyShown) && (+ <section aria-labelledby="channels-title" className="space-y-4">+ <h2 id="channels-title" className="font-heading text-[24px]">+ My channels+ </h2>+ {channels.isLoading ? (+ <div className="grid grid-cols-1 gap-x-5 gap-y-7 sm:grid-cols-2 lg:grid-cols-4">+ {Array.from({ length: 4 }, (_, i) => (+ <div key={i}>+ <Skeleton className="aspect-video rounded-xl" />+ <Skeleton className="mt-3 h-4 w-2/3" />+ </div>+ ))}+ </div>+ ) : channels.data?.length ? (+ <div className="grid grid-cols-1 gap-x-5 gap-y-7 sm:grid-cols-2 lg:grid-cols-4">+ {channels.data.map((c) => (+ <ChannelCard key={c.id} channel={c} />+ ))}+ </div>+ ) : (+ <EmptyChannels />+ )}+ </section>+ )}++ {hasChannels && <StarterSection starters={starters} row />}<section aria-label="How it works" className="grid gap-3 sm:grid-cols-3">{STEPS.map((s, i) => (diff --git a/src/components/marketing/click-to-ad.tsx b/src/components/marketing/click-to-ad.tsxindex ec15730c..28b4d778 100644--- a/src/components/marketing/click-to-ad.tsx+++ b/src/components/marketing/click-to-ad.tsx@@ -2,7 +2,7 @@import { useQueryClient } from "@tanstack/react-query";import { Check, Clapperboard, Loader2, MousePointerClick, PenLine, RefreshCw, Wand2 } from "lucide-react";-import { useEffect, useMemo, useRef, useState } from "react";+import { Suspense, useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";import { Switch } from "@/components/ui/switch";@@ -12,16 +12,19 @@ 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 { SelfHostNote } from "@/components/self-host-note";+import { StarterSection } from "@/components/starters/starter-section";import { useCoverPlayback } from "@/components/template-cover";import type { SlotValue } from "@/components/studio/media-slot";import { uploadFile, useLikelyVisitor } from "@/lib/api";import { AD_STYLES, END_CARD, KIT_LABELS, type AdStyle, type BrandKit, type MarketingRun, type Product, type RunEstimate } from "@/lib/catalog/marketing";import { formatCost } from "@/lib/format";+import type { StarterCardData } from "@/lib/starters/types";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";import { templateCover } from "@/lib/template-covers";import { recipeKey } from "@/lib/motion/recipe";import { endCardPng, siteLabel, type EndCardInput } from "./end-card";+import { ProductParam } from "./product-param";import { EndCardMotionPanel, renderRecipe, useEndCardMotion, type EndCardChoice } from "./end-card-motion";import { addRuns, send, useBrand, useEstimate, useProductActions, useProducts, useReadingProduct, useUpdateBrand } from "./hooks";import type { ModelInfo } from "./model-info";@@ -143,8 +146,11 @@ function KitBrand({ brand }: { brand: BrandKit }) {);}-/** 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> }) {+/**+ * Click to Ad: product link → product kit → style → a 9:16 ad of up to 12 s with voiceover and captions.+ * starters: the ready products (src/lib/starters/catalog.ts), first while there are no saved products.+ */+export function ClickToAd({ models, starters = [] }: { models: Record<string, ModelInfo>; starters?: StarterCardData[] }) {const qc = useQueryClient();const { engine, setEngine } = useMarketingEngine();const products = useProducts();@@ -318,6 +324,11 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {{visitor && <SelfHostNote className="mx-auto mt-3 max-w-xl">Click to Ad isn't available here.</SelfHostNote>}</div>+ <Suspense fallback={null}>+ <ProductParam products={products.data} onProduct={choose} />+ </Suspense>+ {products.isSuccess && !products.data.length && <StarterSection starters={starters} className="pb-3" />}+<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)} disabled={visitor} />{reading && <KitProgress />}@@ -518,6 +529,8 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {}/></div>++ {!!products.data?.length && <StarterSection starters={starters} row className="pt-8" />}</div></div>);diff --git a/src/components/marketing/marketing-studio.tsx b/src/components/marketing/marketing-studio.tsxindex dbc25bae..aa39bca6 100644--- a/src/components/marketing/marketing-studio.tsx+++ b/src/components/marketing/marketing-studio.tsx@@ -15,16 +15,19 @@ import { withoutOwnGpu } from "@/lib/catalog/engines";import { Switch } from "@/components/ui/switch";import { DRAWN_WORDS_HINT, DRAWN_WORDS_LABEL, FORMATS, formatModels, looksLikeWebsite, pickable, MAX_PROMPT, openingAspect, TEMPLATE_INDEX, type FormatId, type MarketingCategory, type MarketingTemplate, type RunEstimate } from "@/lib/catalog/marketing";import { SelfHostNote } from "@/components/self-host-note";+import { StarterSection } from "@/components/starters/starter-section";import { formatCost } from "@/lib/format";import { useIsOwner, useLikelyVisitor, useModelAccess } from "@/lib/api";import { keepOffered, offered } from "@/lib/model-access";+import type { StarterCardData } from "@/lib/starters/types";import { cn } from "@/lib/utils";-import { addRuns, send, useBrands, useEstimate } from "./hooks";+import { addRuns, send, useBrands, useEstimate, useProducts } from "./hooks";import type { MarketingRun } from "@/lib/catalog/marketing";import { toastError } from "@/lib/refusals";import { templateCover } from "@/lib/template-covers";import type { ModelInfo } from "./model-info";-import { AvatarSlot, HookPicker, ProductSlot, SettingPicker, VoiceControl, type ProductChoice } from "./pickers";+import { AvatarSlot, HookPicker, ProductSlot, productChoice, SettingPicker, VoiceControl, type ProductChoice } from "./pickers";+import { ProductParam } from "./product-param";import { RunsList } from "./runs";import { EmptyIcon, MarketingHeader, useMarketingEngine } from "./shell";import { TemplateGallery, type MediaFilter } from "./template-gallery";@@ -291,10 +294,11 @@ function FormatChip({ draft, onFormat }: { draft: Draft; onFormat: (f: FormatId)function UrlParams({ onTemplate, onTab }: { onTemplate: (t: MarketingTemplate) => void; onTab: (t: "templates" | "generations") => void }) {const q = useSearchParams();- const done = useRef(false);+ // The address read last: a ready shoot opened from this page (?template=…&product=…) is read too, once.+ const done = useRef<string | null>(null);useEffect(() => {- if (done.current) return;- done.current = true;+ if (done.current === q.toString()) return;+ done.current = q.toString();const t = q.get("template");if (t && TEMPLATE_INDEX.get(t)) onTemplate(TEMPLATE_INDEX.get(t)!);if (q.get("tab") === "generations") onTab("generations");@@ -302,8 +306,12 @@ function UrlParams({ onTemplate, onTab }: { onTemplate: (t: MarketingTemplate) =return null;}-/** Marketing Studio: pick a template (or a format), add your product, avatar, hook and brand kit, and generate. */-export function MarketingStudio({ models }: { models: Record<string, ModelInfo> }) {+/**+ * Marketing Studio: pick a template (or a format), add your product, avatar, hook and brand kit, and generate.+ * starters: the ready shoots (a product with its photo and a template; src/lib/starters/catalog.ts), above the templates+ * while there are no saved products.+ */+export function MarketingStudio({ models, starters = [] }: { models: Record<string, ModelInfo>; starters?: StarterCardData[] }) {const qc = useQueryClient();const { engine, setEngine } = useMarketingEngine();const [tab, setTab] = useState<"templates" | "generations">("templates");@@ -331,6 +339,7 @@ export function MarketingStudio({ models }: { models: Record<string, ModelInfo>const [savedBrand, pickBrand] = useSavedBrand();const brands = useBrands();const brandId = savedBrand && brands.data?.some((b) => b.id === savedBrand) ? savedBrand : null;+ const products = useProducts();const pickTemplate = (t: MarketingTemplate) => {setDraft((d) => withTemplate(d, t));@@ -418,6 +427,7 @@ export function MarketingStudio({ models }: { models: Record<string, ModelInfo><MarketingHeader title="Marketing Studio" active="studio" engine={engine} onEngine={setEngine} selfHostedOnly /><Suspense fallback={null}><UrlParams onTemplate={pickTemplate} onTab={setTab} />+ <ProductParam products={products.data} onProduct={(p) => set({ product: productChoice(p) })} /></Suspense><div className="mx-auto w-full min-w-0 max-w-[1240px] flex-1 px-3 pb-10 sm:px-6"><div className="pt-6 pb-2 text-center sm:pt-10">@@ -427,6 +437,7 @@ export function MarketingStudio({ models }: { models: Record<string, ModelInfo></p>{visitor && <SelfHostNote className="mx-auto mt-3 max-w-xl">Marketing Studio isn't available here.</SelfHostNote>}</div>+ {products.isSuccess && !products.data.length && <StarterSection starters={starters} className="mt-6 mb-4" />}<div role="tablist" aria-label="View" className="mx-auto mt-4 flex w-fit rounded-full bg-muted p-0.5">{(["templates", "generations"] as const).map((t) => (<button key={t} role="tab" aria-selected={tab === t} onClick={() => setTab(t)} className={cn("h-8 rounded-full px-4 text-[13px] font-medium text-muted-foreground", tab === t && "bg-background text-foreground shadow-soft")}>@@ -463,6 +474,7 @@ export function MarketingStudio({ models }: { models: Record<string, ModelInfo>/>)}</div>+ {tab === "templates" && !!products.data?.length && <StarterSection starters={starters} row className="mt-12" />}</div>{/* Docked composer */}diff --git a/src/components/marketing/product-param.tsx b/src/components/marketing/product-param.tsxnew file mode 100644index 00000000..4e9e342e--- /dev/null+++ b/src/components/marketing/product-param.tsx@@ -0,0 +1,34 @@+"use client";++import { useSearchParams } from "next/navigation";+import { useEffect, useRef } from "react";+import type { Product } from "@/lib/catalog/marketing";++/**+ * A product named in the address (`?product=<id>`, where a ready-made starter opens): picked once the products load.+ * One the loaded list doesn't have yet (made a moment ago) is read on its own. Render it inside a Suspense boundary+ * (it reads the search params).+ */+export function ProductParam({ products, onProduct }: { products: Product[] | undefined; onProduct: (p: Product) => void }) {+ const id = useSearchParams().get("product");+ const done = useRef<string | null>(null);+ // The page's own picker, as it is now (a new function each render).+ const pick = useRef(onProduct);+ useEffect(() => {+ pick.current = onProduct;+ });+ useEffect(() => {+ if (!id || done.current === id || !products) return;+ done.current = id;+ const p = products.find((x) => x.id === id);+ if (p) return pick.current(p);+ void fetch(`/api/products/${encodeURIComponent(id)}`)+ .then((r) => (r.ok ? (r.json() as Promise<Product>) : null))+ .then((q) => {+ // Still the product the address names.+ if (q && done.current === id) pick.current(q);+ })+ .catch(() => {});+ }, [id, products]);+ return null;+}diff --git a/src/components/starters/starter-icon.tsx b/src/components/starters/starter-icon.tsxnew file mode 100644index 00000000..eb040850--- /dev/null+++ b/src/components/starters/starter-icon.tsx@@ -0,0 +1,11 @@+"use client";++// The starters' icons, by lucide name (src/lib/starters/catalog.ts). Its own small map: a page loads only these.+import { FlaskConical, Gem, Landmark, Leaf, Sailboat, Scissors, Shirt, ShoppingBag, Sparkles, Sun, Waves, type LucideIcon } from "lucide-react";++export const STARTER_ICONS: Record<string, LucideIcon> = { FlaskConical, Gem, Landmark, Leaf, Sailboat, Scissors, Shirt, ShoppingBag, Sun, Waves };++export function StarterIcon({ name, className }: { name: string; className?: string }) {+ const Icon: LucideIcon = STARTER_ICONS[name] ?? Sparkles;+ return <Icon className={className} />;+}diff --git a/src/components/starters/starter-page.tsx b/src/components/starters/starter-page.tsxnew file mode 100644index 00000000..132d1a32--- /dev/null+++ b/src/components/starters/starter-page.tsx@@ -0,0 +1,164 @@+"use client";++import { ArrowLeft, ArrowRight, Loader2, Plus } from "lucide-react";+import Link from "next/link";+import { Button } from "@/components/ui/button";+import { PageShell } from "@/components/page-shell";+import { SelfHostNote } from "@/components/self-host-note";+import { CoverArt, CoverImg, useCoverPlayback } from "@/components/template-cover";+import { useIsOwner, useIsVisitor } from "@/lib/api";+import { STARTER_SURFACES, starterShown, type StarterCardData, type StarterInput } from "@/lib/starters/types";+import { StarterIcon } from "./starter-icon";+import { useStarterUse } from "./starter-section";+import { StepsGlyph } from "./steps-glyph";++function Input({ input }: { input: StarterInput }) {+ return (+ <li className="rounded-xl border bg-card p-3.5">+ <div className="flex items-start gap-3">+ {input.image && (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={input.image.thumb} alt="" loading="lazy" decoding="async" className="size-14 shrink-0 rounded-lg border object-cover" />+ )}+ <div className="min-w-0">+ <p className="text-[14px] font-medium">{input.label}</p>+ {input.image && <p className="text-[13px] text-muted-foreground">{input.image.name}</p>}+ </div>+ </div>+ {input.text && <p className="mt-2 rounded-lg bg-muted/60 px-3 py-2 text-[13px] text-pretty whitespace-pre-line">{input.text}</p>}+ </li>+ );+}++/**+ * A ready-made starter's page (`<studio>/start/<id>`): what it makes, what goes in, the steps and what comes out, for+ * everyone. The owner makes it (or fills the studio's composer with it) from here; a guest or an account, who can't+ * save it here, reads how it works. One with no real cover yet is the owner's only.+ */+export function StarterPage({ s }: { s: StarterCardData }) {+ const owner = useIsOwner();+ const visitor = useIsVisitor();+ const { use, busy } = useStarterUse();+ const { ref, playing, asked, handlers } = useCoverPlayback<HTMLDivElement>(`starter-page/${s.id}`, s.cover);+ const surface = STARTER_SURFACES[s.surface];++ if (!starterShown(s, true) && !owner) {+ return (+ <PageShell>+ {visitor && (+ <div className="py-16 text-center">+ <p className="text-[15px] text-muted-foreground">This starter isn't here.</p>+ <Link href={surface.base} className="mt-3 inline-flex text-[14px] font-medium underline underline-offset-4">+ Back to {surface.name}+ </Link>+ </div>+ )}+ </PageShell>+ );+ }++ const heading = "text-[13px] font-semibold tracking-wide text-muted-foreground uppercase";+ const cover = s.cover;++ return (+ <PageShell wide>+ <Link href={surface.base} className="inline-flex items-center gap-1.5 text-[13px] text-muted-foreground hover:text-foreground">+ <ArrowLeft className="size-3.5" /> {surface.name}+ </Link>+ <div className="mt-3 grid gap-6 lg:grid-cols-[minmax(0,3fr)_minmax(0,2fr)] lg:gap-10">+ <div className="min-w-0">+ <div ref={ref} {...handlers} className="relative aspect-[16/9] overflow-hidden rounded-2xl border bg-muted">+ {cover ? (+ cover.frames.length > 1 ? (+ <div className="absolute inset-0 grid auto-cols-fr grid-flow-col gap-0.5">+ {cover.frames.map((f) => (+ <CoverImg key={f.src} frame={f} sizes="(max-width: 1024px) 34vw, 280px" />+ ))}+ </div>+ ) : (+ <CoverArt cover={cover} sizes="(max-width: 1024px) 100vw, 820px" playing={playing} asked={asked} />+ )+ ) : (+ <div className="absolute inset-0" style={{ background: `linear-gradient(135deg, oklch(0.62 0.12 ${s.hue} / 0.14), transparent 70%)` }}>+ <StepsGlyph steps={s.steps.length} className="p-8" />+ </div>+ )}+ {owner && !cover && <span className="absolute top-3 right-3 rounded-full bg-background/90 px-2 py-0.5 text-[11px] font-medium text-muted-foreground shadow-soft">No cover yet</span>}+ </div>+ </div>++ <div className="min-w-0">+ <div className="flex items-center gap-3">+ <span className="grid size-9 shrink-0 place-items-center rounded-lg border bg-card">+ <StarterIcon name={s.icon} className="size-4" />+ </span>+ <h1 className="font-heading text-[30px] leading-tight text-balance">{s.name}</h1>+ </div>+ <p className="mt-2 text-[15px] text-pretty text-muted-foreground">{s.description}</p>++ {owner ? (+ <div className="mt-4 flex flex-wrap items-center gap-3">+ {s.use.kind === "fill" ? (+ <Button asChild className="rounded-full">+ <Link href={s.use.href}>+ <Plus /> Use template+ </Link>+ </Button>+ ) : (+ <Button className="rounded-full" onClick={() => void use(s)} disabled={busy === s.id}>+ {busy === s.id ? <Loader2 className="animate-spin" /> : <Plus />} Use template+ </Button>+ )}+ </div>+ ) : s.tryIn ? (+ // A guest or an account makes the same from the same photo in its app, the example loaded there.+ <div className="mt-4 flex flex-wrap items-center gap-3">+ <Button asChild className="rounded-full">+ <Link href={s.tryIn.href}>+ Try it in {s.tryIn.label} <ArrowRight />+ </Link>+ </Button>+ </div>+ ) : (+ <SelfHostNote className="mt-3">{surface.unavailable}</SelfHostNote>+ )}++ <section aria-labelledby="goes-in" className="mt-8">+ <h2 id="goes-in" className={heading}>+ What goes in+ </h2>+ <ul className="mt-2 space-y-2">+ {s.inputs.map((i) => (+ <Input key={i.label} input={i} />+ ))}+ </ul>+ </section>++ <section aria-labelledby="the-steps" className="mt-8">+ <h2 id="the-steps" className={heading}>+ The steps+ </h2>+ <ol className="mt-2 space-y-2">+ {s.steps.map((step, i) => (+ <li key={i} className="flex gap-3 text-[14px]">+ <span className="grid size-6 shrink-0 place-items-center rounded-full bg-muted text-[12px] font-medium">{i + 1}</span>+ <span className="min-w-0 pt-0.5 text-pretty">{step}</span>+ </li>+ ))}+ </ol>+ </section>++ <section aria-labelledby="comes-out" className="mt-8">+ <h2 id="comes-out" className={heading}>+ What comes out+ </h2>+ <p className="mt-2 text-[14px] text-pretty">{s.makes}</p>+ <Link href={surface.base} className="mt-4 inline-flex items-center gap-1 text-[13px] font-medium text-muted-foreground hover:text-foreground">+ More in {surface.name} <ArrowRight className="size-3.5" />+ </Link>+ </section>+ </div>+ </div>+ </PageShell>+ );+}diff --git a/src/components/starters/starter-param.tsx b/src/components/starters/starter-param.tsxnew file mode 100644index 00000000..9130c380--- /dev/null+++ b/src/components/starters/starter-param.tsx@@ -0,0 +1,20 @@+"use client";++import { useSearchParams } from "next/navigation";+import { useEffect, useRef } from "react";++/**+ * A ready starter opened from its page (`?starter=<id>`): handed to the studio's composer once per id (Content Factory,+ * Explainer). Render it inside a Suspense boundary (it reads the search params).+ */+export function StarterParam({ onStarter }: { onStarter: (id: string) => void }) {+ const q = useSearchParams();+ const last = useRef<string | null>(null);+ const id = q.get("starter");+ useEffect(() => {+ if (!id || last.current === id) return;+ last.current = id;+ onStarter(id);+ }, [id, onStarter]);+ return null;+}diff --git a/src/components/starters/starter-route.tsx b/src/components/starters/starter-route.tsxnew file mode 100644index 00000000..5c3d88b6--- /dev/null+++ b/src/components/starters/starter-route.tsx@@ -0,0 +1,37 @@+import type { Metadata } from "next";+import { notFound } from "next/navigation";+import { Suspense } from "react";+import { starterIds, starterOn } from "@/lib/starters/catalog";+import { STARTER_SURFACES, type StarterSurface } from "@/lib/starters/types";+import { StarterPage } from "./starter-page";++/*+ * The pages of a studio's ready-made starters (`<studio>/start/<id>`), server-rendered from the catalog: no stored+ * record, so a guest opens them like any page. Each studio's route file is a few lines over these.+ */++export const starterParams = (surface: StarterSurface) => starterIds(surface).map((id) => ({ id }));++export async function starterMetadata(surface: StarterSurface, params: Promise<{ id: string }>): Promise<Metadata> {+ const { id } = await params;+ const s = starterOn(surface, id);+ if (!s) return { title: "Not found" };+ // A starter visitors don't see yet (no real cover): its page is the owner's, kept out of search, its name unsaid.+ if (!s.cover) return { title: `Starter · ${STARTER_SURFACES[surface].name}`, robots: { index: false, follow: false } };+ return { title: `${s.name} · ${STARTER_SURFACES[surface].name}`, description: s.description };+}++async function Starter({ surface, params }: { surface: StarterSurface; params: Promise<{ id: string }> }) {+ const { id } = await params;+ const s = starterOn(surface, id);+ if (!s) notFound();+ return <StarterPage s={s} />;+}++export function StarterRoute({ surface, params }: { surface: StarterSurface; params: Promise<{ id: string }> }) {+ return (+ <Suspense fallback={null}>+ <Starter surface={surface} params={params} />+ </Suspense>+ );+}diff --git a/src/components/starters/starter-section.tsx b/src/components/starters/starter-section.tsxnew file mode 100644index 00000000..360ac5e9--- /dev/null+++ b/src/components/starters/starter-section.tsx@@ -0,0 +1,144 @@+"use client";++import { ArrowRight, Loader2, Plus } from "lucide-react";+import { useQueryClient } from "@tanstack/react-query";+import { useRouter } from "next/navigation";+import { useState, useTransition } from "react";+import { Button } from "@/components/ui/button";+import { StepFlow } from "@/components/canvas/template-card";+import { useEngine, useIsOwner } from "@/lib/api";+import { responseError, toastError } from "@/lib/refusals";+import { STARTER_SURFACES, starterHref, starterShown, type StarterCardData } from "@/lib/starters/types";+import { cn } from "@/lib/utils";+import { StarterCard } from "./starter-card";+import { StarterIcon } from "./starter-icon";+import { StepsGlyph } from "./steps-glyph";++/**+ * The owner's "Use template": a starter made on the server (POST /api/starters/<id>) opens where it answers; one that+ * fills a composer fills it here (`onFill`, on its own studio's page) or opens its studio with `?starter=`.+ */+export function useStarterUse(onFill?: (id: string) => void) {+ const router = useRouter();+ const qc = useQueryClient();+ const [engine] = useEngine();+ const [making, setMaking] = useState<string | null>(null);+ // The page it opens may be this one (Click to Ad, Marketing Studio): busy until that address has rendered.+ const [opening, setOpening] = useState<string | null>(null);+ const [navigating, startTransition] = useTransition();+ const use = async (s: StarterCardData) => {+ if (s.use.kind === "fill") {+ if (onFill) onFill(s.id);+ else router.push(s.use.href);+ return;+ }+ setMaking(s.id);+ try {+ const res = await fetch(`/api/starters/${encodeURIComponent(s.id)}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ engine }) });+ const body = (await res.json().catch(() => ({}))) as { href?: string; error?: string };+ if (!res.ok || !body.href) throw responseError(res, body.error ?? "That starter couldn't be made. Please try again.");+ // What it made (a brand, a product, a channel) is in the lists the next page picks it from, before it opens.+ await Promise.all([qc.invalidateQueries({ queryKey: ["brands"] }), qc.invalidateQueries({ queryKey: ["products"] }), qc.invalidateQueries({ queryKey: ["faceless"] })]);+ const href = body.href;+ setOpening(s.id);+ startTransition(() => router.push(href));+ } catch (e) {+ toastError(e);+ } finally {+ setMaking(null);+ }+ };+ return { use, busy: making ?? (navigating ? opening : null) };+}++/** One starter as a card: the whole card opens its page; the owner's action makes or fills it. */+export function StarterTile({ s, owner, busy, onUse }: { s: StarterCardData; owner: boolean; busy: boolean; onUse: () => void }) {+ return (+ <StarterCard+ coverKey={s.coverKey}+ cover={s.cover}+ hue={s.hue}+ flow={<StepFlow steps={s.flow} />}+ overlay={<StepsGlyph steps={s.steps.length} className="p-6" />}+ icon={<StarterIcon name={s.icon} className="size-4" />}+ title={s.name}+ description={s.description}+ href={starterHref(s)}+ badge={owner && !s.cover ? "No cover yet" : undefined}+ action={+ owner ? (+ <Button size="sm" className="w-fit rounded-full" onClick={onUse} disabled={busy}>+ {busy ? <Loader2 className="animate-spin" /> : <Plus />} Use template+ </Button>+ ) : (+ <span className="inline-flex items-center gap-1 text-[13px] font-medium text-foreground">+ See how it works <ArrowRight className="size-3.5 transition-transform group-hover/starter:translate-x-0.5" />+ </span>+ )+ }+ />+ );+}++/**+ * A surface's ready-made starters ("Start from a ready channel"…): every one for the owner (a card with no cover yet is+ * marked), only those with their real cover for a guest or an account. Nothing at all when there is none to show.+ * `row`: one short row (the first three, "See all" for the rest), under the person's own work; a snap scroller on a phone.+ */+export function StarterSection({+ starters,+ row = false,+ onFill,+ className,+ headingLevel = "h2",+ narrow = false,+}: {+ starters: StarterCardData[];+ row?: boolean;+ onFill?: (id: string) => void;+ className?: string;+ headingLevel?: "h2" | "h3";+ /** In a narrow column (Explainer's history): two cards a row at most. */+ narrow?: boolean;+}) {+ // Until the viewer is known to be the owner, the page is a visitor's: only starters with their real cover show.+ const owner = useIsOwner();+ const { use, busy } = useStarterUse(onFill);+ const [all, setAll] = useState(false);+ const shown = starters.filter((s) => starterShown(s, !owner));+ if (!shown.length) return null;+ const surface = STARTER_SURFACES[shown[0].surface];+ const items = row && !all ? shown.slice(0, 3) : shown;+ // Two cards or fewer: two columns at most, so no column stands empty beside them.+ const few = items.length <= 2;+ const H = headingLevel;+ return (+ <section id="starters" aria-labelledby="starters-title" className={cn("scroll-mt-20", className)}>+ <div className="mb-3 flex flex-wrap items-end gap-x-3 gap-y-1">+ <div className="min-w-0 flex-1">+ <H id="starters-title" className="font-heading text-[24px] leading-tight">+ {surface.section}+ </H>+ <p className="mt-0.5 text-[13px] text-muted-foreground">{surface.note}</p>+ </div>+ {row && shown.length > 3 && (+ <button type="button" onClick={() => setAll((v) => !v)} className="text-[13px] font-medium text-muted-foreground underline-offset-4 hover:text-foreground hover:underline">+ {all ? "Show fewer" : "See all"}+ </button>+ )}+ </div>+ <div+ className={cn(+ "grid grid-cols-1 gap-4 sm:grid-cols-2",+ !narrow && !few && "lg:grid-cols-3",+ !narrow && few && "lg:max-w-[880px]",+ row && !all && "-mx-3 flex snap-x snap-mandatory overflow-x-auto px-3 pb-1 sm:mx-0 sm:grid sm:overflow-visible sm:px-0 sm:pb-0 [&>*]:w-[78%] [&>*]:shrink-0 [&>*]:snap-start sm:[&>*]:w-auto",+ )}+ >+ {items.map((s) => (+ <StarterTile key={s.id} s={s} owner={owner} busy={busy === s.id} onUse={() => void use(s)} />+ ))}+ </div>+ </section>+ );+}diff --git a/src/components/starters/steps-glyph.tsx b/src/components/starters/steps-glyph.tsxnew file mode 100644index 00000000..127b7dbd--- /dev/null+++ b/src/components/starters/steps-glyph.tsx@@ -0,0 +1,39 @@+import { cn } from "@/lib/utils";++const BOX = { w: 280, h: 150, gap: 120 };+const TONES = ["var(--chart-2)", "var(--chart-5)", "var(--chart-4)", "var(--chart-3)", "var(--chart-1)", "var(--primary)"];++/**+ * A starter's steps in miniature, for a card that has no cover yet (the owner's only): one rounded box per step, joined+ * by the same curves as a Canvas board's schematic, drawn from the step count.+ */+export function StepsGlyph({ steps, className }: { steps: number; className?: string }) {+ const n = Math.max(2, Math.min(6, steps));+ const w = n * BOX.w + (n - 1) * BOX.gap;+ const pad = 80;+ // Every other box a little lower, so the line reads as a flow.+ const y = (i: number) => (i % 2 ? 90 : 0);+ return (+ <svg viewBox={`${-pad} ${-pad} ${w + pad * 2} ${BOX.h + 90 + pad * 2}`} preserveAspectRatio="xMidYMid meet" className={cn("size-full", className)} aria-hidden>+ {Array.from({ length: n - 1 }, (_, i) => {+ const x1 = i * (BOX.w + BOX.gap) + BOX.w;+ const x2 = x1 + BOX.gap;+ const y1 = y(i) + BOX.h / 2;+ const y2 = y(i + 1) + BOX.h / 2;+ const mx = (x1 + x2) / 2;+ return <path key={i} d={`M${x1},${y1} C${mx},${y1} ${mx},${y2} ${x2},${y2}`} fill="none" stroke="var(--border-strong)" strokeWidth={8} />;+ })}+ {Array.from({ length: n }, (_, i) => {+ const x = i * (BOX.w + BOX.gap);+ return (+ <g key={i}>+ <rect x={x} y={y(i)} width={BOX.w} height={BOX.h} rx={22} fill="var(--card)" stroke="var(--border-strong)" strokeWidth={4} />+ <rect x={x + 24} y={y(i) + 28} width={44} height={44} rx={10} fill={TONES[i % TONES.length]} opacity={0.85} />+ <rect x={x + 84} y={y(i) + 36} width={150} height={14} rx={7} fill="var(--muted-foreground)" opacity={0.35} />+ <rect x={x + 24} y={y(i) + 94} width={220} height={12} rx={6} fill="var(--muted-foreground)" opacity={0.18} />+ </g>+ );+ })}+ </svg>+ );+}diff --git a/src/lib/catalog/canvas.ts b/src/lib/catalog/canvas.tsindex 9a83eb9c..916d11a4 100644--- a/src/lib/catalog/canvas.ts+++ b/src/lib/catalog/canvas.ts@@ -2166,6 +2166,14 @@ const keyframesAnimation = tpl(],);+/** The outfit lookbook's four looks: one outfit and one place each, the model's face, hair and pose kept. */+const LOOKBOOK_LOOKS = [+ { label: "Paris balcony", prompt: "Dress the woman from the photo in an ivory tailored trouser suit on a Paris balcony in morning light, a wrought-iron rail and zinc rooftops behind her. Keep her face, hair and pose, full length." },+ { label: "Opera staircase", prompt: "Dress the woman from the photo in a black velvet column gown on a grand opera staircase lit by crystal chandeliers, red carpet and gilded balustrades around her. Keep her face, hair and pose, full length." },+ { label: "Alpine terrace", prompt: "Dress the woman from the photo in a long camel cashmere coat over a cream knit on a snowy Alpine hotel terrace at golden hour, the peaks glowing behind her. Keep her face, hair and pose, full length." },+ { label: "Yacht deck", prompt: "Dress the woman from the photo in a white linen shirt and wide white trousers on the teak deck of a yacht off Capri in bright sun, the turquoise sea behind her. Keep her face, hair and pose, full length." },+];+export const CANVAS_TEMPLATES: CanvasTemplate[] = [{id: "keyframes-animation",@@ -2244,6 +2252,95 @@ export const CANVAS_TEMPLATES: CanvasTemplate[] = [],),},+ {+ id: "lookbook",+ name: "Outfit lookbook",+ description: "One model photo, four looks in four places, then one moving shot",+ icon: "Shirt",+ hue: 20,+ rank: 2,+ makes: "Four lookbook pictures of the model and a 5-second moving shot of the first look.",+ flow: ["Model", "4 looks", "Film"],+ steps: [+ "A full-length photo of the model goes in.",+ "Four edits dress her in four outfits, each in its own place: a Paris balcony, an opera staircase, an Alpine terrace and a yacht deck.",+ "The four looks sit side by side as a lookbook.",+ "The first look comes to life as a 5-second moving shot.",+ ],+ inputs: { model: "A full-length photo of a person, head to toe." },+ samples: { model: { src: "/examples/app-3d-rotation/1/in-image.jpg", name: "Model photo.jpg" } },+ build: tpl(+ [+ { id: "model", type: "image-input", x: 0, y: ROW + 160, data: { label: "Model photo" } },+ ...LOOKBOOK_LOOKS.map((l, i) => ({+ id: `look${i + 1}`,+ type: "model" as const,+ x: COL,+ y: i * (ROW + 40),+ data: { mediaKind: "image" as const, label: l.label, op: "edit" as const, prompt: l.prompt, params: { aspectRatio: "3:4" } },+ models: { cloud: "nano-banana-pro", open: "oss-qwen-image-21" },+ })),+ { id: "book", type: "output", x: COL * 2, y: 0, data: { label: "Lookbook" }, width: 560 },+ { id: "animate", type: "model", x: COL * 2, y: ROW * 2 + 200, data: { mediaKind: "video", label: "Moving shot", op: "i2v", prompt: "She turns slowly towards the camera and smiles, the ivory suit moving softly, morning light on her face, the Paris rooftops behind her", params: { aspectRatio: "3:4", duration: 5 } }, models: { cloud: "minimax-h3", open: "oss-minimax-h3" } },+ { id: "out", type: "output", x: COL * 3, y: ROW * 2 + 240, data: { label: "Film" } },+ ],+ [+ ...LOOKBOOK_LOOKS.map((_, i): [string, string, string] => ["model", `look${i + 1}`, "images"]),+ ...LOOKBOOK_LOOKS.map((_, i): [string, string] => [`look${i + 1}`, "book"]),+ ["look1", "animate", "images"],+ ["animate", "out"],+ ],+ ),+ },+ {+ id: "music-video",+ name: "Music video",+ description: "Three song scenes as moving shots, joined into one film, and a song in the same mood",+ icon: "Music",+ hue: 315,+ rank: 4,+ makes: "A film of the three scenes and a 30-second song to go with it.",+ flow: ["Lyrics", "Scenes", "Film"],+ steps: [+ "Each row of the table is one scene: a line of the song and what the picture shows.",+ "Every scene becomes a still.",+ "Every still becomes a 5-second moving shot.",+ "The shots are joined into one film.",+ "A 30-second song is made in the same mood.",+ ],+ build: tpl(+ [+ {+ id: "scenes",+ type: "table",+ x: 0,+ y: 40,+ width: 420,+ data: {+ label: "Scenes",+ columns: ["Lyric", "Scene"],+ rows: [+ ["Midnight, the city is ours", "a fashion model in a silver sequin gown dancing on a Tokyo rooftop at night, neon signs glowing behind her"],+ ["I keep the lights on for you", "the same model in the silver gown driving a red vintage convertible on a coast road at night, city lights below"],+ ["Till the sun comes up", "the model laughing on a Malibu beach at sunrise, the silver gown catching the pink light"],+ ],+ },+ },+ { id: "still", type: "model", x: COL + 180, y: 0, data: { mediaKind: "image", label: "Still", prompt: "{Scene}, a music video still, glossy cinematic light, fashion film look", params: { aspectRatio: "16:9" } }, models: { cloud: "nano-banana-pro", open: "oss-qwen-image-21" } },+ { id: "animate", type: "model", x: COL * 2 + 180, y: 0, data: { mediaKind: "video", label: "Moving shot", op: "i2v", prompt: "She moves to the music, her sequin gown shimmering, the camera gliding slowly around her, lights glowing", params: { aspectRatio: "16:9", duration: 5 } }, models: { cloud: "minimax-h3", open: "oss-minimax-h3" } },+ { id: "film", type: "concat", x: COL * 3 + 180, y: 0, data: { label: "Film", params: { aspectRatio: "16:9" } }, models: { cloud: CONCAT_MODELS.cloud, open: CONCAT_MODELS.open } },+ { id: "song", type: "model", x: COL * 3 + 180, y: FILM_ROW, data: { mediaKind: "audio", label: "Song", op: "music", prompt: "Dreamy synth-pop, 104 bpm, a female vocal, glossy and cinematic, a warm night-drive mood", params: { duration: 30 } }, models: { cloud: "elevenlabs-music", open: "oss-ace-step" } },+ { id: "out", type: "output", x: COL * 4 + 220, y: FILM_ROW / 2, data: { label: "Film and song" } },+ ],+ [+ ["scenes", "still", "prompt"],+ ["still", "animate", "images"],+ ["animate", "film", "videos"],+ ["film", "out"],+ ["song", "out"],+ ],+ ),+ },{id: "script-film",name: "Script → storyboard → film",diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex 771b346c..a3e3bc49 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -135,6 +135,8 @@ const LIBRARY_CHANGES: [methods: string, path: RegExp][] = [],["DELETE", /^\/api\/(katana|marketing\/runs|photodump\/packs)\/[^/]+$/],["POST", /^\/api\/canvases\/[^/]+\/duplicate$/],+ // A ready-made starter (a channel, a brand kit with its product) is saved to the owner's library.+ ["POST", /^\/api\/starters\/[^/]+$/],["POST", /^\/api\/assist\/skills\/[^/]+\/duplicate$/],["POST", /^\/api\/ads\/creatives\/[^/]+\/save$/],["POST", /^\/api\/cinema\/projects\/[^/]+\/folders$/],diff --git a/src/lib/record-pages.ts b/src/lib/record-pages.tsindex a0f1cbd4..04a7fdd5 100644--- a/src/lib/record-pages.ts+++ b/src/lib/record-pages.ts@@ -7,6 +7,8 @@* Pure, so the route table is tested without a server.*/import { HUB_MODES, type HubKind } from "./hubs";+import { STARTER_IDS } from "./starters/ids";+import type { StarterSurface } from "./starters/types";export type RecordKind = "cinema" | "canvas" | "assist-project" | "layers" | "shorts" | "brand" | "element" | "channel" | "episode" | "explainer" | "series" | "swap-project";@@ -38,6 +40,10 @@ const PAGES: [RegExp, (m: string[]) => RecordRef][] = [/** Static pages that a record pattern would also match (/ads/multiplier is not a brand). */const FIXED = new Set(["/ads/multiplier"]);+/** A ready-made starter's page (/faceless/start/<id>…): catalog data, not a stored record. */+const STARTER_PAGE = /^\/(faceless|content-factory|explainer|ads|marketing|marketing\/click-to-ad)\/start\/([^/]+)$/;+const STARTER_BASE: Record<string, StarterSurface> = { faceless: "faceless", "content-factory": "content-factory", explainer: "explainer", ads: "ads", marketing: "marketing", "marketing/click-to-ad": "click-to-ad" };+function decode(s: string): string {try {return decodeURIComponent(s);@@ -49,7 +55,7 @@ function decode(s: string): string {/** The record a page path names (null for every other page). A trailing slash is ignored. */export function recordForPath(pathname: string): RecordRef | null {const path = pathname.length > 1 ? pathname.replace(/\/+$/, "") : pathname;- if (FIXED.has(path)) return null;+ if (FIXED.has(path) || STARTER_PAGE.test(path)) return null;for (const [re, ref] of PAGES) {const m = re.exec(path);if (m) return ref(m.slice(1).map(decode));@@ -57,6 +63,12 @@ export function recordForPath(pathname: string): RecordRef | null {return null;}+/** A starter page (/faceless/start/<id>…) whose id isn't one of that studio's starters. A trailing slash is ignored. */+export function unknownStarterPage(pathname: string): boolean {+ const m = STARTER_PAGE.exec(pathname.length > 1 ? pathname.replace(/\/+$/, "") : pathname);+ return !!m && !STARTER_IDS[STARTER_BASE[m[1]]].includes(decode(m[2]));+}+/** /audio/<mode>, /video-tools/<mode> and /upscale/<mode> with a mode the hub doesn't have. */export function unknownHubMode(pathname: string): boolean {const m = /^\/(audio|video-tools|upscale)\/([^/]+)\/?$/.exec(pathname);diff --git a/src/lib/starters/ads.ts b/src/lib/starters/ads.tsnew file mode 100644index 00000000..2510dd3b--- /dev/null+++ b/src/lib/starters/ads.ts@@ -0,0 +1,148 @@+/**+ * The ad studios' ready brands and products (Ads Studio, Click to Ad, Marketing Studio): one brand kit and product per+ * photo, shared by name, so a second "Use template" on the same product reuses it. Server only, listed in catalog.ts.+ */+import "server-only";+import type { Starter, StarterProduct } from "./catalog";++const MAISON_VERRE: StarterProduct = {+ brand: {+ name: "Maison Verre",+ description:+ "Maison Verre is a small Paris perfume house. Its first scent, Eau de Verre, is a fresh green fragrance of fig leaf, vetiver and sea salt, poured into hand-blown sea-glass bottles with solid oak caps, for people who wear one scent and make it their own.",+ colors: ["#7FB5A5", "#C9A46A", "#F4EFE6"],+ },+ product: {+ name: "Eau de Verre",+ description: "A fresh green eau de parfum of fig leaf, vetiver and sea salt, in a hand-blown sea-glass bottle with a solid oak cap. 50 ml.",+ sellingPoints: ["Hand-blown sea-glass bottle", "Fig leaf, vetiver and sea salt", "Made in Paris in small batches"],+ price: 145,+ currency: "EUR",+ image: { src: "/examples/app-product-shot/1/in-image.jpg", name: "Eau de Verre.jpg" },+ },+};++const STUDIO_MARLOW: StarterProduct = {+ brand: {+ name: "Studio Marlow",+ description:+ "Studio Marlow makes leather goods and tailoring in limited runs, hand-stitched in Florence, for women who want one great bag instead of five okay ones.",+ colors: ["#8A4B2A", "#EFE6DA", "#1F1B18"],+ },+ product: {+ name: "The Marlow top-handle bag",+ description: "A structured top-handle bag in cognac calf leather, hand-stitched in Florence, with brushed-gold hardware and a suede-lined interior.",+ sellingPoints: ["Cognac calf leather", "Hand-stitched in Florence", "Brushed-gold hardware"],+ price: 690,+ currency: "EUR",+ image: { src: "/examples/app-packshot/1/in-image.jpg", name: "Marlow bag.jpg" },+ },+};++const productWords = (k: StarterProduct) => [+ { label: "Brand", text: k.brand.description },+ { label: "Product", text: `${k.product.name}: ${k.product.description}` },+];++export const AD_STARTERS: Starter[] = [+ {+ id: "ads.maison-verre",+ surface: "ads",+ rank: 1,+ name: "Maison Verre perfume",+ description: "A Paris perfume house with its first scent, ready for on-brand ads in every size",+ icon: "FlaskConical",+ hue: 165,+ flow: ["Brand", "Product", "Ads"],+ steps: ["The brand kit is set up: its story, colours and tone.", "Its perfume is added with a product photo, its words and its price.", "Pick how many ads: each gets a headline, a picture and a call to action, in 1:1, 4:5 and 9:16."],+ makes: "On-brand static ads for the perfume, in three sizes.",+ words: productWords(MAISON_VERRE),+ // Its own cover (an ad in its sizes) is on its way: until then it's the owner's only.+ tryIn: { app: "app-product-shot", example: "app-product-shot.1" },+ seed: { kind: "product", kit: MAISON_VERRE, open: { to: "brand" } },+ },+ {+ id: "ads.studio-marlow",+ surface: "ads",+ rank: 2,+ name: "Studio Marlow leather",+ description: "A Florence leather-goods label with its top-handle bag, ready for on-brand ads",+ icon: "ShoppingBag",+ hue: 25,+ flow: ["Brand", "Product", "Ads"],+ steps: ["The brand kit is set up: its story, colours and tone.", "Its bag is added with a product photo, its words and its price.", "Pick how many ads: each gets a headline, a picture and a call to action, in 1:1, 4:5 and 9:16."],+ makes: "On-brand static ads for the bag, in three sizes.",+ words: productWords(STUDIO_MARLOW),+ // Its own cover (an ad in its sizes) is on its way: until then it's the owner's only.+ tryIn: { app: "app-packshot", example: "app-packshot.1" },+ seed: { kind: "product", kit: STUDIO_MARLOW, open: { to: "brand" } },+ },++ // Click to Ad: a product with its photo, ready for a 9:16 video ad.+ {+ id: "c2a.eau-de-verre",+ surface: "click-to-ad",+ rank: 1,+ name: "Perfume video ad",+ description: "A sea-glass perfume bottle becomes a 9:16 ad with voiceover and captions",+ icon: "FlaskConical",+ hue: 165,+ flow: ["Product", "Style", "Ad"],+ steps: ["The perfume is added with its photo, its words and its brand's colours.", "Pick a style: calm studio shots, an unboxing or a creator.", "A script is written, voiced and laid over moving shots of the bottle, with captions and an end card."],+ makes: "A 9:16 video ad of up to 12 seconds, with voiceover and captions.",+ words: productWords(MAISON_VERRE).slice(1),+ // Its own cover (an ad in its sizes) is on its way: until then it's the owner's only.+ tryIn: { app: "app-product-shot", example: "app-product-shot.1" },+ seed: { kind: "product", kit: MAISON_VERRE, open: { to: "click-to-ad" } },+ },+ {+ id: "c2a.marlow-bag",+ surface: "click-to-ad",+ rank: 2,+ name: "Handbag video ad",+ description: "A cognac leather bag becomes a 9:16 ad with voiceover and captions",+ icon: "ShoppingBag",+ hue: 25,+ flow: ["Product", "Style", "Ad"],+ steps: ["The bag is added with its photo, its words and its brand's colours.", "Pick a style: calm studio shots, an unboxing or a creator.", "A script is written, voiced and laid over moving shots of the bag, with captions and an end card."],+ makes: "A 9:16 video ad of up to 12 seconds, with voiceover and captions.",+ words: productWords(STUDIO_MARLOW).slice(1),+ // Its own cover (an ad in its sizes) is on its way: until then it's the owner's only.+ tryIn: { app: "app-packshot", example: "app-packshot.1" },+ seed: { kind: "product", kit: STUDIO_MARLOW, open: { to: "click-to-ad" } },+ },++ // Marketing Studio: a product photo and the template that sets its scene.+ {+ id: "mk.perfume-moss",+ surface: "marketing",+ rank: 1,+ name: "Perfume on moss and stone",+ description: "The perfume photo, set on moss and river stones in soft forest light",+ icon: "Leaf",+ hue: 135,+ flow: ["Product", "Scene", "Shot"],+ steps: ["The perfume and its photo go in.", "The Moss & Stone scene is picked: moss, smooth river stones and soft forest light.", "Press Generate: the bottle is shot in that scene, true to its shape and label."],+ makes: "A product shot of the perfume in a natural forest scene.",+ words: [...productWords(MAISON_VERRE).slice(1), { label: "Scene", text: "The product nestled on moss and smooth river stones, soft forest light filtering through mist." }],+ coverFrom: "app-product-shot",+ tryIn: { app: "app-product-shot", example: "app-product-shot.1" },+ seed: { kind: "product", kit: MAISON_VERRE, open: { to: "marketing", template: "ps-moss-stone" } },+ },+ {+ id: "mk.bag-packshot",+ surface: "marketing",+ rank: 2,+ name: "Handbag packshot",+ description: "The bag photo, as a clean packshot on a seamless white background",+ icon: "ShoppingBag",+ hue: 25,+ flow: ["Product", "Scene", "Shot"],+ steps: ["The bag and its photo go in.", "The Studio White scene is picked: a clean packshot on a seamless white background.", "Press Generate: the bag is shot in that scene, true to its shape and colour."],+ makes: "A clean e-commerce packshot of the bag.",+ words: [...productWords(STUDIO_MARLOW).slice(1), { label: "Scene", text: "A clean e-commerce packshot on a seamless white background." }],+ coverFrom: "app-packshot",+ tryIn: { app: "app-packshot", example: "app-packshot.1" },+ seed: { kind: "product", kit: STUDIO_MARLOW, open: { to: "marketing", template: "ps-studio-white" } },+ },+];diff --git a/src/lib/starters/catalog.ts b/src/lib/starters/catalog.tsnew file mode 100644index 00000000..b91abbf3--- /dev/null+++ b/src/lib/starters/catalog.ts@@ -0,0 +1,184 @@+/**+ * The ready-made starters of Faceless Studio, Content Factory, Explainer, Ads Studio, Click to Ad and Marketing Studio+ * (Canvas's are its templates: src/lib/catalog/canvas.ts). Server only: a page gets its few slim cards+ * (starterCards), and the words, settings and sample files stay here. What the owner's "Use template" makes is in+ * src/server/starters.ts.+ *+ * Built once, when the module loads: a starter that names a style, a preset, a template or a sample file that isn't+ * there throws, so the build fails rather than a page (tests/starters-catalog.test.ts checks the same and more).+ */+import "server-only";+import { getPreset } from "@/lib/catalog";+import { CF_LENGTH_VALUES, getPreset as getCfPreset } from "@/lib/catalog/content-factory";+import { EXPLAINER_STYLE_IDS, FACELESS_LENGTHS, FACELESS_STYLE_IDS, GENRES, type FacelessGenre } from "@/lib/catalog/faceless";+import { TEMPLATE_INDEX } from "@/lib/catalog/marketing";+import { exampleSurfaceOf } from "@/lib/examples/catalog";+import { EXAMPLE_MEDIA } from "@/lib/examples/media.generated";+import { presetCover } from "@/lib/preset-covers";+import { thumbOf } from "@/lib/preset-cards";+import { PRESET_PEAKS } from "@/lib/preset-peaks.generated";+import { templateCover, type TemplateCover } from "@/lib/template-covers";+import { AD_STARTERS } from "./ads";+import { CONTENT_FACTORY_STARTERS } from "./content-factory";+import { EXPLAINER_STARTERS } from "./explainer";+import { FACELESS_STARTERS } from "./faceless";+import type { StarterCardData, StarterFill, StarterInput, StarterSurface } from "./types";++/** A sample file a starter brings: a published example input (src/lib/examples/media.generated.ts). */+export interface StarterSample {+ src: string;+ name: string;+}++/** A brand kit with one product and its photo (Ads Studio, Click to Ad, Marketing Studio share them by name). */+export interface StarterProduct {+ brand: { name: string; description: string; colors: string[] };+ product: { name: string; description: string; sellingPoints: string[]; price: number; currency: string; image: StarterSample };+}++/** What the owner's tap makes or fills. */+export type StarterSeed =+ | { kind: "faceless"; channel: { idea: string; genre: FacelessGenre; name: string }; episode: { topic: string; styleId: string; length: number } }+ | { kind: "fill"; fill: StarterFill }+ | { kind: "product"; kit: StarterProduct; open: { to: "brand" } | { to: "click-to-ad" } | { to: "marketing"; template: string } };++export interface Starter {+ id: string;+ surface: StarterSurface;+ /** Ascending inside its surface: the most premium first. */+ rank: number;+ name: string;+ description: string;+ icon: string;+ hue: number;+ flow: string[];+ steps: string[];+ makes: string;+ /** The words that go in, shown on its page (a photo is added from the seed's sample). */+ words: { label: string; text: string }[];+ /** Until its own cover (starters/<id>) is made: a published preset cover that shows the same product. */+ coverFrom?: string;+ /**+ * The app that makes the same thing from the same photo, with that example loaded (`/apps/<app>?example=<example>`):+ * where a guest or an account goes from the starter's page, and the "More to try" tile its studio leaves out.+ */+ tryIn?: { app: string; example: string };+ seed: StarterSeed;+}++// ---------------------------------------------------------------------------+// The starters, one file per studio++export const STARTERS: Starter[] = [...FACELESS_STARTERS, ...CONTENT_FACTORY_STARTERS, ...EXPLAINER_STARTERS, ...AD_STARTERS];++// ---------------------------------------------------------------------------+// Checks, once, when the module loads++export function assertStarters(list: Starter[] = STARTERS): void {+ const ids = new Set<string>();+ for (const s of list) {+ if (ids.has(s.id)) throw new Error(`Starter ${s.id}: listed twice`);+ ids.add(s.id);+ if (!/^[a-z0-9]+\.[a-z0-9-]+$/.test(s.id)) throw new Error(`Starter ${s.id}: an id is <surface>.<slug>`);+ const seed = s.seed;+ if (seed.kind === "faceless") {+ if (!GENRES.some((g) => g.id === seed.channel.genre)) throw new Error(`Starter ${s.id}: no genre ${seed.channel.genre}`);+ if (!FACELESS_STYLE_IDS.includes(seed.episode.styleId)) throw new Error(`Starter ${s.id}: no Faceless style ${seed.episode.styleId}`);+ if (!FACELESS_LENGTHS.includes(seed.episode.length)) throw new Error(`Starter ${s.id}: ${seed.episode.length} s isn't a Faceless length`);+ } else if (seed.kind === "fill") {+ const f = seed.fill;+ if (f.kind === "content-factory") {+ if (!getCfPreset(f.presetId)) throw new Error(`Starter ${s.id}: no Content Factory preset ${f.presetId}`);+ if (!CF_LENGTH_VALUES.includes(f.length)) throw new Error(`Starter ${s.id}: ${f.length} s isn't a Content Factory length`);+ } else if (!EXPLAINER_STYLE_IDS.includes(f.styleId)) throw new Error(`Starter ${s.id}: no Explainer style ${f.styleId}`);+ } else {+ if (!EXAMPLE_MEDIA[seed.kit.product.image.src]) throw new Error(`Starter ${s.id}: ${seed.kit.product.image.src} isn't a published example file`);+ if (seed.open.to === "marketing" && !TEMPLATE_INDEX.get(seed.open.template)) throw new Error(`Starter ${s.id}: no Marketing template ${seed.open.template}`);+ }+ if (s.coverFrom && !presetCover(s.coverFrom)) throw new Error(`Starter ${s.id}: no preset cover ${s.coverFrom}`);+ if (s.tryIn) {+ if (!getPreset(s.tryIn.app)) throw new Error(`Starter ${s.id}: no app ${s.tryIn.app}`);+ if (exampleSurfaceOf(s.tryIn.example) !== `app:${s.tryIn.app}`) throw new Error(`Starter ${s.id}: ${s.tryIn.example} isn't an example of ${s.tryIn.app}`);+ }+ }+}++assertStarters();++// ---------------------------------------------------------------------------+// Cards and pages++export const getStarter = (id: string): Starter | undefined => STARTERS.find((s) => s.id === id);++/** A preset's cover as a starter's, resting on its peak frame (the finished shot) where it has one. */+function presetAsCover(id: string): TemplateCover | undefined {+ const c = presetCover(id);+ if (!c) return undefined;+ const peak = PRESET_PEAKS[id];+ const poster = peak && c.video ? `/previews/presets/peak/${id}.jpg?v=${peak.v}` : c.poster;+ const thumb = peak && c.video ? thumbOf(poster) : c.thumb;+ return { poster, thumb, ...(c.video && { video: c.video }), ...(peak && c.video && { at: peak.at }), frames: [{ src: poster, thumb }] };+}++/** A starter's real cover: its own (starters/<id>), else the preset cover that shows the same thing. */+export function starterCover(s: Pick<Starter, "id" | "coverFrom">): TemplateCover | undefined {+ return templateCover("starters", s.id) ?? (s.coverFrom ? presetAsCover(s.coverFrom) : undefined);+}++function inputs(s: Starter): StarterInput[] {+ const photo = s.seed.kind === "product" ? s.seed.kit.product.image : undefined;+ return [+ ...(photo ? [{ label: "Product photo", image: { thumb: EXAMPLE_MEDIA[photo.src]?.thumb ?? photo.src, name: photo.name } }] : []),+ ...s.words.map((w) => ({ label: w.label, text: w.text })),+ ];+}++export function starterCard(s: Starter): StarterCardData {+ const cover = starterCover(s);+ return {+ id: s.id,+ surface: s.surface,+ rank: s.rank,+ name: s.name,+ description: s.description,+ icon: s.icon,+ hue: s.hue,+ flow: s.flow,+ steps: s.steps,+ makes: s.makes,+ inputs: inputs(s),+ ...(cover && { cover }),+ coverKey: `starters/${s.id}`,+ ...(s.tryIn && {+ tryIn: { href: `/apps/${s.tryIn.app}?example=${encodeURIComponent(s.tryIn.example)}`, label: getPreset(s.tryIn.app)?.name ?? "the app", example: s.tryIn.example },+ }),+ use: s.seed.kind === "fill" ? { kind: "fill", href: `${s.surface === "content-factory" ? "/content-factory" : "/explainer"}?starter=${encodeURIComponent(s.id)}` } : { kind: "create" },+ };+}++/** A surface's starters as cards, covered first, then by rank (a visitor's list drops the ones with no cover). */+export function starterCards(surface: StarterSurface): StarterCardData[] {+ return STARTERS.filter((s) => s.surface === surface)+ .map(starterCard)+ .sort((a, b) => Number(!a.cover) - Number(!b.cover) || a.rank - b.rank);+}++/** The composers' fills of a surface, by starter id (small: the page gets them all). */+export function starterFills(surface: "content-factory" | "explainer"): Record<string, StarterFill> {+ return Object.fromEntries(STARTERS.flatMap((s) => (s.surface === surface && s.seed.kind === "fill" ? [[s.id, s.seed.fill] as const] : [])));+}++/** Every starter page of a surface, prerendered. */+export const starterIds = (surface: StarterSurface) => STARTERS.filter((s) => s.surface === surface).map((s) => s.id);++/** The starter a page shows, or undefined (not this surface's). */+export function starterOn(surface: StarterSurface, id: string): StarterCardData | undefined {+ const s = getStarter(id);+ return s && s.surface === surface ? starterCard(s) : undefined;+}++/** A Faceless starter's first episode topic, for its new channel's episode setup (`?starter=`). */+export function facelessTopic(id: string | undefined): string | undefined {+ const s = id ? getStarter(id) : undefined;+ return s?.seed.kind === "faceless" ? s.seed.episode.topic : undefined;+}diff --git a/src/lib/starters/content-factory.ts b/src/lib/starters/content-factory.tsnew file mode 100644index 00000000..51cb35e5--- /dev/null+++ b/src/lib/starters/content-factory.ts@@ -0,0 +1,60 @@+/**+ * Content Factory's ready series: a trending style and an idea, filled into the composer. Server only, listed in+ * catalog.ts.+ */+import "server-only";+import type { Starter } from "./catalog";++export const CONTENT_FACTORY_STARTERS: Starter[] = [+ {+ id: "cf.underwater-fashion-week",+ surface: "content-factory",+ rank: 1,+ name: "Fashion week, underwater",+ description: "What if Paris fashion week was held underwater? Quick glossy 3D scenes, vertical",+ icon: "Waves",+ hue: 200,+ flow: ["Style", "Idea", "Short"],+ steps: ["The style is set: an impossible question, answered in quick 3D scenes.", "The idea is in: what if Paris fashion week was held underwater?", "A script, a narrator, pictures, motion, music and captions are made in that style."],+ makes: "A 30-second vertical short with narration, music and captions.",+ words: [+ { label: "Style", text: "What if…? An impossible question, answered in quick 3D scenes." },+ { label: "Make a video about", text: "What if Paris fashion week was held underwater?" },+ ],+ seed: { kind: "fill", fill: { kind: "content-factory", presetId: "what-if", prompt: "What if Paris fashion week was held underwater?", length: 30, episodes: 1 } },+ },+ {+ id: "cf.perfume-atelier",+ surface: "content-factory",+ rank: 2,+ name: "A perfume atelier in a bottle",+ description: "A tiny perfume atelier inside a crystal bottle, in miniature close-ups",+ icon: "FlaskConical",+ hue: 40,+ flow: ["Style", "Idea", "Short"],+ steps: ["The style is set: a tiny world, filmed in miniature close-ups.", "The idea is in: a tiny perfume atelier inside a crystal bottle.", "A script, a narrator, pictures, motion, music and captions are made in that style."],+ makes: "A 30-second vertical short with narration, music and captions.",+ words: [+ { label: "Style", text: "Tiny worlds: a miniature world, filmed up close." },+ { label: "Make a video about", text: "A tiny perfume atelier inside a crystal bottle" },+ ],+ seed: { kind: "fill", fill: { kind: "content-factory", presetId: "tiny-worlds", prompt: "A tiny perfume atelier inside a crystal bottle", length: 30, episodes: 1 } },+ },+ {+ id: "cf.narcissus",+ surface: "content-factory",+ rank: 3,+ name: "Narcissus, the supermodel",+ description: "The myth of Narcissus, retold as the story of a modern supermodel",+ icon: "Gem",+ hue: 280,+ flow: ["Style", "Idea", "Short"],+ steps: ["The style is set: an old myth, retold for today.", "The idea is in: Narcissus as a modern supermodel.", "A script, a narrator, pictures, motion, music and captions are made in that style."],+ makes: "A 30-second vertical short with narration, music and captions.",+ words: [+ { label: "Style", text: "Myth retold: an ancient story, told for today." },+ { label: "Make a video about", text: "Narcissus retold as a modern supermodel" },+ ],+ seed: { kind: "fill", fill: { kind: "content-factory", presetId: "myth-retold", prompt: "Narcissus retold as a modern supermodel", length: 30, episodes: 1 } },+ },+];diff --git a/src/lib/starters/explainer.ts b/src/lib/starters/explainer.tsnew file mode 100644index 00000000..6ef8e999--- /dev/null+++ b/src/lib/starters/explainer.ts@@ -0,0 +1,60 @@+/**+ * Explainer's ready explainers: a topic, a style, a length and a voice, filled into the form. Server only, listed in+ * catalog.ts.+ */+import "server-only";+import type { Starter } from "./catalog";++export const EXPLAINER_STARTERS: Starter[] = [+ {+ id: "ex.couture-400-hours",+ surface: "explainer",+ rank: 1,+ name: "A couture gown in 400 hours",+ description: "How a couture gown takes 400 hours to make, in editorial motion graphics",+ icon: "Scissors",+ hue: 265,+ flow: ["Topic", "Script", "Video"],+ steps: ["The topic, the style and the length are set.", "A script is written to explain it, scene by scene.", "Each scene gets a picture, motion and a calm narrator, then subtitles and music."],+ makes: "A 1-minute explainer video with narration and subtitles, in 16:9.",+ words: [+ { label: "What it explains", text: "How a couture gown takes 400 hours to make" },+ { label: "Style", text: "Editorial motion graphics" },+ ],+ seed: { kind: "fill", fill: { kind: "explainer", prompt: "How a couture gown takes 400 hours to make", styleId: "editorial-motion-graphics", duration: 60, aspect: "16:9", voice: "pFZP5JQG7iQjIQuC4Bku" } },+ },+ {+ id: "ex.riviera-light",+ surface: "explainer",+ rank: 2,+ name: "The golden Riviera light",+ description: "Why the light on the French Riviera looks golden, painted in watercolour",+ icon: "Sun",+ hue: 45,+ flow: ["Topic", "Script", "Video"],+ steps: ["The topic, the style and the length are set.", "A script is written to explain it, scene by scene.", "Each scene gets a picture, motion and a narrator, then subtitles and music."],+ makes: "A 45-second explainer video with narration and subtitles, in 16:9.",+ words: [+ { label: "What it explains", text: "Why the light on the Riviera looks golden" },+ { label: "Style", text: "Watercolour chronicle" },+ ],+ seed: { kind: "fill", fill: { kind: "explainer", prompt: "Why the light on the Riviera looks golden", styleId: "watercolor-chronicle", duration: 45, aspect: "16:9" } },+ },+ {+ id: "ex.perfume-notes",+ surface: "explainer",+ rank: 3,+ name: "A perfume's notes, explained",+ description: "A perfume's top, heart and base notes, in clean studio-lit 3D",+ icon: "FlaskConical",+ hue: 250,+ flow: ["Topic", "Script", "Video"],+ steps: ["The topic, the style and the length are set.", "A script is written to explain it, scene by scene.", "Each scene gets a picture, motion and a narrator, then subtitles and music."],+ makes: "A 45-second explainer video with narration and subtitles, in 16:9.",+ words: [+ { label: "What it explains", text: "A perfume's top, heart and base notes, explained" },+ { label: "Style", text: "Studio 3D" },+ ],+ seed: { kind: "fill", fill: { kind: "explainer", prompt: "A perfume's top, heart and base notes, explained", styleId: "studio-3d", duration: 45, aspect: "16:9" } },+ },+];diff --git a/src/lib/starters/faceless.ts b/src/lib/starters/faceless.tsnew file mode 100644index 00000000..d7721631--- /dev/null+++ b/src/lib/starters/faceless.ts@@ -0,0 +1,90 @@+/**+ * Faceless Studio's ready channels: a channel, its first episode's topic and its look (the owner's "Use template" makes+ * the channel and opens its first episode, src/server/starters.ts). Server only, listed in catalog.ts.+ */+import "server-only";+import type { Starter } from "./catalog";++export const FACELESS_STARTERS: Starter[] = [+ {+ id: "faceless.boat-hotels",+ surface: "faceless",+ rank: 1,+ name: "Hotels you reach by boat",+ description: "A calm luxury travel channel. Episode 1: five hotels you can only reach by boat",+ icon: "Sailboat",+ hue: 200,+ flow: ["Idea", "Script", "Episode"],+ steps: [+ "The channel is set up with its idea, its name and its look.",+ "Episode 1's topic is ready: five hotels you can only reach by boat.",+ "A script is written scene by scene, for you to read and change.",+ "Each scene gets a picture, motion, a narrator and music, then the film is put together with subtitles.",+ ],+ makes: "A 1-minute narrated episode with subtitles, and a channel ready for the next one.",+ words: [+ { label: "Channel idea", text: "Channel about the world's most beautiful hotels you can only reach by boat" },+ { label: "Episode 1", text: "Five hotels you can only reach by boat" },+ { label: "Look", text: "Editorial motion graphics: layered photo cutouts, clean labels and documentary pacing." },+ ],+ seed: {+ kind: "faceless",+ channel: { idea: "Channel about the world's most beautiful hotels you can only reach by boat", genre: "education", name: "Only by Boat" },+ episode: { topic: "Five hotels you can only reach by boat", styleId: "editorial-motion-graphics", length: 60 },+ },+ },+ {+ id: "faceless.couture-icons",+ surface: "faceless",+ rank: 2,+ name: "Dresses that changed fashion",+ description: "A fashion history channel in paper collage. Episode 1: the little black dress",+ icon: "Shirt",+ hue: 330,+ flow: ["Idea", "Script", "Episode"],+ steps: [+ "The channel is set up with its idea, its name and its look.",+ "Episode 1's topic is ready: the little black dress, from 1926 to today.",+ "A script is written scene by scene, for you to read and change.",+ "Each scene gets a picture, motion, a narrator and music, then the film is put together with subtitles.",+ ],+ makes: "A 1-minute narrated episode with subtitles, and a channel ready for the next one.",+ words: [+ { label: "Channel idea", text: "Channel about the dresses that changed fashion" },+ { label: "Episode 1", text: "The little black dress: from 1926 to today" },+ { label: "Look", text: "Paper collage: layered magazine cutouts with torn edges and halftone print texture." },+ ],+ seed: {+ kind: "faceless",+ channel: { idea: "Channel about the dresses that changed fashion", genre: "history", name: "Couture Icons" },+ episode: { topic: "The little black dress: from 1926 to today", styleId: "paper-collage", length: 60 },+ },+ },+ {+ id: "faceless.lost-empires",+ surface: "faceless",+ rank: 3,+ name: "Lost empires of the sea",+ description: "Ancient Mediterranean history in watercolour. Episode 1: the rise and fall of the Minoans",+ icon: "Landmark",+ hue: 30,+ flow: ["Idea", "Script", "Episode"],+ steps: [+ "The channel is set up with its idea, its name and its look.",+ "Episode 1's topic is ready: the rise and fall of the Minoans.",+ "A script is written scene by scene, for you to read and change.",+ "Each scene gets a picture, motion, a narrator and music, then the film is put together with subtitles.",+ ],+ makes: "A 1-minute narrated episode with subtitles, and a channel ready for the next one.",+ words: [+ { label: "Channel idea", text: "Channel about the lost empires of the Mediterranean" },+ { label: "Episode 1", text: "The rise and fall of the Minoans" },+ { label: "Look", text: "Watercolour chronicle: loose painterly washes on textured paper, cinematic framing." },+ ],+ seed: {+ kind: "faceless",+ channel: { idea: "Channel about the lost empires of the Mediterranean", genre: "history", name: "Lost Empires" },+ episode: { topic: "The rise and fall of the Minoans", styleId: "watercolor-chronicle", length: 60 },+ },+ },+];diff --git a/src/lib/starters/ids.ts b/src/lib/starters/ids.tsnew file mode 100644index 00000000..0e57e31a--- /dev/null+++ b/src/lib/starters/ids.ts@@ -0,0 +1,14 @@+/**+ * Every starter's id by studio, client-safe and tiny, for the proxy: a starter page whose id isn't here gets a real 404+ * (src/lib/record-pages.ts unknownStarterPage). tests/starters-catalog.test.ts checks it matches the catalog.+ */+import type { StarterSurface } from "./types";++export const STARTER_IDS: Record<StarterSurface, readonly string[]> = {+ faceless: ["faceless.boat-hotels", "faceless.couture-icons", "faceless.lost-empires"],+ "content-factory": ["cf.underwater-fashion-week", "cf.perfume-atelier", "cf.narcissus"],+ explainer: ["ex.couture-400-hours", "ex.riviera-light", "ex.perfume-notes"],+ ads: ["ads.maison-verre", "ads.studio-marlow"],+ "click-to-ad": ["c2a.eau-de-verre", "c2a.marlow-bag"],+ marketing: ["mk.perfume-moss", "mk.bag-packshot"],+};diff --git a/src/lib/starters/types.ts b/src/lib/starters/types.tsnew file mode 100644index 00000000..3bfb2ce1--- /dev/null+++ b/src/lib/starters/types.ts@@ -0,0 +1,68 @@+/**+ * Ready-made starters outside Canvas (client-safe: no catalog). A starter is a real piece of work, a channel, a series,+ * an explainer, a brand kit or a product with its photo, filled with its own words and settings, so it runs as it is.+ * The list lives on the server (src/lib/starters/catalog.ts); pages get these slim cards as props.+ */+import type { TemplateCover } from "@/lib/template-covers";++export type StarterSurface = "faceless" | "content-factory" | "explainer" | "ads" | "click-to-ad" | "marketing";++/** Where each surface lives, and where its starters' pages are (`<base>/start/<id>`). */+export const STARTER_SURFACES: Record<StarterSurface, { base: string; name: string; section: string; note: string; unavailable: string }> = {+ faceless: { base: "/faceless", name: "Faceless Studio", section: "Start from a ready channel", note: "Each one comes with its idea, its first episode and its look, so it runs as it is.", unavailable: "Faceless channels aren't available here." },+ "content-factory": { base: "/content-factory", name: "Content Factory", section: "Start from a ready series", note: "A style and an idea, ready to make. Change anything before you start.", unavailable: "Content Factory isn't available here." },+ explainer: { base: "/explainer", name: "Explainer", section: "Start from a ready explainer", note: "A topic, a style and a length, ready to make.", unavailable: "Explainer videos aren't available here." },+ ads: { base: "/ads", name: "Ads Studio", section: "Start from a ready brand", note: "A brand kit with a product and its photo, ready for ads.", unavailable: "Brand kits aren't available here." },+ "click-to-ad": { base: "/marketing/click-to-ad", name: "Click to Ad", section: "Start from a ready product", note: "A product with its photo and words, ready for a video ad.", unavailable: "Click to Ad isn't available here." },+ marketing: { base: "/marketing", name: "Marketing Studio", section: "Start from a ready shoot", note: "A product photo and a scene, ready to make.", unavailable: "Marketing Studio isn't available here." },+};++/** What goes in, as a starter's page shows it: its words, or its photo. */+export interface StarterInput {+ label: string;+ text?: string;+ image?: { thumb: string; name: string };+}++/** What the owner's "Use template" does: make it on the server (POST /api/starters/<id>), or fill the composer on this page. */+export type StarterUse = { kind: "create" } | { kind: "fill"; href: string };++/** A starter as its card and its page show it. Its words are visitor words: no model names. */+export interface StarterCardData {+ id: string;+ surface: StarterSurface;+ rank: number;+ name: string;+ description: string;+ /** lucide icon name (StarterIcon). */+ icon: string;+ hue: number;+ /** The steps as a word or two each, over the cover's corner. */+ flow: string[];+ /** The steps in plain words (its page's "The steps"). */+ steps: string[];+ /** What comes out, in plain words. */+ makes: string;+ inputs: StarterInput[];+ /** Its real cover, when it has one: visitors only see starters that have it. */+ cover?: TemplateCover;+ /** The cover's key, for one-clip-at-a-time playback. */+ coverKey: string;+ use: StarterUse;+ /** The app that makes the same from the same photo, its example loaded: a visitor's next step from the page. */+ tryIn?: { href: string; label: string; example: string };+}++/**+ * The composer a "fill" starter loads (Content Factory, Explainer): small enough to pass to the page, read when the+ * page opens with `?starter=<id>` or when the owner taps "Use template" on its card.+ */+export type StarterFill =+ | { kind: "content-factory"; presetId: string; prompt: string; length: number; episodes: number }+ | { kind: "explainer"; prompt: string; styleId: string; duration: "auto" | number; aspect: "9:16" | "16:9"; voice?: string };++/** The starter's page (`<base>/start/<id>`). */+export const starterHref = (s: Pick<StarterCardData, "id" | "surface">) => `${STARTER_SURFACES[s.surface].base}/start/${s.id}`;++/** Who sees a starter's card: a visitor only one with its real cover (the owner sees all, marked). */+export const starterShown = (s: Pick<StarterCardData, "cover">, visitor: boolean) => !visitor || !!s.cover;diff --git a/src/lib/template-covers.ts b/src/lib/template-covers.tsindex 7b75556a..dd624dfb 100644--- a/src/lib/template-covers.ts+++ b/src/lib/template-covers.ts@@ -1,16 +1,16 @@/*** The real covers of the studios' template and style tiles (Marketing Studio's templates, Fashion Factory, Photodump* packs, the Shorts and Mixed Media looks, Canvas templates, Content Factory's trending styles, the Explainer styles,- * Fuobe Soul's looks, AI Influencer's character types, and the example pictures of Character Sheet, Storyboard and- * Elements), from template-covers.generated.ts (pnpm eval:covers --templates). A tile that isn't listed keeps its drawn- * art. Every URL comes from the manifest with its version (?v=): never build one here without it.+ * Fuobe Soul's looks, AI Influencer's character types, the example pictures of Character Sheet, Storyboard and+ * Elements, and the studios' ready-made starters), from template-covers.generated.ts (pnpm eval:covers --templates). A+ * tile that isn't listed keeps its drawn art. Every URL comes from the manifest with its version (?v=): never build one here without it.*/import { thumbOf, type PresetPreview } from "./preset-cards";import { TEMPLATE_COVERS, type TemplateCoverEntry } from "./template-covers.generated";-export type TemplateGroup = "marketing" | "fashion" | "photodump" | "shorts" | "mixed-media" | "canvas" | "content-factory" | "explainer" | "soul" | "influencer" | "examples";+export type TemplateGroup = "marketing" | "fashion" | "photodump" | "shorts" | "mixed-media" | "canvas" | "content-factory" | "explainer" | "soul" | "influencer" | "examples" | "starters";-export const TEMPLATE_GROUPS: readonly TemplateGroup[] = ["marketing", "fashion", "photodump", "shorts", "mixed-media", "canvas", "content-factory", "explainer", "soul", "influencer", "examples"];+export const TEMPLATE_GROUPS: readonly TemplateGroup[] = ["marketing", "fashion", "photodump", "shorts", "mixed-media", "canvas", "content-factory", "explainer", "soul", "influencer", "examples", "starters"];/** One still of a cover, and its 320 px copy (thumbs/ next to it, with the same version). */export interface CoverFrame {diff --git a/src/proxy.ts b/src/proxy.tsindex 8d590a5d..a556ac8d 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -1,7 +1,7 @@import { NextResponse, type NextRequest } from "next/server";import { APPS } from "@/lib/catalog/apps";import { modeHref, type HubKind } from "@/lib/hubs";-import { recordForPath, unknownHubMode } from "@/lib/record-pages";+import { recordForPath, unknownHubMode, unknownStarterPage } from "@/lib/record-pages";import { countsAsView, SHARE_VIEW_HEADER, shareRoute } from "@/lib/share";import {ACCOUNT_LIBRARY_MESSAGE,@@ -69,7 +69,7 @@ const APP_IDS = new Set(APPS.map((a) => a.id));function pass(request: NextRequest): NextResponse {const { pathname } = request.nextUrl;const app = /^\/apps\/([^/]+)\/?$/.exec(pathname)?.[1];- if ((app && !APP_IDS.has(safeDecode(app))) || unknownHubMode(pathname)) return notFound(request);+ if ((app && !APP_IDS.has(safeDecode(app))) || unknownHubMode(pathname) || unknownStarterPage(pathname)) return notFound(request);const record = recordForPath(pathname);if (record && !recordExists(record)) return notFound(request);return NextResponse.next();diff --git a/src/server/canvas-samples.ts b/src/server/canvas-samples.tsindex 45018d85..ecdec386 100644--- a/src/server/canvas-samples.ts+++ b/src/server/canvas-samples.ts@@ -39,6 +39,12 @@ function storedSample(abs: string): string {return saveFile({ data, contentType: contentTypeFor(abs), name: key, source: "derived" }).url;}+/** A sample's stored copy (/api/files/…), made once and reused, or null when it names no file Fuobe ships (other starters' photos). */+export function adoptSample(src: string): string | null {+ const abs = sampleFile(src);+ return abs ? storedSample(abs) : null;+}+/*** The board with its starting files in place: each input node a sample names gets the stored copy and a plain name. A* sample whose file isn't there leaves its input empty (the board still opens, and asks for that one file).diff --git a/src/server/starters.ts b/src/server/starters.tsnew file mode 100644index 00000000..00a1c6c5--- /dev/null+++ b/src/server/starters.ts@@ -0,0 +1,68 @@+import "server-only";+import type { Engine } from "@/lib/catalog/types";+import { getStarter, type StarterProduct } from "@/lib/starters/catalog";+import { createManualBrand, createProduct, listBrands, listProducts, updateProduct } from "./brand";+import { adoptSample } from "./canvas-samples";+import { createChannel } from "./faceless";++/**+ * The owner's "Use template" on a starter that is made here (POST /api/starters/<id>): a Faceless channel set up for+ * its first episode, or a brand kit with its product and photo (Ads Studio, Click to Ad, Marketing Studio). It answers+ * where to go next. A starter that fills a composer (Content Factory, Explainer) is opened, not made.+ *+ * Guests get 401 and accounts 403 "library" before this runs (LIBRARY_CHANGES in src/lib/guest-access.ts): a starter+ * is saved to the owner's library.+ */++export class StarterError extends Error {+ constructor(+ message: string,+ readonly status = 400,+ ) {+ super(message);+ }+}++/**+ * The starter's brand kit and product: the ones made before (by name) while they are there, else new ones. Its photo+ * is a stored copy of the published sample, made once.+ */+async function brandAndProduct(kit: StarterProduct): Promise<{ brandId: string; productId: string }> {+ const photo = adoptSample(kit.product.image.src);+ if (!photo) throw new StarterError("That starter's photo is missing", 500);+ const known = listBrands().find((b) => b.name === kit.brand.name);+ const brand = known ?? (await createManualBrand({ name: kit.brand.name, description: kit.brand.description, colors: kit.brand.colors, images: [photo] }));+ // The same product made before is reused; one whose photo was taken off gets it back (not a second copy).+ const had = listProducts(brand.id).find((p) => p.name === kit.product.name);+ const product =+ (had && (had.images.length ? had : updateProduct(had.id, { images: [photo] }))) ??+ createProduct(+ { name: kit.product.name, brandId: brand.id, description: kit.product.description, sellingPoints: kit.product.sellingPoints, price: kit.product.price, currency: kit.product.currency, images: [photo] },+ { force: true },+ );+ return { brandId: brand.id, productId: product.id };+}++/** Make the starter and say where it opens. */+export async function createFromStarter(id: string, engine: Engine): Promise<{ href: string }> {+ const s = getStarter(id);+ if (!s) throw new StarterError("That starter doesn't exist", 404);+ const seed = s.seed;+ if (seed.kind === "fill") throw new StarterError("That starter opens in its studio: nothing to make here");+ if (seed.kind === "faceless") {+ const channel = await createChannel({+ idea: seed.channel.idea,+ genre: seed.channel.genre,+ engine,+ name: seed.channel.name,+ settings: { styleId: seed.episode.styleId, length: seed.episode.length },+ });+ return { href: `/faceless/${channel.id}/new?starter=${encodeURIComponent(s.id)}` };+ }+ const { brandId, productId } = await brandAndProduct(seed.kit);+ const open = seed.open;+ // The brand opens on "New ads", its product in place: pick how many and make them.+ if (open.to === "brand") return { href: `/ads/${brandId}?step=new` };+ if (open.to === "click-to-ad") return { href: `/marketing/click-to-ad?product=${productId}` };+ return { href: `/marketing?template=${encodeURIComponent(open.template)}&product=${productId}` };+}diff --git a/tests/e2e/starters-b.mjs b/tests/e2e/starters-b.mjsnew file mode 100644index 00000000..1e3eb46f--- /dev/null+++ b/tests/e2e/starters-b.mjs@@ -0,0 +1,258 @@+// The ready-made starters of Faceless Studio, Content Factory, Explainer, Ads Studio, Click to Ad and Marketing Studio,+// and Canvas's Outfit lookbook and Music video boards, as a guest, a fresh account and the owner, at 390 and 1440 px:+// the owner's empty studio leads with its starters (each one marked until its cover exists), visitors see only starters+// with a real cover and no model or engine words, every starter has a read-only page, and the owner's "Use template"+// opens the channel's first episode, the filled composer, the brand kit, the product's ad or the product shot, ready+// to run. After that the owner's own work leads and the starters sit in one row below.+//+// node tests/e2e/starters-b.mjs <app address> <owner password> [screenshot folder]+// Against `next start` with a fresh data dir, FUOBE_PUBLIC_SIGNUP=1 and demo mode on (FUOBE_DEMO_MODE=on).+import fs from "node:fs";+import path from "node:path";+import { launch, PHONE, DESKTOP } from "./_browser.mjs";++const [app, password, shots] = process.argv.slice(2);+if (!app || !password) throw new Error("usage: node tests/e2e/starters-b.mjs <app address> <owner password> [screenshot folder]");+if (shots) fs.mkdirSync(shots, { recursive: true });++const ENGINE_WORDS = /Fuobe DoP|Effects 2\.0|\bGPU\b|Qwen|MiniMax|Nano Banana|Seedance|Ideogram|Kling|ElevenLabs|ACE-Step|placeholder/;+const failures = [];+const check = (name, ok, detail = "") => {+ console.log(`${ok ? "ok " : "FAIL"} ${name}${detail ? ` (${detail})` : ""}`);+ if (!ok) failures.push(name);+};++/** Each studio, the heading of its starters, how many it has, and whether visitors see them yet (a real cover). */+const SURFACES = [+ { path: "/faceless", heading: "Start from a ready channel", n: 3, covered: false, first: "faceless.boat-hotels" },+ { path: "/content-factory", heading: "Start from a ready series", n: 3, covered: false, first: "cf.underwater-fashion-week" },+ { path: "/explainer", heading: "Start from a ready explainer", n: 3, covered: false, first: "ex.couture-400-hours" },+ // An ad and a video ad wait for their own covers (a plain product shot isn't what they make).+ { path: "/ads", heading: "Start from a ready brand", n: 2, covered: false, first: "ads.maison-verre" },+ { path: "/marketing/click-to-ad", heading: "Start from a ready product", n: 2, covered: false, first: "c2a.eau-de-verre" },+ { path: "/marketing", heading: "Start from a ready shoot", n: 2, covered: true, first: "mk.perfume-moss", tryIn: "/apps/app-product-shot?example=app-product-shot.1" },+];++async function signIn(ctx, persona) {+ if (persona === "owner") {+ const r = await ctx.request.post(`${app}/api/auth/login`, { data: { password } });+ if (!r.ok()) throw new Error(`owner login ${r.status()}`);+ } else if (persona === "account") {+ const email = `starters-b-${Date.now()}-${Math.random().toString(36).slice(2, 6)}@example.com`;+ const r = await ctx.request.post(`${app}/api/auth/signup`, { data: { email, password: "starters-b-pw-123" } });+ if (!r.ok()) throw new Error(`signup ${r.status()}`);+ }+}++const browser = await launch();+try {+ for (const persona of ["guest", "account", "owner"]) {+ for (const [size, device] of [+ ["390", PHONE],+ ["1440", DESKTOP],+ ]) {+ const tag = `${persona} ${size}`;+ const ctx = await browser.newContext({ ...device, colorScheme: "light" });+ await signIn(ctx, persona);+ const page = await ctx.newPage();+ page.setDefaultTimeout(30_000);+ const errors = [];+ // Click to Ad's end-card Save button reads the viewer's runs label from the browser (a hydration mismatch, #418, for+ // an account): not this page's, logged apart so it doesn't hide a new error.+ const known = [];+ page.on("pageerror", (e) => (/\/marketing\/click-to-ad/.test(page.url()) && /#418/.test(String(e)) ? known : errors).push(`${page.url()} :: ${String(e).slice(0, 200)}`));+ const shot = async (name) => shots && page.screenshot({ path: path.join(shots, `${name}--${persona}--${size}.png`), fullPage: false });+ const fullShot = async (name) => shots && page.screenshot({ path: path.join(shots, `${name}--${persona}--${size}--full.png`), fullPage: true });+ const sideways = () => page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);+ const text = () => page.locator("main, body").first().innerText();+ const owner = persona === "owner";++ // ---- Each studio's first screen, with nothing of one's own yet+ for (const s of SURFACES) {+ const name = s.path.slice(1).replaceAll("/", "-");+ await page.goto(`${app}${s.path}`, { waitUntil: "load", timeout: 180_000 });+ if (owner || s.covered) await page.getByRole("heading", { name: s.heading }).waitFor({ timeout: 60_000 }).catch(() => {});+ else await page.waitForTimeout(2500);+ const section = page.locator("#starters");+ const cards = section.locator("article");+ const n = await cards.count();+ const t = await text();+ if (owner) {+ check(`${tag}: ${s.path} leads with its ${s.n} starters`, n === s.n, `${n}`);+ check(`${tag}: ${s.path} starters each have Use template`, (await section.getByRole("button", { name: "Use template" }).count()) === s.n);+ if (!s.covered) check(`${tag}: ${s.path} marks the starters without a cover`, (await section.getByText("No cover yet").count()) === s.n);+ } else if (s.covered) {+ check(`${tag}: ${s.path} shows its covered starters to a visitor`, n === s.n && (await cards.evaluateAll((els) => els.every((e) => e.querySelector("img")))), `${n}`);+ check(`${tag}: ${s.path} visitor cards say See how it works`, (await section.getByText("See how it works").count()) === s.n && !/Use template|No cover yet/.test(await section.innerText()));+ const firstCard = await cards.first().evaluate((e) => e.getBoundingClientRect().top + window.scrollY);+ check(`${tag}: ${s.path} starters sit near the top`, firstCard < (size === "390" ? 2200 : 1400), `${Math.round(firstCard)} px`);+ } else {+ check(`${tag}: ${s.path} shows a visitor no starter without its cover`, n === 0 && !/No cover yet|Use template/.test(t) && !t.includes(s.heading));+ }+ if (!owner) check(`${tag}: no model or engine words on ${s.path}`, !ENGINE_WORDS.test(n ? await section.innerText() : ""), (t.match(ENGINE_WORDS) ?? [""])[0]);+ check(`${tag}: no sideways scroll on ${s.path}`, (await sideways()) <= 1, `${await sideways()} px`);+ await shot(`${name}-first`);+ if (size === "1440" || s.covered) await fullShot(`${name}-first`);++ // The starter's page.+ await page.goto(`${app}${s.path}/start/${s.first}`, { waitUntil: "load" });+ if (owner || s.covered) {+ await page.getByRole("heading", { name: "What goes in" }).waitFor({ timeout: 60_000 });+ const pt = await text();+ check(`${tag}: ${s.first}'s page says what goes in, the steps and what comes out`, /The steps/i.test(pt) && /What comes out/i.test(pt));+ if (owner) {+ // The owner's action shows once the viewer is known (after hydration).+ await page.getByText("Use template").first().waitFor({ timeout: 30_000 }).catch(() => {});+ check(`${tag}: the owner can use ${s.first} from its page`, (await page.getByRole("button", { name: "Use template" }).count()) + (await page.getByRole("link", { name: "Use template" }).count()) === 1);+ }+ else {+ check(`${tag}: ${s.first}'s page has no model words and no Use template`, !ENGINE_WORDS.test(pt) && !/Use template/.test(pt), (pt.match(ENGINE_WORDS) ?? [""])[0]);+ check(`${tag}: ${s.first}'s page shows its photo`, (await page.locator("main img, body img").count()) >= 2);+ if (s.tryIn) {+ // A visitor goes on to the app that makes the same from the same photo, its example loaded.+ const go = page.getByRole("link", { name: /^Try it in / });+ await go.waitFor({ timeout: 30_000 }).catch(() => {});+ check(`${tag}: ${s.first}'s page leads a visitor to the app with its example`, (await go.getAttribute("href").catch(() => null)) === s.tryIn);+ if (size === "1440") {+ await go.click();+ await page.waitForURL((u) => u.pathname === s.tryIn.split("?")[0], { timeout: 60_000 });+ await page.getByText("In the composer").first().waitFor({ timeout: 60_000 }).catch(() => {});+ check(`${tag}: the app opens with the starter's example in the composer`, /In the composer/.test(await text()));+ await shot(`${name}-try-in`);+ }+ }+ }+ check(`${tag}: no sideways scroll on ${s.first}'s page`, (await sideways()) <= 1, `${await sideways()} px`);+ } else {+ await page.getByText("This starter isn't here.").waitFor({ timeout: 30_000 }).catch(() => {});+ const pt = await text();+ check(`${tag}: ${s.first} (no cover yet) isn't shown to a visitor`, /This starter isn.t here/.test(pt) && !/The steps/i.test(pt));+ }+ await shot(`${name}-start`);+ }++ // A starter page whose id isn't that studio's answers a real 404.+ if (size === "1440") {+ for (const bad of ["/ads/start/faceless.boat-hotels", "/explainer/start/nope.x"]) {+ const r = await page.goto(`${app}${bad}`, { waitUntil: "load" });+ check(`${tag}: ${bad} is a real 404`, r?.status() === 404, String(r?.status()));+ }+ // A starter not shown yet keeps its name out of the page title.+ await page.goto(`${app}/faceless/start/faceless.boat-hotels`, { waitUntil: "load" });+ check(`${tag}: a starter with no cover yet has a neutral title`, !/Hotels you reach by boat/.test(await page.title()), await page.title());+ }++ // Explainer with no history: the owner's ready explainers stand where the history is, without its tabs and search.+ if (owner) {+ await page.goto(`${app}/explainer`, { waitUntil: "load" });+ await page.getByRole("heading", { name: SURFACES[2].heading }).waitFor({ timeout: 60_000 });+ check(`${tag}: Explainer hides the empty History toolbar under its starters`, !(await page.getByRole("heading", { name: "History" }).isVisible()) && !(await page.getByRole("textbox", { name: "Search your explainers" }).isVisible()));+ }++ // Canvas's new boards: the owner sees them marked, visitors not until their covers exist.+ await page.goto(`${app}/canvas`, { waitUntil: "load" });+ await page.getByRole("heading", { name: "What's a canvas?" }).waitFor({ timeout: 60_000 });+ if (owner) await page.getByRole("button", { name: "Use template" }).first().waitFor();+ else await page.waitForTimeout(1500);+ const ct = await page.locator("#templates").innerText();+ if (owner) check(`${tag}: Canvas lists Outfit lookbook and Music video for the owner`, /Outfit lookbook/.test(ct) && /Music video/.test(ct));+ else check(`${tag}: Canvas keeps Outfit lookbook and Music video from visitors until their covers exist`, !/Outfit lookbook|Music video/.test(ct));++ // ---- The owner's "Use template", studio by studio+ if (owner && size === "1440") {+ const tapFirstUse = async (s) => {+ await page.goto(`${app}${s.path}`, { waitUntil: "load" });+ await page.getByRole("heading", { name: s.heading }).waitFor({ timeout: 60_000 });+ await page.locator("#starters article").first().getByRole("button", { name: "Use template" }).click();+ };++ // Faceless: the channel is made, its first episode's setup opens with the topic in.+ await tapFirstUse(SURFACES[0]);+ await page.waitForURL(/\/faceless\/[^/]+\/new\?starter=/, { timeout: 60_000 });+ const own = page.locator("textarea").first();+ await own.waitFor();+ check(`${tag}: a ready channel opens its first episode with the topic written in`, (await own.inputValue()) === "Five hotels you can only reach by boat");+ await shot("faceless-from-starter");+ await page.getByRole("button", { name: "Next" }).click();+ await page.getByRole("heading", { name: "Video settings" }).waitFor();+ check(`${tag}: the channel's look is the starter's`, /Editorial Motion Graphics/.test(await text()));+ await page.getByRole("button", { name: /Write the script/ }).click();+ await page.waitForURL(/\/faceless\/[^/]+\/(?!new)[^/?]+$/, { timeout: 60_000 });+ check(`${tag}: Write the script makes episode 1`, true);+ await page.goto(`${app}/faceless`, { waitUntil: "load" });+ await page.getByRole("heading", { name: "My channels" }).waitFor();+ await page.getByRole("heading", { name: SURFACES[0].heading }).waitFor({ timeout: 30_000 }).catch(() => {});+ const order = await page.evaluate(() => [...document.querySelectorAll("h2")].map((h) => h.textContent?.trim()));+ check(`${tag}: with a channel, My channels leads and the starters sit below`, order.indexOf("My channels") >= 0 && order.indexOf("My channels") < order.indexOf(SURFACES[0].heading), order.join(" | "));+ await shot("faceless-with-channel");++ // Content Factory: the composer fills with the style and the idea.+ await tapFirstUse(SURFACES[1]);+ await page.waitForTimeout(800);+ const cfPrompt = await page.locator("textarea").first().inputValue();+ check(`${tag}: a ready series fills the composer`, cfPrompt === "What if Paris fashion week was held underwater?" && /Preset: What if/.test(await text()), cfPrompt);+ await shot("content-factory-filled");+ await page.goto(`${app}/content-factory?starter=cf.narcissus`, { waitUntil: "load" });+ await page.waitForTimeout(1500);+ check(`${tag}: ?starter= fills the composer too`, (await page.locator("textarea").first().inputValue()) === "Narcissus retold as a modern supermodel" && /Preset: Myths retold/i.test(await text()));+ await page.getByRole("button", { name: /^Generate$/ }).click();+ await page.waitForURL(/\/content-factory\/[^/?]+$/, { timeout: 90_000 });+ check(`${tag}: Generate makes the series`, true);+ await shot("content-factory-series");++ // Explainer: the form fills with the topic, style and length.+ await tapFirstUse(SURFACES[2]);+ await page.waitForTimeout(800);+ const exPrompt = await page.locator("textarea").first().inputValue();+ check(`${tag}: a ready explainer fills the form`, exPrompt === "How a couture gown takes 400 hours to make" && /Editorial Motion Graphics/.test(await text()), exPrompt);+ await shot("explainer-filled");+ await page.getByRole("button", { name: /^Generate$/ }).click();+ await page.waitForURL(/\/explainer\/[^/?]+$/, { timeout: 90_000 });+ check(`${tag}: Generate makes the explainer`, true);++ // Click to Ad first, on a data dir with no products yet: the product it makes is picked on this same page.+ await tapFirstUse(SURFACES[4]);+ await page.waitForURL(/\/marketing\/click-to-ad\?product=/, { timeout: 90_000 });+ await page.getByText("Your product kit").first().waitFor({ timeout: 60_000 }).catch(() => {});+ check(`${tag}: a ready product opens Click to Ad with its kit (first product made)`, /Your product kit/.test(await text()) && !/No saved products yet/.test(await text()));+ check(`${tag}: Click to Ad's Use template stops spinning once open`, (await page.locator("#starters .animate-spin").count()) === 0);+ await shot("click-to-ad-from-starter");++ // Marketing Studio's second shoot makes a product no one made before: the template and that product are in.+ await page.goto(`${app}${SURFACES[5].path}`, { waitUntil: "load" });+ await page.getByRole("heading", { name: SURFACES[5].heading }).waitFor({ timeout: 60_000 });+ await page.locator("#starters article").nth(1).getByRole("button", { name: "Use template" }).click();+ await page.waitForURL(/\/marketing\?template=ps-studio-white&product=/, { timeout: 90_000 });+ await page.locator('img[src^="/api/files/"]').first().waitFor({ timeout: 60_000 }).catch(() => {});+ check(`${tag}: a ready shoot opens with its template and its new product`, /Studio White/.test(await text()) && (await page.locator('img[src^="/api/files/"]').count()) > 0);+ check(`${tag}: Marketing's Use template stops spinning once open`, (await page.locator("#starters .animate-spin").count()) === 0);+ await shot("marketing-from-starter");++ // Ads Studio: the brand kit with its product (the perfume's, made by Click to Ad, reused).+ await tapFirstUse(SURFACES[3]);+ await page.waitForURL(/\/ads\/[^/?]+\?step=new$/, { timeout: 90_000 });+ await page.getByText("Eau de Verre").first().waitFor({ timeout: 60_000 }).catch(() => {});+ check(`${tag}: a ready brand opens with its product`, /Maison Verre/.test(await text()) && /Eau de Verre/.test(await text()));+ await shot("ads-brand-from-starter");++ // With products of its own, Ads Studio's brands lead and the starters sit below.+ await page.goto(`${app}/ads`, { waitUntil: "load" });+ await page.getByRole("heading", { name: "Your brands" }).waitFor();+ await page.getByRole("heading", { name: "Start from a ready brand" }).waitFor({ timeout: 30_000 }).catch(() => {});+ const ads = await page.evaluate(() => [...document.querySelectorAll("h2")].map((h) => h.textContent?.trim()));+ check(`${tag}: with brands, Your brands leads and the starters sit below`, ads.indexOf("Your brands") >= 0 && ads.indexOf("Your brands") < ads.indexOf("Start from a ready brand"), ads.join(" | "));+ }+ check(`${tag}: no page errors`, errors.length === 0, errors[0]);+ if (known.length) console.log(`note ${tag}: ${known.length} known end-card hydration error(s) on Click to Ad`);+ await ctx.close();+ }+ }+} finally {+ await browser.close();+}++if (failures.length) {+ console.log(`\n${failures.length} check(s) failed`);+ process.exit(1);+}+console.log("\nall checks passed");diff --git a/tests/record-pages.test.ts b/tests/record-pages.test.tsindex 97288e6d..854a3264 100644--- a/tests/record-pages.test.ts+++ b/tests/record-pages.test.ts@@ -54,8 +54,9 @@ describe("record pages (real 404s)", () => {};walk(app, []);expect(routes.length).toBeGreaterThan(40);- // Ids the catalog answers for (apps, hub modes, Canvas templates), not stored records, and share tokens: the proxy checks those itself.- const catalog = /^\/(apps|audio|video-tools|upscale|s|canvas\/start)\/\[/;+ // Ids the catalog answers for (apps, hub modes, Canvas templates, ready-made starters' pages), not stored records, and+ // share tokens: the proxy checks those itself.+ const catalog = /^\/(apps|audio|video-tools|upscale|s|canvas\/start)\/\[|\/start\/\[id\]$/;for (const route of routes) {if (!route.includes("[")) {expect(recordForPath(route), route).toBeNull();diff --git a/tests/starters-catalog.test.ts b/tests/starters-catalog.test.tsnew file mode 100644index 00000000..1c103611--- /dev/null+++ b/tests/starters-catalog.test.ts@@ -0,0 +1,174 @@+import { createElement, type FC } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vitest";+import { MODELS } from "@/lib/catalog/models";+import { guestRead, isLibraryChange } from "@/lib/guest-access";+import { recordForPath, unknownStarterPage } from "@/lib/record-pages";+import { assertStarters, STARTERS, starterCards, starterFills, starterIds, starterOn, type Starter } from "@/lib/starters/catalog";+import { STARTER_IDS } from "@/lib/starters/ids";+import { STARTER_SURFACES, starterHref, starterShown, type StarterSurface } from "@/lib/starters/types";+import { sampleFile } from "@/server/canvas-samples";+import { exampleStat } from "@/server/example-files";++// The ready-made starters of Faceless Studio, Content Factory, Explainer, Ads Studio, Click to Ad and Marketing Studio:+// each names what exists (a style, a preset, a template, a published photo), speaks plain visitor words, and shows+// to a guest or an account only with its real cover. tests/starters-create.test.ts makes and runs every one.++const { StarterTile } = await import("@/components/starters/starter-section");+const tile = (props: Record<string, unknown>) => renderToStaticMarkup(createElement(StarterTile as FC<Record<string, unknown>>, props));++const SURFACES = Object.keys(STARTER_SURFACES) as StarterSurface[];+/** Words visitors never read: engine words and product terms that aren't theirs. */+const ENGINE_WORDS = /Fuobe DoP|Effects 2\.0|\bGPU\b|ComfyUI|Variant|\bfal\b|Replicate|\bLLM\b|placeholder|demo/i;+const NEGATIONS = /\b(no|not|without|never|unmarked|logo-free)\b/i;+const visitorWords = (s: Starter) => [s.name, s.description, s.makes, ...s.steps, ...s.flow, ...s.words.map((w) => `${w.label} ${w.text}`)].join("\n");++describe("the starters catalog", () => {+ it("has ready starters on every surface, ids unique and named <surface>.<slug>, ranks unique per surface", () => {+ expect(() => assertStarters()).not.toThrow();+ for (const surface of SURFACES) {+ const list = STARTERS.filter((s) => s.surface === surface);+ expect(list.length, surface).toBeGreaterThanOrEqual(2);+ expect(new Set(list.map((s) => s.rank)).size, surface).toBe(list.length);+ }+ expect(STARTERS.filter((s) => s.surface === "faceless")).toHaveLength(3);+ expect(STARTERS.filter((s) => s.surface === "content-factory")).toHaveLength(3);+ expect(STARTERS.filter((s) => s.surface === "explainer")).toHaveLength(3);+ });++ it("refuses a starter that names what isn't there", () => {+ const one = STARTERS[0];+ const bad = (seed: Starter["seed"]) => () => assertStarters([{ ...one, seed }]);+ expect(bad({ kind: "faceless", channel: { idea: "x", genre: "history", name: "x" }, episode: { topic: "x", styleId: "nope", length: 60 } })).toThrow(/no Faceless style/);+ expect(bad({ kind: "faceless", channel: { idea: "x", genre: "history", name: "x" }, episode: { topic: "x", styleId: "paper-collage", length: 45 } })).toThrow(/isn't a Faceless length/);+ expect(bad({ kind: "fill", fill: { kind: "content-factory", presetId: "nope", prompt: "x", length: 30, episodes: 1 } })).toThrow(/no Content Factory preset/);+ expect(bad({ kind: "fill", fill: { kind: "explainer", prompt: "x", styleId: "nope", duration: 60, aspect: "16:9" } })).toThrow(/no Explainer style/);+ const kit = STARTERS.find((s) => s.seed.kind === "product")!.seed;+ if (kit.kind !== "product") throw new Error("no product starter");+ expect(bad({ ...kit, kit: { ...kit.kit, product: { ...kit.kit.product, image: { src: "/examples/nope/1/in-image.jpg", name: "x" } } } })).toThrow(/published example file/);+ expect(bad({ ...kit, open: { to: "marketing", template: "nope" } })).toThrow(/no Marketing template/);+ expect(() => assertStarters([one, one])).toThrow(/listed twice/);+ });++ it("speaks plain, short visitor words: no model names, no engine words, only what is wanted", () => {+ const names = MODELS.map((m) => m.name).filter((n) => n.length > 4);+ for (const s of STARTERS) {+ expect(s.name.length, s.id).toBeLessThanOrEqual(32);+ expect(s.description.length, s.id).toBeLessThanOrEqual(90);+ for (const w of s.flow) expect(w.length, `${s.id} ${w}`).toBeLessThanOrEqual(10);+ expect(s.steps.length, s.id).toBeGreaterThanOrEqual(2);+ const words = visitorWords(s);+ expect(words, s.id).not.toMatch(ENGINE_WORDS);+ for (const name of names) expect(words, `${s.id}: ${name}`).not.toContain(name);+ // The words a starter puts in (its prompts and topics) name only what should be there.+ const seed = s.seed;+ const prompts = seed.kind === "faceless" ? [seed.channel.idea, seed.episode.topic] : seed.kind === "fill" ? [seed.fill.prompt] : [seed.kit.brand.description, seed.kit.product.description];+ for (const p of prompts) expect(p, s.id).not.toMatch(NEGATIONS);+ }+ });++ it("brings only published example photos, read with the bytes the manifest lists", () => {+ for (const s of STARTERS)+ if (s.seed.kind === "product") {+ const src = s.seed.kit.product.image.src;+ expect(exampleStat(src), `${s.id} ${src}`).toBeTruthy();+ expect(sampleFile(src), `${s.id} ${src}`).toBeTruthy();+ }+ });++ it("covers Marketing's shoots with the app cover that shows the same shot, and keeps the rest for the owner until theirs are made", () => {+ for (const s of STARTERS) {+ const card = starterOn(s.surface, s.id)!;+ expect(card.coverKey).toBe(`starters/${s.id}`);+ // An ad and a video ad aren't a plain product shot: Ads Studio and Click to Ad wait for their own covers.+ if (s.surface === "ads" || s.surface === "click-to-ad") expect(s.coverFrom, s.id).toBeUndefined();+ if (s.surface === "marketing") {+ expect(card.cover, s.id).toBeTruthy();+ // It rests on the finished shot, and plays the clip.+ expect(card.cover!.poster, s.id).toMatch(/^\/previews\/presets\/peak\/app-[a-z-]+\.jpg\?v=[0-9a-f]{8}$/);+ expect(card.cover!.video, s.id).toMatch(/\?v=[0-9a-f]{8}$/);+ }+ // A product's photo shows on its page; words show as words; a visitor goes on to the app that makes the same.+ if (s.seed.kind === "product") {+ expect(card.inputs[0].image?.thumb, s.id).toMatch(/^\/examples\//);+ expect(card.tryIn?.href, s.id).toMatch(/^\/apps\/app-[a-z-]+\?example=app-[a-z-]+\.1$/);+ // The same photo as the example it links.+ expect(s.seed.kit.product.image.src, s.id).toBe(`/examples/${s.tryIn!.app}/1/in-image.jpg`);+ }+ }+ });++ it("lists a surface's cards covered first, then by rank; a visitor sees only covered ones", () => {+ for (const surface of SURFACES) {+ const cards = starterCards(surface);+ expect(cards.map((c) => c.id).sort()).toEqual(starterIds(surface).sort());+ const covered = cards.map((c) => !!c.cover);+ expect(covered, surface).toEqual([...covered].sort((a, b) => Number(b) - Number(a)));+ for (const c of cards) {+ expect(starterShown(c, false)).toBe(true);+ expect(starterShown(c, true)).toBe(!!c.cover);+ expect(starterHref(c)).toBe(`${STARTER_SURFACES[surface].base}/start/${c.id}`);+ }+ }+ expect(starterOn("faceless", "cf.narcissus")).toBeUndefined();+ });++ it("fills Content Factory and Explainer from the address, and makes the others on the server", () => {+ for (const c of [...starterCards("content-factory"), ...starterCards("explainer")]) {+ expect(c.use.kind, c.id).toBe("fill");+ if (c.use.kind === "fill") expect(c.use.href).toBe(`${STARTER_SURFACES[c.surface].base}?starter=${encodeURIComponent(c.id)}`);+ }+ for (const surface of ["faceless", "ads", "click-to-ad", "marketing"] as const) for (const c of starterCards(surface)) expect(c.use.kind, c.id).toBe("create");+ expect(Object.keys(starterFills("content-factory")).sort()).toEqual(starterIds("content-factory").sort());+ expect(Object.keys(starterFills("explainer")).sort()).toEqual(starterIds("explainer").sort());+ });+});++describe("who may use a starter", () => {+ it("opens a starter's page to everyone, as catalog data, not a stored record", () => {+ for (const s of STARTERS) {+ const href = starterHref(s);+ expect(recordForPath(href), href).toBeNull();+ expect(guestRead(href), href).toEqual({ kind: "pass" });+ expect(unknownStarterPage(href), href).toBe(false);+ expect(unknownStarterPage(`${href}/`), href).toBe(false);+ }+ });++ it("answers a real 404 for a starter page that isn't that studio's (the proxy's client-safe id list matches the catalog)", () => {+ for (const surface of SURFACES) expect([...STARTER_IDS[surface]].sort(), surface).toEqual(starterIds(surface).sort());+ expect(unknownStarterPage("/ads/start/faceless.boat-hotels")).toBe(true);+ expect(unknownStarterPage("/explainer/start/nope.x")).toBe(true);+ expect(unknownStarterPage("/marketing/click-to-ad/start/mk.perfume-moss")).toBe(true);+ expect(unknownStarterPage("/marketing/start/mk.perfume-moss")).toBe(false);+ expect(unknownStarterPage("/faceless/abc/def")).toBe(false);+ });++ it("makes a starter for the owner only: an account's POST is a library change", () => {+ for (const s of STARTERS) expect(isLibraryChange("POST", `/api/starters/${s.id}`), s.id).toBe(true);+ expect(isLibraryChange("GET", "/api/starters/faceless.boat-hotels")).toBe(false);+ });+});++describe("a starter's card", () => {+ const covered = starterCards("marketing")[0];+ const bare = starterCards("faceless").find((c) => !c.cover);++ it("shows a visitor the cover, the steps in a few words and how it works; the owner a Use template", () => {+ const visitor = tile({ s: covered, owner: false, busy: false, onUse: () => {} });+ expect(visitor).toContain("See how it works");+ expect(visitor).not.toContain("Use template");+ expect(visitor).not.toContain("No cover yet");+ expect(visitor).toContain(`href="${starterHref(covered)}"`);+ for (const w of covered.flow) expect(visitor).toContain(w);+ const owner = tile({ s: covered, owner: true, busy: false, onUse: () => {} });+ expect(owner).toContain("Use template");+ });++ it("marks a card with no cover yet for the owner, drawn as its steps", () => {+ if (!bare) return;+ const owner = tile({ s: bare, owner: true, busy: false, onUse: () => {} });+ expect(owner).toContain("No cover yet");+ expect(owner).toContain("<svg");+ });+});diff --git a/tests/starters-create.test.ts b/tests/starters-create.test.tsnew file mode 100644index 00000000..8192535a--- /dev/null+++ b/tests/starters-create.test.ts@@ -0,0 +1,222 @@+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 { EpisodeSettings, EpisodeView } from "@/lib/catalog/faceless";++// Every ready-made starter of Faceless Studio, Content Factory, Explainer, Ads Studio, Click to Ad and Marketing Studio,+// made as the owner's "Use template" makes it, on a fresh data dir, then run on the demo provider to the end: the+// channel's first episode, the series, the explainer, the ads, the video ad and the product shot.++vi.mock("next/server", async (importOriginal) => ({+ ...(await importOriginal<typeof import("next/server")>()),+ connection: async () => {},+ after: (task: unknown) => void Promise.resolve(typeof task === "function" ? (task as () => unknown)() : task).catch(() => {}),+}));++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-starters-"));+process.env.FUOBE_DATA_DIR = dir;+// Nothing listens: models run on the demo provider, and there's no LLM (the offline writers run).+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 gens = await import("@/server/generations");+const faceless = await import("@/server/faceless");+const cf = await import("@/server/content-factory");+const brand = await import("@/server/brand");+const mk = await import("@/server/marketing");+const ads = await import("@/server/ads");+const { absolutePath, filesRel, listAssets } = await import("@/server/storage");+const { sampleFile } = await import("@/server/canvas-samples");+const route = await import("@/app/api/starters/[id]/route");+const explainerRoute = await import("@/app/api/explainer/route");+const { STARTERS, facelessTopic, getStarter } = await import("@/lib/starters/catalog");+const { getPreset } = await import("@/lib/catalog/content-factory");+const { defaultSettings, genreInfo } = await import("@/lib/catalog/faceless");+const { TEMPLATE_INDEX } = await import("@/lib/catalog/marketing");++beforeAll(() => {+ setSetting("demoMode", "auto");+ setSetting("enhanceProvider", "none");+});+afterAll(() => {+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch {}+});++const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));+const use = async (id: string, engine: "cloud" | "open" = "cloud") => {+ const res = await route.POST(new Request("http://x/api", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ engine }) }), { params: Promise.resolve({ id }) });+ return { status: res.status, body: (await res.json()) as { href?: string; error?: string } };+};+const view = (id: string): EpisodeView => JSON.parse(JSON.stringify(faceless.episodeView(id)));++/** Follow an episode until it's finished (demo jobs: a few seconds a step). */+async function finished(id: string, ms = 150_000): Promise<EpisodeView> {+ const end = Date.now() + ms;+ for (;;) {+ const v = view(id);+ if (v.episode.status === "review" && !v.episode.error) faceless.renderEpisode(id);+ if (["done", "failed", "write-failed"].includes(v.episode.status) || (v.episode.status === "review" && v.episode.error)) return v;+ if (Date.now() > end) throw new Error(`timed out: ${v.episode.status} ${Math.round(v.progress * 100)}%`);+ await sleep(500);+ }+}++async function settled(id: string, ms = 120_000) {+ 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 sleep(300);+ }+}++const of = (surface: string) => STARTERS.filter((s) => s.surface === surface);++describe("Use template", () => {+ it("answers 404 for an unknown starter, and 400 for one that only fills its studio's composer", async () => {+ expect((await use("faceless.nope")).status).toBe(404);+ const fill = await use("cf.underwater-fashion-week");+ expect(fill.status).toBe(400);+ expect(fill.body.error).toMatch(/opens in its studio/);+ });++ it("Faceless: makes the channel with its name and look, opens its first episode's setup, and the episode renders", async () => {+ const runs = of("faceless").map(async (s) => {+ const seed = s.seed.kind === "faceless" ? s.seed : null;+ if (!seed) throw new Error(s.id);+ const { status, body } = await use(s.id);+ expect(status, s.id).toBe(201);+ const m = /^\/faceless\/([^/]+)\/new\?starter=(.+)$/.exec(body.href ?? "");+ expect(m, body.href).toBeTruthy();+ const channel = faceless.getChannel(m![1])!;+ expect(channel).toMatchObject({ name: seed.channel.name, genre: seed.channel.genre, settings: { styleId: seed.episode.styleId, length: seed.episode.length } });+ // The episode setup reads the topic from the address, then posts what the page would.+ const topic = facelessTopic(decodeURIComponent(m![2]));+ expect(topic).toBe(seed.episode.topic);+ const settings: EpisodeSettings = { ...channel.settings, styleRefs: [], elements: [], engine: "cloud" };+ const ep = faceless.createEpisode({ kind: "faceless", channelId: channel.id, topic: topic!, settings });+ await faceless.scriptWritten(ep.id);+ const v = await finished(ep.id);+ expect(v.episode.status, `${s.id}: ${v.episode.error ?? ""}`).toBe("done");+ expect(v.episode.settings.styleId).toBe(seed.episode.styleId);+ });+ await Promise.all(runs);+ }, 300_000);++ it("Content Factory: each ready series plans on its trending style and makes its episode", async () => {+ const runs = of("content-factory").map(async (s) => {+ const f = s.seed.kind === "fill" && s.seed.fill.kind === "content-factory" ? s.seed.fill : null;+ if (!f) throw new Error(s.id);+ const preset = getPreset(f.presetId)!;+ const series = await cf.createSeries({ reference: { kind: "preset", presetId: f.presetId }, engine: "cloud" });+ const made = await cf.generateSeries(series.id, {+ prompt: f.prompt,+ settings: { engine: "cloud", length: f.length, episodes: f.episodes, animation: preset.brief.animation, genre: preset.genre, aspect: preset.brief.aspect },+ });+ expect(made.episodes, s.id).toHaveLength(f.episodes);+ for (const e of made.episodes) {+ const v = await finished(e.id);+ expect(v.episode.status, `${s.id}: ${v.episode.error ?? ""}`).toBe("done");+ }+ });+ await Promise.all(runs);+ }, 300_000);++ it("Explainer: each ready explainer renders with its style, length, shape and voice", async () => {+ const runs = of("explainer").map(async (s) => {+ const f = s.seed.kind === "fill" && s.seed.fill.kind === "explainer" ? s.seed.fill : null;+ if (!f) throw new Error(s.id);+ const base = defaultSettings("cloud", genreInfo("education"), { explainer: true });+ const settings: EpisodeSettings = { ...base, styleId: f.styleId, aspect: f.aspect, length: f.duration === "auto" ? base.length : f.duration, auto: f.duration === "auto", ...(f.voice && { voice: { kind: "preset" as const, id: f.voice } }) };+ const res = await explainerRoute.POST(new Request("http://x/api", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt: f.prompt, sources: [], settings }) }));+ expect(res.status, s.id).toBe(201);+ const ep = (await res.json()) as { id: string };+ await faceless.scriptWritten(ep.id);+ const v = await finished(ep.id);+ expect(v.episode.status, `${s.id}: ${v.episode.error ?? ""}`).toBe("done");+ expect(v.episode.settings).toMatchObject({ styleId: f.styleId, aspect: f.aspect });+ });+ await Promise.all(runs);+ }, 300_000);++ it("Ads, Click to Ad and Marketing: one brand kit and product per brand, its photo stored once, out of the Library", async () => {+ for (const s of STARTERS.filter((x) => x.seed.kind === "product")) {+ const { status, body } = await use(s.id);+ expect(status, `${s.id} ${body.error ?? ""}`).toBe(201);+ expect(body.href, s.id).toMatch(s.surface === "ads" ? /^\/ads\/[^/?]+\?step=new$/ : s.surface === "click-to-ad" ? /^\/marketing\/click-to-ad\?product=/ : /^\/marketing\?template=[^&]+&product=/);+ }+ // Two brands, one product each, whichever surface made them; the photo is the published sample's bytes.+ const brands = brand.listBrands();+ expect(brands.map((b) => b.name).sort()).toEqual(["Maison Verre", "Studio Marlow"]);+ for (const b of brands) {+ const products = brand.listProducts(b.id);+ expect(products, b.name).toHaveLength(1);+ const kit = STARTERS.map((x) => (x.seed.kind === "product" ? x.seed.kit : null)).find((k) => k?.brand.name === b.name)!;+ expect(products[0]).toMatchObject({ name: kit.product.name, price: kit.product.price, currency: kit.product.currency });+ const stored = fs.readFileSync(absolutePath(filesRel(products[0].images[0])!));+ expect(stored.equals(fs.readFileSync(sampleFile(kit.product.image.src)!)), b.name).toBe(true);+ expect(b.colors).toEqual(kit.brand.colors);+ // The stored photo is a starter's file: the Library's lists don't show it.+ expect(listAssets({ limit: 1000 }).some((a) => a.url === products[0].images[0]), b.name).toBe(false);+ }+ // A product whose photo was taken off gets it back on the next Use template: still one product, not a second.+ const marlow = brands.find((b) => b.name === "Studio Marlow")!;+ const bag = brand.listProducts(marlow.id)[0];+ brand.updateProduct(bag.id, { images: [] });+ const again = await use("mk.bag-packshot");+ expect(again.status).toBe(201);+ expect(again.body.href).toContain(`product=${bag.id}`);+ expect(brand.listProducts(marlow.id)).toHaveLength(1);+ expect(brand.listProducts(marlow.id)[0].images).toHaveLength(1);+ });++ it("Ads Studio: the ready brand makes its ads on the demo provider", async () => {+ for (const s of of("ads")) {+ const { body } = await use(s.id);+ const brandId = new URL(body.href!, "http://x").pathname.split("/").pop()!;+ const product = brand.listProducts(brandId)[0];+ const { creatives, run } = ads.createBatch({ brandId, engine: "cloud", items: [{ productId: product.id, count: 2 }] });+ await run;+ const made = ads.listCreatives({ brandId }).filter((c) => creatives.some((x) => x.id === c.id));+ expect(made, s.id).toHaveLength(2);+ for (const c of made) {+ const g = await settled(c.generationId!);+ expect(g.status, `${s.id}: ${g.message ?? ""}`).toBe("succeeded");+ }+ }+ }, 180_000);++ it("Click to Ad: the ready product makes its 9:16 video ad on the demo provider", async () => {+ for (const s of of("click-to-ad")) {+ const { body } = await use(s.id);+ const productId = new URL(body.href!, "http://x").searchParams.get("product")!;+ const { run, script } = await mk.runClickToAd({ engine: "cloud", productId, styleId: "clean-minimal" });+ expect(script.length, s.id).toBeGreaterThan(10);+ for (const id of run.finalIds) {+ const g = await settled(id, 180_000);+ expect(g.status, `${s.id}: ${g.message ?? ""}`).toBe("succeeded");+ }+ }+ }, 400_000);++ it("Marketing Studio: the ready shoot runs its template on its product", async () => {+ for (const s of of("marketing")) {+ const { body } = await use(s.id);+ const q = new URL(body.href!, "http://x").searchParams;+ const template = TEMPLATE_INDEX.get(q.get("template")!)!;+ const product = brand.getProduct(q.get("product")!)!;+ const { runs } = await mk.runMarketing({ engine: "cloud", format: template.format, templateId: template.id, productId: product.id, brandId: product.brandId ?? undefined });+ for (const r of runs)+ for (const id of r.finalIds) {+ const g = await settled(id);+ expect(g.status, `${s.id}: ${g.message ?? ""}`).toBe("succeeded");+ }+ expect(getStarter(s.id)).toBeTruthy();+ }+ }, 180_000);+});diff --git a/tests/template-covers.test.ts b/tests/template-covers.test.tsindex 0429228b..b6395dd8 100644--- a/tests/template-covers.test.ts+++ b/tests/template-covers.test.ts@@ -16,6 +16,7 @@ import { lookSet } from "@/lib/catalog/soul-cards";import { CREATURE_TYPES, HUMAN_TIERS } from "@/lib/influencer";import { PRESET_PEAKS } from "@/lib/preset-peaks.generated";import { PRESET_PREVIEWS } from "@/lib/preset-previews.generated";+import { STARTERS } from "@/lib/starters/catalog";import { TEMPLATE_GROUPS, templateCover, type TemplateGroup } from "@/lib/template-covers";import { TEMPLATE_COVERS } from "@/lib/template-covers.generated";@@ -54,6 +55,8 @@ const TILES: Record<TemplateGroup, string[]> = {influencer: [...HUMAN_TIERS, ...CREATURE_TYPES].map((t) => `tier-${t.id}`),// The example pictures of the empty pages: Character Sheet, Storyboard (six frames), Elements (four pictures).examples: ["character-sheet", "storyboard-heist", "element-maya", "element-rooftop-bar", "element-aurora", "element-together"],+ // The studios' ready-made starters, by starter id (src/lib/starters/catalog.ts).+ starters: STARTERS.map((s) => s.id),};const VERSIONED = /^(\/previews\/[^?]+)\?v=([0-9a-f]{8})$/;const sha8 = (...files: string[]) => {@@ -122,13 +125,14 @@ describe("the template covers manifest", () => {else if (group === "fashion" || group === "photodump" || ["product-angles", "script-film", "table-film", "clips-film", "compare-image", "storyboard-heist"].includes(id))e = { poster: t(key, n), frames: [2, 3, 4, 5, 6].slice(0, id === "storyboard-heist" ? 5 : group === "photodump" ? 3 : 2).map((k) => t(key, n + k, `-${k}`)) };else if (group === "shorts") e = { poster: t(key, n), video: `/previews/templates/${key}.mp4?v=${v(n + 1)}`, at: 3.542 };- else if (group === "marketing" || group === "content-factory") e = { poster: t(key, n), video: `/previews/templates/${key}.mp4?v=${v(n + 1)}` };+ else if (group === "marketing" || group === "content-factory" || group === "starters") e = { poster: t(key, n), video: `/previews/templates/${key}.mp4?v=${v(n + 1)}` };else e = { poster: t(key, n) };lines.push(` ${JSON.stringify(key)}: ${JSON.stringify(gen.slimEntry(key, { poster: e.poster, ...(e.video && { video: e.video }), ...(e.at && { at: e.at }), ...(e.frames && { frames: e.frames }) }))}`);}}- // The studios' tiles (240, with Keyframes → animation), Fuobe Soul's looks (139), AI Influencer's types (9) and the empty pages' examples (6).- expect(lines).toHaveLength(240 + 139 + 9 + 6);+ // The studios' tiles (242, with Keyframes → animation, Outfit lookbook and Music video), Fuobe Soul's looks (139),+ // AI Influencer's types (9), the empty pages' examples (6) and the studios' ready-made starters (15).+ expect(lines).toHaveLength(242 + 139 + 9 + 6 + 15);const text = `{\n${lines.join(",\n")}\n}`;expect(text.length).toBeLessThan(36_000);expect(gzipSync(text).length).toBeLessThan(8_000);