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
fix: fold canon/character imageRef renders into the render call (#1362)
Adam Eivye28d77a12954
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3cd8a25bec..19406b92ea 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -148,3 +148,5 @@- **[issue-1329] The mflux LoRA trainer now logs a one-line runtime fingerprint at startup, so every run log (and any future GPU-watchdog paniclog) self-documents the exact numerical stack it ran on.** The macOS GPU watchdog kernel panics that hard-reboot the box during long mflux runs (`docs/research/2026-06-13-mflux-training-watchdog-panic.md`) are version-specific to the mflux/mlx/mlx-metal/mlx-lm trio, and PortOS installs `mflux>=0.17` as a *floor* (`scripts/setup-image-video.sh`) — so the stack can drift silently and a paniclog couldn't say which versions were live. `train_mflux_lora.py` now emits a single `STATUS:` line at the top of `main()` (`runtime · mflux X · mlx Y · mlx-metal Z · mlx-lm W · <chip> · <os> · python <v>`) reusing the shared `_runner_common.build_runtime_fingerprint` (the same definition the video-gen `/status` probe uses, so the two never drift). Best-effort: a fingerprint failure logs an "unavailable" line and never aborts a training run. This is the code half of #1329; the *bisect + pin a validated trio* half is a human M5 bench session (each failing candidate hard-reboots the machine) and stays open. (`scripts/train_mflux_lora.py`, #1329)- **[issue-1207] Messages, Wiki, Feature Agents, and Creative Director now use the shared `PageHeader` title bar.** These four tabbed/top-level pages still hand-rolled the same icon + `<h1>` + subtitle + `border-b border-port-border` bar with their own padding and title scale, so navigating between them and the already-adopted pages (Brain, MeatSpace, Settings, Goals, Calendar, Insights — #1182) produced visual jitter. Each now renders `PageHeader` with its stats/controls moved into the `actions` slot: Messages' account count, Wiki's page/source counts + vault `<select>`, Feature Agents' refresh button + "New Agent" link, and Creative Director's smoke-test + "New project" buttons. Creative Director's subtitle token reconciles from `text-port-text-muted` to `PageHeader`'s `text-gray-500` (and its title from `font-semibold` to the shared `font-bold`) as called out in the issue. AIProviders/PromptManager were correctly left alone — they render inside the Settings shell, not a standalone bar. (`client/src/pages/Messages.jsx`, `client/src/pages/Wiki.jsx`, `client/src/pages/FeatureAgents.jsx`, `client/src/pages/CreativeDirector.jsx`, #1207)++- **[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)diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsxindex 5a312ca7f5..b7d1f8d9c2 100644--- a/client/src/components/pipeline/stages/NounsStage.jsx+++ b/client/src/components/pipeline/stages/NounsStage.jsx@@ -20,7 +20,6 @@ import {} from 'lucide-react';import toast from '../../ui/Toast';import {- updateUniverse,refineUniverseCharacter,getUniverseSeriesNames,} from '../../../services/apiUniverseBuilder';@@ -34,6 +33,7 @@ import {import { composeStyledPrompt } from '../../../lib/composeStyledPrompt';import { composeCleanPlatePrompt } from '../../../lib/cleanPlatePrompt';import { universeStylePreset } from '../../../lib/universeStylePreset';+import { buildUniverseSectionRenderTag } from '../../../lib/universeRunTag';import useMounted from '../../../hooks/useMounted';import useUniverse from '../../../hooks/useUniverse';import { useCanonPatch } from '../../../hooks/useCanonPatch';@@ -48,7 +48,7 @@ import {readPipelineImageSettings,pipelineImageCfgToRenderOpts,} from '../../../lib/pipelineImageDefaults';-import { BIBLE_LIMITS } from '../../../lib/bibleLimits';+import { BIBLE_LIMITS, capImageRefs } from '../../../lib/bibleLimits';// Per-kind metadata. `descFor` picks the most visual field for ref-image// generation; `descField`/`descFieldFallback`/`descFieldMax` bind CanonCard's@@ -370,10 +370,16 @@ export default function NounsStage({ issue, series, onStageUpdate }) {baseOpts.negativePrompt || '',universeStylePreset(universe, series),);+ // Durable section-local render tag (#1362): the server resolves the+ // universe collection + appends the finished render to the entry's+ // `imageRefs[]` via `appendEntryImageRef`, so the client no longer PATCHes+ // on completion (see handleRefCompleted).+ const universeRun = buildUniverseSectionRenderTag(universe, kind.key, entry);const payload = {...baseOpts,prompt: styled.prompt,negativePrompt: styled.negativePrompt || undefined,+ ...(universeRun ? { universeRun } : {}),};const queued = await generateImage(payload).catch((err) => { toast.error(err.message || 'Render failed'); return null; });@@ -382,7 +388,7 @@ export default function NounsStage({ issue, series, onStageUpdate }) {toast.success(`Rendering reference for ${entry.name}`);};- const handleRenderCleanPlate = async (entry) => {+ const handleRenderCleanPlate = async (kind, entry) => {// Match CanonCard's button-enable predicate (descFor includes palette +// recurringDetails for settings) — composeCleanPlatePrompt builds a valid// prompt from any of {description, palette, recurringDetails}, so gating@@ -400,36 +406,47 @@ export default function NounsStage({ issue, series, onStageUpdate }) {plate.negativePrompt,universeStylePreset(universe, series),);+ const universeRun = buildUniverseSectionRenderTag(universe, kind.key, entry);const queued = await generateImage({...baseOpts,prompt: styled.prompt,negativePrompt: styled.negativePrompt || undefined,+ ...(universeRun ? { universeRun } : {}),}).catch((err) => { toast.error(err.message || 'Clean plate render failed'); return null; });if (!queued?.jobId || !mountedRef.current) return;setRenderingJobs((prev) => ({ ...prev, [entry.id]: queued.jobId }));toast.success(`Rendering clean plate for ${entry.name}`);};- // Pin a freshly-completed render onto the universe's imageRefs[]. Server- // replaces the full kind list on PATCH, so we send the entire kind array- // with this entry mutated. Single-user app — no race.- const handleRefCompleted = useCallback(async (kindKey, entryId, filename) => {- if (!filename || !universe) return;+ // Clear the spinner + optimistically mirror the completed render onto the+ // entry's `imageRefs[]`. As of #1362 the section-local render carries a+ // durable `universeRun.entryRef` tag, so the server-side+ // `appendEntryImageRef` completion hook persists the ref — the client no+ // longer PATCHes here (a full-array `updateUniverse` would be redundant and+ // could clobber a concurrent sibling append with a stale list). The optimistic+ // stamp is dedup-guarded (`includes`) and last-N capped to mirror the durable+ // write; functional `setUniverse` reads the freshest draft so back-to-back+ // sibling completions chain instead of clobbering.+ const handleRefCompleted = useCallback((kindKey, entryId, filename) => {setRenderingJobs((prev) => {if (!prev[entryId]) return prev;const next = { ...prev };delete next[entryId];return next;});- const list = (universe[kindKey] || []).map((e) =>- e.id === entryId- ? { ...e, imageRefs: [...(e.imageRefs || []), filename] }- : e,- );- const updated = await updateUniverse(universe.id, { [kindKey]: list })- .catch((err) => { toast.error(`Save failed: ${err.message}`); return null; });- if (updated && mountedRef.current) setUniverse(updated);- }, [universe, setUniverse, mountedRef]);+ if (!filename) return;+ setUniverse((cur) => {+ if (!cur) return cur;+ const list = Array.isArray(cur[kindKey]) ? cur[kindKey] : [];+ const nextList = list.map((e) => {+ if (e?.id !== entryId) return e;+ const refs = Array.isArray(e.imageRefs) ? e.imageRefs : [];+ if (refs.includes(filename)) return e;+ return { ...e, imageRefs: capImageRefs([...refs, filename]) };+ });+ return { ...cur, [kindKey]: nextList };+ });+ }, [setUniverse]);// Inline-edit channel for canon fields the user picks directly (today:// setting intExt + timeOfDay chips). Optimistic — UI updates before the@@ -573,7 +590,7 @@ export default function NounsStage({ issue, series, onStageUpdate }) {onRefine={handleRefineCharacter}refiningCharacterId={refiningCharacterId}onPatchEntry={(entryId, patch) => handlePatchEntry(kind, entryId, patch)}- onRenderCleanPlate={handleRenderCleanPlate}+ onRenderCleanPlate={(entry) => handleRenderCleanPlate(kind, entry)}seriesNameMap={seriesNameMap}/>))}diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsxindex b3252bd297..e0291636b2 100644--- a/client/src/components/universe/UniverseCanonSection.jsx+++ b/client/src/components/universe/UniverseCanonSection.jsx@@ -38,41 +38,16 @@ import useMounted from '../../hooks/useMounted';import { useCanonPatch } from '../../hooks/useCanonPatch';import CanonCard from '../pipeline/CanonCard';import { pipelineImageCfgToRenderOpts } from '../../lib/pipelineImageDefaults';+import { buildUniverseSectionRenderTag } from '../../lib/universeRunTag';import { universeStylePreset } from '../../lib/universeStylePreset';import { descriptorForCanonEntry } from '../../lib/canonPrompt';import { applySheetPointer } from '../../lib/sheetPointers';-import { BIBLE_LIMITS } from '../../lib/bibleLimits';--const capImageRefs = (refs) => (- refs.length > BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX- ? refs.slice(-BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX)- : refs-);+import { BIBLE_LIMITS, capImageRefs } from '../../lib/bibleLimits';// A universe's canon list for a kind is sometimes absent on a freshly-created// record; normalize to [] so callers can spread/map without a guard each time.const getKindList = (u, kindKey) => (Array.isArray(u?.[kindKey]) ? u[kindKey] : []);-// Durable section-local render tag (#1395). Carries the canon `entryRef` so the-// server-side completion hook (universeBuilderCollectionHook) appends the-// finished render to the entry's `imageRefs[]` even after this page unmounts —-// converging these renders onto the same durable path batch renders use, so the-// client no longer needs to PATCH the universe on completion. `universeName`-// lets the route resolve the universe gallery collection (renders also land-// there, matching the base-style probe + batch paths). Returns null when the-// universe/entry identity isn't resolvable yet (render still proceeds untagged).-const buildSectionRenderTag = (universe, kindKey, entry) => (- universe?.id && universe?.name && entry?.id- ? {- universeId: universe.id,- universeName: universe.name,- entryRef: { kind: 'canon', kindKey, id: entry.id },- label: entry.name || kindKey,- category: kindKey,- }- : null-);-// Build an embedded canon entry from a picked catalog ingredient. The// ingredient's `payload` already carries the same field names the universe// canon sanitizer whitelists (name / physicalDescription / description / …),@@ -426,7 +401,7 @@ export default function UniverseCanonSection({universe,baseNegative: baseOpts.negativePrompt,});- const universeRun = buildSectionRenderTag(universe, kind.key, entry);+ const universeRun = buildUniverseSectionRenderTag(universe, kind.key, entry);const queued = await generateImage({...baseOpts,prompt: styled.prompt,@@ -488,7 +463,7 @@ export default function UniverseCanonSection({plate.negativePrompt,universe ? universeStylePreset(universe) : null,);- const universeRun = buildSectionRenderTag(universe, kind.key, entry);+ const universeRun = buildUniverseSectionRenderTag(universe, kind.key, entry);const queued = await generateImage({...baseOpts,prompt: styled.prompt,@@ -530,7 +505,7 @@ export default function UniverseCanonSection({}, [onUniverseChange]);// Section-local renders now carry a durable `universeRun.entryRef` tag- // (buildSectionRenderTag), so the server-side `appendEntryImageRef` hook+ // (buildUniverseSectionRenderTag), so the server-side `appendEntryImageRef` hook// persists the new filename even if this page unmounts mid-render — the// client just clears the spinner and mirrors the ref into the draft (no// PATCH). The durable hook is idempotent against this optimistic stamp.diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex b3c2864536..5542f6d622 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -31,6 +31,7 @@ grep -i "what you want to do" client/src/lib/README.md| `seasonStructure.js` | Mirror of `server/lib/seasonStructure.js`. || `sheetPointers.js` | Mirror of the character-sheet pointer helpers from `server/lib/storyBible.js`. `LEGACY_SHEET_VARIANT_ID` + `readSheetPointer` / `listSheetPointers` / `applySheetPointer` for traversing both the legacy `referenceSheetImageRef` field and the `referenceSheets` map. || `universeStylePreset.js` | Build the client-side style preset that `composeStyledPrompt` layers on top. |+| `universeRunTag.js` | `buildUniverseSectionRenderTag(universe, kindKey, entry)` — the durable `universeRun` job tag the canon-render call sites (UniverseCanonSection, NounsStage, Story Builder characters step) pass to `generateImage` so the server auto-files the render into the universe collection AND appends it to the entry's `imageRefs[]` (no client follow-up PATCH). || `beatColors.js` | `BEAT_KIND_COLORS` + `getBeatKindColor(kind)` — per-kind display colors for reader-map emotional beats (kinds defined server-side in `storyArc.js`). Keeps every beat visualization consistent. || `bibleLimits.js` | Mirror of `server/lib/storyBible.js` `BIBLE_LIMITS`. || `catalogTypes.js` | Client mirror of `server/lib/catalogTypes.js` — catalog ingredient type registry (label, badge color, primary-content key/label, snippet fallback chain, per-type editor field list) for the Catalog list/picker/editor. |diff --git a/client/src/lib/bibleLimits.js b/client/src/lib/bibleLimits.jsindex 1084ae3dd9..ea53785946 100644--- a/client/src/lib/bibleLimits.js+++ b/client/src/lib/bibleLimits.js@@ -79,3 +79,13 @@ export const BIBLE_LIMITS = Object.freeze({VOICE_ID_MAX: 200,INGREDIENT_ID_MAX: 64,});++// Client-side helper (no server mirror): trim an imageRefs list to the+// server-enforced last-N cap (IMAGE_REFS_PER_ENTRY_MAX). Shared by the+// optimistic imageRefs-append paths in the universe/canon render surfaces so a+// local stamp never grows past what the durable server append keeps.+export const capImageRefs = (refs) => (+ refs.length > BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX+ ? refs.slice(-BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX)+ : refs+);diff --git a/client/src/lib/bibleLimits.test.js b/client/src/lib/bibleLimits.test.jsnew file mode 100644index 0000000000..b1db42b7cb--- /dev/null+++ b/client/src/lib/bibleLimits.test.js@@ -0,0 +1,18 @@+import { describe, it, expect } from 'vitest';+import { BIBLE_LIMITS, capImageRefs } from './bibleLimits.js';++describe('capImageRefs', () => {+ it('returns the list unchanged when at or under the cap', () => {+ const refs = ['a.png', 'b.png'];+ expect(capImageRefs(refs)).toBe(refs); // same reference — no copy+ });++ it('keeps only the most recent N when over the cap', () => {+ const max = BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX;+ const refs = Array.from({ length: max + 3 }, (_, i) => `r${i}.png`);+ const capped = capImageRefs(refs);+ expect(capped).toHaveLength(max);+ expect(capped[0]).toBe('r3.png'); // dropped the 3 oldest+ expect(capped[capped.length - 1]).toBe(`r${max + 2}.png`);+ });+});diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 423731b04a..c12d70c4c2 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -10,6 +10,7 @@ export * from './personaTraitBlend.js';export * from './scenePrompt.js';export * from './seasonStructure.js';export * from './sheetPointers.js';+export * from './universeRunTag.js';export * from './universeStylePreset.js';// === Pipeline / image-gen defaults ===diff --git a/client/src/lib/universeRunTag.js b/client/src/lib/universeRunTag.jsnew file mode 100644index 0000000000..a4ef78d118--- /dev/null+++ b/client/src/lib/universeRunTag.js@@ -0,0 +1,32 @@+// Build the durable section-local render tag that converges canon/character+// reference renders onto the same server-side auto-filing path batch renders+// use. When this tag rides a `generateImage` call as `universeRun`, the route+// (server/routes/imageGen.js) resolves the universe's media collection and tags+// the queued job, so `universeBuilderCollectionHook` files the finished render+// into that collection AND `appendEntryImageRef` durably appends the filename to+// the entry's `imageRefs[]` — even if the originating page unmounts mid-render.+//+// This is the front-end half of the generate-then-attach removal (#1362): the+// three canon-render call sites (UniverseCanonSection, NounsStage, the Story+// Builder characters step) previously POSTed an untagged render and then made a+// second full-array `updateUniverse` PATCH on completion to append the ref. With+// this tag the server append is the source of truth; the client only mirrors the+// ref into its local draft optimistically.+//+// `entryRef.kind` is always `'canon'` here (characters/places/objects all live+// under a top-level universe array keyed by `kindKey`). The shape mirrors the+// batch path's entryRef (server/services/universeBuilder.js `ENTRY_REF_KIND`)+// and the route's Zod schema (canon → kindKey + id).+//+// Returns null when the universe/entry identity isn't resolvable yet — the+// caller still renders, just untagged (no auto-file).+export function buildUniverseSectionRenderTag(universe, kindKey, entry) {+ if (!universe?.id || !universe?.name || !kindKey || !entry?.id) return null;+ return {+ universeId: universe.id,+ universeName: universe.name,+ entryRef: { kind: 'canon', kindKey, id: entry.id },+ label: entry.name || kindKey,+ category: kindKey,+ };+}diff --git a/client/src/lib/universeRunTag.test.js b/client/src/lib/universeRunTag.test.jsnew file mode 100644index 0000000000..23323a138f--- /dev/null+++ b/client/src/lib/universeRunTag.test.js@@ -0,0 +1,30 @@+import { describe, it, expect } from 'vitest';+import { buildUniverseSectionRenderTag } from './universeRunTag.js';++describe('buildUniverseSectionRenderTag', () => {+ const universe = { id: 'uni-1', name: 'Aether' };+ const entry = { id: 'chr-7', name: 'Vesper' };++ it('builds the canon entryRef tag from universe + entry identity', () => {+ expect(buildUniverseSectionRenderTag(universe, 'characters', entry)).toEqual({+ universeId: 'uni-1',+ universeName: 'Aether',+ entryRef: { kind: 'canon', kindKey: 'characters', id: 'chr-7' },+ label: 'Vesper',+ category: 'characters',+ });+ });++ it('falls back the label to the kindKey when the entry has no name', () => {+ const tag = buildUniverseSectionRenderTag(universe, 'places', { id: 'plc-2' });+ expect(tag.label).toBe('places');+ expect(tag.entryRef).toEqual({ kind: 'canon', kindKey: 'places', id: 'plc-2' });+ });++ it('returns null when identity is not yet resolvable', () => {+ expect(buildUniverseSectionRenderTag(null, 'characters', entry)).toBeNull();+ expect(buildUniverseSectionRenderTag({ id: 'uni-1' }, 'characters', entry)).toBeNull(); // no name+ expect(buildUniverseSectionRenderTag(universe, 'characters', { name: 'x' })).toBeNull(); // no id+ expect(buildUniverseSectionRenderTag(universe, '', entry)).toBeNull(); // no kindKey+ });+});diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsxindex 2abfb78808..e2e289c226 100644--- a/client/src/pages/StoryBuilder.jsx+++ b/client/src/pages/StoryBuilder.jsx@@ -4,6 +4,8 @@ import { filterSelectableModels } from '../utils/providers';import { composeCanonStyledPrompt } from '../lib/composeStyledPrompt';import { descriptorForCanonEntry } from '../lib/canonPrompt';import { pipelineImageCfgToRenderOpts } from '../lib/pipelineImageDefaults';+import { buildUniverseSectionRenderTag } from '../lib/universeRunTag';+import { capImageRefs } from '../lib/bibleLimits';import useImageRenderSettings from '../hooks/useImageRenderSettings';import useSingleImageRender from '../hooks/useSingleImageRender';import EntryThumbSlot from '../components/universe/EntryThumbSlot';@@ -24,7 +26,7 @@ import {setStorySessionSync, reconcileStorySession, storyStepProgressSseUrl,getUniverse, getPipelineSeries, listPipelineIssues,analyzeImport, commitImport, retryImporterIssues, IMPORTER_CONTENT_TYPES,- getProviders, updateUniverse,+ getProviders,} from '../services/api';import ArcCanvas from '../components/pipeline/ArcCanvas';import { useArcCanvasSync } from '../hooks/useArcCanvasSync';@@ -601,7 +603,7 @@ function RefineBox({ onRefine, disabled, busy, running, phase }) {);}-function StepPanel({ session, universe, series, issues, stepId, locked, onChanged, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {+function StepPanel({ session, universe, series, issues, stepId, locked, onChanged, onSeriesUpdate, onIssuesUpdate, onFlushPending, onUniverseCharRef }) {const { start, busy, phase, op } = useStepStream(session.id, stepId);const arc = series?.arc || {};const isRunning = (which) => busy && op === which;@@ -761,7 +763,7 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChange);}if (stepId === 'characters') {- return <StepCharacters session={session} universe={universe} locked={locked} onChanged={onChanged} />;+ return <StepCharacters session={session} universe={universe} locked={locked} onChanged={onChanged} onUniverseCharRef={onUniverseCharRef} />;}if (stepId === 'issues') {return <IssuesPanel session={session} series={series} issues={issues} onChanged={onChanged} />;@@ -793,27 +795,21 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChange// `composeCanonStyledPrompt` helper + `useSingleImageRender` jobId lifecycle →// EntryThumbSlot (spinner → image), and persists the resulting filename onto// the universe canon entry's imageRefs.-function StepCharacters({ session, universe, locked, onChanged }) {+function StepCharacters({ session, universe, locked, onChanged, onUniverseCharRef }) {const cast = universe?.characters || [];const { imageCfg } = useImageRenderSettings();const [refiningId, setRefiningId] = useState(null);const { start: startRefine, busy: refineBusy, phase: refinePhase } = useStepStream(session.id, 'characters');- // Section-local renders don't carry a universeRun tag, so the server's- // imageRef append hook never fires — persist the filename ourselves. Refetch- // the freshest universe before appending so a sibling character's just-- // persisted imageRef isn't clobbered by a stale full-array PATCH.- const onCharRendered = async (filename, charId) => {- if (!universe?.id) return;- const fresh = await getUniverse(universe.id, { silent: true }).catch(() => null);- const chars = (fresh?.characters) || universe.characters || [];- const list = chars.map((e) => (- e.id === charId- ? { ...e, imageRefs: (e.imageRefs || []).includes(filename) ? e.imageRefs : [...(e.imageRefs || []), filename] }- : e- ));- await updateUniverse(universe.id, { characters: list }, { silent: true }).catch(() => {});- onChanged();+ // Section-local renders now carry a durable `universeRun.entryRef` tag (#1362),+ // so the server-side `appendEntryImageRef` hook persists the filename onto the+ // character's `imageRefs[]` — the client no longer refetches + PATCHes (a+ // full-array `updateUniverse` could clobber a sibling's just-persisted ref+ // with a stale list). Just mirror the ref into the loaded universe draft+ // optimistically for an instant thumbnail.+ const onCharRendered = (filename, charId) => {+ if (!universe?.id || !filename) return;+ onUniverseCharRef?.(charId, filename);};// One render per character, keyed by char id. `buildPrompt(charId)` composes@@ -833,7 +829,13 @@ function StepCharacters({ session, universe, locked, onChanged }) {onError: (err) => toast.error(err?.message || 'Render failed'),});- const renderChar = (c) => queueCharRender(imageCfg, c.id);+ const renderChar = (c) => {+ // Tag the render so the server auto-files it onto the character's+ // `imageRefs[]` (#1362). `useSingleImageRender.render` merges the third arg+ // into the generate payload.+ const tag = buildUniverseSectionRenderTag(universe, 'characters', c);+ queueCharRender(imageCfg, c.id, tag ? { universeRun: tag } : undefined);+ };const refineChar = (entryId) => {if (refineBusy) return;@@ -1028,6 +1030,27 @@ function StoryBuilderDetail({ storyId, stepParam }) {setLoading(false);}, [storyId]);+ // Optimistically mirror a completed character render onto the loaded+ // universe's `imageRefs[]`. The Story Builder characters step now tags its+ // render with a durable `universeRun.entryRef` (#1362), so the server-side+ // `appendEntryImageRef` hook persists the ref — this stamp just drives an+ // instant thumbnail without a refetch (which could race the durable write).+ // Dedup-guarded + last-N capped to mirror the server append.+ const applyUniverseCharRef = useCallback((charId, filename) => {+ if (!charId || !filename) return;+ setUniverse((cur) => {+ if (!cur) return cur;+ const chars = Array.isArray(cur.characters) ? cur.characters : [];+ const nextChars = chars.map((c) => {+ if (c?.id !== charId) return c;+ const refs = Array.isArray(c.imageRefs) ? c.imageRefs : [];+ if (refs.includes(filename)) return c;+ return { ...c, imageRefs: capImageRefs([...refs, filename]) };+ });+ return { ...cur, characters: nextChars };+ });+ }, []);+// ── Embedded ArcCanvas wiring (plotArc step) ──────────────────────────────// The Arc Canvas edits series.arc + the issue roadmap in place, so it needs// server-confirmed setters. The flush is usually a no-op here (the bible@@ -1279,6 +1302,7 @@ function StoryBuilderDetail({ storyId, stepParam }) {onSeriesUpdate={updateSeriesFromServer}onIssuesUpdate={handleIssuesUpdate}onFlushPending={flushPending}+ onUniverseCharRef={applyUniverseCharRef}/>{/* Footer: lock + navigation */}diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsxindex 50c7b5f429..a8209b1fa6 100644--- a/client/src/pages/UniverseBuilder.jsx+++ b/client/src/pages/UniverseBuilder.jsx@@ -54,21 +54,11 @@ import { hasCanonDescriptorContent, descriptorForCanonEntry } from '../lib/canonimport { listSheetPointers } from '../lib/sheetPointers';import { upsertByIdPrepend } from '../lib/upsertByIdPrepend';import { sameJsonShape } from '../lib/sameJsonShape';-import { BIBLE_LIMITS } from '../lib/bibleLimits';+import { capImageRefs } from '../lib/bibleLimits';import {mergeVariations, mergeCanonByName, mergeExpandIntoDraft, extractPreservedFromDraft,} from '../lib/universeBuilderExpand';-// Mirror of server-side appendEntryImageRef cap (most recent N wins). Used-// so optimistic on-completion appends produce the same final array shape-// the server would, preventing a brief window where a save round-trip-// could reorder the visible thumbnails.-const capImageRefs = (refs) => (- refs.length > BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX- ? refs.slice(-BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX)- : refs-);-const CATEGORY_LABELS = {landscapes: 'Landscapes',environments: 'Environments',