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

show rendered composite boards as thumbnails, like every other universe surface

[._.]/ Adam Eivy2e8b4bff7c00
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9f9fc7fcc9..54cfda2916 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -73,3 +73,5 @@
- **`completeAgent` had three addresses, and the four callers that most needed one address were using the wrong one.** Continuing #3450's sequencing: `agentManagement.js`, `agentLifecycle.js`, `agentFinalization.js` and `agentCliSpawning.js` all reached the completion transition through the `cosAgents.js` barrel. These four are the callers the "move the caller above the facade" recipe cannot reach — the first two DEFINE transitions `agentOrchestrator.js` re-exports, so importing the facade from either is the cycle itself, and the other two are leaves those two must call to spawn and to finalize. So the rule they follow is the other half of the same property: above the facade's closure a transition comes from the facade, inside it from the module that DECLARES it (`cosAgentLifecycle.js`), and never from a barrel. `cleanupOrphanedAgents`'s `await import('./cos.js')` went with it — it was pulling `completeAgent` and `getAgents` through the `cos.js` re-export block while the module was already a static import three lines up, so the deferral bought no cycle protection at all. The new guard in `agentImportCycles.test.js` derives the transition names from the facade's export blocks and walks re-export edges to work out which modules forward them, so a barrel added later is covered without being named; it catches a named import, a renamed one, a namespace property read, a destructure off a namespace handle, and the three deferred spellings of the same reaches — including `const { completeAgent } = await import('./cos.js')`, the exact pattern this change deleted. Each bypass-probed.
- **The "Pick from Gallery" picker could only be narrowed by typing, so finding one object in one universe meant recalling a word from its prompt.** It now carries two dropdowns beside the search box: a scope select that groups every universe and media collection under `<optgroup>`s, and a type select built from the `entryCategory`/`entryKind` tags the Universe Builder stamps onto sidecars, labelled through the same `humanizeCategory` the Builder uses. Those two are separate vocabularies — a user-authored bucket can legitimately be keyed `canon` — so the type options are prefixed by which field they filter and grouped under Categories/Entry kinds rather than flattened into one list where the bucket and the stage would silently match each other. All three filters AND-combine, and both dropdowns list only universes/collections/types that actually match an image currently in the picker — a scope that can only ever produce an empty grid isn't offered, and a selection that stops matching resets itself to "All" rather than silently blanking the grid. Collection membership is matched on the stored `{ kind, ref }` pair (the same `<kind>:<ref>` string `normalizeImage` puts on `item.key`), not on a bare filename, so a collection holding video refs alongside images filters correctly. Both option fetches are best-effort: if the collections or universes call fails the picker keeps working, falling back to the universe name stamped on each sidecar, and the fetched lists are dropped on close so a reopen can't filter fresh images against stale membership. Sidecars are unvalidated JSON that also arrive from peers, so a tag that isn't a usable string is skipped rather than crashing the render — which surfaced a latent bug in the shared `humanizeCategory`: its label lookup wasn't `hasOwn`-guarded, so a user-authored category keyed `constructor` or `toString` resolved to an inherited function and handed every caller a label that throws on the next string method (#3479).
+
+- **Composite boards were the only Universe Builder surface with no thumbnail, so a rendered board looked unrendered.** Characters, places, objects and category variations all show their latest render as an `EntryThumbSlot` avatar with a click-to-preview lightbox; the Composites tab showed label + prompt only. Nothing was missing server-side — `compile.js` already stamps an `entryRef` of kind `sheet` on each queued board render and the completion hook already appends the resulting filename to that board's `imageRefs[]`, so the data was sitting in the record with nothing reading it. Composite rows now render through the same `EntryCard` shell + three-state `EntryThumbSlot` the variation and canon rows use (in-flight spinner → rendered thumbnail → empty placeholder with a one-click render button), so their spacing and locked accent can no longer drift from the other surfaces, and clicking a board opens the same page-level lightbox with the real render prompt hydrated from the gallery sidecar. `useRenderJobQueue` had been dropping `sheet`-kind jobs on the grounds that no row consumed them; with every kind the server stamps now settled by a row, the filter is deleted rather than widened — an allowlist that already covers everything can only ever fail closed on the next kind added, silently, with no spinner and no error. Two things this collapsed rather than copied: the row settles through `EntryThumbSlot`'s existing `onComplete` bridge instead of opening a second `useMediaJobProgress` subscription against a jobId the slot is already watching (which is what the variation and canon rows do, at the cost of a row re-render per diffusion tick), and the append-dedupe-cap that had been inlined at four client call sites is now `appendImageRefById` in `lib/bibleLimits.js`, the client mirror of the server's `mapAppendImageRef`.
diff --git a/client/src/components/universeBuilder/CompositeSheetsEditor.jsx b/client/src/components/universeBuilder/CompositeSheetsEditor.jsx
index 069395d0d7..22fc3e5a79 100644
--- a/client/src/components/universeBuilder/CompositeSheetsEditor.jsx
+++ b/client/src/components/universeBuilder/CompositeSheetsEditor.jsx
@@ -2,12 +2,27 @@ import { useState } from 'react';
import { Plus, Play, Lock, Unlock, Edit3, X } from 'lucide-react';
import { COMPOSITE_PROMPT_MAX } from '../../services/api';
import { COMPOSITE_BOARD_KINDS, compositeKindLabel } from '../../lib/universeBuilderShared';
+import EntryCard from '../universe/EntryCard';
+import EntryThumbSlot from '../universe/EntryThumbSlot';
// Composite-boards editor for the Universe Builder Composites tab. Add / edit /
// remove reference sheets + world-pitch posters, with per-board + bulk lock
// toggles (locked boards survive AI Expand). Extracted from UniverseBuilder.jsx
// (#2374). Pure presentational — `onChange(nextSheets)` owns persistence.
-export default function CompositeSheetsEditor({ sheets, onChange, canRender = false, onRender = null }) {
+export default function CompositeSheetsEditor({
+ sheets, onChange, canRender = false, onRender = null,
+ // Clicking a board's thumbnail opens the page-level MediaPreview lightbox,
+ // same as variation / canon rows. Receives the visible filename.
+ onPreview = null,
+ // Per-row render-pending plumbing, mirroring the variation grid:
+ // `pendingByEntryId[sheet.id]` is the in-flight jobId (or undefined), and
+ // `onJobSettled(sheetId, filename | null, jobId)` fires when that job reaches
+ // a terminal state so the parent can append the new filename to the board's
+ // imageRefs[] and clear the pending entry. A terminal failure/cancel yields no
+ // filename, so it settles with `null` on the same callback rather than a
+ // second one — the parent's clear path is identical either way.
+ pendingByEntryId = {}, onJobSettled = null,
+}) {
const [adding, setAdding] = useState(false);
const [newKind, setNewKind] = useState('reference_sheet');
const [newLabel, setNewLabel] = useState('');
@@ -158,87 +173,135 @@ export default function CompositeSheetsEditor({ sheets, onChange, canRender = fa
) : (
<ul className="flex flex-col gap-1.5 max-h-96 overflow-y-auto">
{sheets.map((sheet, idx) => (
- <li key={`${sheet.label}-${idx}`} className={`bg-port-bg border rounded p-2 text-sm ${sheet.locked ? 'border-port-accent/50' : 'border-port-border'}`}>
- {editIdx === idx ? (
- <div className="flex flex-col gap-1">
- <select
- value={editKind}
- onChange={(e) => setEditKind(e.target.value)}
- className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm min-h-[40px]"
- >
- {COMPOSITE_BOARD_KINDS.map((kind) => (
- <option key={kind.value} value={kind.value}>{kind.label}</option>
- ))}
- </select>
- <input
- value={editLabel}
- onChange={(e) => setEditLabel(e.target.value)}
- className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm"
- maxLength={120}
- />
- <textarea
- value={editPrompt}
- onChange={(e) => setEditPrompt(e.target.value)}
- rows={8}
- className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm"
- maxLength={COMPOSITE_PROMPT_MAX}
- />
- <div className="flex gap-2">
- <button onClick={saveEdit} className="text-xs px-2 py-1 bg-port-accent text-white rounded min-h-[40px] sm:min-h-0">Save</button>
- <button onClick={() => setEditIdx(null)} className="text-xs px-2 py-1 bg-port-bg text-gray-300 rounded min-h-[40px] sm:min-h-0">Cancel</button>
- </div>
- </div>
- ) : (
- <div className="flex items-start justify-between gap-2">
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- <div className="text-white font-medium truncate">{sheet.label}</div>
- <span className="shrink-0 text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded bg-port-accent/10 text-port-accent border border-port-accent/20">
- {compositeKindLabel(sheet.kind)}
- </span>
- </div>
- <div className="text-xs text-gray-400 line-clamp-3">{sheet.prompt}</div>
- </div>
- <div className="flex items-center gap-1 shrink-0">
- {onRender && (
- <button
- onClick={() => onRender(sheet)}
- disabled={!canRender}
- className="p-1 text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed rounded"
- title={canRender ? 'Render this board' : 'Save the world and configure a render backend to enable'} aria-label={canRender ? 'Render this board' : 'Save the world and configure a render backend to enable'}
- >
- <Play size={14} />
- </button>
- )}
- <button
- onClick={() => toggleLockAt(idx)}
- className={`p-1 rounded ${sheet.locked ? 'text-port-accent hover:bg-port-accent/20' : 'text-gray-500 hover:text-gray-300'}`}
- title={sheet.locked ? 'Locked — AI expand will preserve this board' : 'Lock this board against AI expand'} aria-label={sheet.locked ? 'Locked — AI expand will preserve this board' : 'Lock this board against AI expand'}
- aria-pressed={!!sheet.locked}
+ editIdx === idx ? (
+ <EntryCard
+ key={`${sheet.label}-${idx}`}
+ locked={!!sheet.locked}
+ body={(
+ <div className="flex flex-col gap-1">
+ <select
+ value={editKind}
+ onChange={(e) => setEditKind(e.target.value)}
+ className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm min-h-[40px]"
>
- {sheet.locked ? <Lock size={14} /> : <Unlock size={14} />}
- </button>
- <button
- onClick={() => startEdit(idx, sheet)}
- className="p-1 text-gray-400 hover:text-port-accent rounded"
- title="Edit" aria-label="Edit"
- >
- <Edit3 size={14} />
- </button>
- <button
- onClick={() => removeAt(idx)}
- className="p-1 text-gray-400 hover:text-port-error rounded"
- title="Remove" aria-label="Remove"
- >
- <X size={14} />
- </button>
+ {COMPOSITE_BOARD_KINDS.map((kind) => (
+ <option key={kind.value} value={kind.value}>{kind.label}</option>
+ ))}
+ </select>
+ <input
+ value={editLabel}
+ onChange={(e) => setEditLabel(e.target.value)}
+ className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm"
+ maxLength={120}
+ />
+ <textarea
+ value={editPrompt}
+ onChange={(e) => setEditPrompt(e.target.value)}
+ rows={8}
+ className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm"
+ maxLength={COMPOSITE_PROMPT_MAX}
+ />
+ <div className="flex gap-2">
+ <button onClick={saveEdit} className="text-xs px-2 py-1 bg-port-accent text-white rounded min-h-[40px] sm:min-h-0">Save</button>
+ <button onClick={() => setEditIdx(null)} className="text-xs px-2 py-1 bg-port-bg text-gray-300 rounded min-h-[40px] sm:min-h-0">Cancel</button>
+ </div>
</div>
- </div>
- )}
- </li>
+ )}
+ />
+ ) : (
+ <SheetRow
+ key={`${sheet.label}-${idx}`}
+ sheet={sheet}
+ canRender={canRender}
+ onRender={onRender ? () => onRender(sheet) : null}
+ onPreview={onPreview}
+ inFlightJobId={pendingByEntryId?.[sheet.id] || null}
+ onJobSettled={onJobSettled}
+ onToggleLock={() => toggleLockAt(idx)}
+ onStartEdit={() => startEdit(idx, sheet)}
+ onRemove={() => removeAt(idx)}
+ />
+ )
))}
</ul>
)}
</section>
);
}
+
+// Display row for one composite board. Renders through `EntryCard` for the same
+// reason VariationCard and CanonCard do — the locked-accent border and the
+// thumbnail / title / body / actions slot layout stay in lock-step across every
+// universe surface instead of drifting per editor.
+function SheetRow({
+ sheet, canRender, onRender, onPreview,
+ inFlightJobId, onJobSettled,
+ onToggleLock, onStartEdit, onRemove,
+}) {
+ const renders = Array.isArray(sheet.imageRefs) ? sheet.imageRefs : [];
+ // Three-state thumbnail (pending spinner / rendered image / empty placeholder
+ // with a one-click render button), matching the variation + canon rows so a
+ // rendered board reads the same way its characters / places / objects do.
+ // `onComplete` is EntryThumbSlot's own settle bridge — it fires with the
+ // rendered filename, or with `null` on a terminal failure/cancel — so the row
+ // needs no second `useMediaJobProgress` subscription against a jobId the slot
+ // is already watching. `inFlightJobId` comes back from the closure because the
+ // parent shifts exactly that jobId out of the board's pending queue.
+ const thumbnail = (
+ <EntryThumbSlot
+ inFlightJobId={inFlightJobId}
+ imageRefs={renders}
+ alt={`${sheet.label} render`}
+ canRender={canRender}
+ onRender={onRender}
+ onPreview={onPreview}
+ onComplete={onJobSettled ? (filename) => onJobSettled(sheet.id, filename, inFlightJobId) : null}
+ />
+ );
+ const title = (
+ <div className="flex items-center gap-2">
+ <div className="text-sm text-white font-medium truncate">{sheet.label}</div>
+ <span className="shrink-0 text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded bg-port-accent/10 text-port-accent border border-port-accent/20">
+ {compositeKindLabel(sheet.kind)}
+ </span>
+ </div>
+ );
+ const body = <div className="text-xs text-gray-400 line-clamp-3">{sheet.prompt}</div>;
+ const actions = (
+ <div className="flex items-center gap-1">
+ {onRender && (
+ <button
+ onClick={onRender}
+ disabled={!canRender}
+ className="p-1 text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed rounded"
+ title={canRender ? 'Render this board' : 'Save the world and configure a render backend to enable'} aria-label={canRender ? 'Render this board' : 'Save the world and configure a render backend to enable'}
+ >
+ <Play size={14} />
+ </button>
+ )}
+ <button
+ onClick={onToggleLock}
+ className={`p-1 rounded ${sheet.locked ? 'text-port-accent hover:bg-port-accent/20' : 'text-gray-500 hover:text-gray-300'}`}
+ title={sheet.locked ? 'Locked — AI expand will preserve this board' : 'Lock this board against AI expand'} aria-label={sheet.locked ? 'Locked — AI expand will preserve this board' : 'Lock this board against AI expand'}
+ aria-pressed={!!sheet.locked}
+ >
+ {sheet.locked ? <Lock size={14} /> : <Unlock size={14} />}
+ </button>
+ <button
+ onClick={onStartEdit}
+ className="p-1 text-gray-400 hover:text-port-accent rounded"
+ title="Edit" aria-label="Edit"
+ >
+ <Edit3 size={14} />
+ </button>
+ <button
+ onClick={onRemove}
+ className="p-1 text-gray-400 hover:text-port-error rounded"
+ title="Remove" aria-label="Remove"
+ >
+ <X size={14} />
+ </button>
+ </div>
+ );
+ return <EntryCard locked={!!sheet.locked} thumbnail={thumbnail} title={title} body={body} actions={actions} />;
+}
diff --git a/client/src/components/universeBuilder/CompositeSheetsEditor.test.jsx b/client/src/components/universeBuilder/CompositeSheetsEditor.test.jsx
index 2486fbeafe..d90969059f 100644
--- a/client/src/components/universeBuilder/CompositeSheetsEditor.test.jsx
+++ b/client/src/components/universeBuilder/CompositeSheetsEditor.test.jsx
@@ -1,10 +1,20 @@
-import { describe, it, expect, vi } from 'vitest';
-import { render, screen } from '@testing-library/react';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import CompositeSheetsEditor from './CompositeSheetsEditor.jsx';
+// The row's thumbnail slot subscribes to its in-flight job through
+// useMediaJobProgress (socket + fetch). Stub it so the rows render offline;
+// `job` is mutable so a test can drive the completion / failure paths.
+let job = { status: 'queued', filename: null, error: null };
+vi.mock('../../hooks/useMediaJobProgress', () => ({
+ default: () => ({ progress: 0, step: 0, totalSteps: 0, currentImage: null, ...job }),
+}));
+
const sheet = (over = {}) => ({ kind: 'reference_sheet', label: 'Costume sheet', prompt: 'A clean sheet.', locked: true, ...over });
+beforeEach(() => { job = { status: 'queued', filename: null, error: null }; });
+
describe('CompositeSheetsEditor', () => {
it('shows the empty state and count', () => {
render(<CompositeSheetsEditor sheets={[]} onChange={() => {}} />);
@@ -38,4 +48,64 @@ describe('CompositeSheetsEditor', () => {
await userEvent.click(screen.getByTitle('Render this board'));
expect(onRender).toHaveBeenCalledWith(s);
});
+
+ it('shows a thumbnail for a board that has rendered images', () => {
+ render(
+ <CompositeSheetsEditor
+ sheets={[sheet({ label: 'Pitch', imageRefs: ['old.png', 'newest.png'] })]}
+ onChange={() => {}}
+ />,
+ );
+ const img = screen.getByAltText('Pitch render');
+ expect(img).toHaveAttribute('src', '/data/images/newest.png');
+ });
+
+ it('clicking a rendered thumbnail opens the preview with the visible filename', async () => {
+ const onPreview = vi.fn();
+ render(
+ <CompositeSheetsEditor
+ sheets={[sheet({ label: 'Pitch', imageRefs: ['newest.png'] })]}
+ onChange={() => {}}
+ onPreview={onPreview}
+ />,
+ );
+ await userEvent.click(screen.getByRole('button', { name: /preview pitch render/i }));
+ expect(onPreview).toHaveBeenCalledWith('newest.png');
+ });
+
+ it('a board with no renders offers the empty-state render affordance', async () => {
+ const onRender = vi.fn();
+ const s = sheet();
+ render(<CompositeSheetsEditor sheets={[s]} onChange={() => {}} onRender={onRender} canRender />);
+ await userEvent.click(screen.getByRole('button', { name: /render image for this item/i }));
+ expect(onRender).toHaveBeenCalledWith(s);
+ });
+
+ it('settles with the rendered filename when the row\'s in-flight job completes', async () => {
+ job = { status: 'completed', filename: 'fresh.png', error: null };
+ const onJobSettled = vi.fn();
+ render(
+ <CompositeSheetsEditor
+ sheets={[sheet({ id: 'sheet-1' })]}
+ onChange={() => {}}
+ pendingByEntryId={{ 'sheet-1': 'job-9' }}
+ onJobSettled={onJobSettled}
+ />,
+ );
+ await waitFor(() => expect(onJobSettled).toHaveBeenCalledWith('sheet-1', 'fresh.png', 'job-9'));
+ });
+
+ it('settles with a null filename on a terminal failure so the parent still clears the pending entry', async () => {
+ job = { status: 'failed', filename: null, error: 'boom' };
+ const onJobSettled = vi.fn();
+ render(
+ <CompositeSheetsEditor
+ sheets={[sheet({ id: 'sheet-1' })]}
+ onChange={() => {}}
+ pendingByEntryId={{ 'sheet-1': 'job-9' }}
+ onJobSettled={onJobSettled}
+ />,
+ );
+ await waitFor(() => expect(onJobSettled).toHaveBeenCalledWith('sheet-1', null, 'job-9'));
+ });
});
diff --git a/client/src/components/universeBuilder/UniverseBuilderPage.jsx b/client/src/components/universeBuilder/UniverseBuilderPage.jsx
index 41d490fe42..14ba3b4cdc 100644
--- a/client/src/components/universeBuilder/UniverseBuilderPage.jsx
+++ b/client/src/components/universeBuilder/UniverseBuilderPage.jsx
@@ -33,7 +33,7 @@ import CompositeSheetsEditor from './CompositeSheetsEditor';
import RenderTab from './RenderTab';
import UniverseBibleTab from './UniverseBibleTab';
import { OtherTab, TrunkView } from './UniverseTrunkPanels';
-import { capImageRefs } from '../../lib/bibleLimits';
+import { appendImageRefById } from '../../lib/bibleLimits';
import { totalVariationCount } from '../../lib/universeBuilderCounts';
import {
TAB_BIBLE,
@@ -252,32 +252,55 @@ export default function UniverseBuilder() {
const totalVariations = totalVariationCount(draft);
const totalSheets = draft.compositeSheets?.length || 0;
- // Shared by every bucket grid (trunk tabs + Other). Optimistically append the
- // new filename to the variation's imageRefs[] so the row swaps from spinner →
- // rendered image without a roundtrip. Server already stamped this via the
- // collection hook; the next universe refetch will agree. Then pull the fresh
- // sidecar into galleryByFilename so the lightbox opens with the real
- // prompt/settings rather than label-only metadata.
- const handleEntryJobCompleted = useCallback((entryId, filename, bucket, completedJobId = null) => {
- if (!filename || !bucket) {
- clearPendingForEntry(entryId, completedJobId);
- return;
- }
- setDraft((d) => {
- const cat = d.categories?.[bucket];
- if (!cat?.variations) return d;
- const variations = cat.variations.map((v) => {
- if (v.id !== entryId) return v;
- const refs = Array.isArray(v.imageRefs) ? v.imageRefs : [];
- if (refs.includes(filename)) return v;
- return { ...v, imageRefs: capImageRefs([...refs, filename]) };
+ // Settle one row's render job: optimistically append the new filename to that
+ // entry's imageRefs[] so the row swaps from spinner → rendered image without a
+ // roundtrip, then shift the jobId out of the row's pending queue and pull the
+ // fresh sidecar into galleryByFilename so the lightbox opens with the real
+ // prompt/settings rather than label-only metadata. The server's completion
+ // hook already stamped the ref durably; the next universe refetch will agree.
+ // `applyAppend(draft, appended)` is the only per-surface part — it splices the
+ // updated list back into whichever collection owns the row (a category's
+ // variations vs. the top-level compositeSheets), and returns the draft
+ // unchanged when the collection isn't there.
+ const settleEntryJob = useCallback((entryId, filename, completedJobId, selectList, applyAppend) => {
+ if (filename) {
+ setDraft((d) => {
+ const appended = appendImageRefById(selectList(d), entryId, filename);
+ // `null` (no such collection) or an unchanged array (unknown id / ref
+ // already present) both mean there's nothing to re-render for.
+ if (!appended || appended === selectList(d)) return d;
+ return applyAppend(d, appended);
});
- return { ...d, categories: { ...d.categories, [bucket]: { ...cat, variations } } };
- });
+ bumpGalleryRefresh();
+ }
clearPendingForEntry(entryId, completedJobId);
- bumpGalleryRefresh();
}, [clearPendingForEntry, setDraft, bumpGalleryRefresh]);
+ // Shared by every bucket grid (trunk tabs + Other).
+ const handleEntryJobCompleted = useCallback((entryId, filename, bucket, completedJobId = null) => {
+ settleEntryJob(
+ entryId,
+ bucket ? filename : null,
+ completedJobId,
+ (d) => d.categories?.[bucket]?.variations,
+ (d, variations) => ({
+ ...d,
+ categories: { ...d.categories, [bucket]: { ...d.categories[bucket], variations } },
+ }),
+ );
+ }, [settleEntryJob]);
+
+ // Composite boards on the Composites tab.
+ const handleSheetJobSettled = useCallback((sheetId, filename, settledJobId = null) => {
+ settleEntryJob(
+ sheetId,
+ filename,
+ settledJobId,
+ (d) => d.compositeSheets,
+ (d, compositeSheets) => ({ ...d, compositeSheets }),
+ );
+ }, [settleEntryJob]);
+
return (
<div className="flex flex-col h-full">
<section className="flex-1 flex flex-col gap-3 p-4 min-h-0 overflow-y-auto">
@@ -459,6 +482,9 @@ export default function UniverseBuilder() {
onChange={updateCompositeSheets}
canRender={canRender}
onRender={(sheet) => runRender({ promptMode: 'sheets', sheetSelection: [sheet.label] })}
+ onPreview={openPreviewByFilename}
+ pendingByEntryId={pendingHeadByEntryId}
+ onJobSettled={handleSheetJobSettled}
/>
{/* Add-bucket row stays available here for power users who want to
introduce a brand-new custom bucket without going through
diff --git a/client/src/hooks/useRenderJobQueue.js b/client/src/hooks/useRenderJobQueue.js
index 9963a50c7f..f5823f8d1e 100644
--- a/client/src/hooks/useRenderJobQueue.js
+++ b/client/src/hooks/useRenderJobQueue.js
@@ -49,18 +49,18 @@ export function useRenderJobQueue() {
});
}, []);
- // Append freshly-queued jobs to their per-entry queues. Each `entryJobs`
- // item is `{ jobId, entryRef: { id, kind } }`; only `variation` / `canon`
- // kinds have per-row pending UI, so sheet (and other) kinds are skipped —
- // otherwise their jobIds would accumulate forever with no consumer to clear
- // them.
+ // Append freshly-queued jobs to their per-entry queues. Each `entryJobs` item
+ // is `{ jobId, entryRef: { id, kind } }`. Kind-agnostic on purpose: every kind
+ // the server stamps an entryRef for (`ENTRY_REF_KIND` — variation, sheet,
+ // canon) now renders a row that settles its own job, so an allowlist here
+ // would only ever fail closed on a kind added later — silently no spinner, no
+ // error — instead of failing visibly.
const enqueueEntryJobs = useCallback((entryJobs) => {
if (!Array.isArray(entryJobs) || entryJobs.length === 0) return;
setPendingByEntryId((prev) => {
const next = { ...prev };
for (const { jobId, entryRef } of entryJobs) {
if (!jobId || !entryRef?.id) continue;
- if (entryRef.kind !== 'variation' && entryRef.kind !== 'canon') continue;
const existing = Array.isArray(next[entryRef.id]) ? next[entryRef.id] : [];
next[entryRef.id] = [...existing, jobId];
}
diff --git a/client/src/hooks/useRenderJobQueue.test.jsx b/client/src/hooks/useRenderJobQueue.test.jsx
index 4dbdf40bff..cffe145888 100644
--- a/client/src/hooks/useRenderJobQueue.test.jsx
+++ b/client/src/hooks/useRenderJobQueue.test.jsx
@@ -9,19 +9,21 @@ describe('useRenderJobQueue', () => {
expect(result.current.pendingHeadByEntryId).toEqual({});
});
- it('enqueues variation and canon jobs, skipping other kinds', () => {
+ it('enqueues every entryRef kind the server stamps, keyed by entry id', () => {
const { result } = renderHook(() => useRenderJobQueue());
act(() => {
result.current.enqueueEntryJobs([
{ jobId: 'j1', entryRef: { id: 'a', kind: 'variation' } },
{ jobId: 'j2', entryRef: { id: 'b', kind: 'canon' } },
+ // Composite boards render an EntryThumbSlot too, so their jobs are
+ // tracked and settled the same way.
{ jobId: 'j3', entryRef: { id: 'c', kind: 'sheet' } },
{ jobId: 'j4', entryRef: { id: 'a', kind: 'variation' } },
]);
});
- expect(result.current.pendingByEntryId).toEqual({ a: ['j1', 'j4'], b: ['j2'] });
+ expect(result.current.pendingByEntryId).toEqual({ a: ['j1', 'j4'], b: ['j2'], c: ['j3'] });
// Head map exposes only the first jobId per entry.
- expect(result.current.pendingHeadByEntryId).toEqual({ a: 'j1', b: 'j2' });
+ expect(result.current.pendingHeadByEntryId).toEqual({ a: 'j1', b: 'j2', c: 'j3' });
});
it('ignores malformed entries and no-ops on empty input', () => {
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 02263c0cde..94e45c5176 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -36,7 +36,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `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. |
| `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback; `computeDragSpan({kind, startSpan, deltaSec, gridPoints, ...})` resolves a timeline drag gesture (`'move'` or `'right'` — no `'left'`, since the render can only trim from a clip's own frame 0) into a new span; `shouldMarkBeatAligned({kind, snapped, wasPersisted})` gates the `beatAligned` flag so a reposition-only drag can't silently promote an unpersisted scene's placeholder fallback duration into a "saved exactly" render duration; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.jsx`. |
-| `bibleLimits.js` | Mirror of `server/lib/storyBible.js` `BIBLE_LIMITS`. |
+| `bibleLimits.js` | Mirror of `server/lib/storyBible.js` `BIBLE_LIMITS`, plus `capImageRefs` / `appendImageRefById` for the optimistic imageRefs-append paths. |
| `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. |
| `creativeDirectorPlan.js` | Pure presentation helpers for the CD studio Plan board (CDO Phase 4) — annotate `plan.steps[]` with tool cost-class/timing/approval flags, cost/status summaries, owning-surface deep links, status/cost badge tone maps. |
| `creativeDirectorPreview.js` | `selectProjectPreview(project)` → `{ kind: 'video'\|'image'\|'audio'\|'none', jobId?, src?, poster?, label, durationSec? }` — picks a CD project's representative produced asset (finalVideoId → last rendered scene → last done plan video/image step → `musicBed` audio → startingImageFile) for the list cards + Overview tab (#2702, audio #2772). Pure, computed off the already-returned project payload (no fetch). Plus `previewAspectClass(aspectRatio)` (literal Tailwind classes — a computed `aspect-[w/h]` never lands in the build), `startingImageSrc()` (client mirror of `localImageFilename`), and the `videoSrcForJob`/`videoPosterForJob`/`imageSrcForJob`/`musicBedSrc` path builders — the one client-side definition of the `<jobId>`-named asset convention, shared with `ScenePreview.jsx`. |
diff --git a/client/src/lib/bibleLimits.js b/client/src/lib/bibleLimits.js
index 7ef9c5b953..0dccd96347 100644
--- a/client/src/lib/bibleLimits.js
+++ b/client/src/lib/bibleLimits.js
@@ -103,3 +103,24 @@ export const capImageRefs = (refs) => (
? refs.slice(-BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX)
: refs
);
+
+// Optimistic client mirror of the server's `mapAppendImageRef` (see
+// `server/services/universeBuilder/crud.js`): append `filename` to the
+// id-matched entry's imageRefs[], deduped and capped. The server's completion
+// hook has already made this durable — this only swaps the row from spinner to
+// thumbnail without waiting for the next refetch, so it returns the SAME array
+// and entry references when nothing changed (unknown id, or the ref is already
+// there) and callers can hand the result straight to setState without forcing a
+// re-render. Non-array input returns `null` so a caller can bail on its update.
+export const appendImageRefById = (entries, id, filename) => {
+ if (!Array.isArray(entries) || !id || !filename) return null;
+ let changed = false;
+ const next = entries.map((entry) => {
+ if (entry?.id !== id) return entry;
+ const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : [];
+ if (refs.includes(filename)) return entry;
+ changed = true;
+ return { ...entry, imageRefs: capImageRefs([...refs, filename]) };
+ });
+ return changed ? next : entries;
+};
diff --git a/client/src/lib/bibleLimits.test.js b/client/src/lib/bibleLimits.test.js
index b1db42b7cb..2aba1e35a7 100644
--- a/client/src/lib/bibleLimits.test.js
+++ b/client/src/lib/bibleLimits.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { BIBLE_LIMITS, capImageRefs } from './bibleLimits.js';
+import { BIBLE_LIMITS, appendImageRefById, capImageRefs } from './bibleLimits.js';
describe('capImageRefs', () => {
it('returns the list unchanged when at or under the cap', () => {
@@ -16,3 +16,36 @@ describe('capImageRefs', () => {
expect(capped[capped.length - 1]).toBe(`r${max + 2}.png`);
});
});
+
+describe('appendImageRefById', () => {
+ it('appends the filename to the id-matched entry only', () => {
+ const entries = [{ id: 'a', imageRefs: ['old.png'] }, { id: 'b' }];
+ const next = appendImageRefById(entries, 'b', 'new.png');
+ expect(next).toEqual([{ id: 'a', imageRefs: ['old.png'] }, { id: 'b', imageRefs: ['new.png'] }]);
+ expect(next[0]).toBe(entries[0]); // untouched entries keep their reference
+ });
+
+ it('caps the appended list to the per-entry maximum', () => {
+ const max = BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX;
+ const imageRefs = Array.from({ length: max }, (_, i) => `r${i}.png`);
+ const [entry] = appendImageRefById([{ id: 'a', imageRefs }], 'a', 'new.png');
+ expect(entry.imageRefs).toHaveLength(max);
+ expect(entry.imageRefs[max - 1]).toBe('new.png');
+ expect(entry.imageRefs).not.toContain('r0.png');
+ });
+
+ // The same array back is the caller's signal that no re-render is needed —
+ // the completion bridge can fire more than once for one job, and the server's
+ // durable append may already be reflected in a refetched draft.
+ it('returns the same array when the ref is already present or the id is unknown', () => {
+ const entries = [{ id: 'a', imageRefs: ['dup.png'] }];
+ expect(appendImageRefById(entries, 'a', 'dup.png')).toBe(entries);
+ expect(appendImageRefById(entries, 'nope', 'new.png')).toBe(entries);
+ });
+
+ it('returns null when there is no list, id, or filename to work with', () => {
+ expect(appendImageRefById(undefined, 'a', 'new.png')).toBeNull();
+ expect(appendImageRefById([{ id: 'a' }], null, 'new.png')).toBeNull();
+ expect(appendImageRefById([{ id: 'a' }], 'a', null)).toBeNull();
+ });
+});