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: real chat turns on the free text helper, with words as they come and the place in line
Adarshb9db4aa5658f
diff --git a/src/app/api/chat/threads/[id]/reply/route.ts b/src/app/api/chat/threads/[id]/reply/route.tsindex 1d64e461..cca18e52 100644--- a/src/app/api/chat/threads/[id]/reply/route.ts+++ b/src/app/api/chat/threads/[id]/reply/route.ts@@ -133,6 +133,7 @@ export async function POST(request: Request, ctx: RouteContext<"/api/chat/threadpending = t;timer ??= setTimeout(flush, 60);},+ onQueue: (position) => send({ type: "queue", position }),},key,);diff --git a/src/components/chat/hooks.ts b/src/components/chat/hooks.tsindex 717d660d..724f646c 100644--- a/src/components/chat/hooks.ts+++ b/src/components/chat/hooks.ts@@ -61,7 +61,7 @@ export function useStartChat() {export type ReplyState =| { phase: "idle" }- | { phase: "waiting" }+ | { phase: "waiting"; position?: number }| { phase: "writing"; text: string }| { phase: "failed"; message: string; code: string; retryAfterS?: number };@@ -138,6 +138,7 @@ export function useReply(threadId: string) {continue;}if (e.type === "user") patch((t) => ({ ...t, messages: [...t.messages.filter((m) => m.id !== temp?.id), e.message] }));+ else if (e.type === "queue") setState((s) => (s.phase === "waiting" ? { phase: "waiting", position: e.position } : s));else if (e.type === "text") {// Only a model that streams sends text on the way; a whole reply comes with done alone.texts++;diff --git a/src/components/chat/thread-view.tsx b/src/components/chat/thread-view.tsxindex 1f709591..8721d33d 100644--- a/src/components/chat/thread-view.tsx+++ b/src/components/chat/thread-view.tsx@@ -247,6 +247,9 @@ export function ThreadView({ id }: { id: string }) {</Bubble>)}</Row>+ {state.phase === "waiting" && state.position !== undefined && state.position > 0 && (+ <p className={cn("mt-1.5 text-[12px] text-muted-foreground", c && "ml-9")}>{state.position === 1 ? "Up next" : `${ordinal(state.position)} in line`}</p>+ )}</li>)}{state.phase === "failed" && (@@ -337,6 +340,8 @@ function Frame({ children }: { children: React.ReactNode }) {return <div className="flex h-content min-w-0 flex-col">{children}</div>;}+const ordinal = (n: number) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : ["th", "st", "nd", "rd"][n % 10] ?? "th"}`;+/** "Today 14:02", "Yesterday 09:10" or "12 Nov 18:30": the label over a run after a long pause. */function stamp(t: number): string {const d = new Date(t);diff --git a/src/lib/chat/prompt.ts b/src/lib/chat/prompt.tsindex 58604301..34ff8034 100644--- a/src/lib/chat/prompt.ts+++ b/src/lib/chat/prompt.ts@@ -98,6 +98,23 @@ export function fitHistory(turns: ChatTurn[], budget: number): { turns: ChatTurnreturn { turns: out, dropped: turns.length - out.length };}+/**+ * Turns as strict chat templates want them (Gemma's): the person first, then strictly taking turns. Back-to-back+ * messages from one side are joined, and a story that opens with the character's greeting gets a short cue before it.+ */+export function alternate(turns: ChatTurn[]): ChatTurn[] {+ const out: ChatTurn[] = [];+ for (const t of turns) {+ const content = t.content.trim();+ if (!content) continue;+ const last = out.at(-1);+ if (last && last.role === t.role) last.content = `${last.content}\n\n${content}`;+ else out.push({ role: t.role, content });+ }+ if (out[0]?.role === "assistant") out.unshift({ role: "user", content: "*The scene begins.*" });+ return out;+}+/*** One text for a model that takes a single message (the free helper before it took chat turns): the history as a* transcript, then the ask to write the next reply.diff --git a/src/server/chat/backend.ts b/src/server/chat/backend.tsindex 7e569d6b..ec13daed 100644--- a/src/server/chat/backend.ts+++ b/src/server/chat/backend.ts@@ -1,9 +1,9 @@import "server-only";-import { fitHistory, summaryAsk, tidyReply, transcript, type ChatTurn } from "@/lib/chat/prompt";+import { alternate, fitHistory, summaryAsk, tidyReply, transcript, type ChatTurn } from "@/lib/chat/prompt";import type { ChatEngine, ChatErrorCode } from "@/lib/chat/types";import { readSse } from "../llm/sse";import { runAsTenant } from "../tenant";-import { askHelper, freeHelperOn, helperKnown, HELPER_LIMITS, type HelperAnswer } from "../text-helper";+import { askHelper, freeHelperOn, helperKnown, HELPER_LIMITS, helperMessagesProblem, type HelperAnswer } from "../text-helper";/*** Where Fuobe Chat's replies come from:@@ -24,8 +24,10 @@ export interface ReplyAsk {image?: { data: Buffer; contentType: string } | null;temperature?: number;signal?: AbortSignal;- /** The reply so far, as it is written (a model that doesn't stream says it once, at the end). */+ /** The reply so far, as it is written (a model that doesn't stream says nothing until the end). */onText?: (soFar: string) => void;+ /** The place in line while the free model is busy with others (1: next). */+ onQueue?: (position: number) => void;}export type ReplyAnswer = { text: string; dropped: number } | { error: ChatErrorCode; message: string; retryAfterS?: number };@@ -50,6 +52,8 @@ export function siteStatus(who: string): { on: boolean; known: boolean } {/** History room for the free helper: its message limit, less the transcript's own words. */const SITE_BUDGET = HELPER_LIMITS.userChars - 600;+/** History room for chat turns on the free helper (its own limit for all turns, with room for joining them). */+const CHAT_BUDGET = HELPER_LIMITS.chatChars - 800;/** History room for a hosted model through the person's key (its context is far larger). */const KEY_BUDGET = 24_000;@@ -60,9 +64,33 @@ function fromHelper(a: Exclude<HelperAnswer, { text: string }>): ReplyAnswer {}async function siteReply(ask: ReplyAsk): Promise<ReplyAnswer> {- const fit = fitHistory(ask.turns, SITE_BUDGET);return asTenant(ask.who, async () => {- if (!freeHelperOn(Date.now(), { vision: !!ask.image })) {+ const vision = !!ask.image;+ // A worker that takes chat turns: the history as real turns, the reply as it's written, the place in line.+ if (freeHelperOn(Date.now(), { chat: true, vision })) {+ const fit = fitHistory(ask.turns, CHAT_BUDGET);+ const messages = alternate(fit.turns);+ if (helperMessagesProblem(messages)) return { error: "failed", message: CHAT_WORDS.failed } as ReplyAnswer;+ const a = await askHelper({+ task: "chat",+ system: ask.system,+ messages,+ sampling: ask.temperature === undefined ? undefined : { temperature: ask.temperature },+ ...(ask.image && { images: [ask.image] }),+ signal: ask.signal,+ onText: (t) => {+ const tidy = tidyReply(t, ask.speaker);+ if (tidy) ask.onText?.(tidy);+ },+ onQueue: ask.onQueue,+ });+ if ("error" in a) return fromHelper(a);+ const text = tidyReply(a.text, ask.speaker);+ return text ? { text, dropped: fit.dropped } : ({ error: "failed", message: CHAT_WORDS.failed } as ReplyAnswer);+ }+ // A worker from before chat turns: one message, the history as a transcript.+ const fit = fitHistory(ask.turns, SITE_BUDGET);+ if (!freeHelperOn(Date.now(), { vision })) {return { error: helperKnown() ? "busy" : "no-model", message: helperKnown() ? CHAT_WORDS.busy : CHAT_WORDS["no-model"] } as ReplyAnswer;}const a = await askHelper({@@ -95,8 +123,9 @@ export async function checkOpenRouterKey(key: string, signal?: AbortSignal): Proasync function keyReply(ask: ReplyAsk, key: { key: string; model: string }): Promise<ReplyAnswer> {const fit = fitHistory(ask.turns, KEY_BUDGET);const messages: unknown[] = [{ role: "system", content: ask.system }];- fit.turns.forEach((t, i) => {- const last = i === fit.turns.length - 1;+ const turns = alternate(fit.turns);+ turns.forEach((t, i) => {+ const last = i === turns.length - 1;if (last && t.role === "user" && ask.image) {messages.push({role: "user",diff --git a/tests/chat.test.ts b/tests/chat.test.tsindex 2c3cdc03..245ca012 100644--- a/tests/chat.test.ts+++ b/tests/chat.test.ts@@ -122,6 +122,20 @@ describe("what the model reads", () => {expect(prompt.makeItHref({ studio: "music", prompt: "lo-fi & rain" })).toBe("/audio/music?prompt=lo-fi%20%26%20rain");});+ it("hands strict chat templates turns that start with the person and take turns", () => {+ const out = prompt.alternate([+ { role: "assistant", content: "*looks up* Hello." },+ { role: "user", content: "Hi" },+ { role: "user", content: "Are you there?" },+ { role: "assistant", content: "" },+ { role: "assistant", content: "Yes." },+ { role: "user", content: "Good." },+ ]);+ expect(out.map((t) => t.role)).toEqual(["user", "assistant", "user", "assistant", "user"]);+ expect(out[2].content).toBe("Hi\n\nAre you there?");+ expect(helper.helperMessagesProblem(out)).toBeNull();+ });+it("names a chat from its first line, and tidies a reply", () => {expect(prompt.titleFrom(" Plan a shoot ")).toBe("Plan a shoot");expect(prompt.titleFrom("word ".repeat(30)).length).toBeLessThanOrEqual(61);@@ -262,6 +276,42 @@ describe("a reply", () => {}});+ it("streams a reply from a chat slot as real turns, with the words as they come", async () => {+ let on = true;+ const seen: { messages?: { role: string; content: string }[]; task: string; system: string }[] = [];+ const slot = (async () => {+ while (on) {+ beat();+ const job = helper.claimHelperJob(workerRow(worker), { model: "test", device: "gpu", chat: true });+ if (!job) {+ await new Promise((r) => setTimeout(r, 20));+ continue;+ }+ seen.push(job as never);+ for (const part of ["Ten", "Ten minutes.", "Ten minutes. Show me"]) {+ helper.partialHelperJob(workerRow(worker), job.id, { lease: job.lease, text: part });+ await new Promise((r) => setTimeout(r, 300));+ }+ helper.finishHelperJob(workerRow(worker), job.id, { lease: job.lease, text: "Ten minutes. Show me what you brought." });+ }+ })();+ try {+ const t = (await (await threadsRoute.POST(req(cookies.a, "/api/chat/threads", "POST", { kind: "character", characterId: "sienna-vale", text: "Hi Sienna" }))).json()) as { id: string };+ const ev = await events(await replyRoute.POST(req(cookies.a, `/api/chat/threads/${t.id}/reply`, "POST", {}), ctx({ id: t.id })));+ const texts = ev.filter((e) => e.type === "text").map((e) => e.text);+ expect(texts.length).toBeGreaterThan(1);+ expect(ev.at(-1)).toMatchObject({ type: "done", message: { content: "Ten minutes. Show me what you brought." } });+ const job = seen.find((j) => j.task === "chat")!;+ // The greeting opens with a cue, then the turns alternate and end with the person's.+ expect(job.messages?.map((m) => m.role)).toEqual(["user", "assistant", "user"]);+ expect(job.messages?.at(-1)?.content).toBe("Hi Sienna");+ expect(job.system).toContain("You are Sienna Vale.");+ } finally {+ on = false;+ await slot;+ }+ });+it("says when the free model is busy, and keeps the person's message for Try again", async () => {db().prepare("DELETE FROM helper_slots").run();const t = (await (await threadsRoute.POST(req(cookies.a, "/api/chat/threads", "POST", { kind: "chat" }))).json()) as { id: string };