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
tech(M7): Boot-Chunk 2,61 -> 2,11 MB, Streaming rendert nicht mehr die ganze App
David402ec7e37718
diff --git a/src/api/__tests__/mlx-video-blob-lifetime.test.ts b/src/api/__tests__/mlx-video-blob-lifetime.test.tsnew file mode 100644index 00000000..ab699338--- /dev/null+++ b/src/api/__tests__/mlx-video-blob-lifetime.test.ts@@ -0,0 +1,198 @@+/**+ * M7 · "MLX blob URLs are never released".+ *+ * A `blob:` URL pins its Blob in the renderer until somebody revokes it, and an+ * MLX clip is tens to hundreds of megabytes. The old contract was "caller owns+ * the URL's lifetime (revoke it when the gallery item is dropped, if ever)" —+ * and "if ever" is what happened. Repo count at the time: 27 createObjectURL+ * against 20 revokeObjectURL.+ *+ * Two ends are closed here: mlx-video owns what it mints (re-reading a path+ * replaces its predecessor), and createStore releases an item's media on every+ * path that drops it from the gallery — removal, clear, and the silent+ * overflow past the 200-item cap.+ *+ * Run: npx vitest run src/api/__tests__/mlx-video-blob-lifetime.test.ts+ */+import { describe, it, expect, beforeEach, vi } from 'vitest'++const backendCall = vi.fn()++vi.mock('../backend', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../backend')>()+ return { ...actual, backendCall: (...a: unknown[]) => backendCall(...a) }+})++const {+ readVideoAsBlobUrl, releaseVideoBlobUrl, releaseAllVideoBlobUrls, heldVideoBlobUrlCount,+} = await import('../mlx-video')+const { useCreateStore } = await import('../../stores/createStore')+type GalleryItem = import('../../stores/createStore').GalleryItem++// ── a countable stand-in for the renderer's blob table ─────────────────────+let minted = 0+const live = new Set<string>()++beforeEach(() => {+ releaseAllVideoBlobUrls()+ minted = 0+ live.clear()+ backendCall.mockReset()+ // 'AAAA' decodes to three zero bytes — the payload is irrelevant, the+ // bookkeeping is not.+ backendCall.mockResolvedValue('AAAA')+ globalThis.URL.createObjectURL = () => {+ const url = `blob:test/${++minted}`+ live.add(url)+ return url+ }+ globalThis.URL.revokeObjectURL = (url: string) => { live.delete(url) }+ useCreateStore.setState({ gallery: [], audioInput: null, videoInput: null })+})++function galleryItem(id: string, dataUrl?: string): GalleryItem {+ return {+ id, type: 'video', filename: '', subfolder: '', dataUrl,+ prompt: '', negativePrompt: '', model: '', modelType: 'wan',+ seed: 0, steps: 1, cfgScale: 1, sampler: '', scheduler: '',+ width: 1, height: 1, batchSize: 1, createdAt: 0,+ } as GalleryItem+}++describe('mlx-video owns the URLs it mints', () => {+ it('hands back a blob: URL and tracks it', async () => {+ const url = await readVideoAsBlobUrl('/out/a.mp4')+ expect(url).toMatch(/^blob:/)+ expect(live.has(url)).toBe(true)+ expect(heldVideoBlobUrlCount()).toBe(1)+ })++ it('re-reading the SAME path replaces its predecessor instead of stacking', async () => {+ // A restored tile, a retry, a second look at the same render. Before, each+ // one added another full copy of the clip to the renderer's memory.+ const first = await readVideoAsBlobUrl('/out/a.mp4')+ const second = await readVideoAsBlobUrl('/out/a.mp4')+ expect(second).not.toBe(first)+ expect(live.has(first)).toBe(false)+ expect(live.size).toBe(1)+ expect(heldVideoBlobUrlCount()).toBe(1)+ })++ it('different paths are held side by side — they are different renders', async () => {+ await readVideoAsBlobUrl('/out/a.mp4')+ await readVideoAsBlobUrl('/out/b.mp4')+ expect(live.size).toBe(2)+ expect(heldVideoBlobUrlCount()).toBe(2)+ })++ it('release drops the URL and forgets it', async () => {+ const url = await readVideoAsBlobUrl('/out/a.mp4')+ releaseVideoBlobUrl(url)+ expect(live.size).toBe(0)+ expect(heldVideoBlobUrlCount()).toBe(0)+ })++ it('release is safe on anything that is not a blob: URL of ours', () => {+ expect(() => releaseVideoBlobUrl(undefined)).not.toThrow()+ expect(() => releaseVideoBlobUrl(null)).not.toThrow()+ expect(() => releaseVideoBlobUrl('https://cdn.example/x.mp4')).not.toThrow()+ expect(() => releaseVideoBlobUrl('data:video/mp4;base64,AAAA')).not.toThrow()+ // A https:// result must never be revoked — it is not ours to revoke.+ expect(heldVideoBlobUrlCount()).toBe(0)+ })++ it('a double release is a no-op, not a crash', async () => {+ const url = await readVideoAsBlobUrl('/out/a.mp4')+ releaseVideoBlobUrl(url)+ releaseVideoBlobUrl(url)+ expect(heldVideoBlobUrlCount()).toBe(0)+ })+})++describe('the gallery gives its media back', () => {+ it('removing an item releases its blob', async () => {+ const url = await readVideoAsBlobUrl('/out/a.mp4')+ useCreateStore.getState().addToGallery(galleryItem('one', url))+ useCreateStore.getState().removeFromGallery('one')+ expect(live.size).toBe(0)+ })++ it('clearing the gallery releases every blob it held', async () => {+ for (const p of ['/a.mp4', '/b.mp4', '/c.mp4']) {+ useCreateStore.getState().addToGallery(galleryItem(p, await readVideoAsBlobUrl(p)))+ }+ expect(live.size).toBe(3)+ useCreateStore.getState().clearGallery()+ expect(live.size).toBe(0)+ })++ it('an item pushed off the 200-item cap releases its blob too', async () => {+ // This one had no UI at all: the cap dropped the oldest render silently,+ // and with it the only reference that could ever have revoked its bytes.+ const oldest = await readVideoAsBlobUrl('/oldest.mp4')+ useCreateStore.getState().addToGallery(galleryItem('oldest', oldest))+ for (let i = 0; i < 200; i++) {+ useCreateStore.getState().addToGallery(galleryItem(`fill-${i}`))+ }+ expect(useCreateStore.getState().gallery).toHaveLength(200)+ expect(useCreateStore.getState().gallery.some((g) => g.id === 'oldest')).toBe(false)+ expect(live.has(oldest)).toBe(false)+ })++ it('cloud results are left alone — their URLs are not ours', () => {+ useCreateStore.getState().addToGallery({+ ...galleryItem('cloud'), remoteUrl: 'https://cdn.example/x.mp4', jobId: 'j1',+ } as GalleryItem)+ expect(() => useCreateStore.getState().removeFromGallery('cloud')).not.toThrow()+ })++ it('a patch does NOT revoke the URL the tile may still be loading', () => {+ // updateGalleryItem lands while the tile is on screen (a lazy re-sign, a+ // restore-from-disk). Revoking there would break the very media the patch+ // exists to fix.+ const url = 'blob:test/live'+ live.add(url)+ useCreateStore.getState().addToGallery(galleryItem('one', url))+ useCreateStore.getState().updateGalleryItem('one', { dataUrl: 'blob:test/other' })+ expect(live.has(url)).toBe(true)+ })+})++describe('a staged input file is freed when it is replaced', () => {+ const ref = (name: string) => {+ const url = globalThis.URL.createObjectURL(new Blob())+ return { name, url, blob: new Blob() }+ }++ it('picking another driving video releases the previous pick', () => {+ // SpecialIntentControls mints a fresh blob: URL per pick; five+ // re-selections used to pin five files with only the last reachable.+ const first = ref('a.mp4')+ useCreateStore.getState().setVideoInput(first)+ useCreateStore.getState().setVideoInput(ref('b.mp4'))+ expect(live.has(first.url)).toBe(false)+ expect(live.size).toBe(1)+ })++ it('clearing the slot releases it', () => {+ const first = ref('a.mp4')+ useCreateStore.getState().setVideoInput(first)+ useCreateStore.getState().setVideoInput(null)+ expect(live.size).toBe(0)+ })++ it('the same goes for the voice clip', () => {+ const first = ref('a.wav')+ useCreateStore.getState().setAudioInput(first)+ useCreateStore.getState().setAudioInput(ref('b.wav'))+ expect(live.has(first.url)).toBe(false)+ expect(live.size).toBe(1)+ })++ it('re-setting the identical ref does not revoke the URL still in use', () => {+ const only = ref('a.mp4')+ useCreateStore.getState().setVideoInput(only)+ useCreateStore.getState().setVideoInput(only)+ expect(live.has(only.url)).toBe(true)+ })+})diff --git a/src/api/mlx-video.ts b/src/api/mlx-video.tsindex d555e37f..033aa2e0 100644--- a/src/api/mlx-video.ts+++ b/src/api/mlx-video.ts@@ -132,19 +132,89 @@ export async function cancelVideo(): Promise<{ ok: boolean }> {return invokeMedia<{ ok: boolean }>('video_cancel')}+// ── blob: URL ownership ────────────────────────────────────────────────────+//+// A `blob:` URL pins its Blob in the renderer until someone revokes it, and an+// MLX clip is tens to hundreds of megabytes. The old contract here was "caller+// owns the returned URL's lifetime (revoke it when the gallery item is+// dropped, if ever)" — and "if ever" is what actually happened: nothing+// revoked, so every render of a session stayed resident and a long Create+// session grew until the WebView died. This module owns the URLs it mints+// instead, and `createStore` calls `releaseVideoBlobUrl` when an item leaves+// the gallery.+//+// Keyed by source path so re-reading the same file (a restored tile, a retry)+// replaces its predecessor rather than stacking a second copy of the clip.+const blobUrlByPath = new Map<string, string>()++/** 4 MiB of base64 ≈ 3 MiB of video per slice. Big enough that the loop+ * overhead is irrelevant, small enough that the renderer gets a frame in+ * between — a 200 MB clip used to hold the main thread for the whole decode+ * in one go, which is a visibly frozen app, not a slow one. */+const DECODE_CHUNK = 4 * 1024 * 1024++/** Give the event loop a real turn (a microtask would not let anything paint). */+const yieldToRenderer = () => new Promise<void>((resolve) => setTimeout(resolve, 0))++async function decodeBase64(b64: string): Promise<Uint8Array> {+ const binary = atob(b64)+ const bytes = new Uint8Array(binary.length)+ for (let start = 0; start < binary.length; start += DECODE_CHUNK) {+ const end = Math.min(start + DECODE_CHUNK, binary.length)+ for (let i = start; i < end; i++) bytes[i] = binary.charCodeAt(i)+ if (end < binary.length) await yieldToRenderer()+ }+ return bytes+}+/** Read a finished MLX video's bytes (via the `read_media_file` Rust command,* guarded to the app's own video output dir) and turn them into a `blob:`* URL — the CSP's `media-src` allows `blob:` but not `data:`, so this is* the only way to get `<video>` playback + Download working now that the- * old lu-bridge (:47711/videos/<file>) is gone. Caller owns the returned- * URL's lifetime (revoke it when the gallery item is dropped, if ever). */+ * old lu-bridge (:47711/videos/<file>) is gone.+ *+ * The returned URL is owned by this module: it is revoked when the same path+ * is read again, and when `releaseVideoBlobUrl` is called for it. */export async function readVideoAsBlobUrl(path: string): Promise<string> {const b64 = await backendCall<string>('read_media_file', { path })- const binary = atob(b64)- const bytes = new Uint8Array(binary.length)- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)+ const bytes = await decodeBase64(b64)const blob = new Blob([bytes], { type: 'video/mp4' })- return URL.createObjectURL(blob)+ const url = URL.createObjectURL(blob)+ const previous = blobUrlByPath.get(path)+ if (previous) URL.revokeObjectURL(previous)+ blobUrlByPath.set(path, url)+ return url+}++/**+ * Drop a URL this module minted. Safe to call with anything: a non-blob URL, a+ * URL from another source, `undefined` — only a `blob:` string is revoked, and+ * only entries this module is still tracking are forgotten.+ *+ * Revoking is idempotent, so a double call (item removed, then the gallery+ * cleared) costs nothing.+ */+export function releaseVideoBlobUrl(url: string | null | undefined): void {+ if (!url || !url.startsWith('blob:')) return+ for (const [path, held] of blobUrlByPath) {+ if (held === url) {+ blobUrlByPath.delete(path)+ break+ }+ }+ URL.revokeObjectURL(url)+}++/** Revoke everything still held. For a full gallery clear, and for tests. */+export function releaseAllVideoBlobUrls(): void {+ for (const url of blobUrlByPath.values()) URL.revokeObjectURL(url)+ blobUrlByPath.clear()+}++/** How many URLs this module is still holding. Test-facing; a leak is a+ * number that only ever goes up. */+export function heldVideoBlobUrlCount(): number {+ return blobUrlByPath.size}// ── Create-tab wiring (mirrors mlx-image.ts's synthetic-model pattern) ──diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsxindex 657c9e38..0834ce00 100644--- a/src/components/chat/ChatView.tsx+++ b/src/components/chat/ChatView.tsx@@ -36,7 +36,17 @@ import { useRemoteStore } from '../../stores/remoteStore'export function ChatView() {const { sendMessage, stopGeneration, isGenerating, isLoadingModel, regenerateMessage, editAndResend, pendingApproval, approveToolCall, rejectToolCall } = useChat()const activeConversationId = useChatStore((s) => s.activeConversationId)- const conversations = useChatStore((s) => s.conversations)+ // NOT `s.conversations`. That array is replaced on every streaming flush, so+ // subscribing to it re-reconciled the entire chat chrome — composer, plan+ // bar, header controls, none of them memoised — once per frame for the whole+ // duration of an answer, which is why typing during a run felt broken. The+ // only thing this component needs from the conversation while it renders is+ // its mode; a string stands still while tokens arrive. Everything else+ // (model, system prompt, the export payload) is read at click time from+ // getState(), where a fresh value is what you want anyway.+ const activeConvMode = useChatStore(+ (s) => s.conversations.find((c) => c.id === s.activeConversationId)?.mode,+ )const activeModel = useModelStore((s) => s.activeModel)const models = useModelStore((s) => s.models)const [ragPanelOpen, setRagPanelOpen] = useState(false)@@ -79,8 +89,7 @@ export function ChatView() {const remoteClearError = useRemoteStore((s) => s.clearError)const connectedDevices = useRemoteStore((s) => s.connectedDevices)const refreshDevices = useRemoteStore((s) => s.refreshDevices)- const activeConv = conversations.find((c) => c.id === activeConversationId)- const isRemoteChat = activeConv?.mode === 'remote'+ const isRemoteChat = activeConvMode === 'remote'const isThisRemoteActive = isRemoteChat && remoteEnabled && dispatchedConversationId === activeConversationIdconst isThisRemoteStopped = isRemoteChat && !isThisRemoteActiveconst mobileConnectedCount = connectedDevices.length@@ -127,7 +136,10 @@ export function ChatView() {}, [pendingApproval, approveToolCall, rejectToolCall])const handleRemoteReactivate = async () => {- if (!activeConv || !activeConversationId) return+ if (!activeConversationId) return+ const activeConv = useChatStore.getState().conversations+ .find((c) => c.id === activeConversationId)+ if (!activeConv) returntry {await remoteRestart(activeConv.model, activeConv.systemPrompt)useRemoteStore.setState({ dispatchedConversationId: activeConversationId })@@ -226,7 +238,8 @@ export function ChatView() {<buttonkey={fmt}onClick={async () => {- const conv = conversations.find(c => c.id === activeConversationId)+ const conv = useChatStore.getState().conversations+ .find(c => c.id === activeConversationId)setExportOpen(false)if (!conv) returnconst result = await exportConversation(conv, fmt)diff --git a/src/components/chat/CodeBlock.tsx b/src/components/chat/CodeBlock.tsxindex d72c97dc..dd5efa9e 100644--- a/src/components/chat/CodeBlock.tsx+++ b/src/components/chat/CodeBlock.tsx@@ -1,8 +1,132 @@import { useState } from 'react'-import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'-import { oneDark } from 'react-syntax-highlighter/dist/esm/styles/prism'+// PrismLight, NOT the `Prism` barrel. The barrel pulls refractor's ~300+// grammars into the boot chunk (~570 kB of a 2.61 MB App chunk) for a+// highlighter that realistically sees a dozen languages. PrismLight ships the+// engine only; every grammar below is an explicit opt-in.+import SyntaxHighlighter from 'react-syntax-highlighter/dist/esm/prism-light'+// Deep path on purpose: `styles/prism` is a barrel over 46 themes.+import oneDark from 'react-syntax-highlighter/dist/esm/styles/prism/one-dark'import { Copy, Check, ChevronDown } from 'lucide-react'+// ── Grammars ───────────────────────────────────────────────────────────────+//+// What an LLM chat realistically emits, plus everything the Explorer's file+// preview can ask for (see LANGUAGE in lib/file-preview.ts) — a preview that+// silently lost its colours would be a regression, not a saving.+//+// refractor resolves a grammar's own dependencies on registration (tsx pulls+// jsx + typescript, cpp pulls c, csharp pulls clike, php pulls+// markup-templating), so the list stays at the languages a user can name.+import bash from 'react-syntax-highlighter/dist/esm/languages/prism/bash'+import batch from 'react-syntax-highlighter/dist/esm/languages/prism/batch'+import c from 'react-syntax-highlighter/dist/esm/languages/prism/c'+import cpp from 'react-syntax-highlighter/dist/esm/languages/prism/cpp'+import csharp from 'react-syntax-highlighter/dist/esm/languages/prism/csharp'+import css from 'react-syntax-highlighter/dist/esm/languages/prism/css'+import dart from 'react-syntax-highlighter/dist/esm/languages/prism/dart'+import diff from 'react-syntax-highlighter/dist/esm/languages/prism/diff'+import docker from 'react-syntax-highlighter/dist/esm/languages/prism/docker'+import go from 'react-syntax-highlighter/dist/esm/languages/prism/go'+import graphql from 'react-syntax-highlighter/dist/esm/languages/prism/graphql'+import groovy from 'react-syntax-highlighter/dist/esm/languages/prism/groovy'+import hcl from 'react-syntax-highlighter/dist/esm/languages/prism/hcl'+import ini from 'react-syntax-highlighter/dist/esm/languages/prism/ini'+import java from 'react-syntax-highlighter/dist/esm/languages/prism/java'+import javascript from 'react-syntax-highlighter/dist/esm/languages/prism/javascript'+import json from 'react-syntax-highlighter/dist/esm/languages/prism/json'+import jsx from 'react-syntax-highlighter/dist/esm/languages/prism/jsx'+import kotlin from 'react-syntax-highlighter/dist/esm/languages/prism/kotlin'+import less from 'react-syntax-highlighter/dist/esm/languages/prism/less'+import lua from 'react-syntax-highlighter/dist/esm/languages/prism/lua'+import makefile from 'react-syntax-highlighter/dist/esm/languages/prism/makefile'+import markdown from 'react-syntax-highlighter/dist/esm/languages/prism/markdown'+import markup from 'react-syntax-highlighter/dist/esm/languages/prism/markup'+import php from 'react-syntax-highlighter/dist/esm/languages/prism/php'+import powershell from 'react-syntax-highlighter/dist/esm/languages/prism/powershell'+import python from 'react-syntax-highlighter/dist/esm/languages/prism/python'+import r from 'react-syntax-highlighter/dist/esm/languages/prism/r'+import ruby from 'react-syntax-highlighter/dist/esm/languages/prism/ruby'+import rust from 'react-syntax-highlighter/dist/esm/languages/prism/rust'+import scss from 'react-syntax-highlighter/dist/esm/languages/prism/scss'+import sql from 'react-syntax-highlighter/dist/esm/languages/prism/sql'+import swift from 'react-syntax-highlighter/dist/esm/languages/prism/swift'+import toml from 'react-syntax-highlighter/dist/esm/languages/prism/toml'+import tsx from 'react-syntax-highlighter/dist/esm/languages/prism/tsx'+import typescript from 'react-syntax-highlighter/dist/esm/languages/prism/typescript'+import yaml from 'react-syntax-highlighter/dist/esm/languages/prism/yaml'++/** The grammars registered above, keyed by the name refractor knows them as. */+const GRAMMARS: Record<string, unknown> = {+ bash, batch, c, cpp, csharp, css, dart, diff, docker, go, graphql, groovy,+ hcl, ini, java, javascript, json, jsx, kotlin, less, lua, makefile, markdown,+ markup, php, powershell, python, r, ruby, rust, scss, sql, swift, toml, tsx,+ typescript, yaml,+}++for (const [name, grammar] of Object.entries(GRAMMARS)) {+ SyntaxHighlighter.registerLanguage(name, grammar)+}++/**+ * Names refractor answers to once the grammars above are registered — the+ * canonical ids plus the aliases each grammar brings with it (bash→sh/shell,+ * typescript→ts, python→py, markup→html/xml/svg, csharp→cs, …).+ *+ * Hardcoded rather than read from refractor so nothing outside this file has+ * to import the transitive dependency; `CodeBlock.test.ts` cross-checks the+ * set against refractor's real `listLanguages()` so it cannot drift.+ *+ * refractor's built-in plain-text family (`plain`, `plaintext`, `text`, `txt`)+ * is deliberately NOT in here: those must normalise to 'text', which is the+ * branch the highlighter short-circuits before it ever consults a grammar.+ */+export const PRISM_LANGUAGES: ReadonlySet<string> = new Set([+ 'atom', 'bash', 'batch', 'c', 'clike', 'cpp', 'cs', 'csharp', 'css', 'dart',+ 'diff', 'docker', 'dockerfile', 'dotnet', 'go', 'graphql', 'groovy', 'hcl',+ 'html', 'ini', 'java', 'javascript', 'js', 'json', 'jsx', 'kotlin', 'kt',+ 'kts', 'less', 'lua', 'makefile', 'markdown', 'markup', 'markup-templating',+ 'mathml', 'md', 'php', 'powershell', 'py', 'python', 'r', 'rb', 'rss',+ 'ruby', 'rust', 'scss', 'sh', 'shell', 'sql', 'ssml', 'svg', 'swift', 'toml',+ 'ts', 'tsx', 'typescript', 'webmanifest', 'xml', 'yaml', 'yml',+])++/**+ * Fence tags LLMs write that refractor has no alias for. Everything else is+ * either a real id, a real alias, or unknown.+ */+const LANGUAGE_ALIASES: Record<string, string> = {+ 'c#': 'csharp',+ 'c++': 'cpp',+ console: 'bash',+ golang: 'go',+ htm: 'markup',+ jsonc: 'json',+ objectivec: 'c',+ 'obj-c': 'c',+ shellsession: 'bash',+ 'shell-session': 'bash',+ terraform: 'hcl',+ tf: 'hcl',+ rs: 'rust',+ zsh: 'bash',+}++/**+ * Map a fence tag onto a grammar this build actually ships.+ *+ * Unknown tags must land on plain text, never on a throw: the highlighter's+ * own refractor path does catch the "not registered" error, but relying on a+ * library's catch to keep the chat rendering is not a guarantee. Returning+ * 'text' takes the documented no-highlight branch instead.+ */+export function highlightLanguageFor(language?: string): string {+ if (!language) return 'text'+ const key = language.trim().toLowerCase()+ if (!key) return 'text'+ const mapped = LANGUAGE_ALIASES[key] ?? key+ return PRISM_LANGUAGES.has(mapped) ? mapped : 'text'+}+interface Props {code: stringlanguage?: string@@ -63,7 +187,10 @@ export function CodeBlock({ code, language }: Props) {</button></div><SyntaxHighlighter- language={language || 'text'}+ // The RAW tag stays in the header label above; only the highlighter+ // gets the normalised one, so an unknown fence still shows what the+ // model called it while rendering as plain text.+ language={highlightLanguageFor(language)}style={oneDark}customStyle={{margin: 0,diff --git a/src/components/chat/MessageList.tsx b/src/components/chat/MessageList.tsxindex 57a08993..fae39287 100644--- a/src/components/chat/MessageList.tsx+++ b/src/components/chat/MessageList.tsx@@ -1,9 +1,47 @@-import { useCallback, useRef } from 'react'+import { useCallback, useRef, useState } from 'react'+import type { CSSProperties } from 'react'import { useChatStore } from '../../stores/chatStore'import { useAutoScroll } from '../../hooks/useAutoScroll'import { MessageBubble } from './MessageBubble'import { WorkingAnchor } from './WorkingAnchor'+/**+ * Above this many visible messages the transcript stops paying full layout ++ * paint for the part of itself nobody is looking at.+ *+ * Why `content-visibility` and NOT a windowed slice: the list has exactly one+ * scroll mechanism (useAutoScroll pins to `scrollHeight` and re-pins from a+ * ResizeObserver on the content wrapper), and a slice would have to reproduce+ * that pin, the streaming follow, and the "sending jumps to the bottom" resume+ * on top of a moving set of mounted nodes. `content-visibility: auto` keeps+ * every message mounted and every id in the DOM — the pin, the observer, the+ * resume key, Cmd+F and the measure column are all untouched — and lets the+ * engine skip layout/paint for off-screen subtrees instead.+ *+ * The gate is deliberately NOT the audit's plain `length >= 200` check on+ * every render: flipping the property on mid-conversation would collapse every+ * off-screen bubble above the fold to its intrinsic-size estimate in one frame+ * and yank a reader who is scrolled up. It is decided once, when a+ * conversation becomes the active one, so the property is either on from the+ * first paint or off for that visit — never a switch under a live thread.+ */+const CONTENT_VISIBILITY_THRESHOLD = 200++/**+ * The tail stays fully rendered no matter what. The streaming bubble is+ * on-screen (so `auto` would render it anyway), but an exact height at the+ * bottom edge is what the auto-scroll pin measures against, and an estimate+ * there is the one place a wrong guess is visible.+ */+const ALWAYS_RENDERED_TAIL = 3++/** `auto` = keep the real height once a bubble has been rendered; the 8rem is+ * only the never-yet-seen guess. */+const SKIPPABLE: CSSProperties = {+ contentVisibility: 'auto',+ containIntrinsicSize: 'auto 8rem',+}+interface Props {/** GLOBAL generating flag — guards regenerate/edit so a second concurrent* send (which shares the chat hook's stream refs) can't corrupt an in-flight@@ -60,11 +98,26 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModelif (c && cb) cb(c.id, messageId, content)}, [])+ // Decided once per visited conversation, see CONTENT_VISIBILITY_THRESHOLD.+ // React's documented "adjust state when a prop changes" shape: the branch+ // below re-runs this component immediately and only this component, so the+ // gate is settled before anything paints.+ const [skipGate, setSkipGate] = useState<{ id: string | null; on: boolean }>({ id: null, on: false })+if (!conversation) return nullconst visibleMessages = conversation.messages.filter((m) => m.role !== 'system' && !m.hidden)const lastVisibleId = visibleMessages[visibleMessages.length - 1]?.id+ if (skipGate.id !== conversation.id) {+ setSkipGate({+ id: conversation.id,+ on: visibleMessages.length >= CONTENT_VISIBILITY_THRESHOLD,+ })+ }+ const skipOffscreen = skipGate.id === conversation.id && skipGate.on+ const tailStart = visibleMessages.length - ALWAYS_RENDERED_TAIL+return (<divref={scrollRef}@@ -79,24 +132,31 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModelanchor included (G33). */}<div ref={contentRef} className="mx-auto w-full max-w-[var(--lu-measure)]">{visibleMessages- .map((message) => (- <MessageBubble+ .map((message, index) => (+ // The wrapper carries the skip hint so MessageBubble keeps owning+ // its own root class. It is a plain block inside a plain block, so+ // it adds no layout of its own.+ <divkey={message.id}- message={message}- isLast={message.id === lastVisibleId}- // The live generating flag, not `message.usage`: a backend that- // never reports usage would lose the action bar for good.- isStreaming={showTyping && message.id === lastVisibleId && message.role === 'assistant'}- onRegenerate={message.role === 'assistant' && onRegenerate && !isGenerating- ? handleRegenerate- : undefined}- onEdit={message.role === 'user' && onEdit && !isGenerating- ? handleEdit- : undefined}- pendingApprovalId={pendingApprovalId}- onApprove={onApprove}- onReject={onReject}- />+ style={skipOffscreen && index < tailStart ? SKIPPABLE : undefined}+ >+ <MessageBubble+ message={message}+ isLast={message.id === lastVisibleId}+ // The live generating flag, not `message.usage`: a backend that+ // never reports usage would lose the action bar for good.+ isStreaming={showTyping && message.id === lastVisibleId && message.role === 'assistant'}+ onRegenerate={message.role === 'assistant' && onRegenerate && !isGenerating+ ? handleRegenerate+ : undefined}+ onEdit={message.role === 'user' && onEdit && !isGenerating+ ? handleEdit+ : undefined}+ pendingApprovalId={pendingApprovalId}+ onApprove={onApprove}+ onReject={onReject}+ />+ </div>))}{/* The run anchor stays visible the entire time the agent is stillworking, including between tool calls and while the final answerdiff --git a/src/components/chat/__tests__/long-transcripts-stay-cheap.test.ts b/src/components/chat/__tests__/long-transcripts-stay-cheap.test.tsnew file mode 100644index 00000000..2a1e0ea5--- /dev/null+++ b/src/components/chat/__tests__/long-transcripts-stay-cheap.test.ts@@ -0,0 +1,100 @@+/**+ * M7 · RP-1: a long conversation opened every message as a full layout + paint+ * in one synchronous commit, and kept paying for the part of itself nobody was+ * looking at on every streaming frame.+ *+ * The fix is `content-visibility: auto` on the off-screen part of the list, NOT+ * a windowed slice. That choice is the thing this file guards: a slice would+ * unmount messages, and this list's entire scroll behaviour — the pin to+ * `scrollHeight`, the ResizeObserver re-pin (G33), the "sending jumps to the+ * bottom" resume key (G31/G33), Cmd+F over the transcript — is built on every+ * message being in the DOM. So the invariant is: still N nodes, just cheaper+ * ones.+ *+ * There is no render harness in this repo, so this is guarded at the source,+ * like tool-media-lifetime.test.ts and scroll-pins-bottom.test.ts.+ *+ * Run: npx vitest run src/components/chat/__tests__/long-transcripts-stay-cheap.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'++const read = (rel: string) => readFileSync(resolve(__dirname, rel), 'utf8')+const list = read('../MessageList.tsx')+const hook = read('../../../hooks/useAutoScroll.ts')++describe('every message stays mounted — no window, no slice', () => {+ it('the whole filtered list is still mapped', () => {+ expect(list).toMatch(/visibleMessages\s*\n?\s*\.map\(\(message, index\) =>/)+ })++ it('nothing slices, windows or paginates the message array', () => {+ // A slice is what would break the pin, the resume key and Cmd+F.+ expect(list).not.toMatch(/visibleMessages\.slice\(/)+ expect(list).not.toMatch(/react-window|react-virtuoso|virtua/)+ expect(list).not.toMatch(/IntersectionObserver/)+ })++ it('the scroll contract is untouched', () => {+ // Same hook, same trigger, same resume key as before the change.+ expect(list).toContain('useAutoScroll(')+ expect(list).toContain('lastUserMessage?.id')+ expect(list).toContain('ref={contentRef}')+ expect(hook).toContain('new ResizeObserver(')+ })++ it('the Working anchor is still inside the observed wrapper (G33)', () => {+ const wrapper = list.indexOf('ref={contentRef}')+ const anchor = list.indexOf('<WorkingAnchor')+ expect(wrapper).toBeGreaterThan(-1)+ expect(anchor).toBeGreaterThan(wrapper)+ })++ it('the measure column is untouched', () => {+ // W1 introduced this; a virtualisation rewrite is exactly the kind of+ // change that quietly drops it.+ expect(list).toContain('max-w-[var(--lu-measure)]')+ })+})++describe('off-screen messages skip layout and paint', () => {+ it('carries content-visibility with a remembered intrinsic size', () => {+ expect(list).toContain("contentVisibility: 'auto'")+ // `auto` in contain-intrinsic-size = keep the real height once a bubble has+ // been rendered. Without it every scroll-back would re-guess.+ expect(list).toMatch(/containIntrinsicSize: 'auto /)+ })++ it('the hint sits on a wrapper, so MessageBubble keeps owning its root', () => {+ const wrapperIdx = list.indexOf('style={skipOffscreen && index < tailStart')+ const bubbleIdx = list.indexOf('<MessageBubble')+ expect(wrapperIdx).toBeGreaterThan(-1)+ expect(bubbleIdx).toBeGreaterThan(wrapperIdx)+ })++ it('the tail is never skippable', () => {+ // The bottom edge is what the auto-scroll pin measures against; an+ // estimated height there is the one place a wrong guess shows.+ expect(list).toContain('const ALWAYS_RENDERED_TAIL = 3')+ expect(list).toContain('const tailStart = visibleMessages.length - ALWAYS_RENDERED_TAIL')+ expect(list).toContain('index < tailStart')+ })+})++describe('the gate is decided per conversation, not per render', () => {+ it('short transcripts are completely unaffected', () => {+ expect(list).toContain('const CONTENT_VISIBILITY_THRESHOLD = 200')+ expect(list).toContain('visibleMessages.length >= CONTENT_VISIBILITY_THRESHOLD')+ })++ it('it is keyed on the conversation id, so it cannot flip mid-thread', () => {+ // A plain `length >= 200` re-evaluated every render would flip the+ // property on at message 200 of a LIVE thread: every off-screen bubble+ // above the fold collapses to its estimate in one frame, and a reader who+ // is scrolled up gets yanked. Latching on the id makes the answer either+ // "on from the first paint" or "off for this visit".+ expect(list).toContain('if (skipGate.id !== conversation.id)')+ expect(list).toContain('const skipOffscreen = skipGate.id === conversation.id && skipGate.on')+ })+})diff --git a/src/components/create/experimental/SpecialIntentControls.tsx b/src/components/create/experimental/SpecialIntentControls.tsxindex 39224f9e..926b66d2 100644--- a/src/components/create/experimental/SpecialIntentControls.tsx+++ b/src/components/create/experimental/SpecialIntentControls.tsx@@ -44,6 +44,13 @@ export function SpecialControls({ intent }: { intent: CreateIntent }) {// ── shared chip: a small labeled file slot (audio/video/image) ──────────────+/** A staged file plus a `blob:` preview URL for it.+ *+ * The URL's lifetime is closed in createStore's `setAudioInput` /+ * `setVideoInput` (see `releaseReplacedMediaRef`): those two setters are the+ * only way a slot is written, so replacing or clearing a pick always frees+ * the file the previous pick pinned. Do NOT revoke here — the ref outlives+ * this component, it lives in the store. */function mediaRefFrom(file: File): MediaRef {return { name: file.name, url: URL.createObjectURL(file), blob: file }}diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsxindex 683b9abc..1892579b 100644--- a/src/components/layout/AppShell.tsx+++ b/src/components/layout/AppShell.tsx@@ -48,8 +48,14 @@ let resolveRestoreDecided: () => void = () => {}const restoreDecided = new Promise<void>((resolve) => { resolveRestoreDecided = resolve })export function AppShell() {- const { currentView } = useUIStore()- const { settings, updateSettings } = useSettingsStore()+ // Targeted, NOT `useUIStore()`. A whole-store subscription here put the+ // entire app tree behind every uiStore write — and the explorer's resize+ // handle writes `explorerWidth` on every pointermove, so dragging the+ // divider re-rendered Titlebar, Header, Sidebar and the whole active view at+ // pointer-event frequency. Only `currentView` matters to this component.+ const currentView = useUIStore((s) => s.currentView)+ const settings = useSettingsStore((s) => s.settings)+ const updateSettings = useSettingsStore((s) => s.updateSettings)// A/B Compare takes over the chat area; hide the left chat sidebar entirely// while comparing (David 2026-06-06) so the two model columns get full width.const isComparing = useCompareStore((s) => s.isComparing)diff --git a/src/components/layout/Sidebar.tsx b/src/components/layout/Sidebar.tsxindex cb12879c..e961936c 100644--- a/src/components/layout/Sidebar.tsx+++ b/src/components/layout/Sidebar.tsx@@ -1,4 +1,4 @@-import { useState, useEffect } from 'react'+import { useDeferredValue, useEffect, useMemo, useRef, useState } from 'react'import { motion, AnimatePresence } from 'framer-motion'import { Plus, Search, Trash2, Edit3, Check, X, MessageSquare, Code, Radio, Copy, RefreshCw, Square, Wifi, Globe, QrCode } from 'lucide-react'import { useChatStore } from '../../stores/chatStore'@@ -8,23 +8,59 @@ import { useSettingsStore } from '../../stores/settingsStore'import { useCodexStore } from '../../stores/codexStore'import { useRemoteStore, REMOTE_DEV_MODE_ERROR } from '../../stores/remoteStore'import { backendCall, isTauri } from '../../api/backend'-import { formatDate, truncate } from '../../lib/formatters'+import { truncate } from '../../lib/formatters'+import {+ conversationMatches, sameSidebarRows, toSidebarRow, type SidebarRow,+} from './sidebar-rows'export function Sidebar() {- const { conversations, activeConversationId, createConversation, deleteConversation, renameConversation, setActiveConversation } = useChatStore()- const { sidebarOpen, setView } = useUIStore()- const { activeModel } = useModelStore()- const { getActivePersona } = useSettingsStore()+ // Targeted selectors throughout. A whole-store subscription here re-rendered+ // the entire sidebar once per animation frame for the full duration of every+ // streamed answer — and it did so even while another view was on screen,+ // because AppShell mounts the sidebar unconditionally.+ const activeConversationId = useChatStore((s) => s.activeConversationId)+ const createConversation = useChatStore((s) => s.createConversation)+ const deleteConversation = useChatStore((s) => s.deleteConversation)+ const renameConversation = useChatStore((s) => s.renameConversation)+ const setActiveConversation = useChatStore((s) => s.setActiveConversation)+ const sidebarOpen = useUIStore((s) => s.sidebarOpen)+ const setView = useUIStore((s) => s.setView)+ const activeModel = useModelStore((s) => s.activeModel)+ const getActivePersona = useSettingsStore((s) => s.getActivePersona)const personasEnabled = useSettingsStore((s) => s.settings.personasEnabled)const chatMode = useCodexStore((s) => s.chatMode)const setChatMode = useCodexStore((s) => s.setChatMode)- const {- enabled: remoteEnabled, passcode, passcodeExpiresAt, lanUrl, mobileUrl,- qrPngBase64, loading: remoteLoading, error: remoteError,- tunnelActive, tunnelUrl, tunnelLoading, awaitingTunnel,- qrVisible, hideQr, refreshDevices,- dispatchedConversationId, dispatch, undispatch, regenerateToken, restart,- } = useRemoteStore()+ const remoteEnabled = useRemoteStore((s) => s.enabled)+ const passcode = useRemoteStore((s) => s.passcode)+ const passcodeExpiresAt = useRemoteStore((s) => s.passcodeExpiresAt)+ const lanUrl = useRemoteStore((s) => s.lanUrl)+ const mobileUrl = useRemoteStore((s) => s.mobileUrl)+ const qrPngBase64 = useRemoteStore((s) => s.qrPngBase64)+ const remoteLoading = useRemoteStore((s) => s.loading)+ const remoteError = useRemoteStore((s) => s.error)+ const tunnelActive = useRemoteStore((s) => s.tunnelActive)+ const tunnelUrl = useRemoteStore((s) => s.tunnelUrl)+ const tunnelLoading = useRemoteStore((s) => s.tunnelLoading)+ const awaitingTunnel = useRemoteStore((s) => s.awaitingTunnel)+ const qrVisible = useRemoteStore((s) => s.qrVisible)+ const hideQr = useRemoteStore((s) => s.hideQr)+ const refreshDevices = useRemoteStore((s) => s.refreshDevices)+ const dispatchedConversationId = useRemoteStore((s) => s.dispatchedConversationId)+ const dispatch = useRemoteStore((s) => s.dispatch)+ const undispatch = useRemoteStore((s) => s.undispatch)+ const regenerateToken = useRemoteStore((s) => s.regenerateToken)+ const restart = useRemoteStore((s) => s.restart)++ // The list subscribes to the PROJECTION, not to `conversations`. The array+ // itself is replaced on every streaming flush; the projected rows are not,+ // so the selector hands back the very same array and React skips the render.+ const rowCache = useRef<SidebarRow[]>([])+ const rows = useChatStore((s) => {+ const next = s.conversations.map(toSidebarRow)+ if (sameSidebarRows(rowCache.current, next)) return rowCache.current+ rowCache.current = next+ return next+ })const [search, setSearch] = useState('')const [editingId, setEditingId] = useState<string | null>(null)const [editTitle, setEditTitle] = useState('')@@ -41,15 +77,35 @@ export function Sidebar() {const isRemoteMode = chatMode === 'remote'// Filter conversations by current mode- const modeConversations = conversations.filter(c => (c.mode || 'lu') === chatMode)+ const modeConversations = useMemo(+ () => rows.filter((r) => r.mode === chatMode),+ [rows, chatMode],+ )- const filtered = search- ? modeConversations.filter(- (c) =>- c.title.toLowerCase().includes(search.toLowerCase()) ||- c.messages.some((m) => m.content.toLowerCase().includes(search.toLowerCase()))- )- : modeConversations+ // The corpus scan used to run inside the render body against the RAW query,+ // so every streaming frame re-lowercased every message of every chat while+ // the search box had focus. It now runs in a memo keyed on the projected+ // rows (which stand still during streaming) and on a deferred query, and it+ // reads the message bodies through getState() — the bodies must not be part+ // of this component's subscription, or the projection above would be moot.+ const deferredSearch = useDeferredValue(search)+ const needle = deferredSearch.trim().toLowerCase()+ const matches = useMemo(() => {+ if (!needle) return null+ // `rows` is both the freshness signal and the id allowlist: a chat that is+ // not in the projection cannot be in the result list either.+ const known = new Set(rows.map((r) => r.id))+ const hits = new Set<string>()+ for (const c of useChatStore.getState().conversations) {+ if (known.has(c.id) && conversationMatches(c, needle)) hits.add(c.id)+ }+ return hits+ }, [needle, rows])++ const filtered = useMemo(+ () => (matches ? modeConversations.filter((r) => matches.has(r.id)) : modeConversations),+ [matches, modeConversations],+ )const handleNewChat = () => {if (!activeModel) {@@ -180,10 +236,14 @@ export function Sidebar() {// receives its first message, OR (b) as soon as a mobile has authenticated.// refreshDevices() itself sets qrVisible=false when devices.length > 0,// so here we only need to keep the polling alive.- const dispatchedConv = dispatchedConversationId- ? conversations.find((c) => c.id === dispatchedConversationId)- : null- const dispatchedMessageCount = dispatchedConv?.messages.length ?? 0+ // Just the COUNT, straight out of the store: a number changes when a message+ // lands, not on every token of it, so the QR panel's auto-hide no longer+ // drags the whole sidebar along for the ride.+ const dispatchedMessageCount = useChatStore((s) =>+ dispatchedConversationId+ ? s.conversations.find((c) => c.id === dispatchedConversationId)?.messages.length ?? 0+ : 0,+ )useEffect(() => {if (qrVisible && dispatchedMessageCount > 0) hideQr()}, [qrVisible, dispatchedMessageCount, hideQr])@@ -308,7 +368,10 @@ export function Sidebar() {</button><buttononClick={() => {- const conv = conversations.find((c) => c.id === dispatchedConversationId)+ // Read at click time: the row projection carries what a+ // row paints, not the model/system prompt.+ const conv = useChatStore.getState().conversations+ .find((c) => c.id === dispatchedConversationId)restart(conv?.model, conv?.systemPrompt)}}disabled={remoteLoading}@@ -454,7 +517,8 @@ export function Sidebar() {<span className="w-1.5 h-1.5 rounded-full bg-green-400 shrink-0" />)}<p className="text-[0.66rem] truncate flex-1 min-w-0">{truncate(conv.title, 30)}</p>- <span className="text-[0.5rem] text-gray-600 shrink-0">{formatDate(conv.updatedAt)}</span>+ {/* Already formatted in the projection — see SidebarRow. */}+ <span className="text-[0.5rem] text-gray-600 shrink-0">{conv.date}</span></div>)}</div>@@ -602,7 +666,7 @@ export function Sidebar() {<buttonrole="menuitem"onClick={() => {- const conv = conversations.find((c) => c.id === rowMenu.id)+ const conv = rows.find((r) => r.id === rowMenu.id)setEditingId(rowMenu.id)setEditTitle(conv?.title ?? '')setRowMenu(null)diff --git a/src/components/layout/__tests__/streaming-does-not-repaint-the-app.test.ts b/src/components/layout/__tests__/streaming-does-not-repaint-the-app.test.tsnew file mode 100644index 00000000..3074114b--- /dev/null+++ b/src/components/layout/__tests__/streaming-does-not-repaint-the-app.test.ts@@ -0,0 +1,219 @@+/**+ * M7 · "Der Boot-Chunk ist zu 22 % Syntax-Highlighting", the three+ * subscription findings: Sidebar, ChatView and AppShell each subscribed to a+ * whole store, so the entire sidebar, the entire chat chrome and the entire+ * app tree re-rendered once per animation frame for the full duration of every+ * streamed answer.+ *+ * The first half of this file MEASURES that on the real chatStore: it streams+ * 300 tokens into a message and counts how often each subscription shape would+ * have woken React. The second half guards the source, because there is no+ * render harness in this repo (same approach as tool-media-lifetime.test.ts).+ *+ * Run: npx vitest run src/components/layout/__tests__/streaming-does-not-repaint-the-app.test.ts+ */+import { describe, it, expect, beforeEach } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { useChatStore } from '../../../stores/chatStore'+import { sameSidebarRows, toSidebarRow, conversationMatches, type SidebarRow } from '../sidebar-rows'+import type { Message } from '../../../types/chat'++const SRC = resolve(__dirname, '..', '..', '..')+const read = (...p: string[]) => readFileSync(resolve(SRC, ...p), 'utf8')++/** Strip comments: the negative guards below look for a subscription SHAPE,+ * and the comments explaining why that shape is gone contain it verbatim. */+const codeOnly = (src: string) =>+ src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1')++const sidebar = codeOnly(read('components', 'layout', 'Sidebar.tsx'))+const appShell = codeOnly(read('components', 'layout', 'AppShell.tsx'))+const chatView = codeOnly(read('components', 'chat', 'ChatView.tsx'))++const TOKENS = 300++function message(overrides: Partial<Message> = {}): Message {+ return {+ id: `m-${Math.random().toString(36).slice(2)}`,+ role: 'assistant',+ content: '',+ timestamp: Date.now(),+ ...overrides,+ }+}++/**+ * Run a selector after every one of TOKENS streamed appends and count how many+ * distinct values it produced. That count IS the number of renders the+ * component would have been woken for.+ */+function wakeUpsWhileStreaming<T>(selector: (s: ReturnType<typeof useChatStore.getState>) => T): number {+ const id = useChatStore.getState().createConversation('m', '', 'lu')+ const m = message()+ useChatStore.getState().addMessage(id, m)++ let previous = selector(useChatStore.getState())+ let wakeUps = 1 // the first render+ let content = ''+ for (let i = 0; i < TOKENS; i++) {+ content += 'token '+ useChatStore.getState().updateMessageContent(id, m.id, content)+ const next = selector(useChatStore.getState())+ if (!Object.is(next, previous)) {+ wakeUps+++ previous = next+ }+ }+ return wakeUps+}++beforeEach(() => {+ useChatStore.setState({ conversations: [], activeConversationId: null })+})++describe('what a streamed answer costs each subscription shape', () => {+ it('the whole store wakes the subscriber on every single token', () => {+ // This is the shape Sidebar (useChatStore()) and AppShell (useUIStore())+ // used. The number is the finding.+ expect(wakeUpsWhileStreaming((s) => s)).toBe(TOKENS + 1)+ })++ it('so does the bare conversations array — the ChatView shape', () => {+ // A "targeted" selector is not automatically a cheap one: the array is+ // REPLACED on every flush, so `s.conversations` changes identity as often+ // as the whole store does.+ expect(wakeUpsWhileStreaming((s) => s.conversations)).toBe(TOKENS + 1)+ })++ it('the mode of the active conversation wakes it exactly once', () => {+ // ChatView's replacement: a string that does not move while tokens arrive.+ const wakeUps = wakeUpsWhileStreaming(+ (s) => s.conversations.find((c) => c.id === s.activeConversationId)?.mode,+ )+ expect(wakeUps).toBe(1)+ })++ it('the sidebar row projection wakes it exactly once', () => {+ // The production selector, verbatim: project, and hand back the previous+ // array whenever the projection is unchanged.+ let cache: SidebarRow[] = []+ const wakeUps = wakeUpsWhileStreaming((s) => {+ const next = s.conversations.map(toSidebarRow)+ if (sameSidebarRows(cache, next)) return cache+ cache = next+ return next+ })+ expect(wakeUps).toBe(1)+ })++ it('the message COUNT wakes it per message, not per token', () => {+ // The dispatched-chat QR auto-hide reads this. One append, one wake-up.+ expect(wakeUpsWhileStreaming((s) => s.conversations[0]?.messages.length ?? 0)).toBe(1)+ })+})++describe('the projection still reflects everything a row paints', () => {+ it('a rename changes the projection', () => {+ const a = [toSidebarRow({ id: '1', title: 'Old', messages: [], model: '', systemPrompt: '', createdAt: 0, updatedAt: 0 })]+ const b = [toSidebarRow({ id: '1', title: 'New', messages: [], model: '', systemPrompt: '', createdAt: 0, updatedAt: 0 })]+ expect(sameSidebarRows(a, b)).toBe(false)+ })++ it('a new chat changes the projection', () => {+ const base = { title: 'x', messages: [], model: '', systemPrompt: '', createdAt: 0, updatedAt: 0 }+ const a = [toSidebarRow({ ...base, id: '1' })]+ const b = [toSidebarRow({ ...base, id: '1' }), toSidebarRow({ ...base, id: '2' })]+ expect(sameSidebarRows(a, b)).toBe(false)+ })++ it('a mode switch changes the projection', () => {+ const base = { id: '1', title: 'x', messages: [], model: '', systemPrompt: '', createdAt: 0, updatedAt: 0 }+ expect(sameSidebarRows(+ [toSidebarRow({ ...base, mode: 'lu' })],+ [toSidebarRow({ ...base, mode: 'codex' })],+ )).toBe(false)+ })++ it('the row carries the FORMATTED date, not the raw timestamp', () => {+ // The raw timestamp is rewritten by every flush; "Just now" is not. This+ // is the single field that decides whether the list stands still.+ const row = toSidebarRow({+ id: '1', title: 'x', messages: [], model: '', systemPrompt: '',+ createdAt: 0, updatedAt: Date.now(),+ })+ expect(row.date).toBe('Just now')+ expect(row).not.toHaveProperty('updatedAt')+ })+})++describe('search still finds what it found before', () => {+ const conv = {+ id: '1', title: 'Rust notes', model: '', systemPrompt: '', createdAt: 0, updatedAt: 0,+ messages: [message({ content: 'Borrow checker BASICS' }), message({ content: 'lifetimes' })],+ }++ it('matches on the title, case-folded', () => {+ expect(conversationMatches(conv, 'rust')).toBe(true)+ })++ it('matches inside a message body, case-folded', () => {+ expect(conversationMatches(conv, 'basics')).toBe(true)+ })++ it('does not match what is not there', () => {+ expect(conversationMatches(conv, 'python')).toBe(false)+ })+})++// ── source guards ──────────────────────────────────────────────────────────++describe('Sidebar subscribes to what it paints', () => {+ it('no whole-store subscription is left', () => {+ for (const store of ['useChatStore', 'useUIStore', 'useModelStore', 'useSettingsStore', 'useRemoteStore']) {+ // `useStore()` with no selector is the shape that costs a render per+ // frame. `useStore.getState()` and `useStore((s) => …)` are fine.+ expect(sidebar, store).not.toMatch(new RegExp(`${store}\\(\\)`))+ }+ })++ it('the list reads the projection, not the conversations array', () => {+ expect(sidebar).toContain('sameSidebarRows(rowCache.current, next)')+ // The only remaining reads of the raw array are at click time.+ const subscribed = sidebar.match(/useChatStore\(\(s\) => s\.conversations\b/g) ?? []+ expect(subscribed).toHaveLength(0)+ })++ it('the corpus scan is memoised and deferred, not re-run in the render body', () => {+ expect(sidebar).toContain('useDeferredValue(search)')+ expect(sidebar).toMatch(/const matches = useMemo\(/)+ // The old shape lowercased the needle once per conversation AND once per+ // message, inside the render body.+ expect(sidebar).not.toMatch(/includes\(search\.toLowerCase\(\)\)/)+ })+})++describe('ChatView subscribes to what it paints', () => {+ it('does not subscribe to the conversations array', () => {+ expect(chatView).not.toMatch(/useChatStore\(\(s\) => s\.conversations\)/)+ expect(chatView).toContain('const activeConvMode = useChatStore(')+ })++ it('reads the model / system prompt / export payload at click time instead', () => {+ expect(chatView).toMatch(/useChatStore\.getState\(\)\.conversations\s*\n?\s*\.find/)+ })+})++describe('AppShell subscribes to what it paints', () => {+ it('no whole-store uiStore subscription — the resize handle writes to it', () => {+ // ExplorerPanel's divider calls setExplorerWidth on every pointermove.+ // With `useUIStore()` here, that re-rendered Titlebar, Header, Sidebar and+ // the whole active view at pointer-event frequency.+ expect(appShell).not.toMatch(/useUIStore\(\)/)+ expect(appShell).toContain('useUIStore((s) => s.currentView)')+ })++ it('the same goes for the settings store it renders from', () => {+ expect(appShell).not.toMatch(/useSettingsStore\(\)/)+ })+})diff --git a/src/components/layout/sidebar-rows.ts b/src/components/layout/sidebar-rows.tsnew file mode 100644index 00000000..71a9a2f7--- /dev/null+++ b/src/components/layout/sidebar-rows.ts@@ -0,0 +1,46 @@+/**+ * The projection the chat sidebar's list actually paints, split out of+ * Sidebar.tsx so the pure part is testable (and so the component file keeps+ * exporting only its component).+ *+ * Why a projection at all: `chatStore.conversations` is REPLACED on every+ * streaming flush, so any component subscribed to the array re-renders once+ * per animation frame for the whole duration of an answer. A row paints four+ * things, none of which move per token — subscribing to those instead lets the+ * store selector hand back the identical array and React skip the render.+ */+import { formatDate } from '../../lib/formatters'+import type { Conversation } from '../../types/chat'++export interface SidebarRow {+ id: string+ title: string+ mode: string+ /** The FORMATTED date, not `updatedAt`. The raw timestamp is rewritten on+ * every token; "Just now" is not. */+ date: string+}++export function toSidebarRow(c: Conversation): SidebarRow {+ return { id: c.id, title: c.title, mode: c.mode || 'lu', date: formatDate(c.updatedAt) }+}++/** Field-wise equality over two projections. The store selector returns the+ * previous array whenever this holds, which is what stops the re-render. */+export function sameSidebarRows(a: readonly SidebarRow[], b: readonly SidebarRow[]): boolean {+ if (a.length !== b.length) return false+ for (let i = 0; i < a.length; i++) {+ const x = a[i], y = b[i]+ if (x.id !== y.id || x.title !== y.title || x.mode !== y.mode || x.date !== y.date) return false+ }+ return true+}++/** Case-folded substring match over a conversation's title and message bodies.+ * The needle arrives ALREADY lowercased and trimmed: lowercasing it per+ * conversation (or worse, per message, as the old inline filter did) is the+ * work this whole path exists to avoid. */+export function conversationMatches(c: Conversation, needle: string): boolean {+ if (c.title.toLowerCase().includes(needle)) return true+ return c.messages.some((m) => m.content.toLowerCase().includes(needle))+}diff --git a/src/stores/createStore.ts b/src/stores/createStore.tsindex 5a85b2fc..aa20abe7 100644--- a/src/stores/createStore.ts+++ b/src/stores/createStore.ts@@ -3,6 +3,7 @@ import { persist } from 'zustand/middleware'import type { ModelType, ClassifiedModel } from '../api/comfyui'import { classifyModel } from '../api/comfyui'import type { HiresUpscaleMethod } from '../api/hires-fix'+import { releaseVideoBlobUrl } from '../api/mlx-video'// ModelType includes: flux, flux2, zimage, sdxl, sd15, wan, hunyuan, unknownexport type ProgressPhase = 'idle' | 'queued' | 'loading-model' | 'loading-clip' | 'loading-vae' | 'sampling' | 'decoding' | 'complete'@@ -395,6 +396,43 @@ interface CreateState {setComfyRunning: (running: boolean) => void}+/** The gallery keeps the newest N renders. */+const GALLERY_CAP = 200++/**+ * Hand a gallery item's in-memory media back to the renderer.+ *+ * `dataUrl` is a `blob:` URL for everything produced locally — MLX video via+ * `readVideoAsBlobUrl`, images restored from disk via `galleryUrl.ts` — and a+ * blob: URL pins its bytes for the lifetime of the document unless somebody+ * revokes it. Nothing ever did, so a long Create session grew monotonically+ * until the WebView ran out of memory. Every path that drops an item from the+ * gallery goes through here.+ *+ * `releaseVideoBlobUrl` ignores anything that is not a `blob:` string, so+ * cloud `https://` results and legacy `data:` previews pass through untouched.+ */+function releaseItemMedia(item: GalleryItem): void {+ releaseVideoBlobUrl(item.dataUrl)+}++/**+ * Replacing a staged input file must free the one it replaces.+ *+ * `mediaRefFrom` in SpecialIntentControls mints a fresh `blob:` URL for every+ * pick, so re-choosing a driving video or a voice clip five times used to pin+ * five files in the renderer with only the last one reachable. The lifetime is+ * closed HERE rather than at the call site because these two setters are the+ * only way a slot is ever written — a future caller cannot forget.+ *+ * Only the preview URL is dropped; every consumer (local + cloud upload) reads+ * `MediaRef.blob`, which is unaffected by revoking the URL.+ */+function releaseReplacedMediaRef(previous: MediaRef | null, next: MediaRef | null): void {+ if (!previous || previous.url === next?.url) return+ if (previous.url.startsWith('blob:')) URL.revokeObjectURL(previous.url)+}+export const useCreateStore = create<CreateState>()(persist(// Explicit param/return types: LU compiles with `strict: true` (the web@@ -658,9 +696,15 @@ export const useCreateStore = create<CreateState>()(setTrainSteps: (n) => set({ trainSteps: Math.max(100, Math.min(4000, Math.floor(n))) }),setSelectedCharacter: (selectedCharacter) => set({ selectedCharacter }),// Upload and voice-pick are mutually exclusive speech sources.- setAudioInput: (audioInput) => set({ audioInput, ...(audioInput ? { voiceFromJob: null } : {}) }),+ setAudioInput: (audioInput) => {+ releaseReplacedMediaRef(get().audioInput, audioInput)+ set({ audioInput, ...(audioInput ? { voiceFromJob: null } : {}) })+ },setVoiceFromJob: (voiceFromJob) => set({ voiceFromJob, ...(voiceFromJob ? { audioInput: null } : {}) }),- setVideoInput: (videoInput) => set({ videoInput }),+ setVideoInput: (videoInput) => {+ releaseReplacedMediaRef(get().videoInput, videoInput)+ set({ videoInput })+ },bumpCharactersVersion: () => set((s) => ({ charactersVersion: s.charactersVersion + 1 })),setCloudOpModel: (cloudOpModel) => set({ cloudOpModel }),// Picking a lane model adopts its architecture defaults (like@@ -740,11 +784,29 @@ export const useCreateStore = create<CreateState>()(setVhsInstallPrompt: (resolver) => set({ vhsInstallPrompt: resolver }),setError: (error) => set({ error }),setLastGenTime: (time) => set({ lastGenTime: time }),- addToGallery: (item) => set((s) => ({ gallery: [item, ...s.gallery].slice(0, 200) })),+ addToGallery: (item) => set((s) => {+ const next = [item, ...s.gallery]+ // The cap used to drop the oldest renders silently, taking the only+ // reference to their blob: URLs with them — the bytes stayed pinned+ // for the rest of the session with nothing left to revoke them by.+ for (const dropped of next.slice(GALLERY_CAP)) releaseItemMedia(dropped)+ return { gallery: next.slice(0, GALLERY_CAP) }+ }),updateGalleryItem: (id, patch) =>+ // NOT revoking a replaced dataUrl here on purpose: a patch lands while+ // the tile is on screen (a lazy re-sign, a restore-from-disk), and+ // revoking a URL an <img>/<video> may still be loading would break the+ // very media this patch exists to fix.set((s) => ({ gallery: s.gallery.map((g) => (g.id === id ? { ...g, ...patch } : g)) })),- removeFromGallery: (id) => set((s) => ({ gallery: s.gallery.filter((g) => g.id !== id) })),- clearGallery: () => set({ gallery: [] }),+ removeFromGallery: (id) => set((s) => {+ const gone = s.gallery.find((g) => g.id === id)+ if (gone) releaseItemMedia(gone)+ return { gallery: s.gallery.filter((g) => g.id !== id) }+ }),+ clearGallery: () => set((s) => {+ for (const g of s.gallery) releaseItemMedia(g)+ return { gallery: [] }+ }),addToPromptHistory: (prompt) => set((s) => {const filtered = s.promptHistory.filter(p => p !== prompt)return { promptHistory: [prompt, ...filtered].slice(0, 50) }