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(codex): the approval queue survives a restart, and an update is a restart

purplecc883f5301db
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 339ca62d..e4f2ef8e 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -31,7 +31,7 @@ import { requestGenerationCancel } from '../api/vram-handoff'
import { planWithArchitect, renderArchitectPlanSection } from '../api/agents/architect'
import { fetchRepoMap, renderRepoMapSection } from '../api/agents/repo-map'
import { isLocalModelByName } from '../api/agents/model-locality'
-import { useStagedChangesStore } from '../stores/stagedChangesStore'
+import { useStagedChangesStore, flushStagedPersist } from '../stores/stagedChangesStore'
import { computeUnifiedDiff } from '../lib/diff'
import { applyUniqueEdit } from '../lib/surgical-edit'
import { log } from '../lib/logger'
@@ -2013,6 +2013,10 @@ export function useCodex() {
// (2.6.3 — see coalescedStorage), and losing the tool chain would cost
// the next turn its context, not just the transcript.
void flushChatPersist()
+ // Same reasoning for the approval queue: what is still pending is work
+ // the user paid for and has not seen land yet. It has to be on disk
+ // before the app can be closed or updated (2026-08-11).
+ void flushStagedPersist()
codexStore.setThreadStatus(convId, 'idle')
// The per-batch bump above only fires when a batch RETURNS. A user who
diff --git a/src/stores/__tests__/stagedChangesStore-rehydrate.test.ts b/src/stores/__tests__/stagedChangesStore-rehydrate.test.ts
new file mode 100644
index 00000000..97c238ea
--- /dev/null
+++ b/src/stores/__tests__/stagedChangesStore-rehydrate.test.ts
@@ -0,0 +1,98 @@
+/**
+ * A restart, and therefore every update, used to empty the approval queue: the
+ * store lived in memory only. Morgan finished a run on 2026-08-11 whose file
+ * changes could not be applied, and updating to the fix would have thrown them
+ * away before he could retry them.
+ *
+ * This is the real proof, not a source guard: a fresh module load (which is
+ * what a restart is) against a database that already holds a queue.
+ *
+ * Run: npx vitest run src/stores/__tests__/stagedChangesStore-rehydrate.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const DAY = 24 * 60 * 60 * 1000
+
+const disk = vi.hoisted(() => ({ value: null as string | null }))
+
+// idbStorage answers synchronously when IndexedDB is absent, which is exactly
+// the node case here, so hydration stays synchronous.
+vi.mock('../../lib/idbStorage', () => ({
+ idbStorage: {
+ getItem: (_name: string) => disk.value,
+ setItem: (_name: string, value: string) => {
+ disk.value = value
+ },
+ removeItem: () => {
+ disk.value = null
+ },
+ },
+}))
+
+function writeDisk(entries: Record<string, unknown[]>) {
+ disk.value = JSON.stringify({ state: { byChat: entries }, version: 0 })
+}
+
+const entry = (over: Record<string, unknown> = {}) => ({
+ id: 'e1',
+ path: 'src/main.py',
+ resolvedPath: '/proj/src/main.py',
+ workingDirectory: '/proj',
+ oldContent: 'before',
+ newContent: 'after the agent wrote it',
+ diff: '',
+ stagedAt: Date.now() - DAY,
+ ...over,
+})
+
+beforeEach(() => {
+ vi.resetModules()
+ disk.value = null
+})
+
+describe('a restart with a queue on disk', () => {
+ it('brings the pending change back, content and jail root intact', async () => {
+ writeDisk({ 'chat-7': [entry()] })
+
+ const { useStagedChangesStore } = await import('../stagedChangesStore')
+
+ const list = useStagedChangesStore.getState().list('chat-7')
+ expect(list).toHaveLength(1)
+ expect(list[0].newContent).toBe('after the agent wrote it')
+ // Apply runs after the loop cleared the active context, so these two are
+ // what make the write land in the real project folder.
+ expect(list[0].resolvedPath).toBe('/proj/src/main.py')
+ expect(list[0].workingDirectory).toBe('/proj')
+ })
+
+ it('starts clean when the database holds nothing or holds junk', async () => {
+ const fresh = await import('../stagedChangesStore')
+ expect(fresh.useStagedChangesStore.getState().byChat).toEqual({})
+
+ vi.resetModules()
+ disk.value = 'not json at all'
+ const broken = await import('../stagedChangesStore')
+ expect(broken.useStagedChangesStore.getState().byChat).toEqual({})
+ })
+
+ it('leaves a fortnight-old change behind instead of hoarding it forever', async () => {
+ writeDisk({ 'chat-7': [entry({ stagedAt: Date.now() - 15 * DAY })] })
+ const { useStagedChangesStore } = await import('../stagedChangesStore')
+ expect(useStagedChangesStore.getState().list('chat-7')).toEqual([])
+ })
+
+ it('writes what it staged back out, so the next restart finds it', async () => {
+ const { useStagedChangesStore, flushStagedPersist } = await import('../stagedChangesStore')
+ useStagedChangesStore.getState().stage('chat-9', {
+ path: 'app.py',
+ oldContent: 'old',
+ newContent: 'new',
+ diff: '',
+ })
+ await flushStagedPersist()
+
+ expect(disk.value).toBeTruthy()
+ const written = JSON.parse(disk.value as string)
+ expect(written.state.byChat['chat-9'][0].newContent).toBe('new')
+ })
+})
diff --git a/src/stores/__tests__/stagedChangesStore.test.ts b/src/stores/__tests__/stagedChangesStore.test.ts
index e6a9188a..7a085752 100644
--- a/src/stores/__tests__/stagedChangesStore.test.ts
+++ b/src/stores/__tests__/stagedChangesStore.test.ts
@@ -1,5 +1,8 @@
import { describe, it, expect, beforeEach } from 'vitest'
-import { useStagedChangesStore } from '../stagedChangesStore'
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { dirname, resolve } from 'node:path'
+import { useStagedChangesStore, pruneStagedQueues } from '../stagedChangesStore'
describe('stagedChangesStore', () => {
beforeEach(() => {
@@ -147,3 +150,61 @@ describe('stagedChangesStore', () => {
expect(useStagedChangesStore.getState().get('c1', 'unknown')).toBeUndefined()
})
})
+
+// The queue holds approved work that is not on disk yet. It used to live in
+// memory only, so a restart, and therefore every update, emptied it silently
+// (Morgan, 2026-08-11). What comes back from disk is data, not trusted state.
+describe('the queue survives a restart', () => {
+ const NOW = 1_786_500_000_000
+ const DAY = 24 * 60 * 60 * 1000
+ const entry = (over: Record<string, unknown> = {}) => ({
+ id: 'e1',
+ path: 'src/main.py',
+ resolvedPath: '/proj/src/main.py',
+ oldContent: 'before',
+ newContent: 'after',
+ diff: '',
+ stagedAt: NOW - DAY,
+ ...over,
+ })
+
+ it('keeps a pending change that is still recent', () => {
+ const out = pruneStagedQueues({ c1: [entry()] }, NOW)
+ expect(out.c1).toHaveLength(1)
+ expect(out.c1[0].newContent).toBe('after')
+ })
+
+ it('drops what a project has long moved past, and empty chats with it', () => {
+ const out = pruneStagedQueues(
+ { c1: [entry({ stagedAt: NOW - 15 * DAY })], c2: [entry({ id: 'e2' })] },
+ NOW,
+ )
+ expect(out.c1).toBeUndefined()
+ expect(out.c2).toHaveLength(1)
+ })
+
+ it('keeps an entry whose age cannot be read, losing work is the worse failure', () => {
+ const out = pruneStagedQueues({ c1: [entry({ stagedAt: undefined })] }, NOW)
+ expect(out.c1).toHaveLength(1)
+ })
+
+ it('ignores anything that is not a staged change', () => {
+ expect(pruneStagedQueues(undefined, NOW)).toEqual({})
+ expect(pruneStagedQueues({ c1: 'not an array' }, NOW)).toEqual({})
+ expect(pruneStagedQueues({ c1: [null, 42, { id: 'x' }] }, NOW)).toEqual({})
+ // A record with the right shape but no content is not a change either.
+ expect(pruneStagedQueues({ c1: [{ id: 'x', path: 'a' }] }, NOW)).toEqual({})
+ })
+
+ it('writes to IndexedDB through the coalescing wrapper, never to localStorage', () => {
+ const here = dirname(fileURLToPath(import.meta.url))
+ const src = readFileSync(resolve(here, '../stagedChangesStore.ts'), 'utf8')
+ // An entry carries the file twice, so the ~5 MB localStorage cap is not an
+ // option, and a write per set() is what took the renderer's memory out on
+ // 2026-08-03.
+ expect(src).toMatch(/coalescedJSONStorage<StagedChangesState>\(idbStorage\)/)
+ // The word appears in the comment explaining why; the API must not.
+ expect(src).not.toMatch(/localStorage\s*[.[]/)
+ expect(src).toMatch(/export function flushStagedPersist/)
+ })
+})
diff --git a/src/stores/stagedChangesStore.ts b/src/stores/stagedChangesStore.ts
index 787450fc..f438a0c9 100644
--- a/src/stores/stagedChangesStore.ts
+++ b/src/stores/stagedChangesStore.ts
@@ -1,6 +1,9 @@
import { create } from 'zustand'
+import { persist } from 'zustand/middleware'
import { v4 as uuid } from 'uuid'
import { normalizeStagedPath } from '../lib/staged-overlay'
+import { idbStorage } from '../lib/idbStorage'
+import { coalescedJSONStorage } from '../lib/coalescedStorage'
export interface StagedChange {
/** Stable id assigned at stage-time so the UI can key + remove safely. */
@@ -71,7 +74,68 @@ function sameFile(a: Pick<StagedChange, 'path' | 'resolvedPath'>, b: Pick<Staged
)
}
-export const useStagedChangesStore = create<StagedChangesState>()((set, get) => ({
+/**
+ * The queue holds approved work that is not on disk yet, so it must survive a
+ * restart. It did not: the store lived in memory only, and an update (which is
+ * a restart) silently emptied it. Morgan lost a full run that way on
+ * 2026-08-11, on top of the applies that were refused.
+ *
+ * IndexedDB, not localStorage: an entry carries the file twice, before and
+ * after, and a handful of source files blows past the ~5 MB cap. The write is
+ * coalesced for the same reason the chat history is (2026-08-03: a per-set
+ * write serialised multi-megabyte state on every frame and took the renderer's
+ * memory with it).
+ */
+const stagedStorage = coalescedJSONStorage<StagedChangesState>(idbStorage)
+
+/** Force the queue out now instead of waiting for the coalescing window. The
+ * end of a run is the honest durability point, an IndexedDB write cannot
+ * finish during unload. */
+export function flushStagedPersist(): Promise<void> {
+ return stagedStorage.flush()
+}
+
+if (typeof window !== 'undefined' && typeof document !== 'undefined') {
+ window.addEventListener('pagehide', () => { void stagedStorage.flush() })
+ document.addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'hidden') void stagedStorage.flush()
+ })
+}
+
+/** Two weeks. A pending change older than that is measured against a project
+ * that has moved on, and keeping it forever only grows the database. */
+const MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000
+
+/**
+ * What comes back from disk is data, not state we control: an older build, a
+ * half written record, a hand edited database. Keep every entry that still
+ * looks like one and is not ancient, drop the rest. An entry whose age cannot
+ * be read is KEPT, because throwing away work we merely cannot date would be
+ * the very failure this persistence exists to prevent.
+ */
+export function pruneStagedQueues(
+ persisted: unknown,
+ now: number,
+): Record<string, StagedChange[]> {
+ const source = (persisted as Record<string, unknown> | null | undefined) ?? {}
+ if (typeof source !== 'object') return {}
+ const out: Record<string, StagedChange[]> = {}
+ for (const [chatId, raw] of Object.entries(source)) {
+ if (!Array.isArray(raw)) continue
+ const kept = raw.filter((c): c is StagedChange => {
+ if (!c || typeof c !== 'object') return false
+ const entry = c as Partial<StagedChange>
+ if (typeof entry.id !== 'string' || typeof entry.path !== 'string') return false
+ if (typeof entry.newContent !== 'string') return false
+ if (typeof entry.stagedAt !== 'number' || !Number.isFinite(entry.stagedAt)) return true
+ return now - entry.stagedAt < MAX_AGE_MS
+ })
+ if (kept.length > 0) out[chatId] = kept
+ }
+ return out
+}
+
+export const useStagedChangesStore = create<StagedChangesState>()(persist((set, get) => ({
byChat: {},
stage: (chatId, change) => {
@@ -118,4 +182,12 @@ export const useStagedChangesStore = create<StagedChangesState>()((set, get) =>
list: (chatId) => get().byChat[chatId] ?? [],
get: (chatId, id) => (get().byChat[chatId] ?? []).find((c) => c.id === id),
+}), {
+ name: 'staged-changes',
+ storage: stagedStorage,
+ partialize: (state) => ({ byChat: state.byChat }) as StagedChangesState,
+ merge: (persisted, current) => ({
+ ...current,
+ byChat: pruneStagedQueues((persisted as { byChat?: unknown } | null)?.byChat, Date.now()),
+ }),
}))