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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: extract shared buildUniverseRunTag helper for universe-collection job tagging (#1392)
Adam Eivyde1b76c73e7b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 005d48e137..24f25bcd97 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -172,3 +172,5 @@- **[issue-1362] The pipeline Nouns stage and the Story Builder characters step now auto-file their reference renders server-side instead of round-tripping a follow-up PATCH.** Both surfaces used the generate-then-attach anti-pattern that #1395 already removed from the Universe canon section: they POSTed an *untagged* render, then on completion made a second full-array `updateUniverse` PATCH purely to append the new filename onto the entry's `imageRefs[]` (Story Builder even refetched the universe first to avoid clobbering a sibling's `imageRefs[]` — work the server-side append does atomically). The render carried no `universeRun` tag, so the existing `appendEntryImageRef` completion hook never fired and a render that finished *after* the page unmounted lost its attachment. Both call sites now thread a durable `universeRun.entryRef` tag through the generate call (canon → `kindKey` + id, the same shape the batch path uses), so `universeBuilderCollectionHook` files the finished render into the universe collection AND appends it to the entry's `imageRefs[]` independent of any mounted client. The client keeps only an optimistic, dedup-guarded + last-N-capped local stamp for an instant thumbnail (no PATCH; no refetch-before-PATCH race). The tag builder shared by all three call sites is extracted to `client/src/lib/universeRunTag.js` (`buildUniverseSectionRenderTag`), replacing UniverseCanonSection's inline copy. (`client/src/lib/universeRunTag.js`, `client/src/components/pipeline/stages/NounsStage.jsx`, `client/src/pages/StoryBuilder.jsx`, `client/src/components/universe/UniverseCanonSection.jsx`, #1362)- **[issue-1363] Writers-Room storyboard scene renders now attach durably server-side instead of via a generate-then-attach round-trip.** Both render entry points — the per-scene `SceneCard` "Image" button and the cursor-driven `LiveRenderPanel` "Render scene" — fired an *untagged* image render, then on the `image-gen:completed` socket event made a **second** call (`attachWritersRoomSceneImage`) to file the rendered filename onto the analysis snapshot's `sceneImages[sceneId]`. That second call lost the image whenever the render finished *after* the editor unmounted / the user navigated away. The render now threads a durable `writersRoom: { workId, analysisId, sceneId }` job tag, and a new completion hook (`writersRoomSceneImageHook`) files the finished render onto the snapshot AND mirrors it into the work's auto-collection independent of any mounted client — converging this surface onto the same durable hook path the universe (#1395/#1362) and catalog (#1359) renders use. The hook serializes attaches per analysis file so two scenes completing back-to-back can't clobber each other's `sceneImages` entry, and emits a `writers-room:scene-image` socket event so the storyboard boards still update reactively without a refetch. The shared attach+mirror logic the route and hook both run is extracted to `persistSceneImage` (evaluator). Only the async local/Codex lanes ride the media-job queue the hook listens to; the synchronous external SD-API lane (which returns its filename inline) still attaches via the `scene-image` route, so it keeps working. (`server/routes/imageGen.js`, `server/services/writersRoomSceneImageHook.js`, `server/services/writersRoomEvents.js`, `server/services/writersRoom/evaluator.js`, `server/routes/writersRoom.js`, `server/services/socket.js`, `server/index.js`, `client/src/lib/wrImageDefaults.js`, `client/src/components/writers-room/{SceneCard,LiveRenderPanel}.jsx`, #1363)++- **[issue-1392] The three server call sites that resolve a universe media collection and build a `universeRun` job tag now share one `buildUniverseRunTag` helper.** The base-style probe (`imageGen.js`), character reference sheets (`universeCharacterSheet.js`), and batch renders (`universeBuilderRender.js`) each independently called `findOrCreateUniverseCollection` and assembled the same `{ runId, universeId, collectionId, label, category, entryRef? }` tag shape. Extracted to `server/services/universeRunTag.js` (`buildUniverseRunTag`), which provisions the collection best-effort (logs a caller-supplied `errorContext` and drops the collection portion on failure), mints or reuses a `runId`, preserves `entryRef` through a provisioning failure (#1395), and returns `undefined` when there's nothing left to file. The batch path (which mints **one** `runId` outside its per-item loop and reuses it across every compiled item) passes its pre-resolved `collection` + shared `runId` so each per-item tag reuses them without re-provisioning — supported via the helper's optional `collection`/`runId` params. Quality/DRY only — no behavior change. (`server/services/universeRunTag.js`, `server/routes/imageGen.js`, `server/services/universeCharacterSheet.js`, `server/services/universeBuilderRender.js`, #1392)diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex e4694fa30b..03645ebbec 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -43,8 +43,7 @@ import {resolveRegenStrengthDefault,} from '../services/imageGen/regen.js';import { purgeImageRefFromAllUniverses } from '../services/universeCanon.js';-import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';-import { randomUUID } from 'crypto';+import { buildUniverseRunTag } from '../services/universeRunTag.js';const router = Router();@@ -313,27 +312,19 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {// auto-file) rather than failing the user's generation over a side-effect.if (params.universeRun?.universeId) {const { universeId, universeName, label, category, entryRef } = params.universeRun;- const collection = await findOrCreateUniverseCollection({+ // The helper provisions the universe collection (best-effort) and assembles+ // the tag. It preserves `entryRef` even when provisioning fails — the+ // durable `imageRefs[]` append (#1395) must not depend on the gallery+ // collection existing — and returns `undefined` (dropping the tag) only+ // when there's nothing left to do (no collection AND no entryRef).+ params.universeRun = await buildUniverseRunTag({universeId,universeName,- description: `Universe Builder renders for "${universeName}"`,- }).catch((err) => {- console.error(`❌ image-gen → universe collection provision failed: ${err?.message || err}`);- return null;+ label,+ category,+ entryRef,+ errorContext: 'image-gen → universe collection provision failed',});- // Preserve `entryRef` even when collection provisioning fails — the durable- // `imageRefs[]` append (#1395) must not depend on the gallery collection- // existing. Drop the tag entirely only when there's nothing left to do- // (no collection to file into AND no entry to append to).- params.universeRun = (collection || entryRef)- ? {- universeId,- ...(collection ? { runId: randomUUID(), collectionId: collection.id } : {}),- ...(label ? { label } : {}),- ...(category ? { category } : {}),- ...(entryRef ? { entryRef } : {}),- }- : undefined;}// Collapse the catalog-attach params into a single job tag the completiondiff --git a/server/services/universeBuilderRender.js b/server/services/universeBuilderRender.jsindex 5f78d70ee9..9fd2bcafa0 100644--- a/server/services/universeBuilderRender.js+++ b/server/services/universeBuilderRender.js@@ -14,6 +14,7 @@ import * as svc from './universeBuilder.js';import { enqueueJob } from './mediaJobQueue/index.js';import { getSettings } from './settings.js';import { findOrCreateUniverseCollection } from './mediaCollections.js';+import { buildUniverseRunTag } from './universeRunTag.js';import { registerUniverseBuilderRun } from './universeBuilderCollectionHook.js';import { getImageModels, isFlux2 } from '../lib/mediaModels.js';import { usesDiffusersRunner } from '../lib/runners.js';@@ -160,15 +161,17 @@ export async function renderUniverseJobs(universeId, body, mapServiceError) {// through the current sanitizer) lets the hook also append the// rendered filename to the source variation/sheet/canon entry's// `imageRefs[]` so the Universe Builder can show the latest render- // as an avatar next to each item.- universeRun: {- runId,+ // as an avatar next to each item. The pre-resolved `collection` ++ // shared `runId` are passed so each per-item tag reuses them without+ // re-provisioning the collection.+ universeRun: await buildUniverseRunTag({universeId: universe.id,- collectionId: collection.id,+ collection,+ runId,category: item.category,label: item.label,- ...(item.entryRef ? { entryRef: item.entryRef } : {}),- },+ entryRef: item.entryRef,+ }),};let queued;// The queue dispatches directly to imageGen/{codex,local}.generateImage,diff --git a/server/services/universeCharacterSheet.js b/server/services/universeCharacterSheet.jsindex d1b717941d..002cb75dcb 100644--- a/server/services/universeCharacterSheet.js+++ b/server/services/universeCharacterSheet.js@@ -15,7 +15,6 @@import { copyFile, unlink } from 'fs/promises';import { join, basename } from 'path';-import { randomUUID } from 'crypto';import { PATHS, ensureDir, shortId, assertSafeFilename } from '../lib/fileUtils.js';import { ServerError } from '../lib/errorHandler.js';import { getSettings } from './settings.js';@@ -23,7 +22,7 @@ import { getUniverse, updateUniverse } from './universeBuilder.js';import { buildStyleClause, purgeReferenceSheetFromAllUniverses } from './universeCanon.js';import { getImageModels } from '../lib/mediaModels.js';import { enqueueJob, mediaJobEvents } from './mediaJobQueue/index.js';-import { findOrCreateUniverseCollection } from './mediaCollections.js';+import { buildUniverseRunTag } from './universeRunTag.js';import { IMAGE_GEN_MODE } from './imageGen/modes.js';import {flattenStats, flattenPalette, flattenWardrobes, flattenProps, flattenNamedList,@@ -476,22 +475,15 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options// into the same "Universe: <name>" bucket as the rest of the universe's// concept art. Bookkeeping is best-effort — if provisioning fails we still// run the render, just without the collection-filing side-effect.- const collection = await findOrCreateUniverseCollection({+ const universeRun = await buildUniverseRunTag({universeId: universe.id,universeName: universe.name,- description: `Universe Builder renders for "${universe.name}"`,- }).catch((err) => {- console.error(`❌ character sheet → universe collection provision failed: ${err?.message || err}`);- return null;+ label: character.name,+ category: variantConfig.collectionCategory,+ errorContext: 'character sheet → universe collection provision failed',});- if (collection) {- params.universeRun = {- runId: randomUUID(),- universeId: universe.id,- collectionId: collection.id,- category: variantConfig.collectionCategory,- label: character.name,- };+ if (universeRun) {+ params.universeRun = universeRun;}// Enqueue through mediaJobQueue so the render serializes through the rightdiff --git a/server/services/universeRunTag.js b/server/services/universeRunTag.jsnew file mode 100644index 0000000000..683dc2c7d3--- /dev/null+++ b/server/services/universeRunTag.js@@ -0,0 +1,69 @@+import { randomUUID } from 'crypto';+import { findOrCreateUniverseCollection } from './mediaCollections.js';++/**+ * Resolve a universe media collection and assemble the `universeRun` job tag+ * that `universeBuilderCollectionHook` consumes to file a finished render into+ * the universe's "Universe: <name>" bucket (and, when an `entryRef` is present,+ * append it to the source entry's `imageRefs[]`).+ *+ * Provisioning is best-effort: a `findOrCreateUniverseCollection` failure logs+ * `errorContext` and drops the collection portion of the tag (the render still+ * runs, just unfiled). The tag is dropped entirely (returns `undefined`) only+ * when there is nothing left to do — no collection AND no `entryRef`.+ *+ * Callers that batch many renders under one run (universeBuilderRender) provision+ * the collection once and mint a single `runId`, then pass both `collection` and+ * `runId` so each per-item tag reuses them without re-hitting+ * `findOrCreateUniverseCollection`. Single-render callers (base-style probe,+ * character reference sheets) omit both and let the helper provision + mint.+ *+ * @param {object} args+ * @param {string} args.universeId - universe the render belongs to (always tagged).+ * @param {string} [args.universeName] - used to provision/describe the collection+ * when `collection` is not supplied.+ * @param {string} [args.label] - human label for the run/entry (omitted when falsy).+ * @param {string} [args.category] - collection category (omitted when falsy).+ * @param {object} [args.entryRef] - source-entry pointer so the completion hook can+ * append the render to that entry's `imageRefs[]`.+ * @param {string} [args.runId] - caller-supplied run id to reuse across a batch;+ * a fresh one is minted per call when omitted.+ * @param {object|null} [args.collection] - pre-resolved collection (skips provisioning).+ * Pass `undefined` to provision; an explicit `null` means "already resolved, none".+ * @param {string} [args.errorContext] - prefix for the best-effort provisioning error log.+ * @returns {Promise<object|undefined>} the `universeRun` tag, or `undefined` when there+ * is no collection and no `entryRef`.+ */+export async function buildUniverseRunTag({+ universeId,+ universeName,+ label,+ category,+ entryRef,+ runId,+ collection,+ errorContext = 'universe collection provision failed',+}) {+ const resolved = collection !== undefined+ ? collection+ : await findOrCreateUniverseCollection({+ universeId,+ universeName,+ description: `Universe Builder renders for "${universeName}"`,+ }).catch((err) => {+ console.error(`❌ ${errorContext}: ${err?.message || err}`);+ return null;+ });++ // Drop the tag entirely only when there's nothing left to do — no collection+ // to file into AND no entry to append to.+ if (!resolved && !entryRef) return undefined;++ return {+ universeId,+ ...(resolved ? { runId: runId || randomUUID(), collectionId: resolved.id } : {}),+ ...(label ? { label } : {}),+ ...(category ? { category } : {}),+ ...(entryRef ? { entryRef } : {}),+ };+}diff --git a/server/services/universeRunTag.test.js b/server/services/universeRunTag.test.jsnew file mode 100644index 0000000000..30df704d41--- /dev/null+++ b/server/services/universeRunTag.test.js@@ -0,0 +1,121 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock the only side-effecting dependency before importing the module under test.+vi.mock('./mediaCollections.js', () => ({+ findOrCreateUniverseCollection: vi.fn(),+}));++import { buildUniverseRunTag } from './universeRunTag.js';+import { findOrCreateUniverseCollection } from './mediaCollections.js';++describe('buildUniverseRunTag', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('provisions the collection and mints a runId when none is supplied (probe/character-sheet path)', async () => {+ findOrCreateUniverseCollection.mockResolvedValue({ id: 'col-1' });++ const tag = await buildUniverseRunTag({+ universeId: 'u1',+ universeName: 'Nebula',+ label: 'Hero',+ category: 'characters',+ });++ expect(findOrCreateUniverseCollection).toHaveBeenCalledWith({+ universeId: 'u1',+ universeName: 'Nebula',+ description: 'Universe Builder renders for "Nebula"',+ });+ expect(tag).toMatchObject({+ universeId: 'u1',+ collectionId: 'col-1',+ label: 'Hero',+ category: 'characters',+ });+ expect(typeof tag.runId).toBe('string');+ expect(tag.runId.length).toBeGreaterThan(0);+ expect(tag).not.toHaveProperty('entryRef');+ });++ it('omits falsy label/category instead of emitting empty keys', async () => {+ findOrCreateUniverseCollection.mockResolvedValue({ id: 'col-1' });++ const tag = await buildUniverseRunTag({ universeId: 'u1', universeName: 'Nebula' });++ expect(tag).not.toHaveProperty('label');+ expect(tag).not.toHaveProperty('category');+ });++ it('drops the collection portion but preserves entryRef when provisioning fails (probe #1395 path)', async () => {+ findOrCreateUniverseCollection.mockRejectedValue(new Error('db down'));+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const entryRef = { kind: 'canon', kindKey: 'origin' };+ const tag = await buildUniverseRunTag({+ universeId: 'u1',+ universeName: 'Nebula',+ entryRef,+ errorContext: 'image-gen → universe collection provision failed',+ });++ expect(tag).toEqual({ universeId: 'u1', entryRef });+ expect(tag).not.toHaveProperty('runId');+ expect(tag).not.toHaveProperty('collectionId');+ expect(errSpy).toHaveBeenCalledWith(+ expect.stringContaining('image-gen → universe collection provision failed: db down'),+ );+ errSpy.mockRestore();+ });++ it('returns undefined when provisioning fails and there is no entryRef (character-sheet path)', async () => {+ findOrCreateUniverseCollection.mockRejectedValue(new Error('db down'));+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const tag = await buildUniverseRunTag({ universeId: 'u1', universeName: 'Nebula' });++ expect(tag).toBeUndefined();+ errSpy.mockRestore();+ });++ it('reuses a caller-supplied collection + runId without re-provisioning (batch-render path)', async () => {+ const collection = { id: 'col-batch' };++ const tag = await buildUniverseRunTag({+ universeId: 'u1',+ collection,+ runId: 'shared-run',+ category: 'concept',+ label: 'Item 3',+ entryRef: { kind: 'variation', kindKey: 'v3' },+ });++ expect(findOrCreateUniverseCollection).not.toHaveBeenCalled();+ expect(tag).toEqual({+ universeId: 'u1',+ runId: 'shared-run',+ collectionId: 'col-batch',+ label: 'Item 3',+ category: 'concept',+ entryRef: { kind: 'variation', kindKey: 'v3' },+ });+ });++ it('treats an explicit null collection as "resolved, none" (skips provisioning)', async () => {+ const tag = await buildUniverseRunTag({+ universeId: 'u1',+ collection: null,+ entryRef: { kind: 'sheet' },+ });++ expect(findOrCreateUniverseCollection).not.toHaveBeenCalled();+ expect(tag).toEqual({ universeId: 'u1', entryRef: { kind: 'sheet' } });+ });++ it('returns undefined when collection is explicitly null and there is no entryRef', async () => {+ const tag = await buildUniverseRunTag({ universeId: 'u1', collection: null });+ expect(findOrCreateUniverseCollection).not.toHaveBeenCalled();+ expect(tag).toBeUndefined();+ });+});