Skip to content

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

fix: hydrate opened images from their variant group, not a second lookup (#8341)

[._.]/ Adam Eivyc669f65a4a3b
diff --git a/client/src/components/media/MediaPreview.test.jsx b/client/src/components/media/MediaPreview.test.jsx
index 30c30545bc..441325f054 100644
--- a/client/src/components/media/MediaPreview.test.jsx
+++ b/client/src/components/media/MediaPreview.test.jsx
@@ -191,7 +191,10 @@ describe('MediaPreview variant toggle', () => {
fireEvent.click(screen.getByRole('button', { name: 'Open image' }));
await waitFor(() => expect(screen.getByRole('button', { name: otherLabel })).toBeInTheDocument());
- expect(listImageVariants).toHaveBeenCalledWith(open.filename, expect.objectContaining({ signal: expect.anything() }));
+ // No AbortSignal: the read is de-duped with `useHydratedPreviewRoute`
+ // (mediaDetail.js's `fetchImageVariantGroup`, #8341), and aborting one
+ // caller's copy would also cancel the other's share of it.
+ expect(listImageVariants).toHaveBeenCalledWith(open.filename);
// Selecting the other variant must OPEN it — the host cannot resolve that
// filename from its own list, so usePreviewRoute's seeding carries it.
diff --git a/client/src/components/media/mediaDetail.js b/client/src/components/media/mediaDetail.js
index 89d1032fed..b4016faee9 100644
--- a/client/src/components/media/mediaDetail.js
+++ b/client/src/components/media/mediaDetail.js
@@ -1,4 +1,4 @@
-import { getGalleryImages, getVideoHistoryItem } from '../../services/apiImageVideo';
+import { getGalleryImages, getVideoHistoryItem, listImageVariants } from '../../services/apiImageVideo';
import { normalizeImage, normalizeVideo } from './normalize';
/**
@@ -20,13 +20,57 @@ export function mediaRecordRef(item) {
return null;
}
-/** Resolves the stored record, or null when the server holds none. */
-export function fetchMediaRecord(kind, ref) {
- if (kind === 'video') return getVideoHistoryItem(ref, { silent: true });
+// GET /image-gen/:filename/variants read in flight, keyed by filename. This
+// hydration module (`fetchMediaRecord`, below) and `useImageVariants` (the
+// lightbox's original-vs-cleaned toggle) both want this SAME group the
+// instant a preview opens — the group always carries the opened filename's
+// own full record — and their effects commit in the same React flush, so a
+// plain fetch from each site would transfer the same ~group twice (#8341).
+// De-duped only while in flight, not cached past resolution: a later reopen
+// asks the server fresh.
+const variantGroupRequests = new Map();
+
+/**
+ * Raw (unnormalized) variant-group read for one image filename, shared across
+ * every caller that wants it for the same open. Rejects like the underlying
+ * `listImageVariants` call; callers decide their own fallback.
+ */
+export function fetchImageVariantGroup(filename) {
+ if (!filename) return Promise.resolve(null);
+ let request = variantGroupRequests.get(filename);
+ if (!request) {
+ request = listImageVariants(filename)
+ .then((result) => (Array.isArray(result?.items) ? result.items : null))
+ .finally(() => {
+ if (variantGroupRequests.get(filename) === request) variantGroupRequests.delete(filename);
+ });
+ variantGroupRequests.set(filename, request);
+ }
+ return request;
+}
+
+function fetchGalleryLookup(ref) {
return getGalleryImages([ref], { silent: true })
.then((list) => (Array.isArray(list) ? list : []).find((i) => i?.filename === ref) || null);
}
+/**
+ * Resolves the stored record, or null when the server holds none. An image
+ * routes through the shared variant-group read first — that group always
+ * carries the opened filename's own record — so the lightbox costs exactly
+ * one full-record transfer instead of a separate `gallery/lookup` PLUS the
+ * `variants` read `MediaPreview` makes for the original-vs-cleaned toggle.
+ * Falls back to `gallery/lookup` when the variants read fails, or when the
+ * group resolves without the filename (not indexed). Videos have no variants
+ * endpoint and always use the history read.
+ */
+export function fetchMediaRecord(kind, ref) {
+ if (kind === 'video') return getVideoHistoryItem(ref, { silent: true });
+ return fetchImageVariantGroup(ref)
+ .then((items) => (items || []).find((item) => item?.filename === ref) || fetchGalleryLookup(ref))
+ .catch(() => fetchGalleryLookup(ref));
+}
+
/**
* Merge a fetched record over the host's item. The record wins on every field
* it carries; the host's `key` is kept outright, since prev/next nav and the
diff --git a/client/src/hooks/useImageVariants.js b/client/src/hooks/useImageVariants.js
index c894370164..74ed4a38f0 100644
--- a/client/src/hooks/useImageVariants.js
+++ b/client/src/hooks/useImageVariants.js
@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
-import { listImageVariants } from '../services/apiImageVideo';
+import { fetchImageVariantGroup } from '../components/media/mediaDetail';
import { normalizeImage } from '../components/media/normalize';
/**
@@ -33,18 +33,19 @@ export default function useImageVariants(item) {
&& (fetched?.filename === filename || !!fetched?.items?.some((variant) => variant.filename === filename));
useEffect(() => {
if (!filename || holds) return undefined;
- // Abort saves the server the work; `cancelled` guards the state write,
- // because `request()` reports an abort as an ordinary failure and a late
- // rejection would otherwise overwrite the next image's result.
+ // `fetchImageVariantGroup` (mediaDetail.js) de-dupes this read against
+ // `useHydratedPreviewRoute` hydrating the SAME filename at the same
+ // moment (#8341) — no AbortController here, because aborting would also
+ // cancel the other caller's share of the in-flight request. `cancelled`
+ // alone guards the state write against a stale response.
let cancelled = false;
- const controller = new AbortController();
- listImageVariants(filename, { signal: controller.signal })
- .then((result) => {
- if (!cancelled) setFetched({ filename, items: Array.isArray(result?.items) ? result.items.map(normalizeImage) : null });
+ fetchImageVariantGroup(filename)
+ .then((items) => {
+ if (!cancelled) setFetched({ filename, items: Array.isArray(items) ? items.map(normalizeImage) : null });
})
// Non-fatal: `items: null` hands the answer back to the caller's list.
.catch(() => { if (!cancelled) setFetched({ filename, items: null }); });
- return () => { cancelled = true; controller.abort(); };
+ return () => { cancelled = true; };
}, [filename, holds]);
return holds ? fetched.items : null;
}
diff --git a/client/src/hooks/useMediaPreviewActions.test.jsx b/client/src/hooks/useMediaPreviewActions.test.jsx
index 9e1807278f..092d3ece0e 100644
--- a/client/src/hooks/useMediaPreviewActions.test.jsx
+++ b/client/src/hooks/useMediaPreviewActions.test.jsx
@@ -11,6 +11,10 @@ vi.mock('../services/apiImageVideo', () => ({
removeImageWatermark: vi.fn(),
getGalleryImages: vi.fn(),
getVideoHistoryItem: vi.fn(),
+ // Hydration tries this first (mediaDetail.js's `fetchImageVariantGroup`,
+ // #8341); an empty group falls back to `getGalleryImages` exactly like the
+ // "not indexed" case the tests below exercise.
+ listImageVariants: vi.fn(async () => ({ items: [] })),
}));
import { removeImageWatermark, cleanGalleryImage, extractLastFrame, getGalleryImages, getVideoHistoryItem } from '../services/apiImageVideo';
diff --git a/client/src/pages/DeckDetail.preview.test.jsx b/client/src/pages/DeckDetail.preview.test.jsx
index c43ba925b7..67ccc275dd 100644
--- a/client/src/pages/DeckDetail.preview.test.jsx
+++ b/client/src/pages/DeckDetail.preview.test.jsx
@@ -27,6 +27,10 @@ vi.mock('../services/api', () => ({
vi.mock('../services/apiImageVideo', () => ({
getGalleryImages: (...a) => getGalleryImages(...a),
getVideoHistoryItem: (...a) => getVideoHistoryItem(...a),
+ // Hydration tries this first (mediaDetail.js's `fetchImageVariantGroup`,
+ // #8341); an empty group falls back to `getGalleryImages` below exactly
+ // like the "not indexed" case these tests exercise.
+ listImageVariants: vi.fn(async () => ({ items: [] })),
}));
vi.mock('../components/media/MediaPreview', () => ({
default: (props) => { previewProps = props; return null; },
diff --git a/client/src/pages/MediaHistory.test.jsx b/client/src/pages/MediaHistory.test.jsx
index 51ad10f746..f2abdaa8ae 100644
--- a/client/src/pages/MediaHistory.test.jsx
+++ b/client/src/pages/MediaHistory.test.jsx
@@ -2,8 +2,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
-const { fetchPage, deleteImage, saveAnnotation, getGalleryImages, getVideoHistoryItem } = vi.hoisted(() => ({ fetchPage: vi.fn(), deleteImage: vi.fn(), saveAnnotation: vi.fn(), getGalleryImages: vi.fn(), getVideoHistoryItem: vi.fn() }));
-vi.mock('../services/apiImageVideo', () => ({ listMediaGalleryPage: fetchPage, getGalleryImages, getVideoHistoryItem }));
+const { fetchPage, deleteImage, saveAnnotation, getGalleryImages, getVideoHistoryItem, listImageVariants } = vi.hoisted(() => ({ fetchPage: vi.fn(), deleteImage: vi.fn(), saveAnnotation: vi.fn(), getGalleryImages: vi.fn(), getVideoHistoryItem: vi.fn(), listImageVariants: vi.fn() }));
+vi.mock('../services/apiImageVideo', () => ({ listMediaGalleryPage: fetchPage, getGalleryImages, getVideoHistoryItem, listImageVariants }));
vi.mock('../services/api', () => ({ listMediaGalleryPage: fetchPage, deleteImage, deleteVideoHistoryItem: vi.fn(), stitchVideos: vi.fn() }));
vi.mock('../hooks/useMediaCompletionRefresh', () => ({ useMediaCompletionRefresh: () => {} }));
vi.mock('../hooks/useMediaAnnotations', () => ({ useMediaAnnotations: () => ({ annotations: {}, updateAnnotation: saveAnnotation, getCardProps: () => ({}) }) }));
@@ -23,6 +23,11 @@ beforeEach(() => {
return { items: matches.slice(offset, offset + limit), total: matches.length, offset, limit, counts: { all: matches.length, image: matches.length, video: 0 } };
});
getGalleryImages.mockImplementation(async filenames => rows.filter(row => filenames.includes(row.data.filename)).map(row => row.data));
+ // Hydration tries the variants group first (mediaDetail.js's
+ // `fetchImageVariantGroup`, #8341); resolving "not indexed" by default
+ // falls back to `getGalleryImages` so the existing hydration tests below
+ // exercise that fallback exactly as before.
+ listImageVariants.mockImplementation(async () => ({ items: [] }));
deleteImage.mockImplementation(async filename => { rows = rows.filter(row => row.data.filename !== filename); return { ok: true }; });
});
const open = (url = '/media/history') => render(<MemoryRouter initialEntries={[url]}><MediaHistory /></MemoryRouter>);
@@ -76,6 +81,28 @@ describe('bounded media history', () => {
expect(getGalleryImages).toHaveBeenCalledWith(['0.png'], { silent: true });
});
+ // #8341: opening an image used to cost two full-record reads (this
+ // hydration's `gallery/lookup` PLUS the lightbox's own `variants` read for
+ // the original-vs-cleaned toggle). The variants group always carries the
+ // opened filename's own record, so hydration takes it from there and never
+ // falls back to `getGalleryImages`.
+ it('hydrates an opened image from the variants group without a separate gallery lookup', async () => {
+ const full = 'Picture 0 ' + 'with a long stored prompt '.repeat(30);
+ rows[0].data.prompt = full;
+ fetchPage.mockImplementation(async ({ offset = 0 }) => ({
+ items: rows.slice(offset, offset + 60).map(row => ({ kind: row.kind, data: { ...row.data, compact: true, prompt: row.data.prompt.slice(0, 12) + '…' } })),
+ total: rows.length, offset, limit: 60, counts: { all: rows.length, image: rows.length, video: 0 },
+ }));
+ listImageVariants.mockImplementation(async filename => ({
+ items: filename === '0.png' ? [rows[0].data] : [],
+ }));
+ open();
+ fireEvent.click(await screen.findByRole('button', { name: 'Picture 0 wi…' }));
+ expect(await screen.findByRole('dialog')).toHaveTextContent(full.trim());
+ expect(listImageVariants).toHaveBeenCalledWith('0.png');
+ expect(getGalleryImages).not.toHaveBeenCalled();
+ });
+
it('marks a compact record whose detail read fails instead of passing its preview off as complete', async () => {
fetchPage.mockImplementation(async ({ offset = 0 }) => ({
items: rows.slice(offset, offset + 60).map(row => ({ kind: row.kind, data: { ...row.data, compact: true } })),
diff --git a/scripts/perf/browserCollectionAudit.mjs b/scripts/perf/browserCollectionAudit.mjs
index 311e31dafe..7b4b4669f7 100644
--- a/scripts/perf/browserCollectionAudit.mjs
+++ b/scripts/perf/browserCollectionAudit.mjs
@@ -44,7 +44,7 @@ async function scenario(route) {
if (url.origin !== fixture.url) return;
const endpoint = endpointFor(response.url());
const responsePhase = phase;
- if (endpoint !== listEndpoint && !['/api/messages/:account/:message', '/api/video-gen/history/:record', '/api/image-gen/gallery/lookup'].includes(endpoint)) return;
+ if (endpoint !== listEndpoint && !['/api/messages/:account/:message', '/api/video-gen/history/:record', '/api/image-gen/:record/variants'].includes(endpoint)) return;
const inspect = (async () => {
if (response.status() !== 200) {
failures.push({ endpoint, reason: 'collection-http-status', count: response.status(), bytes: 0 }); return;
@@ -61,7 +61,13 @@ async function scenario(route) {
failures.push(...inspected.failures);
} else {
details++;
- if (responsePhase !== 'detail' || (media ? !((Array.isArray(payload) ? payload[0]?.prompt : payload.prompt)?.length >= fixture.cardinalities.detailCharacters) : payload.bodyText?.length !== fixture.cardinalities.detailCharacters)) {
+ // Media detail now arrives as the variants group ({ items: [...] },
+ // the opened filename's own record among them) rather than the
+ // retired gallery/lookup array (#8341); an object payload (video
+ // history) still carries `prompt` directly.
+ const mediaPrompt = Array.isArray(payload) ? payload[0]?.prompt
+ : Array.isArray(payload?.items) ? payload.items[0]?.prompt : payload.prompt;
+ if (responsePhase !== 'detail' || (media ? !(mediaPrompt?.length >= fixture.cardinalities.detailCharacters) : payload.bodyText?.length !== fixture.cardinalities.detailCharacters)) {
failures.push({ endpoint, reason: 'lazy-detail-contract', bytes: body.length });
}
}
diff --git a/scripts/perf/collectionFixture.db.test.js b/scripts/perf/collectionFixture.db.test.js
index df85e6e942..2ae1b6c993 100644
--- a/scripts/perf/collectionFixture.db.test.js
+++ b/scripts/perf/collectionFixture.db.test.js
@@ -65,6 +65,10 @@ describe('isolated fixture using real collection routes and storage', () => {
headers: { 'content-type': 'application/json' }, body: JSON.stringify({ filenames: [image.filename] }) });
expect(lookup.status).toBe(200);
expect((await lookup.json())[0].prompt.length).toBeGreaterThanOrEqual(8192);
+ // The lazy-detail read the lightbox actually makes on open (#8341): the
+ // group always carries the opened filename's own full record.
+ const variants = await get('/api/image-gen/' + encodeURIComponent(image.filename) + '/variants');
+ expect(variants.items.some(item => item.filename === image.filename && item.prompt.length >= 8192)).toBe(true);
const video = compact.items.find(item => item.kind === 'video').data;
expect((await get('/api/video-gen/history/' + video.id)).prompt.length).toBeGreaterThanOrEqual(8192);
const inbox = await get('/api/messages/inbox?limit=11&offset=20&summary=true');
diff --git a/scripts/perf/collectionFixtureWorker.js b/scripts/perf/collectionFixtureWorker.js
index 32aa3d6ec1..9dc4b3f15a 100644
--- a/scripts/perf/collectionFixtureWorker.js
+++ b/scripts/perf/collectionFixtureWorker.js
@@ -106,6 +106,16 @@ async function start() {
// Bounded record hydration the migrated Media History detail view uses.
// Lookup is a POST read; every other non-GET image-gen call stays refused.
gallery.post('/gallery/lookup', express.json({ limit: '64kb' }), galleryReads.lookup);
+ // The lazy-detail read the lightbox actually makes on open (#8341):
+ // hydration and the original-vs-cleaned toggle both resolve from this
+ // group, which always carries the opened filename's own record, instead of
+ // the `gallery/lookup` POST above.
+ gallery.get('/:filename/variants', asyncHandler(async (req, res) => {
+ const { assertGalleryFilename } = await import('../../server/services/imageGen/local.js');
+ assertGalleryFilename(req.params.filename);
+ const { listImageVariants } = await import('../../server/services/mediaAssetIndex/gallery.js');
+ res.json({ items: await listImageVariants(req.params.filename) });
+ }));
app.use('/api/image-gen', (req, res, next) => req.method === 'GET' || req.path === '/gallery/lookup' ? next() : res.sendStatus(405), gallery);
app.get('/api/video-gen/history/:id', createVideoHistoryItemRead());
const messages = express.Router();
diff --git a/scripts/perf/collectionTraffic.js b/scripts/perf/collectionTraffic.js
index b83cf26c35..63a181ab35 100644
--- a/scripts/perf/collectionTraffic.js
+++ b/scripts/perf/collectionTraffic.js
@@ -116,7 +116,7 @@ export function trafficFailures(phases) {
if (['sibling', 'idle'].includes(phase) && endpoint === '/api/messages/inbox' && row.requests) {
failures.push({ endpoint, reason: 'sibling-inbox-fetch', count: row.requests, bytes: row.encodedBytes });
}
- if (phase === 'cold' && ['/api/messages/:account/:message', '/api/video-gen/history/:record', '/api/image-gen/gallery/lookup'].includes(endpoint) && row.requests) {
+ if (phase === 'cold' && ['/api/messages/:account/:message', '/api/video-gen/history/:record', '/api/image-gen/:record/variants'].includes(endpoint) && row.requests) {
failures.push({ endpoint, reason: 'eager-detail-request', count: row.requests, bytes: row.encodedBytes });
}
if (['/api/video-gen/history', '/api/image-gen/history'].includes(endpoint) && row.requests) {