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
feat: preserve image generation metadata in catalog
[._.]/ Adam Eivyb03c1fcca983
diff --git a/server/lib/README.md b/server/lib/README.mdindex 77ea359c6c..130ef776e2 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -347,6 +347,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `imageRgba.js` | Sharp-backed RGBA boundary: `decodeRgbaFrame` decodes an image to `{ data, width, height }`, and `encodePng` turns a raw frame into PNG bytes for the caller's destination/hash policy. || `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. || `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). |+| `pngMetadata.js` | Bounded PNG `tEXt`/`zTXt`/`iTXt` extraction for Stable Diffusion-compatible provenance plus normalization of prompt, negative prompt, sampler, steps, CFG, seed, size, model, and model hash fields. Pure. || `threejsModel.js` | Validated declarative procedural-model schema plus deterministic standalone Three.js factory export for the Three.js Models workspace. Also the cross-section gate: `evaluateThreejsFlatness(spec)` counts distinct vertex planes per axis — relative to the mesh's own size, with a rotation-invariant zero-volume check behind it — and treats an `extrude` with no bevel thickness as the two-plane slab it is to report when the majority of identity-priority features are built only from flat parts — a model that reads right head-on and like cardboard when orbited. `buildThreejsFlatnessFeedback(flatness)` turns that into default refinement feedback; `listSpecNames(names)` is the shared capped name-list formatter both gates use in finding messages. Also the material-plausibility gate: `evaluateThreejsMaterialPlausibility(spec)` keys a bounded per-family prior table (metal, wood, plastic, glass, fabric, ceramic, rubber, stone, leather, paper) off tokens in each material's id and reports channels whose values the named substance does not support — metalness 0.9 oak, transmission 1.0 steel — skipping any id that names no family or two, and any channel the material's `type` never forwards to Three.js. Advisory only: it never clamps, because a stylized model may legitimately break every prior. `buildThreejsMaterialFeedback(plausibility)` turns that into default refinement feedback. The same pass emits a `reflective-material-without-environment` note when a spec authors reflective channels (metalness above 0.6, or any transmission/clearcoat/iridescence) while `environment.preset` is `none` — those channels read off an environment, so in that scene their values cannot be judged at all. Attachments are declared in two forms — the original anchor-less `attachmentPartIds` and the anchored `attachments: [{ partId, anchorPartId | anchorSocket, maxOffset }]` — and `resolveThreejsAttachments(articulation)` merges them into one canonical list (an anchored entry wins over a bare id) so every gate reads the same set; `isThreejsAttachmentAnchored(attachment)` is the shared anchored/unanchored predicate and `DEFAULT_ATTACHMENT_MAX_OFFSET` the default tolerance. The spec-level refinement rejects an anchor that does not resolve, one that is the attachment itself, an anchor chain that cycles, and the model root (the sole top-level part) — which carries no relationship to any body part. The spec carries an optional `environment` block (see `threejsModelEnvironment.js`), and `buildThreejsFactorySource()` stamps its render profile onto `root.userData.sculptRuntime.render` and exports it as `renderProfile`, so a consumer wiring their own `WebGLRenderer` reproduces the model instead of a differently tone-mapped approximation. || `threejsModelAnimation.js` | `summarizeThreejsAnimation(spec)` — clip inventory *and* playback gate over an already-validated Three.js spec: `{ animated, clipCount, cueCount, sequenceCount, movingPartCount, longestClipSeconds, findings, warningCount, clips }`. The schema proves a declared `animation` block is well *formed* (sequences on real parts, inside their clip, never two on one channel at once, never a cue without motion); this reports what the model *declared* — one entry per clip with its role, duration, sequence and distinct-cue counts — plus the ways a well-formed clip still plays badly: a clip authored against a pose the assembly does not build (`clip-start-pose-mismatch`), a handover between sequences that do not meet (`clip-sequence-jump`), a `loop: true` clip that does not return to where it began, a one-shot `idle`, an unfired cue, a long dead tail, and an articulation graph with no clip at all. Advisory warnings only — a static assembly is a complete answer. `buildThreejsAnimationFeedback(animation)` turns those findings into default refinement feedback. A spec with no `animation` key summarizes as not animated — never as evaluated-and-empty. || `threejsModelCoverage.js` | `evaluateThreejsPartCoverage(spec, { family })` — structural assembly gate over an already-validated Three.js spec: flags promised features fused onto the same part set, geometry claimed by no detail, and details nothing was built for (folded minor relief stays a `note`). With a subject family it also warns on a required component the spec never mentions at all — the one check that can fault a spec for what it failed to *promise*. `buildThreejsCoverageFeedback(coverage)` turns the error findings (plus any family gap) into default refinement feedback. |diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.jsindex 84487497bd..b9b8ea31ff 100644--- a/server/lib/catalogValidation.js+++ b/server/lib/catalogValidation.js@@ -598,17 +598,37 @@ export const catalogSyncTagSchema = z.object({syncSequence: z.string().optional(),}).passthrough();-// Media rows carry tombstone fields + editable metadata (role/caption).+// Media rows carry tombstone fields + editable attachment metadata+// (role/caption) and a bounded generation-provenance projection.// `kind` is freeform on the wire (not the strict enum) for the same forward-// compat reason as relations: a newer peer's extra media kind stores// harmlessly rather than 400-ing the whole envelope. `mediaKey` is a reference,// not bytes — the receiver matches it against its own library on apply.+export const catalogMediaMetadataSchema = z.object({+ format: z.string().max(64).optional(),+ parameters: z.string().max(64 * 1024).optional(),+ prompt: z.string().max(16_000).optional(),+ negativePrompt: z.string().max(16_000).optional(),+ steps: z.number().int().min(0).max(100_000).optional(),+ sampler: z.string().max(256).optional(),+ cfgScale: z.number().finite().min(0).max(1_000).optional(),+ seed: z.union([z.number().int(), z.string().max(128)]).optional(),+ width: z.number().int().positive().max(100_000).optional(),+ height: z.number().int().positive().max(100_000).optional(),+ modelHash: z.string().max(256).optional(),+ model: z.string().max(512).optional(),+}).passthrough().refine(+ (metadata) => JSON.stringify(metadata).length <= 96 * 1024,+ { message: 'media metadata exceeds 96KB JSON size cap' },+);+export const catalogSyncMediaSchema = z.object({ingredientId: z.string().max(80),mediaKey: z.string().max(512),kind: z.string().max(32),role: z.string().max(64).nullable().optional(),caption: z.string().max(2_000).nullable().optional(),+ metadata: catalogMediaMetadataSchema.optional(),createdAt: isoDate,deleted: z.boolean().optional(),deletedAt: z.string().nullable().optional(),@@ -642,7 +662,8 @@ export const catalogSyncEnvelopeSchema = z.object({tags: z.array(catalogSyncTagSchema).max(20_000).optional(),media: z.array(catalogSyncMediaSchema).max(20_000).optional(),// Additive catalog v8 block — user-defined type definitions. Optional so a- // ≤v7 peer's envelope (no `catalogTypes`) still validates.+ // ≤v7 peer's envelope (no `catalogTypes`) still validates. Media provenance+ // is the separate additive v9 field on each `media` row above.catalogTypes: z.array(catalogSyncUserTypeSchema).max(64).optional(),portosMeta,}).passthrough();diff --git a/server/lib/catalogValidation.test.js b/server/lib/catalogValidation.test.jsindex b1c68467f8..af64eb8af0 100644--- a/server/lib/catalogValidation.test.js+++ b/server/lib/catalogValidation.test.js@@ -26,6 +26,7 @@ import {catalogMediaAttachSchema,catalogMediaDetachSchema,catalogPortraitSetSchema,+ catalogMediaMetadataSchema,MEDIA_KINDS,catalogUrlIngestSchema,catalogUserTypeSchema,@@ -619,9 +620,18 @@ describe('catalogValidation — catalogSyncEnvelopeSchema media block', () => {media: [{ ingredientId: 'i1', mediaKey: 'a.png', kind: 'portrait', createdAt: '2026-01-01T00:00:00Z' },{ ingredientId: 'i1', mediaKey: 'b.png', kind: 'reference', role: 'mood', caption: 'rainy', createdAt: '2026-01-01T00:00:00Z', deleted: true, deletedAt: '2026-01-02T00:00:00Z' },+ { ingredientId: 'i1', mediaKey: 'c.png', kind: 'reference', metadata: { format: 'a1111', prompt: 'a lighthouse', negativePrompt: 'blur', steps: 18, seed: 9 }, createdAt: '2026-01-01T00:00:00Z' },],});- expect(out.media).toHaveLength(2);+ expect(out.media).toHaveLength(3);+ expect(out.media[2].metadata).toMatchObject({ format: 'a1111', prompt: 'a lighthouse', negativePrompt: 'blur', steps: 18, seed: 9 });+ });++ it('bounds media provenance while allowing provider-specific additive fields', () => {+ expect(catalogMediaMetadataSchema.parse({ prompt: 'a fox', workflow: { provider: 'example' } })).toMatchObject({+ prompt: 'a fox', workflow: { provider: 'example' },+ });+ expect(() => catalogMediaMetadataSchema.parse({ parameters: 'x'.repeat(64 * 1024 + 1) })).toThrow();});it('tolerates a forward (unknown) media kind on the wire', () => {diff --git a/server/lib/db/schema/catalog.js b/server/lib/db/schema/catalog.jsindex 1d15aa10e7..e915fb9474 100644--- a/server/lib/db/schema/catalog.js+++ b/server/lib/db/schema/catalog.js@@ -223,7 +223,9 @@ export const catalogDdl = [// here, so federation ships the key and the receiver matches its own// library (missing → metadata-missing integrity surface). `kind` is an// app-layer enum (MEDIA_KINDS in catalogTypes.js), not a DB CHECK. Soft-- // delete from day one so detaches tombstone + propagate. Mirrors the+ // delete from day one so detaches tombstone + propagate. `metadata` stores+ // bounded generation provenance (prompt, negative prompt, sampler, etc.)+ // when an image carries it. Mirrors the// catalog_ingredient_media block in init-db.sql (parity is asserted by// db.ddlParity.test.js).`CREATE TABLE IF NOT EXISTS catalog_ingredient_media (@@ -232,12 +234,16 @@ export const catalogDdl = [kind VARCHAR(32) NOT NULL,role VARCHAR(64),caption TEXT,+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb,created_at TIMESTAMPTZ DEFAULT NOW(),deleted BOOLEAN DEFAULT FALSE,deleted_at TIMESTAMPTZ,sync_sequence BIGSERIAL,PRIMARY KEY (ingredient_id, media_key, kind))`,+ // CREATE IF NOT EXISTS does not add columns to existing installs, so keep+ // the provenance upgrade idempotent for rows created before this field.+ `ALTER TABLE catalog_ingredient_media ADD COLUMN IF NOT EXISTS metadata JSONB NOT NULL DEFAULT '{}'::jsonb`,`CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_ingredient ON catalog_ingredient_media (ingredient_id)`,`CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_key ON catalog_ingredient_media (media_key)`,`CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_sync_seq ON catalog_ingredient_media (sync_sequence)`,@@ -359,15 +365,17 @@ export const catalogDdl = [EXECUTE FUNCTION update_catalog_relation_sync_seq()`,// Media UPDATE bumps sync_sequence on soft-delete/revival OR a mutable- // field (role/caption) change so a peer sees the edit/tombstone next pull.- // Mirrors the relation trigger but also watches the editable metadata.+ // field (role/caption/metadata) change so a peer sees the edit/tombstone+ // next pull. Mirrors the relation trigger but also watches the editable+ // metadata.`CREATE OR REPLACE FUNCTION update_catalog_media_sync_seq()RETURNS TRIGGER AS $$BEGINIF NEW.deleted IS DISTINCT FROM OLD.deletedOR NEW.deleted_at IS DISTINCT FROM OLD.deleted_atOR NEW.role IS DISTINCT FROM OLD.role- OR NEW.caption IS DISTINCT FROM OLD.caption THEN+ OR NEW.caption IS DISTINCT FROM OLD.caption+ OR NEW.metadata IS DISTINCT FROM OLD.metadata THENNEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_media', 'sync_sequence'));END IF;RETURN NEW;diff --git a/server/lib/index.js b/server/lib/index.jsindex 35069289a5..3dfa2300d3 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -310,6 +310,7 @@ export * from './imageFrameStats.js';export * from './imageRgba.js';export * from './imageWatermark.js';export * from './localImageFilename.js';+export * from './pngMetadata.js';export * from './pgFileFacade.js';export * from './multipart.js';export * from './safetensors.js';diff --git a/server/lib/pngMetadata.js b/server/lib/pngMetadata.jsnew file mode 100644index 0000000000..0fcd124f97--- /dev/null+++ b/server/lib/pngMetadata.js@@ -0,0 +1,241 @@+// PNG text metadata helpers for Stable Diffusion-compatible renders.+//+// The image upload path re-encodes images to PNG with sharp, which deliberately+// drops ancillary chunks. Read the bounded text chunks before that conversion so+// prompt provenance survives as structured application metadata instead of being+// lost with the source bytes.++import { inflateSync } from 'node:zlib';++const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);+const MAX_PNG_CHUNKS = 128;+const MAX_TEXT_BYTES = 64 * 1024;+const MAX_TEXT_CHUNK_BYTES = 256 * 1024;++const TEXT_CHUNK_TYPES = new Set(['tEXt', 'zTXt', 'iTXt']);+const METADATA_KEYS = new Set([+ 'parameters',+ 'prompt',+ 'negative_prompt',+ 'negative prompt',+ 'negativeprompt',+ 'sd-metadata',+ 'sd_metadata',+ 'invokeai_metadata',+ 'metadata',+]);++const asBuffer = (value) => {+ if (Buffer.isBuffer(value)) return value;+ if (value instanceof Uint8Array) return Buffer.from(value);+ return null;+};++const boundedText = (value) => {+ if (typeof value !== 'string') return null;+ const text = value.slice(0, MAX_TEXT_BYTES).trim();+ return text || null;+};++const firstText = (...values) => values.find((value) => typeof value === 'string' && value.trim())?.trim() || null;++const finiteNumber = (value) => {+ const number = typeof value === 'number' ? value : Number(value);+ return Number.isFinite(number) ? number : null;+};++const integerOrString = (value) => {+ if (typeof value === 'string' && value.trim()) {+ const trimmed = value.trim();+ const number = Number(trimmed);+ return Number.isSafeInteger(number) && String(number) === trimmed ? number : trimmed;+ }+ if (typeof value === 'number' && Number.isSafeInteger(value)) return value;+ return null;+};++function addIfPresent(target, key, value) {+ if (value === null || value === undefined || value === '') return;+ target[key] = value;+}++function parseSize(value) {+ if (typeof value !== 'string') return {};+ const match = /^(\d+)\s*x\s*(\d+)$/i.exec(value.trim());+ if (!match) return {};+ return { width: Number(match[1]), height: Number(match[2]) };+}++/**+ * Normalize the useful generation fields from either PNG metadata or a PortOS+ * image sidecar. Unknown sidecar fields are intentionally ignored: catalog+ * metadata is a small, stable provenance projection rather than a copy of an+ * entire provider-specific sidecar or workflow graph.+ */+export function normalizeGenerationMetadata(input) {+ if (!input || typeof input !== 'object' || Array.isArray(input)) return {};+ const metadata = {};++ addIfPresent(metadata, 'format', firstText(input.format));+ addIfPresent(metadata, 'parameters', boundedText(input.parameters));+ addIfPresent(metadata, 'prompt', boundedText(firstText(input.prompt, input.positivePrompt, input.positive_prompt)));+ addIfPresent(metadata, 'negativePrompt', boundedText(firstText(input.negativePrompt, input.negativeprompt, input.negative_prompt, input['negative prompt'], input.negative)));++ const steps = finiteNumber(input.steps ?? input.num_steps);+ if (Number.isInteger(steps) && steps >= 0) metadata.steps = steps;+ addIfPresent(metadata, 'sampler', boundedText(firstText(input.sampler, input.samplerName, input.sampler_name)));++ const cfgScale = finiteNumber(input.cfgScale ?? input.cfg_scale ?? input.guidanceScale ?? input.guidance_scale ?? input.guidance);+ if (cfgScale !== null && cfgScale >= 0) metadata.cfgScale = cfgScale;++ const seed = integerOrString(input.seed);+ if (seed !== null) metadata.seed = seed;++ const size = parseSize(input.size);+ const width = finiteNumber(input.width ?? size.width);+ const height = finiteNumber(input.height ?? size.height);+ if (Number.isInteger(width) && width > 0) metadata.width = width;+ if (Number.isInteger(height) && height > 0) metadata.height = height;++ addIfPresent(metadata, 'modelHash', boundedText(firstText(input.modelHash, input.model_hash)));+ addIfPresent(metadata, 'model', boundedText(firstText(input.model, input.modelName, input.model_name, input.modelId, input.model_id)));++ return metadata;+}++function readNullByte(buffer, start) {+ const index = buffer.indexOf(0, start);+ return index >= start ? index : -1;+}++function inflateText(buffer) {+ try {+ const inflated = inflateSync(buffer, { maxOutputLength: MAX_TEXT_BYTES });+ return boundedText(inflated.toString('utf8'));+ } catch {+ return null;+ }+}++function decodeTextChunk(type, data) {+ const keywordEnd = readNullByte(data, 0);+ if (keywordEnd <= 0 || keywordEnd > 79) return null;+ const keyword = data.toString('latin1', 0, keywordEnd);+ const lowerKeyword = keyword.toLowerCase();++ if (type === 'tEXt') {+ return { keyword, text: boundedText(data.subarray(keywordEnd + 1).toString('utf8')) };+ }++ if (type === 'zTXt') {+ if (keywordEnd + 2 > data.length || data[keywordEnd + 1] !== 0) return null;+ return { keyword, text: inflateText(data.subarray(keywordEnd + 2)) };+ }++ // iTXt: keyword, compression flag, compression method, language tag,+ // translated keyword, then the UTF-8 text. Only method 0 is defined today.+ const header = keywordEnd + 3;+ if (header > data.length || (data[keywordEnd + 1] !== 0 && data[keywordEnd + 1] !== 1) || data[keywordEnd + 2] !== 0) return null;+ const languageEnd = readNullByte(data, header);+ if (languageEnd < 0) return null;+ const translatedEnd = readNullByte(data, languageEnd + 1);+ if (translatedEnd < 0) return null;+ const textData = data.subarray(translatedEnd + 1);+ const text = data[keywordEnd + 1] === 1 ? inflateText(textData) : boundedText(textData.toString('utf8'));+ return { keyword, lowerKeyword, text };+}++function readTextChunks(value) {+ const buffer = asBuffer(value);+ if (!buffer || buffer.length < PNG_SIGNATURE.length || !buffer.subarray(0, 8).equals(PNG_SIGNATURE)) return [];++ const chunks = [];+ let offset = PNG_SIGNATURE.length;+ let count = 0;+ while (offset + 12 <= buffer.length && count++ < MAX_PNG_CHUNKS) {+ const length = buffer.readUInt32BE(offset);+ const chunkEnd = offset + 12 + length;+ if (chunkEnd > buffer.length) break;+ const type = buffer.toString('ascii', offset + 4, offset + 8);+ if (!/^[A-Za-z]{4}$/.test(type)) break;+ if (TEXT_CHUNK_TYPES.has(type) && length <= MAX_TEXT_CHUNK_BYTES) {+ const decoded = decodeTextChunk(type, buffer.subarray(offset + 8, offset + 8 + length));+ if (decoded?.text) chunks.push(decoded);+ }+ offset = chunkEnd;+ if (type === 'IEND') break;+ }+ return chunks;+}++function parseJsonObject(text) {+ if (!text || text.length > MAX_TEXT_BYTES) return null;+ try {+ const value = JSON.parse(text);+ return value && typeof value === 'object' && !Array.isArray(value) ? value : null;+ } catch {+ return null;+ }+}++const SETTINGS_PATTERN = /(?:^|,\s*)(Steps|Sampler(?: name)?|CFG scale|Guidance scale|Seed|Size|Model hash|Model):\s*/gi;++/** Parse the common Automatic1111 `parameters` text block. */+export function parseStableDiffusionParameters(value) {+ const parameters = boundedText(value);+ if (!parameters) return {};++ const lines = parameters.replace(/\r\n?/g, '\n').split('\n');+ const settingsLine = lines.findIndex((line) => /^\s*Steps:\s*/i.test(line));+ const negativeLine = lines.findIndex((line) => /^\s*Negative prompt:\s*/i.test(line));+ const promptEnd = [settingsLine, negativeLine].filter((index) => index >= 0).sort((a, b) => a - b)[0] ?? lines.length;++ const parsed = { format: 'a1111', parameters };+ addIfPresent(parsed, 'prompt', boundedText(lines.slice(0, promptEnd).join('\n')));+ if (negativeLine >= 0 && (settingsLine < 0 || negativeLine < settingsLine)) {+ const end = settingsLine >= 0 ? settingsLine : lines.length;+ addIfPresent(parsed, 'negativePrompt', boundedText(lines.slice(negativeLine, end).join('\n').replace(/^\s*Negative prompt:\s*/i, '')));+ }++ const settings = settingsLine >= 0 ? lines.slice(settingsLine).join(' ') : '';+ const values = {};+ const matches = [...settings.matchAll(SETTINGS_PATTERN)];+ matches.forEach((match, index) => {+ const start = match.index + match[0].length;+ const end = index + 1 < matches.length ? matches[index + 1].index : settings.length;+ values[match[1].toLowerCase()] = settings.slice(start, end).trim().replace(/,+$/, '').trim();+ });+ Object.assign(parsed, {+ steps: values.steps,+ sampler: values.sampler || values['sampler name'],+ cfgScale: values['cfg scale'] || values['guidance scale'],+ seed: values.seed,+ size: values.size,+ modelHash: values['model hash'],+ model: values.model,+ });+ return normalizeGenerationMetadata(parsed);+}++/**+ * Extract a bounded, structured provenance projection from PNG text chunks.+ * Malformed or unsupported metadata is treated as absent so an image upload+ * remains usable; sharp remains the authoritative image-format validator.+ */+export function extractPngGenerationMetadata(value) {+ const result = {};+ for (const chunk of readTextChunks(value)) {+ const key = chunk.keyword.toLowerCase();+ let candidate = {};+ if (key === 'parameters') {+ candidate = parseStableDiffusionParameters(chunk.text);+ } else if (METADATA_KEYS.has(key)) {+ const json = parseJsonObject(chunk.text);+ candidate = json ? normalizeGenerationMetadata(json) : normalizeGenerationMetadata({ [key]: chunk.text });+ }+ for (const [field, fieldValue] of Object.entries(candidate)) {+ if (result[field] === undefined || result[field] === null || result[field] === '') result[field] = fieldValue;+ }+ }+ return result;+}diff --git a/server/lib/pngMetadata.test.js b/server/lib/pngMetadata.test.jsnew file mode 100644index 0000000000..7e771086a8--- /dev/null+++ b/server/lib/pngMetadata.test.js@@ -0,0 +1,103 @@+import { describe, expect, it } from 'vitest';+import { deflateSync } from 'node:zlib';+import {+ extractPngGenerationMetadata,+ normalizeGenerationMetadata,+ parseStableDiffusionParameters,+} from './pngMetadata.js';++const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);++// The parser intentionally does not validate pixel chunks; sharp owns image+// validation. These small chunk fixtures keep the metadata contract focused.+const chunk = (type, data) => {+ const body = Buffer.isBuffer(data) ? data : Buffer.from(data);+ const header = Buffer.alloc(8);+ header.writeUInt32BE(body.length, 0);+ header.write(type, 4, 4, 'ascii');+ return Buffer.concat([header, body, Buffer.alloc(4)]);+};++const textChunk = (keyword, text) => chunk('tEXt', Buffer.concat([Buffer.from(keyword, 'latin1'), Buffer.from([0]), Buffer.from(text)]));+const ztxtChunk = (keyword, text) => chunk('zTXt', Buffer.concat([Buffer.from(keyword, 'latin1'), Buffer.from([0, 0]), deflateSync(Buffer.from(text))]));+const itxtChunk = (keyword, text, compressed = false) => chunk('iTXt', Buffer.concat([+ Buffer.from(keyword, 'utf8'), Buffer.from([0, compressed ? 1 : 0, 0]),+ Buffer.from([0]), Buffer.from([0]), compressed ? deflateSync(Buffer.from(text)) : Buffer.from(text),+]));++describe('parseStableDiffusionParameters', () => {+ it('extracts the prompt, negative prompt, and Automatic1111 settings', () => {+ expect(parseStableDiffusionParameters([+ 'a paper boat on a moonlit lake',+ 'Negative prompt: blurry, text',+ 'Steps: 24, Sampler: DPM++ 2M, CFG scale: 7.5, Seed: 42, Size: 768x512, Model hash: abc123, Model: example-model',+ ].join('\n'))).toEqual({+ format: 'a1111',+ parameters: 'a paper boat on a moonlit lake\nNegative prompt: blurry, text\nSteps: 24, Sampler: DPM++ 2M, CFG scale: 7.5, Seed: 42, Size: 768x512, Model hash: abc123, Model: example-model',+ prompt: 'a paper boat on a moonlit lake',+ negativePrompt: 'blurry, text',+ steps: 24,+ sampler: 'DPM++ 2M',+ cfgScale: 7.5,+ seed: 42,+ width: 768,+ height: 512,+ modelHash: 'abc123',+ model: 'example-model',+ });+ });+});++describe('extractPngGenerationMetadata', () => {+ it('reads tEXt, compressed zTXt, and JSON iTXt metadata without requiring a decoder', () => {+ const parameters = 'a small lighthouse\nNegative prompt: low quality\nSteps: 18, Sampler: Euler a, CFG scale: 6, Seed: 9, Size: 512x512';+ const png = Buffer.concat([+ PNG_SIGNATURE,+ textChunk('parameters', parameters),+ ztxtChunk('negative_prompt', 'low quality, watermark'),+ itxtChunk('sd-metadata', JSON.stringify({ model_name: 'example-sdxl', model_hash: 'deadbeef' }), true),+ chunk('IEND', ''),+ ]);++ expect(extractPngGenerationMetadata(png)).toEqual({+ format: 'a1111',+ parameters,+ prompt: 'a small lighthouse',+ negativePrompt: 'low quality',+ steps: 18,+ sampler: 'Euler a',+ cfgScale: 6,+ seed: 9,+ width: 512,+ height: 512,+ model: 'example-sdxl',+ modelHash: 'deadbeef',+ });+ });++ it('accepts the camel-case negative prompt keyword used by some exporters', () => {+ const png = Buffer.concat([+ PNG_SIGNATURE,+ textChunk('negativePrompt', 'low quality, watermark'),+ chunk('IEND', ''),+ ]);+ expect(extractPngGenerationMetadata(png)).toEqual({ negativePrompt: 'low quality, watermark' });+ });++ it('returns no metadata for non-PNG or malformed chunks', () => {+ expect(extractPngGenerationMetadata(Buffer.from('not a png'))).toEqual({});+ expect(extractPngGenerationMetadata(Buffer.concat([PNG_SIGNATURE, chunk('tEXt', Buffer.from('parameters'))]))).toEqual({});+ });+});++describe('normalizeGenerationMetadata', () => {+ it('maps PortOS sidecar field names to the catalog provenance shape', () => {+ expect(normalizeGenerationMetadata({+ prompt: 'a fox', negativePrompt: 'blurry', guidance: 4, seed: '7',+ width: 640, height: 384, steps: 20, modelId: 'example-model',+ })).toEqual({+ prompt: 'a fox', negativePrompt: 'blurry', cfgScale: 4, seed: 7,+ width: 640, height: 384, steps: 20, model: 'example-model',+ });+ });+});diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 7bed4bb352..df083698ef 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -372,7 +372,12 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// types). A v8 receiver still accepts ≤v7 senders (sender-behind); their// envelopes carry no `catalogTypes` block and the receiver applies the other// kinds as before.- catalog: 8,+ // v9 = catalog media rows carry bounded Stable Diffusion-compatible+ // generation provenance (prompt, negative prompt, sampler, seed, model,+ // and related fields). The metadata field is additive and optional on the+ // wire; a v9 sender must not push it to a ≤v8 receiver that would silently+ // drop it. A v9 receiver still accepts ≤v8 media rows without metadata.+ catalog: 9,// v1 = cross-machine resumable Story Builder sessions (#730). Sessions are// local-only by default and excluded from sync; only `sync: true` sessions// ride the `storyBuilder` snapshot category. This is a brand-NEW synceddiff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.jsindex 0310796401..0e018383d1 100644--- a/server/lib/schemaVersions.test.js+++ b/server/lib/schemaVersions.test.js@@ -44,6 +44,10 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {expect(PORTOS_SCHEMA_VERSIONS.mediaCollections).toBe(1);});+ it('version-gates catalog media generation provenance', () => {+ expect(PORTOS_SCHEMA_VERSIONS.catalog).toBe(9);+ });+it('version-gates the persisted FableLoom shot and reference shape', () => {// v7 adds timed shots and draft character image anchors; v8 adds the// optional per-character five-stage evolution lens on the series plan; v9diff --git a/server/routes/catalog.js b/server/routes/catalog.jsindex 543a897dc9..2d53da02b8 100644--- a/server/routes/catalog.js+++ b/server/routes/catalog.js@@ -48,7 +48,7 @@ import { resolveImageInputPath } from '../lib/fileUtils.js';import { embedIngredient, embedBatch, ingredientEmbedSeed } from '../services/embeddings.js';import { extractIngredientsForScrap } from '../services/catalogExtraction.js';import { ingestFromUrl, ingestFromFile, ingestFromVoice, ingestFromBrain } from '../services/catalogIngestSources.js';-import { uploadIngredientMediaFile, recordIngredientVoiceMemo } from '../services/catalogMedia.js';+import { readImageGenerationMetadata, uploadIngredientMediaFile, recordIngredientVoiceMemo } from '../services/catalogMedia.js';import { migrateBibleToCatalog } from '../scripts/migrateBibleToCatalog.js';import { PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';@@ -486,9 +486,13 @@ router.post('/ingredients/:id/media', asyncHandler(async (req, res) => {if (IMAGE_MEDIA_KINDS.has(body.kind) && !resolveImageInputPath(body.mediaKey)) {throw new ServerError(`Media key "${body.mediaKey}" not found in the media library`, { status: 422 });}+ const metadata = IMAGE_MEDIA_KINDS.has(body.kind)+ ? await readImageGenerationMetadata(body.mediaKey)+ : {};const media = await catalogDB.attachMedia(req.params.id, body.mediaKey, body.kind, {role: body.role ?? null,caption: body.caption ?? null,+ ...(Object.keys(metadata).length > 0 ? { metadata } : {}),});res.status(201).json(media);}));@@ -500,9 +504,11 @@ router.post('/ingredients/:id/media/portrait', asyncHandler(async (req, res) =>if (!resolveImageInputPath(body.mediaKey)) {throw new ServerError(`Media key "${body.mediaKey}" not found in the media library`, { status: 422 });}+ const metadata = await readImageGenerationMetadata(body.mediaKey);const media = await catalogDB.setPortraitMedia(req.params.id, body.mediaKey, {role: body.role ?? null,caption: body.caption ?? null,+ ...(Object.keys(metadata).length > 0 ? { metadata } : {}),});res.status(201).json(media);}));diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 9d7e69f629..b971ee44da 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -564,6 +564,7 @@ CREATE TABLE IF NOT EXISTS catalog_ingredient_media (kind VARCHAR(32) NOT NULL, -- portrait|reference|audio|video|document (MEDIA_KINDS)role VARCHAR(64), -- optional free label (e.g. 'hero-shot', 'angry')caption TEXT,+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb, -- bounded generation provenance when presentcreated_at TIMESTAMPTZ DEFAULT NOW(),deleted BOOLEAN DEFAULT FALSE, -- soft-delete tombstone so detaches propagate to peersdeleted_at TIMESTAMPTZ,@@ -710,14 +711,15 @@ CREATE TRIGGER trg_catalog_relation_sync_seq-- Media UPDATE bumps sync_sequence when a soft-delete/revival OR a mutable-- field (role/caption) changes, so peers receive the edit (or the tombstone)-- on their next pull. Unlike refs/relations, media rows carry editable--- metadata, so the change-detector also watches role + caption.+-- metadata, so the change-detector also watches role + caption + provenance.CREATE OR REPLACE FUNCTION update_catalog_media_sync_seq()RETURNS TRIGGER AS $$BEGINIF NEW.deleted IS DISTINCT FROM OLD.deletedOR NEW.deleted_at IS DISTINCT FROM OLD.deleted_atOR NEW.role IS DISTINCT FROM OLD.role- OR NEW.caption IS DISTINCT FROM OLD.caption THEN+ OR NEW.caption IS DISTINCT FROM OLD.caption+ OR NEW.metadata IS DISTINCT FROM OLD.metadata THENNEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_media', 'sync_sequence'));END IF;RETURN NEW;diff --git a/server/services/catalogDB/media.js b/server/services/catalogDB/media.jsindex 4469a48b14..546c5eef7b 100644--- a/server/services/catalogDB/media.js+++ b/server/services/catalogDB/media.js@@ -4,22 +4,38 @@* catalog_ingredient_media: typed references (portrait/reference/audio/video/* document) into the install's media library. `media_key` is a key into the* library (data/images + the history.jsonl sidecar) — never duplicated bytes.- * Detach is a soft-delete so peers receive the tombstone.+ * Image generation provenance lives in the bounded JSONB `metadata` projection;+ * detach is a soft-delete so peers receive the tombstone.*/import { query } from '../../lib/db.js';import { resolveImageInputPath } from '../../lib/fileUtils.js';import { rowToMedia, groupRowsByIngredient } from './shared.js';-export async function attachMedia(ingredientId, mediaKey, kind, { role = null, caption = null } = {}) {+const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value || {}, key);+const hasMeaningfulMetadata = (value) => value && typeof value === 'object'+ && !Array.isArray(value) && Object.keys(value).length > 0;++export async function attachMedia(ingredientId, mediaKey, kind, options = {}) {+ const { role = null, caption = null } = options;+ // Metadata is additive on the wire and optional at the call boundary. When+ // absent, leave an existing prompt untouched; a legacy attach/re-attach must+ // not erase provenance just because its caller predates this field.+ const hasMetadata = hasOwn(options, 'metadata') && hasMeaningfulMetadata(options.metadata);+ const metadataColumn = hasMetadata ? ', metadata' : '';+ const metadataPlaceholder = hasMetadata ? ', $6' : '';+ const metadataUpdate = hasMetadata ? ', metadata = EXCLUDED.metadata' : '';const result = await query(- `INSERT INTO catalog_ingredient_media (ingredient_id, media_key, kind, role, caption)- VALUES ($1, $2, $3, $4, $5)+ `INSERT INTO catalog_ingredient_media (ingredient_id, media_key, kind, role, caption${metadataColumn})+ VALUES ($1, $2, $3, $4, $5${metadataPlaceholder})ON CONFLICT (ingredient_id, media_key, kind) DO UPDATESET deleted = false, deleted_at = NULL,- role = EXCLUDED.role, caption = EXCLUDED.caption+ role = EXCLUDED.role, caption = EXCLUDED.caption${metadataUpdate}RETURNING *`,- [ingredientId, mediaKey, kind, role, caption],+ [+ ingredientId, mediaKey, kind, role, caption,+ ...(hasMetadata ? [JSON.stringify(options.metadata || {})] : []),+ ],);return rowToMedia(result.rows[0]);}@@ -41,7 +57,8 @@ export async function detachMedia(ingredientId, mediaKey, kind) {// demote any other live portrait. One active portrait per ingredient — the UI// renders it as the ingredient's avatar. Serialized as two statements; the// single-user trust model means no competing writer can interleave.-export async function setPortraitMedia(ingredientId, mediaKey, { role = null, caption = null } = {}) {+export async function setPortraitMedia(ingredientId, mediaKey, options = {}) {+ const { role = null, caption = null } = options;await query(`UPDATE catalog_ingredient_mediaSET deleted = true, deleted_at = NOW()@@ -49,7 +66,9 @@ export async function setPortraitMedia(ingredientId, mediaKey, { role = null, caAND media_key <> $2 AND deleted = false`,[ingredientId, mediaKey],);- return attachMedia(ingredientId, mediaKey, 'portrait', { role, caption });+ const attachOptions = { role, caption };+ if (hasOwn(options, 'metadata')) attachOptions.metadata = options.metadata;+ return attachMedia(ingredientId, mediaKey, 'portrait', attachOptions);}// Live (non-tombstoned) media rows for an ingredient's detail "Media" panel,diff --git a/server/services/catalogDB/shared.js b/server/services/catalogDB/shared.jsindex 91d0d9e351..2a3b5dca87 100644--- a/server/services/catalogDB/shared.js+++ b/server/services/catalogDB/shared.js@@ -162,6 +162,7 @@ export function rowToMedia(row) {kind: row.kind,role: row.role ?? null,caption: row.caption ?? null,+ metadata: row.metadata && typeof row.metadata === 'object' && !Array.isArray(row.metadata) ? row.metadata : {},createdAt: row.created_at.toISOString(),deleted: !!row.deleted,deletedAt: row.deleted_at?.toISOString() ?? null,diff --git a/server/services/catalogDB/sync.js b/server/services/catalogDB/sync.jsindex 2601be1061..0db2bdc232 100644--- a/server/services/catalogDB/sync.js+++ b/server/services/catalogDB/sync.js@@ -74,36 +74,48 @@ export async function upsertMediaFromPeer(media) {// shape to defend against. We still treat "tombstone keys absent" as "peer// has no opinion" so a forked peer that omits them preserves local state on// conflict. On INSERT a tombstone-less row defaults to deleted=false, which- // is correct (brand-new locally, peer believes it active). role/caption are- // always adopted from the peer (LWW is implicit — last writer's envelope wins- // for these tuple-unique rows, same as refs).+ // is correct (brand-new locally, peer believes it active). role/caption and+ // metadata are adopted when the peer includes them (LWW is implicit — last+ // writer's envelope wins for these tuple-unique rows, same as refs); an older+ // peer's absent metadata is no opinion.const hasTombstoneFields =Object.prototype.hasOwnProperty.call(media, 'deleted') ||Object.prototype.hasOwnProperty.call(media, 'deletedAt');+ // A peer that predates media provenance has no `metadata` key. Treat that as+ // no opinion on conflict, just like the tombstone-less compatibility path,+ // so an older peer cannot erase a prompt already stored locally.+ const hasMetadata = Object.prototype.hasOwnProperty.call(media, 'metadata')+ && media.metadata && typeof media.metadata === 'object'+ && !Array.isArray(media.metadata) && Object.keys(media.metadata).length > 0;+ const metadataColumn = hasMetadata ? ', metadata' : '';+ const metadataPlaceholder = hasMetadata ? `, $${hasTombstoneFields ? 9 : 7}` : '';+ const metadataUpdate = hasMetadata ? ', metadata = EXCLUDED.metadata' : '';+ const metadataParam = hasMetadata ? [JSON.stringify(media.metadata || {})] : [];if (hasTombstoneFields) {await query(`INSERT INTO catalog_ingredient_media- (ingredient_id, media_key, kind, role, caption, created_at, deleted, deleted_at)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8)+ (ingredient_id, media_key, kind, role, caption, created_at, deleted, deleted_at${metadataColumn})+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8${metadataPlaceholder})ON CONFLICT (ingredient_id, media_key, kind) DO UPDATESET role = EXCLUDED.role,caption = EXCLUDED.caption,deleted = EXCLUDED.deleted,- deleted_at = EXCLUDED.deleted_at`,+ deleted_at = EXCLUDED.deleted_at${metadataUpdate}`,[media.ingredientId, media.mediaKey, media.kind,media.role ?? null, media.caption ?? null, media.createdAt,!!media.deleted, media.deletedAt || null,+ ...metadataParam,],);} else {await query(`INSERT INTO catalog_ingredient_media- (ingredient_id, media_key, kind, role, caption, created_at)- VALUES ($1, $2, $3, $4, $5, $6)+ (ingredient_id, media_key, kind, role, caption, created_at${metadataColumn})+ VALUES ($1, $2, $3, $4, $5, $6${metadataPlaceholder})ON CONFLICT (ingredient_id, media_key, kind) DO UPDATE- SET role = EXCLUDED.role, caption = EXCLUDED.caption`,- [media.ingredientId, media.mediaKey, media.kind, media.role ?? null, media.caption ?? null, media.createdAt],+ SET role = EXCLUDED.role, caption = EXCLUDED.caption${metadataUpdate}`,+ [media.ingredientId, media.mediaKey, media.kind, media.role ?? null, media.caption ?? null, media.createdAt, ...metadataParam],);}}diff --git a/server/services/catalogDBMedia.test.js b/server/services/catalogDBMedia.test.jsindex 6e4b02bad4..da18d9a05f 100644--- a/server/services/catalogDBMedia.test.js+++ b/server/services/catalogDBMedia.test.js@@ -6,7 +6,8 @@* - setPortraitMedia demotes any other live portrait, then attaches;* - getMissingMediaForIngredient reports only keys that don't resolve against* the local media library (the metadata-missing integrity surface);- * - upsertMediaFromPeer distinguishes "tombstone fields present" from absent.+ * - upsertMediaFromPeer distinguishes "tombstone fields present" from absent;+ * - generation metadata round-trips and stays intact when an older peer omits it.** Postgres is mocked — we capture the SQL/params and assert on them, so the* suite runs without a live database. `resolveImageInputPath` is mocked so the@@ -73,6 +74,13 @@ describe('attachMedia', () => {await catalogDB.attachMedia('i1', 'hero.png', 'reference');expect(calls[0].params).toEqual(['i1', 'hero.png', 'reference', null, null]);});++ it('stores generation provenance alongside the attachment', async () => {+ const metadata = { format: 'a1111', prompt: 'a paper boat', steps: 24, seed: 42 };+ await catalogDB.attachMedia('i1', 'render.png', 'reference', { metadata });+ expect(calls[0].sql).toMatch(/metadata\)/i);+ expect(calls[0].params).toEqual(['i1', 'render.png', 'reference', null, null, JSON.stringify(metadata)]);+ });});describe('detachMedia', () => {@@ -130,6 +138,18 @@ describe('upsertMediaFromPeer', () => {expect(params).toEqual(['i1', 'a.png', 'portrait', 'r', 'c', 't', true, 't2']);});+ it('includes generation provenance when a peer sends the additive field', async () => {+ const metadata = { prompt: 'a lighthouse', negativePrompt: 'blur', seed: 9 };+ await catalogDB.upsertMediaFromPeer({+ ingredientId: 'i1', mediaKey: 'a.png', kind: 'portrait',+ role: 'r', caption: 'c', createdAt: 't', deleted: false, deletedAt: null, metadata,+ });+ const { sql, params } = calls[0];+ expect(sql).toMatch(/metadata\)/i);+ expect(sql).toMatch(/metadata = EXCLUDED\.metadata/i);+ expect(params).toEqual(['i1', 'a.png', 'portrait', 'r', 'c', 't', false, null, JSON.stringify(metadata)]);+ });+it('uses the tombstone-less INSERT (preserve local state) when the keys are absent', async () => {await catalogDB.upsertMediaFromPeer({ingredientId: 'i1', mediaKey: 'a.png', kind: 'portrait', createdAt: 't',@@ -139,6 +159,15 @@ describe('upsertMediaFromPeer', () => {expect(sql).toMatch(/SET role = EXCLUDED.role, caption = EXCLUDED.caption/i);expect(params).toEqual(['i1', 'a.png', 'portrait', null, null, 't']);});++ it('does not erase provenance when a peer has only an empty metadata object', async () => {+ await catalogDB.upsertMediaFromPeer({+ ingredientId: 'i1', mediaKey: 'a.png', kind: 'portrait', createdAt: 't', metadata: {},+ });+ const { sql, params } = calls[0];+ expect(sql).not.toMatch(/metadata = EXCLUDED\.metadata/i);+ expect(params).toEqual(['i1', 'a.png', 'portrait', null, null, 't']);+ });});describe('listIngredients card thumbnail', () => {diff --git a/server/services/catalogImageAttachHook.js b/server/services/catalogImageAttachHook.jsindex 9607bb2b5c..2cb8057c1c 100644--- a/server/services/catalogImageAttachHook.js+++ b/server/services/catalogImageAttachHook.js@@ -25,6 +25,7 @@import { createMediaJobImageHook } from './mediaJobImageHook.js';import { attachMedia, setPortraitMedia, listMediaForIngredient, getIngredient } from './catalogDB.js';+import { readImageGenerationMetadata } from './catalogMedia.js';import { createNewestWinsGuard } from '../lib/createNewestWinsGuard.js';// Newest-render-wins for the PORTRAIT slot only (#1791). The per-ingredient@@ -72,11 +73,15 @@ async function attachGeneratedImage({ ingredientId, kind, filename, queuedAt })if (target === 'portrait' && portraitGuard.isStale(ingredientId, queuedAt)) {target = 'reference';}+ const metadata = await readImageGenerationMetadata(filename);+ const metadataOptions = Object.keys(metadata).length > 0 ? { metadata } : null;if (target === 'portrait') {- await setPortraitMedia(ingredientId, filename);+ if (metadataOptions) await setPortraitMedia(ingredientId, filename, metadataOptions);+ else await setPortraitMedia(ingredientId, filename);portraitGuard.mark(ingredientId, queuedAt);} else {- await attachMedia(ingredientId, filename, 'reference');+ if (metadataOptions) await attachMedia(ingredientId, filename, 'reference', metadataOptions);+ else await attachMedia(ingredientId, filename, 'reference');}return target;}diff --git a/server/services/catalogMedia.js b/server/services/catalogMedia.jsindex 71d8a51b3b..3769ce12bc 100644--- a/server/services/catalogMedia.js+++ b/server/services/catalogMedia.js@@ -12,11 +12,13 @@// replica hashes the file when it federates.import { randomUUID } from 'crypto';+import { readFile } from 'fs/promises';import { join } from 'path';-import { ensureDir, PATHS, atomicWrite } from '../lib/fileUtils.js';+import { ensureDir, PATHS, atomicWrite, resolveImageInputPath } from '../lib/fileUtils.js';+import { extractPngGenerationMetadata, normalizeGenerationMetadata } from '../lib/pngMetadata.js';import { ServerError } from '../lib/errorHandler.js';import { getIngredient, attachMedia } from './catalogDB.js';-import { saveUploadedGalleryImage } from './imageGen/local.js';+import { readImageSidecar, saveUploadedGalleryImage } from './imageGen/local.js';import { transcribe } from './voice/stt.js';// media_key caption cap mirrors catalogMediaAttachSchema.caption (2 000 chars).@@ -33,6 +35,15 @@ const VIDEO_EXT = {'video/mp4': 'mp4', 'video/webm': 'webm', 'video/quicktime': 'mov', 'video/ogg': 'ogv',};+const hasMetadata = (value) => value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0;++const mediaAttachOptions = ({ role = null, caption = null, metadata = {} } = {}) => {+ const options = { role, caption };+ const normalized = normalizeGenerationMetadata(metadata);+ if (hasMetadata(normalized)) options.metadata = normalized;+ return options;+};+/*** Classify a browser-reported MIME into the media library it belongs in. Pure —* unit-tested. Strips any `;codecs=…` parameter first. Returns@@ -47,6 +58,31 @@ export function classifyUploadMime(mimeType) {return null;}+/**+ * Read the generation provenance for an existing gallery image. Sidecars are+ * authoritative for normalized/generated assets; the PNG fallback covers a+ * gallery key that arrived before its sidecar or was created by an older build.+ * Metadata is best-effort: a corrupt sidecar must not make an otherwise valid+ * image impossible to attach.+ */+export async function readImageGenerationMetadata(+ mediaKey,+ {+ readSidecarFn = readImageSidecar,+ readFileFn = readFile,+ resolveImagePathFn = resolveImageInputPath,+ } = {},+) {+ const sidecar = await Promise.resolve(readSidecarFn(mediaKey)).catch(() => null);+ const fromSidecar = normalizeGenerationMetadata(sidecar?.metadata);+ if (hasMetadata(fromSidecar)) return fromSidecar;++ const imagePath = resolveImagePathFn(mediaKey);+ if (!imagePath) return {};+ const bytes = await Promise.resolve(readFileFn(imagePath)).catch(() => null);+ return bytes ? extractPngGenerationMetadata(bytes) : {};+}+// Write raw bytes into a federating library dir under a collision-free// `upload-<uuid8>.<ext>` key. Returns the bare filename (the media_key).async function persistLibraryFile(buffer, dir, ext) {@@ -88,9 +124,12 @@ export async function uploadIngredientMediaFile(if (classified.category === 'image') {// saveUploadedGalleryImage validates size + format and 400s on a non-image.- const { filename: mediaKey } = await saveImageFn(dataBase64);+ const sourceMetadata = extractPngGenerationMetadata(Buffer.from(dataBase64, 'base64'));+ const saved = await saveImageFn(dataBase64);+ const metadata = hasMetadata(saved?.metadata) ? saved.metadata : sourceMetadata;+ const mediaKey = saved.filename;console.log(`📎 Catalog media upload: image ${mediaKey} → ingredient ${ingredientId}`);- return attachMediaFn(ingredientId, mediaKey, classified.kind, meta);+ return attachMediaFn(ingredientId, mediaKey, classified.kind, mediaAttachOptions({ ...meta, metadata }));}const buffer = Buffer.from(dataBase64, 'base64');@@ -98,7 +137,7 @@ export async function uploadIngredientMediaFile(const dir = classified.category === 'audio' ? PATHS.audio : PATHS.videos;const mediaKey = await persistFileFn(buffer, dir, classified.ext);console.log(`📎 Catalog media upload: ${classified.kind} ${mediaKey} → ingredient ${ingredientId} (${(buffer.length / 1024).toFixed(0)}KB, ${filename || 'unnamed'})`);- return attachMediaFn(ingredientId, mediaKey, classified.kind, meta);+ return attachMediaFn(ingredientId, mediaKey, classified.kind, mediaAttachOptions(meta));}/**@@ -128,6 +167,6 @@ export async function recordIngredientVoiceMemo(const ext = AUDIO_EXT[(mimeType || '').toLowerCase().split(';')[0].trim()] || 'wav';const mediaKey = await persistFileFn(buffer, PATHS.audio, ext);console.log(`🎙️ Catalog voice memo: ${mediaKey} → ingredient ${ingredientId} (${transcript.length} chars)`);- const media = await attachMediaFn(ingredientId, mediaKey, 'audio', { role, caption: transcript || null });+ const media = await attachMediaFn(ingredientId, mediaKey, 'audio', mediaAttachOptions({ role, caption: transcript || null }));return { media, transcript };}diff --git a/server/services/catalogMedia.test.js b/server/services/catalogMedia.test.jsindex 7fa59ea3b7..6e429365ae 100644--- a/server/services/catalogMedia.test.js+++ b/server/services/catalogMedia.test.js@@ -1,6 +1,7 @@import { describe, it, expect, vi } from 'vitest';import {classifyUploadMime,+ readImageGenerationMetadata,uploadIngredientMediaFile,recordIngredientVoiceMemo,} from './catalogMedia.js';@@ -48,6 +49,19 @@ describe('uploadIngredientMediaFile', () => {expect(media).toEqual({ mediaKey: 'upload-abcd1234.png', kind: 'reference' });});+ it('persists extracted generation provenance when the gallery saver returns it', async () => {+ const metadata = { format: 'a1111', prompt: 'a paper boat', negativePrompt: 'blurry', steps: 24, seed: 42 };+ const saveImageFn = vi.fn().mockResolvedValue({ filename: 'upload-provenance.png', metadata });+ const attachMediaFn = vi.fn().mockResolvedValue({ mediaKey: 'upload-provenance.png', kind: 'reference', metadata });+ await uploadIngredientMediaFile(+ { ingredientId: 'ing-1', dataBase64: b64('img'), mimeType: 'image/png' },+ { getIngredientFn: okIngredient, attachMediaFn, saveImageFn },+ );+ expect(attachMediaFn).toHaveBeenCalledWith(+ 'ing-1', 'upload-provenance.png', 'reference', { role: null, caption: null, metadata },+ );+ });+it('persists audio bytes to the library dir and attaches as audio', async () => {const persistFileFn = vi.fn().mockResolvedValue('upload-11112222.webm');const attachMediaFn = vi.fn().mockImplementation((id, key, kind) => ({ mediaKey: key, kind }));@@ -84,6 +98,26 @@ describe('uploadIngredientMediaFile', () => {});});+describe('readImageGenerationMetadata', () => {+ it('normalizes sidecar provenance and prefers it over the PNG fallback', async () => {+ const readFileFn = vi.fn();+ const metadata = await readImageGenerationMetadata('render.png', {+ readSidecarFn: async () => ({ metadata: { prompt: 'a fox', guidance: 4, modelId: 'example-model' } }),+ readFileFn,+ resolveImagePathFn: () => '/images/render.png',+ });+ expect(metadata).toEqual({ prompt: 'a fox', cfgScale: 4, model: 'example-model' });+ expect(readFileFn).not.toHaveBeenCalled();+ });++ it('returns no provenance when neither sidecar nor image is readable', async () => {+ await expect(readImageGenerationMetadata('missing.png', {+ readSidecarFn: async () => ({ metadata: {} }),+ resolveImagePathFn: () => null,+ })).resolves.toEqual({});+ });+});+describe('recordIngredientVoiceMemo', () => {it('transcribes, persists audio, and attaches with the transcript in caption', async () => {const transcribeFn = vi.fn().mockResolvedValue({ text: ' hello world ' });diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 047cdb0526..b6bf1e85a0 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -20,6 +20,7 @@ import { join, dirname, resolve as resolvePath, sep as PATH_SEP, basename } fromimport { tmpdir } from 'os';import { randomUUID } from 'crypto';import { atomicWrite, assertSafeFilename, detectImageFormat, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveImageInputPath, tryReadFile, rmGuarded, unlinkGuarded } from '../../lib/fileUtils.js';+import { extractPngGenerationMetadata } from '../../lib/pngMetadata.js';import { ServerError } from '../../lib/errorHandler.js';import { autoCleanGeneratedImage } from '../../lib/imageClean.js';import { rejectDegenerateFrame } from './frameGuard.js';@@ -1162,7 +1163,7 @@ async function refreshImageIndex(filename) {* filename and its `/data/images/` mount path for the caller to store.** @param {string} base64Data - Raw base64 (no data: URI prefix) image bytes- * @returns {Promise<{ filename: string, path: string }>}+ * @returns {Promise<{ filename: string, path: string, metadata: object }>}*/export async function saveUploadedGalleryImage(base64Data) {const buffer = Buffer.from(base64Data, 'base64');@@ -1176,6 +1177,9 @@ export async function saveUploadedGalleryImage(base64Data) {if (!detected) {throw new ServerError('Unsupported image format (expected PNG, JPEG, WebP, or GIF)', { status: 400, code: 'UNSUPPORTED_IMAGE' });}+ // Read Stable Diffusion-compatible PNG text chunks before sharp normalizes+ // the image. JPEG/WebP/GIF uploads simply produce an empty projection.+ const metadata = extractPngGenerationMetadata(buffer);// Normalize to PNG so the gallery's PNG-only list/delete paths manage it.// `.rotate()` with no args bakes in EXIF orientation before the metadata is// dropped, so a camera-JPEG portrait isn't saved sideways/upside-down.@@ -1183,9 +1187,15 @@ export async function saveUploadedGalleryImage(base64Data) {const filename = `upload-${randomUUID().slice(0, 8)}.png`;await ensureDir(PATHS.images);await atomicWrite(join(PATHS.images, filename), png);+ // The normalized PNG intentionally has no source text chunks. Keep the+ // bounded projection in the canonical gallery sidecar so gallery listings,+ // media indexing, and later catalog attachments can still recover it.+ if (Object.keys(metadata).length > 0) {+ await atomicWrite(join(PATHS.images, filename.replace('.png', '.metadata.json')), metadata);+ }await refreshImageIndex(filename);console.log(`📥 Saved uploaded gallery image: ${filename} (${(png.length / 1024).toFixed(0)}KB PNG, from ${detected.mime})`);- return { filename, path: `/data/images/${filename}` };+ return { filename, path: `/data/images/${filename}`, metadata };}export async function listGallery() {diff --git a/server/services/imageGen/saveUploadedGalleryImage.test.js b/server/services/imageGen/saveUploadedGalleryImage.test.jsindex 18e35db27f..d80128f857 100644--- a/server/services/imageGen/saveUploadedGalleryImage.test.js+++ b/server/services/imageGen/saveUploadedGalleryImage.test.js@@ -10,6 +10,32 @@ import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);const isPng = (buf) => buf.subarray(0, 8).equals(PNG_SIGNATURE);+const crc32 = (value) => {+ let crc = 0xffffffff;+ for (const byte of value) {+ crc ^= byte;+ for (let bit = 0; bit < 8; bit++) crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0);+ }+ return (crc ^ 0xffffffff) >>> 0;+};++const pngChunk = (type, data) => {+ const typeBytes = Buffer.from(type, 'ascii');+ const body = Buffer.concat([typeBytes, data]);+ const chunk = Buffer.alloc(data.length + 12);+ chunk.writeUInt32BE(data.length, 0);+ typeBytes.copy(chunk, 4);+ data.copy(chunk, 8);+ chunk.writeUInt32BE(crc32(body), data.length + 8);+ return chunk;+};++const addPngText = (png, keyword, text) => Buffer.concat([+ png.subarray(0, -12),+ pngChunk('tEXt', Buffer.concat([Buffer.from(keyword, 'latin1'), Buffer.from([0]), Buffer.from(text)])),+ png.subarray(-12),+]);+// Redirect PATHS.images at a per-test temp dir so saving an uploaded image// writes into the temp gallery, not the repo's real data/images.let imagesDir;@@ -72,6 +98,22 @@ describe('saveUploadedGalleryImage', () => {}});+ it('extracts Stable Diffusion parameters before normalization and writes a sidecar', async () => {+ const source = addPngText(realPng, 'parameters', [+ 'a paper boat on a moonlit lake',+ 'Negative prompt: blurry, text',+ 'Steps: 24, Sampler: DPM++ 2M, CFG scale: 7.5, Seed: 42, Size: 768x512, Model hash: abc123, Model: example-model',+ ].join('\n'));+ const { filename, metadata } = await saveUploadedGalleryImage(source.toString('base64'));+ expect(metadata).toMatchObject({+ format: 'a1111', prompt: 'a paper boat on a moonlit lake', negativePrompt: 'blurry, text',+ steps: 24, sampler: 'DPM++ 2M', cfgScale: 7.5, seed: 42, width: 768, height: 512,+ modelHash: 'abc123', model: 'example-model',+ });+ const sidecar = join(imagesDir, filename.replace('.png', '.metadata.json'));+ expect(JSON.parse(readFileSync(sidecar, 'utf8'))).toMatchObject(metadata);+ });+it('rejects an empty upload with a 400', async () => {await expect(saveUploadedGalleryImage('')).rejects.toMatchObject({ status: 400 });});