Skip to content

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.

fix: 3 post-E2E hardenings (backup triad + codex loop-guard + stop fast-path)

PurpleDoubleD9c3d63309a03
diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx
index 21c51106..36b2ad2d 100644
--- a/src/components/layout/AppShell.tsx
+++ b/src/components/layout/AppShell.tsx
@@ -89,7 +89,15 @@ export function AppShell() {
})
}, [])
- // Periodically backup stores to %APPDATA% (every 30s)
+ // Backup stores to %APPDATA% — three-pronged so chat history survives
+ // NSIS updates + abrupt process kills:
+ // 1. 10 s safety-net interval (was 30 s — too slow, users lost chats if
+ // they sent a message shortly before an upgrade).
+ // 2. Debounced event-driven backup: 1 s after every chat/codex/memory
+ // mutation. Catches "typed + restart within interval window" case.
+ // 3. beforeunload sync flush on Tauri window close. Fires for graceful
+ // quits and "X" button; does NOT fire for taskkill / NSIS upgrade
+ // (why we need 1+2 as well).
useEffect(() => {
if (!isTauri() || !onboardingDone) return
// Migration: legacy users with localStorage onboardingDone=true but missing
@@ -111,8 +119,30 @@ export function AppShell() {
}
}
doBackup() // immediate first backup
- const interval = setInterval(doBackup, 30_000)
- return () => clearInterval(interval)
+ const interval = setInterval(doBackup, 10_000)
+
+ // Event-driven backup: subscribe to the stores that change most often
+ // (chat conversations, codex chats, memory). Debounce to coalesce bursts
+ // — a 10-message thread arrives in ~1 s, we only want 1 backup call, not 10.
+ let debounceTimer: ReturnType<typeof setTimeout> | null = null
+ const scheduleBackup = () => {
+ if (debounceTimer) clearTimeout(debounceTimer)
+ debounceTimer = setTimeout(doBackup, 1_000)
+ }
+ const unsubChat = useChatStore.subscribe(scheduleBackup)
+
+ // Tauri window close path — triggers on graceful quit (user clicks X)
+ // and on window.close(). Process kill / NSIS update DO NOT fire this,
+ // hence the interval above as a safety net.
+ const onBeforeUnload = () => doBackup()
+ window.addEventListener('beforeunload', onBeforeUnload)
+
+ return () => {
+ clearInterval(interval)
+ if (debounceTimer) clearTimeout(debounceTimer)
+ unsubChat()
+ window.removeEventListener('beforeunload', onBeforeUnload)
+ }
}, [onboardingDone])
useEffect(() => {
diff --git a/src/components/layout/__tests__/AppShell-backup-triad.test.ts b/src/components/layout/__tests__/AppShell-backup-triad.test.ts
new file mode 100644
index 00000000..8ab9a19d
--- /dev/null
+++ b/src/components/layout/__tests__/AppShell-backup-triad.test.ts
@@ -0,0 +1,65 @@
+/**
+ * Smoke tests for the AppShell store backup triad (Bug #7 hotfix, 2026-04-19).
+ *
+ * Before the fix, chat history could be lost when an NSIS update killed the
+ * app between backup intervals. The triad is:
+ * 1. 10s safety-net interval (was 30s)
+ * 2. chatStore.subscribe → debounced backup on any mutation
+ * 3. beforeunload sync flush for graceful quits
+ *
+ * These tests read the source so we catch accidental regressions that would
+ * quietly revert any of the three.
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'fs'
+import { fileURLToPath } from 'url'
+import { dirname, join } from 'path'
+
+const __filename = fileURLToPath(import.meta.url)
+const __dirname = dirname(__filename)
+const src = readFileSync(join(__dirname, '../AppShell.tsx'), 'utf8')
+
+describe('AppShell backup triad (Bug #7)', () => {
+ it('runs the safety-net interval every 10 seconds (not 30 or longer)', () => {
+ expect(src).toContain('setInterval(doBackup, 10_000)')
+ // Make sure the old 30s value is really gone.
+ expect(src).not.toContain('setInterval(doBackup, 30_000)')
+ })
+
+ it('subscribes to chatStore for event-driven backup', () => {
+ expect(src).toContain('useChatStore.subscribe')
+ expect(src).toContain('scheduleBackup')
+ })
+
+ it('debounces event-driven backups with a setTimeout to coalesce bursts', () => {
+ expect(src).toContain('debounceTimer')
+ expect(src).toMatch(/setTimeout\(doBackup,\s*1_?000\)/)
+ })
+
+ it('flushes a final backup on beforeunload (graceful quit)', () => {
+ expect(src).toContain("addEventListener('beforeunload'")
+ expect(src).toContain('onBeforeUnload')
+ })
+
+ it('cleans up all three hooks in the useEffect return', () => {
+ // Regression guard: the return() block must clear interval, debounce,
+ // subscription, and event listener.
+ expect(src).toContain('clearInterval(interval)')
+ expect(src).toContain('unsubChat()')
+ expect(src).toContain("removeEventListener('beforeunload'")
+ expect(src).toContain('clearTimeout(debounceTimer)')
+ })
+
+ it('writes the restore-complete sentinel only when snapshot has entries', () => {
+ // Otherwise an empty fresh install would write the sentinel and block
+ // the next startup's restore attempt.
+ expect(src).toContain('Object.keys(snapshot).length > 0')
+ // The backup-path sentinel-set must come AFTER the length-check (guarded by it).
+ // Note: there's also a restore-path sentinel write (line ~76) — we only
+ // care that at least one occurrence lives after the length guard.
+ const idxLenCheck = src.indexOf('Object.keys(snapshot).length > 0')
+ const allSentinelWrites = [...src.matchAll(/localStorage\.setItem\('lu-restore-complete'/g)]
+ const guardedByLenCheck = allSentinelWrites.some(m => (m.index ?? 0) > idxLenCheck)
+ expect(guardedByLenCheck).toBe(true)
+ })
+})
diff --git a/src/hooks/__tests__/useCodex-loop-detection.test.ts b/src/hooks/__tests__/useCodex-loop-detection.test.ts
new file mode 100644
index 00000000..661a54e4
--- /dev/null
+++ b/src/hooks/__tests__/useCodex-loop-detection.test.ts
@@ -0,0 +1,84 @@
+/**
+ * Smoke tests for the Codex loop-detector (Bug #5 hotfix, 2026-04-19).
+ *
+ * Small / 3B models (qwen2.5-coder:3b, llama3.2:1b) often get stuck
+ * repeating the same file_write + shell_execute batch because a test
+ * fails and they "fix" it by rewriting the same file. The loop detector
+ * aborts with a clear message when the same batch signature appears
+ * twice in a row.
+ *
+ * These tests read the actual source so we catch accidental removal
+ * of the detector during refactors.
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'fs'
+import { fileURLToPath } from 'url'
+import { dirname, join } from 'path'
+
+const __filename = fileURLToPath(import.meta.url)
+const __dirname = dirname(__filename)
+const src = readFileSync(join(__dirname, '../useCodex.ts'), 'utf8')
+
+describe('useCodex loop-detector (Bug #5)', () => {
+ it('declares prevBatchSig tracking variable', () => {
+ expect(src).toContain('prevBatchSig')
+ })
+
+ it('declares sameBatchRepeats counter', () => {
+ expect(src).toContain('sameBatchRepeats')
+ })
+
+ it('computes batch signature from tool name + arguments, sorted', () => {
+ expect(src).toContain('batchSig')
+ expect(src).toContain("tc.function.name + ':' + JSON.stringify(tc.function.arguments)")
+ expect(src).toContain('.sort()')
+ })
+
+ it('halts after 2 identical repeats (total 3 matching batches)', () => {
+ // sameBatchRepeats >= 2 with prevBatchSig === batchSig means 3 batches in a row
+ expect(src).toMatch(/sameBatchRepeats\s*>=\s*2/)
+ })
+
+ it('emits a user-visible halt message mentioning model size', () => {
+ expect(src).toMatch(/same tool sequence repeated/)
+ expect(src).toMatch(/larger model/i)
+ })
+
+ it('resets the repeat counter when the batch changes', () => {
+ expect(src).toContain('sameBatchRepeats = 0')
+ })
+
+ it('checks batch signature AFTER tool calls are collected but BEFORE executing', () => {
+ // The detector sits between "toolCalls.length === 0 break" and the
+ // batch-building for-loop — so it catches the repeat before we burn
+ // an execution slot and another HTTP round-trip.
+ const idxCheck = src.indexOf('batchSig = toolCalls')
+ const idxExec = src.indexOf('budget.addToolCalls(toolCalls.length)')
+ expect(idxCheck).toBeGreaterThan(0)
+ expect(idxExec).toBeGreaterThan(idxCheck)
+ })
+})
+
+describe('useChat stop fast-path (Bug #6)', () => {
+ const chatSrc = readFileSync(join(__dirname, '../useChat.ts'), 'utf8')
+
+ it('checks abort.signal.aborted inside the chunk for-await loop', () => {
+ // The fast-path must live inside the for-await so Stop feels instant
+ // during long thinking chains (Gemma 4, QwQ).
+ expect(chatSrc).toContain('for await (const chunk of stream)')
+ expect(chatSrc).toContain('if (abort.signal.aborted) break')
+ // Must appear AFTER the for-await opens (inside the body, not before).
+ const idxLoop = chatSrc.indexOf('for await (const chunk of stream)')
+ const idxAbort = chatSrc.indexOf('if (abort.signal.aborted) break')
+ expect(idxAbort).toBeGreaterThan(idxLoop)
+ // And within reasonable distance (not 2000 chars away).
+ expect(idxAbort - idxLoop).toBeLessThan(500)
+ })
+})
+
+describe('useCodex stream reader abort fast-path (Bug #6)', () => {
+ it('cancels the reader when signal.aborted inside the NDJSON while loop', () => {
+ expect(src).toMatch(/options\.signal\?\.aborted/)
+ expect(src).toMatch(/reader\.cancel/)
+ })
+})
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index ac057f3a..324a656c 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -212,6 +212,14 @@ export function useChat() {
let firstChunk = true
for await (const chunk of stream) {
+ // Abort fast-path: if the user hit Stop while a thinking-heavy model
+ // (Gemma 4, QwQ) is still generating its thinking block, the fetch
+ // AbortController alone can take 30-60 s to actually close the HTTP
+ // stream — during that time Ollama keeps emitting `thinking` chunks
+ // that we'd otherwise spin on. Check the flag every chunk so Stop
+ // feels instant even mid-thinking.
+ if (abort.signal.aborted) break
+
if (firstChunk) {
firstChunk = false
setIsLoadingModel(false)
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 333ffe0b..a836f350 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -119,6 +119,14 @@ async function streamWithTools(
let toolCalls: ToolCall[] = []
while (true) {
+ // Fast-abort: if the user hits Stop while the model is still generating
+ // (especially in a long thinking phase), cancelling the fetch alone can
+ // take ages to propagate. Check the signal each chunk + actively cancel
+ // the reader so the loop exits immediately.
+ if (options.signal?.aborted) {
+ try { await reader.cancel() } catch {}
+ break
+ }
const { done, value } = await reader.read()
if (done) break
@@ -318,6 +326,14 @@ export function useCodex() {
try {
// Agent loop — max 20 iterations (legacy cap) AND AgentBudget cap,
// whichever is tighter.
+ // Loop-detection: small / 3B models (qwen2.5-coder:3b, llama3.2:1b)
+ // often get stuck repeating the same file_write+shell_execute sequence
+ // because a test fails and they "fix" it by rewriting the same file.
+ // Track the signature of each iteration's tool-call batch; if the same
+ // signature appears twice in a row we abort with a clear message
+ // instead of burning budget on a no-op loop.
+ let prevBatchSig: string | null = null
+ let sameBatchRepeats = 0
for (let i = 0; i < 20 && runningRef.current && !abort.signal.aborted; i++) {
budget.addIteration()
const bx = budget.exceeded()
@@ -477,6 +493,24 @@ export function useCodex() {
// Phase 5b (v2.4.0) — parallel tool execution via tool-executor.
if (!runningRef.current || abort.signal.aborted) break
+ // Loop-detector: compute batch signature (sorted name+args pairs).
+ // Two identical batches in a row → 3 means we're definitely stuck.
+ const batchSig = toolCalls
+ .map(tc => tc.function.name + ':' + JSON.stringify(tc.function.arguments))
+ .sort()
+ .join('|')
+ if (batchSig === prevBatchSig) {
+ sameBatchRepeats++
+ if (sameBatchRepeats >= 2) {
+ const msg = `\n\n_(halted: same tool sequence repeated ${sameBatchRepeats + 1}× — model is looping. Try a larger model like Qwen 3.6 for multi-step code tasks.)_`
+ useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent + msg)
+ break
+ }
+ } else {
+ sameBatchRepeats = 0
+ prevBatchSig = batchSig
+ }
+
type BatchEntry = { tc: typeof toolCalls[number]; ac: AgentToolCall; blockId: string; injectedArgs: Record<string, any> }
const batch: BatchEntry[] = []
budget.addToolCalls(toolCalls.length)