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

Casting record pages: flush header, alternate ages and looks, thumbnail previews

Claudebbaa0853da6b
diff --git a/client/src/components/MediaImage.jsx b/client/src/components/MediaImage.jsx
index a1edc0ebe1..cf886bf136 100644
--- a/client/src/components/MediaImage.jsx
+++ b/client/src/components/MediaImage.jsx
@@ -13,7 +13,7 @@
*
* Props:
* src: string — same as <img>; expected to be `/data/...`
- * fallbackSrc?: string — original to try once if a thumbnail fails
+ * fallbackSrc?: string|string[] — originals to try in order if `src` fails (e.g. a thumbnail)
* assetSrc?: string — original URL whose filename peer sync reports
* alt: string — same as <img>
* className?: string — applies to BOTH the live <img> and the placeholder wrapper
@@ -52,7 +52,9 @@ export default function MediaImage({
...rest
}) {
const [errored, setErrored] = useState(false);
- const [usingFallback, setUsingFallback] = useState(false);
+ // -1 = `src`; otherwise the index into `fallbacks` currently shown.
+ const [fallbackIndex, setFallbackIndex] = useState(-1);
+ const fallbacks = [fallbackSrc].flat().filter((f) => typeof f === 'string' && f && f !== src);
// Bumping `nonce` forces the <img> to re-fetch (cache-busted) when the
// socket says our asset arrived — without it the browser would serve the
// cached 404 forever.
@@ -65,7 +67,7 @@ export default function MediaImage({
// different filename that we DO have locally.
useEffect(() => {
setErrored(false);
- setUsingFallback(false);
+ setFallbackIndex(-1);
setNonce(0);
}, [src, assetSrc]);
@@ -78,7 +80,7 @@ export default function MediaImage({
const handler = (payload) => {
if (payload?.filename === filenameRef.current) {
setErrored(false);
- setUsingFallback(false);
+ setFallbackIndex(-1);
setNonce((n) => n + 1);
}
};
@@ -101,7 +103,7 @@ export default function MediaImage({
// The cache-buster appears only after the first arrival event; the very
// first load (before any 404) uses the bare src so HTTP caching still
// works the way the rest of the UI expects.
- const displaySrc = usingFallback ? fallbackSrc : src;
+ const displaySrc = fallbacks[fallbackIndex] ?? src;
const cacheBustedSrc = nonce > 0 ? `${displaySrc}${displaySrc.includes('?') ? '&' : '?'}_t=${nonce}` : displaySrc;
// Spread `rest` FIRST so the explicit `onError` below wins over a caller-
// provided one — we still forward the event by capturing the caller's
@@ -121,7 +123,7 @@ export default function MediaImage({
// listener still gates the swap-back, so a permanent network error
// doesn't lock the placeholder on forever — user-visible state then
// accurately reflects "asset not loadable right now."
- if (!usingFallback && fallbackSrc && fallbackSrc !== src) setUsingFallback(true);
+ if (fallbackIndex + 1 < fallbacks.length) setFallbackIndex(fallbackIndex + 1);
else setErrored(true);
callerOnError?.(e);
}}
diff --git a/client/src/components/MediaImage.test.jsx b/client/src/components/MediaImage.test.jsx
index 7c601d4461..52657ebf1f 100644
--- a/client/src/components/MediaImage.test.jsx
+++ b/client/src/components/MediaImage.test.jsx
@@ -34,6 +34,17 @@ describe('MediaImage', () => {
expect(img.getAttribute('src')).toBe('/data/images/foo.png');
});
+ // Catches a thumbnail miss stranding a sheet that lives only under image-refs.
+ it('walks a fallback chain in order before showing the placeholder', () => {
+ render(<MediaImage src="/data/image-thumbnails/s.webp" fallbackSrc={['/data/images/s.png', '/data/image-refs/s.png']} alt="sheet" />);
+ fireEvent.error(screen.getByAltText('sheet'));
+ expect(screen.getByAltText('sheet').getAttribute('src')).toBe('/data/images/s.png');
+ fireEvent.error(screen.getByAltText('sheet'));
+ expect(screen.getByAltText('sheet').getAttribute('src')).toBe('/data/image-refs/s.png');
+ fireEvent.error(screen.getByAltText('sheet'));
+ expect(screen.getByText(/Syncing/i)).toBeTruthy();
+ });
+
it('shows the "Syncing" placeholder after an onError fires (asset 404s before pull lands)', () => {
render(<MediaImage src="/data/images/missing.png" alt="ghost" />);
fireEvent.error(screen.getByAltText('ghost'));
diff --git a/client/src/components/catalog/CatalogCard.jsx b/client/src/components/catalog/CatalogCard.jsx
index 581ff1e086..33c1ce0349 100644
--- a/client/src/components/catalog/CatalogCard.jsx
+++ b/client/src/components/catalog/CatalogCard.jsx
@@ -11,6 +11,7 @@
import { Link } from 'react-router';
import { Sparkles, Trash2 } from 'lucide-react';
import MediaImage from '../MediaImage';
+import { imageThumbnailSrc } from '../../lib/imageThumbnailSrc';
import InlineConfirmRow from '../ui/InlineConfirmRow';
import { payloadSnippet } from '../../lib/catalogTypes';
import { ingredientPath, ingredientCoverUrl } from '../../lib/creativeLibraries';
@@ -36,7 +37,9 @@ function CardThumb({ src, alt }) {
<div className="w-14 h-14 shrink-0 rounded-md overflow-hidden border border-port-border bg-port-bg flex items-center justify-center">
{src ? (
<MediaImage
- src={src}
+ src={imageThumbnailSrc(src) || src}
+ fallbackSrc={src}
+ assetSrc={src}
alt={alt}
className="w-full h-full object-cover"
loading="lazy"
diff --git a/client/src/components/catalog/CatalogFormsEditor.jsx b/client/src/components/catalog/CatalogFormsEditor.jsx
new file mode 100644
index 0000000000..465ba74252
--- /dev/null
+++ b/client/src/components/catalog/CatalogFormsEditor.jsx
@@ -0,0 +1,86 @@
+import { Plus, Trash2, UserRound } from 'lucide-react';
+import { newFormId, formAgeField, formAgeLabel } from '../../lib/catalogForms';
+import { BIBLE_LIMITS } from '../../lib/bibleLimits';
+
+const { FORM_LABEL_MAX: LABEL_MAX, FORM_AGE_MAX: AGE_MAX, FORM_DESCRIPTION_MAX: DESCRIPTION_MAX, FORMS_PER_ENTRY_MAX: FORMS_MAX } = BIBLE_LIMITS;
+
+const inputClass = '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';
+const labelClass = 'block text-xs uppercase tracking-wider text-gray-500 mb-1';
+
+const PLACEHOLDERS = {
+ character: { label: 'Age 7', age: '7', description: 'Gap-toothed, oversized yellow raincoat, scabbed knees' },
+ place: { label: 'Abandoned, 2040', age: '2040', description: 'Boarded windows, ivy over the sign, cracked lot' },
+ object: { label: 'Brand new', age: '1986', description: 'Glossy red paint, chrome still bright, tags attached' },
+};
+
+// The record's own fields are its canonical present-story form; `payload.forms`
+// holds alternate ages, eras and looks/styles. Edits are part of the profile
+// draft and persist with Save.
+export default function CatalogFormsEditor({ type, payload, onChange }) {
+ const forms = Array.isArray(payload.forms) ? payload.forms : [];
+ const ageField = formAgeField(type);
+ const ageLabel = formAgeLabel(type);
+ const canonicalAge = ageField && typeof payload[ageField] === 'string' ? payload[ageField].trim() : '';
+ const placeholder = PLACEHOLDERS[type] || PLACEHOLDERS.object;
+
+ const setForms = (next) => onChange('forms', next);
+ const update = (id, patch) => setForms(forms.map((f) => (f.id === id ? { ...f, ...patch } : f)));
+
+ return (
+ <section aria-labelledby="catalog-forms-heading" 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 id="catalog-forms-heading" className="text-sm font-semibold text-white flex items-center gap-1.5">
+ <UserRound size={14} aria-hidden="true" /> Ages &amp; looks
+ </h2>
+ <button type="button" disabled={forms.length >= FORMS_MAX}
+ onClick={() => setForms([...forms, { id: newFormId(), label: '', age: '', description: '' }])}
+ className="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">
+ <Plus size={12} aria-hidden="true" /> Add age or look
+ </button>
+ </div>
+
+ <div className="rounded border border-port-accent/40 bg-port-accent/5 px-3 py-2 text-sm">
+ <span className="text-white font-medium">Canonical</span>
+ <span className="text-gray-400"> · present story</span>
+ {canonicalAge && <span className="text-gray-300"> · {ageLabel} {canonicalAge}</span>}
+ <p className="text-xs text-gray-500 mt-0.5">The profile above. Other ages and looks below render their own sheets and tag their own references.</p>
+ </div>
+
+ {forms.length > 0 && (
+ <ul className="space-y-3">
+ {forms.map((form, index) => {
+ const base = `catalog-form-${form.id || index}`;
+ return (
+ <li key={form.id || index} className="rounded border border-port-border bg-port-bg/40 p-3 space-y-2">
+ <div className="grid grid-cols-[minmax(0,1fr)_6rem_auto] gap-2 items-end">
+ <div className="min-w-0">
+ <label htmlFor={`${base}-label`} className={labelClass}>Name</label>
+ <input id={`${base}-label`} type="text" value={form.label || ''} maxLength={LABEL_MAX}
+ onChange={(e) => update(form.id, { label: e.target.value })} placeholder={placeholder.label} className={inputClass} />
+ </div>
+ <div>
+ <label htmlFor={`${base}-age`} className={labelClass}>{ageLabel}</label>
+ <input id={`${base}-age`} type="text" value={form.age || ''} maxLength={AGE_MAX}
+ onChange={(e) => update(form.id, { age: e.target.value })} placeholder={placeholder.age} className={inputClass} />
+ </div>
+ <button type="button" onClick={() => setForms(forms.filter((f) => f.id !== form.id))}
+ aria-label={`Remove ${form.label || 'this age or look'}`} title="Remove"
+ className="inline-flex items-center justify-center min-w-[40px] min-h-[40px] rounded border border-port-border text-gray-400 hover:text-port-error">
+ <Trash2 size={14} aria-hidden="true" />
+ </button>
+ </div>
+ {!form.label?.trim() && <p className="text-xs text-port-warning">Name it, or Save drops it.</p>}
+ <div>
+ <label htmlFor={`${base}-description`} className={labelClass}>How it looks</label>
+ <textarea id={`${base}-description`} value={form.description || ''} maxLength={DESCRIPTION_MAX} rows={2}
+ onChange={(e) => update(form.id, { description: e.target.value })} placeholder={placeholder.description}
+ className={`${inputClass} resize-y`} />
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </section>
+ );
+}
diff --git a/client/src/components/catalog/CatalogImagePreview.jsx b/client/src/components/catalog/CatalogImagePreview.jsx
index 28f7524829..f1c38a04e2 100644
--- a/client/src/components/catalog/CatalogImagePreview.jsx
+++ b/client/src/components/catalog/CatalogImagePreview.jsx
@@ -2,6 +2,7 @@ import { createContext, useContext } from 'react';
import { X } from 'lucide-react';
import MediaImage from '../MediaImage';
import Modal from '../ui/Modal';
+import { imageThumbnailSrc } from '../../lib/imageThumbnailSrc';
import usePreviewRoute from '../../hooks/usePreviewRoute';
const PreviewContext = createContext(null);
@@ -61,7 +62,12 @@ export function CatalogImagePreviewProvider({ name, children }) {
export default function CatalogImagePreview({ src, fallbackSrc, alt, className = '', loading = 'lazy' }) {
const setPreview = useContext(PreviewContext);
const item = imageFromSrc(src);
- const thumbnail = <MediaImage src={src} fallbackSrc={fallbackSrc} alt={alt} className={className} loading={loading} />;
+ // Inline tiles load the 512px WebP derivative, not the multi-MB original;
+ // the enlarged preview below still opens the original.
+ const thumbSrc = imageThumbnailSrc(src);
+ const thumbnail = thumbSrc
+ ? <MediaImage src={thumbSrc} fallbackSrc={[src, fallbackSrc]} assetSrc={src} alt={alt} className={className} loading={loading} />
+ : <MediaImage src={src} fallbackSrc={fallbackSrc} alt={alt} className={className} loading={loading} />;
if (!item || !setPreview) return thumbnail;
return (
<button type="button" onClick={() => setPreview({ ...item, alt })} aria-label={`Enlarge ${alt}`}
diff --git a/client/src/components/catalog/CatalogReferenceLibrary.jsx b/client/src/components/catalog/CatalogReferenceLibrary.jsx
index 53b6759e0b..503b283c9b 100644
--- a/client/src/components/catalog/CatalogReferenceLibrary.jsx
+++ b/client/src/components/catalog/CatalogReferenceLibrary.jsx
@@ -3,7 +3,8 @@ import { Compass, Star } from 'lucide-react';
import { updateCatalogIngredientMediaLibrary, attachCatalogIngredientMediaFromMoodBoard } from '../../services/apiCatalog';
// Casting reference library: tag each reference/sheet/still/clip of a cast
-// member with the variant it shows (age, era, look) plus tags, mark up to four
+// member with the variant it shows (which of the record's saved ages/looks —
+// `forms`, canonical when untagged — plus age, era) and tags, mark up to four
// as render guides, and filter the library by those fields. The media grid
// below still owns attach/upload/detach/portrait.
export const MAX_CAST_GUIDES = 4;
@@ -12,8 +13,8 @@ const LIBRARY_KINDS = new Set(['portrait', 'reference', 'video']);
const eraFor = (m) => m.library?.variant?.era
|| (Number.isInteger(m.library?.variant?.age) ? (m.library.variant.age < 13 ? 'child' : m.library.variant.age < 20 ? 'teen' : m.library.variant.age < 65 ? 'adult' : 'elder') : '');
-export default function CatalogReferenceLibrary({ ingredientId, media = [], readOnly = false, onChanged }) {
- const [filter, setFilter] = useState({ age: '', era: '', tag: '', guides: false });
+export default function CatalogReferenceLibrary({ ingredientId, media = [], forms = [], readOnly = false, onChanged }) {
+ const [filter, setFilter] = useState({ form: '', age: '', era: '', tag: '', guides: false });
const [error, setError] = useState('');
const [busyKey, setBusyKey] = useState('');
const [boardId, setBoardId] = useState('');
@@ -23,7 +24,9 @@ export default function CatalogReferenceLibrary({ ingredientId, media = [], read
const guideCount = rows.filter((m) => m.library?.guide === true).length;
const ages = [...new Set(rows.map((m) => m.library?.variant?.age).filter(Number.isInteger))].sort((a, b) => a - b);
const tags = [...new Set(rows.flatMap((m) => m.library?.tags || []))].sort();
- const visible = rows.filter((m) => (filter.age === '' || m.library?.variant?.age === Number(filter.age))
+ const formKey = (m) => m.library?.variant?.formId || 'canonical';
+ const visible = rows.filter((m) => (!filter.form || formKey(m) === filter.form)
+ && (filter.age === '' || m.library?.variant?.age === Number(filter.age))
&& (!filter.era || eraFor(m) === filter.era)
&& (!filter.tag || (m.library?.tags || []).includes(filter.tag))
&& (!filter.guides || m.library?.guide === true));
@@ -59,7 +62,16 @@ export default function CatalogReferenceLibrary({ ingredientId, media = [], read
<header className="flex flex-wrap items-center gap-2 text-sm">
<h3 className="font-semibold">Reference library</h3>
<span data-testid="guide-count" className="text-gray-400">{guideCount}/{MAX_CAST_GUIDES} render guides</span>
- <label className="ml-auto flex items-center gap-1">Age
+ {forms.length > 0 && (
+ <label className="ml-auto flex items-center gap-1">Form
+ <select aria-label="Filter by age or look" value={filter.form} onChange={(e) => setFilter({ ...filter, form: e.target.value })} className="bg-port-card">
+ <option value="">All</option>
+ <option value="canonical">Canonical</option>
+ {forms.map((f) => <option key={f.id} value={f.id}>{f.label}</option>)}
+ </select>
+ </label>
+ )}
+ <label className={`${forms.length > 0 ? '' : 'ml-auto '}flex items-center gap-1`}>Age
<select aria-label="Filter by age" value={filter.age} onChange={(e) => setFilter({ ...filter, age: e.target.value })} className="bg-port-card">
<option value="">All</option>
{ages.map((a) => <option key={a} value={a}>{a}</option>)}
@@ -100,6 +112,13 @@ export default function CatalogReferenceLibrary({ ingredientId, media = [], read
</div>
{!readOnly && (
<div className="flex flex-wrap items-center gap-1">
+ {forms.length > 0 && (
+ <select aria-label={`Age or look for ${m.mediaKey}`} value={lib.variant?.formId || ''} className="bg-port-bg"
+ onChange={(e) => save(m, { variant: { ...(lib.variant || {}), formId: e.target.value || undefined } })}>
+ <option value="">Canonical</option>
+ {forms.map((f) => <option key={f.id} value={f.id}>{f.label}</option>)}
+ </select>
+ )}
<input aria-label={`Age for ${m.mediaKey}`} type="number" min="0" max="150" defaultValue={lib.variant?.age ?? ''} className="w-14 bg-port-bg"
onBlur={(e) => {
const age = e.target.value === '' ? undefined : Number(e.target.value);
diff --git a/client/src/components/catalog/CatalogReferenceLibrary.test.jsx b/client/src/components/catalog/CatalogReferenceLibrary.test.jsx
index 815f18d1b2..70868e8c22 100644
--- a/client/src/components/catalog/CatalogReferenceLibrary.test.jsx
+++ b/client/src/components/catalog/CatalogReferenceLibrary.test.jsx
@@ -52,6 +52,20 @@ describe('CatalogReferenceLibrary', () => {
.toHaveBeenCalledWith('cat-chr-1', { boardId: 'mb-1', itemIds: ['a', 'b'], inferAge: true }));
});
+ it('tags a reference with one of the saved ages/looks and filters by it', async () => {
+ const forms = [{ id: 'form-kid', label: 'Age 7' }];
+ const tagged = [
+ { mediaKey: 'kid.png', kind: 'reference', library: { variant: { formId: 'form-kid' } } },
+ { mediaKey: 'now.png', kind: 'reference', library: {} },
+ ];
+ render(<CatalogReferenceLibrary ingredientId="cat-chr-1" media={tagged} forms={forms} />);
+ fireEvent.change(screen.getByLabelText('Filter by age or look'), { target: { value: 'canonical' } });
+ expect(screen.getAllByTestId('library-row')).toHaveLength(1);
+ fireEvent.change(screen.getByLabelText('Age or look for now.png'), { target: { value: 'form-kid' } });
+ await waitFor(() => expect(api.updateCatalogIngredientMediaLibrary)
+ .toHaveBeenCalledWith('cat-chr-1', { mediaKey: 'now.png', kind: 'reference', variant: { formId: 'form-kid' } }));
+ });
+
it('hides editing controls when read-only', () => {
render(<CatalogReferenceLibrary ingredientId="cat-chr-1" media={media} readOnly />);
expect(screen.queryByRole('button', { name: /guide/i })).toBeNull();
diff --git a/client/src/components/catalog/CatalogSheetsPanel.jsx b/client/src/components/catalog/CatalogSheetsPanel.jsx
index f794e96101..75ab0a0f94 100644
--- a/client/src/components/catalog/CatalogSheetsPanel.jsx
+++ b/client/src/components/catalog/CatalogSheetsPanel.jsx
@@ -11,6 +11,7 @@ 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 { formsOf, splitSheetRole } from '../../lib/catalogForms';
import { listCatalogSheetVariants, previewCatalogSheet, renderCatalogSheet } from '../../services/apiCatalog';
// Universe-canon sheets live on the payload as pointers into /data/image-refs.
@@ -88,6 +89,9 @@ const SHEET_EVENT = 'reference-sheet:changed';
// 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`.
+// Sheets group by form: the canonical present-story form first (universe
+// pointers + `sheet:<variant>`), then each alternate age/look
+// (`sheet:<variant>@<formId>`), which always renders through the catalog path.
export default function CatalogSheetsPanel({
ingredientId, payload, universeRef, sheetMedia, missingMedia, onDetach,
blockedReason = null, savedStamp = null, onSheetFile, onPointerSheetReady,
@@ -96,6 +100,7 @@ export default function CatalogSheetsPanel({
const [variants, setVariants] = useState(null);
const [variantsError, setVariantsError] = useState(null);
const [variantId, setVariantId] = useState('');
+ const [formId, setFormId] = useState(''); // '' = canonical
const [starting, setStarting] = useState(false);
const [pending, setPending] = useState(null); // { jobId, role, delegated }
const [armedDetach, setArmedDetach] = useState(null);
@@ -123,7 +128,10 @@ export default function CatalogSheetsPanel({
// (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 forms = formsOf(payload);
+ const activeFormId = forms.some((f) => f.id === formId) ? formId : '';
+ const preview = useModelInputPreview(fetchPreview,
+ { variant: variantId, ...(activeFormId ? { formId: activeFormId } : {}), savedStamp }, { enabled: !!variantId });
const jobId = pending?.jobId || null;
const delegated = !!pending?.delegated;
@@ -157,7 +165,8 @@ export default function CatalogSheetsPanel({
const handleGenerate = async () => {
if (!variant || blockedReason) return;
setStarting(true);
- const queued = await renderCatalogSheet(ingredientId, { variant: variant.id }, { silent: true })
+ const form = forms.find((f) => f.id === activeFormId) || null;
+ const queued = await renderCatalogSheet(ingredientId, { variant: variant.id, ...(form ? { formId: form.id } : {}) }, { silent: true })
.catch((err) => { toast.error(err?.message || 'Sheet render failed'); return null; });
if (!mountedRef.current) return;
setStarting(false);
@@ -167,20 +176,34 @@ export default function CatalogSheetsPanel({
}
setPending({
jobId: queued.jobId,
- role: queued.role || `${SHEET_ROLE_PREFIX}${queued.variant || variant.id}`,
+ role: queued.role || `${SHEET_ROLE_PREFIX}${queued.variant || variant.id}${form ? `@${form.id}` : ''}`,
delegated: queued.delegatedTo === 'universe',
});
+ const what = form ? `${variant.label} · ${form.label}` : variant.label;
toast.success(queued.delegatedTo === 'universe'
- ? `Rendering ${variant.label} on the linked universe…`
- : `Rendering ${variant.label}…`);
+ ? `Rendering ${what} on the linked universe…`
+ : `Rendering ${what}…`);
};
const pointerSheets = pointerSheetsOf(payload);
const sheets = Array.isArray(sheetMedia) ? sheetMedia : [];
const labelFor = (m) => {
- const id = (m.role || '').slice(SHEET_ROLE_PREFIX.length);
+ const { variant: id } = splitSheetRole(m.role, SHEET_ROLE_PREFIX);
return (variants || []).find((v) => v.id === id)?.label || id;
};
+ const sheetsByForm = new Map();
+ for (const m of sheets) {
+ const key = splitSheetRole(m.role, SHEET_ROLE_PREFIX).formId || '';
+ if (!sheetsByForm.has(key)) sheetsByForm.set(key, []);
+ sheetsByForm.get(key).push(m);
+ }
+ const formLabel = (id) => forms.find((f) => f.id === id)?.label || 'Removed age or look';
+ const groups = [
+ { id: '', title: 'Canonical · present story', pointer: pointerSheets, items: sheetsByForm.get('') || [] },
+ ...forms.map((f) => ({ id: f.id, title: [f.label, f.age].filter(Boolean).join(' · '), pointer: [], items: sheetsByForm.get(f.id) || [] })),
+ ...[...sheetsByForm.keys()].filter((k) => k && !forms.some((f) => f.id === k))
+ .map((k) => ({ id: k, title: formLabel(k), pointer: [], items: sheetsByForm.get(k) })),
+ ];
const universePath = universeCanonPath(universeRef);
const busy = starting || !!jobId;
@@ -205,6 +228,16 @@ export default function CatalogSheetsPanel({
) : (
<div className="space-y-2">
<div className="flex items-end gap-2 flex-wrap">
+ {forms.length > 0 && (
+ <div className="min-w-0 flex-1 max-w-sm">
+ <label htmlFor="catalog-sheet-form" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Age or look</label>
+ <select id="catalog-sheet-form" value={activeFormId} onChange={(e) => setFormId(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">
+ <option value="">Canonical · present story</option>
+ {forms.map((f) => <option key={f.id} value={f.id}>{f.label || 'Unnamed'}</option>)}
+ </select>
+ </div>
+ )}
<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}
@@ -229,18 +262,23 @@ export default function CatalogSheetsPanel({
</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} />
- ))}
+ {groups.map((group) => (
+ <div key={group.id || 'canonical'} className="space-y-2">
+ <h3 className="text-xs uppercase tracking-wider text-gray-400">{group.title}</h3>
+ {group.pointer.length > 0 || group.items.length > 0 ? (
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ {group.pointer.map(([v, filename]) => <PointerSheetFigure key={`ptr:${v}`} variant={v} filename={filename} />)}
+ {group.items.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 sheets yet.</p>
+ )}
</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.md
index 1ae561f0d4..0424c62684 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -80,6 +80,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `characterEvolution.js` | The five-stage character evolution lens as the editors consume it. Re-exports `EVOLUTION_STAGES` / `EVOLUTION_OUTCOMES` / `EVOLUTION_STAGE_LABELS` / `EVOLUTION_STAGE_TEXT_FIELDS` / `EVOLUTION_EVIDENCE_FIELDS` / `EVOLUTION_EVIDENCE_STATUSES` / `CHARACTER_EVOLUTION_LIMITS` / `evolutionEvidenceStatus` / `isDeclaredEvolution` from the pure leaf `server/lib/characterEvolution.js` (a guard in `server/lib/characterEvolution.test.js` fails if this file ever restates a vocabulary instead of re-exporting it), adds the editor descriptors `EVOLUTION_STAGE_EDITOR_FIELDS` / `EVOLUTION_OUTCOME_HINTS` (#6440), and the draft-mutation helpers `evolutionStage` / `patchEvolution` / `patchEvolutionStage` / `patchEvolutionEvidence` that keep an editor's draft collapsing to the same shape the server sanitizer produces — so a present-but-empty field is a real clear (#6441). |
| `characterFramework.js` | The narrative-character framework as the editors consume it. Re-exports `CHARACTER_ARC_TYPES` / `CHARACTER_FRAMEWORK_FIELDS` / `CHARACTER_FRAMEWORK_TEXT_FIELDS` / `CHARACTER_FRAMEWORK_LIMITS` / `CHARACTER_PSYCHOLOGY_LIMITS` / `CHARACTER_SLIDER_AXES` / `PSYCHOLOGY_ASSESSMENTS` / `PSYCHOLOGY_DRIVE_AXES` / `RELATIONSHIP_LINK_TYPES` from the pure leaf `server/lib/characterFramework.js`, and adds the editor descriptors `CHARACTER_FRAMEWORK_EDITOR_FIELDS` (Ghost → Wound → Lie → Need → Want, with labels/placeholders/caps), `CHARACTER_MOTIVATIONS_FIELD`, `CHARACTER_SECRETS_FIELD`, `CHARACTER_PSYCHOLOGY_EDITOR_FIELDS` / `CHARACTER_PSYCHOLOGY_NOTE_FIELD` / `CHARACTER_PSYCHOLOGY_DRIVE_HINTS` (#6414), and `CHARACTER_SLIDER_MIN` / `CHARACTER_SLIDER_MAX`. Shared by the Universe cast editor and the Writers Room bible so the two never restate the same field copy (#6417). |
| `characterIntegrity.js` | Display half of the cast-integrity contract (#6415) — re-exports the finding kinds, review statuses, depths, dimensions and `castIntegrityPassed` from `server/lib/characterIntegrityVocabulary.js`, plus the client-only `FINDING_KIND_META` / `REVIEW_STATUS_META` / `DEPTH_META` badge copy and `DIMENSION_LABELS` (read off the server's dimension table), `findingIsRepairable` (which gates the Augment button off `contradictory` findings), `incompleteCoverage` and `humanizeIntegrityField` (a dotted field path rendered for a reader). `characterIntegrity.test.js` checks the tables cover every value the server can emit. |
+| `catalogForms.js` | Alternate forms of a cast record (other ages, eras, looks/styles; `payload.forms`): `newFormId`, `formsOf(payload)`, `formAgeField(type)` / `formAgeLabel(type)` (the canonical form's age/era field), and `splitSheetRole(role)` for `sheet:<variant>@<formId>`. |
| `catalogTypes.js` | The catalog ingredient type registry as the UI consumes it. `CATALOG_TYPES` is PROJECTED from `server/lib/catalogTypes.js` (label, badge color, primary-content key/label, snippet fallback chain, `editableListFields` and its `BIBLE_LIMITS` caps) and decorated with the client-only editor layout (`editorSections` / `editorFields`); `RELATION_KINDS`, `MEDIA_KINDS`, `canonicalTagKey`, `payloadSnippet`, `USER_TYPE_FIELD_KINDS` are re-exported outright. Also the badge/ref-role lookups and the user-defined-type normalization `useCatalogTypes` merges in. |
| `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`. |
@@ -92,6 +93,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `grokVideoClip.js` | Re-export of `server/lib/grokVideoClip.js` — `GROK_VIDEO_DURATIONS` (`[6, 10, 15]`) + `GROK_VIDEO_DEFAULT_DURATION`, the clip lengths grok's `image_to_video` actually delivers. |
| `reactorVideoClip.js` | Re-export of `server/lib/reactorVideoClip.js` — `REACTOR_MAX_PROMPT_LENGTH` (800, counted in the VideoGen prompt field before submit), `REACTOR_MIN_CLIP_SECONDS` / `REACTOR_MAX_CLIP_SECONDS`, the picker list `REACTOR_CLIP_LENGTHS` + `REACTOR_DEFAULT_CLIP_LENGTH` + `reactorClipLengthLabel()`, and the canvas contract `REACTOR_CANVASES` / `REACTOR_ASPECTS` / `REACTOR_DEFAULT_ASPECT` / `reactorCanvas()` / `nearestReactorAspect()`. |
| `runwayVideoModels.js` | Re-export of `server/lib/runwayVideoModels.js` — the curated Runway video model catalog, per-model request rules and `estimateRunwayVideoCostUsd()`. Used by the Music Video Runway pickers and the Video Gen page's Runway backend. |
+| `imageThumbnailSrc.js` | `imageThumbnailSrc(src)` maps a gallery PNG (`/data/images/x.png`) to its on-demand 512px WebP (`/data/image-thumbnails/x.webp`), else null; used by catalog cards and inline catalog previews so lists don't pull multi-MB originals. |
| `imageCleaners.js` | Re-exports `resolveCleanersFromConfig` from the shared pure `server/lib/imageCleanDefaults.js` policy. Reads `{cleanC2PA, denoise}` off a per-mode settings record. `cleanC2PA` defaults are mode-aware (on for `codex` + `external` — the backends that emit C2PA chunks today — off otherwise, as an allow-list rather than a deny-list); `denoise` defaults off everywhere (lossy, opt-in only). |
| `reviewerModels.js` | `reviewerModelsFromDefaults` / `reviewerModelsToDefaults` / `reviewerEffortsFromDefaults` / `reviewerEffortsToDefaults` — adapt the Code Review Defaults' per-reviewer SCALARS (`codexModel`, `ollamaModel`, `claudeEffort`, …) to and from the token-keyed maps `ReviewerPicker`'s Model and Effort columns take. Mirrors `reviewerModelsFromDefaults` / `reviewerEffortsFromDefaults` in `server/lib/reviewerConfig.js`. Also preserves configured-provider model and effort pins in the additive `providerModels` / `providerEfforts` maps, keyed by `provider:<id>`; empty maps clear overrides without changing builtin scalars. |
| `reviewerPins.js` | Client mirror of the whole reviewer vocabulary — the roster (`REVIEWER_VALUES`), `REVIEWER_ALIASES`, `DEFAULT_REVIEWER(S)`, `normalizeReviewers`, the review-username pattern/cap (`MAX_REVIEW_USERNAMES` / `cleanReviewUsername` / `normalizeReviewUsernames`), `MAX_REVIEWER_MAX_ROUNDS`, `REVIEW_STOP_MODES` / `DEFAULT_REVIEW_STOP_MODE`, plus the per-reviewer pin vocabularies (`MODEL_SELECTABLE_REVIEWERS` / `EFFORT_SELECTABLE_REVIEWERS` / `REVIEWER_EFFORT_LEVELS` / `reviewerEffortLevels` / `normalizeReviewerSlug` / `sanitizeReviewerModelInput`) and their bounds. Dependency-free on purpose: the server suite imports it to pin the mirror against `server/lib/reviewerConfig.js`, so it must not reach for a client-only package. Re-exported by `components/cos/constants.js`. `isProviderReviewer` recognizes the shared `provider:<id>` identity alongside legacy harness slugs. |
diff --git a/client/src/lib/catalogForms.js b/client/src/lib/catalogForms.js
new file mode 100644
index 0000000000..6e72914cbd
--- /dev/null
+++ b/client/src/lib/catalogForms.js
@@ -0,0 +1,26 @@
+// Alternate forms of a cast record (other ages, eras, looks/styles). The
+// record's own fields are its canonical present-story form; `payload.forms`
+// holds the rest. A form's sheet is tagged `sheet:<variant>@<formId>` and a
+// reference is tied to a form by `library.variant.formId`.
+import { uuidv4 } from './uuid';
+
+export const FORM_ROLE_SEPARATOR = '@';
+
+// Short ids: the sheet role must fit the 64-char media role cap.
+export const newFormId = () => `form-${uuidv4().slice(0, 8)}`;
+
+// Payload field the canonical form's age lives in, per type (objects have none).
+const AGE_FIELDS = { character: 'age', place: 'era' };
+export const formAgeField = (type) => AGE_FIELDS[type] || null;
+export const formAgeLabel = (type) => (type === 'character' ? 'Age' : 'Era');
+
+export const formsOf = (payload) => (Array.isArray(payload?.forms)
+ ? payload.forms.filter((f) => f && typeof f === 'object' && typeof f.id === 'string')
+ : []);
+
+// `sheet:turnaround@form-1a2b3c4d` → { variant: 'turnaround', formId: 'form-1a2b3c4d' }.
+export function splitSheetRole(role, prefix = 'sheet:') {
+ const rest = typeof role === 'string' && role.startsWith(prefix) ? role.slice(prefix.length) : '';
+ const at = rest.indexOf(FORM_ROLE_SEPARATOR);
+ return at === -1 ? { variant: rest, formId: null } : { variant: rest.slice(0, at), formId: rest.slice(at + 1) || null };
+}
diff --git a/client/src/lib/imageThumbnailSrc.js b/client/src/lib/imageThumbnailSrc.js
new file mode 100644
index 0000000000..286855f145
--- /dev/null
+++ b/client/src/lib/imageThumbnailSrc.js
@@ -0,0 +1,7 @@
+// The served 512px WebP derivative of a gallery PNG (`/data/images/x.png` →
+// `/data/image-thumbnails/x.webp`, generated on first request), or null when
+// `src` is not a gallery PNG. Callers keep the original as the fallback.
+export function imageThumbnailSrc(src) {
+ const match = /^\/data\/images\/([^/?#]+)\.png$/i.exec(typeof src === 'string' ? src : '');
+ return match ? `/data/image-thumbnails/${match[1]}.webp` : null;
+}
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 4661b7d76b..8d62da17f8 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -37,6 +37,7 @@ export * from './bibleLimits.js';
export * from './characterEvolution.js';
export * from './characterFramework.js';
export * from './characterIntegrity.js';
+export * from './catalogForms.js';
export * from './catalogTypes.js';
export * from './creativeDirectorPlan.js';
export * from './creativeLibraries.js';
@@ -53,6 +54,7 @@ export * from './glbFailure.js';
export * from './grokVideoClip.js';
export * from './reactorVideoClip.js';
export * from './runwayVideoModels.js';
+export * from './imageThumbnailSrc.js';
export * from './imageCleaners.js';
export * from './imageGenBackends.js';
// Namespace export: imageGenBackends re-exports every imageGenModes symbol
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsx
index 56ad9f1707..3fce70f8fb 100644
--- a/client/src/pages/CatalogIngredient.jsx
+++ b/client/src/pages/CatalogIngredient.jsx
@@ -61,6 +61,7 @@ import CatalogUnlockNotice from '../components/catalog/CatalogUnlockNotice';
import CatalogPlatesPanel from '../components/catalog/CatalogPlatesPanel';
import CatalogLooksPanel from '../components/catalog/CatalogLooksPanel';
import CatalogCharacterCanon from '../components/catalog/CatalogCharacterCanon';
+import CatalogFormsEditor from '../components/catalog/CatalogFormsEditor';
import CatalogMergePanel from '../components/catalog/CatalogMergePanel';
import CatalogIdentityPanel from '../components/catalog/CatalogIdentityPanel';
import CatalogIdentityNotice from '../components/catalog/CatalogIdentityNotice';
@@ -77,6 +78,7 @@ import { useCatalogTypes } from '../hooks/useCatalogTypes.jsx';
import { timeAgo, formatDateTime } from '../utils/formatters';
import { humanizeIntegrityField } from '../lib/characterIntegrity';
import { listSheetPointers } from '../lib/sheetPointers';
+import { formsOf } from '../lib/catalogForms';
// Per-type editor field list + badge color now come from the shared registry
// (`client/src/lib/catalogTypes.js`). Each editor entry is `[key, label, kind]`
@@ -142,6 +144,9 @@ const DETAIL_TAB_ICONS = {
images: ImageIcon,
};
+// Canon types whose records carry alternate ages/looks (`payload.forms`).
+const FORM_TYPES = new Set(['character', 'place', 'object']);
+
// Payload fields the universe sheet renderer writes (via the canon→catalog
// projection); see lib/sheetPointers.js.
const SHEET_POINTER_KEYS = ['referenceSheetImageRef', 'referenceSheets'];
@@ -657,7 +662,7 @@ function IngredientEditor() {
return (
<CatalogImagePreviewProvider key={record.id} name={record.name}>
- <section className="h-full overflow-y-auto p-4 md:p-6">
+ <fieldset disabled={mergeBusy} className="flex h-full min-h-0 min-w-0 flex-col">
<UnsavedChangesConfirm
guard={routeGuard}
when={!saving}
@@ -665,31 +670,34 @@ function IngredientEditor() {
label={`Discard unsaved changes to ${record.name || 'this ingredient'}`}
onDiscard={discardAndExit}
/>
- <fieldset disabled={mergeBusy} className="w-full min-w-0 space-y-5">
- <header className="flex items-start justify-between gap-3 flex-wrap">
- <div className="flex items-start gap-3 min-w-0">
- <Sparkles className="w-6 h-6 text-port-accent mt-1 flex-shrink-0" aria-hidden="true" />
+ {/* Same flush header + sub-nav as PageHeader/RouteTabsHeader pages:
+ edge to edge under the app nav, only the content below scrolls. */}
+ <header className="shrink-0 px-3 py-2 sm:px-4 sm:py-3 border-b border-port-border">
+ <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-2">
+ <div className="flex items-center gap-2 sm:gap-3 min-w-0">
+ <Link to={backPath} aria-label={`Back to ${library?.label || 'Catalog'}`} title="Back"
+ className="shrink-0 inline-flex items-center justify-center min-w-[40px] min-h-[40px] -ml-2 rounded-lg text-gray-400 hover:text-white">
+ <ArrowLeft size={18} aria-hidden="true" />
+ </Link>
<div className="min-w-0">
- <div className="flex items-center gap-2 flex-wrap">
+ <div className="flex items-center gap-2 min-w-0">
<h1
- className="min-w-0 line-clamp-2 break-words text-2xl font-bold text-white"
+ className="min-w-0 truncate text-lg sm:text-xl font-bold text-white leading-tight"
title={record.name || '(untitled)'}
>
{record.name || '(untitled)'}
</h1>
- <span className={`text-[10px] uppercase tracking-wider px-2 py-0.5 rounded border ${badgeClass}`}>
+ <span className={`shrink-0 text-[10px] uppercase tracking-wider px-2 py-0.5 rounded border ${badgeClass}`}>
{record.type}
</span>
</div>
- <p className="text-xs text-gray-500 mt-1 font-mono break-all">{record.id}</p>
+ <p className="hidden sm:block text-xs text-gray-500 font-mono truncate leading-tight" title={record.id}>{record.id}</p>
</div>
</div>
- <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>
+ <div className="flex items-center gap-2 flex-wrap justify-end">
+ {isDirty && <span className="text-xs text-port-warning" role="status">Unsaved changes</span>}
<button type="button" onClick={handleSave} disabled={saving || lookSaving || unlocking || mergeBusy || identityReadOnly}
- 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">
+ className="inline-flex items-center gap-1.5 min-h-[40px] 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>
<AddToThreadButton
@@ -699,43 +707,45 @@ function IngredientEditor() {
label: name || record.name || record.id
}}
buttonText="Thread"
- className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm border border-port-border text-gray-300 hover:text-white hover:border-port-accent/40 transition-colors"
+ className="inline-flex items-center gap-1.5 min-h-[40px] px-3 py-2 rounded-lg text-sm border border-port-border text-gray-300 hover:text-white hover:border-port-accent/40 transition-colors"
/>
- {isDirty && <span className="text-xs text-port-warning" role="status">Unsaved changes</span>}
{armedDelete ? (
<span className="inline-flex items-center gap-1 text-sm">
- <span className="text-gray-400 px-1">Delete this ingredient?</span>
+ <span className="text-gray-400 px-1">Delete?</span>
<button type="button" onClick={confirmDelete} disabled={identityReadOnly}
- className="inline-flex items-center gap-1 px-3 py-2 rounded-lg bg-port-error/20 text-port-error hover:bg-port-error/30 font-medium">
+ className="inline-flex items-center gap-1 min-h-[40px] px-3 py-2 rounded-lg bg-port-error/20 text-port-error hover:bg-port-error/30 font-medium">
<Trash2 size={14} aria-hidden="true" /> Yes, delete
</button>
<button type="button" onClick={() => setArmedDelete(false)}
- className="px-3 py-2 rounded-lg text-gray-400 hover:text-white">
+ className="min-h-[40px] px-3 py-2 rounded-lg text-gray-400 hover:text-white">
Cancel
</button>
</span>
) : (
<button type="button" onClick={() => setArmedDelete(true)} disabled={identityReadOnly}
- className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm border border-port-border text-gray-400 hover:text-port-error"
+ className="inline-flex items-center justify-center gap-1.5 min-w-[40px] min-h-[40px] px-2.5 sm:px-3 py-2 rounded-lg text-sm border border-port-border text-gray-400 hover:text-port-error"
aria-label="Delete ingredient" title="Delete">
- <Trash2 size={14} /> Delete
+ <Trash2 size={14} aria-hidden="true" /> <span className="hidden sm:inline">Delete</span>
</button>
)}
</div>
- </header>
+ </div>
+ </header>
+
+ {tabs && (
+ <TabPills
+ tabs={tabs}
+ activeTab={activeTab}
+ onChange={(tabId) => navigate(detailTabPath(library, record.id, tabId))}
+ ariaLabel={`${library.label} record sections`}
+ className="w-full min-w-0 shrink-0"
+ />
+ )}
+ <div className="flex-1 min-h-0 overflow-y-auto p-4 md:p-6">
+ <div className="w-full min-w-0 space-y-5">
<CatalogIdentityNotice identity={record.sharedIdentity} type={record.type} />
- {tabs && (
- <TabPills
- tabs={tabs}
- activeTab={activeTab}
- onChange={(tabId) => navigate(detailTabPath(library, record.id, tabId))}
- mobileCompact
- ariaLabel={`${library.label} record sections`}
- />
- )}
-
{activeTab === 'profile' && (
<>
<div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6 space-y-4">
@@ -785,6 +795,12 @@ function IngredientEditor() {
)}
</div>
+ {FORM_TYPES.has(record.type) && (
+ <fieldset disabled={identityReadOnly} className="min-w-0">
+ <CatalogFormsEditor type={record.type} payload={payload} onChange={updatePayload} />
+ </fieldset>
+ )}
+
{record.type === 'character' && (
<>
<CatalogCharacterCanon payload={payload} />
@@ -868,7 +884,7 @@ function IngredientEditor() {
)}
{activeTab === 'references' && record.type === 'character' && (
- <CatalogReferenceLibrary ingredientId={record.id} media={media} readOnly={identityReadOnly} onChanged={refreshMedia} />
+ <CatalogReferenceLibrary ingredientId={record.id} media={media} forms={formsOf(record.payload)} readOnly={identityReadOnly} onChanged={refreshMedia} />
)}
{(activeTab === 'profile' ? !tabs : activeTab === 'references' || activeTab === 'images') && (
@@ -922,8 +938,9 @@ function IngredientEditor() {
onRestore={handleRestore}
/>
)}
- </fieldset>
- </section>
+ </div>
+ </div>
+ </fieldset>
</CatalogImagePreviewProvider>
);
}
diff --git a/client/src/pages/CatalogIngredient.test.jsx b/client/src/pages/CatalogIngredient.test.jsx
index 023158cd98..295f708c83 100644
--- a/client/src/pages/CatalogIngredient.test.jsx
+++ b/client/src/pages/CatalogIngredient.test.jsx
@@ -414,6 +414,20 @@ describe('CatalogIngredient — character sheet', () => {
await waitFor(() => expect(screen.queryByText('Unsaved changes')).toBeNull());
});
+ // Catches an added age/look never reaching the saved payload.
+ it('saves an added age or look as payload.forms', async () => {
+ updateCatalogIngredient.mockImplementation(async (_id, body) => ({ ...CHAR_FIXTURE, ...body }));
+ await renderPage();
+ fireEvent.click(await screen.findByRole('button', { name: /Add age or look/ }));
+ fireEvent.change(screen.getAllByLabelText('Name')[1], { target: { value: 'Age 7' } });
+ fireEvent.change(screen.getByLabelText('How it looks'), { target: { value: 'yellow raincoat' } });
+ fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
+ await waitFor(() => expect(updateCatalogIngredient).toHaveBeenCalled());
+ expect(updateCatalogIngredient.mock.calls[0][1].payload.forms).toEqual([
+ expect.objectContaining({ id: expect.stringMatching(/^form-/), label: 'Age 7', description: 'yellow raincoat' }),
+ ]);
+ });
+
it('keeps edits typed during a save and submits them on the next save', async () => {
let finishSave;
updateCatalogIngredient.mockImplementationOnce(() => new Promise((resolve) => { finishSave = resolve; }));
@@ -987,7 +1001,7 @@ describe('CatalogIngredient — tabbed library record pages', () => {
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'));
+ await waitFor(() => expect(screen.getByAltText('Standard turnaround').getAttribute('src')).toBe('/data/image-thumbnails/sheet-1.webp'));
// Sheets don't carry the profile form or the general media panel.
expect(screen.queryByLabelText('Name')).toBeNull();
expect(screen.queryByAltText('mood.png')).toBeNull();
@@ -1002,7 +1016,7 @@ describe('CatalogIngredient — tabbed library record pages', () => {
id: 'example', type, name: 'Example subject', payload: { primaryImageRef: 'cover.png' },
}));
await renderPage(route);
- expect(screen.getByAltText('Example subject cover')).toHaveAttribute('src', '/data/images/cover.png');
+ expect(screen.getByAltText('Example subject cover')).toHaveAttribute('src', '/data/image-thumbnails/cover.webp');
fireEvent.click(screen.getByRole('button', { name: 'Enlarge Example subject cover' }));
const preview = screen.getByRole('dialog', { name: 'Example subject cover' });
expect(within(preview).getByAltText('Example subject cover')).toHaveAttribute('data-fallback-src', '/data/image-refs/cover.png');
@@ -1017,11 +1031,11 @@ describe('CatalogIngredient — tabbed library record pages', () => {
media: [{ kind: 'portrait', mediaKey: 'chosen.png' }, { kind: 'reference', mediaKey: 'chosen.png' }],
});
const page = await renderPage('/casting/cat-chr-hero/profile');
- expect(screen.getByAltText('Example Hero cover')).toHaveAttribute('src', '/data/images/chosen.png');
+ expect(screen.getByAltText('Example Hero cover')).toHaveAttribute('src', '/data/image-thumbnails/chosen.webp');
page.unmount();
await renderPage('/casting/cat-chr-hero/references');
- expect(screen.getByAltText('Example Hero canon reference')).toHaveAttribute('src', '/data/images/primary.png');
- expect(screen.getAllByRole('img').filter((image) => image.getAttribute('src') === '/data/images/chosen.png')).toHaveLength(1);
+ expect(screen.getByAltText('Example Hero canon reference')).toHaveAttribute('src', '/data/image-thumbnails/primary.webp');
+ expect(screen.getAllByRole('img').filter((image) => image.getAttribute('src') === '/data/image-thumbnails/chosen.webp')).toHaveLength(1);
});
it('keeps archive-only reference media visible on References without using it as a profile cover', async () => {
@@ -1033,7 +1047,7 @@ describe('CatalogIngredient — tabbed library record pages', () => {
expect(screen.queryByAltText('Example Hero cover')).not.toBeInTheDocument();
profile.unmount();
await renderPage('/casting/cat-chr-hero/references');
- expect(screen.getByAltText('Archived source image')).toHaveAttribute('src', '/data/images/archived-source.png');
+ expect(screen.getByAltText('Archived source image')).toHaveAttribute('src', '/data/image-thumbnails/archived-source.webp');
expect(screen.getByRole('button', { name: 'Enlarge Archived source image' })).toBeInTheDocument();
});
@@ -1134,8 +1148,8 @@ describe('CatalogIngredient — tabbed library record pages', () => {
}));
await renderPage('/casting/cat-chr-hero/references');
expect(screen.getAllByAltText('Example Hero canon reference')).toHaveLength(1);
- expect(screen.getByAltText('Example Hero canon reference')).toHaveAttribute('src', '/data/images/existing.png');
- expect(screen.getByAltText('Example Hero canon reference')).toHaveAttribute('data-fallback-src', '/data/image-refs/existing.png');
+ expect(screen.getByAltText('Example Hero canon reference')).toHaveAttribute('src', '/data/image-thumbnails/existing.webp');
+ expect(screen.getByAltText('Example Hero canon reference')).toHaveAttribute('data-fallback-src', '/data/images/existing.png,/data/image-refs/existing.png');
expect(screen.getByText('Primary canon reference')).toBeInTheDocument();
expect(screen.queryByText(/No media yet/)).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Detach', exact: true })).not.toBeInTheDocument();
@@ -1151,9 +1165,9 @@ describe('CatalogIngredient — tabbed library record pages', () => {
});
await renderPage('/casting/cat-chr-hero/references');
const images = screen.getAllByRole('img').map((image) => image.getAttribute('src'));
- expect(images.filter((src) => src === '/data/images/mood.png')).toHaveLength(1);
- expect(images.filter((src) => src === '/data/images/canon-only.png')).toHaveLength(1);
- expect(images).not.toContain('/data/images/sheet-1.png');
+ expect(images.filter((src) => src === '/data/image-thumbnails/mood.webp')).toHaveLength(1);
+ expect(images.filter((src) => src === '/data/image-thumbnails/canon-only.webp')).toHaveLength(1);
+ expect(images).not.toContain('/data/image-thumbnails/sheet-1.webp');
});
it('previews the chosen variant and posts it on Generate, then attaches the finished sheet', async () => {
@@ -1229,10 +1243,10 @@ describe('CatalogIngredient — tabbed library record pages', () => {
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(srcs).toContain('/data/image-thumbnails/mood.webp');
+ expect(srcs).not.toContain('/data/image-thumbnails/sheet-1.webp');
+ expect(srcs).not.toContain('/data/image-thumbnails/plate-1.webp');
+ expect(srcs).not.toContain('/data/image-thumbnails/look-1.webp');
expect(screen.queryByLabelText('Name')).toBeNull();
});
@@ -1247,7 +1261,7 @@ describe('CatalogIngredient — tabbed library record pages', () => {
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'));
+ await waitFor(() => expect(screen.getByAltText('Red scarf').getAttribute('src')).toBe('/data/image-thumbnails/look-1.webp'));
fireEvent.click(screen.getByRole('button', { name: /^Generate$/ }));
expect(await screen.findByRole('button', { name: '+ Universe style' })).toBeTruthy();
@@ -1299,7 +1313,7 @@ describe('CatalogIngredient — tabbed library record pages', () => {
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'));
+ .toContain('/data/image-thumbnails/look-1.webp'));
});
});
diff --git a/server/lib/bibleLimits.js b/server/lib/bibleLimits.js
index ffb979cd38..9d87ced747 100644
--- a/server/lib/bibleLimits.js
+++ b/server/lib/bibleLimits.js
@@ -156,6 +156,12 @@ export const BIBLE_LIMITS = Object.freeze({
WARDROBE_NAME_MAX: 120,
WARDROBE_DESCRIPTION_MAX: 800,
WARDROBES_PER_CHARACTER_MAX: 10,
+ // Alternate forms (other ages, eras, looks/styles) of any canon entry. The
+ // entry's own fields are its canonical present-story form.
+ FORM_LABEL_MAX: 80,
+ FORM_AGE_MAX: 80,
+ FORM_DESCRIPTION_MAX: 1500,
+ FORMS_PER_ENTRY_MAX: 12,
EVIDENCE_ITEM_MAX: 500,
EVIDENCE_PER_ENTRY_MAX: 20,
// Places
diff --git a/server/lib/catalogMediaLibrary.js b/server/lib/catalogMediaLibrary.js
index 5ec7f8f4d0..b56ad45db6 100644
--- a/server/lib/catalogMediaLibrary.js
+++ b/server/lib/catalogMediaLibrary.js
@@ -37,6 +37,10 @@ export function normalizeLibrary(value) {
if (CAST_ERAS.includes(variant.era)) v.era = variant.era;
const wardrobeId = cleanStr(variant.wardrobeId, 59);
if (wardrobeId) v.wardrobeId = wardrobeId;
+ // The record's `payload.forms[]` entry this asset shows; absent = the
+ // canonical present-story form.
+ const formId = cleanStr(variant.formId, 24);
+ if (formId) v.formId = formId;
const label = cleanStr(variant.label, 120);
if (label) v.label = label;
if (Object.keys(v).length) out.variant = v;
@@ -50,7 +54,7 @@ export function normalizeLibrary(value) {
const mediaEra = (m) => m?.library?.variant?.era || eraForAge(m?.library?.variant?.age);
-/** Filter live media rows by `{ age, era, wardrobeId, tag, kind, guide }`. */
+/** Filter live media rows by `{ age, era, wardrobeId, formId, tag, kind, guide }`. */
export function filterLibraryMedia(media, filters = {}) {
const list = Array.isArray(media) ? media : [];
return list.filter((m) => {
@@ -60,6 +64,7 @@ export function filterLibraryMedia(media, filters = {}) {
if (Number.isInteger(filters.age) && lib.variant?.age !== filters.age) return false;
if (filters.era && mediaEra(m) !== filters.era) return false;
if (filters.wardrobeId && lib.variant?.wardrobeId !== filters.wardrobeId) return false;
+ if (filters.formId && lib.variant?.formId !== filters.formId) return false;
if (filters.tag && !(lib.tags || []).includes(String(filters.tag).toLowerCase())) return false;
if (filters.guide === true && lib.guide !== true) return false;
return true;
@@ -75,6 +80,7 @@ function score(m, want) {
const wantEra = want.era || eraForAge(want.age);
if (wantEra && mediaEra(m) === wantEra) s += 30;
if (want.wardrobeId && v.wardrobeId === want.wardrobeId) s += 20;
+ if (want.formId && v.formId === want.formId) s += 40;
if (m.library?.guide) s += 10;
if (m.kind === 'portrait') s += 5;
return s;
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index b99a335504..2775fe538a 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -11,7 +11,7 @@
*/
import { z } from 'zod';
-import { BIBLE_LIMITS } from './storyBible.js';
+import { BIBLE_LIMITS, FORM_ID_PATTERN } from './storyBible.js';
import {
INGREDIENT_TYPE_IDS,
RELATION_KIND_IDS,
@@ -383,6 +383,7 @@ export const catalogMediaLibraryVariantSchema = z.object({
age: z.number().int().min(0).max(150).optional(),
era: z.enum(['child', 'teen', 'adult', 'elder']).optional(),
wardrobeId: z.string().trim().min(1).max(59).optional(),
+ formId: z.string().trim().regex(FORM_ID_PATTERN).optional(),
label: z.string().trim().max(120).optional(),
}).strict();
export const catalogMediaLibraryPatchSchema = z.object({
@@ -405,6 +406,7 @@ export const catalogMediaLibraryQuerySchema = z.object({
age: z.coerce.number().int().min(0).max(150).optional(),
era: z.enum(['child', 'teen', 'adult', 'elder']).optional(),
wardrobeId: z.string().trim().min(1).max(59).optional(),
+ formId: z.string().trim().regex(FORM_ID_PATTERN).optional(),
tag: z.string().trim().min(1).max(40).optional(),
kind: z.enum(MEDIA_KINDS).optional(),
guide: z.enum(['true', 'false']).optional(),
@@ -423,10 +425,13 @@ export const catalogPortraitSetSchema = z.object({
// 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.
+// `formId` renders the sheet for one of the record's alternate forms (another
+// age, era or look/style); absent renders the canonical present-story form.
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(),
+ formId: z.string().trim().regex(FORM_ID_PATTERN).optional(),
overridePrompt: z.string().max(8000).optional(),
overrideNegativePrompt: z.string().max(2000).optional(),
modelId: z.string().trim().max(64).optional(),
@@ -437,6 +442,9 @@ export const catalogSheetRenderSchema = z.object({
} else if (!isLook && body.wardrobeId) {
ctx.addIssue({ code: 'custom', path: ['wardrobeId'], message: 'wardrobeId is only accepted for a look render' });
}
+ if (isLook && body.formId) {
+ ctx.addIssue({ code: 'custom', path: ['formId'], message: 'formId is not accepted for a look render' });
+ }
});
// Media detach body — identifies the tuple to soft-delete.
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index ccfa5b0257..ed874baca6 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -82,7 +82,10 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// Reality universe as fiction.
// v13 = durable character sheet request identities (#11669). Older peers
// must not strip supersession state during an unrelated canon edit.
- universes: 13,
+ // v14 = canon entries gained optional `forms[]` (alternate ages, eras and
+ // looks/styles beside the canonical present-story form). A <=v13 peer would
+ // sanitize them away and LWW the loss back.
+ universes: 14,
// v1 = post-split. Migrations 035/036 introduced the pipeline collection
// layout for issues and series.
// v2 = `stages.audio.audioMode` + `stages.audio.cues[]` added (whole-episode
@@ -444,7 +447,10 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// v12 = `catalog_ingredient_media.library` (Casting reference library:
// variant age/era/wardrobe, tags, render-guide flag). A ≤v11 receiver would
// drop it and whole-row LWW it back, so live transfers need equal versions.
- catalog: 12,
+ // v13 = bible payloads gained optional `forms[]` (alternate ages/looks) and
+ // media `library.variant.formId`. A <=v12 peer's sanitizer and library
+ // normalizer would strip both and whole-row LWW the loss back.
+ catalog: 13,
// v1 = cross-machine resumable Story Builder sessions (#730). Sessions are
// local-only by default and excluded from sync; only `sync: true` sessions
// ride the `storyBuilder` snapshot category. This is a brand-NEW synced
diff --git a/server/lib/storyBible.js b/server/lib/storyBible.js
index b75137bfab..17402bf95e 100644
--- a/server/lib/storyBible.js
+++ b/server/lib/storyBible.js
@@ -454,10 +454,16 @@ const ADDITIVE_CHARACTER_FIELD_VERSIONS = Object.freeze({
psychology: 11,
// v13 — durable per-variant render intent (#11669).
referenceSheetRequests: 13,
+ // v14 — alternate ages/looks beside the canonical form.
+ forms: 14,
});
const ADDITIVE_OBJECT_FIELD_VERSIONS = Object.freeze({
// v7 — structured object↔character attachments (#1288).
attachments: 7,
+ forms: 14,
+});
+const ADDITIVE_PLACE_FIELD_VERSIONS = Object.freeze({
+ forms: 14,
});
// "The sender carried nothing here." Covers both absent-when-empty fields
@@ -507,6 +513,13 @@ export function preserveLegacyCharacterFields(remoteCharacters, localCharacters,
);
}
+/** Preserve additive place fields when an older peer wins LWW. */
+export function preserveLegacyPlaceFields(remotePlaces, localPlaces, senderUniversesVersion) {
+ return preserveLegacyEntryFields(
+ remotePlaces, localPlaces, ADDITIVE_PLACE_FIELD_VERSIONS, senderUniversesVersion,
+ );
+}
+
/** Preserve additive object fields when an older peer wins LWW. */
export function preserveLegacyObjectFields(remoteObjects, localObjects, senderUniversesVersion) {
return preserveLegacyEntryFields(
@@ -818,6 +831,22 @@ function sanitizeCharacterSliders(raw) {
return Object.fromEntries(CHARACTER_SLIDER_AXES.map((axis) => [axis, ensureSlider(src[axis])]));
}
+// Alternate form of a canon entry: another age, era or look/style of the same
+// subject. Ids stay short because a form's sheet role is
+// `sheet:<variant>@<formId>` under the 64-char media role cap.
+export const FORM_ID_PATTERN = /^[A-Za-z0-9_-]{1,24}$/;
+function sanitizeForm(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const label = trimTo(raw.label, BIBLE_LIMITS.FORM_LABEL_MAX);
+ if (!label) return null;
+ return {
+ id: isStr(raw.id) && FORM_ID_PATTERN.test(raw.id) ? raw.id : `form-${randomUUID().slice(0, 8)}`,
+ label,
+ age: trimTo(raw.age, BIBLE_LIMITS.FORM_AGE_MAX),
+ description: trimTo(raw.description, BIBLE_LIMITS.FORM_DESCRIPTION_MAX),
+ };
+}
+
// Shared canon extras applied to every kind. Persists explicit `locked: true`
// AND `locked: false` so a Universe-Builder caller can flip the bit and have
// the change survive round-trips. Missing `locked` still collapses to absent
@@ -848,6 +877,12 @@ function applyCanonExtras(raw) {
else if (raw.locked === false) out.locked = false;
if (raw.spoiler === true) out.spoiler = true;
else if (raw.spoiler === false) out.spoiler = false;
+ // Absent stays absent so entries without alternate forms keep their shape.
+ if (Array.isArray(raw.forms)) {
+ const seen = new Set();
+ out.forms = sanitizeListWith(raw.forms, sanitizeForm, BIBLE_LIMITS.FORMS_PER_ENTRY_MAX)
+ .filter((form) => !seen.has(form.id) && seen.add(form.id));
+ }
return out;
}
diff --git a/server/routes/catalogSheets.test.js b/server/routes/catalogSheets.test.js
index 352e60bc40..3a4a9a4a4c 100644
--- a/server/routes/catalogSheets.test.js
+++ b/server/routes/catalogSheets.test.js
@@ -231,4 +231,58 @@ describe('catalog sheet routes', () => {
expect(mocks.enqueueJob).not.toHaveBeenCalled();
});
});
+
+ describe('alternate age/look sheets', () => {
+ const aged = {
+ ...character,
+ payload: {
+ ...character.payload, age: '34',
+ forms: [
+ { id: 'form-kid', label: 'Age 7', age: '7', description: 'gap-toothed, oversized yellow raincoat' },
+ { id: 'form-empty', label: 'Someday', age: '', description: '' },
+ ],
+ },
+ };
+
+ // Catches a form sheet overwriting the canonical universe pointer (delegated),
+ // landing under the canonical role, or still describing the adult.
+ it('renders a form through the catalog path with its age and look, tagged sheet:<variant>@<formId>', async () => {
+ mocks.getIngredient.mockResolvedValue(aged);
+ mocks.listLiveRefsForIngredient.mockResolvedValue([{ refKind: 'universe', refId: 'universe-1' }]);
+ mocks.getUniverse.mockResolvedValue({
+ id: 'universe-1', name: 'Example Universe', influences: { embrace: [] },
+ characters: [{ id: 'char-entry-1', name: 'Example Hero', ingredientId: 'cat-chr-1' }],
+ });
+ const body = { variant: 'blueprint', formId: 'form-kid' };
+ const preview = await request(app).post('/api/catalog/ingredients/cat-chr-1/sheets/preview').send(body);
+ expect(preview.status).toBe(200);
+ const res = await request(app).post('/api/catalog/ingredients/cat-chr-1/sheets').send(body);
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ role: 'sheet:blueprint@form-kid', delegatedTo: null });
+ const params = queuedParams();
+ expect(params.catalogAttach).toEqual({ ingredientId: 'cat-chr-1', kind: 'reference', role: 'sheet:blueprint@form-kid' });
+ expect(params.prompt).toContain('oversized yellow raincoat');
+ expect(params.prompt).not.toContain('silver coat');
+ expect(preview.body.preview.sentPrompt).toBe(params.prompt);
+ expect(mocks.updateUniverse).not.toHaveBeenCalled();
+ });
+
+ it('refuses an unknown form, an undescribed form and a form on a look', async () => {
+ mocks.getIngredient.mockResolvedValue(aged);
+ const post = (body) => request(app).post('/api/catalog/ingredients/cat-chr-1/sheets').send(body);
+ expect((await post({ formId: 'form-nope' })).status).toBe(400);
+ expect((await post({ formId: 'form-empty' })).status).toBe(400);
+ expect((await post({ variant: 'look', wardrobeId: 'wd-x', formId: 'form-kid' })).status).toBe(400);
+ expect(mocks.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('swaps a place form into its era and description', async () => {
+ mocks.getIngredient.mockResolvedValue({ ...place, payload: { ...place.payload, era: '1985',
+ forms: [{ id: 'form-ruin', label: 'Ruined', age: '2040', description: 'collapsed piers, rusted cranes' }] } });
+ const res = await request(app).post('/api/catalog/ingredients/cat-plc-1/sheets').send({ formId: 'form-ruin' });
+ expect(res.status).toBe(200);
+ expect(queuedParams().prompt).toContain('collapsed piers, rusted cranes');
+ expect(queuedParams().catalogAttach.role).toBe('sheet:environment@form-ruin');
+ });
+ });
});
diff --git a/server/services/catalogSheet.js b/server/services/catalogSheet.js
index 2b51273a75..b348d78a04 100644
--- a/server/services/catalogSheet.js
+++ b/server/services/catalogSheet.js
@@ -15,6 +15,13 @@ import { assertCatalogIdentityWritable } from './catalogDB/identityAccess.js';
* 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>'`.
+ *
+ * A `formId` render draws one of the record's `payload.forms` (another age,
+ * era or look/style) instead of its canonical present-story form: the form's
+ * age and description stand in for the record's own age/era and appearance
+ * text, and the image is tagged `role: 'sheet:<variant>@<formId>'`. Like a
+ * look it always renders through the catalog path, so the universe canon
+ * pointer keeps holding the canonical sheet.
*/
import { ServerError } from '../lib/errorHandler.js';
@@ -102,6 +109,44 @@ function lookVariantFor(ingredient, payload, wardrobeId) {
};
}
+// Which payload fields a form's age and description replace, per type.
+const FORM_FIELDS = Object.freeze({
+ character: { age: 'age', description: 'physicalDescription' },
+ place: { age: 'era', description: 'description' },
+ object: { age: null, description: 'description' },
+});
+const MEDIA_ROLE_MAX = 64;
+
+function formFor(ingredient, payload, formId) {
+ if (!formId) return null;
+ const forms = Array.isArray(payload.forms) ? payload.forms : [];
+ const form = forms.find((f) => f && typeof f === 'object' && f.id === formId);
+ if (!form) {
+ throw new ServerError(`"${ingredient.name}" has no age or look with id "${formId}"`,
+ { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const age = typeof form.age === 'string' ? form.age.trim() : '';
+ const description = typeof form.description === 'string' ? form.description.trim() : '';
+ if (!age && !description) {
+ throw new ServerError(`Describe how "${form.label}" looks before rendering its sheet`,
+ { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ return { ...form, age, description };
+}
+
+// The payload a form's sheet builds from: the record with its age/look swapped in.
+function payloadForForm(type, payload, form) {
+ if (!form) return payload;
+ const fields = FORM_FIELDS[type] || FORM_FIELDS.object;
+ const out = { ...payload };
+ if (form.description) out[fields.description] = form.description;
+ if (form.age) {
+ if (fields.age) out[fields.age] = form.age;
+ else out[fields.description] = [out[fields.description], form.age].filter(Boolean).join(' — ');
+ }
+ return out;
+}
+
// Load + guard the record, resolve its variant and any universe it links to.
async function resolveSheetTarget(id, options) {
const ingredient = await getIngredient(id);
@@ -115,7 +160,7 @@ async function resolveSheetTarget(id, options) {
}
const isLook = options.variant === CATALOG_LOOK_VARIANT_ID;
const variants = variantsForType(ingredient.type);
- const variant = isLook
+ let variant = isLook
? lookVariantFor(ingredient, payload, options.wardrobeId)
: options.variant
? variants.find((v) => v.id === options.variant)
@@ -126,6 +171,14 @@ async function resolveSheetTarget(id, options) {
{ status: 400, code: 'VALIDATION_ERROR' },
);
}
+ const form = formFor(ingredient, payload, options.formId);
+ if (form) {
+ const role = `sheet:${variant.id}@${form.id}`;
+ if (role.length > MEDIA_ROLE_MAX) {
+ throw new ServerError(`Sheet role "${role}" exceeds ${MEDIA_ROLE_MAX} characters`, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ variant = { ...variant, label: `${variant.label} · ${form.label}`, role };
+ }
const refs = await listLiveRefsForIngredient(id);
const universes = [];
@@ -138,13 +191,13 @@ async function resolveSheetTarget(id, options) {
// A local consolidation retains embedded source variants. Render its
// authoritative merged payload instead of delegating to a stale canon copy.
const identityIds = await getIngredientIdentityIds(ingredient.id);
- if (ingredient.type === 'character' && !isLook && identityIds.length === 1) {
+ if (ingredient.type === 'character' && !isLook && !form && identityIds.length === 1) {
for (const universe of universes) {
const entry = (universe.characters || []).find((c) => c.ingredientId === ingredient.id);
if (entry) return { ingredient, payload, variant, delegate: { universeId: universe.id, entryId: entry.id } };
}
}
- return { ingredient, payload, variant, universe: universes[0] ?? null };
+ return { ingredient, payload: payloadForForm(ingredient.type, payload, form), variant, universe: universes[0] ?? null };
}
async function buildCatalogSheet(target, options) {
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index 18f279b301..512f9cba17 100644
--- a/server/services/dataSync.pipelineUniverse.test.js
+++ b/server/services/dataSync.pipelineUniverse.test.js
@@ -163,19 +163,19 @@ describe('dataSync — universe category', () => {
const snap = await dataSync.getSnapshot('universe');
expect(snap.portosMeta).toBeDefined();
expect(typeof snap.portosMeta.portosVersion).toBe('string');
- expect(snap.portosMeta.schemaVersions.universes).toBe(13);
+ expect(snap.portosMeta.schemaVersions.universes).toBe(14);
});
it('applyRemote rejects when sender schemaVersions are AHEAD of local code', async () => {
writeUniverseState({ universes: [], runs: [] });
const result = await dataSync.applyRemote('universe', {
universes: [{ id: 'u-new', name: 'Foundry', updatedAt: '2026-05-17T10:00:00Z' }],
- }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 14 } } });
+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 15 } } });
expect(result.applied).toBe(false);
expect(result.count).toBe(0);
expect(result.blockedBySchema).toBeDefined();
expect(result.blockedBySchema.ahead).toEqual([
- { category: 'universes', senderV: 14, receiverV: 13 },
+ { category: 'universes', senderV: 15, receiverV: 14 },
]);
expect(result.blockedBySchema.senderPortosVersion).toBe('99.0.0');
// Nothing was written.
@@ -232,6 +232,23 @@ describe('dataSync — universe category', () => {
expect(readUniverseState().universes[0].characters[0].referenceSheetRequests).toEqual({ standard: next });
});
+ // Catches an older peer's unrelated canon edit stripping alternate ages/looks.
+ it('keeps character and place forms when a pre-forms peer wins LWW', async () => {
+ const base = { id: 'u-forms', name: 'Example', createdAt: '2026-05-17T09:00:00Z' };
+ const kid = { id: 'form-kid', label: 'Age 7', age: '7', description: 'yellow raincoat' };
+ writeUniverseState({ universes: [{ ...base, updatedAt: '2026-05-17T10:00:00Z',
+ characters: [{ id: 'character-1', name: 'Example', forms: [kid] }],
+ places: [{ id: 'place-1', name: 'Harbor', forms: [{ ...kid, id: 'form-ruin', label: 'Ruined' }] }],
+ }], runs: [] });
+ const behind = await dataSync.applyRemote('universe', { universes: [{ ...base, updatedAt: '2026-05-17T11:00:00Z',
+ characters: [{ id: 'character-1', name: 'Peer edit' }], places: [{ id: 'place-1', name: 'Harbor' }],
+ }] }, { portosMeta: { schemaVersions: { universes: 13 } } });
+ expect(behind.applied).toBe(true);
+ const [universe] = readUniverseState().universes;
+ expect(universe.characters[0].forms).toEqual([kid]);
+ expect(universe.places[0].forms[0].label).toBe('Ruined');
+ });
+
it('applyRemote falls through for legacy senders that send NO portosMeta at all', async () => {
writeUniverseState({ universes: [], runs: [] });
const result = await dataSync.applyRemote('universe', {
diff --git a/server/services/universeBuilder/sync.js b/server/services/universeBuilder/sync.js
index cd563e527e..68725f762a 100644
--- a/server/services/universeBuilder/sync.js
+++ b/server/services/universeBuilder/sync.js
@@ -9,7 +9,7 @@
*/
import {
- isLegacyAbsentValue, preserveLegacyCharacterFields, preserveLegacyObjectFields,
+ isLegacyAbsentValue, preserveLegacyCharacterFields, preserveLegacyObjectFields, preserveLegacyPlaceFields,
} from '../../lib/storyBible.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,
@@ -73,6 +73,7 @@ export function preserveLegacyUniverseFields(remote, local, senderUniversesVersi
// Only touch the lists the remote carries — a raw share-bucket record may
// omit one, and an `undefined`-valued key would clobber it in a patch merge.
if ('characters' in out) out.characters = preserveLegacyCharacterFields(out.characters, local.characters, sender);
+ if ('places' in out) out.places = preserveLegacyPlaceFields(out.places, local.places, sender);
if ('objects' in out) out.objects = preserveLegacyObjectFields(out.objects, local.objects, sender);
return out;
}