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
Chat makes things: a request to make becomes a plan you approve, and its results land in the chat
Adarsh4f04308f2861
diff --git a/src/app/api/chat/threads/[id]/plans/[mid]/route.ts b/src/app/api/chat/threads/[id]/plans/[mid]/route.tsnew file mode 100644index 00000000..c20e5cb2--- /dev/null+++ b/src/app/api/chat/threads/[id]/plans/[mid]/route.ts@@ -0,0 +1,34 @@+import { z } from "zod";+import { body, chatViewer, gone, signUp, tooOften } from "@/server/chat/http";+import { runPlan } from "@/server/chat/make";+import { getMessage, getThread, setMessagePlan } from "@/server/chat/store";+import { enter } from "@/server/rate";++const Post = z.object({ ok: z.boolean() });++/**+ * Answer a plan in a chat: run it (each step through the studios' own route, as the person, with every check a studio+ * run gets) or not. A plan runs once.+ */+export async function POST(request: Request, ctx: RouteContext<"/api/chat/threads/[id]/plans/[mid]">) {+ const v = chatViewer(request);+ if (!v) return signUp();+ const limited = tooOften(v.who, "plans", 20);+ if (limited) return limited;+ const { id, mid } = await ctx.params;+ const p = Post.safeParse(await body(request));+ if (!p.success) return Response.json({ error: "Say whether to make it." }, { status: 400 });+ const m = getMessage(v.who, id, mid);+ if (!m?.plan) return gone();+ if (m.plan.status !== "ready") return Response.json({ error: "This plan has already been answered.", code: "answered" }, { status: 409 });+ // One answer at a time for a plan: a double tap starts it once.+ const leave = enter(`chat-plan:${v.who}:${mid}`, 1);+ if (!leave) return Response.json({ error: "It's starting already.", code: "answered" }, { status: 409 });+ try {+ const plan = p.data.ok ? await runPlan(request, m.plan) : { ...m.plan, status: "declined" as const };+ setMessagePlan(v.who, id, mid, plan);+ return Response.json(getThread(v.who, id));+ } finally {+ leave();+ }+}diff --git a/src/app/api/chat/threads/[id]/reply/route.ts b/src/app/api/chat/threads/[id]/reply/route.tsindex f6d34235..48c494de 100644--- a/src/app/api/chat/threads/[id]/reply/route.ts+++ b/src/app/api/chat/threads/[id]/reply/route.ts@@ -5,6 +5,8 @@ import { answerThread } from "@/server/chat/answer";import { CHAT_WORDS } from "@/server/chat/backend";import { ownPicture } from "@/server/chat/files";import { body, chatViewer, gone, refused, signUp } from "@/server/chat/http";+import { wantsToMake } from "@/lib/chat/make-intent";+import { planMake } from "@/server/chat/make";import { answerLater, cancelPending, isPending } from "@/server/chat/pending";import { addMessage, dropLastReply, getPrefs, getThread, rewindTo, threadTurns } from "@/server/chat/store";import { enter, hit } from "@/server/rate";@@ -63,6 +65,21 @@ export async function POST(request: Request, ctx: RouteContext<"/api/chat/threadleave();return Response.json({ error: "There's nothing to answer yet.", code: "nothing" }, { status: 409 });}+ // Asked to make something (a picture, a clip, a song): a plan to approve, priced as the studio would, not a reply.+ if (userMessage && thread.kind !== "character" && wantsToMake(userMessage.content, !!userMessage.image)) {+ const made = await planMake(request, v.who, userMessage.content, userMessage.image).catch(() => null);+ if (made) {+ const saved = addMessage(v.who, id, "assistant", made.say, null, made.plan);+ leave();+ const lines: ChatEvent[] = [+ { type: "user", message: userMessage },+ { type: "done", message: saved, title: getThread(v.who, id)?.title ?? thread.title },+ ];+ return new Response(lines.map((l) => JSON.stringify(l)).join("\n") + "\n", {+ headers: { "Content-Type": "application/x-ndjson; charset=utf-8", "Cache-Control": "no-store" },+ });+ }+ }// Their own key answers now: it doesn't wait with the free model.if (prefs.engine === "key") cancelPending(v.who, id);diff --git a/src/components/chat/hooks.ts b/src/components/chat/hooks.tsindex 32cb4110..9c51fbc2 100644--- a/src/components/chat/hooks.ts+++ b/src/components/chat/hooks.ts@@ -40,10 +40,18 @@ export function useChatThread(id: string, enabled = true, poll = false) {staleTime: 0,enabled,retry: false,- refetchInterval: poll ? 6_000 : false,+ // A kept message waits for its reply; a plan's runs come in while they're made.+ refetchInterval: (q) => (making(q.state.data) ? 2_000 : poll ? 6_000 : false),});}+/** Are any of a chat's plans still making their results? */+function making(t: ChatThreadView | undefined): boolean {+ if (!t) return false;+ const status = new Map(t.generations.map((g) => [g.id, g.status]));+ return t.messages.some((m) => m.plan?.status === "running" && m.plan.ids.some((id) => !status.has(id) || status.get(id) === "queued" || status.get(id) === "running"));+}+export interface StartChat {kind: ChatKind;characterId?: string | null;diff --git a/src/components/chat/plan-card.tsx b/src/components/chat/plan-card.tsxnew file mode 100644index 00000000..c91c430b--- /dev/null+++ b/src/components/chat/plan-card.tsx@@ -0,0 +1,156 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";+import { AudioLines, Clapperboard, FileText, ImageIcon, Loader2, Play, RefreshCw, Sparkles } from "lucide-react";+import { useMemo, useState } from "react";+import { GenerationCards } from "@/components/assist/transcript";+import { Viewer } from "@/components/studio/viewer";+import { Button } from "@/components/ui/button";+import type { Generation } from "@/lib/catalog/types";+import type { ChatMessage, ChatPlan, ChatThreadView } from "@/lib/chat/types";+import { toastError } from "@/lib/refusals";+import { cn } from "@/lib/utils";+import { chatSend } from "./hooks";++const KIND_ICON = { image: ImageIcon, video: Clapperboard, audio: AudioLines, text: FileText } as const;++/**+ * A plan in a chat: what it makes, on which model, and what each step costs (the studio's own price check); Make it+ * runs it, and its results come into the chat, ready to animate or make again.+ */+export function PlanCard({+ threadId,+ message,+ generations,+ onAnimate,+ onAgain,+}: {+ threadId: string;+ message: ChatMessage & { plan: ChatPlan };+ generations: Map<string, Generation>;+ onAnimate: (url: string) => void;+ onAgain?: () => void;+}) {+ const qc = useQueryClient();+ const plan = message.plan;+ const [busy, setBusy] = useState<"run" | "skip" | null>(null);+ const [open, setOpen] = useState<{ g: Generation; i: number } | null>(null);+ const runnable = plan.jobs.some((j) => !j.error);++ const answer = async (ok: boolean) => {+ setBusy(ok ? "run" : "skip");+ try {+ const t = await chatSend<ChatThreadView>(`/api/chat/threads/${threadId}/plans/${message.id}`, "POST", { ok });+ qc.setQueryData(["chat", "thread", threadId], t);+ } catch (e) {+ toastError(e);+ } finally {+ setBusy(null);+ }+ };++ // The stills it made, numbered as the cards number them, to animate one.+ const stills = useMemo(+ () =>+ plan.ids+ .map((id) => generations.get(id))+ .filter((g): g is Generation => !!g && g.status === "succeeded" && g.kind === "image")+ .flatMap((g) => g.outputs.filter((o) => !o.text).map((o) => o.url)),+ [plan.ids, generations],+ );+ const working = plan.ids.some((id) => {+ const g = generations.get(id);+ return !g || g.status === "queued" || g.status === "running";+ });++ return (+ <div className="mt-2 w-full max-w-[min(100%,620px)] rounded-2xl border bg-background p-3.5 shadow-soft">+ <p className="flex items-center gap-2 text-[13px] font-medium text-muted-foreground">+ <Sparkles className="size-3.5 text-brand-text" />+ {plan.summary}+ </p>+ <ul className="mt-2.5 space-y-2">+ {plan.jobs.map((j, i) => {+ const Icon = KIND_ICON[j.kind as keyof typeof KIND_ICON] ?? ImageIcon;+ return (+ <li key={i} className="flex items-start gap-2.5 text-[14px]">+ <span className="mt-0.5 grid size-7 shrink-0 place-items-center rounded-lg bg-muted text-muted-foreground">+ <Icon className="size-3.5" />+ </span>+ <span className="min-w-0 flex-1">+ <span className="flex flex-wrap items-baseline justify-between gap-x-3">+ <span className="font-medium">+ {j.modelName}+ {j.count > 1 && <span className="font-normal text-muted-foreground"> · {j.count} takes</span>}+ </span>+ {j.price && <span className="text-[13px] text-muted-foreground">{j.price}</span>}+ </span>+ {j.prompt && <span className="mt-0.5 line-clamp-2 block text-[13px] text-muted-foreground">{j.prompt}</span>}+ {j.note && <span className="mt-1 block text-[12.5px] text-brand-text">{j.note}</span>}+ {j.error && <span className="mt-1 block text-[12.5px] text-muted-foreground">{j.error}</span>}+ </span>+ </li>+ );+ })}+ </ul>++ {plan.status === "ready" && (+ <div className="mt-3.5 flex flex-wrap items-center gap-2">+ <Button size="sm" className="rounded-full" disabled={!runnable || !!busy} onClick={() => void answer(true)}>+ {busy === "run" ? <Loader2 className="animate-spin" /> : <Play className="fill-current" />}+ Make it+ </Button>+ <Button size="sm" variant="ghost" className="rounded-full" disabled={!!busy} onClick={() => void answer(false)}>+ Not now+ </Button>+ </div>+ )}+ {plan.status === "declined" && <p className="mt-3 text-[13px] text-muted-foreground">Kept as an idea. Ask again whenever you want it made.</p>}++ {plan.status === "running" && (+ <div className={cn("mt-3.5 space-y-3", !plan.ids.length && "mt-2")}>+ {plan.ids.length > 0 && (+ <GenerationCards+ ids={plan.ids}+ all={generations}+ onOpen={(g, i) => setOpen({ g, i })}+ />+ )}+ {working && plan.ids.length > 0 && !plan.ids.some((id) => generations.get(id)?.status === "succeeded") && (+ <p className="flex items-center gap-2 text-[13px] text-muted-foreground">+ <Loader2 className="size-3.5 animate-spin" />+ Making it now · it appears here when it's ready+ </p>+ )}+ {plan.errors.map((e, i) => (+ <p key={i} className="text-[13px] text-muted-foreground">+ {e}+ </p>+ ))}+ {!working && (stills.length > 0 || onAgain) && (+ <div className="flex flex-wrap gap-1.5">+ {stills.slice(0, 4).map((url, i) => (+ <button+ key={url}+ type="button"+ onClick={() => onAnimate(url)}+ className="inline-flex h-8 items-center gap-1.5 rounded-full border px-3 text-[12.5px] font-medium hover:border-primary hover:text-brand-text"+ >+ <Clapperboard className="size-3.5" />+ {stills.length > 1 ? `Animate #${i + 1}` : "Animate it"}+ </button>+ ))}+ {onAgain && (+ <button type="button" onClick={onAgain} className="inline-flex h-8 items-center gap-1.5 rounded-full border px-3 text-[12.5px] font-medium hover:border-primary hover:text-brand-text">+ <RefreshCw className="size-3.5" />+ Make another+ </button>+ )}+ </div>+ )}+ </div>+ )}+ {open && <Viewer generation={open.g} index={open.i} onClose={() => setOpen(null)} />}+ </div>+ );+}diff --git a/src/components/chat/thread-view.tsx b/src/components/chat/thread-view.tsxindex ee58b3b5..149a553d 100644--- a/src/components/chat/thread-view.tsx+++ b/src/components/chat/thread-view.tsx@@ -4,7 +4,7 @@ import { useQueryClient } from "@tanstack/react-query";import { ArrowLeft, Check, Copy, MoreHorizontal, Pencil, RotateCcw, Share2, Trash2, X } from "lucide-react";import Link from "next/link";import { useRouter } from "next/navigation";-import { useEffect, useLayoutEffect, useRef, useState } from "react";+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { PhoneNavButton } from "@/components/nav/phone-nav-button";import {AlertDialog,@@ -19,6 +19,7 @@ import {import { Button } from "@/components/ui/button";import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import { CHAT_KINDS, playFormat, writeTool, type CharacterCard } from "@/lib/chat/catalog";+import type { Generation } from "@/lib/catalog/types";import type { ChatMessage, ChatThreadView } from "@/lib/chat/types";import { toastError } from "@/lib/refusals";import { cn } from "@/lib/utils";@@ -27,6 +28,7 @@ import { CharacterFace } from "./character-face";import { ChatComposer, type ComposerHandle } from "./composer";import { ChatSettingsDialog, ChilliDot, MangoChilliDialog, ShareDialog } from "./dialogs";import { chatSend, useChatMe, useChatThread, useReply } from "./hooks";+import { PlanCard } from "./plan-card";import { Markdown, ReplyBody } from "./prose";/** One chat: its messages, the reply as it's written, and the box to carry on. */@@ -38,6 +40,7 @@ export function ThreadView({ id }: { id: string }) {const view = useChatThread(id, true, state.phase === "pending");const me = useChatMe();const t = view.data;+ const generations = useMemo(() => new Map((t?.generations ?? []).map((g) => [g.id, g])), [t?.generations]);const waitingForLater = state.phase === "pending" && t?.messages.at(-1)?.role === "user";const [sharing, setSharing] = useState(false);const [settings, setSettings] = useState(false);@@ -223,6 +226,13 @@ export function ThreadView({ id }: { id: string }) {) : (<AssistantTurnm={m}+ threadId={id}+ generations={generations}+ onAnimate={(url) => void ask({ text: "Animate this", image: url })}+ onAgain={(() => {+ const said = t.messages.slice(0, i).findLast((x) => x.role === "user");+ return said?.content ? () => void ask({ text: said.content, image: said.image }) : undefined;+ })()}character={c}first={first}tail={tail}@@ -441,6 +451,10 @@ function UserTurn({ m, tail, fresh, editable, onEdit }: { m: ChatMessage; tail:function AssistantTurn({m,+ threadId,+ generations,+ onAnimate,+ onAgain,character,first,tail,@@ -451,6 +465,10 @@ function AssistantTurn({onRetry,}: {m: ChatMessage;+ threadId: string;+ generations: Map<string, Generation>;+ onAnimate: (url: string) => void;+ onAgain?: () => void;character: CharacterCard | null;first: boolean;tail: boolean;@@ -487,6 +505,11 @@ function AssistantTurn({{/* Earlier replies keep the run tight: their Copy sits beside the bubble and shows on hover. */}{!last && <span className="self-center opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100 max-sm:hidden">{copy}</span>}</Row>+ {m.plan && (+ <div className={cn(character && "ml-9")}>+ <PlanCard threadId={threadId} message={m as ChatMessage & { plan: NonNullable<ChatMessage["plan"]> }} generations={generations} onAnimate={onAnimate} onAgain={onAgain} />+ </div>+ )}{last && (<div className={cn("mt-1 flex gap-0.5 text-muted-foreground", character && "ml-9")}>{copy}diff --git a/src/lib/chat/make-intent.ts b/src/lib/chat/make-intent.tsnew file mode 100644index 00000000..5cc9dc91--- /dev/null+++ b/src/lib/chat/make-intent.ts@@ -0,0 +1,31 @@+/**+ * Does a chat message ask Fuobe to make something (a picture, a clip, a song), not to talk about it? Pure and+ * deliberately careful: a message only becomes a plan when it opens with a making verb and names something that can be+ * made, or edits or animates a picture sent with it. Everything else stays a conversation.+ */++const POLITE = String.raw`(?:(?:hey|hi|ok|okay|so|now|great|nice|cool|please|pls|fuobe)[,!.]?\s+)*(?:(?:can|could|would|will) you\s+|i(?:'d| would) like (?:you )?to\s+|i want (?:you )?to\s+|i need (?:you )?to\s+|let'?s\s+|go ahead and\s+|help me\s+)?(?:please\s+)?`;++const MAKE_VERBS = String.raw`(?:make|create|generate|render|draw|design|paint|illustrate|shoot|film|produce|compose|record|animate|give me|show me|do)`;++/** Things that can be made: a picture, a clip, a sound. */+const MADE = /\b(images?|pictures?|pics?|photos?|photographs?|portraits?|headshots?|selfies?|shots?|stills?|posters?|covers?|logos?|thumbnails?|banners?|wallpapers?|illustrations?|drawings?|paintings?|renders?|mockups?|lookbook|flat ?lay|product shots?|videos?|clips?|reels?|ads?|commercials?|trailers?|animations?|films?|footage|teasers?|storyboards?|songs?|tracks?|music|beats?|jingles?|soundtracks?|voice ?-?overs?|narrations?|sound effects?|sfx|3d models?|characters? sheets?)\b/;++/** Edits that need a picture sent with the message. */+const EDIT = /^(?:remove|erase|change|replace|swap|restyle|relight|recolou?r|upscale|enhance|sharpen|extend|outpaint|crop|fix|retouch|turn|put|add|make (?:it|this|her|him|them)|animate|bring (?:it|this) to life)\b/;++const START = new RegExp(`^${POLITE}${MAKE_VERBS}\\b`, "i");++/** Words that make it a conversation about making, not a request to make ("how do I make a reel?"). */+const TALK = /^(?:how|what|why|when|where|which|who|should|is|are|do|does|can i|could i|tips|ideas?|explain|tell me|write|draft|brainstorm|suggest|help me (?:think|plan|write|decide))\b/i;++export function wantsToMake(text: string, hasPicture = false): boolean {+ const t = text.trim().toLowerCase().replace(/\s+/g, " ");+ if (!t) return false;+ if (TALK.test(t) && !/^(?:can|could|would|will) you (?:please )?(?:make|create|generate|render|draw|design|animate)\b/.test(t)) return false;+ const stripped = t.replace(new RegExp(`^${POLITE}`, "i"), "");+ if (hasPicture && EDIT.test(stripped)) return true;+ if (!START.test(t)) return false;+ if (/^animate\b/.test(stripped)) return hasPicture || MADE.test(t);+ return MADE.test(t);+}diff --git a/src/lib/chat/types.ts b/src/lib/chat/types.tsindex dd538cf3..b07d5f1e 100644--- a/src/lib/chat/types.ts+++ b/src/lib/chat/types.ts@@ -1,13 +1,47 @@+import type { Generation, GenerationRequest, MediaKind } from "@/lib/catalog/types";import type { CharacterCard, ChatKind } from "./catalog";/** What the chat's API sends the browser. */+/** One step of a plan: what it makes, on which model, and what Run costs (the studio's own price check). */+export interface ChatPlanJob {+ modelId: string;+ modelName: string;+ kind: MediaKind;+ prompt: string | null;+ /** How many results. */+ count: number;+ /** What Run shows for it ("Free", "$0.12", the GPUs' own words), or null when it can't run. */+ price: string | null;+ /** Why it can't run, in plain words (it then doesn't). */+ error?: string;+ /** Something the person should know (another model runs it, a setting fitted). */+ note?: string;+}++/** A plan in a chat: made when the person asks to make something, run when they say so. */+export interface ChatPlan {+ summary: string;+ jobs: ChatPlanJob[];+ /** The exact runs Run starts, through the studios' own route. */+ requests: GenerationRequest[];+ status: "ready" | "running" | "declined";+ /** The runs it started. */+ ids: string[];+ /** Runs that were refused when started, in plain words. */+ errors: string[];+ /** The plan made a still to animate after: the results offer Animate. */+ then?: "animate";+}+export interface ChatMessage {id: string;role: "user" | "assistant";content: string;/** A picture the person sent with it (their own file). */image: string | null;+ /** A plan to make something (an assistant message). */+ plan?: ChatPlan;createdAt: number;}@@ -31,6 +65,8 @@ export interface ChatThreadView extends ChatThreadSummary {characterCard: CharacterCard | null;/** The share link's token, while one is live. */shareToken: string | null;+ /** The runs the chat's plans started (the person's own), for their results. */+ generations: Generation[];}/** Where a reply comes from. */diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex 0db4bcf3..109d15c0 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -402,7 +402,7 @@ export const ACCOUNT_PROJECT_ROUTES: RegExp[] = [/^\/api\/starters\/faceless\.[^/]+$/,// Fuobe Chat: its own chats, characters and chat settings (src/server/chat/store.ts). Replies run on the install's free// text helper (which counts each account's use) or on the account's own OpenRouter key, never the studio's keys.- /^\/api\/chat\/(me|key|threads(\/[^/]+(\/(reply|share))?)?|characters(\/[^/]+)?)$/,+ /^\/api\/chat\/(me|key|threads(\/[^/]+(\/(reply|share|plans\/[^/]+))?)?|characters(\/[^/]+)?)$/,];export const accountProjectRoute = (pathname: string): boolean => ACCOUNT_PROJECT_ROUTES.some((r) => r.test(pathname));diff --git a/src/server/chat/make.ts b/src/server/chat/make.tsnew file mode 100644index 00000000..ad348cfe--- /dev/null+++ b/src/server/chat/make.ts@@ -0,0 +1,123 @@+import "server-only";+import { POST as generationsPOST } from "@/app/api/generations/route";+import { getModel } from "@/lib/catalog";+import type { GenerationRequest } from "@/lib/catalog/types";+import type { ChatPlan, ChatPlanJob } from "@/lib/chat/types";+import { formatCost } from "@/lib/format";+import { accountEngineMode } from "../account-keys";+import { offlinePlan } from "../assist/agent";+import { asRequest, planFor } from "../assist/tools";+import { asAccount } from "../generations";++/**+ * Chat's making layer. A request to make something becomes a plan: read by Assist's planner (counts, formats, shots,+ * music, voice-overs, an edit or animation of a sent picture), priced step by step by the studios' own route+ * (POST /api/generations?preview=1) as the person asking, and run through that same route when they say so. So an+ * account's plan gets every check a studio run gets: its own limits, only its own files, where it runs and what it costs,+ * and the moderation and GPU checks. One step per plan: a still that is animated after is two plans (the results offer+ * Animate), because an account's runs start one by one.+ */++type Job = Parameters<typeof asRequest>[0];++/** The request headers a run is made with: the person's own session, as if the studio had sent it. */+function forwarded(from: Request): Headers {+ const h = new Headers();+ for (const k of ["cookie", "authorization", "host", "x-forwarded-host", "x-forwarded-proto", "x-forwarded-for", "x-real-ip", "user-agent", "origin"]) {+ const v = from.headers.get(k);+ if (v) h.set(k, v);+ }+ h.set("content-type", "application/json");+ return h;+}++async function callStudio(from: Request, req: GenerationRequest, preview: boolean): Promise<{ ok: boolean; status: number; body: Record<string, unknown> }> {+ const url = new URL(`/api/generations${preview ? "?preview=1" : ""}`, from.url);+ const res = await generationsPOST(new Request(url, { method: "POST", headers: forwarded(from), body: JSON.stringify(req) }));+ const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;+ return { ok: res.ok, status: res.status, body };+}++const str = (v: unknown) => (typeof v === "string" ? v : null);++/** What Run shows for a step, from the studio's own price check. */+function priceOf(body: Record<string, unknown>): string | null {+ const quote = body.quote as { text?: unknown; allowed?: unknown } | undefined;+ if (quote && typeof quote.text === "string") return quote.allowed === false ? null : quote.text;+ const cost = typeof body.costUsd === "number" ? body.costUsd : null;+ if (body.demo === true) return null;+ return cost === null ? null : cost === 0 ? "Free" : formatCost(cost);+}++/**+ * The plan for a message that asks to make something, or null when the planner reads no picture, clip or sound in it+ * (the chat then answers it as words). `image`: a picture sent with the message (edited or animated).+ */+export async function planMake(from: Request, who: string, text: string, image: string | null): Promise<{ say: string; plan: ChatPlan } | null> {+ const engine = who === "owner" ? "cloud" : accountEngineMode(who) === "open" ? "open" : "cloud";+ // The thing to make, without the asking ("Can you make me a poster for…" → "A poster for…").+ const what = text+ .trim()+ .replace(/^(?:(?:hey|hi|ok|okay|so|now|please|pls)[,!.]?\s+)*(?:(?:can|could|would|will) you\s+|i(?:'d| would) like (?:you )?to\s+|i want (?:you )?to\s+|let'?s\s+)?(?:please\s+)?(?:make|create|generate|render|draw|design|produce|give me|show me)\s+(?:me\s+|us\s+)?/i, "")+ .replace(/[?]+$/, "");+ const ask = what.length >= 3 && what !== text ? what.charAt(0).toUpperCase() + what.slice(1) : text;+ const message = image ? `${ask}\n\nAttached files:\n- image 1: ${image}` : ask;+ const read = offlinePlan(message, engine);+ if (!read || read.tool !== "generate") return null;+ const input = read.input as { summary?: string; jobs?: Job[] };+ const all = (input.jobs ?? []).slice(0, 4);+ // One step per plan: a job that waits for another (animate the still) comes after, from its results.+ const jobs = all.filter((j) => j.after === undefined);+ const then = jobs.length < all.length ? ("animate" as const) : undefined;+ if (!jobs.length) return null;++ // The planner's own check first (an unknown model, a model the GPUs here can't run moves to one that can).+ const planned = (() => {+ const run = () => planFor("generate", { summary: input.summary ?? text.slice(0, 80), jobs }, { engine });+ try {+ return who === "owner" ? run() : asAccount(who, run);+ } catch {+ return null;+ }+ })();++ const out: ChatPlanJob[] = [];+ const requests: GenerationRequest[] = [];+ for (let i = 0; i < jobs.length; i++) {+ const p = planned?.jobs[i];+ // The model it runs on: the planner's pick when it moved the job, else the one asked for.+ const job: Job = p && !p.error ? { ...jobs[i], model_id: p.modelId } : jobs[i];+ const req = { ...asRequest(job), feature: "chat" };+ const model = getModel(req.modelId);+ const check = await callStudio(from, req, true);+ const price = check.ok ? priceOf(check.body) : null;+ const error = !check.ok ? (str(check.body.error) ?? "This step can't run here.") : p?.error;+ out.push({+ modelId: str(check.body.modelId) ?? req.modelId,+ modelName: str(check.body.modelName) ?? model?.name ?? req.modelId,+ kind: (str(check.body.kind) as ChatPlanJob["kind"]) ?? p?.kind ?? model?.kind ?? "image",+ prompt: req.prompt ?? null,+ count: typeof check.body.outputs === "number" ? check.body.outputs : (req.params?.numOutputs ?? 1),+ price: error ? null : price,+ ...(error && { error }),+ ...(p?.changes?.length && { note: p.changes.join(" ") }),+ });+ requests.push(req);+ }+ const say = then ? `${read.say.replace(/\s*[—-]\s*the video starts by itself.*$/i, ".")} Once it's ready, tap Animate on the one you like.` : read.say;+ return { say, plan: { summary: input.summary ?? text.slice(0, 80), jobs: out, requests, status: "ready", ids: [], errors: [], ...(then && { then }) } };+}++/** Run a plan's steps through the studios' route, as the person; each refusal is kept in its own words. */+export async function runPlan(from: Request, plan: ChatPlan): Promise<ChatPlan> {+ const ids: string[] = [];+ const errors: string[] = [];+ for (let i = 0; i < plan.requests.length; i++) {+ if (plan.jobs[i]?.error) continue;+ const r = await callStudio(from, plan.requests[i], false).catch(() => ({ ok: false, status: 500, body: {} as Record<string, unknown> }));+ const items = Array.isArray(r.body.items) ? (r.body.items as { id?: unknown }[]) : [];+ if (r.ok && items.length) ids.push(...items.map((g) => String(g.id)));+ else errors.push(str(r.body.error) ?? `${plan.jobs[i]?.modelName ?? "This step"} didn't start. Tap Make it again.`);+ }+ return { ...plan, status: "running", ids, errors };+}diff --git a/src/server/chat/store.ts b/src/server/chat/store.tsindex b54d5bb1..e1e4ed4f 100644--- a/src/server/chat/store.ts+++ b/src/server/chat/store.ts@@ -2,8 +2,10 @@ import "server-only";import crypto from "node:crypto";import { BUILT_IN_CHARACTERS, builtInCharacter, CHAT_LIMITS, isChatKind, playFormat, writeTool, type CharacterCard, type ChatKind } from "@/lib/chat/catalog";import { titleFrom } from "@/lib/chat/prompt";-import type { ChatEngine, ChatMessage, ChatShareSnapshot, ChatThreadSummary, ChatThreadView } from "@/lib/chat/types";+import type { ChatEngine, ChatMessage, ChatPlan, ChatShareSnapshot, ChatThreadSummary, ChatThreadView } from "@/lib/chat/types";+import { generationAccount } from "../account-library";import { db } from "../db";+import { getGeneration } from "../generations";import { open as openSealed, seal } from "../secret-box";/**@@ -168,10 +170,35 @@ interface MessageRow {role: "user" | "assistant";content: string;image_url: string | null;+ data_json?: string | null;created_at: number;}-const fromMessageRow = (r: MessageRow): ChatMessage => ({ id: r.id, role: r.role, content: r.content, image: r.image_url, createdAt: r.created_at });+function planOf(raw: string | null | undefined): ChatPlan | undefined {+ if (!raw) return undefined;+ try {+ const d = JSON.parse(raw) as { plan?: ChatPlan };+ return d.plan && Array.isArray(d.plan.jobs) ? d.plan : undefined;+ } catch {+ return undefined;+ }+}++const fromMessageRow = (r: MessageRow): ChatMessage => {+ const plan = planOf(r.data_json);+ return { id: r.id, role: r.role, content: r.content, image: r.image_url, ...(plan && { plan }), createdAt: r.created_at };+};++/** Save a message's plan (its status and the runs it started). */+export function setMessagePlan(who: string, threadId: string, messageId: string, plan: ChatPlan): void {+ db().prepare("UPDATE account_chat_messages SET data_json = ? WHERE id = ? AND thread_id = ? AND account_id = ?").run(JSON.stringify({ plan }), messageId, threadId, who);+}++/** One message of a chat, or null. */+export function getMessage(who: string, threadId: string, messageId: string): ChatMessage | null {+ const r = db().prepare("SELECT * FROM account_chat_messages WHERE id = ? AND thread_id = ? AND account_id = ?").get(messageId, threadId, who) as MessageRow | undefined;+ return r ? fromMessageRow(r) : null;+}function summaryOf(who: string, r: ThreadRow, last?: string): ChatThreadSummary {const c = getCharacter(who, r.character_id);@@ -216,7 +243,15 @@ export function getThread(who: string, id: string): ChatThreadView | null {const r = threadRow(who, id);if (!r) return null;const messages = (db().prepare("SELECT * FROM account_chat_messages WHERE thread_id = ? AND account_id = ? ORDER BY seq").all(id, who) as MessageRow[]).map(fromMessageRow);- return { ...summaryOf(who, r, messages.at(-1)?.content), messages, characterCard: getCharacter(who, r.character_id), shareToken: r.share_token };+ const ids = [...new Set(messages.flatMap((m) => m.plan?.ids ?? []))];+ // Only the person's own runs: an account's carry its id, the owner's none.+ const generations = ids.flatMap((g) => {+ const owner = generationAccount(g);+ const mine = who === "owner" ? owner === null : owner === who;+ const gen = mine ? getGeneration(g) : null;+ return gen ? [gen] : [];+ });+ return { ...summaryOf(who, r, messages.at(-1)?.content), messages, characterCard: getCharacter(who, r.character_id), shareToken: r.share_token, generations };}/** What a reply needs that the browser doesn't: the summary and how far it reaches. */@@ -265,7 +300,7 @@ export function createThread(who: string, t: NewThread): ChatThreadView {return getThread(who, id)!;}-export function addMessage(who: string, threadId: string, role: "user" | "assistant", content: string, image: string | null = null): ChatMessage {+export function addMessage(who: string, threadId: string, role: "user" | "assistant", content: string, image: string | null = null, plan?: ChatPlan): ChatMessage {const d = db();return d.transaction(() => {const r = threadRow(who, threadId);@@ -273,8 +308,9 @@ export function addMessage(who: string, threadId: string, role: "user" | "assistconst last = d.prepare("SELECT MAX(seq) AS s, COUNT(*) AS n FROM account_chat_messages WHERE thread_id = ?").get(threadId) as { s: number | null; n: number };if (last.n >= CHAT_LIMITS.messagesPerThread) throw new ChatError("This chat is as long as a chat can be. Start a new one to keep going.", 409, "too-long");const now = Date.now();- const row: MessageRow = { id: newId("cm"), thread_id: threadId, account_id: who, seq: (last.s ?? 0) + 1, role, content, image_url: image, created_at: now };- d.prepare("INSERT INTO account_chat_messages (id, thread_id, account_id, seq, role, content, image_url, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(+ const data = plan ? JSON.stringify({ plan }) : null;+ const row: MessageRow = { id: newId("cm"), thread_id: threadId, account_id: who, seq: (last.s ?? 0) + 1, role, content, image_url: image, data_json: data, created_at: now };+ d.prepare("INSERT INTO account_chat_messages (id, thread_id, account_id, seq, role, content, image_url, data_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run(row.id,row.thread_id,who,@@ -282,6 +318,7 @@ export function addMessage(who: string, threadId: string, role: "user" | "assistrole,content,image,+ data,now,);// The first thing the person says names an open chat.diff --git a/src/server/db.ts b/src/server/db.tsindex c310a0ef..3980bfe6 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1218,6 +1218,10 @@ function open(): Database.Database {db.exec(ACCOUNT_CANVAS_TABLES);// Fuobe Chat (src/server/chat/store.ts): not a numbered migration either.db.exec(CHAT_TABLES);+ // A chat message's plan to make something (its runs and their inputs), for tables made before it.+ if (!(db.prepare("PRAGMA table_info(account_chat_messages)").all() as { name: string }[]).some((c) => c.name === "data_json")) {+ addColumn(db, "ALTER TABLE account_chat_messages ADD COLUMN data_json TEXT");+ }// Where an account's runs go, as it picked (run-on.ts): read only while hosted runs are on, empty otherwise.db.exec(RUN_ON_TABLES);// Runs on this install's GPUs waiting to enter the line (pool-holds.ts): empty unless hosted runs are on.diff --git a/src/server/generations.ts b/src/server/generations.tsindex 7edce7c9..d3310d54 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -867,7 +867,7 @@ export const ASSET_REFS: AssetRef[] = [{ table: "account_canvases", cols: ["pages_json"], what: "account canvas", key: "id", name: "name", account: "account_id" },{ table: "account_projects", cols: ["data_json", "summary_json"], what: "account project", key: "id", name: "name", account: "account_id" },// Fuobe Chat: a picture sent in a chat, a character's portrait, and a shared chat's portrait.- { table: "account_chat_messages", cols: ["image_url"], what: "chat", key: "thread_id", name: "(SELECT title FROM account_chat_threads WHERE id = thread_id)", account: "account_id" },+ { table: "account_chat_messages", cols: ["image_url", "data_json"], what: "chat", key: "thread_id", name: "(SELECT title FROM account_chat_threads WHERE id = thread_id)", account: "account_id" },{ table: "account_chat_characters", cols: ["portrait_url"], what: "chat character", key: "id", name: "name", account: "account_id" },{ table: "account_chat_shares", cols: ["portrait_url"], what: "shared chat", key: "token", name: "json_extract(snapshot_json, '$.title')", account: "account_id" },];diff --git a/tests/chat.test.ts b/tests/chat.test.tsindex 9daefb7b..41ad06a5 100644--- a/tests/chat.test.ts+++ b/tests/chat.test.ts@@ -24,6 +24,7 @@ delete process.env.FUOBE_MODERATION_URL;const prompt = await import("@/lib/chat/prompt");const catalog = await import("@/lib/chat/catalog");const { chatShareRoute } = await import("@/lib/chat/share");+const { wantsToMake } = await import("@/lib/chat/make-intent");const auth = await import("@/server/auth");const { db } = await import("@/server/db");const { resetRates } = await import("@/server/rate");@@ -350,6 +351,69 @@ describe("a reply", () => {});});+describe("making things in a chat", () => {+ it("tells a request to make something from talk about it", () => {+ for (const s of [+ "Make a 3-shot ad for a gold watch",+ "can you make four portraits of a model in a velvet suit",+ "Please create a music track for a rainy café",+ "generate a vertical video of a red gown in the snow",+ "let's make a poster for my launch",+ ])+ expect(wantsToMake(s), s).toBe(true);+ for (const s of ["How do I make a reel go viral?", "What should I wear to a gallery opening?", "Write a caption for my linen post", "make sense?", "I made a video yesterday", "Ideas for a perfume ad"])+ expect(wantsToMake(s), s).toBe(false);+ // An edit or animation of a picture sent with the message.+ expect(wantsToMake("Animate this", true)).toBe(true);+ expect(wantsToMake("remove the background", true)).toBe(true);+ expect(wantsToMake("Animate this", false)).toBe(false);+ });++ it("answers a request to make with a plan priced by the studio's own check, and a plan can be put aside", async () => {+ const t = (await (await threadsRoute.POST(req(cookies.a, "/api/chat/threads", "POST", { kind: "chat" }))).json()) as { id: string };+ const ev = await events(await replyRoute.POST(req(cookies.a, `/api/chat/threads/${t.id}/reply`, "POST", { text: "Make four portraits of a model in a black velvet suit" }), ctx({ id: t.id })));+ expect(ev.map((e) => e.type)).toEqual(["user", "done"]);+ const reply = ev[1].message as { id: string; plan?: { jobs: { modelName: string; count: number }[]; status: string; requests: { feature: string; params?: { numOutputs?: number } }[] } };+ expect(reply.plan?.status).toBe("ready");+ expect(reply.plan?.jobs).toHaveLength(1);+ expect(reply.plan?.jobs[0].modelName).toBeTruthy();+ expect(reply.plan?.requests[0]).toMatchObject({ feature: "chat", params: { numOutputs: 4 } });+ // Not now: kept as an idea, never run, and it can't be answered twice.+ const plansRoute = await import("@/app/api/chat/threads/[id]/plans/[mid]/route");+ const no = await plansRoute.POST(req(cookies.a, `/api/chat/threads/${t.id}/plans/${reply.id}`, "POST", { ok: false }), ctx({ id: t.id, mid: reply.id }));+ expect(no.status).toBe(200);+ expect(store.getThread(a, t.id)!.messages.at(-1)?.plan?.status).toBe("declined");+ const again = await plansRoute.POST(req(cookies.a, `/api/chat/threads/${t.id}/plans/${reply.id}`, "POST", { ok: true }), ctx({ id: t.id, mid: reply.id }));+ expect(again.status).toBe(409);+ // Another account can't answer it.+ const other = await plansRoute.POST(req(cookies.b, `/api/chat/threads/${t.id}/plans/${reply.id}`, "POST", { ok: true }), ctx({ id: t.id, mid: reply.id }));+ expect(other.status).toBe(404);+ // Make it: the steps go through the studios' route as this account, and either start or say why not.+ const ev2 = await events(await replyRoute.POST(req(cookies.a, `/api/chat/threads/${t.id}/reply`, "POST", { text: "Make a poster for a perfume called Midnight Fig" }), ctx({ id: t.id })));+ const second = ev2[1].message as { id: string };+ const run = await plansRoute.POST(req(cookies.a, `/api/chat/threads/${t.id}/plans/${second.id}`, "POST", { ok: true }), ctx({ id: t.id, mid: second.id }));+ expect(run.status).toBe(200);+ const ran = store.getThread(a, t.id)!.messages.find((m) => m.id === second.id)!.plan!;+ expect(ran.status).toBe("running");+ expect(ran.ids.length + ran.errors.length + ran.jobs.filter((j) => j.error).length).toBeGreaterThan(0);+ for (const g of ran.ids) expect(db().prepare("SELECT json_extract(request_json, '$.account') AS a FROM generations WHERE id = ?").get(g)).toEqual({ a });+ });++ it("keeps talk as talk, and characters stay in their story", async () => {+ const slot = standIn(() => "Pick a dark wool coat.");+ try {+ const t = (await (await threadsRoute.POST(req(cookies.a, "/api/chat/threads", "POST", { kind: "chat" }))).json()) as { id: string };+ const ev = await events(await replyRoute.POST(req(cookies.a, `/api/chat/threads/${t.id}/reply`, "POST", { text: "How do I make my outfit look expensive?" }), ctx({ id: t.id })));+ expect((ev.at(-1)?.message as { plan?: unknown } | undefined)?.plan).toBeUndefined();+ const c = (await (await threadsRoute.POST(req(cookies.a, "/api/chat/threads", "POST", { kind: "character", characterId: "kai" }))).json()) as { id: string };+ const ev2 = await events(await replyRoute.POST(req(cookies.a, `/api/chat/threads/${c.id}/reply`, "POST", { text: "Make a song for me, Kai" }), ctx({ id: c.id })));+ expect((ev2.at(-1)?.message as { plan?: unknown } | undefined)?.plan).toBeUndefined();+ } finally {+ await slot.stop();+ }+ });+});+describe("sharing", () => {it("shares a copy at a public link, stops sharing, and goes with the chat", async () => {const t = store.createThread(a, { kind: "chat", mature: false });