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(M4): das Backup schreibt nur noch bei echter Änderung, und Löschen räumt wirklich auf
David9b72e430e789
diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsxindex 1892579b..26bc53ad 100644--- a/src/components/layout/AppShell.tsx+++ b/src/components/layout/AppShell.tsx@@ -24,7 +24,7 @@ import { detectLocalBackends, type DetectedBackend } from '../../lib/backend-detimport { whenRunsIdle } from '../../lib/run-idle'import { backendCall, isTauri } from '../../api/backend'import { idbStorage } from '../../lib/idbStorage'-import { STORE_KEYS, IDB_STORE_KEYS, collectStoreSnapshot } from '../../lib/store-backup'+import { STORE_KEYS, IDB_STORE_KEYS, backupStoresIfChanged, flushSyncStoreBackup } from '../../lib/store-backup'import { idbKeysToRestore, mayReloadForIdbRestore } from '../../lib/idb-restore'import { log } from '../../lib/logger'import { pickForMode } from '../../lib/active-model-mode'@@ -393,23 +393,16 @@ export function AppShell() {if (disposed) returnlet backupInflight = false- // In-memory mirror of the IDB-backed values, refreshed by every doBackup- // run. beforeunload can't await IndexedDB (the page is tearing down), so- // the sync flush below reads from this cache instead — at most one- // debounce-cycle stale, same freshness the old sync handler had.- const idbCache: Record<string, string> = {}const doBackup = async () => {// Inflight guard: the 1 s debounce and the 5 s interval can overlap// now that the snapshot awaits IndexedDB reads.if (backupInflight) returnbackupInflight = true- try {- const snapshot = await collectStoreSnapshot(idbCache)- // Always fire — we want backup even if snapshot is mostly empty, and the- // sentinel tells the restore-flow this is a valid backup.- localStorage.setItem('lu-restore-complete', '1')- backendCall('backup_stores', { data: JSON.stringify(snapshot) }).catch(() => {})- } catch { /* best-effort */ }+ // Writes only when a store actually changed. This used to serialise and+ // re-write the whole history every five seconds no matter what, which is+ // the SSD churn and the GC pressure coalescedStorage exists to prevent —+ // and it ran on an idle app, on battery, for as long as it was open.+ try { await backupStoresIfChanged() } catch { /* best-effort */ }backupInflight = false}@@ -469,30 +462,12 @@ export function AppShell() {}const unsubChat = useChatStore.subscribe(scheduleBackup)- // Synchronous "last write" flush for beforeunload: doBackup awaits- // IndexedDB reads, and an await during page teardown means the trailing- // backup_stores invoke may never fire. Build the snapshot synchronously- // from localStorage + the idbCache mirror instead — no await before the- // invoke, restoring the pre-async guarantee.- const flushSyncBackup = () => {- try {- const snapshot: Record<string, string> = { __ts: new Date().toISOString() }- for (const key of STORE_KEYS) {- const val = IDB_STORE_KEYS.has(key)- ? (idbCache[key] ?? null)- : localStorage.getItem(key)- if (val) snapshot[key] = val- }- localStorage.setItem('lu-restore-complete', '1')- backendCall('backup_stores', { data: JSON.stringify(snapshot) }).catch(() => {})- } catch { /* best-effort */ }- }-const onBeforeUnload = () => {// The 5 s / 30 s intervals cover the common case; this is the "last// write" insurance for changes since the previous interval. Must stay- // synchronous — see flushSyncBackup.- flushSyncBackup()+ // synchronous: an await during page teardown means the trailing+ // backup_stores invoke may never fire.+ flushSyncStoreBackup()void doRagBackup()}window.addEventListener('beforeunload', onBeforeUnload)diff --git a/src/components/layout/__tests__/AppShell-backup-triad.test.ts b/src/components/layout/__tests__/AppShell-backup-triad.test.tsindex 2dc47ad8..e817ae7c 100644--- a/src/components/layout/__tests__/AppShell-backup-triad.test.ts+++ b/src/components/layout/__tests__/AppShell-backup-triad.test.ts@@ -44,9 +44,11 @@ describe('AppShell backup triad (Bug #7)', () => {it('beforeunload flush is synchronous — never awaits IndexedDB during teardown', () => {// doBackup awaits idbStorage reads; an await inside beforeunload means the// trailing backup_stores invoke may never fire. The handler must call the- // sync snapshot (localStorage + idbCache mirror) instead of doBackup.- expect(src).toContain('flushSyncBackup()')- expect(src).toMatch(/const onBeforeUnload = \(\) => \{[^}]*flushSyncBackup\(\)/s)+ // sync snapshot (localStorage + the idb write mirror) instead of doBackup.+ // The snapshot builder moved into lib/store-backup in 2.6.8 so the update+ // path could reach it; the guarantee is unchanged, only its name is.+ expect(src).toContain('flushSyncStoreBackup()')+ expect(src).toMatch(/const onBeforeUnload = \(\) => \{[^}]*flushSyncStoreBackup\(\)/s)expect(src).not.toMatch(/const onBeforeUnload = \(\) => \{[^}]*void doBackup\(\)/s)})@@ -66,13 +68,20 @@ describe('AppShell backup triad (Bug #7)', () => {expect(src).toContain('clearTimeout(debounceTimer)')})- it('includes a __ts timestamp marker so backup fires even if localStorage is empty', () => {- // We intentionally write unconditionally — a fresh install with empty- // localStorage should still write an (empty) backup file so the mtime- // reflects last-run-time, making triage easier. The `__ts` marker is- // what makes snapshot non-empty even when no store has persisted yet.- expect(src).toContain('__ts')- expect(src).toContain('new Date().toISOString()')+ it('includes a __ts timestamp marker so a fresh install still writes a backup', () => {+ // The `__ts` marker is what makes the snapshot non-empty when no store has+ // persisted yet, so a fresh install still writes a file whose mtime says+ // when the app last ran.+ //+ // The original claim here was "we intentionally write UNCONDITIONALLY".+ // That claim is retired: writing every 5 s regardless of whether anything+ // changed was multi-megabyte SSD churn and GC pressure on an idle app. The+ // triad now writes only on a change (backupStoresIfChanged), and the first+ // write of a session always happens because nothing is on disk to compare+ // against — see store-backup-dirty.test.ts.+ const backup = readFileSync(join(__dirname, '../../../lib/store-backup.ts'), 'utf8')+ expect(backup).toContain('__ts')+ expect(backup).toContain('new Date().toISOString()')})it('onboarding-marker migration does NOT re-write the marker when user clicked Settings -> Re-run onboarding', () => {diff --git a/src/lib/__tests__/idbStorage-read-failure.test.ts b/src/lib/__tests__/idbStorage-read-failure.test.tsnew file mode 100644index 00000000..0739315c--- /dev/null+++ b/src/lib/__tests__/idbStorage-read-failure.test.ts@@ -0,0 +1,189 @@+/**+ * A failed IndexedDB READ must never turn into an empty write.+ *+ * M4/4, filed as unproven. It is reachable: `idbGet` used to resolve `null`+ * from its own `onerror`, so an unreadable transaction was indistinguishable+ * from an empty key. zustand hydrated the DEFAULT state from that null and+ * persisted on the very next set() — one bad read replaced the whole chat+ * history, and the appData snapshot (built from the same reads) was replaced+ * seconds later with a copy that no longer had the chats in it either.+ *+ * Run: npx vitest run src/lib/__tests__/idbStorage-read-failure.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'++/**+ * Fake IndexedDB whose reads fail while `failReads` is on. Writes always work,+ * so a write that lands is proof the guard let it through.+ */+function fakeIndexedDB(data: Record<string, string>) {+ const state = { failReads: true }+ const db = {+ objectStoreNames: { contains: () => true },+ createObjectStore: () => {},+ transaction: () => ({+ objectStore: () => ({+ get: (k: string) => {+ const r: Record<string, unknown> = {+ onsuccess: null, onerror: null,+ result: data[k], error: new DOMException('store is not readable', 'NotReadableError'),+ }+ queueMicrotask(() => {+ if (state.failReads) (r.onerror as (() => void) | null)?.()+ else (r.onsuccess as (() => void) | null)?.()+ })+ return r+ },+ put: (v: string, k: string) => { data[k] = v; return {} },+ delete: (k: string) => { delete data[k]; return {} },+ }),+ set oncomplete(fn: () => void) { queueMicrotask(fn) },+ set onerror(_fn: () => void) {},+ set onabort(_fn: () => void) {},+ }),+ }+ return {+ state,+ open: () => {+ const req: Record<string, unknown> = {+ onsuccess: null, onerror: null, onblocked: null, onupgradeneeded: null,+ result: db, error: null,+ }+ queueMicrotask(() => (req.onsuccess as (() => void) | null)?.())+ return req+ },+ }+}++function fakeLocalStorage() {+ const mem = new Map<string, string>()+ return {+ getItem: (k: string) => (mem.has(k) ? mem.get(k)! : null),+ setItem: (k: string, v: string) => void mem.set(k, String(v)),+ removeItem: (k: string) => void mem.delete(k),+ clear: () => mem.clear(),+ get length() { return mem.size },+ key: (i: number) => Array.from(mem.keys())[i] ?? null,+ }+}++const HISTORY = '{"state":{"conversations":[{"id":"a","messages":[1,2,3]}]}}'+const EMPTY = '{"state":{"conversations":[]}}'++describe('idbStorage tells a failed read apart from an empty one', () => {+ beforeEach(() => {+ vi.resetModules()+ vi.stubGlobal('localStorage', fakeLocalStorage())+ })+ afterEach(() => { vi.unstubAllGlobals() })++ it('does not let the state hydrated from a failed read overwrite the stored history', async () => {+ const data: Record<string, string> = { 'chat-conversations': HISTORY }+ const idb = fakeIndexedDB(data)+ vi.stubGlobal('indexedDB', idb)+ const { idbStorage, hasFailedRead } = await import('../idbStorage')++ // Hydration: the read fails, so the store comes up empty.+ expect(await idbStorage.getItem('chat-conversations')).toBeNull()+ expect(hasFailedRead('chat-conversations')).toBe(true)++ // zustand persists that empty state on the next set(). The row must survive.+ idb.state.failReads = false // the transient failure is over+ await idbStorage.setItem('chat-conversations', EMPTY)+ expect(data['chat-conversations']).toBe(HISTORY)+ expect(hasFailedRead('chat-conversations')).toBe(true)+ })++ it('refuses again while the key stays unreadable', async () => {+ const data: Record<string, string> = { 'chat-conversations': HISTORY }+ const idb = fakeIndexedDB(data)+ vi.stubGlobal('indexedDB', idb)+ const { idbStorage } = await import('../idbStorage')++ await idbStorage.getItem('chat-conversations')+ await idbStorage.setItem('chat-conversations', EMPTY)+ expect(data['chat-conversations']).toBe(HISTORY)+ })++ it('releases the hold when a later read proves the key really is empty', async () => {+ // A first run behind a transient failure: nothing is stored, so there is+ // nothing to protect and refusing forever would mean never persisting.+ const data: Record<string, string> = {}+ const idb = fakeIndexedDB(data)+ vi.stubGlobal('indexedDB', idb)+ const { idbStorage, hasFailedRead } = await import('../idbStorage')++ expect(await idbStorage.getItem('chat-conversations')).toBeNull()+ expect(hasFailedRead('chat-conversations')).toBe(true)++ idb.state.failReads = false+ await idbStorage.setItem('chat-conversations', EMPTY)+ expect(data['chat-conversations']).toBe(EMPTY)+ expect(hasFailedRead('chat-conversations')).toBe(false)+ })++ it('a successful read clears the hold and normal writes resume', async () => {+ const data: Record<string, string> = { 'chat-conversations': HISTORY }+ const idb = fakeIndexedDB(data)+ vi.stubGlobal('indexedDB', idb)+ const { idbStorage, hasFailedRead } = await import('../idbStorage')++ await idbStorage.getItem('chat-conversations')+ idb.state.failReads = false+ expect(await idbStorage.getItem('chat-conversations')).toBe(HISTORY)+ expect(hasFailedRead('chat-conversations')).toBe(false)++ await idbStorage.setItem('chat-conversations', EMPTY)+ expect(data['chat-conversations']).toBe(EMPTY)+ })++ it('holds back only the key that failed', async () => {+ const data: Record<string, string> = { 'chat-conversations': HISTORY, 'locally-uncensored-memory': 'mem' }+ const idb = fakeIndexedDB(data)+ vi.stubGlobal('indexedDB', idb)+ const { idbStorage, hasFailedRead } = await import('../idbStorage')++ await idbStorage.getItem('chat-conversations')+ expect(hasFailedRead('locally-uncensored-memory')).toBe(false)++ idb.state.failReads = false+ await idbStorage.setItem('locally-uncensored-memory', 'new-mem')+ expect(data['locally-uncensored-memory']).toBe('new-mem')+ })+})++describe('the appData snapshot is not replaced while a store is unreadable', () => {+ const backendCall = vi.fn()++ beforeEach(() => {+ vi.resetModules()+ backendCall.mockReset()+ backendCall.mockResolvedValue(undefined)+ vi.stubGlobal('localStorage', fakeLocalStorage())+ })+ afterEach(() => { vi.unstubAllGlobals(); vi.doUnmock('../idbStorage') })++ it('skips the write instead of saving a snapshot with the chats missing', async () => {+ // backup_stores REPLACES the file. A snapshot built while the chat key is+ // unreadable simply has no chats in it, and writing it destroys the last+ // copy that did.+ const failed = new Set<string>(['chat-conversations'])+ vi.doMock('../idbStorage', () => ({+ idbStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} },+ hasFailedRead: (k: string) => failed.has(k),+ onIdbWrite: () => () => {},+ }))+ vi.doMock('../../api/backend', () => ({ backendCall: (...a: unknown[]) => backendCall(...a) }))++ const { backupStoresIfChanged, backupStoresNow, flushSyncStoreBackup } = await import('../store-backup')++ expect(await backupStoresIfChanged()).toBe('held-back')+ expect(flushSyncStoreBackup()).toBe('held-back')+ expect(await backupStoresNow()).toBe(false)+ expect(backendCall).not.toHaveBeenCalled()++ failed.clear()+ expect(await backupStoresIfChanged()).toBe('written')+ expect(backendCall).toHaveBeenCalledWith('backup_stores', expect.anything())+ })+})diff --git a/src/lib/__tests__/storage-quota-wiring.test.ts b/src/lib/__tests__/storage-quota-wiring.test.tsnew file mode 100644index 00000000..0545674f--- /dev/null+++ b/src/lib/__tests__/storage-quota-wiring.test.ts@@ -0,0 +1,131 @@+/**+ * createSafeStorage has to be wired to the stores that can hit the quota.+ *+ * M4/5: it was wired to NOTHING. Every localStorage store used zustand's+ * default backend, whose setItem runs synchronously inside `api.setState` — so+ * a QuotaExceededError did not fail a save, it threw out of the store action+ * and out of the React handler that called it. Both prune tiers and+ * StorageQuotaToast were unreachable code guarding a door nobody used.+ *+ * Run: npx vitest run src/lib/__tests__/storage-quota-wiring.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { readFileSync } from 'fs'+import { fileURLToPath } from 'url'+import { dirname, join } from 'path'++const STORES_DIR = join(dirname(fileURLToPath(import.meta.url)), '../../stores')+const loaders = import.meta.glob('../../stores/*.ts')++type Persisted = {+ persist: { getOptions: () => { name?: string; storage?: { setItem: (n: string, v: unknown) => unknown } } }+}++function isPersisted(value: unknown): value is Persisted {+ const p = (value as { persist?: { getOptions?: unknown } } | null)?.persist+ return !!p && typeof p.getOptions === 'function'+}++/**+ * Stores whose writes cannot reach React synchronously and so cannot be the+ * crash this test is about:+ * - anything on idbStorage (chat history, memories, staged changes)+ * - anything behind coalescedJSONStorage, which defers the write to a timer+ * and catches its own failures (downloadStore)+ */+function isSyncLocalStorageStore(file: string): boolean {+ const src = readFileSync(join(STORES_DIR, file), 'utf8')+ return !/idbStorage/.test(src) && !/coalescedJSONStorage/.test(src)+}++/**+ * The one store still on the raw backend. It is outside this change's file+ * package (another workstream owns codexStore.ts this cycle), and it is named+ * here so that wiring it makes this list wrong and this test say so.+ */+const KNOWN_UNWIRED = ['locally-uncensored-codex']++function throwingLocalStorage() {+ return {+ getItem: () => null,+ setItem: () => { throw new DOMException('quota', 'QuotaExceededError') },+ removeItem: () => {},+ clear: () => {},+ get length() { return 0 },+ key: () => null,+ }+}++describe('quota-safe storage is actually wired up', () => {+ const quotaEvents: string[] = []++ beforeEach(() => {+ quotaEvents.length = 0+ vi.stubGlobal('window', {+ dispatchEvent: (e: { type: string }) => { quotaEvents.push(e.type); return true },+ })+ })+ afterEach(() => { vi.unstubAllGlobals() })++ it('no localStorage-backed store lets QuotaExceededError escape into the caller', async () => {+ const escaped: string[] = []+ const stillUnwired: string[] = []++ for (const [path, load] of Object.entries(loaders)) {+ const file = path.split('/').pop()!+ if (!isSyncLocalStorageStore(file)) continue+ const mod = (await load()) as Record<string, unknown>+ for (const value of Object.values(mod)) {+ if (!isPersisted(value)) continue+ const { name, storage } = value.persist.getOptions()+ if (!name || !storage) continue++ vi.stubGlobal('localStorage', throwingLocalStorage())+ let threw = false+ try {+ storage.setItem(name, { state: {}, version: 0 })+ } catch {+ threw = true+ }+ if (threw) (KNOWN_UNWIRED.includes(name) ? stillUnwired : escaped).push(`${file}: ${name}`)+ }+ }++ expect(escaped).toEqual([])+ // If this fails, someone wired the last store — delete it from KNOWN_UNWIRED.+ expect(stillUnwired.map((s) => s.split(': ')[1])).toEqual(KNOWN_UNWIRED)+ })++ it('a dropped write reaches the toast instead of vanishing', async () => {+ vi.resetModules()+ vi.stubGlobal('localStorage', throwingLocalStorage())+ const { createSafeStorage } = await import('../storage-quota')++ createSafeStorage().setItem('chat-settings', '{"state":{}}')++ // StorageQuotaToast listens for exactly this event; before the wiring it+ // could never fire because nothing dispatched from a real store write.+ expect(quotaEvents).toContain('lu:storage-quota-exceeded')+ })++ it('a real store write also reaches the toast', async () => {+ vi.resetModules()+ vi.stubGlobal('localStorage', throwingLocalStorage())+ const { useUIStore } = await import('../../stores/uiStore')++ expect(() => useUIStore.getState().setExplorerCollapsed(true)).not.toThrow()+ expect(quotaEvents).toContain('lu:storage-quota-exceeded')+ })++ it('an error that is NOT a quota error still propagates', async () => {+ vi.resetModules()+ vi.stubGlobal('localStorage', {+ getItem: () => null,+ setItem: () => { throw new TypeError('something else entirely') },+ removeItem: () => {},+ })+ const { createSafeStorage } = await import('../storage-quota')++ expect(() => createSafeStorage().setItem('k', 'v')).toThrow(TypeError)+ })+})diff --git a/src/lib/__tests__/store-backup-covers-every-store.test.ts b/src/lib/__tests__/store-backup-covers-every-store.test.tsnew file mode 100644index 00000000..9cff55e4--- /dev/null+++ b/src/lib/__tests__/store-backup-covers-every-store.test.ts@@ -0,0 +1,106 @@+/**+ * Every persisted store must be in the appData backup key list.+ *+ * M4/2: `staged-changes` — approved code edits that are not on disk yet — was+ * persisted to IndexedDB and listed in NEITHER key list, so the NSIS/WebView2+ * wipe that store_backup.json exists to survive destroyed it anyway. So did+ * `locally-uncensored-todos`, `locally-uncensored-ui`, `lu_release_notes` and+ * `locally-uncensored-downloads`. A prose list nobody checks drifts the moment+ * somebody adds a store, which is exactly what happened.+ *+ * This asks zustand what each store actually persists rather than reading the+ * source, so a renamed key or a new store fails here instead of silently not+ * surviving an update.+ *+ * Run: npx vitest run src/lib/__tests__/store-backup-covers-every-store.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'fs'+import { fileURLToPath } from 'url'+import { dirname, join } from 'path'+import { STORE_KEYS, IDB_STORE_KEYS } from '../store-backup'++const HERE = dirname(fileURLToPath(import.meta.url))+const STORES_DIR = join(HERE, '../../stores')++const loaders = import.meta.glob('../../stores/*.ts')++type PersistedStore = { persist: { getOptions: () => { name?: string } } }++function isPersisted(value: unknown): value is PersistedStore {+ const p = (value as { persist?: { getOptions?: unknown } } | null)?.persist+ return !!p && typeof p.getOptions === 'function'+}++/** file basename -> the persist keys that file declares. */+async function persistKeysByFile(): Promise<Map<string, string[]>> {+ const out = new Map<string, string[]>()+ for (const [path, load] of Object.entries(loaders)) {+ const mod = (await load()) as Record<string, unknown>+ const names: string[] = []+ for (const value of Object.values(mod)) {+ if (!isPersisted(value)) continue+ const name = value.persist.getOptions().name+ if (name) names.push(name)+ }+ if (names.length > 0) out.set(path.split('/').pop()!, names)+ }+ return out+}++describe('the appData backup covers every persisted store', () => {+ it('lists every persist key that exists in src/stores', async () => {+ const byFile = await persistKeysByFile()+ const missing: string[] = []+ for (const [file, names] of byFile) {+ for (const name of names) {+ if (!STORE_KEYS.includes(name)) missing.push(`${file}: ${name}`)+ }+ }+ expect(missing).toEqual([])+ // Sanity: the walk has to actually find stores, or the assertion above is+ // vacuously true and this file guards nothing.+ expect(byFile.size).toBeGreaterThan(20)+ })++ it('names the four keys the 2.6.8 audit found missing', async () => {+ // Spelled out so a future "tidy-up" of the list cannot quietly drop them+ // again — each one is a real loss report, not a hypothetical.+ for (const key of [+ 'staged-changes', // approved edits not yet on disk (Morgan)+ 'locally-uncensored-todos', // the plan a long run is working through+ 'locally-uncensored-ui',+ 'lu_release_notes',+ 'locally-uncensored-downloads', // which model bundles are installed+ ]) {+ expect(STORE_KEYS).toContain(key)+ }+ })++ it('routes every IndexedDB-backed store through IDB_STORE_KEYS', async () => {+ // A key backed by IndexedDB but absent from IDB_STORE_KEYS is read from+ // localStorage by the snapshot builder, where the 2.5.0 migration deleted+ // it — so it backs up as "empty" and restores as nothing.+ const byFile = await persistKeysByFile()+ const wrong: string[] = []+ for (const [file, names] of byFile) {+ const src = readFileSync(join(STORES_DIR, file), 'utf8')+ const backedByIdb = /from '\.\.\/lib\/idbStorage'/.test(src)+ for (const name of names) {+ if (backedByIdb && !IDB_STORE_KEYS.has(name)) wrong.push(`${file}: ${name} is on IndexedDB but not in IDB_STORE_KEYS`)+ if (!backedByIdb && IDB_STORE_KEYS.has(name)) wrong.push(`${file}: ${name} is in IDB_STORE_KEYS but not on IndexedDB`)+ }+ }+ expect(wrong).toEqual([])+ })++ it('keeps IDB_STORE_KEYS a subset of STORE_KEYS', () => {+ // An IDB key that is not in STORE_KEYS is never visited by the snapshot+ // loop at all, so the IDB branch would never run for it.+ for (const key of IDB_STORE_KEYS) expect(STORE_KEYS).toContain(key)+ })++ it('has no duplicate keys', () => {+ expect(new Set(STORE_KEYS).size).toBe(STORE_KEYS.length)+ })+})diff --git a/src/lib/__tests__/store-backup-dirty.test.ts b/src/lib/__tests__/store-backup-dirty.test.tsnew file mode 100644index 00000000..cdf8c940--- /dev/null+++ b/src/lib/__tests__/store-backup-dirty.test.ts@@ -0,0 +1,144 @@+/**+ * The appData snapshot must only be written when a store actually changed.+ *+ * M4: the triad serialised the WHOLE chat history and re-wrote+ * %APPDATA%/store_backup.json every five seconds, unconditionally, with no+ * dirty check — the multi-megabyte churn coalescedStorage was written to stop,+ * reintroduced one layer up and running forever on an idle app.+ *+ * Run: npx vitest run src/lib/__tests__/store-backup-dirty.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'++const backendCall = vi.fn()+vi.mock('../../api/backend', () => ({+ backendCall: (...args: unknown[]) => backendCall(...args),+}))++function fakeLocalStorage() {+ const mem = new Map<string, string>()+ return {+ getItem: (k: string) => (mem.has(k) ? mem.get(k)! : null),+ setItem: (k: string, v: string) => void mem.set(k, String(v)),+ removeItem: (k: string) => void mem.delete(k),+ clear: () => mem.clear(),+ get length() { return mem.size },+ key: (i: number) => Array.from(mem.keys())[i] ?? null,+ }+}++/** Payloads handed to the backup_stores command, parsed. */+function writtenSnapshots() {+ return backendCall.mock.calls+ .filter((c) => c[0] === 'backup_stores')+ .map((c) => JSON.parse((c[1] as { data: string }).data) as Record<string, string>)+}++describe('store backup only writes on a change', () => {+ beforeEach(() => {+ vi.resetModules()+ backendCall.mockReset()+ backendCall.mockResolvedValue(undefined)+ vi.stubGlobal('localStorage', fakeLocalStorage())+ })++ afterEach(() => {+ vi.unstubAllGlobals()+ })++ it('writes the first snapshot of a session and then goes quiet', async () => {+ const { backupStoresIfChanged } = await import('../store-backup')++ expect(await backupStoresIfChanged()).toBe('written')+ expect(writtenSnapshots()).toHaveLength(1)++ // The five-second tick used to fire here, and here, and here...+ expect(await backupStoresIfChanged()).toBe('unchanged')+ expect(await backupStoresIfChanged()).toBe('unchanged')+ expect(await backupStoresIfChanged()).toBe('unchanged')+ expect(writtenSnapshots()).toHaveLength(1)+ })++ it('a changed localStorage-backed store makes exactly one write', async () => {+ const { backupStoresIfChanged } = await import('../store-backup')+ await backupStoresIfChanged()++ localStorage.setItem('chat-settings', '{"state":{"settings":{"theme":"light"}}}')+ expect(await backupStoresIfChanged()).toBe('written')+ expect(await backupStoresIfChanged()).toBe('unchanged')+ expect(writtenSnapshots()).toHaveLength(2)+ expect(writtenSnapshots()[1]['chat-settings']).toContain('light')+ })++ it('a changed IndexedDB-backed store is noticed without re-reading it', async () => {+ const { backupStoresIfChanged } = await import('../store-backup')+ const { idbStorage } = await import('../idbStorage')+ await backupStoresIfChanged()++ await Promise.resolve(idbStorage.setItem('chat-conversations', '{"state":{"conversations":[1]}}'))+ expect(await backupStoresIfChanged()).toBe('written')+ expect(writtenSnapshots()[1]['chat-conversations']).toContain('conversations')+ expect(await backupStoresIfChanged()).toBe('unchanged')+ expect(writtenSnapshots()).toHaveLength(2)+ })++ it('the timestamp alone never counts as a change', async () => {+ const { backupStoresIfChanged } = await import('../store-backup')+ await backupStoresIfChanged()+ const first = writtenSnapshots()[0]+ expect(first.__ts).toBeTruthy() // a fresh install still writes a dated file++ await new Promise((r) => setTimeout(r, 5))+ expect(await backupStoresIfChanged()).toBe('unchanged')+ })++ it('a failed write is retried instead of being remembered as done', async () => {+ const { backupStoresIfChanged } = await import('../store-backup')+ backendCall.mockRejectedValue(new Error('invoke failed'))++ expect(await backupStoresIfChanged()).toBe('written')+ await Promise.resolve() // let the rejection land+ await Promise.resolve()++ backendCall.mockResolvedValue(undefined)+ // Nothing changed in the stores, but nothing reached disk either.+ expect(await backupStoresIfChanged()).toBe('written')+ })++ it('the beforeunload flush never writes a snapshot with the chats missing', async () => {+ // The sync path cannot await IndexedDB, so it reads the write mirror. Until+ // the first async backup has filled it, "no chats" and "nobody has looked"+ // are the same thing — and writing REPLACES the file that has them.+ const { backupStoresIfChanged, flushSyncStoreBackup } = await import('../store-backup')+ const { idbStorage } = await import('../idbStorage')+ await Promise.resolve(idbStorage.setItem('chat-conversations', '{"state":{"conversations":[1]}}'))+ await backupStoresIfChanged()++ // Simulate the mirror being empty at teardown by starting a fresh module+ // with the same stored data: nothing has been written this session.+ vi.resetModules()+ backendCall.mockClear()+ const fresh = await import('../store-backup')+ expect(fresh.flushSyncStoreBackup()).toBe('held-back')+ expect(backendCall).not.toHaveBeenCalled()++ // Once the async path has read the chats once, the sync flush is safe.+ await fresh.backupStoresIfChanged()+ localStorage.setItem('workflow-store', '{"state":{}}')+ expect(fresh.flushSyncStoreBackup()).toBe('written')+ expect(writtenSnapshots().at(-1)!['chat-conversations']).toContain('conversations')+ })++ it('the beforeunload flush is synchronous and also skips an unchanged store', async () => {+ const { backupStoresIfChanged, flushSyncStoreBackup } = await import('../store-backup')+ await backupStoresIfChanged()++ expect(flushSyncStoreBackup()).toBe('unchanged')++ localStorage.setItem('workflow-store', '{"state":{}}')+ // No await anywhere: the page is tearing down and an await would mean the+ // trailing invoke never fires.+ expect(flushSyncStoreBackup()).toBe('written')+ expect(writtenSnapshots()).toHaveLength(2)+ })+})diff --git a/src/lib/idbStorage.ts b/src/lib/idbStorage.tsindex 9cb76c46..8926a4cb 100644--- a/src/lib/idbStorage.ts+++ b/src/lib/idbStorage.ts@@ -77,12 +77,19 @@ function getDB(): Promise<IDBDatabase> {return opening}+// A read that FAILED and a key that holds nothing are the same value — `null` —+// to everything above this module, and the two demand opposite reactions: an+// empty store hydrates clean and may be written over, a failed read must never+// be written over. So the failure has to leave the resolve path entirely.+// `db.transaction()` can also throw synchronously (InvalidStateError once the+// connection has been closed under us by a corrupt profile), which the executor+// turns into a rejection for free.function idbGet(key: string): Promise<string | null> {- return getDB().then((db) => new Promise<string | null>((resolve) => {+ return getDB().then((db) => new Promise<string | null>((resolve, reject) => {const tx = db.transaction(STORE, 'readonly')const r = tx.objectStore(STORE).get(key)r.onsuccess = () => resolve(typeof r.result === 'string' ? r.result : null)- r.onerror = () => resolve(null)+ r.onerror = () => reject(r.error ?? new Error(`indexedDB read failed for ${key}`))}))}function idbSet(key: string, value: string): Promise<void> {@@ -103,6 +110,55 @@ function idbDel(key: string): Promise<void> {}))}+/**+ * Keys whose last IndexedDB read failed for a reason that is NOT "there is+ * nothing under that key".+ *+ * The whole point of the latch: zustand hydrates from whatever getItem hands+ * back, and a failed read hands back the same `null` an empty database does.+ * The store then holds the DEFAULT state, and zustand persists on the very next+ * set() — one unreadable transaction and an untouched 230k-token history is+ * replaced by `{conversations: []}`. The appData snapshot is rebuilt from the+ * same reads seconds later, so the backup goes the same way.+ */+const readFailed = new Set<string>()++/** True while the last read of `name` failed — i.e. while "empty" cannot be+ * trusted. Callers that REPLACE a whole persisted blob (the appData snapshot)+ * must ask before writing. */+export function hasFailedRead(name: string): boolean {+ return readFailed.has(name)+}++/** Test seam: the latch is module state, and a test that provokes a read+ * failure must be able to hand the next test a clean module. */+export function resetIdbFailureLatch(): void {+ readFailed.clear()+}++type IdbWriteListener = (key: string, value: string | null) => void+const writeListeners = new Set<IdbWriteListener>()++/**+ * Called with the value a persisted store just handed this backend (null on+ * removal). Exists so the appData backup can know WHICH stores changed without+ * re-reading multi-megabyte blobs out of IndexedDB on a timer — the listener+ * already has the exact string a read would have returned.+ *+ * Fires only for writes that are actually attempted: a write refused by the+ * read-failure latch must not be mistaken for the new truth.+ */+export function onIdbWrite(fn: IdbWriteListener): () => void {+ writeListeners.add(fn)+ return () => { writeListeners.delete(fn) }+}++function emitWrite(key: string, value: string | null): void {+ for (const fn of writeListeners) {+ try { fn(key, value) } catch { /* a listener must never break the write */ }+ }+}+let _persistAsked = falsefunction askPersist(): void {if (_persistAsked) return@@ -118,25 +174,38 @@ export const idbStorage: StateStorage = {if (!hasIDB) return lsGet(name) // sync path: node tests / degraded webviewaskPersist()return (async () => {+ let v: string | nulltry {- const v = await idbGet(name)- if (v != null) return v- // One-time migration from the legacy localStorage backend.- const legacy = lsGet(name)- if (legacy != null && legacy !== LEGACY_CORRUPT) {- // Migrate into idb, then drop the localStorage copy so the ~5 MB cap is- // freed immediately (only on confirmed idb write — keep it if idb fails).- try { await idbSet(name, legacy); lsDel(name) } catch { /* keep localStorage */ }- return legacy- }- return null- } catch {+ v = await idbGet(name)+ } catch (err) {+ // Latch BEFORE returning anything: from here on `null` is "we could not+ // look", not "there is nothing", and setItem has to know the difference.+ readFailed.add(name)+ log.error('[idbStorage] IndexedDB read failed — hydrating from fallback, writes are held back', {+ key: name,+ err: String(err),+ })return lsGet(name) // idb failed at runtime → localStorage}+ // A read that came back is authoritative in both directions, so a key that+ // recovered stops holding its writes back.+ readFailed.delete(name)+ if (v != null) return v+ // One-time migration from the legacy localStorage backend.+ const legacy = lsGet(name)+ if (legacy != null && legacy !== LEGACY_CORRUPT) {+ // Migrate into idb, then drop the localStorage copy so the ~5 MB cap is+ // freed immediately (only on confirmed idb write — keep it if idb fails).+ try { await idbSet(name, legacy); lsDel(name) } catch { /* keep localStorage */ }+ return legacy+ }+ return null})()},setItem(name: string, value: string): void | Promise<void> {- if (!hasIDB) { lsSet(name, value); return }+ if (!hasIDB) { lsSet(name, value); emitWrite(name, value); return }+ if (readFailed.has(name)) return holdBackWrite(name, value)+ emitWrite(name, value)return (async () => {try {await idbSet(name, value)@@ -161,7 +230,56 @@ export const idbStorage: StateStorage = {})()},removeItem(name: string): void | Promise<void> {+ emitWrite(name, null)if (!hasIDB) { lsDel(name); return }return (async () => { try { await idbDel(name) } catch { /* ignore */ } ; lsDel(name) })()},}++/**+ * A write onto a key whose last read failed. The state being offered was+ * hydrated from that failed read, so it is the DEFAULT state, not the user's —+ * writing it is the data loss this whole latch exists to prevent.+ *+ * One read decides. It is the only thing that can tell the two survivable cases+ * apart, and it is cheap next to what it protects:+ * - reads back a value → the row is intact and this state is not derived+ * from it. Refuse, keep the latch, say so loudly.+ * - reads back nothing → the key really is empty (a first run behind a+ * transient failure). Release the latch and write.+ * - fails again → still blind. Refuse, keep the latch.+ */+function holdBackWrite(name: string, value: string): Promise<void> {+ return (async () => {+ let existing: string | null+ try {+ existing = await idbGet(name)+ } catch (err) {+ log.error('[idbStorage] write held back: the key is still unreadable, refusing to overwrite it', {+ key: name,+ err: String(err),+ })+ return+ }+ if (existing != null) {+ log.error('[idbStorage] write held back: this key HAS data that a failed read hid from hydration', {+ key: name,+ storedBytes: existing.length,+ offeredBytes: value.length,+ })+ return+ }+ readFailed.delete(name)+ emitWrite(name, value)+ try {+ await idbSet(name, value)+ lsDel(name)+ } catch (err) {+ log.warn('[idbStorage] IndexedDB write failed, falling back to localStorage', {+ key: name,+ err: String(err),+ })+ lsSet(name, value)+ }+ })()+}diff --git a/src/lib/persist-version.ts b/src/lib/persist-version.tsnew file mode 100644index 00000000..052af42f--- /dev/null+++ b/src/lib/persist-version.ts@@ -0,0 +1,45 @@+/**+ * What zustand's persist `version` / `migrate` pair actually does, and why most+ * of this app's stores deliberately declare neither.+ *+ * The 2.6.8 audit asked for `version: 1` plus a no-op `migrate` on the 17 stores+ * that have none, on the argument that a store which never declared a version+ * writes no version into its blob — so the day someone adds one, zustand finds+ * `undefined`, skips migrate, and hands the old shape through as if it were+ * already current. Measured against zustand 5.0.12 that is not what happens:+ *+ * let options = { storage: ..., partialize: ..., version: 0, ... }+ * const setItem = () => storage.setItem(options.name, { state, version: options.version })+ * — zustand/esm/middleware.mjs, persistImpl+ *+ * `version: 0` is persistImpl's OWN default, and it is written into every blob.+ * So an "unversioned" store is really a version-0 store, and a future+ * `version: 1` + migrate reaches every existing user with `version === 0`.+ * persist-version.test.ts runs all three facts against the real library.+ *+ * Stamping a number anyway is not free. An older build that declares no version+ * uses the same default 0, sees a blob at 1, has no migrate to call, logs+ * "couldn't be migrated" and hydrates with `migratedState === undefined` — it+ * throws the user's whole persisted state away. That is the R1+ * DOWNGRADE-KONTRAKT codexStore spells out: 2.6.x builds share one WebView+ * profile, so a downgrade is a real path, and a version bump that buys nothing+ * must not cost a reset on it.+ *+ * What IS worth enforcing is the pair. A `version` WITHOUT a `migrate` is the+ * one combination that loses data on any mismatch, in both directions.+ * persist-version.test.ts asserts that no store declares one without the other.+ */++/**+ * The identity migration, for a store that declares a version but has nothing+ * to migrate yet — its job is to exist, so the mismatch branch has something to+ * call instead of discarding the state.+ *+ * Generic so each store's own persisted shape is what comes back out: zustand+ * types `migrate` as `(persistedState: unknown, version: number) => S`, and the+ * cast is the whole point — nothing about the value changes, only what the+ * caller is allowed to assume about it.+ */+export function keepPersistedState<S>(persisted: unknown): S {+ return persisted as S+}diff --git a/src/lib/storage-quota.ts b/src/lib/storage-quota.tsindex 65cb7af9..ac667e0b 100644--- a/src/lib/storage-quota.ts+++ b/src/lib/storage-quota.ts@@ -3,7 +3,8 @@* corrupting Zustand persisted stores.*/-import type { StateStorage } from 'zustand/middleware'+import type { PersistStorage, StateStorage } from 'zustand/middleware'+import { createJSONStorage } from 'zustand/middleware'import { log } from './logger'const MAX_CONVERSATIONS = 100@@ -34,7 +35,17 @@ export function getStorageUsage(): { usedBytes: number; percentFull: number } {return { usedBytes, percentFull: usedBytes / estimatedLimit }}-/** Prune oldest conversations from chat store to free space. */+/**+ * Prune oldest conversations from chat store to free space.+ *+ * WHEN THIS CAN BITE. Since 2.5.0 `chat-conversations` normally lives in+ * IndexedDB and idbStorage deletes the localStorage copy, so on a healthy+ * profile there is nothing here to prune. The tier is for the degraded case+ * idbStorage falls back to: no IndexedDB (a broken WebView2 profile, the node+ * test env), where the history goes back into localStorage and is by far the+ * biggest thing in it — which is exactly when some OTHER store's small write is+ * the one that hits the 5 MB wall.+ */function pruneOldConversations(): boolean {const ls = getLS()if (!ls) return false@@ -170,3 +181,20 @@ export function createSafeStorage(): StateStorage {},}}++/**+ * The persist backend every localStorage-backed store uses.+ *+ * WHY IT IS NOT OPTIONAL. zustand's default is `createJSONStorage(() =>+ * localStorage)`, and its setItem runs SYNCHRONOUSLY inside `api.setState`. A+ * QuotaExceededError there does not fail a save, it throws out of the store+ * action and out of the React event handler that called it — a click that+ * silently takes the screen down. Until 2.6.8 nothing used createSafeStorage,+ * so both prune tiers and StorageQuotaToast were code that could not run.+ *+ * Generic so each store keeps its own partialized type; the returned object is+ * stateless, so sharing the shape across stores costs nothing.+ */+export function safeJSONStorage<S>(): PersistStorage<S> | undefined {+ return createJSONStorage<S>(() => createSafeStorage())+}diff --git a/src/lib/store-backup.ts b/src/lib/store-backup.tsindex d2917c28..6574e7ea 100644--- a/src/lib/store-backup.ts+++ b/src/lib/store-backup.ts@@ -15,12 +15,17 @@* around 230k tokens. sockenmonster on the same build lost nothing.*/import { backendCall } from '../api/backend'-import { idbStorage } from './idbStorage'+import { idbStorage, hasFailedRead, onIdbWrite } from './idbStorage'+import { log } from './logger'/** Every store that is worth carrying across an update or a wiped WebView2* profile. Order is irrelevant, presence is not: a key missing from this list* is a store that silently does not survive, which is how `lu_cloud_notice`- * came back on every update while its own comment claimed it did not. */+ * came back on every update while its own comment claimed it did not.+ *+ * The list is asserted against the persist keys actually declared in+ * src/stores by store-backup-covers-every-store.test.ts — a new persisted+ * store fails that test rather than quietly not surviving an update. */export const STORE_KEYS = ['chat-conversations', 'chat-settings', 'chat-models', 'lu-providers','create-store', 'locally-uncensored-codex',@@ -31,13 +36,98 @@ export const STORE_KEYS = ['rag-store', 'workflow-store', 'lu-cloud-catalog','lu_cloud_notice', 'lu_comfy_notice', 'locally-uncensored-model-health','locally-uncensored-agent-goal',+ // Added 2.6.8. Every one of these was persisted and none of them was listed,+ // so the NSIS/WebView2 wipe this file exists to survive destroyed them:+ // staged-changes approved edits that are not on disk yet — the+ // exact loss Morgan reported on 2026-08-11, one+ // layer further down than the fix he got+ // locally-uncensored-todos the plan a long agent run is working through+ // locally-uncensored-ui explorer geometry+ // lu_release_notes which version's notes were already read+ // locally-uncensored-downloads downloadMeta/bundleMap, i.e. which model+ // bundles are installed; re-deriving it means+ // re-downloading tens of GB+ 'staged-changes', 'locally-uncensored-todos', 'locally-uncensored-ui',+ 'lu_release_notes', 'locally-uncensored-downloads',]-/** These two persist through idbStorage (IndexedDB) since 2.5.0, because the+const STORE_KEY_SET = new Set(STORE_KEYS)++/** These persist through idbStorage (IndexedDB) since 2.5.0, because the* 5 MB localStorage cap could not hold a real history. The snapshot has to* read them from there: the one-time migration deleted their localStorage* copy, so localStorage.getItem answers nothing. */-export const IDB_STORE_KEYS = new Set(['chat-conversations', 'locally-uncensored-memory'])+export const IDB_STORE_KEYS = new Set([+ 'chat-conversations', 'locally-uncensored-memory', 'staged-changes',+])++/**+ * The last snapshot that was actually handed to `backup_stores`, without the+ * timestamp. Everything below compares against it instead of writing blindly.+ */+let lastWritten: Record<string, string> | null = null++/**+ * The newest value each IndexedDB-backed store has written this session.+ *+ * WHY IT EXISTS. The triad's tick used to pull the whole chat history back out+ * of IndexedDB every five seconds just to hand it straight to JSON.stringify —+ * a multi-megabyte string minted, serialised and written to the SSD on a timer,+ * forever, on battery, in an app nobody has touched. Every one of those bytes+ * already passed through idbStorage.setItem on its way to disk, so listening is+ * strictly better than re-reading: same string, no allocation, and the identity+ * of the reference makes the "did anything change" comparison a pointer test.+ */+const idbMirror: Record<string, string> = {}++onIdbWrite((key, value) => {+ if (!IDB_STORE_KEYS.has(key)) return+ if (value == null) delete idbMirror[key]+ else idbMirror[key] = value+})++/**+ * Read an IndexedDB-backed value for the snapshot. Costs one read per key per+ * session: after that the write listener above keeps the mirror current.+ */+async function idbValueForBackup(key: string): Promise<string | null> {+ const mirrored = idbMirror[key]+ if (mirrored !== undefined) return mirrored+ const read = await Promise.resolve(idbStorage.getItem(key)).catch(() => null)+ if (read != null) idbMirror[key] = read+ return read+}++/**+ * Whether the IndexedDB side can be trusted right now.+ *+ * `backup_stores` REPLACES the file. A key whose read failed looks exactly like+ * a key holding nothing, so a snapshot built during a read failure omits the+ * chats and then overwrites the one copy of them that was left. Refusing to+ * write keeps yesterday's backup, which is worth incomparably more than a+ * current one with the history missing.+ */+function idbReadsAreTrustworthy(): boolean {+ for (const key of IDB_STORE_KEYS) {+ if (hasFailedRead(key)) return false+ }+ return true+}++/** True when `next` differs from what is already on disk. Keys whose value is+ * the identical string reference (everything the mirror serves) settle on the+ * pointer comparison. */+function differsFromDisk(next: Record<string, string>): boolean {+ if (!lastWritten) return true+ const prev = lastWritten+ const prevKeys = Object.keys(prev)+ const nextKeys = Object.keys(next)+ if (prevKeys.length !== nextKeys.length) return true+ for (const key of nextKeys) {+ if (prev[key] !== next[key]) return true+ }+ return false+}/*** Read every store into one flat object.@@ -62,23 +152,131 @@ export async function collectStoreSnapshot(return snapshot}+/** The snapshot body without the timestamp — `__ts` changes on every tick and+ * would make every snapshot look dirty. */+async function collectComparableSnapshot(): Promise<Record<string, string>> {+ const body: Record<string, string> = {}+ for (const key of STORE_KEYS) {+ const val = IDB_STORE_KEYS.has(key)+ ? await idbValueForBackup(key)+ : localStorage.getItem(key)+ if (val) body[key] = val+ }+ return body+}++function writeSnapshot(body: Record<string, string>): void {+ try { localStorage.setItem('lu-restore-complete', '1') } catch { /* quota */ }+ // Marked clean optimistically so the next tick can skip, and un-marked if the+ // invoke fails — otherwise one failed write would make the triad believe the+ // change is on disk and it would never be retried.+ lastWritten = body+ backendCall('backup_stores', { data: JSON.stringify({ __ts: new Date().toISOString(), ...body }) })+ .catch(() => { if (lastWritten === body) lastWritten = null })+}++/**+ * What the 5 s interval and the 1 s debounce call.+ *+ * Writes only when a store actually changed. Before this the triad serialised+ * and re-wrote the entire history unconditionally every five seconds — the+ * multi-megabyte churn coalescedStorage was written to stop, reintroduced one+ * layer up, running on an idle app for as long as it is open.+ *+ * Returns what it did, so the caller (and a test) can tell a skipped tick from+ * a written one.+ */+export async function backupStoresIfChanged(): Promise<'written' | 'unchanged' | 'held-back'> {+ if (!idbReadsAreTrustworthy()) {+ log.warn('[store-backup] skipping the snapshot: an IndexedDB store is unreadable right now')+ return 'held-back'+ }+ const body = await collectComparableSnapshot()+ // Asked again: the reads happen between the two checks, and a key that failed+ // during them is missing from `body` while looking exactly like an empty one.+ if (!idbReadsAreTrustworthy()) {+ log.warn('[store-backup] a store became unreadable while the snapshot was being built')+ return 'held-back'+ }+ if (!differsFromDisk(body)) return 'unchanged'+ writeSnapshot(body)+ return 'written'+}++/**+ * beforeunload's flush. Synchronous on purpose: an await during page teardown+ * means the trailing `backup_stores` invoke may never fire, so this reads the+ * localStorage stores directly and the IndexedDB ones from the mirror.+ */+export function flushSyncStoreBackup(): 'written' | 'unchanged' | 'held-back' {+ try {+ if (!idbReadsAreTrustworthy()) return 'held-back'+ // The mirror is the only IndexedDB value reachable without awaiting, and a+ // snapshot built without a key REPLACES a file that had it. Before the+ // first async backup has filled the mirror there is no way to tell "this+ // store is empty" from "nobody has looked yet" — and closing the window in+ // those first seconds would have written the chats out of the backup.+ for (const key of IDB_STORE_KEYS) {+ if (idbMirror[key] !== undefined) continue+ if (lastWritten === null || lastWritten[key] !== undefined) return 'held-back'+ }+ const body: Record<string, string> = {}+ for (const key of STORE_KEYS) {+ const val = IDB_STORE_KEYS.has(key) ? (idbMirror[key] ?? null) : localStorage.getItem(key)+ if (val) body[key] = val+ }+ if (!differsFromDisk(body)) return 'unchanged'+ writeSnapshot(body)+ return 'written'+ } catch {+ return 'held-back' // best-effort: the window is going away either way+ }+}+/*** Build a snapshot and write it, and resolve only once the file is on disk.** The triad's own backup is fire and forget on purpose, it must never hold up* a render. This one is awaited, because its whole reason to exist is the- * caller that is about to end the process.+ * caller that is about to end the process. It ignores the dirty check for the+ * same reason: an update is the one moment worth paying for a redundant write.** Returns whether the file was written. Never throws: a backup that fails is* not a reason to refuse an update the user already agreed to.*/export async function backupStoresNow(): Promise<boolean> {try {+ if (!idbReadsAreTrustworthy()) {+ log.error('[store-backup] refusing to replace the backup: an IndexedDB store is unreadable')+ return false+ }const snapshot = await collectStoreSnapshot()+ if (!idbReadsAreTrustworthy()) {+ log.error('[store-backup] a store became unreadable mid-snapshot, keeping the previous backup')+ return false+ }localStorage.setItem('lu-restore-complete', '1')await backendCall('backup_stores', { data: JSON.stringify(snapshot) })+ // Same body the dirty check compares against, so the tick right after an+ // update-time backup does not rewrite the identical file.+ const body: Record<string, string> = { ...snapshot }+ delete body.__ts+ lastWritten = bodyreturn true} catch {return false}}++/** Test seam. `lastWritten` and the mirror are module state, and a test that+ * wants to observe the FIRST write of a session has to be able to get one. */+export function resetStoreBackupState(): void {+ lastWritten = null+ for (const key of Object.keys(idbMirror)) delete idbMirror[key]+}++/** Exported for the coverage test, which has to know which keys the snapshot+ * is allowed to contain. */+export function isBackedUpKey(key: string): boolean {+ return STORE_KEY_SET.has(key)+}diff --git a/src/stores/__tests__/delete-conversation-cascade.test.ts b/src/stores/__tests__/delete-conversation-cascade.test.tsnew file mode 100644index 00000000..97d052c5--- /dev/null+++ b/src/stores/__tests__/delete-conversation-cascade.test.ts@@ -0,0 +1,112 @@+/**+ * Deleting a chat has to take the chat's side state with it.+ *+ * M4/3: deleteConversation removed exactly one row — the one in+ * `conversations` — and left the conversation id behind in ragStore (plus its+ * 768-float vectors in ragDB), todoStore, permissionStore and+ * stagedChangesStore. Nothing can ever collect those: the id is the only thing+ * that could prove they are orphans, and the id is what was thrown away. The+ * vectors are the expensive half — they kept being exported to+ * rag_chunks_backup.json every 30 s for the lifetime of the installation.+ *+ * Run: npx vitest run src/stores/__tests__/delete-conversation-cascade.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++const deletedDocs: string[] = []+vi.mock('../../lib/ragDB', () => ({+ saveChunks: vi.fn(async () => {}),+ loadChunks: vi.fn(async () => []),+ deleteChunks: vi.fn(async (docId: string) => { deletedDocs.push(docId) }),+}))++import { useChatStore } from '../chatStore'+import { useRAGStore } from '../ragStore'+import { useTodoStore } from '../todoStore'+import { usePermissionStore } from '../permissionStore'+import { useStagedChangesStore } from '../stagedChangesStore'++function seedSideState(id: string) {+ const docId = `doc-${id}`+ useRAGStore.setState((s) => ({+ documents: { ...s.documents, [id]: [{ id: docId, name: 'spec.pdf', size: 10, chunkCount: 2, uploadedAt: 1 } as never] },+ ragEnabled: { ...s.ragEnabled, [id]: true },+ chunks: [+ ...s.chunks,+ { id: `c-${id}`, documentId: docId, content: 'a', embedding: [0.1], index: 0 } as never,+ { id: `o-${id}`, documentId: 'other-doc', content: 'b', embedding: [0.2], index: 0 } as never,+ ],+ }))+ useTodoStore.getState().setTodos(id, [{ content: 'step one', status: 'pending' }])+ usePermissionStore.getState().setConversationOverride(id, 'terminal', 'auto')+ useStagedChangesStore.getState().stage(id, {+ path: 'main.py', oldContent: '', newContent: 'x', diff: '+x',+ })+}++describe('deleteConversation sweeps the four dependent stores', () => {+ beforeEach(() => {+ deletedDocs.length = 0+ useChatStore.setState({ conversations: [], activeConversationId: null })+ useRAGStore.setState({ documents: {}, ragEnabled: {}, chunks: [] })+ useTodoStore.setState({ byConversation: {}, updatedAt: {} })+ usePermissionStore.setState({ conversationOverrides: {} })+ useStagedChangesStore.setState({ byChat: {} })+ })++ it('leaves nothing keyed by the deleted conversation id', () => {+ const id = useChatStore.getState().createConversation('llama3', '')+ seedSideState(id)++ useChatStore.getState().deleteConversation(id)++ expect(useChatStore.getState().conversations).toHaveLength(0)+ expect(useRAGStore.getState().documents).not.toHaveProperty(id)+ expect(useRAGStore.getState().ragEnabled).not.toHaveProperty(id)+ expect(useTodoStore.getState().byConversation).not.toHaveProperty(id)+ expect(useTodoStore.getState().updatedAt).not.toHaveProperty(id)+ expect(usePermissionStore.getState().conversationOverrides).not.toHaveProperty(id)+ expect(useStagedChangesStore.getState().byChat).not.toHaveProperty(id)+ })++ it('deletes the embedding vectors from ragDB, not just the document row', () => {+ const id = useChatStore.getState().createConversation('llama3', '')+ seedSideState(id)++ useChatStore.getState().deleteConversation(id)++ expect(deletedDocs).toEqual([`doc-${id}`])+ // Chunks belonging to another conversation's document stay put.+ expect(useRAGStore.getState().chunks.map((c) => c.documentId)).toEqual(['other-doc'])+ })++ it('does not touch another conversation', () => {+ const keep = useChatStore.getState().createConversation('llama3', '')+ const drop = useChatStore.getState().createConversation('llama3', '')+ seedSideState(keep)+ seedSideState(drop)++ useChatStore.getState().deleteConversation(drop)++ expect(useTodoStore.getState().byConversation).toHaveProperty(keep)+ expect(usePermissionStore.getState().conversationOverrides).toHaveProperty(keep)+ expect(useStagedChangesStore.getState().byChat).toHaveProperty(keep)+ expect(useRAGStore.getState().ragEnabled).toHaveProperty(keep)+ })++ it('one failing store does not stop the other three or the delete itself', () => {+ const id = useChatStore.getState().createConversation('llama3', '')+ seedSideState(id)+ const boom = vi.spyOn(useRAGStore.getState(), 'removeConversation').mockImplementation(() => {+ throw new Error('rag store exploded')+ })++ expect(() => useChatStore.getState().deleteConversation(id)).not.toThrow()++ expect(useChatStore.getState().conversations).toHaveLength(0)+ expect(useTodoStore.getState().byConversation).not.toHaveProperty(id)+ expect(usePermissionStore.getState().conversationOverrides).not.toHaveProperty(id)+ expect(useStagedChangesStore.getState().byChat).not.toHaveProperty(id)+ boom.mockRestore()+ })+})diff --git a/src/stores/__tests__/model-provider-invariant.test.ts b/src/stores/__tests__/model-provider-invariant.test.tsnew file mode 100644index 00000000..f2370889--- /dev/null+++ b/src/stores/__tests__/model-provider-invariant.test.ts@@ -0,0 +1,84 @@+/**+ * The picked model has to belong to a backend that is switched on.+ *+ * M4/7: nothing across modelStore and providerStore enforced that. The only+ * check that existed lives in `setModels`, and it re-validates the pick against+ * the next NON-EMPTY inventory — deliberately, so a transient fetch failure+ * cannot silently change the model. That leaves the window between switching a+ * backend off and the next successful refresh, where the composer still offers+ * a model whose provider is gone and every send fails with model-not-found.+ *+ * Run: npx vitest run src/stores/__tests__/model-provider-invariant.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++vi.mock('../../api/ollama', () => ({ unloadModel: vi.fn(async () => {}) }))+vi.mock('../../api/lmstudio', () => ({ unloadLmStudioModel: vi.fn(async () => {}) }))+vi.mock('../../api/engine', () => ({ activateBuiltinModel: vi.fn(async () => {}) }))++import { useModelStore, providerIdForModel } from '../modelStore'+import { useProviderStore } from '../providerStore'++describe('providerIdForModel', () => {+ it('routes a bare name to Ollama and a prefixed one to its slot', () => {+ expect(providerIdForModel('llama3:8b')).toBe('ollama')+ expect(providerIdForModel('openai::qwen3-8b')).toBe('openai')+ expect(providerIdForModel('anthropic::claude-x')).toBe('anthropic')+ expect(providerIdForModel('lu-cloud::something')).toBe('lu-cloud')+ })++ it('refuses to guess for a prefix no slot owns', () => {+ // Treating an unknown prefix as Ollama's is how a name gets sent to a+ // backend that has never heard of it.+ expect(providerIdForModel('sdxl::checkpoint.safetensors')).toBeNull()+ expect(providerIdForModel(null)).toBeNull()+ expect(providerIdForModel('')).toBeNull()+ })+})++describe('switching a backend off clears a pick it was serving', () => {+ beforeEach(() => {+ useModelStore.setState({ activeModel: null, models: [] })+ useProviderStore.getState().resetProvidersToDefaults()+ })++ it('drops the active model when its provider is disabled', async () => {+ useProviderStore.getState().setProviderConfig('ollama', { enabled: true })+ useModelStore.setState({ activeModel: 'llama3:8b' })++ useProviderStore.getState().setProviderConfig('ollama', { enabled: false })+ await new Promise((r) => setTimeout(r, 0)) // the modelStore import is lazy++ expect(useModelStore.getState().activeModel).toBeNull()+ })++ it('leaves a pick served by a different provider alone', async () => {+ useProviderStore.getState().setProviderConfig('ollama', { enabled: true })+ useProviderStore.getState().setProviderConfig('anthropic', { enabled: true })+ useModelStore.setState({ activeModel: 'anthropic::claude-x' })++ useProviderStore.getState().setProviderConfig('ollama', { enabled: false })+ await new Promise((r) => setTimeout(r, 0))++ expect(useModelStore.getState().activeModel).toBe('anthropic::claude-x')+ })++ it('an edit that does not switch the slot off changes nothing', async () => {+ useProviderStore.getState().setProviderConfig('ollama', { enabled: true })+ useModelStore.setState({ activeModel: 'llama3:8b' })++ useProviderStore.getState().setProviderConfig('ollama', { baseUrl: 'http://localhost:11500' })+ await new Promise((r) => setTimeout(r, 0))++ expect(useModelStore.getState().activeModel).toBe('llama3:8b')+ })++ it('dropActiveModelIfServedBy only fires for the matching slot', () => {+ useModelStore.setState({ activeModel: 'openai::qwen3-8b' })+ useModelStore.getState().dropActiveModelIfServedBy('anthropic')+ expect(useModelStore.getState().activeModel).toBe('openai::qwen3-8b')++ useModelStore.getState().dropActiveModelIfServedBy('openai')+ expect(useModelStore.getState().activeModel).toBeNull()+ })+})diff --git a/src/stores/__tests__/persist-versioning.test.ts b/src/stores/__tests__/persist-versioning.test.tsnew file mode 100644index 00000000..c6df7a8a--- /dev/null+++ b/src/stores/__tests__/persist-versioning.test.ts@@ -0,0 +1,146 @@+/**+ * What zustand's persist `version` / `migrate` actually guarantees.+ *+ * The 2.6.8 audit asked for `version: 1` + a no-op migrate on every store that+ * has neither, on the premise that an unversioned store writes NO version, so a+ * later `version: 1` would find `undefined` and skip the migration for every+ * existing user. Against the vendored zustand (5.0.12) that premise is false —+ * the first three tests here are the proof, run against the real library rather+ * than quoted from it — and acting on it would have cost a real regression:+ * an older build reading a version-1 blob discards the persisted state, which+ * is the R1 DOWNGRADE-KONTRAKT (see codexStore) while 2.6.x builds share one+ * WebView profile.+ *+ * The invariant that IS worth enforcing is the pair: a store that declares a+ * version must declare a migrate, because that is the one combination that+ * throws the user's data away on a mismatch.+ *+ * Run: npx vitest run src/stores/__tests__/persist-versioning.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'fs'+import { fileURLToPath } from 'url'+import { dirname, join } from 'path'+import { create } from 'zustand'+import { persist, createJSONStorage } from 'zustand/middleware'++function memoryStorage() {+ const mem = new Map<string, string>()+ return {+ mem,+ api: {+ getItem: (k: string) => mem.get(k) ?? null,+ setItem: (k: string, v: string) => void mem.set(k, v),+ removeItem: (k: string) => void mem.delete(k),+ },+ }+}++describe('zustand persist versioning, measured not assumed', () => {+ it('a store that declares NO version still writes version 0 into the blob', () => {+ const { mem, api } = memoryStorage()+ const s = create<{ n: number; bump: () => void }>()(persist((set) => ({+ n: 0,+ bump: () => set((x) => ({ n: x.n + 1 })),+ }), { name: 'unversioned', storage: createJSONStorage(() => api as never) }))++ s.getState().bump()+ expect(JSON.parse(mem.get('unversioned')!).version).toBe(0)+ })++ it('a version-0 blob DOES reach a migrate later declared at version 1', () => {+ // This is the audit's claim, inverted: nothing is skipped, because 0 is a+ // number and 0 !== 1.+ const { mem, api } = memoryStorage()+ mem.set('later', JSON.stringify({ state: { n: 7 }, version: 0 }))+ const seen: number[] = []++ const s = create<{ n: number }>()(persist(() => ({ n: 0 }), {+ name: 'later',+ version: 1,+ storage: createJSONStorage(() => api as never),+ migrate: (p, v) => { seen.push(v); return p as { n: number } },+ }))++ expect(seen).toEqual([0])+ expect(s.getState().n).toBe(7)+ })++ it('an older build without a version DISCARDS a version-1 blob', () => {+ // Why the bump is not free. The old build defaults to version 0, sees 1,+ // has no migrate to call, and hydrates from defaults — every setting gone.+ const { mem, api } = memoryStorage()+ mem.set('downgrade', JSON.stringify({ state: { n: 7 }, version: 1 }))++ const s = create<{ n: number }>()(persist(() => ({ n: 0 }), {+ name: 'downgrade',+ storage: createJSONStorage(() => api as never),+ }))++ expect(s.getState().n).toBe(0) // the 7 is gone+ })++ it('the same downgrade keeps the state when a migrate exists', () => {+ const { mem, api } = memoryStorage()+ mem.set('safe', JSON.stringify({ state: { n: 7 }, version: 1 }))++ const s = create<{ n: number }>()(persist(() => ({ n: 0 }), {+ name: 'safe',+ storage: createJSONStorage(() => api as never),+ migrate: (p) => p as { n: number },+ }))++ expect(s.getState().n).toBe(7)+ })+})++const STORES_DIR = join(dirname(fileURLToPath(import.meta.url)), '..')+const loaders = import.meta.glob('../*.ts')++type PersistOptions = { name?: string; version?: number; migrate?: unknown }+type PersistedStore = { persist: { getOptions: () => PersistOptions } }++function isPersisted(value: unknown): value is PersistedStore {+ const p = (value as { persist?: { getOptions?: unknown } } | null)?.persist+ return !!p && typeof p.getOptions === 'function'+}++async function allPersistOptions(): Promise<{ file: string; opts: PersistOptions }[]> {+ const out: { file: string; opts: PersistOptions }[] = []+ for (const [path, load] of Object.entries(loaders)) {+ const mod = (await load()) as Record<string, unknown>+ for (const value of Object.values(mod)) {+ if (isPersisted(value)) out.push({ file: path.split('/').pop()!, opts: value.persist.getOptions() })+ }+ }+ return out+}++describe('every store that declares a version declares a migrate', () => {+ it('has no version-without-migrate anywhere in src/stores', async () => {+ const all = await allPersistOptions()+ expect(all.length).toBeGreaterThan(20)++ // getOptions() hands back the DEFAULTED options, where an undeclared+ // version reads as 0 — indistinguishable from a deliberate 0. So the+ // "declares" half has to come from the source; the "has a migrate" half is+ // structural, straight off the live store.+ const orphans: string[] = []+ for (const { file, opts } of all) {+ const src = readFileSync(join(STORES_DIR, file), 'utf8')+ const declaresVersion = /\n\s{2,}version:\s*\S/.test(src)+ if (declaresVersion && typeof opts.migrate !== 'function') {+ orphans.push(`${file} (${opts.name}) declares a version with no migrate`)+ }+ }++ expect(orphans).toEqual([])+ })++ it('lu-providers specifically — it declared version 1 with no migrate', async () => {+ const all = await allPersistOptions()+ const providers = all.find(({ opts }) => opts.name === 'lu-providers')+ expect(providers).toBeTruthy()+ expect(typeof providers!.opts.migrate).toBe('function')+ })+})diff --git a/src/stores/agentGoalStore.ts b/src/stores/agentGoalStore.tsindex 2472e103..eb9e82ae 100644--- a/src/stores/agentGoalStore.ts+++ b/src/stores/agentGoalStore.ts@@ -13,6 +13,7 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'export interface AgentGoal {text: string@@ -55,7 +56,10 @@ export const useAgentGoalStore = create<AgentGoalState>()(return { goals: next }}),}),- { name: 'locally-uncensored-agent-goal' },+ {+ name: 'locally-uncensored-agent-goal',+ storage: safeJSONStorage(),+ },),)diff --git a/src/stores/agentModeStore.ts b/src/stores/agentModeStore.tsindex 88fc6392..15564255 100644--- a/src/stores/agentModeStore.ts+++ b/src/stores/agentModeStore.ts@@ -1,5 +1,6 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'import type { SandboxLevel } from '../types/agent-mode'import type { AgentWorkspace } from '../types/agent-workspace'@@ -120,6 +121,9 @@ export const useAgentModeStore = create<AgentModeState>()(return get().agentModeActive[conversationId] ?? false},}),- { name: 'locally-uncensored-agent-mode' }+ {+ name: 'locally-uncensored-agent-mode',+ storage: safeJSONStorage(),+ }))diff --git a/src/stores/agentWorkflowStore.ts b/src/stores/agentWorkflowStore.tsindex e0b82f67..ffd14fd4 100644--- a/src/stores/agentWorkflowStore.ts+++ b/src/stores/agentWorkflowStore.ts@@ -1,5 +1,6 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'import { v4 as uuid } from 'uuid'import type { AgentWorkflow, WorkflowExecution, StepResult } from '../types/agent-workflows'import { BUILT_IN_WORKFLOWS } from '../lib/built-in-workflows'@@ -143,6 +144,7 @@ export const useAgentWorkflowStore = create<AgentWorkflowState>()(}),{name: 'locally-uncensored-agent-workflows',+ storage: safeJSONStorage(),version: 1,migrate: (persistedState, version) => {const state = persistedState as anydiff --git a/src/stores/benchmarkStore.ts b/src/stores/benchmarkStore.tsindex ce53b037..6b5c15c2 100644--- a/src/stores/benchmarkStore.ts+++ b/src/stores/benchmarkStore.ts@@ -1,5 +1,6 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'import type { BenchmarkResult } from '../lib/benchmark-prompts'interface BenchmarkState {@@ -74,6 +75,7 @@ export const useBenchmarkStore = create<BenchmarkState>()(}),{name: 'lu-benchmark-store',+ storage: safeJSONStorage(),// Only the measurements are worth keeping. Run state is about the run// that is happening now: a persisted isRunning left over from a crash// greys out the Run button forever, and a persisted error greets thediff --git a/src/stores/chatStore.ts b/src/stores/chatStore.tsindex 3f2d287f..f0243dcd 100644--- a/src/stores/chatStore.ts+++ b/src/stores/chatStore.ts@@ -8,6 +8,11 @@ import { coalescedJSONStorage } from '../lib/coalescedStorage'import { migrateBlockInPlace } from '../api/agents/block-helpers'import { useGenerationStore } from './generationStore'import { useRemoteStore } from './remoteStore'+import { useRAGStore } from './ragStore'+import { useTodoStore } from './todoStore'+import { usePermissionStore } from './permissionStore'+import { useStagedChangesStore } from './stagedChangesStore'+import { log } from '../lib/logger'/*** Rehydration migration for Phase 1 (v2.4.0) — wraps legacy@@ -29,6 +34,35 @@ export function migratePersistedChat(state: any): any {return state}+/**+ * Everything OUTSIDE this store that is keyed by conversation id.+ *+ * Deleting a chat used to remove exactly one row — the one in `conversations` —+ * and leave five other stores holding that id forever. Nothing ever collects+ * them, because the id is the only thing that could prove they are orphans and+ * the id is what was just thrown away. The RAG side is the expensive one: its+ * 768-float embedding vectors stay in IndexedDB AND keep being exported to+ * rag_chunks_backup.json every 30 s for the lifetime of the installation.+ *+ * Each store is its own try/catch: one of them failing must not leave the other+ * four uncleaned, and none of them may stop the chat from being deleted.+ *+ * Exported so a test can assert the sweep without going through the store.+ */+export function dropConversationSideState(id: string): void {+ const steps: [string, () => void][] = [+ ['rag', () => useRAGStore.getState().removeConversation(id)],+ ['todos', () => useTodoStore.getState().clearTodos(id)],+ ['permissions', () => usePermissionStore.getState().clearConversationOverrides(id)],+ ['staged-changes', () => useStagedChangesStore.getState().clear(id)],+ ]+ for (const [what, run] of steps) {+ try { run() } catch (err) {+ log.warn('[chatStore] could not clear side state for a deleted chat', { store: what, err: String(err) })+ }+ }+}+interface ChatState {conversations: Conversation[]activeConversationId: string | null@@ -169,6 +203,7 @@ export const useChatStore = create<ChatState>()(void remote.undispatch()}} catch { /* best-effort */ }+ dropConversationSideState(id)set((state) => ({conversations: state.conversations.filter((c) => c.id !== id),activeConversationId:@@ -429,6 +464,20 @@ export const useChatStore = create<ChatState>()(// Phase 1 (v2.4.0) — rehydrate legacy singular `toolCall` into `toolCalls[]`.// Persisted shape is whatever was last written; migration runs on every load// and is idempotent, so version bumps are not required.+ //+ // Deliberately still NO `version` here, and the 2.6.8 audit's argument for+ // adding one does not survive contact with zustand 5.0.12. It assumed an+ // unversioned store writes no version, so a later `version: 1` would find+ // `undefined` and skip migrate for every existing user. It writes 0 —+ // `version: 0` is persistImpl's own default and it goes into the blob — and+ // a v0 blob DOES reach a migrate declared at 1. See persist-version.ts for+ // the executable proof.+ //+ // Adding a number is not free either: an older build declaring no version+ // reads its own 0, sees a blob at 1, has no migrate, and throws the entire+ // chat history away. That is the R1 DOWNGRADE-KONTRAKT (see codexStore) —+ // 2.6.x builds share one WebView profile — so stamping a number here would+ // buy nothing and cost a reset on every downgrade.merge: (persistedState: any, currentState: ChatState) => {const migrated = migratePersistedChat(persistedState)return { ...currentState, ...(migrated || {}) }diff --git a/src/stores/cloudCatalogStore.ts b/src/stores/cloudCatalogStore.tsindex 90a6aca3..3c94b866 100644--- a/src/stores/cloudCatalogStore.ts+++ b/src/stores/cloudCatalogStore.ts@@ -6,6 +6,7 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'import { CLOUD_MODEL_SEED, type CloudModel } from '../lib/render/cloud-models'import type { RenderKind, RenderOp } from '../lib/render/cloud-jobs'import { getCatalog, type CatalogOps, type CloudCatalog } from '../api/cloud/catalog'@@ -39,7 +40,10 @@ export const useCloudCatalogStore = create<CloudCatalogState>()(mediaLive: c.media_live,}),}),- { name: 'lu-cloud-catalog' },+ {+ name: 'lu-cloud-catalog',+ storage: safeJSONStorage(),+ },),)diff --git a/src/stores/cloudNoticeStore.ts b/src/stores/cloudNoticeStore.tsindex ec792986..5d611911 100644--- a/src/stores/cloudNoticeStore.ts+++ b/src/stores/cloudNoticeStore.ts@@ -1,5 +1,6 @@import { create } from "zustand";import { persist } from "zustand/middleware";+import { safeJSONStorage } from "../lib/storage-quota"/*** How long a cloud render stays retrievable. Single source of truth for the@@ -36,7 +37,10 @@ export const useCloudNoticeStore = create<CloudNoticeState>()(retentionNoticeSeen: false,setRetentionNoticeSeen: (v) => set({ retentionNoticeSeen: v }),}),- { name: "lu_cloud_notice" },+ {+ name: "lu_cloud_notice",+ storage: safeJSONStorage(),+ },),);diff --git a/src/stores/comfyNoticeStore.ts b/src/stores/comfyNoticeStore.tsindex 64028ff1..5f8f741b 100644--- a/src/stores/comfyNoticeStore.ts+++ b/src/stores/comfyNoticeStore.ts@@ -1,5 +1,6 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'import { PENDING_SIGNATURE } from '../lib/comfy-cors-notice'/**@@ -50,6 +51,9 @@ export const useComfyNoticeStore = create<ComfyNoticeState>()(: s,),}),- { name: 'lu_comfy_notice' },+ {+ name: 'lu_comfy_notice',+ storage: safeJSONStorage(),+ },),)diff --git a/src/stores/createStore.ts b/src/stores/createStore.tsindex aa20abe7..e3df4c17 100644--- a/src/stores/createStore.ts+++ b/src/stores/createStore.ts@@ -1,5 +1,6 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'import type { ModelType, ClassifiedModel } from '../api/comfyui'import { classifyModel } from '../api/comfyui'import type { HiresUpscaleMethod } from '../api/hires-fix'@@ -817,6 +818,7 @@ export const useCreateStore = create<CreateState>()(}),{name: 'create-store',+ storage: safeJSONStorage(),partialize: (state) => ({mode: state.mode,videoBackend: state.videoBackend,diff --git a/src/stores/mcpStore.ts b/src/stores/mcpStore.tsindex 2cf092a1..f9da0441 100644--- a/src/stores/mcpStore.ts+++ b/src/stores/mcpStore.ts@@ -1,5 +1,6 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'import type { MCPServerConfig, MCPToolDefinition } from '../api/mcp/types'interface MCPState {@@ -60,6 +61,7 @@ export const useMCPStore = create<MCPState>()(}),{name: 'locally-uncensored-mcp-servers',+ storage: safeJSONStorage(),partialize: (state) => ({servers: state.servers,}),diff --git a/src/stores/modelHealthStore.ts b/src/stores/modelHealthStore.tsindex 17c8e049..507dbb4c 100644--- a/src/stores/modelHealthStore.ts+++ b/src/stores/modelHealthStore.ts@@ -1,5 +1,6 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'/*** Tracks which installed Ollama models have stale manifests (rejected by@@ -59,6 +60,7 @@ export const useModelHealthStore = create<ModelHealthState>()(}),{name: 'locally-uncensored-model-health',+ storage: safeJSONStorage(),// `dismissed` persists as of 2.5.9: the banner re-ran its startup scan and// came back on EVERY launch while a stale model sat on disk, so closing it// meant nothing. A fresh scan that finds stale models clears the flagdiff --git a/src/stores/modelStore.ts b/src/stores/modelStore.tsindex 02579c63..19cb2223 100644--- a/src/stores/modelStore.ts+++ b/src/stores/modelStore.ts@@ -1,5 +1,6 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'import type { AIModel, PullProgress, ModelCategory } from '../types/models'import { unloadModel } from '../api/ollama'import { unloadLmStudioModel } from '../api/lmstudio'@@ -9,6 +10,27 @@ import { isTauri, backendCall } from '../api/backend'import { useChatStore } from './chatStore'import { log } from '../lib/logger'+/**+ * Which provider slot a model name routes to.+ *+ * LU prefixes every non-Ollama model with the id of the provider that serves+ * it ("openai::qwen3-8b"); a bare name goes to Ollama. Pure, because the point+ * of it is to be assertable without a store.+ *+ * `null` means "no slot in this build owns that name" — an unknown prefix is+ * not silently treated as Ollama's, which is how a checkpoint name ends up+ * being sent to a backend that has never heard of it.+ */+export function providerIdForModel(name: string | null | undefined): ProviderId | null {+ if (!name) return null+ const sep = name.indexOf('::')+ if (sep < 0) return 'ollama'+ const prefix = name.slice(0, sep)+ return PROVIDER_IDS.includes(prefix as ProviderId) ? (prefix as ProviderId) : null+}++const PROVIDER_IDS: readonly ProviderId[] = ['ollama', 'openai', 'anthropic', 'lu-cloud']+export interface PullState {progress: PullProgresscontroller: AbortController@@ -52,6 +74,13 @@ interface ModelState {dismissPull: (name: string) => voidsetIsModelLoading: (loading: boolean) => voidsetCategoryFilter: (category: ModelCategory) => void+ /** Nothing across these two stores enforced that the picked model belongs to+ * a backend that is still switched on. `setModels` only re-checks the pick+ * against the next NON-EMPTY inventory, so between switching a provider off+ * and the next successful refresh the composer showed a model whose backend+ * was gone and every send failed with model-not-found. providerStore calls+ * this the moment a slot goes dark. */+ dropActiveModelIfServedBy: (providerId: ProviderId) => void}export const useModelStore = create<ModelState>()(@@ -258,9 +287,21 @@ export const useModelStore = create<ModelState>()(setIsModelLoading: (loading) => set({ isModelLoading: loading }),setCategoryFilter: (category) => set({ categoryFilter: category }),++ dropActiveModelIfServedBy: (providerId) => {+ const active = get().activeModel+ if (!active || providerIdForModel(active) !== providerId) return+ log.warn('[modelStore] the picked model\'s backend was switched off, clearing the pick', {+ model: active, provider: providerId,+ })+ // Through setActiveModel, not a bare set(): the model that is going+ // away is also the one holding VRAM, and that release lives there.+ get().setActiveModel(null)+ },}),{name: 'chat-models',+ storage: safeJSONStorage(),partialize: (state) => ({ activeModel: state.activeModel, categoryFilter: state.categoryFilter }),})diff --git a/src/stores/permissionStore.ts b/src/stores/permissionStore.tsindex 9ca5234c..d84cf766 100644--- a/src/stores/permissionStore.ts+++ b/src/stores/permissionStore.ts@@ -1,5 +1,6 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'import type { PermissionMap, PermissionLevel, ToolCategory } from '../api/mcp/types'import { DEFAULT_PERMISSIONS } from '../api/mcp/types'@@ -117,6 +118,7 @@ export const usePermissionStore = create<PermissionState>()(}),{name: 'locally-uncensored-permissions',+ storage: safeJSONStorage(),version: 3,migrate: migratePermissionState,}diff --git a/src/stores/providerStore.ts b/src/stores/providerStore.tsindex fcc7dd26..b4b53d45 100644--- a/src/stores/providerStore.ts+++ b/src/stores/providerStore.ts@@ -7,6 +7,8 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'+import { keepPersistedState } from '../lib/persist-version'+import { safeJSONStorage } from '../lib/storage-quota'import type { ProviderId, ProviderConfig } from '../api/providers/types'import { clearProviderCache } from '../api/providers/registry'import { onLocalSlotChanged } from '../lib/builtin-slot-eviction'@@ -145,6 +147,17 @@ export const useProviderStore = create<ProviderState>()(},}))clearProviderCache() // invalidate cached clients+ // A slot going dark makes the picked model unservable, and nothing used+ // to notice: the pick is only re-validated against the next NON-EMPTY+ // model list, so until a refresh lands the composer offers a model whose+ // backend is off. Imported lazily on purpose — modelStore reaches back+ // here through chatStore/remoteStore, and a static edge would close that+ // circle at module-init time.+ if (before?.enabled && get().providers[id]?.enabled === false) {+ void import('./modelStore')+ .then((m) => m.useModelStore.getState().dropActiveModelIfServedBy(id))+ .catch(() => { /* best-effort: the next inventory refresh re-checks */ })+ }// Every route that moves the shared local slot comes through here (Add// Provider, Enable on the standby card, Remove, Disable, onboarding), so// the memory question is asked here, once. R12/R13 measured the answer@@ -275,7 +288,13 @@ export const useProviderStore = create<ProviderState>()(}),{name: 'lu-providers',+ storage: safeJSONStorage(),version: 1,+ // A version WITHOUT a migrate is the one combination that loses data:+ // zustand logs "couldn't be migrated" and hydrates from defaults, i.e. it+ // throws every configured backend away. Harmless today (no blob carries a+ // numeric version yet), fatal the day this store goes to 2.+ migrate: keepPersistedState,// Blobs persisted before the lu-cloud provider existed lack its entry —// backfill every missing provider from defaults so getProvider() can't// hit an undefined config after an update.diff --git a/src/stores/ragStore.ts b/src/stores/ragStore.tsindex 2edaa751..82a3c172 100644--- a/src/stores/ragStore.ts+++ b/src/stores/ragStore.ts@@ -1,5 +1,6 @@import { create } from "zustand"import { persist } from "zustand/middleware"+import { safeJSONStorage } from "../lib/storage-quota"import type { DocumentMeta, TextChunk } from "../types/rag"import { saveChunks, loadChunks, deleteChunks } from "../lib/ragDB"import { log } from "../lib/logger"@@ -38,6 +39,14 @@ interface RAGState {setIndexing: (indexing: boolean) => voidsetIndexingProgress: (progress: { current: number; total: number } | null) => voidclearConversationDocs: (conversationId: string) => void+ /** Everything this conversation owns, gone: the document list, the RAG+ * toggle, the in-memory chunks and their 768-float vectors in IndexedDB.+ * clearConversationDocs empties the document array but LEAVES the two keys+ * behind, which is right while the chat still exists and wrong once it does+ * not — a deleted chat's entry would sit in `documents` forever and its+ * vectors would keep being exported to rag_chunks_backup.json every 30 s for+ * the lifetime of the installation. */+ removeConversation: (conversationId: string) => voidsetLastRetrievedChunks: (chunks: { chunk: TextChunk; score: number }[]) => voidsetContextWarning: (warning: string | null) => voidsetPullingEmbeddingModel: (pulling: boolean) => void@@ -173,6 +182,28 @@ export const useRAGStore = create<RAGState>()(}))},+ removeConversation: (conversationId) => {+ const docIds = (get().documents[conversationId] || []).map((d) => d.id)+ for (const docId of docIds) {+ deleteChunks(docId).catch((err) =>+ log.error("Failed to delete chunks from IndexedDB", { err })+ )+ }+ set((state) => {+ const documents = { ...state.documents }+ const ragEnabled = { ...state.ragEnabled }+ delete documents[conversationId]+ delete ragEnabled[conversationId]+ return {+ documents,+ ragEnabled,+ chunks: docIds.length > 0+ ? state.chunks.filter((c) => !docIds.includes(c.documentId))+ : state.chunks,+ }+ })+ },+setLastRetrievedChunks: (chunks) => set({ lastRetrievedChunks: chunks }),setContextWarning: (warning) => set({ contextWarning: warning }),@@ -190,6 +221,7 @@ export const useRAGStore = create<RAGState>()(}),{name: "rag-store",+ storage: safeJSONStorage(),partialize: (state) => ({documents: state.documents,ragEnabled: state.ragEnabled,diff --git a/src/stores/releaseNotesStore.ts b/src/stores/releaseNotesStore.tsindex 44346c0f..a9a12fa8 100644--- a/src/stores/releaseNotesStore.ts+++ b/src/stores/releaseNotesStore.ts@@ -1,5 +1,6 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'import { releaseNoteFor } from '../lib/release-notes'/**@@ -21,7 +22,10 @@ export const useReleaseNotesStore = create<ReleaseNotesState>()(lastNotesVersion: null,markNotesSeen: (version) => set({ lastNotesVersion: version }),}),- { name: 'lu_release_notes' },+ {+ name: 'lu_release_notes',+ storage: safeJSONStorage(),+ },),)diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex e907037c..333d3fb6 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -1,5 +1,6 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'import type { Settings, Persona } from '../types/settings'import { DEFAULT_SETTINGS, BUILT_IN_PERSONAS } from '../lib/constants'@@ -152,6 +153,7 @@ export const useSettingsStore = create<SettingsState>()(}),{name: 'chat-settings',+ storage: safeJSONStorage(),version: STORE_VERSION,migrate: (persisted: any, version: number) => {if (version < STORE_VERSION) {diff --git a/src/stores/todoStore.ts b/src/stores/todoStore.tsindex 5e39a6e0..60ccaa9c 100644--- a/src/stores/todoStore.ts+++ b/src/stores/todoStore.ts@@ -1,5 +1,6 @@import { create } from 'zustand'-import { persist, createJSONStorage } from 'zustand/middleware'+import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'/*** The plan a long run is working through, written by the model itself.@@ -84,7 +85,7 @@ export const useTodoStore = create<TodoState>()(}),{name: 'locally-uncensored-todos',- storage: createJSONStorage(() => localStorage),+ storage: safeJSONStorage(),},),)diff --git a/src/stores/uiStore.ts b/src/stores/uiStore.tsindex a598c8cb..f6f54e15 100644--- a/src/stores/uiStore.ts+++ b/src/stores/uiStore.ts@@ -1,5 +1,6 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'import type { SettingsTab } from '../lib/settings-reset'export type View = 'chat' | 'models' | 'settings' | 'create' | 'benchmark'@@ -111,6 +112,7 @@ export const useUIStore = create<UIState>()(}),{name: 'locally-uncensored-ui',+ storage: safeJSONStorage(),// EXACTLY the two explorer fields (plan C3 / R1). This store was not// persisted at all before, and persisting it naively would carry// currentView and cloudGateOpen across restarts: the app would reopen ondiff --git a/src/stores/updateStore.ts b/src/stores/updateStore.tsindex a8036f92..1cf81749 100644--- a/src/stores/updateStore.ts+++ b/src/stores/updateStore.ts@@ -2,6 +2,7 @@ import { create } from 'zustand'import { withDetail } from '../lib/error-text'import { log } from '../lib/logger'import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'import { version as currentVersion } from '../../package.json'import { isTauri, backendCall, openExternal } from '../api/backend'import { stopBundledEngine, stopBundledEmbed } from '../api/engine'@@ -367,6 +368,7 @@ export const useUpdateStore = create<UpdateState>()(}),{name: 'lu-update-checker-v2',+ storage: safeJSONStorage(),// downloadStatus is deliberately NOT persisted: the Update handle lives// in module-level `_pendingUpdate`, which dies with the process — a// rehydrated 'downloaded'/'downloading'/'error' state would render badgediff --git a/src/stores/voiceStore.ts b/src/stores/voiceStore.tsindex b91eb0b9..a9e45ce2 100644--- a/src/stores/voiceStore.ts+++ b/src/stores/voiceStore.ts@@ -1,5 +1,6 @@import { create } from "zustand";import { persist } from "zustand/middleware";+import { safeJSONStorage } from "../lib/storage-quota"interface VoiceState {// Transient state (not persisted)@@ -155,6 +156,7 @@ export const useVoiceStore = create<VoiceState>()(}),{name: "locally-uncensored-voice",+ storage: safeJSONStorage(),partialize: (state) => ({sttEnabled: state.sttEnabled,ttsEnabled: state.ttsEnabled,diff --git a/src/stores/workflowStore.ts b/src/stores/workflowStore.tsindex daffebd7..ca5c9af1 100644--- a/src/stores/workflowStore.ts+++ b/src/stores/workflowStore.ts@@ -1,5 +1,6 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'import { v4 as uuid } from 'uuid'import { isVideoModelType, type ModelType, } from '../api/comfyui'import type { WorkflowTag, WorkflowTemplate } from '../types/workflows'@@ -438,6 +439,7 @@ export const useWorkflowStore = create<WorkflowState>()(}),{name: 'workflow-store',+ storage: safeJSONStorage(),},),)