Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(gallery): the gallery list moves to IndexedDB without the 200 cap (C27)

purple4d05f4a64169
diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx
index 623aa5d1..aa64baa9 100644
--- a/src/components/layout/AppShell.tsx
+++ b/src/components/layout/AppShell.tsx
@@ -69,6 +69,7 @@ import { ChatRescueHint } from './ChatRescueHint'
import { HfLinkInbox } from '../models/HfLinkInbox'
import { useNeuronFollowsPersona } from '../../hooks/useNeuronFollowsPersona'
import { NEURONS_ENABLED } from '../../lib/features'
+import { startGalleryStore } from '../../lib/gallery-persist-wiring'
// Aus der Komponente herausgezogen: `new Set(STORE_KEYS)` entstand bei jedem
// Render neu und war damit die instabile Referenz, wegen der der Restore-Effekt
@@ -640,6 +641,10 @@ export function AppShell() {
// state over the only good store_backup.json.
await restoreDecided
if (disposed) return
+ // The gallery list to IndexedDB (3.1.0, C27), after the restore above
+ // wrote its copy back. Its failure keeps the old way and must not cost
+ // the backups below.
+ void startGalleryStore().catch(() => {})
let backupInflight = false
const doBackup = async () => {
diff --git a/src/lib/__tests__/gallery-persist.test.ts b/src/lib/__tests__/gallery-persist.test.ts
new file mode 100644
index 00000000..6b69e467
--- /dev/null
+++ b/src/lib/__tests__/gallery-persist.test.ts
@@ -0,0 +1,318 @@
+/**
+ * C27 (3.1.0): the gallery list moves from the create-store blob in
+ * localStorage (cap 200) to its own IndexedDB key, without a cap.
+ *
+ * After the chat loss of 3.0.9 the rule for this move is: nothing a user made
+ * may get lost on the way, also not when the app dies in the middle of it.
+ * These tests run the move against a storage that can fail to read, fail to
+ * write and lose a write (a kill), and check every entry each time.
+ *
+ * Run: npx vitest run src/lib/__tests__/gallery-persist.test.ts
+ */
+import { describe, expect, it } from 'vitest'
+import {
+ GALLERY_BEFORE_MOVE_KEY, GALLERY_KEY, MIRROR_SORTED, MIRROR_UNSORTED, DELETED_KEPT,
+ downgradeMirror, joinAtStart, joinGalleries, rememberDeleted, sanitizeEntries, startGalleryPersistence,
+ storedForm, type StoredEntry,
+} from '../gallery-persist'
+
+interface Entry extends StoredEntry {
+ prompt: string
+ dataUrl?: string
+ unavailable?: boolean
+}
+
+const entry = (n: number, extra: Partial<Entry> = {}): Entry => ({ id: `g${n}`, createdAt: n, prompt: `prompt ${n}`, ...extra })
+const range = (from: number, count: number, extra: Partial<Entry> = {}) => Array.from({ length: count }, (_, i) => entry(from + count - 1 - i, extra))
+const ids = (items: readonly StoredEntry[]) => items.map((g) => g.id)
+
+/** An async key/value storage like idbStorage, with the ways it can go wrong. */
+function memStorage(seed: Record<string, string> = {}) {
+ const data = new Map(Object.entries(seed))
+ const failed = new Set<string>()
+ const ctl = {
+ data,
+ /** Reads of these keys fail (idbStorage latches them in hasFailedRead). */
+ failReads: new Set<string>(),
+ /** Writes of these keys throw. */
+ failWrites: new Set<string>(),
+ /** Writes report success and land nowhere: the app was killed. */
+ killed: false,
+ writes: [] as string[],
+ }
+ const storage = {
+ getItem: async (k: string) => {
+ if (ctl.failReads.has(k)) { failed.add(k); return null }
+ failed.delete(k)
+ return data.get(k) ?? null
+ },
+ setItem: async (k: string, v: string) => {
+ if (ctl.failWrites.has(k)) throw new Error('disk full')
+ if (ctl.killed) return
+ ctl.writes.push(k)
+ data.set(k, v)
+ },
+ removeItem: async (k: string) => { data.delete(k) },
+ }
+ return { storage, readFailed: (k: string) => failed.has(k), ctl }
+}
+
+/** The create store as far as the move sees it. */
+function fakeStore(initial: Entry[]) {
+ let items = initial
+ const listeners = new Set<(n: Entry[], p: Entry[]) => void>()
+ const store = {
+ uncapped: false,
+ getItems: () => items,
+ setItems: (next: Entry[]) => {
+ const prev = items
+ items = next
+ for (const l of listeners) l(next, prev)
+ },
+ subscribe: (l: (n: Entry[], p: Entry[]) => void) => { listeners.add(l); return () => { listeners.delete(l) } },
+ setUncapped: (on: boolean) => { store.uncapped = on },
+ }
+ return store
+}
+
+function stored(ctl: { data: Map<string, string> }): Entry[] | null {
+ const raw = ctl.data.get(GALLERY_KEY)
+ return raw ? (JSON.parse(raw).state.items as Entry[]) : null
+}
+
+async function start(mem: ReturnType<typeof memStorage>, store: ReturnType<typeof fakeStore>, hydrated?: Entry[]) {
+ return startGalleryPersistence<Entry>({
+ storage: mem.storage,
+ readFailed: mem.readFailed,
+ durable: true,
+ getItems: store.getItems,
+ hydratedItems: hydrated ? () => hydrated : undefined,
+ setItems: store.setItems,
+ subscribe: store.subscribe,
+ setUncapped: store.setUncapped,
+ waitMs: 0,
+ })
+}
+
+describe('the first move', () => {
+ it('keeps the old list as it was, then stores every entry and checks it', async () => {
+ const legacy = [...range(1, 150), ...range(500, 40, { folderId: 'f-1' })]
+ const mem = memStorage()
+ const store = fakeStore(legacy)
+ const h = await start(mem, store)
+ expect(h.state).toBe('saved')
+ expect(store.uncapped).toBe(true)
+ // The copy by hand comes first and is the old list, word for word.
+ expect(mem.ctl.writes[0]).toBe(GALLERY_BEFORE_MOVE_KEY)
+ expect(JSON.parse(mem.ctl.data.get(GALLERY_BEFORE_MOVE_KEY)!)).toEqual(legacy)
+ expect(new Set(ids(stored(mem.ctl)!))).toEqual(new Set(ids(legacy)))
+ expect(stored(mem.ctl)!.find((g) => g.id === 'g520')).toEqual(entry(520, { folderId: 'f-1' }))
+ })
+
+ it('an empty gallery writes no copy and still moves', async () => {
+ const mem = memStorage()
+ const h = await start(mem, fakeStore([]))
+ expect(h.state).toBe('saved')
+ expect(mem.ctl.data.has(GALLERY_BEFORE_MOVE_KEY)).toBe(false)
+ expect(stored(mem.ctl)).toEqual([])
+ })
+
+ it('never stores runtime fields', async () => {
+ const mem = memStorage()
+ await start(mem, fakeStore([entry(1, { dataUrl: 'blob:x', unavailable: true })]))
+ expect(stored(mem.ctl)![0]).toEqual(entry(1))
+ })
+})
+
+describe('no cap after the move', () => {
+ it('3000 stored plus the 200 copy: all 3000 and the new ones, nothing dropped', async () => {
+ const big = range(1, 3000)
+ const mem = memStorage({ [GALLERY_KEY]: JSON.stringify({ state: { items: big }, version: 1 }) })
+ // The create-store copy: the newest 200, plus 5 renders an older build made after a downgrade.
+ const copy = [...range(5001, 5), ...big.slice(0, 200)]
+ const store = fakeStore(copy)
+ const h = await start(mem, store)
+ expect(h.state).toBe('saved')
+ expect(store.getItems()).toHaveLength(3005)
+ expect(ids(store.getItems()).slice(0, 6)).toEqual(['g5005', 'g5004', 'g5003', 'g5002', 'g5001', 'g3000'])
+ expect(stored(mem.ctl)).toHaveLength(3005)
+ // Nothing was copied aside: there was a stored list already.
+ expect(mem.ctl.data.has(GALLERY_BEFORE_MOVE_KEY)).toBe(false)
+ })
+
+ it('every later change is written, many changes in one write', async () => {
+ const mem = memStorage()
+ const store = fakeStore(range(1, 3))
+ const h = await start(mem, store)
+ const before = mem.ctl.writes.length
+ for (let i = 0; i < 50; i++) store.setItems([entry(100 + i), ...store.getItems()])
+ await h.flush()
+ expect(mem.ctl.writes.length - before).toBe(1)
+ expect(stored(mem.ctl)).toHaveLength(53)
+ })
+})
+
+describe('a read that failed', () => {
+ it('writes nothing and keeps the cap', async () => {
+ const original = JSON.stringify({ state: { items: range(1, 900) }, version: 1 })
+ const mem = memStorage({ [GALLERY_KEY]: original })
+ mem.ctl.failReads.add(GALLERY_KEY)
+ const store = fakeStore(range(1000, 200))
+ const h = await start(mem, store)
+ expect(h.state).toBe('unreadable')
+ expect(store.uncapped).toBe(false)
+ expect(mem.ctl.writes).toEqual([])
+ expect(mem.ctl.data.get(GALLERY_KEY)).toBe(original)
+ // Later changes are not written either.
+ store.setItems([entry(5000), ...store.getItems()])
+ await h.flush()
+ expect(mem.ctl.writes).toEqual([])
+ })
+
+ it('a damaged value is set aside, never written over', async () => {
+ const mem = memStorage({ [GALLERY_KEY]: '{"state": {"items": [trunc' })
+ const store = fakeStore(range(1, 10))
+ const h = await start(mem, store)
+ expect(h.state).toBe('saved')
+ const aside = [...mem.ctl.data.keys()].find((k) => k.startsWith(`${GALLERY_KEY}-damaged-`))
+ expect(aside).toBeDefined()
+ expect(mem.ctl.data.get(aside!)).toBe('{"state": {"items": [trunc')
+ expect(stored(mem.ctl)).toHaveLength(10)
+ })
+})
+
+describe('killed in the middle of the move', () => {
+ it('before the list landed: the next start moves it again, nothing lost, the copy is not replaced', async () => {
+ const legacy = range(1, 120)
+ const mem = memStorage()
+ // The copy lands, then the app dies: the list write and everything after it go nowhere.
+ const realSet = mem.storage.setItem
+ let n = 0
+ mem.storage.setItem = async (k, v) => { n++; if (n > 1) mem.ctl.killed = true; return realSet(k, v) }
+ const first = await start(mem, fakeStore(legacy))
+ expect(first.state).toBe('unconfirmed')
+ expect(mem.ctl.data.has(GALLERY_KEY)).toBe(false)
+ expect(JSON.parse(mem.ctl.data.get(GALLERY_BEFORE_MOVE_KEY)!)).toHaveLength(120)
+
+ // Next launch: the create-store copy is still the old list, plus one render.
+ mem.storage.setItem = realSet
+ mem.ctl.killed = false
+ const second = fakeStore([entry(999), ...legacy])
+ const h = await start(mem, second)
+ expect(h.state).toBe('saved')
+ expect(stored(mem.ctl)).toHaveLength(121)
+ // The copy by hand is still the list from before the first move.
+ expect(JSON.parse(mem.ctl.data.get(GALLERY_BEFORE_MOVE_KEY)!)).toHaveLength(120)
+ })
+
+ it('after the list landed, before the check: the next start joins without doubles', async () => {
+ const legacy = range(1, 120)
+ const mem = memStorage()
+ await start(mem, fakeStore(legacy))
+ const h = await start(mem, fakeStore(legacy))
+ expect(h.state).toBe('saved')
+ expect(stored(mem.ctl)).toHaveLength(120)
+ expect(new Set(ids(stored(mem.ctl)!)).size).toBe(120)
+ })
+
+ it('the copy by hand cannot be written: no move, the old way holds', async () => {
+ const legacy = range(1, 50)
+ const mem = memStorage()
+ mem.ctl.failWrites.add(GALLERY_BEFORE_MOVE_KEY)
+ const store = fakeStore(legacy)
+ const h = await start(mem, store)
+ expect(h.state).toBe('unreadable')
+ expect(store.uncapped).toBe(false)
+ expect(mem.ctl.data.has(GALLERY_KEY)).toBe(false)
+ expect(store.getItems()).toBe(legacy)
+ })
+
+ it('the list write throws: it stays in memory without the cap and is written on the next change', async () => {
+ const mem = memStorage()
+ mem.ctl.failWrites.add(GALLERY_KEY)
+ const store = fakeStore(range(1, 30))
+ const h = await start(mem, store)
+ expect(h.state).toBe('unconfirmed')
+ expect(store.getItems()).toHaveLength(30)
+ mem.ctl.failWrites.delete(GALLERY_KEY)
+ store.setItems([entry(77), ...store.getItems()])
+ expect(await h.verify()).toBe(true)
+ expect(stored(mem.ctl)).toHaveLength(31)
+ })
+})
+
+describe('what changed in the app wins', () => {
+ it('a deleted entry does not come back from the create-store copy', async () => {
+ const mem = memStorage()
+ const store = fakeStore(range(1, 5))
+ const h = await start(mem, store)
+ store.setItems(store.getItems().filter((g) => g.id !== 'g3'))
+ await h.flush()
+ h.stop()
+ // The copy in localStorage missed that write (quota) and still has g3.
+ const next = fakeStore(range(1, 5))
+ await start(mem, next)
+ expect(ids(next.getItems())).not.toContain('g3')
+ })
+
+ it('a change made before the move ran is kept over the stored entry', async () => {
+ const mem = memStorage({ [GALLERY_KEY]: JSON.stringify({ state: { items: range(1, 4) }, version: 1 }) })
+ const atLaunch = range(1, 4)
+ // Moved to a folder and one removed, while the restore was still deciding.
+ const now = atLaunch.filter((g) => g.id !== 'g2').map((g) => (g.id === 'g4' ? { ...g, folderId: 'f-9' } : g))
+ const store = fakeStore(now)
+ await start(mem, store, atLaunch)
+ expect(ids(store.getItems())).toEqual(['g4', 'g3', 'g1'])
+ expect(store.getItems()[0].folderId).toBe('f-9')
+ })
+})
+
+describe('the parts', () => {
+ it('joinGalleries keeps every entry of both sides', () => {
+ const { items, added } = joinGalleries(range(1, 3), [...range(2, 3), entry(9)])
+ expect(ids(items)).toEqual(['g9', 'g4', 'g3', 'g2', 'g1'])
+ expect(added).toBe(2)
+ })
+
+ it('joinAtStart without a stored list keeps memory as it is', () => {
+ const memory = range(1, 3)
+ expect(joinAtStart({ stored: null, memory, hydrated: memory, deleted: [] }).items).toEqual(memory)
+ })
+
+ it('downgradeMirror keeps the newest unsorted and sorted entries, hidden ones last', () => {
+ const items = [
+ ...range(10000, MIRROR_UNSORTED + 50),
+ ...range(5000, MIRROR_SORTED + 50, { folderId: 'f' }),
+ ...range(1, 10, { hidden: true }),
+ ]
+ const m = downgradeMirror(items)
+ expect(m.filter((g) => !g.folderId)).toHaveLength(MIRROR_UNSORTED)
+ expect(m.filter((g) => g.folderId)).toHaveLength(MIRROR_SORTED)
+ expect(m.some((g) => g.hidden)).toBe(false)
+ expect(m[0].id).toBe(`g${10000 + MIRROR_UNSORTED + 49}`)
+ // A small list is the copy itself.
+ const small = range(1, 20)
+ expect(downgradeMirror(small)).toBe(small)
+ })
+
+ it('rememberDeleted keeps the newest ids only', () => {
+ const many = Array.from({ length: DELETED_KEPT + 10 }, (_, i) => `d${i}`)
+ const kept = rememberDeleted([], many)
+ expect(kept).toHaveLength(DELETED_KEPT)
+ expect(kept[kept.length - 1]).toBe(`d${DELETED_KEPT + 9}`)
+ })
+
+ it('sanitizeEntries keeps unknown fields and drops only what cannot be an entry', () => {
+ const out = sanitizeEntries<Entry>([
+ entry(1, { prompt: 'x' }), null, 'nope', { createdAt: 3 }, { id: 'g1', createdAt: 9 },
+ { id: 'g5', createdAt: 'later', future: { a: 1 }, tags: ['a', 'A', 7, ' b '], hidden: 'yes' },
+ ])
+ expect(ids(out)).toEqual(['g1', 'g5'])
+ expect(out[1]).toEqual({ id: 'g5', createdAt: 0, future: { a: 1 }, tags: ['a', 'b'] })
+ })
+
+ it('storedForm leaves an entry without runtime fields as the same object', () => {
+ const e = entry(1)
+ expect(storedForm(e)).toBe(e)
+ })
+})
diff --git a/src/lib/__tests__/gallery-tags.test.ts b/src/lib/__tests__/gallery-tags.test.ts
new file mode 100644
index 00000000..add893e9
--- /dev/null
+++ b/src/lib/__tests__/gallery-tags.test.ts
@@ -0,0 +1,61 @@
+/**
+ * Tags and hiding in the gallery (D27, 3.1.0): the pure rules.
+ *
+ * Run: npx vitest run src/lib/__tests__/gallery-tags.test.ts
+ */
+import { describe, expect, it } from 'vitest'
+import { TAG_MAX, TAGS_PER_ITEM, cleanTag, hasTag, hiddenCount, itemsInView, sanitizeTags, tagCounts, withTag, withoutTag } from '../gallery-tags'
+
+describe('tags', () => {
+ it('cleanTag drops a leading #, folds spaces, cuts long ones, refuses empty ones', () => {
+ expect(cleanTag(' #My tag ')).toBe('My tag')
+ expect(cleanTag('##')).toBeNull()
+ expect(cleanTag('x'.repeat(TAG_MAX + 9))).toHaveLength(TAG_MAX)
+ })
+
+ it('withTag ignores case for doubles and stops at the limit', () => {
+ let tags: string[] | undefined
+ tags = withTag(tags, 'Cat')
+ expect(withTag(tags, 'cat')).toBe(tags)
+ for (let i = 0; i < 20; i++) tags = withTag(tags, `t${i}`)
+ expect(tags).toHaveLength(TAGS_PER_ITEM)
+ })
+
+ it('withoutTag gives undefined once the last tag is gone', () => {
+ expect(withoutTag(['a'], 'A')).toBeUndefined()
+ const same = ['a']
+ expect(withoutTag(same, 'b')).toBe(same)
+ })
+
+ it('sanitizeTags keeps clean strings only', () => {
+ expect(sanitizeTags(['a', 3, null, 'A', ''])).toEqual(['a'])
+ expect(sanitizeTags('a')).toBeUndefined()
+ })
+
+ it('tagCounts sorts by use, then by name', () => {
+ expect(tagCounts([{ tags: ['b', 'a'] }, { tags: ['B'] }, {}])).toEqual([{ tag: 'b', count: 2 }, { tag: 'a', count: 1 }])
+ })
+})
+
+describe('the view', () => {
+ const items = [
+ { id: '1', tags: ['x'] },
+ { id: '2', hidden: true, tags: ['x'] },
+ { id: '3', folderId: 'f' },
+ { id: '4', folderId: 'f', tags: ['X'] },
+ ]
+ const view = (v: Partial<{ folderId: string | null; tag: string | null; hidden: boolean }>) =>
+ itemsInView(items, { folderId: null, tag: null, hidden: false, ...v }).map((g) => g.id)
+
+ it('hidden entries only in the Hidden view', () => {
+ expect(view({})).toEqual(['1', '3', '4'])
+ expect(view({ hidden: true })).toEqual(['2'])
+ expect(hiddenCount(items)).toBe(1)
+ })
+
+ it('folder and tag filter together', () => {
+ expect(view({ tag: 'x' })).toEqual(['1', '4'])
+ expect(view({ folderId: 'f', tag: 'x' })).toEqual(['4'])
+ expect(hasTag(items[3], 'x')).toBe(true)
+ })
+})
diff --git a/src/lib/gallery-persist-wiring.ts b/src/lib/gallery-persist-wiring.ts
new file mode 100644
index 00000000..735b6b3b
--- /dev/null
+++ b/src/lib/gallery-persist-wiring.ts
@@ -0,0 +1,60 @@
+// The gallery list on IndexedDB in the app (lib/gallery-persist.ts has the
+// why and the steps). Started once the restore at launch has decided
+// (components/layout/AppShell.tsx, mobile/boot/backup.ts): a restore writes
+// `lu-gallery` back from the appData backup first, and the move must read that
+// value, not write the short list of the create-store blob in front of it.
+
+import { idbStorage, hasFailedRead } from './idbStorage'
+import { log } from './logger'
+import { useCreateStore, setGalleryUncapped, type GalleryItem } from '../stores/createStore'
+import { startGalleryPersistence, type GalleryPersistState, type GalleryPersistence } from './gallery-persist'
+
+// The list as the create-store blob gave it. The create store hydrates from
+// localStorage synchronously, so this is read after hydration.
+const atLaunch: GalleryItem[] = useCreateStore.getState().gallery
+
+let running: Promise<GalleryPersistence> | null = null
+let current: GalleryPersistence | null = null
+
+/** Start the move and the writes. Runs once; later calls get the same handle. */
+export function startGalleryStore(): Promise<GalleryPersistence> {
+ running ??= startGalleryPersistence<GalleryItem>({
+ storage: idbStorage,
+ readFailed: hasFailedRead,
+ durable: typeof indexedDB !== 'undefined' && indexedDB !== null,
+ getItems: () => useCreateStore.getState().gallery,
+ hydratedItems: () => atLaunch,
+ setItems: (gallery) => useCreateStore.setState({ gallery }),
+ subscribe: (listener) => useCreateStore.subscribe((s, prev) => {
+ if (s.gallery !== prev.gallery) listener(s.gallery, prev.gallery)
+ }),
+ setUncapped: setGalleryUncapped,
+ }).then((handle) => {
+ current = handle
+ log.info('[gallery] gallery storage', { state: handle.state })
+ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
+ // Best effort on the way out, like the chats: the window does not wait
+ // for an IndexedDB write. The small copy in localStorage covers the rest.
+ window.addEventListener('pagehide', () => { void handle.flush() })
+ document.addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'hidden') void handle.flush()
+ })
+ }
+ return handle
+ }, (err: unknown) => {
+ log.error('[gallery] starting the gallery storage failed, keeping the old way', { err: String(err) })
+ running = null
+ throw err
+ })
+ return running
+}
+
+/** Write a pending change of the gallery now. */
+export function flushGalleryStore(): Promise<void> {
+ return current ? current.flush() : Promise.resolve()
+}
+
+/** How the gallery is stored right now. */
+export function galleryStoreState(): GalleryPersistState {
+ return current?.state ?? 'waiting'
+}
diff --git a/src/lib/gallery-persist.ts b/src/lib/gallery-persist.ts
new file mode 100644
index 00000000..67509737
--- /dev/null
+++ b/src/lib/gallery-persist.ts
@@ -0,0 +1,349 @@
+// The gallery list on IndexedDB, without the cap (3.1.0, C27).
+//
+// boromirofgeo, Discord 05.11. and 06.11.2026: "200 not enough", after the
+// gallery had dropped his sorted folders (D3b). Until 3.1.0 the list sat in the
+// create-store blob in localStorage, about 5 MB for the whole origin, so it was
+// cut at 200 unsorted entries.
+//
+// Now the full list lives under its own IndexedDB key, `lu-gallery`, written
+// through lib/idbStorage like the chats: the same read-failure latch (a list
+// that could not be read is never written over), the same appData backup
+// (lib/store-backup STORE_KEYS) and the same restore after a wiped profile.
+//
+// The way over, safe at every step (tests: gallery-persist*.test.ts):
+// 1. Read `lu-gallery`. A read that failed stops here: the old way stays,
+// cap and all, and nothing is written. Next start tries again.
+// 2. Nothing there yet and an old list in memory: that list is written once
+// to `lu-gallery-before-310` as it was, before anything else happens.
+// 3. The stored list and the one in memory are joined by id. Nothing is
+// dropped: an entry in either side is in the result, unless it was
+// deleted in the app since (`deleted`, kept for this purpose).
+// 4. Written, then read back and checked entry by entry. Only then is the
+// move called done.
+// 5. The create-store blob keeps a small copy, the newest entries
+// (downgradeMirror). It is what an older LU reads after a downgrade, and
+// what step 3 joins back in after an upgrade. It replaces the old list in
+// place, so there is no separate delete that could come too early.
+// A kill anywhere in between leaves either the old list (steps 1 to 3) or both
+// (4, 5), and the next start runs the same steps over what it finds.
+
+import type { StateStorage } from 'zustand/middleware'
+import { coalescedJSONStorage, type CoalescedStorage } from './coalescedStorage'
+import { log } from './logger'
+import { sanitizeTags } from './gallery-tags'
+
+export const GALLERY_KEY = 'lu-gallery'
+/** The old list, exactly as it was before the first move. Written once, never
+ * overwritten, never read by the app: the way back by hand. */
+export const GALLERY_BEFORE_MOVE_KEY = 'lu-gallery-before-310'
+/** Version of the stored value. */
+export const GALLERY_DOC_VERSION = 1
+
+/** Entries an older LU keeps in the create-store copy: unsorted ones. */
+export const MIRROR_UNSORTED = 200
+/** And entries in folders. The old cap kept every one of those; the copy
+ * keeps the newest 300, so the blob stays within localStorage. */
+export const MIRROR_SORTED = 300
+/** Ids of deleted entries kept so the copy cannot bring them back. */
+export const DELETED_KEPT = 5000
+
+/** Fields that only exist while the app runs (createStore partialize strips
+ * the same ones). */
+const RUNTIME_FIELDS = ['dataUrl', 'unavailable', 'unavailableReason', 'reloadKey'] as const
+
+/** The least an entry needs for this module. */
+export interface StoredEntry {
+ id: string
+ createdAt: number
+ folderId?: string
+ hidden?: boolean
+ tags?: string[]
+}
+
+export interface GalleryDoc<T extends StoredEntry> {
+ items: T[]
+ /** Ids deleted in the app, newest last. */
+ deleted?: string[]
+}
+
+/** An entry as it is stored: without its runtime fields. */
+export function storedForm<T extends StoredEntry>(item: T): T {
+ if (!RUNTIME_FIELDS.some((k) => k in item)) return item
+ const copy: Record<string, unknown> = { ...(item as object) }
+ for (const k of RUNTIME_FIELDS) delete copy[k]
+ return copy as unknown as T
+}
+
+/**
+ * Entries read back from storage. Only what cannot be an entry at all goes (no
+ * object, no id); every other field is kept as written, so nothing a user made
+ * is thrown away for a field this version does not know. Doubles keep the
+ * first. Tags and the hidden flag are cleaned, they are read by this code.
+ */
+export function sanitizeEntries<T extends StoredEntry>(raw: unknown): T[] {
+ if (!Array.isArray(raw)) return []
+ const out: T[] = []
+ const seen = new Set<string>()
+ for (const r of raw) {
+ if (!r || typeof r !== 'object' || Array.isArray(r)) continue
+ const e = r as Record<string, unknown>
+ if (typeof e.id !== 'string' || !e.id || seen.has(e.id)) continue
+ seen.add(e.id)
+ const fixed: Record<string, unknown> = { ...e }
+ if (typeof fixed.createdAt !== 'number' || !Number.isFinite(fixed.createdAt)) fixed.createdAt = 0
+ if ('hidden' in fixed && typeof fixed.hidden !== 'boolean') delete fixed.hidden
+ if ('tags' in fixed) {
+ const tags = sanitizeTags(fixed.tags)
+ if (tags) fixed.tags = tags
+ else delete fixed.tags
+ }
+ out.push(fixed as unknown as T)
+ }
+ return out
+}
+
+/** Newest first; equal times keep their order. */
+export function newestFirst<T extends StoredEntry>(items: readonly T[]): T[] {
+ return items
+ .map((g, i) => ({ g, i }))
+ .sort((a, b) => b.g.createdAt - a.g.createdAt || a.i - b.i)
+ .map(({ g }) => g)
+}
+
+/**
+ * Join two lists by id. Every entry of `primary` stays as it is; an entry of
+ * `other` comes in when `primary` does not have its id and it was not deleted.
+ * The result is newest first. `added` counts what came from `other`.
+ */
+export function joinGalleries<T extends StoredEntry>(
+ primary: readonly T[],
+ other: readonly T[],
+ deleted: Iterable<string> = [],
+): { items: T[]; added: number } {
+ const have = new Set(primary.map((g) => g.id))
+ const gone = new Set(deleted)
+ const extra = other.filter((g) => !have.has(g.id) && !gone.has(g.id))
+ if (extra.length === 0) return { items: primary as T[], added: 0 }
+ return { items: newestFirst([...primary, ...extra]), added: extra.length }
+}
+
+/**
+ * Step 3 with what happened in this session before it ran. `hydrated` is the
+ * list as the create-store blob gave it at launch, `memory` the list now. An
+ * entry changed since launch (moved, tagged, hidden: a new object) wins over
+ * the stored one; an entry removed since launch is deleted here too, so the
+ * stored list cannot bring it back.
+ */
+export function joinAtStart<T extends StoredEntry>(args: {
+ stored: readonly T[] | null
+ memory: readonly T[]
+ hydrated: readonly T[]
+ deleted: readonly string[]
+}): { items: T[]; deleted: string[]; added: number } {
+ const { stored, memory, hydrated } = args
+ const memIds = new Set(memory.map((g) => g.id))
+ const deleted = rememberDeleted(args.deleted, hydrated.filter((g) => !memIds.has(g.id)).map((g) => g.id))
+ if (!stored) return { items: newestFirst(memory), deleted, added: 0 }
+ const atLaunch = new Map(hydrated.map((g) => [g.id, g]))
+ const changed = new Map(memory.filter((g) => atLaunch.has(g.id) && atLaunch.get(g.id) !== g).map((g) => [g.id, g]))
+ const gone = new Set(deleted)
+ const primary = stored.filter((g) => !gone.has(g.id)).map((g) => changed.get(g.id) ?? g)
+ const { items, added } = joinGalleries(primary, memory, deleted)
+ return { items, deleted, added }
+}
+
+/**
+ * The small copy in the create-store blob (step 5 above): the newest
+ * MIRROR_UNSORTED unsorted entries and the newest MIRROR_SORTED in folders,
+ * hidden ones last in line. `items` is newest first.
+ */
+export function downgradeMirror<T extends StoredEntry>(items: readonly T[]): T[] {
+ const out: T[] = []
+ let unsorted = 0
+ let sorted = 0
+ for (const pass of [false, true]) {
+ for (const g of items) {
+ if (!!g.hidden !== pass) continue
+ if (g.folderId) { if (sorted < MIRROR_SORTED) { out.push(g); sorted++ } }
+ else if (unsorted < MIRROR_UNSORTED) { out.push(g); unsorted++ }
+ }
+ }
+ return out.length === items.length ? (items as T[]) : newestFirst(out)
+}
+
+/** `deleted` with `ids` added, the oldest dropped past DELETED_KEPT. */
+export function rememberDeleted(deleted: readonly string[], ids: readonly string[]): string[] {
+ if (ids.length === 0) return deleted as string[]
+ const fresh = new Set(ids)
+ const next = [...deleted.filter((id) => !fresh.has(id)), ...ids]
+ return next.length > DELETED_KEPT ? next.slice(next.length - DELETED_KEPT) : next
+}
+
+/** What the move came to; for the log, the panel and the tests. */
+export type GalleryPersistState =
+ /** Not started, or waiting for the restore decision. The old way holds. */
+ | 'waiting'
+ /** `lu-gallery` could not be read. The old way holds, nothing is written. */
+ | 'unreadable'
+ /** No IndexedDB here. The old way holds. */
+ | 'unavailable'
+ /** Written and read back entry by entry. No cap. */
+ | 'saved'
+ /** Running without the cap, but the last check did not find every entry. */
+ | 'unconfirmed'
+
+export interface GalleryPersistDeps<T extends StoredEntry> {
+ /** lib/idbStorage in the app. */
+ storage: StateStorage
+ /** idbStorage's hasFailedRead. */
+ readFailed: (key: string) => boolean
+ /** False where IndexedDB is missing: idbStorage would then write to
+ * localStorage, which cannot hold a list without the cap. */
+ durable: boolean
+ getItems: () => T[]
+ /** The list as it was right after the create store hydrated at launch
+ * (the same objects). Defaults to the list when the move starts. */
+ hydratedItems?: () => T[]
+ setItems: (items: T[]) => void
+ /** Called with the list every time it changes. Returns the unsubscribe. */
+ subscribe: (listener: (items: T[], prev: T[]) => void) => () => void
+ /** Told when the list may grow past the cap. */
+ setUncapped: (on: boolean) => void
+ /** Coalescing window of the writes, ms. */
+ waitMs?: number
+}
+
+export interface GalleryPersistence {
+ readonly state: GalleryPersistState
+ /** Write what is pending now. Resolves when it has landed. */
+ flush: () => Promise<void>
+ /** Write, read back, compare. True when every entry is stored. */
+ verify: () => Promise<boolean>
+ stop: () => void
+}
+
+function parseDoc<T extends StoredEntry>(raw: string | null): { doc: GalleryDoc<T> | null; damaged: boolean } {
+ if (raw == null) return { doc: null, damaged: false }
+ try {
+ const value = JSON.parse(raw) as { state?: unknown } | null
+ const state = value && typeof value === 'object' ? (value as { state?: unknown }).state : null
+ if (!state || typeof state !== 'object' || !Array.isArray((state as { items?: unknown }).items)) {
+ return { doc: null, damaged: true }
+ }
+ const s = state as { items: unknown; deleted?: unknown }
+ const deleted = Array.isArray(s.deleted) ? s.deleted.filter((d): d is string => typeof d === 'string') : []
+ return { doc: { items: sanitizeEntries<T>(s.items), deleted }, damaged: false }
+ } catch {
+ return { doc: null, damaged: true }
+ }
+}
+
+/**
+ * Run the move (steps 1 to 4 above) and keep the list written afterwards.
+ * Resolves once the first write has been checked (or the read failed).
+ */
+export async function startGalleryPersistence<T extends StoredEntry>(deps: GalleryPersistDeps<T>): Promise<GalleryPersistence> {
+ let state: GalleryPersistState = 'waiting'
+ let ready = false
+ let deleted: string[] = []
+ let unsubscribe: (() => void) | null = null
+ const writer: CoalescedStorage<GalleryDoc<T>> = coalescedJSONStorage<GalleryDoc<T>>(deps.storage, {
+ ready: () => ready,
+ waitMs: deps.waitMs ?? 400,
+ maxWaitMs: 3000,
+ })
+ const queue = (items: readonly T[]) => {
+ writer.setItem(GALLERY_KEY, { state: { items: items.map(storedForm), deleted }, version: GALLERY_DOC_VERSION })
+ }
+ const verify = async (): Promise<boolean> => {
+ await writer.flush()
+ const wanted = deps.getItems()
+ let back: string | null
+ try {
+ back = await Promise.resolve(deps.storage.getItem(GALLERY_KEY))
+ } catch {
+ back = null
+ }
+ const { doc } = deps.readFailed(GALLERY_KEY) ? { doc: null } : parseDoc<T>(back)
+ const stored = new Set((doc?.items ?? []).map((g) => g.id))
+ const ok = !!doc && wanted.every((g) => stored.has(g.id))
+ state = ok ? 'saved' : 'unconfirmed'
+ return ok
+ }
+ const handle: GalleryPersistence = {
+ get state() { return state },
+ flush: () => writer.flush(),
+ verify,
+ stop: () => { unsubscribe?.(); unsubscribe = null },
+ }
+
+ if (!deps.durable) {
+ state = 'unavailable'
+ return handle
+ }
+
+ // 1. Read.
+ let raw: string | null
+ try {
+ raw = await Promise.resolve(deps.storage.getItem(GALLERY_KEY))
+ } catch (err) {
+ raw = null
+ log.error('[gallery] reading the gallery list threw', { err: String(err) })
+ state = 'unreadable'
+ return handle
+ }
+ if (deps.readFailed(GALLERY_KEY)) {
+ log.error('[gallery] the gallery list could not be read, keeping the old way and writing nothing')
+ state = 'unreadable'
+ return handle
+ }
+ const { doc, damaged } = parseDoc<T>(raw)
+ if (damaged && raw != null) {
+ // Kept aside as it is, never written over: what cannot be read now may be
+ // read by hand later.
+ const aside = `${GALLERY_KEY}-damaged-${Date.now()}`
+ try { await Promise.resolve(deps.storage.setItem(aside, raw)) } catch { /* the log says it */ }
+ log.error('[gallery] the stored gallery list is damaged, set aside and starting from the list in memory', { aside })
+ }
+ deleted = doc?.deleted ?? []
+
+ // 2. The old list, once, before the first write.
+ const before = deps.getItems()
+ if (!doc && before.length > 0) {
+ try {
+ const there = await Promise.resolve(deps.storage.getItem(GALLERY_BEFORE_MOVE_KEY))
+ if (there == null && !deps.readFailed(GALLERY_BEFORE_MOVE_KEY)) {
+ await Promise.resolve(deps.storage.setItem(GALLERY_BEFORE_MOVE_KEY, JSON.stringify(before.map(storedForm))))
+ }
+ } catch (err) {
+ // No copy, no move: the old way holds until a copy can be made.
+ log.error('[gallery] could not keep a copy of the old gallery list, not moving it yet', { err: String(err) })
+ state = 'unreadable'
+ return handle
+ }
+ }
+
+ // 3. Join. What the store got while we read (a render that finished) is in
+ // getItems() now and joins too.
+ const memory = deps.getItems()
+ const joined = joinAtStart({ stored: doc?.items ?? null, memory, hydrated: deps.hydratedItems?.() ?? before, deleted })
+ deleted = joined.deleted
+ ready = true
+ deps.setUncapped(true)
+ if (joined.items.length !== memory.length || joined.items.some((g, i) => g !== memory[i])) deps.setItems(joined.items)
+ if (joined.added > 0 || doc) log.info('[gallery] gallery list loaded', { stored: doc?.items.length ?? 0, joined: joined.added })
+
+ unsubscribe = deps.subscribe((items, prev) => {
+ if (items === prev) return
+ const now = new Set(items.map((g) => g.id))
+ const gone = prev.filter((g) => !now.has(g.id)).map((g) => g.id)
+ deleted = rememberDeleted(deleted, gone)
+ queue(items)
+ })
+
+ // 4. Write and check.
+ queue(deps.getItems())
+ const ok = await verify()
+ if (!ok) log.error('[gallery] the gallery list did not read back complete, it stays in memory and is written again on the next change')
+ return handle
+}
diff --git a/src/lib/gallery-tags.ts b/src/lib/gallery-tags.ts
new file mode 100644
index 00000000..c25a1cb2
--- /dev/null
+++ b/src/lib/gallery-tags.ts
@@ -0,0 +1,107 @@
+// Hide and tag gallery entries (3.1.0, Discord D27, promised 05.11.2026 to
+// boromirofgeo: "hide from gallery" and tags).
+//
+// Both are labels inside the app, like folders (lib/gallery-folders.ts):
+// hiding an entry takes it out of the list and keeps its file, its prompt and
+// its folder; a tag is a short word on the entry that the gallery can filter
+// by. Nothing here reaches a file.
+
+/** Longest tag kept. */
+export const TAG_MAX = 32
+/** Most tags on one entry. */
+export const TAGS_PER_ITEM = 12
+
+/** The shape of an entry as far as hiding and tags are concerned. */
+export interface TaggedItem {
+ hidden?: boolean
+ tags?: string[]
+ folderId?: string
+}
+
+/** A typed tag made ready to keep, or null when nothing is left of it. A
+ * leading "#" is dropped, inner spaces fold to one. */
+export function cleanTag(raw: string): string | null {
+ const clean = raw.replace(/\s+/g, ' ').trim().replace(/^#+\s*/, '').slice(0, TAG_MAX).trim()
+ return clean ? clean : null
+}
+
+const same = (a: string, b: string) => a.toLocaleLowerCase() === b.toLocaleLowerCase()
+
+/** Whether the entry carries `tag`, whatever its case. */
+export function hasTag(item: TaggedItem, tag: string): boolean {
+ return (item.tags ?? []).some((t) => same(t, tag))
+}
+
+/** The entry's tags with `tag` added. Unchanged (same array) when it is there
+ * already, when the tag is empty, or when the entry is full. */
+export function withTag(tags: readonly string[] | undefined, raw: string): string[] | undefined {
+ const tag = cleanTag(raw)
+ const list = tags ?? []
+ if (!tag || list.some((t) => same(t, tag)) || list.length >= TAGS_PER_ITEM) return tags as string[] | undefined
+ return [...list, tag]
+}
+
+/** The entry's tags without `tag`; undefined when none are left. */
+export function withoutTag(tags: readonly string[] | undefined, tag: string): string[] | undefined {
+ if (!tags) return undefined
+ const left = tags.filter((t) => !same(t, tag))
+ if (left.length === tags.length) return tags as string[]
+ return left.length > 0 ? left : undefined
+}
+
+/**
+ * A tag list read back from storage. Anything that is not a short string goes,
+ * so a damaged blob gives fewer tags instead of a crash.
+ */
+export function sanitizeTags(raw: unknown): string[] | undefined {
+ if (!Array.isArray(raw)) return undefined
+ let out: string[] | undefined
+ for (const t of raw) {
+ if (typeof t !== 'string') continue
+ out = withTag(out, t)
+ }
+ return out
+}
+
+/** Every tag in use, the most used first, then by name. Spelled as it was
+ * first met. */
+export function tagCounts(items: readonly TaggedItem[]): { tag: string; count: number }[] {
+ const byKey = new Map<string, { tag: string; count: number }>()
+ for (const g of items) {
+ for (const t of g.tags ?? []) {
+ const key = t.toLocaleLowerCase()
+ const hit = byKey.get(key)
+ if (hit) hit.count++
+ else byKey.set(key, { tag: t, count: 1 })
+ }
+ }
+ return [...byKey.values()].sort((a, b) => b.count - a.count || a.tag.localeCompare(b.tag))
+}
+
+export interface GalleryView {
+ /** null: "All". */
+ folderId: string | null
+ /** null: no tag filter. */
+ tag: string | null
+ /** Show the hidden entries instead of the others. */
+ hidden: boolean
+}
+
+/**
+ * The entries one view shows, in the order they come. Hidden entries appear
+ * only in the "Hidden" view, which shows nothing else, so a hidden entry is
+ * never in the way and always one click from coming back.
+ */
+export function itemsInView<T extends TaggedItem>(items: readonly T[], view: GalleryView): T[] {
+ return items.filter((g) =>
+ !!g.hidden === view.hidden
+ && (view.folderId === null || g.folderId === view.folderId)
+ && (view.tag === null || hasTag(g, view.tag)))
+}
+
+/** How many entries are hidden. */
+export function hiddenCount(items: readonly TaggedItem[]): number {
+ let n = 0
+ for (const g of items) if (g.hidden) n++
+ return n
+}
diff --git a/src/lib/store-backup.ts b/src/lib/store-backup.ts
index aac15859..b31bd0af 100644
--- a/src/lib/store-backup.ts
+++ b/src/lib/store-backup.ts
@@ -118,6 +118,9 @@ export const STORE_KEYS = [
// settings of this backup when they are newer. Listed last, so a snapshot
// reads it after the settings it stamps.
'lu-mobile-settings-stamp',
+ // 3.1.0 (C27): the gallery list without the cap, on IndexedDB
+ // (lib/gallery-persist.ts). The create-store blob keeps only a short copy.
+ 'lu-gallery',
]
/** The phone keys of STORE_KEYS, for the tests that hold the two lists together. */
@@ -257,6 +260,8 @@ export const IDB_STORE_KEYS = new Set([
'chat-conversations', 'locally-uncensored-memory', 'staged-changes',
// The Remote chats of the phone shell (mobile/remote/remoteClientStore.ts).
'lu-mobile-remote',
+ // The gallery list (lib/gallery-persist.ts, 3.1.0).
+ 'lu-gallery',
])
/**
diff --git a/src/mobile/boot/backup.ts b/src/mobile/boot/backup.ts
index 436fb589..e632e49c 100644
--- a/src/mobile/boot/backup.ts
+++ b/src/mobile/boot/backup.ts
@@ -18,6 +18,7 @@ import { useSettingsStore } from '../../stores/settingsStore'
import { installSavedCharactersBackup, restoreSavedCharactersAtStart } from '../lib/saved-characters-backup'
import { onLifecycle } from '../platform/lifecycle'
import { restoreDecided } from './restore'
+import { startGalleryStore } from '../../lib/gallery-persist-wiring'
const STORE_INTERVAL_MS = 5_000
const CHAT_DEBOUNCE_MS = 1_000
@@ -50,6 +51,9 @@ export function startBackup(): () => void {
// Never write the first backup before the restore looked at the old one.
await restoreDecided
if (disposed) return
+ // The gallery list to IndexedDB (3.1.0, C27), after the restore wrote its
+ // copy back. Its failure keeps the old way and must not cost the backups.
+ void startGalleryStore().catch(() => {})
let storesBusy = false
const backupStores = async () => {
diff --git a/src/stores/__tests__/galerie-ohne-deckel-c27.test.ts b/src/stores/__tests__/galerie-ohne-deckel-c27.test.ts
new file mode 100644
index 00000000..bfd2cb3a
--- /dev/null
+++ b/src/stores/__tests__/galerie-ohne-deckel-c27.test.ts
@@ -0,0 +1,109 @@
+// @vitest-environment jsdom
+/**
+ * C27 (3.1.0) in the create store: no cap once the list has its own IndexedDB
+ * key, the create-store blob keeps only the short copy for a downgrade, and
+ * entries can be hidden and tagged (D27).
+ *
+ * The move itself: src/lib/__tests__/gallery-persist.test.ts.
+ *
+ * Run: npx vitest run src/stores/__tests__/galerie-ohne-deckel-c27.test.ts
+ */
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { useCreateStore, setGalleryUncapped, type GalleryItem } from '../createStore'
+import { MIRROR_SORTED, MIRROR_UNSORTED } from '../../lib/gallery-persist'
+import { itemsInView, tagCounts } from '../../lib/gallery-tags'
+
+const item = (n: number, extra: Partial<GalleryItem> = {}): GalleryItem => ({
+ id: `g${n}`, type: 'image', filename: `ComfyUI_${n}.png`, subfolder: '', prompt: `prompt ${n}`,
+ negativePrompt: '', model: 'm.safetensors', modelType: 'sdxl', seed: n, steps: 20, cfgScale: 5, sampler: 'euler',
+ scheduler: 'normal', width: 1024, height: 1024, batchSize: 1, createdAt: n, ...extra,
+})
+const st = () => useCreateStore.getState()
+const storedGallery = () => JSON.parse(localStorage.getItem('create-store') ?? '{}').state.gallery as GalleryItem[]
+
+beforeEach(() => {
+ localStorage.clear()
+ useCreateStore.setState({
+ backend: 'local', gallery: [], galleryFolders: [{ id: 'f-1', name: 'Sorted' }], galleryFolderOpen: null,
+ galleryTagOpen: null, galleryShowHidden: false, galleryNotice: null,
+ })
+})
+afterEach(() => { setGalleryUncapped(false) })
+
+describe('without the cap', () => {
+ it('keeps 1500 renders and says nothing about trimming', () => {
+ setGalleryUncapped(true)
+ for (let i = 0; i < 1500; i++) st().addToGallery(item(i))
+ expect(st().gallery).toHaveLength(1500)
+ expect(st().galleryNotice).toBeNull()
+ })
+
+ it('the create-store blob holds only the short copy, newest first', () => {
+ setGalleryUncapped(true)
+ for (let i = 0; i < 400; i++) st().addToGallery(item(i, { folderId: 'f-1' }))
+ for (let i = 0; i < 400; i++) st().addToGallery(item(1000 + i))
+ const blob = storedGallery()
+ expect(blob.filter((g) => !g.folderId)).toHaveLength(MIRROR_UNSORTED)
+ expect(blob.filter((g) => g.folderId)).toHaveLength(MIRROR_SORTED)
+ expect(blob[0].id).toBe('g1399')
+ })
+
+ it('before the move the cap holds as it did (no IndexedDB, or not read yet)', () => {
+ for (let i = 0; i < 300; i++) st().addToGallery(item(i))
+ expect(st().gallery).toHaveLength(200)
+ expect(storedGallery()).toHaveLength(200)
+ })
+})
+
+describe('hide and tags (D27)', () => {
+ beforeEach(() => { useCreateStore.setState({ gallery: [item(3), item(2), item(1)] }) })
+
+ it('a hidden entry keeps its file, prompt and folder and shows only under Hidden', () => {
+ st().moveToGalleryFolder(['g2'], 'f-1')
+ st().setGalleryHidden(['g2'], true)
+ const g2 = st().gallery.find((g) => g.id === 'g2')!
+ expect(g2).toMatchObject({ hidden: true, filename: 'ComfyUI_2.png', prompt: 'prompt 2', folderId: 'f-1' })
+ expect(itemsInView(st().gallery, { folderId: null, tag: null, hidden: false }).map((g) => g.id)).toEqual(['g3', 'g1'])
+ expect(itemsInView(st().gallery, { folderId: null, tag: null, hidden: true }).map((g) => g.id)).toEqual(['g2'])
+ st().setGalleryHidden(['g2'], false)
+ expect(st().gallery.find((g) => g.id === 'g2')!.hidden).toBeUndefined()
+ })
+
+ it('tags go on several entries, once each, and come off again', () => {
+ st().tagGalleryItems(['g1', 'g3'], ' #Portrait ')
+ st().tagGalleryItems(['g1'], 'portrait')
+ st().tagGalleryItems(['g1'], 'night')
+ expect(st().gallery.find((g) => g.id === 'g1')!.tags).toEqual(['Portrait', 'night'])
+ expect(tagCounts(st().gallery)).toEqual([{ tag: 'Portrait', count: 2 }, { tag: 'night', count: 1 }])
+ expect(itemsInView(st().gallery, { folderId: null, tag: 'PORTRAIT', hidden: false }).map((g) => g.id)).toEqual(['g3', 'g1'])
+ st().setGalleryTagOpen('night')
+ st().untagGalleryItems(['g1'], 'NIGHT')
+ expect(st().gallery.find((g) => g.id === 'g1')!.tags).toEqual(['Portrait'])
+ // Nobody carries the filtered tag any more: the filter goes.
+ expect(st().galleryTagOpen).toBeNull()
+ })
+
+ it('hidden and tags are stored, the view is not', () => {
+ st().setGalleryHidden(['g1'], true)
+ st().tagGalleryItems(['g3'], 'keep')
+ st().setGalleryShowHidden(true)
+ const blob = JSON.parse(localStorage.getItem('create-store')!).state
+ expect(blob.gallery.find((g: GalleryItem) => g.id === 'g1').hidden).toBe(true)
+ expect(blob.gallery.find((g: GalleryItem) => g.id === 'g3').tags).toEqual(['keep'])
+ expect(blob).not.toHaveProperty('galleryShowHidden')
+ expect(blob).not.toHaveProperty('galleryTagOpen')
+ })
+})
+
+describe('restore from the output folder', () => {
+ it('adds only entries for files the gallery does not list yet', () => {
+ useCreateStore.setState({ gallery: [item(5), item(1)] })
+ const n = st().restoreGalleryItems([
+ item(9, { id: 'r-a', filename: 'ComfyUI_9.png' }),
+ item(1, { id: 'r-b', filename: 'ComfyUI_1.png' }),
+ item(3, { id: 'r-c', filename: 'ComfyUI_3.png', subfolder: 'video' }),
+ ])
+ expect(n).toBe(2)
+ expect(st().gallery.map((g) => g.id)).toEqual(['r-a', 'g5', 'r-c', 'g1'])
+ })
+})
diff --git a/src/stores/createStore.ts b/src/stores/createStore.ts
index c7118d6c..f8e640b8 100644
--- a/src/stores/createStore.ts
+++ b/src/stores/createStore.ts
@@ -15,6 +15,8 @@ import { TRAIN_CAPTION_MAX } from '../lib/train-captions'
import { isMobile } from '../lib/device-kind'
import { isRecord } from '../types/json-guards'
import { cleanFolderName, newFolderId, sanitizeFolders, FOLDER_CAP, type GalleryFolder } from '../lib/gallery-folders'
+import { withTag, withoutTag } from '../lib/gallery-tags'
+import { downgradeMirror, sanitizeEntries } from '../lib/gallery-persist'
/**
* Fields a persisted blob must never put back into live state: they steer the
@@ -36,6 +38,8 @@ const RUNTIME_ONLY_KEYS: readonly string[] = [
'galleryFolderOpen',
// The line about trimmed entries belongs to the moment it happened.
'galleryNotice',
+ // The tag filter and the Hidden view belong to the session, like the open folder.
+ 'galleryTagOpen', 'galleryShowHidden',
// Review A kleiner Punkt 1 (studio-r2): the cloud video length selection,
// own fields since this bugfix. Session-scratch like source/mask, not a
// preference worth remembering across restarts.
@@ -339,6 +343,11 @@ export interface GalleryItem {
* Only a label in the app, the file stays where it is. Absent: no folder,
* the entry is found under "All" only. */
folderId?: string
+ /** Hidden from the gallery (3.1.0, D27). The file, the prompt and the folder
+ * stay; the entry shows only in the Hidden view (lib/gallery-tags.ts). */
+ hidden?: boolean
+ /** Short words the gallery filters by (3.1.0, D27). Labels in the app only. */
+ tags?: string[]
}
export interface CreateState {
@@ -592,6 +601,10 @@ export interface CreateState {
* lands in it, and a folder picked yesterday must not file today's renders
* without the user seeing it. */
galleryFolderOpen: string | null
+ /** The tag the gallery filters by, null for none. Runtime only. */
+ galleryTagOpen: string | null
+ /** The gallery shows its hidden entries instead of the others. Runtime only. */
+ galleryShowHidden: boolean
/** Said once when the cap took older unsorted entries (D3b). Runtime only. */
galleryNotice: string | null
promptHistory: string[]
@@ -754,6 +767,17 @@ export interface CreateState {
/** File entries under a folder, or under none with null. */
moveToGalleryFolder: (ids: readonly string[], folderId: string | null) => void
setGalleryFolderOpen: (id: string | null) => void
+ /** Hide entries or show them again (3.1.0, D27). The files stay. */
+ setGalleryHidden: (ids: readonly string[], hidden: boolean) => void
+ /** Put a tag on entries; a tag they carry already is left alone. */
+ tagGalleryItems: (ids: readonly string[], tag: string) => void
+ /** Take a tag off entries. */
+ untagGalleryItems: (ids: readonly string[], tag: string) => void
+ setGalleryTagOpen: (tag: string | null) => void
+ setGalleryShowHidden: (on: boolean) => void
+ /** Entries found again in the output folder (3.1.0, C27). Ids it has
+ * already, and files it already lists, are left out. Returns how many came in. */
+ restoreGalleryItems: (items: readonly GalleryItem[]) => number
dismissGalleryNotice: () => void
addToPromptHistory: (prompt: string) => void
/** Drop a single remembered prompt (the X next to the entry). */
@@ -766,9 +790,24 @@ export interface CreateState {
setMlxUpscale: (installed: boolean) => void
}
-/** The gallery keeps the newest N unsorted renders. */
+/** Without IndexedDB the gallery keeps the newest N unsorted renders. */
const GALLERY_CAP = 200
+/**
+ * True once the gallery list has its own IndexedDB key (lib/gallery-persist.ts,
+ * 3.1.0, C27). From then on nothing is capped: the create-store blob only
+ * keeps the small copy for a downgrade. Until then, and wherever IndexedDB
+ * cannot be read, the cap of 200 holds as before, because the whole list then
+ * still lives in localStorage.
+ */
+let galleryUncapped = false
+export function setGalleryUncapped(on: boolean): void {
+ galleryUncapped = on
+}
+export function isGalleryUncapped(): boolean {
+ return galleryUncapped
+}
+
/** What the gallery says when the cap took entries (D3b). */
export const GALLERY_TRIMMED_NOTICE =
'Older unsorted images were removed from the gallery, the files are still in your output folder.'
@@ -781,6 +820,7 @@ export const GALLERY_TRIMMED_NOTICE =
* oldest go first. The caller frees the dropped ones' media and says so.
*/
export function capGallery(items: readonly GalleryItem[]): { kept: GalleryItem[]; dropped: GalleryItem[] } {
+ if (galleryUncapped) return { kept: items as GalleryItem[], dropped: [] }
const kept: GalleryItem[] = []
const dropped: GalleryItem[] = []
let unsorted = 0
@@ -1212,6 +1252,8 @@ export const useCreateStore = create<CreateState>()(
gallery: [],
galleryFolders: [],
galleryFolderOpen: null,
+ galleryTagOpen: null,
+ galleryShowHidden: false,
galleryNotice: null,
promptHistory: [],
imageModelList: [],
@@ -1862,6 +1904,49 @@ export const useCreateStore = create<CreateState>()(
setGalleryFolderOpen: (id) => set((s) => ({
galleryFolderOpen: id !== null && s.galleryFolders.some((f) => f.id === id) ? id : null,
})),
+ // Hidden and tags (D27). Labels only, like folders: nothing reaches a file.
+ setGalleryHidden: (ids, hidden) => set((s) => {
+ const pick = new Set(ids)
+ return {
+ gallery: s.gallery.map((g) => (pick.has(g.id) && !!g.hidden !== hidden ? { ...g, hidden: hidden || undefined } : g)),
+ }
+ }),
+ tagGalleryItems: (ids, tag) => set((s) => {
+ const pick = new Set(ids)
+ return {
+ gallery: s.gallery.map((g) => {
+ if (!pick.has(g.id)) return g
+ const tags = withTag(g.tags, tag)
+ return tags === g.tags ? g : { ...g, tags }
+ }),
+ }
+ }),
+ untagGalleryItems: (ids, tag) => set((s) => {
+ const pick = new Set(ids)
+ const gallery = s.gallery.map((g) => {
+ if (!pick.has(g.id)) return g
+ const tags = withoutTag(g.tags, tag)
+ return tags === g.tags ? g : { ...g, tags }
+ })
+ // A filter on a tag nobody carries any more would show an empty list.
+ const open = s.galleryTagOpen
+ const still = open !== null && gallery.some((g) => (g.tags ?? []).some((t) => t.toLocaleLowerCase() === open.toLocaleLowerCase()))
+ return { gallery, galleryTagOpen: still ? open : null }
+ }),
+ setGalleryTagOpen: (tag) => set({ galleryTagOpen: tag }),
+ setGalleryShowHidden: (on) => set({ galleryShowHidden: on }),
+ restoreGalleryItems: (items) => {
+ const s = get()
+ const ids = new Set(s.gallery.map((g) => g.id))
+ const files = new Set(s.gallery.map((g) => `${g.subfolder ?? ''}/${g.filename}`))
+ const fresh = items.filter((g) => !ids.has(g.id) && !files.has(`${g.subfolder ?? ''}/${g.filename}`))
+ if (fresh.length === 0) return 0
+ const joined = [...s.gallery, ...fresh].sort((a, b) => b.createdAt - a.createdAt)
+ const { kept, dropped } = capGallery(joined)
+ for (const g of dropped) releaseItemMedia(g)
+ set(dropped.length > 0 ? { gallery: kept, galleryNotice: GALLERY_TRIMMED_NOTICE } : { gallery: kept })
+ return fresh.length - dropped.length
+ },
addToPromptHistory: (prompt) => set((s) => {
const filtered = s.promptHistory.filter(p => p !== prompt)
return { promptHistory: [prompt, ...filtered].slice(0, 50) }
@@ -1957,7 +2042,13 @@ export const useCreateStore = create<CreateState>()(
// dataUrls would blow the origin quota (~5-10 MB in WebView2/WKWebView)
// and every subsequent set() would throw, killing ALL create-store
// persistence. Cloud items carry remoteUrl + jobId and re-sign lazily.
- gallery: state.gallery.map(({ dataUrl, unavailable, unavailableReason, reloadKey, ...g }: GalleryItem) => g),
+ //
+ // 3.1.0 (C27): once the full list has its own IndexedDB key
+ // (lib/gallery-persist.ts) this is only the small copy an older LU
+ // reads after a downgrade. Before that, and wherever IndexedDB cannot
+ // be read, it is the whole (capped) list, as it always was.
+ gallery: (galleryUncapped ? downgradeMirror(state.gallery) : state.gallery)
+ .map(({ dataUrl, unavailable, unavailableReason, reloadKey, ...g }: GalleryItem) => g),
// Folders are an id and a short name each, capped (lib/gallery-folders.ts).
// Additive: an older blob has none and merge() gives it the empty list.
galleryFolders: state.galleryFolders,
@@ -2042,6 +2133,9 @@ export const useCreateStore = create<CreateState>()(
// Gallery folders came in 3.0.7. An older blob has no list (the
// default stays), a damaged one is cleaned instead of trusted.
if ('galleryFolders' in safe) safe.galleryFolders = sanitizeFolders(safe.galleryFolders)
+ // 3.1.0: entries carry tags and a hidden flag the gallery reads. A
+ // damaged list loses only what cannot be an entry at all.
+ if ('gallery' in safe) safe.gallery = sanitizeEntries<GalleryItem>(safe.gallery)
// 3.0.9 B24: an older blob has no lanes, a damaged one is cleaned.
if ('loraLanes' in safe) safe.loraLanes = sanitizeLoraLanes(safe.loraLanes)
// 3.0.8 D20: an unknown recipe name would reach the trainer as text.