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
v2.5.0: chat + memory persistence → IndexedDB (kills the 5 MB localStorage cap)
purplecb3e490a60ec
diff --git a/src/lib/__tests__/idbStorage.test.ts b/src/lib/__tests__/idbStorage.test.tsnew file mode 100644index 00000000..107576f7--- /dev/null+++ b/src/lib/__tests__/idbStorage.test.ts@@ -0,0 +1,50 @@+import { describe, it, expect, vi, afterEach } from 'vitest'+import { idbStorage } from '../idbStorage'++// The vitest env is `node`: no `indexedDB`, so idbStorage takes its SYNC+// localStorage fallback. That sync path is exactly what keeps Zustand+// hydration synchronous in the suite (the 2580 store tests rely on it) — in+// the real WebView2 app `indexedDB` exists and the adapter goes async + idb.+function mockLS(init: Record<string, string> = {}): Storage {+ const store: Record<string, string> = { ...init }+ return {+ getItem: vi.fn((k: string) => store[k] ?? null),+ setItem: vi.fn((k: string, v: string) => { store[k] = v }),+ removeItem: vi.fn((k: string) => { delete store[k] }),+ clear: vi.fn(() => { for (const k in store) delete store[k] }),+ get length() { return Object.keys(store).length },+ key: vi.fn((i: number) => Object.keys(store)[i] ?? null),+ }+}++describe('idbStorage (no-IndexedDB fallback path)', () => {+ afterEach(() => {+ try { delete (globalThis as any).localStorage } catch { /* ignore */ }+ })++ it('round-trips via localStorage SYNCHRONOUSLY (no Promise) when idb is absent', () => {+ Object.defineProperty(globalThis, 'localStorage', { value: mockLS(), writable: true, configurable: true })+ // setItem must NOT return a Promise here (keeps persist hydration sync in tests)+ const setResult = idbStorage.setItem('chat-conversations', '{"state":{"conversations":[]}}')+ expect(setResult).toBeUndefined()+ const got = idbStorage.getItem('chat-conversations')+ expect(got).toBe('{"state":{"conversations":[]}}')+ expect(typeof (got as any)?.then).not.toBe('function') // sync string, not a thenable+ idbStorage.removeItem('chat-conversations')+ expect(idbStorage.getItem('chat-conversations')).toBeNull()+ })++ it('getItem returns null for a missing key', () => {+ Object.defineProperty(globalThis, 'localStorage', { value: mockLS(), writable: true, configurable: true })+ expect(idbStorage.getItem('nonexistent')).toBeNull()+ })++ it('never throws when localStorage is unavailable (SSR / locked)', () => {+ Object.defineProperty(globalThis, 'localStorage', {+ get() { throw new Error('blocked') }, configurable: true,+ })+ expect(() => idbStorage.setItem('k', 'v')).not.toThrow()+ expect(idbStorage.getItem('k')).toBeNull()+ expect(() => idbStorage.removeItem('k')).not.toThrow()+ })+})diff --git a/src/lib/idbStorage.ts b/src/lib/idbStorage.tsnew file mode 100644index 00000000..4ec0b201--- /dev/null+++ b/src/lib/idbStorage.ts@@ -0,0 +1,143 @@+/**+ * IndexedDB-backed Zustand persist storage (v2.5.0).+ *+ * WHY: chat history + memories were persisted to localStorage, whose hard+ * ~5 MB per-origin cap is far too small for real chat history (long threads,+ * inline images, imported transcripts). localStorage is also the wrong tool —+ * it's a tiny synchronous key/value store. The standard fix web apps use is+ * IndexedDB, which is disk-backed and scales to tens of GB (Chromium grants an+ * origin up to ~60% of free disk, more with persistent-storage). LU already+ * uses IndexedDB for RAG chunks + memory embeddings; this brings the chat ++ * memory STORES onto the same durable, large backend.+ *+ * DESIGN:+ * - idb-first, with a ONE-TIME migration read from the legacy localStorage+ * key (so existing users keep their chats/memories on upgrade), after which+ * the localStorage copy is dropped to free that 5 MB.+ * - SYNC localStorage fallback when IndexedDB is unavailable (the vitest+ * `node` env, or a degraded webview). Returning a plain value (not a+ * Promise) there keeps Zustand hydration synchronous in tests — exactly the+ * old behaviour — so the suite is unaffected. In the real WebView2 app+ * `indexedDB` exists, so getItem/setItem return Promises and persist+ * hydrates asynchronously (a sub-100 ms tick on launch).+ * - `navigator.storage.persist()` is requested once so the browser treats the+ * data as durable and never evicts it under pressure.+ *+ * Still wrapped in `createJSONStorage(() => idbStorage)` at the call site — the+ * FIX-3 lesson: Zustand v5 `storage` needs a PersistStorage, and createJSONStorage+ * does the object<->string (de)serialisation around this string StateStorage.+ */+import type { StateStorage } from 'zustand/middleware'++const DB_NAME = 'locally-uncensored-store'+const STORE = 'kv'+const DB_VERSION = 1++// FIX-3-era corrupt localStorage value ("[object Object]"). Must never be+// hydrated or migrated — treat it as absent so the store starts clean.+const LEGACY_CORRUPT = '[object Object]'++function lsGet(k: string): string | null {+ try { return typeof localStorage !== 'undefined' ? localStorage.getItem(k) : null } catch { return null }+}+function lsSet(k: string, v: string): void {+ try { if (typeof localStorage !== 'undefined') localStorage.setItem(k, v) } catch { /* quota/SSR */ }+}+function lsDel(k: string): void {+ try { if (typeof localStorage !== 'undefined') localStorage.removeItem(k) } catch { /* SSR */ }+}++const hasIDB: boolean = (() => {+ try { return typeof indexedDB !== 'undefined' && indexedDB !== null } catch { return false }+})()++let _db: Promise<IDBDatabase> | null = null+function getDB(): Promise<IDBDatabase> {+ if (_db) return _db+ _db = new Promise<IDBDatabase>((resolve, reject) => {+ const req = indexedDB.open(DB_NAME, DB_VERSION)+ req.onupgradeneeded = () => {+ const db = req.result+ if (!db.objectStoreNames.contains(STORE)) db.createObjectStore(STORE)+ }+ req.onsuccess = () => resolve(req.result)+ req.onerror = () => reject(req.error)+ req.onblocked = () => reject(new Error('indexedDB open blocked'))+ })+ return _db+}++function idbGet(key: string): Promise<string | null> {+ return getDB().then((db) => new Promise<string | null>((resolve) => {+ 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)+ }))+}+function idbSet(key: string, value: string): Promise<void> {+ return getDB().then((db) => new Promise<void>((resolve, reject) => {+ const tx = db.transaction(STORE, 'readwrite')+ tx.objectStore(STORE).put(value, key)+ tx.oncomplete = () => resolve()+ tx.onerror = () => reject(tx.error)+ tx.onabort = () => reject(tx.error)+ }))+}+function idbDel(key: string): Promise<void> {+ return getDB().then((db) => new Promise<void>((resolve) => {+ const tx = db.transaction(STORE, 'readwrite')+ tx.objectStore(STORE).delete(key)+ tx.oncomplete = () => resolve()+ tx.onerror = () => resolve()+ }))+}++let _persistAsked = false+function askPersist(): void {+ if (_persistAsked) return+ _persistAsked = true+ try {+ const s = (navigator as any)?.storage+ if (s && typeof s.persist === 'function') s.persist().catch(() => {})+ } catch { /* not supported */ }+}++export const idbStorage: StateStorage = {+ getItem(name: string): string | null | Promise<string | null> {+ if (!hasIDB) return lsGet(name) // sync path: node tests / degraded webview+ askPersist()+ return (async () => {+ try {+ 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 {+ return lsGet(name) // idb failed at runtime → localStorage+ }+ })()+ },+ setItem(name: string, value: string): void | Promise<void> {+ if (!hasIDB) { lsSet(name, value); return }+ return (async () => {+ try {+ await idbSet(name, value)+ lsDel(name) // drop the migrated localStorage copy → frees the 5 MB cap+ } catch {+ lsSet(name, value) // idb write failed → localStorage best-effort+ }+ })()+ },+ removeItem(name: string): void | Promise<void> {+ if (!hasIDB) { lsDel(name); return }+ return (async () => { try { await idbDel(name) } catch { /* ignore */ } ; lsDel(name) })()+ },+}diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.tsindex f871d533..139e7fbc 100644--- a/src/stores/chatStore.ts+++ b/src/stores/chatStore.ts@@ -3,7 +3,7 @@ import { persist, createJSONStorage } from 'zustand/middleware'import { v4 as uuid } from 'uuid'import type { Conversation, Message } from '../types/chat'import type { AgentBlock } from '../types/agent-mode'-import { createSafeStorage } from '../lib/storage-quota'+import { idbStorage } from '../lib/idbStorage'import { migrateBlockInPlace } from '../api/agents/block-helpers'/**@@ -208,12 +208,11 @@ export const useChatStore = create<ChatState>()(}),{name: 'chat-conversations',- // zustand v5: `storage` expects a PersistStorage (object-based). createSafeStorage- // is a STRING-based StateStorage, so it MUST be wrapped in createJSONStorage.- // Passing it raw made zustand hand the {state,version} OBJECT straight to- // setItem → localStorage.setItem(name, object) → "[object Object]" → chats- // never hydrated and were wiped on every restart (v2.5.0 regression).- storage: createJSONStorage(() => createSafeStorage()),+ // IndexedDB (disk-backed, tens of GB) instead of localStorage's ~5 MB cap —+ // chat history with inline images needs the room. idbStorage migrates existing+ // localStorage data on first read. createJSONStorage wrap is still required+ // (zustand v5 PersistStorage; raw StateStorage → "[object Object]", see FIX-3).+ storage: createJSONStorage(() => idbStorage),// 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.diff --git a/src/stores/memoryStore.ts b/src/stores/memoryStore.tsindex bd15d9e2..2e70e47e 100644--- a/src/stores/memoryStore.ts+++ b/src/stores/memoryStore.ts@@ -3,7 +3,7 @@ import { persist, createJSONStorage } from 'zustand/middleware'import { v4 as uuid } from 'uuid'import type { MemoryEntry, MemoryCategory, MemoryFile, MemoryType, MemorySettings } from '../types/agent-mode'import { MEMORY_MIGRATION_MAP, MEMORY_BUDGET_TIERS } from '../types/agent-mode'-import { createSafeStorage } from '../lib/storage-quota'+import { idbStorage } from '../lib/idbStorage'import { generateEmbeddings } from '../api/rag'import { saveVector, loadVectors, deleteVector, clearAll as clearAllVectors, type MemoryVectorRecord } from '../lib/memoryEmbedDB'import { scoreMemoriesBlended, isStale, type BlendCandidate } from '../lib/memory-retrieval'@@ -674,11 +674,11 @@ export const useMemoryStore = create<MemoryState>()(// bump exists only to run migrateV2toV3 so the shape is explicit and// future migrations have a clean baseline.version: 3,- // zustand v5: wrap the STRING-based createSafeStorage in createJSONStorage,- // else zustand passes the {state,version} object to setItem → "[object Object]"- // → memories never hydrate and are wiped on restart (v2.5.0 regression). Same- // root cause + fix as chatStore.- storage: createJSONStorage(() => createSafeStorage()),+ // IndexedDB (idbStorage) instead of localStorage — memories + their growth+ // shouldn't be capped at ~5 MB; idb is disk-backed and migrates existing+ // localStorage data on first read. createJSONStorage wrap still required+ // (zustand v5 PersistStorage; raw StateStorage → "[object Object]", FIX-3).+ storage: createJSONStorage(() => idbStorage),migrate: (persistedState, version) => {let state: any = persistedStateif (version < 2) {