Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Elements: @mention characters, locations, props and styles in any prompt

Claude24d1f7f304c9
diff --git a/next.config.ts b/next.config.ts
index a0cf0c73..8f1d6d73 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -4,6 +4,12 @@ const nextConfig: NextConfig = {
/* config options here */
cacheComponents: true,
partialPrefetching: true,
+ async redirects() {
+ return [
+ { source: "/characters", destination: "/elements", permanent: true },
+ { source: "/characters/:id", destination: "/elements/:id", permanent: true },
+ ];
+ },
turbopack: {
rules: {
"*.css": {
diff --git a/src/app/(studio)/characters/[id]/page.tsx b/src/app/(studio)/characters/[id]/page.tsx
deleted file mode 100644
index 9294fb43..00000000
--- a/src/app/(studio)/characters/[id]/page.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-import type { Metadata } from "next";
-import { Suspense } from "react";
-import { CharacterStudio } from "@/components/characters-view";
-
-export const metadata: Metadata = { title: "Character" };
-
-async function Studio({ params }: { params: PageProps<"/characters/[id]">["params"] }) {
- const { id } = await params;
- return <CharacterStudio id={id} />;
-}
-
-export default function Page({ params }: PageProps<"/characters/[id]">) {
- return (
- <Suspense fallback={null}>
- <Studio params={params} />
- </Suspense>
- );
-}
diff --git a/src/app/(studio)/characters/page.tsx b/src/app/(studio)/characters/page.tsx
deleted file mode 100644
index d511c75e..00000000
--- a/src/app/(studio)/characters/page.tsx
+++ /dev/null
@@ -1,8 +0,0 @@
-import type { Metadata } from "next";
-import { CharactersView } from "@/components/characters-view";
-
-export const metadata: Metadata = { title: "Characters" };
-
-export default function Page() {
- return <CharactersView />;
-}
diff --git a/src/app/(studio)/elements/[id]/page.tsx b/src/app/(studio)/elements/[id]/page.tsx
new file mode 100644
index 00000000..ca2a30ef
--- /dev/null
+++ b/src/app/(studio)/elements/[id]/page.tsx
@@ -0,0 +1,18 @@
+import type { Metadata } from "next";
+import { Suspense } from "react";
+import { ElementStudio } from "@/components/elements-view";
+
+export const metadata: Metadata = { title: "Element" };
+
+async function Studio({ params }: { params: PageProps<"/elements/[id]">["params"] }) {
+ const { id } = await params;
+ return <ElementStudio id={id} />;
+}
+
+export default function Page({ params }: PageProps<"/elements/[id]">) {
+ return (
+ <Suspense fallback={null}>
+ <Studio params={params} />
+ </Suspense>
+ );
+}
diff --git a/src/app/(studio)/elements/page.tsx b/src/app/(studio)/elements/page.tsx
new file mode 100644
index 00000000..6e62b44c
--- /dev/null
+++ b/src/app/(studio)/elements/page.tsx
@@ -0,0 +1,8 @@
+import type { Metadata } from "next";
+import { ElementsView } from "@/components/elements-view";
+
+export const metadata: Metadata = { title: "Elements" };
+
+export default function Page() {
+ return <ElementsView />;
+}
diff --git a/src/app/api/characters/[id]/route.ts b/src/app/api/characters/[id]/route.ts
deleted file mode 100644
index 3ce56802..00000000
--- a/src/app/api/characters/[id]/route.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { connection } from "next/server";
-import { deleteCharacter, getCharacter } from "@/server/characters";
-
-export async function GET(_req: Request, ctx: RouteContext<"/api/characters/[id]">) {
- await connection();
- const { id } = await ctx.params;
- const c = getCharacter(id);
- return c ? Response.json(c) : Response.json({ error: "Not found" }, { status: 404 });
-}
-
-export async function DELETE(_req: Request, ctx: RouteContext<"/api/characters/[id]">) {
- const { id } = await ctx.params;
- deleteCharacter(id);
- return new Response(null, { status: 204 });
-}
diff --git a/src/app/api/characters/route.ts b/src/app/api/characters/route.ts
deleted file mode 100644
index 146ac7d2..00000000
--- a/src/app/api/characters/route.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { connection } from "next/server";
-import { z } from "zod";
-import { createCharacter, listCharacters } from "@/server/characters";
-
-const Body = z.object({
- name: z.string().min(1).max(60),
- description: z.string().max(500).optional(),
- references: z.array(z.string().startsWith("/api/files/")).min(1).max(20),
-});
-
-export async function GET() {
- await connection();
- return Response.json({ items: listCharacters() });
-}
-
-export async function POST(request: Request) {
- const parsed = Body.safeParse(await request.json().catch(() => null));
- if (!parsed.success) return Response.json({ error: "Give your character a name and at least one photo" }, { status: 400 });
- return Response.json(createCharacter(parsed.data), { status: 201 });
-}
diff --git a/src/app/api/elements/[id]/route.ts b/src/app/api/elements/[id]/route.ts
new file mode 100644
index 00000000..f0aa6033
--- /dev/null
+++ b/src/app/api/elements/[id]/route.ts
@@ -0,0 +1,30 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { deleteElement, getElement, updateElement } from "@/server/elements";
+
+const Patch = z.object({
+ name: z.string().trim().min(1).max(60).optional(),
+ description: z.string().max(500).nullable().optional(),
+ references: z.array(z.string().startsWith("/api/files/")).max(20).optional(),
+});
+
+export async function GET(_req: Request, ctx: RouteContext<"/api/elements/[id]">) {
+ await connection();
+ const { id } = await ctx.params;
+ const el = getElement(id);
+ return el ? Response.json(el) : Response.json({ error: "Not found" }, { status: 404 });
+}
+
+export async function PATCH(request: Request, ctx: RouteContext<"/api/elements/[id]">) {
+ const { id } = await ctx.params;
+ const parsed = Patch.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Invalid element" }, { status: 400 });
+ const el = updateElement(id, parsed.data);
+ return el ? Response.json(el) : Response.json({ error: "Not found" }, { status: 404 });
+}
+
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/elements/[id]">) {
+ const { id } = await ctx.params;
+ deleteElement(id);
+ return new Response(null, { status: 204 });
+}
diff --git a/src/app/api/elements/route.ts b/src/app/api/elements/route.ts
new file mode 100644
index 00000000..1dbf5c9c
--- /dev/null
+++ b/src/app/api/elements/route.ts
@@ -0,0 +1,27 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { createElement, listElements } from "@/server/elements";
+
+const Kind = z.enum(["character", "location", "prop", "style"]);
+
+const Body = z.object({
+ name: z.string().trim().min(1).max(60),
+ kind: Kind.default("character"),
+ description: z.string().max(500).optional(),
+ references: z.array(z.string().startsWith("/api/files/")).max(20),
+});
+
+export async function GET(request: Request) {
+ await connection();
+ const kind = Kind.safeParse(new URL(request.url).searchParams.get("kind"));
+ return Response.json({ items: listElements(kind.success ? kind.data : undefined) });
+}
+
+export async function POST(request: Request) {
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Give the element a name" }, { status: 400 });
+ if (!parsed.data.references.length && !parsed.data.description?.trim()) {
+ return Response.json({ error: "Add at least one photo or a description" }, { status: 400 });
+ }
+ return Response.json(createElement(parsed.data), { status: 201 });
+}
diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsx
index 23d508a3..e35af840 100644
--- a/src/components/app-sidebar.tsx
+++ b/src/components/app-sidebar.tsx
@@ -5,6 +5,7 @@ import { usePathname } from "next/navigation";
import { useTheme } from "next-themes";
import { Suspense } from "react";
import {
+ AtSign,
AudioLines,
Boxes,
Clapperboard,
@@ -17,7 +18,6 @@ import {
Mic2,
Moon,
Plus,
- ScanFace,
Settings,
Sparkles,
Star,
@@ -66,7 +66,7 @@ const NAV = [
{ href: "/lipsync", label: "Lipsync & avatars", icon: Mic2 },
{ href: "/motion-control", label: "Motion control", icon: PersonStanding },
{ href: "/video-edit", label: "Edit video", icon: Scissors },
- { href: "/characters", label: "Characters", icon: ScanFace },
+ { href: "/elements", label: "Elements", icon: AtSign },
{ href: "/upscale", label: "Upscale", icon: ZoomIn },
{ href: "/audio", label: "Audio", icon: AudioLines },
],
diff --git a/src/components/characters-view.tsx b/src/components/characters-view.tsx
deleted file mode 100644
index bb4aa538..00000000
--- a/src/components/characters-view.tsx
+++ /dev/null
@@ -1,201 +0,0 @@
-"use client";
-
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { Loader2, Plus, ScanFace, Trash2, X } from "lucide-react";
-import Link from "next/link";
-import { useMemo, useState } from "react";
-import { nanoid } from "nanoid";
-import { toast } from "sonner";
-import { PageShell } from "@/components/page-shell";
-import { PageHeader } from "@/components/preset-gallery";
-import { Button } from "@/components/ui/button";
-import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
-import { Input } from "@/components/ui/input";
-import { StudioPage } from "@/components/studio/studio-page";
-import { fileToSlot, MediaSlot, type SlotValue } from "@/components/studio/media-slot";
-import type { StudioConfig } from "@/components/studio/studio-context";
-
-interface Character {
- id: string;
- name: string;
- description: string | null;
- references: string[];
- createdAt: number;
-}
-
-function useCharacters() {
- return useQuery({
- queryKey: ["characters"],
- queryFn: async () => ((await (await fetch("/api/characters")).json()) as { items: Character[] }).items,
- });
-}
-
-function CreateDialog() {
- const qc = useQueryClient();
- const [open, setOpen] = useState(false);
- const [name, setName] = useState("");
- const [photos, setPhotos] = useState<SlotValue[]>([]);
- const create = useMutation({
- mutationFn: async () => {
- const res = await fetch("/api/characters", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name, references: photos.filter((p) => p.ref).map((p) => p.ref) }),
- });
- const body = await res.json();
- if (!res.ok) throw new Error(body.error);
- return body as Character;
- },
- onSuccess: () => {
- toast.success(`${name} is ready`);
- void qc.invalidateQueries({ queryKey: ["characters"] });
- setOpen(false);
- setName("");
- setPhotos([]);
- },
- onError: (e) => toast.error((e as Error).message),
- });
- const uploading = photos.some((p) => p.uploading);
- const addFiles = (files: FileList | File[]) => {
- for (const f of [...files].slice(0, 20 - photos.length)) {
- const id = nanoid(6);
- void fileToSlot(f, (v) =>
- setPhotos((ps) => {
- if (!v) return ps.filter((p) => p.id !== id);
- return ps.some((p) => p.id === id) ? ps.map((p) => (p.id === id ? { ...v, id } : p)) : [...ps, { ...v, id }];
- }),
- );
- }
- };
- return (
- <Dialog open={open} onOpenChange={setOpen}>
- <DialogTrigger asChild>
- <Button>
- <Plus /> New character
- </Button>
- </DialogTrigger>
- <DialogContent className="sm:max-w-[520px]">
- <DialogHeader>
- <DialogTitle>New character</DialogTitle>
- <DialogDescription>Upload 3–20 clear photos of one person from different angles. Fuobe uses them as identity references on every generation.</DialogDescription>
- </DialogHeader>
- <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Name, e.g. Maya" />
- <div
- className="flex flex-wrap gap-2"
- onDragOver={(e) => e.preventDefault()}
- onDrop={(e) => {
- e.preventDefault();
- addFiles(e.dataTransfer.files);
- }}
- >
- {photos.map((p) => (
- <div key={p.id} className="relative size-20 overflow-hidden rounded-xl border bg-muted">
- {/* eslint-disable-next-line @next/next/no-img-element */}
- <img src={p.preview} alt="" className="size-full object-cover" />
- {p.uploading && (
- <div className="absolute inset-0 grid place-items-center bg-background/60">
- <Loader2 className="size-4 animate-spin" />
- </div>
- )}
- <button onClick={() => setPhotos((ps) => ps.filter((x) => x.id !== p.id))} className="absolute top-1 right-1 grid size-5 place-items-center rounded-full bg-foreground/80 text-background" aria-label="Remove">
- <X className="size-3" />
- </button>
- </div>
- ))}
- {photos.length < 20 && <MediaSlot label="Add photos" kind="image" value={null} onChange={(v) => v && setPhotos((ps) => [...ps, { ...v, id: nanoid(6) }])} onFile={(f) => addFiles([f])} size="lg" />}
- </div>
- <DialogFooter>
- <Button disabled={!name.trim() || !photos.length || uploading || create.isPending} onClick={() => create.mutate()}>
- {create.isPending && <Loader2 className="animate-spin" />} Create character
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
-}
-
-export function CharactersView() {
- const qc = useQueryClient();
- const chars = useCharacters();
- return (
- <PageShell>
- <PageHeader
- title="Characters"
- description="Keep the same person across every image and video. Cloud runs use multi-reference models (Nano Banana Pro, Seedream); open-source runs use Qwen-Image-Edit or FLUX.2 with the same references."
- >
- <CreateDialog />
- </PageHeader>
- {chars.isLoading ? (
- <Loader2 className="size-5 animate-spin text-muted-foreground" />
- ) : chars.data?.length ? (
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
- {chars.data.map((c) => (
- <div key={c.id} className="group relative overflow-hidden rounded-xl border bg-background">
- <Link href={`/characters/${c.id}`} className="block">
- <div className="grid aspect-square grid-cols-2 grid-rows-2 gap-0.5 bg-muted">
- {c.references.slice(0, 4).map((r) => (
- // eslint-disable-next-line @next/next/no-img-element
- <img key={r} src={r} alt="" className={c.references.length === 1 ? "col-span-2 row-span-2 size-full object-cover" : "size-full object-cover"} />
- ))}
- </div>
- <div className="p-3">
- <p className="font-medium">{c.name}</p>
- <p className="text-[12px] text-muted-foreground">{c.references.length} reference photos</p>
- </div>
- </Link>
- <button
- onClick={async () => {
- await fetch(`/api/characters/${c.id}`, { method: "DELETE" });
- void qc.invalidateQueries({ queryKey: ["characters"] });
- toast("Deleted");
- }}
- className="absolute top-2 right-2 grid size-8 place-items-center rounded-lg bg-background/80 text-muted-foreground opacity-0 backdrop-blur transition group-hover:opacity-100 hover:text-destructive"
- aria-label="Delete character"
- >
- <Trash2 className="size-4" />
- </button>
- </div>
- ))}
- </div>
- ) : (
- <div className="rounded-xl border border-primary/10 bg-brand-faint px-6 py-14 text-center">
- <ScanFace className="mx-auto size-8 text-brand-text" />
- <p className="mt-3 font-heading text-[22px]">No characters yet</p>
- <p className="mt-1 text-[14px] text-muted-foreground">Create one from a few photos, then put them in any scene.</p>
- </div>
- )}
- </PageShell>
- );
-}
-
-export function CharacterStudio({ id }: { id: string }) {
- const q = useQuery({
- queryKey: ["character", id],
- queryFn: async () => {
- const r = await fetch(`/api/characters/${id}`);
- if (!r.ok) throw new Error("Character not found");
- return (await r.json()) as Character;
- },
- });
- const config = useMemo<StudioConfig | null>(() => {
- const c = q.data;
- if (!c) return null;
- return {
- feature: `character:${c.id}`,
- title: c.name,
- hero: `Where should ${c.name} go next?`,
- placeholder: `Describe a scene with ${c.name}… e.g. “walking through a Tokyo night market, candid street photo”`,
- kind: "image",
- ops: ["edit"],
- feed: { features: [`character:${c.id}`] },
- slots: [],
- multiRef: { label: "Add ref", max: 14 },
- defaultModels: { cloud: "nano-banana-pro", open: "oss-qwen-edit" },
- promptSuffix: `The person is the same individual shown in the reference images: keep their exact face, identity, skin tone and hair.`,
- };
- }, [q.data]);
- if (q.isError) return <PageShell><p className="text-muted-foreground">Character not found.</p></PageShell>;
- if (!config || !q.data) return <PageShell><Loader2 className="size-5 animate-spin text-muted-foreground" /></PageShell>;
- const refs = q.data.references.map((r) => `ref=${encodeURIComponent(r)}`).join("&");
- return <StudioPage config={config} key={refs} initialRefs={q.data.references} />;
-}
diff --git a/src/components/elements-view.tsx b/src/components/elements-view.tsx
new file mode 100644
index 00000000..a4a89a28
--- /dev/null
+++ b/src/components/elements-view.tsx
@@ -0,0 +1,374 @@
+"use client";
+
+import { AtSign, Check, Copy, Loader2, Pencil, Plus, Trash2, X } from "lucide-react";
+import Link from "next/link";
+import { useRouter, useSearchParams } from "next/navigation";
+import { Suspense, useEffect, useMemo, useState } from "react";
+import { nanoid } from "nanoid";
+import { toast } from "sonner";
+import { PageShell } from "@/components/page-shell";
+import { PageHeader } from "@/components/preset-gallery";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { Skeleton } from "@/components/ui/skeleton";
+import { StudioPage } from "@/components/studio/studio-page";
+import { fileToSlot, MediaSlot, type SlotValue } from "@/components/studio/media-slot";
+import { ELEMENT_ICONS } from "@/components/studio/prompt-input";
+import type { StudioConfig } from "@/components/studio/studio-context";
+import { useDeleteElement, useElement, useElements, useSaveElement } from "@/lib/api";
+import { ELEMENT_KINDS, elementKindInfo, handleFor, type ElementKind, type StudioElement } from "@/lib/catalog/elements";
+import { cn } from "@/lib/utils";
+
+const TIPS: Record<ElementKind, string> = {
+ character: "3–20 clear photos of one person: different angles, at least one full-body, no sunglasses, filters or group shots.",
+ location: "1–6 photos of the place from a few viewpoints.",
+ prop: "1–4 clean photos of the object, ideally on a plain background.",
+ style: "2–10 images that share the look you want: palette, lighting, grain, mood.",
+};
+
+const MAX_PHOTOS = 20;
+
+function PhotoGrid({ photos, setPhotos }: { photos: SlotValue[]; setPhotos: React.Dispatch<React.SetStateAction<SlotValue[]>> }) {
+ const addFiles = (files: FileList | File[]) => {
+ for (const f of [...files].slice(0, MAX_PHOTOS - photos.length)) {
+ const id = nanoid(6);
+ void fileToSlot(f, (v) =>
+ setPhotos((ps) => {
+ if (!v) return ps.filter((p) => p.id !== id);
+ return ps.some((p) => p.id === id) ? ps.map((p) => (p.id === id ? { ...v, id } : p)) : [...ps, { ...v, id }];
+ }),
+ );
+ }
+ };
+ return (
+ <div
+ className="flex flex-wrap gap-2"
+ onDragOver={(e) => e.preventDefault()}
+ onDrop={(e) => {
+ e.preventDefault();
+ addFiles(e.dataTransfer.files);
+ }}
+ >
+ {photos.map((p) => (
+ <div key={p.id} className="relative size-20 overflow-hidden rounded-xl border bg-muted">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={p.preview} alt="" className="size-full object-cover" />
+ {p.uploading && (
+ <div className="absolute inset-0 grid place-items-center bg-background/60">
+ <Loader2 className="size-4 animate-spin" />
+ </div>
+ )}
+ <button
+ onClick={() => setPhotos((ps) => ps.filter((x) => x.id !== p.id))}
+ className="absolute top-1 right-1 grid size-5 place-items-center rounded-full bg-foreground/80 text-background"
+ aria-label="Remove photo"
+ >
+ <X className="size-3" />
+ </button>
+ </div>
+ ))}
+ {photos.length < MAX_PHOTOS && (
+ <MediaSlot
+ label="Add photos"
+ kind="image"
+ value={null}
+ onChange={(v) => v && setPhotos((ps) => [...ps, { ...v, id: nanoid(6) }])}
+ onFile={(f) => addFiles([f])}
+ size="lg"
+ />
+ )}
+ </div>
+ );
+}
+
+/** Create or edit an element. */
+export function ElementDialog({
+ open,
+ onOpenChange,
+ element,
+ defaultKind = "character",
+ onSaved,
+}: {
+ open: boolean;
+ onOpenChange: (o: boolean) => void;
+ element?: StudioElement;
+ defaultKind?: ElementKind;
+ onSaved?: (el: StudioElement) => void;
+}) {
+ const save = useSaveElement();
+ const [kind, setKind] = useState<ElementKind>(element?.kind ?? defaultKind);
+ const [name, setName] = useState(element?.name ?? "");
+ const [description, setDescription] = useState(element?.description ?? "");
+ const [photos, setPhotos] = useState<SlotValue[]>(() => (element?.references ?? []).map((r) => ({ id: nanoid(6), ref: r, preview: r, kind: "image" })));
+
+ useEffect(() => {
+ if (!open) return;
+ setKind(element?.kind ?? defaultKind);
+ setName(element?.name ?? "");
+ setDescription(element?.description ?? "");
+ setPhotos((element?.references ?? []).map((r) => ({ id: nanoid(6), ref: r, preview: r, kind: "image" })));
+ }, [open, element, defaultKind]);
+
+ const uploading = photos.some((p) => p.uploading);
+ const refs = photos.filter((p) => p.ref).map((p) => p.ref);
+ const canSave = !!name.trim() && (refs.length > 0 || !!description.trim()) && !uploading && !save.isPending;
+
+ const submit = () =>
+ save.mutate(
+ { id: element?.id, name, kind, description: description || null, references: refs },
+ {
+ onSuccess: (el) => {
+ toast.success(element ? "Saved" : `@${el.handle} is ready — type @ in any prompt`);
+ onOpenChange(false);
+ onSaved?.(el);
+ },
+ onError: (e) => toast.error((e as Error).message),
+ },
+ );
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-[560px]">
+ <DialogHeader>
+ <DialogTitle>{element ? `Edit ${element.name}` : "New element"}</DialogTitle>
+ <DialogDescription>Save it once, then type @ in any image or video prompt to put it in the shot.</DialogDescription>
+ </DialogHeader>
+ {!element && (
+ <div className="grid grid-cols-4 gap-1 rounded-xl bg-muted p-1">
+ {ELEMENT_KINDS.map((k) => {
+ const Icon = ELEMENT_ICONS[k.kind];
+ return (
+ <button
+ key={k.kind}
+ onClick={() => setKind(k.kind)}
+ className={cn(
+ "flex h-14 flex-col items-center justify-center gap-1 rounded-lg text-[12px] font-medium text-muted-foreground transition",
+ kind === k.kind && "bg-background text-foreground shadow-soft",
+ )}
+ >
+ <Icon className="size-4" />
+ {k.label}
+ </button>
+ );
+ })}
+ </div>
+ )}
+ <div className="space-y-1.5">
+ <Input
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder={kind === "character" ? "Name, e.g. Maya" : kind === "location" ? "Name, e.g. Rooftop bar" : kind === "prop" ? "Name, e.g. Red sneaker" : "Name, e.g. Film noir"}
+ autoFocus
+ />
+ <p className="flex items-center gap-1 px-1 text-[12px] text-muted-foreground">
+ <AtSign className="size-3" />
+ {name.trim() ? handleFor(name) : "handle"} <span className="text-subtle-foreground">— how you mention it in prompts</span>
+ </p>
+ </div>
+ <Textarea
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ rows={2}
+ placeholder="Short description (optional) — used when a model can't take photos, e.g. “woman in her 30s, short copper hair, freckles”"
+ className="resize-none text-sm"
+ />
+ <div className="space-y-2">
+ <p className="text-[12px] text-muted-foreground">{TIPS[kind]}</p>
+ <PhotoGrid photos={photos} setPhotos={setPhotos} />
+ </div>
+ <DialogFooter>
+ <Button disabled={!canSave} onClick={submit}>
+ {save.isPending && <Loader2 className="animate-spin" />} {element ? "Save" : `Create ${elementKindInfo(kind).label.toLowerCase()}`}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function HandleCopy({ handle }: { handle: string }) {
+ const [done, setDone] = useState(false);
+ return (
+ <button
+ onClick={(e) => {
+ e.preventDefault();
+ void navigator.clipboard?.writeText(`@${handle}`);
+ setDone(true);
+ setTimeout(() => setDone(false), 1200);
+ }}
+ className="inline-flex items-center gap-1 rounded-md px-1 text-[12px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
+ title="Copy handle"
+ >
+ @{handle} {done ? <Check className="size-3" /> : <Copy className="size-3 opacity-0 transition-opacity group-hover:opacity-100" />}
+ </button>
+ );
+}
+
+function ElementCard({ el }: { el: StudioElement }) {
+ const del = useDeleteElement();
+ const Icon = ELEMENT_ICONS[el.kind];
+ return (
+ <div className="group relative overflow-hidden rounded-xl border bg-background transition-shadow hover:shadow-normal">
+ <Link href={`/elements/${el.id}`} className="block">
+ <div className="grid aspect-square grid-cols-2 grid-rows-2 gap-0.5 bg-muted">
+ {el.references.length ? (
+ el.references.slice(0, 4).map((r, i, arr) => (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ key={r}
+ src={r}
+ alt=""
+ className={cn(
+ "size-full object-cover",
+ arr.length === 1 && "col-span-2 row-span-2",
+ arr.length === 2 && "row-span-2",
+ arr.length === 3 && i === 0 && "row-span-2",
+ )}
+ />
+ ))
+ ) : (
+ <div className="col-span-2 row-span-2 grid place-items-center text-muted-foreground">
+ <Icon className="size-8" />
+ </div>
+ )}
+ </div>
+ </Link>
+ <div className="flex items-start justify-between gap-2 p-3">
+ <div className="min-w-0">
+ <p className="truncate font-medium">{el.name}</p>
+ <HandleCopy handle={el.handle} />
+ </div>
+ <span className="mt-0.5 inline-flex shrink-0 items-center gap-1 rounded-full bg-secondary px-2 py-0.5 text-[11px] text-secondary-foreground">
+ <Icon className="size-3" /> {elementKindInfo(el.kind).label}
+ </span>
+ </div>
+ <button
+ onClick={() => {
+ del.mutate(el.id);
+ toast(`Deleted ${el.name}`);
+ }}
+ className="absolute top-2 right-2 grid size-8 place-items-center rounded-lg bg-background/80 text-muted-foreground opacity-0 backdrop-blur transition group-hover:opacity-100 hover:text-destructive"
+ aria-label={`Delete ${el.name}`}
+ >
+ <Trash2 className="size-4" />
+ </button>
+ </div>
+ );
+}
+
+function ElementsBody() {
+ const sp = useSearchParams();
+ const router = useRouter();
+ const els = useElements();
+ const [tab, setTab] = useState<ElementKind | "all">("all");
+ const [open, setOpen] = useState(sp.get("new") === "1");
+ const list = useMemo(() => (els.data ?? []).filter((e) => tab === "all" || e.kind === tab), [els.data, tab]);
+
+ return (
+ <PageShell>
+ <PageHeader
+ title="Elements"
+ description="Characters, locations, props and styles you can reuse. Save one once, then type @ in any image or video prompt — Fuobe sends its photos as references, or its trained LoRA when you've trained one."
+ >
+ <Button onClick={() => setOpen(true)}>
+ <Plus /> New element
+ </Button>
+ </PageHeader>
+ <div className="mb-5 flex gap-1">
+ {(["all", ...ELEMENT_KINDS.map((k) => k.kind)] as const).map((k) => (
+ <button
+ key={k}
+ onClick={() => setTab(k)}
+ className={cn(
+ "h-8 rounded-full px-3 text-[13px] font-medium text-muted-foreground transition-colors hover:bg-accent",
+ tab === k && "bg-secondary text-foreground",
+ )}
+ >
+ {k === "all" ? "All" : elementKindInfo(k).plural}
+ </button>
+ ))}
+ </div>
+ {els.isLoading ? (
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
+ {[0, 1, 2, 3].map((i) => (
+ <Skeleton key={i} className="aspect-[4/5] rounded-xl" />
+ ))}
+ </div>
+ ) : list.length ? (
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
+ {list.map((el) => (
+ <ElementCard key={el.id} el={el} />
+ ))}
+ </div>
+ ) : (
+ <div className="rounded-xl border border-primary/10 bg-brand-faint px-6 py-14 text-center">
+ <AtSign className="mx-auto size-8 text-brand-text" />
+ <p className="mt-3 font-heading text-[22px]">{tab === "all" ? "No elements yet" : `No ${elementKindInfo(tab).plural.toLowerCase()} yet`}</p>
+ <p className="mx-auto mt-1 max-w-md text-[14px] text-muted-foreground">
+ Save a person, a place or a product from a few photos. Then write “@Maya walking into @Rooftop_bar” in any prompt.
+ </p>
+ <Button className="mt-5" variant="outline" onClick={() => setOpen(true)}>
+ <Plus /> New element
+ </Button>
+ </div>
+ )}
+ <ElementDialog
+ open={open}
+ onOpenChange={(o) => {
+ setOpen(o);
+ if (!o && sp.get("new")) router.replace("/elements");
+ }}
+ defaultKind={tab === "all" ? "character" : tab}
+ />
+ </PageShell>
+ );
+}
+
+export function ElementsView() {
+ return (
+ <Suspense fallback={null}>
+ <ElementsBody />
+ </Suspense>
+ );
+}
+
+/** A studio for one element: the prompt starts with its @handle, references are resolved by the server. */
+export function ElementStudio({ id }: { id: string }) {
+ const q = useElement(id);
+ const [editing, setEditing] = useState(false);
+ const el = q.data;
+ const config = useMemo<StudioConfig | null>(() => {
+ if (!el) return null;
+ return {
+ feature: `element:${el.id}`,
+ title: el.name,
+ hero: el.kind === "character" ? `Where should ${el.name} go next?` : el.kind === "location" ? `What happens at ${el.name}?` : el.kind === "prop" ? `Where should ${el.name} show up?` : `What should look like ${el.name}?`,
+ subtitle: `Mention @${el.handle} in any studio to use ${el.kind === "character" ? "them" : "it"} there too.`,
+ placeholder: `Describe a scene with @${el.handle}…`,
+ kind: "image",
+ ops: ["t2i", "edit"],
+ feed: { features: [`element:${el.id}`, `character:${el.id}`] },
+ slots: [],
+ multiRef: { label: "Add ref", max: 8 },
+ defaultModels: { cloud: "nano-banana-pro", open: "oss-qwen-edit" },
+ };
+ }, [el]);
+ if (q.isError) return <PageShell><p className="text-muted-foreground">Element not found.</p></PageShell>;
+ if (!config || !el) return <PageShell><Loader2 className="size-5 animate-spin text-muted-foreground" /></PageShell>;
+ return (
+ <>
+ <StudioPage
+ config={config}
+ initialPrompt={`@${el.handle} `}
+ header={
+ <Button variant="ghost" size="sm" onClick={() => setEditing(true)}>
+ <Pencil /> Edit
+ </Button>
+ }
+ />
+ <ElementDialog open={editing} onOpenChange={setEditing} element={el} />
+ </>
+ );
+}
diff --git a/src/components/home-view.tsx b/src/components/home-view.tsx
index 3084340f..9ae6135c 100644
--- a/src/components/home-view.tsx
+++ b/src/components/home-view.tsx
@@ -23,7 +23,7 @@ const TOOLS = [
{ href: "/effects", label: "Effects", desc: `${EFFECTS.length} viral VFX`, icon: Sparkles, hue: 20 },
{ href: "/apps", label: "Apps", desc: `${APPS.length} one-click tools`, icon: Wand2, hue: 200 },
{ href: "/lipsync", label: "Lipsync", desc: "Talking avatars", icon: Mic2, hue: 150 },
- { href: "/characters", label: "Characters", desc: "Consistent people", icon: ScanFace, hue: 320 },
+ { href: "/elements", label: "Elements", desc: "@ characters, places, props", icon: ScanFace, hue: 320 },
{ href: "/upscale", label: "Upscale", desc: "Images & video", icon: ZoomIn, hue: 240 },
{ href: "/audio", label: "Audio", desc: "Voice, SFX, music", icon: AudioLines, hue: 60 },
];
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index 05e1c05b..5fe4038c 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -2,6 +2,7 @@
import {
ArrowUp,
+ AtSign,
Clock,
Copy as CopyIcon,
Film,
@@ -25,15 +26,19 @@ import { Kbd } from "@/components/ui/kbd";
import { EFFECTS, getModel, getPreset, modelsFor, MOTIONS } from "@/lib/catalog";
import { estimateCost, planGeneration, routesFor } from "@/lib/catalog/plan";
import { OPERATION_LABELS, type GenerationRequest, type ModelDef, type Operation, type Preset } from "@/lib/catalog/types";
-import { enhance, useCreateGeneration, useEngine, useStatus } from "@/lib/api";
+import { enhance, useCreateGeneration, useElements, useEngine, useStatus } from "@/lib/api";
+import { applyMentions, type StudioElement } from "@/lib/catalog/elements";
import { formatCost, ratioValue } from "@/lib/format";
import { cn } from "@/lib/utils";
import { PRESET_ICONS } from "@/components/preset-icons";
import { fileToSlot, MediaSlot, SlotPreview, type SlotValue } from "./media-slot";
import { ModelPicker } from "./model-picker";
+import { ELEMENT_ICONS, PromptInput, type PromptInputHandle } from "./prompt-input";
import { useStudio } from "./studio-context";
import { nanoid } from "nanoid";
+const EMPTY: StudioElement[] = [];
+
// ---------------------------------------------------------------------------
// Chips
@@ -250,8 +255,9 @@ export function Composer({ docked }: { docked: boolean }) {
const [engine, setEngine] = useEngine();
const create = useCreateGeneration();
const [enhancing, setEnhancing] = useState(false);
- const textarea = useRef<HTMLTextAreaElement>(null);
+ const promptRef = useRef<PromptInputHandle>(null);
const status = useStatus().data;
+ const elements = useElements().data ?? EMPTY;
const preset: Preset | undefined = draft.presetId ? getPreset(draft.presetId) : config.preset;
const lockedModel = preset?.type === "app";
@@ -267,7 +273,9 @@ export function Composer({ docked }: { docked: boolean }) {
if (next && getModel(next)) setDraft((d) => ({ modelId: next, params: { ...getModel(next)!.defaults, numOutputs: d.params.numOutputs, enhancePrompt: d.params.enhancePrompt } }));
}, [engine, model, lockedModel, preset, config.defaultModels, setDraft]);
- const request = buildRequest(config.feature, draft, undefined, config.promptSuffix);
+ const rawRequest = buildRequest(config.feature, draft, undefined, config.promptSuffix);
+ const mentions = model ? applyMentions(rawRequest, model, elements) : { request: rawRequest, mentioned: [], notes: [] };
+ const request = mentions.request;
let op: Operation | undefined;
let blocker: string | null = null;
let cost: number | null = null;
@@ -295,7 +303,8 @@ export function Composer({ docked }: { docked: boolean }) {
if (blocker) toast(blocker);
return;
}
- create.mutate(buildRequest(config.feature, draft, op, config.promptSuffix), {
+ // The server resolves @mentions itself; only pin the operation when nothing was mentioned.
+ create.mutate(buildRequest(config.feature, draft, mentions.mentioned.length ? undefined : op, config.promptSuffix), {
onSuccess: (items) => {
toast.success(items.length > 1 ? `${items.length} jobs queued` : "Queued", { duration: 1500 });
},
@@ -397,22 +406,49 @@ export function Composer({ docked }: { docked: boolean }) {
{/* Prompt */}
{showPrompt && (
- <textarea
- ref={textarea}
+ <PromptInput
+ ref={promptRef}
value={draft.prompt}
- onChange={(e) => setDraft({ prompt: e.target.value })}
- onKeyDown={(e) => {
- if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
- e.preventDefault();
- submit();
- }
- }}
- rows={1}
+ onChange={(v) => setDraft({ prompt: v })}
+ onSubmit={submit}
placeholder={preset?.promptPlaceholder ?? config.placeholder}
- className="field-sizing-content max-h-52 min-h-12 w-full resize-none bg-transparent px-2.5 py-1.5 text-base leading-relaxed outline-none placeholder:text-subtle-foreground"
+ elements={elements}
/>
)}
+ {/* @mentioned elements */}
+ {mentions.mentioned.length > 0 && (
+ <div className="flex flex-wrap items-center gap-1.5 px-2 pb-2">
+ {mentions.mentioned.map((el) => {
+ const Icon = ELEMENT_ICONS[el.kind];
+ const words = mentions.notes.find((n) => n.startsWith(`${el.name} `));
+ return (
+ <Tooltip key={el.id}>
+ <TooltipTrigger asChild>
+ <span className={cn("inline-flex h-7 items-center gap-1.5 rounded-full border bg-background pr-2.5 pl-0.5 text-[12px] font-medium", words && "border-dashed text-muted-foreground")}>
+ <span className="grid size-6 place-items-center overflow-hidden rounded-full bg-muted">
+ {el.references[0] ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={el.references[0]} alt="" className="size-full object-cover" />
+ ) : (
+ <Icon className="size-3.5" />
+ )}
+ </span>
+ {el.name}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ {words ??
+ (el.loras.some((l) => l.modelId === model?.id)
+ ? `Uses ${el.name}'s trained LoRA on ${model?.name}`
+ : `${el.name}'s photos are sent as reference images`)}
+ </TooltipContent>
+ </Tooltip>
+ );
+ })}
+ </div>
+ )}
+
{/* Preset options (apps) */}
{preset?.options?.length ? (
<div className="flex flex-wrap gap-3 px-1.5 pb-2">
@@ -456,6 +492,21 @@ export function Composer({ docked }: { docked: boolean }) {
) : (
<Chip icon={Sparkles}>{model?.name}</Chip>
)}
+ {showPrompt && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ onClick={() => promptRef.current?.startMention()}
+ className="grid size-8 shrink-0 place-items-center rounded-full bg-secondary text-secondary-foreground transition-colors hover:bg-accent"
+ aria-label="Add an element"
+ >
+ <AtSign className="size-3.5" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>Add a character, location or prop · type @</TooltipContent>
+ </Tooltip>
+ )}
{config.presetPicker && (
<PresetChip
type={config.presetPicker}
diff --git a/src/components/studio/prompt-input.tsx b/src/components/studio/prompt-input.tsx
new file mode 100644
index 00000000..c3edfd7d
--- /dev/null
+++ b/src/components/studio/prompt-input.tsx
@@ -0,0 +1,213 @@
+"use client";
+
+import { AtSign, MapPin, Package, Palette, Plus, ScanFace } from "lucide-react";
+import Link from "next/link";
+import { forwardRef, useImperativeHandle, useMemo, useRef, useState } from "react";
+import { elementKindInfo, mentionAtCaret, type ElementKind, type StudioElement } from "@/lib/catalog/elements";
+import { cn } from "@/lib/utils";
+
+export const ELEMENT_ICONS: Record<ElementKind, typeof ScanFace> = {
+ character: ScanFace,
+ location: MapPin,
+ prop: Package,
+ style: Palette,
+};
+
+export interface PromptInputHandle {
+ focus: () => void;
+ /** Insert "@" at the caret and open the element menu. */
+ startMention: () => void;
+}
+
+const MENTION = /@([\p{L}\p{N}_-]+)/gu;
+
+/** Mirror of the textarea text with known @handles highlighted (drawn behind the transparent text). */
+function Highlights({ text, handles }: { text: string; handles: Set<string> }) {
+ const parts: React.ReactNode[] = [];
+ let last = 0;
+ for (const m of text.matchAll(MENTION)) {
+ if (!handles.has(m[1].toLowerCase())) continue;
+ parts.push(text.slice(last, m.index));
+ parts.push(
+ <mark key={m.index} className="rounded-[5px] bg-brand-faint text-brand-text shadow-[0_0_0_2px_var(--brand-faint)]">
+ {m[0]}
+ </mark>,
+ );
+ last = m.index + m[0].length;
+ }
+ parts.push(text.slice(last));
+ // A trailing zero-width space keeps the mirror's height in step with a trailing newline.
+ return (
+ <>
+ {parts}
+ {"​"}
+ </>
+ );
+}
+
+export const PromptInput = forwardRef<
+ PromptInputHandle,
+ {
+ value: string;
+ onChange: (v: string) => void;
+ onSubmit: () => void;
+ placeholder?: string;
+ elements: StudioElement[];
+ className?: string;
+ }
+>(function PromptInput({ value, onChange, onSubmit, placeholder, elements, className }, ref) {
+ const ta = useRef<HTMLTextAreaElement>(null);
+ const mirror = useRef<HTMLDivElement>(null);
+ const [caret, setCaret] = useState<number | null>(null);
+ const [active, setActive] = useState(0);
+ const [dismissed, setDismissed] = useState<number | null>(null);
+
+ const handles = useMemo(() => new Set(elements.map((e) => e.handle.toLowerCase())), [elements]);
+ const mention = caret != null ? mentionAtCaret(value, caret) : null;
+ const open = !!mention && dismissed !== mention.start;
+ const matches = useMemo(() => {
+ if (!mention) return [];
+ const q = mention.query.toLowerCase();
+ return elements
+ .filter((e) => !q || e.handle.toLowerCase().includes(q) || e.name.toLowerCase().includes(q))
+ .sort((a, b) => Number(b.handle.toLowerCase().startsWith(q)) - Number(a.handle.toLowerCase().startsWith(q)))
+ .slice(0, 8);
+ }, [mention, elements]);
+
+ const syncCaret = () => setCaret(ta.current?.selectionStart ?? null);
+
+ const insert = (el: StudioElement) => {
+ if (!mention) return;
+ const end = caret ?? value.length;
+ const next = `${value.slice(0, mention.start)}@${el.handle} ${value.slice(end)}`;
+ const pos = mention.start + el.handle.length + 2;
+ onChange(next);
+ requestAnimationFrame(() => {
+ ta.current?.focus();
+ ta.current?.setSelectionRange(pos, pos);
+ setCaret(pos);
+ });
+ };
+
+ useImperativeHandle(ref, () => ({
+ focus: () => ta.current?.focus(),
+ startMention: () => {
+ const el = ta.current;
+ const at = el?.selectionStart ?? value.length;
+ const needsSpace = at > 0 && !/\s/.test(value[at - 1] ?? "");
+ const next = `${value.slice(0, at)}${needsSpace ? " " : ""}@${value.slice(at)}`;
+ const pos = at + (needsSpace ? 2 : 1);
+ onChange(next);
+ setDismissed(null);
+ requestAnimationFrame(() => {
+ el?.focus();
+ el?.setSelectionRange(pos, pos);
+ setCaret(pos);
+ });
+ },
+ }));
+
+ const shared = "w-full px-2.5 py-1.5 text-left text-base leading-relaxed whitespace-pre-wrap break-words";
+
+ return (
+ <div className={cn("relative", className)}>
+ <div ref={mirror} aria-hidden className={cn(shared, "pointer-events-none absolute inset-0 overflow-hidden text-foreground")}>
+ <Highlights text={value} handles={handles} />
+ </div>
+ <textarea
+ ref={ta}
+ value={value}
+ onChange={(e) => {
+ onChange(e.target.value);
+ setCaret(e.target.selectionStart);
+ setActive(0);
+ }}
+ onSelect={syncCaret}
+ onClick={syncCaret}
+ onBlur={() => setTimeout(() => setCaret(null), 120)}
+ onScroll={(e) => {
+ if (mirror.current) mirror.current.scrollTop = e.currentTarget.scrollTop;
+ }}
+ onKeyDown={(e) => {
+ if (open && matches.length) {
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
+ e.preventDefault();
+ setActive((i) => (i + (e.key === "ArrowDown" ? 1 : matches.length - 1)) % matches.length);
+ return;
+ }
+ if (e.key === "Enter" || e.key === "Tab") {
+ e.preventDefault();
+ insert(matches[Math.min(active, matches.length - 1)]);
+ return;
+ }
+ }
+ if (open && e.key === "Escape") {
+ e.preventDefault();
+ setDismissed(mention!.start);
+ return;
+ }
+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ onSubmit();
+ }
+ }}
+ rows={1}
+ placeholder={placeholder}
+ spellCheck
+ className={cn(
+ shared,
+ "scrollbar-none relative field-sizing-content max-h-52 min-h-12 resize-none bg-transparent text-transparent caret-foreground outline-none placeholder:text-subtle-foreground selection:bg-brand-faint selection:text-transparent",
+ )}
+ />
+ {open && (
+ <div
+ role="listbox"
+ className="absolute bottom-full left-0 z-50 mb-2 w-[min(92vw,320px)] overflow-hidden rounded-xl border bg-popover p-1 text-popover-foreground shadow-heavy animate-in fade-in-0 zoom-in-95"
+ onMouseDown={(e) => e.preventDefault()}
+ >
+ <p className="flex items-center gap-1.5 px-2 pt-1.5 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">
+ <AtSign className="size-3" /> Elements
+ </p>
+ {matches.map((el, i) => {
+ const Icon = ELEMENT_ICONS[el.kind];
+ return (
+ <button
+ key={el.id}
+ role="option"
+ aria-selected={i === active}
+ onMouseEnter={() => setActive(i)}
+ onClick={() => insert(el)}
+ className={cn("flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left", i === active && "bg-accent")}
+ >
+ <span className="grid size-8 shrink-0 place-items-center overflow-hidden rounded-md bg-muted text-muted-foreground">
+ {el.references[0] ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={el.references[0]} alt="" className="size-full object-cover" />
+ ) : (
+ <Icon className="size-4" />
+ )}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[13px] font-medium">@{el.handle}</span>
+ <span className="block truncate text-[11px] text-muted-foreground">
+ {elementKindInfo(el.kind).label}
+ {el.references.length ? ` · ${el.references.length} photo${el.references.length > 1 ? "s" : ""}` : ""}
+ {el.loras.length ? " · trained" : ""}
+ </span>
+ </span>
+ </button>
+ );
+ })}
+ {!matches.length && (
+ <p className="px-2 py-3 text-[13px] text-muted-foreground">
+ {elements.length ? "No element with that name." : "No elements yet. Save a character, location or prop once, then @mention it anywhere."}
+ </p>
+ )}
+ <Link href="/elements?new=1" className="mt-1 flex items-center gap-2 rounded-lg border-t px-2 py-2 text-[13px] text-muted-foreground hover:bg-accent hover:text-foreground">
+ <Plus className="size-3.5" /> New element
+ </Link>
+ </div>
+ )}
+ </div>
+ );
+});
diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsx
index c3901e5c..e28d9988 100644
--- a/src/components/studio/studio-page.tsx
+++ b/src/components/studio/studio-page.tsx
@@ -188,7 +188,15 @@ function StudioBody({ header }: { header?: React.ReactNode }) {
);
}
-function StudioInner({ config, header, initialRefs }: { config: StudioConfig; header?: React.ReactNode; initialRefs?: string[] }) {
+interface StudioPageProps {
+ config: StudioConfig;
+ header?: React.ReactNode;
+ initialRefs?: string[];
+ /** Prompt to start with when the URL doesn't carry one (e.g. "@Maya "). */
+ initialPrompt?: string;
+}
+
+function StudioInner({ config, header, initialRefs, initialPrompt }: StudioPageProps) {
const sp = useSearchParams();
const [engine] = useEngine();
// Recompute the initial draft only when the handoff params change.
@@ -196,6 +204,7 @@ function StudioInner({ config, header, initialRefs }: { config: StudioConfig; he
const initial = useMemo(() => {
const d = initialDraft(config, new URLSearchParams(key), engine);
if (initialRefs?.length) d.refs = [...initialRefs.map((u) => slot(u)!), ...d.refs];
+ if (initialPrompt && !d.prompt) d.prompt = initialPrompt;
return d;
}, [config, key]); // eslint-disable-line react-hooks/exhaustive-deps
return (
@@ -205,10 +214,10 @@ function StudioInner({ config, header, initialRefs }: { config: StudioConfig; he
);
}
-export function StudioPage({ config, header, initialRefs }: { config: StudioConfig; header?: React.ReactNode; initialRefs?: string[] }) {
+export function StudioPage(props: StudioPageProps) {
return (
<Suspense fallback={null}>
- <StudioInner config={config} header={header} initialRefs={initialRefs} />
+ <StudioInner {...props} />
</Suspense>
);
}
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 140f4d28..57dea3ff 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -2,6 +2,7 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useSyncExternalStore } from "react";
+import type { ElementKind, StudioElement } from "./catalog/elements";
import type { Engine, Generation, GenerationRequest, MediaKind } from "./catalog/types";
export interface Asset {
@@ -121,6 +122,51 @@ export function useAssets(source?: "upload" | "generation", kind?: MediaKind) {
});
}
+// ---------------------------------------------------------------------------
+// Elements (@characters, locations, props, styles)
+
+export function useElements() {
+ return useQuery({
+ queryKey: ["elements"],
+ queryFn: async () => (await json<{ items: StudioElement[] }>(await fetch("/api/elements"))).items,
+ staleTime: 10_000,
+ });
+}
+
+export function useElement(id: string) {
+ return useQuery({
+ queryKey: ["elements", id],
+ queryFn: async () => json<StudioElement>(await fetch(`/api/elements/${id}`)),
+ });
+}
+
+export function useSaveElement() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async (body: { id?: string; name: string; kind?: ElementKind; description?: string | null; references: string[] }) => {
+ const { id, ...rest } = body;
+ return json<StudioElement>(
+ await fetch(id ? `/api/elements/${id}` : "/api/elements", {
+ method: id ? "PATCH" : "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(rest),
+ }),
+ );
+ },
+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["elements"] }),
+ });
+}
+
+export function useDeleteElement() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async (id: string) => {
+ await fetch(`/api/elements/${id}`, { method: "DELETE" });
+ },
+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["elements"] }),
+ });
+}
+
// ---------------------------------------------------------------------------
// Provider status
diff --git a/src/lib/catalog/elements.ts b/src/lib/catalog/elements.ts
new file mode 100644
index 00000000..98e9082a
--- /dev/null
+++ b/src/lib/catalog/elements.ts
@@ -0,0 +1,193 @@
+/**
+ * Elements: reusable characters, locations, props and styles that can be dropped into
+ * any prompt with `@handle` (Higgsfield's "Elements" / Soul ID). Resolution is pure so the
+ * server (authoritative), the composer (live preview + cost) and the agent share it.
+ */
+import type { Engine, GenerationRequest, LoraRef, ModelDef, Operation } from "./types";
+
+export type ElementKind = "character" | "location" | "prop" | "style";
+
+export const ELEMENT_KINDS: { kind: ElementKind; label: string; plural: string; noun: string; refs: number }[] = [
+ { kind: "character", label: "Character", plural: "Characters", noun: "the person", refs: 3 },
+ { kind: "location", label: "Location", plural: "Locations", noun: "the location", refs: 2 },
+ { kind: "prop", label: "Prop", plural: "Props", noun: "the object", refs: 1 },
+ { kind: "style", label: "Style", plural: "Styles", noun: "the visual style", refs: 2 },
+];
+
+export const elementKindInfo = (k: ElementKind) => ELEMENT_KINDS.find((x) => x.kind === k) ?? ELEMENT_KINDS[0];
+
+/** A trained identity LoRA for an element (Soul ID parity). */
+export interface ElementLora {
+ engine: Engine;
+ /** Model the LoRA was trained for; it's only applied when that model runs. */
+ modelId: string;
+ /** ComfyUI models/loras file name (open) or a URL the cloud LoRA endpoint accepts. */
+ file: string;
+ url?: string;
+ trigger: string;
+ strength?: number;
+}
+
+export interface StudioElement {
+ id: string;
+ name: string;
+ handle: string;
+ kind: ElementKind;
+ description: string | null;
+ references: string[];
+ loras: ElementLora[];
+ status: "ready" | "training" | "failed";
+ createdAt: number;
+}
+
+/** `Maya Lopez` → `Maya_Lopez`. Letters, digits, `_` and `-` only. */
+export function handleFor(name: string): string {
+ return (
+ name
+ .trim()
+ .replace(/\s+/g, "_")
+ .replace(/[^\p{L}\p{N}_-]/gu, "")
+ .slice(0, 40) || "element"
+ );
+}
+
+const MENTION = /@([\p{L}\p{N}_-]+)/gu;
+
+/** Elements mentioned in a prompt, in order of first mention, without duplicates. */
+export function findMentions(prompt: string | undefined, elements: StudioElement[]): StudioElement[] {
+ if (!prompt || !elements.length) return [];
+ const byHandle = new Map(elements.map((e) => [e.handle.toLowerCase(), e]));
+ const out: StudioElement[] = [];
+ for (const m of prompt.matchAll(MENTION)) {
+ const el = byHandle.get(m[1].toLowerCase());
+ if (el && !out.includes(el)) out.push(el);
+ }
+ return out;
+}
+
+/** The `@partial` being typed at the caret, if any. */
+export function mentionAtCaret(text: string, caret: number): { start: number; query: string } | null {
+ const before = text.slice(0, caret);
+ const m = /(^|[\s(“"'])@([\p{L}\p{N}_-]*)$/u.exec(before);
+ if (!m) return null;
+ return { start: caret - m[2].length - 1, query: m[2] };
+}
+
+export interface MentionResolution {
+ request: GenerationRequest;
+ mentioned: StudioElement[];
+ /** Human notes, e.g. "Maya is described in words — Kling 2.5 can't take reference images". */
+ notes: string[];
+}
+
+const ops = (m: ModelDef) => new Set(m.routes.map((r) => r.op));
+
+/**
+ * Turn `@handle` mentions into reference images (or a trained LoRA + trigger word) and a
+ * prompt that tells the model which image is which. Leaves the request alone when nothing
+ * is mentioned.
+ */
+export function applyMentions(req: GenerationRequest, model: ModelDef, elements: StudioElement[]): MentionResolution {
+ const mentioned = findMentions(req.prompt, elements);
+ if (!mentioned.length) return { request: req, mentioned, notes: [] };
+
+ const notes: string[] = [];
+ const has = ops(model);
+ const existing = [...(req.inputs?.images ?? [])];
+ let op: Operation | undefined = req.op;
+
+ // Where can references go?
+ let budget = 0;
+ if (model.kind === "image" && has.has("edit")) {
+ budget = Math.max(0, (model.options.maxImages ?? 1) - existing.length);
+ if (!op || op === "t2i") op = undefined; // edit is inferred once images are attached
+ } else if (model.kind === "video" && has.has("ref2v") && !req.inputs?.endImage && (existing.length === 0 || op === "ref2v")) {
+ budget = Math.max(0, (model.options.maxImages ?? 4) - existing.length);
+ }
+
+ // LoRAs win over references for the model they were trained on.
+ const loras: LoraRef[] = [...(req.loras ?? [])];
+ const viaLora = new Set<string>();
+ for (const el of mentioned) {
+ const l = el.loras.find((x) => x.modelId === model.id && x.engine === model.engine);
+ if (l) {
+ loras.push({ file: l.file, url: l.url, strength: l.strength ?? 1, trigger: l.trigger });
+ viaLora.add(el.id);
+ }
+ }
+
+ // Share the reference budget: one image each first, then fill up to each kind's ideal count.
+ const wanted = mentioned.filter((e) => !viaLora.has(e.id) && e.references.length);
+ const take = new Map<string, number>(wanted.map((e) => [e.id, 0]));
+ let left = budget;
+ for (let round = 0; left > 0; round++) {
+ let gave = false;
+ for (const e of wanted) {
+ const want = Math.min(e.references.length, elementKindInfo(e.kind).refs);
+ if (left > 0 && take.get(e.id)! < want && take.get(e.id)! === round) {
+ take.set(e.id, round + 1);
+ left--;
+ gave = true;
+ }
+ }
+ if (!gave) break;
+ }
+
+ const images = [...existing];
+ const positions = new Map<string, number[]>();
+ for (const e of wanted) {
+ const n = take.get(e.id) ?? 0;
+ const pos: number[] = [];
+ for (const ref of e.references.slice(0, n)) {
+ images.push(ref);
+ pos.push(images.length);
+ }
+ positions.set(e.id, pos);
+ }
+ if (model.kind === "video" && images.length > existing.length) op = "ref2v";
+
+ // Rewrite the prompt: "@Maya" → "Maya", plus who/what each image is.
+ let prompt = req.prompt ?? "";
+ const seen = new Set<string>();
+ prompt = prompt.replace(MENTION, (whole, h: string) => {
+ const el = mentioned.find((e) => e.handle.toLowerCase() === h.toLowerCase());
+ if (!el) return whole;
+ const first = !seen.has(el.id);
+ seen.add(el.id);
+ const lora = loras.find((l) => viaLora.has(el.id) && el.loras.some((x) => x.file === l.file));
+ if (lora?.trigger && first) return `${lora.trigger} ${el.name}`;
+ if (first && !positions.get(el.id)?.length && !viaLora.has(el.id) && el.description) return `${el.name} (${el.description.replace(/[.\s]+$/, "")})`;
+ return el.name;
+ });
+ const legend = mentioned
+ .map((e) => {
+ const pos = positions.get(e.id) ?? [];
+ if (!pos.length) return null;
+ const which = pos.length === 1 ? `image ${pos[0]}` : `images ${pos.slice(0, -1).join(", ")} and ${pos[pos.length - 1]}`;
+ const noun = elementKindInfo(e.kind).noun;
+ return e.kind === "character"
+ ? `${e.name} is ${noun} in ${which} — keep their exact face, identity, skin tone and hair`
+ : e.kind === "style"
+ ? `Use ${noun} of ${which} for ${e.name}`
+ : `${e.name} is ${noun} in ${which}`;
+ })
+ .filter(Boolean);
+ if (legend.length) prompt = `${prompt.trim().replace(/[.\s]+$/, "")}. ${legend.join(". ")}.`;
+
+ for (const e of mentioned) {
+ if (viaLora.has(e.id)) continue;
+ if (!positions.get(e.id)?.length) {
+ notes.push(
+ budget === 0
+ ? `${e.name} is described in words — ${model.name} can't take reference images here`
+ : `${e.name} is described in words — no room for more reference images`,
+ );
+ }
+ }
+
+ return {
+ request: { ...req, op, prompt, inputs: { ...req.inputs, images: images.length ? images : undefined }, loras: loras.length ? loras : undefined },
+ mentioned,
+ notes,
+ };
+}
diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.ts
index ebb4d1e5..e400a881 100644
--- a/src/lib/catalog/plan.ts
+++ b/src/lib/catalog/plan.ts
@@ -104,6 +104,7 @@ export function planGeneration(
if (sameModel) op = op ?? route.op;
}
+ if (req.loras?.length) loras = [...loras, ...req.loras];
op = op ?? inferOperation(model, req);
if (!routesFor(model, op).length) {
throw new Error(`${model.name} can't do ${op} — try another model`);
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 54d3e6c1..84cf94b8 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -216,6 +216,8 @@ export interface GenerationRequest {
params?: GenParams;
/** Values for preset option pickers (apps). */
presetOptions?: Record<string, string>;
+ /** Server-side only: LoRAs added by @element mentions (trained identities). */
+ loras?: LoraRef[];
}
/** Canonical, provider-ready input (asset refs already resolved to provider URLs/filenames). */
diff --git a/src/server/characters.ts b/src/server/characters.ts
deleted file mode 100644
index 390579af..00000000
--- a/src/server/characters.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import "server-only";
-import { nanoid } from "nanoid";
-import { db } from "./db";
-
-export interface Character {
- id: string;
- name: string;
- description: string | null;
- references: string[];
- triggerWord: string | null;
- loraFile: string | null;
- status: "ready" | "training" | "failed";
- createdAt: number;
-}
-
-interface Row {
- id: string;
- name: string;
- description: string | null;
- reference_asset_ids_json: string;
- trigger_word: string | null;
- lora_file: string | null;
- status: Character["status"];
- created_at: number;
-}
-
-const toCharacter = (r: Row): Character => ({
- id: r.id,
- name: r.name,
- description: r.description,
- references: JSON.parse(r.reference_asset_ids_json) as string[],
- triggerWord: r.trigger_word,
- loraFile: r.lora_file,
- status: r.status,
- createdAt: r.created_at,
-});
-
-export function listCharacters(): Character[] {
- return (db().prepare("SELECT * FROM characters ORDER BY created_at DESC").all() as Row[]).map(toCharacter);
-}
-
-export function getCharacter(id: string): Character | null {
- const r = db().prepare("SELECT * FROM characters WHERE id = ?").get(id) as Row | undefined;
- return r ? toCharacter(r) : null;
-}
-
-export function createCharacter(input: { name: string; description?: string; references: string[] }): Character {
- const now = Date.now();
- const row: Row = {
- id: nanoid(10),
- name: input.name.trim().slice(0, 60),
- description: input.description?.trim() || null,
- reference_asset_ids_json: JSON.stringify(input.references.slice(0, 20)),
- trigger_word: null,
- lora_file: null,
- status: "ready",
- created_at: now,
- };
- db()
- .prepare(
- `INSERT INTO characters (id, name, description, reference_asset_ids_json, trigger_word, lora_file, status, created_at, updated_at)
- VALUES (@id, @name, @description, @reference_asset_ids_json, @trigger_word, @lora_file, @status, @created_at, @created_at)`,
- )
- .run(row);
- return toCharacter(row);
-}
-
-export function deleteCharacter(id: string): void {
- db().prepare("DELETE FROM characters WHERE id = ?").run(id);
-}
diff --git a/src/server/db.ts b/src/server/db.ts
index 4676d093..df013d9d 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -61,6 +61,10 @@ const MIGRATIONS: string[] = [
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);`,
+ // Characters become Elements (characters, locations, props, styles) with @handles and trained LoRAs.
+ `ALTER TABLE characters ADD COLUMN kind TEXT NOT NULL DEFAULT 'character';
+ ALTER TABLE characters ADD COLUMN handle TEXT;
+ ALTER TABLE characters ADD COLUMN loras_json TEXT;`,
];
declare global {
diff --git a/src/server/elements.ts b/src/server/elements.ts
new file mode 100644
index 00000000..4cce20a5
--- /dev/null
+++ b/src/server/elements.ts
@@ -0,0 +1,104 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { handleFor, type ElementKind, type ElementLora, type StudioElement } from "@/lib/catalog/elements";
+import { db } from "./db";
+
+interface Row {
+ id: string;
+ name: string;
+ handle: string | null;
+ kind: ElementKind;
+ description: string | null;
+ reference_asset_ids_json: string;
+ loras_json: string | null;
+ status: StudioElement["status"];
+ created_at: number;
+}
+
+const toElement = (r: Row): StudioElement => ({
+ id: r.id,
+ name: r.name,
+ handle: r.handle ?? handleFor(r.name),
+ kind: r.kind,
+ description: r.description,
+ references: JSON.parse(r.reference_asset_ids_json) as string[],
+ loras: r.loras_json ? (JSON.parse(r.loras_json) as ElementLora[]) : [],
+ status: r.status,
+ createdAt: r.created_at,
+});
+
+export function listElements(kind?: ElementKind): StudioElement[] {
+ const rows = kind
+ ? db().prepare("SELECT * FROM characters WHERE kind = ? ORDER BY created_at DESC").all(kind)
+ : db().prepare("SELECT * FROM characters ORDER BY created_at DESC").all();
+ return (rows as Row[]).map(toElement);
+}
+
+export function getElement(id: string): StudioElement | null {
+ const r = db().prepare("SELECT * FROM characters WHERE id = ?").get(id) as Row | undefined;
+ return r ? toElement(r) : null;
+}
+
+/** A handle nobody else uses: Maya, Maya_2, Maya_3… */
+function uniqueHandle(name: string, exceptId?: string): string {
+ const base = handleFor(name);
+ const taken = new Set(
+ (db().prepare("SELECT id, handle FROM characters").all() as { id: string; handle: string | null }[])
+ .filter((r) => r.id !== exceptId)
+ .map((r) => (r.handle ?? "").toLowerCase()),
+ );
+ if (!taken.has(base.toLowerCase())) return base;
+ for (let i = 2; ; i++) if (!taken.has(`${base}_${i}`.toLowerCase())) return `${base}_${i}`;
+}
+
+export function createElement(input: { name: string; kind: ElementKind; description?: string; references: string[] }): StudioElement {
+ const now = Date.now();
+ const name = input.name.trim().slice(0, 60);
+ const row = {
+ id: nanoid(10),
+ name,
+ handle: uniqueHandle(name),
+ kind: input.kind,
+ description: input.description?.trim() || null,
+ reference_asset_ids_json: JSON.stringify(input.references.slice(0, 20)),
+ loras_json: null,
+ status: "ready" as const,
+ created_at: now,
+ };
+ db()
+ .prepare(
+ `INSERT INTO characters (id, name, handle, kind, description, reference_asset_ids_json, loras_json, status, created_at, updated_at)
+ VALUES (@id, @name, @handle, @kind, @description, @reference_asset_ids_json, @loras_json, @status, @created_at, @created_at)`,
+ )
+ .run(row);
+ return toElement(row);
+}
+
+export function updateElement(
+ id: string,
+ patch: { name?: string; description?: string | null; references?: string[]; loras?: ElementLora[]; status?: StudioElement["status"] },
+): StudioElement | null {
+ const cur = getElement(id);
+ if (!cur) return null;
+ const name = patch.name?.trim().slice(0, 60) || cur.name;
+ db()
+ .prepare(
+ `UPDATE characters SET name = @name, handle = @handle, description = @description, reference_asset_ids_json = @refs,
+ loras_json = @loras, status = @status, updated_at = @now WHERE id = @id`,
+ )
+ .run({
+ id,
+ name,
+ handle: name === cur.name ? cur.handle : uniqueHandle(name, id),
+ description: patch.description === undefined ? cur.description : patch.description?.trim() || null,
+ refs: JSON.stringify((patch.references ?? cur.references).slice(0, 20)),
+ loras: JSON.stringify(patch.loras ?? cur.loras),
+ status: patch.status ?? cur.status,
+ now: Date.now(),
+ });
+ return getElement(id);
+}
+
+export function deleteElement(id: string): void {
+ db().prepare("DELETE FROM characters WHERE id = ?").run(id);
+}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 20a0f3da..b89c1255 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -3,6 +3,7 @@ import fs from "node:fs";
import path from "node:path";
import { nanoid } from "nanoid";
import { getModel, getPreset } from "@/lib/catalog";
+import { applyMentions } from "@/lib/catalog/elements";
import { estimateCost, planGeneration, routesFor } from "@/lib/catalog/plan";
import {
OPERATION_OUTPUT,
@@ -14,6 +15,7 @@ import {
type ProviderId,
} from "@/lib/catalog/types";
import { db } from "./db";
+import { listElements } from "./elements";
import { enhancePrompt } from "./enhance";
import { provider } from "./providers";
import type { RemoteOutput } from "./providers/types";
@@ -160,7 +162,10 @@ export function chooseRoute(candidates: ModelRoute[]): { route: ModelRoute; demo
// ---------------------------------------------------------------------------
// Create
-export function createGenerations(req: GenerationRequest): Generation[] {
+export function createGenerations(original: GenerationRequest): Generation[] {
+ // @element mentions become reference images / LoRAs; the stored request keeps the mentions for "Reuse".
+ const model = getModel(original.modelId);
+ const req = model ? applyMentions(original, model, listElements()).request : original;
const plan = planGeneration(req, getModel, getPreset);
const mode = engineMode();
if (mode !== "both" && plan.model.engine !== mode) {
@@ -192,7 +197,7 @@ export function createGenerations(req: GenerationRequest): Generation[] {
progress: null,
message: demo ? "Demo mode — no provider connected" : "Submitting",
prompt: plan.prompt,
- request_json: JSON.stringify(req),
+ request_json: JSON.stringify(original),
provider_input_json: null,
external_id: null,
external_meta_json: null,
diff --git a/tests/elements.test.ts b/tests/elements.test.ts
new file mode 100644
index 00000000..380eda57
--- /dev/null
+++ b/tests/elements.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from "vitest";
+import { getModel, getPreset } from "@/lib/catalog";
+import { applyMentions, findMentions, handleFor, mentionAtCaret, type StudioElement } from "@/lib/catalog/elements";
+import { planGeneration } from "@/lib/catalog/plan";
+
+const el = (over: Partial<StudioElement>): StudioElement => ({
+ id: over.handle ?? "x",
+ name: "Maya",
+ handle: "Maya",
+ kind: "character",
+ description: null,
+ references: ["/api/files/a.png", "/api/files/b.png", "/api/files/c.png", "/api/files/d.png"],
+ loras: [],
+ status: "ready",
+ createdAt: 0,
+ ...over,
+});
+
+const maya = el({});
+const bar = el({ name: "Rooftop bar", handle: "Rooftop_bar", kind: "location", references: ["/api/files/bar.png"] });
+
+describe("handles and mentions", () => {
+ it("builds handles from names", () => {
+ expect(handleFor("Maya Lopez")).toBe("Maya_Lopez");
+ expect(handleFor(" Café #1 ")).toBe("Café_1");
+ });
+ it("finds known mentions once, case-insensitively", () => {
+ expect(findMentions("@maya at @Rooftop_bar with @Maya and @nobody", [maya, bar]).map((e) => e.handle)).toEqual(["Maya", "Rooftop_bar"]);
+ });
+ it("detects the mention being typed", () => {
+ expect(mentionAtCaret("hello @Ma", 9)).toEqual({ start: 6, query: "Ma" });
+ expect(mentionAtCaret("mail@x", 6)).toBeNull();
+ expect(mentionAtCaret("@", 1)).toEqual({ start: 0, query: "" });
+ });
+});
+
+describe("applyMentions", () => {
+ it("attaches references to an image edit model and explains which image is which", () => {
+ const nb = getModel("nano-banana-pro")!;
+ const { request, notes } = applyMentions({ feature: "image", modelId: nb.id, prompt: "@Maya sipping coffee at @Rooftop_bar" }, nb, [maya, bar]);
+ expect(request.inputs?.images?.length).toBe(4);
+ expect(request.prompt).toContain("Maya sipping coffee at Rooftop bar");
+ expect(request.prompt).toContain("Maya is the person in images 1, 2 and 3");
+ expect(request.prompt).toContain("Rooftop bar is the location in image 4");
+ expect(notes).toEqual([]);
+ expect(planGeneration(request, getModel, getPreset).op).toBe("edit");
+ });
+
+ it("switches video models with reference support to reference-to-video", () => {
+ const m = getModel("seedance-2-5")!;
+ expect(m.routes.some((r) => r.op === "ref2v")).toBe(true);
+ const { request } = applyMentions({ feature: "video", modelId: m.id, prompt: "@Maya dances" }, m, [maya]);
+ expect(request.op).toBe("ref2v");
+ expect(planGeneration(request, getModel, getPreset).op).toBe("ref2v");
+ });
+
+ it("falls back to the description when the model can't take references", () => {
+ const m = getModel("kling-2-5-turbo")!;
+ const described = el({ description: "short copper hair, freckles." });
+ const { request, notes } = applyMentions({ feature: "video", modelId: m.id, prompt: "@Maya runs" }, m, [described]);
+ expect(request.inputs?.images).toBeUndefined();
+ expect(request.prompt).toBe("Maya (short copper hair, freckles) runs");
+ expect(notes[0]).toMatch(/described in words/);
+ });
+
+ it("uses a trained LoRA instead of references on the model it was trained for", () => {
+ const m = getModel("oss-z-image-turbo")!;
+ const trained = el({ loras: [{ engine: "open", modelId: m.id, file: "maya.safetensors", trigger: "mya woman" }] });
+ const { request } = applyMentions({ feature: "image", modelId: m.id, prompt: "@Maya on a beach" }, m, [trained]);
+ expect(request.loras).toEqual([{ file: "maya.safetensors", url: undefined, strength: 1, trigger: "mya woman" }]);
+ expect(request.prompt).toBe("mya woman Maya on a beach");
+ expect(planGeneration(request, getModel, getPreset).loras.map((l) => l.file)).toEqual(["maya.safetensors"]);
+ });
+
+ it("leaves requests without mentions untouched", () => {
+ const nb = getModel("nano-banana-pro")!;
+ const req = { feature: "image", modelId: nb.id, prompt: "email [email protected]" };
+ expect(applyMentions(req, nb, [maya]).request).toBe(req);
+ });
+});