Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(catalog): expose stored character canon and reference images (#11975)
[._.]/989202c33cef
diff --git a/client/src/components/catalog/CatalogCharacterCanon.jsx b/client/src/components/catalog/CatalogCharacterCanon.jsxnew file mode 100644index 0000000000..7fdffc3e28--- /dev/null+++ b/client/src/components/catalog/CatalogCharacterCanon.jsx@@ -0,0 +1,111 @@+import CollapsibleSection from '../ui/CollapsibleSection';+import {+ CHARACTER_FRAMEWORK_EDITOR_FIELDS,+ CHARACTER_PSYCHOLOGY_EDITOR_FIELDS,+ CHARACTER_PSYCHOLOGY_NOTE_FIELD,+ CHARACTER_SLIDER_AXES,+ PSYCHOLOGY_DRIVE_AXES,+} from '../../lib/characterFramework';+import { humanizeIntegrityField } from '../../lib/characterIntegrity';+import { formatCount } from '../../utils/formatters';++const object = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};+const list = (value) => Array.isArray(value) ? value : [];+const text = (value) => typeof value === 'string' ? value.trim()+ : typeof value === 'number' && Number.isFinite(value) ? formatCount(value) : '';+const strings = (value) => list(value).filter((item) => typeof item === 'string' && item.trim()).join('\n');+const fields = (value, descriptors) => descriptors.map(({ name, label }) => [label, text(object(value)[name])]);++// These are authored canon fields, not a dump of the payload's control fields+// or provider metadata. Shared editor descriptors keep narrative labels aligned+// with the Universe and Writers Room surfaces that own their structured editors.+export default function CatalogCharacterCanon({ payload }) {+ const canon = object(payload);+ const psychology = object(canon.psychology);+ const voice = object(canon.voiceCanon);+ const groups = [+ ['Character framework', [+ ...fields(canon, CHARACTER_FRAMEWORK_EDITOR_FIELDS),+ ['Arc type', text(canon.arcType)],+ ['Secrets', strings(canon.secrets)],+ ...CHARACTER_SLIDER_AXES.map((axis) => [humanizeIntegrityField(axis), text(object(canon.sliders)[axis])]),+ ]],+ ['Psychology', [+ ['Assessment', text(psychology.assessment)],+ ...fields(psychology, [...CHARACTER_PSYCHOLOGY_EDITOR_FIELDS, CHARACTER_PSYCHOLOGY_NOTE_FIELD]),+ ...PSYCHOLOGY_DRIVE_AXES.flatMap((axis) => {+ const drive = object(object(psychology.drives)[axis]);+ return ['desire', 'fear'].map((key) => [humanizeIntegrityField(`${axis}.${key}`), text(drive[key])]);+ }),+ ]],+ ['Props', list(canon.props).flatMap((item) => {+ const prop = object(item);+ const name = text(prop.name);+ if (!name) return [];+ const details = fields(prop, [+ { name: 'purpose', label: 'Purpose' },+ { name: 'materials', label: 'Materials' },+ { name: 'notes', label: 'Notes' },+ ]).filter(([, value]) => value).map(([label, value]) => `${label}: ${value}`).join('\n');+ return [[name, details || 'No further description.']];+ })],+ ...[['expressions', 'Expressions'], ['handGestures', 'Hand gestures']].map(([key, label]) => [+ label, list(canon[key]).flatMap((item) => {+ const row = object(item);+ return text(row.name) ? [[text(row.name), text(row.description) || 'No further description.']] : [];+ }),+ ]),+ ['Character relationships', list(canon.relationshipLinks).flatMap((item) => {+ const row = object(item);+ const target = text(row.targetCharacterId);+ if (!target) return [];+ const opposition = object(row.opposition);+ return [[target, [text(row.type), text(row.description),+ ...fields(opposition, [+ { name: 'axis', label: 'Opposition' },+ { name: 'thisRole', label: 'This character' },+ { name: 'targetRole', label: 'Other character' },+ { name: 'note', label: 'Note' },+ ]).filter(([, value]) => value).map(([label, value]) => `${label}: ${value}`),+ ].filter(Boolean).join('\n') || 'Linked character']];+ })],+ ['Voice direction', [+ ['Description', text(voice.description)],+ ['Default delivery', text(voice.defaultDelivery)],+ ['Emotional range', strings(voice.emotionalRange)],+ ['Avoid', strings(voice.avoid)],+ ['Source policy', text(voice.sourcePolicy)],+ ['Review status', typeof voice.approved === 'boolean' ? (voice.approved ? 'Approved' : 'Candidate') : ''],+ ...list(voice.pronunciations).flatMap((item) => {+ const row = object(item);+ return text(row.term) && text(row.pronunciation) ? [[text(row.term), text(row.pronunciation)]] : [];+ }),+ ]],+ ['Story evidence', [+ ['First appearance', text(canon.firstAppearance)],+ ['Missing from prose', strings(canon.missingFromProse)],+ ]],+ ['Production', [['Generation prompt', text(canon.prompt)]]],+ ].map(([label, rows]) => [label, rows.filter(([, value]) => value)])+ .filter(([, rows]) => rows.length > 0);++ if (groups.length === 0) return null;+ return (+ <section aria-label="Additional character canon" className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <h2 className="text-sm font-semibold text-white">Additional character canon</h2>+ <p className="text-xs text-gray-500">Stored story and production details. Read-only here.</p>+ {groups.map(([label, rows]) => (+ <CollapsibleSection key={label} label={label} size="bar" defaultOpen bodyClassName="pb-3">+ <dl className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ {rows.map(([name, value], index) => (+ <div key={`${name}-${index}`} className="min-w-0">+ <dt className="text-xs font-medium text-gray-400 break-words">{name}</dt>+ <dd className="text-sm text-gray-300 whitespace-pre-wrap break-words">{value}</dd>+ </div>+ ))}+ </dl>+ </CollapsibleSection>+ ))}+ </section>+ );+}diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsxindex 4c0db728cc..7e037a9fff 100644--- a/client/src/pages/CatalogIngredient.jsx+++ b/client/src/pages/CatalogIngredient.jsx@@ -56,6 +56,7 @@ import CatalogSheetsPanel, { ReferenceSheetPanel } from '../components/catalog/Cimport CatalogUnlockNotice from '../components/catalog/CatalogUnlockNotice';import CatalogPlatesPanel from '../components/catalog/CatalogPlatesPanel';import CatalogLooksPanel from '../components/catalog/CatalogLooksPanel';+import CatalogCharacterCanon from '../components/catalog/CatalogCharacterCanon';import CharacterLoraChip from '../components/loraTraining/CharacterLoraChip';import TagPicker from '../components/TagPicker';import GenericIngredientFields from '../components/GenericIngredientFields';@@ -67,6 +68,7 @@ import {} from '../lib/creativeLibraries';import { useCatalogTypes } from '../hooks/useCatalogTypes.jsx';import { timeAgo, formatDateTime } from '../utils/formatters';+import { humanizeIntegrityField } from '../lib/characterIntegrity';// 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]`@@ -723,6 +725,7 @@ export default function CatalogIngredient() {{record.type === 'character' && (<>+ <CatalogCharacterCanon payload={payload} />{!tabs && <ReferenceSheetPanel payload={payload} universeRef={universeRef} />}{/* Trained-LoRA link + dataset entry point. The catalog id IS theingredientId the trained sidecars carry; the universe entryId@@ -804,6 +807,9 @@ export default function CatalogIngredient() {{(activeTab === 'profile' ? !tabs : activeTab === 'references' || activeTab === 'images') && (<MediaPanelmedia={tabs ? media.filter(isReferenceTabRow) : media}+ canonImageRefs={Array.isArray(payload.imageRefs) ? payload.imageRefs.filter((ref) =>+ !media.some((m) => (m.kind === 'portrait' || m.kind === 'reference') && m.mediaKey === ref)) : []}+ primaryImageRef={payload.primaryImageRef}missingMedia={missingMedia}onAttach={handleAttachMedia}onSetPortrait={handleSetPortrait}@@ -1369,7 +1375,7 @@ function GenerateImageControl({ ingredientId, name, description, universeId, onC);}-function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, onUploadFile, onRecordVoice, genIngredientId, genName, genDescription, genUniverseId, onGenerated }) {+function MediaPanel({ media, canonImageRefs = [], primaryImageRef, missingMedia, onAttach, onSetPortrait, onDetach, onUploadFile, onRecordVoice, genIngredientId, genName, genDescription, genUniverseId, onGenerated }) {const [pickerOpen, setPickerOpen] = useState(false);const [dragOver, setDragOver] = useState(false);const [busy, setBusy] = useState(false); // upload or transcription in flight@@ -1378,6 +1384,7 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, onconst list = Array.isArray(media) ? media : [];const portrait = list.find((m) => m.kind === 'portrait');const others = list.filter((m) => m.kind !== 'portrait');+ const canonImages = [...new Set(canonImageRefs.filter((ref) => typeof ref === 'string' && ref.trim()))];const doUpload = async (file) => {if (!file || busy) return;@@ -1485,7 +1492,26 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, on</div>)}- {list.length === 0 && (+ {canonImages.length > 0 && (+ <div className="mt-3 space-y-2">+ <h3 className="text-xs font-semibold text-gray-300">Canon images</h3>+ <p className="text-xs text-gray-500">Existing canon references, shown read-only.</p>+ <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">+ {canonImages.map((filename) => (+ <figure key={filename} className="min-w-0 rounded border border-port-border overflow-hidden bg-port-bg">+ <MediaImage src={`/data/images/${encodeURIComponent(filename)}`} alt={`${genName} canon reference`}+ fallbackSrc={`/data/image-refs/${encodeURIComponent(filename)}`}+ className="w-full aspect-square object-contain" />+ <figcaption className="text-xs text-gray-400 p-2 break-words">+ {filename === primaryImageRef ? 'Primary canon reference' : 'Canon reference'}+ </figcaption>+ </figure>+ ))}+ </div>+ </div>+ )}++ {list.length === 0 && canonImages.length === 0 && (<p className="text-xs text-gray-500">No media yet. Attach a generated portrait, a mood/reference image, an uploaded file, or a recorded voice memo.</p>)}@@ -1696,6 +1722,15 @@ function diffRevisionAgainstCurrent(revision, current, fields) {const to = curPayload[key] ?? '';if (String(from) !== String(to)) out.push({ key, label, from: String(from), to: String(to) });}+ // Array editors and read-only/forward-compatible canon fields are not in+ // editorFields. Their changes must never make a revision look identical.+ const displayed = new Set(out.map((change) => change.key));+ const additional = [...new Set([...Object.keys(revPayload), ...Object.keys(curPayload)])]+ .filter((key) => !displayed.has(key) && !sameValue(revPayload[key], curPayload[key]));+ if (additional.length > 0) out.push({+ key: '__additional', label: 'Additional fields changed',+ summary: additional.map(humanizeIntegrityField).join(', '),+ });return out;}@@ -1784,14 +1819,14 @@ function RevisionsPanel({ revisions, current, fields, onRestore }) {{diff.map((d) => (<div key={d.key} className="text-[11px]"><dt className="text-gray-500 uppercase tracking-wider text-[9px] mb-0.5">{d.label}</dt>- <dd className="grid grid-cols-1 sm:grid-cols-2 gap-1">+ {d.summary ? <dd className="text-gray-300 break-words">{d.summary}</dd> : <dd className="grid grid-cols-1 sm:grid-cols-2 gap-1"><span className="px-1.5 py-0.5 rounded bg-port-error/10 text-port-error/90 break-words">{d.from || <em className="text-gray-600">empty</em>}</span><span className="px-1.5 py-0.5 rounded bg-port-success/10 text-port-success/90 break-words">{d.to || <em className="text-gray-600">empty</em>}</span>- </dd>+ </dd>}</div>))}</dl>diff --git a/client/src/pages/CatalogIngredient.test.jsx b/client/src/pages/CatalogIngredient.test.jsxindex 1372fa7418..8c4d53a519 100644--- a/client/src/pages/CatalogIngredient.test.jsx+++ b/client/src/pages/CatalogIngredient.test.jsx@@ -7,7 +7,7 @@*/import { describe, it, expect, vi, beforeEach } from 'vitest';-import { act, render, screen, waitFor, fireEvent } from '@testing-library/react';+import { act, render, screen, waitFor, fireEvent, within } from '@testing-library/react';import { createMemoryRouter, RouterProvider } from 'react-router';// Stable navigate mock — returning a fresh vi.fn() per call would change the@@ -117,7 +117,7 @@ vi.mock('../services/apiImageVideo', () => ({})),}));vi.mock('../components/IngredientPicker', () => ({ default: () => null }));-vi.mock('../components/MediaImage', () => ({ default: ({ src, alt }) => <img src={src} alt={alt} /> }));+vi.mock('../components/MediaImage', () => ({ default: ({ src, alt, fallbackSrc }) => <img src={src} alt={alt} data-fallback-src={fallbackSrc} /> }));vi.mock('../components/loraTraining/CharacterLoraChip', () => ({ default: () => null }));vi.mock('../components/TagPicker', () => ({default: ({ value = [], onChange }) => (@@ -419,6 +419,107 @@ describe('CatalogIngredient — character sheet', () => {expect(screen.getByDisplayValue('Being underestimated.')).toBeTruthy();});+ it('shows additional stored canon read-only on a locked character and preserves it on an unrelated save', async () => {+ const character = {+ ...CHAR_FIXTURE, name: 'Example courier',+ payload: {+ ...CHAR_FIXTURE.payload, locked: true,+ ghost: 'Lost the first dispatch.', want: 'Deliver the final letter.', arcType: 'positive',+ secrets: ['Keeps a duplicate map.'], sliders: { proactivity: 0, competence: null },+ psychology: { assessment: 'unknown', assessmentNote: 'The narrator cannot read this mind.',+ drives: { connection: { desire: 'A place at the table.' } } },+ props: [{ name: 'Compass', purpose: 'Find the route.', materials: 'Brass', notes: 'One dent.' }],+ expressions: [{ name: 'Alert', description: 'Eyes follow every doorway.' }],+ handGestures: [{ name: 'Wait', description: 'Palm held forward.' }],+ relationshipLinks: [{ targetCharacterId: 'chr-example-guide', type: 'ally', description: 'Shared a crossing.' }],+ voiceCanon: { description: 'Low and steady.', approved: false, pronunciations: [{ term: 'Example', pronunciation: 'ig-ZAM-pul' }] },+ firstAppearance: 'Opening chapter', missingFromProse: ['The compass origin.'],+ futureCanon: { retained: true },+ },+ };+ getCatalogIngredientDetails.mockResolvedValue(detailsOf(character));+ updateCatalogIngredient.mockImplementation(async (_id, patch) => ({ ...character, ...patch }));+ await renderPage('/casting/cat-chr-1/profile');+ const panel = screen.getByRole('region', { name: 'Additional character canon' });+ const canon = within(panel);+ for (const value of ['Lost the first dispatch.', 'Deliver the final letter.', 'Keeps a duplicate map.', '0',+ 'unknown', 'The narrator cannot read this mind.', 'A place at the table.', 'Compass',+ 'Eyes follow every doorway.', 'Palm held forward.', 'chr-example-guide', 'Low and steady.',+ 'Candidate', 'ig-ZAM-pul', 'Opening chapter', 'The compass origin.']) {+ expect(canon.getByText(value)).toBeInTheDocument();+ }+ expect(canon.getByText(/Materials: Brass/)).toBeInTheDocument();+ expect(canon.queryByRole('textbox')).not.toBeInTheDocument();+ expect(canon.queryByText('Competence')).not.toBeInTheDocument();+ expect(canon.queryByText(/futureCanon|retained/)).not.toBeInTheDocument();+ expect(updateCatalogIngredient).not.toHaveBeenCalled();+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Example route keeper' } });+ fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));+ await waitFor(() => expect(updateCatalogIngredient).toHaveBeenCalledWith(character.id,+ expect.objectContaining({ name: 'Example route keeper', payload: character.payload }), expect.anything()));+ });++ it('preserves an explicit not-applicable assessment and safely skips malformed optional canon', async () => {+ getCatalogIngredientDetails.mockResolvedValue(detailsOf({+ ...CHAR_FIXTURE,+ payload: { ...CHAR_FIXTURE.payload, ghost: { invalid: true }, secrets: [null, {}],+ props: [null, {}, { name: { invalid: true } }], expressions: 'invalid', handGestures: [false],+ relationshipLinks: [null], voiceCanon: [], sliders: { competence: false },+ psychology: { assessment: 'not-applicable', drives: { survival: null } } },+ }));+ await renderPage();+ const canon = within(screen.getByRole('region', { name: 'Additional character canon' }));+ expect(canon.getByText('not-applicable')).toBeInTheDocument();+ expect(canon.queryByRole('button', { name: 'Props' })).not.toBeInTheDocument();+ expect(canon.queryByText(/\[object Object\]|false|invalid/)).not.toBeInTheDocument();+ });++ it('does not invent additional canon for an unfilled legacy character', async () => {+ await renderPage();+ expect(screen.queryByRole('region', { name: 'Additional character canon' })).not.toBeInTheDocument();+ });++ it('shows a stored generation prompt for a legacy character with no other canon details', async () => {+ getCatalogIngredientDetails.mockResolvedValue(detailsOf({+ ...CHAR_FIXTURE, payload: { prompt: 'An example courier in a blue coat, standing beside a milestone.' },+ }));+ await renderPage();+ const canon = within(screen.getByRole('region', { name: 'Additional character canon' }));+ expect(canon.getByText('Generation prompt')).toBeInTheDocument();+ expect(canon.getByText('An example courier in a blue coat, standing beside a milestone.')).toBeInTheDocument();+ expect(canon.queryByRole('textbox')).not.toBeInTheDocument();+ });++ it.each([+ ['nested canon', { psychology: { strategy: 'Takes the long route.' } }, 'Psychology'],+ ['array fields', { aliases: ['Example alias'] }, 'Aliases'],+ ['previously absent fields', { notes: '' }, 'Notes'],+ ])('reports revision changes to %s even when editable scalar text matches', async (_label, changed, fieldLabel) => {+ getCatalogIngredientDetails.mockResolvedValue({+ ...detailsOf(CHAR_FIXTURE),+ revisions: [{ ...CHAR_FIXTURE, id: 'rev-1', source: 'user', payload: { ...CHAR_FIXTURE.payload, ...changed } }],+ });+ await renderPage();+ const history = within(screen.getByRole('heading', { name: /Revision history/ }).closest('section'));+ fireEvent.click(history.getByRole('button'));+ expect(history.queryByText('Identical to the current saved state.')).not.toBeInTheDocument();+ expect(history.getByText('Additional fields changed')).toBeInTheDocument();+ expect(history.getByText(fieldLabel)).toBeInTheDocument();+ });++ it('recognizes an identical complete revision despite object key order', async () => {+ const payload = { ...CHAR_FIXTURE.payload, psychology: { strategy: 'Waits.', assessment: 'unknown' } };+ const revisionPayload = { ...payload, psychology: { assessment: 'unknown', strategy: 'Waits.' } };+ getCatalogIngredientDetails.mockResolvedValue({+ ...detailsOf({ ...CHAR_FIXTURE, payload }),+ revisions: [{ ...CHAR_FIXTURE, id: 'rev-1', source: 'user', payload: revisionPayload }],+ });+ await renderPage();+ const history = within(screen.getByRole('heading', { name: /Revision history/ }).closest('section'));+ fireEvent.click(history.getByRole('button'));+ expect(history.getByText('Identical to the current saved state.')).toBeInTheDocument();+ });+it('shows the source scrap by TITLE (not the bare id) and links to it, with siblings from the same source (#7617)', async () => {getCatalogIngredientDetails.mockImplementation(async () => detailsOf({...CHAR_FIXTURE,@@ -793,6 +894,35 @@ describe('CatalogIngredient — tabbed library record pages', () => {expect(screen.queryByAltText('mood.png')).toBeNull();});+ it('shows existing canon images on References even when no catalog media is attached', async () => {+ getCatalogIngredientDetails.mockResolvedValue(detailsOf({+ ...HERO, payload: { ...HERO.payload, locked: true,+ imageRefs: ['existing.png', 'existing.png', null, {}], primaryImageRef: 'existing.png' },+ }));+ 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.getByText('Primary canon reference')).toBeInTheDocument();+ expect(screen.queryByText(/No media yet/)).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Detach', exact: true })).not.toBeInTheDocument();+ const api = await import('../services/apiCatalog');+ expect(api.attachCatalogIngredientMedia).not.toHaveBeenCalled();+ expect(updateCatalogIngredient).not.toHaveBeenCalled();+ });++ it('does not repeat canon images already attached in a media role', async () => {+ getCatalogIngredientDetails.mockResolvedValue({+ ...detailsOf({ ...HERO, payload: { ...HERO.payload, imageRefs: ['mood.png', 'sheet-1.png', 'canon-only.png'] } }),+ media: MEDIA,+ });+ 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');+ });+it('previews the chosen variant and posts it on Generate, then attaches the finished sheet', async () => {const api = await import('../services/apiCatalog');api.renderCatalogSheet.mockResolvedValue({ jobId: 'sheet-job', variant: 'expressions', role: 'sheet:expressions', delegatedTo: null });