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: load Media History as compact visible cards and hydrate records on demand (#8292)

[._.]/ Adam Eivy4b5f69dde76e
diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsx
index 2381acfa85..04629d8e2e 100644
--- a/client/src/components/media/MediaLightbox.jsx
+++ b/client/src/components/media/MediaLightbox.jsx
@@ -443,11 +443,14 @@ export default function MediaLightbox({
regenAvailable={regenAvailable}
regenBounds={regenBounds}
copy={copy}
- onRefine={() => setRefineOpen(true)}
+ // A compact list item holds a prompt PREVIEW until its record is
+ // hydrated (#8292) — refining or editing it would treat the
+ // truncation as the saved prompt.
+ onRefine={item.compact ? undefined : () => setRefineOpen(true)}
onPromptFrom={() => setPromptFromOpen(true)}
annotation={annotation}
onAnnotationChange={onAnnotationChange}
- onPromptChange={onPromptChange}
+ onPromptChange={item.compact ? undefined : onPromptChange}
variantGroup={variantGroup}
onSelectVariant={onSelectVariant}
/>
@@ -638,7 +641,15 @@ function SettingsPane({
</header>
<div className="flex-1 overflow-y-auto p-3 space-y-3 text-xs">
- {onPromptChange ? (
+ {item.compact ? (
+ <div>
+ <span className="block mb-1 text-gray-500 uppercase tracking-wide">Prompt</span>
+ <p className="text-gray-400 whitespace-pre-wrap">{item.prompt}</p>
+ {item.detailError
+ ? <p role="alert" className="mt-1 text-port-error">Full details could not be loaded. Close and reopen to retry.</p>
+ : <p role="status" className="mt-1 text-gray-500">Loading full details…</p>}
+ </div>
+ ) : onPromptChange ? (
<div>
<div className="flex items-center justify-between mb-1">
<label htmlFor="media-prompt" className="text-gray-500 uppercase tracking-wide">Prompt</label>
diff --git a/client/src/components/media/MediaLightbox.test.jsx b/client/src/components/media/MediaLightbox.test.jsx
index c28b7b9ca3..3a7776eadc 100644
--- a/client/src/components/media/MediaLightbox.test.jsx
+++ b/client/src/components/media/MediaLightbox.test.jsx
@@ -317,3 +317,21 @@ describe('MediaLightbox render-time row', () => {
expect(screen.queryByText('Render time')).toBeNull();
});
});
+
+// A compact gallery row (#8292) holds a prompt preview until the host hydrates
+// its record: editing or refining it would treat the truncation as the prompt.
+describe('MediaLightbox compact preview item', () => {
+ it('withholds prompt editing and refine until the full record arrives, and reports a failed load', () => {
+ const onPromptChange = vi.fn();
+ const compact = { ...imageItem, compact: true, prompt: 'a cat port…' };
+ const { rerender } = render(<MediaLightbox item={compact} onClose={() => {}} onPromptChange={onPromptChange} />);
+ expect(screen.queryByLabelText('Prompt')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Refine Prompt' })).toBeNull();
+ expect(screen.getByRole('status')).toHaveTextContent('Loading full details');
+ rerender(<MediaLightbox item={{ ...compact, detailError: true }} onClose={() => {}} onPromptChange={onPromptChange} />);
+ expect(screen.getByRole('alert')).toHaveTextContent('could not be loaded');
+ rerender(<MediaLightbox item={imageItem} onClose={() => {}} onPromptChange={onPromptChange} />);
+ expect(screen.getByLabelText('Prompt')).toHaveValue('a cat portrait');
+ expect(screen.getByRole('button', { name: 'Refine Prompt' })).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/media/mediaDetail.js b/client/src/components/media/mediaDetail.js
new file mode 100644
index 0000000000..89d1032fed
--- /dev/null
+++ b/client/src/components/media/mediaDetail.js
@@ -0,0 +1,64 @@
+import { getGalleryImages, getVideoHistoryItem } from '../../services/apiImageVideo';
+import { normalizeImage, normalizeVideo } from './normalize';
+
+/**
+ * Full-record reads for a normalized media item, shared by the lightbox's lazy
+ * hydration (`useHydratedPreviewRoute`) and by actions that hand a record's
+ * prompt/settings to a generator (`useMediaPreviewActions`).
+ *
+ * An item from a compact gallery list (`item.compact`, #8292) carries only a
+ * prompt PREVIEW. Nothing may edit that preview or pass it on as the prompt —
+ * `hydrateMediaItem` is the one way to turn such an item into the real record.
+ */
+
+// What the record is looked up BY: images by filename, videos by history id.
+// An item with neither (a synthetic entry backed by no gallery record) has
+// nothing to hydrate from.
+export function mediaRecordRef(item) {
+ if (item?.kind === 'image' && item.filename) return item.filename;
+ if (item?.kind === 'video' && item.id) return item.id;
+ 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 });
+ return getGalleryImages([ref], { silent: true })
+ .then((list) => (Array.isArray(list) ? list : []).find((i) => i?.filename === ref) || null);
+}
+
+/**
+ * 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
+ * annotation lookup match on it.
+ */
+export function mergeMediaRecord(item, record) {
+ const normalize = item.kind === 'video' ? normalizeVideo : normalizeImage;
+ // A host label may stand in for a record with no prompt — but never a
+ // compact preview, which is a truncation of text the record itself lacks.
+ const fallbackPrompt = item.compact ? undefined : item.prompt;
+ const merged = normalize({ ...record, prompt: record.prompt || fallbackPrompt });
+ return {
+ ...merged,
+ key: item.key,
+ negativePrompt: merged.negativePrompt || (item.compact ? null : item.negativePrompt) || null,
+ // A host may point at a file the normalizer can't address from the record
+ // alone — a video-history entry with no thumbnail still has the host's
+ // job-scoped poster.
+ previewUrl: merged.previewUrl || item.previewUrl || null,
+ downloadUrl: merged.downloadUrl || item.downloadUrl || null,
+ };
+}
+
+/**
+ * The complete item for an action that reads prompt/settings. A full item is
+ * returned as-is; a compact one is hydrated, and a failed or empty lookup
+ * throws rather than falling back to the preview.
+ */
+export async function hydrateMediaItem(item) {
+ if (!item?.compact) return item;
+ const ref = mediaRecordRef(item);
+ const record = ref ? await fetchMediaRecord(item.kind, ref) : null;
+ if (!record) throw new Error('Full media details are unavailable');
+ return mergeMediaRecord(item, record);
+}
diff --git a/client/src/components/media/normalize.js b/client/src/components/media/normalize.js
index 3877878d32..4cb7c1b029 100644
--- a/client/src/components/media/normalize.js
+++ b/client/src/components/media/normalize.js
@@ -101,6 +101,9 @@ export function normalizeImage(i) {
// MUST survive normalization (same contract as `regenerated` above).
watermarkRemoved: i.watermarkRemoved === true,
provenance: i.provenance || null,
+ // A compact gallery row (#8292) holds only a prompt preview; see
+ // mediaDetail.js for the hydration every prompt consumer goes through.
+ compact: i.compact === true,
raw: i,
};
}
@@ -135,6 +138,7 @@ export function normalizeVideo(v) {
renderMs: Number.isFinite(v.renderMs) ? v.renderMs : null,
hidden: !!v.hidden,
provenance: v.provenance || null,
+ compact: v.compact === true,
raw: v,
};
}
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 3ccd462506..e62163712a 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -72,7 +72,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useMediaPreviewActions` | Shared MediaPreview / MediaLightbox action handlers (images + videos — dispatch by `item.kind`). | New surface that exposes the same 4 preview actions. |
| `useClonedGltf` | Clones a drei-cached GLTF scene with skeleton bindings intact and wires its animations; the colocated `GltfPrimitive` prevents R3F from disposing shared cache resources. Accepts an optional animation transform for derived clip sets. | Any skinned GLTF rendered from `useGLTF`; render its scene through `GltfPrimitive` so remounts cannot inherit disposed geometry or materials. |
| `usePreviewRoute` | URL-driven `[preview, setPreview]` via `?preview=<filename>`. | Any page hosting `<MediaPreview>` — gives the preview a deep-link. |
-| `useHydratedPreviewRoute` | `usePreviewRoute` plus a lazy single-item lookup of the OPEN preview's gallery record (image sidecar or video-history entry), merged over the host's item. | Any page that owns its own media refs and composes a styled prompt on the way out (pipeline canon refs, music-video scenes, deck cards) — otherwise the lightbox shows a label the renderer never saw. Use eager `useGallerySidecars` when the page needs records for more than the lightbox. |
+| `useHydratedPreviewRoute` | `usePreviewRoute` plus a lazy single-item lookup of the OPEN preview's gallery record (image sidecar or video-history entry), merged over the host's item. A compact list item (`item.compact`) never falls back to its prompt preview; a failed lookup marks it `detailError`. | Media History's compact grid, and any page that owns its own media refs and composes a styled prompt on the way out (pipeline canon refs, music-video scenes, deck cards) — otherwise the lightbox shows a label the renderer never saw. Use eager `useGallerySidecars` when the page needs records for more than the lightbox. |
| `useImageGenForm` | Owns Image Gen form fields, model/LoRA catalog loading, legacy and remix URL restoration, image-input object URLs, mode-dependent capabilities, and image-pick/remix actions. | Image Gen form compositions that need the complete prompt, model, conditioning-image, cleaner, and handoff lifecycle. |
| `useImageGenGallery` | Owns Image Gen gallery filters, normalized recent/hidden cards, annotations, URL preview state, and local gallery mutations. | Image Gen gallery and lightbox surfaces that share recent-image, annotation, and preview behavior. |
| `useImageGenPageRuntime` | Composes the Image Gen form and gallery with backend probes, job/SSE progress, batch submission, cancellation, result/error state, federated targets, and regeneration. | The Image Gen page runtime when its route should remain presentational. |
diff --git a/client/src/hooks/useHydratedPreviewRoute.js b/client/src/hooks/useHydratedPreviewRoute.js
index df7ebe593e..6118af6121 100644
--- a/client/src/hooks/useHydratedPreviewRoute.js
+++ b/client/src/hooks/useHydratedPreviewRoute.js
@@ -1,7 +1,6 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import usePreviewRoute from './usePreviewRoute';
-import { getGalleryImages, getVideoHistoryItem } from '../services/apiImageVideo';
-import { normalizeImage, normalizeVideo } from '../components/media/normalize';
+import { fetchMediaRecord, mediaRecordRef, mergeMediaRecord } from '../components/media/mediaDetail';
/**
* `usePreviewRoute` plus lazy hydration of the OPEN item from its gallery
@@ -35,20 +34,27 @@ import { normalizeImage, normalizeVideo } from '../components/media/normalize';
* annotation lookup both match on it, so a key that drifted from the list would
* silently disable both.
*
+ * A compact list item (`item.compact`, #8292) carries only a prompt preview,
+ * so for it a failed or empty lookup is not a quiet miss: the returned preview
+ * stays `compact` and gains `detailError: true`, and closing then reopening it
+ * retries. The lightbox withholds prompt editing while an item is compact.
+ *
* Same `[preview, setPreview]` shape as `usePreviewRoute`; `options` passes
* straight through (`paramName`, `resolveItem`).
*/
export default function useHydratedPreviewRoute(items, options) {
const [preview, setPreview] = usePreviewRoute(items, options);
- // What the record is looked up BY: images by filename, videos by history id.
- // An item with neither (a synthetic entry backed by no gallery record) has
- // nothing to hydrate from and passes through untouched.
+ // An item with no filename/id (a synthetic entry backed by no gallery
+ // record) has nothing to hydrate from and passes through untouched.
const kind = preview?.kind;
- const ref = (kind === 'image' && preview.filename) || (kind === 'video' && preview.id) || null;
+ const ref = mediaRecordRef(preview);
+ const compact = !!preview?.compact;
// Cache the fetched records, not the merged items: the host's item identity
// can change between opens (a re-render rebuilding the list) while the record
// for a given filename/id does not.
const [records, setRecords] = useState(() => new Map());
+ // Compact items whose lookup failed or found nothing — cleared on retry.
+ const [failed, setFailed] = useState(() => new Set());
// Every key already ATTEMPTED — hits and misses alike, so a legacy render
// that has no record, or one whose lookup 404s, is asked for once rather than
// on every reopen. Held in a ref so the effect can read it without taking the
@@ -60,45 +66,37 @@ export default function useHydratedPreviewRoute(items, options) {
const lookupKey = `${kind}:${ref}`;
if (!ref || attemptedRef.current.has(lookupKey)) return undefined;
let cancelled = false;
+ setFailed((prev) => (prev.has(lookupKey) ? withoutKey(prev, lookupKey) : prev));
const settle = (record) => {
if (cancelled) return;
- attemptedRef.current.add(lookupKey);
- if (record) setRecords((prev) => new Map(prev).set(lookupKey, record));
+ if (record) {
+ attemptedRef.current.add(lookupKey);
+ setRecords((prev) => new Map(prev).set(lookupKey, record));
+ } else if (compact) {
+ // Left unattempted so a reopen asks again.
+ setFailed((prev) => new Set(prev).add(lookupKey));
+ } else {
+ // A full host item settles a failed lookup as a miss: non-fatal, and
+ // the host's own label stands in for it.
+ attemptedRef.current.add(lookupKey);
+ }
};
- // A failed lookup settles as a miss: non-fatal, and the host's own label
- // stands in for it.
- fetchRecord(kind, ref).then(settle, () => settle(null));
+ fetchMediaRecord(kind, ref).then(settle, () => settle(null));
return () => { cancelled = true; };
- }, [kind, ref]);
+ }, [kind, ref, compact]);
const hydrated = useMemo(() => {
- const record = ref ? records.get(`${kind}:${ref}`) : null;
- return record ? mergeRecord(preview, record) : preview;
- }, [preview, kind, ref, records]);
+ const lookupKey = `${kind}:${ref}`;
+ const record = ref ? records.get(lookupKey) : null;
+ if (record) return mergeMediaRecord(preview, record);
+ return preview?.compact && failed.has(lookupKey) ? { ...preview, detailError: true } : preview;
+ }, [preview, kind, ref, records, failed]);
return [hydrated, setPreview];
}
-function fetchRecord(kind, ref) {
- if (kind === 'video') return getVideoHistoryItem(ref, { silent: true });
- return getGalleryImages([ref], { silent: true })
- .then((list) => (Array.isArray(list) ? list : []).find((i) => i?.filename === ref) || null);
-}
-
-function mergeRecord(item, record) {
- const normalize = item.kind === 'video' ? normalizeVideo : normalizeImage;
- // `prompt` is the whole point, and it is the one fallback that has to happen
- // BEFORE normalize — which would otherwise substitute its own '(no prompt)'
- // for a record that carries none, burying the host's label under it.
- const merged = normalize({ ...record, prompt: record.prompt || item.prompt });
- return {
- ...merged,
- key: item.key,
- negativePrompt: merged.negativePrompt || item.negativePrompt || null,
- // A host may point at a file the normalizer can't address from the record
- // alone — a video-history entry with no thumbnail still has the host's
- // job-scoped poster.
- previewUrl: merged.previewUrl || item.previewUrl || null,
- downloadUrl: merged.downloadUrl || item.downloadUrl || null,
- };
+function withoutKey(set, key) {
+ const next = new Set(set);
+ next.delete(key);
+ return next;
}
diff --git a/client/src/hooks/useMediaPreviewActions.js b/client/src/hooks/useMediaPreviewActions.js
index 4530a0d0c5..12e23e9c19 100644
--- a/client/src/hooks/useMediaPreviewActions.js
+++ b/client/src/hooks/useMediaPreviewActions.js
@@ -3,6 +3,18 @@ import { useNavigate } from 'react-router';
import toast from '../components/ui/Toast';
import { cleanGalleryImage, extractLastFrame, removeImageWatermark } from '../services/apiImageVideo';
import { normalizeVideoTiling } from '../lib/videoTilingOptions';
+import { hydrateMediaItem } from '../components/media/mediaDetail';
+
+// Handoffs that copy a record's prompt/settings into a generator form read the
+// FULL record: a compact gallery item (#8292) only holds a prompt preview, so
+// it is hydrated first, and a failed lookup stops the action with a toast
+// instead of silently sending the truncated text. Resolves null on failure.
+async function withFullDetail(item) {
+ return hydrateMediaItem(item).catch((err) => {
+ toast.error(err.message || 'Could not load full media details');
+ return null;
+ });
+}
// Common image render-setting params shared by the image branch of Remix and by
// Send-to-image-to-image — both open /media/image with these fields prefilled.
@@ -82,7 +94,9 @@ export default function useMediaPreviewActions({ onCleanComplete = null } = {})
// filename, rather than maintaining a second field-by-field restore path.
// The destination resolves the record and reuses its in-page restore logic.
// Filename-less images and id-less videos keep their legacy bundles for
- // compatibility; those bundles are not extended.
+ // compatibility; those bundles are not extended. A compact gallery item
+ // always carries its filename/id, so it takes the reference path and never
+ // needs hydrating here.
const handleRemix = useCallback((item) => {
if (!item) return;
if (item.kind === 'video') {
@@ -128,8 +142,10 @@ export default function useMediaPreviewActions({ onCleanComplete = null } = {})
// ImageGen page resolves `?initImageFile=<basename>` against the gallery and
// nudges to an i2i-capable backend. Deliberately omits the `remix` param so it
// reads as a distinct intent from plain Remix.
- const handleSendToImage = useCallback((item) => {
- if (!item?.filename || item.kind === 'video') return;
+ const handleSendToImage = useCallback(async (source) => {
+ if (!source?.filename || source.kind === 'video') return;
+ const item = await withFullDetail(source);
+ if (!item) return;
const params = buildImageGenParams(item);
// Drop modelId: i2i is image-driven and the page may auto-switch the user to
// a different (i2i-capable) backend, so the source's model — often a
@@ -144,8 +160,10 @@ export default function useMediaPreviewActions({ onCleanComplete = null } = {})
// Send to Video: open the Video Gen page with the image queued as the
// i2v source.
- const handleSendToVideo = useCallback((item) => {
- if (!item?.filename) return;
+ const handleSendToVideo = useCallback(async (source) => {
+ if (!source?.filename) return;
+ const item = await withFullDetail(source);
+ if (!item) return;
const params = buildVideoGenParams(item);
params.set('sourceImageFile', item.filename);
navigate(`/media/video?${params}`);
@@ -166,8 +184,11 @@ export default function useMediaPreviewActions({ onCleanComplete = null } = {})
// Takes the NORMALIZED item (normalizeVideo) — buildVideoGenParams reads the
// prompt/negative off that shape, so a raw history record must be normalized
// by the caller rather than passed through.
- const handleContinue = useCallback(async (item) => {
- if (!item?.id) return;
+ const handleContinue = useCallback(async (source) => {
+ if (!source?.id) return;
+ // Before extracting, so a failed lookup leaves no orphaned frame behind.
+ const item = await withFullDetail(source);
+ if (!item) return;
const { filename } = await extractLastFrame(item.id, { silent: true }).catch((err) => {
toast.error(err.message || 'Failed to extract last frame');
return {};
diff --git a/client/src/hooks/useMediaPreviewActions.test.jsx b/client/src/hooks/useMediaPreviewActions.test.jsx
index f81a961f1e..9e1807278f 100644
--- a/client/src/hooks/useMediaPreviewActions.test.jsx
+++ b/client/src/hooks/useMediaPreviewActions.test.jsx
@@ -9,9 +9,13 @@ vi.mock('../services/apiImageVideo', () => ({
cleanGalleryImage: vi.fn(),
extractLastFrame: vi.fn(),
removeImageWatermark: vi.fn(),
+ getGalleryImages: vi.fn(),
+ getVideoHistoryItem: vi.fn(),
}));
-import { removeImageWatermark, cleanGalleryImage, extractLastFrame } from '../services/apiImageVideo';
+import { removeImageWatermark, cleanGalleryImage, extractLastFrame, getGalleryImages, getVideoHistoryItem } from '../services/apiImageVideo';
+import toast from '../components/ui/Toast';
+import { normalizeImage, normalizeVideo } from '../components/media/normalize';
const parseNav = () => {
const url = navigate.mock.calls.at(-1)?.[0] || '';
@@ -142,9 +146,9 @@ describe('useMediaPreviewActions.handleRemix', () => {
describe('useMediaPreviewActions.handleSendToImage', () => {
beforeEach(() => navigate.mockReset());
- it('navigates to /media/image with the image queued as init + settings carried', () => {
+ it('navigates to /media/image with the image queued as init + settings carried', async () => {
const { result } = renderHook(() => useMediaPreviewActions());
- result.current.handleSendToImage({
+ await result.current.handleSendToImage({
kind: 'image', filename: 'cat.png', prompt: 'a cat', negativePrompt: 'blurry',
modelId: 'flux2', width: 1024, height: 768, seed: 7, steps: 8, guidance: 3.5, quantize: '8',
});
@@ -162,18 +166,18 @@ describe('useMediaPreviewActions.handleSendToImage', () => {
expect(params.get('remix')).toBeNull();
});
- it('skips the (no prompt) placeholder so it does not seed the next render', () => {
+ it('skips the (no prompt) placeholder so it does not seed the next render', async () => {
const { result } = renderHook(() => useMediaPreviewActions());
- result.current.handleSendToImage({ kind: 'image', filename: 'x.png', prompt: '(no prompt)' });
+ await result.current.handleSendToImage({ kind: 'image', filename: 'x.png', prompt: '(no prompt)' });
const { params } = parseNav();
expect(params.get('initImageFile')).toBe('x.png');
expect(params.get('prompt')).toBeNull();
});
- it('is a no-op for videos and for items without a filename', () => {
+ it('is a no-op for videos and for items without a filename', async () => {
const { result } = renderHook(() => useMediaPreviewActions());
- result.current.handleSendToImage({ kind: 'video', filename: 'clip.mp4' });
- result.current.handleSendToImage({ kind: 'image' });
+ await result.current.handleSendToImage({ kind: 'video', filename: 'clip.mp4' });
+ await result.current.handleSendToImage({ kind: 'image' });
expect(navigate).not.toHaveBeenCalled();
});
});
@@ -206,6 +210,52 @@ describe('useMediaPreviewActions.handleContinue', () => {
});
});
+// A compact gallery row (#8292) carries only a prompt preview; every handoff
+// that copies prompt/settings must read the stored record instead.
+describe('useMediaPreviewActions with compact gallery items', () => {
+ const fullPrompt = 'a lighthouse at dusk, '.repeat(40) + 'ending detail';
+ beforeEach(() => {
+ navigate.mockReset(); extractLastFrame.mockReset(); getGalleryImages.mockReset();
+ getVideoHistoryItem.mockReset(); toast.error.mockReset();
+ });
+
+ it('hands the full stored prompt and settings to Send to Video and Send to image', async () => {
+ getGalleryImages.mockResolvedValue([{ filename: 'tower.png', prompt: fullPrompt, negativePrompt: 'fog', width: 832, height: 1216, seed: 9 }]);
+ const item = normalizeImage({ compact: true, filename: 'tower.png', prompt: 'a lighthouse at dusk…' });
+ const { result } = renderHook(() => useMediaPreviewActions());
+ await result.current.handleSendToVideo(item);
+ let { params } = parseNav();
+ expect(getGalleryImages).toHaveBeenCalledWith(['tower.png'], { silent: true });
+ expect(params.get('prompt')).toBe(fullPrompt);
+ expect(params.get('negativePrompt')).toBe('fog');
+ expect(params.get('w')).toBe('832');
+ await result.current.handleSendToImage(item);
+ ({ params } = parseNav());
+ expect(params.get('prompt')).toBe(fullPrompt);
+ expect(params.get('seed')).toBe('9');
+ });
+
+ it('stops with an error instead of sending the preview when the record cannot be read', async () => {
+ getGalleryImages.mockResolvedValue([]);
+ getVideoHistoryItem.mockRejectedValue(new Error('offline'));
+ const { result } = renderHook(() => useMediaPreviewActions());
+ await result.current.handleSendToVideo(normalizeImage({ compact: true, filename: 'gone.png', prompt: 'preview…' }));
+ await result.current.handleContinue(normalizeVideo({ compact: true, id: 'vid-9', filename: 'v.mp4', prompt: 'preview…' }));
+ expect(navigate).not.toHaveBeenCalled();
+ expect(extractLastFrame).not.toHaveBeenCalled();
+ expect(toast.error).toHaveBeenCalledTimes(2);
+ });
+
+ it('continues a compact clip with its full prompt', async () => {
+ getVideoHistoryItem.mockResolvedValue({ id: 'vid-3', filename: 'v.mp4', prompt: fullPrompt, width: 768, height: 512 });
+ extractLastFrame.mockResolvedValue({ filename: 'last.png' });
+ const { result } = renderHook(() => useMediaPreviewActions());
+ await result.current.handleContinue(normalizeVideo({ compact: true, id: 'vid-3', filename: 'v.mp4', prompt: 'preview…' }));
+ expect(getVideoHistoryItem).toHaveBeenCalledWith('vid-3', { silent: true });
+ expect(parseNav().params.get('prompt')).toBe(fullPrompt);
+ });
+});
+
describe('useMediaPreviewActions.handleRemoveWatermark', () => {
beforeEach(() => removeImageWatermark.mockReset());
diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsx
index 458b2bf05a..ca1fac8f20 100644
--- a/client/src/pages/MediaHistory.jsx
+++ b/client/src/pages/MediaHistory.jsx
@@ -19,7 +19,7 @@ import { normalizeImage, normalizeMediaRow, normalizeVideo } from '../components
import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';
import { useMediaAnnotations } from '../hooks/useMediaAnnotations';
import useMediaPreviewActions from '../hooks/useMediaPreviewActions';
-import usePreviewRoute from '../hooks/usePreviewRoute';
+import useHydratedPreviewRoute from '../hooks/useHydratedPreviewRoute';
import { useGalleryPage } from '../hooks/useGalleryPage';
import {
deleteVideoHistoryItem, stitchVideos, deleteImage,
@@ -48,7 +48,11 @@ export default function MediaHistory() {
}, [saveAnnotation]);
const toggleStar = useCallback(item => item?.key && updateAnnotation(item.key, { starred: !annotations[item.key]?.starred }), [annotations, updateAnnotation]);
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 });
+ // Visible rows only, as compact cards (#8292): the full record — prompt,
+ // negative prompt, settings — is read when a card is opened or handed to a
+ // generator, never for the whole page. Search and counts stay server-side
+ // over the full metadata.
+ const page = useGalleryPage({ kind: filter, q: query, starred: favoritesOnly, summary: true, hidden: false, compact: true }, { media: true, revision: annotationRevision, paused: favoritesOnly && annotationSaves > 0 });
const { loading, counts, refresh } = page;
const items = useMemo(() => page.items.map(normalizeMediaRow), [page.items]);
const setItems = useCallback(updater => page.setItems(previous => {
@@ -58,7 +62,7 @@ export default function MediaHistory() {
}), [page.setItems]);
const filtered = items;
const visibleItems = items;
- const [preview, setPreview] = usePreviewRoute(items);
+ const [preview, setPreview] = useHydratedPreviewRoute(items);
useMediaCompletionRefresh({ onImageCompleted: refresh, onVideoCompleted: refresh });
const toggleSelect = useCallback((videoId) => {
diff --git a/client/src/pages/MediaHistory.test.jsx b/client/src/pages/MediaHistory.test.jsx
index 7d3065fdad..51ad10f746 100644
--- a/client/src/pages/MediaHistory.test.jsx
+++ b/client/src/pages/MediaHistory.test.jsx
@@ -2,15 +2,15 @@ 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 } = vi.hoisted(() => ({ fetchPage: vi.fn(), deleteImage: vi.fn(), saveAnnotation: vi.fn() }));
-vi.mock('../services/apiImageVideo', () => ({ listMediaGalleryPage: fetchPage }));
+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 }));
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: () => ({}) }) }));
vi.mock('../hooks/useMediaPreviewActions', () => ({ default: () => ({}) }));
vi.mock('../components/media/VideoUpscaleDrawer', () => ({ default: () => null }));
-vi.mock('../components/media/MediaPreview', () => ({ default: ({ preview }) => preview ? <div role="dialog">{preview.prompt}</div> : null }));
-vi.mock('../components/media/MediaCard', () => ({ default: ({ item, onDelete, onToggleStar }) => <div><span>{item.prompt}</span><button type="button" onClick={() => onToggleStar(item)}>Favorite {item.filename}</button><button type="button" onClick={() => onDelete(item)}>Delete {item.filename}</button></div> }));
+vi.mock('../components/media/MediaPreview', () => ({ default: ({ preview }) => preview ? <div role="dialog">{preview.prompt}{preview.detailError && ' [details unavailable]'}</div> : null }));
+vi.mock('../components/media/MediaCard', () => ({ default: ({ item, onDelete, onToggleStar, onPreview }) => <div><button type="button" onClick={() => onPreview(item)}>{item.prompt}</button><button type="button" onClick={() => onToggleStar(item)}>Favorite {item.filename}</button><button type="button" onClick={() => onDelete(item)}>Delete {item.filename}</button></div> }));
import MediaHistory from './MediaHistory';
let rows;
@@ -22,6 +22,7 @@ beforeEach(() => {
const matches = rows.filter(row => (!filename || row.data.filename === filename) && row.data.prompt.includes(q));
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));
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>);
@@ -31,7 +32,7 @@ describe('bounded media history', () => {
open();
await screen.findByText('Picture 0');
expect(screen.queryByText('Picture 60')).toBeNull();
- expect(fetchPage).toHaveBeenCalledWith(expect.objectContaining({ limit: 60, offset: 0, summary: true }), { silent: true });
+ expect(fetchPage).toHaveBeenCalledWith(expect.objectContaining({ limit: 60, offset: 0, summary: true, hidden: false, compact: true }), { silent: true });
fetchPage.mockRejectedValueOnce(new Error('Page unavailable'));
fireEvent.click(screen.getByRole('button', { name: /Show more/ }));
await screen.findByRole('alert');
@@ -61,6 +62,31 @@ describe('bounded media history', () => {
expect(screen.queryByRole('button', { name: /Show more/ })).toBeNull();
});
+ it('opens a compact card by hydrating only that record, and never shows the preview as its prompt', 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 },
+ }));
+ open();
+ fireEvent.click(await screen.findByRole('button', { name: 'Picture 0 wi…' }));
+ expect(await screen.findByRole('dialog')).toHaveTextContent(full.trim());
+ expect(getGalleryImages).toHaveBeenCalledTimes(1);
+ expect(getGalleryImages).toHaveBeenCalledWith(['0.png'], { silent: true });
+ });
+
+ 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 } })),
+ total: rows.length, offset, limit: 60, counts: { all: rows.length, image: rows.length, video: 0 },
+ }));
+ getGalleryImages.mockRejectedValue(new Error('offline'));
+ open();
+ fireEvent.click(await screen.findByRole('button', { name: 'Picture 3' }));
+ await waitFor(() => expect(screen.getByRole('dialog')).toHaveTextContent('Picture 3 [details unavailable]'));
+ });
+
it('resolves an older deep-linked preview with a one-item request outside the loaded page', async () => {
open('/media/history?preview=image:60.png');
expect(await screen.findByRole('dialog')).toHaveTextContent('Picture 60');
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 479b4e472a..5680f69482 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -28,9 +28,9 @@ export const repairImageModel = (modelId, { deep = false } = {}) => request(`/im
});
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, starred, summary, filename, kind, media, collectionId, universeId, entryCategory, entryKind } = {}, options = {}) => {
+export const listImageGalleryPage = ({ limit = 60, offset = 0, q = '', hidden, starred, summary, compact, filename, kind, media, collectionId, universeId, entryCategory, entryKind } = {}, options = {}) => {
const params = new URLSearchParams({ limit, offset, q });
- for (const [key, value] of Object.entries({ hidden, starred, summary, filename, kind, media, collectionId, universeId, entryCategory, entryKind })) {
+ for (const [key, value] of Object.entries({ hidden, starred, summary, compact, filename, kind, media, collectionId, universeId, entryCategory, entryKind })) {
if (value !== undefined) params.set(key, value);
}
return request(`/image-gen/gallery?${params}`, options);
diff --git a/scripts/perf/collectionFixture.db.test.js b/scripts/perf/collectionFixture.db.test.js
index 5791a57d9e..df85e6e942 100644
--- a/scripts/perf/collectionFixture.db.test.js
+++ b/scripts/perf/collectionFixture.db.test.js
@@ -56,6 +56,17 @@ describe('isolated fixture using real collection routes and storage', () => {
expect(page.items.every(item => !item.data.hidden)).toBe(true);
const next = await get('/api/image-gen/gallery?limit=7&offset=7&media=true&kind=all&hidden=false');
expect(next.items.map(item => item.data.filename).some(name => page.items.some(item => item.data.filename === name))).toBe(false);
+ const compact = await get('/api/image-gen/gallery?limit=60&offset=0&media=true&kind=all&summary=true&hidden=false&compact=true');
+ expect(compact).toMatchObject({ total: 3240, hiddenTotal: 360 });
+ expect(Buffer.byteLength(JSON.stringify(compact))).toBeLessThan(60 * 2048);
+ expect(compact.items.every(item => item.data.compact && item.data.prompt.length <= 512)).toBe(true);
+ const image = compact.items.find(item => item.kind === 'image').data;
+ const lookup = await fetch(fixture.url + '/api/image-gen/gallery/lookup', { method: 'POST',
+ 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);
+ 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');
expect(inbox.total).toBe(4000);
expect(inbox.messages).toHaveLength(11);
diff --git a/scripts/perf/collectionFixtureWorker.js b/scripts/perf/collectionFixtureWorker.js
index 695abb117a..32aa3d6ec1 100644
--- a/scripts/perf/collectionFixtureWorker.js
+++ b/scripts/perf/collectionFixtureWorker.js
@@ -82,6 +82,7 @@ async function start() {
phase = 'routes';
const { createImageGalleryHandlers } = await import('../../server/routes/imageGalleryRead.js');
+ const { createVideoHistoryItemRead } = await import('../../server/routes/videoHistoryRead.js');
const { messageInboxRead, messageDetailRead } = await import('../../server/routes/messageInboxRead.js');
const { listAccounts } = await import('../../server/services/messageAccounts.js');
const { errorMiddleware, asyncHandler } = await import('../../server/lib/errorHandler.js');
@@ -102,7 +103,11 @@ async function start() {
gallery.get('/gallery/collections', galleryReads.collections);
gallery.get('/gallery/facets', galleryReads.facets);
gallery.get('/gallery', galleryReads.list);
- app.use('/api/image-gen', (req, res, next) => req.method === 'GET' ? next() : res.sendStatus(405), gallery);
+ // 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);
+ 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();
messages.get('/accounts', asyncHandler(async (_req, res) => res.json(await listAccounts())));
messages.get('/inbox', messageInboxRead);
diff --git a/server/routes/imageGalleryRead.js b/server/routes/imageGalleryRead.js
index 95b014bc12..28975430b7 100644
--- a/server/routes/imageGalleryRead.js
+++ b/server/routes/imageGalleryRead.js
@@ -11,6 +11,8 @@ export function createImageGalleryHandlers(listGallery = async () => (await impo
hidden: z.enum(['true', 'false']).optional().transform(v => v === undefined ? undefined : v === 'true'),
starred: z.enum(['true', 'false']).optional().transform(v => v === 'true'),
summary: z.enum(['true', 'false']).optional().transform(v => v === 'true'),
+ // Opt-in card projection for migrated consumers; omitted keeps full records.
+ compact: z.enum(['true', 'false']).optional().transform(v => v === 'true'),
filename: z.string().min(1).max(255).optional(),
kind: z.enum(['image', 'video', 'all']).default('image'),
media: z.enum(['true', 'false']).optional().transform(v => v === 'true'),
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 1238193597..540d9df2a9 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -240,6 +240,31 @@ describe('Image Gen Routes', () => {
expect(empty.body).toEqual({ items: [], total: 0, limit: 60, offset: 0 });
});
+ // #8292: migrated consumers opt into compact card rows; search and visible
+ // counts still read the full stored metadata, and older callers keep full records.
+ it('projects compact visible rows on request while searching the full prompt', async () => {
+ const longPrompt = 'harbor at dawn '.repeat(60) + 'lighthouse';
+ const items = [
+ { filename: 'a.png', prompt: longPrompt, negativePrompt: 'blur '.repeat(200), path: '/data/images/a.png', seed: 3, width: 64, height: 64, cfgScale: 4, cleanedFrom: 'root.png' },
+ { filename: 'b.png', prompt: 'short', hidden: true },
+ ];
+ imageGen.local.listGallery.mockResolvedValue(items);
+ const compact = await request(app).get('/api/image-gen/gallery?limit=5&hidden=false&summary=true&compact=true&q=lighthouse');
+ expect(compact.status).toBe(200);
+ expect(compact.body).toMatchObject({ total: 1, hiddenTotal: 0 });
+ const [row] = compact.body.items;
+ expect(row).toMatchObject({ compact: true, filename: 'a.png', path: '/data/images/a.png', seed: 3, width: 64, cleanedFrom: 'root.png' });
+ expect(row.prompt.length).toBeLessThanOrEqual(241);
+ expect(longPrompt.startsWith(row.prompt.slice(0, -1))).toBe(true);
+ expect(row).not.toHaveProperty('negativePrompt');
+ expect(row).not.toHaveProperty('cfgScale');
+ const visible = await request(app).get('/api/image-gen/gallery?limit=5&hidden=false&summary=true&compact=true');
+ expect(visible.body).toMatchObject({ total: 1, hiddenTotal: 1 });
+ const full = await request(app).get('/api/image-gen/gallery?limit=5&hidden=false');
+ expect(full.body.items).toEqual([items[0]]);
+ expect((await request(app).get('/api/image-gen/gallery?compact=yes')).status).toBe(400);
+ });
+
it('hydrates only requested filenames and rejects an oversized reference batch', async () => {
const items = [{ filename: 'a.png', prompt: 'first' }, { filename: 'b.png', prompt: 'second' }];
imageGen.local.listGallery.mockResolvedValue(items);
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index dfb4cfec79..b06067921a 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -11,6 +11,7 @@ import { basename } from 'path';
import os from 'os';
import { z } from 'zod';
import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
+import { createVideoHistoryItemRead, historyRecordIdSchema } from './videoHistoryRead.js';
import { uploadFields } from '../lib/multipart.js';
import {
validateRequest, videoModelTermsSchema,
@@ -1097,20 +1098,6 @@ router.post('/cancel', asyncHandler(async (req, res) => {
res.json({ ok: false, reason: 'no active or queued video render' });
}));
-// The ONE contract every `/history/:id*` route resolves its record id through
-// (#5713) — GET, DELETE, visibility and prompt all name the same stored row, so
-// they share one schema instead of three (loose / strict / none).
-//
-// It stays looser than `historyIdSchema` below on purpose: that UUID check suits
-// ids this install MINTS, but entries also arrive from a caller-supplied
-// download id and from federated peers, so a `.guid()` gate here would 400 rows
-// that are legitimately in the list. The charset bound is the floor — every
-// legitimate id is `[A-Za-z0-9._-]+`, and a value carrying a path segment or a
-// `..` can no longer parse, so `safeUnder()` two modules away in historyOps is
-// defense in depth rather than the only thing standing between a hostile id and
-// an unlink loop.
-const historyRecordIdSchema = z.string().trim().min(1).max(200)
- .regex(/^[A-Za-z0-9._-]+$/, 'invalid history id');
const updatePromptSchema = z.object({ prompt: z.string().max(8000) });
// `hidden` is required: reading an absent body as `false` turned a malformed
// request into a silent unhide.
@@ -1120,19 +1107,8 @@ router.get('/history', asyncHandler(async (_req, res) => {
res.json(await loadHistory());
}));
-// One history entry by id (#4165). A history id is NOT the filename stem — the
-// timeline renderer mints `timeline-<project>-<ts>.mp4` beside an independent
-// `randomUUID()` id — so a client holding only an id (a Creative Director
-// `finalVideoId`, an EpisodeVideoStage final) has to ask the server which file
-// it points at. Before this route existed, every such surface pulled the WHOLE
-// history list to find one row.
-router.get('/history/:id', asyncHandler(async (req, res) => {
- const parsed = historyRecordIdSchema.safeParse(req.params.id);
- if (!parsed.success) failValidation(parsed);
- const entry = await getHistoryItem(parsed.data);
- if (!entry) throw new ServerError('Not found', { status: 404, code: 'NOT_FOUND' });
- res.json(entry);
-}));
+// One history entry by id (#4165) — see videoHistoryRead.js.
+router.get('/history/:id', createVideoHistoryItemRead(getHistoryItem));
// Upload a video into the shared gallery (#4188) — the video counterpart of
// POST /api/image-gen/upload. Lands the bytes under PATHS.videos with a
diff --git a/server/routes/videoHistoryRead.js b/server/routes/videoHistoryRead.js
new file mode 100644
index 0000000000..4a72c0876d
--- /dev/null
+++ b/server/routes/videoHistoryRead.js
@@ -0,0 +1,34 @@
+// One-record video-history read, shared by the video-gen router and the
+// isolated collection-audit fixture so both exercise the same production
+// handler without importing the generation stack.
+import { z } from 'zod';
+import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
+
+// The ONE contract every `/history/:id*` route resolves its record id through
+// (#5713) — GET, DELETE, visibility and prompt all name the same stored row, so
+// they share one schema instead of three (loose / strict / none).
+//
+// It stays looser than a UUID check on purpose: that suits ids this install
+// MINTS, but entries also arrive from a caller-supplied download id and from
+// federated peers, so a `.guid()` gate here would 400 rows that are
+// legitimately in the list. The charset bound is the floor — every legitimate
+// id is `[A-Za-z0-9._-]+`, and a value carrying a path segment or a `..` can no
+// longer parse, so `safeUnder()` in historyOps is defense in depth rather than
+// the only thing standing between a hostile id and an unlink loop.
+export const historyRecordIdSchema = z.string().trim().min(1).max(200)
+ .regex(/^[A-Za-z0-9._-]+$/, 'invalid history id');
+
+// One history entry by id (#4165). A history id is NOT the filename stem — the
+// timeline renderer mints `timeline-<project>-<ts>.mp4` beside an independent
+// `randomUUID()` id — so a client holding only an id (a Creative Director
+// `finalVideoId`, an EpisodeVideoStage final, a compact Media History card) has
+// to ask the server for the record instead of pulling the whole history list.
+export function createVideoHistoryItemRead(getHistoryItem = async (id) => (await import('../services/videoGen/history.js')).getHistoryItem(id)) {
+ return asyncHandler(async (req, res) => {
+ const parsed = historyRecordIdSchema.safeParse(req.params.id);
+ if (!parsed.success) failValidation(parsed);
+ const entry = await getHistoryItem(parsed.data);
+ if (!entry) throw new ServerError('Not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(entry);
+ });
+}
diff --git a/server/services/mediaAssetIndex/gallery.js b/server/services/mediaAssetIndex/gallery.js
index 999dde2572..f756462ac3 100644
--- a/server/services/mediaAssetIndex/gallery.js
+++ b/server/services/mediaAssetIndex/gallery.js
@@ -9,6 +9,33 @@ const time = value => Number.isFinite(Date.parse(value)) ? Date.parse(value) : 0
const text = value => typeof value === 'string' && value.trim() ? value : null;
const readImages = async diskReader => (diskReader || (await import('../imageGen/local.js')).listGallery)();
+// Card fields a compact list row keeps: identity, file addressing, lineage
+// badges and the chips MediaCard renders. Everything else — full prompts,
+// negative prompts, provider payloads — stays on the record and is read on
+// demand (`/gallery/lookup`, `/video-gen/history/:id`).
+const COMPACT_FIELDS = ['id', 'filename', 'path', 'thumbnail', 'createdAt', 'hidden', 'width', 'height',
+ 'model', 'modelId', 'mode', 'seed', 'steps', 'numFrames', 'fps', 'renderMs', 'loraFilenames',
+ 'lora_filenames', 'loraPaths', 'lora_paths', 'stitchedFrom', 'upscaledFrom', 'extractedFromVideoId',
+ 'cleanedFrom', 'autoCleaned', 'regenerated', 'watermarkRemoved'];
+const COMPACT_PROMPT_CHARS = 240;
+
+/**
+ * Opt-in list projection (#8292). `compact: true` marks the row as a PREVIEW:
+ * its prompt is cut to a display label, so a consumer must hydrate the full
+ * record before editing it or handing its prompt/settings to a generation
+ * action. Search and counts still run over the full stored metadata.
+ */
+function compactGalleryRecord(data) {
+ if (!data || typeof data !== 'object') return data;
+ const row = { compact: true };
+ for (const field of COMPACT_FIELDS) if (data[field] !== undefined) row[field] = data[field];
+ const prompt = text(data.prompt) || text(data.metadata?.prompt);
+ if (prompt) {
+ row.prompt = prompt.length > COMPACT_PROMPT_CHARS ? `${prompt.slice(0, COMPACT_PROMPT_CHARS).trimEnd()}…` : prompt;
+ }
+ return row;
+}
+
async function resolveScope({ collectionId, starred, mediaKeys, collectionSnapshot }) {
let keys = mediaKeys;
let excludeKeys;
@@ -35,7 +62,7 @@ async function resolveScope({ collectionId, starred, mediaKeys, collectionSnapsh
/** Bounded reads; sidecars remain the reconcile authority and test escape hatch. */
export async function listGalleryPage({
- limit = 60, offset = 0, q = '', hidden, filename, starred = false, summary = false,
+ limit = 60, offset = 0, q = '', hidden, filename, starred = false, summary = false, compact = false,
kind = 'image', media = false, cover = false, videoSnapshot, collectionSnapshot, collectionId, universeId, entryCategory, entryKind, mediaKeys,
} = {}, diskReader) {
const mixed = media || kind !== 'image';
@@ -88,6 +115,9 @@ export async function listGalleryPage({
countAssets(filters), summary ? countAssets({ ...filters, hidden: true }) : undefined,
]);
}
+ if (compact) {
+ items = items.map(item => mixed ? { kind: item.kind, data: compactGalleryRecord(item.data) } : compactGalleryRecord(item));
+ }
return { items, total, limit, offset, ...(summary ? { hiddenTotal, ...(counts ? { counts } : {}) } : {}) };
}
diff --git a/server/services/mediaAssetIndex/gallery.test.js b/server/services/mediaAssetIndex/gallery.test.js
index b0178bf214..16ed20ce4c 100644
--- a/server/services/mediaAssetIndex/gallery.test.js
+++ b/server/services/mediaAssetIndex/gallery.test.js
@@ -53,6 +53,20 @@ describe('indexed gallery page', () => {
expect(params.slice(-2)).toEqual([1, 1]);
});
+ it('projects compact mixed rows after the indexed query without changing counts', async () => {
+ vi.stubEnv('NODE_ENV', 'production');
+ vi.stubEnv('VITEST', undefined);
+ vi.stubEnv('MEMORY_BACKEND', 'db');
+ loadHistory.mockResolvedValue([]);
+ const video = { id: 'clip-1', filename: 'clip.mp4', thumbnail: 'clip.png', prompt: 'x'.repeat(8192), stitchedFrom: ['a', 'b'], guidanceScale: 3 };
+ query.mockResolvedValue({ rows: [{ items: [{ kind: 'video', data: video }], total: '9', hiddenTotal: '2', image: '4', video: '5' }] });
+ const page = await listGalleryPage({ kind: 'all', media: true, summary: true, hidden: false, compact: true, limit: 60 });
+ expect(page).toMatchObject({ total: 9, hiddenTotal: 2, counts: { image: 4, video: 5, all: 9 } });
+ expect(page.items).toEqual([{ kind: 'video', data: {
+ compact: true, id: 'clip-1', filename: 'clip.mp4', thumbnail: 'clip.png', stitchedFrom: ['a', 'b'], prompt: 'x'.repeat(240) + '…',
+ } }]);
+ });
+
it('does not turn an index failure into a full disk scan', async () => {
vi.stubEnv('NODE_ENV', 'production');
vi.stubEnv('VITEST', undefined);