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: a message waits for the free model instead of showing an error
Adarsh205b47dc89a9
diff --git a/src/app/api/chat/threads/[id]/reply/route.ts b/src/app/api/chat/threads/[id]/reply/route.tsindex cca18e52..f6d34235 100644--- a/src/app/api/chat/threads/[id]/reply/route.ts+++ b/src/app/api/chat/threads/[id]/reply/route.ts@@ -1,11 +1,12 @@import { z } from "zod";import { CHAT_LIMITS } from "@/lib/chat/catalog";-import { systemPrompt, type ChatTurn } from "@/lib/chat/prompt";-import type { ChatEvent } from "@/lib/chat/types";-import { chatReply, CHAT_WORDS, summarize } from "@/server/chat/backend";-import { ownPicture, readPicture } from "@/server/chat/files";+import type { ChatEvent, ChatMessage } from "@/lib/chat/types";+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 { addMessage, chatKey, dropLastReply, getPrefs, getThread, rewindTo, setSummary, threadMemory, threadTurns } from "@/server/chat/store";+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";const Post = z.object({@@ -18,15 +19,10 @@ const Post = z.object({edit: z.string().max(60).nullish(),});-const TEMPERATURE = { chat: 0.7, ideas: 0.95, write: 0.7, character: 1.0, play: 1.0 } as const;--/** A summary is brought up to date once this many turns have fallen out of what the model sees. */-const SUMMARY_EVERY = 6;-/**- * Answer in a chat. The answer streams as one JSON object per line (ChatEvent): the person's message as saved, the- * reply as it is written, then the saved reply, or what went wrong. The person's message stays when a reply fails, so- * Try again answers it.+ * Answer in a chat. The answer streams as one JSON object per line (ChatEvent): the person's message as saved, how the+ * wait goes (starting up, the place in line), the reply as it is written, then the saved reply. When the free model+ * isn't up in time, the person's message stays and is answered later ("pending"): never an error for that.*/export async function POST(request: Request, ctx: RouteContext<"/api/chat/threads/[id]/reply">) {const v = chatViewer(request);@@ -48,7 +44,7 @@ export async function POST(request: Request, ctx: RouteContext<"/api/chat/threadconst leave = v.who === "owner" ? () => {} : enter(`chat-replying:${v.who}`, 1);if (!leave) return Response.json({ error: "A reply is still being written. Wait for it, then send again.", code: "busy" }, { status: 409 });- let userMessage = null;+ let userMessage: ChatMessage | null = null;try {const text = p.data.text?.trim() ?? "";const image = p.data.image ? ownPicture(v.who, p.data.image) : null;@@ -63,44 +59,20 @@ export async function POST(request: Request, ctx: RouteContext<"/api/chat/threadconst status = (e as { status?: number }).status;return status ? Response.json({ error: (e as Error).message }, { status }) : refused(e);}-- const turns = threadTurns(v.who, id);- const last = turns.at(-1);- if (!last || last.role !== "user") {+ if (threadTurns(v.who, id).at(-1)?.role !== "user") {leave();return Response.json({ error: "There's nothing to answer yet.", code: "nothing" }, { status: 409 });}- const memory = threadMemory(v.who, id);- const character = thread.characterCard;- const speaker = character?.name ?? "You";- const system = systemPrompt({ kind: thread.kind, character, tool: thread.tool, play: thread.play, mature: prefs.mature, summary: memory?.summary });- // What the model reads: the summary covers turns up to summary_upto; a picture-only turn says so in words.- const asTurn = (m: (typeof turns)[number]): ChatTurn => ({ role: m.role, content: m.content || (m.image ? "(sent a picture)" : "") });- const visible = turns.filter((m) => m.seq > (memory?.upto ?? 0)).map(asTurn);- const picture = last.image ? await readPicture(v.who, last.image) : null;- const key = prefs.engine === "key" ? chatKey(v.who) : null;+ // Their own key answers now: it doesn't wait with the free model.+ if (prefs.engine === "key") cancelPending(v.who, id);const enc = new TextEncoder();const abort = new AbortController();request.signal.addEventListener("abort", () => abort.abort(), { once: true });- let released = false;- const release = () => {- if (!released) leave();- released = true;- };-const stream = new ReadableStream<Uint8Array>({async start(controller) {let open = true;- const close = () => {- open = false;- try {- controller.close();- } catch {- // Already closed: the person left.- }- };const send = (e: ChatEvent) => {if (!open) return;try {@@ -110,64 +82,54 @@ export async function POST(request: Request, ctx: RouteContext<"/api/chat/thread}};// Text as it's written, at most every 60 ms (the last always goes).- let pending: string | null = null;+ let text: string | null = null;let timer: ReturnType<typeof setTimeout> | null = null;const flush = () => {timer = null;- if (pending !== null) send({ type: "text", text: pending });- pending = null;+ if (text !== null) send({ type: "text", text });+ text = null;};try {if (userMessage) send({ type: "user", message: userMessage });- const answer = await chatReply(- prefs.engine,- {- who: v.who,- system,- turns: visible,- speaker,- image: picture,- temperature: TEMPERATURE[thread.kind],- signal: abort.signal,- onText: (t) => {- pending = t;- timer ??= setTimeout(flush, 60);- },- onQueue: (position) => send({ type: "queue", position }),+ // Already waiting for the free model: that answer comes here when it's ready (with this message too).+ if (prefs.engine !== "key" && isPending(v.who, id)) {+ send({ type: "pending" });+ return;+ }+ const answer = await answerThread(v.who, id, {+ signal: abort.signal,+ onText: (t) => {+ text = t;+ timer ??= setTimeout(flush, 60);},- key,- );+ onQueue: (position) => send({ type: "queue", position }),+ onStatus: (status) => send({ type: "status", status }),+ });if (timer) clearTimeout(timer);flush();- if ("error" in answer) {+ if ("pending" in answer) {+ // Kept: answered as soon as the free model is up, even if the person has left.+ answerLater(v.who, id);+ send({ type: "pending" });+ } else if ("nothing" in answer) {+ send({ type: "pending" });+ } else if ("error" in answer) {send({ type: "error", code: answer.error, message: answer.message, ...(answer.retryAfterS && { retryAfterS: answer.retryAfterS }) });- return;- }- const saved = addMessage(v.who, id, "assistant", answer.text);- send({ type: "done", message: saved, title: getThread(v.who, id)?.title ?? thread.title });- release();- close();- // Keep a long chat coherent: once enough turns have fallen out of view, fold them into the summary (after- // the reply is out, so the person can carry on meanwhile).- if (answer.dropped >= SUMMARY_EVERY) {- const fold = threadTurns(v.who, id)- .filter((m) => m.seq > (memory?.upto ?? 0))- .slice(0, answer.dropped);- const upto = fold.at(-1)?.seq;- if (upto) {- const s = await summarize(v.who, memory?.summary ?? null, fold.map(asTurn), speaker, key).catch(() => null);- if (s) setSummary(v.who, id, s, upto);- }- }+ } else send({ type: "done", message: answer.message, title: answer.title });} catch {send({ type: "error", code: "failed", message: CHAT_WORDS.failed });} finally {- release();- close();+ leave();+ open = false;+ try {+ controller.close();+ } catch {+ // Already closed: the person left.+ }}},cancel() {- // The person left: the reply stops; what was sent before stays.+ // The person left: the reply stops; their message stays (and is answered when they come back).abort.abort();},});diff --git a/src/app/api/chat/threads/[id]/route.ts b/src/app/api/chat/threads/[id]/route.tsindex 38dabfd1..979c4d75 100644--- a/src/app/api/chat/threads/[id]/route.ts+++ b/src/app/api/chat/threads/[id]/route.ts@@ -1,6 +1,7 @@import { connection } from "next/server";import { z } from "zod";import { body, chatViewer, gone, refused, signUp, tooOften } from "@/server/chat/http";+import { cancelPending } from "@/server/chat/pending";import { deleteThread, getPrefs, getThread, renameThread } from "@/server/chat/store";/** One of the person's chats with its messages (another's reads as gone). */@@ -36,5 +37,6 @@ export async function DELETE(request: Request, ctx: RouteContext<"/api/chat/threconst v = chatViewer(request);if (!v) return signUp();const { id } = await ctx.params;+ cancelPending(v.who, id);return deleteThread(v.who, id) ? Response.json({ ok: true }) : gone();}diff --git a/src/components/chat/hooks.ts b/src/components/chat/hooks.tsindex 724f646c..bff02e58 100644--- a/src/components/chat/hooks.ts+++ b/src/components/chat/hooks.ts@@ -32,8 +32,16 @@ export function useCharacters(enabled = true) {return useQuery({ queryKey: ["chat", "characters"], queryFn: async () => json<{ items: CharacterCard[] }>(await fetch("/api/chat/characters")), staleTime: 30_000, enabled });}-export function useChatThread(id: string, enabled = true) {- return useQuery({ queryKey: ["chat", "thread", id], queryFn: async () => json<ChatThreadView>(await fetch(`/api/chat/threads/${id}`)), staleTime: 0, enabled, retry: false });+/** One chat. `poll`: look for a reply that's coming later (a message kept until the free model is ready). */+export function useChatThread(id: string, enabled = true, poll = false) {+ return useQuery({+ queryKey: ["chat", "thread", id],+ queryFn: async () => json<ChatThreadView>(await fetch(`/api/chat/threads/${id}`)),+ staleTime: 0,+ enabled,+ retry: false,+ refetchInterval: poll ? 6_000 : false,+ });}export interface StartChat {@@ -61,7 +69,9 @@ export function useStartChat() {export type ReplyState =| { phase: "idle" }- | { phase: "waiting"; position?: number }+ | { phase: "waiting"; position?: number; starting?: boolean }+ /** Kept: the reply comes here as soon as the free model is ready (the page looks for it meanwhile). */+ | { phase: "pending" }| { phase: "writing"; text: string }| { phase: "failed"; message: string; code: string; retryAfterS?: number };@@ -139,6 +149,11 @@ export function useReply(threadId: string) {}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 === "status") setState((s) => (s.phase === "waiting" ? { phase: "waiting", starting: true } : s));+ else if (e.type === "pending") {+ ended = true;+ setState({ phase: "pending" });+ }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 8721d33d..3cf63c08 100644--- a/src/components/chat/thread-view.tsx+++ b/src/components/chat/thread-view.tsx@@ -33,10 +33,12 @@ import { Markdown, ReplyBody } from "./prose";export function ThreadView({ id }: { id: string }) {const router = useRouter();const qc = useQueryClient();- const view = useChatThread(id);- const me = useChatMe();const { state, ask, stop, revealId: reveal } = useReply(id);+ // A kept message: look for its reply until it's here.+ const view = useChatThread(id, true, state.phase === "pending");+ const me = useChatMe();const t = view.data;+ const waitingForLater = state.phase === "pending" && t?.messages.at(-1)?.role === "user";const [sharing, setSharing] = useState(false);const [settings, setSettings] = useState(false);const [chilli, setChilli] = useState(false);@@ -247,11 +249,40 @@ 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>+ {state.phase === "waiting" && (state.starting || (state.position ?? 0) > 0) && (+ <p className={cn("mt-1.5 text-[12px] text-muted-foreground", c && "ml-9")}>+ {state.starting && !state.position ? "Starting up…" : state.position === 1 ? "Up next" : `${(state.position ?? 1) - 1} ahead of you`}+ </p>)}</li>)}+ {waitingForLater && (+ <li className="mt-4 animate-in duration-300 fade-in-0">+ <div className={cn("flex flex-wrap items-center gap-x-3 gap-y-2 text-[13px] text-muted-foreground", c && "ml-9")} role="status">+ <span className="inline-flex items-center gap-2">+ <span className="size-1.5 animate-pulse rounded-full bg-primary motion-reduce:animate-none" aria-hidden />+ We'll answer here as soon as it's ready.+ </span>+ {me.data?.key && me.data.engine === "site" && (+ <Button+ size="sm"+ variant="secondary"+ className="h-7 rounded-full"+ onClick={async () => {+ try {+ qc.setQueryData(["chat", "me"], await chatSend("/api/chat/me", "PATCH", { engine: "key" }));+ await ask({});+ } catch (e) {+ toastError(e);+ }+ }}+ >+ Answer with my model+ </Button>+ )}+ </div>+ </li>+ )}{state.phase === "failed" && (<li className="mt-5 animate-in duration-200 fade-in-0"><div className="flex flex-wrap items-center gap-3 rounded-2xl border bg-muted/40 p-3.5 text-[14px]">@@ -340,7 +371,6 @@ 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 {diff --git a/src/lib/chat/types.ts b/src/lib/chat/types.tsindex 68962113..dd538cf3 100644--- a/src/lib/chat/types.ts+++ b/src/lib/chat/types.ts@@ -52,6 +52,10 @@ export interface ChatMe {export type ChatEvent =| { type: "user"; message: ChatMessage }| { type: "queue"; position: number }+ /** The free model is starting up: the reply is still coming. */+ | { type: "status"; status: "starting" }+ /** The message is kept and answered here as soon as the free model is ready. */+ | { type: "pending" }| { type: "text"; text: string }| { type: "done"; message: ChatMessage; title: string }| { type: "error"; code: ChatErrorCode; message: string; retryAfterS?: number };diff --git a/src/server/chat/answer.ts b/src/server/chat/answer.tsnew file mode 100644index 00000000..aa41d58f--- /dev/null+++ b/src/server/chat/answer.ts@@ -0,0 +1,79 @@+import "server-only";+import { systemPrompt, type ChatTurn } from "@/lib/chat/prompt";+import type { ChatErrorCode, ChatMessage } from "@/lib/chat/types";+import { chatReply, summarize } from "./backend";+import { readPicture } from "./files";+import { addMessage, chatKey, getPrefs, getThread, setSummary, threadMemory, threadTurns } from "./store";++/**+ * Write the reply to a chat's last message (the person's) and save it. Used by the reply route, which streams it, and+ * by the retry that answers later when the free model was starting up (src/server/chat/pending.ts).+ */++const TEMPERATURE = { chat: 0.7, ideas: 0.95, write: 0.7, character: 1.0, play: 1.0 } as const;++/** A summary is brought up to date once this many turns have fallen out of what the model sees. */+const SUMMARY_EVERY = 6;++export type AnswerResult =+ | { message: ChatMessage; title: string }+ /** The free model didn't come up in time: the message waits, and is answered later. */+ | { pending: true }+ /** Nothing to answer: the last message isn't the person's (answered meanwhile, or none). */+ | { nothing: true }+ | { error: ChatErrorCode; message: string; retryAfterS?: number };++export interface AnswerOptions {+ signal?: AbortSignal;+ /** How long the free model may take to come up and take the turn. */+ waitMs?: number;+ onText?: (soFar: string) => void;+ onQueue?: (position: number) => void;+ onStatus?: (status: "starting") => void;+}++export async function answerThread(who: string, id: string, o: AnswerOptions = {}): Promise<AnswerResult> {+ const thread = getThread(who, id);+ if (!thread) return { error: "failed", message: "That chat is gone." };+ const prefs = getPrefs(who);+ if (thread.mature && !prefs.mature) return { error: "blocked", message: "This chat is in Mango Chilli mode. Turn it on to carry on." };+ const turns = threadTurns(who, id);+ const last = turns.at(-1);+ if (!last || last.role !== "user") return { nothing: true };+ const memory = threadMemory(who, id);+ const character = thread.characterCard;+ const speaker = character?.name ?? "You";+ const system = systemPrompt({ kind: thread.kind, character, tool: thread.tool, play: thread.play, mature: prefs.mature, summary: memory?.summary });+ // What the model reads: the summary covers turns up to summary_upto; a picture-only turn says so in words.+ const asTurn = (m: (typeof turns)[number]): ChatTurn => ({ role: m.role, content: m.content || (m.image ? "(sent a picture)" : "") });+ const visible = turns.filter((m) => m.seq > (memory?.upto ?? 0)).map(asTurn);+ const picture = last.image ? await readPicture(who, last.image) : null;+ const key = prefs.engine === "key" ? chatKey(who) : null;++ const answer = await chatReply(+ prefs.engine,+ { who, system, turns: visible, speaker, image: picture, temperature: TEMPERATURE[thread.kind], signal: o.signal, waitMs: o.waitMs, onText: o.onText, onQueue: o.onQueue, onStatus: o.onStatus },+ key,+ );+ if ("pending" in answer) return { pending: true };+ if ("error" in answer) return answer;+ // Answered meanwhile (a retry and the person's own visit): keep the first answer only.+ const now = threadTurns(who, id).at(-1);+ if (!now || now.role !== "user") return { nothing: true };+ const saved = addMessage(who, id, "assistant", answer.text);++ // Keep a long chat coherent: once enough turns have fallen out of view, fold them into the summary (after the reply+ // is saved, so the person can carry on meanwhile).+ if (answer.dropped >= SUMMARY_EVERY) {+ const fold = threadTurns(who, id)+ .filter((m) => m.seq > (memory?.upto ?? 0))+ .slice(0, answer.dropped);+ const upto = fold.at(-1)?.seq;+ if (upto) {+ void summarize(who, memory?.summary ?? null, fold.map(asTurn), speaker, key)+ .then((s) => s && setSummary(who, id, s, upto))+ .catch(() => {});+ }+ }+ return { message: saved, title: getThread(who, id)?.title ?? thread.title };+}diff --git a/src/server/chat/backend.ts b/src/server/chat/backend.tsindex ec13daed..053d493a 100644--- a/src/server/chat/backend.ts+++ b/src/server/chat/backend.ts@@ -28,17 +28,25 @@ export interface ReplyAsk {onText?: (soFar: string) => void;/** The place in line while the free model is busy with others (1: next). */onQueue?: (position: number) => void;+ /** The free model is starting up (or every slot is taken): the reply is still coming. */+ onStatus?: (status: "starting") => void;+ /** How long to wait for the free model before keeping the message for later (SITE_WAIT_MS). */+ waitMs?: number;}-export type ReplyAnswer = { text: string; dropped: number } | { error: ChatErrorCode; message: string; retryAfterS?: number };+export type ReplyAnswer =+ | { text: string; dropped: number }+ /** The free model didn't come up in time: the message is kept and answered later. */+ | { pending: true }+ | { error: ChatErrorCode; message: string; retryAfterS?: number };export const CHAT_WORDS: Record<ChatErrorCode, string> = {- busy: "The free chat model is busy or resting right now. Try again in a moment.",+ busy: "We'll answer here as soon as it's ready.",limit: "That's a lot of messages in a short time. Take a breather and try again soon.",blocked: "This message can't be answered here.",failed: "The reply didn't finish. Try again.","sign-in": "Create a free account to chat.",- "no-model": "The free chat model isn't switched on here yet. Add your own OpenRouter key in chat settings to chat now.",+ "no-model": "We'll answer here as soon as it's ready.","key-refused": "OpenRouter didn't accept your key. Check it in chat settings.","too-long": "This chat is as long as a chat can be. Start a new one to keep going.",};@@ -63,48 +71,74 @@ function fromHelper(a: Exclude<HelperAnswer, { text: string }>): ReplyAnswer {return { error: code, message, ...(a.retryAfterS ? { retryAfterS: a.retryAfterS } : {}) };}-async function siteReply(ask: ReplyAsk): Promise<ReplyAnswer> {- return asTenant(ask.who, async () => {- 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;- }+/** How long a reply waits for the free model to come up before the message is kept for later. */+export const SITE_WAIT_MS = Number(process.env.FUOBE_CHAT_WAIT_MS) || 120_000;++const nap = (ms: number, signal?: AbortSignal) =>+ new Promise<void>((resolve) => {+ const t = setTimeout(resolve, ms);+ signal?.addEventListener(+ "abort",+ () => {+ clearTimeout(t);+ resolve();+ },+ { once: true },+ );+ });++/** One try on the free model: chat turns on a worker that takes them, else the history as one transcript. */+async function siteTry(ask: ReplyAsk, waitMs: number): Promise<ReplyAnswer | "busy"> {+ const vision = !!ask.image;+ 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 };const a = await askHelper({- task: "write",+ task: "chat",system: ask.system,- user: transcript(fit.turns, ask.speaker),+ messages,+ sampling: ask.temperature === undefined ? undefined : { temperature: ask.temperature },...(ask.image && { images: [ask.image] }),signal: ask.signal,+ waitMs,+ onText: (t) => {+ const tidy = tidyReply(t, ask.speaker);+ if (tidy) ask.onText?.(tidy);+ },+ onQueue: ask.onQueue,});- if ("error" in a) return fromHelper(a);+ if ("error" in a) return a.error === "busy" ? "busy" : fromHelper(a);const text = tidyReply(a.text, ask.speaker);- if (!text) return { error: "failed", message: CHAT_WORDS.failed } as ReplyAnswer;- // Whole, with no text on the way: the browser shows it as if written.- return { text, dropped: fit.dropped };+ return text ? { text, dropped: fit.dropped } : { error: "failed", message: CHAT_WORDS.failed };+ }+ if (!freeHelperOn(Date.now(), { vision })) return "busy";+ const fit = fitHistory(ask.turns, SITE_BUDGET);+ const a = await askHelper({ task: "write", system: ask.system, user: transcript(fit.turns, ask.speaker), ...(ask.image && { images: [ask.image] }), signal: ask.signal, waitMs });+ if ("error" in a) return a.error === "busy" ? "busy" : fromHelper(a);+ const text = tidyReply(a.text, ask.speaker);+ // Whole, with no text on the way: the browser shows it as if written.+ return text ? { text, dropped: fit.dropped } : { error: "failed", message: CHAT_WORDS.failed };+}++/**+ * A reply from the free model. While it starts up (a worker restarting for an update) or every slot is taken, this+ * keeps waiting and asking again, saying "starting" meanwhile; past `waitMs` the message is kept for later (pending),+ * never shown as an error.+ */+async function siteReply(ask: ReplyAsk): Promise<ReplyAnswer> {+ return asTenant(ask.who, async () => {+ const deadline = Date.now() + (ask.waitMs ?? SITE_WAIT_MS);+ for (;;) {+ if (ask.signal?.aborted) return { error: "failed", message: CHAT_WORDS.failed } as ReplyAnswer;+ const left = deadline - Date.now();+ if (left <= 0) return { pending: true } as ReplyAnswer;+ const r = await siteTry(ask, Math.max(5_000, Math.min(45_000, left)));+ if (r !== "busy") return r;+ if (Date.now() >= deadline) return { pending: true } as ReplyAnswer;+ ask.onStatus?.("starting");+ await nap(2_500, ask.signal);+ }});}diff --git a/src/server/chat/pending.ts b/src/server/chat/pending.tsnew file mode 100644index 00000000..ea207a5a--- /dev/null+++ b/src/server/chat/pending.ts@@ -0,0 +1,66 @@+import "server-only";+import { enter } from "../rate";+import { answerThread } from "./answer";++/**+ * Chats waiting for the free model to come up: the person's message is kept, and this answers it as soon as the model+ * takes turns again (the page shows it when it arrives). One retry per chat, in this server; after a restart the chat+ * page asks again when it's opened, since its last message is still the person's.+ */++const RETRY_EVERY_MS = Number(process.env.FUOBE_CHAT_RETRY_MS) || 10_000;+const KEEP_TRYING_MS = 6 * 60 * 60_000;+const loops = new Map<string, AbortController>();+const keyOf = (who: string, id: string) => `${who}:${id}`;++export const isPending = (who: string, id: string): boolean => loops.has(keyOf(who, id));++/** Stop waiting for one chat (the person answers with their own key, or deletes the chat). */+export function cancelPending(who: string, id: string): void {+ const k = keyOf(who, id);+ loops.get(k)?.abort();+ loops.delete(k);+}++const nap = (ms: number, signal: AbortSignal) =>+ new Promise<void>((resolve) => {+ const t = setTimeout(resolve, ms);+ signal.addEventListener(+ "abort",+ () => {+ clearTimeout(t);+ resolve();+ },+ { once: true },+ );+ });++/** Answer this chat's last message once the free model is up (at most one retry per chat). */+export function answerLater(who: string, id: string): void {+ const k = keyOf(who, id);+ if (loops.has(k)) return;+ const ac = new AbortController();+ loops.set(k, ac);+ void (async () => {+ const end = Date.now() + KEEP_TRYING_MS;+ try {+ while (!ac.signal.aborted && Date.now() < end) {+ await nap(RETRY_EVERY_MS, ac.signal);+ if (ac.signal.aborted) return;+ // One reply at a time per person: a reply the person asked for goes first.+ const leave = who === "owner" ? () => {} : enter(`chat-replying:${who}`, 1);+ if (!leave) continue;+ try {+ const r = await answerThread(who, id, { signal: ac.signal, waitMs: 45_000 });+ if (!("pending" in r)) return;+ } catch {+ // A failure this time: the next round tries again.+ } finally {+ leave();+ }+ }+ } finally {+ if (loops.get(k) === ac) loops.delete(k);+ }+ })();+}diff --git a/tests/chat.test.ts b/tests/chat.test.tsindex 0107026c..9daefb7b 100644--- a/tests/chat.test.ts+++ b/tests/chat.test.ts@@ -15,6 +15,9 @@ process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:7";process.env.FUOBE_PUBLIC_SIGNUP = "1";process.env.FUOBE_HOSTED_RUNS = "1";+// Short waits for the free model here (the site waits about two minutes, then retries every 10 s).+process.env.FUOBE_CHAT_WAIT_MS = "800";+process.env.FUOBE_CHAT_RETRY_MS = "150";delete process.env.FUOBE_PASSWORD;delete process.env.FUOBE_MODERATION_URL;@@ -320,14 +323,30 @@ describe("a reply", () => {}});- it("says when the free model is busy, and keeps the person's message for Try again", async () => {+ it("never shows an error while the free model starts up: the message waits and is answered when it's ready", 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 };const ev = await events(await replyRoute.POST(req(cookies.a, `/api/chat/threads/${t.id}/reply`, "POST", { text: "Hello?" }), ctx({ id: t.id })));expect(ev[0].type).toBe("user");- expect(ev.at(-1)).toMatchObject({ type: "error" });- expect(["busy", "no-model"]).toContain(ev.at(-1)?.code);+ expect(ev.some((e) => e.type === "status" && e.status === "starting")).toBe(true);+ expect(ev.some((e) => e.type === "error")).toBe(false);+ expect(ev.at(-1)?.type).toBe("pending");expect(store.getThread(a, t.id)!.messages.map((m) => m.role)).toEqual(["user"]);+ // Asking again meanwhile doesn't start a second wait: it says the answer is on its way.+ const again = await events(await replyRoute.POST(req(cookies.a, `/api/chat/threads/${t.id}/reply`, "POST", {}), ctx({ id: t.id })));+ expect(again.map((e) => e.type)).toEqual(["pending"]);+ // The model comes up: the kept message is answered by itself, with nobody asking again.+ const slot = standIn(() => "Hello! I'm here.");+ try {+ const end = Date.now() + 15_000;+ while (store.getThread(a, t.id)!.messages.length < 2 && Date.now() < end) await new Promise((r) => setTimeout(r, 100));+ expect(store.getThread(a, t.id)!.messages.map((m) => [m.role, m.content])).toEqual([+ ["user", "Hello?"],+ ["assistant", "Hello! I'm here."],+ ]);+ } finally {+ await slot.stop();+ }});});