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 reply keeps going through a reload and the page follows it to the end
Adarsh9df15935b752
diff --git a/src/app/api/chat/threads/[id]/reply/route.ts b/src/app/api/chat/threads/[id]/reply/route.tsindex 7c8ce5bc..7e7f0159 100644--- a/src/app/api/chat/threads/[id]/reply/route.ts+++ b/src/app/api/chat/threads/[id]/reply/route.ts@@ -7,6 +7,7 @@ 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 { isLive, join, startLive, stopLive } from "@/server/chat/live";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";@@ -37,6 +38,10 @@ export async function POST(request: Request, ctx: RouteContext<"/api/chat/threadconst prefs = getPrefs(v.who);if (thread.mature && !prefs.mature) return Response.json({ error: "This chat is in Mango Chilli mode. Turn it on to carry on.", code: "mature-off" }, { status: 403 });+ // The page opened (or reloaded) while its reply is being written: it joins that reply, never starts a second one.+ const plain = !p.data.text?.trim() && !p.data.image && !p.data.retry && !p.data.edit;+ if (plain && isLive(v.who, id)) return watch(request, v.who, id, null);+// Replies a minute per person, on any engine (the free helper counts its own use too).if (v.who !== "owner") {const r = hit(`chat-reply:${v.who}`, 20, 60_000);@@ -45,6 +50,11 @@ export async function POST(request: Request, ctx: RouteContext<"/api/chat/thread// One reply at a time per person.const 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 });+ // A reply for this chat is on its way (asked from another tab a moment ago): join it.+ if (plain && isLive(v.who, id)) {+ leave();+ return watch(request, v.who, id, null);+ }let userMessage: ChatMessage | null = null;try {@@ -83,76 +93,119 @@ export async function POST(request: Request, ctx: RouteContext<"/api/chat/thread// 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 });+ // 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)) {+ leave();+ const lines: ChatEvent[] = [...(userMessage ? [{ type: "user", message: userMessage } as const] : []), { type: "pending" }];+ return new Response(lines.map((l) => JSON.stringify(l)).join("\n") + "\n", {+ headers: NDJSON,+ });+ }+ // The reply is written apart from this request: a reload or a closed tab doesn't stop it, and it is saved.+ startLive(v.who, id, async (signal, emit) => {+ // Text as it's written, at most every 60 ms (the last always goes).+ let text: string | null = null;+ let timer: ReturnType<typeof setTimeout> | null = null;+ const flush = () => {+ timer = null;+ if (text !== null) emit({ type: "text", text });+ text = null;+ };+ try {+ const answer = await answerThread(v.who, id, {+ from: request,+ signal,+ onText: (t) => {+ text = t;+ timer ??= setTimeout(flush, 60);+ },+ onQueue: (position) => emit({ type: "queue", position }),+ onStatus: (status) => emit({ type: "status", status }),+ });+ if (timer) clearTimeout(timer);+ flush();+ if (signal.aborted) emit({ type: "error", code: "failed", message: "Stopped." });+ else if ("pending" in answer) {+ // Kept: answered as soon as the free model is up, even if the person has left.+ answerLater(v.who, id);+ emit({ type: "pending" });+ } else if ("nothing" in answer) emit({ type: "pending" });+ else if ("error" in answer)+ emit({+ type: "error",+ code: answer.error,+ message: answer.message,+ ...(answer.retryAfterS && { retryAfterS: answer.retryAfterS }),+ });+ else emit({ type: "done", message: answer.message, title: answer.title });+ } catch {+ emit({ type: "error", code: "failed", message: CHAT_WORDS.failed });+ } finally {+ if (timer) clearTimeout(timer);+ leave();+ }+ });+ return watch(request, v.who, id, userMessage);+}++/** Stop: the reply being written ends now and isn't saved; the person's message stays. */+export async function DELETE(request: Request, ctx: RouteContext<"/api/chat/threads/[id]/reply">) {+ const v = chatViewer(request);+ if (!v) return signUp();+ const { id } = await ctx.params;+ if (!getThread(v.who, id)) return gone();+ return Response.json({ stopped: stopLive(v.who, id) });+}++const NDJSON = {+ "Content-Type": "application/x-ndjson; charset=utf-8",+ "Cache-Control": "no-store",+ "X-Accel-Buffering": "no",+};++/**+ * This page's view of the chat's reply, one JSON object per line: the person's message as saved (when this request+ * added one), what has happened so far, then each event until the reply ends. The page leaving stops only the view.+ */+function watch(request: Request, who: string, id: string, userMessage: ChatMessage | null): Response {+ const enc = new TextEncoder();+ let unwatch: (() => void) | null = null;const stream = new ReadableStream<Uint8Array>({- async start(controller) {+ start(controller) {let open = true;- const send = (e: ChatEvent) => {+ const close = () => {if (!open) return;+ open = false;+ unwatch?.();try {- controller.enqueue(enc.encode(`${JSON.stringify(e)}\n`));+ controller.close();} catch {- open = false;+ // Already closed: the person left.}};- // Text as it's written, at most every 60 ms (the last always goes).- let text: string | null = null;- let timer: ReturnType<typeof setTimeout> | null = null;- const flush = () => {- timer = null;- if (text !== null) send({ type: "text", text });- text = null;- };- try {- if (userMessage) send({ type: "user", message: userMessage });- // 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, {- from: request,- signal: abort.signal,- onText: (t) => {- text = t;- timer ??= setTimeout(flush, 60);- },- onQueue: (position) => send({ type: "queue", position }),- onStatus: (status) => send({ type: "status", status }),- });- if (timer) clearTimeout(timer);- flush();- 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 }) });- } else send({ type: "done", message: answer.message, title: answer.title });- } catch {- send({ type: "error", code: "failed", message: CHAT_WORDS.failed });- } finally {- leave();- open = false;+ const send = (e: ChatEvent) => {+ if (!open) return;try {- controller.close();+ controller.enqueue(enc.encode(`${JSON.stringify(e)}\n`));} catch {- // Already closed: the person left.+ open = false;}+ if (e.type === "done" || e.type === "pending" || e.type === "error") queueMicrotask(close);+ };+ if (userMessage) send({ type: "user", message: userMessage });+ unwatch = join(who, id, send);+ // Ended before this page joined: the saved reply, or (still waiting for the free model) the kept message.+ if (!unwatch) {+ const th = getThread(who, id);+ const last = th?.messages.at(-1);+ send(th && last?.role === "assistant" ? { type: "done", message: last, title: th.title } : { type: "pending" });}+ request.signal.addEventListener("abort", close, { once: true });},cancel() {- // The person left: the reply stops; their message stays (and is answered when they come back).- abort.abort();+ unwatch?.();},});-- return new Response(stream, {- headers: { "Content-Type": "application/x-ndjson; charset=utf-8", "Cache-Control": "no-store", "X-Accel-Buffering": "no" },- });+ return new Response(stream, { headers: NDJSON });}diff --git a/src/app/api/chat/threads/[id]/route.ts b/src/app/api/chat/threads/[id]/route.tsindex b160c4fd..a0076246 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 { stopLive } from "@/server/chat/live";import { cancelPending } from "@/server/chat/pending";import { deleteThread, getPrefs, getThread, renameThread, setArchived } from "@/server/chat/store";@@ -41,5 +42,6 @@ export async function DELETE(request: Request, ctx: RouteContext<"/api/chat/threif (!v) return signUp();const { id } = await ctx.params;cancelPending(v.who, id);+ stopLive(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 d6cb8e87..7947fbd8 100644--- a/src/components/chat/hooks.ts+++ b/src/components/chat/hooks.ts@@ -94,8 +94,8 @@ export type ReplyState =export function useReply(threadId: string) {const qc = useQueryClient();const [state, setState] = useState<ReplyState>({ phase: "idle" });- /** The reply that arrived in one piece (no text on the way): the page shows it as if written. */- const [revealId, setRevealId] = useState<string | null>(null);+ /** Replies this page watched being written: they show as they are. Any other reply that arrives while the page is open shows as if written. */+ const [streamedIds, setStreamedIds] = useState<ReadonlySet<string>>(() => new Set());const ctl = useRef<AbortController | null>(null);const patch = useCallback(@@ -133,6 +133,11 @@ export function useReply(threadId: string) {}if (!res.ok || !res.body) {const e = (await res.json().catch(() => ({}))) as { error?: string; code?: string };+ // Answered a moment ago (in another tab, or just before this page asked): the saved chat has the reply.+ if (res.status === 409 && e.code === "nothing") {+ await qc.invalidateQueries({ queryKey: ["chat", "thread", threadId] });+ return setState({ phase: "idle" });+ }// The guest card opens by itself (watchGuestRefusals); the message stays for Try again.responseError(res, new Error(e.error ?? ""));void qc.invalidateQueries({ queryKey: ["chat", "thread", threadId] });@@ -166,6 +171,7 @@ export function useReply(threadId: string) {else if (e.type === "pending") {ended = true;setState({ phase: "pending" });+ void qc.invalidateQueries({ queryKey: ["chat", "thread", threadId] });}else if (e.type === "text") {// Only a model that streams sends text on the way; a whole reply comes with done alone.@@ -174,8 +180,8 @@ export function useReply(threadId: string) {setState({ phase: "writing", text: e.text });} else if (e.type === "done") {ended = true;- if (!streamed) setRevealId(e.message.id);- patch((t) => ({ ...t, title: e.title, messages: [...t.messages, e.message] }));+ if (streamed) setStreamedIds((s) => new Set(s).add(e.message.id));+ patch((t) => ({ ...t, title: e.title, messages: [...t.messages.filter((m) => m.id !== e.message.id), e.message] }));setState({ phase: "idle" });void qc.invalidateQueries({ queryKey: ["chat", "threads"] });} else if (e.type === "error") {@@ -195,10 +201,15 @@ export function useReply(threadId: string) {[patch, qc, threadId],);+ // Stop ends the reply on the server too (leaving the page doesn't: the reply carries on and is saved).const stop = useCallback(() => {ctl.current?.abort();setState({ phase: "idle" });- }, []);+ void fetch(`/api/chat/threads/${threadId}/reply`, { method: "DELETE" }).catch(() => {});+ }, [threadId]);++ /** The kept message has its reply now (the page saw it arrive): nothing is waiting any more. */+ const settle = useCallback(() => setState((s) => (s.phase === "pending" ? { phase: "idle" } : s)), []);- return { state, ask, stop, revealId };+ return { state, ask, stop, settle, streamedIds };}diff --git a/src/components/chat/thread-view.tsx b/src/components/chat/thread-view.tsxindex bac737c9..15b822cc 100644--- a/src/components/chat/thread-view.tsx+++ b/src/components/chat/thread-view.tsx@@ -1,10 +1,10 @@"use client";import { useQueryClient } from "@tanstack/react-query";-import { Archive, ArchiveRestore, ArrowLeft, Check, Copy, MoreHorizontal, Pencil, RotateCcw, Share2, Trash2, X } from "lucide-react";+import { Archive, ArchiveRestore, ArrowDown, 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, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { RailButton } from "@/components/assist/shell";import { PhoneNavButton } from "@/components/nav/phone-nav-button";@@ -38,7 +38,7 @@ import { Markdown, ReplyBody } from "./prose";export function ThreadView({ id }: { id: string }) {const router = useRouter();const qc = useQueryClient();- const { state, ask, stop, revealId: reveal } = useReply(id);+ const { state, ask, stop, settle, streamedIds } = useReply(id);// A kept message: look for its reply until it's here.const view = useChatThread(id, true, state.phase === "pending");const me = useChatMe();@@ -66,21 +66,45 @@ export function ThreadView({ id }: { id: string }) {// Messages that arrive while the page is open animate in; the ones it opened with don't.const [openedAt] = useState(() => Date.now());- // Follow the chat to its end, unless the person scrolled up to read: at once when it opens, smoothly after.+ // The kept message got its reply (it arrived while the page waited): nothing is waiting any more.+ const lastRole = t?.messages.at(-1)?.role;+ useEffect(() => {+ if (state.phase === "pending" && lastRole === "assistant") settle();+ }, [state.phase, lastRole, settle]);++ // Follow the chat to its end while the person is there. Scrolling up by hand lets go; scrolling back down (or the+ // arrow) follows again. Anything that makes the chat taller (a reply being written, a picture loading) keeps the+ // end in view, so a long reply never stops at the reply box.const scroller = useRef<HTMLDivElement>(null);+ const content = useRef<HTMLDivElement>(null);const pinned = useRef(true);- const firstScroll = useRef(true);+ const byHand = useRef(0);+ const [away, setAway] = useState(false);+ const toEnd = useCallback((smooth = false) => {+ const el = scroller.current;+ if (!el) return;+ el.scrollTo({ top: el.scrollHeight, behavior: smooth && !window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "smooth" : "auto" });+ }, []);const streamed = state.phase === "writing" ? state.text.length : 0;useLayoutEffect(() => {- const el = scroller.current;- if (!el || !pinned.current || !t) return;- const instant = firstScroll.current || window.matchMedia("(prefers-reduced-motion: reduce)").matches;- firstScroll.current = false;- el.scrollTo({ top: el.scrollHeight, behavior: instant ? "auto" : "smooth" });- }, [t, t?.messages.length, streamed, state.phase]);+ if (pinned.current) toEnd();+ }, [t, t?.messages.length, streamed, state.phase, toEnd]);+ useEffect(() => {+ const el = content.current;+ if (!el) return;+ const ro = new ResizeObserver(() => {+ if (pinned.current) toEnd();+ });+ ro.observe(el);+ return () => ro.disconnect();+ }, [toEnd]);+ const hand = () => {+ byHand.current = performance.now();+ };const send = async (text: string, image: string | null) => {pinned.current = true;+ setAway(false);// A light tap on phones that have it, as the message goes.navigator.vibrate?.(8);if (editing) {@@ -200,12 +224,20 @@ export function ThreadView({ id }: { id: string }) {<divref={scroller}className="min-h-0 flex-1 overflow-y-auto px-4 sm:px-6"+ onWheel={hand}+ onTouchMove={hand}+ onPointerDown={hand}+ onKeyDown={hand}onScroll={(e) => {const el = e.currentTarget;- pinned.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;+ const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 80;+ // Only the person's own scrolling lets go of the end; the page's own scrolling never does.+ if (atEnd) pinned.current = true;+ else if (performance.now() - byHand.current < 500) pinned.current = false;+ setAway(!pinned.current);}}>- <div className="mx-auto w-full max-w-[760px] py-6">+ <div ref={content} className="mx-auto w-full max-w-[760px] py-6">{c && (<div className="mb-8 flex flex-col items-center text-center"><CharacterFace name={c.name} accent={c.accent} portrait={c.portrait} rounded="card" className="aspect-[3/4] w-32 shadow-strong sm:w-40" />@@ -257,7 +289,7 @@ export function ThreadView({ id }: { id: string }) {first={first}tail={tail}fresh={fresh}- reveal={m.id === reveal}+ reveal={fresh && !streamedIds.has(m.id)}last={m.id === lastAssistant?.id}canRetry={canRetry}onRetry={() => void ask({ retry: true })}@@ -348,7 +380,23 @@ export function ThreadView({ id }: { id: string }) {</div></div>- <div className="shrink-0 px-4 pb-[max(0.75rem,env(safe-area-inset-bottom))] sm:px-6">+ <div className="relative shrink-0 px-4 pb-[max(0.75rem,env(safe-area-inset-bottom))] sm:px-6">+ {away && (+ <button+ type="button"+ onClick={() => {+ pinned.current = true;+ setAway(false);+ toEnd(true);+ }}+ className="absolute -top-12 left-1/2 z-10 grid size-9 -translate-x-1/2 animate-in place-items-center rounded-full border bg-background/90 text-foreground shadow-strong backdrop-blur duration-200 fade-in-0 zoom-in-95 hover:bg-accent"+ aria-label="Go to the latest message"+ title="Go to the latest message"+ >+ <ArrowDown className="size-4" />+ {busy && <span className="absolute -top-0.5 -right-0.5 size-2.5 animate-pulse rounded-full bg-primary motion-reduce:animate-none" aria-hidden />}+ </button>+ )}<div className="mx-auto w-full max-w-[760px]">{editing && (<div className="mb-1.5 flex items-center gap-2 px-2 text-[12.5px] text-muted-foreground">diff --git a/src/server/chat/answer.ts b/src/server/chat/answer.tsindex 2960738b..d8c4364b 100644--- a/src/server/chat/answer.ts+++ b/src/server/chat/answer.ts@@ -78,6 +78,8 @@ export async function answerThread(who: string, id: string, o: AnswerOptions = {},key,);+ // Stopped: nothing of it is saved.+ if (o.signal?.aborted) return { error: "failed", message: "Stopped." };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.diff --git a/src/server/chat/live.ts b/src/server/chat/live.tsnew file mode 100644index 00000000..c74d7ca6--- /dev/null+++ b/src/server/chat/live.ts@@ -0,0 +1,100 @@+import "server-only";+import type { ChatEvent } from "@/lib/chat/types";++/**+ * Replies being written now, one per chat. A reply belongs to the chat, not to the page that asked for it: when the+ * person reloads or leaves, it carries on and is saved. A page that opens the chat meanwhile joins it: it gets the+ * reply so far at once, then the rest as it's written. Only Stop (or a deleted chat) ends a reply early.+ */++type Listener = (e: ChatEvent) => void;++type Live = {+ abort: AbortController;+ listeners: Set<Listener>;+ /** What a page that joins now needs to catch up: the wait (place in line, warming up) and the text so far. */+ position?: number;+ starting?: boolean;+ text?: string;+ /** The last event (done, pending or error): set once the reply has ended. */+ end?: ChatEvent;+};++const lives = new Map<string, Live>();+const keyOf = (who: string, id: string) => `${who}:${id}`;++export const isLive = (who: string, id: string): boolean => {+ const l = lives.get(keyOf(who, id));+ return !!l && !l.end;+};++/**+ * Write a reply for this chat, apart from any one page. `run` gets the reply's signal and `emit`; whatever it emits+ * goes to every page that is watching. The returned function joins the reply, as `join` does.+ */+export function startLive(who: string, id: string, run: (signal: AbortSignal, emit: (e: ChatEvent) => void) => Promise<void>): void {+ const k = keyOf(who, id);+ const live: Live = { abort: new AbortController(), listeners: new Set() };+ lives.set(k, live);+ const emit = (e: ChatEvent) => {+ if (e.type === "queue") live.position = e.position;+ else if (e.type === "status") live.starting = true;+ else if (e.type === "text") {+ // Writing now: the wait is over, and a page that joins shows only the words.+ live.text = e.text;+ live.position = undefined;+ live.starting = undefined;+ } else if (e.type === "done" || e.type === "pending" || e.type === "error") live.end = e;+ for (const l of live.listeners) {+ try {+ l(e);+ } catch {+ live.listeners.delete(l);+ }+ }+ };+ void run(live.abort.signal, emit)+ .catch(() =>+ emit({+ type: "error",+ code: "failed",+ message: "The reply didn't finish. Tap Write it again.",+ }),+ )+ .finally(() => {+ if (!live.end)+ emit({+ type: "error",+ code: "failed",+ message: "The reply didn't finish. Tap Write it again.",+ });+ live.listeners.clear();+ if (lives.get(k) === live) lives.delete(k);+ });+}++/**+ * Watch this chat's reply: first what has happened so far, then each event as it comes. Returns the function that+ * stops watching (the reply carries on), or null when no reply is being written.+ */+export function join(who: string, id: string, listener: Listener): (() => void) | null {+ const live = lives.get(keyOf(who, id));+ if (!live) return null;+ if (live.end) {+ listener(live.end);+ return () => {};+ }+ if (live.position) listener({ type: "queue", position: live.position });+ if (live.starting) listener({ type: "status", status: "starting" });+ if (live.text) listener({ type: "text", text: live.text });+ live.listeners.add(listener);+ return () => live.listeners.delete(listener);+}++/** Stop: the reply ends now and isn't saved. The person's message stays. */+export function stopLive(who: string, id: string): boolean {+ const live = lives.get(keyOf(who, id));+ if (!live || live.end) return false;+ live.abort.abort();+ return true;+}diff --git a/tests/chat.test.ts b/tests/chat.test.tsindex b0209ce1..4cdebc63 100644--- a/tests/chat.test.ts+++ b/tests/chat.test.ts@@ -340,6 +340,130 @@ describe("a reply", () => {}});+ it("keeps writing when the page reloads or closes: the page that opens joins the same reply, and only Stop ends it", async () => {+ let on = true;+ let jobs = 0;+ 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;+ }+ jobs++;+ const words = "One idea at a time, written slowly so a reload lands in the middle of it.".split(" ");+ let gone = false;+ for (let i = 1; i <= words.length && !gone; i++) {+ gone =+ "ok" !==+ helper.partialHelperJob(workerRow(worker), job.id, {+ lease: job.lease,+ text: words.slice(0, i).join(" "),+ });+ await new Promise((r) => setTimeout(r, 120));+ }+ if (!gone)+ helper.finishHelperJob(workerRow(worker), job.id, {+ lease: job.lease,+ text: words.join(" "),+ });+ }+ })();+ const post = (id: string, body: unknown, signal?: AbortSignal) =>+ replyRoute.POST(+ new Request(`http://localhost:3000/api/chat/threads/${id}/reply`, {+ method: "POST",+ headers: {+ cookie: cookies.a,+ host: "localhost:3000",+ "content-type": "application/json",+ },+ body: JSON.stringify(body),+ signal,+ }),+ ctx({ id }),+ );+ /** Read events until `stop` says so; returns them (the stream stays open). */+ const readUntil = async (res: Response, stop: (e: { type: string; [k: string]: unknown }) => boolean) => {+ const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader();+ const got: { type: string; [k: string]: unknown }[] = [];+ let buf = "";+ for (;;) {+ const { value, done } = await reader.read();+ if (done) return got;+ buf += value;+ const lines = buf.split("\n");+ buf = lines.pop()!;+ for (const l of lines.filter(Boolean)) {+ got.push(JSON.parse(l));+ if (stop(got.at(-1)!)) {+ void reader.cancel().catch(() => {});+ return got;+ }+ }+ }+ };+ try {+ const t = (await (+ await threadsRoute.POST(+ req(cookies.a, "/api/chat/threads", "POST", {+ kind: "chat",+ text: "Give me one idea",+ }),+ )+ ).json()) as { id: string };+ // The page reloads part way through the reply.+ const first = new AbortController();+ const before = await readUntil(await post(t.id, {}, first.signal), (e) => e.type === "text" && String(e.text).split(" ").length >= 3);+ first.abort();+ expect(before.at(-1)?.type).toBe("text");+ // The reloaded page asks again: it joins the same reply, starting from the words so far, and no second one starts.+ const after = await events(await post(t.id, {}));+ expect(after[0].type).toBe("text");+ expect(String(after[0].text).split(" ").length).toBeGreaterThanOrEqual(3);+ expect(after.at(-1)).toMatchObject({+ type: "done",+ message: {+ content: "One idea at a time, written slowly so a reload lands in the middle of it.",+ },+ });+ expect(jobs).toBe(1);+ expect(store.getThread(a, t.id)!.messages.map((m) => m.role)).toEqual(["user", "assistant"]);+ // Asked again once it's saved: nothing to answer (the page shows the saved reply), still no second one.+ const late = await post(t.id, {});+ expect(late.status).toBe(409);+ expect(((await late.json()) as { code: string }).code).toBe("nothing");+ expect(jobs).toBe(1);++ // A page closed part way: the reply is still written and saved.+ const closed = new AbortController();+ await readUntil(await post(t.id, { text: "Another?" }, closed.signal), (e) => e.type === "text");+ closed.abort();+ const end = Date.now() + 15_000;+ while (store.getThread(a, t.id)!.messages.length < 4 && Date.now() < end) await new Promise((r) => setTimeout(r, 50));+ expect(store.getThread(a, t.id)!.messages.map((m) => m.role)).toEqual(["user", "assistant", "user", "assistant"]);++ // Stop ends it: nothing of it is saved, the person's message stays.+ const res = await post(t.id, { text: "And one more?" });+ const seenText = readUntil(res, (e) => e.type === "error" || e.type === "done");+ await new Promise((r) => setTimeout(r, 400));+ const stopped = (await (await replyRoute.DELETE(req(cookies.a, `/api/chat/threads/${t.id}/reply`, "DELETE"), ctx({ id: t.id }))).json()) as {+ stopped: boolean;+ };+ expect(stopped.stopped).toBe(true);+ expect((await seenText).at(-1)?.type).toBe("error");+ expect(store.getThread(a, t.id)!.messages.map((m) => m.role)).toEqual(["user", "assistant", "user", "assistant", "user"]);+ } finally {+ on = false;+ await slot;+ }+ });+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 };