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
Assist: a chat agent that plans the shoot, prices it, asks first, then runs it
Claude3bc4b149d0ad
diff --git a/src/app/(studio)/assist/page.tsx b/src/app/(studio)/assist/page.tsxnew file mode 100644index 00000000..c45d62e6--- /dev/null+++ b/src/app/(studio)/assist/page.tsx@@ -0,0 +1,13 @@+import type { Metadata } from "next";+import { Suspense } from "react";+import { AssistView } from "@/components/assist-view";++export const metadata: Metadata = { title: "Assist" };++export default function Page() {+ return (+ <Suspense>+ <AssistView />+ </Suspense>+ );+}diff --git a/src/app/api/assist/[id]/approval/route.ts b/src/app/api/assist/[id]/approval/route.tsnew file mode 100644index 00000000..2d548cc6--- /dev/null+++ b/src/app/api/assist/[id]/approval/route.ts@@ -0,0 +1,20 @@+import { after } from "next/server";+import { z } from "zod";+import { answerApproval, AssistBusyError, run } from "@/server/assist/agent";++const Body = z.object({ approve: z.boolean() });++/** Approve (run) or decline the plan on the thread's approval card; the agent then carries on. */+export async function POST(request: Request, ctx: RouteContext<"/api/assist/[id]/approval">) {+ const { id } = await ctx.params;+ const parsed = Body.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Say approve true or false" }, { status: 400 });+ try {+ const thread = await answerApproval(id, parsed.data.approve);+ const reply = run(id);+ after(() => reply);+ return Response.json(thread);+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: e instanceof AssistBusyError ? 409 : 404 });+ }+}diff --git a/src/app/api/assist/[id]/messages/route.ts b/src/app/api/assist/[id]/messages/route.tsnew file mode 100644index 00000000..227b0934--- /dev/null+++ b/src/app/api/assist/[id]/messages/route.ts@@ -0,0 +1,17 @@+import { after } from "next/server";+import { addMessage, AssistBusyError, run } from "@/server/assist/agent";+import { AssistMessage } from "@/server/assist/schemas";++export async function POST(request: Request, ctx: RouteContext<"/api/assist/[id]/messages">) {+ const { id } = await ctx.params;+ const parsed = AssistMessage.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Write a message" }, { status: 400 });+ try {+ const thread = addMessage(id, parsed.data.text, parsed.data.attachments);+ const reply = run(id);+ after(() => reply);+ return Response.json(thread);+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: e instanceof AssistBusyError ? 409 : 404 });+ }+}diff --git a/src/app/api/assist/[id]/route.ts b/src/app/api/assist/[id]/route.tsnew file mode 100644index 00000000..e3593a4e--- /dev/null+++ b/src/app/api/assist/[id]/route.ts@@ -0,0 +1,23 @@+import { connection } from "next/server";+import { z } from "zod";+import { deleteThread, getThread, updateThread } from "@/server/assist/agent";++const Patch = z.object({ autoApprove: z.boolean().optional(), title: z.string().trim().min(1).max(80).optional() });++export async function GET(_req: Request, ctx: RouteContext<"/api/assist/[id]">) {+ await connection();+ const view = getThread((await ctx.params).id);+ return view ? Response.json(view) : Response.json({ error: "Not found" }, { status: 404 });+}++export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/[id]">) {+ const parsed = Patch.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Invalid change" }, { status: 400 });+ const t = updateThread((await ctx.params).id, parsed.data);+ return t ? Response.json(t) : Response.json({ error: "Not found" }, { status: 404 });+}++export async function DELETE(_req: Request, ctx: RouteContext<"/api/assist/[id]">) {+ deleteThread((await ctx.params).id);+ return new Response(null, { status: 204 });+}diff --git a/src/app/api/assist/route.ts b/src/app/api/assist/route.tsnew file mode 100644index 00000000..5520ae54--- /dev/null+++ b/src/app/api/assist/route.ts@@ -0,0 +1,24 @@+import { after, connection } from "next/server";+import { z } from "zod";+import { addMessage, agentKind, createThread, listThreads, run } from "@/server/assist/agent";+import { AssistMessage } from "@/server/assist/schemas";++const Create = AssistMessage.extend({ engine: z.enum(["cloud", "open"]), autoApprove: z.boolean().optional() });++export async function GET() {+ await connection();+ return Response.json({ threads: listThreads(), agent: agentKind() });+}++/** Start a chat with its first message; the agent replies in the background (poll the thread). */+export async function POST(request: Request) {+ const parsed = Create.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Write a message" }, { status: 400 });+ const { text, attachments, engine, autoApprove } = parsed.data;+ const thread = createThread({ engine, autoApprove });+ const updated = addMessage(thread.id, text, attachments);+ // Claimed now (not in after()) so a poll that lands first doesn't see a stale "running" thread.+ const reply = run(thread.id);+ after(() => reply);+ return Response.json(updated, { status: 201 });+}diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsxindex 6de12b69..cc5364b1 100644--- a/src/components/app-sidebar.tsx+++ b/src/components/app-sidebar.tsx@@ -6,6 +6,7 @@ import { useTheme } from "next-themes";import { Suspense } from "react";import {AtSign,+ MessageCircle,GalleryHorizontal,Layers,Crop,@@ -58,6 +59,7 @@ const NAV = [label: "Create",items: [{ href: "/", label: "Home", icon: Home },+ { href: "/assist", label: "Assist", icon: MessageCircle },{ href: "/image", label: "Image", icon: ImageIcon },{ href: "/video", label: "Video", icon: Video },{ href: "/edit", label: "Edit", icon: Wand2 },diff --git a/src/components/assist-view.tsx b/src/components/assist-view.tsxnew file mode 100644index 00000000..f1667a2c--- /dev/null+++ b/src/components/assist-view.tsx@@ -0,0 +1,555 @@+"use client";++import { ArrowUp, AudioLines, Bot, Check, CircleAlert, Clapperboard, Cpu, History, ImageIcon, Loader2, Paperclip, Plus, Search, Sparkles, Trash2, Video, X } from "lucide-react";+import Link from "next/link";+import { usePathname, useRouter, useSearchParams } from "next/navigation";+import { useEffect, useMemo, useRef, useState } from "react";+import { nanoid } from "nanoid";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { SidebarTrigger } from "@/components/ui/sidebar";+import { Switch } from "@/components/ui/switch";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { EngineSwitch } from "@/components/studio/engine-switch";+import { FailedTile, MediaThumb, PendingTile, tileRatio } from "@/components/studio/feed";+import { Viewer } from "@/components/studio/viewer";+import { uploadFile, useAssistActions, useAssistThread, useAssistThreads, useCreateGeneration, useEngine } from "@/lib/api";+import type { AssistItem, AssistThread, PlannedJob } from "@/lib/assist";+import { OPERATION_LABELS, type Generation, type MediaKind } from "@/lib/catalog/types";+import { formatCost, timeAgo } from "@/lib/format";+import { cn } from "@/lib/utils";++const SUGGESTIONS = [+ "A 3-shot product ad for a matte black perfume bottle — hero still, then animate it",+ "Four moody portraits of a lighthouse keeper, 35mm film, then pick the best and animate it",+ "Storyboard a 6-frame heist in Paris at night",+ "A 10-second vertical video of a fox running through snow, with sound",+];++const KIND_ICON: Record<MediaKind | "storyboard", typeof ImageIcon> = { image: ImageIcon, video: Video, audio: AudioLines, storyboard: Clapperboard };++interface Attachment {+ id: string;+ preview: string;+ url?: string;+ kind: MediaKind;+}++// ---------------------------------------------------------------------------+// Composer++function Composer({+ onSend,+ disabled,+ placeholder,+ autoFocus,+ footer,+}: {+ onSend: (text: string, attachments: string[]) => Promise<void>;+ disabled?: boolean;+ placeholder: string;+ autoFocus?: boolean;+ footer?: React.ReactNode;+}) {+ const [text, setText] = useState("");+ const [files, setFiles] = useState<Attachment[]>([]);+ const [sending, setSending] = useState(false);+ const input = useRef<HTMLInputElement>(null);+ const uploading = files.some((f) => !f.url);+ const ready = text.trim().length > 0 && !uploading && !sending && !disabled;++ const add = (list: FileList | null) => {+ for (const f of Array.from(list ?? []).slice(0, 8 - files.length)) {+ const id = nanoid(6);+ const kind: MediaKind = f.type.startsWith("video") ? "video" : f.type.startsWith("audio") ? "audio" : "image";+ setFiles((xs) => [...xs, { id, kind, preview: URL.createObjectURL(f) }]);+ uploadFile(f)+ .then((a) => setFiles((xs) => xs.map((x) => (x.id === id ? { ...x, url: a.url } : x))))+ .catch((e) => {+ toast.error((e as Error).message);+ setFiles((xs) => xs.filter((x) => x.id !== id));+ });+ }+ };++ const send = async () => {+ if (!ready) return;+ setSending(true);+ try {+ await onSend(text.trim(), files.map((f) => f.url!));+ setText("");+ setFiles([]);+ } catch (e) {+ toast.error((e as Error).message);+ } finally {+ setSending(false);+ }+ };++ return (+ <div+ className="rounded-composer border bg-background p-2.5 shadow-soft transition focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint"+ onDragOver={(e) => e.preventDefault()}+ onDrop={(e) => {+ e.preventDefault();+ add(e.dataTransfer.files);+ }}+ >+ {files.length > 0 && (+ <div className="mb-2 flex flex-wrap gap-2 px-1 pt-1">+ {files.map((f) => (+ <div key={f.id} className="relative size-14 overflow-hidden rounded-lg border bg-muted">+ {f.kind === "image" ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={f.preview} alt="" className="size-full object-cover" />+ ) : f.kind === "video" ? (+ <video src={f.preview} muted className="size-full object-cover" />+ ) : (+ <AudioLines className="m-auto mt-4 size-5 text-muted-foreground" />+ )}+ {!f.url && <Loader2 className="absolute inset-0 m-auto size-4 animate-spin text-foreground" />}+ <button+ onClick={() => setFiles((xs) => xs.filter((x) => x.id !== f.id))}+ className="absolute top-0.5 right-0.5 grid size-4 place-items-center rounded-full bg-foreground/80 text-background"+ aria-label="Remove attachment"+ >+ <X className="size-2.5" />+ </button>+ </div>+ ))}+ </div>+ )}+ <textarea+ value={text}+ autoFocus={autoFocus}+ onChange={(e) => setText(e.target.value)}+ onPaste={(e) => e.clipboardData.files.length && add(e.clipboardData.files)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {+ e.preventDefault();+ void send();+ }+ }}+ rows={1}+ placeholder={placeholder}+ className="field-sizing-content max-h-56 min-h-12 w-full resize-none bg-transparent px-2 py-1.5 text-base leading-relaxed outline-none placeholder:text-subtle-foreground"+ />+ <div className="mt-1 flex items-center gap-2">+ <input ref={input} type="file" accept="image/*,video/*,audio/*" multiple hidden onChange={(e) => (add(e.target.files), (e.target.value = ""))} />+ <Tooltip>+ <TooltipTrigger asChild>+ <button onClick={() => input.current?.click()} className="grid size-9 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Attach files">+ <Paperclip className="size-4" />+ </button>+ </TooltipTrigger>+ <TooltipContent>Attach photos, video or audio</TooltipContent>+ </Tooltip>+ {footer}+ <Button size="icon" className="ml-auto size-10 rounded-full" disabled={!ready} onClick={() => void send()} aria-label="Send">+ {sending ? <Loader2 className="animate-spin" /> : <ArrowUp />}+ </Button>+ </div>+ </div>+ );+}++function AskFirst({ checked, onChange }: { checked: boolean; onChange: (v: boolean) => void }) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <label className="inline-flex h-9 cursor-pointer items-center gap-2 rounded-full px-2.5 text-[13px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground">+ <Switch size="sm" checked={checked} onCheckedChange={onChange} aria-label="Ask before generating" />+ Ask first+ </label>+ </TooltipTrigger>+ <TooltipContent>{checked ? "You approve each plan and its cost before anything runs" : "Plans run right away — no approval card"}</TooltipContent>+ </Tooltip>+ );+}++// ---------------------------------------------------------------------------+// Transcript items++/** Paragraphs, "- " bullets and **bold** — the little markdown the assistant uses. */+function Prose({ text }: { text: string }) {+ const inline = (s: string) => s.split(/(\*\*[^*]+\*\*)/g).map((p, i) => (p.startsWith("**") && p.endsWith("**") ? <strong key={i}>{p.slice(2, -2)}</strong> : p));+ return (+ <div className="space-y-2.5 text-[15px] leading-relaxed">+ {text.split(/\n{2,}/).map((para, i) => {+ const lines = para.split("\n");+ if (lines.every((l) => /^\s*([-*•]|\d+\.)\s/.test(l))) {+ return (+ <ul key={i} className="list-disc space-y-1 pl-5 marker:text-muted-foreground">+ {lines.map((l, j) => (+ <li key={j}>{inline(l.replace(/^\s*([-*•]|\d+\.)\s/, ""))}</li>+ ))}+ </ul>+ );+ }+ return (+ <p key={i} className="whitespace-pre-wrap">+ {inline(para)}+ </p>+ );+ })}+ </div>+ );+}++function jobPrice(j: PlannedJob): string {+ if (j.error) return "—";+ if (j.demo) return "Demo";+ if (j.costUsd === 0) return "Free";+ return j.costUsd === null ? "Price varies" : formatCost(j.costUsd);+}++function ApprovalCard({ item, live, onAnswer }: { item: Extract<AssistItem, { role: "approval" }>; live: boolean; onAnswer: (ok: boolean) => Promise<void> }) {+ const [busy, setBusy] = useState<boolean | null>(null);+ const runnable = item.jobs.some((j) => !j.error);+ const allDemo = item.jobs.every((j) => j.demo || j.error);+ const total = allDemo ? "Demo run — no provider connected" : item.totalUsd === null ? "Some prices vary" : item.totalUsd === 0 ? "Free" : `≈ ${formatCost(item.totalUsd)}`;+ const answer = async (ok: boolean) => {+ setBusy(ok);+ try {+ await onAnswer(ok);+ } catch (e) {+ toast.error((e as Error).message);+ } finally {+ setBusy(null);+ }+ };+ return (+ <div className={cn("animate-fade-up overflow-hidden rounded-2xl border bg-background shadow-soft", item.status !== "pending" && "opacity-80")}>+ <div className="flex items-center gap-2 border-b bg-muted/40 px-4 py-2.5">+ <Sparkles className="size-3.5 text-brand-text" />+ <p className="min-w-0 flex-1 truncate text-[13px] font-medium">{item.summary}</p>+ {item.status === "approved" && (+ <span className="inline-flex items-center gap-1 text-[12px] font-medium text-brand-text">+ <Check className="size-3" /> Approved+ </span>+ )}+ {item.status === "declined" && <span className="text-[12px] text-muted-foreground">Skipped</span>}+ </div>+ <ul className="divide-y">+ {item.jobs.map((j, i) => {+ const Icon = KIND_ICON[j.op === "storyboard" ? "storyboard" : j.kind];+ return (+ <li key={i} className="flex gap-3 px-4 py-3">+ <span className="mt-0.5 grid size-8 shrink-0 place-items-center rounded-lg bg-secondary">+ <Icon className="size-4" />+ </span>+ <div className="min-w-0 flex-1">+ <p className="text-[13px] font-medium">+ {j.modelName}+ <span className="font-normal text-muted-foreground">+ {" · "}+ {j.op === "storyboard" ? `Storyboard · ${j.count} frames` : `${OPERATION_LABELS[j.op] ?? j.op}${j.count > 1 ? ` · ${j.count} takes` : ""}`}+ </span>+ </p>+ <p className="mt-0.5 line-clamp-2 text-[13px] text-muted-foreground">{j.prompt}</p>+ {j.error && (+ <p className="mt-1 flex items-center gap-1 text-[12px] text-destructive">+ <CircleAlert className="size-3" /> {j.error}+ </p>+ )}+ </div>+ <span className="shrink-0 font-mono text-[12px] text-muted-foreground">{jobPrice(j)}</span>+ </li>+ );+ })}+ </ul>+ <div className="flex flex-wrap items-center gap-2 border-t px-4 py-2.5">+ <p className="text-[12px] text-muted-foreground">{total}</p>+ {live && item.status === "pending" && (+ <div className="ml-auto flex gap-1.5">+ <Button variant="ghost" size="sm" disabled={busy !== null} onClick={() => void answer(false)}>+ Not now+ </Button>+ <Button size="sm" disabled={busy !== null || !runnable} onClick={() => void answer(true)}>+ {busy ? <Loader2 className="animate-spin" /> : <Check />} Run{item.totalUsd && !allDemo ? ` · ${formatCost(item.totalUsd)}` : ""}+ </Button>+ </div>+ )}+ </div>+ </div>+ );+}++function GenerationCards({ ids, all, storyboard, onOpen }: { ids: string[]; all: Map<string, Generation>; storyboard?: boolean; onOpen: (g: Generation, i: number) => void }) {+ const create = useCreateGeneration();+ const gens = ids.map((id) => all.get(id)).filter((g): g is Generation => !!g);+ if (!gens.length) return null;+ const tiles = gens.flatMap((g) => {+ const ratio = tileRatio(g);+ if (g.status === "succeeded") {+ return g.outputs.map((o, i) => (+ <button key={`${g.id}-${i}`} onClick={() => onOpen(g, i)} className="group relative overflow-hidden rounded-xl bg-muted" style={{ aspectRatio: ratio }}>+ <MediaThumb output={o} className="transition duration-300 group-hover:scale-[1.02]" />+ {g.provider === "mock" && <span className="absolute top-2 left-2 rounded-full bg-background/80 px-2 py-0.5 text-[10px] font-medium">Demo</span>}+ </button>+ ));+ }+ if (g.status === "failed" || g.status === "canceled") {+ return [<FailedTile key={g.id} g={g} ratio={ratio} onRetry={() => create.mutate(g.request, { onError: (e) => toast.error((e as Error).message) })} />];+ }+ return Array.from({ length: Math.max(1, g.request.params?.numOutputs ?? 1) }, (_, i) => <PendingTile key={`${g.id}-${i}`} g={g} ratio={ratio} />);+ });+ const portrait = tileRatio(gens[0]) < 1;+ return (+ <div className={cn("grid gap-2", storyboard ? "grid-cols-2 sm:grid-cols-4" : portrait ? "grid-cols-2 sm:grid-cols-3" : tiles.length === 1 ? "grid-cols-1 sm:w-4/5" : "grid-cols-2")}>+ {tiles}+ </div>+ );+}++function Transcript({ thread, all, onAnswer, onOpen }: { thread: AssistThread; all: Map<string, Generation>; onAnswer: (ok: boolean) => Promise<void>; onOpen: (g: Generation, i: number) => void }) {+ const lastApproval = thread.items.findLast((i) => i.role === "approval")?.id;+ return (+ <div className="space-y-5">+ {thread.items.map((item) => {+ switch (item.role) {+ case "user":+ return (+ <div key={item.id} className="flex animate-fade-up flex-col items-end gap-2">+ {item.attachments?.length ? (+ <div className="flex flex-wrap justify-end gap-1.5">+ {item.attachments.map((a) => (+ <div key={a} className="size-16 overflow-hidden rounded-xl border bg-muted">+ <MediaThumb output={{ url: a, kind: /\.(mp4|webm|mov)$/i.test(a) ? "video" : /\.(mp3|wav|ogg|m4a)$/i.test(a) ? "audio" : "image" }} />+ </div>+ ))}+ </div>+ ) : null}+ <div className="max-w-[85%] rounded-2xl rounded-br-md bg-secondary px-4 py-2.5 text-[15px] leading-relaxed whitespace-pre-wrap">{item.text}</div>+ </div>+ );+ case "assistant":+ return (+ <div key={item.id} className="animate-fade-up">+ <Prose text={item.text} />+ </div>+ );+ case "tool":+ return (+ <p key={item.id} className="flex items-center gap-1.5 text-[12px] text-muted-foreground">+ <Search className="size-3" /> {item.text}+ </p>+ );+ case "approval":+ return <ApprovalCard key={item.id} item={item} live={item.id === lastApproval && thread.status === "waiting"} onAnswer={onAnswer} />;+ case "generations":+ return <GenerationCards key={item.id} ids={item.ids} all={all} storyboard={item.storyboard} onOpen={onOpen} />;+ case "notice":+ return (+ <p+ key={item.id}+ className={cn("flex items-start gap-2 rounded-xl px-3 py-2 text-[13px]", item.tone === "error" ? "bg-destructive/10 text-destructive" : "bg-muted text-muted-foreground")}+ >+ <CircleAlert className="mt-0.5 size-3.5 shrink-0" /> {item.text}+ </p>+ );+ }+ })}+ {thread.status === "running" && (+ <p className="shimmer-text animate-shimmer-text flex items-center gap-2 text-[14px] font-medium">+ <Sparkles className="size-3.5" /> Thinking…+ </p>+ )}+ </div>+ );+}++// ---------------------------------------------------------------------------++function HistoryButton({ current, onPick }: { current: string | null; onPick: (id: string | null) => void }) {+ const threads = useAssistThreads();+ const actions = useAssistActions();+ const [open, setOpen] = useState(false);+ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <Button variant="ghost" size="sm" className="text-muted-foreground">+ <History /> <span className="hidden sm:inline">History</span>+ </Button>+ </PopoverTrigger>+ <PopoverContent align="end" className="w-80 p-1.5">+ {threads.data?.threads.length ? (+ <ul className="max-h-96 overflow-y-auto">+ {threads.data.threads.map((t) => (+ <li key={t.id} className="group flex items-center">+ <button+ onClick={() => {+ onPick(t.id);+ setOpen(false);+ }}+ className={cn("min-w-0 flex-1 rounded-lg px-2.5 py-2 text-left hover:bg-accent", t.id === current && "bg-accent")}+ >+ <p className="truncate text-[13px] font-medium">{t.title}</p>+ <p className="text-[11px] text-muted-foreground">{timeAgo(t.updatedAt)}</p>+ </button>+ <button+ onClick={() => {+ void actions.remove(t.id);+ if (t.id === current) onPick(null);+ }}+ className="grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground opacity-0 group-hover:opacity-100 hover:text-destructive focus:opacity-100"+ aria-label={`Delete ${t.title}`}+ >+ <Trash2 className="size-3.5" />+ </button>+ </li>+ ))}+ </ul>+ ) : (+ <p className="px-3 py-6 text-center text-[13px] text-muted-foreground">No chats yet</p>+ )}+ </PopoverContent>+ </Popover>+ );+}++export function AssistView() {+ const router = useRouter();+ const pathname = usePathname();+ const params = useSearchParams();+ const id = params.get("c");+ const [engine, setEngine] = useEngine();+ const [askFirst, setAskFirst] = useState(true);+ const [open, setOpen] = useState<{ g: Generation; i: number } | null>(null);+ const threads = useAssistThreads();+ const view = useAssistThread(id);+ const actions = useAssistActions();+ const end = useRef<HTMLDivElement>(null);++ const go = (next: string | null) => router.replace(next ? `${pathname}?c=${next}` : pathname, { scroll: false });+ const thread = view.data?.thread;+ const all = useMemo(() => new Map((view.data?.generations ?? []).map((g) => [g.id, g])), [view.data?.generations]);+ const viewable = useMemo(+ () =>+ (thread?.items ?? []).flatMap((i) => (i.role === "generations" ? i.ids : [])).flatMap((gid) => {+ const g = all.get(gid);+ return g?.status === "succeeded" ? g.outputs.map((_, k) => ({ g, i: k })) : [];+ }),+ [thread?.items, all],+ );+ const pos = open ? viewable.findIndex((v) => v.g.id === open.g.id && v.i === open.i) : -1;++ const count = thread?.items.length ?? 0;+ const status = thread?.status;+ useEffect(() => {+ end.current?.scrollIntoView({ behavior: "smooth", block: "end" });+ }, [count, status]);++ const agent = thread?.agent ?? threads.data?.agent;+ const offline = agent === "offline";+ const agentBadge = agent && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Link href="/settings" className="inline-flex h-7 items-center gap-1.5 rounded-full bg-muted px-2.5 text-[12px] font-medium whitespace-nowrap text-muted-foreground hover:text-foreground">+ {offline ? <Cpu className="size-3" /> : <Bot className="size-3" />}+ <span className={cn(id && "hidden sm:inline")}>{offline ? "Offline planner" : "Claude"}</span>+ </Link>+ </TooltipTrigger>+ <TooltipContent className="max-w-64">+ {offline ? "A simple rule-based planner. Add an Anthropic API key in Settings for the full assistant that picks models, chains steps and checks results." : "Claude plans the shoot, picks models and runs them with your approval."}+ </TooltipContent>+ </Tooltip>+ );++ return (+ <div className="flex h-svh min-w-0 flex-col">+ <header className="flex h-14 shrink-0 items-center gap-2 px-3 sm:px-6">+ <SidebarTrigger className="md:hidden" />+ <h1 className="min-w-0 truncate font-heading text-[22px] leading-none">{thread?.title ?? "Assist"}</h1>+ <div className="ml-auto flex items-center gap-1">+ {agentBadge}+ <HistoryButton current={id} onPick={go} />+ {id && (+ <Button variant="ghost" size="sm" onClick={() => go(null)}>+ <Plus /> <span className="hidden sm:inline">New chat</span>+ </Button>+ )}+ </div>+ </header>++ {!id ? (+ <main className="flex min-h-0 flex-1 flex-col items-center justify-center overflow-y-auto px-3 pb-16 sm:px-6">+ <div className="w-full max-w-[760px]">+ <div className="mb-6 text-center">+ <h2 className="font-heading text-display text-balance">What are we making?</h2>+ <p className="mt-2 text-[14px] text-muted-foreground">Describe the whole job. Assist picks the models, shows you the plan and cost, then runs every step.</p>+ </div>+ <Composer+ autoFocus+ placeholder="e.g. “A launch campaign for my sneaker: 3 hero stills, then a 5s vertical video of the best one”"+ onSend={async (text, attachments) => {+ const t = await actions.start({ text, attachments, engine, autoApprove: !askFirst });+ go(t.id);+ }}+ footer={+ <>+ <EngineSwitch value={engine} onChange={setEngine} size="sm" />+ <AskFirst checked={askFirst} onChange={setAskFirst} />+ </>+ }+ />+ <div className="mt-4 flex flex-wrap justify-center gap-2">+ {SUGGESTIONS.map((s) => (+ <button+ key={s}+ onClick={async () => {+ try {+ const t = await actions.start({ text: s, engine, autoApprove: !askFirst });+ go(t.id);+ } catch (e) {+ toast.error((e as Error).message);+ }+ }}+ className="max-w-full rounded-full border bg-background px-3.5 py-1.5 text-left text-[13px] text-muted-foreground transition hover:border-primary hover:text-foreground"+ >+ {s}+ </button>+ ))}+ </div>+ </div>+ </main>+ ) : (+ <>+ <main className="min-h-0 flex-1 overflow-y-auto px-3 sm:px-6">+ <div className="mx-auto w-full max-w-[760px] py-4">+ {view.isError ? (+ <p className="py-20 text-center text-muted-foreground">This chat doesn't exist anymore.</p>+ ) : thread ? (+ <Transcript thread={thread} all={all} onAnswer={(ok) => actions.answer(thread.id, ok)} onOpen={(g, i) => setOpen({ g, i })} />+ ) : (+ <Loader2 className="mx-auto mt-20 animate-spin text-muted-foreground" />+ )}+ <div ref={end} className="h-4" />+ </div>+ </main>+ <div className="shrink-0 px-3 pb-4 sm:px-6">+ <div className="mx-auto w-full max-w-[760px]">+ <Composer+ placeholder={thread?.status === "waiting" ? "Or tell me what to change…" : "Ask for changes, variations or the next step…"}+ disabled={!thread || thread.status === "running"}+ onSend={(text, attachments) => actions.send(id, { text, attachments })}+ footer={thread && <AskFirst checked={!thread.autoApprove} onChange={(v) => void actions.setAutoApprove(thread.id, !v)} />}+ />+ </div>+ </div>+ </>+ )}++ {open && pos >= 0 && (+ <Viewer+ generation={viewable[pos].g}+ index={viewable[pos].i}+ onClose={() => setOpen(null)}+ onPrev={pos > 0 ? () => setOpen(viewable[pos - 1]) : undefined}+ onNext={pos < viewable.length - 1 ? () => setOpen(viewable[pos + 1]) : undefined}+ />+ )}+ </div>+ );+}diff --git a/src/lib/api.ts b/src/lib/api.tsindex caa1ef4a..3f826f93 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 { AssistThread, AssistThreadSummary, AssistThreadView } from "./assist";import type { ElementKind, StudioElement } from "./catalog/elements";import type { Engine, Generation, GenerationRequest, MediaKind } from "./catalog/types";@@ -285,3 +286,65 @@ export function useEngine(): [Engine, (e: Engine) => void, EngineMode] {);return [mode === "both" ? engine : mode, set, mode];}++// ---------------------------------------------------------------------------+// Assist++export function useAssistThreads() {+ return useQuery({+ queryKey: ["assist"],+ queryFn: async () => json<{ threads: AssistThreadSummary[]; agent: AssistThread["agent"] }>(await fetch("/api/assist")),+ });+}++export function useAssistThread(id: string | null) {+ return useQuery({+ queryKey: ["assist", id],+ enabled: !!id,+ queryFn: async () => json<AssistThreadView>(await fetch(`/api/assist/${id}`)),+ // Fast while the agent works, slower while generations render, idle otherwise.+ refetchInterval: (q) => {+ const d = q.state.data;+ if (!d) return false;+ if (d.thread.status === "running") return 900;+ return d.generations.some((g) => g.status === "queued" || g.status === "running") ? 1500 : false;+ },+ });+}++export function useAssistActions() {+ const qc = useQueryClient();+ const refresh = (id: string) => {+ void qc.invalidateQueries({ queryKey: ["assist", id] });+ void qc.invalidateQueries({ queryKey: ["assist"], exact: true });+ };+ const post = async <T,>(url: string, body: unknown, method = "POST") =>+ json<T>(await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));+ return {+ start: async (body: { text: string; attachments?: string[]; engine: Engine; autoApprove: boolean }) => {+ const t = await post<AssistThread>("/api/assist", body);+ qc.setQueryData<AssistThreadView>(["assist", t.id], { thread: t, generations: [] });+ refresh(t.id);+ return t;+ },+ send: async (id: string, body: { text: string; attachments?: string[] }) => {+ const t = await post<AssistThread>(`/api/assist/${id}/messages`, body);+ qc.setQueryData<AssistThreadView>(["assist", id], (old) => ({ thread: t, generations: old?.generations ?? [] }));+ refresh(id);+ },+ answer: async (id: string, approve: boolean) => {+ const t = await post<AssistThread>(`/api/assist/${id}/approval`, { approve });+ qc.setQueryData<AssistThreadView>(["assist", id], (old) => ({ thread: t, generations: old?.generations ?? [] }));+ refresh(id);+ },+ setAutoApprove: async (id: string, autoApprove: boolean) => {+ await post(`/api/assist/${id}`, { autoApprove }, "PATCH");+ refresh(id);+ },+ remove: async (id: string) => {+ await fetch(`/api/assist/${id}`, { method: "DELETE" });+ qc.removeQueries({ queryKey: ["assist", id] });+ void qc.invalidateQueries({ queryKey: ["assist"], exact: true });+ },+ };+}diff --git a/src/lib/assist.ts b/src/lib/assist.tsnew file mode 100644index 00000000..21983444--- /dev/null+++ b/src/lib/assist.ts@@ -0,0 +1,67 @@+/**+ * Assist: a chat agent that plans a shoot, picks models, shows the cost, asks before spending+ * and then runs the generations (Higgsfield's "Supercomputer"). Shared by the server loop and the UI.+ */+import type { Engine, Generation, MediaKind, Operation } from "./catalog/types";++/** One job the agent wants to run, priced before the user approves it. */+export interface PlannedJob {+ tool: "generate" | "create_storyboard";+ modelId: string;+ modelName: string;+ kind: MediaKind;+ op: Operation | "storyboard";+ prompt: string;+ /** Generations this job creates (outputs × jobs, or storyboard frames). */+ count: number;+ costUsd: number | null;+ /** No provider connected: it would run as a demo. */+ demo: boolean;+ /** Can't run as planned (missing input, model blocked by engine mode…). */+ error?: string;+}++export type AssistItem =+ | { id: string; role: "user"; text: string; attachments?: string[] }+ | { id: string; role: "assistant"; text: string }+ | { id: string; role: "tool"; text: string }+ | { id: string; role: "approval"; summary: string; jobs: PlannedJob[]; totalUsd: number | null; status: "pending" | "approved" | "declined" }+ | { id: string; role: "generations"; ids: string[]; storyboard?: boolean }+ | { id: string; role: "notice"; text: string; tone: "info" | "error" };++export type AssistStatus = "idle" | "running" | "waiting";++export interface AssistThread {+ id: string;+ title: string;+ status: AssistStatus;+ /** "claude" = the full agent; "offline" = a rule-based planner (no LLM configured). */+ agent: "claude" | "offline";+ engine: Engine;+ /** Run plans without the approval card. */+ autoApprove: boolean;+ items: AssistItem[];+ createdAt: number;+ updatedAt: number;+}++export interface AssistThreadSummary {+ id: string;+ title: string;+ status: AssistStatus;+ updatedAt: number;+}++export interface AssistThreadView {+ thread: AssistThread;+ /** Generations referenced by the thread's cards. */+ generations: Generation[];+}++export const totalCost = (jobs: PlannedJob[]): number | null =>+ jobs.some((j) => j.costUsd === null && !j.demo) ? null : Math.round(jobs.reduce((s, j) => s + (j.costUsd ?? 0), 0) * 1000) / 1000;++export function threadTitle(text: string): string {+ const t = text.trim().replace(/\s+/g, " ");+ return t.length > 60 ? `${t.slice(0, 57).replace(/\s+\S*$/, "")}…` : t || "New chat";+}diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.tsnew file mode 100644index 00000000..269eb518--- /dev/null+++ b/src/server/assist/agent.ts@@ -0,0 +1,534 @@+import "server-only";+import Anthropic from "@anthropic-ai/sdk";+import { nanoid } from "nanoid";+import { AUDIO_STUDIO, EDIT_STUDIO, IMAGE_STUDIO, MUSIC_STUDIO, VIDEO_STUDIO } from "@/lib/studios";+import { type AssistItem, type AssistThread, type AssistThreadSummary, type AssistThreadView, threadTitle } from "@/lib/assist";+import type { Engine, Generation } from "@/lib/catalog/types";+import { db } from "../db";+import { getGeneration } from "../generations";+import { engineMode, getSetting } from "../settings";+import { readRef } from "../storage";+import { apiTools, getTool, planFor, type ToolContext } from "./tools";++/**+ * The Assist agent loop. History is kept exactly as the API returned it (append-only, thinking+ * included) so later turns stay valid; generations that cost money stop the loop with an approval+ * card, and the user's answer resumes it with the matching tool results.+ */++type MessageParam = Anthropic.Beta.BetaMessageParam;+type ToolResult = Anthropic.Beta.BetaToolResultBlockParam;+type UserBlock = Exclude<MessageParam["content"], string>[number];++export interface ModelRequest {+ system: { stable: string; turn: string };+ messages: MessageParam[];+ tools: Anthropic.Beta.BetaTool[];+ ctx: ToolContext;+}+export type ModelCall = (req: ModelRequest) => Promise<Anthropic.Beta.BetaMessage>;++const MAX_STEPS = 16;+const MAX_IMAGE_BYTES = 3_500_000;++// ---------------------------------------------------------------------------+// Storage++interface Pending {+ approvalItemId: string;+ /** Results of the turn's tools that already ran (read-only ones). */+ results: ToolResult[];+ /** The gated calls waiting for the user. */+ gated: { id: string; name: string; input: unknown }[];+ /** tool_use ids in the order the model sent them. */+ order: string[];+}++interface Row {+ id: string;+ title: string;+ status: AssistThread["status"];+ agent: AssistThread["agent"];+ engine: Engine;+ auto_approve: number;+ messages_json: string;+ items_json: string;+ pending_json: string | null;+ created_at: number;+ updated_at: number;+}++interface State {+ thread: AssistThread;+ messages: MessageParam[];+ pending: Pending | null;+}++declare global {+ var __fuobeAssistRuns: Set<string> | undefined;+}+const runs = (globalThis.__fuobeAssistRuns ??= new Set());++function load(id: string): State | null {+ const r = db().prepare("SELECT * FROM assist_threads WHERE id = ?").get(id) as Row | undefined;+ if (!r) return null;+ const s: State = {+ thread: {+ id: r.id,+ title: r.title,+ status: r.status,+ agent: r.agent,+ engine: r.engine,+ autoApprove: !!r.auto_approve,+ items: JSON.parse(r.items_json) as AssistItem[],+ createdAt: r.created_at,+ updatedAt: r.updated_at,+ },+ messages: JSON.parse(r.messages_json) as MessageParam[],+ pending: r.pending_json ? (JSON.parse(r.pending_json) as Pending) : null,+ };+ // A run that died with the server (restart, crash) leaves the thread "running": reopen it.+ if (s.thread.status === "running" && !runs.has(id)) {+ s.thread.status = "idle";+ push(s, { role: "notice", tone: "error", text: "This reply was interrupted. Send a message to carry on." });+ save(s);+ }+ return s;+}++function save(s: State): void {+ s.thread.updatedAt = Date.now();+ db()+ .prepare(+ `INSERT INTO assist_threads (id, title, status, agent, engine, auto_approve, messages_json, items_json, pending_json, created_at, updated_at)+ VALUES (@id, @title, @status, @agent, @engine, @auto_approve, @messages_json, @items_json, @pending_json, @created_at, @updated_at)+ ON CONFLICT(id) DO UPDATE SET title = @title, status = @status, auto_approve = @auto_approve, messages_json = @messages_json,+ items_json = @items_json, pending_json = @pending_json, updated_at = @updated_at`,+ )+ .run({+ id: s.thread.id,+ title: s.thread.title,+ status: s.thread.status,+ agent: s.thread.agent,+ engine: s.thread.engine,+ auto_approve: s.thread.autoApprove ? 1 : 0,+ messages_json: JSON.stringify(s.messages),+ items_json: JSON.stringify(s.thread.items),+ pending_json: s.pending ? JSON.stringify(s.pending) : null,+ created_at: s.thread.createdAt,+ updated_at: s.thread.updatedAt,+ });+}++type NewItem = AssistItem extends infer T ? (T extends AssistItem ? Omit<T, "id"> : never) : never;+function push(s: State, item: NewItem | AssistItem): AssistItem {+ const full = { ...item, id: ("id" in item && item.id) || nanoid(10) } as AssistItem;+ s.thread.items.push(full);+ return full;+}++export function listThreads(): AssistThreadSummary[] {+ return (db().prepare("SELECT id, title, status, updated_at FROM assist_threads ORDER BY updated_at DESC LIMIT 100").all() as Row[]).map((r) => ({+ id: r.id,+ title: r.title,+ status: r.status,+ updatedAt: r.updated_at,+ }));+}++export function getThread(id: string): AssistThreadView | null {+ const s = load(id);+ if (!s) return null;+ const ids = s.thread.items.flatMap((i) => (i.role === "generations" ? i.ids : []));+ const generations = ids.map((g) => getGeneration(g)).filter((g): g is Generation => !!g);+ return { thread: s.thread, generations };+}++export function deleteThread(id: string): void {+ db().prepare("DELETE FROM assist_threads WHERE id = ?").run(id);+}++export function updateThread(id: string, patch: { autoApprove?: boolean; title?: string }): AssistThread | null {+ const s = load(id);+ if (!s) return null;+ if (patch.autoApprove !== undefined) s.thread.autoApprove = patch.autoApprove;+ if (patch.title) s.thread.title = patch.title;+ save(s);+ return s.thread;+}++/** Claude when a key is set (and the install allows it), else the offline planner. */+export function agentKind(): AssistThread["agent"] {+ const choice = getSetting("enhanceProvider");+ if (!getSetting("anthropicKey") || choice === "none" || choice === "ollama") return "offline";+ return choice === "anthropic" || engineMode() !== "open" ? "claude" : "offline";+}++export function createThread(opts: { engine: Engine; autoApprove?: boolean; title?: string }): AssistThread {+ const now = Date.now();+ const s: State = {+ thread: { id: nanoid(12), title: opts.title ?? "New chat", status: "idle", agent: agentKind(), engine: opts.engine, autoApprove: !!opts.autoApprove, items: [], createdAt: now, updatedAt: now },+ messages: [],+ pending: null,+ };+ save(s);+ return s.thread;+}++// ---------------------------------------------------------------------------+// Messages++/** User content goes into the last user turn when there is one (after a refusal or an error). */+function appendUser(messages: MessageParam[], blocks: UserBlock[]): void {+ const last = messages.at(-1);+ if (last?.role === "user") {+ const prior = typeof last.content === "string" ? [{ type: "text" as const, text: last.content }] : last.content;+ last.content = [...prior, ...blocks];+ } else {+ messages.push({ role: "user", content: blocks });+ }+}++/** Tool calls left without results (a crash mid-tool) would make every later request invalid. */+function closeDanglingToolUses(messages: MessageParam[]): void {+ const last = messages.at(-1);+ if (last?.role !== "assistant" || typeof last.content === "string") return;+ const uses = last.content.filter((b) => b.type === "tool_use");+ if (uses.length) {+ messages.push({ role: "user", content: uses.map((u) => ({ type: "tool_result" as const, tool_use_id: (u as { id: string }).id, is_error: true, content: "Interrupted before this ran." })) });+ }+}++const FILE_KIND = (url: string) => (/\.(mp4|webm|mov|mkv)$/i.test(url) ? "video" : /\.(mp3|wav|ogg|m4a|flac|aac)$/i.test(url) ? "audio" : "image");++function userBlocks(text: string, attachments: string[]): UserBlock[] {+ const blocks: UserBlock[] = [];+ const lines = attachments.map((a, i) => `- ${FILE_KIND(a)} ${i + 1}: ${a}`);+ blocks.push({ type: "text", text: attachments.length ? `${text}\n\nAttached files (pass these URLs as inputs):\n${lines.join("\n")}` : text });+ // Local images are stored by URL and sent as base64 at request time (see hydrate).+ for (const a of attachments.filter((x) => FILE_KIND(x) === "image").slice(0, 4)) blocks.push({ type: "image", source: { type: "url", url: a } });+ return blocks;+}++/** Turn stored local image URLs into base64 (the API can't reach this machine). */+async function hydrate(messages: MessageParam[]): Promise<MessageParam[]> {+ const cache = new Map<string, UserBlock>();+ const one = async (b: UserBlock): Promise<UserBlock> => {+ if (b.type !== "image" || b.source.type !== "url" || !b.source.url.startsWith("/api/files/")) return b;+ const url = b.source.url;+ if (!cache.has(url)) {+ try {+ const { data, contentType } = await readRef(url);+ if (data.length > MAX_IMAGE_BYTES || !/^image\/(png|jpeg|webp|gif)$/.test(contentType)) throw new Error("too big");+ cache.set(url, { type: "image", source: { type: "base64", media_type: contentType as "image/png", data: data.toString("base64") } });+ } catch {+ cache.set(url, { type: "text", text: `[image ${url} can't be shown]` });+ }+ }+ return cache.get(url)!;+ };+ return Promise.all(+ messages.map(async (m) => {+ if (m.role !== "user" || typeof m.content === "string") return m;+ const content = await Promise.all(+ m.content.map(async (b) =>+ b.type === "tool_result" && Array.isArray(b.content) ? { ...b, content: (await Promise.all(b.content.map((c) => one(c as UserBlock)))) as typeof b.content } : one(b),+ ),+ );+ return { ...m, content };+ }),+ );+}++// ---------------------------------------------------------------------------+// System prompt++const STABLE_SYSTEM = `You are Fuobe Assist, the creative assistant inside Fuobe — an AI image, video and audio studio. You plan and run generations for the user with the tools you have.++How you work:+- Understand the brief. If something essential is missing (what the subject is, or which of their files to use) ask one short question; otherwise make sensible creative choices and go.+- Look up models with search_models before you generate, and pick the model that best fits the job, the user's engine preference and their budget. Prefer connected models. Mention the model you picked and why in one line.+- Write rich, specific prompts: subject, setting, light, lens and composition; for video, the motion and camera move in time order. Keep any text the user wants rendered exactly.+- Call generate (or create_storyboard) directly. The app shows the user a plan card with the cost and runs it when they approve — never ask "shall I go ahead?" in text.+- For multi-step work (an image, then animate it; a hero shot, then variations), wait for the first results with check_generations and pass its output URL into the next generate call. Use look=true when judging the results matters.+- Use the user's files by the URLs listed in their message. Earlier outputs are found with list_recent. Saved characters and products are Elements: check list_elements and write their @handle in prompts.+- Results show up in the chat by themselves, so don't repeat URLs back. After starting jobs, say briefly what's coming; after they finish, give a short take and suggest a next step.+- Be brief and friendly. Plain sentences, no headings. Prices are estimates in USD; open-source models run free on the user's own GPU.`;++function turnSystem(t: AssistThread): string {+ const mode = engineMode();+ const engine =+ mode === "open"+ ? "This install runs open-source models only (ComfyUI on the user's GPU)."+ : mode === "cloud"+ ? "This install runs paid cloud APIs only."+ : t.engine === "open"+ ? "The user prefers open-source models (ComfyUI, free on their GPU); use paid ones only when no open model can do the job, and say so."+ : "The user prefers paid cloud models (best quality); open-source models are available too.";+ const approval = t.autoApprove ? "Auto-run is on: generations start without an approval card, so keep plans within what the user asked for." : "Ask-first is on: each generate call shows an approval card.";+ return `Today is ${new Date().toISOString().slice(0, 10)}. ${engine} ${approval}`;+}++// ---------------------------------------------------------------------------+// Models++export const claude: ModelCall = async ({ system, messages, tools }) => {+ const client = new Anthropic({ apiKey: getSetting("anthropicKey") });+ return client.beta.messages.create({+ model: "claude-opus-5-5",+ max_tokens: 16000,+ thinking: { type: "adaptive" },+ output_config: { effort: "medium" },+ betas: ["server-side-fallback-2026-07-01"],+ fallbacks: "default",+ system: [+ { type: "text", text: system.stable, cache_control: { type: "ephemeral" } },+ { type: "text", text: system.turn },+ ],+ tools,+ messages: await hydrate(messages),+ });+};++/** A rule-based planner with the same shape as a model reply, for installs without an LLM. */+export const offline: ModelCall = async ({ messages, ctx }) => {+ const last = messages.at(-1);+ const blocks = last && typeof last.content !== "string" ? last.content : [];+ const reply = (content: Anthropic.Beta.BetaContentBlock[], stop: Anthropic.Beta.BetaStopReason): Anthropic.Beta.BetaMessage =>+ ({ id: `msg_offline_${nanoid(8)}`, type: "message", role: "assistant", model: "offline", content, stop_reason: stop, stop_sequence: null, stop_details: null, usage: null }) as unknown as Anthropic.Beta.BetaMessage;+ const text = (t: string) => ({ type: "text", text: t, citations: null }) as Anthropic.Beta.BetaTextBlock;++ const results = blocks.filter((b): b is ToolResult => b.type === "tool_result");+ const said = blocks.filter((b) => b.type === "text").map((b) => (b as { text: string }).text).join("\n");+ if (results.length && !said.trim()) {+ const body = results.map((r) => (typeof r.content === "string" ? r.content : "")).join(" ");+ if (results.some((r) => r.is_error)) return reply([text(/declined/i.test(body) ? "Okay, I won't run that. Tell me what to change." : `That didn't start: ${body.replace(/^.*"error":"([^"]+)".*$/, "$1")}`)], "end_turn");+ return reply([text("On it — the results will appear here as they finish. Want variations, a different look, or to animate one?")], "end_turn");+ }+ const plan = offlinePlan(said, ctx.engine);+ if (!plan) return reply([text("Tell me what to make — an image, a video, a voice-over or a storyboard — and attach any photos to use.")], "end_turn");+ return reply(+ [text(plan.say), { type: "tool_use", id: `toolu_offline_${nanoid(10)}`, name: plan.tool, input: plan.input, caller: { type: "direct" } } as unknown as Anthropic.Beta.BetaToolUseBlock],+ "tool_use",+ );+};++const NUMBER_WORDS: Record<string, number> = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8 };++/** Read a request like "3 vertical videos of a fox, animate this" into one tool call. */+export function offlinePlan(message: string, preferred: Engine): { tool: string; input: Record<string, unknown>; say: string } | null {+ const [body, attached = ""] = message.split(/\n\nAttached files[^\n]*\n/);+ const text = body.trim();+ if (!text) return null;+ const files = [...attached.matchAll(/^- (image|video|audio) \d+: (\S+)$/gm)].map((m) => ({ kind: m[1], url: m[2] }));+ const images = files.filter((f) => f.kind === "image").map((f) => f.url);+ const t = text.toLowerCase();+ const mode = engineMode();+ const engine: Engine = mode === "both" ? preferred : mode;+ const count = (() => {+ const m = /\b(\d|one|two|three|four|five|six|seven|eight)\s+(?:\w+\s+)?(images?|pictures?|photos?|versions?|takes?|variations?|options?|videos?|clips?|frames?|panels?|scenes?|shots?)\b/.exec(t);+ return m ? (NUMBER_WORDS[m[1]] ?? Number(m[1])) : undefined;+ })();+ const aspect = /\b(vertical|portrait|9:16|reels?|tiktok|stories|story format)\b/.test(t) ? "9:16" : /\b(square|1:1)\b/.test(t) ? "1:1" : /\b(wide|landscape|16:9|widescreen)\b/.test(t) ? "16:9" : undefined;++ if (/\b(storyboard|comic|panels|shot list)\b/.test(t) || (count && /\b(frames|scenes|panels)\b/.test(t))) {+ const frames = Math.max(1, Math.min(8, count ?? 4));+ return {+ tool: "create_storyboard",+ input: { story: text, frames, ...(images.length && { references: images.slice(0, 4) }), ...(aspect && { aspect_ratio: aspect }) },+ say: `I'll split that into ${frames} frames with the same characters and look, each made from the one before.`,+ };+ }+ const pick = (d: { cloud: string; open: string }) => (engine === "open" && d.open ? d.open : d.cloud);+ const isMusic = /\b(music|song|soundtrack|beat|jingle)\b/.test(t);+ const isSpeech = !isMusic && /\b(voice ?over|narrat\w*|read (this|it|out)|say|speak|text to speech|tts)\b/.test(t);+ const isVideo = !isMusic && !isSpeech && (files.some((f) => f.kind === "video") || /\b(videos?|clips?|animate|animation|motion|films?|footage|movies?|trailers?|commercials?)\b/.test(t));+ if (isMusic || isSpeech) {+ const quoted = /["“]([^"”]+)["”]/.exec(text)?.[1] ?? text.replace(/^.*?:\s*/, "");+ return {+ tool: "generate",+ input: { summary: isMusic ? "A music track" : "A voice-over", jobs: [{ model_id: pick(isMusic ? MUSIC_STUDIO.defaultModels : AUDIO_STUDIO.defaultModels), prompt: isMusic ? text : quoted }] },+ say: isMusic ? "Here's a track for that." : "I'll record that as a voice-over.",+ };+ }+ const studio = isVideo ? VIDEO_STUDIO : images.length ? EDIT_STUDIO : IMAGE_STUDIO;+ const n = Math.max(1, Math.min(4, count ?? (isVideo ? 1 : 2)));+ const job = { model_id: pick(studio.defaultModels), prompt: text, ...(images.length && { images: images.slice(0, isVideo ? 1 : 4) }), ...(aspect && { aspect_ratio: aspect }), ...(n > 1 && { outputs: n }) };+ const what = isVideo ? (images.length ? "animate your image" : "make the video") : images.length ? "edit your image" : `make ${n} take${n === 1 ? "" : "s"}`;+ return { tool: "generate", input: { summary: `${isVideo ? "Video" : images.length ? "Edit" : "Image"}: ${text.slice(0, 80)}`, jobs: [job] }, say: `I'll ${what} with the default ${isVideo ? "video" : "image"} model.` };+}++// ---------------------------------------------------------------------------+// The loop++async function runTool(name: string, input: unknown, ctx: ToolContext): Promise<{ result: Omit<ToolResult, "tool_use_id">; items: AssistItem[] }> {+ const tool = getTool(name);+ if (!tool) return { result: { type: "tool_result", is_error: true, content: `Unknown tool ${name}` }, items: [] };+ const parsed = tool.schema.safeParse(input);+ if (!parsed.success) return { result: { type: "tool_result", is_error: true, content: `Invalid input: ${parsed.error.issues.map((i: { path: PropertyKey[]; message: string }) => `${i.path.map(String).join(".")} ${i.message}`).join("; ")}` }, items: [] };+ try {+ const out = await tool.run(parsed.data, ctx);+ return { result: { type: "tool_result", content: out.content, ...(out.isError && { is_error: true }) }, items: out.items ?? [] };+ } catch (e) {+ return { result: { type: "tool_result", is_error: true, content: (e as Error).message }, items: [] };+ }+}++function ordered(results: ToolResult[], order: string[]): ToolResult[] {+ return [...results].sort((a, b) => order.indexOf(a.tool_use_id) - order.indexOf(b.tool_use_id));+}++async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {+ const ctx: ToolContext = { engine: s.thread.engine };+ const res = await model({ system: { stable: STABLE_SYSTEM, turn: turnSystem(s.thread) }, messages: s.messages, tools: apiTools(), ctx });++ if (res.stop_reason === "refusal") {+ // Nothing is appended: the user's turn stays last and their next message joins it.+ push(s, { role: "notice", tone: "error", text: res.stop_details?.explanation || "Claude declined this request. Try rephrasing it." });+ return "stop";+ }+ if (res.stop_reason === "model_context_window_exceeded") {+ push(s, { role: "notice", tone: "error", text: "This chat is too long to continue. Start a new one." });+ return "stop";+ }+ s.messages.push({ role: "assistant", content: res.content });+ const text = res.content+ .filter((b): b is Anthropic.Beta.BetaTextBlock => b.type === "text")+ .map((b) => b.text)+ .join("\n\n")+ .trim();+ if (text) push(s, { role: "assistant", text });+ if (res.stop_reason === "pause_turn") return "continue";++ const uses = res.content.filter((b): b is Anthropic.Beta.BetaToolUseBlock => b.type === "tool_use");+ if (res.stop_reason === "max_tokens") {+ if (!uses.length) {+ push(s, { role: "notice", tone: "info", text: "The reply was cut short." });+ return "stop";+ }+ // A cut-off tool call may be incomplete: don't run it, ask for a shorter one.+ s.messages.push({ role: "user", content: uses.map((u) => ({ type: "tool_result" as const, tool_use_id: u.id, is_error: true, content: "Your reply hit the output limit before this call was complete. Make the call again, shorter." })) });+ return "continue";+ }+ if (!uses.length) return "stop";++ const results: ToolResult[] = [];+ const gated: Pending["gated"] = [];+ for (const u of uses) {+ if (getTool(u.name)?.gated && !s.thread.autoApprove) {+ gated.push({ id: u.id, name: u.name, input: u.input });+ continue;+ }+ const { result, items } = await runTool(u.name, u.input, ctx);+ results.push({ ...result, tool_use_id: u.id });+ for (const it of items) push(s, it);+ }+ const order = uses.map((u) => u.id);+ if (gated.length) {+ const plans = gated.map((g) => planFor(g.name, g.input, ctx));+ const jobs = plans.flatMap((p) => p.jobs);+ const summaries = gated.map((g) => (g.input as { summary?: string }).summary).filter(Boolean);+ const total = plans.some((p) => p.total === null) ? null : plans.reduce((n, p) => n + (p.total ?? 0), 0);+ const item = push(s, { role: "approval", summary: summaries.join(" · ") || (gated[0].name === "create_storyboard" ? "Storyboard" : "Generate"), jobs, totalUsd: total, status: "pending" });+ s.pending = { approvalItemId: item.id, results, gated, order };+ s.thread.status = "waiting";+ return "stop";+ }+ s.messages.push({ role: "user", content: ordered(results, order) });+ return "continue";+}++const MODELS: Record<AssistThread["agent"], ModelCall> = { claude, offline };++/**+ * Run the agent until it ends its turn or waits for approval. Call it right after addMessage or+ * answerApproval: it claims the thread synchronously, so the "running" status they saved stays valid.+ */+export async function run(id: string, model?: ModelCall): Promise<void> {+ if (runs.has(id)) return;+ runs.add(id);+ try {+ const s = load(id);+ if (!s) return;+ const call = model ?? MODELS[s.thread.agent];+ s.thread.status = "running";+ save(s);+ for (let i = 0; i < MAX_STEPS; i++) {+ let next: "continue" | "stop";+ try {+ next = await step(s, call);+ } catch (e) {+ push(s, { role: "notice", tone: "error", text: errorText(e) });+ next = "stop";+ }+ if (next === "stop") break;+ save(s);+ if (i === MAX_STEPS - 1) push(s, { role: "notice", tone: "info", text: "Paused after many steps. Send a message to keep going." });+ }+ if (s.thread.status === "running") s.thread.status = "idle";+ save(s);+ } finally {+ runs.delete(id);+ }+}++function errorText(e: unknown): string {+ if (e instanceof Anthropic.AuthenticationError) return "Your Anthropic API key was rejected. Check it in Settings → API keys.";+ if (e instanceof Anthropic.RateLimitError) return "Claude is rate-limited right now. Try again in a minute.";+ if (e instanceof Anthropic.APIError) return `Claude returned an error (${e.status ?? "network"}): ${e.message}`;+ return (e as Error).message || "Something went wrong";+}++export class AssistBusyError extends Error {}++/** Add the user's message; a pending plan they didn't approve is declined with their message as feedback. */+export function addMessage(id: string, text: string, attachments: string[] = []): AssistThread {+ const s = load(id);+ if (!s) throw new Error("Not found");+ if (s.thread.status === "running" || runs.has(id)) throw new AssistBusyError("Still working on the last message");+ if (!s.thread.items.some((i) => i.role === "user")) s.thread.title = threadTitle(text);+ // Tool results first: they answer the assistant's last turn.+ const results = s.pending ? decline(s, "The user replied with new instructions instead of approving; follow them.") : [];+ if (!results.length) closeDanglingToolUses(s.messages);+ appendUser(s.messages, [...results, ...userBlocks(text, attachments)]);+ push(s, { role: "user", text, ...(attachments.length && { attachments }) });+ s.thread.status = "running";+ save(s);+ return s.thread;+}++function settle(s: State, approved: boolean): Pending {+ const p = s.pending!;+ const item = s.thread.items.find((i) => i.id === p.approvalItemId);+ if (item?.role === "approval") item.status = approved ? "approved" : "declined";+ s.pending = null;+ return p;+}++function decline(s: State, why = "The user declined this plan. Ask what they'd like to change."): ToolResult[] {+ const p = settle(s, false);+ return ordered([...p.results, ...p.gated.map((g) => ({ type: "tool_result" as const, tool_use_id: g.id, is_error: true, content: why }))], p.order);+}++async function approve(s: State): Promise<ToolResult[]> {+ const p = settle(s, true);+ const results = [...p.results];+ for (const g of p.gated) {+ const { result, items } = await runTool(g.name, g.input, { engine: s.thread.engine });+ results.push({ ...result, tool_use_id: g.id });+ for (const it of items) push(s, it);+ }+ return ordered(results, p.order);+}++/** The user's answer on the approval card. */+export async function answerApproval(id: string, ok: boolean): Promise<AssistThread> {+ const s = load(id);+ if (!s) throw new Error("Not found");+ if (!s.pending || s.thread.status !== "waiting") throw new AssistBusyError("Nothing is waiting for approval");+ const results = ok ? await approve(s) : decline(s);+ s.messages.push({ role: "user", content: results });+ s.thread.status = "running";+ save(s);+ return s.thread;+}diff --git a/src/server/assist/schemas.ts b/src/server/assist/schemas.tsnew file mode 100644index 00000000..aebc34a9--- /dev/null+++ b/src/server/assist/schemas.ts@@ -0,0 +1,6 @@+import { z } from "zod";++export const AssistMessage = z.object({+ text: z.string().trim().min(1).max(8000),+ attachments: z.array(z.string().startsWith("/api/files/")).max(8).optional(),+});diff --git a/src/server/assist/tools.ts b/src/server/assist/tools.tsnew file mode 100644index 00000000..03e12d22--- /dev/null+++ b/src/server/assist/tools.ts@@ -0,0 +1,388 @@+import "server-only";+import type Anthropic from "@anthropic-ai/sdk";+import { z } from "zod";+import { modelsFor } from "@/lib/catalog";+import { OPERATION_LABELS, type GenerationRequest, type MediaKind, type ModelDef, type Operation } from "@/lib/catalog/types";+import { type AssistItem, type PlannedJob, totalCost } from "@/lib/assist";+import { STORYBOARD_MODELS } from "@/lib/catalog/storyboard";+import { listElements } from "../elements";+import { createGenerations, getGeneration, listGenerations, previewGeneration } from "../generations";+import { provider } from "../providers";+import { engineMode } from "../settings";+import { readRef } from "../storage";+import { createStoryboard } from "../storyboard";++type ResultContent = Anthropic.Beta.BetaToolResultBlockParam["content"];++export interface ToolContext {+ engine: "cloud" | "open";+}++export interface ToolOutcome {+ content: ResultContent;+ isError?: boolean;+ /** Cards to show in the chat (generations started, a short "looked up models" line…). */+ items?: AssistItem[];+}++interface ToolDef<S extends z.ZodType> {+ name: string;+ description: string;+ schema: S;+ /** Spends money or GPU time: waits for the user's approval unless auto-approve is on. */+ gated?: boolean;+ strict?: boolean;+ run: (input: z.infer<S>, ctx: ToolContext) => Promise<ToolOutcome>;+ /** For gated tools: what the run would do, priced. */+ plan?: (input: z.infer<S>, ctx: ToolContext) => PlannedJob[];+}++const defineTool = <S extends z.ZodType>(def: ToolDef<S>) => def;++const ref = z.string().describe("A file URL from the chat: an attachment or an earlier output (/api/files/…).");++// ---------------------------------------------------------------------------+// search_models++const KINDS = ["image", "video", "audio"] as const;++function summarize(m: ModelDef) {+ const o = m.options;+ const configured = m.routes.some((r) => provider(r.provider).isConfigured());+ return {+ id: m.id,+ name: m.name,+ vendor: m.vendor,+ engine: m.engine === "open" ? "open source (ComfyUI)" : "paid cloud API",+ about: m.tagline,+ does: [...new Set(m.routes.map((r) => r.op))].map((op) => `${op} (${OPERATION_LABELS[op]})`),+ price: m.engine === "open" ? "free (your GPU)" : m.pricing ? `$${m.pricing.usd} per ${m.pricing.unit}${m.pricing.note ? ` — ${m.pricing.note}` : ""}` : "unknown",+ connected: configured,+ ...(o.aspectRatios && { aspectRatios: o.aspectRatios }),+ ...(o.resolutions && { resolutions: o.resolutions }),+ ...(o.durations && { durations: o.durations }),+ ...(o.maxImages && { maxReferenceImages: o.maxImages }),+ ...(o.maxOutputs && { maxOutputsPerRun: o.maxOutputs }),+ ...(o.audio && { nativeAudio: o.audio === "always" ? "always on" : "optional" }),+ ...(o.endFrame && { endFrame: true }),+ ...(o.multiShot && { multiShot: `up to ${o.multiShot.maxShots} shots` }),+ ...(o.voices?.length && { voices: o.voices.slice(0, 12).map((v) => v.id) }),+ ...(o.voiceClone && { voiceClone: true }),+ ...(o.presets && { needs: o.presets.required ? `a ${o.presets.label} (pick in the studio)` : undefined }),+ };+}++const searchModels = defineTool({+ name: "search_models",+ description:+ "Look up the models this studio can run for a kind of output. Call it before generate whenever you haven't already looked up models for this kind of job in this chat, and whenever the user names a model, asks what's best or cheapest, or wants a capability (audio, end frame, multi-shot, a voice). Returns ids, what each does, price, options and whether a provider is connected.",+ schema: z.object({+ kind: z.enum(KINDS).describe("Output kind."),+ task: z.string().optional().describe("Operation id to filter by, e.g. t2i, edit, t2v, i2v, flf2v, ref2v, extend, lipsync, avatar, tts, upscale-image."),+ query: z.string().optional().describe("Words to match in the model name, vendor or description, e.g. 'kling', 'cheap', 'photoreal'."),+ }),+ async run({ kind, task, query }, ctx) {+ const mode = engineMode();+ let list = modelsFor({ kind: kind as MediaKind, ops: task ? [task as Operation] : undefined, engine: mode === "both" ? "all" : mode });+ if (query) {+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);+ const scored = list.map((m) => {+ const hay = `${m.name} ${m.vendor} ${m.family} ${m.tagline} ${m.id}`.toLowerCase();+ return { m, s: words.filter((w) => hay.includes(w)).length };+ });+ if (scored.some((x) => x.s)) list = scored.filter((x) => x.s).sort((a, b) => b.s - a.s).map((x) => x.m);+ }+ // The engine the user picked first, then the rest.+ list = [...list].sort((a, b) => Number(b.engine === ctx.engine) - Number(a.engine === ctx.engine));+ const shown = list.slice(0, 20);+ return {+ content: JSON.stringify({ engineMode: mode, preferredEngine: ctx.engine, total: list.length, models: shown.map(summarize) }),+ items: [{ id: "", role: "tool", text: `Looked up ${list.length} ${kind} model${list.length === 1 ? "" : "s"}${task ? ` for ${OPERATION_LABELS[task as Operation] ?? task}` : ""}` }],+ };+ },+});++// ---------------------------------------------------------------------------+// list_elements++const listElementsTool = defineTool({+ name: "list_elements",+ description:+ "List the user's saved Elements (characters, locations, props, styles, voices). Call it when the user mentions a character, person, place or product by name, or uses an @handle. Writing @handle in a generate prompt makes the model use that element's reference photos or trained identity.",+ schema: z.object({}),+ async run() {+ const els = listElements();+ return {+ content: JSON.stringify(+ els.map((e) => ({+ handle: `@${e.handle}`,+ name: e.name,+ kind: e.kind,+ description: e.description,+ referencePhotos: e.references.length,+ trainedFor: e.loras.map((l) => l.modelId),+ })),+ ),+ items: [{ id: "", role: "tool", text: `Checked your elements (${els.length})` }],+ };+ },+});++// ---------------------------------------------------------------------------+// list_recent / check_generations++function genSummary(id: string) {+ const g = getGeneration(id);+ if (!g) return { id, status: "unknown id" };+ return {+ id: g.id,+ status: g.status,+ model: g.modelId,+ op: g.op,+ kind: g.kind,+ prompt: g.request.prompt?.slice(0, 300),+ ...(g.progress !== null && g.status === "running" && { progress: g.progress }),+ ...(g.error && { error: g.error }),+ ...(g.provider === "mock" && { demo: true }),+ outputs: g.outputs.map((o) => ({ url: o.url, kind: o.kind, ...(o.draftId && { draftId: o.draftId }) })),+ };+}++const listRecent = defineTool({+ name: "list_recent",+ description:+ "List the user's most recent generations with their output URLs. Call it when the user refers to something they made earlier ('animate my last image', 'the one from before') so you can pass its URL as an input.",+ schema: z.object({+ limit: z.number().int().optional().describe("How many (default 8, up to 30)."),+ kind: z.enum(KINDS).optional(),+ }),+ async run({ limit, kind }) {+ const items = listGenerations({ kind, limit: Math.max(1, Math.min(30, limit ?? 8)) });+ return { content: JSON.stringify(items.map((g) => genSummary(g.id))) };+ },+});++const TERMINAL = new Set(["succeeded", "failed", "canceled"]);+const LOOK_LIMIT = 4;+const LOOK_BYTES = 3_500_000;++const checkGenerations = defineTool({+ name: "check_generations",+ description:+ "Get the status and output URLs of generations you started. Call it when you need an output to continue (animate an image you just made, upscale it, use it as a reference) — set wait_seconds to wait for them to finish. Set look to true to see finished images yourself, e.g. to pick the best take or check the result matches the brief.",+ schema: z.object({+ ids: z.array(z.string()).describe("Generation ids returned by generate or create_storyboard."),+ wait_seconds: z.number().int().optional().describe("Wait up to this long (max 120) for all of them to finish. 0 = just report."),+ look: z.boolean().optional().describe("Attach finished image outputs so you can see them (up to 4)."),+ }),+ async run({ ids, wait_seconds, look }) {+ const until = Date.now() + Math.max(0, Math.min(120, wait_seconds ?? 0)) * 1000;+ let summaries = ids.slice(0, 20).map(genSummary);+ while (Date.now() < until && summaries.some((s) => !TERMINAL.has(s.status))) {+ await new Promise((r) => setTimeout(r, 1500));+ summaries = ids.slice(0, 20).map(genSummary);+ }+ const blocks: Exclude<ResultContent, string | undefined> = [{ type: "text", text: JSON.stringify(summaries) }];+ if (look) {+ const images = summaries.flatMap((s) => ("outputs" in s ? (s.outputs ?? []).filter((o) => o.kind === "image").map((o) => ({ id: s.id, url: o.url })) : []));+ for (const img of images.slice(0, LOOK_LIMIT)) {+ try {+ const { data, contentType } = await readRef(img.url);+ if (data.length > LOOK_BYTES || !/^image\/(png|jpeg|webp|gif)$/.test(contentType)) continue;+ blocks.push({ type: "text", text: `Output of ${img.id}: ${img.url}` });+ blocks.push({ type: "image", source: { type: "base64", media_type: contentType as "image/png", data: data.toString("base64") } });+ } catch {+ // Unreadable output: the URL is still in the summary.+ }+ }+ }+ return {+ content: blocks,+ items: [{ id: "", role: "tool", text: `Checked ${ids.length} generation${ids.length === 1 ? "" : "s"}${look ? " and looked at the results" : ""}` }],+ };+ },+});++// ---------------------------------------------------------------------------+// generate++const Job = z.object({+ model_id: z.string().describe("Model id from search_models."),+ prompt: z.string().describe("The full prompt. Put @handles here to use saved elements."),+ op: z.string().optional().describe("Operation id (t2i, edit, t2v, i2v, flf2v, ref2v, extend, tts…). Usually inferred from the inputs; set it when ambiguous."),+ images: z.array(ref).optional().describe("Input images: the image to edit, the start frame, or references, in order."),+ end_image: ref.optional().describe("End frame (first-and-last-frame video)."),+ video: ref.optional().describe("Input video (extend, edit, lipsync, upscale…)."),+ audio: ref.optional().describe("Input audio (lipsync, avatar)."),+ aspect_ratio: z.string().optional().describe("e.g. 16:9, 9:16, 1:1 — one the model lists."),+ resolution: z.string().optional().describe("e.g. 1080p, 2K — one the model lists."),+ duration: z.number().optional().describe("Seconds, for video and music — one the model lists."),+ outputs: z.number().int().optional().describe("How many takes (1–4)."),+ generate_audio: z.boolean().optional().describe("Native audio on/off, for video models that offer it."),+ voice: z.string().optional().describe("Voice id for text to speech."),+ negative_prompt: z.string().optional(),+});+type JobInput = z.infer<typeof Job>;++function toRequest(j: JobInput): GenerationRequest {+ const inputs = {+ ...(j.images?.length && { images: j.images }),+ ...(j.end_image && { endImage: j.end_image }),+ ...(j.video && { video: j.video }),+ ...(j.audio && { audio: j.audio }),+ };+ return {+ feature: "assist",+ modelId: j.model_id,+ op: j.op as Operation | undefined,+ prompt: j.prompt,+ negativePrompt: j.negative_prompt,+ inputs: Object.keys(inputs).length ? inputs : undefined,+ params: {+ aspectRatio: j.aspect_ratio,+ resolution: j.resolution,+ duration: j.duration,+ numOutputs: j.outputs ? Math.max(1, Math.min(4, j.outputs)) : undefined,+ generateAudio: j.generate_audio,+ voice: j.voice,+ },+ };+}++function planJob(j: JobInput): PlannedJob {+ const req = toRequest(j);+ try {+ const p = previewGeneration(req);+ return { tool: "generate", modelId: p.model.id, modelName: p.model.name, kind: p.model.kind, op: p.op, prompt: j.prompt, count: p.outputs, costUsd: p.costUsd, demo: p.demo };+ } catch (e) {+ return { tool: "generate", modelId: j.model_id, modelName: j.model_id, kind: "image", op: (j.op as Operation) ?? "t2i", prompt: j.prompt, count: 0, costUsd: 0, demo: false, error: (e as Error).message };+ }+}++const GenerateInput = z.object({+ summary: z.string().describe("One short sentence describing the plan, shown on the approval card."),+ jobs: z.array(Job).describe("1–6 jobs. Jobs in one call run in parallel; to use one job's output in another, call generate again after check_generations."),+});++const generate = defineTool({+ name: "generate",+ description:+ "Start image, video or audio generations. The app shows the user the plan with its cost and runs it once they approve, so call this directly instead of asking for confirmation in text. Returns generation ids; their results appear in the chat by themselves.",+ schema: GenerateInput,+ gated: true,+ strict: true,+ plan: ({ jobs }) => jobs.slice(0, 6).map(planJob),+ async run({ jobs }) {+ const ids: string[] = [];+ const results: unknown[] = [];+ for (const j of jobs.slice(0, 6)) {+ try {+ const gens = createGenerations(toRequest(j));+ ids.push(...gens.map((g) => g.id));+ results.push({ model: j.model_id, started: gens.map((g) => g.id), demo: gens.some((g) => g.provider === "mock") || undefined, costUsd: gens.reduce((s, g) => s + (g.costUsd ?? 0), 0) || undefined });+ } catch (e) {+ results.push({ model: j.model_id, error: (e as Error).message });+ }+ }+ const failed = results.length && ids.length === 0;+ return {+ content: JSON.stringify(results),+ isError: !!failed,+ items: ids.length ? [{ id: "", role: "generations", ids }] : undefined,+ };+ },+});++// ---------------------------------------------------------------------------+// create_storyboard++const StoryboardInput = z.object({+ story: z.string().optional().describe("The story to split into frames (or give scenes)."),+ scenes: z.array(z.string()).optional().describe("One description per frame, in order (up to 8)."),+ frames: z.number().int().optional().describe("Number of frames when splitting a story (1–8, default 4)."),+ references: z.array(ref).optional().describe("Up to 4 character/style reference images used for every frame."),+ style: z.string().optional().describe("A look applied to every frame, e.g. 'moody 35mm film'."),+ aspect_ratio: z.string().optional(),+});++const storyboard = defineTool({+ name: "create_storyboard",+ description:+ "Make a storyboard: up to 8 consecutive frames of one film with the same characters and look, each made from the previous one. Use it for comics, storyboards, shot lists and 'tell this story in N images'. Gated by the same approval card as generate.",+ schema: StoryboardInput,+ gated: true,+ strict: true,+ plan: (s, ctx) => {+ const engine = engineMode() === "both" ? ctx.engine : (engineMode() as "cloud" | "open");+ const m = STORYBOARD_MODELS[engine];+ const n = Math.max(1, Math.min(8, s.scenes?.length || s.frames || 4));+ let one: ReturnType<typeof previewGeneration> | null = null;+ let error: string | undefined;+ try {+ one = previewGeneration({ feature: "storyboard", modelId: m.first, prompt: s.story || s.scenes?.[0] || "frame", params: { aspectRatio: s.aspect_ratio } });+ } catch (e) {+ error = (e as Error).message;+ }+ if (!s.story?.trim() && !s.scenes?.some((x) => x.trim())) error = "Give a story or scenes";+ return [+ {+ tool: "create_storyboard",+ modelId: m.first,+ modelName: one?.model.name ?? m.first,+ kind: "image",+ op: "storyboard",+ prompt: s.story || (s.scenes ?? []).join(" / "),+ count: n,+ costUsd: one?.costUsd === null || !one ? null : one.costUsd * n,+ demo: one?.demo ?? false,+ error,+ },+ ];+ },+ async run(s, ctx) {+ const engine = engineMode() === "both" ? ctx.engine : (engineMode() as "cloud" | "open");+ const r = await createStoryboard({ engine, story: s.story, scenes: s.scenes, frames: s.frames, references: s.references, style: s.style, aspectRatio: s.aspect_ratio });+ return {+ content: JSON.stringify({ frames: r.items.map((g, i) => ({ id: g.id, scene: r.scenes[i] })), note: "Frames render one after another; each waits for the previous." }),+ items: [{ id: "", role: "generations", ids: r.items.map((g) => g.id), storyboard: true }],+ };+ },+});++// ---------------------------------------------------------------------------++// eslint-disable-next-line @typescript-eslint/no-explicit-any+export const TOOLS: ToolDef<any>[] = [searchModels, listElementsTool, listRecent, checkGenerations, generate, storyboard];+export const getTool = (name: string) => TOOLS.find((t) => t.name === name);++/** JSON Schema for the API: every object closed, constraints the API doesn't take removed (zod still checks them). */+function apiSchema(schema: z.ZodType): Anthropic.Beta.BetaTool.InputSchema {+ const json = z.toJSONSchema(schema) as Record<string, unknown>;+ const walk = (node: unknown): unknown => {+ if (Array.isArray(node)) return node.map(walk);+ if (!node || typeof node !== "object") return node;+ const out: Record<string, unknown> = {};+ for (const [k, v] of Object.entries(node)) {+ if (["$schema", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "minLength", "maxLength", "maxItems", "minItems", "multipleOf"].includes(k)) continue;+ out[k] = k === "properties" ? Object.fromEntries(Object.entries(v as object).map(([p, s]) => [p, walk(s)])) : walk(v);+ }+ if (out.type === "object") out.additionalProperties = false;+ return out;+ };+ return walk(json) as Anthropic.Beta.BetaTool.InputSchema;+}++export function apiTools(): Anthropic.Beta.BetaTool[] {+ return TOOLS.map((t) => ({+ name: t.name,+ description: t.description,+ input_schema: apiSchema(t.schema),+ ...(t.strict && { strict: true }),+ }));+}++export function planFor(name: string, input: unknown, ctx: ToolContext): { jobs: PlannedJob[]; total: number | null } {+ const t = getTool(name);+ const jobs = t?.plan?.(input, ctx) ?? [];+ return { jobs, total: totalCost(jobs) };+}diff --git a/src/server/db.ts b/src/server/db.tsindex bdacf3e8..994f90a9 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -86,6 +86,21 @@ const MIGRATIONS: string[] = [CREATE INDEX IF NOT EXISTS trainings_element ON trainings(element_id);`,// Chained jobs (storyboard frames wait for the previous frame).`ALTER TABLE generations ADD COLUMN depends_on TEXT;`,+ // Assist chats: the model's message history, the transcript shown in the UI and a pending approval.+ `CREATE TABLE IF NOT EXISTS assist_threads (+ id TEXT PRIMARY KEY,+ title TEXT NOT NULL,+ status TEXT NOT NULL,+ agent TEXT NOT NULL,+ engine TEXT NOT NULL,+ auto_approve INTEGER NOT NULL DEFAULT 0,+ messages_json TEXT NOT NULL DEFAULT '[]',+ items_json TEXT NOT NULL DEFAULT '[]',+ pending_json TEXT,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS assist_threads_updated ON assist_threads(updated_at DESC);`,];declare global {diff --git a/src/server/generations.ts b/src/server/generations.tsindex 2dba54db..6703151c 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -185,6 +185,12 @@ function prepare(original: GenerationRequest) {return { req, plan, route, demo, providerId, cost: demo ? 0 : estimateCost(plan.model, plan.params, 1) };}+/** What a request would run as — model, operation, job count and cost — without starting it. */+export function previewGeneration(req: GenerationRequest) {+ const { plan, demo, providerId, cost } = prepare(req);+ return { model: plan.model, op: plan.op, jobs: plan.jobs, outputs: plan.jobs * plan.perJobOutputs, demo, providerId, costUsd: cost === null ? null : cost * plan.jobs };+}+export interface CreateOptions {/** Group several requests (storyboard frames) into one batch. */batchId?: string;diff --git a/tests/assist.test.ts b/tests/assist.test.tsnew file mode 100644index 00000000..aadbe6fa--- /dev/null+++ b/tests/assist.test.ts@@ -0,0 +1,237 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import type Anthropic from "@anthropic-ai/sdk";++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";++const { setSetting } = await import("@/server/settings");+const agent = await import("@/server/assist/agent");+const { apiTools } = await import("@/server/assist/tools");+const { db } = await import("@/server/db");++type Msg = Anthropic.Beta.BetaMessage;+type Block = Anthropic.Beta.BetaContentBlock;++beforeAll(() => setSetting("demoMode", "auto"));+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++const text = (t: string) => ({ type: "text", text: t, citations: null }) as Block;+const use = (id: string, name: string, input: unknown) => ({ type: "tool_use", id, name, input }) as unknown as Block;+const reply = (content: Block[], stop: Anthropic.Beta.BetaStopReason, extra: Partial<Msg> = {}) => ({ content, stop_reason: stop, stop_details: null, ...extra }) as Msg;++/** A model that answers from a script and records each request. */+function scripted(...turns: Msg[]) {+ const seen: Anthropic.Beta.BetaMessageParam[][] = [];+ const call: import("@/server/assist/agent").ModelCall = async ({ messages }) => {+ seen.push(structuredClone(messages));+ const next = turns.shift();+ if (!next) throw new Error("script ran out");+ return next;+ };+ return { call, seen };+}++const history = (id: string) => JSON.parse((db().prepare("SELECT messages_json FROM assist_threads WHERE id = ?").get(id) as { messages_json: string }).messages_json) as Anthropic.Beta.BetaMessageParam[];++const job = { model_id: "nano-banana-pro", prompt: "a red fox in snow, golden hour" };++describe("assist tools", () => {+ it("sends closed, constraint-free schemas and strict gated tools", () => {+ const tools = apiTools();+ const json = JSON.stringify(tools);+ expect(json).not.toMatch(/"(maximum|minimum|maxItems|minLength|\$schema)"/);+ const objects: Record<string, unknown>[] = [];+ const walk = (n: unknown) => {+ if (Array.isArray(n)) return n.forEach(walk);+ if (n && typeof n === "object") {+ if ((n as { type?: string }).type === "object") objects.push(n as Record<string, unknown>);+ Object.values(n).forEach(walk);+ }+ };+ tools.forEach((t) => walk(t.input_schema));+ expect(objects.every((o) => o.additionalProperties === false)).toBe(true);+ expect(tools.find((t) => t.name === "generate")?.strict).toBe(true);+ expect(tools.find((t) => t.name === "search_models")?.strict).toBeUndefined();+ });+});++describe("assist loop", () => {+ it("pauses on a paid plan, then answers every call of that turn in one message", async () => {+ const t = agent.createThread({ engine: "cloud" });+ agent.addMessage(t.id, "Make a fox photo");+ const m = scripted(+ reply([text("Let me check models."), use("toolu_a", "search_models", { kind: "image" }), use("toolu_b", "generate", { summary: "A fox photo", jobs: [job] })], "tool_use"),+ reply([text("Your fox is on the way.")], "end_turn"),+ );+ await agent.run(t.id, m.call);+ let v = agent.getThread(t.id)!;+ expect(v.thread.status).toBe("waiting");+ const card = v.thread.items.find((i) => i.role === "approval");+ expect(card).toMatchObject({ status: "pending", summary: "A fox photo", jobs: [{ modelId: "nano-banana-pro", count: 1, demo: true }] });+ expect(v.thread.items.some((i) => i.role === "tool")).toBe(true);+ expect(history(t.id).map((x) => x.role)).toEqual(["user", "assistant"]);++ await agent.answerApproval(t.id, true);+ await agent.run(t.id, m.call);+ v = agent.getThread(t.id)!;+ expect(v.thread.status).toBe("idle");+ expect(v.thread.items.find((i) => i.role === "approval")).toMatchObject({ status: "approved" });+ expect(v.generations).toHaveLength(1);+ // The resumed request carried both results, in the order of the calls.+ const results = m.seen[1].at(-1)!.content as Anthropic.Beta.BetaToolResultBlockParam[];+ expect(results.map((r) => r.tool_use_id)).toEqual(["toolu_a", "toolu_b"]);+ expect(results[1].is_error).toBeUndefined();+ expect(v.thread.items.at(-1)).toMatchObject({ role: "assistant", text: "Your fox is on the way." });+ expect(v.thread.title).toBe("Make a fox photo");+ });++ it("treats a new message as declining the plan, with the results before the text", async () => {+ const t = agent.createThread({ engine: "cloud" });+ agent.addMessage(t.id, "Fox video");+ await agent.run(t.id, scripted(reply([use("toolu_c", "generate", { summary: "Fox", jobs: [job] })], "tool_use")).call);+ agent.addMessage(t.id, "Actually make it a wolf");+ const last = history(t.id).at(-1)!;+ const content = last.content as { type: string; is_error?: boolean; text?: string }[];+ expect(content[0]).toMatchObject({ type: "tool_result", is_error: true });+ expect(content[1]).toMatchObject({ type: "text", text: "Actually make it a wolf" });+ expect(agent.getThread(t.id)!.thread.items.find((i) => i.role === "approval")).toMatchObject({ status: "declined" });+ await agent.run(t.id, scripted(reply([text("Wolf it is.")], "end_turn")).call);+ });++ it("runs gated tools straight away when auto-run is on", async () => {+ const t = agent.createThread({ engine: "cloud", autoApprove: true });+ agent.addMessage(t.id, "Two foxes");+ await agent.run(t.id, scripted(reply([use("toolu_d", "generate", { summary: "Foxes", jobs: [{ ...job, outputs: 2 }] })], "tool_use"), reply([text("Done.")], "end_turn")).call);+ const v = agent.getThread(t.id)!;+ expect(v.thread.items.some((i) => i.role === "approval")).toBe(false);+ expect(v.thread.items.find((i) => i.role === "generations")).toBeTruthy();+ expect(v.thread.status).toBe("idle");+ });++ it("doesn't run a tool call cut off by max_tokens", async () => {+ const t = agent.createThread({ engine: "cloud", autoApprove: true });+ agent.addMessage(t.id, "Fox");+ const m = scripted(reply([use("toolu_e", "generate", { summary: "Fo" })], "max_tokens"), reply([text("Retried.")], "end_turn"));+ await agent.run(t.id, m.call);+ const res = (m.seen[1].at(-1)!.content as Anthropic.Beta.BetaToolResultBlockParam[])[0];+ expect(res).toMatchObject({ tool_use_id: "toolu_e", is_error: true });+ expect(agent.getThread(t.id)!.generations).toHaveLength(0);+ });++ it("returns invalid tool input to the model as an error", async () => {+ const t = agent.createThread({ engine: "cloud", autoApprove: true });+ agent.addMessage(t.id, "Fox");+ const m = scripted(reply([use("toolu_f", "search_models", { kind: "smell" })], "tool_use"), reply([text("Oops.")], "end_turn"));+ await agent.run(t.id, m.call);+ expect((m.seen[1].at(-1)!.content as Anthropic.Beta.BetaToolResultBlockParam[])[0]).toMatchObject({ is_error: true });+ });++ it("keeps the history valid after a refusal", async () => {+ const t = agent.createThread({ engine: "cloud" });+ agent.addMessage(t.id, "something");+ await agent.run(t.id, scripted(reply([], "refusal", { stop_details: { type: "refusal", category: null, explanation: "Not this one." } as Msg["stop_details"] })).call);+ const v = agent.getThread(t.id)!;+ expect(v.thread.items.at(-1)).toMatchObject({ role: "notice", text: "Not this one." });+ agent.addMessage(t.id, "something else");+ const h = history(t.id);+ expect(h).toHaveLength(1);+ expect((h[0].content as { text: string }[]).map((b) => b.text)).toEqual(["something", "something else"]);+ await agent.run(t.id, scripted(reply([text("Sure.")], "end_turn")).call);+ });++ it("refuses a message while a reply is still running", async () => {+ const t = agent.createThread({ engine: "cloud" });+ agent.addMessage(t.id, "one");+ let release!: () => void;+ const slow: import("@/server/assist/agent").ModelCall = () => new Promise((r) => (release = () => r(reply([text("ok")], "end_turn"))));+ const p = agent.run(t.id, slow);+ expect(() => agent.addMessage(t.id, "two")).toThrow(/Still working/);+ expect(agent.getThread(t.id)!.thread.status).toBe("running");+ release();+ await p;+ });+});++describe("offline planner", () => {+ it("reads counts, formats and attachments into one tool call", () => {+ expect(agent.offlinePlan("Make three vertical videos of a fox running", "cloud")).toMatchObject({+ tool: "generate",+ input: { jobs: [{ model_id: "seedance-2-5", aspect_ratio: "9:16", outputs: 3 }] },+ });+ expect(agent.offlinePlan("Put a hat on him\n\nAttached files (pass these URLs as inputs):\n- image 1: /api/files/a.png", "open")).toMatchObject({+ input: { jobs: [{ model_id: "oss-qwen-edit", images: ["/api/files/a.png"] }] },+ });+ expect(agent.offlinePlan("A storyboard in 6 frames: a heist in Paris", "cloud")).toMatchObject({ tool: "create_storyboard", input: { frames: 6 } });+ expect(agent.offlinePlan("Write a lo-fi song for studying", "open")).toMatchObject({ input: { jobs: [{ model_id: "oss-ace-step" }] } });+ expect(agent.offlinePlan(" ", "cloud")).toBeNull();+ });++ it("plans, waits for approval and starts demo generations end to end", async () => {+ const t = agent.createThread({ engine: "cloud" });+ agent.addMessage(t.id, "A cozy cabin in the snow, square");+ await agent.run(t.id, agent.offline);+ expect(agent.getThread(t.id)!.thread.status).toBe("waiting");+ await agent.answerApproval(t.id, true);+ await agent.run(t.id, agent.offline);+ const v = agent.getThread(t.id)!;+ expect(v.thread.status).toBe("idle");+ expect(v.generations.length).toBeGreaterThan(0);+ expect(v.generations[0].request.params?.aspectRatio).toBe("1:1");+ expect(v.thread.items.at(-1)).toMatchObject({ role: "assistant" });+ });+});++describe("claude request", () => {+ it("sends adaptive thinking, effort, server-side fallback, strict tools and local images as base64", async () => {+ const { saveFile } = await import("@/server/storage");+ const png = Buffer.from("89504e470d0a1a0a0000000d4948445200000001000000010806000000", "hex");+ const asset = saveFile({ data: png, contentType: "image/png", source: "upload" });+ setSetting("anthropicKey", "sk-ant-test");+ const t = agent.createThread({ engine: "open" });+ expect(t.agent).toBe("claude");+ agent.addMessage(t.id, "Animate this", [asset.url]);+ const sent: { url: string; headers: Headers; body: Record<string, unknown> }[] = [];+ const realFetch = globalThis.fetch;+ const answers = [+ { content: [{ type: "tool_use", id: "toolu_1", name: "search_models", input: { kind: "video", task: "i2v" } }], stop_reason: "tool_use" },+ { content: [{ type: "text", text: "Ready when you are." }], stop_reason: "end_turn" },+ ];+ globalThis.fetch = (async (url: string, init: RequestInit) => {+ sent.push({ url: String(url), headers: new Headers(init.headers), body: JSON.parse(String(init.body)) });+ const a = answers.shift()!;+ return new Response(JSON.stringify({ id: "msg_1", type: "message", role: "assistant", model: "claude-opus-5-5", stop_sequence: null, stop_details: null, usage: { input_tokens: 1, output_tokens: 1 }, ...a }), {+ status: 200,+ headers: { "content-type": "application/json" },+ });+ }) as typeof fetch;+ try {+ await agent.run(t.id);+ } finally {+ globalThis.fetch = realFetch;+ setSetting("anthropicKey", "");+ }+ expect(sent).toHaveLength(2);+ const [first, second] = sent;+ expect(first.url).toMatch(/\/v1\/messages\?beta=true$/);+ expect(first.headers.get("anthropic-beta")).toContain("server-side-fallback-2026-07-01");+ expect(first.body).toMatchObject({ model: "claude-opus-5-5", thinking: { type: "adaptive" }, output_config: { effort: "medium" }, fallbacks: "default" });+ expect(first.body.tool_choice).toBeUndefined();+ const system = first.body.system as { text: string; cache_control?: unknown }[];+ expect(system[0].cache_control).toEqual({ type: "ephemeral" });+ expect(system[1].text).toMatch(/prefers open-source/);+ const content = (first.body.messages as { content: { type: string; source?: { type: string; data?: string } }[] }[])[0].content;+ expect(content[1]).toMatchObject({ type: "image", source: { type: "base64" } });+ expect(content[1].source?.data).toBe(png.toString("base64"));+ // The stored history keeps the URL, not the bytes.+ expect(JSON.stringify(history(t.id))).not.toContain(png.toString("base64"));+ // The second request replays the assistant turn verbatim and answers its call.+ const msgs = second.body.messages as { role: string; content: { type: string; tool_use_id?: string }[] }[];+ expect(msgs.map((m) => m.role)).toEqual(["user", "assistant", "user"]);+ expect(msgs[2].content[0]).toMatchObject({ type: "tool_result", tool_use_id: "toolu_1" });+ expect(agent.getThread(t.id)!.thread.items.at(-1)).toMatchObject({ role: "assistant", text: "Ready when you are." });+ });+});