Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(backup): drain image completion and pair replacements before snapshots
[._.]/ Adam Eivy9a18c36461db
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 1aba6af6d2..8b497eb551 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -100,8 +100,8 @@ Admission inventory (`withBackupAssetPublication`):| YouTube ingest (`youtubeIngest.js`) | Covered (#9982 partial): downloads run outside admission; the index record that first names a transcript or audio file takes the lease, and forgetting an ingest drops the record and unlinks its files under one lease || Digital twin documents and genome upload/delete (`digital-twin-documents.js`, `genome.js`) | Covered (#9982 partial): each document file or raw genome file and the meta record naming it is one lease, including deletion || Derived media index (`mediaAssetIndex/`) | Rebuilt: `media_assets` rows are excluded from snapshot dumps; database restore rebuilds atomically from disk before reopening admission, and relevant file restores refresh the mirror |-| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): image generation tails || Explicit file purge (`dataManager.js`, `routes/uploads.js`, `routes/attachments.js`) | Covered: single and bulk deletions hold one lease. These operator-directed removals may intentionally leave external references; admission prevents a snapshot from interleaving with the removal, not from preserving that already-deleted state |+| Image generation completion, upscale/clean tails, variants and sketch pairs (`imageGen/*.js`, `mediaSketches.js`) | Covered (#9982 partial): provider output publication through sidecar and cleanup takes one lease; remote replacement and variant/sketch rewrites restore previous files on failure || Durable replacement/deletion owners not yet classified | Outstanding (#9982) || Snapshot consistency claim (`backupAssetOwners.js`, see below) | Covered (#9982 partial) || Database restore execution and backend-cutover acceptance (`backup.js`, `databasePreflight.js`) | Covered (#9983) |diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.jsindex a4768d7241..f422947b6b 100644--- a/server/lib/backupAssetOwners.js+++ b/server/lib/backupAssetOwners.js@@ -325,15 +325,15 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([modules: ['services/mediaAssetIndex/index.js', 'services/mediaAssetIndex/db.js'],},{- // The post-exit tails of the generation lanes (upscale, sidecar, auto-clean),- // variants and sketch pairs. `imageGen/local.js` takes the lease only for- // gallery upload, sidecar edits and deletion, not for its generation tail.+ // Provider completion (upscale, sidecar, auto-clean), remote promotion,+ // variants and sketch pairs retain admission through their failure cleanup.id: 'image-generation-completion-tails',- status: 'outstanding',+ status: 'admitted',modules: ['services/imageGen/local.js', 'services/imageGen/agy.js', 'services/imageGen/codex.js','services/imageGen/grok.js', 'services/imageGen/fal.js', 'services/imageGen/external.js','services/imageGen/remote.js', 'services/imageGen/variants.js', 'services/mediaSketches.js',+ 'services/imageGen/publication.js', 'services/imageGen/index.js',],},{diff --git a/server/services/imageGen/agy.js b/server/services/imageGen/agy.jsindex c2e916ac01..7003b7b216 100644--- a/server/services/imageGen/agy.js+++ b/server/services/imageGen/agy.js@@ -1,3 +1,4 @@+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Image Gen — Antigravity (`agy`) CLI provider.@@ -411,72 +412,75 @@ async function runAgy(job, jobId, bin, args, {finalizeJobFailure(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);});proc.on('close', async (code, signal) => {- clearTimeout(timeoutTimer);- try {- if (code !== 0 || processError) {- removeScratch();- const reason = processError?.message || (signal ? `Killed by signal ${signal}` : `Exit code ${code}`);- return finalizeJobFailure(job, jobId, proc, `Agy generation failed: ${reason}\n${stderrTail.trim().split('\n').slice(-6).join('\n')}`);- }- const harvested = await harvestStagedImage(stagingPath, harvestTimeoutMs);- if (!harvested.found) {+ await withBackupAssetPublication(async () => {+ clearTimeout(timeoutTimer);+ try {+ if (code !== 0 || processError) {+ removeScratch();+ const reason = processError?.message || (signal ? `Killed by signal ${signal}` : `Exit code ${code}`);+ return finalizeJobFailure(job, jobId, proc, `Agy generation failed: ${reason}\n${stderrTail.trim().split('\n').slice(-6).join('\n')}`);+ }+ const harvested = await harvestStagedImage(stagingPath, harvestTimeoutMs);+ if (!harvested.found) {+ removeScratch();+ const prefix = harvested.invalid ? 'Agy wrote a non-image file at the directed path. ' : '';+ return finalizeJobFailure(job, jobId, proc, `${prefix}${noImageReason(stdoutTail)}`);+ }+ // A PNG landed — but the harvest gate only proves it is image bytes, not+ // that generate_image made them. Reject a file the agent drew itself.+ // The narration tail rides along like every other failure path here: it+ // carries WHY the tool was skipped (the 429 that triggers a fabricated+ // stand-in is only ever stated there), which the quota card then reads.+ const fabricated = await checkFabrication(scratchDir, AGY_TOOL);+ if (fabricated) {+ removeScratch();+ return finalizeJobFailure(job, jobId, proc, `${fabricated} ${noImageReason(stdoutTail)}`);+ }+ if (harvested.format === 'png') {+ await copyFileGuarded(stagingPath, outputPath);+ await unlinkGuarded(stagingPath).catch(() => {});+ } else {+ const pngBytes = await sharp(stagingPath).png().toBuffer();+ await atomicWrite(outputPath, pngBytes);+ }removeScratch();- const prefix = harvested.invalid ? 'Agy wrote a non-image file at the directed path. ' : '';- return finalizeJobFailure(job, jobId, proc, `${prefix}${noImageReason(stdoutTail)}`);- }- // A PNG landed — but the harvest gate only proves it is image bytes, not- // that generate_image made them. Reject a file the agent drew itself.- // The narration tail rides along like every other failure path here: it- // carries WHY the tool was skipped (the 429 that triggers a fabricated- // stand-in is only ever stated there), which the quota card then reads.- const fabricated = await checkFabrication(scratchDir, AGY_TOOL);- if (fabricated) {+ // Degenerate-frame gate (#4173) — before the sidecar, so a decodable but+ // contentless canvas never becomes a gallery record.+ const emptyFrame = await rejectDegenerateFrame(outputPath);+ if (emptyFrame) {+ return finalizeJobFailure(job, jobId, proc, emptyFrame);+ }+ const sidecar = join(PATHS.images, `${jobId}.metadata.json`);+ // `job.renderStartedAtMs` is the queue-ingestion instant generateImage+ // captured, so the spread measures the render itself — not the time the+ // job spent queued behind other renders.+ await atomicWrite(sidecar, { ...meta, ...renderTimingFields(job.renderStartedAtMs) });+ await autoCleanGeneratedImage({+ cleanC2PA,+ denoise,+ pngPath: outputPath,+ sidecarPath: sidecar,+ mode: IMAGE_GEN_MODE.AGY,+ });+ job.status = 'complete';+ if (activeProcs.get(jobId) === proc) activeProcs.delete(jobId);+ activeJobs.delete(jobId);+ console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (agy)`);+ const result = { filename, path: `/data/images/${filename}` };+ dispatchTerminalEvent(+ jobId,+ () => broadcastSse(job, { type: 'complete', result }),+ () => imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.AGY, generationId: jobId, path: result.path, filename }),+ );+ closeJobAfterDelay(jobs, jobId);+ } catch (err) {+ await Promise.all([outputPath, join(PATHS.images, `${jobId}.metadata.json`)].map(path => unlinkGuarded(path).catch(() => {})));removeScratch();- return finalizeJobFailure(job, jobId, proc, `${fabricated} ${noImageReason(stdoutTail)}`);+ // force: true — 'complete' is already stamped above; see+ // createJobFailureFinalizer's doc comment in sseUtils.js.+ finalizeJobFailure(job, jobId, proc, `Agy post-exit handler failed: ${err?.message || err}`, { force: true });}- if (harvested.format === 'png') {- await copyFileGuarded(stagingPath, outputPath);- await unlinkGuarded(stagingPath).catch(() => {});- } else {- const pngBytes = await sharp(stagingPath).png().toBuffer();- await atomicWrite(outputPath, pngBytes);- }- removeScratch();- // Degenerate-frame gate (#4173) — before the sidecar, so a decodable but- // contentless canvas never becomes a gallery record.- const emptyFrame = await rejectDegenerateFrame(outputPath);- if (emptyFrame) {- return finalizeJobFailure(job, jobId, proc, emptyFrame);- }- const sidecar = join(PATHS.images, `${jobId}.metadata.json`);- // `job.renderStartedAtMs` is the queue-ingestion instant generateImage- // captured, so the spread measures the render itself — not the time the- // job spent queued behind other renders.- await atomicWrite(sidecar, { ...meta, ...renderTimingFields(job.renderStartedAtMs) }).catch(() => maintenance.markCurrentUnsettled());- await autoCleanGeneratedImage({- cleanC2PA,- denoise,- pngPath: outputPath,- sidecarPath: sidecar,- mode: IMAGE_GEN_MODE.AGY,- });- job.status = 'complete';- if (activeProcs.get(jobId) === proc) activeProcs.delete(jobId);- activeJobs.delete(jobId);- console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (agy)`);- const result = { filename, path: `/data/images/${filename}` };- dispatchTerminalEvent(- jobId,- () => broadcastSse(job, { type: 'complete', result }),- () => imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.AGY, generationId: jobId, path: result.path, filename }),- );- closeJobAfterDelay(jobs, jobId);- } catch (err) {- removeScratch();- // force: true — 'complete' is already stamped above; see- // createJobFailureFinalizer's doc comment in sseUtils.js.- finalizeJobFailure(job, jobId, proc, `Agy post-exit handler failed: ${err?.message || err}`, { force: true });- }+ });});}diff --git a/server/services/imageGen/agy.test.js b/server/services/imageGen/agy.test.jsindex 885817999c..7911b846e6 100644--- a/server/services/imageGen/agy.test.js+++ b/server/services/imageGen/agy.test.js@@ -1,3 +1,4 @@+import { acquireBackupSnapshotCut } from '../../lib/backupSnapshotBoundary.js';import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { mkdir, readFile, rm, writeFile } from 'fs/promises';import { existsSync } from 'fs';@@ -265,7 +266,12 @@ describe('agy image provider', () => {Buffer.from('fakepngbody'),]);await writeFile(stagingPathFor(job.jobId), png);+ const releaseCut = await acquireBackupSnapshotCut();+ try {await closeChild(0, 0);+ await new Promise(resolve => setImmediate(resolve));+ expect(existsSync(join(FAKE_IMAGES_DIR, job.filename)), 'provider completion must wait outside a held snapshot').toBe(false);+ } finally { releaseCut(); }const deadline = Date.now() + 3000;while (Date.now() < deadline && completed.mock.calls.length === 0) {diff --git a/server/services/imageGen/backupAdmission.test.js b/server/services/imageGen/backupAdmission.test.jsnew file mode 100644index 0000000000..cfb4a33ae0--- /dev/null+++ b/server/services/imageGen/backupAdmission.test.js@@ -0,0 +1,116 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++const state = vi.hoisted(() => ({ root: '', beforeWrite: null }));+vi.mock('../../lib/fileUtils.js', async importOriginal => {+ const actual = await importOriginal();+ return {+ ...actual,+ PATHS: { get images() { return state.root; }, get data() { return state.root; } },+ atomicWrite: async (path, data) => {+ await state.beforeWrite?.(path);+ return actual.atomicWrite(path, data);+ },+ };+});+vi.mock('../mediaCollections.js', () => ({ listCollections: async () => [], addItem: vi.fn(), ERR_DUPLICATE: 'duplicate' }));+vi.mock('../mediaAssetIndex/index.js', () => ({ indexImage: vi.fn() }));+vi.mock('../../lib/databaseMaintenanceJournal.js', () => ({ assertDatabaseAdmission() {} }));++const { persistVariant } = await import('./variants.js');+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');+const turn = () => new Promise(resolve => setImmediate(resolve));+function deferred() {+ let resolve;+ const promise = new Promise(done => { resolve = done; });+ return { promise, resolve };+}+const variant = () => persistVariant({ sourceFilename: 'source.png', outFilename: 'variant.png',+ data: Buffer.from('new pixels'), variantMeta: { prompt: 'new metadata' }, logLine: '🖼️ Example variant' });+async function snapshot() {+ const files = {};+ for (const name of await readdir(state.root)) files[name] = await readFile(join(state.root, name), 'utf8');+ return files;+}++beforeEach(async () => {+ state.root = await mkdtemp(join(tmpdir(), 'image-backup-admission-'));+ state.beforeWrite = null;+});+afterEach(async () => { state.beforeWrite = null; await rm(state.root, { recursive: true, force: true }); });++describe('variant publication versus snapshot file copy', () => {+ it('holds a requested cut between pixel replacement and its metadata, then snapshots the completed pair', async () => {+ const reached = deferred(); const finish = deferred();+ state.beforeWrite = async path => { if (path.endsWith('.metadata.json')) { reached.resolve(); await finish.promise; } };+ const publishing = variant();+ await reached.promise;+ expect(await readFile(join(state.root, 'variant.png'), 'utf8')).toBe('new pixels');+ let cutReady = false;+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });+ try {+ await turn();+ expect(cutReady, 'snapshot must not capture pixels without their sidecar').toBe(false);+ } finally { finish.resolve(); }+ await publishing;+ const release = await cut;+ try {+ expect(await snapshot()).toEqual({ 'variant.png': 'new pixels', 'variant.metadata.json': expect.stringContaining('new metadata') });+ } finally { release(); }+ });++ it('leaves an existing snapshot unchanged while a replacement waits outside its cut', async () => {+ await writeFile(join(state.root, 'variant.png'), 'old pixels');+ await writeFile(join(state.root, 'variant.metadata.json'), '{"prompt":"old metadata"}');+ const release = await acquireBackupSnapshotCut();+ const publishing = variant();+ try {+ await turn();+ expect(await snapshot()).toEqual({ 'variant.png': 'old pixels', 'variant.metadata.json': '{"prompt":"old metadata"}' });+ } finally { release(); }+ await publishing;+ expect((await snapshot())['variant.png']).toBe('new pixels');+ });++ it('restores the old pair before a failed replacement releases a waiting snapshot', async () => {+ await writeFile(join(state.root, 'variant.png'), 'old pixels');+ await writeFile(join(state.root, 'variant.metadata.json'), '{"prompt":"old metadata"}');+ const reached = deferred(); const finish = deferred();+ state.beforeWrite = async path => {+ if (path.endsWith('.metadata.json')) { reached.resolve(); await finish.promise; throw new Error('sidecar disk failure'); }+ };+ const publishing = variant();+ const failed = expect(publishing).rejects.toThrow('sidecar disk failure');+ await reached.promise;+ let cutReady = false;+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });+ try { await turn(); expect(cutReady).toBe(false); } finally { finish.resolve(); }+ await failed;+ const release = await cut;+ try {+ expect(await snapshot()).toEqual({ 'variant.png': 'old pixels', 'variant.metadata.json': '{"prompt":"old metadata"}' });+ } finally { release(); }+ });+});++it('serializes sketch replacement/deletion and snapshots matching PNG and vector state', async () => {+ // mediaSketches captures its data directory when imported; load only after the synthetic root exists.+ const { saveSketch, removeSketch, getSketch, getSketchPng } = await import('../mediaSketches.js');+ const key = 'image:example.png';+ const input = { width: 10, height: 10, strokes: [{ mode: 'draw', color: '#ffffff', size: 2, points: [{ x: 1, y: 1 }] }],+ png: `data:image/png;base64,${Buffer.from('sketch pixels').toString('base64')}` };+ await mkdir(join(state.root, 'media-sketches'), { recursive: true });+ await saveSketch(key, input);+ const release = await acquireBackupSnapshotCut();+ const deleting = removeSketch(key);+ try {+ await turn();+ expect((await getSketch(key)).hasPng).toBe(true);+ expect((await getSketchPng(key)).toString()).toBe('sketch pixels');+ } finally { release(); }+ await deleting;+ expect(await getSketch(key)).toBeNull();+ expect(await getSketchPng(key)).toBeNull();+});diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.jsindex 83acc29045..52b5d94e1c 100644--- a/server/services/imageGen/codex.js+++ b/server/services/imageGen/codex.js@@ -1,4 +1,4 @@-import { maintenance } from '../../lib/maintenanceAdmission.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';/*** Image Gen — Codex CLI provider.*@@ -37,7 +37,7 @@ import { existsSync } from 'fs';import { join } from 'path';import { homedir } from 'os';import { randomUUID } from 'crypto';-import { atomicWrite, copyFileGuarded, ensureDir, PATHS, sleep } from '../../lib/fileUtils.js';+import { atomicWrite, copyFileGuarded, ensureDir, PATHS, sleep, unlinkGuarded } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { autoCleanGeneratedImage } from '../../lib/imageClean.js';import { imageGenEvents } from '../imageGenEvents.js';@@ -398,73 +398,76 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cle});proc.on('close', async (code, signal) => {- clearTimeout(timeoutTimer);- // Don't clear activeProcess yet — the post-exit handler still does- // async work (harvest + copyFile + sidecar). Clearing the- // module-scoped guard up front would let a new generation start- // while we're still finalizing this one, then the in-flight- // finalizer could clobber the new job's activeJob snapshot.- // EventEmitter doesn't await async listeners — without this try/catch,- // a throw from harvestLatestImage / copyFile would surface as an- // unhandled rejection (process-killing on Node ≥15) and the job would- // be stuck in 'running' forever with no SSE error to the client.- try {- if (code !== 0 || processError) {- const reason = processError?.message || (signal ? `Killed by signal ${signal}` : `Exit code ${code}`);- const tail = stderrTail.trim().split('\n').slice(-6).join('\n');- return finalizeJobFailure(job, jobId, proc, `Codex generation failed: ${reason}\n${tail}`);- }- if (!sessionId) {- return finalizeJobFailure(job, jobId, proc, 'Codex returned no session id — output format may have changed');- }- // Codex writes the PNG asynchronously while it's wrapping up the turn.- // Empirically the file is on disk by the time `codex exec` exits, but- // poll for a few seconds in case there's a flush lag on slow disks.- const harvested = await harvestGeneratedImage(sessionId, harvestTimeoutMs);- if (!harvested) {- return finalizeJobFailure(job, jobId, proc, noImageReason(stdoutTail));+ await withBackupAssetPublication(async () => {+ clearTimeout(timeoutTimer);+ // Don't clear activeProcess yet — the post-exit handler still does+ // async work (harvest + copyFile + sidecar). Clearing the+ // module-scoped guard up front would let a new generation start+ // while we're still finalizing this one, then the in-flight+ // finalizer could clobber the new job's activeJob snapshot.+ // EventEmitter doesn't await async listeners — without this try/catch,+ // a throw from harvestLatestImage / copyFile would surface as an+ // unhandled rejection (process-killing on Node ≥15) and the job would+ // be stuck in 'running' forever with no SSE error to the client.+ try {+ if (code !== 0 || processError) {+ const reason = processError?.message || (signal ? `Killed by signal ${signal}` : `Exit code ${code}`);+ const tail = stderrTail.trim().split('\n').slice(-6).join('\n');+ return finalizeJobFailure(job, jobId, proc, `Codex generation failed: ${reason}\n${tail}`);+ }+ if (!sessionId) {+ return finalizeJobFailure(job, jobId, proc, 'Codex returned no session id — output format may have changed');+ }+ // Codex writes the PNG asynchronously while it's wrapping up the turn.+ // Empirically the file is on disk by the time `codex exec` exits, but+ // poll for a few seconds in case there's a flush lag on slow disks.+ const harvested = await harvestGeneratedImage(sessionId, harvestTimeoutMs);+ if (!harvested) {+ return finalizeJobFailure(job, jobId, proc, noImageReason(stdoutTail));+ }+ if (harvested.path) {+ await copyFileGuarded(harvested.path, outputPath);+ } else {+ await atomicWrite(outputPath, harvested.buffer);+ }+ // Degenerate-frame gate (#4173) — before the sidecar, so a decodable but+ // contentless canvas never becomes a gallery record.+ const emptyFrame = await rejectDegenerateFrame(outputPath);+ if (emptyFrame) {+ return finalizeJobFailure(job, jobId, proc, emptyFrame);+ }+ // Sidecar metadata so the gallery can recover prompt/seed/etc. The+ // codex sessionId is the closest analogue to a seed for gpt-image-2+ // (which doesn't expose one) — uniquely identifies the run and is+ // useful for traceability even though it doesn't reproduce the output.+ const sidecar = join(PATHS.images, `${jobId}.metadata.json`);+ // `job.renderStartedAtMs` is the queue-ingestion instant generateImage+ // captured, so the spread measures the render itself — not the time the+ // job spent queued behind other renders.+ await atomicWrite(sidecar, { ...meta, codexSessionId: sessionId, ...renderTimingFields(job.renderStartedAtMs) });+ // Cleaners run BEFORE the SSE complete + completed events so subscribers+ // see the cleaned bytes. codex output is the highest-value target for+ // C2PA stripping because gpt-image is the one provider that embeds+ // provenance metadata.+ await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath: outputPath, sidecarPath: sidecar, mode: IMAGE_GEN_MODE.CODEX });+ job.status = 'complete';+ if (activeProcs.get(jobId) === proc) activeProcs.delete(jobId);+ activeJobs.delete(jobId);+ console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (codex)`);+ const result = { filename, path: `/data/images/${filename}` };+ dispatchTerminalEvent(+ jobId,+ () => broadcastSse(job, { type: 'complete', result }),+ () => imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.CODEX, generationId: jobId, path: `/data/images/${filename}`, filename }),+ );+ closeJobAfterDelay(jobs, jobId);+ } catch (err) {+ await Promise.all([outputPath, join(PATHS.images, `${jobId}.metadata.json`)].map(path => unlinkGuarded(path).catch(() => {})));+ // force: true — 'complete' is already stamped above; see+ // createJobFailureFinalizer's doc comment in sseUtils.js.+ finalizeJobFailure(job, jobId, proc, `Codex post-exit handler failed: ${err?.message || err}`, { force: true });}- if (harvested.path) {- await copyFileGuarded(harvested.path, outputPath);- } else {- await atomicWrite(outputPath, harvested.buffer);- }- // Degenerate-frame gate (#4173) — before the sidecar, so a decodable but- // contentless canvas never becomes a gallery record.- const emptyFrame = await rejectDegenerateFrame(outputPath);- if (emptyFrame) {- return finalizeJobFailure(job, jobId, proc, emptyFrame);- }- // Sidecar metadata so the gallery can recover prompt/seed/etc. The- // codex sessionId is the closest analogue to a seed for gpt-image-2- // (which doesn't expose one) — uniquely identifies the run and is- // useful for traceability even though it doesn't reproduce the output.- const sidecar = join(PATHS.images, `${jobId}.metadata.json`);- // `job.renderStartedAtMs` is the queue-ingestion instant generateImage- // captured, so the spread measures the render itself — not the time the- // job spent queued behind other renders.- await atomicWrite(sidecar, { ...meta, codexSessionId: sessionId, ...renderTimingFields(job.renderStartedAtMs) }).catch(() => maintenance.markCurrentUnsettled());- // Cleaners run BEFORE the SSE complete + completed events so subscribers- // see the cleaned bytes. codex output is the highest-value target for- // C2PA stripping because gpt-image is the one provider that embeds- // provenance metadata.- await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath: outputPath, sidecarPath: sidecar, mode: IMAGE_GEN_MODE.CODEX });- job.status = 'complete';- if (activeProcs.get(jobId) === proc) activeProcs.delete(jobId);- activeJobs.delete(jobId);- console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (codex)`);- const result = { filename, path: `/data/images/${filename}` };- dispatchTerminalEvent(- jobId,- () => broadcastSse(job, { type: 'complete', result }),- () => imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.CODEX, generationId: jobId, path: `/data/images/${filename}`, filename }),- );- closeJobAfterDelay(jobs, jobId);- } catch (err) {- // force: true — 'complete' is already stamped above; see- // createJobFailureFinalizer's doc comment in sseUtils.js.- finalizeJobFailure(job, jobId, proc, `Codex post-exit handler failed: ${err?.message || err}`, { force: true });- }+ });});}diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.jsindex 3dadae2cb4..1a2ab7a1f4 100644--- a/server/services/imageGen/codex.test.js+++ b/server/services/imageGen/codex.test.js@@ -59,6 +59,7 @@ vi.mock('../../lib/fileUtils.js', async () => {// imageGenEvents is fine to import for real, but we don't want stray// listeners between tests. Reset its emitter state in beforeEach.+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');const codex = await import('./codex.js');const { imageGenEvents } = await import('../imageGenEvents.js');@@ -395,7 +396,12 @@ describe('codex provider — image harvest', () => {child.stderr.emit('data', Buffer.from(`session id: ${sessionId}\n`));// Then close cleanly.child.exitCode = 0;+ const releaseCut = await acquireBackupSnapshotCut();+ try {child.emit('close', 0, null);+ await new Promise(resolve => setImmediate(resolve));+ expect(existsSync(join(FAKE_IMAGES_DIR, job.filename)), 'provider completion must wait outside a held snapshot').toBe(false);+ } finally { releaseCut(); }// Poll until the completed event fires (the harvest is async).const deadline = Date.now() + 3000;diff --git a/server/services/imageGen/external.js b/server/services/imageGen/external.jsindex be667143d9..7390b13258 100644--- a/server/services/imageGen/external.js+++ b/server/services/imageGen/external.js@@ -1,3 +1,6 @@+import { publishImageFiles } from './publication.js';+import { rejectDegenerateFrame } from './frameGuard.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';/*** Image Gen — External provider.*@@ -153,19 +156,25 @@ export async function generateImage({ sdapiUrl, prompt, negativePrompt, width, hconst data = await res.json();if (!data.images?.length) throw new Error('SD API returned no images');- await ensureDir(PATHS.images);- const filename = `${randomUUID()}.png`;- const pngPath = join(PATHS.images, filename);- await atomicWrite(pngPath, Buffer.from(data.images[0], 'base64'));- // Auto-clean BEFORE the SSE complete fires so the URL the client opens- // serves the cleaned bytes. External mode has no sidecar — pass null so- // the helper just patches the PNG in place.- await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath, sidecarPath: null, mode: IMAGE_GEN_MODE.EXTERNAL });- const path = `/data/images/${filename}`;- console.log(`🖼️ Image saved: ${filename}`);- activeJob = null;- imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.EXTERNAL, generationId, path, filename });- return { generationId, filename, path, mode: IMAGE_GEN_MODE.EXTERNAL, model };+ return await withBackupAssetPublication(async () => {+ await ensureDir(PATHS.images);+ const filename = `${randomUUID()}.png`;+ const pngPath = join(PATHS.images, filename);+ return publishImageFiles([pngPath], async () => {+ await atomicWrite(pngPath, Buffer.from(data.images[0], 'base64'));+ const reason = await rejectDegenerateFrame(pngPath);+ if (reason) throw new ServerError(reason, { status: 502, code: 'DEGENERATE_FRAME' });+ // Auto-clean BEFORE the SSE complete fires so the URL the client opens+ // serves the cleaned bytes. External mode has no sidecar — pass null so+ // the helper just patches the PNG in place.+ await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath, sidecarPath: null, mode: IMAGE_GEN_MODE.EXTERNAL });+ const path = `/data/images/${filename}`;+ console.log(`🖼️ Image saved: ${filename}`);+ activeJob = null;+ imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.EXTERNAL, generationId, path, filename });+ return { generationId, filename, path, mode: IMAGE_GEN_MODE.EXTERNAL, model };+ });+ });} catch (err) {if (activeJob?.generationId === generationId) activeJob = null;imageGenEvents.emit('failed', {diff --git a/server/services/imageGen/external.test.js b/server/services/imageGen/external.test.jsindex fcc79116d6..2086d2f62e 100644--- a/server/services/imageGen/external.test.js+++ b/server/services/imageGen/external.test.js@@ -11,6 +11,7 @@ vi.mock('../../lib/fileUtils.js', () => ({atomicWrite: vi.fn(),PATHS: { images: '/tmp/portos-external-image-test' },}));+vi.mock('./frameGuard.js', () => ({ rejectDegenerateFrame: async () => null }));vi.mock('../../lib/imageClean.js', () => ({ autoCleanGeneratedImage: vi.fn() }));vi.mock('../imageGenEvents.js', () => ({ imageGenEvents }));diff --git a/server/services/imageGen/fal.js b/server/services/imageGen/fal.jsindex 9779846287..f5e398ea27 100644--- a/server/services/imageGen/fal.js+++ b/server/services/imageGen/fal.js@@ -1,4 +1,4 @@-import { maintenance } from '../../lib/maintenanceAdmission.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';/*** Image Gen — fal.ai queue REST API provider.*@@ -336,53 +336,62 @@ async function runFal(job, jobId, {});if (entry.aborted) return finalizeCanceled(job, jobId);- // Signature-sniff before anything reaches the gallery: an error page or- // truncated body must never be accepted as an image. The gallery serves- // by extension and sidecars assume PNG, so a JPEG/WebP result is- // transcoded rather than shipped mislabeled.- const format = detectImageFormat(bytes)?.format;- if (!format) return finalizeJobFailure(job, jobId, null, 'fal.ai returned a file that is not an image');- await atomicWrite(outputPath, format === 'png' ? bytes : await sharp(bytes).png().toBuffer());- wroteOutput = true;- if (entry.aborted) {- await unlinkGuarded(outputPath).catch(() => {});- return finalizeCanceled(job, jobId);- }-- // Degenerate-frame gate (#4173) — a moderated/blank result must fail- // here, not become a gallery record.- const emptyFrame = await rejectDegenerateFrame(outputPath);- if (emptyFrame) {- await unlinkGuarded(outputPath).catch(() => {});- return finalizeJobFailure(job, jobId, null, emptyFrame);- }-- const sidecar = join(PATHS.images, `${jobId}.metadata.json`);- const actualSeed = Number.isInteger(result?.seed) ? result.seed : (request.body.seed ?? null);- await atomicWrite(sidecar, {- ...meta,- ...(request.body.aspect_ratio ? { aspectRatio: request.body.aspect_ratio } : {}),- ...(request.resolution ? { resolution: request.resolution } : {}),- ...(actualSeed != null ? { seed: actualSeed } : {}),- // An ESTIMATE from the catalog's published prices — fal.ai bills the- // account; this only lets a gallery record say roughly what it cost.- estimatedCostUsd: request.estimatedCostUsd,- ...renderTimingFields(job.renderStartedAtMs),- }).catch(() => maintenance.markCurrentUnsettled());- // Cleaners run BEFORE the SSE complete + completed events so subscribers- // see the cleaned bytes.- await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath: outputPath, sidecarPath: sidecar, mode: MODE });- job.status = 'complete';- if (activeRequests.get(jobId) === entry) activeRequests.delete(jobId);- activeJobs.delete(jobId);- console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (fal ${request.endpointId}, ~$${request.estimatedCostUsd})`);- const done = { filename, path: `/data/images/${filename}` };- dispatchTerminalEvent(- jobId,- () => broadcastSse(job, { type: 'complete', result: done }),- () => imageGenEvents.emit('completed', { mode: MODE, generationId: jobId, path: done.path, filename }),- );- closeJobAfterDelay(jobs, jobId);+ await withBackupAssetPublication(async () => {+ try {+ // Signature-sniff before anything reaches the gallery: an error page or+ // truncated body must never be accepted as an image. The gallery serves+ // by extension and sidecars assume PNG, so a JPEG/WebP result is+ // transcoded rather than shipped mislabeled.+ const format = detectImageFormat(bytes)?.format;+ if (!format) return finalizeJobFailure(job, jobId, null, 'fal.ai returned a file that is not an image');+ await atomicWrite(outputPath, format === 'png' ? bytes : await sharp(bytes).png().toBuffer());+ wroteOutput = true;+ if (entry.aborted) {+ await unlinkGuarded(outputPath).catch(() => {});+ return finalizeCanceled(job, jobId);+ }++ // Degenerate-frame gate (#4173) — a moderated/blank result must fail+ // here, not become a gallery record.+ const emptyFrame = await rejectDegenerateFrame(outputPath);+ if (emptyFrame) {+ await unlinkGuarded(outputPath).catch(() => {});+ return finalizeJobFailure(job, jobId, null, emptyFrame);+ }++ const sidecar = join(PATHS.images, `${jobId}.metadata.json`);+ const actualSeed = Number.isInteger(result?.seed) ? result.seed : (request.body.seed ?? null);+ await atomicWrite(sidecar, {+ ...meta,+ ...(request.body.aspect_ratio ? { aspectRatio: request.body.aspect_ratio } : {}),+ ...(request.resolution ? { resolution: request.resolution } : {}),+ ...(actualSeed != null ? { seed: actualSeed } : {}),+ // An ESTIMATE from the catalog's published prices — fal.ai bills the+ // account; this only lets a gallery record say roughly what it cost.+ estimatedCostUsd: request.estimatedCostUsd,+ ...renderTimingFields(job.renderStartedAtMs),+ });+ // Cleaners run BEFORE the SSE complete + completed events so subscribers+ // see the cleaned bytes.+ await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath: outputPath, sidecarPath: sidecar, mode: MODE });+ job.status = 'complete';+ if (activeRequests.get(jobId) === entry) activeRequests.delete(jobId);+ activeJobs.delete(jobId);+ console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (fal ${request.endpointId}, ~$${request.estimatedCostUsd})`);+ const done = { filename, path: `/data/images/${filename}` };+ dispatchTerminalEvent(+ jobId,+ () => broadcastSse(job, { type: 'complete', result: done }),+ () => imageGenEvents.emit('completed', { mode: MODE, generationId: jobId, path: done.path, filename }),+ );+ closeJobAfterDelay(jobs, jobId);+ } catch (err) {+ if (wroteOutput && job.status !== 'complete') {+ await Promise.all([outputPath, join(PATHS.images, `${jobId}.metadata.json`)].map(path => unlinkGuarded(path).catch(() => {})));+ }+ throw err;+ }+ });} catch (err) {// An unanticipated throw (input encode, retrieval, transcode) may still// leave the remote request queued or running — cancel it. cancelFalRequest@@ -390,7 +399,6 @@ async function runFal(job, jobId, {// submitted. `force` because the success tail stamps 'complete' before its// last awaits.await cancelFalRequest(entry);- if (wroteOutput && job.status !== 'complete') await unlinkGuarded(outputPath).catch(() => {});if (entry.aborted) return finalizeCanceled(job, jobId);finalizeJobFailure(job, jobId, null, `fal.ai image generation failed: ${err?.message || err}`, { force: true });}diff --git a/server/services/imageGen/fal.test.js b/server/services/imageGen/fal.test.jsindex 2b1cea4ada..bd239bc918 100644--- a/server/services/imageGen/fal.test.js+++ b/server/services/imageGen/fal.test.js@@ -1,3 +1,4 @@+import { acquireBackupSnapshotCut } from '../../lib/backupSnapshotBoundary.js';import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { mkdir, rm, readFile, writeFile } from 'fs/promises';import { existsSync } from 'fs';@@ -102,12 +103,18 @@ describe('imageGen/fal — generateImage', () => {endpoint: 'fal-ai/nano-banana-2', output: await noiseImage(64, 36, 'jpeg'), result: { seed: 42 },});+ const releaseCut = await acquireBackupSnapshotCut();const job = await fal.generateImage({model: 'fal-ai/nano-banana-2', prompt: ' a neon harbour ', negativePrompt: 'blurry', width: 1920, height: 1080,});expect(job).toMatchObject({ mode: 'fal', status: 'running', filename: `${job.jobId}.png`, path: `/data/images/${job.jobId}.png` });expect(started).toHaveBeenCalledWith(expect.objectContaining({ generationId: job.jobId }));+ try {+ await vi.waitFor(() => expect(calls.some(call => call.url === CDN_URL)).toBe(true));+ await new Promise(resolve => setImmediate(resolve));+ expect(existsSync(join(FAKE_IMAGES_DIR, job.filename))).toBe(false);+ } finally { releaseCut(); }const event = await waitForTerminal(job.jobId);expect(event).toMatchObject({ type: 'completed', mode: 'fal', filename: `${job.jobId}.png` });diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.jsindex 2c32083f0a..8f87ccf8d7 100644--- a/server/services/imageGen/grok.js+++ b/server/services/imageGen/grok.js@@ -1,3 +1,4 @@+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Image Gen — xAI Grok Build CLI provider.@@ -371,80 +372,83 @@ async function runGrok(job, jobId, bin, args, {});proc.on('close', async (code, signal) => {- clearTimeout(timeoutTimer);- cleanupPromptFile();- // EventEmitter doesn't await async listeners — without this try/catch,- // a throw from the harvest/copy would surface as an unhandled rejection- // and the job would be stuck in 'running' forever with no SSE error.- try {- if (code !== 0 || processError) {- const reason = processError?.message || (signal ? `Killed by signal ${signal}` : `Exit code ${code}`);- const tail = stderrTail.trim().split('\n').slice(-6).join('\n');- removeScratch();- return finalizeJobFailure(job, jobId, proc, `Grok generation failed: ${reason}\n${tail}`);- }- // Grok writes the file during the turn; empirically it's on disk by- // exit, but poll a few seconds in case of flush lag on slow disks. The- // harvest signature-sniffs the bytes so a text error, truncated file,- // or non-image payload is never accepted into the gallery as a PNG.- const harvested = await harvestStagedImage(stagingPath, harvestTimeoutMs);- if (!harvested.found) {+ await withBackupAssetPublication(async () => {+ clearTimeout(timeoutTimer);+ cleanupPromptFile();+ // EventEmitter doesn't await async listeners — without this try/catch,+ // a throw from the harvest/copy would surface as an unhandled rejection+ // and the job would be stuck in 'running' forever with no SSE error.+ try {+ if (code !== 0 || processError) {+ const reason = processError?.message || (signal ? `Killed by signal ${signal}` : `Exit code ${code}`);+ const tail = stderrTail.trim().split('\n').slice(-6).join('\n');+ removeScratch();+ return finalizeJobFailure(job, jobId, proc, `Grok generation failed: ${reason}\n${tail}`);+ }+ // Grok writes the file during the turn; empirically it's on disk by+ // exit, but poll a few seconds in case of flush lag on slow disks. The+ // harvest signature-sniffs the bytes so a text error, truncated file,+ // or non-image payload is never accepted into the gallery as a PNG.+ const harvested = await harvestStagedImage(stagingPath, harvestTimeoutMs);+ if (!harvested.found) {+ removeScratch();+ const prefix = harvested.invalid ? 'Grok wrote a non-image file at the directed path. ' : '';+ return finalizeJobFailure(job, jobId, proc, `${prefix}${noImageReason(stdoutTail)}`);+ }+ // Image bytes are not proof the image tool made them — reject a picture+ // the agent drew with code (see fabricationGuard.js). The narration tail+ // rides along like every other failure path here: it carries WHY the tool+ // was skipped, which the quota card reads to spot a rate-limit block.+ const fabricated = await checkFabrication(scratchDir, toolName);+ if (fabricated) {+ removeScratch();+ return finalizeJobFailure(job, jobId, proc, `${fabricated} ${noImageReason(stdoutTail)}`);+ }+ if (harvested.format === 'png') {+ await copyFileGuarded(stagingPath, outputPath);+ await unlinkGuarded(stagingPath).catch(() => {});+ } else {+ // Grok wrote a real image but not a PNG (jpeg/webp/gif) despite the+ // prompt. The gallery serves by extension and sidecars assume PNG,+ // so transcode rather than shipping mislabeled bytes.+ const pngBytes = await sharp(stagingPath).png().toBuffer();+ await atomicWrite(outputPath, pngBytes);+ }removeScratch();- const prefix = harvested.invalid ? 'Grok wrote a non-image file at the directed path. ' : '';- return finalizeJobFailure(job, jobId, proc, `${prefix}${noImageReason(stdoutTail)}`);- }- // Image bytes are not proof the image tool made them — reject a picture- // the agent drew with code (see fabricationGuard.js). The narration tail- // rides along like every other failure path here: it carries WHY the tool- // was skipped, which the quota card reads to spot a rate-limit block.- const fabricated = await checkFabrication(scratchDir, toolName);- if (fabricated) {+ // Degenerate-frame gate (#4173) — a decline that still emitted a flat+ // canvas must fail here, not become a gallery record.+ const emptyFrame = await rejectDegenerateFrame(outputPath);+ if (emptyFrame) {+ return finalizeJobFailure(job, jobId, proc, emptyFrame);+ }+ // Sidecar metadata so the gallery can recover prompt/ratio/etc.+ const sidecar = join(PATHS.images, `${jobId}.metadata.json`);+ // `job.renderStartedAtMs` is the queue-ingestion instant generateImage+ // captured, so the spread measures the render itself — not the time the+ // job spent queued behind other renders.+ await atomicWrite(sidecar, { ...meta, ...renderTimingFields(job.renderStartedAtMs) });+ // Cleaners run BEFORE the SSE complete + completed events so+ // subscribers see the cleaned bytes.+ await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath: outputPath, sidecarPath: sidecar, mode: IMAGE_GEN_MODE.GROK });+ job.status = 'complete';+ if (activeProcs.get(jobId) === proc) activeProcs.delete(jobId);+ activeJobs.delete(jobId);+ console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (grok)`);+ const result = { filename, path: `/data/images/${filename}` };+ dispatchTerminalEvent(+ jobId,+ () => broadcastSse(job, { type: 'complete', result }),+ () => imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.GROK, generationId: jobId, path: `/data/images/${filename}`, filename }),+ );+ closeJobAfterDelay(jobs, jobId);+ } catch (err) {+ await Promise.all([outputPath, join(PATHS.images, `${jobId}.metadata.json`)].map(path => unlinkGuarded(path).catch(() => {})));removeScratch();- return finalizeJobFailure(job, jobId, proc, `${fabricated} ${noImageReason(stdoutTail)}`);- }- if (harvested.format === 'png') {- await copyFileGuarded(stagingPath, outputPath);- await unlinkGuarded(stagingPath).catch(() => {});- } else {- // Grok wrote a real image but not a PNG (jpeg/webp/gif) despite the- // prompt. The gallery serves by extension and sidecars assume PNG,- // so transcode rather than shipping mislabeled bytes.- const pngBytes = await sharp(stagingPath).png().toBuffer();- await atomicWrite(outputPath, pngBytes);+ // force: true — 'complete' is already stamped above; see+ // createJobFailureFinalizer's doc comment in sseUtils.js.+ finalizeJobFailure(job, jobId, proc, `Grok post-exit handler failed: ${err?.message || err}`, { force: true });}- removeScratch();- // Degenerate-frame gate (#4173) — a decline that still emitted a flat- // canvas must fail here, not become a gallery record.- const emptyFrame = await rejectDegenerateFrame(outputPath);- if (emptyFrame) {- return finalizeJobFailure(job, jobId, proc, emptyFrame);- }- // Sidecar metadata so the gallery can recover prompt/ratio/etc.- const sidecar = join(PATHS.images, `${jobId}.metadata.json`);- // `job.renderStartedAtMs` is the queue-ingestion instant generateImage- // captured, so the spread measures the render itself — not the time the- // job spent queued behind other renders.- await atomicWrite(sidecar, { ...meta, ...renderTimingFields(job.renderStartedAtMs) }).catch(() => maintenance.markCurrentUnsettled());- // Cleaners run BEFORE the SSE complete + completed events so- // subscribers see the cleaned bytes.- await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath: outputPath, sidecarPath: sidecar, mode: IMAGE_GEN_MODE.GROK });- job.status = 'complete';- if (activeProcs.get(jobId) === proc) activeProcs.delete(jobId);- activeJobs.delete(jobId);- console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (grok)`);- const result = { filename, path: `/data/images/${filename}` };- dispatchTerminalEvent(- jobId,- () => broadcastSse(job, { type: 'complete', result }),- () => imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.GROK, generationId: jobId, path: `/data/images/${filename}`, filename }),- );- closeJobAfterDelay(jobs, jobId);- } catch (err) {- removeScratch();- // force: true — 'complete' is already stamped above; see- // createJobFailureFinalizer's doc comment in sseUtils.js.- finalizeJobFailure(job, jobId, proc, `Grok post-exit handler failed: ${err?.message || err}`, { force: true });- }+ });});}diff --git a/server/services/imageGen/grok.test.js b/server/services/imageGen/grok.test.jsindex 605d4b287d..d3a40777af 100644--- a/server/services/imageGen/grok.test.js+++ b/server/services/imageGen/grok.test.js@@ -1,3 +1,4 @@+import { acquireBackupSnapshotCut } from '../../lib/backupSnapshotBoundary.js';import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { posixPath } from '../../lib/testHelper.js';@@ -279,7 +280,12 @@ describe('grok provider — directed-path harvest', () => {]);await mkdir(join(tmpdir(), `portos-grok-${job.jobId}`), { recursive: true });await writeFile(stagingPathFor(job.jobId), fakePngBytes);+ const releaseCut = await acquireBackupSnapshotCut();+ try {await closeChild(0, 0);+ await new Promise(resolve => setImmediate(resolve));+ expect(existsSync(join(FAKE_IMAGES_DIR, job.filename)), 'provider completion must wait outside a held snapshot').toBe(false);+ } finally { releaseCut(); }const deadline = Date.now() + 3000;while (Date.now() < deadline && completedListener.mock.calls.length === 0) {diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.jsindex 7580ad406a..b4685b5164 100644--- a/server/services/imageGen/index.js+++ b/server/services/imageGen/index.js@@ -1,3 +1,4 @@+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { maintenance } from '../../lib/maintenanceAdmission.js';import { randomUUID } from 'node:crypto';import { imageGenEvents } from '../imageGenEvents.js';@@ -218,11 +219,13 @@ async function generateAdmittedImage(params) {* event that create the gallery record.*/async function guardResolvedFrame(result) {- const pngPath = result?.outputPath- || (result?.filename && result?.path ? join(PATHS.images, result.filename) : null);- const reason = pngPath ? await rejectDegenerateFrame(pngPath) : null;- if (reason) throw new ServerError(reason, { status: 502, code: 'DEGENERATE_FRAME' });- return result;+ return withBackupAssetPublication(async () => {+ const pngPath = result?.outputPath+ || (result?.filename && result?.path ? join(PATHS.images, result.filename) : null);+ const reason = pngPath ? await rejectDegenerateFrame(pngPath) : null;+ if (reason) throw new ServerError(reason, { status: 502, code: 'DEGENERATE_FRAME' });+ return result;+ });}// Build the default avatar prompt for the human-centered Character surface (#2677).diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex cf8fa2d552..3042962ee6 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -935,258 +935,261 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =});proc.on('close', async (code, signal) => {- // Guard against the spawn-ENOENT path where 'error' already finalized- // the job. Node fires 'error' THEN 'close' (with code -2/null signal)- // for a missing binary, and re-running the failure path here would- // emit a second 'failed' event + second SSE error frame.- if (finalized) return;- finalized = true;- // Emit any final unterminated marker line each stream wrote without a- // trailing newline (a SIGKILL mid-write, or a progress bar whose last- // redraw never terminated) BEFORE nulling activeJob — handleLine's- // inference-progress branch mutates activeJob, so flushing first keeps a- // final progress line able to update it (mirrors videoGen's ordering).- stderrReader.flush();- stdoutReader.flush();- activeProcess = null;- activeJob = null;- void releaseHeavyClaim();- if (watcher) { try { watcher.close(); } catch { /* ignore */ } }- void removeStepwise();- // EventEmitter doesn't await async listeners — without this try/catch, a- // throw from any of the post-exit work below (rejectDegenerateFrame,- // sharp, atomicWrite, autoCleanGeneratedImage) would surface as an- // unhandled rejection (process-killing on Node >= 15), leave the job- // stuck in 'running' forever, and hang any connected SSE client with no- // terminal frame. Mirrors codex.js / grok.js's finalizeJobFailure.- // `terminalEmitted` is set right before each branch's `broadcastSse` call- // — i.e. once we've committed to a terminal outcome and are about to tell- // consumers about it, not after. That ordering matters: it's set BEFORE- // the SSE frame goes out, not after imageGenEvents.emit(), so a listener- // that itself throws while handling one of these events can't cause the- // catch below to retry the very emit that just threw. It's also checked- // in the catch so a throw AFTER a terminal event was already dispatched- // (e.g. autoCleanGeneratedImage failing once job.status is already- // 'complete') logs the secondary failure without re-emitting a- // contradictory terminal frame or downgrading a delivered 'complete'.- let terminalEmitted = false;- try {- // Degenerate-frame gate (#4173): a runner can exit 0 having written a PNG- // that decodes fine and holds no content (a solid-black frame from a run- // that produced nothing). Fail the job instead of saving a black tile —- // the file is removed so no gallery scan can pick it up. An unmeasurable- // frame yields no reason and falls through to the normal success path.- const emptyFrame = code === 0 ? await rejectDegenerateFrame(outputPath) : null;- if (emptyFrame) {- job.status = 'error';- job.error = emptyFrame;- console.error(`❌ Image generation failed [${jobId.slice(0, 8)}]: ${emptyFrame}`);- terminalEmitted = true;- dispatchTerminalEvent(- jobId,- () => broadcastSse(job, { type: 'error', error: emptyFrame }),- () => imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: emptyFrame }),- );- return;- }- if (code !== 0 || processError) {- job.status = 'error';- const reason = processError?.message || (signal ? `Killed by signal ${signal}` : `Exit code ${code}`);- // Extract a structured user-error if the runner emitted one- // (USER_ERROR:gated_repo:black-forest-labs/FLUX.2-klein-9B), and find- // the matching `❌ …` prose line that follows it. Fall back to the last- // 10 stderr lines if no structured error was emitted (unknown crash).- const lines = stderrBuffer.split('\n').map((l) => l.trim()).filter(Boolean);- const structIdx = lines.findIndex((l) => l.startsWith('USER_ERROR:'));- let userMessage = null;- let userKind = null;- let userRepo = null;- if (structIdx >= 0) {- // Split with limit=2 so a kind containing colons can't shred the repo.- const [kind, ...rest] = lines[structIdx].slice('USER_ERROR:'.length).split(':');- userKind = kind;- userRepo = rest.join(':') || null;- const proseIdx = lines.findIndex((l, i) => i > structIdx && l.startsWith('❌'));- userMessage = proseIdx >= 0 ? lines[proseIdx].replace(/^❌\s*/, '') : null;+ await withBackupAssetPublication(async () => {+ // Guard against the spawn-ENOENT path where 'error' already finalized+ // the job. Node fires 'error' THEN 'close' (with code -2/null signal)+ // for a missing binary, and re-running the failure path here would+ // emit a second 'failed' event + second SSE error frame.+ if (finalized) return;+ finalized = true;+ // Emit any final unterminated marker line each stream wrote without a+ // trailing newline (a SIGKILL mid-write, or a progress bar whose last+ // redraw never terminated) BEFORE nulling activeJob — handleLine's+ // inference-progress branch mutates activeJob, so flushing first keeps a+ // final progress line able to update it (mirrors videoGen's ordering).+ stderrReader.flush();+ stdoutReader.flush();+ activeProcess = null;+ activeJob = null;+ void releaseHeavyClaim();+ if (watcher) { try { watcher.close(); } catch { /* ignore */ } }+ void removeStepwise();+ // EventEmitter doesn't await async listeners — without this try/catch, a+ // throw from any of the post-exit work below (rejectDegenerateFrame,+ // sharp, atomicWrite, autoCleanGeneratedImage) would surface as an+ // unhandled rejection (process-killing on Node >= 15), leave the job+ // stuck in 'running' forever, and hang any connected SSE client with no+ // terminal frame. Mirrors codex.js / grok.js's finalizeJobFailure.+ // `terminalEmitted` is set right before each branch's `broadcastSse` call+ // — i.e. once we've committed to a terminal outcome and are about to tell+ // consumers about it, not after. That ordering matters: it's set BEFORE+ // the SSE frame goes out, not after imageGenEvents.emit(), so a listener+ // that itself throws while handling one of these events can't cause the+ // catch below to retry the very emit that just threw. It's also checked+ // in the catch so a throw AFTER a terminal event was already dispatched+ // (e.g. autoCleanGeneratedImage failing once job.status is already+ // 'complete') logs the secondary failure without re-emitting a+ // contradictory terminal frame or downgrading a delivered 'complete'.+ let terminalEmitted = false;+ try {+ // Degenerate-frame gate (#4173): a runner can exit 0 having written a PNG+ // that decodes fine and holds no content (a solid-black frame from a run+ // that produced nothing). Fail the job instead of saving a black tile —+ // the file is removed so no gallery scan can pick it up. An unmeasurable+ // frame yields no reason and falls through to the normal success path.+ const emptyFrame = code === 0 ? await rejectDegenerateFrame(outputPath) : null;+ if (emptyFrame) {+ job.status = 'error';+ job.error = emptyFrame;+ console.error(`❌ Image generation failed [${jobId.slice(0, 8)}]: ${emptyFrame}`);+ terminalEmitted = true;+ dispatchTerminalEvent(+ jobId,+ () => broadcastSse(job, { type: 'error', error: emptyFrame }),+ () => imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: emptyFrame }),+ );+ return;}- // Heuristic detection for non-USER_ERROR failures we can still- // surface actionably. mflux's entry-point shim breaks when a partial- // package upgrade leaves user-site at the right version number but- // with stale file layout — Python imports the wrong `mflux/` first.- // Easier to spot at the source than to teach the user to read pip diffs.- if (!userMessage) {- const mfluxBroken = lines.some((l) => /ModuleNotFoundError: No module named 'mflux\.models\.flux\.cli'/.test(l));- if (mfluxBroken) {- userKind = 'mflux_install_corrupted';- userMessage = 'Your mflux install is corrupted (entry-point shim and package layout out of sync). Repair with: `pip uninstall -y mflux && pip install --user --force-reinstall --no-cache-dir --no-deps mflux`. If you use conda, run the same in your conda env\'s pip.';+ if (code !== 0 || processError) {+ job.status = 'error';+ const reason = processError?.message || (signal ? `Killed by signal ${signal}` : `Exit code ${code}`);+ // Extract a structured user-error if the runner emitted one+ // (USER_ERROR:gated_repo:black-forest-labs/FLUX.2-klein-9B), and find+ // the matching `❌ …` prose line that follows it. Fall back to the last+ // 10 stderr lines if no structured error was emitted (unknown crash).+ const lines = stderrBuffer.split('\n').map((l) => l.trim()).filter(Boolean);+ const structIdx = lines.findIndex((l) => l.startsWith('USER_ERROR:'));+ let userMessage = null;+ let userKind = null;+ let userRepo = null;+ if (structIdx >= 0) {+ // Split with limit=2 so a kind containing colons can't shred the repo.+ const [kind, ...rest] = lines[structIdx].slice('USER_ERROR:'.length).split(':');+ userKind = kind;+ userRepo = rest.join(':') || null;+ const proseIdx = lines.findIndex((l, i) => i > structIdx && l.startsWith('❌'));+ userMessage = proseIdx >= 0 ? lines[proseIdx].replace(/^❌\s*/, '') : null;}- }- // The precheck passed (or its memoized "healthy" answer is now stale) and- // the runtime still failed to import. Bust the health cache so the next- // status poll reports the truth instead of the cached pass, and name the- // same one-button remedy rather than leaving the caller with "Exit code 1".- if (userKind === 'torch_runtime_broken') invalidateFlux2Health();- if (!userMessage && usesTorchVenv(model)) {- const importBroken = lines.some((l) => /^(ModuleNotFoundError|ImportError)\b/.test(l) || /cannot import name /.test(l));- if (importBroken) {- invalidateFlux2Health();- userKind = 'torch_runtime_broken';- userMessage = `The shared torch image runtime at ${FLUX2_VENV_DEFAULT} could not import its packages. Reinstall it from Settings › Image Gen › Local, then retry this render.`;+ // Heuristic detection for non-USER_ERROR failures we can still+ // surface actionably. mflux's entry-point shim breaks when a partial+ // package upgrade leaves user-site at the right version number but+ // with stale file layout — Python imports the wrong `mflux/` first.+ // Easier to spot at the source than to teach the user to read pip diffs.+ if (!userMessage) {+ const mfluxBroken = lines.some((l) => /ModuleNotFoundError: No module named 'mflux\.models\.flux\.cli'/.test(l));+ if (mfluxBroken) {+ userKind = 'mflux_install_corrupted';+ userMessage = 'Your mflux install is corrupted (entry-point shim and package layout out of sync). Repair with: `pip uninstall -y mflux && pip install --user --force-reinstall --no-cache-dir --no-deps mflux`. If you use conda, run the same in your conda env\'s pip.';+ }}- }- // Legacy mflux-generate is a pre-built binary, so it doesn't emit the- // structured USER_ERROR markers the flux2/z-image Python runners use.- // Match the raw huggingface_hub stack instead — `GatedRepoError` or the- // "Cannot access gated repo for url …/<owner>/<name>/…" prose. Extract- // the repo so the UI banner can link the user straight to the license- // page (and we set kind=gated_repo so the client knows to surface the- // token-entry form).- if (!userMessage) {- const gatedText = lines.join('\n');- // Classify as gated ONLY on a gated-specific signal — extractGatedRepo- // matches any huggingface.co/<owner>/<repo> URL, so a non-gated failure- // (404, network error) that merely prints a HF URL must NOT be turned- // into a misleading license-request flow. Extract the repo for the link- // only after the gated signal is confirmed.- const hasGatedError = isGatedRepoError(gatedText);- if (hasGatedError) {- userKind = 'gated_repo';- userRepo = extractGatedRepo(gatedText);- const repoText = userRepo || 'the model';- userMessage = `Access to ${repoText} is gated. Accept the license at https://huggingface.co/${userRepo || '<repo>'} and paste your HuggingFace token into Image Gen settings, then retry.`;+ // The precheck passed (or its memoized "healthy" answer is now stale) and+ // the runtime still failed to import. Bust the health cache so the next+ // status poll reports the truth instead of the cached pass, and name the+ // same one-button remedy rather than leaving the caller with "Exit code 1".+ if (userKind === 'torch_runtime_broken') invalidateFlux2Health();+ if (!userMessage && usesTorchVenv(model)) {+ const importBroken = lines.some((l) => /^(ModuleNotFoundError|ImportError)\b/.test(l) || /cannot import name /.test(l));+ if (importBroken) {+ invalidateFlux2Health();+ userKind = 'torch_runtime_broken';+ userMessage = `The shared torch image runtime at ${FLUX2_VENV_DEFAULT} could not import its packages. Reinstall it from Settings › Image Gen › Local, then retry this render.`;+ }}- }- const tail = lines.slice(-10).join('\n');- const errorText = userMessage- ? `${userMessage}\n\n(diagnostic) ${reason}`- : `Generation failed: ${reason}\n${tail}`;- console.error(`❌ Image generation failed [${jobId.slice(0, 8)}]: ${userMessage || reason}`);- job.error = userMessage || errorText;- job.errorKind = userKind;- job.errorRepo = userRepo;- terminalEmitted = true;- // Propagate the friendly message (not the raw "Exit code 1") to the- // job queue so its `failed` log line and future SSE replays carry it.- dispatchTerminalEvent(- jobId,- () => broadcastSse(job, { type: 'error', error: errorText, kind: userKind, repo: userRepo }),- () => imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: job.error }),- );- } else {- job.status = 'complete';- // Large-source regen (issue #912): the render ran at a clamped FLUX-sane- // resolution. Upscale the result back to the requested delivery size so- // the watermark-free copy matches the original's resolution. `meta.width/- // height` currently hold the render dims; record those as render* and- // promote the delivered dims so the gallery shows the real file size.- const targetW = Math.round(Number(upscaleTo?.width));- const targetH = Math.round(Number(upscaleTo?.height));- if (targetW > 0 && targetH > 0 && (targetW !== meta.width || targetH !== meta.height)) {- const resized = await sharp(outputPath)- .resize(targetW, targetH, { fit: 'fill', kernel: 'lanczos3' })- // compressionLevel 6 (sharp default) — near-identical size to 9 but- // markedly faster, and this re-encode is on the render-completion path.- .png({ compressionLevel: 6 })- .toBuffer()- .catch((err) => { console.warn(`⚠️ Regen upscale failed for ${filename}: ${err?.message || err}`); return null; });- if (resized) {- await atomicWrite(outputPath, resized).catch(() => maintenance.markCurrentUnsettled());- meta.renderWidth = meta.width;- meta.renderHeight = meta.height;- meta.width = targetW;- meta.height = targetH;- console.log(`🔍 Upscaled regen [${jobId.slice(0, 8)}] ${meta.renderWidth}x${meta.renderHeight} → ${targetW}x${targetH}`);+ // Legacy mflux-generate is a pre-built binary, so it doesn't emit the+ // structured USER_ERROR markers the flux2/z-image Python runners use.+ // Match the raw huggingface_hub stack instead — `GatedRepoError` or the+ // "Cannot access gated repo for url …/<owner>/<name>/…" prose. Extract+ // the repo so the UI banner can link the user straight to the license+ // page (and we set kind=gated_repo so the client knows to surface the+ // token-entry form).+ if (!userMessage) {+ const gatedText = lines.join('\n');+ // Classify as gated ONLY on a gated-specific signal — extractGatedRepo+ // matches any huggingface.co/<owner>/<repo> URL, so a non-gated failure+ // (404, network error) that merely prints a HF URL must NOT be turned+ // into a misleading license-request flow. Extract the repo for the link+ // only after the gated signal is confirmed.+ const hasGatedError = isGatedRepoError(gatedText);+ if (hasGatedError) {+ userKind = 'gated_repo';+ userRepo = extractGatedRepo(gatedText);+ const repoText = userRepo || 'the model';+ userMessage = `Access to ${repoText} is gated. Accept the license at https://huggingface.co/${userRepo || '<repo>'} and paste your HuggingFace token into Image Gen settings, then retry.`;+ }}- }- // Regen fidelity (issue #912): for a regen pass, measure how much the- // delivered image actually changed vs. the source so the sidecar records- // the *realized* delta, not just the requested strength. Catches the- // mflux strength-0.0 footgun, silent txt2img fallbacks, and over-mutation.- // Best-effort — a decode failure just skips the stamp.- if (regenOf && validInitImagePath) {- const delta = await import('./regen.js')- .then(({ computePixelDelta }) => computePixelDelta(validInitImagePath, outputPath))- .catch(() => null);- if (delta) {- meta.regenPixelDeltaPct = delta.pixelDeltaPct;- meta.regenPsnr = delta.psnr;- console.log(`📐 Regen fidelity [${jobId.slice(0, 8)}]: ${delta.pixelDeltaPct}% changed, PSNR ${delta.psnr}dB`);+ const tail = lines.slice(-10).join('\n');+ const errorText = userMessage+ ? `${userMessage}\n\n(diagnostic) ${reason}`+ : `Generation failed: ${reason}\n${tail}`;+ console.error(`❌ Image generation failed [${jobId.slice(0, 8)}]: ${userMessage || reason}`);+ job.error = userMessage || errorText;+ job.errorKind = userKind;+ job.errorRepo = userRepo;+ terminalEmitted = true;+ // Propagate the friendly message (not the raw "Exit code 1") to the+ // job queue so its `failed` log line and future SSE replays carry it.+ dispatchTerminalEvent(+ jobId,+ () => broadcastSse(job, { type: 'error', error: errorText, kind: userKind, repo: userRepo }),+ () => imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: job.error }),+ );+ } else {+ job.status = 'complete';+ // Large-source regen (issue #912): the render ran at a clamped FLUX-sane+ // resolution. Upscale the result back to the requested delivery size so+ // the watermark-free copy matches the original's resolution. `meta.width/+ // height` currently hold the render dims; record those as render* and+ // promote the delivered dims so the gallery shows the real file size.+ const targetW = Math.round(Number(upscaleTo?.width));+ const targetH = Math.round(Number(upscaleTo?.height));+ if (targetW > 0 && targetH > 0 && (targetW !== meta.width || targetH !== meta.height)) {+ const resized = await sharp(outputPath)+ .resize(targetW, targetH, { fit: 'fill', kernel: 'lanczos3' })+ // compressionLevel 6 (sharp default) — near-identical size to 9 but+ // markedly faster, and this re-encode is on the render-completion path.+ .png({ compressionLevel: 6 })+ .toBuffer()+ .catch((err) => { console.warn(`⚠️ Regen upscale failed for ${filename}: ${err?.message || err}`); return null; });+ if (resized) {+ await atomicWrite(outputPath, resized);+ meta.renderWidth = meta.width;+ meta.renderHeight = meta.height;+ meta.width = targetW;+ meta.height = targetH;+ console.log(`🔍 Upscaled regen [${jobId.slice(0, 8)}] ${meta.renderWidth}x${meta.renderHeight} → ${targetW}x${targetH}`);+ }}+ // Regen fidelity (issue #912): for a regen pass, measure how much the+ // delivered image actually changed vs. the source so the sidecar records+ // the *realized* delta, not just the requested strength. Catches the+ // mflux strength-0.0 footgun, silent txt2img fallbacks, and over-mutation.+ // Best-effort — a decode failure just skips the stamp.+ if (regenOf && validInitImagePath) {+ const delta = await import('./regen.js')+ .then(({ computePixelDelta }) => computePixelDelta(validInitImagePath, outputPath))+ .catch(() => null);+ if (delta) {+ meta.regenPixelDeltaPct = delta.pixelDeltaPct;+ meta.regenPsnr = delta.psnr;+ console.log(`📐 Regen fidelity [${jobId.slice(0, 8)}]: ${delta.pixelDeltaPct}% changed, PSNR ${delta.psnr}dB`);+ }+ }+ // Sidecar: persist a metadata record next to the PNG so the gallery+ // and Remix flow can recover prompt/seed/steps even if mflux's own+ // --metadata sidecar lives at a slightly different filename shape.+ // A non-gallery target (issue #2264, the Image Cleaner's temp render)+ // skips this write entirely — the temp bytes are consumed by an explicit+ // result-fetch, so there's no gallery record to hydrate.+ const sidecar = join(outputDir, `${jobId}.metadata.json`);+ if (!skipSidecar) {+ // Render timing is stamped onto `meta` (not spread at the write) so the+ // sidecar and the `autoCleanGeneratedImage` rewrite below agree on it.+ Object.assign(meta, renderTimingFields(job.renderStartedAtMs));+ await atomicWrite(sidecar, meta);+ // Cleaners run BEFORE the SSE complete + completed events so subscribers+ // see the cleaned bytes. Local FLUX renders never carry C2PA chunks so+ // cleanC2PA is a no-op on local — denoise is the only mode that does+ // anything here. A throw here (or from the rest of this branch) is+ // caught below, before any terminal event has gone out for this job.+ await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath: outputPath, sidecarPath: sidecar, mode: IMAGE_GEN_MODE.LOCAL });+ }+ console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename}${skipSidecar ? ' (temp, no sidecar)' : ''}`);+ // A non-gallery render has no `/data/images` mount — carry the absolute+ // `outputPath` so the queue/route can read the finished bytes; `path`+ // stays null so nothing treats it as a gallery URL.+ const result = { filename, seed: actualSeed, path: publicPath, outputPath, ...(meta.executionProvenance ? { executionProvenance: meta.executionProvenance } : {}) };+ terminalEmitted = true;+ // Include `seed` so /sdapi/v1/txt2img can surface the actual seed used+ // (mflux generates a random one if the client didn't pass one). Emit the+ // gallery `completed` (which drives the media-asset index + peer-sync+ // hooks) ONLY for a gallery target — a temp render must not be indexed or+ // federated. The queue's own `completed` handler still fires off the+ // return value below, so the job settles either way.+ dispatchTerminalEvent(+ jobId,+ () => broadcastSse(job, { type: 'complete', result }),+ () => {+ if (!skipSidecar) {+ imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, path: publicPath, filename, seed: actualSeed, ...(meta.executionProvenance ? { executionProvenance: meta.executionProvenance } : {}) });+ } else {+ // `temp: true` tells the media-asset-index + peer-sync hooks to+ // ignore this render — there's no gallery file or sidecar to+ // index/federate.+ imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, path: null, filename, seed: actualSeed, outputPath, temp: true, ...(meta.executionProvenance ? { executionProvenance: meta.executionProvenance } : {}) });+ }+ },+ );}- // Sidecar: persist a metadata record next to the PNG so the gallery- // and Remix flow can recover prompt/seed/steps even if mflux's own- // --metadata sidecar lives at a slightly different filename shape.- // A non-gallery target (issue #2264, the Image Cleaner's temp render)- // skips this write entirely — the temp bytes are consumed by an explicit- // result-fetch, so there's no gallery record to hydrate.- const sidecar = join(outputDir, `${jobId}.metadata.json`);- if (!skipSidecar) {- // Render timing is stamped onto `meta` (not spread at the write) so the- // sidecar and the `autoCleanGeneratedImage` rewrite below agree on it.- Object.assign(meta, renderTimingFields(job.renderStartedAtMs));- await atomicWrite(sidecar, meta).catch(() => maintenance.markCurrentUnsettled());- // Cleaners run BEFORE the SSE complete + completed events so subscribers- // see the cleaned bytes. Local FLUX renders never carry C2PA chunks so- // cleanC2PA is a no-op on local — denoise is the only mode that does- // anything here. A throw here (or from the rest of this branch) is- // caught below, before any terminal event has gone out for this job.- await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath: outputPath, sidecarPath: sidecar, mode: IMAGE_GEN_MODE.LOCAL });+ } catch (err) {+ const reason = err?.message || String(err);+ console.error(`❌ Image generation post-exit handler failed [${jobId.slice(0, 8)}]: ${reason}`);+ // `terminalEmitted` is already true here only when the throw came from+ // dispatching a terminal event itself (a downstream broadcastSse/+ // imageGenEvents listener throwing) — that event already reached+ // consumers, so don't downgrade a delivered outcome (e.g. a 'complete'+ // frame the client already saw) to 'error', and don't retry the same+ // emit that just threw.+ if (!terminalEmitted) {+ await Promise.all([outputPath, join(outputDir, `${jobId}.metadata.json`)].map(path => unlinkGuarded(path).catch(() => {})));+ job.status = 'error';+ job.error = reason;+ // `dispatchTerminalEvent` guards each call independently — a throwing+ // SSE writer (a dead client's `res.write`) can't suppress the+ // `imageGenEvents.emit` (or vice versa), and neither can re-throw out+ // of this catch, which would escape the close handler as an+ // unhandled rejection. job.status/job.error above are already correct+ // even if delivery fails partway, and `finally` below still runs the+ // job cleanup.+ dispatchTerminalEvent(+ jobId,+ () => broadcastSse(job, { type: 'error', error: reason }),+ () => imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: reason }),+ );}- console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename}${skipSidecar ? ' (temp, no sidecar)' : ''}`);- // A non-gallery render has no `/data/images` mount — carry the absolute- // `outputPath` so the queue/route can read the finished bytes; `path`- // stays null so nothing treats it as a gallery URL.- const result = { filename, seed: actualSeed, path: publicPath, outputPath, ...(meta.executionProvenance ? { executionProvenance: meta.executionProvenance } : {}) };- terminalEmitted = true;- // Include `seed` so /sdapi/v1/txt2img can surface the actual seed used- // (mflux generates a random one if the client didn't pass one). Emit the- // gallery `completed` (which drives the media-asset index + peer-sync- // hooks) ONLY for a gallery target — a temp render must not be indexed or- // federated. The queue's own `completed` handler still fires off the- // return value below, so the job settles either way.- dispatchTerminalEvent(- jobId,- () => broadcastSse(job, { type: 'complete', result }),- () => {- if (!skipSidecar) {- imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, path: publicPath, filename, seed: actualSeed, ...(meta.executionProvenance ? { executionProvenance: meta.executionProvenance } : {}) });- } else {- // `temp: true` tells the media-asset-index + peer-sync hooks to- // ignore this render — there's no gallery file or sidecar to- // index/federate.- imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, path: null, filename, seed: actualSeed, outputPath, temp: true, ...(meta.executionProvenance ? { executionProvenance: meta.executionProvenance } : {}) });- }- },- );- }- } catch (err) {- const reason = err?.message || String(err);- console.error(`❌ Image generation post-exit handler failed [${jobId.slice(0, 8)}]: ${reason}`);- // `terminalEmitted` is already true here only when the throw came from- // dispatching a terminal event itself (a downstream broadcastSse/- // imageGenEvents listener throwing) — that event already reached- // consumers, so don't downgrade a delivered outcome (e.g. a 'complete'- // frame the client already saw) to 'error', and don't retry the same- // emit that just threw.- if (!terminalEmitted) {- job.status = 'error';- job.error = reason;- // `dispatchTerminalEvent` guards each call independently — a throwing- // SSE writer (a dead client's `res.write`) can't suppress the- // `imageGenEvents.emit` (or vice versa), and neither can re-throw out- // of this catch, which would escape the close handler as an- // unhandled rejection. job.status/job.error above are already correct- // even if delivery fails partway, and `finally` below still runs the- // job cleanup.- dispatchTerminalEvent(- jobId,- () => broadcastSse(job, { type: 'error', error: reason }),- () => imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: reason }),- );+ } finally {+ closeJobAfterDelay(jobs, jobId);}- } finally {- closeJobAfterDelay(jobs, jobId);- }+ });});return { jobId, filename, path: `/data/images/${filename}`, generationId: jobId, mode: IMAGE_GEN_MODE.LOCAL, model: modelId, seed: actualSeed };diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.jsindex 15d65e48de..6741686173 100644--- a/server/services/imageGen/local.test.js+++ b/server/services/imageGen/local.test.js@@ -1,9 +1,12 @@import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest';-import { mkdtempSync, rmSync } from 'fs';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';import { EventEmitter } from 'node:events';+// These lifecycle tests drive the child directly; preview watchers are unrelated.+vi.mock('fs', async original => ({ ...await original(), watch: vi.fn(() => ({ close() {} })) }));+const mockSpawn = vi.fn();vi.mock('../../lib/childProcess.js', async (original) => ({ ...await original(), spawn: (...args) => mockSpawn(...args) }));vi.mock('../../lib/heavyJobClaim.js', () => ({ claimHeavyLocalJob: async () => ({ ok: true, release: async () => {} }) }));@@ -52,6 +55,8 @@ beforeAll(async () => {vi.resetModules();({ buildArgs, buildSidecarMeta, resolveOutputPlacement, parseImageExecutionMarker, generateImage } = await import('./local.js'));({ PATHS } = await import('../../lib/fileUtils.js'));+ PATHS.images = join(tmpRegistryDir, 'images');+ mkdirSync(PATHS.images);});describe('imageGen local.parseImageExecutionMarker', () => {@@ -1197,3 +1202,41 @@ describe('local render terminal dispatch — SSE/lifecycle decoupling (#8915)',errSpy.mockRestore();});});+++it('drains a snapshot through local upscale and the sidecar naming the delivered dimensions', async () => {+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');+ mockIsFlux2VenvHealthy.mockResolvedValue(true);+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ mockSpawn.mockReturnValue(child);+ const { default: sharp } = await import('sharp');+ const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');+ const { imageGenEvents } = await import('../imageGenEvents.js');+ let reachedFrame;+ const reached = new Promise(resolve => { reachedFrame = resolve; });+ let finishFrame;+ const frame = new Promise(resolve => { finishFrame = resolve; });+ mockRejectDegenerateFrame.mockImplementationOnce(async () => { reachedFrame(); await frame; return null; });+ const job = await generateImage({ modelId: 'qwen-image-2.1', prompt: 'example', width: 64, height: 64,+ upscaleTo: { width: 128, height: 128 } });+ const pixels = await sharp({ create: { width: 64, height: 64, channels: 3, background: '#123456' } }).png().toBuffer();+ writeFileSync(join(PATHS.images, job.filename), pixels);+ const completed = new Promise(resolve => imageGenEvents.once('completed', resolve));+ child.emit('close', 0);+ await reached;+ let cutReady = false;+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });+ try {+ await new Promise(resolve => setImmediate(resolve));+ expect(cutReady, 'snapshot must drain the upscale and metadata tail').toBe(false);+ } finally { finishFrame(); }+ await completed;+ const release = await cut;+ try {+ expect(await sharp(join(PATHS.images, job.filename)).metadata()).toMatchObject({ width: 128, height: 128 });+ expect(JSON.parse(readFileSync(join(PATHS.images, `${job.jobId}.metadata.json`), 'utf8')))+ .toMatchObject({ width: 128, height: 128, renderWidth: 64, renderHeight: 64 });+ } finally { release(); }+});diff --git a/server/services/imageGen/publication.js b/server/services/imageGen/publication.jsnew file mode 100644index 0000000000..a8786afce6--- /dev/null+++ b/server/services/imageGen/publication.js@@ -0,0 +1,27 @@+import { readFile } from 'node:fs/promises';+import { atomicWrite, unlinkGuarded } from '../../lib/fileCore.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';+import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';++const publications = createKeyCachedQueue();++/** Replace an image/sketch pair together, restoring its previous bytes on failure. */+export function publishImageFiles(paths, work) {+ return withBackupAssetPublication(() => publications(paths[0], async () => {+ const previous = await Promise.all(paths.map(path => readFile(path).catch(error => {+ if (error.code === 'ENOENT') return null;+ throw error;+ })));+ try {+ return await work();+ } catch (error) {+ // Wait for every rollback before releasing admission, including a failed one.+ const restored = await Promise.allSettled(paths.map((path, i) => previous[i] === null+ ? unlinkGuarded(path).catch(err => { if (err.code !== 'ENOENT') throw err; })+ : atomicWrite(path, previous[i])));+ const failures = restored.filter(result => result.status === 'rejected').map(result => result.reason);+ if (failures.length) throw new AggregateError([error, ...failures], 'Image publication and rollback failed');+ throw error;+ }+ }));+}diff --git a/server/services/imageGen/remote.js b/server/services/imageGen/remote.jsindex 3ad9f49704..474a2c7dad 100644--- a/server/services/imageGen/remote.js+++ b/server/services/imageGen/remote.js@@ -1,3 +1,5 @@+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';+import { publishImageFiles } from './publication.js';/*** Durable consumer-side adapter for federated image jobs.*@@ -66,6 +68,7 @@ const executor = createRemoteMediaExecutor({// filename is the same shape imageGen/local.js uses, which is what lets the// gallery, the media index, and the provider-side result guard all agree.resolveDestination: ({ jobId }) => ({ dir: PATHS.images, filename: `${jobId}.png` }),+ publishResult: (work, { path, dir, jobId }) => withBackupAssetPublication(() => publishImageFiles([path, join(dir, `${jobId}.metadata.json`)], work)),async finalize({ jobId, dir, filename, request, remoteJob, peerId, renderStartedAtMs }) {// Honest sidecar: only fields this render actually had. Seed is the// requested one (wire-v1 results carry no rendered seed), so a render thatdiff --git a/server/services/imageGen/variants.js b/server/services/imageGen/variants.jsindex 8616ebcf55..a6531f9a62 100644--- a/server/services/imageGen/variants.js+++ b/server/services/imageGen/variants.js@@ -1,3 +1,5 @@+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';+import { publishImageFiles } from './publication.js';/*** Image variant helpers — shared logic for the three synchronous variant* endpoints: clean, remove-watermark, and light-regen.@@ -7,7 +9,7 @@* and returns a gallery-compatible response object. The three operations share* an identical persist-variant tail:*- * await Promise.all([writeFile(outPath, data), writeFile(sidecarPath, …)])+ * await atomicWrite(outPath, data); await atomicWrite(sidecarPath, …)* const filed = await autoFileCleanedToSourceCollections(src, out)* console.log(…)* return { …variantMeta, filename, path, width, height, … }@@ -98,32 +100,32 @@ export async function persistVariant({// current and future caller.const untimedVariantMeta = omitRenderTiming(variantMeta);- await Promise.all([- atomicWrite(outPath, data),- atomicWrite(sidecarPath, untimedVariantMeta),- ]);+ return withBackupAssetPublication(() => publishImageFiles([outPath, sidecarPath], async () => {+ await atomicWrite(outPath, data);+ await atomicWrite(sidecarPath, untimedVariantMeta);- await import('../mediaAssetIndex/index.js')- .then(m => m.indexImage({ filename: outFilename }))- .catch(err => console.error(`❌ Media index variant refresh failed: ${err.message}`));+ await import('../mediaAssetIndex/index.js')+ .then(m => m.indexImage({ filename: outFilename }))+ .catch(err => console.error(`❌ Media index variant refresh failed: ${err.message}`));- const filedCollections = await autoFileCleanedToSourceCollections(sourceFilename, outFilename).catch((err) => {- console.warn(`⚠️ Auto-file ${outFilename} → source collections failed: ${err?.message || err}`);- return [];- });+ const filedCollections = await autoFileCleanedToSourceCollections(sourceFilename, outFilename).catch((err) => {+ console.warn(`⚠️ Auto-file ${outFilename} → source collections failed: ${err?.message || err}`);+ return [];+ });- console.log(`${logLine}${filedCollections.length ? `, filed to ${filedCollections.length} collection(s)` : ''}`);+ console.log(`${logLine}${filedCollections.length ? `, filed to ${filedCollections.length} collection(s)` : ''}`);- return {- ...untimedVariantMeta,- filename: outFilename,- path: `/data/images/${outFilename}`,- ...(width != null ? { width } : {}),- ...(height != null ? { height } : {}),- ...(sizeBefore != null ? { sizeBefore } : {}),- ...(sizeAfter != null ? { sizeAfter, sizeBytes: sizeAfter } : {}),- ...extraFields,- };+ return {+ ...untimedVariantMeta,+ filename: outFilename,+ path: `/data/images/${outFilename}`,+ ...(width != null ? { width } : {}),+ ...(height != null ? { height } : {}),+ ...(sizeBefore != null ? { sizeBefore } : {}),+ ...(sizeAfter != null ? { sizeAfter, sizeBytes: sizeAfter } : {}),+ ...extraFields,+ };+ }));}// ---------------------------------------------------------------------------diff --git a/server/services/imageGenEvents.js b/server/services/imageGenEvents.jsindex 1174f00ebf..61de5d1267 100644--- a/server/services/imageGenEvents.js+++ b/server/services/imageGenEvents.js@@ -1,3 +1,4 @@+import { runOutsideBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';import { EventEmitter } from 'events';import { makeEmitterFaultIsolating } from '../lib/faultIsolatedEmitter.js';@@ -11,3 +12,11 @@ export const imageGenEvents = makeEmitterFaultIsolating(new EventEmitter());// memory growth in pm2 status, not as the warning. 200 leaves headroom for// short overlap during job churn.imageGenEvents.setMaxListeners(200);++// Async completion listeners own their leases instead of borrowing the provider's.+const emit = imageGenEvents.emit;+imageGenEvents.emit = function (event, ...args) {+ return event === 'completed'+ ? runOutsideBackupAssetPublication(() => emit.call(this, event, ...args))+ : emit.call(this, event, ...args);+};diff --git a/server/services/mediaSketches.js b/server/services/mediaSketches.jsindex 28a58fbace..0bbb754531 100644--- a/server/services/mediaSketches.js+++ b/server/services/mediaSketches.js@@ -1,3 +1,5 @@+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';+import { publishImageFiles } from './imageGen/publication.js';/*** Sketch & annotation overlays for generated media, keyed by `<kind>:<ref>`.*@@ -160,34 +162,39 @@ export async function saveSketch(key, input) {throw makeErr('Only image media or blank-canvas sketches can be annotated', ERR_VALIDATION);}const clean = sanitizeSketchInput(input);- await ensureDir(SKETCH_DIR);-- if (clean.strokes.length === 0) {- await removeSketch(key);- return { key, width: clean.width, height: clean.height, strokes: [], updatedAt: null, hasPng: false };- }-- const hasPng = !!clean.png;- if (hasPng) await atomicWrite(pngPathFor(key), clean.png);- // A re-save that carries only vectors (no PNG) must drop any prior flattened- // export, otherwise `hasPng:false` in the JSON disagrees with a stale- // `<id>.png` that getSketchPng() would keep streaming.- else await unlinkGuarded(pngPathFor(key)).catch(() => {});- const record = {- key,- width: clean.width,- height: clean.height,- strokes: clean.strokes,- updatedAt: new Date().toISOString(),- hasPng,- };- await atomicWrite(jsonPathFor(key), record);- return record;+ return withBackupAssetPublication(() => publishImageFiles([pngPathFor(key), jsonPathFor(key)], async () => {+ await ensureDir(SKETCH_DIR);++ if (clean.strokes.length === 0) {+ await unlinkGuarded(jsonPathFor(key)).catch(error => { if (error.code !== 'ENOENT') throw error; });+ await unlinkGuarded(pngPathFor(key)).catch(error => { if (error.code !== 'ENOENT') throw error; });+ return { key, width: clean.width, height: clean.height, strokes: [], updatedAt: null, hasPng: false };+ }++ const hasPng = !!clean.png;+ if (hasPng) await atomicWrite(pngPathFor(key), clean.png);+ // A re-save that carries only vectors (no PNG) must drop any prior flattened+ // export, otherwise `hasPng:false` in the JSON disagrees with a stale+ // `<id>.png` that getSketchPng() would keep streaming.+ else await unlinkGuarded(pngPathFor(key)).catch(error => { if (error.code !== 'ENOENT') throw error; });+ const record = {+ key,+ width: clean.width,+ height: clean.height,+ strokes: clean.strokes,+ updatedAt: new Date().toISOString(),+ hasPng,+ };+ await atomicWrite(jsonPathFor(key), record);+ return record;+ }));}/** Remove a key's sidecar (json + png). Idempotent. */export async function removeSketch(key) {if (!isValidKey(key)) throw makeErr(`Invalid key: ${key}`, ERR_VALIDATION);- await unlinkGuarded(jsonPathFor(key)).catch(() => {});- await unlinkGuarded(pngPathFor(key)).catch(() => {});+ return withBackupAssetPublication(() => publishImageFiles([pngPathFor(key), jsonPathFor(key)], async () => {+ await unlinkGuarded(jsonPathFor(key)).catch(error => { if (error.code !== 'ENOENT') throw error; });+ await unlinkGuarded(pngPathFor(key)).catch(error => { if (error.code !== 'ENOENT') throw error; });+ }));}diff --git a/server/services/mediaSketches.test.js b/server/services/mediaSketches.test.jsindex bbc6f761f1..0e6e26649d 100644--- a/server/services/mediaSketches.test.js+++ b/server/services/mediaSketches.test.js@@ -13,6 +13,11 @@ vi.mock('../lib/fileUtils.js', () => ({}));vi.mock('fs/promises', () => ({+ readFile: vi.fn(async path => {+ if (!fileStore.has(path)) throw Object.assign(new Error('missing'), { code: 'ENOENT' });+ const value = fileStore.get(path);+ return Buffer.isBuffer(value) ? value : Buffer.from(JSON.stringify(value));+ }),unlink: vi.fn(async (path) => { fileStore.delete(path); }),access: vi.fn(async (path) => { if (!fileStore.has(path)) throw new Error('ENOENT'); }),}));