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

Render reference sheets for catalog records, places and objects (#11940)

[._.]/dd05984d9121
diff --git a/server/deadExports.test.js b/server/deadExports.test.js
index 6c01c34f58..0d367186c2 100644
--- a/server/deadExports.test.js
+++ b/server/deadExports.test.js
@@ -70,8 +70,11 @@ function addedExportNames() {
return addedExportNamesFromDiff(diff);
}
+// Untracked (non-ignored) files count as callers too: addedExportNames diffs the
+// working tree, and pregate validates uncommitted work, so a new caller file
+// that is not yet `git add`ed must not make its import look orphaned.
function trackedFiles() {
- return execFileSync('git', ['ls-files', '-z'], { cwd: ROOT, maxBuffer: GIT_MAX_BUFFER })
+ return execFileSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], { cwd: ROOT, maxBuffer: GIT_MAX_BUFFER })
.toString('utf8').split('\0').filter(Boolean)
.filter(file => /\.(?:[cm]?[jt]sx?|json|md)$/.test(file))
.filter(file => existsSync(join(ROOT, file)))
diff --git a/server/index.js b/server/index.js
index 77bcbdcbfa..ba412523ab 100644
--- a/server/index.js
+++ b/server/index.js
@@ -59,6 +59,7 @@ import featureAgentsRoutes from './routes/featureAgents.js';
import feedsRoutes from './routes/feeds.js';
import gsdRoutes from './routes/gsd.js';
import catalogRoutes from './routes/catalog.js';
+import catalogSheetRoutes from './routes/catalogSheets.js';
import memoryRoutes from './routes/memory.js';
import tribeRoutes from './routes/tribe.js';
import userActionsRoutes from './routes/userActions.js';
@@ -378,6 +379,7 @@ app.use('/api/cos', cosRoutes);
app.use('/api/feature-agents', featureAgentsRoutes);
app.use('/api/feeds', feedsRoutes);
app.use('/api/catalog', catalogRoutes);
+app.use('/api/catalog', catalogSheetRoutes);
app.use('/api/memory', memoryRoutes);
app.use('/api/tribe', tribeRoutes);
app.use('/api/user-actions', userActionsRoutes);
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index 6d4acab5c6..11817247a8 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -379,6 +379,15 @@ export const catalogPortraitSetSchema = z.object({
caption: z.string().trim().max(2_000).optional().nullable(),
}).strict();
+// Reference-sheet render/preview body. The prompt overrides are the user's own
+// words and are sent exactly as typed — no trim (#11317).
+export const catalogSheetRenderSchema = z.object({
+ variant: z.string().trim().min(1).max(48).optional(),
+ overridePrompt: z.string().max(8000).optional(),
+ overrideNegativePrompt: z.string().max(2000).optional(),
+ modelId: z.string().trim().max(64).optional(),
+}).strict();
+
// Media detach body — identifies the tuple to soft-delete.
export const catalogMediaDetachSchema = z.object({
mediaKey: z.string().trim().min(1).max(512),
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.js
index 9ee56818ed..98bdaf9ace 100644
--- a/server/lib/hostControlRoutes.js
+++ b/server/lib/hostControlRoutes.js
@@ -866,6 +866,10 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
'POST /api/catalog/ingest/file',
'POST /api/catalog/ingest/voice',
'POST /api/catalog/ingest/brain',
+ // A catalog reference sheet queues the same image render as the universe
+ // sheet route above, whose backend may be an agent harness (Codex). The
+ // preview only builds text and stays open.
+ 'POST /api/catalog/ingredients/:id/sheets',
// Importer, Brain and analytics AI (#11036): caller text, stored reference
// data and a caller-chosen provider reach a non-tool-free runner. Authorize
diff --git a/server/routes/catalogSheets.js b/server/routes/catalogSheets.js
new file mode 100644
index 0000000000..64bef52736
--- /dev/null
+++ b/server/routes/catalogSheets.js
@@ -0,0 +1,31 @@
+/**
+ * Catalog reference sheets: the sheet kinds a record's type offers, a preview
+ * of exactly what a render would send, and the render itself.
+ */
+
+import { Router } from 'express';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import { catalogSheetRenderSchema } from '../lib/catalogValidation.js';
+import { getIngredient } from '../services/catalogDB.js';
+import { listCatalogSheetVariants, previewCatalogSheet, renderCatalogSheet } from '../services/catalogSheet.js';
+
+const router = Router();
+
+router.get('/ingredients/:id/sheets/variants', asyncHandler(async (req, res) => {
+ const ingredient = await getIngredient(req.params.id);
+ if (!ingredient) throw new ServerError('Ingredient not found', { status: 404, code: 'NOT_FOUND' });
+ res.json({ variants: listCatalogSheetVariants(ingredient.type) });
+}));
+
+router.post('/ingredients/:id/sheets/preview', asyncHandler(async (req, res) => {
+ const options = validateRequest(catalogSheetRenderSchema, req.body ?? {});
+ res.json({ preview: await previewCatalogSheet(req.params.id, options) });
+}));
+
+router.post('/ingredients/:id/sheets', asyncHandler(async (req, res) => {
+ const options = validateRequest(catalogSheetRenderSchema, req.body ?? {});
+ res.json(await renderCatalogSheet(req.params.id, options));
+}));
+
+export default router;
diff --git a/server/routes/catalogSheets.test.js b/server/routes/catalogSheets.test.js
new file mode 100644
index 0000000000..c64f7e1fe1
--- /dev/null
+++ b/server/routes/catalogSheets.test.js
@@ -0,0 +1,159 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+// The route runs the real sheet services; only the stores, settings and the
+// media queue (the render's terminal effect) are doubled.
+const mocks = vi.hoisted(() => ({
+ getIngredient: vi.fn(),
+ listLiveRefsForIngredient: vi.fn(),
+ getUniverse: vi.fn(),
+ updateUniverse: vi.fn(),
+ getSettings: vi.fn(),
+ enqueueJob: vi.fn(),
+ getImageModels: vi.fn(),
+}));
+
+vi.mock('../lib/imageCleanDefaults.js', () => ({
+ resolveImageCleaners: vi.fn(() => ({ cleanC2PA: false, denoise: false })),
+}));
+vi.mock('../services/catalogDB.js', () => ({
+ getIngredient: (...args) => mocks.getIngredient(...args),
+ listLiveRefsForIngredient: (...args) => mocks.listLiveRefsForIngredient(...args),
+}));
+vi.mock('../services/universeBuilder.js', () => ({
+ getUniverse: (...args) => mocks.getUniverse(...args),
+ updateUniverse: (...args) => mocks.updateUniverse(...args),
+}));
+vi.mock('../services/settings.js', () => ({ getSettings: (...args) => mocks.getSettings(...args) }));
+vi.mock('../services/mediaJobQueue/index.js', () => ({
+ enqueueJob: (...args) => mocks.enqueueJob(...args),
+ getJob: vi.fn(),
+ mediaJobEvents: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },
+}));
+vi.mock('../services/universeRunTag.js', () => ({ buildUniverseRunTag: vi.fn(async () => null) }));
+vi.mock('../services/universeCharacterSheetSlot.js', () => ({
+ claimPendingSheetSlot: vi.fn(),
+ getPendingSheetSlot: vi.fn(),
+ releasePendingSheetSlot: vi.fn(),
+}));
+vi.mock('../lib/mediaModels.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ getImageModels: (...args) => mocks.getImageModels(...args),
+}));
+
+const router = (await import('./catalogSheets.js')).default;
+
+const app = express();
+app.use(express.json());
+app.use('/api/catalog', router);
+app.use(errorMiddleware);
+
+const character = {
+ id: 'cat-chr-1', type: 'character', name: 'Example Hero',
+ payload: { physicalDescription: 'tall, silver coat', role: 'courier' },
+};
+const place = {
+ id: 'cat-plc-1', type: 'place', name: 'Example Harbor',
+ payload: { description: 'fog over wooden piers', palette: 'slate, rust', intExt: 'EXT', timeOfDay: 'dawn' },
+};
+const object = {
+ id: 'cat-obj-1', type: 'object', name: 'Example Lantern',
+ payload: { description: 'brass storm lantern with a cracked lens', significance: 'a family heirloom' },
+};
+
+const queuedParams = (n = 0) => mocks.enqueueJob.mock.calls[n][0].params;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.listLiveRefsForIngredient.mockResolvedValue([]);
+ mocks.getSettings.mockResolvedValue({ imageGen: { mode: 'local', local: { pythonPath: '/python', modelId: 'dev' } } });
+ mocks.getImageModels.mockReturnValue([{ id: 'dev', hardwareCompatibility: { state: 'available' } }]);
+ mocks.enqueueJob.mockReturnValue({ jobId: 'job-1', position: 1 });
+ mocks.updateUniverse.mockResolvedValue({});
+});
+
+describe('catalog sheet routes', () => {
+ it('lists the variants a type offers', async () => {
+ mocks.getIngredient.mockResolvedValue(place);
+ const res = await request(app).get('/api/catalog/ingredients/cat-plc-1/sheets/variants');
+ expect(res.status).toBe(200);
+ expect(res.body.variants.map((v) => v.id)).toEqual(['environment']);
+ });
+
+ // Catches a catalog-only render missing the attach tag/role (the image would
+ // never reach the record, or would take its portrait) or claiming a universe style.
+ it('queues a catalog-only character with the attach tag, the sheet role and the default-style chip', async () => {
+ mocks.getIngredient.mockResolvedValue(character);
+ const res = await request(app).post('/api/catalog/ingredients/cat-chr-1/sheets').send({ variant: 'blueprint' });
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ jobId: 'job-1', variant: 'blueprint', delegatedTo: null });
+ const params = queuedParams();
+ expect(params.catalogAttach).toEqual({ ingredientId: 'cat-chr-1', kind: 'reference', role: 'sheet:blueprint' });
+ expect(params.characterSheet).toBeUndefined();
+ const ids = params.promptAdditions.map((a) => a.id);
+ expect(ids).toEqual(['sheet-default-style', 'sheet-negatives']);
+ expect(params.prompt).toContain(params.promptAdditions[0].text);
+ expect(params.prompt).toContain('Example Hero');
+ });
+
+ it('delegates a universe-linked character to the universe renderer', async () => {
+ mocks.getIngredient.mockResolvedValue(character);
+ 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 res = await request(app).post('/api/catalog/ingredients/cat-chr-1/sheets').send({});
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ delegatedTo: 'universe', universeId: 'universe-1', entryId: 'char-entry-1', variant: 'standard' });
+ const params = queuedParams();
+ expect(params.characterSheet).toMatchObject({ universeId: 'universe-1', entryId: 'char-entry-1', variant: 'standard' });
+ expect(params.catalogAttach).toBeUndefined();
+ });
+
+ it('refuses a variant the type does not offer, and a locked record', async () => {
+ mocks.getIngredient.mockResolvedValue(place);
+ const wrong = await request(app).post('/api/catalog/ingredients/cat-plc-1/sheets').send({ variant: 'blueprint' });
+ expect(wrong.status).toBe(400);
+
+ mocks.getIngredient.mockResolvedValue({ ...object, payload: { ...object.payload, locked: true } });
+ const locked = await request(app).post('/api/catalog/ingredients/cat-obj-1/sheets').send({});
+ expect(locked.status).toBe(409);
+
+ mocks.getIngredient.mockResolvedValue(null);
+ const missing = await request(app).post('/api/catalog/ingredients/cat-obj-9/sheets').send({});
+ expect(missing.status).toBe(404);
+ expect(mocks.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ // Catches the preview and the render drifting apart (#11317).
+ it('previews exactly the prompt the render queues, for a place and an object', async () => {
+ for (const [record, marker] of [[place, 'ENVIRONMENT REFERENCE SHEET'], [object, 'PRODUCT REFERENCE SHEET']]) {
+ mocks.enqueueJob.mockClear();
+ mocks.getIngredient.mockResolvedValue(record);
+ const preview = await request(app).post(`/api/catalog/ingredients/${record.id}/sheets/preview`).send({});
+ expect(preview.status).toBe(200);
+ const sent = preview.body.preview;
+ expect(sent.sentPrompt).toContain(marker);
+ expect(sent.sentPrompt).toContain(record.name);
+
+ await request(app).post(`/api/catalog/ingredients/${record.id}/sheets`).send({});
+ const params = queuedParams();
+ expect(sent.sentPrompt).toBe(params.prompt);
+ expect(sent.sentNegativePrompt).toBe(params.negativePrompt);
+ expect(sent.promptAdditions).toEqual(params.promptAdditions);
+ expect(params.catalogAttach.role).toBe(`sheet:${record.type === 'place' ? 'environment' : 'product'}`);
+ }
+ });
+
+ it('sends a typed override exactly as written, with no additions', async () => {
+ mocks.getIngredient.mockResolvedValue(object);
+ const typed = ' my own lantern sheet\n';
+ const res = await request(app).post('/api/catalog/ingredients/cat-obj-1/sheets/preview')
+ .send({ overridePrompt: typed, overrideNegativePrompt: 'blur ' });
+ expect(res.body.preview.sentPrompt).toBe(typed);
+ expect(res.body.preview.promptAdditions).toEqual([]);
+ });
+});
diff --git a/server/services/catalogDB.facets.db.test.js b/server/services/catalogDB.facets.db.test.js
index f22436b105..60f9c5f35e 100644
--- a/server/services/catalogDB.facets.db.test.js
+++ b/server/services/catalogDB.facets.db.test.js
@@ -172,6 +172,23 @@ describe.skipIf(!runDb)('catalogDB facets + album filters (#1762)', () => {
expect(items[0].usage).toEqual({ universe: 1, series: 1 });
});
+ // Uniquely catches a newer reference sheet / look / plate becoming the card
+ // cover over an older plain reference image.
+ it('never picks a sheet, look or plate image as the card thumbnail', async () => {
+ const ing = await catalogDB.createIngredient({ type: 'place', name: `Thumb ${nonce}` });
+ createdIngredientIds.add(ing.id);
+ await catalogDB.attachMedia(ing.id, `plain-${nonce}.png`, 'reference');
+ await catalogDB.attachMedia(ing.id, `sheet-${nonce}.png`, 'reference', { role: 'sheet:environment' });
+ await catalogDB.attachMedia(ing.id, `look-${nonce}.png`, 'reference', { role: 'look:night' });
+ await catalogDB.attachMedia(ing.id, `plate-${nonce}.png`, 'reference', { role: 'plate' });
+ const { items } = await catalogDB.listIngredients({ ids: [ing.id], limit: 5 });
+ expect(items[0].thumbnailKey).toBe(`plain-${nonce}.png`);
+
+ await catalogDB.detachMedia(ing.id, `plain-${nonce}.png`, 'reference');
+ const after = await catalogDB.listIngredients({ ids: [ing.id], limit: 5 });
+ expect(after.items[0].thumbnailKey).toBeNull();
+ });
+
it('getCatalogFacets aggregates type/universe/series/tag facets + bucket counts', async () => {
const linked = await catalogDB.createIngredient({ type: 'character', name: `FacetLinked ${nonce}`, tags: [TAG] });
const seriesLinked = await catalogDB.createIngredient({ type: 'character', name: `FacetSeries ${nonce}` });
diff --git a/server/services/catalogDB/ingredients.js b/server/services/catalogDB/ingredients.js
index 83464f2421..eb02e884ce 100644
--- a/server/services/catalogDB/ingredients.js
+++ b/server/services/catalogDB/ingredients.js
@@ -315,13 +315,15 @@ const INGREDIENT_LIGHT_COLS = 'id, type, name, payload, tags, embedding_model, o
// Correlated subquery that yields the card-thumbnail media key for each row:
// the live portrait when set, otherwise the most recent live reference image.
// Non-image media kinds (audio/video/document) are excluded so a card never
-// points an <img> at an unrenderable key. Used only by listIngredients' light
-// path (see the note there).
+// points an <img> at an unrenderable key. Working images filed with a role —
+// reference sheets (`sheet:*`), looks (`look:*`) and plates — never become the
+// cover. Used only by listIngredients' light path (see the note there).
const THUMBNAIL_KEY_SUBQUERY = `(
SELECT m.media_key FROM catalog_ingredient_media m
WHERE m.ingredient_id = catalog_ingredients.id
AND m.deleted = false
AND m.kind IN ('portrait', 'reference')
+ AND (m.role IS NULL OR NOT (m.role LIKE 'sheet:%' OR m.role LIKE 'look:%' OR m.role = 'plate'))
ORDER BY (m.kind = 'portrait') DESC, m.created_at DESC
LIMIT 1
) AS thumbnail_key`;
diff --git a/server/services/catalogImageAttachHook.js b/server/services/catalogImageAttachHook.js
index 2cb8057c1c..67a877ccad 100644
--- a/server/services/catalogImageAttachHook.js
+++ b/server/services/catalogImageAttachHook.js
@@ -42,7 +42,7 @@ const portraitGuard = createNewestWinsGuard();
// ('portrait' | 'reference'), 'duplicate' when the client already filed it,
// 'gone' when the target ingredient no longer exists, or throws on a real DB
// error (caught by the factory).
-async function attachGeneratedImage({ ingredientId, kind, filename, queuedAt }) {
+async function attachGeneratedImage({ ingredientId, kind, role, filename, queuedAt }) {
// The ingredient can be deleted between enqueue and completion (a render
// outlives its editor by minutes). `getIngredient` filters `deleted = false`,
// so this skips a hard-deleted ingredient (FK would throw) AND a soft-deleted
@@ -63,11 +63,15 @@ async function attachGeneratedImage({ ingredientId, kind, filename, queuedAt })
return 'duplicate';
}
const hasPortrait = existing.some((m) => m.kind === 'portrait');
- // Explicit kind wins; otherwise auto: first image → portrait, later → reference
- // (mirrors CatalogIngredient.jsx `handleGeneratedImage`).
- let target = kind === 'portrait' || kind === 'reference'
- ? kind
- : (hasPortrait ? 'reference' : 'portrait');
+ // A role-tagged render (a reference sheet, `sheet:<variant>`) is always a
+ // reference: it must never take the portrait slot. Otherwise explicit kind
+ // wins; else auto: first image → portrait, later → reference (mirrors
+ // CatalogIngredient.jsx `handleGeneratedImage`).
+ const mediaRole = typeof role === 'string' && role.trim() ? role.trim() : null;
+ let target = mediaRole ? 'reference'
+ : kind === 'portrait' || kind === 'reference'
+ ? kind
+ : (hasPortrait ? 'reference' : 'portrait');
// A stale would-be-portrait must not demote a newer portrait. Keep the image
// as a reference rather than dropping it (references are additive).
if (target === 'portrait' && portraitGuard.isStale(ingredientId, queuedAt)) {
@@ -80,7 +84,8 @@ async function attachGeneratedImage({ ingredientId, kind, filename, queuedAt })
else await setPortraitMedia(ingredientId, filename);
portraitGuard.mark(ingredientId, queuedAt);
} else {
- if (metadataOptions) await attachMedia(ingredientId, filename, 'reference', metadataOptions);
+ const referenceOptions = { ...(mediaRole ? { role: mediaRole } : {}), ...(metadataOptions || {}) };
+ if (Object.keys(referenceOptions).length > 0) await attachMedia(ingredientId, filename, 'reference', referenceOptions);
else await attachMedia(ingredientId, filename, 'reference');
}
return target;
@@ -99,7 +104,7 @@ const hook = createMediaJobImageHook({
serializeKey: ({ ingredientId }) => ingredientId,
describe: ({ ingredientId }) => ingredientId,
attach: ({ ingredientId, tag, filename, queuedAt }) => attachGeneratedImage({
- ingredientId, kind: tag.kind, filename, queuedAt,
+ ingredientId, kind: tag.kind, role: tag.role, filename, queuedAt,
}),
onAttached: ({ ingredientId, filename }, status) => {
if (status === 'portrait' || status === 'reference') {
diff --git a/server/services/catalogImageAttachHook.test.js b/server/services/catalogImageAttachHook.test.js
index ba0f7ddaa3..373500fec1 100644
--- a/server/services/catalogImageAttachHook.test.js
+++ b/server/services/catalogImageAttachHook.test.js
@@ -70,6 +70,17 @@ describe('catalogImageAttachHook', () => {
expect(setPortraitMedia).not.toHaveBeenCalled();
});
+ // Uniquely catches a reference sheet taking the portrait slot of a record
+ // with no media, or losing its `sheet:<variant>` role on the way to the row.
+ it('files a role-tagged render as a reference with its role, never the portrait', async () => {
+ mediaJobEvents.emit('completed', completedImageJob({
+ catalogAttach: { ingredientId: 'ing-sheet', kind: 'portrait', role: 'sheet:environment' },
+ }, 'sheet.png'));
+ await waitFor(() => attachMedia.mock.calls.length > 0);
+ expect(attachMedia).toHaveBeenCalledWith('ing-sheet', 'sheet.png', 'reference', { role: 'sheet:environment' });
+ expect(setPortraitMedia).not.toHaveBeenCalled();
+ });
+
it('honors an explicit portrait kind even when a portrait already exists', async () => {
listMediaForIngredient.mockResolvedValue([{ mediaKey: 'old.png', kind: 'portrait' }]);
mediaJobEvents.emit('completed', completedImageJob({ catalogAttach: { ingredientId: 'ing-4', kind: 'portrait' } }, 'new.png'));
diff --git a/server/services/catalogSheet.js b/server/services/catalogSheet.js
new file mode 100644
index 0000000000..619933123a
--- /dev/null
+++ b/server/services/catalogSheet.js
@@ -0,0 +1,168 @@
+/**
+ * Catalog reference sheets: a sheet for a catalog record without needing a
+ * universe, plus environment (place) and product (object) sheet kinds.
+ *
+ * A character already linked to a universe canon entry delegates to the
+ * universe renderer, so its sheet keeps landing on the canon pointer. Every
+ * other record builds from its own payload and queues an image job tagged
+ * `catalogAttach` with `role: 'sheet:<variant>'`; catalogImageAttachHook files
+ * the finished image as a `reference` media row with that role (never the
+ * portrait), and the card-cover query skips sheet roles.
+ */
+
+import { ServerError } from '../lib/errorHandler.js';
+import { universeAestheticLine } from '../lib/universeVisualStyle.js';
+import { recordRenderPin } from '../lib/renderTargets.js';
+import { shortId } from '../lib/fileUtils.js';
+import { getIngredient, listLiveRefsForIngredient } from './catalogDB.js';
+import { getUniverse } from './universeBuilder.js';
+import { enqueueJob } from './mediaJobQueue/index.js';
+import {
+ DEFAULT_CHARACTER_SHEET_STYLE,
+ buildSheetRenderParams,
+ getSheetVariantBuilder,
+ listSheetVariants,
+ previewCharacterReferenceSheet,
+ renderCharacterReferenceSheet,
+} from './universeCharacterSheet.js';
+import {
+ DEFAULT_ENVIRONMENT_SHEET_STYLE,
+ DEFAULT_PRODUCT_SHEET_STYLE,
+ buildEnvironmentSheetPrompt,
+ buildProductSheetPrompt,
+} from './catalogSheetPrompts.js';
+
+const CATALOG_SHEET_VARIANTS = Object.freeze({
+ place: Object.freeze([Object.freeze({
+ id: 'environment',
+ label: 'Environment sheet',
+ description: 'Establishing wide, reverse angle, detail inserts and a palette strip of the empty location.',
+ build: buildEnvironmentSheetPrompt,
+ defaultStyle: DEFAULT_ENVIRONMENT_SHEET_STYLE,
+ negativesLabel: 'Environment sheet negatives',
+ })]),
+ object: Object.freeze([Object.freeze({
+ id: 'product',
+ label: 'Product sheet',
+ description: 'Front, side, back and top views on a plain backdrop, with a scale reference and macro detail.',
+ build: buildProductSheetPrompt,
+ defaultStyle: DEFAULT_PRODUCT_SHEET_STYLE,
+ negativesLabel: 'Product sheet negatives',
+ })]),
+});
+
+function characterVariants() {
+ return listSheetVariants().map((v) => ({
+ ...v,
+ build: getSheetVariantBuilder(v.id),
+ defaultStyle: DEFAULT_CHARACTER_SHEET_STYLE,
+ negativesLabel: 'Character sheet negatives',
+ }));
+}
+
+function variantsForType(type) {
+ if (type === 'character') return characterVariants();
+ return Object.prototype.hasOwnProperty.call(CATALOG_SHEET_VARIANTS, type) ? CATALOG_SHEET_VARIANTS[type] : [];
+}
+
+/** The sheet kinds a catalog type can render (empty for types without one). */
+export function listCatalogSheetVariants(type) {
+ return variantsForType(type).map(({ id, label, description }) => ({ id, label, description }));
+}
+
+// Load + guard the record, resolve its variant and any universe it links to.
+async function resolveSheetTarget(id, options) {
+ const ingredient = await getIngredient(id);
+ if (!ingredient) throw new ServerError('Ingredient not found', { status: 404, code: 'NOT_FOUND' });
+ const payload = ingredient.payload && typeof ingredient.payload === 'object' ? ingredient.payload : {};
+ if (payload.locked === true) {
+ throw new ServerError(
+ `"${ingredient.name}" is locked — unlock it before rendering a reference sheet`,
+ { status: 409, code: 'CATALOG_INGREDIENT_LOCKED' },
+ );
+ }
+ const variants = variantsForType(ingredient.type);
+ const variant = options.variant
+ ? variants.find((v) => v.id === options.variant)
+ : variants[0];
+ if (!variant) {
+ throw new ServerError(
+ `Sheet variant "${options.variant ?? ''}" is not available for a ${ingredient.type}`,
+ { status: 400, code: 'VALIDATION_ERROR' },
+ );
+ }
+
+ const refs = await listLiveRefsForIngredient(id);
+ const universes = [];
+ for (const ref of refs) {
+ if (ref.refKind !== 'universe') continue;
+ // A ref can outlive its universe (getUniverse throws NOT_FOUND then).
+ const universe = await getUniverse(ref.refId).catch(() => null);
+ if (universe) universes.push(universe);
+ }
+ if (ingredient.type === 'character') {
+ for (const universe of universes) {
+ const entry = (universe.characters || []).find((c) => c.ingredientId === id);
+ if (entry) return { ingredient, payload, variant, delegate: { universeId: universe.id, entryId: entry.id } };
+ }
+ }
+ return { ingredient, payload, variant, universe: universes[0] ?? 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);
+ const universeStyle = universe ? universeAestheticLine(universe) : '';
+ return buildSheetRenderParams({
+ built,
+ options,
+ styleLine: 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) : {},
+ });
+}
+
+/** What a catalog sheet render would send, built by the render's own code. */
+export async function previewCatalogSheet(id, options = {}) {
+ const target = await resolveSheetTarget(id, options);
+ if (target.delegate) {
+ return previewCharacterReferenceSheet(target.delegate.universeId, target.delegate.entryId, {
+ ...options, variant: target.variant.id,
+ });
+ }
+ const { params } = await buildCatalogSheet(target, options);
+ return {
+ sentPrompt: params.prompt,
+ ...(params.negativePrompt ? { sentNegativePrompt: params.negativePrompt } : {}),
+ promptAdditions: params.promptAdditions || [],
+ };
+}
+
+/** Queue a sheet render for a catalog record; returns `{ jobId, variant, delegatedTo }`. */
+export async function renderCatalogSheet(id, options = {}) {
+ const target = await resolveSheetTarget(id, options);
+ if (target.delegate) {
+ const { universeId, entryId } = target.delegate;
+ 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 role = `sheet:${target.variant.id}`;
+ params.catalogAttach = { ingredientId: id, kind: 'reference', role };
+ const queued = await enqueueJob({ kind: 'image', params });
+ console.log(`🎨 Catalog ${target.variant.label} render — ingredient=${shortId(id)} job=${shortId(queued.jobId)} mode=${activeMode} model=${modelId}`);
+ return {
+ jobId: queued.jobId,
+ generationId: queued.jobId,
+ variant: target.variant.id,
+ role,
+ delegatedTo: null,
+ queuePosition: queued.position,
+ };
+}
diff --git a/server/services/catalogSheetPrompts.js b/server/services/catalogSheetPrompts.js
new file mode 100644
index 0000000000..cc1cf6b7ca
--- /dev/null
+++ b/server/services/catalogSheetPrompts.js
@@ -0,0 +1,107 @@
+/**
+ * Catalog reference-sheet prompt builders for places and objects.
+ *
+ * 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.
+ */
+
+import { ServerError } from '../lib/errorHandler.js';
+import { universeAestheticLine } from '../lib/universeVisualStyle.js';
+import { REFERENCE_SHEET_CONSTANTS } from './universeCharacterSheet.js';
+
+const { DEFAULT_WIDTH, DEFAULT_HEIGHT } = REFERENCE_SHEET_CONSTANTS;
+
+const trim = (s) => (typeof s === 'string' ? s.trim() : '');
+
+export const DEFAULT_ENVIRONMENT_SHEET_STYLE = 'Style: cinematic environment concept art with grounded lighting, readable depth, and a deliberate, cohesive color script.';
+export const DEFAULT_PRODUCT_SHEET_STYLE = 'Style: clean industrial-design product rendering with accurate materials, crisp edges, and soft studio lighting.';
+
+function requireEntry(entry, fn) {
+ if (!entry || typeof entry !== 'object') {
+ throw new ServerError(`${fn}: entry is required`, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+}
+
+/** Environment sheet for a place: establishing wide, reverse, inserts, palette — no people. */
+export function buildEnvironmentSheetPrompt(universe, place) {
+ requireEntry(place, 'buildEnvironmentSheetPrompt');
+ const styleBits = universeAestheticLine(universe || {});
+ const name = trim(place.name) || 'Unnamed place';
+ const slugline = trim(place.slugline);
+ const description = trim(place.description);
+ const palette = trim(place.palette);
+ const era = trim(place.era);
+ const weather = trim(place.weather);
+ const intExt = trim(place.intExt);
+ const timeOfDay = trim(place.timeOfDay);
+ const recurring = trim(place.recurringDetails);
+ const visualPrompt = trim(place.prompt);
+
+ const headerBits = [
+ `Location: ${name}.`,
+ slugline ? `Slugline: ${slugline}.` : '',
+ intExt ? `${intExt === 'INT' ? 'Interior' : 'Exterior'}.` : '',
+ timeOfDay ? `Time of day: ${timeOfDay}.` : '',
+ era ? `Era: ${era}.` : '',
+ weather ? `Weather: ${weather}.` : '',
+ ].filter(Boolean).join(' ');
+
+ const promptParts = [
+ 'ENVIRONMENT REFERENCE SHEET — single location design page laid out in clear panels with thin borders, clean typography, and labeled zones. The location is EMPTY: no people, no characters, no figures anywhere on the sheet.',
+ styleBits || DEFAULT_ENVIRONMENT_SHEET_STYLE,
+ `Sheet header (top of sheet): ${headerBits}`,
+ description ? `Location description: ${description}` : '',
+ visualPrompt ? `Visual notes: ${visualPrompt}` : '',
+ `Establishing wide shot (large top zone): a wide establishing view of ${name} showing its full layout, scale, and how the space reads at a glance, labeled "ESTABLISHING".`,
+ `Reverse angle (middle left): the same location seen from the opposite direction, so the space reads consistently in three dimensions, labeled "REVERSE".`,
+ `Detail inserts (middle right): a row of three close-up inserts of characteristic surfaces, fixtures, and textures of ${name}, each labeled.`,
+ recurring ? `Recurring details panel: labeled callouts of the details that must stay consistent in every shot — ${recurring}.` : '',
+ palette
+ ? `Color palette strip (bottom): a row of labeled color swatch chips taken from the location — ${palette}.`
+ : `Color palette strip (bottom): a row of five labeled color swatch chips sampled from the location's dominant colors.`,
+ 'Layout: thin black panel borders on off-white paper. Light grey labels under each zone. The same location, lighting, and architecture across every panel. Render in one consistent style throughout the page — do NOT mix art styles between panels.',
+ ].filter(Boolean);
+
+ return {
+ prompt: promptParts.join('\n\n'),
+ negativePrompt: 'people, person, characters, figures, crowd, faces, text artifacts, watermark, signature, blurry, distorted perspective, inconsistent architecture, low contrast labels',
+ width: DEFAULT_WIDTH,
+ height: DEFAULT_HEIGHT,
+ modelId: null,
+ };
+}
+
+/** Product sheet for an object: orthographic views on a plain backdrop, scale reference, macro detail. */
+export function buildProductSheetPrompt(universe, object) {
+ requireEntry(object, 'buildProductSheetPrompt');
+ const styleBits = universeAestheticLine(universe || {});
+ const name = trim(object.name) || 'Unnamed object';
+ const aliases = Array.isArray(object.aliases) ? object.aliases.map(trim).filter(Boolean).join(', ') : '';
+ const description = trim(object.description);
+ const significance = trim(object.significance);
+ const visualPrompt = trim(object.prompt);
+
+ const promptParts = [
+ 'PRODUCT REFERENCE SHEET — single object design page laid out in clear panels with thin borders, clean typography, and labeled views, on a plain seamless light-grey backdrop.',
+ styleBits || DEFAULT_PRODUCT_SHEET_STYLE,
+ `Sheet header (top of sheet): Object: ${name}.${aliases ? ` Also known as: ${aliases}.` : ''}`,
+ description ? `Object description: ${description}` : '',
+ significance ? `Significance: ${significance}` : '',
+ visualPrompt ? `Visual notes: ${visualPrompt}` : '',
+ `Orthographic views (large top zone): four views of ${name} side by side at identical scale — FRONT, SIDE, BACK, TOP — each on the plain backdrop with a soft contact shadow and a caption strip reading "FRONT", "SIDE", "BACK", "TOP".`,
+ `Scale reference (lower left): ${name} beside a simple measuring ruler and a neutral reference object so its real-world size reads clearly, labeled "SCALE".`,
+ `Macro detail (lower right): two close-up macro shots of the most distinctive material, surface finish, marking, or mechanism of ${name}, each labeled.`,
+ 'Layout: thin black panel borders, light grey labels under each view. The same object, materials, and proportions in every view. No hands, no people, no busy background. Render in one consistent style throughout the page.',
+ ].filter(Boolean);
+
+ return {
+ prompt: promptParts.join('\n\n'),
+ negativePrompt: 'hands, people, person, busy background, clutter, multiple different objects, text artifacts, watermark, signature, blurry, distorted proportions, inconsistent views, low contrast labels',
+ width: DEFAULT_WIDTH,
+ height: DEFAULT_HEIGHT,
+ modelId: null,
+ };
+}
diff --git a/server/services/universeCharacterSheet.js b/server/services/universeCharacterSheet.js
index af1b7f6c8e..1d39d85129 100644
--- a/server/services/universeCharacterSheet.js
+++ b/server/services/universeCharacterSheet.js
@@ -71,6 +71,10 @@ const DEFAULT_HAND_GESTURES = Object.freeze([
const trim = (s) => (typeof s === 'string' ? s.trim() : '');
+// Style line a sheet carries when no universe supplies one (a catalog-only
+// record). Exported so the catalog renderer can list it as a prompt addition.
+export const DEFAULT_CHARACTER_SHEET_STYLE = 'Style: contemporary illustrated character design with confident line work and saturated, intentional color.';
+
// Shared field bag used by every variant's prompt builder. Centralizes the
// trim/flatten calls so a new variant only writes the style-specific layout
// sentences. Pure — caller decides which fields to weave into its prompt.
@@ -144,7 +148,7 @@ export function buildCharacterReferenceSheetPrompt(universe, character) {
// header lead, then the per-zone layout enumeration.
const promptParts = [
'CHARACTER REFERENCE SHEET — single dense reference page laid out in clear panels with thin borders, clean typography, and labeled zones.',
- styleBits || 'Style: contemporary illustrated character design with confident line work and saturated, intentional color.',
+ styleBits || DEFAULT_CHARACTER_SHEET_STYLE,
`Character header (top of sheet): ${headerBits}`,
physical ? `Physical description: ${physical}` : '',
statsLine ? `Stats panel (small table, left side of header): ${statsLine}.` : '',
@@ -243,7 +247,7 @@ export function buildCharacterBlueprintSheetPrompt(universe, character) {
// "labels" that come out as gibberish glyphs.
const promptParts = [
`A character concept sheet of ${subject}, featuring detailed front, back, and side views, along with close-up sketches of facial features, costume details, and accessories. Annotated design notes and clearly labeled components are arranged across the layout, rendered in a refined blueprint style with glowing ${accent} accents and a structured ${base} base design, presented on a clean white background with a polished professional character design presentation.`,
- styleBits || 'Style: contemporary illustrated character design with confident line work and saturated, intentional color.',
+ styleBits || DEFAULT_CHARACTER_SHEET_STYLE,
`Header banner across the top of the sheet reads, in bold legible typography: "${name.toUpperCase()}${role ? ` — ${role.toUpperCase()}` : ''}".`,
`Main turnaround zone (large, fills the left two-thirds of the sheet): four full-body views of ${name} at consistent scale — FRONT, 3/4, SIDE, BACK — all fully illustrated in the universe's color palette. Each view sits over a small caption strip; the four caption strips read, left to right: ${turnaroundLabels}.`,
physical ? `Physical description (annotation paragraph next to the turnaround): ${physical}` : '',
@@ -319,6 +323,11 @@ function getVariantConfig(variant = LEGACY_SHEET_VARIANT_ID) {
return SHEET_VARIANTS[variant];
}
+/** The prompt builder for one character sheet variant (400 on an unknown id). */
+export function getSheetVariantBuilder(variant) {
+ return getVariantConfig(variant).build;
+}
+
// Catalog for the UI — pure, no I/O. The client renders one panel row per
// entry. New entries here become available everywhere without further wiring.
export function listSheetVariants() {
@@ -375,42 +384,28 @@ function subscribeToSheetJob(jobId, handlers) {
}
/**
- * Returns immediately with `{ jobId, generationId, filename, path }`.
- * Deferred copy + character stamp run when imageGenEvents emits 'completed';
- * any failure there is logged (the client tracks the render via SSE).
+ * The queued image params for a sheet: typed overrides, labeled additions
+ * (#11317), size, and the cloud/local model choice. Shared by every sheet
+ * renderer AND its preview so what a preview shows is what the render sends.
*
- * `variant` selects the sheet style ('standard' = illustrated turnaround,
- * 'blueprint' = annotated concept sheet on white). Defaults to 'standard'
- * so existing callers (and the legacy route) stay unchanged.
+ * `styleLine` is the style block the template carries; it is listed as
+ * `styleChip` only when the template (not a typed override) is sent and the
+ * block is actually in it. A typed override is sent exactly as written.
+ * Returns `{ params, prompt, negativePrompt, modelId, activeMode }`.
*/
-export async function renderCharacterReferenceSheet(universeId, entryId, options = {}) {
- const variant = options.variant || LEGACY_SHEET_VARIANT_ID;
- const variantConfig = getVariantConfig(variant);
- const universe = await getUniverse(universeId);
- const list = Array.isArray(universe.characters) ? universe.characters : [];
- const character = list.find((c) => c.id === entryId);
- if (!character) {
- throw new ServerError(`Character ${entryId} not found in universe`, {
- status: 404, code: 'UNIVERSE_CANON_NOT_FOUND',
- });
- }
- // Same frozen-identity guard the character refine/expand flows enforce —
- // the UI gates this too, but the route is reachable directly so the lock
- // has to be enforced server-side as well. 409 mirrors refineUniverseCharacter.
- if (character.locked === true) {
- throw new ServerError(
- `Character "${character.name}" is locked — unlock it before rendering a reference sheet`,
- { status: 409, code: 'UNIVERSE_CANON_LOCKED' },
- );
- }
-
- const built = variantConfig.build(universe, character);
-
+export async function buildSheetRenderParams({
+ built,
+ options = {},
+ styleLine = '',
+ renderPin = {},
+ styleChip = { id: 'universe-style', label: 'Universe style' },
+ negativesLabel = 'Character sheet negatives',
+}) {
const prompt = typeof options.overridePrompt === 'string' && options.overridePrompt.trim()
- ? options.overridePrompt.trim()
+ ? options.overridePrompt
: built.prompt;
const negativePrompt = typeof options.overrideNegativePrompt === 'string' && options.overrideNegativePrompt.trim()
- ? options.overrideNegativePrompt.trim()
+ ? options.overrideNegativePrompt
: built.negativePrompt;
const settings = await getSettings();
@@ -418,13 +413,12 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
// the media-job queue with the active mode set; codex and local are both
// first-class. External SD-API has no multi-zone layout support, so it
// gets a clear remediation rather than a silently-degraded render.
- // Render-target ladder (#3231): the universe's persisted pin (Phase 3) →
+ // Render-target ladder (#3231): the record's persisted pin (Phase 3) →
// the universe-character-sheet pin in settings.renderDefaults → the install
// default → local.
- const renderPin = recordRenderPin(universe);
const sheetTarget = resolveRenderTargetConfig(settings, RENDER_TARGET.UNIVERSE_CHARACTER_SHEET, {
- recordMode: renderPin.mode,
- recordModel: renderPin.modelId,
+ recordMode: renderPin?.mode,
+ recordModel: renderPin?.modelId,
fallbackMode: IMAGE_GEN_MODE.LOCAL,
});
const activeMode = sheetTarget.mode;
@@ -440,13 +434,12 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
// user zooms. resolveSheetDimensions bumps codex up to 4K landscape while
// local FLUX keeps its memory-tuned 2048×1536 defaults.
const { width, height } = resolveSheetDimensions(activeMode, built.width, built.height);
- // The sheet template is PortOS's own text around the character's fields; the
- // universe style and the sheet negatives it carries are listed on the
- // render's sent-prompt record (#11317). A typed override is sent as written.
- const styleLine = universeAestheticLine(universe);
+ // The sheet template is PortOS's own text around the record's fields; the
+ // style and the sheet negatives it carries are listed on the render's
+ // sent-prompt record (#11317). A typed override is sent as written.
const promptAdditions = [
- prompt === built.prompt && styleLine && prompt.includes(styleLine.trim()) ? promptAddition('universe-style', 'Universe style', styleLine) : null,
- negativePrompt === built.negativePrompt ? promptAddition('sheet-negatives', 'Character sheet negatives', built.negativePrompt) : null,
+ prompt === built.prompt && styleLine && prompt.includes(styleLine.trim()) ? promptAddition(styleChip.id, styleChip.label, styleLine) : null,
+ negativePrompt === built.negativePrompt ? promptAddition('sheet-negatives', negativesLabel, built.negativePrompt) : null,
].filter(Boolean);
const baseParams = {
mode: activeMode,
@@ -481,6 +474,61 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
{ status: 400, code: 'UNIVERSE_CHARACTER_SHEET_UNSUPPORTED_MODE' },
);
}
+ return { params, prompt, negativePrompt, modelId, activeMode };
+}
+
+// Load + guard one universe character and build its sheet params. Shared by
+// the render and its preview.
+async function prepareCharacterSheet(universeId, entryId, options) {
+ const variant = options.variant || LEGACY_SHEET_VARIANT_ID;
+ const variantConfig = getVariantConfig(variant);
+ const universe = await getUniverse(universeId);
+ const list = Array.isArray(universe.characters) ? universe.characters : [];
+ const character = list.find((c) => c.id === entryId);
+ if (!character) {
+ throw new ServerError(`Character ${entryId} not found in universe`, {
+ status: 404, code: 'UNIVERSE_CANON_NOT_FOUND',
+ });
+ }
+ // Same frozen-identity guard the character refine/expand flows enforce —
+ // the UI gates this too, but the route is reachable directly so the lock
+ // has to be enforced server-side as well. 409 mirrors refineUniverseCharacter.
+ if (character.locked === true) {
+ throw new ServerError(
+ `Character "${character.name}" is locked — unlock it before rendering a reference sheet`,
+ { status: 409, code: 'UNIVERSE_CANON_LOCKED' },
+ );
+ }
+ const built = variantConfig.build(universe, character);
+ const sheet = await buildSheetRenderParams({
+ built, options, styleLine: universeAestheticLine(universe), renderPin: recordRenderPin(universe),
+ });
+ return { variant, variantConfig, universe, character, ...sheet };
+}
+
+/** What a universe character's sheet render would send, without queueing it. */
+export async function previewCharacterReferenceSheet(universeId, entryId, options = {}) {
+ const { params } = await prepareCharacterSheet(universeId, entryId, options);
+ return {
+ sentPrompt: params.prompt,
+ ...(params.negativePrompt ? { sentNegativePrompt: params.negativePrompt } : {}),
+ promptAdditions: params.promptAdditions || [],
+ };
+}
+
+/**
+ * Returns immediately with `{ jobId, generationId, filename, path }`.
+ * Deferred copy + character stamp run when imageGenEvents emits 'completed';
+ * any failure there is logged (the client tracks the render via SSE).
+ *
+ * `variant` selects the sheet style ('standard' = illustrated turnaround,
+ * 'blueprint' = annotated concept sheet on white). Defaults to 'standard'
+ * so existing callers (and the legacy route) stay unchanged.
+ */
+export async function renderCharacterReferenceSheet(universeId, entryId, options = {}) {
+ const {
+ variant, variantConfig, universe, character, params, prompt, modelId, activeMode,
+ } = await prepareCharacterSheet(universeId, entryId, options);
// Resolve (or create) the universe's media collection up front, then attach
// a `universeRun` tag to the job so `universeBuilderCollectionHook` files