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(React19): 37 echte Hook-Fehler behoben, ohne eine einzige Regel stillzulegen
Davidaf7a40ae5480
diff --git a/src/components/agents/WorkflowRunner.tsx b/src/components/agents/WorkflowRunner.tsxindex 3fce8077..507936c9 100644--- a/src/components/agents/WorkflowRunner.tsx+++ b/src/components/agents/WorkflowRunner.tsx@@ -1,4 +1,4 @@-import { useState } from 'react'+import { useEffect, useState } from 'react'import { Loader2, Check, X, Circle, Send, Square } from 'lucide-react'import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'import type { StepStatus } from '../../types/agent-workflows'@@ -39,6 +39,19 @@ export function WorkflowRunner({const execution = useAgentWorkflowStore((s) => s.executions.find(e => e.id === executionId))const [inputValue, setInputValue] = useState('')+ // The clock the "Running… Ns" line divides by. It used to be `Date.now()`+ // read straight from the render body — impure (React 19 `purity`), and it+ // only advanced when the store happened to push a step update, so a slow+ // step froze the counter. A one-second tick while the run is live says the+ // same thing honestly; a finished run needs no clock at all.+ const live = execution?.status === 'running' || execution?.status === 'waiting_input'+ const [now, setNow] = useState(() => Date.now())+ useEffect(() => {+ if (!live) return+ const t = setInterval(() => setNow(Date.now()), 1000)+ return () => clearInterval(t)+ }, [live, executionId])+if (!execution) return nullconst handleSubmitInput = () => {@@ -49,7 +62,7 @@ export function WorkflowRunner({const elapsed = execution.completedAt? Math.round((execution.completedAt - execution.startedAt) / 1000)- : Math.round((Date.now() - execution.startedAt) / 1000)+ : Math.max(0, Math.round((now - execution.startedAt) / 1000))return (<div className="space-y-3 p-3 rounded-lg border border-white/10 bg-white/[0.02]">diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsxindex 2f10f66d..72b62e29 100644--- a/src/components/chat/ChatInput.tsx+++ b/src/components/chat/ChatInput.tsx@@ -46,6 +46,27 @@ interface Props {composerActions?: ReactNode}+/** How long the synchronous double-fire guard below stays shut. */+const SEND_LOCK_MS = 700++/**+ * The double-fire guard's clock read, deliberately OUTSIDE the component.+ *+ * Reading `Date.now()` from a function declared in the component body puts an+ * impure call in the render path as far as React 19 is concerned (`purity`),+ * and the rule is right about where such a read belongs: not in a component,+ * not in a hook. Moving the whole check out here keeps it exactly as+ * synchronous as it was — the point of the guard is that it decides inside the+ * same tick as the second keydown — and makes it a thing that can be reasoned+ * about (and tested) on its own. Returns false when the send must be dropped.+ */+function passSendLock(lock: { current: number }): boolean {+ const now = Date.now()+ if (now - lock.current < SEND_LOCK_MS) return false+ lock.current = now+ return true+}+function fileToImageAttachment(file: File): Promise<ImageAttachment> {return new Promise((resolve, reject) => {const reader = new FileReader()@@ -153,9 +174,7 @@ export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onAppconst handleSend = () => {const trimmed = input.trim()if ((!trimmed && images.length === 0) || isGenerating || disabled) return- const now = Date.now()- if (now - sendLockRef.current < 700) return- sendLockRef.current = now+ if (!passSendLock(sendLockRef)) returnonSend(trimmed || '(image)', images.length > 0 ? images : undefined)setInput('')setImages([])diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsxindex 3c7e2cde..6d7c459f 100644--- a/src/components/chat/CodexView.tsx+++ b/src/components/chat/CodexView.tsx@@ -83,10 +83,12 @@ export function CodexView() {// git_status/diff/commit/log; if git is missing those tools fail. Probe on// open and surface a minimal install banner when it's not on PATH.const [gitStatus, setGitStatus] = useState<GitStatus | null>(null)- const [gitChecking, setGitChecking] = useState(false)+ // Starts as `true` because the probe below starts with the component: the+ // effect used to flip it on synchronously, which is a cascading render for a+ // value that was already knowable at mount (React 19 `set-state-in-effect`).+ const [gitChecking, setGitChecking] = useState(true)useEffect(() => {let cancelled = false- setGitChecking(true)checkGitInstalled().then((s) => { if (!cancelled) setGitStatus(s) }).catch(() => {})diff --git a/src/components/chat/LoopBar.tsx b/src/components/chat/LoopBar.tsxindex cd5eba26..f71fcced 100644--- a/src/components/chat/LoopBar.tsx+++ b/src/components/chat/LoopBar.tsx@@ -17,17 +17,20 @@ interface Props {export function LoopBar({ onStop }: Props) {const loop = useAgentLoopStore((s) => s.loop)const activeConversationId = useChatStore((s) => s.activeConversationId)- // Re-render once a second so the countdown to the next pass actually counts.- const [, tick] = useState(0)+ // The clock the countdown divides by, read once a second in the interval+ // instead of on every render. Reading `Date.now()` down in the render body+ // was impure (React 19 `purity`) AND it made the countdown depend on+ // something re-rendering this bar, which is not what "counts down" means.+ const [now, setNow] = useState(() => Date.now())useEffect(() => {if (!loop) return- const t = setInterval(() => tick((n) => n + 1), 1000)+ const t = setInterval(() => setNow(Date.now()), 1000)return () => clearInterval(t)}, [loop])if (!loop || loop.conversationId !== activeConversationId) return null- const secs = Math.max(0, Math.ceil((loop.nextAt - Date.now()) / 1000))+ const secs = Math.max(0, Math.ceil((loop.nextAt - now) / 1000))const passLabel = loop.cap > 0 ? `pass ${loop.pass} of ${loop.cap}` : `pass ${loop.pass}`return (diff --git a/src/components/chat/MessageList.tsx b/src/components/chat/MessageList.tsxindex fae39287..f359c0b1 100644--- a/src/components/chat/MessageList.tsx+++ b/src/components/chat/MessageList.tsx@@ -1,4 +1,4 @@-import { useCallback, useRef, useState } from 'react'+import { useCallback, useEffect, useRef, useState } from 'react'import type { CSSProperties } from 'react'import { useChatStore } from '../../stores/chatStore'import { useAutoScroll } from '../../hooks/useAutoScroll'@@ -85,8 +85,13 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel// 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.+ // The refresh happens in an effect, not in the render body: writing a ref+ // while rendering is a mutation React is allowed to throw away or replay+ // (React 19 `refs`). Both readers below are user-event handlers, which never+ // run before the effects of the render they belong to, so they still only+ // ever see the current conversation and callbacks.const bind = useRef({ conversation, onRegenerate, onEdit })- bind.current = { conversation, onRegenerate, onEdit }+ useEffect(() => { bind.current = { conversation, onRegenerate, onEdit } })const handleRegenerate = useCallback((messageId: string) => {const { conversation: c, onRegenerate: cb } = bind.currentdiff --git a/src/components/chat/ModelPickerCard.tsx b/src/components/chat/ModelPickerCard.tsxindex af6443e3..a1b30ef8 100644--- a/src/components/chat/ModelPickerCard.tsx+++ b/src/components/chat/ModelPickerCard.tsx@@ -79,8 +79,13 @@ export function ModelPickerCard({ request }: { request: ModelPickRequest }) {// Auto-continue 5s before the store's headless fallback so the countdown// resolves with the user's ON-SCREEN selection, not just the default.const [secondsLeft, setSecondsLeft] = useState(Math.max(5, Math.floor((MODEL_PICK_TIMEOUT_MS - 5000) / 1000)))+ // Refreshed from an effect, not from the render body: a ref written while+ // rendering is a mutation React may discard or replay (React 19 `refs`). The+ // only reader is the interval below, which first fires a full second after+ // the effects of the render it was started in, so it still reads the pick+ // that is on screen.const stateRef = useRef({ selected, save })- stateRef.current = { selected, save }+ useEffect(() => { stateRef.current = { selected, save } })useEffect(() => {const t = setInterval(() => {diff --git a/src/components/chat/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsxindex 66dcd5b3..17955dea 100644--- a/src/components/chat/ToolCallBlock.tsx+++ b/src/components/chat/ToolCallBlock.tsx@@ -9,7 +9,7 @@ import { ModelPickerCard, ChangeModelInline, pickKindForToolCall } from './Modelimport { DiffView } from './DiffView'import { commandIcon } from '../../lib/shell-command-classify'import { requestGenerationCancel } from '../../api/vram-handoff'-import { fileUrlToPath, readLocalFileAsBlobUrl } from '../../lib/local-media-url'+import { fileUrlToPath, readLocalFileAsBlobUrl, displayableMedia, type MediaRead } from '../../lib/local-media-url'import { hiddenFromTranscript } from '../../lib/transcript-visibility'// F1 (konata3602 commitment 2026-05-23) + render fix (konata3602 bug 2026-06-07)@@ -102,35 +102,34 @@ export function localMediaUrlFromResult(result: string | null | undefined): stri*/function useDisplayableMediaUrl(url: string | null): { url: string | null; missing: boolean } {const path = url ? fileUrlToPath(url) : null- // Nothing creates a blob: URL for a tool result any more, so one appearing in- // a stored result necessarily came from an earlier session and its blob died- // with that window. Saying so beats rendering a broken picture frame.- const staleBlob = !!url && url.startsWith('blob:')- const [resolved, setResolved] = useState<string | null>(null)- const [missing, setMissing] = useState(false)+ // Only the READ is state now; what the element shows is derived from it by+ // displayableMedia (lib/local-media-url), which also carries the "a stored+ // blob: URL is necessarily dead" rule. The two resets this hook used to write+ // back from the effect body — no path at all, and a new path whose read has+ // not landed yet — were cascading renders for facts the render already had+ // (React 19 `set-state-in-effect`), and the `missing` one could land late+ // enough to paint the previous file's "gone" over the new one.+ const [read, setRead] = useState<MediaRead | null>(null)useEffect(() => {- if (!path) { setResolved(null); setMissing(false); return }+ if (!path) returnlet live = truelet made: string | null = null- setMissing(false)readLocalFileAsBlobUrl(path).then((blobUrl) => {// Unmounted while reading: revoke immediately, nothing will show it.if (!live) { URL.revokeObjectURL(blobUrl); return }made = blobUrl- setResolved(blobUrl)+ setRead({ path, url: blobUrl, missing: false })})- .catch(() => { if (live) setMissing(true) })+ .catch(() => { if (live) setRead({ path, url: null, missing: true }) })return () => {live = falseif (made) URL.revokeObjectURL(made)}}, [path])- if (staleBlob) return { url: null, missing: true }- if (!path) return { url, missing: false }- return { url: resolved, missing }+ return displayableMedia(url, path, read)}// Pull the "<file>" back out of the "<kind> generated: <file> (prompt: …"@@ -179,13 +178,23 @@ const SHELL_COMMAND_ICONS: Record<string, typeof Search> = {test: FlaskConical,read: FileText,terminal: Terminal,+ // A backgrounded call or a task handle is a job, not a command.+ background: History,}-function shellIconFor(toolCall: AgentToolCall): typeof Search {+/**+ * Which SHELL_COMMAND_ICONS face a shell call wears.+ *+ * Returns the KEY, not the component. React 19's `static-components` rule+ * cannot see through a helper that hands a component back, and it is right to+ * be strict: a component built during render loses its state every time. The+ * lookup itself therefore has to stay visible as a lookup, at the use site.+ */+function shellIconKey(toolCall: AgentToolCall): string {const command = toolCall.args?.command- if (toolCall.args?.background || typeof toolCall.args?.task === 'string') return History- if (typeof command !== 'string') return Terminal- return SHELL_COMMAND_ICONS[commandIcon(command)] ?? Terminal+ if (toolCall.args?.background || typeof toolCall.args?.task === 'string') return 'background'+ if (typeof command !== 'string') return 'terminal'+ return commandIcon(command)}const STATUS_ICONS = {@@ -215,7 +224,9 @@ function ToolCallBlockImpl({ toolCall, onApprove, onReject }: Props) {// Default: collapsed (closed)const [open, setOpen] = useState(toolCall.status === 'pending_approval')- const ToolIcon = toolCall.toolName === 'shell_execute' ? shellIconFor(toolCall) : (TOOL_ICONS[toolCall.toolName] || Terminal)+ const ToolIcon = toolCall.toolName === 'shell_execute'+ ? (SHELL_COMMAND_ICONS[shellIconKey(toolCall)] ?? Terminal)+ : (TOOL_ICONS[toolCall.toolName] || Terminal)const StatusIcon = STATUS_ICONS[toolCall.status]const isRunning = toolCall.status === 'running'const isPending = toolCall.status === 'pending_approval'diff --git a/src/components/chat/WorkingAnchor.tsx b/src/components/chat/WorkingAnchor.tsxindex 6e09e7f1..8cb9351b 100644--- a/src/components/chat/WorkingAnchor.tsx+++ b/src/components/chat/WorkingAnchor.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef, useState } from 'react'+import { useEffect, useState } from 'react'import { formatElapsed } from '../../lib/format-elapsed'interface Props {@@ -20,13 +20,27 @@ interface Props {*/export function WorkingAnchor({ isRunning, label }: Props) {const [elapsed, setElapsed] = useState(0)- const startRef = useRef(Date.now())++ // The clock resets in the render where `isRunning` flips, not in an effect+ // afterwards. Two things were wrong with the effect version: `useRef(Date.now())`+ // read the clock on every render (React 19 `purity`), and `setElapsed(0)`+ // inside the effect body is a cascading render (`set-state-in-effect`) that+ // lands AFTER paint — so the first quarter second of a new run showed the+ // previous run's time. React's documented "adjust state while rendering"+ // shape re-runs only this component, before anything paints.+ const [wasRunning, setWasRunning] = useState(isRunning)+ if (wasRunning !== isRunning) {+ setWasRunning(isRunning)+ setElapsed(0)+ }useEffect(() => {- if (!isRunning) { setElapsed(0); return }- startRef.current = Date.now()+ if (!isRunning) return+ // The start belongs to this run, so it lives in the run's own closure —+ // no ref, and nothing left over from the previous run to read back.+ const start = Date.now()const interval = setInterval(() => {- setElapsed(Math.floor((Date.now() - startRef.current) / 1000))+ setElapsed(Math.floor((Date.now() - start) / 1000))}, 250)return () => clearInterval(interval)}, [isRunning])diff --git a/src/components/chat/__tests__/tool-media-lifetime.test.ts b/src/components/chat/__tests__/tool-media-lifetime.test.tsindex 876a37e4..21191a78 100644--- a/src/components/chat/__tests__/tool-media-lifetime.test.ts+++ b/src/components/chat/__tests__/tool-media-lifetime.test.ts@@ -26,6 +26,7 @@ const read = (...p: string[]) => readFileSync(resolve(SRC, ...p), 'utf8')const tools = read('api', 'mcp', 'builtin-tools.ts')const block = read('components', 'chat', 'ToolCallBlock.tsx')+const media = read('lib', 'local-media-url.ts')describe('nothing writes a session-scoped URL into a stored result', () => {it('the helper that minted them is gone', () => {@@ -66,15 +67,22 @@ describe('the viewer owns the blob, so it can end', () => {})it('says so when the file is gone instead of showing a broken frame', () => {- expect(block).toMatch(/setMissing\(true\)/)+ // The failed read is recorded AGAINST ITS PATH, so a stale "gone" can never+ // paint over the next file's frame. What the element then shows is+ // displayableMedia's job — see src/lib/__tests__/derived-ui-state.test.ts,+ // which exercises pending / landed / failed / stale-tag directly. (Was a+ // bare `setMissing(true)` before the React 19 set-state-in-effect fix.)+ expect(block).toMatch(/setRead\(\{ path, url: null, missing: true \}\)/)+ expect(block).toMatch(/return displayableMedia\(url, path, read\)/)expect(block).toMatch(/no longer on disk/)})it('treats a blob: URL in a stored result as already dead', () => {// Nothing creates one any more, so any that appears was recorded by an- // older build and its blob died with that window.- expect(block).toMatch(/const staleBlob = !!url && url\.startsWith\('blob:'\)/)- expect(block).toMatch(/if \(staleBlob\) return \{ url: null, missing: true \}/)+ // older build and its blob died with that window. The rule moved into+ // lib/local-media-url.ts with the rest of the display derivation; it is+ // asserted end-to-end in derived-ui-state.test.ts.+ expect(media).toMatch(/if \(rawUrl && rawUrl\.startsWith\('blob:'\)\) return \{ url: null, missing: true \}/)})it('picks the element kind from the raw result, not the resolved URL', () => {diff --git a/src/components/cloud/CloudGateModal.tsx b/src/components/cloud/CloudGateModal.tsxindex 9cb26e7d..fc2a0c62 100644--- a/src/components/cloud/CloudGateModal.tsx+++ b/src/components/cloud/CloudGateModal.tsx@@ -100,8 +100,16 @@ export function CloudGateModal() {// Signed-out walkthrough position. Reset to the hero every time the gate// opens so a re-open never lands mid-flow.+ // The reset happens in the render where `open` flips, using React's+ // documented "adjust state while rendering" shape. As an effect it was a+ // cascading render (React 19 `set-state-in-effect`) that landed after paint,+ // so a re-open showed one frame of the step the gate was last left on.const [step, setStep] = useState<Step>('intro')- useEffect(() => { if (open) setStep('intro') }, [open])+ const [wasOpen, setWasOpen] = useState(open)+ if (wasOpen !== open) {+ setWasOpen(open)+ if (open) setStep('intro')+ }// The moment the account clears every gate — already provisioned when the// gate opens, a fresh login, or a re-check after subscribing — flip thediff --git a/src/components/cloud/CloudSwitch.tsx b/src/components/cloud/CloudSwitch.tsxindex a43f9dc2..9c9bc226 100644--- a/src/components/cloud/CloudSwitch.tsx+++ b/src/components/cloud/CloudSwitch.tsx@@ -25,18 +25,24 @@ export function CloudSwitch() {// model silently, and bill the next question (Nebenbefund 4, R5 re-measure// 2026-08-30). See lib/cloud-switch-guard for why it is two clicks on this// one control and not a dialog.- const [armed, setArmed] = useState(false)+ const [armedRaw, setArmed] = useState(false)+ // A mode change made anywhere else settles the switch too. That used to be+ // an effect writing `false` back into state after the fact (React 19+ // `set-state-in-effect`); "armed while already in cloud" is simply not a+ // state this switch has, so it is ruled out by the derivation instead — and+ // now on the same frame as the mode change rather than a paint later.+ const armed = armedRaw && !on// An armed switch goes back to sleep on its own, so it is never lying in// wait minutes later for a click that means something else entirely.+ // Keyed on the raw flag, not the derived one: the timer has to run down even+ // while the derivation is already hiding the armed state, or a mode change+ // made elsewhere would leave the flag standing indefinitely.useEffect(() => {- if (!armed) return+ if (!armedRaw) returnconst t = setTimeout(() => setArmed(false), CLOUD_ARM_TIMEOUT_MS)return () => clearTimeout(t)- }, [armed])-- // A mode change made anywhere else settles the switch too.- useEffect(() => { if (on) setArmed(false) }, [on])+ }, [armedRaw])const toggle = () => {switch (cloudSwitchClick({ on, available, armed })) {diff --git a/src/components/create/canvas/MaskCanvasEngine.ts b/src/components/create/canvas/MaskCanvasEngine.tsindex 708ada1f..780aba47 100644--- a/src/components/create/canvas/MaskCanvasEngine.ts+++ b/src/components/create/canvas/MaskCanvasEngine.ts@@ -8,6 +8,19 @@ export type Tool = 'brush' | 'eraser'const UNDO_CAP = 20+/**+ * The brush a fresh engine starts with: 6% of the longest source edge.+ *+ * Exported because the editor's brush-size slider has to show this number from+ * its very first render. Reading it back off a just-constructed engine inside+ * an effect meant a setState in an effect body (React 19 `set-state-in-effect`)+ * for a value that is a plain function of the source dimensions the editor+ * already holds. The constructor uses it too, so the two cannot drift apart.+ */+export function defaultBrushSize(width: number, height: number): number {+ return Math.round(Math.max(Math.max(1, Math.round(width)), Math.max(1, Math.round(height))) * 0.06)+}+export class MaskCanvasEngine {readonly width: numberreadonly height: number@@ -30,7 +43,7 @@ export class MaskCanvasEngine {this.mask.height = this.height// willReadFrequently: undo snapshots + hasPaint do frequent getImageData.this.ctx = this.mask.getContext('2d', { willReadFrequently: true })!- this.brushSize = Math.round(Math.max(this.width, this.height) * 0.06)+ this.brushSize = defaultBrushSize(this.width, this.height)}// ── stroke lifecycle (coords are in SOURCE pixels) ──diff --git a/src/components/create/experimental/MaskEditor.tsx b/src/components/create/experimental/MaskEditor.tsxindex eb8f4c1c..be28bc69 100644--- a/src/components/create/experimental/MaskEditor.tsx+++ b/src/components/create/experimental/MaskEditor.tsx@@ -6,7 +6,7 @@ import {} from 'lucide-react'import { useCreateStore, type ImageRef } from '../../../stores/createStore'import { uploadImage } from '../../../api/comfyui'-import { MaskCanvasEngine, type Tool } from '../canvas/MaskCanvasEngine'+import { MaskCanvasEngine, defaultBrushSize, type Tool } from '../canvas/MaskCanvasEngine'import { Slider } from '../ui/Slider'import { Button } from '../ui/Button'import { cn } from '../ui/cn'@@ -47,10 +47,35 @@ function MaskEditorInner({ onClose }: { onClose: () => void }) {const engineRef = useRef<MaskCanvasEngine | null>(null)const [tool, setTool] = useState<Tool>('brush')- const [brushSize, setBrushSize] = useState(0)+ // Seeded from the same pure formula the engine's constructor uses, so the+ // slider is right on the very first paint. It used to start at 0 and be+ // corrected from the init effect by reading the fresh engine back (React 19+ // `set-state-in-effect`).+ const [brushSize, setBrushSize] = useState(() => defaultBrushSize(source.width, source.height))const [view, setView] = useState({ scale: 1, x: 0, y: 0 })- const [, force] = useState(0)- const rerender = useCallback(() => force((n) => n + 1), [])++ // What the toolbar needs to know about the engine, mirrored into state at the+ // moments that change it. This used to be a forced re-render (`force`) plus a+ // read of engineRef.current straight from the render body — a ref read while+ // rendering (React 19 `refs`), and one that can tear: the ref is free to hold+ // a different engine than the tree currently being rendered.+ const [history, setHistory] = useState({ canUndo: false, canRedo: false })+ const syncHistory = useCallback(() => {+ const e = engineRef.current+ setHistory({ canUndo: !!e?.canUndo(), canRedo: !!e?.canRedo() })+ }, [])++ // A swapped source means the init effect below builds a NEW engine: default+ // brush, empty undo/redo. Both are settled here, while rendering, so the+ // toolbar never paints the previous image's brush size or a live Undo button+ // for history that no longer exists. This is the same reset the effect used+ // to do afterwards, one paint earlier.+ const [renderedFor, setRenderedFor] = useState(source)+ if (renderedFor !== source) {+ setRenderedFor(source)+ setBrushSize(defaultBrushSize(source.width, source.height))+ setHistory({ canUndo: false, canRedo: false })+ }const painting = useRef(false)const spaceDown = useRef(false)@@ -58,6 +83,15 @@ function MaskEditorInner({ onClose }: { onClose: () => void }) {const panStart = useRef({ x: 0, y: 0, vx: 0, vy: 0 })const touched = useRef(false)+ // `panning` and `spaceDown` stay refs — a pointer stream must not wait for a+ // re-render to know whether it is panning — but the cursor they decide IS+ // rendered, so it is mirrored into state at the four events that move them.+ // Reading the refs from the render body was wrong twice over: a render-time+ // ref read (React 19 `refs`), and holding Space re-renders nothing by itself,+ // so the grab cursor only ever appeared on the next unrelated render.+ const [grabCursor, setGrabCursor] = useState(false)+ const syncCursor = useCallback(() => setGrabCursor(panning.current || spaceDown.current), [])+const maxBrush = Math.round(Math.max(source.width, source.height) * 0.4)const renderOverlay = useCallback(() => {@@ -69,7 +103,6 @@ function MaskEditorInner({ onClose }: { onClose: () => void }) {useEffect(() => {const e = new MaskCanvasEngine(source.width, source.height)engineRef.current = e- setBrushSize(e.brushSize)const img = new Image()img.onload = () => {@@ -78,9 +111,10 @@ function MaskEditorInner({ onClose }: { onClose: () => void }) {}img.src = source.urlrenderOverlay()- rerender()+ // No history sync here any more: a brand-new engine has empty stacks, which+ // is exactly what the state above already says for this source.return () => { engineRef.current = null }- }, [source, renderOverlay, rerender])+ }, [source, renderOverlay])// ── fit view to viewport ──useLayoutEffect(() => {@@ -121,6 +155,7 @@ function MaskEditorInner({ onClose }: { onClose: () => void }) {const eng = engineRef.current!if (spaceDown.current || e.button === 1) {panning.current = true+ syncCursor()panStart.current = { x: e.clientX, y: e.clientY, vx: view.x, vy: view.y }try { (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId) } catch { /* synthetic / unsupported */ }return@@ -148,8 +183,9 @@ function MaskEditorInner({ onClose }: { onClose: () => void }) {}const endInteraction = () => {- if (painting.current) { engineRef.current!.endStroke(); painting.current = false; rerender() }+ if (painting.current) { engineRef.current!.endStroke(); painting.current = false; syncHistory() }panning.current = false+ syncCursor()}const onWheel = (e: React.WheelEvent) => {@@ -168,24 +204,24 @@ function MaskEditorInner({ onClose }: { onClose: () => void }) {useEffect(() => {const onKey = (e: KeyboardEvent) => {if (e.key === 'Escape') { onClose(); return }- if (e.key === ' ') { spaceDown.current = true; return }+ if (e.key === ' ') { spaceDown.current = true; syncCursor(); return }const eng = engineRef.currentif (!eng) returnconst mod = e.metaKey || e.ctrlKey- if (mod && e.key.toLowerCase() === 'z') { e.preventDefault(); if (e.shiftKey) eng.redo(); else eng.undo(); renderOverlay(); rerender(); return }- if (e.key === 'y') { eng.redo(); renderOverlay(); rerender(); return }+ if (mod && e.key.toLowerCase() === 'z') { e.preventDefault(); if (e.shiftKey) eng.redo(); else eng.undo(); renderOverlay(); syncHistory(); return }+ if (e.key === 'y') { eng.redo(); renderOverlay(); syncHistory(); return }if (e.key === '[') { setBrush(eng, Math.max(4, eng.brushSize - 8)) }if (e.key === ']') { setBrush(eng, Math.min(maxBrush, eng.brushSize + 8)) }if (e.key.toLowerCase() === 'b') { eng.tool = 'brush'; setTool('brush') }if (e.key.toLowerCase() === 'e') { eng.tool = 'eraser'; setTool('eraser') }- if (e.key.toLowerCase() === 'i') { eng.invert(); renderOverlay(); rerender() }+ if (e.key.toLowerCase() === 'i') { eng.invert(); renderOverlay(); syncHistory() }}- const onUp = (e: KeyboardEvent) => { if (e.key === ' ') spaceDown.current = false }+ const onUp = (e: KeyboardEvent) => { if (e.key === ' ') { spaceDown.current = false; syncCursor() } }const setBrush = (eng: MaskCanvasEngine, n: number) => { eng.brushSize = n; setBrushSize(n) }window.addEventListener('keydown', onKey)window.addEventListener('keyup', onUp)return () => { window.removeEventListener('keydown', onKey); window.removeEventListener('keyup', onUp) }- }, [onClose, renderOverlay, rerender, maxBrush])+ }, [onClose, renderOverlay, syncHistory, syncCursor, maxBrush])const apply = async () => {const eng = engineRef.current!@@ -207,7 +243,6 @@ function MaskEditorInner({ onClose }: { onClose: () => void }) {onClose()}- const eng = engineRef.currentreturn (<motion.divinitial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}@@ -230,15 +265,15 @@ function MaskEditorInner({ onClose }: { onClose: () => void }) {{/* toolbar */}<div className="flex items-center gap-2 px-4 py-2 border-b border-white/[0.05] shrink-0 flex-wrap"><div className="inline-flex gap-0.5 p-0.5 rounded-[var(--radius-control)] bg-white/[0.04] border border-white/[0.06]">- <ToolBtn active={tool === 'brush'} icon={Brush} label="Brush (B)" onClick={() => { eng && (eng.tool = 'brush'); setTool('brush') }} />- <ToolBtn active={tool === 'eraser'} icon={Eraser} label="Eraser (E)" onClick={() => { eng && (eng.tool = 'eraser'); setTool('eraser') }} />+ <ToolBtn active={tool === 'brush'} icon={Brush} label="Brush (B)" onClick={() => { const e = engineRef.current; if (e) e.tool = 'brush'; setTool('brush') }} />+ <ToolBtn active={tool === 'eraser'} icon={Eraser} label="Eraser (E)" onClick={() => { const e = engineRef.current; if (e) e.tool = 'eraser'; setTool('eraser') }} /></div>- <div className="w-40"><Slider label="Size" min={4} max={maxBrush} step={1} value={brushSize} onChange={(v) => { if (eng) eng.brushSize = v; setBrushSize(v) }} unit="px" /></div>+ <div className="w-40"><Slider label="Size" min={4} max={maxBrush} step={1} value={brushSize} onChange={(v) => { const e = engineRef.current; if (e) e.brushSize = v; setBrushSize(v) }} unit="px" /></div><Divider />- <Button variant="ghost" size="sm" icon={Undo2} iconOnly title="Undo (⌘Z)" disabled={!eng?.canUndo()} onClick={() => { eng?.undo(); renderOverlay(); rerender() }} />- <Button variant="ghost" size="sm" icon={Redo2} iconOnly title="Redo (⇧⌘Z)" disabled={!eng?.canRedo()} onClick={() => { eng?.redo(); renderOverlay(); rerender() }} />- <Button variant="ghost" size="sm" icon={FlipHorizontal2} iconOnly title="Invert (I)" onClick={() => { eng?.invert(); renderOverlay(); rerender() }} />- <Button variant="ghost" size="sm" icon={Trash2} iconOnly title="Clear" onClick={() => { eng?.clear(); renderOverlay(); rerender() }} />+ <Button variant="ghost" size="sm" icon={Undo2} iconOnly title="Undo (⌘Z)" disabled={!history.canUndo} onClick={() => { engineRef.current?.undo(); renderOverlay(); syncHistory() }} />+ <Button variant="ghost" size="sm" icon={Redo2} iconOnly title="Redo (⇧⌘Z)" disabled={!history.canRedo} onClick={() => { engineRef.current?.redo(); renderOverlay(); syncHistory() }} />+ <Button variant="ghost" size="sm" icon={FlipHorizontal2} iconOnly title="Invert (I)" onClick={() => { engineRef.current?.invert(); renderOverlay(); syncHistory() }} />+ <Button variant="ghost" size="sm" icon={Trash2} iconOnly title="Clear" onClick={() => { engineRef.current?.clear(); renderOverlay(); syncHistory() }} /><Divider /><Button variant="ghost" size="sm" icon={ZoomOut} iconOnly title="Zoom out" onClick={() => setView((v) => ({ ...v, scale: Math.max(0.05, v.scale / 1.2) }))} /><Button variant="ghost" size="sm" icon={ZoomIn} iconOnly title="Zoom in" onClick={() => setView((v) => ({ ...v, scale: Math.min(8, v.scale * 1.2) }))} />@@ -253,7 +288,7 @@ function MaskEditorInner({ onClose }: { onClose: () => void }) {ref={viewportRef}onWheel={onWheel}className="flex-1 min-h-0 min-w-0 overflow-hidden relative flex items-center justify-center"- style={{ cursor: panning.current || spaceDown.current ? 'grab' : 'none' }}+ style={{ cursor: grabCursor ? 'grab' : 'none' }}><divref={stackRef}diff --git a/src/components/create/experimental/useComfyMedia.ts b/src/components/create/experimental/useComfyMedia.tsindex fb41259a..3086ed95 100644--- a/src/components/create/experimental/useComfyMedia.ts+++ b/src/components/create/experimental/useComfyMedia.ts@@ -15,25 +15,29 @@ import { useCreateStore, type GalleryItem } from '../../../stores/createStore'*/export function useComfyMedia(item: GalleryItem | null) {const base = item ? galleryItemUrl(item) : ''- const [src, setSrc] = useState(base)+ // The proxy fallback's blob: URL, tagged with the base URL it stands in for.+ // The tag is what turns the reset into a derivation: when the underlying URL+ // changes (a cloud re-sign swaps remoteUrl) the tag simply stops matching and+ // `src` falls back to the direct /view — no effect writing state back into+ // React on the way (React 19 `set-state-in-effect`).+ const [proxied, setProxied] = useState<{ base: string; url: string } | null>(null)+ const src = proxied && proxied.base === base ? proxied.url : baseconst blobRef = useRef<string | null>(null)const triedProxy = useRef(false)- // Reset when the underlying URL changes (e.g. a cloud re-sign swaps remoteUrl).+ // Re-arm the proxy fallback for the new URL, and release the blob the old one+ // left behind — in the cleanup, so it is revoked at exactly the moment `src`+ // stops pointing at it, and on unmount too.useEffect(() => {triedProxy.current = false- if (blobRef.current) {- URL.revokeObjectURL(blobRef.current)- blobRef.current = null+ return () => {+ if (blobRef.current) {+ URL.revokeObjectURL(blobRef.current)+ blobRef.current = null+ }}- setSrc(base)}, [base])- // Release the blob when the element unmounts.- useEffect(() => () => {- if (blobRef.current) URL.revokeObjectURL(blobRef.current)- }, [])-const onError = useCallback(() => {if (!item) returnif (triedProxy.current) {@@ -44,7 +48,7 @@ export function useComfyMedia(item: GalleryItem | null) {void proxiedComfyBlobUrl(item).then((blob) => {if (blob) {blobRef.current = blob- setSrc(blob)+ setProxied({ base, url: blob })// Proxy rescued a /view the direct load couldn't reach. On a LOCAL// host that means ComfyUI 0.19+ rejected the cross-origin load and// the --enable-cors-header hint is actionable. On a REMOTE host@@ -56,7 +60,7 @@ export function useComfyMedia(item: GalleryItem | null) {recoverGalleryUrl(item)}})- }, [item])+ }, [item, base])const onLoad = useCallback(() => { if (item) markGalleryItemAvailable(item) }, [item])diff --git a/src/components/layout/DownloadBadge.tsx b/src/components/layout/DownloadBadge.tsxindex 358221ed..a8b5bd77 100644--- a/src/components/layout/DownloadBadge.tsx+++ b/src/components/layout/DownloadBadge.tsx@@ -8,6 +8,7 @@ import { isPermanentDownloadError } from '../../api/discover'import { useMlxInstallStore } from '../../stores/mlxInstallStore'import { isMlxImageHost } from '../../api/mlx-image'import { formatBytes } from '../../lib/formatters'+import { trayAfterPulse, TRAY_CLOSED, NO_PULSE } from '../../lib/download-tray'function ProgressBar({ progress }: { progress: number }) {return (@@ -21,7 +22,12 @@ export function DownloadBadge() {const { activePulls, pullModel, pausePull, dismissPull } = useModels()const comfyDownloads = useDownloadStore(s => s.downloads)const bundleMap = useDownloadStore(s => s.bundleMap)- const [open, setOpen] = useState(false)+ // Whether the tray is open, and whether it was the TRAY that opened it —+ // one value, because the two are only ever decided together. `auto` used+ // to be a ref written from effects; see the transition block further down+ // for why both moved out of effects.+ const [tray, setTray] = useState(TRAY_CLOSED)+ const open = tray.openconst ref = useRef<HTMLDivElement>(null)// Text model entries@@ -60,25 +66,26 @@ export function DownloadBadge() {// Click outside to closeuseEffect(() => {const handler = (e: MouseEvent) => {- if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false)+ if (ref.current && !ref.current.contains(e.target as Node)) setTray((t) => ({ ...t, open: false }))}document.addEventListener('mousedown', handler)return () => document.removeEventListener('mousedown', handler)}, [])- // Auto-open when a new download starts- const autoOpened = useRef(false)- useEffect(() => {- if (totalActive > 0) { setOpen(true); autoOpened.current = true }- }, [totalActive])-- // An auto-opened tray had no way back: cancel the download (or let the last- // one finish) and the panel kept hanging over the app reading "No active- // downloads" until you happened to click somewhere else. It only closes- // itself when it opened itself, so a tray the user opened by hand stays put.- useEffect(() => {- if (!hasAny && autoOpened.current) { setOpen(false); autoOpened.current = false }- }, [hasAny])+ // The tray opens and closes itself with the downloads; trayAfterPulse+ // (lib/download-tray) holds the rule and says why. Both halves used to be+ // effects writing state back into React on every change of the download+ // picture (React 19 `set-state-in-effect`), one paint too late. The same two+ // transitions are applied here off the previous render's numbers, in React's+ // documented "adjust state while rendering" shape: it re-runs this component+ // and only this component, before anything paints.+ const [seen, setSeen] = useState(NO_PULSE)+ if (seen.active !== totalActive || seen.any !== hasAny) {+ const now = { active: totalActive, any: hasAny }+ setSeen(now)+ const next = trayAfterPulse(tray, seen, now)+ if (next !== tray) setTray(next)+ }// Self-heal polling: comfy download progress comes from a polled Rust/bridge// endpoint, and polling was only ever kicked off from the Discover page. So a@@ -98,7 +105,7 @@ export function DownloadBadge() {<div ref={ref} className="relative">{/* Icon trigger */}<button- onClick={() => { setOpen(!open); autoOpened.current = false }}+ onClick={() => setTray({ open: !open, auto: false })}className={`relative p-1 rounded-md transition-colors ${hasAny? 'text-blue-400 hover:bg-blue-500/10'diff --git a/src/components/models/DiscoverModels.tsx b/src/components/models/DiscoverModels.tsxindex f7f16b70..af1bb63b 100644--- a/src/components/models/DiscoverModels.tsx+++ b/src/components/models/DiscoverModels.tsx@@ -1,4 +1,4 @@-import { useState, useEffect } from 'react'+import { useCallback, useState, useEffect } from 'react'import { bundleIsComplete, bundleIsDownloading, bundleHasErrors } from '../../lib/bundle-state'import { motion } from 'framer-motion'import { Search, XCircle, Loader2, Sparkles, Unlock, ShieldCheck, ExternalLink, Download, CheckCircle } from 'lucide-react'@@ -122,26 +122,30 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:// Check which bundles are REALLY installed (file size validated, not just file existence)const [bundleStatuses, setBundleStatuses] = useState<Record<string, boolean>>({})- const refreshBundleStatuses = () => {+ // Memoised so the two effects below can name it as the dependency it is+ // instead of hiding it from the dep array. It only closes over `category`,+ // so its identity changes exactly when the effects had to re-run anyway —+ // no re-subscription loop.+ const refreshBundleStatuses = useCallback(() => {if (category !== 'image' && category !== 'video') returnconst allBundles = [...getImageBundles(), ...getVideoBundles()]checkBundlesInstalled(allBundles).then(statuses => setBundleStatuses(statuses))- }+ }, [category])useEffect(() => {refreshBundleStatuses()- }, [category])+ }, [refreshBundleStatuses])// Re-check bundle statuses when a download completesuseEffect(() => {const handler = () => refreshBundleStatuses()window.addEventListener('comfyui-model-downloaded', handler)return () => window.removeEventListener('comfyui-model-downloaded', handler)- }, [category])+ }, [refreshBundleStatuses])// Start polling on mount if there are active downloadsuseEffect(() => {dlStore.getState().refresh()- }, [])+ }, [dlStore])const isText = category === 'text'const isImage = category === 'image'diff --git a/src/components/onboarding/BackendSelector.tsx b/src/components/onboarding/BackendSelector.tsxindex 39b2ad8a..866e8a8b 100644--- a/src/components/onboarding/BackendSelector.tsx+++ b/src/components/onboarding/BackendSelector.tsx@@ -8,12 +8,12 @@* from Settings → Providers going forward.*/-import { useEffect, useState } from 'react'+import { useState } from 'react'import { Modal } from '../ui/Modal'import { useProviderStore } from '../../stores/providerStore'import { useUIStore } from '../../stores/uiStore'import { PROVIDER_PRESETS } from '../../api/providers/types'-import type { DetectedBackend } from '../../lib/backend-detector'+import { selectedBackendId, type DetectedBackend } from '../../lib/backend-detector'interface Props {open: boolean@@ -22,18 +22,21 @@ interface Props {}export function BackendSelector({ open, backends, onClose }: Props) {- const [selected, setSelected] = useState<string>(backends[0]?.id || '')// AppShell mounts this with an EMPTY `backends` array and fills it seconds// later, once the idle-time detection has run. A useState initialiser runs- // once, so the default above read `[]` and `selected` stayed the empty+ // once, so a plain `useState(backends[0]?.id)` read `[]` and stayed the empty// string for good: the dialog opened with no row marked, and "Use selected"// found nothing under that name, dismissed itself and configured nothing.// Same class as the picker bug of R10, a position taken from a list before- // the list exists. Re-seed it the moment a list arrives, and never overwrite- // a choice the user has already made.- useEffect(() => {- setSelected((cur) => (backends.some((b) => b.id === cur) ? cur : backends[0]?.id || ''))- }, [backends])+ // the list exists.+ //+ // So the SELECTION is not stored, only the user's own pick is; the effective+ // row is derived by selectedBackendId (lib/backend-detector), which carries+ // the rule the effect used to write back into state one render late (React 19+ // `set-state-in-effect`). As a derivation it is simply correct on the render+ // the list arrives in.+ const [picked, setPicked] = useState<string | null>(null)+ const selected = selectedBackendId(picked, backends)// Pre-checked: the common case is "saw it once, don't bug me again". User can// uncheck if they want it to re-appear on next launch.const [dontShowAgain, setDontShowAgain] = useState(true)@@ -114,7 +117,7 @@ export function BackendSelector({ open, backends, onClose }: Props) {{backends.map(backend => (<buttonkey={backend.id}- onClick={() => setSelected(backend.id)}+ onClick={() => setPicked(backend.id)}className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-left transition-colors ${selected === backend.id? 'bg-white/10 border border-white/15'diff --git a/src/components/settings/MemorySettings.tsx b/src/components/settings/MemorySettings.tsxindex f47e030b..63f911d2 100644--- a/src/components/settings/MemorySettings.tsx+++ b/src/components/settings/MemorySettings.tsx@@ -23,7 +23,12 @@ export function MemorySettings() {const [confirmClear, setConfirmClear] = useState(false)const [addingNew, setAddingNew] = useState(false)const [editingId, setEditingId] = useState<string | null>(null)- const [contextBudgetLabel, setContextBudgetLabel] = useState('')+ // Only the ASYNC half of the budget line is state; "no model selected" is a+ // fact the render already has and is derived below. Writing it from the+ // effect was a cascading render for something nothing had to be fetched for+ // (React 19 `set-state-in-effect`).+ const activeModel = useModelStore((s) => s.activeModel)+ const [budgetLabel, setBudgetLabel] = useState('')// Feature FF: reveal outdated (stale/superseded) entries, read-only.const [showOutdated, setShowOutdated] = useState(false)const [reembedState, setReembedState] = useState<'idle' | 'running' | 'done'>('idle')@@ -42,23 +47,23 @@ export function MemorySettings() {const [editContent, setEditContent] = useState('')// ── Context budget detection ────────────────────────────────+ const contextBudgetLabel = activeModel ? budgetLabel : 'No model selected'useEffect(() => {- const model = useModelStore.getState().activeModel- if (!model) {- setContextBudgetLabel('No model selected')- return- }- getModelMaxTokens(model).then((ctx) => {+ if (!activeModel) return+ let cancelled = false+ getModelMaxTokens(activeModel).then((ctx) => {+ if (cancelled) returnconst override = settings.maxMemoriesOverrideconst budget = effectiveMemoryBudget(ctx, override)const manual = override != null && override > 0 ? ' (manual)' : ''if (budget.budgetTokens === 0) {- setContextBudgetLabel(`${Math.round(ctx / 1024)}K ctx, memory injection disabled`)+ setBudgetLabel(`${Math.round(ctx / 1024)}K ctx, memory injection disabled`)} else {- setContextBudgetLabel(`${Math.round(ctx / 1024)}K ctx, up to ${budget.maxMemories} memories injected${manual}`)+ setBudgetLabel(`${Math.round(ctx / 1024)}K ctx, up to ${budget.maxMemories} memories injected${manual}`)}- }).catch(() => setContextBudgetLabel(''))- }, [settings.maxMemoriesOverride])+ }).catch(() => { if (!cancelled) setBudgetLabel('') })+ return () => { cancelled = true }+ }, [activeModel, settings.maxMemoriesOverride])const isEntryStale = (e: MemoryFile) => e.stale === true || typeof e.supersededBy === 'string'const staleCount = entries.filter(isEntryStale).lengthdiff --git a/src/components/three/ParticleField.tsx b/src/components/three/ParticleField.tsxindex 4032662c..ccd6a9b0 100644--- a/src/components/three/ParticleField.tsx+++ b/src/components/three/ParticleField.tsx@@ -1,4 +1,4 @@-import { useRef, useMemo } from 'react'+import { useRef, useState } from 'react'import { useFrame, useThree } from '@react-three/fiber'import * as THREE from 'three'@@ -12,6 +12,46 @@ import * as THREE from 'three'*/const PARTICLE_COUNT = 3000+/**+ * One field's worth of particles: a random point on a shell between r=3 and+ * r=7, a random grey, a random size.+ *+ * Random, and that is the point — but the randomness may not happen while the+ * component renders. React is free to render a component more than once for+ * one commit, and a re-run here would silently mint a SECOND set of buffers+ * while the geometry below still holds the first: the animation loop would+ * then read its rest positions out of one array and write its frames into+ * another, and the field would freeze mid-motion. Hence a plain function,+ * called once per mount from a lazy state initialiser.+ */+function makeParticles(count: number) {+ const positions = new Float32Array(count * 3)+ const colors = new Float32Array(count * 3)+ const sizes = new Float32Array(count)++ for (let i = 0; i < count; i++) {+ const i3 = i * 3+ // Sphere distribution+ const theta = Math.random() * Math.PI * 2+ const phi = Math.acos(2 * Math.random() - 1)+ const r = 3 + Math.random() * 4++ positions[i3] = r * Math.sin(phi) * Math.cos(theta)+ positions[i3 + 1] = r * Math.sin(phi) * Math.sin(theta)+ positions[i3 + 2] = r * Math.cos(phi)++ // Subtle white/gray+ const brightness = 0.3 + Math.random() * 0.4+ colors[i3] = brightness+ colors[i3 + 1] = brightness+ colors[i3 + 2] = brightness + Math.random() * 0.1++ sizes[i] = 1.5 + Math.random() * 2+ }++ return { positions, colors, sizes }+}+export function ParticleField() {const pointsRef = useRef<THREE.Points>(null)const mouseRef = useRef(new THREE.Vector2(0, 0))@@ -19,33 +59,11 @@ export function ParticleField() {const count = PARTICLE_COUNT- const { positions, colors, sizes } = useMemo(() => {- const positions = new Float32Array(count * 3)- const colors = new Float32Array(count * 3)- const sizes = new Float32Array(count)-- for (let i = 0; i < count; i++) {- const i3 = i * 3- // Sphere distribution- const theta = Math.random() * Math.PI * 2- const phi = Math.acos(2 * Math.random() - 1)- const r = 3 + Math.random() * 4-- positions[i3] = r * Math.sin(phi) * Math.cos(theta)- positions[i3 + 1] = r * Math.sin(phi) * Math.sin(theta)- positions[i3 + 2] = r * Math.cos(phi)-- // Subtle white/gray- const brightness = 0.3 + Math.random() * 0.4- colors[i3] = brightness- colors[i3 + 1] = brightness- colors[i3 + 2] = brightness + Math.random() * 0.1-- sizes[i] = 1.5 + Math.random() * 2- }-- return { positions, colors, sizes }- }, [count])+ // A lazy state initialiser, NOT useMemo: useMemo is a hint React may throw+ // away and recompute, which for this component means brand-new buffers under+ // a running animation. State is a guarantee — these three arrays are created+ // once per mounted field and stay the ones the geometry was built from.+ const [{ positions, colors, sizes }] = useState(() => makeParticles(count))useFrame(({ clock, pointer }) => {if (!pointsRef.current) returndiff --git a/src/hooks/useActiveContextWindow.ts b/src/hooks/useActiveContextWindow.tsindex da1abe7b..6c7e8d40 100644--- a/src/hooks/useActiveContextWindow.ts+++ b/src/hooks/useActiveContextWindow.ts@@ -34,6 +34,11 @@ export interface ActiveContext {adjustable: boolean}+/** What the hook reports while there is no model, or none resolved yet. */+const NO_CONTEXT: ActiveContext = {+ provider: 'unknown', contextWindow: 0, modelMax: 0, sendWindow: 0, isTrue: false, adjustable: false,+}+/*** Resolve the REAL context window of the active model, provider-aware, so the* TokenCounter denominator and the Context dropdown agree and never lie:@@ -50,9 +55,15 @@ export function useActiveContextWindow(reloadTick = 0): ActiveContext {const builtinCtx = useSettingsStore((s) => s.settings.builtinEngine.ctx)const sendWindowTokens = useSettingsStore((s) => s.settings.codexSendWindowTokens)const capEnabled = useSettingsStore((s) => s.settings.contextDecay)- const [state, setState] = useState<ActiveContext>({- provider: 'unknown', contextWindow: 0, modelMax: 0, sendWindow: 0, isTrue: false, adjustable: false,- })+ // The resolved window carries the model it was resolved FOR. That tag does+ // two jobs: the "no model" case becomes a derivation instead of a setState+ // fired from the effect body (React 19 `set-state-in-effect`), and a model+ // switch no longer reports the PREVIOUS model's window during the probe.+ // The second one matters for this hook in particular — everything above is+ // about the counter never lying, and "62k of 262k" under a model that has+ // 8k is exactly the lie. Unresolved reads as unknown, which is the state+ // every consumer already handles on mount.+ const [resolved, setResolved] = useState<{ model: string; ctx: ActiveContext } | null>(null)// Re-read whenever a model reload finishes anywhere (the Context dropdown// fires this), so every consumer — counter AND dropdown — reflects the new@@ -65,12 +76,10 @@ export function useActiveContextWindow(reloadTick = 0): ActiveContext {}, [])useEffect(() => {- if (!activeModel) {- setState({ provider: 'unknown', contextWindow: 0, modelMax: 0, sendWindow: 0, isTrue: false, adjustable: false })- return- }+ if (!activeModel) returnlet cancelled = falseconst providerId = getProviderIdFromModel(activeModel)+ const setState = (ctx: ActiveContext) => setResolved({ model: activeModel, ctx });(async () => {// ── Ollama: num_ctx is per-request, so what we send == what runs. ──@@ -177,5 +186,5 @@ export function useActiveContextWindow(reloadTick = 0): ActiveContext {return () => { cancelled = true }}, [activeModel, override, builtinCtx, sendWindowTokens, capEnabled, reloadTick, reloadBump])- return state+ return activeModel && resolved?.model === activeModel ? resolved.ctx : NO_CONTEXT}diff --git a/src/hooks/useMemory.ts b/src/hooks/useMemory.tsindex 88b0e720..84490015 100644--- a/src/hooks/useMemory.ts+++ b/src/hooks/useMemory.ts@@ -6,7 +6,6 @@* failures must never disrupt the chat experience.*/-import { useCallback } from 'react'import { useMemoryStore } from '../stores/memoryStore'import { useModelStore } from '../stores/modelStore'import { useProviderStore } from '../stores/providerStore'@@ -301,13 +300,25 @@ async function resolveAndSaveMemory(memory: ExtractedMemory, conversationId: struseMemoryStore.getState().applyWriteDecision(decision, { newId: newId || undefined })}-export function useMemory() {+/**+ * The hook's surface, built once at module load.+ *+ * `extractMemoriesFromPair` is a module function — it closes over nothing from+ * a render, so it is already as stable as a value gets and there was nothing+ * for `useCallback` to memoise. Wrapping it also broke React 19's `use-memo`+ * rule, which insists the memo hooks take an inline function so the compiler+ * can see what it is memoising. Handing back a frozen object keeps the+ * identity every consumer had.+ */+const MEMORY_API = Object.freeze({/*** Fire-and-forget extraction: asks the active LLM to analyze a conversation* exchange and save any extracted memories. Rate-limited to every 3rd turn* and skips short responses.*/- const extractAndSave = useCallback(extractMemoriesFromPair, [])+ extractAndSave: extractMemoriesFromPair,+})- return { extractAndSave }+export function useMemory() {+ return MEMORY_API}diff --git a/src/lib/__tests__/cloud-teaser-click-identity.test.ts b/src/lib/__tests__/cloud-teaser-click-identity.test.tsindex 1de97493..ec536696 100644--- a/src/lib/__tests__/cloud-teaser-click-identity.test.ts+++ b/src/lib/__tests__/cloud-teaser-click-identity.test.ts@@ -212,16 +212,28 @@ describe('the same mistake, swept for elsewhere', () => {it('the backend dialog re-seeds its choice when the detected list arrives', () => {// AppShell mounts it with an empty array and fills it seconds later, so// the useState default read `[]` and "Use selected" found nothing.+ //+ // The re-seed used to be a `useEffect(..., [backends])` writing the answer+ // back into state; since the React 19 set-state-in-effect fix the rule is+ // the pure `selectedBackendId` and the dialog derives the row on every+ // render, which settles it ON the render the list arrives in rather than a+ // paint later. Both halves of the rule — "the pick while the list holds it,+ // otherwise row one" — are exercised in+ // src/lib/__tests__/derived-ui-state.test.ts; what is pinned here is that+ // the dialog uses it and grows no effect to undo it.const sel = read('src/components/onboarding/BackendSelector.tsx')- expect(sel).toMatch(/backends\.some\(\(b\) => b\.id === cur\) \? cur : backends\[0\]\?\.id/)- expect(sel).toMatch(/\}, \[backends\]\)/)+ expect(sel).toMatch(/const selected = selectedBackendId\(picked, backends\)/)+ expect(sel).not.toMatch(/useEffect/)+ const det = read('src/lib/backend-detector.ts')+ expect(det).toMatch(/return backends\[0\]\?\.id \|\| ''/)})it('NEGATIVE CONTROL: it still confirms by id, and a made choice survives', () => {const sel = read('src/components/onboarding/BackendSelector.tsx')expect(sel).toMatch(/backends\.find\(b => b\.id === selected\)/)- // The re-seed keeps `cur` whenever the list still holds it, so a user who- // picked before the list settled is not overruled.- expect(sel).toMatch(/setSelected\(\(cur\) =>/)+ // A pick the user made before the list settled is not overruled: it is+ // returned as-is whenever the list still holds it.+ const det = read('src/lib/backend-detector.ts')+ expect(det).toMatch(/if \(picked !== null && backends\.some\(\(b\) => b\.id === picked\)\) return picked/)})})diff --git a/src/lib/__tests__/derived-ui-state.test.ts b/src/lib/__tests__/derived-ui-state.test.tsnew file mode 100644index 00000000..9d49688d--- /dev/null+++ b/src/lib/__tests__/derived-ui-state.test.ts@@ -0,0 +1,82 @@+/**+ * Two rules that used to be `useEffect`s writing state back into React, now+ * pure functions — tested as BEHAVIOUR rather than as source text.+ *+ * Both were flagged by React 19's `set-state-in-effect`, and in both cases the+ * rule itself never needed an effect: it is a function of things the render+ * already has. The source-pinning tests that guarded them+ * (cloud-teaser-click-identity.test.ts, tool-media-lifetime.test.ts) had to be+ * re-pointed at the new seam, so the guarantees live here where the spelling+ * cannot break them.+ *+ * Every case is what the effect version did.+ *+ * Run: npx vitest run src/lib/__tests__/derived-ui-state.test.ts+ */+import { describe, it, expect } from 'vitest'+import { selectedBackendId } from '../backend-detector'+import { displayableMedia } from '../local-media-url'++const OLLAMA = { id: 'ollama' }+const LMSTUDIO = { id: 'lmstudio' }++describe('the backend dialog picks a row the moment the list arrives', () => {+ it('marks nothing while the detection has not run', () => {+ // AppShell mounts the dialog with an EMPTY array. The old bug was a+ // useState default frozen on `[]`, so "Use selected" found nothing.+ expect(selectedBackendId(null, [])).toBe('')+ })++ it('falls to the first row the second the list is filled in', () => {+ expect(selectedBackendId(null, [OLLAMA, LMSTUDIO])).toBe('ollama')+ })++ it('does not overrule a user who picked before the list settled', () => {+ expect(selectedBackendId('lmstudio', [OLLAMA, LMSTUDIO])).toBe('lmstudio')+ })++ it('drops a pick the list no longer holds', () => {+ expect(selectedBackendId('vllm', [OLLAMA, LMSTUDIO])).toBe('ollama')+ })++ it('drops a pick when the list empties again', () => {+ expect(selectedBackendId('ollama', [])).toBe('')+ })+})++describe('a tool result says what it can actually show', () => {+ it('hands back anything that is not one of our files', () => {+ const view = 'http://localhost:8188/view?filename=x.png'+ expect(displayableMedia(view, null, null)).toEqual({ url: view, missing: false })+ })++ it('treats a stored blob: URL as already dead', () => {+ // Nothing mints them any more, so one in a persisted result came from an+ // older window and its blob died with it. Saying so beats a broken frame.+ expect(displayableMedia('blob:abc', null, null)).toEqual({ url: null, missing: true })+ })++ it('shows nothing, and does not cry missing, while the read is in flight', () => {+ expect(displayableMedia('file:///a.png', '/a.png', null)).toEqual({ url: null, missing: false })+ })++ it('shows the fresh blob once the read lands', () => {+ const read = { path: '/a.png', url: 'blob:fresh', missing: false }+ expect(displayableMedia('file:///a.png', '/a.png', read)).toEqual({ url: 'blob:fresh', missing: false })+ })++ it('says the file is gone when the read failed', () => {+ const read = { path: '/a.png', url: null, missing: true }+ expect(displayableMedia('file:///a.png', '/a.png', read)).toEqual({ url: null, missing: true })+ })++ it('never lets one file’s outcome speak for another', () => {+ // The read is async: a result can land after the block has moved on. An+ // untagged outcome would paint the previous file's blob — or its "gone" —+ // over the new one.+ const stale = { path: '/old.png', url: 'blob:old', missing: false }+ expect(displayableMedia('file:///new.png', '/new.png', stale)).toEqual({ url: null, missing: false })+ const staleMissing = { path: '/old.png', url: null, missing: true }+ expect(displayableMedia('file:///new.png', '/new.png', staleMissing)).toEqual({ url: null, missing: false })+ })+})diff --git a/src/lib/__tests__/download-tray.test.ts b/src/lib/__tests__/download-tray.test.tsnew file mode 100644index 00000000..0f2e48de--- /dev/null+++ b/src/lib/__tests__/download-tray.test.ts@@ -0,0 +1,81 @@+/**+ * The downloads tray's open/close rule, as BEHAVIOUR.+ *+ * DownloadBadge-autoclose.test.ts guards the same three guarantees at the+ * source, because there is no render harness in this repo. That test had to be+ * re-pointed when the two `useEffect`s moved out of the component (React 19+ * `set-state-in-effect`), so this file exists to make the guarantees themselves+ * — not their spelling — the thing that is checked.+ *+ * Every case below is what the OLD two-effect version did, transition for+ * transition:+ *+ * effect A, deps [totalActive]: if (totalActive > 0) { open = true; auto = true }+ * effect B, deps [hasAny]: if (!hasAny && auto) { open = false; auto = false }+ * button: open = !open; auto = false+ *+ * Run: npx vitest run src/lib/__tests__/download-tray.test.ts+ */+import { describe, it, expect } from 'vitest'+import { trayAfterPulse, TRAY_CLOSED, NO_PULSE, type TrayState } from '../download-tray'++const OPEN_AUTO: TrayState = { open: true, auto: true }+const OPEN_BY_HAND: TrayState = { open: true, auto: false }++describe('the tray opens itself when a download starts', () => {+ it('opens on the first running download', () => {+ expect(trayAfterPulse(TRAY_CLOSED, NO_PULSE, { active: 1, any: true })).toEqual(OPEN_AUTO)+ })++ it('opens for a download that was already running when the badge mounted', () => {+ // The badge is always mounted, but a restored (persisted) download can be+ // running before this component's first render. NO_PULSE is what makes that+ // read as "just started", the way the mount pass of the old effect did.+ expect(trayAfterPulse(TRAY_CLOSED, NO_PULSE, { active: 3, any: true })).toEqual(OPEN_AUTO)+ })++ it('opens again for a NEW download after the user closed it by hand', () => {+ const closedByHand: TrayState = { open: false, auto: false }+ expect(trayAfterPulse(closedByHand, { active: 1, any: true }, { active: 2, any: true }))+ .toEqual(OPEN_AUTO)+ })++ it('stays put when nothing about the picture changed', () => {+ const same = { active: 2, any: true }+ expect(trayAfterPulse(TRAY_CLOSED, same, same)).toBe(TRAY_CLOSED)+ })+})++describe('the tray closes itself, but only if it opened itself', () => {+ it('closes when the last entry goes away', () => {+ expect(trayAfterPulse(OPEN_AUTO, { active: 0, any: true }, { active: 0, any: false }))+ .toEqual({ open: false, auto: false })+ })++ it('leaves a hand-opened tray alone when the list empties', () => {+ expect(trayAfterPulse(OPEN_BY_HAND, { active: 0, any: true }, { active: 0, any: false }))+ .toBe(OPEN_BY_HAND)+ })++ it('stays open while a finished or paused row is still there to read', () => {+ // active drops to 0 but `any` is still true: the download completed and its+ // row is what the user is meant to see. This is why the close is keyed on+ // `any` and not on `active`.+ expect(trayAfterPulse(OPEN_AUTO, { active: 1, any: true }, { active: 0, any: true }))+ .toBe(OPEN_AUTO)+ })++ it('does not close a tray that is already shut', () => {+ expect(trayAfterPulse(TRAY_CLOSED, { active: 0, any: true }, { active: 0, any: false }))+ .toBe(TRAY_CLOSED)+ })+})++describe('a start beats a finish in the same change', () => {+ it('opening wins when both could apply', () => {+ // Cannot actually happen (active > 0 implies any), but the old code ran+ // effect A before effect B, so the order is pinned rather than assumed.+ expect(trayAfterPulse(OPEN_AUTO, { active: 0, any: true }, { active: 1, any: false }))+ .toEqual(OPEN_AUTO)+ })+})diff --git a/src/lib/backend-detector.ts b/src/lib/backend-detector.tsindex 865d7972..3a85275c 100644--- a/src/lib/backend-detector.ts+++ b/src/lib/backend-detector.ts@@ -15,6 +15,27 @@ export interface DetectedBackend {port: number}+/**+ * Which detected backend the selection dialog has marked, given the user's own+ * pick (null until they click) and the list as it currently stands.+ *+ * AppShell mounts the dialog with an EMPTY list and fills it seconds later,+ * once the idle-time detection has run, so a position taken from the list+ * before the list exists is the bug this exists to prevent: the dialog opened+ * with no row marked, and "Use selected" found nothing under that name,+ * dismissed itself and configured nothing (same class as the picker bug of+ * R10). The rule has two halves and always had: keep the user's pick while the+ * list still holds it, otherwise fall to the first row there is.+ *+ * It lives here, as a pure function, because the repo has no render harness —+ * this is the part worth testing, and it is the part that used to be an effect+ * writing the answer back into state one render after it was knowable.+ */+export function selectedBackendId(picked: string | null, backends: { id: string }[]): string {+ if (picked !== null && backends.some((b) => b.id === picked)) return picked+ return backends[0]?.id || ''+}+const PROBE_TIMEOUT = 2000 // 2 seconds — backend probe must be fast or skipped/**diff --git a/src/lib/download-tray.ts b/src/lib/download-tray.tsnew file mode 100644index 00000000..b042e4e3--- /dev/null+++ b/src/lib/download-tray.ts@@ -0,0 +1,66 @@+/**+ * When the downloads tray in the header opens and closes itself.+ *+ * The tray opens itself the moment a download starts, and closes itself again+ * when there is nothing left to show — but ONLY if it was the tray that opened+ * it. A tray the user opened by hand stays put. (Regression of 2026-07-26: an+ * auto-opened tray had no way back, so the panel hung over the app reading+ * "No active downloads" until the user happened to click somewhere else.)+ *+ * This used to live in two `useEffect`s inside DownloadBadge that wrote the+ * answer back into React state after every change of the download picture,+ * which React 19 flags as `set-state-in-effect` — a cascading render, landing a+ * paint later than it had to. The rule itself never depended on effects, so it+ * is a pure function here and the component applies it while rendering. Being+ * pure is also the only way it can be tested at all: the repo has no render+ * harness (vitest runs in `node`, there is no @testing-library).+ */++/** Is the tray open, and was it the tray or the user that opened it. */+export interface TrayState {+ open: boolean+ /** True only while the tray is showing itself unasked. */+ auto: boolean+}++/** The download picture in one glance. */+export interface DownloadPulse {+ /** How many downloads are running right now (paused/finished excluded). */+ active: number+ /** Whether there is ANY entry at all — running, paused, finished or failed. */+ any: boolean+}++/**+ * The tray after the download picture changed from `seen` to `now`.+ *+ * Returns the SAME object when nothing applies, so a caller can skip the state+ * write entirely.+ *+ * Two transitions, in the order the two old effects ran in:+ *+ * 1. The number of running downloads changed and something is running: a+ * download started, so show the tray and remember that WE opened it.+ * Keyed on the count changing, not on "> 0", so the tray does not+ * re-assert itself on every unrelated re-render.+ * 2. The last entry went away and the tray is the one that opened itself:+ * close it. Keyed on `any` (every entry, not just active ones), so a+ * finished or failed row stays readable until it is cleared.+ */+export function trayAfterPulse(tray: TrayState, seen: DownloadPulse, now: DownloadPulse): TrayState {+ if (seen.active !== now.active && now.active > 0) return { open: true, auto: true }+ if (seen.any !== now.any && !now.any && tray.auto) return { open: false, auto: false }+ return tray+}++/** The tray as it starts out: shut, and not by anyone's decision. */+export const TRAY_CLOSED: TrayState = { open: false, auto: false }++/**+ * The pulse the component compares its FIRST render against.+ *+ * Zero on purpose: a download already running when the badge mounts has to+ * count as one that just started, which is what the mount pass of the old+ * auto-open effect did.+ */+export const NO_PULSE: DownloadPulse = { active: 0, any: false }diff --git a/src/lib/local-media-url.ts b/src/lib/local-media-url.tsindex f8d4a8ce..5d7d7ff5 100644--- a/src/lib/local-media-url.ts+++ b/src/lib/local-media-url.ts@@ -35,6 +35,43 @@ export function fileUrlToPath(url: string): string | null {}}+/**+ * The outcome of one local-file read, tagged with the path it was made for.+ *+ * The tag is not decoration: the read is async, so a result can land after the+ * block has moved on to a different file, and an untagged outcome would paint+ * the previous file's blob — or its "gone" — over the new one.+ */+export interface MediaRead {+ path: string+ url: string | null+ missing: boolean+}++/**+ * What a tool result's media area shows.+ *+ * Extracted from ToolCallBlock's `useDisplayableMediaUrl` so the rule can be+ * exercised directly — the repo has no render harness, and the rule is the part+ * worth guarding. It is the same rule the hook has always followed:+ *+ * - a `blob:` URL in a STORED result is necessarily dead (nothing mints them+ * any more, so it came from an older window) → say the file is gone;+ * - anything that is not one of our `file://` URLs is handed straight back;+ * - one of ours shows nothing until its read lands, then either the fresh+ * blob or "gone".+ */+export function displayableMedia(+ rawUrl: string | null,+ path: string | null,+ read: MediaRead | null,+): { url: string | null; missing: boolean } {+ if (rawUrl && rawUrl.startsWith('blob:')) return { url: null, missing: true }+ if (!path) return { url: rawUrl, missing: false }+ const current = read && read.path === path ? read : null+ return { url: current?.url ?? null, missing: current?.missing ?? false }+}+export function guessMimeFromName(filename: string): string {const ext = filename.toLowerCase().split('.').pop() || ''if (ext === 'mp4') return 'video/mp4'