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

resolve the original-vs-cleaned toggle server-side so it works from either end (#7346)

[._.]/ Adam Eivy00ea6bd8df6e
diff --git a/client/src/components/media/MediaPreview.jsx b/client/src/components/media/MediaPreview.jsx
index 516f9c67f9..f775771073 100644
--- a/client/src/components/media/MediaPreview.jsx
+++ b/client/src/components/media/MediaPreview.jsx
@@ -2,6 +2,7 @@ import { useMemo, useCallback, useEffect, useState } from 'react';
import MediaLightbox from './MediaLightbox';
import { getMediaNavProps } from '../../lib/mediaNavigation';
import { computeImageVariantGroup } from './variants';
+import useImageVariants from '../../hooks/useImageVariants';
import { updateImagePrompt, updateVideoPrompt } from '../../services/apiImageVideo';
// Thin wrapper around MediaLightbox that owns the consistent wiring every
@@ -45,28 +46,54 @@ export default function MediaPreview({
raw: preview.raw ? { ...preview.raw, prompt: prompt === '(no prompt)' ? '' : prompt } : preview.raw,
};
}, [preview, promptOverride]);
- // Original-vs-cleaned toggle. Computed from the same `items` list that
- // drives prev/next nav — so if the cleaned copy was auto-filed into this
- // page's source collection, both variants are present and the toggle
- // appears. Returns null for non-image previews or single-variant items.
+ // Original-vs-cleaned toggle, computed over the UNION of the host's items
+ // and the image's fetched lineage — neither source alone is complete. The
+ // host list misses a copy it never held (see useImageVariants), while the
+ // fetched set misses one the user just made, because a Clean splices the new
+ // variant into the host's state (useMediaPreviewActions' onCleanComplete)
+ // after the server set was read. Returns null for a non-image preview or a
+ // lone variant.
//
- // `preview` is substituted for its own entry in that list first. A host that
- // hydrates the OPEN item only (`useHydratedPreviewRoute`) learns `cleanedFrom`
- // for the preview and not for the row it came from — and this scan matches
- // cleaned copies by reading `cleanedFrom` off the LIST, so without the
- // substitution the open cleaned image never finds its own original and the
- // toggle stays inert on exactly the pages that hydrate lazily.
- const variantItems = useMemo(() => {
- if (!preview || !Array.isArray(items)) return items;
- const index = items.findIndex((i) => i?.key === preview.key);
- if (index === -1 || items[index] === preview) return items;
- const next = items.slice();
- next[index] = preview;
- return next;
- }, [items, preview]);
+ // `preview` is substituted for its own entry in the host list first, which
+ // is what the list scan needs while the lookup is in flight or after it
+ // failed: a host that hydrates the OPEN item only (`useHydratedPreviewRoute`)
+ // learns `cleanedFrom` for the preview and not for the row it came from, and
+ // the scan reads `cleanedFrom` off the LIST.
+ const fetchedVariants = useImageVariants(preview);
+ const variantCandidates = useMemo(() => {
+ let list = Array.isArray(items) ? items : [];
+ if (preview) {
+ const index = list.findIndex((i) => i?.key === preview.key);
+ if (index !== -1 && list[index] !== preview) {
+ list = list.slice();
+ list[index] = preview;
+ }
+ }
+ // A union with an empty set is the list itself — the short-circuit is an
+ // optimization, not a read of `[]` as "not fetched".
+ if (!fetchedVariants?.length) return list;
+ const hostByFilename = new Map(list
+ .filter((item) => item?.kind === 'image' && item.filename)
+ .map((item) => [item.filename, item]));
+ // The fetched record wins on LINEAGE — that is the whole point, since the
+ // host's own row is exactly what may not carry `cleanedFrom`. But the
+ // host's `key` wins outright wherever it lists the same file: picking a
+ // variant writes that key to the URL, and prev/next nav (getAdjacentMedia)
+ // and the annotation lookup both match on it, so a key that drifted from
+ // the list would silently disable both (same contract useHydratedPreviewRoute
+ // keeps when it merges a record over a host item).
+ const byFilename = new Map(fetchedVariants.map((variant) => {
+ const hosted = hostByFilename.get(variant.filename);
+ return [variant.filename, hosted ? { ...variant, key: hosted.key } : variant];
+ }));
+ for (const [filename, item] of hostByFilename) {
+ if (!byFilename.has(filename)) byFilename.set(filename, item);
+ }
+ return [...byFilename.values()];
+ }, [fetchedVariants, items, preview]);
const variantGroup = useMemo(
- () => computeImageVariantGroup(preview, variantItems),
- [preview, variantItems]
+ () => computeImageVariantGroup(preview, variantCandidates),
+ [preview, variantCandidates]
);
const onSelectVariant = useCallback((nextItem) => {
if (!nextItem) return;
diff --git a/client/src/components/media/MediaPreview.test.jsx b/client/src/components/media/MediaPreview.test.jsx
index a14680dbb1..30c30545bc 100644
--- a/client/src/components/media/MediaPreview.test.jsx
+++ b/client/src/components/media/MediaPreview.test.jsx
@@ -1,29 +1,36 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { useState } from 'react';
+import { useMemo, useState } from 'react';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter, useLocation } from 'react-router';
import MediaPreview from './MediaPreview';
import usePreviewRoute from '../../hooks/usePreviewRoute';
-import { updateVideoPrompt } from '../../services/apiImageVideo';
+import { updateVideoPrompt, listImageVariants, listMediaGalleryPage } from '../../services/apiImageVideo';
vi.mock('../../services/apiImageVideo', () => ({
updateImagePrompt: vi.fn(),
updateVideoPrompt: vi.fn(),
+ listImageVariants: vi.fn(),
+ listMediaGalleryPage: vi.fn(),
}));
// Keep this test focused on the wrapper's save/state contract. The lightbox has
// its own interaction coverage; this stub exposes the item it receives and
// invokes the same callback the real Save prompt button uses.
vi.mock('./MediaLightbox', () => ({
- default: ({ item, onPromptChange, variantGroup }) => item ? (
+ default: ({ item, onPromptChange, variantGroup, onSelectVariant }) => item ? (
<div data-testid="lightbox">
<span data-testid="lightbox-prompt">{item.prompt}</span>
+ <span data-testid="lightbox-filename">{item.filename}</span>
<button type="button" onClick={() => onPromptChange(item, 'a saved prompt')}>
Save prompt
</button>
{variantGroup && (
<ul data-testid="variant-group">
- {variantGroup.group.map((v) => <li key={v.item.key}>{v.label}</li>)}
+ {variantGroup.group.map((entry) => (
+ <li key={entry.item.filename}>
+ <button type="button" onClick={() => onSelectVariant(entry.item)}>{entry.label}</button>
+ </li>
+ ))}
</ul>
)}
</div>
@@ -111,7 +118,16 @@ describe('MediaPreview prompt saving', () => {
});
});
-describe('MediaPreview variant group', () => {
+describe('MediaPreview variant group — list-scan fallback', () => {
+ // Pinned with the lookup failing, because that is when the scan is the only
+ // source: a successful fetch supersedes it.
+ beforeEach(() => {
+ listImageVariants.mockReset();
+ listImageVariants.mockRejectedValue(new Error('offline'));
+ listMediaGalleryPage.mockReset();
+ listMediaGalleryPage.mockResolvedValue({ items: [] });
+ });
+
// A host that hydrates only the OPEN item (`useHydratedPreviewRoute`) hands
// us a `preview` carrying `cleanedFrom` while the row it came from — still in
// `items` — does not. The variant scan reads `cleanedFrom` off the list, so
@@ -127,13 +143,134 @@ describe('MediaPreview variant group', () => {
</MemoryRouter>,
);
- it('pairs a lazily hydrated cleaned image with its original', () => {
+ it('pairs a lazily hydrated cleaned image with its original', async () => {
renderWith(CLEANED_HYDRATED);
- expect(screen.getByTestId('variant-group').textContent).toBe('OriginalCleaned (light)');
+ await waitFor(() => expect(screen.getByTestId('variant-group').textContent).toBe('OriginalCleaned (light)'));
});
- it('renders no toggle when nothing in the set is a cleaned copy', () => {
+ it('renders no toggle when nothing in the set is a cleaned copy', async () => {
renderWith(ORIGINAL);
+ await waitFor(() => expect(listImageVariants).toHaveBeenCalled());
expect(screen.queryByTestId('variant-group')).toBeNull();
});
});
+
+// The original-vs-cleaned toggle. Neither source of lineage is complete on its
+// own: a host list can miss a copy it never held (a deck card, a scene ref, or
+// a gallery page whose 60-row window no longer reaches the other variant),
+// while the fetched set misses one the user just made in this session.
+const FOX = { filename: 'fox.png', prompt: 'a fox' };
+const FOX_CLEANED = { filename: 'fox_clean-resize-squeeze.png', prompt: 'a fox', cleanedFrom: 'fox.png', cleanLevel: 'resize-squeeze' };
+const asItem = (row) => ({ ...row, kind: 'image', key: `image:${row.filename}`, previewUrl: `/data/images/${row.filename}` });
+
+// The host lists only what it holds, exactly as a deck card or scene does.
+function VariantHarness({ hostRows = [FOX], open = FOX }) {
+ const items = useMemo(() => hostRows.map(asItem), [hostRows]);
+ const [preview, setPreview] = usePreviewRoute(items);
+ return (
+ <>
+ <button type="button" onClick={() => setPreview(asItem(open))}>Open image</button>
+ <MediaPreview preview={preview} setPreview={setPreview} items={items} />
+ </>
+ );
+}
+
+describe('MediaPreview variant toggle', () => {
+ beforeEach(() => {
+ listImageVariants.mockReset();
+ listImageVariants.mockResolvedValue({ items: [FOX, FOX_CLEANED] });
+ listMediaGalleryPage.mockReset();
+ listMediaGalleryPage.mockResolvedValue({ items: [] });
+ });
+
+ it.each([
+ ['the original', FOX, 'Cleaned (resize-squeeze)', FOX_CLEANED.filename],
+ ['a cleaned copy', FOX_CLEANED, 'Original', FOX.filename],
+ ])('offers the other variant when %s is opened from a host that lists neither', async (_label, open, otherLabel, otherFilename) => {
+ render(<MemoryRouter><VariantHarness hostRows={[open]} open={open} /></MemoryRouter>);
+ 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() }));
+
+ // Selecting the other variant must OPEN it — the host cannot resolve that
+ // filename from its own list, so usePreviewRoute's seeding carries it.
+ fireEvent.click(screen.getByRole('button', { name: otherLabel }));
+ await waitFor(() => expect(screen.getByTestId('lightbox-filename')).toHaveTextContent(otherFilename));
+ });
+
+ // The group is closed under the toggle, so the second click must not refetch
+ // an identical set — which would also blank the toggle for the round trip.
+ it('reuses the fetched group across toggle clicks', async () => {
+ render(<MemoryRouter><VariantHarness /></MemoryRouter>);
+ fireEvent.click(screen.getByRole('button', { name: 'Open image' }));
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Cleaned (resize-squeeze)' })).toBeInTheDocument());
+
+ fireEvent.click(screen.getByRole('button', { name: 'Cleaned (resize-squeeze)' }));
+ await waitFor(() => expect(screen.getByTestId('lightbox-filename')).toHaveTextContent(FOX_CLEANED.filename));
+ expect(screen.getByRole('button', { name: 'Original' })).toBeInTheDocument();
+ expect(listImageVariants).toHaveBeenCalledTimes(1);
+ });
+
+ // A Clean splices the new copy into the host list; the set fetched when the
+ // image opened predates it. Merging is what keeps the toggle from vanishing.
+ it('still offers a variant the host holds but the fetched set predates', async () => {
+ listImageVariants.mockResolvedValue({ items: [FOX] });
+ render(<MemoryRouter><VariantHarness hostRows={[FOX, FOX_CLEANED]} /></MemoryRouter>);
+ fireEvent.click(screen.getByRole('button', { name: 'Open image' }));
+
+ await waitFor(() => expect(listImageVariants).toHaveBeenCalled());
+ expect(screen.getByRole('button', { name: 'Cleaned (resize-squeeze)' })).toBeInTheDocument();
+ });
+
+ it('renders no toggle when neither source knows of another variant', async () => {
+ listImageVariants.mockResolvedValue({ items: [FOX] });
+ render(<MemoryRouter><VariantHarness /></MemoryRouter>);
+ fireEvent.click(screen.getByRole('button', { name: 'Open image' }));
+
+ await waitFor(() => expect(listImageVariants).toHaveBeenCalled());
+ expect(screen.queryByRole('button', { name: 'Original' })).not.toBeInTheDocument();
+ });
+
+ it('falls back to the host list when the lookup fails', async () => {
+ listImageVariants.mockRejectedValue(new Error('offline'));
+ render(<MemoryRouter><VariantHarness hostRows={[FOX, FOX_CLEANED]} /></MemoryRouter>);
+ fireEvent.click(screen.getByRole('button', { name: 'Open image' }));
+
+ await waitFor(() => expect(listImageVariants).toHaveBeenCalled());
+ expect(screen.getByRole('button', { name: 'Cleaned (resize-squeeze)' })).toBeInTheDocument();
+ });
+
+ // Picking a variant writes its key to the URL, and prev/next nav plus the
+ // annotation lookup both match on the HOST's key — a key taken from the
+ // fetched record would silently disable both on a host that keys its own way.
+ it('keeps the host key for a file the host lists, while taking the fetched lineage', async () => {
+ const nounKeyed = { ...asItem(FOX), key: 'noun:fox.png' };
+ function NounHarness() {
+ const items = useMemo(() => [nounKeyed], []);
+ const [preview, setPreview] = usePreviewRoute(items);
+ return (
+ <>
+ <button type="button" onClick={() => setPreview(nounKeyed)}>Open image</button>
+ <MediaPreview preview={preview} setPreview={setPreview} items={items} />
+ <LocationProbe />
+ </>
+ );
+ }
+ render(<MemoryRouter><NounHarness /></MemoryRouter>);
+ fireEvent.click(screen.getByRole('button', { name: 'Open image' }));
+ // The fetched lineage is what surfaces the toggle at all here.
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Cleaned (resize-squeeze)' })).toBeInTheDocument());
+
+ fireEvent.click(screen.getByRole('button', { name: 'Original' }));
+ await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('preview=noun%3Afox.png'));
+ });
+
+ it('fetches nothing for a video preview', async () => {
+ render(<MemoryRouter><PromptSaveHarness /></MemoryRouter>);
+ fireEvent.click(screen.getByRole('button', { name: 'Open video' }));
+
+ await waitFor(() => expect(screen.getByTestId('lightbox')).toBeInTheDocument());
+ expect(listImageVariants).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/media/normalize.js b/client/src/components/media/normalize.js
index 7bf24582c3..3877878d32 100644
--- a/client/src/components/media/normalize.js
+++ b/client/src/components/media/normalize.js
@@ -105,6 +105,11 @@ export function normalizeImage(i) {
};
}
+// Gallery/history rows arrive as { kind, data } from the mixed-media endpoints.
+// Three callers were each re-deriving this ternary; the row shape belongs here,
+// beside the two normalizers it dispatches between.
+export const normalizeMediaRow = (row) => (row.kind === 'image' ? normalizeImage(row.data) : normalizeVideo(row.data));
+
export function normalizeVideo(v) {
const loraNames = (pickLoraFilenames(v) || []).filter(Boolean);
return {
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 9ddd292450..8c514836c2 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -247,4 +247,6 @@ grep -i "what you want to do" client/src/hooks/README.md
|---|---|---|
| `useEidoverseFrame` | Per-load Eidoverse handshake with origin/window/session validation and browser-only label preferences. | Embedding the managed Eidoverse renderer. |
| `useGallerySidecars` | Hydrates a known filename list into its image-metadata sidecars (the prompt actually sent, negative, model, seed, size), keyed on contents rather than array identity, with a `setSidecar` splice for a freshly written record. | Any page showing renders it owns the refs for (universe draft, deck cards) that must open the lightbox on the real render prompt. |
+| `useGalleryPreviewResolver` | Builds the stable `resolveItem` callback that resolves a `?preview=` param the host's own items list does not contain, by looking the record up in the gallery and normalizing it. `usePreviewRoute` uses it as its DEFAULT. | Call it directly only to narrow the lookup — `collectionId` scopes it to one collection. |
+| `useImageVariants` | Fetches the original-vs-cleaned variant set for the one open image (`GET /api/image-gen/:filename/variants`), normalized; reuses the held group across toggle clicks and aborts a superseded lookup. `null` while unfetched or failed, `[]` when the image is not indexed. | `MediaPreview` calls it for every image preview; neither a page-owned ref list nor a 60-row gallery window is a complete source of variant lineage. |
| `useGalleryPage` | Bounded image or mixed-media browsing with debounced server search, scopes, totals, stale-response cancellation and retryable next pages. | Gallery grids and pickers; `getGalleryImages` hydrates known references separately. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 5a0db13b86..6fed651dbd 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -27,6 +27,8 @@ export { default as useFieldDraft } from './useFieldDraft.js';
export { default as useFableLoomAiRun } from './useFableLoomAiRun.js';
export { default as useFocusTrap } from './useFocusTrap.js';
export { default as useGallerySidecars } from './useGallerySidecars.js';
+export { default as useGalleryPreviewResolver } from './useGalleryPreviewResolver.js';
+export { default as useImageVariants } from './useImageVariants.js';
export { default as useNoteSave } from './useNoteSave.js';
export { default as useHoverTooltip } from './useHoverTooltip.js';
export { default as useHydratedPreviewRoute } from './useHydratedPreviewRoute.js';
diff --git a/client/src/hooks/useGalleryPreviewResolver.js b/client/src/hooks/useGalleryPreviewResolver.js
new file mode 100644
index 0000000000..48bf52daa4
--- /dev/null
+++ b/client/src/hooks/useGalleryPreviewResolver.js
@@ -0,0 +1,28 @@
+import { useCallback } from 'react';
+import { listMediaGalleryPage } from '../services/apiImageVideo';
+import { normalizeMediaRow } from '../components/media/normalize';
+
+/**
+ * `resolveItem` for `usePreviewRoute` — resolve a `?preview=` param the host's
+ * own items list cannot account for, by looking the record up in the gallery.
+ * `usePreviewRoute` uses this as its default, so a host only calls it directly
+ * to scope the lookup to one collection.
+ *
+ * `key` is what `usePreviewRoute` put in the URL — an `image:`/`video:` key, or
+ * a bare filename for hosts that never prefixed one.
+ *
+ * @param {object} [options]
+ * @param {string} [options.collectionId] - scope the lookup to one collection
+ * @returns {Function} stable async `(key) => normalized item | null`
+ */
+export default function useGalleryPreviewResolver({ collectionId } = {}) {
+ return useCallback(async (key) => {
+ const kind = key.startsWith('video:') ? 'video' : key.startsWith('image:') ? 'image' : 'all';
+ const filename = key.replace(/^(image|video):/, '');
+ const page = await listMediaGalleryPage(
+ { limit: 1, kind, filename, ...(collectionId ? { collectionId } : {}) },
+ { silent: true },
+ );
+ return page.items[0] ? normalizeMediaRow(page.items[0]) : null;
+ }, [collectionId]);
+}
diff --git a/client/src/hooks/useHydratedPreviewRoute.js b/client/src/hooks/useHydratedPreviewRoute.js
index 1eb34a6f99..df7ebe593e 100644
--- a/client/src/hooks/useHydratedPreviewRoute.js
+++ b/client/src/hooks/useHydratedPreviewRoute.js
@@ -24,12 +24,11 @@ import { normalizeImage, normalizeVideo } from '../components/media/normalize';
* the lightbox (Universe Builder reads them for thumbs) still wants the eager
* `useGallerySidecars` map.
*
- * One item is the wrong unit for anything set-level, so lineage is only PARTLY
- * restored: `MediaPreview` substitutes the hydrated preview into the list it
- * scans, which is enough to pair an open CLEANED copy with its original, but
- * opening the original finds no cleaned sibling, because the siblings in the
- * list still carry no `cleanedFrom`. Hydrating the whole list is the only shape
- * that serves both directions — see #7346.
+ * One item is the wrong unit for anything set-level, so the variant toggle is
+ * no longer built from this at all: `MediaPreview` asks the server for the
+ * open image's lineage (`useImageVariants`), which answers both directions from
+ * either end. Substituting the hydrated preview into the scanned list remains
+ * the fallback while that lookup is in flight or after it fails (#7346).
*
* The record wins on every field it carries; the host's item is the fallback,
* and its `key` is kept outright — prev/next nav (`getAdjacentMedia`) and the
diff --git a/client/src/hooks/useImageVariants.js b/client/src/hooks/useImageVariants.js
new file mode 100644
index 0000000000..c894370164
--- /dev/null
+++ b/client/src/hooks/useImageVariants.js
@@ -0,0 +1,50 @@
+import { useEffect, useState } from 'react';
+import { listImageVariants } from '../services/apiImageVideo';
+import { normalizeImage } from '../components/media/normalize';
+
+/**
+ * Fetch the original-vs-cleaned variant set for the ONE image the lightbox has
+ * open, so the toggle is built from real lineage rather than from whatever list
+ * the host page happens to hold.
+ *
+ * A host list can't answer this, for two separate reasons. A page whose list is
+ * a projection of its own refs (a deck's card `imageRefs`, a pipeline or
+ * music-video scene) never contains the copy at all: cleaning auto-files it
+ * into the source's media COLLECTIONS, not onto the card. And a gallery page
+ * only holds a window — 60 rows, newest first — while a clean stamps the copy
+ * with a fresh `createdAt`, so cleaning anything older than that window
+ * separates the pair there too. Hydrating the whole list to find out would be
+ * the whole-list POST #7343 removed.
+ *
+ * Returns `null` while unfetched or after a failed lookup, so the caller keeps
+ * its own list as the answer. `[]` means the image is not indexed.
+ *
+ * @param {object|null} item - the open preview item; non-image items fetch nothing
+ * @returns {object[]|null} normalized image records, or null when not fetched
+ */
+export default function useImageVariants(item) {
+ const filename = item?.kind === 'image' && item.filename ? item.filename : null;
+ const [fetched, setFetched] = useState(null);
+ // A group is closed under the toggle, so switching to a variant we already
+ // hold would re-request an identical set and blank the toggle for the round
+ // trip. Also true for a filename a lookup already failed on, so one failure
+ // doesn't retry forever.
+ const holds = !!filename
+ && (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.
+ 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 });
+ })
+ // 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(); };
+ }, [filename, holds]);
+ return holds ? fetched.items : null;
+}
diff --git a/client/src/hooks/usePreviewRoute.js b/client/src/hooks/usePreviewRoute.js
index 7925ff67b0..6aaafd3c24 100644
--- a/client/src/hooks/usePreviewRoute.js
+++ b/client/src/hooks/usePreviewRoute.js
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useSearchParams } from 'react-router';
+import useGalleryPreviewResolver from './useGalleryPreviewResolver';
// URL-driven MediaPreview state. Returns `[preview, setPreview]` with the same
// shape every MediaPreview host already expects, but the source of truth is a
@@ -24,7 +25,16 @@ import { useSearchParams } from 'react-router';
// the browser back button closes the modal. Subsequent prev/next navigation
// and the open→closed transition use replace so the gallery doesn't pollute
// the history stack.
+// `resolveItem` defaults to a gallery lookup rather than being per-host wiring:
+// the lightbox can navigate to an item the host never listed — picking the other
+// entry in the original-vs-cleaned toggle is exactly that, since a cleaned copy
+// is auto-filed into the source's media COLLECTIONS and never onto a deck card
+// or scene ref. Left opt-in, a host that forgot it would render the toggle and
+// then close the lightbox on the click. Pass one only to narrow the lookup
+// (MediaCollectionDetail scopes it to its collection).
export default function usePreviewRoute(items, { paramName = 'preview', resolveItem } = {}) {
+ const galleryResolver = useGalleryPreviewResolver();
+ const resolver = resolveItem || galleryResolver;
const [searchParams, setSearchParams] = useSearchParams();
// React Router may replace both values after navigation. Refs let callers
// keep one action identity (important for memoized gallery cards) while the
@@ -47,13 +57,17 @@ export default function usePreviewRoute(items, { paramName = 'preview', resolveI
}, [items, previewParam]);
const [resolved, setResolved] = useState(null);
+ // Read by setPreview's stable callback without making the resolver its dep.
+ const resolverRef = useRef(resolver);
+ resolverRef.current = resolver;
+ const alreadyResolved = resolved?.param === previewParam && resolved.resolver === resolver;
useEffect(() => {
- if (!previewParam || localPreview || !resolveItem) return;
+ if (!previewParam || localPreview || alreadyResolved) return;
let cancelled = false;
- resolveItem(previewParam).then(item => { if (!cancelled) setResolved({ param: previewParam, item, resolver: resolveItem }); }).catch(() => {});
+ resolver(previewParam).then(item => { if (!cancelled) setResolved({ param: previewParam, item, resolver }); }).catch(() => {});
return () => { cancelled = true; };
- }, [previewParam, localPreview, resolveItem]);
- const preview = localPreview || (resolved?.param === previewParam && resolved.resolver === resolveItem ? resolved.item : null);
+ }, [previewParam, localPreview, alreadyResolved, resolver]);
+ const preview = localPreview || (alreadyResolved ? resolved.item : null);
const setPreview = useCallback((item) => {
const currentSearchParams = searchParamsRef.current;
@@ -61,7 +75,14 @@ export default function usePreviewRoute(items, { paramName = 'preview', resolveI
const isOpen = !!item;
const next = new URLSearchParams(currentSearchParams);
if (!item) next.delete(paramName);
- else next.set(paramName, item.key || item.filename || '');
+ else {
+ const param = item.key || item.filename || '';
+ next.set(paramName, param);
+ // Seed the resolver with the item the caller already handed us, so an
+ // opened item the host does not list (a variant picked from the toggle)
+ // renders immediately instead of round-tripping to fetch what we hold.
+ setResolved({ param, item, resolver: resolverRef.current });
+ }
setSearchParamsRef.current(next, { replace: wasOpen || !isOpen });
}, [paramName]);
diff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsx
index 43c70006de..bd7417a5d0 100644
--- a/client/src/pages/MediaCollectionDetail.jsx
+++ b/client/src/pages/MediaCollectionDetail.jsx
@@ -8,15 +8,15 @@ import MediaCard from '../components/media/MediaCard';
import AttributionList from '../components/media/AttributionList';
import MediaPreview from '../components/media/MediaPreview';
import BulkTargetPicker from '../components/media/BulkTargetPicker';
-import { normalizeImage, normalizeVideo } from '../components/media/normalize';
+import { normalizeMediaRow } from '../components/media/normalize';
import { useMediaAnnotations } from '../hooks/useMediaAnnotations';
import { useAsyncAction } from '../hooks/useAsyncAction';
+import useGalleryPreviewResolver from '../hooks/useGalleryPreviewResolver';
import { UNSORTED_ID, buildUnsortedCollection } from '../lib/unsorted';
import {
getMediaCollection, updateMediaCollection,
listMediaCollections,
addMediaCollectionItem, removeMediaCollectionItem,
- listMediaGalleryPage,
deleteImage, deleteVideoHistoryItem,
pullMissingMetadata,
} from '../services/api';
@@ -60,13 +60,8 @@ export default function MediaCollectionDetail() {
}, [id, isUnsorted, page.refresh]);
useEffect(() => { refresh(); }, [refresh]);
const items = useMemo(() => page.items.filter(row => isUnsorted || collection?.items?.some(ref => ref.kind === row.kind && ref.ref === (row.kind === 'image' ? row.data.filename : row.data.id)))
- .map(row => row.kind === 'image' ? normalizeImage(row.data) : normalizeVideo(row.data)), [page.items, collection, isUnsorted]);
- const resolvePreview = useCallback(async key => {
- const kind = key.startsWith('video:') ? 'video' : key.startsWith('image:') ? 'image' : 'all';
- const result = await listMediaGalleryPage({ collectionId: id, kind, filename: key.replace(/^(image|video):/, ''), limit: 1 }, { silent: true });
- const row = result.items[0];
- return row ? row.kind === 'image' ? normalizeImage(row.data) : normalizeVideo(row.data) : null;
- }, [id]);
+ .map(normalizeMediaRow), [page.items, collection, isUnsorted]);
+ const resolvePreview = useGalleryPreviewResolver({ collectionId: id });
const [preview, setPreview] = usePreviewRoute(items, { resolveItem: resolvePreview });
// Unsorted-only action: pull gen-params sidecars for bare images from peers.
diff --git a/client/src/pages/MediaCollectionDetail.test.jsx b/client/src/pages/MediaCollectionDetail.test.jsx
index 5a1df961fa..c168a34c52 100644
--- a/client/src/pages/MediaCollectionDetail.test.jsx
+++ b/client/src/pages/MediaCollectionDetail.test.jsx
@@ -94,20 +94,25 @@ vi.mock('../components/sharing/ShareToButton', () => ({
default: () => null,
}));
-vi.mock('../components/media/normalize', () => ({
- normalizeImage: (i) => ({
+vi.mock('../components/media/normalize', () => {
+ const normalizeImage = (i) => ({
kind: 'image',
key: `image:${i.filename}`,
filename: i.filename,
ref: i.filename,
- }),
- normalizeVideo: (v) => ({
+ });
+ const normalizeVideo = (v) => ({
kind: 'video',
key: `video:${v.id}`,
id: v.id,
ref: v.id,
- }),
-}));
+ });
+ return {
+ normalizeImage,
+ normalizeVideo,
+ normalizeMediaRow: (row) => (row.kind === 'image' ? normalizeImage(row.data) : normalizeVideo(row.data)),
+ };
+});
import toast from '../components/ui/Toast';
import MediaCollectionDetail from './MediaCollectionDetail';
diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsx
index 2e9f9d4027..a7e4e72ede 100644
--- a/client/src/pages/MediaHistory.jsx
+++ b/client/src/pages/MediaHistory.jsx
@@ -14,14 +14,14 @@ import MediaCard from '../components/media/MediaCard';
import MediaPreview from '../components/media/MediaPreview';
import VideoUpscaleDrawer from '../components/media/VideoUpscaleDrawer';
import FavoritesFilterChip from '../components/media/FavoritesFilterChip';
-import { normalizeImage, normalizeVideo } from '../components/media/normalize';
+import { normalizeImage, normalizeMediaRow, normalizeVideo } from '../components/media/normalize';
import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';
import { useMediaAnnotations } from '../hooks/useMediaAnnotations';
import useMediaPreviewActions from '../hooks/useMediaPreviewActions';
import usePreviewRoute from '../hooks/usePreviewRoute';
import { useGalleryPage } from '../hooks/useGalleryPage';
import {
- listMediaGalleryPage, deleteVideoHistoryItem, stitchVideos, deleteImage,
+ deleteVideoHistoryItem, stitchVideos, deleteImage,
} from '../services/api';
const FILTERS = [
@@ -30,13 +30,6 @@ const FILTERS = [
{ id: 'video', label: 'Videos' },
];
-const normalizeRow = row => row.kind === 'image' ? normalizeImage(row.data) : normalizeVideo(row.data);
-const resolvePreview = async key => {
- const kind = key.startsWith('video:') ? 'video' : key.startsWith('image:') ? 'image' : 'all';
- const filename = key.replace(/^(image|video):/, '');
- const page = await listMediaGalleryPage({ limit: 1, kind, filename }, { silent: true });
- return page.items[0] ? normalizeRow(page.items[0]) : null;
-};
export default function MediaHistory() {
const navigate = useNavigate();
@@ -56,15 +49,15 @@ export default function MediaHistory() {
const annotationRevision = favoritesOnly ? JSON.stringify(Object.entries(annotations).map(([key, value]) => [key, value.starred, value.updatedAt]).sort()) : '';
const page = useGalleryPage({ kind: filter, q: query, starred: favoritesOnly, summary: true }, { media: true, revision: annotationRevision, paused: favoritesOnly && annotationSaves > 0 });
const { loading, counts, refresh } = page;
- const items = useMemo(() => page.items.map(normalizeRow), [page.items]);
+ const items = useMemo(() => page.items.map(normalizeMediaRow), [page.items]);
const setItems = useCallback(updater => page.setItems(previous => {
- const normalized = previous.map(normalizeRow);
+ const normalized = previous.map(normalizeMediaRow);
const next = typeof updater === 'function' ? updater(normalized) : updater;
return next.map(item => ({ kind: item.kind, data: { ...item.raw, prompt: item.prompt } }));
}), [page.setItems]);
const filtered = items;
const visibleItems = items;
- const [preview, setPreview] = usePreviewRoute(items, { resolveItem: resolvePreview });
+ const [preview, setPreview] = usePreviewRoute(items);
useMediaCompletionRefresh({ onImageCompleted: refresh, onVideoCompleted: refresh });
const toggleSelect = useCallback((videoId) => {
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index b057729589..09f885f3ae 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -91,6 +91,10 @@ vi.mock('../services/apiImageVideo.js', () => ({
getVideoHistoryItem: vi.fn(async (id) => (id === 'rh-9'
? { id: 'rh-9', filename: 'final.mp4' }
: Promise.reject(Object.assign(new Error('Not found'), { status: 404 })))),
+ // Scene refs are a projection, so the lightbox resolves variant lineage and
+ // any variant it opens through the gallery rather than this page's list.
+ listImageVariants: vi.fn(async () => ({ items: [] })),
+ listMediaGalleryPage: vi.fn(async () => ({ items: [] })),
}));
vi.mock('../services/apiTracks.js', () => ({
listTracks: vi.fn(async () => []),
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 976c3d7eab..761786d060 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -100,7 +100,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| File | Purpose |
|---|---|
-| `apiImageVideo.js` | Image-gen local backend extras; bounded image/mixed gallery pages, global facets and collection summaries, exact-reference `getGalleryImages`, plus models, LoRAs, cancel and delete. |
+| `apiImageVideo.js` | Image-gen local backend extras; bounded image/mixed gallery pages, global facets and collection summaries, exact-reference `getGalleryImages`, one image's original-vs-cleaned variant set via `listImageVariants`, plus models, LoRAs, cancel and delete. |
| `apiLoraTraining.js` | Character LoRA training — datasets (CRUD, upload, generate, slice, caption), training runs (start/list/cancel + status), character→LoRA link lookup. |
| `apiMedia.js` | Screenshots + media assets. Also owns the multi-file upload orchestration — `processScreenshotUploads` / `processAttachmentUploads` — moved from `utils/fileUpload.js` since they perform network I/O, not pure transforms. `utils/fileUpload.js` keeps only the pure helpers/constants and no longer re-exports these. |
| `apiMediaJobs.js` | Media generation job tracking + `refineMediaPrompt` / `promptFromMedia` (vision reverse-prompt). |
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index e7b9f17c0b..b2b7ba093e 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -66,6 +66,12 @@ export const setImageHidden = (filename, hidden, options = {}) => request(`/imag
export const updateImagePrompt = (filename, prompt, options = {}) => request(`/image-gen/${encodeURIComponent(filename)}/prompt`, {
method: 'PATCH', body: JSON.stringify({ prompt }), ...options,
});
+// Original-vs-cleaned variant set for ONE image: the original record plus every
+// copy whose `cleanedFrom` names it. Lets a lightbox host whose item list is a
+// projection of its own refs (deck cards, pipeline/music-video scenes) render
+// the variant toggle without hydrating that whole list. Returns `{ items }`.
+export const listImageVariants = (filename, options = {}) =>
+ request(`/image-gen/${encodeURIComponent(filename)}/variants`, { silent: true, ...options });
export const cleanGalleryImage = (filename, options = {}) => request(`/image-gen/${encodeURIComponent(filename)}/clean`, {
method: 'POST',
body: JSON.stringify({}),
diff --git a/server/routes/imageGen.clean.test.js b/server/routes/imageGen.clean.test.js
index 4fac5cf141..3c55402fa6 100644
--- a/server/routes/imageGen.clean.test.js
+++ b/server/routes/imageGen.clean.test.js
@@ -259,3 +259,55 @@ describe('POST /api/image-gen/:filename/clean', () => {
});
});
});
+
+// The lightbox's original-vs-cleaned toggle. Before this endpoint the client
+// reconstructed the group by scanning whatever item list its host page held —
+// which a deck, pipeline stage or music-video page cannot supply, because the
+// cleaned copy is auto-filed into the source's COLLECTIONS and never lands on
+// the card/scene ref that page actually lists. One call answers both directions
+// instead of hydrating that whole list.
+describe('GET /api/image-gen/:filename/variants', () => {
+ let app;
+
+ beforeEach(() => {
+ app = express();
+ app.use(express.json());
+ app.use('/api/image-gen', imageGenRoutes);
+ app.use(errorMiddleware);
+ listCollectionsMock.mockReset();
+ listCollectionsMock.mockResolvedValue([]);
+ addItemMock.mockReset();
+ addItemMock.mockResolvedValue({});
+ });
+
+ const variantsOf = async (filename) => {
+ const res = await request(app).get(`/api/image-gen/${filename}/variants`);
+ expect(res.status).toBe(200);
+ return res.body.items.map((item) => item.filename);
+ };
+
+ it('resolves the same pair from either end after a real clean', async () => {
+ await writeFile(join(sandbox, 'toggle-1.png'), pngFixture);
+ await writeFile(join(sandbox, 'toggle-1.metadata.json'), JSON.stringify({ prompt: 'a fox' }));
+ const cleaned = (await request(app).post('/api/image-gen/toggle-1.png/clean').send({})).body.filename;
+
+ // Opening the ORIGINAL is the direction a host-list scan could never
+ // answer: every sibling it holds reports `cleanedFrom: undefined`.
+ expect(await variantsOf('toggle-1.png')).toEqual(['toggle-1.png', cleaned]);
+ expect(await variantsOf(cleaned)).toEqual(['toggle-1.png', cleaned]);
+ });
+
+ it('returns the group root alone for an image with no copies', async () => {
+ await writeFile(join(sandbox, 'toggle-solo.png'), pngFixture);
+ expect(await variantsOf('toggle-solo.png')).toEqual(['toggle-solo.png']);
+ });
+
+ it('returns an empty set for a filename that is not in the gallery', async () => {
+ expect(await variantsOf('toggle-missing.png')).toEqual([]);
+ });
+
+ it('rejects a traversal filename rather than reading outside the gallery', async () => {
+ const res = await request(app).get('/api/image-gen/..%2F..%2Fetc%2Fpasswd/variants');
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 3ea32ca952..f6c60d6be8 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -908,6 +908,15 @@ router.delete('/:filename', asyncHandler(async (req, res) => {
res.json({ ...result, canonRefsRemoved: universePurge.removed });
}));
+// Variant set for ONE image, for the lightbox original-vs-cleaned toggle —
+// see listImageVariants for why no host list can answer it.
+router.get('/:filename/variants', asyncHandler(async (req, res) => {
+ const filename = req.params.filename;
+ local.assertGalleryFilename(filename);
+ const { listImageVariants } = await import('../services/mediaAssetIndex/gallery.js');
+ res.json({ items: await listImageVariants(filename, local.listGallery) });
+}));
+
router.post('/:filename/visibility', asyncHandler(async (req, res) => {
res.json(await local.setImageHidden(req.params.filename, !!req.body?.hidden));
}));
diff --git a/server/services/mediaAssetIndex/db.js b/server/services/mediaAssetIndex/db.js
index b58b07e080..c60f9761cc 100644
--- a/server/services/mediaAssetIndex/db.js
+++ b/server/services/mediaAssetIndex/db.js
@@ -93,7 +93,7 @@ export async function removeAsset(mediaKey) {
// 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, filename, mediaKeys, excludeKeys, universeId, entryCategory, entryKind, cover } = {}) {
+function assetFilter({ kind, q = '', hidden, filename, cleanedFrom, mediaKeys, excludeKeys, universeId, entryCategory, entryKind, cover } = {}) {
const params = [];
const clauses = [];
if (kind) { params.push(kind); clauses.push(`kind = $${params.length}`); }
@@ -112,7 +112,10 @@ function assetFilter({ kind, q = '', hidden, filename, mediaKeys, excludeKeys, u
params.push(excludeKeys);
clauses.push(`NOT (media_key = ANY($${params.length}::text[]))`);
}
- for (const [field, value] of Object.entries({ universeId, entryCategory, entryKind })) {
+ // `cleanedFrom` is the variant-lineage reverse lookup: given an original
+ // filename it returns every cleaned/regenerated/de-watermarked copy that
+ // points back at it. Same jsonb-scalar shape as the universe filters below.
+ for (const [field, value] of Object.entries({ cleanedFrom, universeId, entryCategory, entryKind })) {
if (value !== undefined) {
params.push(value);
clauses.push(`data->>'${field}' = $${params.length}`);
diff --git a/server/services/mediaAssetIndex/gallery.js b/server/services/mediaAssetIndex/gallery.js
index 99f04dd985..1afcebe471 100644
--- a/server/services/mediaAssetIndex/gallery.js
+++ b/server/services/mediaAssetIndex/gallery.js
@@ -134,3 +134,49 @@ export async function listGalleryCollectionSummaries(diskReader) {
});
return summaries;
}
+
+/**
+ * Resolve one image's original-vs-cleaned variant set: the group root plus
+ * every record whose `cleanedFrom` names it. One call answers the lightbox
+ * toggle from either end — pass a cleaned copy and it walks back to the root
+ * first — so no caller has to hold a list wide enough to contain both.
+ *
+ * An image with no copies yields just its own root; `[]` means the filename is
+ * not indexed at all.
+ *
+ * @param {string} filename - gallery basename of the image the user opened
+ * @param {Function} [diskReader] - listGallery override for the test/file escape hatch
+ * @returns {Promise<object[]>} gallery-shaped records: root first, then its copies
+ */
+export async function listImageVariants(filename, diskReader) {
+ if (typeof filename !== 'string' || !filename) return [];
+ // A variant's `cleanedFrom` is anchored at the ROOT original by every writer
+ // in imageGen/variants.js, so one hop always lands on the group root. An
+ // auto-cleaned image replaced its source in place and carries no
+ // `cleanedFrom`, so it IS the root — matching the client's grouping.
+ const rootOf = image => text(image.cleanedFrom) || image.filename;
+ const isRoot = image => image && !text(image.cleanedFrom);
+
+ if (escapeHatch()) {
+ // One snapshot for all three lookups: each read is a directory scan plus a
+ // sidecar read per image, so re-reading per lookup would cost 3N file reads
+ // to answer one toggle.
+ const images = await readImages(diskReader);
+ const self = images.find(image => image?.filename === filename);
+ if (!self) return [];
+ const root = rootOf(self);
+ const original = images.find(image => image?.filename === root && isRoot(image));
+ return [...(original ? [original] : []), ...images.filter(image => image?.cleanedFrom === root)];
+ }
+
+ const [self] = await listAssets({ kind: 'image', filename, limit: 1 });
+ if (!self) return [];
+ const root = rootOf(self);
+ // Independent once the root is known — serially they would cost an extra
+ // round trip on every cleaned-copy open.
+ const [[original], copies] = await Promise.all([
+ root === filename ? [self] : listAssets({ kind: 'image', filename: root, limit: 1 }),
+ listAssets({ kind: 'image', cleanedFrom: root }),
+ ]);
+ return [...(isRoot(original) ? [original] : []), ...copies];
+}
diff --git a/server/services/mediaAssetIndex/gallery.test.js b/server/services/mediaAssetIndex/gallery.test.js
index c82d790863..eb088b0dd6 100644
--- a/server/services/mediaAssetIndex/gallery.test.js
+++ b/server/services/mediaAssetIndex/gallery.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
-import { listGalleryPage, listGalleryFacets, listGalleryCollectionSummaries } from './gallery.js';
+import { listGalleryPage, listGalleryFacets, listGalleryCollectionSummaries, listImageVariants } from './gallery.js';
import { imageToRow } from './logic.js';
import { query } from '../../lib/db.js';
@@ -111,3 +111,43 @@ describe('scoped browsing compatibility', () => {
expect(summaries.find(s => s.id === 'unsorted')).toMatchObject({ total: 1, counts: { image: 1, video: 0, all: 1 } });
});
});
+
+// The route test (routes/imageGen.clean.test.js) owns the both-directions
+// contract end to end against a real clean. What only lives here: the SQL the
+// indexed path emits, and the disk path the route test cannot reach because
+// the test runner always takes the escape hatch.
+describe('image variant lookup', () => {
+ const original = { filename: 'fox.png', path: '/data/images/fox.png', prompt: 'a fox' };
+ const cleaned = { filename: 'fox_clean-resize-squeeze.png', path: '/data/images/fox_clean-resize-squeeze.png', cleanedFrom: 'fox.png', cleanLevel: 'resize-squeeze' };
+
+ it.each([
+ ['the original', 'fox.png'],
+ ['a cleaned copy', 'fox_clean-resize-squeeze.png'],
+ ])('reads the whole gallery once per call when opened from %s', async (_label, opened) => {
+ const disk = vi.fn(async () => [original, cleaned, { filename: 'unrelated.png' }]);
+ expect(await listImageVariants(opened, disk)).toEqual([original, cleaned]);
+ // Each read is a directory scan plus a sidecar read per image.
+ expect(disk).toHaveBeenCalledTimes(1);
+ expect(query).not.toHaveBeenCalled();
+ });
+
+ // An auto-cleaned image replaced its source in place and carries no
+ // `cleanedFrom`, so it IS the group root, never a sibling of itself.
+ it('returns just the group root for an auto-cleaned image', async () => {
+ const auto = { filename: 'owl.png', autoCleaned: true };
+ expect(await listImageVariants('owl.png', vi.fn(async () => [auto]))).toEqual([auto]);
+ });
+
+ it('binds the reverse lookup to the group root and scopes it to images', async () => {
+ vi.stubEnv('NODE_ENV', 'production');
+ vi.stubEnv('VITEST', undefined);
+ vi.stubEnv('MEMORY_BACKEND', 'db');
+ query.mockImplementation(async sql => sql.includes("data->>'cleanedFrom'")
+ ? { rows: [imageToRow(cleaned)] } : { rows: [imageToRow(original)] });
+ // Opened from the CLEANED copy, so the root is reached via its cleanedFrom.
+ expect(await listImageVariants(cleaned.filename, vi.fn())).toEqual([original, cleaned]);
+ const [sql, params] = query.mock.calls.find(([sql]) => sql.includes("data->>'cleanedFrom'"));
+ expect(sql).toContain('kind = $1');
+ expect(params).toEqual(['image', 'fox.png']);
+ });
+});