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
fix(persist): one failed IndexedDB open stopped saving chats for the session
purple7801f4d713d1
diff --git a/src/lib/__tests__/idbStorage-retry.test.ts b/src/lib/__tests__/idbStorage-retry.test.tsnew file mode 100644index 00000000..32e1bd97--- /dev/null+++ b/src/lib/__tests__/idbStorage-retry.test.ts@@ -0,0 +1,125 @@+/**+ * Persist backend must recover from a failed IndexedDB open (2026-07-28)+ *+ * getDB() cached the promise it returned — including a REJECTED one. A single+ * transient open failure (a second window blocking an upgrade, a busy profile+ * directory) therefore poisoned every later read and write for the rest of the+ * session: chat history quietly stopped being saved until the app restarted.+ *+ * Run: npx vitest run src/lib/__tests__/idbStorage-retry.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'++type OpenReq = {+ onsuccess: (() => void) | null+ onerror: (() => void) | null+ onblocked: (() => void) | null+ onupgradeneeded: (() => void) | null+ result: any+ error: any+}++/** Minimal fake IDB: `failures` opens reject, everything after succeeds. */+function fakeIndexedDB(failures: number, data: Record<string, string>) {+ let opens = 0+ const db = {+ objectStoreNames: { contains: () => true },+ createObjectStore: () => {},+ transaction: () => ({+ objectStore: () => ({+ get: (k: string) => {+ const r: any = { onsuccess: null, onerror: null, result: data[k] }+ queueMicrotask(() => r.onsuccess?.())+ 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 {+ opens: () => opens,+ open: () => {+ opens+++ const req: OpenReq = {+ onsuccess: null,+ onerror: null,+ onblocked: null,+ onupgradeneeded: null,+ result: db,+ error: new Error('open failed'),+ }+ const shouldFail = opens <= failures+ queueMicrotask(() => (shouldFail ? req.onerror?.() : req.onsuccess?.()))+ return req+ },+ }+}++/** The vitest env is node — no DOM storage. */+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, v),+ removeItem: (k: string) => void mem.delete(k),+ clear: () => mem.clear(),+ }+}++describe('idbStorage after a failed open', () => {+ let ls: ReturnType<typeof fakeLocalStorage>++ beforeEach(() => {+ vi.resetModules()+ ls = fakeLocalStorage()+ vi.stubGlobal('localStorage', ls)+ })++ afterEach(() => {+ vi.unstubAllGlobals()+ })++ it('opens again on the next call instead of failing forever', async () => {+ const data: Record<string, string> = { 'chat-conversations': '{"kept":true}' }+ const fake = fakeIndexedDB(1, data)+ vi.stubGlobal('indexedDB', fake)++ const { idbStorage } = await import('../idbStorage')++ // First read hits the failing open and degrades to localStorage (empty).+ const first = await idbStorage.getItem('chat-conversations')+ expect(first).toBeNull()++ // Second read must open a NEW connection, not reuse the rejected promise.+ const second = await idbStorage.getItem('chat-conversations')+ expect(second).toBe('{"kept":true}')+ expect(fake.opens()).toBe(2)+ })++ it('writes reach IndexedDB again after a failed open', async () => {+ const data: Record<string, string> = {}+ const fake = fakeIndexedDB(1, data)+ vi.stubGlobal('indexedDB', fake)++ const { idbStorage } = await import('../idbStorage')++ await idbStorage.setItem('chat-conversations', 'first')+ // The failed open pushed this into localStorage.+ expect(ls.getItem('chat-conversations')).toBe('first')++ await idbStorage.setItem('chat-conversations', 'second')+ expect(data['chat-conversations']).toBe('second')+ })+})diff --git a/src/lib/idbStorage.ts b/src/lib/idbStorage.tsindex 4ec0b201..9cb76c46 100644--- a/src/lib/idbStorage.ts+++ b/src/lib/idbStorage.ts@@ -28,6 +28,7 @@* does the object<->string (de)serialisation around this string StateStorage.*/import type { StateStorage } from 'zustand/middleware'+import { log } from './logger'const DB_NAME = 'locally-uncensored-store'const STORE = 'kv'@@ -54,7 +55,7 @@ const hasIDB: boolean = (() => {let _db: Promise<IDBDatabase> | null = nullfunction getDB(): Promise<IDBDatabase> {if (_db) return _db- _db = new Promise<IDBDatabase>((resolve, reject) => {+ const opening = new Promise<IDBDatabase>((resolve, reject) => {const req = indexedDB.open(DB_NAME, DB_VERSION)req.onupgradeneeded = () => {const db = req.result@@ -64,7 +65,16 @@ function getDB(): Promise<IDBDatabase> {req.onerror = () => reject(req.error)req.onblocked = () => reject(new Error('indexedDB open blocked'))})- return _db+ _db = opening+ // A FAILED open must not stay cached. Keeping the rejected promise meant one+ // transient failure — a second window blocking the upgrade, a momentarily+ // busy profile dir — turned into "every read and write fails for the rest of+ // the session", i.e. the user's chats silently stopped being saved until+ // restart. Dropping it lets the next call open again.+ opening.catch(() => {+ if (_db === opening) _db = null+ })+ return opening}function idbGet(key: string): Promise<string | null> {@@ -131,8 +141,22 @@ export const idbStorage: StateStorage = {try {await idbSet(name, value)lsDel(name) // drop the migrated localStorage copy → frees the 5 MB cap- } catch {+ } catch (err) {+ // Say it out loud. localStorage swallows its own quota errors, so if+ // this fallback also fails nothing anywhere would ever mention that the+ // user's chats are no longer being saved — they would simply be gone+ // after the next launch.+ log.warn('[idbStorage] IndexedDB write failed, falling back to localStorage', {+ key: name,+ err: String(err),+ })lsSet(name, value) // idb write failed → localStorage best-effort+ if (lsGet(name) !== value) {+ log.error('[idbStorage] BOTH backends failed — this state is NOT being persisted', {+ key: name,+ bytes: value.length,+ })+ }}})()},