Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
perf: page and search gallery images when importing LoRA datasets (#7040)
[._.]/ Adam Eivyd5d721ef5411
diff --git a/client/src/components/loraTraining/ImportGalleryDialog.jsx b/client/src/components/loraTraining/ImportGalleryDialog.jsxindex f90df7d9a4..b9b157b72b 100644--- a/client/src/components/loraTraining/ImportGalleryDialog.jsx+++ b/client/src/components/loraTraining/ImportGalleryDialog.jsx@@ -3,51 +3,52 @@** Multi-select picker over the local image gallery (GET /api/image-gen/gallery)* — the "choose images already in the system" path alongside upload/generate/- * slice. Reuses the same normalize + search helpers as GalleryImagePicker, but- * accumulates a selection and imports them all in one POST. The server copies+ * slice. Loads bounded, server-searched pages and accumulates a selection+ * across pages before importing them all in one POST. The server copies* each into the dataset (independent of the gallery original).*/-import { useCallback, useEffect, useMemo, useState } from 'react';+import { useCallback, useEffect, useRef, useState } from 'react';import { Search, X, RefreshCw, Loader2, Check } from 'lucide-react';import Modal from '../ui/Modal';import MediaCard from '../media/MediaCard';import toast from '../ui/Toast';import { normalizeImage } from '../media/normalize';-import { listImageGallery, importLoraDatasetGalleryImages } from '../../services/api';-import { buildMediaHaystack, tokenizeQuery, matchHaystack } from '../../lib/mediaSearch';+import { listImageGalleryPage, importLoraDatasetGalleryImages } from '../../services/api';const MAX_IMPORT = 50;export default function ImportGalleryDialog({ dataset, onClose, onImported }) {const [items, setItems] = useState([]);const [loading, setLoading] = useState(false);+ const [total, setTotal] = useState(0);+ const [offset, setOffset] = useState(0);+ const requestId = useRef(0);+ const [error, setError] = useState(false);+ const [retry, setRetry] = useState(0);const [query, setQuery] = useState('');const [selected, setSelected] = useState([]); // ordered list of filenamesconst [importing, setImporting] = useState(false);useEffect(() => {- let cancelled = false;+ const id = ++requestId.current;setLoading(true);- listImageGallery()- .then((images) => {- if (cancelled) return;- const normalized = (Array.isArray(images) ? images : [])- .map(normalizeImage)- .filter((it) => !it.hidden && it.filename);- setItems(normalized);+ setError(false);+ listImageGalleryPage({ limit: 60, offset, q: query, hidden: false }, { silent: true })+ .then(page => {+ if (id !== requestId.current) return;+ const next = page.items.map(normalizeImage);+ setItems(prev => offset === 0 ? next : [...prev, ...next]);+ setTotal(page.total);})- .catch(err => { console.warn('⚠️ Failed to load gallery images: ' + err.message); if (!cancelled) setItems([]); })- .finally(() => { if (!cancelled) setLoading(false); });- return () => { cancelled = true; };- }, []);-- const haystacks = useMemo(() => items.map(buildMediaHaystack), [items]);- const tokens = useMemo(() => tokenizeQuery(query), [query]);- const filtered = useMemo(- () => (tokens.length === 0 ? items : items.filter((_, idx) => matchHaystack(haystacks[idx], tokens))),- [items, haystacks, tokens],- );+ .catch(err => {+ if (id !== requestId.current) return;+ setError(true);+ toast.error(err.message || 'Failed to load gallery');+ })+ .finally(() => { if (id === requestId.current) setLoading(false); });+ return () => { requestId.current += 1; };+ }, [query, offset, retry]);const toggle = useCallback((filename) => {setSelected((prev) => {@@ -91,7 +92,7 @@ export default function ImportGalleryDialog({ dataset, onClose, onImported }) {<inputtype="text"value={query}- onChange={(e) => setQuery(e.target.value)}+ onChange={(e) => { setQuery(e.target.value); setOffset(0); setItems([]); setTotal(0); }}placeholder="Search prompt, model, seed, LoRA…"aria-label="Search gallery images"className="w-full pl-7 pr-7 py-1.5 text-xs bg-port-bg border border-port-border rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"@@ -100,7 +101,7 @@ export default function ImportGalleryDialog({ dataset, onClose, onImported }) {{query && (<buttontype="button"- onClick={() => setQuery('')}+ onClick={() => { setQuery(''); setOffset(0); setItems([]); setTotal(0); }}className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-white"aria-label="Clear search">@@ -119,17 +120,17 @@ export default function ImportGalleryDialog({ dataset, onClose, onImported }) {</div><div className="flex-1 overflow-y-auto p-3">- {loading ? (+ {loading && offset === 0 ? (<div className="flex items-center justify-center gap-2 text-xs text-gray-400 py-10"><RefreshCw className="w-4 h-4 animate-spin" /> Loading gallery…</div>- ) : filtered.length === 0 ? (+ ) : items.length === 0 ? (<div className="text-xs text-gray-500 py-10 text-center">- {items.length === 0 ? 'No images in your gallery yet.' : 'No images match your search.'}+ {error ? 'Gallery could not be loaded.' : query.trim() ? 'No images match your search.' : 'No images in your gallery yet.'}</div>) : (<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">- {filtered.map((item) => {+ {items.map((item) => {const idx = selected.indexOf(item.filename);return (<MediaCard@@ -145,6 +146,13 @@ export default function ImportGalleryDialog({ dataset, onClose, onImported }) {})}</div>)}+ {error && <button type="button" onClick={() => setRetry(n => n + 1)} className="w-full min-h-[44px] text-port-accent">Retry loading images</button>}+ {!error && items.length < total && (+ <button type="button" disabled={loading} onClick={() => setOffset(items.length)}+ className="w-full min-h-[44px] mt-3 text-sm text-port-accent disabled:opacity-50">+ {loading ? 'Loading…' : 'Show more'}+ </button>+ )}</div><div className="flex items-center justify-between gap-3 p-3 border-t border-port-border">diff --git a/client/src/components/loraTraining/ImportGalleryDialog.test.jsx b/client/src/components/loraTraining/ImportGalleryDialog.test.jsxnew file mode 100644index 0000000000..5f101bd048--- /dev/null+++ b/client/src/components/loraTraining/ImportGalleryDialog.test.jsx@@ -0,0 +1,36 @@+import { describe, it, expect, vi } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import ImportGalleryDialog from './ImportGalleryDialog';++const api = vi.hoisted(() => ({+ listImageGalleryPage: vi.fn(),+ importLoraDatasetGalleryImages: vi.fn(),+}));+vi.mock('../../services/api', () => api);+vi.mock('../media/MediaCard', () => ({+ default: ({ item, onClick }) => <button onClick={() => onClick(item)}>{item.filename}</button>,+}));+vi.mock('../ui/Modal', () => ({ default: ({ children }) => <div>{children}</div> }));++describe('gallery import paging', () => {+ it('pages and searches on the server while retaining selected filenames', async () => {+ api.listImageGalleryPage.mockImplementation(async ({ offset, q }) => ({+ items: [{ filename: q ? 'found.png' : offset ? 'second.png' : 'first.png' }],+ total: q ? 1 : 2, limit: 60, offset,+ }));+ api.importLoraDatasetGalleryImages.mockResolvedValue({ images: [] });+ render(<ImportGalleryDialog dataset={{ id: 'dataset' }} />);+ fireEvent.click(await screen.findByText('first.png'));+ fireEvent.click(screen.getByRole('button', { name: 'Show more' }));+ await screen.findByText('second.png');+ expect(api.listImageGalleryPage).toHaveBeenCalledWith(+ { limit: 60, offset: 1, q: '', hidden: false }, { silent: true });+ fireEvent.change(screen.getByLabelText('Search gallery images'), { target: { value: 'fox' } });+ await screen.findByText('found.png');+ expect(screen.queryByText('first.png')).toBeNull();+ expect(api.listImageGalleryPage).toHaveBeenLastCalledWith(+ { limit: 60, offset: 0, q: 'fox', hidden: false }, { silent: true });+ fireEvent.click(screen.getByRole('button', { name: 'Import 1' }));+ await waitFor(() => expect(api.importLoraDatasetGalleryImages).toHaveBeenCalledWith('dataset', ['first.png']));+ });+});diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex 92a93dbc29..1b646446cc 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -27,6 +27,12 @@ export const repairImageModel = (modelId, { deep = false } = {}) => request(`/imsilent: true,});export const listImageGallery = (options = {}) => request('/image-gen/gallery', options);+// Opt-in page envelope; keep listImageGallery's legacy array/options signature.+export const listImageGalleryPage = ({ limit = 60, offset = 0, q = '', hidden } = {}, options = {}) => {+ const params = new URLSearchParams({ limit, offset, q });+ if (hidden !== undefined) params.set('hidden', hidden);+ return request(`/image-gen/gallery?${params}`, options);+};export const getActiveImageJob = () => request('/image-gen/active');// cancelImageGen({ all: true }) cancels every queued/running image job.// cancelImageGen({ jobId }) cancels a specific job. Plain cancelImageGen()diff --git a/docs/IMAGE_GALLERY.md b/docs/IMAGE_GALLERY.mdnew file mode 100644index 0000000000..52c8d90eb7--- /dev/null+++ b/docs/IMAGE_GALLERY.md@@ -0,0 +1,30 @@+# Image gallery reads++Legacy `GET /api/image-gen/gallery` returns the complete disk-derived array.+New consumers should request a page:++- Recent images: `GET /api/image-gen/gallery?limit=5`+- Search and paging: `GET /api/image-gen/gallery?limit=60&offset=60&q=fox`+- Exclude hidden images: add `hidden=false`.++Supplying any of `limit`, `offset`, `q`, or `hidden` selects the envelope+`{ items, total, limit, offset }`. The default limit is 60; allowed limits are+1–200. Offset is a nonnegative integer. Total counts all matching rows, including+when the requested offset is beyond the end. Items preserve their gallery metadata.++Production pages read the derived PostgreSQL `media_assets` index with SQL LIMIT+and OFFSET. Ordering is newest first with a stable media-key tie break. Search+matches all whitespace-separated tokens, case-insensitively, anywhere in the+metadata JSON (including prompt and filename); percent and underscore are literal.+No request scans sidecars to recover from a database error.++Sidecars remain authoritative. Boot reconcile scans disk and repairs index drift.+The file/test escape hatch filters and slices its small disk gallery. Generation+uses the existing completed-event upsert; uploads, variants, prompt and visibility+edits refresh that same index hook. Confirmed image deletion still unindexes.++The LoRA import dialog uses this page contract. Image Gen, Media History, and the+other legacy consumers have not yet migrated. Their global scopes, favorites,+counts, collection membership, and deep-linked previews must remain correct when+they migrate; limiting their old arrays without moving filters to the server is+not sufficient.diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 1177847ef0..a2b499e753 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -787,8 +787,21 @@ router.get('/loras', asyncHandler(async (_req, res) => {res.json(await local.listLoraFilenames());}));-router.get('/gallery', asyncHandler(async (_req, res) => {- res.json(await local.listGallery());+const galleryQuerySchema = z.object({+ limit: z.coerce.number().int().min(1).max(200).default(60),+ offset: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),+ q: z.string().max(500).default(''),+ hidden: z.enum(['true', 'false']).optional().transform(v => v === undefined ? undefined : v === 'true'),+});++router.get('/gallery', asyncHandler(async (req, res) => {+ // No paging keys preserves the full legacy array for callers not migrated yet.+ // New callers use ?limit=5 (recent strip) or ?limit=60&offset=0&q=...+ const paginated = ['limit', 'offset', 'q', 'hidden'].some(key => req.query[key] !== undefined);+ if (!paginated) return res.json(await local.listGallery());+ const options = validateRequest(galleryQuerySchema, req.query);+ const { listGalleryPage } = await import('../services/mediaAssetIndex/gallery.js');+ res.json(await listGalleryPage(options, local.listGallery));}));// SSE progress stream. Local renders run via the mediaJobQueue and emitdiff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex cc86a01737..54e56f99a9 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -214,6 +214,29 @@ describe('Image Gen Routes', () => {vi.clearAllMocks();});+ describe('GET /api/image-gen/gallery', () => {+ it('preserves legacy arrays and pages/searches the test disk fallback', async () => {+ const items = [+ { filename: 'a.png', prompt: 'red fox', path: '/data/images/a.png', seed: 42 },+ { filename: 'b.png', prompt: 'red fox', path: '/data/images/b.png' },+ { filename: 'c.png', prompt: 'blue fox', hidden: true },+ ];+ imageGen.local.listGallery.mockResolvedValue(items);+ expect((await request(app).get('/api/image-gen/gallery')).body).toEqual(items);+ const page = await request(app).get('/api/image-gen/gallery?limit=1&offset=1&q=red&hidden=false');+ expect(page.status).toBe(200);+ expect(page.body).toEqual({ items: [items[1]], total: 2, limit: 1, offset: 1 });+ const empty = await request(app).get('/api/image-gen/gallery?q=missing');+ expect(empty.body).toEqual({ items: [], total: 0, limit: 60, offset: 0 });+ });++ it.each(['limit=0', 'limit=201', 'offset=-1', 'limit=1.5', 'q=a&q=b'])('rejects invalid paging: %s', async query => {+ const response = await request(app).get('/api/image-gen/gallery?' + query);+ expect(response.status).toBe(400);+ expect(imageGen.local.listGallery).not.toHaveBeenCalled();+ });+ });+describe('GET /api/image-gen/status', () => {it('should return connection status', async () => {imageGen.checkConnection.mockResolvedValue({ connected: true, model: 'flux-v1' });diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 077a05d1e5..7d9c4443e6 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -1111,6 +1111,12 @@ const MAX_GALLERY_UPLOAD_BYTES = 16 * 1024 * 1024;// the cleaner's guard (lib/imageClean.js MAX_PIXELS) — sharp throws past it.const MAX_GALLERY_UPLOAD_PIXELS = 96 * 1000 * 1000;+async function refreshImageIndex(filename) {+ await import('../mediaAssetIndex/index.js')+ .then(m => m.indexImage({ filename }))+ .catch(err => console.error(`❌ Media index image refresh failed: ${err.message}`));+}+/*** Persist user-uploaded image bytes (base64) into the gallery dir under* `data/images/` so the file rides the existing `image` peer-sync asset path@@ -1144,6 +1150,7 @@ export async function saveUploadedGalleryImage(base64Data) {const filename = `upload-${randomUUID().slice(0, 8)}.png`;await ensureDir(PATHS.images);await atomicWrite(join(PATHS.images, filename), png);+ await refreshImageIndex(filename);console.log(`📥 Saved uploaded gallery image: ${filename} (${(png.length / 1024).toFixed(0)}KB PNG, from ${detected.mime})`);return { filename, path: `/data/images/${filename}` };}@@ -1209,6 +1216,7 @@ export async function setImageHidden(filename, hidden) {const { path: sidecarPath, metadata } = await readImageSidecar(filename);metadata.hidden = !!hidden;await atomicWrite(sidecarPath, metadata);+ await refreshImageIndex(filename);return { ok: true, hidden: metadata.hidden };}@@ -1219,6 +1227,7 @@ export async function updateImagePrompt(filename, prompt) {if (trimmedPrompt) metadata.prompt = trimmedPrompt;else delete metadata.prompt;await atomicWrite(sidecarPath, metadata);+ await refreshImageIndex(filename);return { filename, prompt: trimmedPrompt };}diff --git a/server/services/imageGen/variants.js b/server/services/imageGen/variants.jsindex bc7c46c490..8616ebcf55 100644--- a/server/services/imageGen/variants.js+++ b/server/services/imageGen/variants.js@@ -103,6 +103,10 @@ export async function persistVariant({atomicWrite(sidecarPath, untimedVariantMeta),]);+ await import('../mediaAssetIndex/index.js')+ .then(m => m.indexImage({ filename: outFilename }))+ .catch(err => console.error(`❌ Media index variant refresh failed: ${err.message}`));+const filedCollections = await autoFileCleanedToSourceCollections(sourceFilename, outFilename).catch((err) => {console.warn(`⚠️ Auto-file ${outFilename} → source collections failed: ${err?.message || err}`);return [];diff --git a/server/services/mediaAssetIndex/db.js b/server/services/mediaAssetIndex/db.jsindex 44d9af9e38..8bc82b4143 100644--- a/server/services/mediaAssetIndex/db.js+++ b/server/services/mediaAssetIndex/db.js@@ -13,9 +13,8 @@* cheap to re-run; called at boot. Still the* backstop for OUT-OF-BAND removals (a file* deleted off-disk never runs a delete hook).- * - listAssets(...) — query helper (no consumer reads it for- * correctness yet; here for the follow-up slices- * that make collections/catalog resolve through it)+ * - listAssets(...) — bounded gallery reads; legacy callers may+ * still request an unbounded array** The image + video disk readers are dynamically imported inside reconcile so* importing this module (e.g. for upsertAsset from a generation hook) never@@ -93,26 +92,40 @@ export async function removeAsset(mediaKey) {await query(`DELETE FROM media_assets WHERE media_key = $1`, [mediaKey]);}-/** List index rows, newest first. Optional `kind` filter ('image' | 'video'). */-export async function listAssets({ kind } = {}) {- const result = kind- ? await query(`SELECT data FROM media_assets WHERE kind = $1 ORDER BY created_at DESC`, [kind])- : await query(`SELECT data FROM media_assets ORDER BY created_at DESC`);+// Parameters stay bound, including literal substring search (percent and underscore+// in a prompt are not SQL wildcards). Count and page share exactly one predicate.+function assetFilter({ kind, q = '', hidden } = {}) {+ const params = [];+ const clauses = [];+ if (kind) { params.push(kind); clauses.push(`kind = $${params.length}`); }+ if (hidden !== undefined) {+ clauses.push(hidden ? `data->>'hidden' = 'true'` : `COALESCE(data->>'hidden', 'false') <> 'true'`);+ }+ for (const token of q.trim().toLowerCase().split(/\s+/).filter(Boolean)) {+ params.push(token);+ clauses.push(`strpos(lower(data::text), $${params.length}) > 0`);+ }+ return { params, where: clauses.length ? ` WHERE ${clauses.join(' AND ')}` : '' };+}++/** List index rows. Omitting limit retains the legacy array contract. */+export async function listAssets({ limit, offset = 0, ...filters } = {}) {+ const { params, where } = assetFilter(filters);+ let paging = '';+ if (limit !== undefined) {+ params.push(limit, offset);+ paging = ` LIMIT $${params.length - 1} OFFSET $${params.length}`;+ }+ const result = await query(+ `SELECT data FROM media_assets${where} ORDER BY created_at DESC, media_key ASC${paging}`, params,+ );return result.rows.map(rowToAsset);}-/**- * Count index rows. Optional `kind` filter ('image' | 'video').- *- * Use this over `listAssets().length` when only the tally is wanted: listAssets selects and- * JSON-parses the full payload of every rendered image and video, which is a lot of work to- * throw away for one number (the character skill registry reads this on every- * `GET /api/character`).- */-export async function countAssets({ kind } = {}) {- const result = kind- ? await query(`SELECT COUNT(*) AS count FROM media_assets WHERE kind = $1`, [kind])- : await query(`SELECT COUNT(*) AS count FROM media_assets`);+/** Count matching rows without materializing their JSONB payloads. */+export async function countAssets(filters = {}) {+ const { params, where } = assetFilter(filters);+ const result = await query(`SELECT COUNT(*) AS count FROM media_assets${where}`, params);return parseInt(result.rows[0].count, 10);}diff --git a/server/services/mediaAssetIndex/gallery.js b/server/services/mediaAssetIndex/gallery.jsnew file mode 100644index 0000000000..c7cb70a436--- /dev/null+++ b/server/services/mediaAssetIndex/gallery.js@@ -0,0 +1,19 @@+import { isTestRunner } from '../../lib/runtimeEnv.js';+import { listAssets, countAssets } from './db.js';++/** Bounded gallery reads. Disk remains the reconcile authority and test escape hatch. */+export async function listGalleryPage({ limit = 60, offset = 0, q = '', hidden } = {}, diskReader) {+ const filters = { kind: 'image', q, hidden };+ if (process.env.MEMORY_BACKEND === 'file' || isTestRunner()) {+ const read = diskReader || (await import('../imageGen/local.js')).listGallery;+ const tokens = q.trim().toLowerCase().split(/\s+/).filter(Boolean);+ const items = (await read()).filter(item =>+ (hidden === undefined || !!item.hidden === hidden)+ && tokens.every(token => JSON.stringify(item).toLowerCase().includes(token)));+ return { items: items.slice(offset, offset + limit), total: items.length, limit, offset };+ }+ const [items, total] = await Promise.all([+ listAssets({ ...filters, limit, offset }), countAssets(filters),+ ]);+ return { items, total, limit, offset };+}diff --git a/server/services/mediaAssetIndex/gallery.test.js b/server/services/mediaAssetIndex/gallery.test.jsnew file mode 100644index 0000000000..362e7adc1a--- /dev/null+++ b/server/services/mediaAssetIndex/gallery.test.js@@ -0,0 +1,36 @@+import { describe, it, expect, vi, afterEach } from 'vitest';+import { listGalleryPage } from './gallery.js';+import { query } from '../../lib/db.js';++vi.mock('../../lib/db.js', () => ({ query: vi.fn() }));+afterEach(() => { vi.unstubAllEnvs(); vi.resetAllMocks(); });++describe('indexed gallery page', () => {+ it('bounds production SQL reads and preserves metadata without invoking disk', async () => {+ vi.stubEnv('NODE_ENV', 'production');+ vi.stubEnv('VITEST', undefined);+ vi.stubEnv('MEMORY_BACKEND', 'db');+ const item = { filename: 'fox.png', path: '/data/images/fox.png', prompt: '100% fox', seed: 8 };+ query.mockImplementation(async sql => sql.includes('COUNT(*)')+ ? { rows: [{ count: '27' }] } : { rows: [{ data: item }] });+ const disk = vi.fn();+ expect(await listGalleryPage({ limit: 5, offset: 10, q: '100% fox', hidden: false }, disk))+ .toEqual({ items: [item], total: 27, limit: 5, offset: 10 });+ const [sql, params] = query.mock.calls.find(([sql]) => sql.startsWith('SELECT data'));+ expect(sql).toContain('ORDER BY created_at DESC, media_key ASC LIMIT $4 OFFSET $5');+ expect(params).toEqual(['image', '100%', 'fox', 5, 10]);+ expect(sql).toContain('strpos(lower(data::text), $2)');+ expect(sql).toContain("COALESCE(data->>'hidden', 'false') <> 'true'");+ expect(disk).not.toHaveBeenCalled();+ });++ it('does not turn an index failure into a full disk scan', async () => {+ vi.stubEnv('NODE_ENV', 'production');+ vi.stubEnv('VITEST', undefined);+ vi.stubEnv('MEMORY_BACKEND', 'db');+ query.mockRejectedValue(new Error('database unavailable'));+ const disk = vi.fn();+ await expect(listGalleryPage({}, disk)).rejects.toThrow('database unavailable');+ expect(disk).not.toHaveBeenCalled();+ });+});diff --git a/server/services/mediaAssetIndex/index.js b/server/services/mediaAssetIndex/index.jsindex 11b8934cb8..ca1fdb68fe 100644--- a/server/services/mediaAssetIndex/index.js+++ b/server/services/mediaAssetIndex/index.js@@ -37,7 +37,8 @@ function isEscapeHatch() {// Index a single just-generated image. The 'completed' event carries the// filename; the full metadata is in the sidecar the generator just wrote.-async function onImageCompleted({ filename, temp } = {}) {+export async function indexImage({ filename, temp } = {}) {+ if (isEscapeHatch()) return;if (typeof filename !== 'string' || !filename) return;// A non-gallery temp render (issue #2264, Image Cleaner GPU pass) has no// gallery file or sidecar — skip indexing it. It lives in imageCleanTmp and@@ -45,13 +46,15 @@ async function onImageCompleted({ filename, temp } = {}) {if (temp) return;const { readImageSidecar } = await import('../imageGen/local.js');const { metadata } = await readImageSidecar(filename);- // Mirror listGallery's entry shape (filename + path + spread sidecar). One- // intentional gap: listGallery synthesizes createdAt from the file birthtime- // when the sidecar lacks one (e.g. external/SD-mode images write no sidecar);- // the hook has no stat here, so a sidecar-less image's createdAt falls back to- // `now` in imageToRow and is corrected on the next boot reconcile (which is- // the source of truth for createdAt). Cosmetic: only the sort key jitters.- const row = imageToRow({ filename, path: `/data/images/${filename}`, ...metadata });+ // Match disk gallery's timestamp fallback for uploads without a sidecar.+ let createdAt = metadata.createdAt;+ if (!createdAt) {+ const [{ stat }, { join }, { PATHS }] = await Promise.all([+ import('node:fs/promises'), import('node:path'), import('../../lib/fileUtils.js'),+ ]);+ createdAt = (await stat(join(PATHS.images, filename))).birthtime.toISOString();+ }+ const row = imageToRow({ filename, path: `/data/images/${filename}`, createdAt, ...metadata });await upsertAsset(row).catch((err) => console.error(`❌ Media index image upsert failed: ${err.message}`));}@@ -113,7 +116,7 @@ export async function initMediaAssetIndex() {// The completed handlers run outside the request lifecycle (event emitter),// so an uncaught throw would crash Node — each handler is self-contained and// its upsert .catch()es. Wrap the dispatch too, defensively.- imageGenEvents.on('completed', (p) => { onImageCompleted(p).catch((err) => console.error(`❌ Media index image hook: ${err.message}`)); });+ imageGenEvents.on('completed', (p) => { indexImage(p).catch((err) => console.error(`❌ Media index image hook: ${err.message}`)); });videoGenEvents.on('completed', (p) => { onVideoCompleted(p).catch((err) => console.error(`❌ Media index video hook: ${err.message}`)); });subscribed = true;}