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

feat([issue-1354]): catalog card thumbnails, image generation, and canon sync

[._.]/ Adam Eivydc8351e4c615
diff --git a/client/src/pages/Catalog.jsx b/client/src/pages/Catalog.jsx
index 53aa18371a..98ffea4a91 100644
--- a/client/src/pages/Catalog.jsx
+++ b/client/src/pages/Catalog.jsx
@@ -8,15 +8,16 @@
* extract page. Delete uses an armed two-click confirm (no window.confirm).
*/
-import { useState, useEffect, useMemo, useCallback } from 'react';
+import { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom';
-import { Sparkles, Plus, Search, FileInput, Trash2, Loader2 } from 'lucide-react';
+import { Sparkles, Plus, Search, FileInput, Trash2, Loader2, RefreshCw } from 'lucide-react';
import toast from '../components/ui/Toast';
import {
listCatalogIngredients,
createCatalogIngredient,
deleteCatalogIngredient,
getCatalogStats,
+ rerunCatalogMigration,
} from '../services/apiCatalog';
import { payloadSnippet } from '../lib/catalogTypes';
import { useCatalogTypes } from '../hooks/useCatalogTypes.jsx';
@@ -36,6 +37,30 @@ function TypeBadge({ type, getType }) {
);
}
+// Card thumbnail: the ingredient's portrait (or most recent reference image),
+// resolved from the media library at /data/images/<key>. Falls back to a dimmed
+// Sparkles placeholder when there's no image or the file fails to load, so every
+// card keeps the same footprint and the grid stays aligned.
+function CardThumb({ mediaKey, alt }) {
+ const [failed, setFailed] = useState(false);
+ const showImage = !!mediaKey && !failed;
+ return (
+ <div className="w-14 h-14 shrink-0 rounded-md overflow-hidden border border-port-border bg-port-bg flex items-center justify-center">
+ {showImage ? (
+ <img
+ src={`/data/images/${mediaKey}`}
+ alt={alt}
+ className="w-full h-full object-cover"
+ loading="lazy"
+ onError={() => setFailed(true)}
+ />
+ ) : (
+ <Sparkles size={18} className="text-gray-600" aria-hidden="true" />
+ )}
+ </div>
+ );
+}
+
export default function Catalog() {
// Merged type registry (system + user-defined). `types` drives the filter
// chips + the New-form dropdown; `getType` resolves badge/primary-content.
@@ -57,6 +82,10 @@ export default function Catalog() {
const [creating, setCreating] = useState(false);
// Armed-row id for two-click delete (no window.confirm).
const [armedId, setArmedId] = useState(null);
+ // "Sync from Universes" — re-runs the bible→catalog backfill so canon
+ // characters/places/objects added after the one-time boot promotion show up
+ // in the catalog. In flight while the server walks every universe.
+ const [syncing, setSyncing] = useState(false);
useEffect(() => {
const t = setTimeout(() => setQ(searchInput.trim()), 300);
@@ -152,6 +181,31 @@ export default function Catalog() {
loadStats();
};
+ // Re-run the bible→catalog backfill to pull in canon entities that aren't in
+ // the catalog yet (the boot-time promotion only runs once per install, so
+ // characters added to a universe later never get promoted without this).
+ // `force: true` ignores the one-time marker. Idempotent — already-promoted
+ // entries are skipped server-side — so it's safe to click repeatedly.
+ const handleSync = async () => {
+ setSyncing(true);
+ const result = await rerunCatalogMigration({ force: true, silent: true }).catch((err) => {
+ toast.error(err?.message || 'Sync from universes failed');
+ return null;
+ });
+ setSyncing(false);
+ if (!result) return;
+ const promoted = result?.stats?.promoted ?? result?.promoted ?? 0;
+ toast.success(
+ promoted > 0
+ ? `Synced ${promoted} canon item${promoted === 1 ? '' : 's'} into the catalog`
+ : 'Catalog already up to date with your universes',
+ );
+ if (promoted > 0) {
+ loadItems();
+ loadStats();
+ }
+ };
+
// Single reset path used by Cancel + toolbar toggle + post-submit so all
// three "form dismissed" paths leave the same clean state — without this,
// stale name/content text reappears the next time the form opens.
@@ -171,6 +225,18 @@ export default function Catalog() {
</span>
</div>
<div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={handleSync}
+ disabled={syncing}
+ title="Pull canon characters, places, and objects from your universes into the catalog"
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg border border-port-border bg-port-card hover:bg-port-bg text-white text-sm font-medium disabled:opacity-50"
+ >
+ {syncing
+ ? <Loader2 size={16} className="animate-spin" aria-hidden="true" />
+ : <RefreshCw size={16} aria-hidden="true" />}
+ {syncing ? 'Syncing…' : 'Sync from Universes'}
+ </button>
<Link
to="/catalog/ingest"
className="inline-flex items-center gap-2 px-3 py-2 rounded-lg border border-port-border bg-port-card hover:bg-port-bg text-white text-sm font-medium"
@@ -321,20 +387,23 @@ export default function Catalog() {
<li key={it.id} className="relative bg-port-card border border-port-border rounded-lg hover:border-port-accent/60 transition-colors">
<Link
to={`/catalog/${encodeURIComponent(it.type)}/${encodeURIComponent(it.id)}`}
- className={`flex flex-col gap-2 p-3 min-h-[88px] ${armed ? 'pr-32' : 'pr-10'}`}
+ className={`flex gap-3 p-3 min-h-[88px] ${armed ? 'pr-32' : 'pr-10'}`}
>
- <span className="block text-white font-medium truncate">{name}</span>
- <span className="flex items-center gap-1.5 flex-wrap">
- <TypeBadge type={it.type} getType={getType} />
- {(it.tags || []).slice(0, 4).map((tag) => (
- <span key={tag} className="text-[10px] px-1.5 py-0.5 rounded bg-port-bg border border-port-border text-gray-400">
- {tag}
- </span>
- ))}
+ <CardThumb mediaKey={it.thumbnailKey} alt={name} />
+ <span className="flex flex-col gap-2 min-w-0 flex-1">
+ <span className="block text-white font-medium truncate">{name}</span>
+ <span className="flex items-center gap-1.5 flex-wrap">
+ <TypeBadge type={it.type} getType={getType} />
+ {(it.tags || []).slice(0, 4).map((tag) => (
+ <span key={tag} className="text-[10px] px-1.5 py-0.5 rounded bg-port-bg border border-port-border text-gray-400">
+ {tag}
+ </span>
+ ))}
+ </span>
+ {payloadSnippet(it.payload, it.type, 120, getType) ? (
+ <span className="text-xs text-gray-400 line-clamp-2">{payloadSnippet(it.payload, it.type, 120, getType)}</span>
+ ) : null}
</span>
- {payloadSnippet(it.payload, it.type, 120, getType) ? (
- <span className="text-xs text-gray-400 line-clamp-3">{payloadSnippet(it.payload, it.type, 120, getType)}</span>
- ) : null}
</Link>
<div className="absolute top-2 right-2">
{/* The delete control is a sibling of the <Link>, not a
diff --git a/client/src/pages/Catalog.test.jsx b/client/src/pages/Catalog.test.jsx
index b1c0631c73..2ce9eaaab9 100644
--- a/client/src/pages/Catalog.test.jsx
+++ b/client/src/pages/Catalog.test.jsx
@@ -7,6 +7,7 @@ vi.mock('../services/apiCatalog', () => ({
createCatalogIngredient: vi.fn(),
deleteCatalogIngredient: vi.fn(),
getCatalogStats: vi.fn(),
+ rerunCatalogMigration: vi.fn(),
}));
vi.mock('../components/ui/Toast', () => ({
@@ -25,6 +26,7 @@ import {
createCatalogIngredient,
deleteCatalogIngredient,
getCatalogStats,
+ rerunCatalogMigration,
} from '../services/apiCatalog';
import { listCatalogTypes } from '../services/apiCatalogTypes';
import toast from '../components/ui/Toast';
@@ -44,6 +46,7 @@ beforeEach(() => {
vi.clearAllMocks();
listCatalogIngredients.mockResolvedValue({ items: sample });
getCatalogStats.mockResolvedValue({ total: 2, byType: { character: 1, place: 1 } });
+ rerunCatalogMigration.mockResolvedValue({ stats: { promoted: 0 } });
// Default: system registry only (the hook merges with the static fallback).
listCatalogTypes.mockResolvedValue({ types: [] });
});
@@ -158,6 +161,47 @@ describe('Catalog page', () => {
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('load failed'));
});
+ it('syncs from universes and reloads the list when items were promoted', async () => {
+ rerunCatalogMigration.mockResolvedValue({ stats: { promoted: 3 } });
+ renderCatalog();
+ await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
+ const callsBefore = listCatalogIngredients.mock.calls.length;
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /Sync from Universes/i }));
+ });
+
+ expect(rerunCatalogMigration).toHaveBeenCalledWith(
+ expect.objectContaining({ force: true, silent: true }),
+ );
+ // A non-zero promote count reloads the list + stats so new items appear.
+ await waitFor(() => expect(listCatalogIngredients.mock.calls.length).toBeGreaterThan(callsBefore));
+ expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/Synced 3 canon items/i));
+ });
+
+ it('reports an up-to-date catalog without reloading when nothing was promoted', async () => {
+ rerunCatalogMigration.mockResolvedValue({ stats: { promoted: 0 } });
+ renderCatalog();
+ await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
+ const callsBefore = listCatalogIngredients.mock.calls.length;
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /Sync from Universes/i }));
+ });
+
+ expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/already up to date/i));
+ expect(listCatalogIngredients.mock.calls.length).toBe(callsBefore);
+ });
+
+ it('renders a card thumbnail when the ingredient has a thumbnail key', async () => {
+ listCatalogIngredients.mockResolvedValue({
+ items: [{ ...sample[0], thumbnailKey: 'hero.png' }],
+ });
+ renderCatalog();
+ const img = await screen.findByAltText('Echo Saint');
+ expect(img.getAttribute('src')).toBe('/data/images/hero.png');
+ });
+
it('renders a user-defined type as a filter chip from the merged registry', async () => {
listCatalogTypes.mockResolvedValue({
types: [{ id: 'faction', label: 'Faction', system: false, badgeColor: 'bg-gray-500/20 text-gray-300 border-gray-500/40', primaryContentKey: 'creed', primaryContentLabel: 'Creed', snippetFallbackKeys: ['creed'], fields: [] }],
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsx
index 39f1c45f2b..e555a22641 100644
--- a/client/src/pages/CatalogIngredient.jsx
+++ b/client/src/pages/CatalogIngredient.jsx
@@ -24,6 +24,10 @@ import {
detachCatalogIngredientMedia,
} from '../services/apiCatalog';
import { listImageGallery } from '../services/apiImageVideo';
+import { generateImage } from '../services/apiSystem';
+import { composeCanonStyledPrompt } from '../lib/composeStyledPrompt';
+import useMounted from '../hooks/useMounted';
+import MediaJobThumb from '../components/pipeline/MediaJobThumb';
import IngredientPicker from '../components/IngredientPicker';
import MediaImage from '../components/MediaImage';
import CharacterLoraChip from '../components/loraTraining/CharacterLoraChip';
@@ -59,6 +63,24 @@ function REFKIND_LABEL(kind) {
return kind;
}
+// Build the image-generation prompt source from the (live, editable) payload:
+// the type's primary content field first, then a curated set of *visual*
+// description fields, so a character renders from physicalDescription and a
+// place/object/idea from description/summary. Intentionally narrower than the
+// type's full snippetFallbackKeys — keys like `role`/`notes`/`significance`
+// describe the entity but don't depict it, and would seed weak prompts.
+// Returns '' when nothing usable is present — the generate button gates on it.
+const GENERATION_DESCRIPTION_KEYS = ['physicalDescription', 'description', 'summary'];
+function deriveGenerationDescription(payload, typeDef) {
+ if (!payload || typeof payload !== 'object') return '';
+ const keys = [typeDef?.primaryContentKey, ...GENERATION_DESCRIPTION_KEYS].filter(Boolean);
+ for (const k of keys) {
+ const v = payload[k];
+ if (typeof v === 'string' && v.trim()) return v.trim();
+ }
+ return '';
+}
+
export default function CatalogIngredient() {
const { id } = useParams();
const navigate = useNavigate();
@@ -214,6 +236,21 @@ export default function CatalogIngredient() {
setMedia((prev) => prev.filter((m) => !(m.mediaKey === mediaKey && m.kind === kind)));
};
+ // A freshly-generated image lands in the media library as `<jobId>.png`; wire
+ // it onto this ingredient. First image becomes the portrait (so it shows as
+ // the card thumbnail immediately); later ones attach as references.
+ const handleGeneratedImage = useCallback(async (filename) => {
+ if (!record || !filename) return;
+ const hasPortrait = media.some((m) => m.kind === 'portrait');
+ const ok = await (hasPortrait
+ ? attachCatalogIngredientMedia(record.id, { mediaKey: filename, kind: 'reference' }, { silent: true })
+ : setCatalogIngredientPortrait(record.id, { mediaKey: filename }, { silent: true })
+ ).then(() => true).catch((err) => { toast.error(err?.message || 'Failed to attach generated image'); return false; });
+ if (!ok) return;
+ refreshMedia();
+ toast.success(hasPortrait ? 'Generated image attached' : 'Generated portrait set');
+ }, [record, media, refreshMedia]);
+
const handleSave = async () => {
if (!record) return;
const trimmedName = name.trim();
@@ -293,6 +330,9 @@ export default function CatalogIngredient() {
// generic field renderer for it. System types keep their existing branches.
const isUserType = typeDef.system === false;
const badgeClass = CATALOG_BADGE_BY_ID[record.type] || 'bg-gray-500/20 text-gray-300 border-gray-500/40';
+ // Prompt source for the Media panel's "Generate" affordance — derived from the
+ // currently-edited payload so tweaks to the description feed the next render.
+ const genDescription = deriveGenerationDescription(payload, typeDef);
// Group refs by kind for the "Appears in" panel. Tolerates either an array
// of `{ refKind, refId, role }` or a server-grouped shape.
@@ -423,6 +463,9 @@ export default function CatalogIngredient() {
onAttach={handleAttachMedia}
onSetPortrait={handleSetPortrait}
onDetach={handleDetachMedia}
+ genName={record.name}
+ genDescription={genDescription}
+ onGenerated={handleGeneratedImage}
/>
<RevisionsPanel
@@ -802,7 +845,69 @@ function RelationsPanel({ record, relations, onAdd, onRemove }) {
// file-upload + voice-memo capture are intentionally out of scope here and
// land via the separate `[catalog-source-kinds-url-file-voice]` item — the
// `onAttach(mediaKey, kind)` seam is all those paths need to reuse.
-function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach }) {
+// "Generate" affordance for the Media panel — turns the ingredient's
+// description into an image via the same image-gen queue the Universe canon
+// renders use. The generated file lands in the media library as `<jobId>.png`;
+// `MediaJobThumb` surfaces the live diffusion preview and fires `onFilename`
+// once complete, which routes to `onComplete` to attach it onto the ingredient.
+// Disabled when the description is blank — there's nothing to render from.
+function GenerateImageControl({ name, description, onComplete }) {
+ const mountedRef = useMounted();
+ const [jobId, setJobId] = useState(null);
+ const [starting, setStarting] = useState(false);
+ const canGenerate = !!(description && description.trim());
+
+ const handleGenerate = async () => {
+ if (!canGenerate) {
+ toast.error('Add a description before generating an image');
+ return;
+ }
+ setStarting(true);
+ const styled = composeCanonStyledPrompt({ name: name || 'Subject', description, universe: null });
+ const queued = await generateImage(
+ { prompt: styled.prompt, negativePrompt: styled.negativePrompt || undefined },
+ { silent: true },
+ ).catch((err) => { toast.error(err?.message || 'Image generation failed'); return null; });
+ if (!mountedRef.current) return;
+ setStarting(false);
+ if (!queued?.jobId) return;
+ setJobId(queued.jobId);
+ toast.success('Generating image…');
+ };
+
+ // Fires once when the in-flight job completes (MediaJobThumb forwards the
+ // rendered filename). Clear the job so the thumb unmounts, then hand the
+ // filename up to be attached as portrait/reference.
+ const handleFilename = useCallback((filename) => {
+ if (!filename) return;
+ setJobId(null);
+ onComplete?.(filename);
+ }, [onComplete]);
+
+ return (
+ <span className="inline-flex items-center gap-2">
+ {jobId && (
+ <MediaJobThumb jobId={jobId} label="Generated image" size="xs" onFilename={handleFilename} />
+ )}
+ <button
+ type="button"
+ onClick={handleGenerate}
+ disabled={!canGenerate || starting || !!jobId}
+ title={canGenerate
+ ? 'Generate an image from this item’s description'
+ : 'Add a description first to generate an image'}
+ className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-port-border text-gray-300 hover:text-white hover:border-port-accent disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {starting || jobId
+ ? <Loader2 size={12} className="animate-spin" aria-hidden="true" />
+ : <Sparkles size={12} aria-hidden="true" />}
+ {jobId ? 'Generating…' : 'Generate'}
+ </button>
+ </span>
+ );
+}
+
+function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, genName, genDescription, onGenerated }) {
const [pickerOpen, setPickerOpen] = useState(false);
const [dragOver, setDragOver] = useState(false);
const list = Array.isArray(media) ? media : [];
@@ -820,14 +925,17 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach })
return (
<section className="bg-port-card border border-port-border rounded-lg p-4">
- <div className="flex items-center justify-between mb-3">
+ <div className="flex items-center justify-between mb-3 gap-2 flex-wrap">
<h2 className="text-sm font-semibold text-white flex items-center gap-1.5">
<ImageIcon size={14} aria-hidden="true" /> Media
</h2>
- <button type="button" onClick={() => setPickerOpen(true)}
- className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-port-border text-gray-300 hover:text-white hover:border-port-accent">
- <Plus size={12} aria-hidden="true" /> Pick from gallery
- </button>
+ <div className="flex items-center gap-2">
+ <GenerateImageControl name={genName} description={genDescription} onComplete={onGenerated} />
+ <button type="button" onClick={() => setPickerOpen(true)}
+ className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-port-border text-gray-300 hover:text-white hover:border-port-accent">
+ <Plus size={12} aria-hidden="true" /> Pick from gallery
+ </button>
+ </div>
</div>
<div
diff --git a/client/src/pages/CatalogIngredient.test.jsx b/client/src/pages/CatalogIngredient.test.jsx
index c2434dfd7f..1f2dbee02f 100644
--- a/client/src/pages/CatalogIngredient.test.jsx
+++ b/client/src/pages/CatalogIngredient.test.jsx
@@ -72,6 +72,17 @@ vi.mock('../services/apiCatalog', () => ({
detachCatalogIngredientMedia: vi.fn(),
}));
+vi.mock('../services/apiSystem', () => ({ generateImage: vi.fn() }));
+// Stand-in for the live image-gen thumb: fire onFilename as soon as a jobId is
+// handed in, simulating a completed render without the socket/job machinery.
+vi.mock('../components/pipeline/MediaJobThumb', async () => {
+ const { useEffect } = await import('react');
+ function MockMediaJobThumb({ jobId, onFilename }) {
+ useEffect(() => { if (jobId && onFilename) onFilename(`${jobId}.png`); }, [jobId, onFilename]);
+ return null;
+ }
+ return { default: MockMediaJobThumb };
+});
vi.mock('../services/apiImageVideo', () => ({ listImageGallery: vi.fn(async () => []) }));
vi.mock('../components/IngredientPicker', () => ({ default: () => null }));
vi.mock('../components/MediaImage', () => ({ default: ({ src, alt }) => <img src={src} alt={alt} /> }));
@@ -166,6 +177,38 @@ describe('CatalogIngredient — character sheet', () => {
expect(screen.getByText(/Re-render in Universe Builder/i)).toBeTruthy();
});
+ it('generates an image from the description and sets it as the portrait', async () => {
+ const { generateImage } = await import('../services/apiSystem');
+ const { setCatalogIngredientPortrait } = await import('../services/apiCatalog');
+ generateImage.mockResolvedValue({ jobId: 'job-1' });
+ setCatalogIngredientPortrait.mockResolvedValue({});
+ renderPage();
+ await waitFor(() => expect(screen.getByDisplayValue('Sharp eyes, ink-stained cuffs.')).toBeTruthy());
+
+ fireEvent.click(screen.getByRole('button', { name: /^Generate$/i }));
+
+ await waitFor(() => expect(generateImage).toHaveBeenCalled());
+ // Prompt is composed from the name + the type's primary description field.
+ const [genPayload] = generateImage.mock.calls[0];
+ expect(genPayload.prompt).toMatch(/Ada Lovelace/);
+ expect(genPayload.prompt).toMatch(/Sharp eyes/);
+ // The MediaJobThumb stub fires onFilename → with no existing portrait the
+ // render is attached as THE portrait.
+ await waitFor(() => expect(setCatalogIngredientPortrait).toHaveBeenCalledWith(
+ 'cat-chr-1', { mediaKey: 'job-1.png' }, { silent: true },
+ ));
+ });
+
+ it('disables Generate when the ingredient has no description text', async () => {
+ getCatalogIngredientDetails.mockImplementation(async () => detailsOf({
+ ...CHAR_FIXTURE,
+ payload: { role: 'Mentor' }, // no physicalDescription/description/summary
+ }));
+ renderPage();
+ await waitFor(() => expect(screen.getByRole('button', { name: /^Generate$/i })).toBeTruthy());
+ expect(screen.getByRole('button', { name: /^Generate$/i })).toHaveProperty('disabled', true);
+ });
+
it('collapses a sheet section when its header is clicked', async () => {
renderPage();
await waitFor(() => expect(screen.getByDisplayValue('she/her')).toBeTruthy());
diff --git a/server/services/catalogDB.js b/server/services/catalogDB.js
index 05b7dbef22..14bfd22d29 100644
--- a/server/services/catalogDB.js
+++ b/server/services/catalogDB.js
@@ -686,6 +686,20 @@ export async function reviveDeletedIngredient(id, { type, name, payload = {}, ta
// directly instead of fetching-then-JS-filtering.
const INGREDIENT_LIGHT_COLS = 'id, type, name, payload, tags, embedding_model, origin_instance_id, created_at, updated_at, deleted, deleted_at, sync_sequence';
+// Correlated subquery that yields the card-thumbnail media key for each row:
+// the live portrait when set, otherwise the most recent live reference image.
+// Non-image media kinds (audio/video/document) are excluded so a card never
+// points an <img> at an unrenderable key. Used only by listIngredients' light
+// path (see the note there).
+const THUMBNAIL_KEY_SUBQUERY = `(
+ SELECT m.media_key FROM catalog_ingredient_media m
+ WHERE m.ingredient_id = catalog_ingredients.id
+ AND m.deleted = false
+ AND m.kind IN ('portrait', 'reference')
+ ORDER BY (m.kind = 'portrait') DESC, m.created_at DESC
+ LIMIT 1
+ ) AS thumbnail_key`;
+
export async function listIngredients({ type, tag, query: q, limit = 50, offset = 0, includeEmbedding = false, embeddingMissing = false, staleEmbeddingModel = null } = {}) {
const conditions = ['deleted = false'];
const params = [];
@@ -721,12 +735,23 @@ export async function listIngredients({ type, tag, query: q, limit = 50, offset
? `ORDER BY ts_rank_cd(search_tsv, websearch_to_tsquery('english', $${qIdx})) DESC, created_at DESC`
: `ORDER BY created_at DESC`;
params.push(limit, offset);
- const cols = includeEmbedding ? '*' : INGREDIENT_LIGHT_COLS;
+ // Card-thumbnail key: the live portrait if one exists, else the most recent
+ // reference image. Mirrors listMediaForIngredient's `(kind='portrait') DESC,
+ // created_at DESC` ordering so the card shows the same image the detail page
+ // treats as the avatar. Scoped to the light-column list path only — the
+ // includeEmbedding admin paths (re-embed/backfill) don't render cards and
+ // don't pay for the correlated subquery. The field rides ALONGSIDE
+ // rowToIngredient's shape (attached below), so the sync/revision payloads
+ // that share rowToIngredient stay untouched.
+ const cols = includeEmbedding ? '*' : `${INGREDIENT_LIGHT_COLS}, ${THUMBNAIL_KEY_SUBQUERY}`;
const result = await query(
`SELECT ${cols} FROM catalog_ingredients ${where} ${orderBy} LIMIT $${idx++} OFFSET $${idx}`,
params,
);
- return { items: result.rows.map(rowToIngredient), nextOffset: offset + result.rows.length };
+ return {
+ items: result.rows.map((row) => ({ ...rowToIngredient(row), thumbnailKey: row.thumbnail_key ?? null })),
+ nextOffset: offset + result.rows.length,
+ };
}
diff --git a/server/services/catalogDBMedia.test.js b/server/services/catalogDBMedia.test.js
index 1b10a0ea85..e8f68e1bed 100644
--- a/server/services/catalogDBMedia.test.js
+++ b/server/services/catalogDBMedia.test.js
@@ -141,6 +141,39 @@ describe('upsertMediaFromPeer', () => {
});
});
+describe('listIngredients card thumbnail', () => {
+ const ingredientRow = (overrides = {}) => ({
+ id: 'cat-chr-1', type: 'character', name: 'Echo', payload: {}, tags: [],
+ embedding_model: null, origin_instance_id: null,
+ created_at: new Date('2026-01-01T00:00:00Z'), updated_at: new Date('2026-01-01T00:00:00Z'),
+ deleted: false, deleted_at: null, sync_sequence: 1,
+ ...overrides,
+ });
+
+ it('selects the portrait-or-latest-reference media key as thumbnail_key', async () => {
+ const db = await import('../lib/db.js');
+ db.query.mockResolvedValueOnce({ rows: [ingredientRow({ thumbnail_key: 'hero.png' })] });
+ const { items } = await catalogDB.listIngredients({ limit: 10 });
+ // mockResolvedValueOnce bypasses the factory's `calls` push, so read the
+ // captured SQL from the mock's own call log (as the getMaxSequences test does).
+ const sql = db.query.mock.calls.at(-1)[0].replace(/\s+/g, ' ');
+ // The correlated subquery prefers a live portrait, then the most recent
+ // live reference, and excludes unrenderable (audio/video/document) kinds.
+ expect(sql).toMatch(/FROM catalog_ingredient_media m/i);
+ expect(sql).toMatch(/m\.kind IN \('portrait', 'reference'\)/i);
+ expect(sql).toMatch(/ORDER BY \(m\.kind = 'portrait'\) DESC, m\.created_at DESC/i);
+ expect(sql).toMatch(/AS thumbnail_key/i);
+ expect(items[0].thumbnailKey).toBe('hero.png');
+ });
+
+ it('maps a null thumbnail_key (no image attached) to null', async () => {
+ const db = await import('../lib/db.js');
+ db.query.mockResolvedValueOnce({ rows: [ingredientRow({ thumbnail_key: null })] });
+ const { items } = await catalogDB.listIngredients({ limit: 10 });
+ expect(items[0].thumbnailKey).toBeNull();
+ });
+});
+
describe('getMaxSequences includes the media cursor', () => {
it('selects MAX(sync_sequence) from catalog_ingredient_media AS media', async () => {
const db = await import('../lib/db.js');