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
Give Casting, Environments and Objects records Sheets, Plates and References tabs (#11948)
[._.]/381dce6b234d
diff --git a/client/src/App.jsx b/client/src/App.jsxindex d788c1dc41..56c154b881 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -610,11 +610,11 @@ export default function App() {<Route path="catalog/:type/:id" element={<CatalogIngredient />} /><Route path="casting" element={<CreativeLibrary key="casting" libraryId="casting" />} /><Route path="casting/import" element={<CreativeCastImport />} />- <Route path="casting/:id" element={<CatalogIngredient />} />+ <Route path="casting/:id/:tab?" element={<CatalogIngredient />} /><Route path="environments" element={<CreativeLibrary key="environments" libraryId="environments" />} />- <Route path="environments/:id" element={<CatalogIngredient />} />+ <Route path="environments/:id/:tab?" element={<CatalogIngredient />} /><Route path="objects" element={<CreativeLibrary key="objects" libraryId="objects" />} />- <Route path="objects/:id" element={<CatalogIngredient />} />+ <Route path="objects/:id/:tab?" element={<CatalogIngredient />} /><Route path="code-animation" element={<CodeAnimation />} /><Route path="code-animation/:jobId" element={<CodeAnimation />} /><Route path="code-animation/production" element={<CodeAnimation />} />diff --git a/client/src/components/catalog/CatalogMediaTile.jsx b/client/src/components/catalog/CatalogMediaTile.jsxnew file mode 100644index 0000000000..8554f0e8a6--- /dev/null+++ b/client/src/components/catalog/CatalogMediaTile.jsx@@ -0,0 +1,76 @@+import { Mic, Star, X } from 'lucide-react';+import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';+import MediaImage from '../MediaImage';++// One catalog media attachment tile. Images render via <MediaImage> (which+// shows a "syncing" placeholder when the asset hasn't arrived — the same+// surface the `missing` integrity flag warns about). Audio/video render inline+// players (bytes served from /data/audio and /data/videos); a voice memo's+// transcript rides in `caption`. Other kinds render a labeled chip.+// `onSetPortrait` is optional (sheet tiles omit it); `extraActions` adds+// tab-specific buttons (Plates' mark/unmark) to the hover action row, and+// `label` captions the tile (a sheet's variant); `contain` shows a wide image+// (a sheet) whole instead of a square crop.+export default function CatalogMediaTile({+ m, missing, isPortrait = false, onSetPortrait, onDetach, armedDetach, onArmDetach, extraActions = null, label = null, contain = false,+}) {+ const isImage = m.kind === 'portrait' || m.kind === 'reference';+ const isAudio = m.kind === 'audio';+ const isVideo = m.kind === 'video';+ const tileKey = `${m.mediaKey}:${m.kind}`;+ return (+ <div className="relative group rounded border border-port-border overflow-hidden bg-port-bg">+ {isImage && (+ <MediaImage src={`/data/images/${m.mediaKey}`} alt={label || m.caption || m.kind}+ className={contain ? 'w-full object-contain max-h-[420px]' : isPortrait ? 'w-full max-w-[180px] aspect-square object-cover' : 'w-full aspect-square object-cover'} />+ )}+ {isAudio && (+ <div className="p-2 flex flex-col gap-1">+ <div className="text-[10px] uppercase tracking-wider text-gray-400 flex items-center gap-1">+ <Mic size={10} aria-hidden="true" /> {m.role === 'voice-memo' ? 'voice memo' : 'audio'}+ </div>+ <audio controls preload="none" src={`/data/audio/${m.mediaKey}`} className="w-full" />+ {m.caption && <p className="text-[11px] text-gray-300 whitespace-pre-wrap line-clamp-4">{m.caption}</p>}+ </div>+ )}+ {isVideo && (+ <video controls preload="none" src={`/data/videos/${m.mediaKey}`} className="w-full aspect-square object-cover bg-black" />+ )}+ {!isImage && !isAudio && !isVideo && (+ <div className="w-full aspect-square flex items-center justify-center text-[10px] uppercase tracking-wider text-gray-400 px-1 text-center break-all">+ {m.kind}<br />{m.mediaKey}+ </div>+ )}+ {label && (+ <div className="text-[10px] uppercase tracking-wider text-gray-500 px-2 py-1 border-t border-port-border truncate">{label}</div>+ )}+ {missing && (+ <span className="absolute top-1 left-1 text-[9px] px-1 py-0.5 rounded bg-port-warning/20 text-port-warning border border-port-warning/40"+ title="This asset isn't in your media library yet (received from a peer before the file arrived).">+ missing+ </span>+ )}+ <div className="port-media-overlay absolute top-1 right-1 flex gap-1 rounded opacity-100 sm:opacity-0 sm:group-hover:opacity-100 focus-within:opacity-100 transition-opacity">+ {extraActions}+ {!isPortrait && isImage && onSetPortrait && (+ <button type="button" onClick={() => onSetPortrait(m.mediaKey)} title="Set as portrait" aria-label="Set as portrait"+ className="port-media-overlay-item p-2 sm:p-1 rounded hover:text-port-warning">+ <Star size={12} aria-hidden="true" />+ </button>+ )}+ {onDetach && (armedDetach === tileKey ? (+ <ConfirmButtonPair prompt="Detach?" confirmText="Detach" cancelText="Cancel"+ ariaLabel="Confirm media detach" onConfirm={() => {+ onArmDetach(null);+ onDetach(m.mediaKey, m.kind);+ }} onCancel={() => onArmDetach(null)} largeTouchTargets />+ ) : (+ <button type="button" onClick={() => onArmDetach(tileKey)} title="Detach" aria-label="Detach"+ className="port-media-overlay-item p-2 sm:p-1 rounded hover:text-port-error">+ <X size={12} aria-hidden="true" />+ </button>+ ))}+ </div>+ </div>+ );+}diff --git a/client/src/components/catalog/CatalogPlatesPanel.jsx b/client/src/components/catalog/CatalogPlatesPanel.jsxnew file mode 100644index 0000000000..57748cd305--- /dev/null+++ b/client/src/components/catalog/CatalogPlatesPanel.jsx@@ -0,0 +1,65 @@+import { useState } from 'react';+import { Clapperboard, Loader2, Pin, PinOff } from 'lucide-react';+import CatalogMediaTile from './CatalogMediaTile';++// The Plates tab for an environment: set plates are reference images whose+// catalog media role is `plate`. Marking/unmarking re-attaches the same media+// key with a new role (the attach endpoint upserts role on the existing row),+// via `onSetRole(media, role)` which resolves true on success.+export default function CatalogPlatesPanel({ plates, candidates, missingMedia, onSetRole, onDetach }) {+ const [armedDetach, setArmedDetach] = useState(null);+ const [busyKey, setBusyKey] = useState(null);+ const plateList = Array.isArray(plates) ? plates : [];+ const candidateList = Array.isArray(candidates) ? candidates : [];++ const setRole = async (m, role) => {+ if (busyKey) return;+ setBusyKey(m.mediaKey);+ await onSetRole(m, role);+ setBusyKey(null);+ };++ const roleButton = (m, role, label, Icon) => (+ <button type="button" onClick={() => setRole(m, role)} disabled={!!busyKey}+ title={label} aria-label={label}+ className="port-media-overlay-item p-2 sm:p-1 rounded hover:text-port-accent disabled:opacity-50">+ {busyKey === m.mediaKey+ ? <Loader2 size={12} className="animate-spin" aria-hidden="true" />+ : <Icon size={12} aria-hidden="true" />}+ </button>+ );++ return (+ <section className="bg-port-card border border-port-border rounded-lg p-4 space-y-4">+ <div>+ <h2 className="text-sm font-semibold text-white flex items-center gap-1.5 mb-3">+ <Clapperboard size={14} aria-hidden="true" /> Set plates+ </h2>+ {plateList.length > 0 ? (+ <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">+ {plateList.map((m) => (+ <CatalogMediaTile key={`${m.mediaKey}:${m.kind}`} m={m} missing={missingMedia?.has?.(m.mediaKey)}+ onDetach={onDetach} armedDetach={armedDetach} onArmDetach={setArmedDetach}+ extraActions={roleButton(m, null, 'Unmark plate', PinOff)} />+ ))}+ </div>+ ) : (+ <p className="text-xs text-gray-500">No plates yet. Mark a reference image below as a plate.</p>+ )}+ </div>+ <div>+ <h3 className="text-xs uppercase tracking-wider text-gray-500 mb-2">Mark a reference image as a plate</h3>+ {candidateList.length > 0 ? (+ <div className="grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-6 gap-2">+ {candidateList.map((m) => (+ <CatalogMediaTile key={`${m.mediaKey}:${m.kind}`} m={m} missing={missingMedia?.has?.(m.mediaKey)}+ extraActions={roleButton(m, 'plate', 'Mark as plate', Pin)} />+ ))}+ </div>+ ) : (+ <p className="text-xs text-gray-500">No reference images to mark. Attach or generate some on the References tab.</p>+ )}+ </div>+ </section>+ );+}diff --git a/client/src/components/catalog/CatalogSheetsPanel.jsx b/client/src/components/catalog/CatalogSheetsPanel.jsxnew file mode 100644index 0000000000..c594d861ff--- /dev/null+++ b/client/src/components/catalog/CatalogSheetsPanel.jsx@@ -0,0 +1,246 @@+import { useCallback, useEffect, useState } from 'react';+import { Link } from 'react-router';+import { ExternalLink, Image as ImageIcon, Loader2, Sparkles } from 'lucide-react';+import toast from '../ui/Toast';+import MediaImage from '../MediaImage';+import MediaJobThumb from '../pipeline/MediaJobThumb';+import ModelInputPreview from '../media/ModelInputPreview';+import CatalogMediaTile from './CatalogMediaTile';+import socket from '../../services/socket';+import useMounted from '../../hooks/useMounted';+import { useModelInputPreview } from '../../hooks/useModelInputPreview';+import { LEGACY_SHEET_VARIANT_ID, readSheetPointer, listSheetPointers } from '../../lib/sheetPointers.js';+import { SHEET_ROLE_PREFIX } from '../../lib/creativeLibraries';+import { listCatalogSheetVariants, previewCatalogSheet, renderCatalogSheet } from '../../services/apiCatalog';++// Universe-canon sheets live on the payload as pointers into /data/image-refs.+// `[variant, filename]` pairs, with the legacy pointer de-duplicated against a+// named variant that carries the same file.+export function pointerSheetsOf(payload) {+ const legacy = readSheetPointer(payload, LEGACY_SHEET_VARIANT_ID);+ return listSheetPointers(payload)+ .filter(({ filename }, index) => typeof filename === 'string'+ && (index === 0 && legacy || filename !== legacy))+ .map(({ variant, filename }) => [variant, filename]);+}++const universeCanonPath = (universeRef) => (universeRef?.refId+ ? `/universes/${encodeURIComponent(universeRef.refId)}#canon`+ : null);++function PointerSheetFigure({ variant, filename }) {+ return (+ <figure className="rounded border border-port-border overflow-hidden bg-port-bg">+ <MediaImage src={`/data/image-refs/${filename}`} alt={`${variant} reference sheet`}+ className="w-full object-contain max-h-[420px]" />+ <figcaption className="text-[10px] uppercase tracking-wider text-gray-500 px-2 py-1 border-t border-port-border">+ {variant}+ </figcaption>+ </figure>+ );+}++// The untabbed (/catalog/character/:id) read-only view of a character's+// universe sheets, with a deep-link to the Universe Builder canon section+// (`#canon`, the anchor its hash-scroll resolves).+export function ReferenceSheetPanel({ payload, universeRef }) {+ const variants = pointerSheetsOf(payload);+ const hasSheet = variants.length > 0;+ const universePath = universeCanonPath(universeRef);+ return (+ <section className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center justify-between gap-2 mb-3 flex-wrap">+ <h2 className="text-sm font-semibold text-white flex items-center gap-1.5">+ <ImageIcon size={14} aria-hidden="true" /> Reference sheet+ </h2>+ {universePath && (+ <Link to={universePath}+ className="inline-flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded border border-port-border text-gray-300 hover:text-white hover:border-port-accent">+ <Sparkles size={12} aria-hidden="true" />+ {hasSheet ? 'Re-render in Universe Builder' : 'Render in Universe Builder'}+ <ExternalLink size={11} aria-hidden="true" />+ </Link>+ )}+ </div>+ {hasSheet ? (+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ {variants.map(([variant, filename]) => <PointerSheetFigure key={variant} variant={variant} filename={filename} />)}+ </div>+ ) : (+ <p className="text-xs text-gray-500">+ No reference sheet rendered yet.+ {universePath+ ? ' Render one from the linked universe (it carries the style data the renderer needs).'+ : ' Link this character to a universe to render a reference sheet from its style data.'}+ </p>+ )}+ </section>+ );+}++const SHEET_EVENT = 'reference-sheet:changed';++// The Sheets tab: universe pointer sheets plus `sheet:<variant>` catalog+// media, a variant picker, the server's preview of exactly what the render+// sends, and Generate. The render reads the SAVED record, so Generate is gated+// by `blockedReason` while the profile has unsaved edits or a save is running.+// A catalog-only render completes through MediaJobThumb (job socket events)+// and is attached optimistically via `onSheetFile` (the server hook is+// idempotent); a universe-linked character's render delegates to the canon+// renderer and lands as a payload pointer, announced by `reference-sheet:changed`.+export default function CatalogSheetsPanel({+ ingredientId, payload, universeRef, sheetMedia, missingMedia, onDetach,+ blockedReason = null, savedStamp = null, onSheetFile, onPointerSheetReady,+}) {+ const mountedRef = useMounted();+ const [variants, setVariants] = useState(null);+ const [variantsError, setVariantsError] = useState(null);+ const [variantId, setVariantId] = useState('');+ const [starting, setStarting] = useState(false);+ const [pending, setPending] = useState(null); // { jobId, role, delegated }+ const [armedDetach, setArmedDetach] = useState(null);++ useEffect(() => {+ let active = true;+ setVariants(null);+ setVariantsError(null);+ listCatalogSheetVariants(ingredientId, { silent: true })+ .then((r) => {+ if (!active) return;+ const list = Array.isArray(r?.variants) ? r.variants : [];+ setVariants(list);+ setVariantId((cur) => (list.some((v) => v.id === cur) ? cur : list[0]?.id || ''));+ })+ .catch((err) => {+ if (!active) return;+ setVariants([]);+ setVariantsError(err?.message || 'Failed to load sheet kinds');+ });+ return () => { active = false; };+ }, [ingredientId]);++ // `savedStamp` rides in the body only to re-run the preview after a save+ // (the server builds it from the saved record); it is stripped before the call.+ const fetchPreview = useCallback(({ savedStamp: _stamp, ...body }, options) =>+ previewCatalogSheet(ingredientId, body, options).then((r) => r?.preview ?? null), [ingredientId]);+ const preview = useModelInputPreview(fetchPreview, { variant: variantId, savedStamp }, { enabled: !!variantId });++ const jobId = pending?.jobId || null;+ const delegated = !!pending?.delegated;+ useEffect(() => {+ if (!jobId || !delegated) return undefined;+ const onChanged = (data) => {+ if (data?.jobId !== jobId) return;+ setPending(null);+ if (data.status === 'ready') onPointerSheetReady?.();+ else if (data.status === 'failed') toast.error('Sheet render finished but the sheet could not be saved');+ };+ socket.on(SHEET_EVENT, onChanged);+ return () => { socket.off(SHEET_EVENT, onChanged); };+ }, [jobId, delegated, onPointerSheetReady]);++ const role = pending?.role;+ const handleFilename = useCallback((filename) => {+ if (!filename || delegated) return;+ setPending(null);+ onSheetFile?.(filename, role);+ }, [delegated, role, onSheetFile]);++ const handleStatus = useCallback((status) => {+ if (status !== 'failed' && status !== 'canceled') return;+ setPending(null);+ if (status === 'failed') toast.error('Sheet render failed');+ }, []);++ const variant = (variants || []).find((v) => v.id === variantId) || null;++ const handleGenerate = async () => {+ if (!variant || blockedReason) return;+ setStarting(true);+ const queued = await renderCatalogSheet(ingredientId, { variant: variant.id }, { silent: true })+ .catch((err) => { toast.error(err?.message || 'Sheet render failed'); return null; });+ if (!mountedRef.current) return;+ setStarting(false);+ if (!queued?.jobId) {+ if (queued) toast.error('Sheet render returned no job');+ return;+ }+ setPending({+ jobId: queued.jobId,+ role: queued.role || `${SHEET_ROLE_PREFIX}${queued.variant || variant.id}`,+ delegated: queued.delegatedTo === 'universe',+ });+ toast.success(queued.delegatedTo === 'universe'+ ? `Rendering ${variant.label} on the linked universe…`+ : `Rendering ${variant.label}…`);+ };++ const pointerSheets = pointerSheetsOf(payload);+ const sheets = Array.isArray(sheetMedia) ? sheetMedia : [];+ const labelFor = (m) => {+ const id = (m.role || '').slice(SHEET_ROLE_PREFIX.length);+ return (variants || []).find((v) => v.id === id)?.label || id;+ };+ const universePath = universeCanonPath(universeRef);+ const busy = starting || !!jobId;++ return (+ <section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <h2 className="text-sm font-semibold text-white flex items-center gap-1.5">+ <ImageIcon size={14} aria-hidden="true" /> Reference sheets+ </h2>+ {universePath && (+ <Link to={universePath}+ className="inline-flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded border border-port-border text-gray-300 hover:text-white hover:border-port-accent">+ Universe canon <ExternalLink size={11} aria-hidden="true" />+ </Link>+ )}+ </div>++ {variants === null ? (+ <p className="text-xs text-gray-500 inline-flex items-center gap-1"><Loader2 size={12} className="animate-spin" aria-hidden="true" /> Loading sheet kinds…</p>+ ) : variants.length === 0 ? (+ <p className="text-xs text-gray-500">{variantsError || 'This record type has no reference sheet kinds.'}</p>+ ) : (+ <div className="space-y-2">+ <div className="flex items-end gap-2 flex-wrap">+ <div className="min-w-0 flex-1 max-w-sm">+ <label htmlFor="catalog-sheet-variant" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Sheet kind</label>+ <select id="catalog-sheet-variant" value={variantId} onChange={(e) => setVariantId(e.target.value)} disabled={busy}+ className="w-full px-2 py-2 bg-port-bg border border-port-border rounded text-sm text-white focus:outline-none focus:border-port-accent">+ {variants.map((v) => <option key={v.id} value={v.id}>{v.label}</option>)}+ </select>+ </div>+ <button type="button" onClick={handleGenerate} disabled={busy || !!blockedReason || !variant}+ title={blockedReason || undefined}+ className="inline-flex items-center gap-1.5 min-h-[40px] px-3 py-2 rounded bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium">+ {busy ? <Loader2 size={14} className="animate-spin" aria-hidden="true" /> : <Sparkles size={14} aria-hidden="true" />}+ {jobId ? 'Rendering…' : 'Generate sheet'}+ </button>+ {jobId && (+ <MediaJobThumb jobId={jobId} label="Reference sheet" size="xs"+ onFilename={handleFilename} onStatus={handleStatus} />+ )}+ </div>+ {variant?.description && <p className="text-xs text-gray-400">{variant.description}</p>}+ {blockedReason && <p className="text-xs text-port-warning" role="status">{blockedReason}</p>}+ <ModelInputPreview preview={preview} prompt="" />+ </div>+ )}++ {pointerSheets.length > 0 || sheets.length > 0 ? (+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ {pointerSheets.map(([v, filename]) => <PointerSheetFigure key={`ptr:${v}`} variant={v} filename={filename} />)}+ {sheets.map((m) => (+ <CatalogMediaTile key={`${m.mediaKey}:${m.kind}`} m={m} label={labelFor(m)} contain+ missing={missingMedia?.has?.(m.mediaKey)} onDetach={onDetach}+ armedDetach={armedDetach} onArmDetach={setArmedDetach} />+ ))}+ </div>+ ) : (+ <p className="text-xs text-gray-500">No reference sheets yet.</p>+ )}+ </section>+ );+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 364438965e..f95878adf1 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -84,7 +84,7 @@ grep -i "what you want to do" client/src/lib/README.md| `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`. || `creativeDirectorStatus.js` | `describeCreativeDirectorStatus(project, { activeAgents, activeTab })` → `{ headline, tone, facts, next }` — the one "where it stands, what's next" status line for a CD project (stage in words, whether it waits on the user, a single `start`/`resume`/`edit-draft`/`goto`/`open-final` next action). Pure; rendered by `components/ui/RecordStatusLine`. |-| `creativeLibraries.js` | `CREATIVE_LIBRARIES` — the Casting / Environments / Objects pages as views over the catalog's character / place / object ingredients, with `libraryById` / `libraryForType` / `libraryForPathname`, `ingredientPath(ingredient)` (library detail route, else `/catalog/:type/:id`), `ingredientCoverUrl(ingredient)` (attached media, else the canon starred/first render, both under `/data/images`) and `usageSummary(usage)` ("1 universe · 2 videos" from the list endpoint's link counts). |+| `creativeLibraries.js` | `CREATIVE_LIBRARIES` — the Casting / Environments / Objects pages as views over the catalog's character / place / object ingredients, with `libraryById` / `libraryForType` / `libraryForPathname`, `ingredientPath(ingredient)` (library detail route, else `/catalog/:type/:id`), `ingredientCoverUrl(ingredient)` (attached media, else the canon starred/first render, both under `/data/images`) `usageSummary(usage)` ("1 universe · 2 videos" from the list endpoint's link counts), per-library `detailTabs` with `resolveDetailTab` / `detailTabPath` (record page sections at `/casting/:id/:tab`), and media-role predicates `isSheetMedia` / `isPlateMedia` / `isReferenceTabMedia` (`sheet:*`, `plate`, `look:*`). || `editorialRoadmap.js` | `projectAnalyzedPoints` (aggregate roadmap → analyzed chart points with arc-position `frac`) + `dominant` (most-frequent string). Shared by EditorialRoadmapPanel and the Reader Map page. || `federatedMediaReadiness.js` | One reading of a peer’s federated media-provider readiness (#4348), shared by the Instances peer card and the System Health capacity panel so the two cannot disagree. `resolvePeerMediaReadiness(peer, { now })` maps the stored probe onto a display state/label/tone plus its remedy text, queue snapshot, capabilities, and per-kind allowlists; it re-derives `stale` when the snapshot’s `freshUntil` has passed, so a snapshot probed as `ready` cannot keep reading `ready` after the server would refuse to submit against it. Also exports `FEDERATED_MEDIA_KINDS` (audio/image/video + their config fields and icons), the state/help tables, and `peerMediaProviderConfig`. `summarizePeerMediaQueue(queue)` renders the peer’s queue block into finished display segments — slot occupancy, how many jobs drain in parallel, and which kinds are busy — so every surface shows the same words, dropping any segment an older provider did not send rather than showing it as a zero. `federatedMediaModelsForPeer(peer, kind)` intersects the local per-kind allowlist with the peer’s advertised capabilities and returns the capability entries (with their `ready` / `unavailableReason`), so no surface can offer a model the server would refuse or hide why a listed one cannot run. `federatedMediaSupports(status, feature, capability)` mirrors the server helper of the same name and is the ONE place the "absent reads as false" rule lives on this side (#4826): it answers whether the peer’s BUILD speaks a wire feature (`lyrics`, `inputAssets`) from the status-root `features` list, retaining only the legacy `inputAssets` capability block for peers on the previous build because that signal is genuinely per-model, and `peerMediaProviderSnapshot(peer)` returns the status payload to ask it against. `peerModelAcceptsInput(capability, role, status)` / `peerModelRequiresInput(capability)` read the capability’s `inputAssets` block — which conditioning slots (`initImage` / `referenceImages` / `sourceImage` / `lastImage`) a peer model takes, and whether it can render without one — gated first on the build speaking conditioning at all, with **absent reading as NO**, so a provider predating that field is never offered a render it would reject. Display only — the server re-probes and fail-closes before any job leaves. || `fableLoomReadiness.js` | Ordered FableLoom readiness plus the twelve-stage producer workflow spanning foundation, challenges, outlines, editorial, continuity, media, and final hosting. |diff --git a/client/src/lib/creativeLibraries.js b/client/src/lib/creativeLibraries.jsindex 0afc4c734d..dddf589b11 100644--- a/client/src/lib/creativeLibraries.js+++ b/client/src/lib/creativeLibraries.js@@ -2,10 +2,25 @@// character, place and object ingredients. The catalog row stays the single// record; these entries only say which page owns a type and how to name it.+// `detailTabs` are the record page's sections (`/casting/:id/:tab`); the+// first is the default and an unknown tab falls back to it.+const tab = (id, label) => Object.freeze({ id, label });+const PROFILE = tab('profile', 'Profile');+const SHEETS = tab('sheets', 'Sheets');+export const CREATIVE_LIBRARIES = Object.freeze([- Object.freeze({ id: 'casting', type: 'character', path: '/casting', label: 'Casting', singular: 'cast member', empty: 'No cast yet.' }),- Object.freeze({ id: 'environments', type: 'place', path: '/environments', label: 'Environments', singular: 'environment', empty: 'No environments yet.' }),- Object.freeze({ id: 'objects', type: 'object', path: '/objects', label: 'Objects', singular: 'object', empty: 'No objects yet.' }),+ Object.freeze({+ id: 'casting', type: 'character', path: '/casting', label: 'Casting', singular: 'cast member', empty: 'No cast yet.',+ detailTabs: Object.freeze([PROFILE, SHEETS, tab('references', 'References')]),+ }),+ Object.freeze({+ id: 'environments', type: 'place', path: '/environments', label: 'Environments', singular: 'environment', empty: 'No environments yet.',+ detailTabs: Object.freeze([PROFILE, SHEETS, tab('plates', 'Plates'), tab('references', 'References')]),+ }),+ Object.freeze({+ id: 'objects', type: 'object', path: '/objects', label: 'Objects', singular: 'object', empty: 'No objects yet.',+ detailTabs: Object.freeze([PROFILE, SHEETS, tab('images', 'Images')]),+ }),]);export const libraryById = (id) => CREATIVE_LIBRARIES.find((lib) => lib.id === id) || null;@@ -23,6 +38,30 @@ export function ingredientPath(ingredient) {return lib ? `${lib.path}/${id}` : `/catalog/${encodeURIComponent(ingredient?.type || 'idea')}/${id}`;}+// The detail tab a `:tab` route param names, falling back to the first+// (Profile) for an absent or unknown one.+export function resolveDetailTab(library, tabParam) {+ const tabs = library?.detailTabs || [];+ return (tabs.find((t) => t.id === tabParam) || tabs[0] || null)?.id ?? null;+}++// Route for one tab of a library record; the default tab is the bare record path.+export function detailTabPath(library, id, tabId) {+ const base = `${library.path}/${encodeURIComponent(id || '')}`;+ return tabId && tabId !== library.detailTabs?.[0]?.id ? `${base}/${encodeURIComponent(tabId)}` : base;+}++// Catalog media roles that belong to their own tab rather than References:+// rendered sheets (`sheet:<variant>`), wardrobe looks (`look:<id>`) and set+// plates (`plate`).+export const SHEET_ROLE_PREFIX = 'sheet:';+export const LOOK_ROLE_PREFIX = 'look:';+export const PLATE_ROLE = 'plate';+const roleOf = (m) => (typeof m?.role === 'string' ? m.role : '');+export const isSheetMedia = (m) => roleOf(m).startsWith(SHEET_ROLE_PREFIX);+export const isPlateMedia = (m) => roleOf(m) === PLATE_ROLE;+export const isReferenceTabMedia = (m) => !isSheetMedia(m) && !isPlateMedia(m) && !roleOf(m).startsWith(LOOK_ROLE_PREFIX);+// Cover image for a card. Attached catalog media wins; canon-mirrored rows fall// back to the universe's starred or first render. Both are gallery files under// /data/images (only canon reference sheets live under /data/image-refs).diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsxindex 7344be08c2..cc268bafe2 100644--- a/client/src/pages/CatalogIngredient.jsx+++ b/client/src/pages/CatalogIngredient.jsx@@ -1,14 +1,15 @@-import { LEGACY_SHEET_VARIANT_ID, readSheetPointer, listSheetPointers } from '../lib/sheetPointers.js';/*** CatalogIngredient — detail/editor for a single catalog ingredient. Loaded- * via /catalog/:type/:id; the type from the loaded record is the source of- * truth. Side panels surface source scraps and inbound refs (universes /- * pipeline series / issues / writers-room). Full-width page; owns its scroll.+ * via /catalog/:type/:id (one untabbed scroll) or a library route+ * (/casting/:id/:tab?, /environments/…, /objects/…) where the library's+ * `detailTabs` split it into Profile / Sheets / Plates / References|Images.+ * The tab lives in the URL; form state lives here so switching tabs keeps an+ * unsaved draft. Full-width page; owns its scroll.*/import { useCallback, useEffect, useRef, useState } from 'react';import { useNavigate, useParams, useLocation, Link } from 'react-router';-import { Sparkles, Save, Trash2, ArrowLeft, Loader2, ExternalLink, Plus, X, History, RotateCcw, Image as ImageIcon, Star, ChevronDown, Upload, Mic, Square } from 'lucide-react';+import { Sparkles, Save, Trash2, ArrowLeft, Loader2, Plus, X, History, RotateCcw, Image as ImageIcon, ChevronDown, Upload, Mic, Square, UserRound, LayoutGrid, Images, Clapperboard } from 'lucide-react';import toast from '../components/ui/Toast';import FilePickerButton from '../components/ui/FilePickerButton';import Modal from '../components/ui/Modal.jsx';@@ -16,6 +17,7 @@ import ConfirmButtonPair from '../components/ui/ConfirmButtonPair.jsx';import UnsavedChangesConfirm from '../components/ui/UnsavedChangesConfirm.jsx';import AutoSizeTextarea from '../components/ui/AutoSizeTextarea';import PageSkeleton from '../components/ui/PageSkeleton';+import TabPills from '../components/ui/TabPills';import {getCatalogIngredientDetails,updateCatalogIngredient,@@ -36,7 +38,11 @@ import { arrayBufferToBase64 } from '../lib/audioRecorder';import useMemoRecorder from '../hooks/useMemoRecorder';import { useGalleryPage } from '../hooks/useGalleryPage';import { generateImage } from '../services/apiSystem';-import { composeCanonStyledPrompt } from '../lib/composeStyledPrompt';+import { previewImagePrompt } from '../services/apiImageVideo';+import { composeStyledPrompt, stylePromptAdditions } from '../lib/composeStyledPrompt';+import { universeStylePreset, withUniverseLabel } from '../lib/universeStylePreset';+import { useModelInputPreview } from '../hooks/useModelInputPreview';+import ModelInputPreview from '../components/media/ModelInputPreview';import { threadRefLabel, threadRefUrl } from '../lib/threadRefKinds.js';import ThreadRefChip from '../components/brain/ThreadRefChip';import AddToThreadButton from '../components/threads/AddToThreadButton';@@ -45,12 +51,18 @@ import useMounted from '../hooks/useMounted';import MediaJobThumb from '../components/pipeline/MediaJobThumb';import IngredientPicker from '../components/IngredientPicker';import MediaImage from '../components/MediaImage';+import CatalogMediaTile from '../components/catalog/CatalogMediaTile';+import CatalogSheetsPanel, { ReferenceSheetPanel } from '../components/catalog/CatalogSheetsPanel';+import CatalogPlatesPanel from '../components/catalog/CatalogPlatesPanel';import CharacterLoraChip from '../components/loraTraining/CharacterLoraChip';import TagPicker from '../components/TagPicker';import GenericIngredientFields from '../components/GenericIngredientFields';import useUnsavedChangesGuard from '../hooks/useUnsavedChangesGuard';import { getCatalogType, CATALOG_BADGE_BY_ID, RELATION_KINDS, getRelationKind } from '../lib/catalogTypes';-import { libraryForPathname, ingredientPath } from '../lib/creativeLibraries';+import {+ libraryForPathname, ingredientPath, resolveDetailTab, detailTabPath,+ isSheetMedia, isPlateMedia, isReferenceTabMedia,+} from '../lib/creativeLibraries';import { useCatalogTypes } from '../hooks/useCatalogTypes.jsx';import { timeAgo, formatDateTime } from '../utils/formatters';@@ -109,6 +121,18 @@ export function buildGenerationPromptSeed(payload, typeDef, tags = []) {// Compare JSON-shaped editor values by value while ignoring object-key order.// A catalog payload can arrive from a peer with the same fields in a different// order; that is not an edit the user needs to save.+const DETAIL_TAB_ICONS = {+ profile: UserRound,+ sheets: LayoutGrid,+ plates: Clapperboard,+ references: Images,+ images: ImageIcon,+};++// Payload fields the universe sheet renderer writes (via the canon→catalog+// projection); see lib/sheetPointers.js.+const SHEET_POINTER_KEYS = ['referenceSheetImageRef', 'referenceSheets'];+function stableSerialize(value) {return JSON.stringify(value, (_key, current) => {if (!current || typeof current !== 'object' || Array.isArray(current)) return current;@@ -128,7 +152,7 @@ function ingredientPayload(value) {}export default function CatalogIngredient() {- const { id } = useParams();+ const { id, tab: tabParam } = useParams();const activeVisitRef = useRef({ id, generation: 0 });if (activeVisitRef.current.id !== id) {activeVisitRef.current = { id, generation: activeVisitRef.current.generation + 1 };@@ -137,7 +161,8 @@ export default function CatalogIngredient() {// Opened from Casting / Environments / Objects → Back and post-delete return// there; otherwise to the catalog.const { pathname } = useLocation();- const backPath = libraryForPathname(pathname)?.path || '/catalog';+ const library = libraryForPathname(pathname);+ const backPath = library?.path || '/catalog';// Merged type registry (system + user-defined). Falls back synchronously to// the static built-ins so the editor renders before the fetch resolves.const { getType: getMergedType } = useCatalogTypes();@@ -341,6 +366,60 @@ export default function CatalogIngredient() {toast.success('Voice memo attached');}, [record, refreshMedia]);+ // Re-attach an existing media row under a new role (mark/unmark a plate).+ // The attach endpoint upserts role/caption on the (ingredient, key, kind)+ // row, so the caption is passed back unchanged.+ const handleSetMediaRole = useCallback(async (m, role) => {+ if (!record || !m?.mediaKey) return false;+ const updated = await attachCatalogIngredientMedia(+ record.id,+ { mediaKey: m.mediaKey, kind: m.kind, role, caption: m.caption ?? null },+ { silent: true },+ ).catch((err) => { toast.error(err?.message || 'Failed to update media'); return null; });+ if (!updated) return false;+ setMedia((prev) => prev.map((row) => (+ row.mediaKey === m.mediaKey && row.kind === m.kind ? { ...row, ...updated, role } : row+ )));+ toast.success(role ? 'Marked as plate' : 'Plate unmarked');+ return true;+ }, [record]);++ // A finished catalog-only sheet render: attach it under its `sheet:<variant>`+ // role right away (the server-side attach hook files the same row and is+ // idempotent against this), then reconcile the media list.+ const handleSheetFile = useCallback(async (filename, role) => {+ if (!record || !filename) return;+ const ok = await attachCatalogIngredientMedia(record.id, { mediaKey: filename, kind: 'reference', role }, { silent: true })+ .then(() => true)+ .catch((err) => { toast.error(err?.message || 'Failed to attach the rendered sheet'); return false; });+ refreshMedia();+ if (ok) toast.success('Reference sheet ready');+ }, [record, refreshMedia]);++ // A universe-delegated sheet landed as a canon pointer, which the canon→catalog+ // projection already copied onto this row. Pull just the pointer fields into+ // both the saved record and the draft, so an unsaved edit stays intact and+ // stays exactly as dirty as it was.+ const refreshSheetPointers = useCallback(() => {+ if (!id) return;+ const requestedId = id;+ getCatalogIngredientDetails(id, { silent: true })+ .then((d) => {+ if (activeVisitRef.current.id !== requestedId || !d?.ingredient) return;+ const fresh = ingredientPayload(d.ingredient.payload);+ const pointers = {};+ for (const key of SHEET_POINTER_KEYS) {+ if (Object.hasOwn(fresh, key)) pointers[key] = fresh[key];+ }+ setRecord((prev) => (prev?.id === requestedId+ ? { ...prev, payload: { ...ingredientPayload(prev.payload), ...pointers } }+ : prev));+ setPayload((cur) => ({ ...cur, ...pointers }));+ toast.success('Reference sheet ready');+ })+ .catch(() => { toast.error('Reference sheet rendered — reload to see it'); });+ }, [id]);+const handleSave = async () => {if (!record) return;const submittedId = record.id;@@ -421,7 +500,11 @@ export default function CatalogIngredient() {|| !sameValue(tags, Array.isArray(record.tags) ? record.tags : [])|| !sameValue(payload, ingredientPayload(record.payload))));- const routeGuard = useUnsavedChangesGuard(isDirty);+ // Tab switches within this record change the pathname but not the editor;+ // scope the guard to the record so only a real exit asks to discard.+ const routeGuard = useUnsavedChangesGuard(isDirty, {+ scopePath: library ? `${library.path}/${encodeURIComponent(id || '')}` : undefined,+ });const discardAndExit = useCallback(() => {// The parked route is leaving, so unmounting discards the local draft. Do// not clear isDirty before proceeding: the shared guard auto-proceeds when@@ -477,6 +560,15 @@ export default function CatalogIngredient() {// canon entry of any universe.const universeRef = (refsByKind.universe || [])[0] || null;+ // Library routes split the page into the library's tabs; the plain+ // /catalog/:type/:id route (and a record opened under the wrong library)+ // keeps the single untabbed scroll, which renders as the 'profile' tab plus+ // its media panel.+ const tabs = library && library.type === record.type+ ? library.detailTabs.map((t) => ({ ...t, icon: DETAIL_TAB_ICONS[t.id] }))+ : null;+ const activeTab = tabs ? resolveDetailTab(library, tabParam) : 'profile';+return (<section className="h-full overflow-y-auto p-4 md:p-6"><UnsavedChangesConfirm@@ -505,7 +597,7 @@ export default function CatalogIngredient() {<p className="text-xs text-gray-500 mt-1 font-mono">{record.id}</p></div></div>- <div className="flex items-center gap-2">+ <div className="flex items-center gap-2 flex-wrap"><Link to={backPath} className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm text-gray-400 hover:text-white"><ArrowLeft size={14} aria-hidden="true" /> Back</Link>@@ -545,88 +637,133 @@ export default function CatalogIngredient() {</div></header>- <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6 space-y-4">- <div>- <label htmlFor="ingredient-name" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Name</label>- <input id="ingredient-name" type="text" value={name} onChange={(e) => setName(e.target.value)} maxLength={200}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent" />- </div>- <div>- <label htmlFor="ingredient-tags" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">- Tags- </label>- <TagPicker id="ingredient-tags" value={tags} onChange={setTags}- placeholder="mentor, antagonist, season-1" />- </div>- {isUserType- ? <GenericIngredientFields fields={fields} payload={payload} onChange={updatePayload} />- : sections- ? sections.map((section) => (- <SheetSection key={section.title} title={section.title}- fields={section.fields} payload={payload} onChange={updatePayload} />- ))- : fields.map(([key, label, kind]) => (- <SheetField key={key} fieldKey={key} label={label} kind={kind}- value={payload[key] ?? ''} onChange={updatePayload} />- ))}-- {/* Structured array-field editors (aliases / color palette / stats).- Driven by the type's registry-declared `editableListFields`; the- same durable catalog row the Universe Builder canon surface edits.- Light/user types declare none and skip this entirely. */}- {!isUserType && Array.isArray(typeDef.editableListFields) && typeDef.editableListFields.length > 0 && (- <EditableListFields fields={typeDef.editableListFields} payload={payload} onChange={updatePayload} />- )}- </div>+ {tabs && (+ <TabPills+ tabs={tabs}+ activeTab={activeTab}+ onChange={(tabId) => navigate(detailTabPath(library, record.id, tabId))}+ mobileCompact+ ariaLabel={`${library.label} record sections`}+ />+ )}- {record.type === 'character' && (+ {activeTab === 'profile' && (<>- <ReferenceSheetPanel payload={payload} universeRef={universeRef} />- {/* Trained-LoRA link + dataset entry point. The catalog id IS the- ingredientId the trained sidecars carry; the universe entryId- isn't known on this surface, so the chip links an existing- dataset rather than offering find-or-create. */}- <div className="bg-port-card border border-port-border rounded-lg p-4">- <div className="text-xs uppercase tracking-wider text-gray-500 mb-2">Character LoRA</div>- <CharacterLoraChip ingredientId={record.id} />+ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6 space-y-4">+ <div>+ <label htmlFor="ingredient-name" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Name</label>+ <input id="ingredient-name" type="text" value={name} onChange={(e) => setName(e.target.value)} maxLength={200}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent" />+ </div>+ <div>+ <label htmlFor="ingredient-tags" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">+ Tags+ </label>+ <TagPicker id="ingredient-tags" value={tags} onChange={setTags}+ placeholder="mentor, antagonist, season-1" />+ </div>+ {isUserType+ ? <GenericIngredientFields fields={fields} payload={payload} onChange={updatePayload} />+ : sections+ ? sections.map((section) => (+ <SheetSection key={section.title} title={section.title}+ fields={section.fields} payload={payload} onChange={updatePayload} />+ ))+ : fields.map(([key, label, kind]) => (+ <SheetField key={key} fieldKey={key} label={label} kind={kind}+ value={payload[key] ?? ''} onChange={updatePayload} />+ ))}++ {/* Structured array-field editors (aliases / color palette / stats).+ Driven by the type's registry-declared `editableListFields`; the+ same durable catalog row the Universe Builder canon surface edits.+ Light/user types declare none and skip this entirely. */}+ {!isUserType && Array.isArray(typeDef.editableListFields) && typeDef.editableListFields.length > 0 && (+ <EditableListFields fields={typeDef.editableListFields} payload={payload} onChange={updatePayload} />+ )}+ </div>++ {record.type === 'character' && (+ <>+ {!tabs && <ReferenceSheetPanel payload={payload} universeRef={universeRef} />}+ {/* Trained-LoRA link + dataset entry point. The catalog id IS the+ ingredientId the trained sidecars carry; the universe entryId+ isn't known on this surface, so the chip links an existing+ dataset rather than offering find-or-create. */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="text-xs uppercase tracking-wider text-gray-500 mb-2">Character LoRA</div>+ <CharacterLoraChip ingredientId={record.id} />+ </div>+ </>+ )}++ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">+ <SourcesPanel sources={record.sources} evidence={payload?.evidence} />+ <RefsPanel refsByKind={refsByKind} /></div>++ <RelationsPanel+ record={record}+ relations={relations}+ evidence={payload?.evidence}+ onAdd={handleAddRelation}+ onRemove={handleRemoveRelation}+ /></>)}- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- <SourcesPanel sources={record.sources} evidence={payload?.evidence} />- <RefsPanel refsByKind={refsByKind} />- </div>+ {activeTab === 'sheets' && (+ <CatalogSheetsPanel+ ingredientId={record.id}+ payload={payload}+ universeRef={universeRef}+ sheetMedia={media.filter(isSheetMedia)}+ missingMedia={missingMedia}+ onDetach={handleDetachMedia}+ blockedReason={saving+ ? 'Saving — the sheet renders from the saved record.'+ : isDirty ? 'Save your profile edits first — the sheet renders from the saved record.' : null}+ savedStamp={record.updatedAt || null}+ onSheetFile={handleSheetFile}+ onPointerSheetReady={refreshSheetPointers}+ />+ )}- <RelationsPanel- record={record}- relations={relations}- evidence={payload?.evidence}- onAdd={handleAddRelation}- onRemove={handleRemoveRelation}- />+ {activeTab === 'plates' && (+ <CatalogPlatesPanel+ plates={media.filter(isPlateMedia)}+ candidates={media.filter((m) => m.kind === 'reference' && isReferenceTabMedia(m))}+ missingMedia={missingMedia}+ onSetRole={handleSetMediaRole}+ onDetach={handleDetachMedia}+ />+ )}- <MediaPanel- media={media}- missingMedia={missingMedia}- onAttach={handleAttachMedia}- onSetPortrait={handleSetPortrait}- onDetach={handleDetachMedia}- onUploadFile={handleUploadFile}- onRecordVoice={handleRecordVoiceMemo}- genIngredientId={record.id}- genName={name}- genDescription={genDescription}- genUniverseId={universeRef?.refId || null}- onGenerated={handleGeneratedImage}- />+ {(activeTab === 'profile' ? !tabs : activeTab === 'references' || activeTab === 'images') && (+ <MediaPanel+ media={tabs ? media.filter(isReferenceTabMedia) : media}+ missingMedia={missingMedia}+ onAttach={handleAttachMedia}+ onSetPortrait={handleSetPortrait}+ onDetach={handleDetachMedia}+ onUploadFile={handleUploadFile}+ onRecordVoice={handleRecordVoiceMemo}+ genIngredientId={record.id}+ genName={name}+ genDescription={genDescription}+ genUniverseId={universeRef?.refId || null}+ onGenerated={handleGeneratedImage}+ />+ )}- <RevisionsPanel- revisions={revisions}- current={record}- fields={fields}- onRestore={handleRestore}- />+ {activeTab === 'profile' && (+ <RevisionsPanel+ revisions={revisions}+ current={record}+ fields={fields}+ onRestore={handleRestore}+ />+ )}</div></section>);@@ -832,71 +969,6 @@ function StatListEditor({ field, value, onChange }) {);}-// "Reference sheet" panel — shows the rendered character turnaround sheet when-// one exists (payload.referenceSheetImageRef / referenceSheets[]), served from-// the /data/image-refs/ static prefix. When no sheet exists but the character-// belongs to a universe, surfaces a deep-link to render one on the Universe-// Builder surface, which carries the universe's full style data (styleNotes,-// influences, palette, render settings) the renderer needs. Rendering inline-// here would duplicate that heavy pipeline — the deep-link keeps one render-// path. The link targets the universe's `#canon` section (the anchor the-// Universe Builder hash-scroll resolves).-function ReferenceSheetPanel({ payload, universeRef }) {- const legacy = readSheetPointer(payload, LEGACY_SHEET_VARIANT_ID);- // De-dup: the legacy pointer can duplicate a named variant's filename.- const variants = listSheetPointers(payload)- .filter(({ filename }, index) => typeof filename === 'string'- && (index === 0 && legacy || filename !== legacy))- .map(({ variant, filename }) => [variant, filename]);- const hasSheet = variants.length > 0;-- // Deep-link to the universe's canon section (`id="canon"`, the one anchor the- // Universe Builder hash-scroll handler resolves) — a per-character anchor- // isn't rendered there, so #canon lands the user on the canon surface where- // the character + its render controls live.- const universePath = universeRef?.refId- ? `/universes/${encodeURIComponent(universeRef.refId)}#canon`- : null;-- return (- <section className="bg-port-card border border-port-border rounded-lg p-4">- <div className="flex items-center justify-between gap-2 mb-3 flex-wrap">- <h2 className="text-sm font-semibold text-white flex items-center gap-1.5">- <ImageIcon size={14} aria-hidden="true" /> Reference sheet- </h2>- {universePath && (- <Link to={universePath}- className="inline-flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded border border-port-border text-gray-300 hover:text-white hover:border-port-accent">- <Sparkles size={12} aria-hidden="true" />- {hasSheet ? 'Re-render in Universe Builder' : 'Render in Universe Builder'}- <ExternalLink size={11} aria-hidden="true" />- </Link>- )}- </div>- {hasSheet ? (- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">- {variants.map(([variant, filename]) => (- <figure key={variant} className="rounded border border-port-border overflow-hidden bg-port-bg">- <MediaImage src={`/data/image-refs/${filename}`} alt={`${variant} reference sheet`}- className="w-full object-contain max-h-[420px]" />- <figcaption className="text-[10px] uppercase tracking-wider text-gray-500 px-2 py-1 border-t border-port-border">- {variant}- </figcaption>- </figure>- ))}- </div>- ) : (- <p className="text-xs text-gray-500">- No reference sheet rendered yet.- {universePath- ? ' Render one from the linked universe (it carries the style data the renderer needs).'- : ' Link this character to a universe to render a reference sheet from its style data.'}- </p>- )}- </section>- );-}-// "Relations" panel — ingredient↔ingredient edges. Outbound edges (this// ingredient → other) are user-editable here; inbound edges (other → this// ingredient) are read-only because the owning ingredient is the other end.@@ -1061,35 +1133,53 @@ function GenerateImageControl({ ingredientId, name, description, universeId, onCconst [prompt, setPrompt] = useState('');const [negativePrompt, setNegativePrompt] = useState('');- // Open the editor and prefill the prompt with the composed default: the- // ingredient's visual seed + tags, layered on the linked universe's style- // preset (fetched lazily — the page deliberately doesn't load the universe up- // front). A failed/missing universe just omits the preset; the seed still- // renders. Don't clobber a prompt the user already edited (re-open keeps it).+ // The linked universe's style preset travels BESIDE the prompt box, never in+ // it (#11317): the box holds only the record's own words, the preset becomes+ // a labeled "Universe style" addition, and the preview below shows the exact+ // composed text the server will send. Fetched lazily on first open — the+ // page deliberately doesn't load the universe up front; a failed/missing+ // universe just omits the preset.+ const [universe, setUniverse] = useState(null);+ const universeRequestedRef = useRef(false);++ // Open the editor and prefill the prompt with the record's own seed:+ // "<name>: <visual description + tags>", with a dangling "Name:" trimmed when+ // there is no description yet. Don't clobber a prompt the user already+ // edited (re-open keeps it).const openEditor = async () => {setEditing(true);- if (prompt.trim()) return; // keep prior edits when re-opening- setPrefilling(true);- let universe = null;- if (universeId) {- universe = await getUniverse(universeId, { silent: true }).catch(() => null);+ if (!prompt.trim()) {+ const seed = `${name || 'Subject'}: ${description || ''}`.replace(/:\s*$/, '');+ setPrompt(seed);}- const styled = composeCanonStyledPrompt({- name: name || 'Subject',- description: description || '',- universe,- });+ if (!universeId || universeRequestedRef.current) return;+ universeRequestedRef.current = true;+ setPrefilling(true);+ const loaded = await getUniverse(universeId, { silent: true }).catch(() => null);if (!mountedRef.current) return;- // The textarea is editable during the (awaited) universe fetch, so the user- // may have started typing before it resolved — apply the composed prefill- // only when the field is still empty, via a functional updater that reads- // the latest state (the closure's `prompt` is stale across the await).- // Trim a dangling "Name:" when the ingredient had no visual description yet.- setPrompt((cur) => (cur.trim() ? cur : (styled.prompt || name || '').replace(/:\s*$/, '')));- setNegativePrompt((cur) => (cur.trim() ? cur : (styled.negativePrompt || '')));+ setUniverse(loaded || null);setPrefilling(false);};+ // One request body for both the preview and Generate, so what the preview+ // shows is what the render sends: the user's words composed with the+ // universe preset (the same shared composer the Image Gen page uses), with+ // the preset declared as `promptAdditions` so the server records/labels it.+ const stylePreset = universe ? withUniverseLabel(universeStylePreset(universe)) : null;+ const buildRequest = (userPrompt, userNegative) => {+ const composed = composeStyledPrompt(userPrompt, userNegative, stylePreset);+ const additions = stylePromptAdditions(stylePreset);+ return {+ prompt: composed.prompt,+ negativePrompt: composed.negativePrompt || undefined,+ ...(additions.length ? { promptAdditions: additions } : {}),+ };+ };+ const previewBody = buildRequest(prompt.trim(), negativePrompt.trim());+ const modelInputPreview = useModelInputPreview(previewImagePrompt, previewBody, {+ enabled: editing && !prefilling && prompt.trim().length > 0,+ });+const handleRender = async () => {const finalPrompt = prompt.trim();if (!finalPrompt) {@@ -1099,8 +1189,7 @@ function GenerateImageControl({ ingredientId, name, description, universeId, onCsetStarting(true);const queued = await generateImage({- prompt: finalPrompt,- negativePrompt: negativePrompt.trim() || undefined,+ ...buildRequest(finalPrompt, negativePrompt.trim()),// Durable attach (#1359): tag the queued job with the target ingredient// so the server-side completion hook files the render even if this page// unmounts before a long local/Codex render finishes. The onComplete@@ -1171,7 +1260,7 @@ function GenerateImageControl({ ingredientId, name, description, universeId, onC)}{editing && (- <div className="absolute right-0 z-20 mt-2 w-80 max-w-[90vw] rounded-lg border border-port-border bg-port-card p-3 shadow-xl space-y-2"+ <div className="absolute right-0 z-20 mt-2 w-80 max-w-[calc(100vw-1rem)] max-h-[80vh] overflow-y-auto rounded-lg border border-port-border bg-port-card p-3 shadow-xl space-y-2"style={{ top: '100%' }}><div className="flex items-center justify-between"><span className="text-xs font-semibold text-white">Generate image</span>@@ -1198,6 +1287,7 @@ function GenerateImageControl({ ingredientId, name, description, universeId, onCclassName="mt-1 w-full text-xs bg-port-bg border border-port-border rounded px-2 py-1 text-gray-200 min-h-[44px]"/></label>+ <ModelInputPreview preview={modelInputPreview} prompt={prompt} /><div className="flex items-center justify-end gap-2 pt-1"><button type="button" onClick={() => setEditing(false)}className="text-xs px-2 py-1 rounded border border-port-border text-gray-400 hover:text-white">@@ -1317,7 +1407,7 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, on{portrait && (<div className="mb-3"><div className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">Portrait</div>- <MediaTile m={portrait} missing={missingMedia.has(portrait.mediaKey)} isPortrait+ <CatalogMediaTile m={portrait} missing={missingMedia.has(portrait.mediaKey)} isPortraitonSetPortrait={onSetPortrait} onDetach={onDetach} armedDetach={armedDetach}onArmDetach={setArmedDetach} /></div>@@ -1326,7 +1416,7 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, on{others.length > 0 && (<div className="grid grid-cols-2 sm:grid-cols-3 gap-2">{others.map((m) => (- <MediaTile key={`${m.mediaKey}:${m.kind}`} m={m} missing={missingMedia.has(m.mediaKey)}+ <CatalogMediaTile key={`${m.mediaKey}:${m.kind}`} m={m} missing={missingMedia.has(m.mediaKey)}onSetPortrait={onSetPortrait} onDetach={onDetach} armedDetach={armedDetach}onArmDetach={setArmedDetach} />))}@@ -1351,68 +1441,6 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, on);}-// One media attachment tile. Images render via <MediaImage> (gracefully shows a-// "syncing" placeholder when the asset hasn't arrived — the same surface the-// `missing` integrity flag warns about). Audio/video render inline players-// (their bytes are served from /data/audio and /data/videos); a voice memo's-// transcript rides in `caption`. Other kinds render a labeled chip.-function MediaTile({ m, missing, isPortrait = false, onSetPortrait, onDetach, armedDetach, onArmDetach }) {- const isImage = m.kind === 'portrait' || m.kind === 'reference';- const isAudio = m.kind === 'audio';- const isVideo = m.kind === 'video';- return (- <div className="relative group rounded border border-port-border overflow-hidden bg-port-bg">- {isImage && (- <MediaImage src={`/data/images/${m.mediaKey}`} alt={m.caption || m.kind}- className={isPortrait ? 'w-full max-w-[180px] aspect-square object-cover' : 'w-full aspect-square object-cover'} />- )}- {isAudio && (- <div className="p-2 flex flex-col gap-1">- <div className="text-[10px] uppercase tracking-wider text-gray-400 flex items-center gap-1">- <Mic size={10} aria-hidden="true" /> {m.role === 'voice-memo' ? 'voice memo' : 'audio'}- </div>- <audio controls preload="none" src={`/data/audio/${m.mediaKey}`} className="w-full" />- {m.caption && <p className="text-[11px] text-gray-300 whitespace-pre-wrap line-clamp-4">{m.caption}</p>}- </div>- )}- {isVideo && (- <video controls preload="none" src={`/data/videos/${m.mediaKey}`} className="w-full aspect-square object-cover bg-black" />- )}- {!isImage && !isAudio && !isVideo && (- <div className="w-full aspect-square flex items-center justify-center text-[10px] uppercase tracking-wider text-gray-400 px-1 text-center">- {m.kind}<br />{m.mediaKey}- </div>- )}- {missing && (- <span className="absolute top-1 left-1 text-[9px] px-1 py-0.5 rounded bg-port-warning/20 text-port-warning border border-port-warning/40"- title="This asset isn't in your media library yet (received from a peer before the file arrived).">- missing- </span>- )}- <div className="absolute top-1 right-1 flex gap-1 opacity-100 sm:opacity-0 sm:group-hover:opacity-100 focus-within:opacity-100 transition-opacity">- {!isPortrait && isImage && (- <button type="button" onClick={() => onSetPortrait(m.mediaKey)} title="Set as portrait" aria-label="Set as portrait"- className="p-2 sm:p-1 rounded bg-black/60 text-gray-200 hover:text-port-warning">- <Star size={12} aria-hidden="true" />- </button>- )}- {armedDetach === `${m.mediaKey}:${m.kind}` ? (- <ConfirmButtonPair prompt="Detach?" confirmText="Detach" cancelText="Cancel"- ariaLabel="Confirm media detach" onConfirm={() => {- onArmDetach(null);- onDetach(m.mediaKey, m.kind);- }} onCancel={() => onArmDetach(null)} largeTouchTargets />- ) : (- <button type="button" onClick={() => onArmDetach(`${m.mediaKey}:${m.kind}`)} title="Detach" aria-label="Detach"- className="p-2 sm:p-1 rounded bg-black/60 text-gray-200 hover:text-port-error">- <X size={12} aria-hidden="true" />- </button>- )}- </div>- </div>- );-}-// Modal that lists the existing media gallery (history) so the user can attach// or set-portrait from already-generated assets — the "scoped to existing media// history" requirement. Never uploads; it only references library keys.diff --git a/client/src/pages/CatalogIngredient.test.jsx b/client/src/pages/CatalogIngredient.test.jsxindex 820b02102a..e9fd510081 100644--- a/client/src/pages/CatalogIngredient.test.jsx+++ b/client/src/pages/CatalogIngredient.test.jsx@@ -70,6 +70,17 @@ vi.mock('../services/apiCatalog', () => ({attachCatalogIngredientMedia: vi.fn(),setCatalogIngredientPortrait: vi.fn(),detachCatalogIngredientMedia: vi.fn(),+ listCatalogSheetVariants: vi.fn(async () => ({ variants: [] })),+ previewCatalogSheet: vi.fn(async () => ({ preview: null })),+ renderCatalogSheet: vi.fn(),+}));+// Universe-delegated sheet renders announce completion on this broadcast.+const { socketHandlers } = vi.hoisted(() => ({ socketHandlers: new Map() }));+vi.mock('../services/socket', () => ({+ default: {+ on: (event, fn) => socketHandlers.set(event, fn),+ off: (event) => socketHandlers.delete(event),+ },}));vi.mock('../services/apiSystem', () => ({ generateImage: vi.fn() }));@@ -96,7 +107,15 @@ vi.mock('../components/pipeline/MediaJobThumb', async () => {}return { default: MockMediaJobThumb };});-vi.mock('../services/apiImageVideo', () => ({ listImageGalleryPage: vi.fn(async () => ({ items: [], total: 0, offset: 0, limit: 60 })) }));+vi.mock('../services/apiImageVideo', () => ({+ listImageGalleryPage: vi.fn(async () => ({ items: [], total: 0, offset: 0, limit: 60 })),+ // Echo the request as the "sent" prompt, with its declared additions as chips.+ previewImagePrompt: vi.fn(async (body) => ({+ sentPrompt: body.prompt,+ ...(body.negativePrompt ? { sentNegativePrompt: body.negativePrompt } : {}),+ promptAdditions: body.promptAdditions || [],+ })),+}));vi.mock('../components/IngredientPicker', () => ({ default: () => null }));vi.mock('../components/MediaImage', () => ({ default: ({ src, alt }) => <img src={src} alt={alt} /> }));vi.mock('../components/loraTraining/CharacterLoraChip', () => ({ default: () => null }));@@ -122,6 +141,9 @@ const renderPage = async (path = '/catalog/character/cat-chr-1') => {const router = createMemoryRouter([{ path: '/catalog', element: <div>Catalog index</div> },{ path: '/catalog/:type/:id', element: <CatalogIngredient /> },+ { path: '/casting', element: <div>Casting index</div> },+ { path: '/casting/:id/:tab?', element: <CatalogIngredient /> },+ { path: '/environments/:id/:tab?', element: <CatalogIngredient /> },], { initialEntries: [path] });const result = render(<RouterProvider router={router} />);await act(async () => {});@@ -601,10 +623,10 @@ describe('CatalogIngredient — character sheet', () => {await waitFor(() => expect(screen.queryByDisplayValue('she/her')).toBeNull());});- // The universe style-preset layering is the headline "stays on-model" feature- // — pin that the linked universe is fetched by its refId and its embrace/avoid- // tokens reach the composed prompt + negative, not just the null path.- it('layers the linked universe style preset onto the composed prompt and negative', async () => {+ // #11317: the box holds only the record's own words. The linked universe's+ // style rides beside it as a labeled addition, the preview shows the exact+ // composed text, and the render sends that same composed request.+ it('keeps the universe style out of the prompt box and sends it as a labeled addition', async () => {const { getUniverse } = await import('../services/apiUniverseBuilder');const { generateImage } = await import('../services/apiSystem');getUniverse.mockResolvedValue({@@ -618,19 +640,22 @@ describe('CatalogIngredient — character sheet', () => {fireEvent.click(screen.getByRole('button', { name: /^Generate$/i }));const promptBox = await screen.findByPlaceholderText(/Describe the image to render/i);- // Preset embrace tokens prepend the subject prompt (diffusion weights earliest- // tokens heaviest) — see composeStyledPrompt.- await waitFor(() => expect(promptBox.value).toMatch(/neon noir/));- expect(promptBox.value).toMatch(/Ada Lovelace/);// Fetched by the ingredient's universe refId, silently (no error toast).expect(getUniverse).toHaveBeenCalledWith('u-1', { silent: true });+ // The preview names the universe style as a chip once the universe loads.+ fireEvent.click(await screen.findByRole('button', { name: '+ Universe style' }));+ expect(screen.getByText(/neon noir, rain-slick streets/)).toBeTruthy();+ expect(screen.getByRole('button', { name: '+ Style negatives' })).toBeTruthy();+ // The editable prompt is only the record's own seed — no preset tokens.+ expect(promptBox.value).toBe('Ada Lovelace: Sharp eyes, ink-stained cuffs.. mentor, My Cool Universe');+ expect(screen.getByLabelText(/Negative prompt/).value).toBe('');fireEvent.click(screen.getByRole('button', { name: /^Render$/i }));await waitFor(() => expect(generateImage).toHaveBeenCalled());const [payload] = generateImage.mock.calls[0];- expect(payload.prompt).toMatch(/neon noir/);- // Universe avoid tokens become the render's negative prompt.+ expect(payload.prompt).toMatch(/^neon noir, rain-slick streets\. Ada Lovelace: Sharp eyes/);expect(payload.negativePrompt).toMatch(/cartoon/);+ expect(payload.promptAdditions.map((addition) => addition.label)).toEqual(['Universe style', 'Style negatives']);getUniverse.mockResolvedValue(null); // restore default for any later test});@@ -714,6 +739,176 @@ describe('CatalogIngredient — character sheet', () => {});});+describe('CatalogIngredient — tabbed library record pages', () => {+ const HERO = {+ id: 'cat-chr-hero',+ type: 'character',+ name: 'Example Hero',+ tags: [],+ payload: {+ physicalDescription: 'Tall, green cloak.',+ referenceSheetImageRef: 'hero-standard.png',+ referenceSheets: { expressions: 'hero-expressions.png' },+ },+ refs: [{ refKind: 'universe', refId: 'u-example', refName: 'Example Universe' }],+ sources: [],+ };+ const MEDIA = [+ { mediaKey: 'portrait.png', kind: 'portrait', role: null },+ { mediaKey: 'mood.png', kind: 'reference', role: null },+ { mediaKey: 'sheet-1.png', kind: 'reference', role: 'sheet:standard' },+ { mediaKey: 'plate-1.png', kind: 'reference', role: 'plate' },+ { mediaKey: 'look-1.png', kind: 'reference', role: 'look:wardrobe-1' },+ ];+ const SHEET_VARIANTS = [+ { id: 'standard', label: 'Standard turnaround', description: 'Front, side and back views.' },+ { id: 'expressions', label: 'Expression sheet', description: 'Six expressions.' },+ ];++ beforeEach(async () => {+ const api = await import('../services/apiCatalog');+ getCatalogIngredientDetails.mockImplementation(async () => ({ ...detailsOf(HERO), media: MEDIA }));+ api.listCatalogSheetVariants.mockImplementation(async () => ({ variants: SHEET_VARIANTS }));+ api.previewCatalogSheet.mockImplementation(async (_id, body) => ({+ preview: {+ sentPrompt: `Example style. ${body.variant} sheet of Example Hero`,+ promptAdditions: [{ id: 'universe-style', label: 'Universe style', text: 'Example style.' }],+ },+ }));+ api.renderCatalogSheet.mockReset();+ api.attachCatalogIngredientMedia.mockReset();+ socketHandlers.clear();+ });++ it('shows universe pointer sheets and sheet media on /casting/:id/sheets', async () => {+ await renderPage('/casting/cat-chr-hero/sheets');+ expect(await screen.findByRole('tab', { name: /Sheets/ })).toHaveAttribute('aria-selected', 'true');+ expect(screen.getByAltText('standard reference sheet').getAttribute('src')).toBe('/data/image-refs/hero-standard.png');+ expect(screen.getByAltText('expressions reference sheet').getAttribute('src')).toBe('/data/image-refs/hero-expressions.png');+ await waitFor(() => expect(screen.getByAltText('Standard turnaround').getAttribute('src')).toBe('/data/images/sheet-1.png'));+ // Sheets don't carry the profile form or the general media panel.+ expect(screen.queryByLabelText('Name')).toBeNull();+ expect(screen.queryByAltText('mood.png')).toBeNull();+ });++ it('previews the chosen variant and posts it on Generate, then attaches the finished sheet', async () => {+ const api = await import('../services/apiCatalog');+ api.renderCatalogSheet.mockResolvedValue({ jobId: 'sheet-job', variant: 'expressions', role: 'sheet:expressions', delegatedTo: null });+ api.attachCatalogIngredientMedia.mockResolvedValue({});+ await renderPage('/casting/cat-chr-hero/sheets');++ fireEvent.change(await screen.findByLabelText('Sheet kind'), { target: { value: 'expressions' } });+ expect(screen.getByText('Six expressions.')).toBeTruthy();+ expect(await screen.findByRole('button', { name: '+ Universe style' })).toBeTruthy();+ await waitFor(() => expect(api.previewCatalogSheet).toHaveBeenLastCalledWith(+ 'cat-chr-hero', { variant: 'expressions' }, { silent: true },+ ));++ fireEvent.click(screen.getByRole('button', { name: /Generate sheet/ }));+ await waitFor(() => expect(api.renderCatalogSheet).toHaveBeenCalledWith(+ 'cat-chr-hero', { variant: 'expressions' }, { silent: true },+ ));+ expect(toast.success).toHaveBeenCalledWith('Rendering Expression sheet…');+ // The MediaJobThumb stub completes the job; the sheet attaches under its role.+ await waitFor(() => expect(api.attachCatalogIngredientMedia).toHaveBeenCalledWith(+ 'cat-chr-hero', { mediaKey: 'sheet-job.png', kind: 'reference', role: 'sheet:expressions' }, { silent: true },+ ));+ });++ it('refreshes canon pointers when a universe-delegated sheet is announced ready', async () => {+ const api = await import('../services/apiCatalog');+ api.renderCatalogSheet.mockResolvedValue({ jobId: 'canon-job', variant: 'standard', delegatedTo: 'universe' });+ await renderPage('/casting/cat-chr-hero/sheets');+ fireEvent.click(await screen.findByRole('button', { name: /Generate sheet/ }));+ await waitFor(() => expect(socketHandlers.has('reference-sheet:changed')).toBe(true));+ expect(api.attachCatalogIngredientMedia).not.toHaveBeenCalled();++ getCatalogIngredientDetails.mockImplementation(async () => ({+ ...detailsOf({ ...HERO, payload: { ...HERO.payload, referenceSheetImageRef: 'hero-standard-v2.png' } }),+ media: MEDIA,+ }));+ await act(async () => {+ socketHandlers.get('reference-sheet:changed')({ jobId: 'canon-job', status: 'ready' });+ });+ await waitFor(() => expect(screen.getByAltText('standard reference sheet').getAttribute('src'))+ .toBe('/data/image-refs/hero-standard-v2.png'));+ });++ it('keeps an unsaved name edit across tab switches without a discard prompt', async () => {+ const { router } = await renderPage('/casting/cat-chr-hero');+ const nameInput = await screen.findByLabelText('Name');+ fireEvent.change(nameInput, { target: { value: 'Example Hero Renamed' } });+ expect(screen.getByText('Unsaved changes')).toBeTruthy();++ await act(async () => { await router.navigate('/casting/cat-chr-hero/sheets'); });+ expect(router.state.location.pathname).toBe('/casting/cat-chr-hero/sheets');+ expect(screen.queryByText(/Discard your unsaved changes/)).toBeNull();+ // A dirty profile gates the render, which reads the saved record.+ expect(await screen.findByRole('button', { name: /Generate sheet/ })).toBeDisabled();++ await act(async () => { await router.navigate('/casting/cat-chr-hero'); });+ expect(screen.getByLabelText('Name').value).toBe('Example Hero Renamed');++ // Leaving the record is still guarded.+ await act(async () => { await router.navigate('/casting'); });+ expect(router.state.location.pathname).toBe('/casting/cat-chr-hero');+ });++ it('falls back to Profile for an unknown tab', async () => {+ await renderPage('/casting/cat-chr-hero/nonsense');+ expect(await screen.findByRole('tab', { name: /Profile/ })).toHaveAttribute('aria-selected', 'true');+ expect(screen.getByLabelText('Name').value).toBe('Example Hero');+ });++ it('lists only reference media on References (no sheets, plates, or looks)', async () => {+ await renderPage('/casting/cat-chr-hero/references');+ await waitFor(() => expect(screen.getByAltText('portrait')).toBeTruthy());+ const srcs = screen.getAllByRole('img').map((img) => img.getAttribute('src'));+ expect(srcs).toContain('/data/images/mood.png');+ expect(srcs).not.toContain('/data/images/sheet-1.png');+ expect(srcs).not.toContain('/data/images/plate-1.png');+ expect(srcs).not.toContain('/data/images/look-1.png');+ expect(screen.queryByLabelText('Name')).toBeNull();+ });++ it('marks a reference image as a plate on the environment Plates tab', async () => {+ const api = await import('../services/apiCatalog');+ api.attachCatalogIngredientMedia.mockResolvedValue({ mediaKey: 'mood.png', kind: 'reference', role: 'plate' });+ getCatalogIngredientDetails.mockImplementation(async () => ({+ ...detailsOf({ ...HERO, id: 'cat-plc-1', type: 'place', name: 'Example Harbor', payload: {}, refs: [] }),+ media: MEDIA,+ }));+ await renderPage('/environments/cat-plc-1/plates');+ expect(await screen.findByRole('button', { name: 'Unmark plate' })).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Mark as plate' }));+ await waitFor(() => expect(api.attachCatalogIngredientMedia).toHaveBeenCalledWith(+ 'cat-plc-1', { mediaKey: 'mood.png', kind: 'reference', role: 'plate', caption: null }, { silent: true },+ ));+ await waitFor(() => expect(screen.getAllByRole('button', { name: 'Unmark plate' })).toHaveLength(2));+ });++ it('keeps /catalog/:type/:id untabbed with every panel on one page', async () => {+ getCatalogIngredientDetails.mockImplementation(async () => ({+ ...detailsOf({ id: 'cat-idea-1', type: 'idea', name: 'Example Idea', tags: [], payload: {}, refs: [], sources: [] }),+ media: MEDIA,+ }));+ await renderPage('/catalog/idea/cat-idea-1');+ expect(await screen.findByLabelText('Name')).toBeTruthy();+ expect(screen.queryByRole('tablist')).toBeNull();+ expect(screen.getByRole('heading', { name: /Media/ })).toBeTruthy();+ expect(screen.getByRole('heading', { name: 'Relations' })).toBeTruthy();+ });++ it('prefills the image prompt with only the record\'s own words', async () => {+ getCatalogIngredientDetails.mockImplementation(async () => ({ ...detailsOf({ ...HERO, refs: [] }), media: [] }));+ await renderPage('/casting/cat-chr-hero/references');+ fireEvent.click(await screen.findByRole('button', { name: /^Generate$/i }));+ const promptBox = await screen.findByPlaceholderText(/Describe the image to render/i);+ expect(promptBox.value).toBe('Example Hero: Tall, green cloak.');+ expect(screen.getByLabelText(/Negative prompt/).value).toBe('');+ });+});+describe('buildGenerationPromptSeed', () => {const charType = { primaryContentKey: 'physicalDescription' };diff --git a/client/src/services/README.md b/client/src/services/README.mdindex ac24a38d28..8902b2d82f 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -59,7 +59,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiReferenceRepos.js` | Per-app reference-repo registry. || `apiReview.js` | Review hub. || `apiCodeReview.js` | Code Review Defaults (Review Loop reviewer chain + per-backend local-LLM model). |-| `apiCatalog.js` | Creative catalog ingredients (list/create/update/delete + `listCatalogIngredientsByIds` / facets) and scrap ingest (create/extract/commit + url/file/voice/brain). |+| `apiCatalog.js` | Creative catalog ingredients (list/create/update/delete + `listCatalogIngredientsByIds` / facets) scrap ingest (create/extract/commit + url/file/voice/brain), and reference sheets (`listCatalogSheetVariants` / `previewCatalogSheet` / `renderCatalogSheet`). || `apiCatalogTypes.js` | User-defined catalog ingredient types (list active registry + create/update/delete user types). || `apiRuns.js` | Agent run history. || `apiScaffold.js` | App scaffolding templates. |diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.jsindex 35fb32e8dd..68cf392b04 100644--- a/client/src/services/apiCatalog.js+++ b/client/src/services/apiCatalog.js@@ -191,6 +191,20 @@ export const uploadCatalogIngredientMediaFile = (id, body, options) =>export const recordCatalogIngredientVoiceMemo = (id, body, options) =>request(`/catalog/ingredients/${enc(id)}/media/voice`, { method: 'POST', body: JSON.stringify(body), ...options });+// --- Reference sheets ---------------------------------------------------+// Sheet kinds a record's type offers ({ variants: [{ id, label, description }] }),+// the exact prompt a render would send ({ preview: { sentPrompt, … } }), and the+// render itself ({ jobId, variant, delegatedTo }). `body` is { variant, ...overrides }.++export const listCatalogSheetVariants = (id, options) =>+ request(`/catalog/ingredients/${enc(id)}/sheets/variants`, options);++export const previewCatalogSheet = (id, body = {}, options) =>+ request(`/catalog/ingredients/${enc(id)}/sheets/preview`, { method: 'POST', body: JSON.stringify(body), ...options });++export const renderCatalogSheet = (id, body = {}, options) =>+ request(`/catalog/ingredients/${enc(id)}/sheets`, { method: 'POST', body: JSON.stringify(body), ...options });+// --- Bulk import / export ----------------------------------------------export const bulkImportCatalogIngredients = (body, options) =>