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: reject degenerate generated frames before they become records or vision calls (#4173)
[._.]/ Adam Eivyf42b2b2f28f1
diff --git a/.changelog/next/added-issue-4173.md b/.changelog/next/added-issue-4173.mdnew file mode 100644index 0000000000..701f18c621--- /dev/null+++ b/.changelog/next/added-issue-4173.md@@ -0,0 +1 @@+- Image Gen, sprite reference locking and the vision judge now reject a degenerate generated frame (solid fill, empty alpha, near-zero entropy) instead of saving a blank tile as a gallery record or spending a vision-provider call on itdiff --git a/server/lib/README.md b/server/lib/README.mdindex 9f498f61a9..edc7226687 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -165,6 +165,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. || `fileWriteQueue.js` | Serialize read-modify-write cycles so they don't interleave. `createFileWriteQueue()` → single-tail `queue(fn)` for one shared file; `createRecordWriteQueue(assertId?)` → id-keyed `queueRecordWrite(id, fn)` where same-id cycles serialize and different-id cycles run in parallel (the queue the PG/file store facades use for `collectionStore.queueRecordWrite` parity); `createKeyedFileWriteQueue()` → `queueKeyedWrite(key, fn)` that collapses the pipeline stage stores' hand-rolled `Map` + per-key `createFileWriteQueue` factory (falsy keys → shared `'__unknown__'` tail; self-pruning via `createKeyCachedQueue`). || `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `compositeIgnoreZone(base, original, mask, { feather })` (preserve-region compositing: restore original pixels into a feathered mask over a diffused result) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer` and appends a CPU light diffusion pass (`applyLightRegen` from `services/imageGen/regen.js`) for the `diffusion=light` SynthID-disruption step. |+| `imageFrameStats.js` | Degenerate-frame classifier (#4173) — `describeFrameStats(bufferOrPath)` runs one `sharp` `.stats()` decode and returns `{ ok, reason, perChannel }`, rejecting `solid-fill` (every colour channel stdev under `SOLID_FILL_STDEV_EPSILON`), `fully-transparent` (alpha max 0) and `near-empty` (greyscale entropy under `NEAR_EMPTY_ENTROPY_FLOOR`). Deliberately NOT a quality judge: a legitimately dark or minimalist render keeps real per-channel variance and is accepted. `ok` is three-valued — `true`/`false`/`null`, where `null` means could-not-measure (undecodable buffer, or under `MIN_JUDGEABLE_PIXELS`) and must never read as degenerate; gate on `isDegenerateFrame(stats)` / `ok === false`, never `!ok`. Called by the Image Gen provider completion seams, sprite reference normalization, and `visionTest.js` (so a paid vision call is never spent on a blank frame). || `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`). || `localMemory.js` | Shared best-effort local-model unload + available-memory report (`prepareLocalMemory`) for GPU-heavy local work; only loopback Ollama / LM Studio backends are evicted. |diff --git a/server/lib/imageFrameStats.js b/server/lib/imageFrameStats.jsnew file mode 100644index 0000000000..b7cae3c423--- /dev/null+++ b/server/lib/imageFrameStats.js@@ -0,0 +1,134 @@+/**+ * Degenerate-frame classifier (issue #4173).+ *+ * PortOS validates that a generated image *decodes*, never that it has+ * *content*. A decodable but degenerate frame — a solid-black render from a+ * local run that produced nothing, a fully-transparent sheet from a failed+ * sprite pass, a flat fill from a cloud CLI that declined and still emitted a+ * canvas — currently reaches the gallery, the sidecar, an entry's `imageRefs[]`+ * and (worst) a paid vision judge asked to describe a black square.+ *+ * `describeFrameStats` is the cheap numeric tell for that case: one `sharp`+ * `.stats()` decode gives per-channel mean/stdev plus the greyscale entropy,+ * and a frame whose every channel has stdev ≈ 0 is a solid fill that cannot be+ * a real render.+ *+ * TWO PROPERTIES THIS MODULE MUST KEEP:+ *+ * 1. **It is not a quality judge.** Only the mathematically degenerate case is+ * rejected. A legitimately dark, low-key or minimalist render still carries+ * real per-channel variance and MUST be accepted — the thresholds below sit+ * far under anything an encoder can represent as signal precisely so that a+ * real frame can never trip them.+ *+ * 2. **Sentinel correctness** (root CLAUDE.md): "could not compute stats" must+ * NOT collapse into "degenerate". `ok` is three-valued —+ * `true` = measured, has content+ * `false` = measured, degenerate (`reason` names which)+ * `null` = NOT measured (undecodable buffer, or too few pixels to judge)+ * A `null` is logged and must never be treated as a generation failure; an+ * undecodable buffer stays the caller's existing `INVALID_IMAGE` path.+ * Callers therefore gate on `ok === false`, never on `!ok`.+ */++import sharp from 'sharp';++// Per-channel stdev, in 8-bit levels, under which a channel counts as flat.+// A genuinely flat fill reports exactly 0. Half of one 0-255 level is below+// the smallest difference an 8-bit encoder can even represent, so no real+// render — however dark — can land beneath it, while PNG/JPEG quantization+// noise in a real frame sits orders of magnitude above it.+export const SOLID_FILL_STDEV_EPSILON = 0.5;++// Shannon entropy (bits/pixel over the greyscale histogram, 0-8) under which a+// frame counts as empty. 0.05 bits ≈ fewer than ~0.5% of pixels differing from+// a single value — the indexed/palette analogue of a flat fill, which the+// stdev test can miss when a paletted encoder rounds a two-bucket histogram.+// A real render, even a near-black one, scores whole bits above this.+export const NEAR_EMPTY_ENTROPY_FLOOR = 0.05;++// Below this pixel count the statistics carry no information: a legitimate+// 8x8 icon or a 2x2 test tile really can be one flat color, so anything under+// 16x16 is reported as unjudgeable (`ok: null`) rather than degenerate.+export const MIN_JUDGEABLE_PIXELS = 256;++export const FRAME_REASON = {+ SOLID_FILL: 'solid-fill',+ FULLY_TRANSPARENT: 'fully-transparent',+ NEAR_EMPTY: 'near-empty',+ STATS_UNAVAILABLE: 'stats-unavailable',+ TOO_SMALL: 'too-small-to-judge',+};++// The reasons that mean "the backend produced no content". `stats-unavailable`+// and `too-small-to-judge` are deliberately NOT in here — they ride `ok: null`.+export const DEGENERATE_FRAME_REASONS = [+ FRAME_REASON.SOLID_FILL,+ FRAME_REASON.FULLY_TRANSPARENT,+ FRAME_REASON.NEAR_EMPTY,+];++const result = (ok, reason, perChannel = null) => ({ ok, reason, perChannel });++/**+ * Classify a decoded image as having content or being degenerate.+ *+ * @param {Buffer|string} input encoded image bytes (or a path sharp can open)+ * @returns {Promise<{ ok: boolean|null, reason: string|null, perChannel: Array<{ mean: number, stdev: number, min: number, max: number }>|null }>}+ */+export async function describeFrameStats(input) {+ // One sharp instance per read — `metadata()` and `stats()` both consume the+ // pipeline, so sharing an instance between them is not safe.+ // Most callers run outside the Express request lifecycle (child-process+ // completion handlers), and a decode failure is explicitly NOT a verdict —+ // so the failure is captured, logged, and reported as the `null` sentinel.+ // `sharp()` itself throws synchronously for an empty/absent buffer, so the+ // whole probe runs inside a promise chain that converts that into the same+ // rejection an undecodable buffer produces.+ const probe = await Promise.resolve()+ .then(async () => ({ metadata: await sharp(input).metadata(), stats: await sharp(input).stats() }))+ .catch((err) => ({ err }));+ if (probe.err) {+ console.warn(`⚠️ Frame stats unavailable, skipping degenerate-frame check: ${probe.err?.message || probe.err}`);+ return result(null, FRAME_REASON.STATS_UNAVAILABLE);+ }++ const { metadata, stats } = probe;+ const channels = Array.isArray(stats.channels) ? stats.channels : [];+ if (!channels.length) {+ console.warn('⚠️ Frame stats returned no channels, skipping degenerate-frame check');+ return result(null, FRAME_REASON.STATS_UNAVAILABLE);+ }++ const pixels = Number(metadata.width) * Number(metadata.height);+ if (!Number.isFinite(pixels) || pixels < MIN_JUDGEABLE_PIXELS) {+ return result(null, FRAME_REASON.TOO_SMALL);+ }++ const perChannel = channels.map(({ mean, stdev, min, max }) => ({ mean, stdev, min, max }));++ // Alpha first: a fully-transparent sheet can carry arbitrary garbage in its+ // colour channels, so the colour tests below would not see it.+ if (metadata.hasAlpha) {+ const alpha = perChannel[perChannel.length - 1];+ if (alpha.max === 0) return result(false, FRAME_REASON.FULLY_TRANSPARENT, perChannel);+ }++ // Only the colour channels decide "flat" — a fully-OPAQUE alpha channel is+ // itself flat by definition and would otherwise veto every normal PNG.+ const colour = metadata.hasAlpha ? perChannel.slice(0, -1) : perChannel;+ if (colour.length && colour.every((c) => c.stdev < SOLID_FILL_STDEV_EPSILON)) {+ return result(false, FRAME_REASON.SOLID_FILL, perChannel);+ }++ // sharp reports entropy only when it could compute one; a missing value is+ // not evidence of emptiness, so it falls through to `ok: true`.+ if (typeof stats.entropy === 'number' && stats.entropy < NEAR_EMPTY_ENTROPY_FLOOR) {+ return result(false, FRAME_REASON.NEAR_EMPTY, perChannel);+ }++ return result(true, null, perChannel);+}++/** True only for a measured, degenerate verdict — never for the `null` sentinel. */+export const isDegenerateFrame = (stats) => stats?.ok === false;diff --git a/server/lib/imageFrameStats.test.js b/server/lib/imageFrameStats.test.jsnew file mode 100644index 0000000000..c80955fd9c--- /dev/null+++ b/server/lib/imageFrameStats.test.js@@ -0,0 +1,145 @@+import { describe, it, expect } from 'vitest';+import sharp from 'sharp';+import {+ describeFrameStats,+ isDegenerateFrame,+ FRAME_REASON,+ MIN_JUDGEABLE_PIXELS,+} from './imageFrameStats.js';++const SIDE = 64; // 4096 px — comfortably over MIN_JUDGEABLE_PIXELS++// Every fixture is synthesized here: no binary fixture is committed and no+// image from the running instance is ever read.+const solid = (background, channels = 3) => sharp({+ create: { width: SIDE, height: SIDE, channels, background },+}).png().toBuffer();++// Raw RGB gradient so we control the exact pixel values.+const fromPixels = (fill, { channels = 3, width = SIDE, height = SIDE } = {}) => {+ const raw = Buffer.alloc(width * height * channels);+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ const i = (y * width + x) * channels;+ const px = fill(x, y);+ for (let c = 0; c < channels; c++) raw[i + c] = px[c];+ }+ }+ return sharp(raw, { raw: { width, height, channels } }).png().toBuffer();+};++describe('describeFrameStats', () => {+ it('rejects a solid black frame as a flat fill', async () => {+ const stats = await describeFrameStats(await solid({ r: 0, g: 0, b: 0 }));+ expect(stats.ok).toBe(false);+ expect(stats.reason).toBe(FRAME_REASON.SOLID_FILL);+ expect(isDegenerateFrame(stats)).toBe(true);+ });++ it('rejects a solid white frame as a flat fill', async () => {+ const stats = await describeFrameStats(await solid({ r: 255, g: 255, b: 255 }));+ expect(stats.ok).toBe(false);+ expect(stats.reason).toBe(FRAME_REASON.SOLID_FILL);+ });++ it('rejects a solid mid-grey frame as a flat fill', async () => {+ const stats = await describeFrameStats(await solid({ r: 118, g: 118, b: 118 }));+ expect(stats.ok).toBe(false);+ expect(stats.reason).toBe(FRAME_REASON.SOLID_FILL);+ });++ it('rejects a fully transparent sheet even when its colour channels vary', async () => {+ // Noisy RGB under a zero alpha — the colour tests alone would pass it.+ const buf = await fromPixels((x, y) => [(x * 7) % 256, (y * 11) % 256, (x + y) % 256, 0], { channels: 4 });+ const stats = await describeFrameStats(buf);+ expect(stats.ok).toBe(false);+ expect(stats.reason).toBe(FRAME_REASON.FULLY_TRANSPARENT);+ });++ it('ACCEPTS a very dark but real low-key gradient (not a quality judge)', async () => {+ // Deepest pixel 0, brightest 12/255 — the sort of near-black night render+ // a naive brightness heuristic would throw away.+ const buf = await fromPixels((x, y) => {+ const v = Math.round(((x + y) / (2 * (SIDE - 1))) * 12);+ return [v, v, v + (x % 2)];+ });+ const stats = await describeFrameStats(buf);+ expect(stats.ok).toBe(true);+ expect(stats.reason).toBeNull();+ expect(isDegenerateFrame(stats)).toBe(false);+ });++ it('ACCEPTS a minimalist frame that is mostly one colour with a real subject', async () => {+ const buf = await fromPixels((x, y) => {+ const inSubject = x > 20 && x < 44 && y > 20 && y < 44;+ return inSubject ? [220, 180, 90] : [8, 8, 10];+ });+ const stats = await describeFrameStats(buf);+ expect(stats.ok).toBe(true);+ });++ it('ACCEPTS a normal photo-like frame', async () => {+ const buf = await fromPixels((x, y) => [+ (x * 3 + y) % 256,+ (y * 5 + x * 2) % 256,+ (x * x + y * y) % 256,+ ]);+ const stats = await describeFrameStats(buf);+ expect(stats.ok).toBe(true);+ expect(stats.perChannel).toHaveLength(3);+ });++ it('ACCEPTS an opaque frame whose alpha channel is flat by definition', async () => {+ const buf = await fromPixels((x, y) => [(x * 4) % 256, (y * 4) % 256, 128, 255], { channels: 4 });+ const stats = await describeFrameStats(buf);+ expect(stats.ok).toBe(true);+ });++ it('rejects a near-empty frame whose single stray pixel leaves entropy at the floor', async () => {+ const buf = await fromPixels((x, y) => (x === 0 && y === 0 ? [255, 255, 255] : [0, 0, 0]));+ const stats = await describeFrameStats(buf);+ expect(stats.ok).toBe(false);+ // Either tell is correct here; what matters is that it is not accepted.+ expect([FRAME_REASON.SOLID_FILL, FRAME_REASON.NEAR_EMPTY]).toContain(stats.reason);+ });+});++describe('describeFrameStats sentinels', () => {+ it('returns ok:null (not degenerate) for an undecodable buffer', async () => {+ const stats = await describeFrameStats(Buffer.from('not an image at all'));+ expect(stats.ok).toBeNull();+ expect(stats.reason).toBe(FRAME_REASON.STATS_UNAVAILABLE);+ expect(stats.perChannel).toBeNull();+ // The crux: "could not compute" must NOT read as "degenerate".+ expect(isDegenerateFrame(stats)).toBe(false);+ });++ it('returns ok:null for an empty buffer rather than calling it empty content', async () => {+ const stats = await describeFrameStats(Buffer.alloc(0));+ expect(stats.ok).toBeNull();+ expect(isDegenerateFrame(stats)).toBe(false);+ });++ it('returns ok:null for a frame too small for its statistics to mean anything', async () => {+ const tiny = await sharp({ create: { width: 2, height: 2, channels: 3, background: '#fff' } }).png().toBuffer();+ const stats = await describeFrameStats(tiny);+ expect(stats.ok).toBeNull();+ expect(stats.reason).toBe(FRAME_REASON.TOO_SMALL);+ expect(isDegenerateFrame(stats)).toBe(false);+ });++ it('judges a frame exactly at the minimum size', async () => {+ const side = Math.sqrt(MIN_JUDGEABLE_PIXELS);+ const buf = await sharp({ create: { width: side, height: side, channels: 3, background: '#000' } })+ .png().toBuffer();+ const stats = await describeFrameStats(buf);+ expect(stats.ok).toBe(false);+ expect(stats.reason).toBe(FRAME_REASON.SOLID_FILL);+ });++ it('isDegenerateFrame is false for a missing/garbled verdict', () => {+ expect(isDegenerateFrame(null)).toBe(false);+ expect(isDegenerateFrame(undefined)).toBe(false);+ expect(isDegenerateFrame({})).toBe(false);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex d9bf60229b..901f52bc64 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -165,6 +165,7 @@ export * from './icloudFile.js';export * from './spawnCwd.js';export * from './schemaVersions.js';export * from './imageClean.js';+export * from './imageFrameStats.js';export * from './imageWatermark.js';export * from './localImageFilename.js';export * from './localMemory.js';diff --git a/server/services/imageGen/agy.js b/server/services/imageGen/agy.jsindex da22ed1267..c2701e50be 100644--- a/server/services/imageGen/agy.js+++ b/server/services/imageGen/agy.js@@ -31,6 +31,7 @@ import { killWithEscalation } from '../../lib/killWithEscalation.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';import { imageGenEvents } from '../imageGenEvents.js';import { buildNoImageReason } from './noImageReason.js';+import { rejectDegenerateFrame } from './frameGuard.js';import { checkFabrication, noFabricationClause } from './fabricationGuard.js';import {AGY_IMAGEGEN_IMAGE_MODEL, IMAGE_GEN_MODE, IMAGE_TOOL_NAMES, describeFidelity,@@ -368,6 +369,12 @@ async function runAgy(job, jobId, bin, args, {await sharp(stagingPath).png().toFile(outputPath);}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 finalizeError(job, jobId, proc, emptyFrame);+ }const sidecar = join(PATHS.images, `${jobId}.metadata.json`);await atomicWrite(sidecar, meta).catch(() => {});await autoCleanGeneratedImage({diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.jsindex 3cf1197c3a..80b085441a 100644--- a/server/services/imageGen/codex.js+++ b/server/services/imageGen/codex.js@@ -47,6 +47,7 @@ import {describeFidelity, visualReferenceRole,} from './modes.js';import { buildNoImageReason } from './noImageReason.js';+import { rejectDegenerateFrame } from './frameGuard.js';import { resolveInputImages } from './inputImages.js';import { cloudPromptRequired } from './cloudProviderConfig.js';@@ -406,6 +407,12 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cle} else {await writeFile(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 finalizeError(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 isdiff --git a/server/services/imageGen/frameGuard.js b/server/services/imageGen/frameGuard.jsnew file mode 100644index 0000000000..a0f9e8e5d1--- /dev/null+++ b/server/services/imageGen/frameGuard.js@@ -0,0 +1,53 @@+/**+ * Image Gen — degenerate-frame gate (issue #4173).+ *+ * Every provider path could previously finish "successfully" having written a+ * frame that decodes but has no content, and that frame became a gallery+ * record, a sidecar, an `imageRefs[]` entry, and a paid vision-judge call.+ * This is the one seam every provider's completion funnels through before it+ * writes a sidecar and emits `completed`.+ *+ * Contract — `degenerateFrameReason(pngPath)`:+ * - returns a user-facing failure string ONLY for a measured degenerate+ * verdict (`describeFrameStats(...).ok === false`);+ * - returns `null` for a healthy frame, for a frame whose stats could not be+ * computed (`ok: null`), and for a file that isn't on disk yet. Absent /+ * unmeasurable must never be reported as a generation failure — the+ * existing missing-file and `INVALID_IMAGE` paths still own those.+ *+ * Note the dispatcher (`index.js#generateImage`) can only apply this to a+ * provider that resolves AFTER writing its bytes (the synchronous external+ * SD-API path). The four job-based providers return a `jobId` long before the+ * PNG lands, so each of them calls the gate from its own completion handler.+ */++import { readFile, unlink } from 'fs/promises';+import { basename } from 'path';+import { describeFrameStats, isDegenerateFrame } from '../../lib/imageFrameStats.js';+import { describeDegenerateFrame } from './noImageReason.js';++/**+ * @param {string} pngPath absolute path to the frame a provider just wrote+ * @returns {Promise<string|null>} narrated failure, or null to let it through+ */+export async function degenerateFrameReason(pngPath) {+ if (!pngPath) return null;+ // A missing file is not this gate's verdict to give — the providers already+ // have a "no image was written" path with far better narration.+ const buffer = await readFile(pngPath).catch(() => null);+ if (!buffer) return null;+ const stats = await describeFrameStats(buffer);+ if (!isDegenerateFrame(stats)) return null;+ console.warn(`🚫 Rejected empty frame (${stats.reason}): ${basename(pngPath)}`);+ return describeDegenerateFrame(stats.reason);+}++/**+ * Same gate, plus the cleanup a job-based provider needs: the empty PNG is+ * removed so a half-written render can't be picked up by the gallery scan.+ */+export async function rejectDegenerateFrame(pngPath) {+ const reason = await degenerateFrameReason(pngPath);+ if (reason) await unlink(pngPath).catch(() => {});+ return reason;+}diff --git a/server/services/imageGen/frameGuard.test.js b/server/services/imageGen/frameGuard.test.jsnew file mode 100644index 0000000000..07250e77ad--- /dev/null+++ b/server/services/imageGen/frameGuard.test.js@@ -0,0 +1,113 @@+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import { mkdtemp, rm, writeFile, access } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import sharp from 'sharp';++// The dispatcher pulls in every provider module; stub them so the suite stays+// about the degenerate-frame gate and nothing spawns a CLI or touches settings.+vi.mock('../settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));+vi.mock('./local.js', () => ({ generateImage: vi.fn(), getActiveJob: () => null, attachSseClient: () => false, cancel: () => false }));+vi.mock('./codex.js', () => ({ generateImage: vi.fn(), getActiveJob: () => null, attachSseClient: () => false, cancelAll: () => false }));+vi.mock('./grok.js', () => ({ generateImage: vi.fn(), getActiveJob: () => null, attachSseClient: () => false, cancelAll: () => false }));+vi.mock('./agy.js', () => ({ generateImage: vi.fn(), getActiveJob: () => null, attachSseClient: () => false, cancelAll: () => false }));+vi.mock('./external.js', () => ({ generateImage: vi.fn(), checkConnection: vi.fn(), getActiveJob: () => null }));++import * as external from './external.js';+import { generateImage } from './index.js';+import { degenerateFrameReason, rejectDegenerateFrame } from './frameGuard.js';++let dir;+const SIDE = 64;++const writePng = async (name, buffer) => {+ dir ||= await mkdtemp(join(tmpdir(), 'portos-framegate-'));+ const path = join(dir, name);+ await writeFile(path, buffer);+ return path;+};++const solidPng = (background) => sharp({+ create: { width: SIDE, height: SIDE, channels: 3, background },+}).png().toBuffer();++const realPng = () => {+ const raw = Buffer.alloc(SIDE * SIDE * 3);+ for (let y = 0; y < SIDE; y++) {+ for (let x = 0; x < SIDE; x++) {+ const i = (y * SIDE + x) * 3;+ raw[i] = (x * 3) % 256;+ raw[i + 1] = (y * 5) % 256;+ raw[i + 2] = (x + y) % 256;+ }+ }+ return sharp(raw, { raw: { width: SIDE, height: SIDE, channels: 3 } }).png().toBuffer();+};++const exists = (p) => access(p).then(() => true, () => false);++beforeEach(() => { vi.clearAllMocks(); });+afterAll(async () => { if (dir) await rm(dir, { recursive: true, force: true }); });++describe('degenerateFrameReason', () => {+ it('narrates a solid-fill frame in words the UI can show', async () => {+ const path = await writePng('black.png', await solidPng({ r: 0, g: 0, b: 0 }));+ const reason = await degenerateFrameReason(path);+ expect(reason).toMatch(/no content/i);+ expect(reason).toMatch(/flat color/i);+ });++ it('passes a real frame through', async () => {+ const path = await writePng('real.png', await realPng());+ expect(await degenerateFrameReason(path)).toBeNull();+ });++ it('passes an undecodable file through — that is the INVALID_IMAGE path, not this gate', async () => {+ const path = await writePng('garbage.png', Buffer.from('not a png'));+ expect(await degenerateFrameReason(path)).toBeNull();+ });++ it('passes a not-yet-written file through rather than inventing a failure', async () => {+ expect(await degenerateFrameReason(join(tmpdir(), 'portos-does-not-exist-4173.png'))).toBeNull();+ expect(await degenerateFrameReason(null)).toBeNull();+ });++ it('rejectDegenerateFrame deletes the empty PNG, and leaves a real one alone', async () => {+ const empty = await writePng('empty.png', await solidPng({ r: 255, g: 255, b: 255 }));+ expect(await rejectDegenerateFrame(empty)).toMatch(/no content/i);+ expect(await exists(empty)).toBe(false);++ const good = await writePng('keep.png', await realPng());+ expect(await rejectDegenerateFrame(good)).toBeNull();+ expect(await exists(good)).toBe(true);+ });+});++describe('generateImage degenerate-frame gate', () => {+ it('surfaces a failure when a provider writes a solid-fill PNG', async () => {+ const outputPath = await writePng('provider-solid.png', await solidPng({ r: 0, g: 0, b: 0 }));+ vi.mocked(external.generateImage).mockResolvedValue({+ filename: 'provider-solid.png', path: '/data/images/provider-solid.png', outputPath,+ });++ await expect(generateImage({ prompt: 'a cat' })).rejects.toMatchObject({ code: 'DEGENERATE_FRAME' });+ // No gallery record: the empty frame is gone from disk too.+ expect(await exists(outputPath)).toBe(false);+ });++ it('returns the artifact untouched when the frame has real content', async () => {+ const outputPath = await writePng('provider-real.png', await realPng());+ const artifact = { filename: 'provider-real.png', path: '/data/images/provider-real.png', outputPath };+ vi.mocked(external.generateImage).mockResolvedValue(artifact);++ await expect(generateImage({ prompt: 'a cat' })).resolves.toBe(artifact);+ expect(await exists(outputPath)).toBe(true);+ });++ it('lets a job-based provider return its jobId before the render lands', async () => {+ // Nothing is on disk yet — the gate must not read that as an empty frame.+ const artifact = { jobId: 'job-1', generationId: 'job-1', filename: 'pending.png', path: '/data/images/pending.png' };+ vi.mocked(external.generateImage).mockResolvedValue(artifact);+ await expect(generateImage({ prompt: 'a cat' })).resolves.toBe(artifact);+ });+});diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.jsindex f2203ac8f5..29f4183684 100644--- a/server/services/imageGen/grok.js+++ b/server/services/imageGen/grok.js@@ -44,6 +44,7 @@ import { imageGenEvents } from '../imageGenEvents.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';import { killWithEscalation } from '../../lib/killWithEscalation.js';import { buildNoImageReason } from './noImageReason.js';+import { rejectDegenerateFrame } from './frameGuard.js';import { checkFabrication, noFabricationClause } from './fabricationGuard.js';import sharp from 'sharp';import { bufferedSpawn, killProcessTree, prepareCliSpawn } from '../../lib/bufferedSpawn.js';@@ -401,6 +402,12 @@ async function runGrok(job, jobId, bin, args, {await sharp(stagingPath).png().toFile(outputPath);}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 finalizeError(job, jobId, proc, emptyFrame);+ }// Sidecar metadata so the gallery can recover prompt/ratio/etc.const sidecar = join(PATHS.images, `${jobId}.metadata.json`);await atomicWrite(sidecar, meta).catch(() => {});diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.jsindex 9a1bd33552..a718e41a29 100644--- a/server/services/imageGen/index.js+++ b/server/services/imageGen/index.js@@ -12,6 +12,7 @@* exists for users whose Codex plan doesn't expose the image_gen tool.*/+import { join } from 'path';import { getSettings } from '../settings.js';import { resolveCleanersFromConfig } from '../../lib/imageClean.js';import * as external from './external.js';@@ -23,6 +24,9 @@ import {IMAGE_GEN_MODE, IMAGE_GEN_MODES, CLOUD_IMAGE_GEN_MODES, isEditCapableMode,} from './modes.js';import { resolveCloudProviderConfig } from './cloudProviderConfig.js';+import { rejectDegenerateFrame } from './frameGuard.js';+import { PATHS } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';// Cloud-CLI provider modules keyed by mode, so the shared gate in// checkConnection/generateImage dispatches without a per-provider branch.@@ -126,12 +130,31 @@ export async function generateImage(params) {const cloud = resolveCloudProviderConfig(s, mode, { model: cloudModel });if (cloud) {if (!cloud.enabled) throw cloud.disabledError;- return CLOUD_PROVIDERS[mode].generateImage({ ...cloud.providerParams, cleanC2PA, denoise, ...normalized });+ return guardResolvedFrame(await CLOUD_PROVIDERS[mode].generateImage({ ...cloud.providerParams, cleanC2PA, denoise, ...normalized }));}if (mode === IMAGE_GEN_MODE.LOCAL) {- return local.generateImage({ pythonPath: pythonPath(s), cleanC2PA, denoise, ...normalized });+ return guardResolvedFrame(await local.generateImage({ pythonPath: pythonPath(s), cleanC2PA, denoise, ...normalized }));}- return external.generateImage({ sdapiUrl: sdapiUrl(s), cleanC2PA, denoise, ...normalized });+ return guardResolvedFrame(await external.generateImage({ sdapiUrl: sdapiUrl(s), cleanC2PA, denoise, ...normalized }));+}++/**+ * Degenerate-frame gate at the dispatcher seam (issue #4173) — a provider must+ * not be able to hand back an artifact that decodes but has no content.+ *+ * This covers every provider that resolves AFTER writing its bytes (the+ * synchronous external SD-API path, and any future one shaped like it). The+ * four job-based providers return a `jobId` while the render is still running,+ * so there is nothing on disk to judge here — they call the same gate from+ * their own completion handlers, before the sidecar write and the `completed`+ * 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;}const DEFAULT_NEGATIVE_PROMPT = 'blurry, low quality, distorted, deformed, ugly, watermark, text, signature';diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 70b5018bf8..e613dfc11b 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -22,6 +22,7 @@ import { randomUUID } from 'crypto';import { atomicWrite, assertSafeFilename, detectImageFormat, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveImageInputPath, tryReadFile } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { autoCleanGeneratedImage } from '../../lib/imageClean.js';+import { rejectDegenerateFrame } from './frameGuard.js';import { imageGenEvents } from '../imageGenEvents.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';import { resolveFlux2Python, FLUX2_VENV_DEFAULT } from '../../lib/pythonSetup.js';@@ -758,6 +759,21 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =void releaseHeavyClaim();if (watcher) { try { watcher.close(); } catch { /* ignore */ } }rm(stepwiseDir, { recursive: true, force: true }).catch(() => {});+ // 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.log(`❌ Image generation failed [${jobId.slice(0, 8)}]: ${emptyFrame}`);+ broadcastSse(job, { type: 'error', error: emptyFrame });+ imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: emptyFrame });+ closeJobAfterDelay(jobs, jobId);+ return;+ }if (code !== 0) {job.status = 'error';const reason = signal ? `Killed by signal ${signal}` : `Exit code ${code}`;diff --git a/server/services/imageGen/noImageReason.js b/server/services/imageGen/noImageReason.jsindex 62239500c3..df92db145b 100644--- a/server/services/imageGen/noImageReason.js+++ b/server/services/imageGen/noImageReason.js@@ -37,3 +37,22 @@ export function buildNoImageReason(stdoutTail = '', { hint, dropLine, describe }const said = lines.slice(-NARRATION_LINES).join(' ').slice(-NARRATION_MAX_CHARS);return said ? describe(said) : hint;}++/**+ * The other way a run can end without an image: it wrote a file that decodes+ * fine and has no content (issue #4173). Same narrator, different input — the+ * verdict is a `reason` from `lib/imageFrameStats.js`, not stdout — so the UI+ * says something true instead of rendering a black tile.+ */+const DEGENERATE_FRAME_DETAIL = {+ 'solid-fill': 'it is a single flat color',+ 'fully-transparent': 'it is fully transparent',+ 'near-empty': 'it has almost no detail',+};++export function describeDegenerateFrame(reason) {+ const detail = DEGENERATE_FRAME_DETAIL[reason];+ return detail+ ? `The backend wrote an image with no content — ${detail}. Nothing was saved; try again or switch models.`+ : 'The backend wrote an image with no content. Nothing was saved; try again or switch models.';+}diff --git a/server/services/sprites/normalize.js b/server/services/sprites/normalize.jsindex 9afa9aca37..04aaff7ca1 100644--- a/server/services/sprites/normalize.js+++ b/server/services/sprites/normalize.js@@ -30,6 +30,8 @@import sharp from 'sharp';import { copyFile } from 'fs/promises';import { hexToRgb, keyChannelSplit, keyShareFn } from './chromaKey.js';+import { describeFrameStats, isDegenerateFrame } from '../../lib/imageFrameStats.js';+import { ServerError } from '../../lib/errorHandler.js';const FRAME_HEIGHT_FRAC = 0.80;const FRAME_BOTTOM_FRAC = 0.07;@@ -54,7 +56,36 @@ export { hexToRgb };* color. The lock path runs palette extraction AND normalization off ONE* analysis so a multi-MP candidate is decoded and scanned once.*/+const DEGENERATE_FRAME_DETAIL = {+ 'solid-fill': 'a single flat color',+ 'fully-transparent': 'fully transparent',+ 'near-empty': 'almost no detail',+};++/**+ * Degenerate-frame gate for a sprite candidate (issue #4173).+ *+ * A blank candidate has no foreground at all, so `normalizeFromAnalysis` /+ * `recompositeOnKey` copy it straight through and it gets locked, atlased and+ * published as a real reference frame. Refuse it up front instead.+ *+ * Only a MEASURED degenerate verdict rejects: a candidate whose stats could+ * not be computed (`ok: null`) falls through untouched, so an undecodable file+ * still reaches the existing `imageError` / `INVALID_IMAGE` handling rather+ * than being mislabeled as empty.+ */+export async function assertFrameHasContent(src) {+ const stats = await describeFrameStats(src);+ if (!isDegenerateFrame(stats)) return stats;+ const detail = DEGENERATE_FRAME_DETAIL[stats.reason] || 'no content';+ throw new ServerError(+ `Candidate frame has no content (${detail}) — regenerate it before locking.`,+ { status: 422, code: 'DEGENERATE_FRAME' },+ );+}+export async function analyzeForeground(src, maskKeyHex) {+ await assertFrameHasContent(src);const key = hexToRgb(maskKeyHex);const { data, info } = await sharp(src).flatten({ background: { r: 255, g: 255, b: 255 } })diff --git a/server/services/sprites/normalize.test.js b/server/services/sprites/normalize.test.jsindex 20e2088e21..672547d0a0 100644--- a/server/services/sprites/normalize.test.js+++ b/server/services/sprites/normalize.test.js@@ -20,6 +20,10 @@ afterAll(() => rmSync(dir, { recursive: true, force: true }));const MAGENTA = { r: 255, g: 0, b: 255 };const GREEN = { r: 0, g: 255, b: 0 };+// Within MASK_CHANNEL_THRESHOLD (40) of MAGENTA on every channel, so it never+// registers as foreground — but it is real variance, so the degenerate-frame+// gate (#4173) still passes the image through to the mask.+const NEAR_KEY = { r: 245, g: 20, b: 245 };// 64×64 key-color canvas with a green rectangle at x∈[20,30), y∈[10,30).async function writeCandidate(path, { bg = MAGENTA, fg = GREEN } = {}) {@@ -143,12 +147,54 @@ describe('normalizeAnchorFrame', () => {it('copies through an image with no detectable foreground', async () => {const src = join(dir, 'blank.png');const dest = join(dir, 'blank-out.png');- await writeCandidate(src, { fg: MAGENTA }); // rectangle same as background+ // Real variance, but every pixel sits within the mask threshold of the key+ // (max-channel diff 20 < 40), so nothing is detected as foreground. Still a+ // legitimate frame as far as the degenerate-frame gate is concerned.+ await writeCandidate(src, { fg: NEAR_KEY });const result = await normalizeAnchorFrame(src, dest, { maskKeyHex: '#FF00FF', canvasKeyHex: '#FF00FF' });expect(result.copiedThrough).toBe(true);const img = await readRaw(dest);expect(img.width).toBe(64); // untouched original});++ it('refuses a candidate that is a single flat color (#4173)', async () => {+ const src = join(dir, 'flat.png');+ const dest = join(dir, 'flat-out.png');+ await writeCandidate(src, { fg: MAGENTA }); // rectangle same as background+ await expect(normalizeAnchorFrame(src, dest, { maskKeyHex: '#FF00FF', canvasKeyHex: '#FF00FF' }))+ .rejects.toMatchObject({ code: 'DEGENERATE_FRAME', status: 422 });+ });++ it('refuses a fully transparent candidate (#4173)', async () => {+ const src = join(dir, 'transparent.png');+ const dest = join(dir, 'transparent-out.png');+ const w = 64; const h = 64;+ const buf = Buffer.alloc(w * h * 4);+ for (let p = 0; p < w * h; p++) {+ buf[p * 4] = p % 256; buf[p * 4 + 1] = (p * 3) % 256; buf[p * 4 + 2] = (p * 7) % 256;+ buf[p * 4 + 3] = 0; // varied colour under a zero alpha+ }+ await sharp(buf, { raw: { width: w, height: h, channels: 4 } }).png().toFile(src);+ await expect(normalizeAnchorFrame(src, dest, { maskKeyHex: '#FF00FF', canvasKeyHex: '#FF00FF' }))+ .rejects.toMatchObject({ code: 'DEGENERATE_FRAME' });+ });++ it('does NOT refuse a very dark but real candidate — the gate is not a quality judge', async () => {+ const src = join(dir, 'dark.png');+ const dest = join(dir, 'dark-out.png');+ const w = 64; const h = 64;+ const buf = Buffer.alloc(w * h * 3);+ for (let y = 0; y < h; y++) {+ for (let x = 0; x < w; x++) {+ const i = (y * w + x) * 3;+ const v = Math.round(((x + y) / (2 * (w - 1))) * 12); // 0..12 of 255+ buf[i] = v; buf[i + 1] = v; buf[i + 2] = v + (x % 2);+ }+ }+ await sharp(buf, { raw: { width: w, height: h, channels: 3 } }).png().toFile(src);+ await expect(normalizeAnchorFrame(src, dest, { maskKeyHex: '#FF00FF', canvasKeyHex: '#FF00FF' }))+ .resolves.toBeTruthy();+ });});describe('extractForegroundPalette', () => {@@ -239,8 +285,15 @@ describe('recompositeOnKey (#2979 — turnaround sheet re-key)', () => {it('copies through a sheet with no detectable foreground', async () => {const src = join(dir, 'sheet-blank.png');const dest = join(dir, 'sheet-blank-out.png');- await writeCandidate(src, { fg: MAGENTA });+ await writeCandidate(src, { fg: NEAR_KEY });const analysis = await analyzeForeground(src, '#FF00FF');expect((await recompositeOnKey(analysis, src, dest, '#00FF00')).copiedThrough).toBe(true);});++ it('refuses a flat sheet before it can be locked and atlased (#4173)', async () => {+ const src = join(dir, 'sheet-flat.png');+ await writeCandidate(src, { fg: MAGENTA });+ await expect(analyzeForeground(src, '#FF00FF'))+ .rejects.toMatchObject({ code: 'DEGENERATE_FRAME' });+ });});diff --git a/server/services/visionTest.frameGuard.test.js b/server/services/visionTest.frameGuard.test.jsnew file mode 100644index 0000000000..71bafcb60d--- /dev/null+++ b/server/services/visionTest.frameGuard.test.js@@ -0,0 +1,81 @@+/**+ * Degenerate-frame gate on the vision path (issue #4173): a blank screenshot+ * must never be forwarded to a vision provider, because that spends a real+ * (often paid) call asking a model to describe a solid black square.+ */+import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest';+import { mkdtemp, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import sharp from 'sharp';++let dir;++vi.mock('./providers.js', () => ({+ getProviderById: vi.fn(async () => ({+ id: 'lmstudio', type: 'api', endpoint: 'http://127.0.0.1:1234/v1', defaultModel: 'vision-model',+ })),+}));+vi.mock('../lib/fetchWithTimeout.js', () => ({ fetchWithTimeout: vi.fn() }));+vi.mock('./ollamaManager.js', () => ({ ensureProviderReady: vi.fn(async () => ({ success: true })) }));+vi.mock('./visionCli.js', () => ({ describeImageViaCli: vi.fn() }));+vi.mock('../lib/aiToolkit/internal/endpointGuard.js', () => ({+ assertSecretEndpoint: vi.fn(),+ evaluateSecretEndpoint: vi.fn(() => ({ ok: true })),+}));+vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ PATHS: { ...actual.PATHS, screenshots: '/unused-in-this-suite' },+ resolveScreenshot: vi.fn((name) => join(dir, name)),+ };+});++import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';+import { testVision } from './visionTest.js';++const SIDE = 64;+const write = async (name, buffer) => { await writeFile(join(dir, name), buffer); return name; };+const solid = (background) => sharp({ create: { width: SIDE, height: SIDE, channels: 3, background } }).png().toBuffer();+const real = () => {+ const raw = Buffer.alloc(SIDE * SIDE * 3);+ for (let p = 0; p < SIDE * SIDE; p++) {+ raw[p * 3] = p % 256; raw[p * 3 + 1] = (p * 3) % 256; raw[p * 3 + 2] = (p * 7) % 256;+ }+ return sharp(raw, { raw: { width: SIDE, height: SIDE, channels: 3 } }).png().toBuffer();+};++beforeAll(async () => { dir = await mkdtemp(join(tmpdir(), 'portos-visiontest-')); });+afterAll(async () => { await rm(dir, { recursive: true, force: true }); });+beforeEach(() => { vi.clearAllMocks(); });++describe('testVision degenerate-frame gate', () => {+ it('refuses to spend a vision call on a solid-fill screenshot', async () => {+ const name = await write('blank.png', await solid({ r: 0, g: 0, b: 0 }));+ await expect(testVision({ imagePath: name, prompt: 'what is this?', expectedContent: 'cat' }))+ .rejects.toThrow(/no content/i);+ expect(fetchWithTimeout).not.toHaveBeenCalled();+ });++ it('still sends a real screenshot to the provider', async () => {+ const name = await write('real.png', await real());+ vi.mocked(fetchWithTimeout).mockResolvedValue({+ ok: true,+ json: async () => ({ choices: [{ message: { content: 'a cat' } }] }),+ });+ const result = await testVision({ imagePath: name, prompt: 'what is this?', expectedContent: 'cat' });+ expect(fetchWithTimeout).toHaveBeenCalled();+ expect(result.success).toBe(true);+ });++ it('does not block an undecodable screenshot on this gate — that is a different failure', async () => {+ const name = await write('garbage.png', Buffer.from('not a png'));+ vi.mocked(fetchWithTimeout).mockResolvedValue({+ ok: true,+ json: async () => ({ choices: [{ message: { content: 'unreadable' } }] }),+ });+ await testVision({ imagePath: name, prompt: 'what is this?', expectedContent: 'unreadable' });+ expect(fetchWithTimeout).toHaveBeenCalled();+ });+});diff --git a/server/services/visionTest.js b/server/services/visionTest.jsindex 646ae4edf7..2536d3de01 100644--- a/server/services/visionTest.js+++ b/server/services/visionTest.js@@ -9,6 +9,7 @@ import { readFile, readdir } from 'fs/promises';import { extname } from 'path';import { getProviderById } from './providers.js';import { PATHS, resolveScreenshot } from '../lib/fileUtils.js';+import { describeFrameStats, isDegenerateFrame } from '../lib/imageFrameStats.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';import { describeImageViaCli } from './visionCli.js';@@ -51,6 +52,14 @@ async function loadImageAsBase64(imagePath) {}const buffer = await readFile(fullPath);+ // Degenerate-frame gate (#4173): never spend a vision-provider call asking a+ // model to describe a solid black square. Only a MEASURED degenerate verdict+ // refuses — an image whose stats could not be computed (`ok: null`) is sent+ // as before, because "couldn't measure" is not "has no content".+ const stats = await describeFrameStats(buffer);+ if (isDegenerateFrame(stats)) {+ throw new Error(`image has no content (${stats.reason}) — not sending it to the vision provider`);+ }const mimeType = getMimeType(fullPath);return `data:${mimeType};base64,${buffer.toString('base64')}`;}