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
file base-style probe renders into the universe collection; fix spinner leak on universe switch
[._.]/ Adam Eivybfa1ccff093d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c2c33d7727..b388a985b3 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -107,6 +107,8 @@- **Deleting a brain memory now hard-prunes its mapped vector row instead of leaving a dead embedding in Postgres forever.** A user-initiated brain delete used to flow through the bridge's archive path (`UPDATE memories SET status='archived'`), which correctly hides the entry from search but left the row and its 768-dim embedding in the database indefinitely — so clearing a large import (e.g. a 1,482-record ChatGPT export) orphaned ~1,482 vectors that nothing ever reclaimed. The bridge now distinguishes a **genuine local delete** (a `{type}:deleted` / `journals:deleted` event, emitted only by the local `remove()`/`deleteJournal` paths) from a **sync-driven archive** (a peer delete arriving via the event-silent `applyRemoteRecord` → `sync:applied`): a real local delete hard-deletes the mapped memory row + embedding and drops its bridge-map entry, while a synced delete stays soft-archived so a peer un-delete can still resurrect it. A present-but-archived record is always kept soft (archived ≠ deleted). (`server/services/brainMemoryBridge.js`, #1318)+- **The Universe "Base style" image now lands in the universe's media collection, not just the probe slot.** Generating the base-style probe persisted the result onto the universe's `styleImageRefs[]` (so it showed in the probe thumbnail) but never filed it into the "Universe: <name>" media collection the way batch renders and character reference sheets do — because the probe renders through the generic `/image-gen/generate` route, which carried no collection tag. The probe render now passes the universe's identity as an argument on the generate call, and the route resolves the universe collection **server-side** and tags the queued job, so the existing completion hook (`universeBuilderCollectionHook`) files the finished image into the collection and enriches its sidecar with universe context — no front-end post-generation bookkeeping. The client never sends or knows a collectionId; resolution and filing are entirely server-side. Best-effort: if collection provisioning fails the render still proceeds (it just isn't auto-filed). The base-style slot is now also keyed by universe id in both the Universe Builder and Story Builder, so an in-flight render's spinner — and its completion handler — no longer leak onto the next universe when you switch selection mid-render (the abandoned render still files into its own universe's collection server-side). (`server/routes/imageGen.js`, `client/src/hooks/useSingleImageRender.js`, `client/src/components/universe/StyleProbeImage.jsx`, `client/src/pages/UniverseBuilder.jsx`, `client/src/pages/StoryBuilder.jsx`)+- **The "Claim Issue" scheduled CoS task no longer reports an empty queue when there are claimable issues.** The task's prompt skipped any issue carrying the `plan` label, calling them "tracking/umbrella" issues. But `do-replan --issues` labels *every* migrated backlog item `plan` — atomic bug-fixes included — so that rule discarded the entire actionable backlog and the task always exited with "no eligible issue" even with dozens of ready-to-work issues open. The prompt now treats `plan` as the claimable-queue label (matching the `/do:next --issues` flow) and skips only true epics (an `epic` label or a "(epic)" title, which need per-slice shipping). Non-customized installs auto-upgrade to the corrected prompt on the next schedule load. (`server/services/taskPromptDefaults/`)- **A late failure while finishing a local video render now fails the job cleanly instead of crashing the server (or leaving the job stuck "running").** When a render's child process exited and the final bookkeeping step (saving the clip to history, writing its thumbnail) threw, the error escaped the process-close handler as an unhandled rejection — which on modern Node can take down the whole server, and in any case left the media job wedged at "running" forever with no error ever reaching the UI. Both of `videoGen`'s child-close handlers (the main render finalizer and the last-frame extractor used by chained/extend renders) now catch such failures and surface them as a normal terminal error on the job, so the render is reported as failed and the next one proceeds. This path is newly exercised by LoRA-fused renders. (`server/services/videoGen/local.js`, #1334)diff --git a/client/src/components/universe/StyleProbeImage.jsx b/client/src/components/universe/StyleProbeImage.jsxindex cb7c895e2b..39243acf80 100644--- a/client/src/components/universe/StyleProbeImage.jsx+++ b/client/src/components/universe/StyleProbeImage.jsx@@ -11,7 +11,10 @@* renders (generateImage + EntryThumbSlot spinner/display) and persists the* resulting filename onto the universe's `styleImageRefs[]` so it survives* reload and shows in both the Universe Builder and the Story Builder- * aesthetic step.+ * aesthetic step. The render also carries a `universeRun` collection target so+ * the server files the finished image into the universe's "Universe: <name>"+ * media collection — the same auto-filing path batch renders and character+ * reference sheets use — instead of the front-end doing it post-generation.*/import { useRef } from 'react';import { Sparkles } from 'lucide-react';@@ -110,7 +113,15 @@ export default function StyleProbeImage({ universe, onUniverseChange, canRender// Capture the style key the moment the job is queued so the async completion// can detect mid-render style drift.const probe = buildStyleProbePrompt(universe);- const queuedJobId = await queueRender(imageCfg);+ // Tag the render with the universe's collection target so the SERVER files+ // the finished image into the "Universe: <name>" collection (the same+ // auto-filing path batch renders use), alongside persisting the ref onto+ // `styleImageRefs` in onComplete. The collectionId is resolved server-side+ // from this identity — the client never does collection bookkeeping.+ const universeRun = universe?.id && universe?.name+ ? { universeId: universe.id, universeName: universe.name, label: 'Base style', category: 'style' }+ : undefined;+ const queuedJobId = await queueRender(imageCfg, undefined, universeRun && { universeRun });if (queuedJobId) probeStyleKeyRef.current = JSON.stringify(probe);};diff --git a/client/src/hooks/useSingleImageRender.js b/client/src/hooks/useSingleImageRender.jsindex 451a6f072e..674bb511c0 100644--- a/client/src/hooks/useSingleImageRender.js+++ b/client/src/hooks/useSingleImageRender.js@@ -38,7 +38,9 @@ const SINGLE_KEY = '__single__';* - `jobId` — the single in-flight job's id (or null). Convenience for* single-target callers; multi-target callers read `renderingJobs[key]`.* - `renderingJobs` — `{ [key]: jobId }` for callers rendering several subjects.- * - `render(imageCfg, key)` — queue a render; returns the queued jobId or null.+ * - `render(imageCfg, key, extraParams)` — queue a render; returns the queued+ * jobId or null. `extraParams` is merged into the generate payload (e.g. a+ * `universeRun` collection target the server routes the finished render to).* - `handleComplete(filename, key)` — clear the job + run the guarded onComplete.*/export default function useSingleImageRender({ buildPrompt, onComplete, onError } = {}) {@@ -56,12 +58,16 @@ export default function useSingleImageRender({ buildPrompt, onComplete, onErrorconst onErrorRef = useRef(onError);onErrorRef.current = onError;- const render = useCallback(async (imageCfg, key = SINGLE_KEY) => {+ const render = useCallback(async (imageCfg, key = SINGLE_KEY, extraParams = undefined) => {const built = buildPromptRef.current?.(key);if (!built) return null; // caller aborted (already toasted why)const baseOpts = pipelineImageCfgToRenderOpts(imageCfg);+ // `extraParams` lets a caller attach extra fields to the generate payload+ // (e.g. the base-style probe's `universeRun` collection target) so the+ // server can route the finished render — the front-end does no+ // post-generation bookkeeping of its own.const queued = await generateImage(- { ...baseOpts, prompt: built.prompt, negativePrompt: built.negativePrompt || undefined },+ { ...baseOpts, prompt: built.prompt, negativePrompt: built.negativePrompt || undefined, ...(extraParams || {}) },{ silent: true },).catch((err) => { onErrorRef.current?.(err); return null; });if (!queued?.jobId) return null;diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsxindex 25b1e3a282..2abfb78808 100644--- a/client/src/pages/StoryBuilder.jsx+++ b/client/src/pages/StoryBuilder.jsx@@ -682,7 +682,9 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChange<FieldBlock label="Influences — embrace" value={(universe?.influences?.embrace || []).join(', ')} /><FieldBlock label="Influences — avoid" value={(universe?.influences?.avoid || []).join(', ')} /><div className="border-t border-port-border pt-3">- <StyleProbeImage universe={universe} onUniverseChange={() => onChanged()} canRender={!locked} />+ {/* Keyed by universe id so an in-flight base-style render's spinner ++ completion stay scoped to one universe across a selection change. */}+ <StyleProbeImage key={universe?.id || 'new'} universe={universe} onUniverseChange={() => onChanged()} canRender={!locked} /></div><div className="flex items-center gap-2">{!locked && genButton('Expand aesthetic', Boolean((universe?.premise || universe?.styleNotes || '').trim()))}diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsxindex 864321e8ff..50c7b5f429 100644--- a/client/src/pages/UniverseBuilder.jsx+++ b/client/src/pages/UniverseBuilder.jsx@@ -3029,7 +3029,14 @@ function BibleTab({only that field into the draft so unsaved style edits aren't lost.`styleDirty` blocks the render while influences have unsaved edits —otherwise the probe pins to a saved record that lacks that style. */}+ {/* Key by universe id so the probe's in-flight render state (the+ EntryThumbSlot spinner + the async completion handler) is scoped+ to one universe. Without the key the editor stays mounted across a+ `/universes/:id` switch and the prior universe's spinner — and its+ completion — would leak onto the next universe's slot. The server+ still files the abandoned render into its own collection. */}<StyleProbeImage+ key={draft.id || 'new'}universe={draft}onUniverseChange={(updated) => updateDraft({ styleImageRefs: updated?.styleImageRefs || [] })}onPreview={onPreview}diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex e888b85b85..e3d5f3b986 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -43,6 +43,8 @@ import {resolveRegenStrengthDefault,} from '../services/imageGen/regen.js';import { purgeImageRefFromAllUniverses } from '../services/universeCanon.js';+import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';+import { randomUUID } from 'crypto';const router = Router();@@ -99,6 +101,20 @@ const generateSchema = z.object({cleanC2PA: z.boolean().optional(),denoise: z.boolean().optional(),autoClean: z.boolean().optional(),+ // Optional universe-collection target. When present, the route resolves the+ // universe's media collection server-side and tags the queued job so+ // `universeBuilderCollectionHook` files the finished render into that+ // collection — the same auto-filing path batch renders and character+ // reference sheets use. The client passes only the universe identity (never+ // a collectionId — that's server-resolved), so the front-end does no+ // collection bookkeeping. The base-style probe (StyleProbeImage) is the sole+ // caller today; JSON-only (the multipart ImageGen page never sends it).+ universeRun: z.object({+ universeId: z.string().min(1).max(200),+ universeName: z.string().min(1).max(200),+ label: z.string().max(200).optional(),+ category: z.string().max(64).optional(),+ }).optional(),}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });// JSON callers (SDAPI bridge, avatar route, the Imagine page's old payload@@ -247,6 +263,27 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {referenceImageFields: REFERENCE_IMAGE_FIELDS,});+ // Resolve an optional universe-collection target into a job tag the+ // completion hook understands. Done server-side so a base-style probe lands+ // in the same "Universe: <name>" bucket as batch renders without the+ // front-end doing any collection bookkeeping. Best-effort: a provisioning+ // failure drops the tag and the render still proceeds (it just won't+ // auto-file) rather than failing the user's generation over a side-effect.+ if (params.universeRun?.universeId) {+ const { universeId, universeName, label, category } = params.universeRun;+ const collection = await findOrCreateUniverseCollection({+ universeId,+ universeName,+ description: `Universe Builder renders for "${universeName}"`,+ }).catch((err) => {+ console.error(`❌ image-gen → universe collection provision failed: ${err?.message || err}`);+ return null;+ });+ params.universeRun = collection+ ? { runId: randomUUID(), universeId, collectionId: collection.id, label, category }+ : undefined;+ }+// 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), ordiff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex 735dd6d4d0..1abc4ce536 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -52,6 +52,13 @@ vi.mock('../services/mediaJobQueue/index.js', () => ({listJobs: vi.fn(() => []),}));+// The /generate route resolves an optional universeRun collection target via+// findOrCreateUniverseCollection. Mock it so the universeRun test asserts the+// tag-resolution wiring without touching real collection storage.+vi.mock('../services/mediaCollections.js', () => ({+ findOrCreateUniverseCollection: vi.fn(async ({ universeId }) => ({ id: `col-${universeId}` })),+}));+// HOST_ARCH is read at request time inside `buildSetupCheck`, so backing it// with a hoisted mutable holder + getter lets tests flip between arm64 and// x86_64 hosts without re-mocking. Default arm64 keeps every existing test@@ -88,6 +95,7 @@ vi.mock('fs/promises', async (importOriginal) => {import * as imageGen from '../services/imageGen/index.js';import * as mediaJobQueue from '../services/mediaJobQueue/index.js';import { getSettings } from '../services/settings.js';+import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';describe('Image Gen Routes', () => {let app;@@ -295,6 +303,71 @@ describe('Image Gen Routes', () => {expect(imageGen.generateImage).not.toHaveBeenCalled();});+ // The base-style probe passes a `universeRun` identity so the SERVER files+ // the finished render into the universe collection. The route must resolve+ // the collectionId server-side and tag the queued job — the front-end never+ // sends a collectionId or does post-generation bookkeeping.+ describe('universeRun collection target', () => {+ it('resolves the collection server-side and tags the queued job', async () => {+ getSettings.mockResolvedValueOnce({ imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } });+ mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'queued-style', position: 1, status: 'queued' });++ const response = await request(app)+ .post('/api/image-gen/generate')+ .send({+ prompt: 'a moody noir skyline',+ universeRun: { universeId: 'uni-1', universeName: 'NoirVerse', label: 'Base style', category: 'style' },+ });++ expect(response.status).toBe(200);+ expect(findOrCreateUniverseCollection).toHaveBeenCalledWith(+ expect.objectContaining({ universeId: 'uni-1', universeName: 'NoirVerse' }),+ );+ const [call] = mediaJobQueue.enqueueJob.mock.calls;+ // collectionId is server-resolved (never client-supplied), runId minted,+ // label/category preserved — exactly what universeBuilderCollectionHook reads.+ expect(call[0].params.universeRun).toEqual(expect.objectContaining({+ universeId: 'uni-1',+ collectionId: 'col-uni-1',+ label: 'Base style',+ category: 'style',+ }));+ expect(typeof call[0].params.universeRun.runId).toBe('string');+ });++ it('drops the tag (still renders) when collection provisioning fails', async () => {+ getSettings.mockResolvedValueOnce({ imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } });+ mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'queued-style-2', position: 1, status: 'queued' });+ findOrCreateUniverseCollection.mockRejectedValueOnce(new Error('db down'));++ const response = await request(app)+ .post('/api/image-gen/generate')+ .send({+ prompt: 'a moody noir skyline',+ universeRun: { universeId: 'uni-2', universeName: 'FailVerse', label: 'Base style', category: 'style' },+ });++ // The render still proceeds — a collection-filing miss must not fail it.+ expect(response.status).toBe(200);+ const [call] = mediaJobQueue.enqueueJob.mock.calls;+ expect(call[0].params.universeRun).toBeUndefined();+ });++ it('ignores universeRun without a universeId (no collection resolution)', async () => {+ getSettings.mockResolvedValueOnce({ imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } });+ mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'queued-plain', position: 1, status: 'queued' });++ const response = await request(app)+ .post('/api/image-gen/generate')+ .send({ prompt: 'a plain render' });++ expect(response.status).toBe(200);+ expect(findOrCreateUniverseCollection).not.toHaveBeenCalled();+ const [call] = mediaJobQueue.enqueueJob.mock.calls;+ expect(call[0].params.universeRun).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/universeBuilderCollectionHook.test.js b/server/services/universeBuilderCollectionHook.test.jsindex 2cde8226cf..057d2e0c8d 100644--- a/server/services/universeBuilderCollectionHook.test.js+++ b/server/services/universeBuilderCollectionHook.test.js@@ -347,4 +347,42 @@ describe('universeBuilderCollectionHook', () => {expect(sc.universeName).toBe('BatchVerse');}});++ it('files a base-style probe render (universeRun tag, no entryRef) into the collection', async () => {+ const seeded = await seedUniverse({ name: 'StyleVerse' });+ const c = await makeCollection(seeded.id);+ const filename = 'base-style.png';+ writeSidecar(filename, { id: 'base-style', prompt: 'a moody noir skyline', seed: 7 });+ hook.registerUniverseBuilderRun({ runId: 'r-style', universeId: seeded.id, jobCount: 1 });++ // Mirrors the job the generic /image-gen/generate route enqueues for the+ // base-style probe: a universeRun tag carrying the resolved collectionId ++ // a 'style' label/category, but NO entryRef (the probe isn't a canon entry).+ mediaJobEvents.emit('completed', {+ kind: 'image',+ result: { filename },+ params: {+ universeRun: {+ runId: 'r-style',+ universeId: seeded.id,+ collectionId: c.id,+ category: 'style',+ label: 'Base style',+ },+ },+ });++ await waitFor(() => hook.__testing.getActiveRuns().size === 0);+ const col = await collections.getCollection(c.id);+ expect(col.items.some((it) => it.kind === 'image' && it.ref === filename)).toBe(true);+ // Sidecar gains universe context (so the collection lightbox shows the world)+ // without clobbering the original generation metadata.+ const sc = readSidecar(filename);+ expect(sc.universeId).toBe(seeded.id);+ expect(sc.universeName).toBe('StyleVerse');+ expect(sc.entryLabel).toBe('Base style');+ expect(sc.entryCategory).toBe('style');+ expect(sc.prompt).toBe('a moody noir skyline');+ expect(sc.seed).toBe(7);+ });});