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: require visual direction before rendering character looks
[._.]/ Adam Eivy71c463805c8e
diff --git a/client/src/components/catalog/CatalogLooksPanel.jsx b/client/src/components/catalog/CatalogLooksPanel.jsxindex a671ed0866..15deafec1b 100644--- a/client/src/components/catalog/CatalogLooksPanel.jsx+++ b/client/src/components/catalog/CatalogLooksPanel.jsx@@ -4,6 +4,7 @@ import toast from '../ui/Toast';import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';import MediaJobThumb from '../pipeline/MediaJobThumb';import ModelInputPreview from '../media/ModelInputPreview';+import UniverseMoodBoardPicker, { useStyleSourceLists, BOARD_FOLLOW_UNIVERSE, BOARD_NONE } from '../media/UniverseMoodBoardPicker';import CatalogMediaTile from './CatalogMediaTile';import useMounted from '../../hooks/useMounted';import { useModelInputPreview } from '../../hooks/useModelInputPreview';@@ -53,13 +54,32 @@ function LookForm({ formId, initial, busy, onSubmit, onCancel }) {// The server's preview of exactly what this look's render sends (prompt plus// labeled style/negative additions), then Render. Mounted only while open so// the preview is fetched on demand.-function LookGenerate({ ingredientId, wardrobe, blockedReason, savedStamp, onLookFile, onClose }) {+function LookGenerate({ ingredientId, wardrobe, initialUniverseId, blockedReason, savedStamp, onLookFile, onClose }) {const mountedRef = useMounted();const [starting, setStarting] = useState(false);const [pending, setPending] = useState(null); // { jobId, role }- const fetchPreview = useCallback(({ savedStamp: _stamp, ...body }, options) =>- previewCatalogSheet(ingredientId, body, options).then((r) => r?.preview ?? null), [ingredientId]);- const preview = useModelInputPreview(fetchPreview, { variant: 'look', wardrobeId: wardrobe.id, savedStamp });+ const lists = useStyleSourceLists();+ const [universeId, setUniverseId] = useState(initialUniverseId || '');+ const [moodBoardChoice, setMoodBoardChoice] = useState(BOARD_FOLLOW_UNIVERSE);+ const [visualDirection, setVisualDirection] = useState({ style: '', camera: '', lighting: '', environment: '' });+ const body = {+ variant: 'look', wardrobeId: wardrobe.id, universeId,+ ...(moodBoardChoice !== BOARD_FOLLOW_UNIVERSE ? { moodBoardId: moodBoardChoice === BOARD_NONE ? '' : moodBoardChoice } : {}),+ visualDirection,+ };+ const previewBody = { ...body, savedStamp };+ const requestKey = JSON.stringify(previewBody);+ const fetchPreview = useCallback(({ savedStamp: stamp, ...optionsBody }, options) =>+ previewCatalogSheet(ingredientId, optionsBody, options).then((r) => r?.preview+ ? { ...r.preview, requestKey: JSON.stringify({ ...optionsBody, savedStamp: stamp }) } : null), [ingredientId]);+ const loadedPreview = useModelInputPreview(fetchPreview, previewBody);+ // The hook retains its last result while a new request debounces. A changed+ // field must immediately invalidate that result's permission to render.+ const current = loadedPreview.preview?.requestKey === requestKey;+ const preview = current ? loadedPreview : { preview: null, error: loadedPreview.error };+ const direction = preview.preview?.visualDirection;+ const renderBlocked = blockedReason || preview.error || (!current ? 'Updating visual direction preview…'+ : !direction?.ready ? `Define before rendering: ${direction?.missing?.join(', ') || 'visual direction'}` : null);const role = pending?.role;const handleFilename = useCallback((filename) => {@@ -74,9 +94,9 @@ function LookGenerate({ ingredientId, wardrobe, blockedReason, savedStamp, onLoo}, []);const handleRender = async () => {- if (blockedReason) return;+ if (renderBlocked || starting || pending) return;setStarting(true);- const queued = await renderCatalogSheet(ingredientId, { variant: 'look', wardrobeId: wardrobe.id }, { silent: true })+ const queued = await renderCatalogSheet(ingredientId, body, { silent: true }).catch((err) => { toast.error(err?.message || 'Look render failed'); return null; });if (!mountedRef.current) return;setStarting(false);@@ -91,10 +111,34 @@ function LookGenerate({ ingredientId, wardrobe, blockedReason, savedStamp, onLooconst busy = starting || !!pending;return (<div className="space-y-2 rounded border border-port-border bg-port-bg/40 p-3">+ <fieldset disabled={busy} className="space-y-3">+ <legend className="text-sm font-medium text-white">Look visual direction</legend>+ <p className="text-xs text-gray-400">Choose the world this look belongs to, then define its photography. These choices apply to this render. No illustration or animation style is assumed.</p>+ <UniverseMoodBoardPicker lists={lists} universeId={universeId} moodBoardChoice={moodBoardChoice}+ onUniverseChange={setUniverseId} onBoardChoiceChange={setMoodBoardChoice}+ idPrefix={`look-${wardrobe.id}-style`} labelClass="block text-xs text-gray-400 mb-1" inputClass={inputClass} />+ {!universeId && <p className="text-xs text-port-warning">No universe selected. Choose a mood board or describe an overall style below.</p>}+ {direction?.moodBoard && <p className="text-xs text-gray-400">Mood board: {direction.moodBoard.name}{!direction.moodBoard.hasStyle && ' — no composed style yet. Compose its style on the board or enter an overall style below.'}</p>}+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ {[+ ['style', 'Overall style / medium', 'Optional with a defined source style. Otherwise specify photography, illustration or another deliberate medium.'],+ ['camera', 'Camera', 'Lens, framing, perspective and film or camera treatment.'],+ ['lighting', 'Lighting', 'Light sources, softness, contrast, color and time of day.'],+ ['environment', 'Environment', 'The world, era and backdrop — including a plain backdrop if intended.'],+ ].map(([key, label, placeholder]) => (+ <div key={key}>+ <label htmlFor={`look-${wardrobe.id}-${key}`} className="block text-xs text-gray-400 mb-1">{label}</label>+ <textarea id={`look-${wardrobe.id}-${key}`} value={visualDirection[key]} rows={2} maxLength={1200}+ placeholder={placeholder} className={inputClass}+ onChange={(e) => setVisualDirection((prev) => ({ ...prev, [key]: e.target.value }))} />+ </div>+ ))}+ </div>+ </fieldset><ModelInputPreview preview={preview} prompt="" />- {blockedReason && <p className="text-xs text-port-warning" role="status">{blockedReason}</p>}+ {renderBlocked && <p className="text-xs text-port-warning" role="status">{renderBlocked}</p>}<div className="flex items-center gap-2 flex-wrap">- <button type="button" onClick={handleRender} disabled={busy || !!blockedReason} title={blockedReason || undefined}+ <button type="button" onClick={handleRender} disabled={busy || !!renderBlocked} title={renderBlocked || undefined}className="inline-flex items-center gap-1.5 min-h-[36px] px-3 py-1.5 rounded bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed text-white text-xs font-medium">{busy ? <Loader2 size={12} className="animate-spin" aria-hidden="true" /> : <Sparkles size={12} aria-hidden="true" />}{pending ? 'Rendering…' : 'Render look'}@@ -110,7 +154,7 @@ function LookGenerate({ ingredientId, wardrobe, blockedReason, savedStamp, onLoo}function LookCard({- ingredientId, wardrobe, images, candidates, missingMedia, editLocked, savingList,+ ingredientId, wardrobe, initialUniverseId, images, candidates, missingMedia, editLocked, savingList,blockedReason, savedStamp, onSave, onDelete, onSetRole, onDetach, onLookFile,}) {const [mode, setMode] = useState(null); // 'edit' | 'generate' | 'attach' | 'delete'@@ -175,7 +219,7 @@ function LookCard({)}{mode === 'generate' && (<LookGenerate ingredientId={ingredientId} wardrobe={wardrobe} blockedReason={blockedReason}- savedStamp={savedStamp} onLookFile={onLookFile} onClose={() => setMode(null)} />+ initialUniverseId={initialUniverseId} savedStamp={savedStamp} onLookFile={onLookFile} onClose={() => setMode(null)} />)}{mode === 'attach' && (<div className="rounded border border-port-border bg-port-bg/40 p-3">@@ -218,7 +262,7 @@ function LookCard({// the payload as sent. Deleting a look leaves its images attached; they then// show on References.export default function CatalogLooksPanel({- ingredientId, wardrobes, lookMedia, candidates, missingMedia, editLocked = false,+ ingredientId, initialUniverseId, wardrobes, lookMedia, candidates, missingMedia, editLocked = false,blockedReason = null, savedStamp = null, onSaveWardrobes, onSetRole, onDetach, onLookFile,}) {const [adding, setAdding] = useState(false);@@ -262,7 +306,7 @@ export default function CatalogLooksPanel({<p className="text-xs text-gray-500">No looks yet. Add one to describe an outfit, then generate or attach its images.</p>)}{list.map((w) => (- <LookCard key={w.id} ingredientId={ingredientId} wardrobe={w}+ <LookCard key={w.id} ingredientId={ingredientId} wardrobe={w} initialUniverseId={initialUniverseId}images={media.filter((m) => lookIdOf(m) === w.id)} candidates={candidateList}missingMedia={missingMedia} editLocked={editLocked || savingList} savingList={savingList}blockedReason={blockedReason} savedStamp={savedStamp}diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsxindex 80f453ff6c..7c1450ae9f 100644--- a/client/src/pages/CatalogIngredient.jsx+++ b/client/src/pages/CatalogIngredient.jsx@@ -858,7 +858,9 @@ function IngredientEditor() {{activeTab === 'looks' && (<CatalogLooksPanel+ key={record.id}ingredientId={record.id}+ initialUniverseId={refsByKind.universe?.length === 1 ? universeRef?.refId : ''}wardrobes={wardrobes}lookMedia={media.filter((m) => liveLookIds.has(lookIdOf(m))).map(protectMedia)}candidates={media.filter((m) => m.kind === 'reference' && isReferenceTabRow(m)).map(protectMedia)}diff --git a/client/src/pages/CatalogIngredient.test.jsx b/client/src/pages/CatalogIngredient.test.jsxindex 39065d4b21..7e7a1d6864 100644--- a/client/src/pages/CatalogIngredient.test.jsx+++ b/client/src/pages/CatalogIngredient.test.jsx@@ -94,7 +94,12 @@ vi.mock('../services/apiCatalogTypes', () => ({// The editable-prompt panel lazily fetches the linked universe to layer its// style preset onto the composed prompt; default to "no universe" so the seed// renders bare unless a test overrides it.-vi.mock('../services/apiUniverseBuilder', () => ({ getUniverse: vi.fn(async () => null) }));+vi.mock('../services/apiUniverseBuilder', () => ({+ getUniverse: vi.fn(async () => null),+ listUniverseNames: vi.fn(async () => [{ id: 'u-1', name: 'Example World' }]),+ listUniverseStyles: vi.fn(async () => [{ id: 'u-1', influences: { embrace: ['Analog photography'] } }]),+}));+vi.mock('../services/apiMoodBoard', () => ({ listMoodBoardNames: vi.fn(async () => [{ id: 'mb-1', name: 'Example Board' }]) }));// Stand-in for the live image-gen thumb: fire onFilename as soon as a jobId is// handed in, simulating a completed render without the socket/job machinery.vi.mock('../components/pipeline/MediaJobThumb', async () => {@@ -985,12 +990,19 @@ describe('CatalogIngredient — tabbed library record pages', () => {const api = await import('../services/apiCatalog');getCatalogIngredientDetails.mockImplementation(async () => ({ ...detailsOf(HERO), media: MEDIA }));api.listCatalogSheetVariants.mockImplementation(async () => ({ variants: SHEET_VARIANTS }));- api.previewCatalogSheet.mockImplementation(async (_id, body) => ({- preview: {+ api.previewCatalogSheet.mockImplementation(async (_id, body) => {+ const missing = ['camera', 'lighting', 'environment'].filter((key) => !body.visualDirection?.[key]?.trim());+ if (!body.universeId && !body.moodBoardId && !body.visualDirection?.style?.trim()) missing.unshift('Overall style / medium');+ return { preview: {sentPrompt: `Example style. ${body.variant} sheet of Example Hero`,promptAdditions: [{ id: 'universe-style', label: 'Universe style', text: 'Example style.' }],- },- }));+ ...(body.variant === 'look' ? { visualDirection: {+ ready: missing.length === 0,+ missing,+ universe: { id: 'u-1', name: 'Example World' }, moodBoard: null,+ } } : {}),+ } };+ });api.renderCatalogSheet.mockReset();api.attachCatalogIngredientMedia.mockReset();socketHandlers.clear();@@ -1290,18 +1302,54 @@ describe('CatalogIngredient — tabbed library record pages', () => {fireEvent.click(screen.getByRole('button', { name: /^Generate$/ }));expect(await screen.findByRole('button', { name: '+ Universe style' })).toBeTruthy();+ expect(screen.getByRole('button', { name: /Render look/ })).toBeDisabled();+ fireEvent.change(screen.getByLabelText('Camera'), { target: { value: '50mm film photography' } });+ fireEvent.change(screen.getByLabelText('Lighting'), { target: { value: 'Window light' } });+ fireEvent.change(screen.getByLabelText('Environment'), { target: { value: 'Timber room' } });+ await waitFor(() => expect(screen.getByRole('button', { name: /Render look/ })).toBeEnabled());+ const expectedBody = { variant: 'look', wardrobeId: 'wardrobe-1', universeId: 'u-example',+ visualDirection: { style: '', camera: '50mm film photography', lighting: 'Window light', environment: 'Timber room' } };expect(api.previewCatalogSheet).toHaveBeenLastCalledWith(- 'cat-chr-hero', { variant: 'look', wardrobeId: 'wardrobe-1' }, { silent: true },+ 'cat-chr-hero', expectedBody, { silent: true },);fireEvent.click(screen.getByRole('button', { name: /Render look/ }));await waitFor(() => expect(api.renderCatalogSheet).toHaveBeenCalledWith(- 'cat-chr-hero', { variant: 'look', wardrobeId: 'wardrobe-1' }, { silent: true },+ 'cat-chr-hero', expectedBody, { silent: true },));await waitFor(() => expect(api.attachCatalogIngredientMedia).toHaveBeenCalledWith('cat-chr-hero', { mediaKey: 'look-job.png', kind: 'reference', role: 'look:wardrobe-1' }, { silent: true },));});+ it('invalidates render readiness immediately when direction changes and keeps rendering blocked after a preview failure', async () => {+ const api = await import('../services/apiCatalog');+ await renderPage('/casting/cat-chr-hero/looks');+ fireEvent.click(await screen.findByRole('button', { name: /^Generate$/ }));+ for (const label of ['Camera', 'Lighting', 'Environment']) fireEvent.change(screen.getByLabelText(label), { target: { value: `Example ${label}` } });+ await waitFor(() => expect(screen.getByRole('button', { name: /Render look/ })).toBeEnabled());+ api.previewCatalogSheet.mockRejectedValueOnce(new Error('Style source unavailable'));+ fireEvent.change(screen.getByLabelText('Lighting'), { target: { value: 'Different lighting' } });+ expect(screen.getByRole('button', { name: /Render look/ })).toBeDisabled();+ await screen.findAllByText('Style source unavailable');+ expect(screen.getByRole('button', { name: /Render look/ })).toBeDisabled();+ expect(api.renderCatalogSheet).not.toHaveBeenCalled();+ });++ it('shows an unlinked character’s missing style and lets a mood board supply it without attaching a universe', async () => {+ const api = await import('../services/apiCatalog');+ getCatalogIngredientDetails.mockResolvedValue({ ...detailsOf({ ...HERO, refs: [] }), media: MEDIA });+ await renderPage('/casting/cat-chr-hero/looks');+ fireEvent.click(await screen.findByRole('button', { name: /^Generate$/ }));+ expect(screen.getByText(/No universe selected/)).toBeTruthy();+ for (const label of ['Camera', 'Lighting', 'Environment']) fireEvent.change(screen.getByLabelText(label), { target: { value: `Example ${label}` } });+ await screen.findByText('Define before rendering: Overall style / medium');+ expect(screen.getByRole('button', { name: /Render look/ })).toBeDisabled();+ await screen.findByRole('option', { name: 'Example Board' });+ fireEvent.change(screen.getByLabelText('Mood board'), { target: { value: 'mb-1' } });+ await waitFor(() => expect(screen.getByRole('button', { name: /Render look/ })).toBeEnabled());+ expect(api.previewCatalogSheet).toHaveBeenLastCalledWith('cat-chr-hero', expect.objectContaining({ universeId: '', moodBoardId: 'mb-1' }), { silent: true });+ });+// Catches a look save dropping the rest of the saved payload, reusing or// omitting ids, or failing to show the new look.it('adds a look by saving payload.wardrobes with a stamped wd- id and the rest of the payload intact', async () => {diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.jsindex 8c791a074a..3fd5114200 100644--- a/server/lib/catalogValidation.js+++ b/server/lib/catalogValidation.js@@ -435,6 +435,15 @@ export const catalogSheetRenderSchema = z.object({overridePrompt: z.string().max(8000).optional(),overrideNegativePrompt: z.string().max(2000).optional(),modelId: z.string().trim().max(64).optional(),+ universeId: z.string().max(128).optional(),+ // Absent follows the selected universe's linked board; '' explicitly opts out.+ moodBoardId: z.string().max(128).optional(),+ visualDirection: z.object({+ style: z.string().max(1200).optional(),+ camera: z.string().max(1200).optional(),+ lighting: z.string().max(1200).optional(),+ environment: z.string().max(1200).optional(),+ }).strict().optional(),}).strict().superRefine((body, ctx) => {const isLook = body.variant === CATALOG_LOOK_VARIANT_ID;if (isLook && !body.wardrobeId) {@@ -445,6 +454,12 @@ export const catalogSheetRenderSchema = z.object({if (isLook && body.formId) {ctx.addIssue({ code: 'custom', path: ['formId'], message: 'formId is not accepted for a look render' });}+ if (!isLook && ['universeId', 'moodBoardId', 'visualDirection'].some((key) => body[key] !== undefined)) {+ ctx.addIssue({ code: 'custom', message: 'Visual direction options are only accepted for a look render' });+ }+ if (isLook && body.overridePrompt !== undefined) {+ ctx.addIssue({ code: 'custom', path: ['overridePrompt'], message: 'Use visualDirection for a look so its world and photography direction remain in the sent prompt' });+ }});// Media detach body — identifies the tuple to soft-delete.diff --git a/server/routes/catalogSheets.test.js b/server/routes/catalogSheets.test.jsindex 3a4a9a4a4c..03d882c734 100644--- a/server/routes/catalogSheets.test.js+++ b/server/routes/catalogSheets.test.js@@ -14,6 +14,7 @@ const mocks = vi.hoisted(() => ({getSettings: vi.fn(),enqueueJob: vi.fn(),getImageModels: vi.fn(),+ getBoard: vi.fn(),}));vi.mock('../lib/imageCleanDefaults.js', () => ({@@ -28,6 +29,7 @@ vi.mock('../services/universeBuilder.js', () => ({getUniverse: (...args) => mocks.getUniverse(...args),updateUniverse: (...args) => mocks.updateUniverse(...args),}));+vi.mock('../services/moodBoard/db.js', () => ({ getBoard: (...args) => mocks.getBoard(...args) }));vi.mock('../services/settings.js', () => ({ getSettings: (...args) => mocks.getSettings(...args) }));vi.mock('../services/mediaJobQueue/index.js', () => ({enqueueJob: (...args) => mocks.enqueueJob(...args),@@ -74,6 +76,7 @@ beforeEach(() => {mocks.getImageModels.mockReturnValue([{ id: 'dev', hardwareCompatibility: { state: 'available' } }]);mocks.enqueueJob.mockReturnValue({ jobId: 'job-1', position: 1 });mocks.updateUniverse.mockResolvedValue({});+ mocks.getBoard.mockResolvedValue(null);});describe('catalog sheet routes', () => {@@ -168,6 +171,7 @@ describe('catalog sheet routes', () => {});describe('look renders', () => {+ const visualDirection = { camera: ' 50mm film photography\n', lighting: 'Soft window light', environment: 'A weathered timber room' };const dressed = {...character,payload: {@@ -186,7 +190,7 @@ describe('catalog sheet routes', () => {id: 'universe-1', name: 'Example Universe', influences: { embrace: ['ink and watercolor'] },characters: [{ id: 'char-entry-1', name: 'Example Hero', ingredientId: 'cat-chr-1' }],});- const body = { variant: 'look', wardrobeId: 'wd-scarf' };+ const body = { variant: 'look', wardrobeId: 'wd-scarf', visualDirection };const preview = await request(app).post('/api/catalog/ingredients/cat-chr-1/sheets/preview').send(body);expect(preview.status).toBe(200);const sent = preview.body.preview;@@ -208,6 +212,68 @@ describe('catalog sheet routes', () => {expect(params.negativePrompt).toBe(negatives.text);expect(params.prompt).not.toContain(negatives.text);expect(params.promptAdditions.map((a) => a.id)).toContain('universe-style');+ expect(sent.visualDirection).toMatchObject({ ready: true, missing: [], universe: { id: 'universe-1' } });+ expect(params.prompt).toContain(visualDirection.camera);+ expect(params.prompt).not.toContain('Even, soft studio lighting');+ expect(params.prompt).not.toContain('contemporary illustrated');+ });++ it('shows missing world and photography direction and refuses to spend a render on the default style', async () => {+ mocks.getIngredient.mockResolvedValue(dressed);+ const body = { variant: 'look', wardrobeId: 'wd-scarf' };+ const preview = await request(app).post('/api/catalog/ingredients/cat-chr-1/sheets/preview').send(body);+ expect(preview.body.preview.visualDirection).toEqual({ ready: false,+ missing: ['Overall style / medium', 'Camera', 'Lighting', 'Environment'], universe: null, moodBoard: null });+ expect(preview.body.preview.promptAdditions.map((a) => a.id)).not.toContain('sheet-default-style');+ const res = await request(app).post('/api/catalog/ingredients/cat-chr-1/sheets').send(body);+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('LOOK_VISUAL_DIRECTION_REQUIRED');+ expect(mocks.enqueueJob).not.toHaveBeenCalled();+ });++ it('uses a chosen universe’s notes and linked board style and avoids in both preview and queued input', async () => {+ mocks.getIngredient.mockResolvedValue(dressed);+ mocks.getUniverse.mockResolvedValue({ id: 'chosen', name: 'Example World', styleNotes: 'Tactile photographic grain',+ influences: { embrace: [], avoid: ['plastic skin'] }, moodBoardId: 'board-1' });+ mocks.getBoard.mockResolvedValue({ id: 'board-1', name: 'Example Board', style: { prompt: 'Naturalistic analog film', negativePrompt: '3D animation' } });+ const body = { variant: 'look', wardrobeId: 'wd-scarf', universeId: 'chosen', visualDirection };+ const preview = await request(app).post('/api/catalog/ingredients/cat-chr-1/sheets/preview').send(body);+ expect(preview.body.preview.visualDirection).toMatchObject({ ready: true, moodBoard: { id: 'board-1', hasStyle: true } });+ const res = await request(app).post('/api/catalog/ingredients/cat-chr-1/sheets').send(body);+ expect(res.status).toBe(200);+ const params = queuedParams();+ expect(params.prompt).toBe(preview.body.preview.sentPrompt);+ expect(params.prompt).toContain('Tactile photographic grain');+ expect(params.prompt).toContain('Naturalistic analog film');+ expect(params.negativePrompt).toContain('plastic skin');+ expect(params.negativePrompt).toContain('3D animation');+ expect(params.prompt).not.toContain('3D animation');+ });++ it('supports an unlinked board or authored style, but a board without composed direction does not satisfy style', async () => {+ mocks.getIngredient.mockResolvedValue(dressed);+ mocks.getBoard.mockResolvedValue({ id: 'board-1', name: 'Example Board', items: [{ type: 'image', url: '/image.png' }] });+ const body = { variant: 'look', wardrobeId: 'wd-scarf', moodBoardId: 'board-1', visualDirection };+ const preview = await request(app).post('/api/catalog/ingredients/cat-chr-1/sheets/preview').send(body);+ expect(preview.body.preview.visualDirection.missing).toEqual(['Overall style / medium']);+ const res = await request(app).post('/api/catalog/ingredients/cat-chr-1/sheets').send({ ...body,+ visualDirection: { ...visualDirection, style: 'Live-action photography' } });+ expect(res.status).toBe(200);+ expect(queuedParams().prompt).toContain('Live-action photography');+ });++ it('requires a source choice for multiple worlds and surfaces lookup failures without silently falling back', async () => {+ mocks.getIngredient.mockResolvedValue(dressed);+ mocks.listLiveRefsForIngredient.mockResolvedValue([{ refKind: 'universe', refId: 'u-1' }, { refKind: 'universe', refId: 'u-2' }]);+ const body = { variant: 'look', wardrobeId: 'wd-scarf', visualDirection };+ const post = (options) => request(app).post('/api/catalog/ingredients/cat-chr-1/sheets').send(options);+ expect((await post(body)).body.code).toBe('LOOK_UNIVERSE_REQUIRED');+ mocks.getUniverse.mockRejectedValueOnce(Object.assign(new Error('Universe unavailable'), { status: 503 }));+ expect((await post({ ...body, universeId: 'u-1' })).status).toBe(503);+ expect((await post({ ...body, universeId: '', moodBoardId: 'missing-board' })).status).toBe(404);+ expect((await post({ ...body, overridePrompt: 'bypass direction' })).status).toBe(400);+ expect((await post({ ...body, visualDirection: { lighting: 123 } })).status).toBe(400);+ expect(mocks.enqueueJob).not.toHaveBeenCalled();});it('is not offered among the sheet variants', async () => {diff --git a/server/services/catalogSheet.js b/server/services/catalogSheet.jsindex b348d78a04..25b09f9265 100644--- a/server/services/catalogSheet.js+++ b/server/services/catalogSheet.js@@ -25,7 +25,8 @@ import { assertCatalogIdentityWritable } from './catalogDB/identityAccess.js';*/import { ServerError } from '../lib/errorHandler.js';-import { universeAestheticLine } from '../lib/universeVisualStyle.js';+import { universeAestheticLine, universeVisualStyleTokens } from '../lib/universeVisualStyle.js';+import { getBoard } from './moodBoard/db.js';import { recordRenderPin } from '../lib/renderTargets.js';import { shortId } from '../lib/fileUtils.js';import { getIngredient, getIngredientIdentityIds, listLiveRefsForIngredient } from './catalogDB.js';@@ -102,8 +103,7 @@ function lookVariantFor(ingredient, payload, wardrobeId) {return {id: CATALOG_LOOK_VARIANT_ID,label: 'Look',- build: (universe, entry) => buildCharacterLookPrompt(universe, entry, wardrobe),- defaultStyle: DEFAULT_CHARACTER_SHEET_STYLE,+ build: (universe, entry, direction) => buildCharacterLookPrompt(universe, entry, wardrobe, direction),negativesLabel: 'Look negatives',role: `look:${wardrobe.id}`,};@@ -182,10 +182,19 @@ async function resolveSheetTarget(id, options) {const refs = await listLiveRefsForIngredient(id);const universes = [];- for (const ref of refs) {+ const universeRefs = isLook && options.universeId !== undefined+ ? (options.universeId ? [{ refKind: 'universe', refId: options.universeId }] : [])+ : refs;+ if (isLook && options.universeId === undefined && new Set(universeRefs.filter((r) => r.refKind === 'universe').map((r) => r.refId)).size > 1) {+ throw new ServerError('Choose which universe supplies this look’s visual direction', { status: 400, code: 'LOOK_UNIVERSE_REQUIRED' });+ }+ for (const ref of universeRefs) {if (ref.refKind !== 'universe') continue;// A ref can outlive its universe (getUniverse throws NOT_FOUND then).- const universe = await getUniverse(ref.refId).catch(() => null);+ const universe = await getUniverse(ref.refId).catch((error) => {+ if (!isLook && error?.code === 'NOT_FOUND') return null;+ throw error;+ });if (universe) universes.push(universe);}// A local consolidation retains embedded source variants. Render its@@ -200,23 +209,61 @@ async function resolveSheetTarget(id, options) {return { ingredient, payload: payloadForForm(ingredient.type, payload, form), variant, universe: universes[0] ?? null };}+// Presence is checked without rewriting authored text. Board pins alone are+// not a style definition: use the board's explicitly composed style prompt.+async function lookDirection(universe, options) {+ const boardId = options.moodBoardId ?? universe?.moodBoardId;+ const board = boardId ? await getBoard(boardId) : null;+ if (boardId && !board) throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });+ const hasText = (text) => typeof text === 'string' && !!text.trim();+ const additions = [];+ const add = (id, label, text) => {+ if (hasText(text)) additions.push({ id, label, text });+ };+ add('universe-style', `Universe style · ${universe?.name || ''}`, universe ? universeAestheticLine(universe) : '');+ add('universe-style-notes', 'Universe style notes', universe?.styleNotes);+ for (const [index, ref] of (universe?.styleReferences || []).entries()) {+ add(`universe-style-reference-${index}`, ref.title || 'Universe style reference', ref.prompt);+ }+ add('mood-board-style', `Mood board style · ${board?.name || ''}`, board?.style?.prompt);+ const authored = options.visualDirection || {};+ const hasSourceStyle = additions.length > 0;+ const fields = { style: 'Overall style / medium', camera: 'Camera', lighting: 'Lighting', environment: 'Environment' };+ for (const [key, label] of Object.entries(fields)) add(`look-${key}`, label, authored[key]);+ const missing = Object.entries(fields).filter(([key]) => !hasText(authored[key]) && !(key === 'style' && hasSourceStyle)).map(([, label]) => label);+ return {+ additions,+ styleLine: additions.map((a) => `${a.label}: ${a.text}`).join('\n\n'),+ negatives: [...universeVisualStyleTokens(universe).avoid, board?.style?.negativePrompt].filter(hasText).join(', '),+ status: {+ ready: missing.length === 0,+ missing,+ universe: universe ? { id: universe.id, name: universe.name } : null,+ moodBoard: board ? { id: board.id, name: board.name, hasStyle: hasText(board.style?.prompt) } : null,+ },+ };+}+async function buildCatalogSheet(target, options) {const { ingredient, payload, variant, universe } = target;const entry = { ...payload, name: ingredient.name };- // The builders take a universe object; an empty one means "no universe" and- // the template carries the variant's default style line instead.- const built = variant.build(universe || {}, entry);+ // Other sheets retain their default style; looks require explicit direction.+ const direction = variant.id === CATALOG_LOOK_VARIANT_ID ? await lookDirection(universe, options) : null;+ const built = variant.build(universe || {}, entry, direction);+ if (direction?.negatives) built.negativePrompt += `, ${direction.negatives}`;const universeStyle = universe ? universeAestheticLine(universe) : '';- return buildSheetRenderParams({+ const result = await buildSheetRenderParams({built,options,- styleLine: universeStyle || variant.defaultStyle,+ styleLine: direction ? '' : universeStyle || variant.defaultStyle,styleChip: universeStyle? { id: 'universe-style', label: 'Universe style' }: { id: 'sheet-default-style', label: 'Default sheet style' },negativesLabel: variant.negativesLabel,renderPin: universe ? recordRenderPin(universe) : {},});+ if (direction) result.params.promptAdditions = [...direction.additions, ...(result.params.promptAdditions || [])];+ return { ...result, visualDirection: direction?.status };}/** What a catalog sheet render would send, built by the render's own code. */@@ -227,11 +274,12 @@ export async function previewCatalogSheet(id, options = {}) {...options, variant: target.variant.id,});}- const { params } = await buildCatalogSheet(target, options);+ const { params, visualDirection } = await buildCatalogSheet(target, options);return {sentPrompt: params.prompt,...(params.negativePrompt ? { sentNegativePrompt: params.negativePrompt } : {}),promptAdditions: params.promptAdditions || [],+ ...(visualDirection ? { visualDirection } : {}),};}@@ -244,7 +292,10 @@ export async function renderCatalogSheet(id, options = {}) {const result = await renderCharacterReferenceSheet(universeId, entryId, { ...options, variant: target.variant.id });return { ...result, delegatedTo: 'universe', universeId, entryId };}- const { params, modelId, activeMode } = await buildCatalogSheet(target, options);+ const { params, modelId, activeMode, visualDirection } = await buildCatalogSheet(target, options);+ if (visualDirection && !visualDirection.ready) {+ throw new ServerError(`Define the look’s visual direction before rendering: ${visualDirection.missing.join(', ')}`, { status: 400, code: 'LOOK_VISUAL_DIRECTION_REQUIRED' });+ }const role = target.variant.role || `sheet:${target.variant.id}`;params.catalogAttach = { ingredientId: id, kind: 'reference', role };const queued = await enqueueJob({ kind: 'image', params });diff --git a/server/services/catalogSheetPrompts.js b/server/services/catalogSheetPrompts.jsindex f1e03d37ee..90140fec66 100644--- a/server/services/catalogSheetPrompts.js+++ b/server/services/catalogSheetPrompts.js@@ -5,13 +5,13 @@* Same contract as the character builders in universeCharacterSheet.js:* `(universe, entry) → { prompt, negativePrompt, width, height, modelId }`,* pure, no I/O. `universe` may be an empty object (a catalog record with no- * linked universe); the sheet then carries the variant's default style line,- * which the renderer lists as a prompt addition.+ * linked universe). Place/object sheets carry their default style; a look+ * receives explicit visual direction from its renderer.*/import { ServerError } from '../lib/errorHandler.js';import { universeAestheticLine } from '../lib/universeVisualStyle.js';-import { DEFAULT_CHARACTER_SHEET_STYLE, REFERENCE_SHEET_CONSTANTS, extractCharacterPromptCommon } from './universeCharacterSheet.js';+import { REFERENCE_SHEET_CONSTANTS, extractCharacterPromptCommon } from './universeCharacterSheet.js';const { DEFAULT_WIDTH, DEFAULT_HEIGHT } = REFERENCE_SHEET_CONSTANTS;@@ -109,13 +109,12 @@ export function buildProductSheetPrompt(universe, object) {/*** Look reference for a character wearing one of its wardrobes: the same- * person (identity from the record's own fields) in full-body views on a plain- * backdrop, no text. `wardrobe` is a `payload.wardrobes` entry.+ * person (identity from the record's own fields) in full-body views using the+ * chosen visual direction, no text. `wardrobe` is a `payload.wardrobes` entry.*/-export function buildCharacterLookPrompt(universe, character, wardrobe) {+export function buildCharacterLookPrompt(universe, character, wardrobe, direction) {requireEntry(character, 'buildCharacterLookPrompt');requireEntry(wardrobe, 'buildCharacterLookPrompt');- const styleBits = universeAestheticLine(universe || {});const { name, age, pronouns, physical, silhouette, posture, special, visualIdentity, visualNotes } =extractCharacterPromptCommon(character);const lookName = trim(wardrobe.name) || 'Unnamed look';@@ -128,8 +127,8 @@ export function buildCharacterLookPrompt(universe, character, wardrobe) {].filter(Boolean).join(' ');const promptParts = [- `LOOK REFERENCE — a costume reference of one character, ${name}, wearing a single outfit, shown as three full-body views side by side at identical scale: FRONT, THREE-QUARTER and BACK, standing in a relaxed neutral pose on a plain seamless light-grey backdrop.`,- styleBits || DEFAULT_CHARACTER_SHEET_STYLE,+ `LOOK REFERENCE — a costume reference of one character, ${name}, wearing a single outfit, shown as three full-body views side by side at identical scale: FRONT, THREE-QUARTER and BACK, standing in a relaxed neutral pose. Use the visual direction below consistently across every view, including its medium, camera, lighting and environment.`,+ direction?.styleLine || '',identityBits,physical ? `Physical description: ${physical}` : '',silhouette ? `Silhouette: ${silhouette}` : '',@@ -139,7 +138,7 @@ export function buildCharacterLookPrompt(universe, character, wardrobe) {visualNotes ? `Visual notes: ${visualNotes}` : '',`Outfit: ${lookName}.`,lookDescription ? `Outfit description: ${lookDescription}` : '',- `Every view shows the same person with the same face, hair, proportions and the complete outfit from head to toe, including footwear and accessories. Even, soft studio lighting. No props beyond what the outfit includes, no other people, no text, no labels, no captions.`,+ `Every view shows the same person with the same face, hair, proportions and the complete outfit from head to toe, including footwear and accessories. Keep the outfit readable within the specified environment. No props beyond what the outfit includes, no other people, no text, no labels, no captions.`,].filter(Boolean);return {