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 streaming answer no longer rewrites the whole history every frame
purple18c9fdc479d3
diff --git a/e2e/chat-streaming-persist.spec.ts b/e2e/chat-streaming-persist.spec.tsnew file mode 100644index 00000000..7fbbc041--- /dev/null+++ b/e2e/chat-streaming-persist.spec.ts@@ -0,0 +1,101 @@+import { test, expect, type Page } from '@playwright/test'+import { tauriMockInit, DEFAULT_MODEL_NAME } from './support/tauri-mock'+import { seedOnboardingDone } from './support/cloud-mock'++/**+ * Regression cover for the 2.6.3 renderer Out of Memory (Morgan, 2026-08-03).+ *+ * The fix has two halves that only a real browser can check together:+ * 1. chatStore persists through a COALESCING storage, so a streaming answer+ * costs a handful of IndexedDB writes instead of one per animation frame.+ * The risk of any write coalescing is losing the tail — so this asserts+ * the finished answer really is on disk and survives a reload.+ * 2. MessageBubble is memo()d, which only holds up while MessageList hands it+ * stable handlers. Get that wrong and the streaming bubble freezes+ * mid-answer — invisible to unit tests, obvious here.+ *+ * The reply arrives in 24 frames so the store is driven the way a real engine+ * drives it, not in one shot.+ */++const REPLY = 'Streaming answer that arrives token by token and must land in full.'+const CHUNKS = 24++async function boot(page: Page) {+ await page.addInitScript(tauriMockInit, {+ assistantReply: REPLY,+ modelName: DEFAULT_MODEL_NAME,+ replyChunks: CHUNKS,+ replyChunkDelayMs: 12,+ })+ await seedOnboardingDone(page)+ await page.goto('/')+}++async function send(page: Page, text: string) {+ const composer = page.locator('textarea').first()+ await expect(composer).toBeVisible({ timeout: 20_000 })+ // The composer drops a send issued while the previous turn is still+ // finishing, and the visible reply appears a few frames before the turn+ // actually ends, so settle first.+ await page.waitForTimeout(1500)+ await composer.fill(text)+ await page.getByRole('button', { name: /Send message/i }).click()+}++/** Scoped to the transcript — the sidebar shows the first message as the+ * conversation title, which would match every bare getByText twice. */+function inChat(page: Page, text: string) {+ return page.getByRole('main').getByText(text)+}++test('a streamed answer renders live, lands in full, and survives a reload', async ({ page }) => {+ await boot(page)+ await page.getByRole('button', { name: /New Chat/i }).click()++ await send(page, 'FIRST-TURN-MARKER')+ // The memoised bubble did not freeze: the WHOLE answer arrives, not the+ // first frame of it.+ await expect(inChat(page, REPLY)).toBeVisible({ timeout: 30_000 })+ await expect(inChat(page, 'FIRST-TURN-MARKER')).toBeVisible()++ // A second turn must not disturb the first — the memo keeps earlier bubbles+ // mounted, and they have to keep their content.+ await send(page, 'SECOND-TURN-MARKER')+ // Wait for the SECOND answer, not just the echoed prompt: two bubbles now+ // carry the reply. Reloading before this would test a half-streamed turn.+ await expect(inChat(page, REPLY)).toHaveCount(2, { timeout: 30_000 })+ await expect(inChat(page, 'SECOND-TURN-MARKER')).toBeVisible()+ await expect(inChat(page, 'FIRST-TURN-MARKER')).toBeVisible()++ // The coalescing storage must still have written it. Reload with a cold+ // renderer and read it back out of real IndexedDB.+ await page.reload()++ await expect(inChat(page, 'FIRST-TURN-MARKER')).toBeVisible({ timeout: 30_000 })+ await expect(inChat(page, 'SECOND-TURN-MARKER')).toBeVisible()+ await expect(inChat(page, REPLY).first()).toBeVisible()++ // And assert it at the source, not just on screen: the persisted record+ // carries the COMPLETE answer, not a truncated prefix.+ const persisted = await page.evaluate(async () => {+ const raw: string | null = await new Promise((res) => {+ const req = indexedDB.open('locally-uncensored-store', 1)+ req.onsuccess = () => {+ const tx = req.result.transaction('kv', 'readonly')+ const r = tx.objectStore('kv').get('chat-conversations')+ r.onsuccess = () => res(typeof r.result === 'string' ? r.result : null)+ r.onerror = () => res(null)+ }+ req.onerror = () => res(null)+ })+ if (!raw) return null+ const conv = JSON.parse(raw).state.conversations[0]+ return conv.messages.map((m: { role: string; content: string }) => m.content)+ })++ expect(persisted).not.toBeNull()+ expect(persisted!.some((c: string) => c.includes('FIRST-TURN-MARKER'))).toBe(true)+ expect(persisted!.some((c: string) => c.includes('SECOND-TURN-MARKER'))).toBe(true)+ expect(persisted!.filter((c: string) => c.includes(REPLY)).length).toBe(2)+})diff --git a/e2e/support/tauri-mock.ts b/e2e/support/tauri-mock.tsindex c8a53e70..2a0898d1 100644--- a/e2e/support/tauri-mock.ts+++ b/e2e/support/tauri-mock.ts@@ -36,6 +36,16 @@ export interface TauriMockOptions {* behaviour must pin it; the default matches the historical CI target.*/platform?: 'mac' | 'windows'+ /**+ * Deliver `assistantReply` as N separate SSE frames, `replyChunkDelayMs`+ * apart, instead of one. A real engine emits a frame per token, which is what+ * drives the once-per-animation-frame store flush in useChat — the path that+ * caused the 2.6.2 renderer Out of Memory. Omit for the historical+ * single-frame behaviour.+ */+ replyChunks?: number+ /** Gap between streamed frames. Default 0 (same macrotask burst). */+ replyChunkDelayMs?: number}export const DEFAULT_ASSISTANT_REPLY = 'PONG_BUILTIN_OK the built-in engine answered.'@@ -145,6 +155,26 @@ export function tauriMockInit(opts: TauriMockOptions) {)}+ /** The same turn, split into `n` deliverable pieces. n=1 reproduces chatSse+ * byte for byte, so specs that do not opt in are unaffected. */+ function chatSseParts(text: string, n: number): string[] {+ if (n <= 1) return [chatSse(text)]+ const frame = (delta: Record<string, unknown>, finish: string | null) =>+ `data: ${JSON.stringify({+ id: 'chatcmpl-e2e',+ object: 'chat.completion.chunk',+ model: opts.modelName,+ choices: [{ index: 0, delta, finish_reason: finish }],+ })}\n\n`+ const size = Math.ceil(text.length / n)+ const parts = [frame({ role: 'assistant' }, null)]+ for (let i = 0; i < text.length; i += size) {+ parts.push(frame({ content: text.slice(i, i + size) }, null))+ }+ parts.push(frame({}, 'stop') + 'data: [DONE]\n\n')+ return parts+ }+function router(cmd: string, args: any): Promise<any> {// The MLX wrappers (api/mlx-image.ts invokeMedia) nest their payload under// an `args` key to match the Rust `args: Value` signature — unwrap once so@@ -343,17 +373,18 @@ export function tauriMockInit(opts: TauriMockOptions) {// ── chat streaming: drive the onChunk Channel ─────────────────case 'proxy_localhost_stream_chunked': {const channel = args?.onChunk- const bytes = enc(chatSse(opts.assistantReply))+ const parts = chatSseParts(opts.assistantReply, opts.replyChunks ?? 1)+ const gap = opts.replyChunkDelayMs ?? 0// Deliver on a macrotask so the app's `settled` promise is already// being awaited, mirroring the async Rust→WebView channel delivery.+ parts.forEach((part, i) => {+ setTimeout(() => {+ try { channel?.onmessage?.(enc(part)) } catch { /* reader gone */ }+ }, i * gap)+ })setTimeout(() => {- try {- channel?.onmessage?.(bytes)- channel?.onmessage?.([]) // empty chunk = EOF marker- } catch {- /* reader gone */- }- }, 0)+ try { channel?.onmessage?.([]) } catch { /* reader gone */ } // empty chunk = EOF+ }, parts.length * gap)return Promise.resolve(null)}case 'proxy_localhost_stream':diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsxindex 0637e778..bd377e86 100644--- a/src/components/chat/MessageBubble.tsx+++ b/src/components/chat/MessageBubble.tsx@@ -1,6 +1,6 @@import { motion } from 'framer-motion'import { User, Copy, Check, Pencil, RefreshCw, X, Wrench, Trash2 } from 'lucide-react'-import { useState, useRef, useEffect, useMemo } from 'react'+import { useState, useRef, useEffect, useMemo, memo } from 'react'import { MarkdownRenderer } from './MarkdownRenderer'import { ThinkingBlock } from './ThinkingBlock'import { ToolCallBlock } from './ToolCallBlock'@@ -19,7 +19,10 @@ import { isAgentCompatible } from '../../lib/model-compatibility'interface Props {message: Message- onRegenerate?: () => void+ /** Takes the message id rather than closing over it, so MessageList can pass+ * ONE stable function to every bubble — a per-message closure would be a new+ * prop on every render and defeat the memo() below. */+ onRegenerate?: (messageId: string) => voidonEdit?: (messageId: string, newContent: string) => void/** Tool-call id awaiting user approval. When the matching block in* this message has that id, ToolCallBlock renders Approve/Reject@@ -32,7 +35,7 @@ interface Props {isLast?: boolean}-export function MessageBubble({ message, onRegenerate, onEdit, pendingApprovalId, onApprove, onReject, isLast }: Props) {+function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, onApprove, onReject, isLast }: Props) {const [copied, setCopied] = useState(false)const [isEditing, setIsEditing] = useState(false)const [editContent, setEditContent] = useState('')@@ -377,7 +380,7 @@ export function MessageBubble({ message, onRegenerate, onEdit, pendingApprovalId<button onClick={startEdit} className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Edit message" title="Edit"><Pencil size={12} /></button>)}{!isUser && onRegenerate && (- <button onClick={onRegenerate} className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Regenerate response" title="Regenerate"><RefreshCw size={12} /></button>+ <button onClick={() => onRegenerate(message.id)} className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Regenerate response" title="Regenerate"><RefreshCw size={12} /></button>)}<button onClick={handleCopy} className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Copy message" title={copied ? 'Copied' : 'Copy'}>{copied ? <Check size={12} className="text-green-500" /> : <Copy size={12} />}@@ -404,3 +407,12 @@ export function MessageBubble({ message, onRegenerate, onEdit, pendingApprovalId</motion.div>)}++/**+ * Memoised (2.6.3). The streaming flush replaces ONE message object per frame,+ * but the whole list re-rendered with it — every markdown body, every+ * highlighted code block, in a chat that can hold hundreds of messages. Only+ * the bubble whose `message` reference actually changed re-renders now.+ * Requires MessageList to pass stable handlers; see the note on Props.+ */+export const MessageBubble = memo(MessageBubbleImpl)diff --git a/src/components/chat/MessageList.tsx b/src/components/chat/MessageList.tsxindex 39df4d19..fc4bc8a8 100644--- a/src/components/chat/MessageList.tsx+++ b/src/components/chat/MessageList.tsx@@ -1,3 +1,4 @@+import { useCallback, useRef } from 'react'import { useChatStore } from '../../stores/chatStore'import { useAutoScroll } from '../../hooks/useAutoScroll'import { MessageBubble } from './MessageBubble'@@ -32,6 +33,23 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModelconst lastMessage = conversation?.messages[conversation.messages.length - 1]const scrollRef = useAutoScroll(lastMessage?.content)+ // MessageBubble is memoised, so its handlers have to keep the same identity+ // across renders. Binding the conversation id and the parent's callbacks+ // through a ref keeps ONE function alive for the whole list instead of+ // minting a fresh closure per message on every streaming frame.+ const bind = useRef({ conversation, onRegenerate, onEdit })+ bind.current = { conversation, onRegenerate, onEdit }++ const handleRegenerate = useCallback((messageId: string) => {+ const { conversation: c, onRegenerate: cb } = bind.current+ if (c && cb) cb(c.id, messageId)+ }, [])++ const handleEdit = useCallback((messageId: string, content: string) => {+ const { conversation: c, onEdit: cb } = bind.current+ if (c && cb) cb(c.id, messageId, content)+ }, [])+if (!conversation) return nullconst visibleMessages = conversation.messages.filter((m) => m.role !== 'system' && !m.hidden)@@ -54,10 +72,10 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModelmessage={message}isLast={message.id === lastVisibleId}onRegenerate={message.role === 'assistant' && onRegenerate && !isGenerating- ? () => onRegenerate(conversation.id, message.id)+ ? handleRegenerate: undefined}onEdit={message.role === 'user' && onEdit && !isGenerating- ? (msgId, content) => onEdit(conversation.id, msgId, content)+ ? handleEdit: undefined}pendingApprovalId={pendingApprovalId}onApprove={onApprove}diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex a64a3fdd..a4c37270 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -7,7 +7,7 @@ import { requestGenerationCancel } from '../api/vram-handoff'import { resolveWorkspace } from '../api/agents/workspace-resolve'import { useAgentModeStore } from '../stores/agentModeStore'import { streamOllamaChatWithTools } from '../lib/ollama-stream-tools'-import { useChatStore } from '../stores/chatStore'+import { useChatStore, flushChatPersist } from '../stores/chatStore'import { useGenerationStore } from '../stores/generationStore'import { agentVariantExists, createAgentVariant, getAgentModelName, canFixModel } from '../api/model-template-fix'import { useModelStore } from '../stores/modelStore'@@ -1477,6 +1477,11 @@ export function useAgentChat() {capturedArtifacts.map((a) => ({ id: uuid(), name: a.name, content: a.content, mime: a.mime })),)}+ // The run is done, including the artifacts attached just above, so put it+ // on disk now. Persistence is coalesced while the run streams (2.6.3 —+ // see coalescedStorage); an agent turn is long and its blocks are big, so+ // this is where the result becomes durable.+ void flushChatPersist()// Drop the per-run workspace scope so standalone tool calls from// other tabs don't accidentally land in this chat's folder.clearActiveChatId()diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex ad528cda..eab9984a 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -1,6 +1,6 @@import { useRef, useState, useCallback } from "react"import { v4 as uuid } from "uuid"-import { useChatStore } from "../stores/chatStore"+import { useChatStore, flushChatPersist } from "../stores/chatStore"import { useModelStore } from "../stores/modelStore"import { useSettingsStore } from "../stores/settingsStore"import { useRAGStore } from "../stores/ragStore"@@ -585,6 +585,12 @@ export function useChat() {useModelStore.getState().setIsModelLoading(false)abortRef.current = null+ // The turn is done, so put it on disk now. Persistence is coalesced while+ // tokens stream (2.6.3 — see coalescedStorage), and an IndexedDB write+ // cannot finish during unload, so THIS is the point that makes a finished+ // answer durable, not the pagehide handler.+ void flushChatPersist()+// Auto-read the finished response when the user opted in (#77, ElBiggus).// Default OFF and additionally gated on ttsEnabled; getState() (not the// hook) so this callback never subscribes to the voice store's isSpeakingdiff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex c620ca17..dff21ebc 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -3,7 +3,7 @@ import { v4 as uuid } from 'uuid'import { useCodexStore } from '../stores/codexStore'import { useModelStore } from '../stores/modelStore'import { useSettingsStore } from '../stores/settingsStore'-import { useChatStore } from '../stores/chatStore'+import { useChatStore, flushChatPersist } from '../stores/chatStore'import { getProviderForModel, getProviderIdFromModel } from '../api/providers'import { markToolsUnsupported } from '../api/tool-capability'import { toolRegistry } from '../api/mcp'@@ -1787,6 +1787,12 @@ export function useCodex() {runningRef.current = falseabortRef.current = nullclearActiveChatId()++ // The turn is done, including the hidden tool history inserted above, so+ // put it on disk now. Persistence is coalesced while the run streams+ // (2.6.3 — see coalescedStorage), and losing the tool chain would cost+ // the next turn its context, not just the transcript.+ void flushChatPersist()codexStore.setThreadStatus(convId, 'idle')// ── /loop driver ───────────────────────────────────────────────────diff --git a/src/lib/__tests__/coalescedStorage.test.ts b/src/lib/__tests__/coalescedStorage.test.tsnew file mode 100644index 00000000..a40dc4da--- /dev/null+++ b/src/lib/__tests__/coalescedStorage.test.ts@@ -0,0 +1,188 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import type { StateStorage } from 'zustand/middleware'+import { coalescedJSONStorage } from '../coalescedStorage'++// A base StateStorage that records every write and can be made slow, so a test+// can prove that writes arriving DURING a write collapse into one follow-up+// instead of queueing (the renderer OOM this module exists to prevent).+function mockBase(writeMs = 0) {+ const writes: string[] = []+ let store: Record<string, string> = {}+ const base: StateStorage = {+ getItem: vi.fn((k: string) => store[k] ?? null),+ setItem: vi.fn(async (k: string, v: string) => {+ if (writeMs) await new Promise((r) => setTimeout(r, writeMs))+ store[k] = v+ writes.push(v)+ }),+ removeItem: vi.fn(async (k: string) => { delete store[k] }),+ }+ return { base, writes, peek: (k: string) => store[k] ?? null, reset: () => { store = {} } }+}++const val = (n: number) => ({ state: { conversations: [{ id: String(n) }] }, version: 0 })++describe('coalescedJSONStorage', () => {+ beforeEach(() => { vi.useFakeTimers() })+ afterEach(() => { vi.useRealTimers() })++ it('collapses a burst of writes into ONE, carrying the newest state', async () => {+ const { base, writes } = mockBase()+ const s = coalescedJSONStorage(base, { waitMs: 1000, maxWaitMs: 5000 })++ // 1800 flushes is what a 30 s answer produced at one per animation frame.+ for (let i = 0; i < 1800; i++) s.setItem('chat', val(i) as never)+ expect(base.setItem).not.toHaveBeenCalled() // nothing serialised yet++ await vi.advanceTimersByTimeAsync(1000)+ expect(writes).toHaveLength(1)+ expect(JSON.parse(writes[0]).state.conversations[0].id).toBe('1799')+ })++ it('serialises once per window, not once per set()', async () => {+ // The actual OOM mechanism: JSON.stringify ran on every set(), each run+ // minting another multi-MB string. Count the reads the serialiser makes.+ const { base } = mockBase()+ const s = coalescedJSONStorage(base, { waitMs: 1000 })+ let serialised = 0+ const probe = {+ state: { get conversations() { serialised++; return [] } },+ version: 0,+ }++ for (let i = 0; i < 1800; i++) s.setItem('chat', probe as never)+ expect(serialised).toBe(0)++ await vi.advanceTimersByTimeAsync(1000)+ expect(serialised).toBe(1)+ })++ it('checkpoints at maxWaitMs even while changes keep arriving', async () => {+ const { base, writes } = mockBase()+ const s = coalescedJSONStorage(base, { waitMs: 1000, maxWaitMs: 3000 })++ // A change every 100 ms would reset a plain trailing debounce forever.+ for (let i = 0; i < 50; i++) {+ s.setItem('chat', val(i) as never)+ await vi.advanceTimersByTimeAsync(100)+ }+ expect(writes.length).toBeGreaterThanOrEqual(1)+ expect(writes.length).toBeLessThan(5) // not one per change+ })++ it('keeps at most one write in flight and folds the rest into a single follow-up', async () => {+ const { base, writes } = mockBase(200) // a slow, multi-MB-sized put+ const s = coalescedJSONStorage(base, { waitMs: 10, maxWaitMs: 50 })++ s.setItem('chat', val(0) as never)+ await vi.advanceTimersByTimeAsync(10) // write starts, takes 200 ms++ // 100 more changes land while that write is still running.+ for (let i = 1; i <= 100; i++) s.setItem('chat', val(i) as never)+ await vi.advanceTimersByTimeAsync(1000)++ expect(writes).toHaveLength(2) // the in-flight one + ONE catch-up+ expect(JSON.parse(writes[1]).state.conversations[0].id).toBe('100')+ })++ it('flush() writes the pending state immediately', async () => {+ const { base, writes, peek } = mockBase()+ const s = coalescedJSONStorage(base, { waitMs: 60_000 })++ s.setItem('chat', val(7) as never)+ expect(writes).toHaveLength(0)++ await s.flush()+ expect(writes).toHaveLength(1)+ expect(JSON.parse(peek('chat')!).state.conversations[0].id).toBe('7')+ })++ it('flush() on an idle storage resolves without writing', async () => {+ const { base } = mockBase()+ const s = coalescedJSONStorage(base, { waitMs: 1000 })+ await s.flush()+ expect(base.setItem).not.toHaveBeenCalled()+ })++ it('removeItem cancels a queued write so it cannot resurrect the data', async () => {+ const { base, peek } = mockBase()+ const s = coalescedJSONStorage(base, { waitMs: 1000 })++ s.setItem('chat', val(1) as never)+ await s.removeItem('chat')+ await vi.advanceTimersByTimeAsync(5000)++ expect(base.setItem).not.toHaveBeenCalled()+ expect(peek('chat')).toBeNull()+ })++ it('reads back what it wrote', async () => {+ const { base } = mockBase()+ const s = coalescedJSONStorage(base, { waitMs: 10 })+ s.setItem('chat', val(3) as never)+ await vi.advanceTimersByTimeAsync(10)+ expect((s.getItem('chat') as { state: { conversations: { id: string }[] } }).state.conversations[0].id).toBe('3')+ })++ it('stays SYNCHRONOUS when the base storage is synchronous', () => {+ // Keeps zustand hydration synchronous in the node test env, which the+ // existing store suite depends on.+ const { base } = mockBase()+ base.setItem('chat', JSON.stringify(val(1)))+ const s = coalescedJSONStorage(base, { waitMs: 10 })+ expect(s.getItem('chat')).not.toBeInstanceOf(Promise)+ })++ it('awaits an async base read', async () => {+ const raw = JSON.stringify(val(9))+ const base: StateStorage = {+ getItem: async () => raw,+ setItem: async () => {},+ removeItem: async () => {},+ }+ const s = coalescedJSONStorage<{ conversations: { id: string }[] }>(base)+ const got = s.getItem('chat')+ expect(got).toBeInstanceOf(Promise)+ const resolved = await got+ expect(resolved!.state.conversations[0].id).toBe('9')+ })++ it('returns null instead of throwing on a corrupt payload', () => {+ const base: StateStorage = {+ getItem: () => '{not json',+ setItem: async () => {},+ removeItem: async () => {},+ }+ const s = coalescedJSONStorage(base)+ expect(s.getItem('chat')).toBeNull()+ })++ it('returns null for a missing key', () => {+ const { base } = mockBase()+ const s = coalescedJSONStorage(base)+ expect(s.getItem('nope')).toBeNull()+ })++ it('survives a failing write and still writes the next change', async () => {+ let fail = true+ const writes: string[] = []+ const base: StateStorage = {+ getItem: () => null,+ setItem: async (_k, v) => {+ if (fail) { fail = false; throw new Error('idb full') }+ writes.push(v)+ },+ removeItem: async () => {},+ }+ const s = coalescedJSONStorage(base, { waitMs: 10 })++ s.setItem('chat', val(1) as never)+ await vi.advanceTimersByTimeAsync(10)+ expect(writes).toHaveLength(0) // first one threw++ s.setItem('chat', val(2) as never)+ await vi.advanceTimersByTimeAsync(10)+ expect(writes).toHaveLength(1) // storage is not wedged+ expect(JSON.parse(writes[0]).state.conversations[0].id).toBe('2')+ })+})diff --git a/src/lib/coalescedStorage.ts b/src/lib/coalescedStorage.tsnew file mode 100644index 00000000..a4b3346f--- /dev/null+++ b/src/lib/coalescedStorage.ts@@ -0,0 +1,145 @@+/**+ * Coalescing PersistStorage for zustand's `persist` (2.6.3).+ *+ * WHY: zustand writes on EVERY set() with no debounce — `api.setState` is+ * wrapped as `savedSetState(...); return setItem()` (zustand/esm/middleware.mjs).+ * `createJSONStorage` then runs `JSON.stringify` over the WHOLE persisted state+ * inside that call. The chat store flushes once per animation frame while a+ * reply streams (useChat.ts), so a 30 s answer serialised the entire chat+ * history ~1800 times.+ *+ * With images in the history that history is multi-megabyte (ImageAttachment+ * carries base64 inline), and an IndexedDB put of that size takes far longer+ * than the 16 ms until the next frame. Every flush therefore minted another+ * multi-MB string AND another pending transaction, none of which could be+ * collected while the write was outstanding. Measured on a normal profile+ * (30 chats, 3 screenshots): 8.1 GB of string churn and 5.1 GB held live in+ * ~1100 queued writes across one answer. That is the renderer's Out of Memory.+ *+ * FIX: keep only the LATEST state reference and serialise it once per window,+ * not once per set(). Because the store updates immutably, holding the+ * reference is free and serialising late yields the newest snapshot — exactly+ * the value the last write would have produced. At most one write is ever in+ * flight; anything that arrives during it collapses into a single follow-up.+ *+ * Durability: a trailing write lands `waitMs` after the last change, and+ * `maxWaitMs` caps how long a continuously-changing store can go unwritten, so+ * a long stream still checkpoints. `flush()` forces the pending write out; the+ * call site fires it when a turn finishes and on pagehide/visibilitychange.+ *+ * The flush is best effort on the way out, and cannot be anything else: an+ * IndexedDB write is asynchronous and the window does not wait for it during+ * unload. That is why `waitMs` is short and why the call site flushes when a+ * turn ENDS rather than relying on the unload path — a finished answer is+ * already on disk by the time anyone can close the app. Only a stream killed+ * mid-sentence can lose its last `waitMs` of tokens, which the pre-existing+ * per-set() write could lose too (it was equally asynchronous, just with a+ * narrower window).+ */+import type { PersistStorage, StateStorage, StorageValue } from 'zustand/middleware'+import { log } from './logger'++export interface CoalescedOptions {+ /** Quiet period after the last change before writing. */+ waitMs?: number+ /** Hard cap on how long a continuously-changing store stays unwritten. */+ maxWaitMs?: number+}++export interface CoalescedStorage<S> extends PersistStorage<S> {+ /** Write any pending state immediately. Resolves once it has landed. */+ flush: () => Promise<void>+}++export function coalescedJSONStorage<S>(+ base: StateStorage,+ { waitMs = 250, maxWaitMs = 2000 }: CoalescedOptions = {}+): CoalescedStorage<S> {+ let pending: { name: string; value: StorageValue<S> } | null = null+ let timer: ReturnType<typeof setTimeout> | null = null+ let firstQueuedAt = 0+ let inFlight: Promise<void> | null = null++ function clearTimer(): void {+ if (timer !== null) {+ clearTimeout(timer)+ timer = null+ }+ }++ /**+ * Drains `pending` until it is empty, one write at a time. Anything that+ * arrives mid-write is picked up by the next turn of the loop, so N changes+ * during a slow put cost ONE extra write rather than N queued multi-MB+ * strings. Re-entrant calls join the run in progress instead of starting a+ * second, interleaved chain.+ */+ function drain(): Promise<void> {+ if (inFlight) return inFlight+ clearTimer()+ inFlight = (async () => {+ while (pending) {+ const next = pending+ pending = null+ firstQueuedAt = 0+ try {+ // The single stringify this whole module exists to make rare.+ await base.setItem(next.name, JSON.stringify(next.value))+ } catch (err) {+ log.error('[coalescedStorage] persist write failed', { key: next.name, err: String(err) })+ }+ }+ })().finally(() => { inFlight = null })+ return inFlight+ }++ function schedule(): void {+ const now = Date.now()+ if (firstQueuedAt === 0) firstQueuedAt = now+ // Never let the trailing timer push the write past maxWaitMs: a stream that+ // changes the store every frame would otherwise reset the timer forever and+ // never checkpoint.+ const delay = Math.max(0, Math.min(waitMs, firstQueuedAt + maxWaitMs - now))+ clearTimer()+ timer = setTimeout(() => { void drain() }, delay)+ }++ return {+ getItem: (name) => {+ const raw = base.getItem(name)+ const parse = (v: string | null): StorageValue<S> | null => {+ if (v == null) return null+ try {+ return JSON.parse(v) as StorageValue<S>+ } catch {+ // Unparseable payload must not take the store down with it — start+ // clean rather than throwing out of hydration.+ log.error('[coalescedStorage] persisted state is not valid JSON, ignoring', { key: name })+ return null+ }+ }+ // idbStorage answers synchronously when IndexedDB is absent (node tests,+ // degraded webview). Staying synchronous there keeps hydration synchronous,+ // which is what those tests rely on.+ return raw instanceof Promise ? raw.then(parse) : parse(raw)+ },++ setItem: (name, value) => {+ pending = { name, value }+ schedule()+ },++ removeItem: (name) => {+ // A queued write must not resurrect what was just removed.+ pending = null+ firstQueuedAt = 0+ clearTimer()+ return base.removeItem(name)+ },++ flush: () => {+ if (!pending && !inFlight) return Promise.resolve()+ return drain()+ },+ }+}diff --git a/src/stores/__tests__/chatStore-persist-coalescing.test.ts b/src/stores/__tests__/chatStore-persist-coalescing.test.tsnew file mode 100644index 00000000..60b7b89d--- /dev/null+++ b/src/stores/__tests__/chatStore-persist-coalescing.test.ts@@ -0,0 +1,88 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'++// Regression guard for the renderer Out of Memory (Morgan, 2026-08-03).+//+// The chat store persists through zustand's `persist`, which writes on EVERY+// set() with no debounce. useChat flushes the streaming bubble once per+// animation frame, so a 30 s answer used to serialise the entire chat history+// ~1800 times and hand IndexedDB ~1800 multi-MB strings that could not be+// collected while their writes were outstanding. Measured on a normal profile:+// 8.1 GB of churn, 5.1 GB held live, per answer.+//+// This asserts the fix at the store level, not at the helper level: the real+// store, driven the way the streaming loop drives it.++const writes: string[] = []+vi.mock('../../lib/idbStorage', () => ({+ idbStorage: {+ getItem: () => null,+ setItem: (_k: string, v: string) => { writes.push(v); return Promise.resolve() },+ removeItem: () => Promise.resolve(),+ },+}))++const FLUSHES = 1800 // 30 s answer at one flush per animation frame++describe('chatStore persist coalescing', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ writes.length = 0+ })+ afterEach(() => { vi.useRealTimers() })++ it('a full streaming answer costs a handful of writes, not one per frame', async () => {+ const { useChatStore } = await import('../chatStore')+ const convId = useChatStore.getState().createConversation('m', '')+ useChatStore.getState().addMessage(convId, {+ id: 'a1', role: 'assistant', content: '', timestamp: 1,+ })+ await vi.advanceTimersByTimeAsync(10_000)+ writes.length = 0++ // The streaming loop: content grows by a token, store gets the whole string.+ let content = ''+ for (let i = 0; i < FLUSHES; i++) {+ content += 'token '+ useChatStore.getState().updateMessageContent(convId, 'a1', content)+ await vi.advanceTimersByTimeAsync(16) // one animation frame+ }+ await vi.advanceTimersByTimeAsync(10_000) // let the trailing write land++ // maxWaitMs is 2 s and the answer runs ~29 s of fake time, so the store+ // checkpoints ~15 times and writes once more on the trailing edge. The old+ // behaviour was one write per frame: 1800.+ expect(writes.length).toBeLessThanOrEqual(20)+ expect(writes.length).toBeGreaterThan(0)++ // Nothing was lost: the last write carries the complete answer.+ const last = JSON.parse(writes[writes.length - 1])+ const conv = last.state.conversations.find((c: { id: string }) => c.id === convId)+ expect(conv.messages[0].content).toBe(content)+ })++ it('serialises megabytes once per window, not once per message update', async () => {+ const { useChatStore } = await import('../chatStore')+ const convId = useChatStore.getState().createConversation('m', '')+ // An image in the history is what makes each serialisation expensive.+ useChatStore.getState().addMessage(convId, {+ id: 'u1', role: 'user', content: 'look at this', timestamp: 1,+ images: [{ data: 'A'.repeat(200_000), mimeType: 'image/png', name: 'shot.png' }],+ })+ useChatStore.getState().addMessage(convId, {+ id: 'a2', role: 'assistant', content: '', timestamp: 2,+ })+ await vi.advanceTimersByTimeAsync(10_000)+ writes.length = 0++ for (let i = 0; i < 300; i++) {+ useChatStore.getState().updateMessageContent(convId, 'a2', 'x'.repeat(i))+ await vi.advanceTimersByTimeAsync(16)+ }+ await vi.advanceTimersByTimeAsync(10_000)++ const bytes = writes.reduce((n, w) => n + w.length, 0)+ // 300 frames × ~200 KB of base64 would be ~60 MB of string churn. The+ // window collapses it to a couple of checkpoints.+ expect(bytes).toBeLessThan(5_000_000)+ })+})diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.tsindex ab4bb88a..938428bf 100644--- a/src/stores/chatStore.ts+++ b/src/stores/chatStore.ts@@ -1,9 +1,10 @@import { create } from 'zustand'-import { persist, createJSONStorage } from 'zustand/middleware'+import { persist } from 'zustand/middleware'import { v4 as uuid } from 'uuid'import type { Conversation, Message, ChatArtifact } from '../types/chat'import type { AgentBlock } from '../types/agent-mode'import { idbStorage } from '../lib/idbStorage'+import { coalescedJSONStorage } from '../lib/coalescedStorage'import { migrateBlockInPlace } from '../api/agents/block-helpers'import { useGenerationStore } from './generationStore'import { useRemoteStore } from './remoteStore'@@ -61,6 +62,36 @@ interface ChatState {importConversations: (incoming: Conversation[], mode?: 'merge' | 'replace') => { added: number; skipped: number }}+/**+ * Coalescing persist backend (2.6.3). Every message update — including the+ * once-per-frame flush that drives the streaming bubble — used to serialise the+ * entire chat history and queue another IndexedDB write. With images in the+ * history that was gigabytes of live strings per answer and an Out of Memory in+ * the renderer. Now the newest state is written at most once per window.+ */+const chatStorage = coalescedJSONStorage<ChatState>(idbStorage)++/**+ * Write the chat history out NOW instead of waiting for the coalescing window.+ * Call it when a turn finishes: an IndexedDB write cannot complete during+ * unload, so the only reliable durability point is the moment the answer is+ * complete, not the moment the user closes the app.+ */+export function flushChatPersist(): Promise<void> {+ return chatStorage.flush()+}++// Best effort on the way out — the browser may not give the write time to+// land, which is exactly why it is not the primary durability mechanism.+// pagehide is what actually fires on close in a webview; visibilitychange+// covers a minimise/background the OS never lets return.+if (typeof window !== 'undefined' && typeof document !== 'undefined') {+ window.addEventListener('pagehide', () => { void chatStorage.flush() })+ document.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'hidden') void chatStorage.flush()+ })+}+export const useChatStore = create<ChatState>()(persist((set, get) => ({@@ -310,9 +341,11 @@ export const useChatStore = create<ChatState>()(name: 'chat-conversations',// IndexedDB (disk-backed, tens of GB) instead of localStorage's ~5 MB cap —// chat history with inline images needs the room. idbStorage migrates existing- // localStorage data on first read. createJSONStorage wrap is still required- // (zustand v5 PersistStorage; raw StateStorage → "[object Object]", see FIX-3).- storage: createJSONStorage(() => idbStorage),+ // localStorage data on first read. coalescedJSONStorage does the object<->string+ // (de)serialisation createJSONStorage used to do (zustand v5 wants a+ // PersistStorage; a raw StateStorage → "[object Object]", see FIX-3), and adds+ // the write coalescing this store needs.+ storage: chatStorage,// Phase 1 (v2.4.0) — rehydrate legacy singular `toolCall` into `toolCalls[]`.// Persisted shape is whatever was last written; migration runs on every load// and is idempotent, so version bumps are not required.