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

address review (codex): serialize catalog image-attach per ingredient

[._.]/ Adam Eivye8950a620b33
diff --git a/server/services/catalogImageAttachHook.js b/server/services/catalogImageAttachHook.js
index 98f94eeaf1..6e4171563c 100644
--- a/server/services/catalogImageAttachHook.js
+++ b/server/services/catalogImageAttachHook.js
@@ -53,6 +53,31 @@ async function attachGeneratedImage({ ingredientId, kind, filename }) {
return target;
}
+// Serialize the read→decide→write per ingredient. Two renders for the SAME
+// ingredient completing close together (e.g. two parallel Codex jobs, or a
+// regenerate after navigating back) would otherwise both read an empty media
+// list, both pick 'portrait', and have the second `setPortraitMedia` demote the
+// first — losing the earlier render entirely. Chaining each attach onto the
+// prior one for that ingredient makes the later job observe the first's write,
+// so it correctly falls through to 'reference'. Keyed by ingredientId, so
+// different ingredients still attach concurrently (their Postgres rows don't
+// conflict). In-memory tail, evicted once settled; lost on restart, which is
+// fine — the whole hook is best-effort.
+const attachTails = new Map();
+
+function serializePerIngredient(ingredientId, work) {
+ const prev = attachTails.get(ingredientId) || Promise.resolve();
+ // `work` on both fulfil AND reject so a prior failure doesn't stall the chain.
+ const next = prev.then(work, work);
+ attachTails.set(ingredientId, next);
+ // Evict once settled, but only if nothing newer has chained on. Swallow here
+ // (the eviction branch never rethrows) so it can't surface as an unhandled
+ // rejection — the caller attaches its own `.catch` to the returned promise.
+ const evict = () => { if (attachTails.get(ingredientId) === next) attachTails.delete(ingredientId); };
+ next.then(evict, evict);
+ return next;
+}
+
let completedHandler = null;
export function initCatalogImageAttachHook() {
@@ -73,11 +98,12 @@ export function initCatalogImageAttachHook() {
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';
- });
+ const status = await serializePerIngredient(ingredientId, () =>
+ 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}`);
}
@@ -99,5 +125,6 @@ export const __testing = {
mediaJobEvents.off('completed', completedHandler);
completedHandler = null;
}
+ attachTails.clear();
},
};
diff --git a/server/services/catalogImageAttachHook.test.js b/server/services/catalogImageAttachHook.test.js
index ce1fe18186..51fc2dbc30 100644
--- a/server/services/catalogImageAttachHook.test.js
+++ b/server/services/catalogImageAttachHook.test.js
@@ -32,8 +32,12 @@ describe('catalogImageAttachHook', () => {
beforeEach(() => {
hook.__testing.reset();
hook.initCatalogImageAttachHook();
- attachMedia.mockClear();
- setPortraitMedia.mockClear();
+ // mockReset (not mockClear) so a per-test mockImplementation — e.g. the
+ // stateful store in the serialization test — can't leak into later tests.
+ attachMedia.mockReset();
+ attachMedia.mockResolvedValue({});
+ setPortraitMedia.mockReset();
+ setPortraitMedia.mockResolvedValue({});
listMediaForIngredient.mockReset();
listMediaForIngredient.mockResolvedValue([]);
getIngredient.mockReset();
@@ -97,6 +101,41 @@ describe('catalogImageAttachHook', () => {
expect(attachMedia).not.toHaveBeenCalled();
});
+ it('serializes two same-ingredient completions — first becomes portrait, second a reference (no demote/loss)', async () => {
+ // Stateful media store so the SECOND attach observes the FIRST's write.
+ // Without per-ingredient serialization both would read [] and both pick
+ // 'portrait', and the second setPortraitMedia would demote the first.
+ const rows = [];
+ listMediaForIngredient.mockImplementation(async () => rows.map((r) => ({ ...r })));
+ setPortraitMedia.mockImplementation(async (id, key) => {
+ // Demote any other live portrait (mirrors the real helper), then attach.
+ for (let i = rows.length - 1; i >= 0; i--) {
+ if (rows[i].kind === 'portrait' && rows[i].mediaKey !== key) rows.splice(i, 1);
+ }
+ rows.push({ mediaKey: key, kind: 'portrait' });
+ return {};
+ });
+ attachMedia.mockImplementation(async (id, key, kind) => {
+ rows.push({ mediaKey: key, kind });
+ return {};
+ });
+
+ // Two catalog-tagged jobs for the SAME ingredient complete back-to-back.
+ mediaJobEvents.emit('completed', completedImageJob({ catalogAttach: { ingredientId: 'ing-race' } }, 'a.png'));
+ mediaJobEvents.emit('completed', completedImageJob({ catalogAttach: { ingredientId: 'ing-race' } }, 'b.png'));
+ await waitFor(() => rows.length === 2);
+
+ expect(setPortraitMedia).toHaveBeenCalledTimes(1);
+ expect(setPortraitMedia).toHaveBeenCalledWith('ing-race', 'a.png');
+ expect(attachMedia).toHaveBeenCalledTimes(1);
+ expect(attachMedia).toHaveBeenCalledWith('ing-race', 'b.png', 'reference');
+ // First render survives as the portrait; second is a reference — nothing lost.
+ expect(rows).toEqual([
+ { mediaKey: 'a.png', kind: 'portrait' },
+ { mediaKey: 'b.png', kind: 'reference' },
+ ]);
+ });
+
it('skips attaching when the target ingredient was deleted before the render completed', async () => {
getIngredient.mockResolvedValue(null); // soft- or hard-deleted: getIngredient filters deleted=false
mediaJobEvents.emit('completed', completedImageJob({ catalogAttach: { ingredientId: 'ing-gone' } }, 'orphan.png'));