Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fail agy/grok renders that draw the image with code instead of generating it

[._.]/ Adam Eivy3b9b4dfbe29a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c700b3d139..56cf5ce9ad 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,10 @@
# Unreleased Changes
+## Image Gen
+
+- **Agy and Grok can no longer hand back a picture they drew themselves.** When Antigravity's `generate_image` backend hit its quota (HTTP 429 "you have exhausted your capacity on this model"), agy did not fail the render — it took the instruction "save a PNG at this path" literally and wrote a script that drew a stand-in with a plotting library instead. The result was a real PNG, so it passed the signature check and landed in the gallery looking like a generated image: flat vector shapes, placeholder circles, overlapping labels, and the prompt's own pixel dimensions captioned into the artwork. Both cloud CLIs are now told that only the image tool may produce the image and that reporting a failure is the correct outcome when it can't; a scratch-directory check discards any render whose agent left a drawing script behind. The agy prompt also stopped naming exact pixel dimensions — `generate_image` only exposes an aspect ratio, so that was an instruction it could never satisfy, which is precisely what made reaching for code look reasonable.
+- **The usage page now has an Image Gen card, observed rather than guessed.** The provider cards only ever showed the *agent* model's quota, which is a different bucket from the image backend — when the imagen backend returned 429, the Antigravity card was still reporting the Gemini 5-hour group at 78% left, so nothing on the page explained why renders were failing. These CLIs expose no image-quota API at all (Antigravity's `/usage` panel has rows for `GEMINI MODELS` and `CLAUDE AND GPT MODELS` and nothing for images), so the new card reports what PortOS actually watched happen: a real 0%-left meter with the provider's own stated reset time once a render is refused, and a plain 24h render count otherwise — never a reassuring "100% left" bar for a number nobody can measure. A block clears as soon as a render succeeds again, not merely when the stated reset passes. The card appears only when a cloud image backend is enabled; local renders use your own GPU and have no quota.
+
## Internal
- **[issue-3250] Stabilize Music Video project-selection tests under CI load.** Project-selection coverage now waits for the requested project to be available before opening its board, preventing intermittent false failures.
diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsx
index 2359370a7e..6cdc33f8c6 100644
--- a/client/src/pages/UsagePage.jsx
+++ b/client/src/pages/UsagePage.jsx
@@ -65,6 +65,18 @@ function UsageMeter({ limit }) {
);
}
+// Small labelled stat, used for both the per-period activity counts and the
+// `metrics[]` a backend returns when its quota can't be queried at all.
+function StatTile({ label, value, detail }) {
+ return (
+ <div className="bg-port-bg border border-port-border rounded-lg p-2.5">
+ <div className="text-xs text-gray-400 mb-0.5">{label}</div>
+ <div className="text-sm text-white">{value}</div>
+ {detail && <div className="text-[10px] sm:text-xs text-gray-500 mt-0.5">{detail}</div>}
+ </div>
+ );
+}
+
// One subscription-quota card per enabled provider family. Providers with no
// queryable usage surface (supported: false) render a muted note, never an
// error; a supported adapter that failed transiently shows a soft warning.
@@ -91,27 +103,42 @@ function ProviderQuotaCard({ quota }) {
{quota.supported && !quota.error && (
<div className="space-y-2">
- {quota.limits?.length > 0 ? (
+ {quota.limits?.length > 0 && (
<div>
{quota.limits.map((limit) => (
<UsageMeter key={limit.key} limit={limit} />
))}
</div>
- ) : (
+ )}
+
+ {!quota.limits?.length && !quota.metrics?.length && (
<div className="text-gray-500 text-sm">No rate-limit data reported</div>
)}
+ {/* Backends with no queryable quota report observed counts instead of
+ a meter — a percentage we cannot measure must not be invented. */}
+ {quota.metrics?.length > 0 && (
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
+ {quota.metrics.map((m) => (
+ <StatTile key={m.key} label={m.label} value={m.value} detail={m.detail} />
+ ))}
+ </div>
+ )}
+
{quota.activity?.length > 0 && (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2 pt-1">
{quota.activity.map((a) => (
- <div key={a.period} className="bg-port-bg border border-port-border rounded-lg p-2.5">
- <div className="text-xs text-gray-400 mb-0.5">{a.period}</div>
- <div className="text-sm text-white">
- {formatCompactCount(a.requests)} requests
- <span className="mx-2 text-gray-600">•</span>
- {formatCompactCount(a.sessions)} sessions
- </div>
- </div>
+ <StatTile
+ key={a.period}
+ label={a.period}
+ value={(
+ <>
+ {formatCompactCount(a.requests)} requests
+ <span className="mx-2 text-gray-600">•</span>
+ {formatCompactCount(a.sessions)} sessions
+ </>
+ )}
+ />
))}
</div>
)}
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 8f2d655aa5..7fc26be3de 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -101,6 +101,7 @@ import { initWritersRoomSceneImageHook } from './writersRoomSceneImageHook.js';
import { initMusicVideoSceneImageHook } from './musicVideoSceneImageHook.js';
import { initMusicVideoSceneVideoHook } from './musicVideoSceneVideoHook.js';
import { initCreativeDirectorMusicBedHook } from './creativeDirectorMusicBedHook.js';
+import { initImageGenQuotaHook } from './imageGenQuota.js';
import { initSpriteReferenceImageHook } from './spriteReferenceImageHook.js';
import { initCreativeDirectorSceneImageHook } from './creativeDirectorSceneImageHook.js';
import { initComicPagesFilenameHook } from './pipeline/comicPagesFilenameHook.js';
@@ -461,6 +462,10 @@ const initMediaJobDependentHooks = () => {
// audio render onto its project's `musicBed` field on completion, even if
// the requesting client unmounted mid-render (#1928).
initCreativeDirectorMusicBedHook();
+ // Image-gen quota observation — the cloud image backends expose no quota API,
+ // so the Usage page's Image Gen card is built from renders we watched succeed
+ // or get refused. One bus subscriber, never per-provider edits.
+ initImageGenQuotaHook();
// Sprite reference-candidate hook — copies a completed reference/anchor
// render into the sprite record's reference/candidates/ with a generation
// sidecar (#2896).
diff --git a/server/services/imageGen/agy.js b/server/services/imageGen/agy.js
index fee39e5d0f..733d9f239b 100644
--- a/server/services/imageGen/agy.js
+++ b/server/services/imageGen/agy.js
@@ -25,7 +25,8 @@ 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 { AGY_IMAGEGEN_IMAGE_MODEL, IMAGE_GEN_MODE, nearestAgyAspectRatio } from './modes.js';
+import { checkFabrication, noFabricationClause } from './fabricationGuard.js';
+import { AGY_IMAGEGEN_IMAGE_MODEL, IMAGE_GEN_MODE, IMAGE_TOOL_NAMES, nearestAgyAspectRatio } from './modes.js';
import { withSpawnCwdEnv } from '../../lib/spawnCwd.js';
const AGY_TIMEOUT_MS = (() => {
@@ -130,6 +131,8 @@ export function listModels({ agyPath } = {}) {
});
}
+const AGY_TOOL = IMAGE_TOOL_NAMES[IMAGE_GEN_MODE.AGY];
+
const AGY_NO_IMAGE_HINT =
'Agy returned no image — the selected model may not expose generate_image, or the model declined. Check Settings → Image Gen → Agy CLI.';
@@ -146,14 +149,18 @@ export function buildAgyPrompt({ prompt, negativePrompt, width, height, stagingP
// requested size. Directed on its own line so it reads as an instruction to
// the agent rather than as image content: anything that lands inside the
// tool's `Prompt` becomes part of what gets drawn.
+ //
+ // The exact pixel dimensions are deliberately NOT stated. AspectRatio is the
+ // only size knob generate_image exposes (#3231), so a "target dimensions"
+ // line is an instruction the tool cannot satisfy — which invites the agent to
+ // reach for code that can. It also leaks into the artwork: the render that
+ // exposed this failure mode captioned itself "DIMENSIONS: 832 x 1216 (2:3)".
const ratio = nearestAgyAspectRatio(width, height);
- const dimensions = Number(width) > 0 && Number(height) > 0
- ? `\nTarget dimensions: ${Number(width)}×${Number(height)} pixels.`
- : '';
const aspect = ratio ? `\nPass AspectRatio "${ratio}" to the tool.` : '';
- return `Use your built-in generate_image tool to generate exactly one image.
-Image prompt: ${prompt.trim()}${avoid}${dimensions}${aspect}
+ return `Use your built-in ${AGY_TOOL} tool to generate exactly one image.
+Image prompt: ${prompt.trim()}${avoid}${aspect}
Save the generated image as a PNG file at exactly this path: ${stagingPath}
+${noFabricationClause(AGY_TOOL)}
Do not create any other files, do not modify any code or workspace content, and do not run unrelated tools. When the file is written, you are done.`;
}
@@ -299,6 +306,16 @@ async function runAgy(job, jobId, bin, args, {
const prefix = harvested.invalid ? 'Agy wrote a non-image file at the directed path. ' : '';
return finalizeError(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 finalizeError(job, jobId, proc, `${fabricated} ${noImageReason(stdoutTail)}`);
+ }
if (harvested.format === 'png') {
await rename(stagingPath, outputPath).catch(async () => {
await copyFile(stagingPath, outputPath);
@@ -323,7 +340,7 @@ async function runAgy(job, jobId, bin, args, {
console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (agy)`);
const result = { filename, path: `/data/images/${filename}` };
broadcastSse(job, { type: 'complete', result });
- imageGenEvents.emit('completed', { generationId: jobId, path: result.path, filename });
+ imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.AGY, generationId: jobId, path: result.path, filename });
closeJobAfterDelay(jobs, jobId);
} catch (err) {
removeScratch();
@@ -339,7 +356,7 @@ const finalizeError = (job, jobId, proc, reason) => {
activeJobs.delete(jobId);
console.log(`❌ agy image generation failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);
broadcastSse(job, { type: 'error', error: reason });
- imageGenEvents.emit('failed', { generationId: jobId, error: reason });
+ imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.AGY, generationId: jobId, error: reason });
closeJobAfterDelay(jobs, jobId);
};
diff --git a/server/services/imageGen/agy.test.js b/server/services/imageGen/agy.test.js
index 9c3e59518b..ce92d6fb96 100644
--- a/server/services/imageGen/agy.test.js
+++ b/server/services/imageGen/agy.test.js
@@ -143,6 +143,49 @@ describe('agy image provider', () => {
expect(sidecar.imageModel).toBe('imagen-3.0-generate-002');
});
+ // agy is a coding agent: when generate_image is quota-exhausted it can still
+ // satisfy "a PNG exists at this path" by writing a script that draws one. The
+ // bytes pass the signature gate, so the residue left by the script is what
+ // catches it (see fabricationGuard.js).
+ it('rejects a PNG the agent drew with code instead of generate_image', async () => {
+ const failed = vi.fn();
+ imageGenEvents.on('failed', failed);
+ const job = await agy.generateImage({ prompt: 'a character sheet' });
+ const png = Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ Buffer.from('drawn by matplotlib'),
+ ]);
+ await writeFile(stagingPathFor(job.jobId), png);
+ await writeFile(join(tmpdir(), `portos-agy-${job.jobId}`, 'render_sheet.py'), 'import matplotlib');
+ await closeChild(0, 0);
+
+ const deadline = Date.now() + 3000;
+ while (Date.now() < deadline && failed.mock.calls.length === 0) {
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ expect(failed).toHaveBeenCalledTimes(1);
+ expect(failed.mock.calls[0][0].error).toContain('drawn by code');
+ expect(existsSync(join(FAKE_IMAGES_DIR, job.filename))).toBe(false);
+ });
+
+ it('forbids fabricating the image by any other means', () => {
+ const prompt = agy._internals.buildAgyPrompt({ prompt: 'a fox', stagingPath: '/tmp/out.png' });
+ expect(prompt).toContain('Only the generate_image tool may produce this image');
+ expect(prompt).toContain('Reporting the failure is the correct outcome');
+ });
+
+ it('never states pixel dimensions, which generate_image cannot honor', () => {
+ // AspectRatio is the only size knob (#3231). A "target dimensions" line is
+ // an unsatisfiable instruction that invites the agent to reach for code —
+ // and it leaked into the artwork as a rendered caption.
+ const prompt = agy._internals.buildAgyPrompt({
+ prompt: 'a fox', stagingPath: '/tmp/out.png', width: 832, height: 1216,
+ });
+ expect(prompt).not.toContain('832');
+ expect(prompt).not.toContain('1216');
+ expect(prompt).toContain('Pass AspectRatio "2:3" to the tool.');
+ });
+
// The tool's AspectRatio parameter defaults to '1:1', so a render that names
// only pixel dimensions comes back square no matter what was asked for —
// measured against agy 1.1.8 (1024×1024 with no ratio, 1376×768 with 16:9).
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index 548be147f0..3413ab57c4 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -18,6 +18,15 @@
* because not every Codex account has access to the `image_gen` tool. When
* disabled the dispatcher rejects up front; this module assumes it's enabled
* by the time generateImage() is called.
+ *
+ * No fabrication guard here, unlike agy/grok (see imageGen/fabricationGuard.js):
+ * those direct the agent to write a PNG at a path PortOS chose, which is a goal
+ * a coding agent can satisfy by drawing one when the image tool is unavailable.
+ * Codex is never told a destination — we harvest from its own
+ * `~/.codex/generated_images/<session-id>/` dir and the session JSONL, and it
+ * has no scratch cwd — so there is no "a file exists at path X" criterion for a
+ * fabricated image to meet. If Codex ever gains a directed staging path, it
+ * needs the guard too.
*/
import { spawn } from 'child_process';
@@ -382,7 +391,7 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cle
console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (codex)`);
const result = { filename, path: `/data/images/${filename}` };
broadcastSse(job, { type: 'complete', result });
- imageGenEvents.emit('completed', { generationId: jobId, path: `/data/images/${filename}`, filename });
+ imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.CODEX, generationId: jobId, path: `/data/images/${filename}`, filename });
closeJobAfterDelay(jobs, jobId);
} catch (err) {
finalizeError(job, jobId, proc, `Codex post-exit handler failed: ${err?.message || err}`);
@@ -404,7 +413,7 @@ const finalizeError = (job, jobId, proc, reason) => {
activeJobs.delete(jobId);
console.log(`❌ codex image generation failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);
broadcastSse(job, { type: 'error', error: reason });
- imageGenEvents.emit('failed', { generationId: jobId, error: reason });
+ imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.CODEX, generationId: jobId, error: reason });
closeJobAfterDelay(jobs, jobId);
};
diff --git a/server/services/imageGen/external.js b/server/services/imageGen/external.js
index 731ef8741a..b1586410a7 100644
--- a/server/services/imageGen/external.js
+++ b/server/services/imageGen/external.js
@@ -146,7 +146,7 @@ export async function generateImage({ sdapiUrl, prompt, negativePrompt, width, h
} catch (err) {
stopPolling();
activeJob = null;
- imageGenEvents.emit('failed', { generationId, error: 'Network error contacting image generation service' });
+ imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.EXTERNAL, generationId, error: 'Network error contacting image generation service' });
throw err;
}
stopPolling();
@@ -154,14 +154,14 @@ export async function generateImage({ sdapiUrl, prompt, negativePrompt, width, h
if (!res.ok) {
const errBody = await res.text().catch(() => '');
activeJob = null;
- imageGenEvents.emit('failed', { generationId, error: `SD API error ${res.status}` });
+ imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.EXTERNAL, generationId, error: `SD API error ${res.status}` });
throw new Error(`SD API error ${res.status}: ${errBody.slice(0, 200)}`);
}
const data = await res.json();
if (!data.images?.length) {
activeJob = null;
- imageGenEvents.emit('failed', { generationId, error: 'No images returned' });
+ imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.EXTERNAL, generationId, error: 'No images returned' });
throw new Error('SD API returned no images');
}
@@ -176,6 +176,6 @@ export async function generateImage({ sdapiUrl, prompt, negativePrompt, width, h
const path = `/data/images/${filename}`;
console.log(`🖼️ Image saved: ${filename}`);
activeJob = null;
- imageGenEvents.emit('completed', { generationId, path, filename });
+ imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.EXTERNAL, generationId, path, filename });
return { generationId, filename, path, mode: IMAGE_GEN_MODE.EXTERNAL, model };
}
diff --git a/server/services/imageGen/fabricationGuard.js b/server/services/imageGen/fabricationGuard.js
new file mode 100644
index 0000000000..1860b3433e
--- /dev/null
+++ b/server/services/imageGen/fabricationGuard.js
@@ -0,0 +1,82 @@
+/**
+ * Image Gen — cloud-CLI "don't draw it yourself" guard.
+ *
+ * agy and grok are general coding agents that happen to expose a server-side
+ * image tool. Both are driven by a single-turn prompt that names the tool and
+ * a staging path to write. That framing has a failure mode: the agent reads
+ * "a PNG exists at this path" as the success criterion, so when the image tool
+ * is unavailable — quota exhausted, plan doesn't include it, model declines —
+ * it satisfies the criterion the other way it knows how, by writing a script
+ * that draws a picture with a plotting/imaging library and saving THAT.
+ *
+ * The result is a real PNG at the directed path, so the magic-byte harvest gate
+ * accepts it and it lands in the gallery as if it were generated. Observed on
+ * 2026-07-31: an agy character-sheet render came back as flat vector shapes,
+ * placeholder circles and overlapping labels — with the prompt's own
+ * "Target dimensions: <W>x<H>" metadata rendered into the artwork as a caption.
+ * A later run of the same prompt surfaced the cause directly: HTTP 429
+ * "you have exhausted your capacity on this model ... the generate_image tool
+ * relies entirely on this backend service".
+ *
+ * Two defenses, because either alone is leaky:
+ * 1. `noFabricationClause` — make the TOOL the success criterion and failure
+ * the correct outcome, so there is no goal left to satisfy with code.
+ * 2. `checkFabrication` — a backstop over the scratch dir. Drawing an image
+ * programmatically means leaving a script (or an interpreter's cache)
+ * behind, which the prompt already forbids.
+ */
+
+import { readdir } from 'fs/promises';
+import { extname, sep } from 'path';
+
+// Source/markup extensions an agent would write to draw an image itself
+// (matplotlib/PIL scripts, canvas or SVG/HTML renderers). Deliberately narrow:
+// a CLI's own logs or JSON config in the scratch dir must not trip this.
+const CODE_EXTENSIONS = new Set([
+ '.py', '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx',
+ '.sh', '.bash', '.zsh', '.rb', '.pl', '.php', '.lua', '.r',
+ '.html', '.htm', '.svg',
+]);
+
+// Directory names an interpreter leaves behind when a script actually ran.
+const CODE_DIRS = new Set(['__pycache__', 'node_modules', 'venv', '.venv']);
+
+/**
+ * The clause that forbids producing the image by any means other than the
+ * named tool. Appended to both cloud-CLI prompts.
+ *
+ * The "report the failure instead" half matters as much as the prohibition:
+ * an agent told only "don't use code" but still measured on whether the file
+ * exists is being asked to fail at its stated goal. Naming the empty-handed
+ * outcome as correct is what makes the prohibition followable.
+ *
+ * @param {string} toolName - the provider's image tool (`generate_image`, `image_gen`)
+ */
+export const noFabricationClause = (toolName) =>
+ `Only the ${toolName} tool may produce this image. Do not draw, render, or assemble it by any other means — no code, no scripts, no plotting or imaging libraries, no HTML/SVG/canvas rendering, and no placeholder, mock-up or diagram standing in for the image. If ${toolName} is unavailable, rate-limited, refuses, or errors, write nothing at that path and report what went wrong. Reporting the failure is the correct outcome; an image produced any other way is a failed run.`;
+
+/**
+ * Scan a finished scratch directory for evidence the agent generated the image
+ * with code instead of the image tool, and return the error to fail the render
+ * with — or `null` when the run looks clean.
+ *
+ * Only source files and interpreter caches count. Unknown leftovers are
+ * ignored: a CLI writing its own session state or logs into its cwd is normal
+ * and must not fail an otherwise-good render. The staged output needs no
+ * exemption — an image extension is not in `CODE_EXTENSIONS`.
+ *
+ * @param {string} scratchDir - the throwaway cwd the CLI ran in
+ * @param {string} toolName - the image tool that should have produced the file
+ * @returns {Promise<string|null>} failure reason, or null if clean
+ */
+export async function checkFabrication(scratchDir, toolName) {
+ // Recursive listing rather than a hand-rolled walk so the rule is the same at
+ // every depth — a `scripts/draw.py` or a nested `__pycache__` counts exactly
+ // as much as one dropped beside the output.
+ const paths = await readdir(scratchDir, { recursive: true }).catch(() => []);
+ const residue = paths.filter((rel) =>
+ rel.split(sep).some((segment) => CODE_DIRS.has(segment))
+ || CODE_EXTENSIONS.has(extname(rel).toLowerCase()));
+ if (!residue.length) return null;
+ return `The image was drawn by code, not generated: the agent wrote ${residue.slice(0, 5).join(', ')} in its scratch directory instead of using ${toolName}. This usually means ${toolName} was unavailable (quota exhausted, or not on your plan) and the agent produced a stand-in picture. The file was discarded.`;
+}
diff --git a/server/services/imageGen/fabricationGuard.test.js b/server/services/imageGen/fabricationGuard.test.js
new file mode 100644
index 0000000000..ffbd7d5168
--- /dev/null
+++ b/server/services/imageGen/fabricationGuard.test.js
@@ -0,0 +1,91 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdir, mkdtemp, rm, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { checkFabrication, noFabricationClause } from './fabricationGuard.js';
+
+describe('noFabricationClause', () => {
+ it('names the tool as the only sanctioned producer', () => {
+ const clause = noFabricationClause('generate_image');
+ expect(clause).toContain('Only the generate_image tool may produce this image');
+ });
+
+ it('names the empty-handed outcome as correct', () => {
+ // Without this half the agent is still measured on "a file exists", which
+ // is exactly what drove it to draw one with code when the tool 429'd.
+ const clause = noFabricationClause('image_gen');
+ expect(clause).toContain('write nothing at that path');
+ expect(clause).toContain('Reporting the failure is the correct outcome');
+ });
+
+ it('forbids the specific substitutes an agent reaches for', () => {
+ const clause = noFabricationClause('generate_image');
+ for (const banned of ['no code', 'no scripts', 'plotting', 'SVG', 'placeholder']) {
+ expect(clause).toContain(banned);
+ }
+ });
+});
+
+describe('checkFabrication', () => {
+ let dir;
+ beforeEach(async () => {
+ dir = await mkdtemp(join(tmpdir(), 'portos-fabguard-'));
+ });
+ afterEach(async () => {
+ await rm(dir, { recursive: true, force: true });
+ });
+
+ it('passes a clean run that produced only the staged output', async () => {
+ await writeFile(join(dir, 'output.png'), 'png bytes');
+ expect(await checkFabrication(dir, 'generate_image')).toBe(null);
+ });
+
+ it('flags a drawing script left beside the output', async () => {
+ await writeFile(join(dir, 'output.png'), 'png bytes');
+ await writeFile(join(dir, 'render_sheet.py'), 'import matplotlib');
+ const reason = await checkFabrication(dir, 'generate_image');
+ expect(reason).toContain('render_sheet.py');
+ expect(reason).toContain('drawn by code');
+ expect(reason).toContain('generate_image was unavailable');
+ expect(reason).toContain('discarded');
+ });
+
+ it('flags an interpreter cache directory', async () => {
+ await mkdir(join(dir, '__pycache__'), { recursive: true });
+ expect(await checkFabrication(dir, 'image_gen')).toContain('__pycache__');
+ });
+
+ it('applies the same rule at any depth', async () => {
+ // A nested script counts exactly as much as one beside the output — the
+ // rule must not weaken with depth.
+ await mkdir(join(dir, 'scripts'), { recursive: true });
+ await writeFile(join(dir, 'scripts', 'draw.js'), 'canvas');
+ expect(await checkFabrication(dir, 'image_gen')).toContain(join('scripts', 'draw.js'));
+ });
+
+ it('flags a nested interpreter cache too', async () => {
+ await mkdir(join(dir, 'work', '__pycache__'), { recursive: true });
+ await writeFile(join(dir, 'work', '__pycache__', 'x.pyc'), 'bytecode');
+ expect(await checkFabrication(dir, 'image_gen')).toContain('__pycache__');
+ });
+
+ it('ignores a CLI writing its own session state into its cwd', async () => {
+ // A false positive here fails an otherwise-good render, so non-source
+ // leftovers must not trip the guard.
+ await writeFile(join(dir, 'output.png'), 'png bytes');
+ await writeFile(join(dir, 'session.log'), 'narration');
+ await writeFile(join(dir, '.agy-state.json'), '{}');
+ expect(await checkFabrication(dir, 'generate_image')).toBe(null);
+ });
+
+ it('returns null for a directory that no longer exists', async () => {
+ await rm(dir, { recursive: true, force: true });
+ expect(await checkFabrication(dir, 'generate_image')).toBe(null);
+ });
+
+ it('caps the listed residue so the error stays readable', async () => {
+ for (let i = 0; i < 12; i++) await writeFile(join(dir, `f${i}.py`), 'x');
+ const reason = await checkFabrication(dir, 'image_gen');
+ expect(reason.match(/f\d+\.py/g)).toHaveLength(5);
+ });
+});
diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.js
index 4523cc88b3..f49ff7c70b 100644
--- a/server/services/imageGen/grok.js
+++ b/server/services/imageGen/grok.js
@@ -26,8 +26,10 @@
* image generation. Grok exposes no image-tool-only permission mode, so the
* child is confined the ways we can: it runs with cwd set to a throwaway
* per-job scratch directory (relative-path tool ops and default file writes
- * land there, and the whole dir is removed on every terminal path), and the
- * staged output is signature-sniffed before it is accepted into the gallery.
+ * land there, and the whole dir is removed on every terminal path), the staged
+ * output is signature-sniffed before it is accepted into the gallery, and that
+ * scratch dir is scanned for the script residue that betrays an image the agent
+ * drew itself rather than generated (see fabricationGuard.js).
*/
import { spawn } from 'child_process';
@@ -42,10 +44,11 @@ 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 { checkFabrication, noFabricationClause } from './fabricationGuard.js';
import sharp from 'sharp';
import { bufferedSpawn, killProcessTree, prepareCliSpawn } from '../../lib/bufferedSpawn.js';
import { ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../../lib/grok.js';
-import { IMAGE_GEN_MODE, describeFidelity, nearestAspectRatio } from './modes.js';
+import { IMAGE_GEN_MODE, describeFidelity, grokImageTool, nearestAspectRatio } from './modes.js';
import { withSpawnCwdEnv } from '../../lib/spawnCwd.js';
// 20 minutes — grok's image_gen typically returns in well under a minute, but
@@ -163,7 +166,7 @@ export function buildGrokPrompt({ prompt, negativePrompt, aspectRatio, stagingPa
const task = initImagePath
? `Use your built-in image_edit tool to transform the source image at ${initImagePath} — ${describeFidelity(initImageStrength)}.\nEdit instruction: ${prompt.trim()}${avoid}`
: `Use your built-in image_gen tool to generate exactly one image.\nImage prompt: ${prompt.trim()}${avoid}`;
- return `${task}${ratio}\nSave the generated image as a PNG file at exactly this path: ${stagingPath}\nDo not create any other files, do not modify any code, and do not run any other tools beyond what is needed to generate the image and write it to that path. When the file is written, you are done.`;
+ return `${task}${ratio}\nSave the generated image as a PNG file at exactly this path: ${stagingPath}\n${noFabricationClause(grokImageTool(initImagePath))}\nDo not create any other files, do not modify any code, and do not run any other tools beyond what is needed to generate the image and write it to that path. When the file is written, you are done.`;
}
// `initImageStrength` maps to a fidelity phrase (grok's image_edit has no
@@ -242,6 +245,7 @@ export async function generateImage({
// attaches to the per-job SSE stream (mirrors codex.js/local.js).
runGrok(job, jobId, bin, args, {
useStdin, fullPrompt, cleanupPromptFile, scratchDir, stagingPath, outputPath, filename, meta, cleanC2PA, denoise,
+ toolName: grokImageTool(validInitImagePath),
}).catch((err) => {
console.log(`❌ grok run failed [${jobId.slice(0, 8)}]: ${err?.message}`);
});
@@ -257,6 +261,7 @@ export async function generateImage({
async function runGrok(job, jobId, bin, args, {
useStdin, fullPrompt, cleanupPromptFile, scratchDir, stagingPath, outputPath, filename, meta, cleanC2PA = false, denoise = false,
+ toolName = grokImageTool(null),
}) {
// A path-shaped grokPath (contains a separator) must resolve against the
// PortOS working directory NOW — the child spawns with cwd set to the
@@ -334,6 +339,15 @@ async function runGrok(job, jobId, bin, args, {
const prefix = harvested.invalid ? 'Grok wrote a non-image file at the directed path. ' : '';
return finalizeError(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 finalizeError(job, jobId, proc, `${fabricated} ${noImageReason(stdoutTail)}`);
+ }
if (harvested.format === 'png') {
// Move, not copy — the staging file is PortOS-owned and disposable,
// so rename is a metadata-only op when tmpdir and the gallery share
@@ -361,7 +375,7 @@ async function runGrok(job, jobId, bin, args, {
console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (grok)`);
const result = { filename, path: `/data/images/${filename}` };
broadcastSse(job, { type: 'complete', result });
- imageGenEvents.emit('completed', { generationId: jobId, path: `/data/images/${filename}`, filename });
+ imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.GROK, generationId: jobId, path: `/data/images/${filename}`, filename });
closeJobAfterDelay(jobs, jobId);
} catch (err) {
removeScratch();
@@ -381,7 +395,7 @@ const finalizeError = (job, jobId, proc, reason) => {
activeJobs.delete(jobId);
console.log(`❌ grok image generation failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);
broadcastSse(job, { type: 'error', error: reason });
- imageGenEvents.emit('failed', { generationId: jobId, error: reason });
+ imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.GROK, generationId: jobId, error: reason });
closeJobAfterDelay(jobs, jobId);
};
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 748dc6f4a0..1e0264ed00 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -563,7 +563,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
const reason = `Failed to spawn ${bin}: ${err.message}`;
console.log(`❌ Image generation spawn error [${jobId.slice(0, 8)}]: ${reason}`);
broadcastSse(job, { type: 'error', error: reason });
- imageGenEvents.emit('failed', { generationId: jobId, error: reason });
+ imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: reason });
activeProcess = null;
activeJob = null;
rm(stepwiseDir, { recursive: true, force: true }).catch(() => {});
@@ -808,7 +808,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
broadcastSse(job, { type: 'error', error: errorText, kind: userKind, repo: userRepo });
// 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.
- imageGenEvents.emit('failed', { generationId: jobId, error: userMessage || reason });
+ imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: userMessage || reason });
} else {
job.status = 'complete';
// Large-source regen (issue #912): the render ran at a clamped FLUX-sane
@@ -876,11 +876,11 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
// federated. The queue's own `completed` handler still fires off the
// return value below, so the job settles either way.
if (!skipSidecar) {
- imageGenEvents.emit('completed', { generationId: jobId, path: publicPath, filename, seed: actualSeed });
+ imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, path: publicPath, filename, seed: actualSeed });
} 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', { generationId: jobId, path: null, filename, seed: actualSeed, outputPath, temp: true });
+ imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, path: null, filename, seed: actualSeed, outputPath, temp: true });
}
}
closeJobAfterDelay(jobs, jobId);
diff --git a/server/services/imageGen/modes.js b/server/services/imageGen/modes.js
index d1cba366fb..70a5de2a44 100644
--- a/server/services/imageGen/modes.js
+++ b/server/services/imageGen/modes.js
@@ -31,6 +31,29 @@ export const CLOUD_IMAGE_GEN_MODES = Object.freeze([
IMAGE_GEN_MODE.AGY,
]);
+// The provider-side image tool each cloud CLI is directed to call. Single
+// source: the prompt builders name it, the fabrication guard names it when it
+// rejects a code-drawn stand-in, and the usage card labels its quota row with
+// it — six string literals before this existed. Grok is the one backend with
+// two, picked by whether the render has a source image.
+export const IMAGE_TOOL_NAMES = Object.freeze({
+ [IMAGE_GEN_MODE.AGY]: 'generate_image',
+ [IMAGE_GEN_MODE.GROK]: 'image_gen',
+ [IMAGE_GEN_MODE.CODEX]: 'image_gen',
+});
+
+/** Grok's tool depends on the direction: i2i edits go to `image_edit`. */
+export const grokImageTool = (initImagePath) => (initImagePath ? 'image_edit' : IMAGE_TOOL_NAMES[IMAGE_GEN_MODE.GROK]);
+
+/**
+ * Cloud image backends the user has enabled in Settings → Image Gen. Hoisted
+ * here so callers outside the dispatcher (the usage card) don't re-encode how
+ * a backend is enabled — `settings.imageGen[mode].enabled` was already spelled
+ * out at a dozen sites and drifts the moment enablement grows a nuance.
+ */
+export const enabledCloudImageModes = (settings) =>
+ CLOUD_IMAGE_GEN_MODES.filter((mode) => settings?.imageGen?.[mode]?.enabled === true);
+
// Modes the mediaJobQueue can run (external SD-API stays synchronous — a
// remote HTTP call with no local single-flight constraint to absorb). Single
// source for the pipeline routes' Zod enums and batch-render guards, so a
diff --git a/server/services/imageGenQuota.js b/server/services/imageGenQuota.js
new file mode 100644
index 0000000000..1f60b88484
--- /dev/null
+++ b/server/services/imageGenQuota.js
@@ -0,0 +1,257 @@
+/**
+ * Image Gen — observed quota state for the cloud-CLI backends.
+ *
+ * The cloud image backends have NO queryable quota surface. Antigravity's
+ * `/usage` panel reports only two token groups (`GEMINI MODELS`,
+ * `CLAUDE AND GPT MODELS`) — its own footnote says quota is "consumed
+ * proportionally to the cost of the tokens" — and the imagen backend that
+ * actually renders the pixels is not represented at all. Measured 2026-07-31:
+ * `generate_image` returned 429 RESOURCE_EXHAUSTED while the panel showed the
+ * Gemini 5-hour group at 78% remaining. The agent model and the image backend
+ * are separate buckets, and only one of them is reportable.
+ *
+ * So this module reports what PortOS can actually observe: it dispatches every
+ * cloud image render itself, so it sees the 429 the moment a render hits one,
+ * along with the reset time the provider states in its own error text. That is
+ * the only honest image-quota signal available — it is derived from real
+ * renders, never polled, and costs nothing.
+ *
+ * Deliberately reports NOTHING it has not observed: an un-blocked backend
+ * shows a render count, not a fabricated "100% left" meter, because a quota we
+ * cannot query is not a quota we may claim is healthy.
+ *
+ * Wiring: a single subscriber on the `imageGenEvents` bus, the same shape
+ * `mediaAssetIndex` uses for "do something for every finished image" — NOT
+ * edits in each provider's finalizer. A new backend that emits on the bus is
+ * tracked for free, and the provider suites need no mock of this module.
+ *
+ * Storage is `ephemeral-file` per docs/STORAGE.md — regenerable runtime
+ * telemetry with a hours-long horizon. Deliberately NOT excluded from backup:
+ * the file is tiny, and a restored block that no longer applies self-heals on
+ * the next successful render.
+ */
+
+import { join } from 'path';
+import { IMAGE_GEN_MODE, CLOUD_IMAGE_GEN_MODES, IMAGE_TOOL_NAMES } from './imageGen/modes.js';
+import { imageGenEvents } from './imageGenEvents.js';
+import { atomicWrite, PATHS, readJSONFileStrict } from '../lib/fileUtils.js';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+import { analyzeError, ERROR_CATEGORIES } from '../lib/aiToolkit/errorDetection.js';
+
+const STATE_FILE = () => join(PATHS.data, 'imagegen-quota.json');
+
+// Renders older than this drop out of the rolling activity window.
+const ACTIVITY_WINDOW_MS = 24 * 60 * 60 * 1000;
+// Cap the retained render log so a batch run can't grow the file without
+// bound. Both bounds do work: a batch can exceed this inside one 24h window.
+const MAX_RENDER_SAMPLES = 200;
+
+// Only the cloud CLIs spend remote image quota — local renders run on the
+// user's own GPU and external hits their own SD endpoint, so neither has
+// anything to report. Keyed off CLOUD_IMAGE_GEN_MODES rather than a second
+// hand-maintained list, so a 4th cloud backend is tracked the moment it is
+// added there. Labels mirror the client's MODE_LABELS so one backend doesn't
+// appear under two names across the UI.
+const MODE_LABELS = Object.freeze({
+ [IMAGE_GEN_MODE.AGY]: 'Agy',
+ [IMAGE_GEN_MODE.GROK]: 'Grok',
+ [IMAGE_GEN_MODE.CODEX]: 'Codex',
+});
+
+export const isQuotaTrackedImageMode = (mode) => CLOUD_IMAGE_GEN_MODES.includes(mode);
+
+const rowLabel = (mode) =>
+ `${MODE_LABELS[mode] || mode} · ${IMAGE_TOOL_NAMES[mode] || 'image tool'}`;
+
+// Single tail: two renders finishing together must not interleave their
+// read-modify-write on the shared ledger file.
+const queueQuotaWrite = createFileWriteQueue();
+
+// No in-memory mirror — the read side runs once per Usage-page load and the
+// write side once per render, so re-reading inside the queue (the domainUsage
+// convention) is cheaper than a cache plus its invalidation and test hook.
+async function readLedger() {
+ const { ok, value } = await readJSONFileStrict(STATE_FILE(), null, { logError: false });
+ // A failed/corrupt read must not read as "no renders, no block" — that would
+ // silently clear a real block and report a fake 0. Surface it to the caller.
+ if (!ok) return null;
+ return value && typeof value.modes === 'object' && value.modes !== null ? value : { modes: {} };
+}
+
+/**
+ * Parse an absolute ISO instant out of provider error text.
+ * Antigravity phrases it as `(around 2026-07-31T21:38:09Z)`. Pure.
+ */
+const parseAbsoluteReset = (text) => {
+ const m = text.match(/(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)/);
+ if (!m) return null;
+ const d = new Date(m[1]);
+ return Number.isNaN(d.getTime()) ? null : d.getTime();
+};
+
+/**
+ * Parse a relative reset window (`quota will reset in approximately 5 hours`,
+ * `try again in 30 minutes`) into an absolute epoch ms. Pure given `now`.
+ */
+const parseRelativeReset = (text, now) => {
+ const m = text.match(/(?:reset|retry|try again|available)\b[^.]{0,40}?\bin\s+(?:approximately\s+|about\s+|~\s*)?(\d+(?:\.\d+)?)\s*(second|minute|hour|day)s?/i);
+ if (!m) return null;
+ const unitMs = { second: 1000, minute: 60_000, hour: 3_600_000, day: 86_400_000 }[m[2].toLowerCase()];
+ return now + Number(m[1]) * unitMs;
+};
+
+// Image-backend refusals the shared CLI classifier doesn't cover: it keys on
+// `API Error: 429` / `rate limit` / `too many requests`, none of which match
+// the imagen backend's `429 (Resource Exhausted) ... exhausted your capacity`.
+const IMAGE_QUOTA_PATTERNS = [
+ /\b429\b/,
+ /resource[\s_-]*exhausted/i,
+ /exhausted your (?:capacity|quota)/i,
+ /quota (?:will reset|exceeded|exhausted)/i,
+ /out of (?:quota|credits)/i,
+ /insufficient[\s_-]*quota/i,
+];
+
+// Categories from the shared classifier that mean "refused for quota reasons".
+const QUOTA_CATEGORIES = new Set([
+ ERROR_CATEGORIES.RATE_LIMIT,
+ ERROR_CATEGORIES.USAGE_LIMIT,
+ ERROR_CATEGORIES.QUOTA_EXCEEDED,
+]);
+
+/**
+ * Classify a failed render's error text. Returns `{ exhausted, resetsAt }`
+ * where `resetsAt` is epoch ms or null. Pure given `now`; exported for tests.
+ *
+ * Layered on purpose: the image-specific patterns catch the backend phrasings
+ * measured here, and `analyzeError` folds in every provider phrasing the rest
+ * of the toolkit has already learned, so a new one only has to be taught once.
+ */
+export function parseImageQuotaSignal(text, { now = Date.now() } = {}) {
+ const s = String(text || '');
+ if (!s.trim()) return { exhausted: false, resetsAt: null };
+ const exhausted = IMAGE_QUOTA_PATTERNS.some((re) => re.test(s))
+ || QUOTA_CATEGORIES.has(analyzeError(s).category);
+ if (!exhausted) return { exhausted: false, resetsAt: null };
+ // Absolute wins: a provider that states both ("in ~5 hours (around <ISO>)")
+ // is more precise in the parenthetical, and it survives a slow error path.
+ return { exhausted: true, resetsAt: parseAbsoluteReset(s) ?? parseRelativeReset(s, now) };
+}
+
+/**
+ * Record the outcome of one cloud image render. Awaits the write, so tests can
+ * assert deterministically; the bus subscriber below fires it and forgets.
+ */
+export async function recordImageGenOutcome({ mode, ok, error = '', at = Date.now() } = {}) {
+ if (!isQuotaTrackedImageMode(mode)) return;
+ await queueQuotaWrite(async () => {
+ const ledger = await readLedger();
+ if (!ledger) return; // unreadable ledger — don't overwrite it with a guess
+ const entry = ledger.modes[mode] || (ledger.modes[mode] = { renders: [], blockedUntil: null });
+
+ // Epoch ms, not ISO: every read filters this array by a time window, and
+ // storing strings means re-parsing each one on every pass.
+ entry.renders = [...(entry.renders || []), { at, ok: ok === true }].slice(-MAX_RENDER_SAMPLES);
+
+ if (ok) {
+ // A render that succeeded proves the backend is serving again — clear a
+ // block that outlived its stated reset (providers round "approximately").
+ entry.blockedUntil = null;
+ } else {
+ const signal = parseImageQuotaSignal(error, { now: at });
+ if (signal.exhausted) entry.blockedUntil = signal.resetsAt;
+ }
+ await atomicWrite(STATE_FILE(), ledger);
+ });
+}
+
+let subscribed = false;
+
+/**
+ * Subscribe the quota recorder to the image-generation bus. Called once at
+ * boot from `initMediaJobDependentHooks`. Idempotent.
+ *
+ * The handlers run outside the request lifecycle (event emitter), so an
+ * uncaught throw would crash Node — each dispatch is wrapped, and a telemetry
+ * failure must never be able to fail a render.
+ */
+export function initImageGenQuotaHook() {
+ if (subscribed) return;
+ const note = (ok) => (payload) => {
+ recordImageGenOutcome({ mode: payload?.mode, ok, error: payload?.error })
+ .catch((err) => console.error(`❌ Image-gen quota hook: ${err.message}`));
+ };
+ imageGenEvents.on('completed', note(true));
+ imageGenEvents.on('failed', note(false));
+ subscribed = true;
+}
+
+/** Test-only: allow a suite to re-subscribe against fresh listeners. */
+export function __resetImageGenQuotaHookForTests() {
+ subscribed = false;
+}
+
+/**
+ * Build the usage-panel card for image-gen backends, in the same common shape
+ * the provider-quota families use.
+ *
+ * `limits[]` carries ONLY backends observed to be blocked right now — a real
+ * meter at 0% left with the provider's own reset time. Everything else is
+ * reported as a metric tile, never as an invented percentage.
+ *
+ * Returns null when no cloud image backend is enabled, so the caller simply
+ * renders no card rather than a second "not supported" state.
+ *
+ * @param {string[]} enabledModes - cloud image modes currently enabled
+ */
+export async function getImageGenQuota({ enabledModes = [], now = Date.now() } = {}) {
+ const tracked = enabledModes.filter(isQuotaTrackedImageMode);
+ if (!tracked.length) return null;
+
+ const ledger = await readLedger();
+ const cutoff = now - ACTIVITY_WINDOW_MS;
+ const limits = [];
+ const metrics = [];
+ for (const mode of tracked) {
+ const entry = ledger?.modes?.[mode] || { renders: [], blockedUntil: null };
+ const key = `imagegen-${mode}`;
+ const label = rowLabel(mode);
+ if (entry.blockedUntil > now) {
+ limits.push({
+ key,
+ label,
+ scope: 'image',
+ model: MODE_LABELS[mode] || mode,
+ percentUsed: 100,
+ percentRemaining: 0,
+ resetsAt: new Date(entry.blockedUntil).toISOString(),
+ timezone: null,
+ });
+ continue;
+ }
+ const recent = (entry.renders || []).filter((r) => r.at >= cutoff);
+ const failed = recent.filter((r) => !r.ok).length;
+ metrics.push({
+ key,
+ label,
+ value: recent.length ? `${recent.length} render${recent.length === 1 ? '' : 's'} · 24h` : 'No renders · 24h',
+ detail: failed ? `${failed} failed` : 'quota not reported by this CLI',
+ });
+ }
+
+ return {
+ family: 'imagegen',
+ label: 'Image Gen',
+ supported: true,
+ // Not a burnable quota target: these cards carry no measurable headroom,
+ // so the quota-burn candidate feed must never treat a blocked image
+ // backend as capacity to spend down.
+ burnable: false,
+ limits,
+ activity: [],
+ metrics,
+ approximate: true,
+ fetchedAt: new Date(now).toISOString(),
+ note: 'These image backends expose no quota API, so PortOS reports what it observes: a limit appears only after a render is actually refused. The CLI\'s own usage panel covers the agent model, not the image backend.',
+ };
+}
diff --git a/server/services/imageGenQuota.test.js b/server/services/imageGenQuota.test.js
new file mode 100644
index 0000000000..e0934a38c6
--- /dev/null
+++ b/server/services/imageGenQuota.test.js
@@ -0,0 +1,201 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtemp, rm } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
+
+const TEST_ROOT = await mkdtemp(join(tmpdir(), 'portos-igquota-'));
+vi.mock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ actual.PATHS.data = TEST_ROOT;
+ return actual;
+});
+
+const {
+ parseImageQuotaSignal,
+ recordImageGenOutcome,
+ getImageGenQuota,
+ isQuotaTrackedImageMode,
+ initImageGenQuotaHook,
+ __resetImageGenQuotaHookForTests,
+} = await import('./imageGenQuota.js');
+const { imageGenEvents } = await import('./imageGenEvents.js');
+
+// The verbatim shape Antigravity returned on 2026-07-31 (paths/ids redacted).
+const AGY_429 = 'Agy did not produce an image at the directed path. Agy said: "Here is the error details returned by the API: * **Error Code**: 429 (Resource Exhausted) * **Message**: You have exhausted your capacity on this model. Your quota will reset in approximately 5 hours (around 2026-07-31T21:38:09Z). Since the `generate_image` tool relies entirely on this backend service, I am currently unable to write the requested image to `/tmp/portos-agy-<id>/output.png`. Please try again after the quota resets."';
+
+beforeEach(async () => {
+ __resetImageGenQuotaHookForTests();
+ imageGenEvents.removeAllListeners();
+ await rm(join(TEST_ROOT, 'imagegen-quota.json'), { force: true });
+});
+afterEach(async () => {
+ await rm(join(TEST_ROOT, 'imagegen-quota.json'), { force: true });
+});
+
+describe('parseImageQuotaSignal', () => {
+ it('reads the exact 429 the imagen backend returned', () => {
+ const signal = parseImageQuotaSignal(AGY_429);
+ expect(signal.exhausted).toBe(true);
+ // The parenthetical absolute instant beats the "approximately 5 hours".
+ expect(new Date(signal.resetsAt).toISOString()).toBe('2026-07-31T21:38:09.000Z');
+ });
+
+ it('falls back to the relative window when no absolute time is given', () => {
+ const now = Date.parse('2026-07-31T16:38:09Z');
+ const signal = parseImageQuotaSignal('429: quota will reset in approximately 5 hours.', { now });
+ expect(signal.exhausted).toBe(true);
+ expect(new Date(signal.resetsAt).toISOString()).toBe('2026-07-31T21:38:09.000Z');
+ });
+
+ it('marks a quota block even when no reset time is stated', () => {
+ expect(parseImageQuotaSignal('RESOURCE_EXHAUSTED')).toEqual({ exhausted: true, resetsAt: null });
+ });
+
+ it('does not treat a content decline as a quota block', () => {
+ // Misreading this would show a phantom "0% left" meter with no reset.
+ const signal = parseImageQuotaSignal('Agy said: "I cannot generate that image."');
+ expect(signal.exhausted).toBe(false);
+ });
+
+ it('does not treat a crashed CLI as a quota block', () => {
+ expect(parseImageQuotaSignal('Agy generation failed: Exit code 1').exhausted).toBe(false);
+ expect(parseImageQuotaSignal('Failed to spawn agy: ENOENT').exhausted).toBe(false);
+ expect(parseImageQuotaSignal('').exhausted).toBe(false);
+ });
+});
+
+describe('isQuotaTrackedImageMode', () => {
+ it('tracks the cloud CLIs and ignores local/external', () => {
+ expect(isQuotaTrackedImageMode('agy')).toBe(true);
+ expect(isQuotaTrackedImageMode('grok')).toBe(true);
+ expect(isQuotaTrackedImageMode('codex')).toBe(true);
+ // Local renders on the user's own GPU — there is no remote quota to report.
+ expect(isQuotaTrackedImageMode('local')).toBe(false);
+ expect(isQuotaTrackedImageMode('external')).toBe(false);
+ });
+});
+
+describe('initImageGenQuotaHook', () => {
+ // The recorder rides the imageGenEvents bus rather than provider finalizers,
+ // so a backend that emits on the bus is tracked without touching its code.
+ const flush = () => new Promise((resolve) => setTimeout(resolve, 20));
+
+ it('records a refused render announced on the bus', async () => {
+ initImageGenQuotaHook();
+ imageGenEvents.emit('failed', { mode: 'agy', generationId: 'j1', error: AGY_429 });
+ await flush();
+ const card = await getImageGenQuota({ enabledModes: ['agy'] });
+ expect(card.limits[0].resetsAt).toBe('2026-07-31T21:38:09.000Z');
+ });
+
+ it('ignores a local render on the same bus', async () => {
+ initImageGenQuotaHook();
+ imageGenEvents.emit('completed', { mode: 'local', generationId: 'j2' });
+ await flush();
+ const card = await getImageGenQuota({ enabledModes: ['agy'] });
+ expect(card.metrics[0].value).toBe('No renders · 24h');
+ });
+
+ it('subscribes only once across repeated boots', async () => {
+ initImageGenQuotaHook();
+ initImageGenQuotaHook();
+ imageGenEvents.emit('completed', { mode: 'agy', generationId: 'j3' });
+ await flush();
+ const card = await getImageGenQuota({ enabledModes: ['agy'] });
+ // A double subscription would count this single render twice.
+ expect(card.metrics[0].value).toBe('1 render · 24h');
+ });
+});
+
+describe('getImageGenQuota', () => {
+ const now = Date.parse('2026-07-31T17:00:00Z');
+
+ it('renders no card at all when no cloud image backend is enabled', async () => {
+ // Local renders spend no remote quota — one "should there be a card"
+ // decision, made here, rather than a second not-supported state.
+ expect(await getImageGenQuota({ enabledModes: ['local'], now })).toBe(null);
+ expect(await getImageGenQuota({ enabledModes: [], now })).toBe(null);
+ });
+
+ it('marks the card unburnable so quota-burn never targets it', async () => {
+ // These cards carry no measurable headroom; a 0%-left image meter must not
+ // read to the quota-burn candidate feed as capacity to spend down.
+ await recordImageGenOutcome({ mode: 'agy', ok: true, at: now });
+ expect((await getImageGenQuota({ enabledModes: ['agy'], now })).burnable).toBe(false);
+ });
+
+ it('surfaces a real 0%-left meter with the provider-stated reset', async () => {
+ await recordImageGenOutcome({ mode: 'agy', ok: false, error: AGY_429, at: now });
+ const card = await getImageGenQuota({ enabledModes: ['agy'], now });
+ expect(card.limits).toHaveLength(1);
+ expect(card.limits[0]).toMatchObject({
+ label: 'Agy · generate_image',
+ percentUsed: 100,
+ percentRemaining: 0,
+ resetsAt: '2026-07-31T21:38:09.000Z',
+ });
+ });
+
+ it('reports observed render counts rather than inventing a percentage', async () => {
+ // The whole point of the card: a quota we cannot query must never render
+ // as a reassuring "100% left" meter.
+ await recordImageGenOutcome({ mode: 'agy', ok: true, at: now });
+ await recordImageGenOutcome({ mode: 'agy', ok: true, at: now });
+ const card = await getImageGenQuota({ enabledModes: ['agy'], now });
+ expect(card.limits).toEqual([]);
+ expect(card.metrics).toHaveLength(1);
+ expect(card.metrics[0].value).toBe('2 renders · 24h');
+ expect(card.metrics[0].detail).toContain('quota not reported');
+ });
+
+ it('drops the block once its stated reset has passed', async () => {
+ await recordImageGenOutcome({ mode: 'agy', ok: false, error: AGY_429, at: now });
+ const after = Date.parse('2026-07-31T21:40:00Z');
+ const card = await getImageGenQuota({ enabledModes: ['agy'], now: after });
+ expect(card.limits).toEqual([]);
+ });
+
+ it('clears a stale block as soon as a render succeeds again', async () => {
+ // Providers round "approximately", so a success is stronger evidence than
+ // the stated reset time — without this the card lies until the clock says so.
+ await recordImageGenOutcome({ mode: 'agy', ok: false, error: AGY_429, at: now });
+ await recordImageGenOutcome({ mode: 'agy', ok: true, at: now + 60_000 });
+ const card = await getImageGenQuota({ enabledModes: ['agy'], now: now + 120_000 });
+ expect(card.limits).toEqual([]);
+ });
+
+ it('does not block on a non-quota failure', async () => {
+ await recordImageGenOutcome({ mode: 'agy', ok: false, error: 'Exit code 1', at: now });
+ const card = await getImageGenQuota({ enabledModes: ['agy'], now });
+ expect(card.limits).toEqual([]);
+ expect(card.metrics[0].detail).toBe('1 failed');
+ });
+
+ it('keeps each backend independent', async () => {
+ await recordImageGenOutcome({ mode: 'agy', ok: false, error: AGY_429, at: now });
+ await recordImageGenOutcome({ mode: 'grok', ok: true, at: now });
+ const card = await getImageGenQuota({ enabledModes: ['agy', 'grok'], now });
+ expect(card.limits.map((l) => l.model)).toEqual(['Agy']);
+ expect(card.metrics.map((m) => m.label)).toEqual(['Grok · image_gen']);
+ });
+
+ it('ignores an untracked mode handed to the recorder', async () => {
+ await recordImageGenOutcome({ mode: 'local', ok: false, error: AGY_429, at: now });
+ const card = await getImageGenQuota({ enabledModes: ['agy'], now });
+ expect(card.limits).toEqual([]);
+ });
+
+ it('survives a process restart', async () => {
+ // State lives only on disk — no in-memory mirror to warm.
+ await recordImageGenOutcome({ mode: 'agy', ok: false, error: AGY_429, at: now });
+ const card = await getImageGenQuota({ enabledModes: ['agy'], now });
+ expect(card.limits[0].resetsAt).toBe('2026-07-31T21:38:09.000Z');
+ });
+
+ it('ages renders out of the 24h window', async () => {
+ await recordImageGenOutcome({ mode: 'agy', ok: true, at: now - 25 * 60 * 60 * 1000 });
+ await recordImageGenOutcome({ mode: 'agy', ok: true, at: now });
+ const card = await getImageGenQuota({ enabledModes: ['agy'], now });
+ expect(card.metrics[0].value).toBe('1 render · 24h');
+ });
+});
diff --git a/server/services/providerUsage.js b/server/services/providerUsage.js
index 76b1793d22..4fcad99fd7 100644
--- a/server/services/providerUsage.js
+++ b/server/services/providerUsage.js
@@ -6,20 +6,29 @@ import { getClaudeCodeUsage, systemTimeZone } from './claudeCodeUsage.js';
import { commandBasename, isClaudeCommand } from '../lib/providerModels.js';
import { isGrokCommand } from '../lib/grok.js';
import { scrapeTuiUsage } from '../lib/tuiUsageScrape.js';
+import { getSettings } from './settings.js';
+import { getImageGenQuota } from './imageGenQuota.js';
+import { enabledCloudImageModes } from './imageGen/modes.js';
/**
* Provider subscription-quota adapters for /devtools/usage — one card per
* enabled provider *family* (claude, codex, agy, grok), each answering "how
* much usage do I have left." Every adapter returns the common shape:
*
- * { family, label, supported, plan?, limits[], activity[], approximate,
- * fetchedAt, note?, error? }
+ * { family, label, supported, plan?, limits[], activity[], metrics?[],
+ * approximate, fetchedAt, note?, error?, burnable? }
*
* `supported: false` means the provider has no queryable usage surface at all
* (the UI renders a muted "not available" note, never an error). A supported
* adapter that fails transiently returns `error` instead of throwing so one
* broken CLI can't 500 the whole endpoint.
*
+ * `metrics[]` is for a backend whose quota cannot be queried at all: it renders
+ * as labelled stat tiles instead of a meter, so an adapter never has to invent
+ * a percentage to have something to show. `burnable: false` marks a card the
+ * quota-burn candidate feed must skip — a limit with no measurable headroom is
+ * not capacity to spend down.
+ *
* AI Provider Usage Policy: these fetches run only on user request from the
* usage page — never at server boot — and none of them consume tokens (the
* Claude `/usage` print-mode call is 0-token; the Codex adapter only reads
@@ -515,6 +524,32 @@ export async function getProviderQuotas({ refresh = false } = {}) {
const providers = Array.isArray(result) ? result : (result?.providers || []);
const enabled = providers.filter((p) => p?.enabled && p.ollamaBacked !== true);
const families = resolveEnabledFamilies(providers);
- return Promise.all(families.map((family) =>
+ const familyCards = await Promise.all(families.map((family) =>
fetchFamilyQuota(family, { refresh, providers: enabled.filter((p) => family.matches(p)) })));
+ // Image gen last: it is a derived/observed card, not a provider-family
+ // scrape, and it reads as a footnote to the model-quota cards above it. Not
+ // raced with the family scrapes — this is two small local file reads against
+ // their multi-second TUI PTY spawns, so concurrency would buy no wall-clock.
+ const imageCard = await fetchImageGenQuota();
+ return imageCard ? [...familyCards, imageCard] : familyCards;
}
+
+/**
+ * The image-gen card is keyed off the imageGen SETTINGS, not the provider
+ * registry — a cloud image backend is enabled per-mode in Settings → Image Gen,
+ * independently of whether that CLI is also an enabled agent provider. That is
+ * why it isn't a FAMILIES entry: `resolveEnabledFamilies` gates on
+ * `matches(providerConfig)` and there is no provider config to match.
+ *
+ * Never rejects — a broken read must not 500 the whole usage page, and no card
+ * is a better answer than a card asserting a quota state we failed to read.
+ */
+const fetchImageGenQuota = async () => {
+ const settings = await getSettings().catch(() => null);
+ const enabledModes = enabledCloudImageModes(settings);
+ if (!enabledModes.length) return null; // no cloud image backend → no card
+ return getImageGenQuota({ enabledModes }).catch((err) => {
+ console.error(`❌ Image-gen quota card failed: ${err?.message || err}`);
+ return null;
+ });
+};
diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.js
index 652a632537..c999b41b2f 100644
--- a/server/services/providerUsage.test.js
+++ b/server/services/providerUsage.test.js
@@ -16,6 +16,19 @@ vi.mock('./claudeCodeUsage.js', () => ({
vi.mock('../lib/tuiUsageScrape.js', () => ({
scrapeTuiUsage: vi.fn()
}));
+// The image-gen card keys off imageGen SETTINGS (a cloud image backend is
+// enabled per-mode, independently of the agent-provider registry). Default to
+// none enabled so the family assertions below stay about provider families.
+vi.mock('./settings.js', () => ({
+ getSettings: vi.fn().mockResolvedValue({ imageGen: {} })
+}));
+vi.mock('./imageGenQuota.js', () => ({
+ getImageGenQuota: vi.fn(async ({ enabledModes }) => (enabledModes.length ? {
+ family: 'imagegen', label: 'Image Gen', supported: true, burnable: false,
+ limits: [], activity: [], metrics: enabledModes.map((m) => ({ key: m, label: m, value: '0 renders · 24h' })),
+ approximate: true, fetchedAt: new Date().toISOString()
+ } : null))
+}));
import {
parseCodexRateLimits, mapCodexQuota, resolveEnabledFamilies, getProviderQuotas,
@@ -24,6 +37,8 @@ import {
import { getAllProviders } from './providers.js';
import { scrapeTuiUsage } from '../lib/tuiUsageScrape.js';
import { systemTimeZone } from './claudeCodeUsage.js';
+import { getSettings } from './settings.js';
+import { getImageGenQuota } from './imageGenQuota.js';
// Synthetic Antigravity `/usage` panel — invented values, redacted account, in
// the real rendered shape. The bar percentage is percent REMAINING; a full bar
@@ -162,6 +177,24 @@ describe('getProviderQuotas', () => {
expect(Array.isArray(quotas)).toBe(true);
expect(quotas.map((q) => q.family)).toEqual(['grok']);
});
+
+ it('adds an image-gen card when a cloud image backend is enabled', async () => {
+ // Antigravity's /usage panel reports only its token groups — the imagen
+ // backend that renders the pixels has no row there, so the image card is
+ // derived from observed renders instead (see imageGenQuota.js).
+ getAllProviders.mockResolvedValueOnce({ activeProvider: null, providers: [] });
+ getSettings.mockResolvedValueOnce({ imageGen: { agy: { enabled: true }, local: { enabled: true } } });
+ const quotas = await getProviderQuotas();
+ expect(quotas.map((q) => q.family)).toEqual(['imagegen']);
+ // Only the cloud backend is tracked — local renders spend no remote quota.
+ expect(getImageGenQuota).toHaveBeenCalledWith({ enabledModes: ['agy'] });
+ });
+
+ it('omits the image-gen card entirely when only local image gen is on', async () => {
+ getAllProviders.mockResolvedValueOnce({ activeProvider: null, providers: [] });
+ getSettings.mockResolvedValueOnce({ imageGen: { local: { enabled: true } } });
+ expect(await getProviderQuotas()).toEqual([]);
+ });
});
describe('agyRefreshToIso', () => {