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

Give catalog characters a Looks tab for wardrobe images (#11961)

[._.]/bc91955d403f
diff --git a/client/src/components/catalog/CatalogLooksPanel.jsx b/client/src/components/catalog/CatalogLooksPanel.jsx
new file mode 100644
index 0000000000..176e23ec1d
--- /dev/null
+++ b/client/src/components/catalog/CatalogLooksPanel.jsx
@@ -0,0 +1,272 @@
+import { useCallback, useState } from 'react';
+import { ImagePlus, Loader2, Pencil, Pin, Plus, Shirt, Sparkles, Trash2, Undo2 } from 'lucide-react';
+import toast from '../ui/Toast';
+import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';
+import MediaJobThumb from '../pipeline/MediaJobThumb';
+import ModelInputPreview from '../media/ModelInputPreview';
+import CatalogMediaTile from './CatalogMediaTile';
+import useMounted from '../../hooks/useMounted';
+import { useModelInputPreview } from '../../hooks/useModelInputPreview';
+import { LOOK_ROLE_PREFIX, lookIdOf } from '../../lib/creativeLibraries';
+import { uuidv4 } from '../../lib/uuid';
+import { previewCatalogSheet, renderCatalogSheet } from '../../services/apiCatalog';
+
+// Mirrors BIBLE_LIMITS.WARDROBE_NAME_MAX / WARDROBE_DESCRIPTION_MAX.
+const NAME_MAX = 120;
+const DESCRIPTION_MAX = 800;
+
+const inputClass = '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';
+const smallButton = 'inline-flex items-center gap-1.5 min-h-[36px] px-2.5 py-1.5 rounded border border-port-border text-xs text-gray-300 hover:text-white hover:border-port-accent disabled:opacity-50 disabled:cursor-not-allowed';
+
+function LookForm({ formId, initial, busy, onSubmit, onCancel }) {
+ const [name, setName] = useState(initial?.name || '');
+ const [description, setDescription] = useState(initial?.description || '');
+ const submit = (e) => {
+ e.preventDefault();
+ if (!name.trim() || busy) return;
+ onSubmit({ name: name.trim(), description });
+ };
+ return (
+ <form onSubmit={submit} className="space-y-2 rounded border border-port-border bg-port-bg/40 p-3">
+ <div>
+ <label htmlFor={`${formId}-name`} className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Look name</label>
+ <input id={`${formId}-name`} type="text" value={name} maxLength={NAME_MAX} onChange={(e) => setName(e.target.value)}
+ placeholder="Travel coat" className={inputClass} />
+ </div>
+ <div>
+ <label htmlFor={`${formId}-description`} className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Outfit description</label>
+ <textarea id={`${formId}-description`} value={description} maxLength={DESCRIPTION_MAX} rows={3}
+ onChange={(e) => setDescription(e.target.value)}
+ placeholder="Long grey wool coat, red scarf, scuffed boots" className={inputClass} />
+ </div>
+ <div className="flex items-center gap-2 flex-wrap">
+ <button type="submit" disabled={busy || !name.trim()}
+ className="inline-flex items-center gap-1.5 min-h-[36px] px-3 py-1.5 rounded bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed text-white text-xs font-medium">
+ {busy && <Loader2 size={12} className="animate-spin" aria-hidden="true" />} Save look
+ </button>
+ <button type="button" onClick={onCancel} disabled={busy} className="px-3 py-1.5 text-xs text-gray-400 hover:text-white">Cancel</button>
+ </div>
+ </form>
+ );
+}
+
+// The server's preview of exactly what this look's render sends (prompt plus
+// labeled style/negative additions), then Render. Mounted only while open so
+// the preview is fetched on demand.
+function LookGenerate({ ingredientId, wardrobe, blockedReason, savedStamp, onLookFile, onClose }) {
+ const mountedRef = useMounted();
+ const [starting, setStarting] = useState(false);
+ const [pending, setPending] = useState(null); // { jobId, role }
+ const fetchPreview = useCallback(({ savedStamp: _stamp, ...body }, options) =>
+ previewCatalogSheet(ingredientId, body, options).then((r) => r?.preview ?? null), [ingredientId]);
+ const preview = useModelInputPreview(fetchPreview, { variant: 'look', wardrobeId: wardrobe.id, savedStamp });
+
+ const role = pending?.role;
+ const handleFilename = useCallback((filename) => {
+ if (!filename) return;
+ setPending(null);
+ onLookFile?.(filename, role);
+ }, [role, onLookFile]);
+ const handleStatus = useCallback((status) => {
+ if (status !== 'failed' && status !== 'canceled') return;
+ setPending(null);
+ if (status === 'failed') toast.error('Look render failed');
+ }, []);
+
+ const handleRender = async () => {
+ if (blockedReason) return;
+ setStarting(true);
+ const queued = await renderCatalogSheet(ingredientId, { variant: 'look', wardrobeId: wardrobe.id }, { silent: true })
+ .catch((err) => { toast.error(err?.message || 'Look render failed'); return null; });
+ if (!mountedRef.current) return;
+ setStarting(false);
+ if (!queued?.jobId) {
+ if (queued) toast.error('Look render returned no job');
+ return;
+ }
+ setPending({ jobId: queued.jobId, role: queued.role || `${LOOK_ROLE_PREFIX}${wardrobe.id}` });
+ toast.success(`Rendering ${wardrobe.name}…`);
+ };
+
+ const busy = starting || !!pending;
+ return (
+ <div className="space-y-2 rounded border border-port-border bg-port-bg/40 p-3">
+ <ModelInputPreview preview={preview} prompt="" />
+ {blockedReason && <p className="text-xs text-port-warning" role="status">{blockedReason}</p>}
+ <div className="flex items-center gap-2 flex-wrap">
+ <button type="button" onClick={handleRender} disabled={busy || !!blockedReason} title={blockedReason || undefined}
+ className="inline-flex items-center gap-1.5 min-h-[36px] px-3 py-1.5 rounded bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed text-white text-xs font-medium">
+ {busy ? <Loader2 size={12} className="animate-spin" aria-hidden="true" /> : <Sparkles size={12} aria-hidden="true" />}
+ {pending ? 'Rendering…' : 'Render look'}
+ </button>
+ {pending && (
+ <MediaJobThumb jobId={pending.jobId} label={`${wardrobe.name} look`} size="xs"
+ onFilename={handleFilename} onStatus={handleStatus} />
+ )}
+ {!busy && <button type="button" onClick={onClose} className="px-3 py-1.5 text-xs text-gray-400 hover:text-white">Close</button>}
+ </div>
+ </div>
+ );
+}
+
+function LookCard({
+ ingredientId, wardrobe, images, candidates, missingMedia, editLocked, savingList,
+ blockedReason, savedStamp, onSave, onDelete, onSetRole, onDetach, onLookFile,
+}) {
+ const [mode, setMode] = useState(null); // 'edit' | 'generate' | 'attach' | 'delete'
+ const [armedDetach, setArmedDetach] = useState(null);
+ const [busyKey, setBusyKey] = useState(null);
+ const toggle = (next) => setMode((cur) => (cur === next ? null : next));
+ const role = `${LOOK_ROLE_PREFIX}${wardrobe.id}`;
+
+ const setRole = async (m, nextRole, message) => {
+ if (busyKey) return;
+ setBusyKey(m.mediaKey);
+ const ok = await onSetRole(m, nextRole, message);
+ setBusyKey(null);
+ if (ok && nextRole) setMode(null);
+ };
+ const roleButton = (m, nextRole, label, message, Icon) => (
+ <button type="button" onClick={() => setRole(m, nextRole, message)} 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 (
+ <article className="rounded border border-port-border p-3 space-y-3" aria-label={`Look: ${wardrobe.name}`}>
+ <div className="flex items-start justify-between gap-2 flex-wrap">
+ <div className="min-w-0">
+ <h3 className="text-sm font-medium text-white break-words">{wardrobe.name}</h3>
+ {wardrobe.description && <p className="text-xs text-gray-400 whitespace-pre-wrap break-words mt-0.5">{wardrobe.description}</p>}
+ </div>
+ <div className="flex items-center gap-1.5 flex-wrap">
+ <button type="button" onClick={() => toggle('generate')} className={smallButton} aria-expanded={mode === 'generate'}>
+ <Sparkles size={12} aria-hidden="true" /> Generate
+ </button>
+ <button type="button" onClick={() => toggle('attach')} className={smallButton} aria-expanded={mode === 'attach'}>
+ <ImagePlus size={12} aria-hidden="true" /> Attach image
+ </button>
+ <button type="button" onClick={() => toggle('edit')} disabled={editLocked} className={smallButton}
+ aria-label={`Edit ${wardrobe.name}`} title="Edit">
+ <Pencil size={12} aria-hidden="true" />
+ </button>
+ <button type="button" onClick={() => toggle('delete')} disabled={editLocked}
+ className={`${smallButton} hover:text-port-error`} aria-label={`Delete ${wardrobe.name}`} title="Delete">
+ <Trash2 size={12} aria-hidden="true" />
+ </button>
+ </div>
+ </div>
+
+ {mode === 'delete' && (
+ <ConfirmButtonPair
+ prompt={images.length ? 'Delete this look? Its images move to References.' : 'Delete this look?'}
+ confirmText="Delete look" ariaLabel={`Confirm deleting ${wardrobe.name}`} busy={savingList}
+ onConfirm={async () => { if (await onDelete(wardrobe)) setMode(null); }}
+ onCancel={() => setMode(null)} largeTouchTargets />
+ )}
+ {mode === 'edit' && (
+ <LookForm formId={`look-${wardrobe.id}`} initial={wardrobe} busy={savingList}
+ onSubmit={async (fields) => { if (await onSave({ ...wardrobe, ...fields })) setMode(null); }}
+ onCancel={() => setMode(null)} />
+ )}
+ {mode === 'generate' && (
+ <LookGenerate ingredientId={ingredientId} wardrobe={wardrobe} blockedReason={blockedReason}
+ savedStamp={savedStamp} onLookFile={onLookFile} onClose={() => setMode(null)} />
+ )}
+ {mode === 'attach' && (
+ <div className="rounded border border-port-border bg-port-bg/40 p-3">
+ <h4 className="text-xs uppercase tracking-wider text-gray-500 mb-2">Use a reference image for this look</h4>
+ {candidates.length > 0 ? (
+ <div className="grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-6 gap-2">
+ {candidates.map((m) => (
+ <CatalogMediaTile key={`${m.mediaKey}:${m.kind}`} m={m} missing={missingMedia?.has?.(m.mediaKey)}
+ extraActions={roleButton(m, role, `Use for ${wardrobe.name}`, `Added to ${wardrobe.name}`, Pin)} />
+ ))}
+ </div>
+ ) : (
+ <p className="text-xs text-gray-500">No reference images to use. Attach or generate some on the References tab.</p>
+ )}
+ </div>
+ )}
+
+ {images.length > 0 ? (
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ {images.map((m) => (
+ <CatalogMediaTile key={`${m.mediaKey}:${m.kind}`} m={m} label={wardrobe.name} contain
+ missing={missingMedia?.has?.(m.mediaKey)} onDetach={onDetach}
+ armedDetach={armedDetach} onArmDetach={setArmedDetach}
+ extraActions={roleButton(m, null, 'Move to References', 'Moved to References', Undo2)} />
+ ))}
+ </div>
+ ) : (
+ <p className="text-xs text-gray-500">No images for this look yet.</p>
+ )}
+ </article>
+ );
+}
+
+// The Looks tab for a character: its `payload.wardrobes`, each with the images
+// whose catalog media role is `look:<wardrobe id>`. Looks are saved straight to
+// the record (`onSaveWardrobes(next)` resolves true on success) so a render can
+// use them at once; renders read the SAVED record, so Render is gated by
+// `blockedReason` while the profile has unsaved edits. Ids are stamped here in
+// the `wd-<uuid>` shape the canon sanitizer uses, because a catalog save stores
+// the payload as sent. Deleting a look leaves its images attached; they then
+// show on References.
+export default function CatalogLooksPanel({
+ ingredientId, wardrobes, lookMedia, candidates, missingMedia, editLocked = false,
+ blockedReason = null, savedStamp = null, onSaveWardrobes, onSetRole, onDetach, onLookFile,
+}) {
+ const [adding, setAdding] = useState(false);
+ const [savingList, setSavingList] = useState(false);
+ const list = Array.isArray(wardrobes) ? wardrobes.filter((w) => w && typeof w === 'object' && w.id) : [];
+ const media = Array.isArray(lookMedia) ? lookMedia : [];
+ const candidateList = Array.isArray(candidates) ? candidates : [];
+
+ const save = async (next) => {
+ setSavingList(true);
+ const ok = await onSaveWardrobes(next);
+ setSavingList(false);
+ return ok;
+ };
+ const now = () => new Date().toISOString();
+ const handleAdd = async ({ name, description }) => {
+ const stamp = now();
+ if (await save([...list, { id: `wd-${uuidv4()}`, name, description, createdAt: stamp, updatedAt: stamp }])) setAdding(false);
+ };
+ const handleUpdate = (updated) => save(list.map((w) => (w.id === updated.id ? { ...updated, updatedAt: now() } : w)));
+ const handleDelete = (wardrobe) => save(list.filter((w) => w.id !== wardrobe.id));
+
+ 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">
+ <Shirt size={14} aria-hidden="true" /> Looks
+ </h2>
+ {!adding && (
+ <button type="button" onClick={() => setAdding(true)} disabled={editLocked} className={smallButton}>
+ <Plus size={12} aria-hidden="true" /> Add look
+ </button>
+ )}
+ </div>
+ {editLocked && <p className="text-xs text-gray-500" role="status">Saving the profile — looks can be edited once it finishes.</p>}
+ {adding && (
+ <LookForm formId="look-new" busy={savingList} onSubmit={handleAdd} onCancel={() => setAdding(false)} />
+ )}
+ {list.length === 0 && !adding && (
+ <p className="text-xs text-gray-500">No looks yet. Add one to describe an outfit, then generate or attach its images.</p>
+ )}
+ {list.map((w) => (
+ <LookCard key={w.id} ingredientId={ingredientId} wardrobe={w}
+ images={media.filter((m) => lookIdOf(m) === w.id)} candidates={candidateList}
+ missingMedia={missingMedia} editLocked={editLocked || savingList} savingList={savingList}
+ blockedReason={blockedReason} savedStamp={savedStamp}
+ onSave={handleUpdate} onDelete={handleDelete} onSetRole={onSetRole} onDetach={onDetach} onLookFile={onLookFile} />
+ ))}
+ </section>
+ );
+}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index f95878adf1..eca514349b 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`) `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:*`). |
+| `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(m, liveLookIds?)` (`sheet:*`, `plate`, `look:*`; a look whose wardrobe is gone counts as a reference) and `lookIdOf(m)`. |
| `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.js
index dddf589b11..a5e3226c83 100644
--- a/client/src/lib/creativeLibraries.js
+++ b/client/src/lib/creativeLibraries.js
@@ -11,7 +11,7 @@ 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.',
- detailTabs: Object.freeze([PROFILE, SHEETS, tab('references', 'References')]),
+ detailTabs: Object.freeze([PROFILE, SHEETS, tab('looks', 'Looks'), tab('references', 'References')]),
}),
Object.freeze({
id: 'environments', type: 'place', path: '/environments', label: 'Environments', singular: 'environment', empty: 'No environments yet.',
@@ -60,7 +60,15 @@ 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);
+// The wardrobe id a `look:<id>` media row belongs to, or null.
+export const lookIdOf = (m) => (roleOf(m).startsWith(LOOK_ROLE_PREFIX) ? roleOf(m).slice(LOOK_ROLE_PREFIX.length) : null);
+// `liveLookIds` (a Set of the record's wardrobe ids) keeps a deleted look's
+// images visible on References instead of stranding them under a dead role.
+export const isReferenceTabMedia = (m, liveLookIds = null) => {
+ if (isSheetMedia(m) || isPlateMedia(m)) return false;
+ const lookId = lookIdOf(m);
+ return lookId === null || (liveLookIds ? !liveLookIds.has(lookId) : false);
+};
// 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
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsx
index cc268bafe2..71755af2e6 100644
--- a/client/src/pages/CatalogIngredient.jsx
+++ b/client/src/pages/CatalogIngredient.jsx
@@ -2,14 +2,14 @@
* CatalogIngredient — detail/editor for a single catalog ingredient. Loaded
* 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.
+ * `detailTabs` split it into Profile / Sheets / Looks|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, Plus, X, History, RotateCcw, Image as ImageIcon, ChevronDown, Upload, Mic, Square, UserRound, LayoutGrid, Images, Clapperboard } from 'lucide-react';
+import { Sparkles, Save, Trash2, ArrowLeft, Loader2, Plus, X, History, RotateCcw, Image as ImageIcon, ChevronDown, Upload, Mic, Square, UserRound, LayoutGrid, Images, Clapperboard, Shirt } from 'lucide-react';
import toast from '../components/ui/Toast';
import FilePickerButton from '../components/ui/FilePickerButton';
import Modal from '../components/ui/Modal.jsx';
@@ -54,6 +54,7 @@ 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 CatalogLooksPanel from '../components/catalog/CatalogLooksPanel';
import CharacterLoraChip from '../components/loraTraining/CharacterLoraChip';
import TagPicker from '../components/TagPicker';
import GenericIngredientFields from '../components/GenericIngredientFields';
@@ -61,7 +62,7 @@ import useUnsavedChangesGuard from '../hooks/useUnsavedChangesGuard';
import { getCatalogType, CATALOG_BADGE_BY_ID, RELATION_KINDS, getRelationKind } from '../lib/catalogTypes';
import {
libraryForPathname, ingredientPath, resolveDetailTab, detailTabPath,
- isSheetMedia, isPlateMedia, isReferenceTabMedia,
+ isSheetMedia, isPlateMedia, isReferenceTabMedia, lookIdOf,
} from '../lib/creativeLibraries';
import { useCatalogTypes } from '../hooks/useCatalogTypes.jsx';
import { timeAgo, formatDateTime } from '../utils/formatters';
@@ -124,6 +125,7 @@ export function buildGenerationPromptSeed(payload, typeDef, tags = []) {
const DETAIL_TAB_ICONS = {
profile: UserRound,
sheets: LayoutGrid,
+ looks: Shirt,
plates: Clapperboard,
references: Images,
images: ImageIcon,
@@ -172,6 +174,9 @@ export default function CatalogIngredient() {
const [tags, setTags] = useState([]);
const [payload, setPayload] = useState({});
const [saving, setSaving] = useState(false);
+ // A Looks-tab wardrobe save in flight; the profile Save waits for it so its
+ // draft payload can't write back the previous wardrobes.
+ const [lookSaving, setLookSaving] = useState(false);
const [armedDelete, setArmedDelete] = useState(false);
// { outbound: [...], inbound: [...] } — relations are loaded separately from
// the ingredient record so the panel can refresh independently after add/
@@ -366,10 +371,10 @@ 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) => {
+ // Re-attach an existing media row under a new role (mark/unmark a plate, add
+ // an image to a look). 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, message) => {
if (!record || !m?.mediaKey) return false;
const updated = await attachCatalogIngredientMedia(
record.id,
@@ -380,21 +385,41 @@ export default function CatalogIngredient() {
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');
+ toast.success(message || (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) => {
+ const handleSheetFile = useCallback(async (filename, role, readyMessage = 'Reference sheet ready') => {
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; });
+ .catch((err) => { toast.error(err?.message || 'Failed to attach the rendered image'); return false; });
refreshMedia();
- if (ok) toast.success('Reference sheet ready');
+ if (ok) toast.success(readyMessage);
}, [record, refreshMedia]);
+ const handleLookFile = useCallback((filename, role) => handleSheetFile(filename, role, 'Look ready'), [handleSheetFile]);
+
+ // Save the Looks tab's wardrobe list straight onto the SAVED payload, then
+ // copy just `wardrobes` into the draft so unsaved profile edits stay intact
+ // and exactly as dirty as they were.
+ const handleSaveWardrobes = useCallback(async (wardrobes) => {
+ if (!record) return false;
+ const submittedId = record.id;
+ const nextPayload = { ...ingredientPayload(record.payload), wardrobes };
+ setLookSaving(true);
+ const updated = await updateCatalogIngredient(submittedId, { payload: nextPayload }, { silent: true })
+ .catch((err) => { toast.error(err?.message || 'Failed to save looks'); return null; });
+ setLookSaving(false);
+ if (activeVisitRef.current.id !== submittedId || !updated) return false;
+ const persisted = Object.hasOwn(updated, 'payload') ? ingredientPayload(updated.payload) : nextPayload;
+ setRecord((prev) => (prev?.id === submittedId ? { ...prev, ...updated, payload: persisted } : prev));
+ setPayload((cur) => ({ ...cur, wardrobes: persisted.wardrobes }));
+ refreshRevisions();
+ return true;
+ }, [record, refreshRevisions]);
// 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
@@ -568,6 +593,14 @@ export default function CatalogIngredient() {
? library.detailTabs.map((t) => ({ ...t, icon: DETAIL_TAB_ICONS[t.id] }))
: null;
const activeTab = tabs ? resolveDetailTab(library, tabParam) : 'profile';
+ const wardrobes = record.type === 'character' && Array.isArray(ingredientPayload(record.payload).wardrobes)
+ ? record.payload.wardrobes
+ : [];
+ const liveLookIds = new Set(wardrobes.map((w) => w?.id).filter(Boolean));
+ const isReferenceTabRow = (m) => isReferenceTabMedia(m, liveLookIds);
+ const renderBlockedReason = (subject) => (saving
+ ? `Saving — the ${subject} renders from the saved record.`
+ : isDirty ? `Save your profile edits first — the ${subject} renders from the saved record.` : null);
return (
<section className="h-full overflow-y-auto p-4 md:p-6">
@@ -601,7 +634,7 @@ export default function CatalogIngredient() {
<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>
- <button type="button" onClick={handleSave} disabled={saving}
+ <button type="button" onClick={handleSave} disabled={saving || lookSaving}
className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 text-white text-sm font-medium">
{saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />} Save
</button>
@@ -720,19 +753,34 @@ export default function CatalogIngredient() {
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}
+ blockedReason={renderBlockedReason('sheet')}
savedStamp={record.updatedAt || null}
onSheetFile={handleSheetFile}
onPointerSheetReady={refreshSheetPointers}
/>
)}
+ {activeTab === 'looks' && (
+ <CatalogLooksPanel
+ ingredientId={record.id}
+ wardrobes={wardrobes}
+ lookMedia={media.filter((m) => liveLookIds.has(lookIdOf(m)))}
+ candidates={media.filter((m) => m.kind === 'reference' && isReferenceTabRow(m))}
+ missingMedia={missingMedia}
+ editLocked={saving}
+ blockedReason={renderBlockedReason('look')}
+ savedStamp={record.updatedAt || null}
+ onSaveWardrobes={handleSaveWardrobes}
+ onSetRole={handleSetMediaRole}
+ onDetach={handleDetachMedia}
+ onLookFile={handleLookFile}
+ />
+ )}
+
{activeTab === 'plates' && (
<CatalogPlatesPanel
plates={media.filter(isPlateMedia)}
- candidates={media.filter((m) => m.kind === 'reference' && isReferenceTabMedia(m))}
+ candidates={media.filter((m) => m.kind === 'reference' && isReferenceTabRow(m))}
missingMedia={missingMedia}
onSetRole={handleSetMediaRole}
onDetach={handleDetachMedia}
@@ -741,7 +789,7 @@ export default function CatalogIngredient() {
{(activeTab === 'profile' ? !tabs : activeTab === 'references' || activeTab === 'images') && (
<MediaPanel
- media={tabs ? media.filter(isReferenceTabMedia) : media}
+ media={tabs ? media.filter(isReferenceTabRow) : media}
missingMedia={missingMedia}
onAttach={handleAttachMedia}
onSetPortrait={handleSetPortrait}
diff --git a/client/src/pages/CatalogIngredient.test.jsx b/client/src/pages/CatalogIngredient.test.jsx
index e9fd510081..306c6b67aa 100644
--- a/client/src/pages/CatalogIngredient.test.jsx
+++ b/client/src/pages/CatalogIngredient.test.jsx
@@ -749,6 +749,7 @@ describe('CatalogIngredient — tabbed library record pages', () => {
physicalDescription: 'Tall, green cloak.',
referenceSheetImageRef: 'hero-standard.png',
referenceSheets: { expressions: 'hero-expressions.png' },
+ wardrobes: [{ id: 'wardrobe-1', name: 'Red scarf', description: 'Long red wool scarf.', createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z' }],
},
refs: [{ refKind: 'universe', refId: 'u-example', refName: 'Example Universe' }],
sources: [],
@@ -871,12 +872,79 @@ describe('CatalogIngredient — tabbed library record pages', () => {
expect(screen.queryByLabelText('Name')).toBeNull();
});
+ describe('Looks tab', () => {
+ // Catches the look render losing its wardrobe id or attaching under a role
+ // the Looks tab does not read back.
+ it('lists looks with their images, previews a look and renders it under its look role', async () => {
+ const api = await import('../services/apiCatalog');
+ api.renderCatalogSheet.mockResolvedValue({ jobId: 'look-job', variant: 'look', role: 'look:wardrobe-1', delegatedTo: null });
+ api.attachCatalogIngredientMedia.mockResolvedValue({});
+ await renderPage('/casting/cat-chr-hero/looks');
+ expect(await screen.findByRole('tab', { name: /Looks/ })).toHaveAttribute('aria-selected', 'true');
+ const card = screen.getByRole('article', { name: 'Look: Red scarf' });
+ expect(card.textContent).toContain('Long red wool scarf.');
+ await waitFor(() => expect(screen.getByAltText('Red scarf').getAttribute('src')).toBe('/data/images/look-1.png'));
+
+ fireEvent.click(screen.getByRole('button', { name: /^Generate$/ }));
+ expect(await screen.findByRole('button', { name: '+ Universe style' })).toBeTruthy();
+ expect(api.previewCatalogSheet).toHaveBeenLastCalledWith(
+ 'cat-chr-hero', { variant: 'look', wardrobeId: 'wardrobe-1' }, { silent: true },
+ );
+ fireEvent.click(screen.getByRole('button', { name: /Render look/ }));
+ await waitFor(() => expect(api.renderCatalogSheet).toHaveBeenCalledWith(
+ 'cat-chr-hero', { variant: 'look', wardrobeId: 'wardrobe-1' }, { silent: true },
+ ));
+ await waitFor(() => expect(api.attachCatalogIngredientMedia).toHaveBeenCalledWith(
+ 'cat-chr-hero', { mediaKey: 'look-job.png', kind: 'reference', role: 'look:wardrobe-1' }, { silent: true },
+ ));
+ });
+
+ // Catches a look save dropping the rest of the saved payload, reusing or
+ // omitting ids, or failing to show the new look.
+ it('adds a look by saving payload.wardrobes with a stamped wd- id and the rest of the payload intact', async () => {
+ const added = { id: 'wd-new', name: 'Travel coat', description: 'Grey wool coat.' };
+ updateCatalogIngredient.mockImplementation(async (_id, patch) => ({
+ ...HERO, payload: { ...patch.payload, wardrobes: [HERO.payload.wardrobes[0], added] },
+ }));
+ await renderPage('/casting/cat-chr-hero/looks');
+ fireEvent.click(await screen.findByRole('button', { name: /Add look/ }));
+ fireEvent.change(screen.getByLabelText('Look name'), { target: { value: 'Travel coat' } });
+ fireEvent.change(screen.getByLabelText('Outfit description'), { target: { value: 'Grey wool coat.' } });
+ fireEvent.click(screen.getByRole('button', { name: /Save look/ }));
+
+ await waitFor(() => expect(updateCatalogIngredient).toHaveBeenCalledTimes(1));
+ const [id, patch] = updateCatalogIngredient.mock.calls[0];
+ expect(id).toBe('cat-chr-hero');
+ expect(patch.payload.physicalDescription).toBe('Tall, green cloak.');
+ expect(patch.payload.wardrobes[0]).toEqual(HERO.payload.wardrobes[0]);
+ expect(patch.payload.wardrobes[1]).toMatchObject({ name: 'Travel coat', description: 'Grey wool coat.' });
+ expect(patch.payload.wardrobes[1].id).toMatch(/^wd-[0-9a-f-]{36}$/);
+ expect(await screen.findByRole('article', { name: 'Look: Travel coat' })).toBeTruthy();
+ expect(screen.queryByText('Unsaved changes')).toBeNull();
+ });
+
+ // Catches a deleted look stranding its images under a role no tab shows.
+ it('deletes a look and leaves its images on References', async () => {
+ updateCatalogIngredient.mockImplementation(async (_id, patch) => ({ ...HERO, payload: patch.payload }));
+ const { router } = await renderPage('/casting/cat-chr-hero/looks');
+ fireEvent.click(await screen.findByRole('button', { name: 'Delete Red scarf' }));
+ expect(screen.getByText(/Its images move to References/)).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Delete look' }));
+ await waitFor(() => expect(updateCatalogIngredient.mock.calls[0]?.[1].payload.wardrobes).toEqual([]));
+ await waitFor(() => expect(screen.queryByRole('article', { name: 'Look: Red scarf' })).toBeNull());
+
+ await act(async () => { await router.navigate('/casting/cat-chr-hero/references'); });
+ await waitFor(() => expect(screen.getAllByRole('img').map((img) => img.getAttribute('src')))
+ .toContain('/data/images/look-1.png'));
+ });
+ });
+
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,
+ media: MEDIA.filter((m) => m.mediaKey !== 'look-1.png'),
}));
await renderPage('/environments/cat-plc-1/plates');
expect(await screen.findByRole('button', { name: 'Unmark plate' })).toBeTruthy();
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index 11817247a8..f75a580729 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -381,12 +381,25 @@ export const catalogPortraitSetSchema = z.object({
// Reference-sheet render/preview body. The prompt overrides are the user's own
// words and are sent exactly as typed — no trim (#11317).
+// `wardrobeId` picks the outfit a `look` render dresses the character in: it
+// is required for `look` and refused for every other variant, so a stray id
+// never silently renders a plain sheet. 59 = the 64-char media role cap minus
+// the `look:` prefix the render tags its image with.
+export const CATALOG_LOOK_VARIANT_ID = 'look';
export const catalogSheetRenderSchema = z.object({
variant: z.string().trim().min(1).max(48).optional(),
+ wardrobeId: z.string().trim().min(1).max(59).optional(),
overridePrompt: z.string().max(8000).optional(),
overrideNegativePrompt: z.string().max(2000).optional(),
modelId: z.string().trim().max(64).optional(),
-}).strict();
+}).strict().superRefine((body, ctx) => {
+ const isLook = body.variant === CATALOG_LOOK_VARIANT_ID;
+ if (isLook && !body.wardrobeId) {
+ ctx.addIssue({ code: 'custom', path: ['wardrobeId'], message: 'wardrobeId is required for a look render' });
+ } else if (!isLook && body.wardrobeId) {
+ ctx.addIssue({ code: 'custom', path: ['wardrobeId'], message: 'wardrobeId is only accepted for a look render' });
+ }
+});
// Media detach body — identifies the tuple to soft-delete.
export const catalogMediaDetachSchema = z.object({
diff --git a/server/routes/catalogSheets.test.js b/server/routes/catalogSheets.test.js
index c64f7e1fe1..370b2ed5ac 100644
--- a/server/routes/catalogSheets.test.js
+++ b/server/routes/catalogSheets.test.js
@@ -156,4 +156,69 @@ describe('catalog sheet routes', () => {
expect(res.body.preview.sentPrompt).toBe(typed);
expect(res.body.preview.promptAdditions).toEqual([]);
});
+
+ describe('look renders', () => {
+ const dressed = {
+ ...character,
+ payload: {
+ ...character.payload,
+ wardrobes: [{ id: 'wd-scarf', name: 'Red scarf', description: 'long red wool scarf over a grey travel coat' }],
+ },
+ };
+
+ // Catches a look landing as a generic sheet (wrong role), delegating to the
+ // universe renderer (it would never reach the Looks tab), or dropping the
+ // wardrobe text; and the preview drifting from what is queued (#11317).
+ it('previews and queues a look tagged look:<wardrobeId> through the catalog path, even when universe-linked', async () => {
+ mocks.getIngredient.mockResolvedValue(dressed);
+ mocks.listLiveRefsForIngredient.mockResolvedValue([{ refKind: 'universe', refId: 'universe-1' }]);
+ mocks.getUniverse.mockResolvedValue({
+ id: 'universe-1', name: 'Example Universe', influences: { embrace: ['ink and watercolor'] },
+ characters: [{ id: 'char-entry-1', name: 'Example Hero', ingredientId: 'cat-chr-1' }],
+ });
+ const body = { variant: 'look', wardrobeId: 'wd-scarf' };
+ const preview = await request(app).post('/api/catalog/ingredients/cat-chr-1/sheets/preview').send(body);
+ expect(preview.status).toBe(200);
+ const sent = preview.body.preview;
+ expect(sent.sentPrompt).toContain('long red wool scarf over a grey travel coat');
+ expect(sent.sentPrompt).toContain('Example Hero');
+
+ const res = await request(app).post('/api/catalog/ingredients/cat-chr-1/sheets').send(body);
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ variant: 'look', role: 'look:wd-scarf', delegatedTo: null });
+ const params = queuedParams();
+ expect(params.catalogAttach).toEqual({ ingredientId: 'cat-chr-1', kind: 'reference', role: 'look:wd-scarf' });
+ expect(params.characterSheet).toBeUndefined();
+ expect(sent.sentPrompt).toBe(params.prompt);
+ expect(sent.promptAdditions).toEqual(params.promptAdditions);
+ // Style and negatives travel as labeled additions; the negatives never
+ // ride in the positive prompt.
+ const negatives = params.promptAdditions.find((a) => a.id === 'sheet-negatives');
+ expect(negatives).toMatchObject({ label: 'Look negatives' });
+ expect(params.negativePrompt).toBe(negatives.text);
+ expect(params.prompt).not.toContain(negatives.text);
+ expect(params.promptAdditions.map((a) => a.id)).toContain('universe-style');
+ });
+
+ it('is not offered among the sheet variants', async () => {
+ mocks.getIngredient.mockResolvedValue(dressed);
+ const res = await request(app).get('/api/catalog/ingredients/cat-chr-1/sheets/variants');
+ expect(res.body.variants.map((v) => v.id)).not.toContain('look');
+ });
+
+ it('refuses an unknown wardrobe, a non-character, a missing wardrobeId and a stray one', async () => {
+ mocks.getIngredient.mockResolvedValue(dressed);
+ const wrong = await request(app).post('/api/catalog/ingredients/cat-chr-1/sheets').send({ variant: 'look', wardrobeId: 'wd-other' });
+ expect(wrong.status).toBe(400);
+ const missing = await request(app).post('/api/catalog/ingredients/cat-chr-1/sheets').send({ variant: 'look' });
+ expect(missing.status).toBe(400);
+ const stray = await request(app).post('/api/catalog/ingredients/cat-chr-1/sheets').send({ variant: 'blueprint', wardrobeId: 'wd-scarf' });
+ expect(stray.status).toBe(400);
+
+ mocks.getIngredient.mockResolvedValue({ ...place, payload: { ...place.payload, wardrobes: dressed.payload.wardrobes } });
+ const notCharacter = await request(app).post('/api/catalog/ingredients/cat-plc-1/sheets/preview').send({ variant: 'look', wardrobeId: 'wd-scarf' });
+ expect(notCharacter.status).toBe(400);
+ expect(mocks.enqueueJob).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/server/services/catalogSheet.js b/server/services/catalogSheet.js
index 619933123a..68213c2de4 100644
--- a/server/services/catalogSheet.js
+++ b/server/services/catalogSheet.js
@@ -8,6 +8,12 @@
* `catalogAttach` with `role: 'sheet:<variant>'`; catalogImageAttachHook files
* the finished image as a `reference` media row with that role (never the
* portrait), and the card-cover query skips sheet roles.
+ *
+ * A `look` render (variant `look` + `wardrobeId`) dresses a character in one
+ * of its `payload.wardrobes`. It is driven from the record's Looks tab, so it
+ * is not listed among the sheet variants, and it always renders through the
+ * catalog path — even for a universe-linked character — tagged
+ * `role: 'look:<wardrobeId>'`.
*/
import { ServerError } from '../lib/errorHandler.js';
@@ -30,7 +36,9 @@ import {
DEFAULT_PRODUCT_SHEET_STYLE,
buildEnvironmentSheetPrompt,
buildProductSheetPrompt,
+ buildCharacterLookPrompt,
} from './catalogSheetPrompts.js';
+import { CATALOG_LOOK_VARIANT_ID } from '../lib/catalogValidation.js';
const CATALOG_SHEET_VARIANTS = Object.freeze({
place: Object.freeze([Object.freeze({
@@ -70,6 +78,29 @@ export function listCatalogSheetVariants(type) {
return variantsForType(type).map(({ id, label, description }) => ({ id, label, description }));
}
+// The `look` variant for one wardrobe entry, or a 400 when the record is not
+// a character or the wardrobe is not one of its own.
+function lookVariantFor(ingredient, payload, wardrobeId) {
+ if (ingredient.type !== 'character') {
+ throw new ServerError(`A look render is only available for a character, not a ${ingredient.type}`,
+ { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const wardrobes = Array.isArray(payload.wardrobes) ? payload.wardrobes : [];
+ const wardrobe = wardrobes.find((w) => w && typeof w === 'object' && w.id === wardrobeId);
+ if (!wardrobe) {
+ throw new ServerError(`"${ingredient.name}" has no look with id "${wardrobeId ?? ''}"`,
+ { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ return {
+ id: CATALOG_LOOK_VARIANT_ID,
+ label: 'Look',
+ build: (universe, entry) => buildCharacterLookPrompt(universe, entry, wardrobe),
+ defaultStyle: DEFAULT_CHARACTER_SHEET_STYLE,
+ negativesLabel: 'Look negatives',
+ role: `look:${wardrobe.id}`,
+ };
+}
+
// Load + guard the record, resolve its variant and any universe it links to.
async function resolveSheetTarget(id, options) {
const ingredient = await getIngredient(id);
@@ -81,10 +112,13 @@ async function resolveSheetTarget(id, options) {
{ status: 409, code: 'CATALOG_INGREDIENT_LOCKED' },
);
}
+ const isLook = options.variant === CATALOG_LOOK_VARIANT_ID;
const variants = variantsForType(ingredient.type);
- const variant = options.variant
- ? variants.find((v) => v.id === options.variant)
- : variants[0];
+ const variant = isLook
+ ? lookVariantFor(ingredient, payload, options.wardrobeId)
+ : options.variant
+ ? variants.find((v) => v.id === options.variant)
+ : variants[0];
if (!variant) {
throw new ServerError(
`Sheet variant "${options.variant ?? ''}" is not available for a ${ingredient.type}`,
@@ -100,7 +134,7 @@ async function resolveSheetTarget(id, options) {
const universe = await getUniverse(ref.refId).catch(() => null);
if (universe) universes.push(universe);
}
- if (ingredient.type === 'character') {
+ if (ingredient.type === 'character' && !isLook) {
for (const universe of universes) {
const entry = (universe.characters || []).find((c) => c.ingredientId === id);
if (entry) return { ingredient, payload, variant, delegate: { universeId: universe.id, entryId: entry.id } };
@@ -153,7 +187,7 @@ export async function renderCatalogSheet(id, options = {}) {
return { ...result, delegatedTo: 'universe', universeId, entryId };
}
const { params, modelId, activeMode } = await buildCatalogSheet(target, options);
- const role = `sheet:${target.variant.id}`;
+ const role = target.variant.role || `sheet:${target.variant.id}`;
params.catalogAttach = { ingredientId: id, kind: 'reference', role };
const queued = await enqueueJob({ kind: 'image', params });
console.log(`🎨 Catalog ${target.variant.label} render — ingredient=${shortId(id)} job=${shortId(queued.jobId)} mode=${activeMode} model=${modelId}`);
diff --git a/server/services/catalogSheetPrompts.js b/server/services/catalogSheetPrompts.js
index cc1cf6b7ca..f1e03d37ee 100644
--- a/server/services/catalogSheetPrompts.js
+++ b/server/services/catalogSheetPrompts.js
@@ -1,5 +1,6 @@
/**
- * Catalog reference-sheet prompt builders for places and objects.
+ * Catalog reference-sheet prompt builders for places and objects, plus the
+ * wardrobe look reference for a character.
*
* Same contract as the character builders in universeCharacterSheet.js:
* `(universe, entry) → { prompt, negativePrompt, width, height, modelId }`,
@@ -10,7 +11,7 @@
import { ServerError } from '../lib/errorHandler.js';
import { universeAestheticLine } from '../lib/universeVisualStyle.js';
-import { REFERENCE_SHEET_CONSTANTS } from './universeCharacterSheet.js';
+import { DEFAULT_CHARACTER_SHEET_STYLE, REFERENCE_SHEET_CONSTANTS, extractCharacterPromptCommon } from './universeCharacterSheet.js';
const { DEFAULT_WIDTH, DEFAULT_HEIGHT } = REFERENCE_SHEET_CONSTANTS;
@@ -105,3 +106,47 @@ export function buildProductSheetPrompt(universe, object) {
modelId: null,
};
}
+
+/**
+ * Look reference for a character wearing one of its wardrobes: the same
+ * person (identity from the record's own fields) in full-body views on a plain
+ * backdrop, no text. `wardrobe` is a `payload.wardrobes` entry.
+ */
+export function buildCharacterLookPrompt(universe, character, wardrobe) {
+ requireEntry(character, 'buildCharacterLookPrompt');
+ requireEntry(wardrobe, 'buildCharacterLookPrompt');
+ const styleBits = universeAestheticLine(universe || {});
+ const { name, age, pronouns, physical, silhouette, posture, special, visualIdentity, visualNotes } =
+ extractCharacterPromptCommon(character);
+ const lookName = trim(wardrobe.name) || 'Unnamed look';
+ const lookDescription = trim(wardrobe.description);
+
+ const identityBits = [
+ `Character: ${name}.`,
+ age ? `Age: ${age}.` : '',
+ pronouns ? `Pronouns: ${pronouns}.` : '',
+ ].filter(Boolean).join(' ');
+
+ const promptParts = [
+ `LOOK REFERENCE — a costume reference of one character, ${name}, wearing a single outfit, shown as three full-body views side by side at identical scale: FRONT, THREE-QUARTER and BACK, standing in a relaxed neutral pose on a plain seamless light-grey backdrop.`,
+ styleBits || DEFAULT_CHARACTER_SHEET_STYLE,
+ identityBits,
+ physical ? `Physical description: ${physical}` : '',
+ silhouette ? `Silhouette: ${silhouette}` : '',
+ posture ? `Posture: ${posture}` : '',
+ special ? `Special traits: ${special}` : '',
+ visualIdentity ? `Visual identity: ${visualIdentity}` : '',
+ visualNotes ? `Visual notes: ${visualNotes}` : '',
+ `Outfit: ${lookName}.`,
+ lookDescription ? `Outfit description: ${lookDescription}` : '',
+ `Every view shows the same person with the same face, hair, proportions and the complete outfit from head to toe, including footwear and accessories. Even, soft studio lighting. No props beyond what the outfit includes, no other people, no text, no labels, no captions.`,
+ ].filter(Boolean);
+
+ return {
+ prompt: promptParts.join('\n\n'),
+ negativePrompt: 'text, labels, captions, watermark, signature, multiple different characters, busy background, cropped feet, cropped head, inconsistent outfit between views, distorted anatomy, blurry',
+ width: DEFAULT_WIDTH,
+ height: DEFAULT_HEIGHT,
+ modelId: null,
+ };
+}