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(catalog): expose covers and recorded image relationships

[._.]/ Adam Eivy5ecab0977387
diff --git a/client/src/components/catalog/CatalogImagePreview.jsx b/client/src/components/catalog/CatalogImagePreview.jsx
new file mode 100644
index 0000000000..28f7524829
--- /dev/null
+++ b/client/src/components/catalog/CatalogImagePreview.jsx
@@ -0,0 +1,72 @@
+import { createContext, useContext } from 'react';
+import { X } from 'lucide-react';
+import MediaImage from '../MediaImage';
+import Modal from '../ui/Modal';
+import usePreviewRoute from '../../hooks/usePreviewRoute';
+
+const PreviewContext = createContext(null);
+const NO_ITEMS = [];
+
+function imageIdentity(mount, filename) {
+ if (!['images', 'image-refs'].includes(mount) || !filename || filename === '.' || filename === '..'
+ || /[/\\?#]/.test(filename) || [...filename].some((char) => char.charCodeAt(0) < 32)) return null;
+ return {
+ key: `catalog-image:${mount}:${filename}`,
+ filename,
+ src: `/data/${mount}/${encodeURIComponent(filename)}`,
+ fallbackSrc: `/data/${mount === 'images' ? 'image-refs' : 'images'}/${encodeURIComponent(filename)}`,
+ };
+}
+
+const resolvePreview = async (key) => {
+ const match = /^catalog-image:(images|image-refs):(.+)$/.exec(key);
+ return match ? imageIdentity(match[1], match[2]) : null;
+};
+
+function imageFromSrc(src) {
+ const match = /^\/data\/(images|image-refs)\/([^/?#]+)$/.exec(src || '');
+ if (!match) return null;
+ try {
+ return imageIdentity(match[1], decodeURIComponent(match[2]));
+ } catch {
+ return null;
+ }
+}
+
+// A single route host serves every tile, including a direct link to a related
+// render outside the loaded page. The resolver never searches the gallery or
+// accepts another static mount, an external URL, or a path traversal.
+export function CatalogImagePreviewProvider({ name, children }) {
+ const [preview, setPreview] = usePreviewRoute(NO_ITEMS, { resolveItem: resolvePreview });
+ const alt = preview?.alt || `${name || 'Item'} image ${preview?.filename || ''}`;
+ return (
+ <PreviewContext.Provider value={setPreview}>
+ {children}
+ {preview && (
+ <Modal open onClose={() => setPreview(null)} ariaLabel={alt} size="3xl" usePortal panelClassName="bg-port-card border border-port-border rounded-lg">
+ <div className="flex items-center justify-between gap-3 p-3 border-b border-port-border">
+ <h2 className="text-sm font-semibold text-white break-words">{alt}</h2>
+ <button type="button" onClick={() => setPreview(null)} aria-label="Close image preview"
+ className="shrink-0 min-h-11 min-w-11 flex items-center justify-center p-2 rounded text-gray-400 hover:text-white focus-visible:outline-2 focus-visible:outline-port-accent">
+ <X size={20} aria-hidden="true" />
+ </button>
+ </div>
+ <MediaImage src={preview.src} fallbackSrc={preview.fallbackSrc} alt={alt} className="w-full max-h-[75dvh] object-contain" />
+ </Modal>
+ )}
+ </PreviewContext.Provider>
+ );
+}
+
+export default function CatalogImagePreview({ src, fallbackSrc, alt, className = '', loading = 'lazy' }) {
+ const setPreview = useContext(PreviewContext);
+ const item = imageFromSrc(src);
+ const thumbnail = <MediaImage src={src} fallbackSrc={fallbackSrc} alt={alt} className={className} loading={loading} />;
+ if (!item || !setPreview) return thumbnail;
+ return (
+ <button type="button" onClick={() => setPreview({ ...item, alt })} aria-label={`Enlarge ${alt}`}
+ className="block w-full rounded focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-port-accent">
+ {thumbnail}
+ </button>
+ );
+}
diff --git a/client/src/components/catalog/CatalogMediaTile.jsx b/client/src/components/catalog/CatalogMediaTile.jsx
index 8554f0e8a6..6c39646b96 100644
--- a/client/src/components/catalog/CatalogMediaTile.jsx
+++ b/client/src/components/catalog/CatalogMediaTile.jsx
@@ -1,6 +1,6 @@
import { Mic, Star, X } from 'lucide-react';
import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';
-import MediaImage from '../MediaImage';
+import CatalogImagePreview from './CatalogImagePreview';
// One catalog media attachment tile. Images render via <MediaImage> (which
// shows a "syncing" placeholder when the asset hasn't arrived — the same
@@ -21,7 +21,7 @@ export default function CatalogMediaTile({
return (
<div className="relative group rounded border border-port-border overflow-hidden bg-port-bg">
{isImage && (
- <MediaImage src={`/data/images/${m.mediaKey}`} alt={label || m.caption || m.kind}
+ <CatalogImagePreview src={`/data/images/${encodeURIComponent(m.mediaKey)}`} fallbackSrc={`/data/image-refs/${encodeURIComponent(m.mediaKey)}`} alt={label || m.caption || m.kind}
className={contain ? 'w-full object-contain max-h-[420px]' : isPortrait ? 'w-full max-w-[180px] aspect-square object-cover' : 'w-full aspect-square object-cover'} />
)}
{isAudio && (
diff --git a/client/src/components/catalog/CatalogRelatedImages.jsx b/client/src/components/catalog/CatalogRelatedImages.jsx
new file mode 100644
index 0000000000..f96cc071b5
--- /dev/null
+++ b/client/src/components/catalog/CatalogRelatedImages.jsx
@@ -0,0 +1,68 @@
+import { useCallback } from 'react';
+import { usePagedCollection } from '../../hooks/usePagedCollection';
+import { listCatalogRelatedImages } from '../../services/apiCatalog';
+import InfiniteScrollFooter from '../ui/InfiniteScrollFooter';
+import CatalogImagePreview from './CatalogImagePreview';
+
+const PAGE_SIZE = 24;
+
+export default function CatalogRelatedImages({ ingredientId, name, excludedFilenames = [] }) {
+ const sources = [...new Set(excludedFilenames.filter((filename) => typeof filename === 'string' && filename))].sort();
+ return <RelatedImageResults key={JSON.stringify([ingredientId, sources])}
+ ingredientId={ingredientId} name={name} excludedFilenames={sources} />;
+}
+
+function RelatedImageResults({ ingredientId, name, excludedFilenames }) {
+ const fetchPage = useCallback(async ({ cursor, signal }) => {
+ const offset = cursor ?? 0;
+ const result = await listCatalogRelatedImages(ingredientId, { limit: PAGE_SIZE, offset, signal, silent: true });
+ if (!Array.isArray(result?.items) || !Number.isFinite(result.total) || result.total < 0) {
+ throw new Error('Unable to read related renders. Please retry.');
+ }
+ const items = result.items;
+ return {
+ items: items.map((item) => ({ ...item, id: item.filename })),
+ total: result.total,
+ nextCursor: items.length && offset + items.length < result.total ? offset + items.length : null,
+ };
+ }, [ingredientId]);
+ const page = usePagedCollection(fetchPage);
+ const excluded = new Set(excludedFilenames);
+ const images = page.items.filter((item) => typeof item.filename === 'string' && item.filename && !excluded.has(item.filename));
+
+ return (
+ <section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3" aria-label="Related renders">
+ <h2 className="text-sm font-semibold text-white">Related renders</h2>
+ <p className="text-xs text-gray-500">Generation metadata links these renders to this item’s images. Images can be shared by several items; appearance has not been verified.</p>
+ <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-3">
+ {images.map((item) => (
+ <figure key={item.filename} className="min-w-0 rounded border border-port-border overflow-hidden bg-port-bg">
+ <CatalogImagePreview src={`/data/images/${encodeURIComponent(item.filename)}`}
+ fallbackSrc={`/data/image-refs/${encodeURIComponent(item.filename)}`}
+ alt={`${name || 'Item'} related render ${item.filename}`} className="w-full aspect-square object-contain" />
+ <figcaption className="text-xs text-gray-400 p-2">
+ {item.association === 'derived-image' ? 'Recorded source image'
+ : item.association === 'compiled-reference' ? 'Compiled reference request'
+ : item.association === 'requested-reference' ? 'Recorded input request' : 'Recorded reference input'}
+ {item.provenanceStatus === 'legacy-unverified' && (
+ <span className="block text-port-warning mt-1">Legacy metadata · provider use unconfirmed</span>
+ )}
+ {item.provenanceStatus === 'provider-use-unverified' && (
+ <span className="block text-port-warning mt-1">Requested input · provider use unconfirmed</span>
+ )}
+ {item.provenanceStatus === 'not-supplied' && (
+ <span className="block text-port-warning mt-1">Not supplied to the provider</span>
+ )}
+ {item.missing && <span className="block mt-1 text-port-warning">Image file unavailable</span>}
+ </figcaption>
+ </figure>
+ ))}
+ </div>
+ {page.loaded && !page.hasMore && !images.length && !page.loading && !page.error && (
+ <p className="text-xs text-gray-500">No renders with recorded links to this item’s images.</p>
+ )}
+ <InfiniteScrollFooter hasMore={page.hasMore} loading={page.loading} error={page.error}
+ onLoadMore={page.loadMore} autoLoad={false} label="Load more related renders" endLabel="All recorded related renders loaded" />
+ </section>
+ );
+}
diff --git a/client/src/components/catalog/CatalogSheetsPanel.jsx b/client/src/components/catalog/CatalogSheetsPanel.jsx
index c594d861ff..f794e96101 100644
--- a/client/src/components/catalog/CatalogSheetsPanel.jsx
+++ b/client/src/components/catalog/CatalogSheetsPanel.jsx
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useState } from 'react';
import { Link } from 'react-router';
import { ExternalLink, Image as ImageIcon, Loader2, Sparkles } from 'lucide-react';
import toast from '../ui/Toast';
-import MediaImage from '../MediaImage';
+import CatalogImagePreview from './CatalogImagePreview';
import MediaJobThumb from '../pipeline/MediaJobThumb';
import ModelInputPreview from '../media/ModelInputPreview';
import CatalogMediaTile from './CatalogMediaTile';
@@ -31,7 +31,7 @@ const universeCanonPath = (universeRef) => (universeRef?.refId
function PointerSheetFigure({ variant, filename }) {
return (
<figure className="rounded border border-port-border overflow-hidden bg-port-bg">
- <MediaImage src={`/data/image-refs/${filename}`} alt={`${variant} reference sheet`}
+ <CatalogImagePreview src={`/data/image-refs/${encodeURIComponent(filename)}`} fallbackSrc={`/data/images/${encodeURIComponent(filename)}`} alt={`${variant} reference sheet`}
className="w-full object-contain max-h-[420px]" />
<figcaption className="text-[10px] uppercase tracking-wider text-gray-500 px-2 py-1 border-t border-port-border">
{variant}
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsx
index 7e037a9fff..9e1e87f6fb 100644
--- a/client/src/pages/CatalogIngredient.jsx
+++ b/client/src/pages/CatalogIngredient.jsx
@@ -52,6 +52,8 @@ import MediaJobThumb from '../components/pipeline/MediaJobThumb';
import IngredientPicker from '../components/IngredientPicker';
import MediaImage from '../components/MediaImage';
import CatalogMediaTile from '../components/catalog/CatalogMediaTile';
+import CatalogImagePreview, { CatalogImagePreviewProvider } from '../components/catalog/CatalogImagePreview';
+import CatalogRelatedImages from '../components/catalog/CatalogRelatedImages';
import CatalogSheetsPanel, { ReferenceSheetPanel } from '../components/catalog/CatalogSheetsPanel';
import CatalogUnlockNotice from '../components/catalog/CatalogUnlockNotice';
import CatalogPlatesPanel from '../components/catalog/CatalogPlatesPanel';
@@ -63,12 +65,13 @@ import GenericIngredientFields from '../components/GenericIngredientFields';
import useUnsavedChangesGuard from '../hooks/useUnsavedChangesGuard';
import { getCatalogType, CATALOG_BADGE_BY_ID, RELATION_KINDS, getRelationKind } from '../lib/catalogTypes';
import {
- libraryForPathname, ingredientPath, resolveDetailTab, detailTabPath,
+ libraryForPathname, ingredientPath, ingredientCoverUrl, resolveDetailTab, detailTabPath,
isSheetMedia, isPlateMedia, isReferenceTabMedia, lookIdOf,
} from '../lib/creativeLibraries';
import { useCatalogTypes } from '../hooks/useCatalogTypes.jsx';
import { timeAgo, formatDateTime } from '../utils/formatters';
import { humanizeIntegrityField } from '../lib/characterIntegrity';
+import { listSheetPointers } from '../lib/sheetPointers';
// Per-type editor field list + badge color now come from the shared registry
// (`client/src/lib/catalogTypes.js`). Each editor entry is `[key, label, kind]`
@@ -603,6 +606,11 @@ export default function CatalogIngredient() {
: [];
const liveLookIds = new Set(wardrobes.map((w) => w?.id).filter(Boolean));
const isReferenceTabRow = (m) => isReferenceTabMedia(m, liveLookIds);
+ const coverUrl = ingredientCoverUrl({
+ ...record,
+ thumbnailKey: media.find((m) => m.kind === 'portrait')?.mediaKey || record.thumbnailKey,
+ payload,
+ }) || ingredientCoverUrl({ thumbnailKey: media.find((m) => m.kind === 'reference')?.mediaKey });
const renderBlockedReason = (subject) => (record.payload?.locked === true
? 'Unlock this record above before rendering.'
: saving
@@ -610,6 +618,7 @@ export default function CatalogIngredient() {
: isDirty ? `Save your profile edits first — the ${subject} renders from the saved record.` : null);
return (
+ <CatalogImagePreviewProvider key={record.id} name={record.name}>
<section className="h-full overflow-y-auto p-4 md:p-6">
<UnsavedChangesConfirm
guard={routeGuard}
@@ -618,7 +627,7 @@ export default function CatalogIngredient() {
label={`Discard unsaved changes to ${record.name || 'this ingredient'}`}
onDiscard={discardAndExit}
/>
- <div className="max-w-4xl mx-auto space-y-5">
+ <div className="w-full min-w-0 space-y-5">
<header className="flex items-start justify-between gap-3 flex-wrap">
<div className="flex items-start gap-3 min-w-0">
<Sparkles className="w-6 h-6 text-port-accent mt-1 flex-shrink-0" aria-hidden="true" />
@@ -634,7 +643,7 @@ export default function CatalogIngredient() {
{record.type}
</span>
</div>
- <p className="text-xs text-gray-500 mt-1 font-mono">{record.id}</p>
+ <p className="text-xs text-gray-500 mt-1 font-mono break-all">{record.id}</p>
</div>
</div>
<div className="flex items-center gap-2 flex-wrap">
@@ -690,29 +699,42 @@ export default function CatalogIngredient() {
{activeTab === 'profile' && (
<>
<div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6 space-y-4">
- <div>
- <label htmlFor="ingredient-name" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Name</label>
- <input id="ingredient-name" type="text" value={name} onChange={(e) => setName(e.target.value)} maxLength={200}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent" />
+ <div className={coverUrl ? 'grid grid-cols-1 md:grid-cols-[minmax(0,20rem)_minmax(0,1fr)] gap-5 items-start' : ''}>
+ {coverUrl && (
+ <figure className="min-w-0 rounded-lg border border-port-border bg-port-bg overflow-hidden">
+ <CatalogImagePreview key={coverUrl} src={coverUrl} fallbackSrc={coverUrl.replace('/data/images/', '/data/image-refs/')}
+ alt={`${record.name || 'Ingredient'} cover`} className="w-full max-h-80 object-contain" loading="eager" />
+ <figcaption className="text-xs text-gray-400 p-2">Cover image · select to enlarge</figcaption>
+ </figure>
+ )}
+ <div className="min-w-0 space-y-4">
+ <div>
+ <label htmlFor="ingredient-name" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Name</label>
+ <input id="ingredient-name" type="text" value={name} onChange={(e) => setName(e.target.value)} maxLength={200}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent" />
+ </div>
+ <div>
+ <label htmlFor="ingredient-tags" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">
+ Tags
+ </label>
+ <TagPicker id="ingredient-tags" value={tags} onChange={setTags}
+ placeholder="mentor, antagonist, season-1" />
+ </div>
+ </div>
</div>
- <div>
- <label htmlFor="ingredient-tags" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">
- Tags
- </label>
- <TagPicker id="ingredient-tags" value={tags} onChange={setTags}
- placeholder="mentor, antagonist, season-1" />
+ <div className="grid grid-cols-1 xl:grid-cols-2 gap-4 items-start">
+ {isUserType
+ ? <GenericIngredientFields fields={fields} payload={payload} onChange={updatePayload} />
+ : sections
+ ? sections.map((section) => (
+ <SheetSection key={section.title} title={section.title}
+ fields={section.fields} payload={payload} onChange={updatePayload} />
+ ))
+ : fields.map(([key, label, kind]) => (
+ <SheetField key={key} fieldKey={key} label={label} kind={kind}
+ value={payload[key] ?? ''} onChange={updatePayload} />
+ ))}
</div>
- {isUserType
- ? <GenericIngredientFields fields={fields} payload={payload} onChange={updatePayload} />
- : sections
- ? sections.map((section) => (
- <SheetSection key={section.title} title={section.title}
- fields={section.fields} payload={payload} onChange={updatePayload} />
- ))
- : fields.map(([key, label, kind]) => (
- <SheetField key={key} fieldKey={key} label={label} kind={kind}
- value={payload[key] ?? ''} onChange={updatePayload} />
- ))}
{/* Structured array-field editors (aliases / color palette / stats).
Driven by the type's registry-declared `editableListFields`; the
@@ -807,8 +829,8 @@ export default function CatalogIngredient() {
{(activeTab === 'profile' ? !tabs : activeTab === 'references' || activeTab === 'images') && (
<MediaPanel
media={tabs ? media.filter(isReferenceTabRow) : media}
- canonImageRefs={Array.isArray(payload.imageRefs) ? payload.imageRefs.filter((ref) =>
- !media.some((m) => (m.kind === 'portrait' || m.kind === 'reference') && m.mediaKey === ref)) : []}
+ canonImageRefs={[payload.primaryImageRef, ...(Array.isArray(payload.imageRefs) ? payload.imageRefs : [])].filter((ref) =>
+ !media.some((m) => (m.kind === 'portrait' || m.kind === 'reference') && m.mediaKey === ref))}
primaryImageRef={payload.primaryImageRef}
missingMedia={missingMedia}
onAttach={handleAttachMedia}
@@ -824,6 +846,16 @@ export default function CatalogIngredient() {
/>
)}
+ {(activeTab === 'references' || activeTab === 'images' || (!tabs && activeTab === 'profile')) && (
+ <CatalogRelatedImages key={record.id} ingredientId={record.id} name={record.name}
+ excludedFilenames={[
+ payload.primaryImageRef,
+ ...listSheetPointers(payload).map(({ filename }) => filename),
+ ...(Array.isArray(payload.imageRefs) ? payload.imageRefs : []),
+ ...media.filter((m) => m.kind === 'portrait' || m.kind === 'reference').map((m) => m.mediaKey),
+ ]} />
+ )}
+
{activeTab === 'profile' && (
<RevisionsPanel
revisions={revisions}
@@ -834,6 +866,7 @@ export default function CatalogIngredient() {
)}
</div>
</section>
+ </CatalogImagePreviewProvider>
);
}
@@ -1383,7 +1416,14 @@ function MediaPanel({ media, canonImageRefs = [], primaryImageRef, missingMedia,
const [armedDetach, setArmedDetach] = useState(null);
const list = Array.isArray(media) ? media : [];
const portrait = list.find((m) => m.kind === 'portrait');
- const others = list.filter((m) => m.kind !== 'portrait');
+ const seenImageKeys = new Set(portrait ? [portrait.mediaKey] : []);
+ const others = list.filter((m) => {
+ if (m.kind === 'portrait') return false;
+ if (m.kind !== 'reference') return true;
+ if (seenImageKeys.has(m.mediaKey)) return false;
+ seenImageKeys.add(m.mediaKey);
+ return true;
+ });
const canonImages = [...new Set(canonImageRefs.filter((ref) => typeof ref === 'string' && ref.trim()))];
const doUpload = async (file) => {
@@ -1483,7 +1523,7 @@ function MediaPanel({ media, canonImageRefs = [], primaryImageRef, missingMedia,
)}
{others.length > 0 && (
- <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
+ <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-3">
{others.map((m) => (
<CatalogMediaTile key={`${m.mediaKey}:${m.kind}`} m={m} missing={missingMedia.has(m.mediaKey)}
onSetPortrait={onSetPortrait} onDetach={onDetach} armedDetach={armedDetach}
@@ -1496,10 +1536,10 @@ function MediaPanel({ media, canonImageRefs = [], primaryImageRef, missingMedia,
<div className="mt-3 space-y-2">
<h3 className="text-xs font-semibold text-gray-300">Canon images</h3>
<p className="text-xs text-gray-500">Existing canon references, shown read-only.</p>
- <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
+ <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-3">
{canonImages.map((filename) => (
<figure key={filename} className="min-w-0 rounded border border-port-border overflow-hidden bg-port-bg">
- <MediaImage src={`/data/images/${encodeURIComponent(filename)}`} alt={`${genName} canon reference`}
+ <CatalogImagePreview src={`/data/images/${encodeURIComponent(filename)}`} alt={`${genName} canon reference`}
fallbackSrc={`/data/image-refs/${encodeURIComponent(filename)}`}
className="w-full aspect-square object-contain" />
<figcaption className="text-xs text-gray-400 p-2 break-words">
diff --git a/client/src/pages/CatalogIngredient.test.jsx b/client/src/pages/CatalogIngredient.test.jsx
index 8c4d53a519..3832fc3939 100644
--- a/client/src/pages/CatalogIngredient.test.jsx
+++ b/client/src/pages/CatalogIngredient.test.jsx
@@ -58,6 +58,7 @@ const { detailsOf } = vi.hoisted(() => ({
vi.mock('../services/apiCatalog', () => ({
getCatalogIngredientDetails: vi.fn(async () => detailsOf(CHAR_FIXTURE)),
+ listCatalogRelatedImages: vi.fn(async () => ({ items: [], total: 0, limit: 24, offset: 0 })),
updateCatalogIngredient: vi.fn(),
deleteCatalogIngredient: vi.fn(),
linkCatalogIngredientRelation: vi.fn(),
@@ -134,7 +135,8 @@ vi.mock('../components/TagPicker', () => ({
vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }));
import CatalogIngredient, { buildGenerationPromptSeed } from './CatalogIngredient';
-import { getCatalogIngredientDetails, unlinkCatalogIngredientRelation, updateCatalogIngredient, detachCatalogIngredientMedia, restoreCatalogIngredientRevision, uploadCatalogIngredientMediaFile } from '../services/apiCatalog';
+import CatalogRelatedImages from '../components/catalog/CatalogRelatedImages';
+import { getCatalogIngredientDetails, listCatalogRelatedImages, unlinkCatalogIngredientRelation, updateCatalogIngredient, detachCatalogIngredientMedia, restoreCatalogIngredientRevision, uploadCatalogIngredientMediaFile } from '../services/apiCatalog';
import toast from '../components/ui/Toast';
const renderPage = async (path = '/catalog/character/cat-chr-1') => {
@@ -153,6 +155,7 @@ const renderPage = async (path = '/catalog/character/cat-chr-1') => {
beforeEach(() => {
getCatalogIngredientDetails.mockImplementation(async () => detailsOf(CHAR_FIXTURE));
+ listCatalogRelatedImages.mockReset().mockResolvedValue({ items: [], total: 0, limit: 24, offset: 0 });
updateCatalogIngredient.mockReset();
unlinkCatalogIngredientRelation.mockReset();
detachCatalogIngredientMedia.mockReset();
@@ -894,6 +897,127 @@ describe('CatalogIngredient — tabbed library record pages', () => {
expect(screen.queryByAltText('mood.png')).toBeNull();
});
+ it.each([
+ ['character', '/casting/example/profile'],
+ ['place', '/environments/example/profile'],
+ ['object', '/objects/example/profile'],
+ ])('shows the %s cover on its profile with an accessible enlarged view', async (type, route) => {
+ getCatalogIngredientDetails.mockResolvedValue(detailsOf({
+ id: 'example', type, name: 'Example subject', payload: { primaryImageRef: 'cover.png' },
+ }));
+ await renderPage(route);
+ expect(screen.getByAltText('Example subject cover')).toHaveAttribute('src', '/data/images/cover.png');
+ fireEvent.click(screen.getByRole('button', { name: 'Enlarge Example subject cover' }));
+ const preview = screen.getByRole('dialog', { name: 'Example subject cover' });
+ expect(within(preview).getByAltText('Example subject cover')).toHaveAttribute('data-fallback-src', '/data/image-refs/cover.png');
+ fireEvent.click(within(preview).getByRole('button', { name: 'Close image preview' }));
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ expect(updateCatalogIngredient).not.toHaveBeenCalled();
+ });
+
+ it('shows a primary canon reference omitted from imageRefs and prefers a selected portrait for the cover', async () => {
+ getCatalogIngredientDetails.mockResolvedValue({
+ ...detailsOf({ ...HERO, payload: { primaryImageRef: 'primary.png' } }),
+ media: [{ kind: 'portrait', mediaKey: 'chosen.png' }, { kind: 'reference', mediaKey: 'chosen.png' }],
+ });
+ const page = await renderPage('/casting/cat-chr-hero/profile');
+ expect(screen.getByAltText('Example Hero cover')).toHaveAttribute('src', '/data/images/chosen.png');
+ page.unmount();
+ await renderPage('/casting/cat-chr-hero/references');
+ expect(screen.getByAltText('Example Hero canon reference')).toHaveAttribute('src', '/data/images/primary.png');
+ expect(screen.getAllByRole('img').filter((image) => image.getAttribute('src') === '/data/images/chosen.png')).toHaveLength(1);
+ });
+
+ it('loads related renders only on the media tab, deduplicates known images and retries a failed next page', async () => {
+ getCatalogIngredientDetails.mockResolvedValue(detailsOf({ ...HERO, payload: { imageRefs: ['known.png'] } }));
+ const profile = await renderPage('/casting/cat-chr-hero/profile');
+ expect(listCatalogRelatedImages).not.toHaveBeenCalled();
+ profile.unmount();
+ listCatalogRelatedImages
+ .mockResolvedValueOnce({ items: [
+ { filename: 'known.png', association: 'reference-input' },
+ { filename: 'render-one.png', association: 'reference-input', missing: true, provenanceStatus: 'legacy-unverified' },
+ { filename: 'render-omitted.png', association: 'requested-reference', provenanceStatus: 'not-supplied' },
+ ], total: 4 })
+ .mockRejectedValueOnce(new Error('Related render lookup unavailable'))
+ .mockResolvedValueOnce({ items: [{ filename: 'render-two.png', association: 'compiled-reference', provenanceStatus: 'provider-use-unverified' }], total: 4 });
+ await renderPage('/casting/cat-chr-hero/references');
+ const related = screen.getByRole('region', { name: 'Related renders' });
+ expect(within(related).getAllByRole('img')).toHaveLength(2);
+ expect(within(related).getByText('Image file unavailable')).toBeInTheDocument();
+ expect(within(related).getByText(/Legacy metadata · provider use unconfirmed/)).toBeInTheDocument();
+ expect(within(related).getByText('Not supplied to the provider')).toBeInTheDocument();
+ expect(within(related).getByText(/appearance has not been verified/)).toBeInTheDocument();
+ fireEvent.click(within(related).getByRole('button', { name: 'Load more related renders' }));
+ expect(await within(related).findByRole('alert')).toHaveTextContent('Related render lookup unavailable');
+ fireEvent.click(within(related).getByRole('button', { name: 'Retry loading' }));
+ expect(await within(related).findByAltText('Example Hero related render render-two.png')).toBeInTheDocument();
+ expect(within(related).getByText('Compiled reference request')).toBeInTheDocument();
+ expect(within(related).getByText('Requested input · provider use unconfirmed')).toBeInTheDocument();
+ expect(within(related).getAllByRole('img')).toHaveLength(3);
+ expect(listCatalogRelatedImages).toHaveBeenLastCalledWith('cat-chr-hero', expect.objectContaining({ limit: 24, offset: 3, silent: true }));
+ expect(updateCatalogIngredient).not.toHaveBeenCalled();
+ });
+
+ it('drops a late related-image response after switching catalog records', async () => {
+ let resolveFirst;
+ listCatalogRelatedImages.mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve; }))
+ .mockResolvedValueOnce({ items: [{ filename: 'second-render.png', association: 'reference-input' }], total: 1 });
+ getCatalogIngredientDetails.mockImplementation(async (id) => detailsOf({ ...HERO, id }));
+ const { router } = await renderPage('/casting/first/references');
+ const firstSignal = listCatalogRelatedImages.mock.calls[0][1].signal;
+ await act(async () => { await router.navigate('/casting/second/references'); });
+ expect(await screen.findByAltText('Example Hero related render second-render.png')).toBeInTheDocument();
+ await act(async () => { resolveFirst({ items: [{ filename: 'stale.png', association: 'reference-input' }], total: 1 }); });
+ expect(firstSignal.aborted).toBe(true);
+ expect(screen.queryByAltText('Example Hero related render stale.png')).not.toBeInTheDocument();
+ });
+
+ it('stores preview identity in the URL and browser Back closes its single dialog', async () => {
+ getCatalogIngredientDetails.mockResolvedValue(detailsOf({ ...HERO, payload: { imageRefs: ['one.png', 'two.png'] } }));
+ const { router } = await renderPage('/casting/cat-chr-hero/references');
+ fireEvent.click(screen.getAllByRole('button', { name: 'Enlarge Example Hero canon reference' })[0]);
+ expect(new URLSearchParams(router.state.location.search).get('preview')).toBe('catalog-image:images:one.png');
+ expect(screen.getAllByRole('dialog')).toHaveLength(1);
+ await act(async () => { await router.navigate(-1); });
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ expect(router.state.location.pathname).toBe('/casting/cat-chr-hero/references');
+ });
+
+ it('opens a direct image link beyond loaded results and preserves its static mount', async () => {
+ getCatalogIngredientDetails.mockResolvedValue(detailsOf({ ...HERO, payload: {} }));
+ await renderPage('/casting/cat-chr-hero/references?preview=catalog-image%3Aimage-refs%3Aunlisted.png');
+ const dialog = await screen.findByRole('dialog', { name: 'Example Hero image unlisted.png' });
+ expect(screen.getAllByRole('dialog')).toHaveLength(1);
+ expect(within(dialog).getByRole('img')).toHaveAttribute('src', '/data/image-refs/unlisted.png');
+ expect(within(dialog).getByRole('img')).toHaveAttribute('data-fallback-src', '/data/images/unlisted.png');
+ });
+
+ it.each(['catalog-image:images:../private.png', 'catalog-image:videos:frame.png', 'https://example.com/image.png'])(
+ 'does not resolve a preview outside a local image basename: %s', async (preview) => {
+ await renderPage(`/casting/cat-chr-hero/references?preview=${encodeURIComponent(preview)}`);
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ },
+ );
+
+ it('refreshes related renders only when the source image set changes', async () => {
+ listCatalogRelatedImages.mockResolvedValueOnce({ items: [], total: 0 })
+ .mockResolvedValueOnce({ items: [{ filename: 'new-render.png', association: 'reference-input' }], total: 1 })
+ .mockResolvedValueOnce({ items: [], total: 0 });
+ const { rerender } = render(<CatalogRelatedImages ingredientId="example" name="Example" excludedFilenames={['one.png']} />);
+ expect(await screen.findByText('No renders with recorded links to this item’s images.')).toBeInTheDocument();
+ rerender(<CatalogRelatedImages ingredientId="example" name="Example" excludedFilenames={['one.png', 'one.png']} />);
+ expect(listCatalogRelatedImages).toHaveBeenCalledTimes(1);
+ rerender(<CatalogRelatedImages ingredientId="example" name="Example" excludedFilenames={['one.png', 'two.png']} />);
+ expect(await screen.findByAltText('Example related render new-render.png')).toBeInTheDocument();
+ rerender(<CatalogRelatedImages ingredientId="example" name="Example" excludedFilenames={['two.png', 'one.png']} />);
+ expect(listCatalogRelatedImages).toHaveBeenCalledTimes(2);
+ rerender(<CatalogRelatedImages ingredientId="example" name="Example" excludedFilenames={['one.png']} />);
+ expect(await screen.findByText('No renders with recorded links to this item’s images.')).toBeInTheDocument();
+ expect(screen.queryByAltText('Example related render new-render.png')).not.toBeInTheDocument();
+ expect(listCatalogRelatedImages).toHaveBeenCalledTimes(3);
+ });
+
it('shows existing canon images on References even when no catalog media is attached', async () => {
getCatalogIngredientDetails.mockResolvedValue(detailsOf({
...HERO, payload: { ...HERO.payload, locked: true,
diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.js
index 68cf392b04..3d2f25cfaa 100644
--- a/client/src/services/apiCatalog.js
+++ b/client/src/services/apiCatalog.js
@@ -113,6 +113,11 @@ export const listCatalogIngredientsByIds = async (ids = [], options) => {
export const getCatalogIngredientDetails = (id, options) =>
request(`/catalog/ingredients/${enc(id)}/details`, options);
+export const listCatalogRelatedImages = (id, { limit = 24, offset = 0, ...options } = {}) => {
+ const params = new URLSearchParams({ limit: String(limit), offset: String(offset) });
+ return request(`/catalog/ingredients/${enc(id)}/related-images?${params}`, options);
+};
+
// --- Tags (canonical taxonomy) ------------------------------------------
// Autocomplete over the canonical catalog_tags table. `q` is an optional
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index f75a580729..d3a2457e9f 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -288,6 +288,11 @@ export const catalogRevisionQuerySchema = z.object({
offset: z.coerce.number().int().min(0).optional(),
}).strict();
+export const catalogRelatedImagesQuerySchema = z.object({
+ limit: z.coerce.number().int().min(1).max(100).default(24),
+ offset: z.coerce.number().int().min(0).max(1000000).default(0),
+}).strict();
+
// /ingredients/:id/revisions/:revisionId/restore — re-applies a prior
// revision's name/payload/tags. Optional `source`/`actor` label the NEW
// revision the restore itself produces (defaults to 'user').
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index 4fc72f826b..14750a0b9a 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -35,6 +35,7 @@ import {
catalogBulkEntrySchema,
catalogExportQuerySchema,
catalogRevisionQuerySchema,
+ catalogRelatedImagesQuerySchema,
catalogRevisionRestoreSchema,
catalogUrlIngestSchema,
catalogFileIngestSchema,
@@ -304,6 +305,16 @@ router.get('/ingredients/:id/details', asyncHandler(async (req, res) => {
});
}));
+// Lazy, bounded provenance lookup for the detail page's References tab.
+router.get('/ingredients/:id/related-images', asyncHandler(async (req, res) => {
+ const pagination = validateRequest(catalogRelatedImagesQuerySchema, req.query);
+ const ingredient = await catalogDB.getIngredient(req.params.id);
+ if (!ingredient) throw new ServerError('Ingredient not found', { status: 404 });
+ const media = await catalogDB.listMediaForIngredient(ingredient.id);
+ const { listRelatedImages } = await import('../services/catalogRelatedImages.js');
+ res.json(await listRelatedImages(ingredient, media, pagination));
+}));
+
router.post('/ingredients', asyncHandler(async (req, res) => {
const body = validateRequest(catalogIngredientCreateSchema, req.body);
const ing = await catalogDB.createIngredient({
diff --git a/server/routes/catalog.test.js b/server/routes/catalog.test.js
index 7fc58e3e3c..e8e0626235 100644
--- a/server/routes/catalog.test.js
+++ b/server/routes/catalog.test.js
@@ -70,9 +70,11 @@ const NONCE = Date.now();
const createdIngredientIds = new Set();
const createdScrapIds = new Set();
const receiptKeys = new Set();
+const relatedImageKeys = new Set();
afterAll(async () => {
if (!dbReady) return;
+ await query('DELETE FROM media_assets WHERE media_key = ANY($1::text[])', [[...relatedImageKeys]]);
await query('DELETE FROM catalog_commit_receipts WHERE operation_key = ANY($1::uuid[])', [[...receiptKeys]]);
for (const id of createdIngredientIds) {
await catalogDB.deleteIngredient(id, { hard: true }).catch(() => {});
@@ -83,6 +85,87 @@ afterAll(async () => {
await close();
});
+describe.skipIf(!runDb)('GET /api/catalog/ingredients/:id/related-images', () => {
+ it('pages only direct image provenance, excluding displayed, hidden, malformed and unrelated assets', async () => {
+ const prefix = `related-${NONCE}-`;
+ const primary = `${prefix}cover.png`;
+ const attached = `${prefix}attached.png`;
+ const ing = await catalogDB.createIngredient({ type: 'place', name: 'Example room', payload: { primaryImageRef: primary, imageRefs: [primary], locked: true } });
+ createdIngredientIds.add(ing.id);
+ await catalogDB.attachMedia(ing.id, attached, 'reference');
+ const rows = [
+ ['a', { referenceImageFilenames: [primary], inputProvenance: 'provider-inputs', prompt: 'private prompt' }],
+ ['b', { cleanedFrom: attached }],
+ ['c', { initImageFilename: primary }],
+ ['d', { inputProvenance: 'provider-inputs', referenceImageFilenames: ['other-input.png'],
+ visualConditioning: { assets: [{ filename: primary }], status: 'degraded' } }],
+ ['e', { requestedInputImages: [{ role: 'referenceImages', filename: primary }] }],
+ ['f', { inputProvenance: 'provider-inputs', requestedInputImages: [{ filename: primary }], omittedInputImages: [{ filename: primary }] }],
+ ['omitted', { visualConditioning: { assets: [], omitted: [{ filename: primary }] } }],
+ ['bad-compiled', { visualConditioning: { assets: { filename: primary } } }],
+ ['hidden', { referenceImageFilenames: [primary], hidden: true }],
+ ['unrelated', { prompt: primary, universeId: 'shared-example-universe' }],
+ ['malformed', { referenceImageFilenames: { [primary]: true } }],
+ ['nested-only', { referenceImageFilenames: [`${prefix}a.png`] }],
+ ['cover', { referenceImageFilenames: [attached] }],
+ ['attached', { upscaledFrom: primary }],
+ ];
+ for (const [suffix, data] of rows) {
+ const filename = `${prefix}${suffix}.png`;
+ const key = `image:${filename}`;
+ relatedImageKeys.add(key);
+ await query('INSERT INTO media_assets (media_key, kind, ref, data, created_at) VALUES ($1, $2, $3, $4::jsonb, $5)',
+ [key, 'image', filename, JSON.stringify({ filename, createdAt: '2026-01-01T00:00:00.000Z', ...data }), '2026-01-01T00:00:00.000Z']);
+ }
+ const url = `/api/catalog/ingredients/${ing.id}/related-images`;
+ const first = await request(makeApp()).get(`${url}?limit=2`);
+ expect(first.status).toBe(200);
+ expect(first.body).toMatchObject({ total: 6, limit: 2, offset: 0 });
+ expect(first.body.items.map(item => [item.filename, item.association])).toEqual([
+ [`${prefix}a.png`, 'reference-input'], [`${prefix}b.png`, 'derived-image'],
+ ]);
+ expect(first.body.items[0]).not.toHaveProperty('prompt');
+ expect(first.body.items[0].provenanceStatus).toBe('recorded');
+ // A stale index entry retains its recorded association but is explicit
+ // about absent bytes; the response must not silently claim a valid asset.
+ expect(first.body.items[0].missing).toBe(true);
+ const next = await request(makeApp()).get(`${url}?limit=2&offset=2`);
+ expect(next.body.items.map(item => item.filename)).toEqual([`${prefix}c.png`, `${prefix}d.png`]);
+ expect(next.body.items[0].provenanceStatus).toBe('legacy-unverified');
+ // A marker for OTHER supplied inputs must not upgrade this compiled-only
+ // association to confirmed provider input.
+ expect(next.body.items[1]).toMatchObject({ association: 'compiled-reference', provenanceStatus: 'provider-use-unverified' });
+ const requested = await request(makeApp()).get(`${url}?limit=2&offset=4`);
+ expect(requested.body.items.map(item => [item.association, item.provenanceStatus])).toEqual([
+ ['requested-reference', 'provider-use-unverified'], ['requested-reference', 'not-supplied'],
+ ]);
+ expect((await request(makeApp()).get(`${url}?offset=20`)).body).toMatchObject({ items: [], total: 6 });
+ expect((await request(makeApp()).get(`${url}?limit=101`)).status).toBe(400);
+ expect((await request(makeApp()).get(`${url}?offset=-1`)).status).toBe(400);
+ expect((await request(makeApp()).get('/api/catalog/ingredients/nonexistent/related-images')).status).toBe(404);
+ expect((await catalogDB.getIngredient(ing.id)).payload).toEqual(ing.payload);
+ });
+
+ it('finds renders conditioned by legacy and variant sheets even without a portrait', async () => {
+ const prefix = `related-sheet-${NONCE}-`;
+ const ing = await catalogDB.createIngredient({ type: 'character', name: 'Example sheet character', payload: {
+ referenceSheetImageRef: `${prefix}legacy.png`, referenceSheets: { profile: `${prefix}profile.png` }, locked: true,
+ } });
+ createdIngredientIds.add(ing.id);
+ for (const suffix of ['legacy', 'profile']) {
+ const filename = `${prefix}${suffix}-render.png`;
+ const key = `image:${filename}`;
+ relatedImageKeys.add(key);
+ await query('INSERT INTO media_assets (media_key, kind, ref, data, created_at) VALUES ($1, $2, $3, $4::jsonb, $5)',
+ [key, 'image', filename, JSON.stringify({ referenceImageFilenames: [`${prefix}${suffix}.png`] }), '2026-01-01T00:00:00.000Z']);
+ }
+ const result = await request(makeApp()).get(`/api/catalog/ingredients/${ing.id}/related-images`);
+ expect(result.status).toBe(200);
+ expect(result.body.total).toBe(2);
+ expect(result.body.items.map(item => item.filename)).toEqual([`${prefix}legacy-render.png`, `${prefix}profile-render.png`]);
+ });
+});
+
describe.skipIf(!runDb)('POST /api/catalog/bulk-import — scrap persistence', () => {
it('persists a round-tripped `### Scraps` bullet as a catalog_scraps row + source link', async () => {
const markdown = [
diff --git a/server/services/catalogRelatedImages.js b/server/services/catalogRelatedImages.js
new file mode 100644
index 0000000000..43fe777a7a
--- /dev/null
+++ b/server/services/catalogRelatedImages.js
@@ -0,0 +1,66 @@
+import { query } from '../lib/db.js';
+import { listSheetPointers } from '../lib/sheetPointers.js';
+import { resolveGalleryImage, resolveImageRef } from '../lib/pathSafety.js';
+
+// Only structured, direct provenance is evidence of a relationship. Prompts can
+// contain a whole production bible, and universe/collection membership does not
+// mean that an image depicts this ingredient. Do not recursively widen the set.
+export async function listRelatedImages(ingredient, media, { limit, offset }) {
+ const payload = ingredient.payload || {};
+ const filenames = [...new Set([
+ payload.primaryImageRef,
+ ...(Array.isArray(payload.imageRefs) ? payload.imageRefs : []),
+ ...listSheetPointers(payload).map(sheet => sheet.filename),
+ ...media.filter(m => m.kind === 'portrait' || m.kind === 'reference').map(m => m.mediaKey),
+ ].filter(value => typeof value === 'string' && value.length > 0))];
+ if (!filenames.length) return { items: [], total: 0, limit, offset };
+
+ // Read the existing derived index rather than scanning every sidecar for
+ // each detail request. Count + page share a single database snapshot, and
+ // only card fields leave the server (never prompts or local paths).
+ const result = await query(`
+ WITH candidates AS (
+ SELECT ref, data, created_at,
+ (data->>'cleanedFrom' = ANY($1::text[]) OR data->>'upscaledFrom' = ANY($1::text[])) AS derived,
+ (data->>'initImageFilename' = ANY($1::text[])
+ OR (CASE WHEN jsonb_typeof(data->'referenceImageFilenames') = 'array'
+ THEN data->'referenceImageFilenames' ELSE '[]'::jsonb END) ?| $1::text[]) AS supplied,
+ EXISTS (SELECT 1 FROM jsonb_array_elements(
+ CASE WHEN jsonb_typeof(data #> '{visualConditioning,assets}') = 'array'
+ THEN data #> '{visualConditioning,assets}' ELSE '[]'::jsonb END) AS asset
+ WHERE asset->>'filename' = ANY($1::text[])) AS compiled,
+ EXISTS (SELECT 1 FROM jsonb_array_elements(
+ CASE WHEN jsonb_typeof(data->'requestedInputImages') = 'array'
+ THEN data->'requestedInputImages' ELSE '[]'::jsonb END) AS asset
+ WHERE asset->>'filename' = ANY($1::text[])) AS requested,
+ EXISTS (SELECT 1 FROM jsonb_array_elements(
+ CASE WHEN jsonb_typeof(data->'omittedInputImages') = 'array'
+ THEN data->'omittedInputImages' ELSE '[]'::jsonb END) AS asset
+ WHERE asset->>'filename' = ANY($1::text[])) AS omitted
+ FROM media_assets
+ WHERE kind = 'image' AND COALESCE(data->>'hidden', 'false') <> 'true'
+ AND NOT (ref = ANY($1::text[]))
+ ), linked AS MATERIALIZED (
+ SELECT ref AS filename, created_at,
+ jsonb_build_object('filename', ref, 'width', data->'width',
+ 'height', data->'height', 'createdAt', data->'createdAt',
+ 'provenanceStatus', CASE WHEN derived OR (supplied AND data->>'inputProvenance' = 'provider-inputs')
+ THEN 'recorded' WHEN omitted THEN 'not-supplied'
+ WHEN supplied THEN 'legacy-unverified' ELSE 'provider-use-unverified' END,
+ 'association', CASE WHEN derived THEN 'derived-image'
+ WHEN supplied THEN 'reference-input' WHEN compiled THEN 'compiled-reference'
+ ELSE 'requested-reference' END) AS item
+ FROM candidates WHERE derived OR supplied OR compiled OR requested
+ ), page AS (
+ SELECT item, created_at, filename FROM linked
+ ORDER BY created_at DESC NULLS LAST, filename ASC LIMIT $2 OFFSET $3
+ )
+ SELECT (SELECT count(*)::int FROM linked) AS total,
+ COALESCE((SELECT jsonb_agg(item ORDER BY created_at DESC NULLS LAST, filename ASC) FROM page), '[]'::jsonb) AS items
+ `, [filenames, limit, offset]);
+ const { items, total } = result.rows[0];
+ return {
+ items: items.map(item => ({ ...item, missing: !(resolveGalleryImage(item.filename) || resolveImageRef(item.filename)) })),
+ total, limit, offset,
+ };
+}
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index cf06d1cd22..49637d06e4 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -30,7 +30,7 @@ import { spawn } from '../../lib/childProcess.js';
import { bufferedSpawn, prepareCliSpawn, killProcessTree } from '../../lib/bufferedSpawn.js';
import { readFile, readdir, stat, mkdtemp } from 'fs/promises';
import { existsSync } from 'fs';
-import { join, isAbsolute, resolve, sep } from 'path';
+import { basename, join, isAbsolute, resolve, sep } from 'path';
import { tmpdir } from 'os';
import { codexHomeDir } from '../../lib/codexUserConfig.js';
import { withSpawnCwdEnv } from '../../lib/spawnCwd.js';
@@ -324,6 +324,9 @@ export async function generateImage({
id: jobId, prompt: prompt.trim(), negativePrompt: negativePrompt || '',
width: width ? Number(width) : null, height: height ? Number(height) : null,
filename, mode: IMAGE_GEN_MODE.CODEX, model: effectiveModel,
+ inputProvenance: 'provider-inputs',
+ initImageFilename: inputImages.initPath ? basename(inputImages.initPath) : null,
+ referenceImageFilenames: inputImages.referencePaths.map(path => basename(path)),
...(visualConditioning ? { visualConditioning } : {}),
...sentRecord,
createdAt: new Date().toISOString(),
diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.js
index ad41a32385..892c642567 100644
--- a/server/services/imageGen/codex.test.js
+++ b/server/services/imageGen/codex.test.js
@@ -432,7 +432,10 @@ describe('codex provider — image harvest', () => {
const completedListener = vi.fn();
imageGenEvents.on('completed', completedListener);
- const job = await codex.generateImage({ prompt: 'a fox' });
+ await mkdir(FAKE_IMAGES_DIR, { recursive: true });
+ await writeFile(join(FAKE_IMAGES_DIR, 'source.png'), fakePngBytes);
+ await writeFile(join(FAKE_IMAGES_DIR, 'reference.png'), fakePngBytes);
+ const job = await codex.generateImage({ prompt: 'a fox', initImagePath: 'source.png', referenceImagePaths: ['reference.png', 'missing.png'] });
const child = spawnCalls[0].child;
// Drive the session id banner on stderr (codex prints it there).
@@ -462,6 +465,10 @@ describe('codex provider — image harvest', () => {
// Sidecar metadata exists too.
const sidecar = join(FAKE_IMAGES_DIR, `${job.generationId}.metadata.json`);
expect(existsSync(sidecar)).toBe(true);
+ expect(JSON.parse(await readFile(sidecar, 'utf8'))).toMatchObject({
+ inputProvenance: 'provider-inputs',
+ initImageFilename: 'source.png', referenceImageFilenames: ['reference.png'],
+ });
});
it('crops an off-aspect frame to the requested ratio and records it in the sidecar', async () => {