The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(chat): a late frame no longer overwrites the error or the closing line
purple8be94ee6a930
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex be3bc825..8f90cc49 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -1,4 +1,5 @@import { useRef, useState, useCallback, useEffect } from 'react'+import { frameFlush } from '../lib/frame-flush'import { markCannotThink } from '../lib/model-compatibility'import {type ApprovalEntry,@@ -1163,21 +1164,19 @@ export function useAgentChat() {runState.thinking = ''runState.blocks = []- let frameScheduled = false+ // Closed at the final write and in the catch, so a late frame never lands+ // on the closing line or the error (lib/frame-flush).+ const frames = frameFlush()function scheduleUIUpdate() {- if (!frameScheduled) {- frameScheduled = true- requestAnimationFrame(() => {- const cId = convId!- const mId = assistantMessage.id- useChatStore.getState().updateMessageContent(cId, mId, runState.content)- if (runState.thinking) {- useChatStore.getState().updateMessageThinking(cId, mId, runState.thinking)- }- frameScheduled = false- })- }+ frames.schedule(() => {+ const cId = convId!+ const mId = assistantMessage.id+ useChatStore.getState().updateMessageContent(cId, mId, runState.content)+ if (runState.thinking) {+ useChatStore.getState().updateMessageThinking(cId, mId, runState.thinking)+ }+ })}// Phase 6: lock in the start-of-turn timestamp so the in-turn cache@@ -2800,12 +2799,14 @@ export function useAgentChat() {}// Final store update+ frames.close()useChatStore.getState().updateMessageContent(convId!, assistantMessage.id, runState.content)if (runState.thinking) {useChatStore.getState().updateMessageThinking(convId!, assistantMessage.id, runState.thinking)}} catch (err) {+ frames.close()if ((err as Error).name !== 'AbortError') {const errorMsg = errorText(err) || 'Connection failed'// Bug B3 round 2: a refusal that produced nothing at all (the model'sdiff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex cca10b86..bd57b1d1 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -1,4 +1,5 @@import { useState, useCallback } from "react"+import { frameFlush } from '../lib/frame-flush'import { sendWindowFor } from '../lib/send-window'import { markCannotThink } from '../lib/model-compatibility'import { v4 as uuid } from "uuid"@@ -140,7 +141,7 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],let thinkingAcc = ''let inThink = falselet discardBuf = ''- let frameScheduled = false+ const frames = frameFlush()let groupFinish: string | undefined// A model's own lines are untagged; a "[other-model]" tag in its OWN reply is// it speaking for someone else, which v1 must not show.@@ -216,17 +217,16 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],}}}- if ((chunk.content || (chunk.thinking && keepThinking)) && !frameScheduled) {- frameScheduled = true- requestAnimationFrame(() => {+ if (chunk.content || (chunk.thinking && keepThinking)) {+ frames.schedule(() => {useChatStore.getState().updateMessageContent(convId, assistantMessage.id, stripImpersonatedSpeakers(stripNonCanonicalTags(contentAcc), others))if (keepThinking && thinkingAcc) {useChatStore.getState().updateMessageThinking(convId, assistantMessage.id, thinkingAcc)}- frameScheduled = false})}if (chunk.done) {+ frames.close()if (chunk.finishReason) groupFinish = chunk.finishReason// Same settlement as every other path (2.6.7 Denk-Audit): the state// machine above only fires on a literal `<think>`, and a Qwen3@@ -253,6 +253,7 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],}}}+ frames.close()if (!abort.signal.aborted && !contentAcc.trim()) {// Empty turn: say WHY, length-aware, not a flat "didn't return an answer".// The bubble already labels the speaker, so no model prefix here.@@ -263,6 +264,7 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],)}} catch (err) {+ frames.close()if ((err as Error).name !== 'AbortError') {syncOllamaHealthFromError(err)// Bug B3 round 2: a group round on a strict template used to paste the@@ -1064,6 +1066,8 @@ export function useChat() {// above. `convId` is fixed at this point: the `if (!convId)` branch above// already resolved it to a real string.const run: ChatRun = { convId, content: "", thinking: "", isThinking: false, discardedThinkBuf: "" }+ // Before the try, so the catch can close it (lib/frame-flush).+ const frames = frameFlush()try {// ── Multi-Provider: resolve provider for active model ──@@ -1177,7 +1181,6 @@ export function useChat() {const stream = createStreamWithFallback()- let frameScheduled = falselet firstChunk = true// Thinking visibility is driven by the toggle. When OFF, we still// have to parse <think>…</think> so the state-machine closes@@ -1258,9 +1261,8 @@ export function useChat() {// the reasoning-only phase too (cloud reasoners stream all their// thinking before the first answer token; previously the flush only// ran on content chunks and the chat sat in dead air).- if ((chunk.content || (chunk.thinking && keepThinking)) && !frameScheduled) {- frameScheduled = true- requestAnimationFrame(() => {+ if (chunk.content || (chunk.thinking && keepThinking)) {+ frames.schedule(() => {const cId = run.convIdconst mId = assistantMessage.id// Always strip non-canonical thinking markers (Gemma channel@@ -1273,11 +1275,11 @@ export function useChat() {if (keepThinking && run.thinking) {useChatStore.getState().updateMessageThinking(cId, mId, run.thinking)}- frameScheduled = false})}if (chunk.done) {+ frames.close()if (chunk.finishReason) {finishReason = chunk.finishReasonuseChatStore.getState().updateMessageFinishReason(run.convId, assistantMessage.id, chunk.finishReason)@@ -1317,6 +1319,9 @@ export function useChat() {}}}+ // A stream can end without a done chunk; the lines below write the+ // bubble directly and a late frame must not land on top of them.+ frames.close()// Thought-only completion: the model reasoned and then STOPPED without// a single visible token (gemma4 primed by remembered tool results does@@ -1362,6 +1367,7 @@ export function useChat() {}}} catch (err) {+ frames.close()if ((err as Error).name !== "AbortError") {// Bug C — translate Ollama provider errors into health-store// updates so the header chip + top banner light up reactively.diff --git a/src/lib/__tests__/a-late-frame-does-not-overwrite-the-error.test.ts b/src/lib/__tests__/a-late-frame-does-not-overwrite-the-error.test.tsnew file mode 100644index 00000000..7aa89cf0--- /dev/null+++ b/src/lib/__tests__/a-late-frame-does-not-overwrite-the-error.test.ts@@ -0,0 +1,86 @@+/**+ * Bug hunt 01.10.2026 (H2). The streamed text was written from a+ * requestAnimationFrame callback that was never taken back. The error line+ * (the stall message included) and the empty-answer explanation are written+ * directly, and a frame still pending then put the partial text back on top.+ * A hidden tab runs no frames until it is shown, so there the late frame was+ * certain to win.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { frameFlush } from '../frame-flush'++let queue: Map<number, FrameRequestCallback>+let next = 1+const runFrames = () => { const q = [...queue.values()]; queue.clear(); q.forEach((f) => f(0)) }++beforeEach(() => {+ queue = new Map()+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => { const id = next++; queue.set(id, cb); return id })+ vi.stubGlobal('cancelAnimationFrame', (id: number) => { queue.delete(id) })+})+afterEach(() => vi.unstubAllGlobals())++describe('the streamed-text frame', () => {+ it('a pending frame does not land on the error written after it (the hidden tab case)', () => {+ let bubble = ''+ const frames = frameFlush()+ const partial = 'Writing the pa'+ frames.schedule(() => { bubble = partial })+ // The stream fails while the tab is hidden: no frame has run yet.+ frames.close()+ bubble = 'LU Cloud ended this step: no data from the model for 90 seconds.'+ // The tab is shown again, the frame queue drains.+ runFrames()+ expect(bubble).toBe('LU Cloud ended this step: no data from the model for 90 seconds.')+ })++ it('writes at most once per frame while streaming, with the latest text', () => {+ const writes: string[] = []+ let text = ''+ const frames = frameFlush()+ for (const piece of ['a', 'b', 'c']) {+ text += piece+ frames.schedule(() => writes.push(text))+ }+ runFrames()+ frames.schedule(() => writes.push(text + '!'))+ runFrames()+ expect(writes).toEqual(['abc', 'abc!'])+ })++ it('refuses frames after the stream ended', () => {+ const frames = frameFlush()+ frames.close()+ let ran = false+ frames.schedule(() => { ran = true })+ runFrames()+ expect(ran).toBe(false)+ })+})++describe('every place that streams into a bubble closes the frame before its own write', () => {+ const src = (f: string) => readFileSync(resolve(__dirname, '../../hooks', f), 'utf8')++ it('the chat, both paths', () => {+ const chat = src('useChat.ts')+ expect(chat).not.toMatch(/requestAnimationFrame\(/)+ expect(chat.match(/frames\.schedule\(/g)).toHaveLength(2)+ expect(chat.match(/if \(chunk\.done\) \{\s+frames\.close\(\)/g)).toHaveLength(2)+ expect(chat.match(/\} catch \(err\) \{\s+frames\.close\(\)/g)).toHaveLength(2)+ // After the loop, before the empty-answer lines.+ expect(chat).toMatch(/frames\.close\(\)\s+\/\/ Thought-only completion/)+ expect(chat).toMatch(/frames\.close\(\)\s+if \(!abort\.signal\.aborted && !contentAcc\.trim\(\)\)/)+ })++ it('the Agent tab', () => {+ const agent = src('useAgentChat.ts')+ // (The workflow progress frame stays a plain requestAnimationFrame: it+ // reads the run's current status when it fires, so it cannot write a stale+ // one.)+ expect(agent).toMatch(/function scheduleUIUpdate\(\) \{\s+frames\.schedule\(/)+ expect(agent).toMatch(/\/\/ Final store update\s+frames\.close\(\)/)+ expect(agent).toMatch(/\} catch \(err\) \{\s+frames\.close\(\)\s+if \(\(err as Error\)\.name !== 'AbortError'\)/)+ })+})diff --git a/src/lib/frame-flush.ts b/src/lib/frame-flush.tsnew file mode 100644index 00000000..cb4c2f00--- /dev/null+++ b/src/lib/frame-flush.ts@@ -0,0 +1,37 @@+/**+ * At most one store write per animation frame while a reply streams in, and+ * none after the stream has ended.+ *+ * Bug hunt 01.10.2026 (H2). The chat wrote the streamed text from a+ * requestAnimationFrame callback and never took a pending one back. The end of+ * a stream (the empty-answer explanation) and every error path (the stall+ * message included) write the bubble directly, and a frame still pending then+ * landed on top of that line with the partial text. In a hidden tab frames do+ * not fire at all until the tab is shown again, so the one message written+ * while nobody was looking was the one the late frame overwrote.+ */+export interface FrameFlush {+ /** Run `write` on the next frame, once, unless a frame is already pending or the flush is closed. */+ schedule(write: () => void): void+ /** The stream is over: drop a pending frame and refuse every later one. */+ close(): void+}++export function frameFlush(): FrameFlush {+ let id: number | null = null+ let closed = false+ return {+ schedule(write) {+ if (closed || id !== null) return+ id = requestAnimationFrame(() => {+ id = null+ if (!closed) write()+ })+ },+ close() {+ closed = true+ if (id !== null) cancelAnimationFrame(id)+ id = null+ },+ }+}