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-1359]): durably attach queued catalog renders via a media-job completion hook

[._.]/ Adam Eivy2f51294c6b76
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsx
index 8b6824671b..c62cb0fd1d 100644
--- a/client/src/pages/CatalogIngredient.jsx
+++ b/client/src/pages/CatalogIngredient.jsx
@@ -463,6 +463,7 @@ export default function CatalogIngredient() {
onAttach={handleAttachMedia}
onSetPortrait={handleSetPortrait}
onDetach={handleDetachMedia}
+ genIngredientId={record.id}
genName={name}
genDescription={genDescription}
onGenerated={handleGeneratedImage}
@@ -851,7 +852,7 @@ function RelationsPanel({ record, relations, onAdd, onRemove }) {
// `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 }) {
+function GenerateImageControl({ ingredientId, name, description, onComplete }) {
const mountedRef = useMounted();
const [jobId, setJobId] = useState(null);
const [starting, setStarting] = useState(false);
@@ -865,7 +866,16 @@ function GenerateImageControl({ name, description, onComplete }) {
setStarting(true);
const styled = composeCanonStyledPrompt({ name: name || 'Subject', description, universe: null });
const queued = await generateImage(
- { prompt: styled.prompt, negativePrompt: styled.negativePrompt || undefined },
+ {
+ prompt: styled.prompt,
+ negativePrompt: styled.negativePrompt || undefined,
+ // Durable attach (#1359): tag the queued job with the target ingredient
+ // so the server-side completion hook files the render even if this page
+ // unmounts before a long local/Codex render finishes. The onComplete
+ // callback below stays as the optimistic/immediate-refresh path; the
+ // hook is idempotent so the two never double-attach.
+ ...(ingredientId ? { catalogIngredientId: ingredientId } : {}),
+ },
{ silent: true },
).catch((err) => { toast.error(err?.message || 'Image generation failed'); return null; });
if (!mountedRef.current) return;
@@ -873,11 +883,9 @@ function GenerateImageControl({ name, description, onComplete }) {
if (!queued) return;
if (queued.jobId) {
// Local/Codex modes enqueue a job — track it live via MediaJobThumb,
- // which fires onFilename on completion to attach the result. NOTE: this
- // attach is mounted-callback-bound — navigating away before a long render
- // finishes leaves the image in the gallery unattached (same limitation as
- // UniverseCanonSection's section-local renders). A durable job→ingredient
- // attach is tracked in #1359.
+ // which fires onFilename on completion to attach the result optimistically.
+ // If this page unmounts before the render finishes the server-side
+ // catalogImageAttachHook still attaches it durably (#1359).
setJobId(queued.jobId);
toast.success('Generating image…');
} else if (queued.filename) {
@@ -932,7 +940,7 @@ function GenerateImageControl({ name, description, onComplete }) {
);
}
-function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, genName, genDescription, onGenerated }) {
+function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, genIngredientId, genName, genDescription, onGenerated }) {
const [pickerOpen, setPickerOpen] = useState(false);
const [dragOver, setDragOver] = useState(false);
const list = Array.isArray(media) ? media : [];
@@ -955,7 +963,7 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, ge
<ImageIcon size={14} aria-hidden="true" /> Media
</h2>
<div className="flex items-center gap-2">
- <GenerateImageControl name={genName} description={genDescription} onComplete={onGenerated} />
+ <GenerateImageControl ingredientId={genIngredientId} 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
diff --git a/server/index.js b/server/index.js
index 025bc1bb6e..eece83be2e 100644
--- a/server/index.js
+++ b/server/index.js
@@ -108,6 +108,7 @@ import universeBuilderRoutes from './routes/universeBuilder.js';
import authorsRoutes from './routes/authors.js';
import conflictJournalRoutes from './routes/conflictJournal.js';
import { initUniverseBuilderCollectionHook } from './services/universeBuilderCollectionHook.js';
+import { initCatalogImageAttachHook } from './services/catalogImageAttachHook.js';
import { initComicPagesFilenameHook } from './services/pipeline/comicPagesFilenameHook.js';
import { initStoryboardsFilenameHook } from './services/pipeline/storyboardsFilenameHook.js';
import { initSeasonCoverFilenameHook } from './services/pipeline/seasonCoverFilenameHook.js';
@@ -757,6 +758,10 @@ ensureSelf()
// Universe Builder needs the media job queue running before it can listen
// for `completed` events — so initialize the hook here.
initUniverseBuilderCollectionHook();
+ // Catalog image-attach hook — durably files a queued render onto its target
+ // ingredient on completion, even if the editor page unmounted mid-render
+ // (#1359). Also depends on the media job queue being loaded.
+ initCatalogImageAttachHook();
// Pipeline filename hooks — stamp `filename` onto stage records on
// media-job completion so the UI can still render them after the
// 24h media-job archive TTL elapses.
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index e3d5f3b986..3fa84302c9 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -115,6 +115,16 @@ const generateSchema = z.object({
label: z.string().max(200).optional(),
category: z.string().max(64).optional(),
}).optional(),
+ // Durable catalog attach (#1359). When present, the mediaJobQueue completion
+ // hook (catalogImageAttachHook) files the finished render onto this catalog
+ // ingredient even if the page that started the render has since unmounted —
+ // so a long queued local/Codex render is no longer lost to navigation.
+ // `catalogMediaKind` forces portrait/reference; omitted = auto (first image →
+ // portrait, later → reference, mirroring the client's optimistic path). Only
+ // the async (local/codex) lanes need this — the synchronous external SD-API
+ // path returns the filename to the client, which attaches it directly.
+ catalogIngredientId: z.string().min(1).max(200).optional(),
+ catalogMediaKind: z.enum(['portrait', 'reference']).optional(),
}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });
// JSON callers (SDAPI bridge, avatar route, the Imagine page's old payload
@@ -284,6 +294,19 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
: undefined;
}
+ // Collapse the catalog-attach params into a single job tag the completion
+ // hook understands (#1359). Folded into `params` so it rides into both the
+ // local and codex `enqueueJob` branches below via `...params`; the raw fields
+ // are dropped so persisted job.params carries only the canonical tag.
+ if (params.catalogIngredientId) {
+ params.catalogAttach = {
+ ingredientId: params.catalogIngredientId,
+ ...(params.catalogMediaKind ? { kind: params.catalogMediaKind } : {}),
+ };
+ }
+ delete params.catalogIngredientId;
+ delete params.catalogMediaKind;
+
// Multer's tmp upload is no longer needed once we've copied it into
// PATHS.images. Use res.on('close') so the temp files are cleaned up whether
// generateImage resolves, throws (handled by errorHandler middleware), or
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 1abc4ce536..c945ef018a 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -368,6 +368,62 @@ describe('Image Gen Routes', () => {
});
});
+ // Durable catalog attach (#1359): the Catalog ingredient editor's Generate
+ // button passes `catalogIngredientId` so the queued job carries a
+ // `catalogAttach` tag the completion hook reads to file the render even if
+ // the page unmounts. The route collapses the raw fields into the tag and
+ // drops them from params.
+ describe('catalogAttach tag', () => {
+ it('folds catalogIngredientId into a catalogAttach job tag and drops the raw field', async () => {
+ getSettings.mockResolvedValueOnce({ imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } });
+ mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'queued-cat', position: 1, status: 'queued' });
+
+ const response = await request(app)
+ .post('/api/image-gen/generate')
+ .send({ prompt: 'a catalog hero', catalogIngredientId: 'ing-42' });
+
+ expect(response.status).toBe(200);
+ const [call] = mediaJobQueue.enqueueJob.mock.calls;
+ expect(call[0].params.catalogAttach).toEqual({ ingredientId: 'ing-42' });
+ // Raw fields are stripped — only the canonical tag persists in job.params.
+ expect(call[0].params.catalogIngredientId).toBeUndefined();
+ expect(call[0].params.catalogMediaKind).toBeUndefined();
+ });
+
+ it('preserves an explicit catalogMediaKind in the tag', async () => {
+ getSettings.mockResolvedValueOnce({ imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } });
+ mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'queued-cat-kind', position: 1, status: 'queued' });
+
+ const response = await request(app)
+ .post('/api/image-gen/generate')
+ .send({ prompt: 'a reference shot', catalogIngredientId: 'ing-7', catalogMediaKind: 'reference' });
+
+ expect(response.status).toBe(200);
+ const [call] = mediaJobQueue.enqueueJob.mock.calls;
+ expect(call[0].params.catalogAttach).toEqual({ ingredientId: 'ing-7', kind: 'reference' });
+ });
+
+ it('rejects an invalid catalogMediaKind', async () => {
+ const response = await request(app)
+ .post('/api/image-gen/generate')
+ .send({ prompt: 'x', catalogIngredientId: 'ing-9', catalogMediaKind: 'thumbnail' });
+ expect(response.status).toBe(400);
+ });
+
+ it('omits catalogAttach when no catalogIngredientId is sent', async () => {
+ getSettings.mockResolvedValueOnce({ imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } });
+ mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'queued-nocat', position: 1, status: 'queued' });
+
+ const response = await request(app)
+ .post('/api/image-gen/generate')
+ .send({ prompt: 'untagged render' });
+
+ expect(response.status).toBe(200);
+ const [call] = mediaJobQueue.enqueueJob.mock.calls;
+ expect(call[0].params.catalogAttach).toBeUndefined();
+ });
+ });
+
// Local mode without a configured pythonPath now rejects up-front (400)
// rather than enqueueing a job that can never run. The queue is meant to
// serialize concurrent renders, not to absorb hard configuration errors.
diff --git a/server/services/catalogImageAttachHook.js b/server/services/catalogImageAttachHook.js
new file mode 100644
index 0000000000..d4a0bf6622
--- /dev/null
+++ b/server/services/catalogImageAttachHook.js
@@ -0,0 +1,96 @@
+/**
+ * Catalog image-attach hook (issue #1359).
+ *
+ * Subscribes to mediaJobEvents and, for each completed image job that carries
+ * `params.catalogAttach.ingredientId`, attaches the rendered filename onto that
+ * catalog ingredient — server-side, independent of any mounted client. This is
+ * the durable counterpart to CatalogIngredient.jsx's mounted `onFilename`
+ * callback: a long-running local/Codex render that completes after the user has
+ * navigated away, refreshed, or switched ingredients still lands a portrait or
+ * reference row (previously the image reached the media library but no row was
+ * ever created, so the attachment was silently lost).
+ *
+ * Decision mirrors the client's optimistic path (`handleGeneratedImage`): the
+ * first image becomes the portrait, later ones attach as references — unless an
+ * explicit `kind` was requested. Idempotent against the client path: when the
+ * filename is already attached (the still-mounted client won the race), the hook
+ * is a no-op, so the same render never lands as both portrait AND reference.
+ *
+ * Mounted once at server boot from server/index.js (after the media job queue is
+ * running). Best-effort: a bookkeeping miss is logged but never thrown — it must
+ * not crash the server or fail the user's render.
+ */
+
+import { mediaJobEvents } from './mediaJobQueue/index.js';
+import { attachMedia, setPortraitMedia, listMediaForIngredient } from './catalogDB.js';
+
+// Resolve the render onto the ingredient. Returns the kind attached
+// ('portrait' | 'reference'), 'duplicate' when the client already filed it, or
+// throws on a real DB error (caught by the caller).
+async function attachGeneratedImage({ ingredientId, kind, filename }) {
+ const existing = await listMediaForIngredient(ingredientId);
+ // Idempotent against the optimistic client path: it already attached this
+ // exact render (under any kind) — don't double-file it as a second kind.
+ if (existing.some((m) => m.mediaKey === filename)) return 'duplicate';
+ const hasPortrait = existing.some((m) => m.kind === 'portrait');
+ // Explicit kind wins; otherwise auto: first image → portrait, later → reference
+ // (mirrors CatalogIngredient.jsx `handleGeneratedImage`).
+ const target = kind === 'portrait' || kind === 'reference'
+ ? kind
+ : (hasPortrait ? 'reference' : 'portrait');
+ if (target === 'portrait') {
+ await setPortraitMedia(ingredientId, filename);
+ } else {
+ await attachMedia(ingredientId, filename, 'reference');
+ }
+ return target;
+}
+
+let completedHandler = null;
+
+export function initCatalogImageAttachHook() {
+ // Idempotent: a stray double-init (test reload, future refactor) would
+ // otherwise register two listeners and double-file every completed image.
+ if (completedHandler) return;
+
+ // EventEmitter does not await async listeners and does not catch their
+ // rejections — a throw here would surface as a process-killing unhandled
+ // rejection on Node ≥15. Use a sync listener that launches an async IIFE with
+ // a top-level catch so this bookkeeping miss can never crash the server.
+ completedHandler = (job) => {
+ void (async () => {
+ if (!job || job.kind !== 'image') return;
+ const tag = job.params?.catalogAttach;
+ const ingredientId = tag?.ingredientId;
+ if (!ingredientId || typeof ingredientId !== 'string') return;
+ const filename = job.result?.filename;
+ if (!filename || typeof filename !== 'string') return;
+
+ const status = await attachGeneratedImage({ ingredientId, kind: tag.kind, filename })
+ .catch((err) => {
+ console.log(`⚠️ catalog image-attach hook failed for ${filename} → ${ingredientId}: ${err?.message || String(err)}`);
+ return 'failed';
+ });
+ if (status === 'portrait' || status === 'reference') {
+ console.log(`🏷️ catalog ingredient ${ingredientId.slice(0, 8)} ← ${status} ${filename}`);
+ }
+ })().catch((err) => {
+ // Last-resort net for synchronous throws (unexpected job shape, etc).
+ console.log(`⚠️ catalog image-attach hook crashed: ${err?.message || err}`);
+ });
+ };
+
+ mediaJobEvents.on('completed', completedHandler);
+ console.log('🏷️ Catalog image-attach hook initialized');
+}
+
+// Test-only reset so suites that re-init can do so cleanly. Removes the
+// previously registered listener so re-init doesn't leak handlers.
+export const __testing = {
+ reset: () => {
+ if (completedHandler) {
+ mediaJobEvents.off('completed', completedHandler);
+ completedHandler = null;
+ }
+ },
+};
diff --git a/server/services/catalogImageAttachHook.test.js b/server/services/catalogImageAttachHook.test.js
new file mode 100644
index 0000000000..b9d9928f39
--- /dev/null
+++ b/server/services/catalogImageAttachHook.test.js
@@ -0,0 +1,106 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+// Mock the DB layer so the hook's attach/decision logic is exercised without a
+// live Postgres. `listMediaForIngredient` is reprogrammed per-test to stand in
+// for the ingredient's current media rows.
+const attachMedia = vi.fn(async () => ({}));
+const setPortraitMedia = vi.fn(async () => ({}));
+const listMediaForIngredient = vi.fn(async () => []);
+vi.mock('./catalogDB.js', () => ({ attachMedia, setPortraitMedia, listMediaForIngredient }));
+
+const { mediaJobEvents } = await import('./mediaJobQueue/index.js');
+const hook = await import('./catalogImageAttachHook.js');
+
+async function waitFor(predicate, { timeoutMs = 1000, intervalMs = 5 } = {}) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (predicate()) return;
+ await new Promise((r) => setTimeout(r, intervalMs));
+ }
+ throw new Error('waitFor: predicate never became true');
+}
+
+const completedImageJob = (params, filename = 'job-abc.png') => ({
+ kind: 'image',
+ params,
+ result: { filename },
+});
+
+describe('catalogImageAttachHook', () => {
+ beforeEach(() => {
+ hook.__testing.reset();
+ hook.initCatalogImageAttachHook();
+ attachMedia.mockClear();
+ setPortraitMedia.mockClear();
+ listMediaForIngredient.mockReset();
+ listMediaForIngredient.mockResolvedValue([]);
+ });
+
+ afterEach(() => {
+ hook.__testing.reset();
+ });
+
+ it('sets the first render as the portrait when the ingredient has no media', async () => {
+ mediaJobEvents.emit('completed', completedImageJob({ catalogAttach: { ingredientId: 'ing-1' } }, 'first.png'));
+ await waitFor(() => setPortraitMedia.mock.calls.length > 0);
+ expect(setPortraitMedia).toHaveBeenCalledWith('ing-1', 'first.png');
+ expect(attachMedia).not.toHaveBeenCalled();
+ });
+
+ it('attaches as a reference when the ingredient already has a portrait', async () => {
+ listMediaForIngredient.mockResolvedValue([{ mediaKey: 'old.png', kind: 'portrait' }]);
+ mediaJobEvents.emit('completed', completedImageJob({ catalogAttach: { ingredientId: 'ing-2' } }, 'second.png'));
+ await waitFor(() => attachMedia.mock.calls.length > 0);
+ expect(attachMedia).toHaveBeenCalledWith('ing-2', 'second.png', 'reference');
+ expect(setPortraitMedia).not.toHaveBeenCalled();
+ });
+
+ it('honors an explicit reference kind even with no existing portrait', async () => {
+ mediaJobEvents.emit('completed', completedImageJob({ catalogAttach: { ingredientId: 'ing-3', kind: 'reference' } }, 'ref.png'));
+ await waitFor(() => attachMedia.mock.calls.length > 0);
+ expect(attachMedia).toHaveBeenCalledWith('ing-3', 'ref.png', 'reference');
+ expect(setPortraitMedia).not.toHaveBeenCalled();
+ });
+
+ it('honors an explicit portrait kind even when a portrait already exists', async () => {
+ listMediaForIngredient.mockResolvedValue([{ mediaKey: 'old.png', kind: 'portrait' }]);
+ mediaJobEvents.emit('completed', completedImageJob({ catalogAttach: { ingredientId: 'ing-4', kind: 'portrait' } }, 'new.png'));
+ await waitFor(() => setPortraitMedia.mock.calls.length > 0);
+ expect(setPortraitMedia).toHaveBeenCalledWith('ing-4', 'new.png');
+ expect(attachMedia).not.toHaveBeenCalled();
+ });
+
+ it('is idempotent — skips when the filename is already attached (client won the race)', async () => {
+ listMediaForIngredient.mockResolvedValue([{ mediaKey: 'dup.png', kind: 'portrait' }]);
+ mediaJobEvents.emit('completed', completedImageJob({ catalogAttach: { ingredientId: 'ing-5' } }, 'dup.png'));
+ // Give the async handler a chance to run, then assert no second write.
+ await new Promise((r) => setTimeout(r, 30));
+ expect(setPortraitMedia).not.toHaveBeenCalled();
+ expect(attachMedia).not.toHaveBeenCalled();
+ });
+
+ it('ignores jobs without a catalogAttach tag', async () => {
+ mediaJobEvents.emit('completed', completedImageJob({ universeRun: { collectionId: 'c1' } }, 'x.png'));
+ mediaJobEvents.emit('completed', completedImageJob({}, 'y.png'));
+ await new Promise((r) => setTimeout(r, 30));
+ expect(listMediaForIngredient).not.toHaveBeenCalled();
+ expect(attachMedia).not.toHaveBeenCalled();
+ expect(setPortraitMedia).not.toHaveBeenCalled();
+ });
+
+ it('ignores non-image jobs and jobs with no result filename', async () => {
+ mediaJobEvents.emit('completed', { kind: 'video', params: { catalogAttach: { ingredientId: 'ing-6' } }, result: { filename: 'v.mp4' } });
+ mediaJobEvents.emit('completed', { kind: 'image', params: { catalogAttach: { ingredientId: 'ing-6' } }, result: {} });
+ await new Promise((r) => setTimeout(r, 30));
+ expect(listMediaForIngredient).not.toHaveBeenCalled();
+ });
+
+ it('swallows a DB error without rejecting (best-effort)', async () => {
+ listMediaForIngredient.mockRejectedValueOnce(new Error('db down'));
+ // Must not throw / leave an unhandled rejection.
+ mediaJobEvents.emit('completed', completedImageJob({ catalogAttach: { ingredientId: 'ing-7' } }, 'z.png'));
+ await new Promise((r) => setTimeout(r, 30));
+ expect(setPortraitMedia).not.toHaveBeenCalled();
+ expect(attachMedia).not.toHaveBeenCalled();
+ });
+});