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

address review (claude): stop the quota card reporting blocks it never observed

[._.]/ Adam Eivyd26cab9ed88e
diff --git a/server/services/imageGen/fabricationGuard.js b/server/services/imageGen/fabricationGuard.js
index 1860b3433e..4b40cda7e0 100644
--- a/server/services/imageGen/fabricationGuard.js
+++ b/server/services/imageGen/fabricationGuard.js
@@ -73,10 +73,29 @@ 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(() => []);
+ //
+ // A scan that FAILS is not a scan that found nothing. ENOENT is a real clean
+ // answer (the dir is gone), but EACCES/EMFILE/EIO on a directory the harvest
+ // just read a file out of means we don't know. This is a backstop, not the
+ // primary defense (the prompt clause is), and failing a legitimate render on
+ // a filesystem hiccup costs the user an image they already spent quota on —
+ // so it passes, but loudly, rather than collapsing into a silent "clean".
+ const paths = await readdir(scratchDir, { recursive: true }).catch((err) => {
+ if (err?.code !== 'ENOENT') {
+ console.error(`⚠️ Fabrication scan failed for ${toolName} (${err?.code || err?.message}) — accepting the render unchecked`);
+ }
+ return [];
+ });
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.`;
+ // This sentence is PortOS's inference, not the provider's words, and it gets
+ // appended to the CLI narration that the image-quota classifier reads. Keep
+ // it free of that classifier's trigger phrases ("quota exhausted", "429",
+ // "rate limit") — otherwise every fabrication rejection self-reports as a
+ // provider quota block, and (worse) overwrites a real one recorded earlier.
+ // The narration appended after it still carries the genuine 429 when there
+ // was one, which is the signal that should decide.
+ 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}. That usually means ${toolName} was not available to it and it 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
index ffbd7d5168..c90e7cab8d 100644
--- a/server/services/imageGen/fabricationGuard.test.js
+++ b/server/services/imageGen/fabricationGuard.test.js
@@ -46,10 +46,22 @@ describe('checkFabrication', () => {
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('generate_image');
expect(reason).toContain('discarded');
});
+ it('keeps quota-classifier trigger phrases out of its own prose', async () => {
+ // This message is PortOS's inference and gets appended to the CLI narration
+ // that imageGenQuota's classifier reads. If it carries that classifier's
+ // trigger words, every fabrication rejection self-reports as a provider
+ // quota block — and overwrites a real one recorded earlier.
+ await writeFile(join(dir, 'draw.py'), 'import matplotlib');
+ const reason = await checkFabrication(dir, 'generate_image');
+ for (const trigger of [/quota (?:will reset|exceeded|exhausted)/i, /\b429\b/, /rate.?limit/i, /resource[\s_-]*exhausted/i]) {
+ expect(trigger.test(reason)).toBe(false);
+ }
+ });
+
it('flags an interpreter cache directory', async () => {
await mkdir(join(dir, '__pycache__'), { recursive: true });
expect(await checkFabrication(dir, 'image_gen')).toContain('__pycache__');
diff --git a/server/services/imageGenQuota.js b/server/services/imageGenQuota.js
index c3e9930300..617b6342ee 100644
--- a/server/services/imageGenQuota.js
+++ b/server/services/imageGenQuota.js
@@ -36,7 +36,6 @@ import { IMAGE_GEN_MODE, CLOUD_IMAGE_GEN_MODES, IMAGE_TOOL_NAMES } from './image
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');
@@ -45,6 +44,10 @@ 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;
+// How long a block whose refusal stated no reset time stays shown. Bounds an
+// otherwise-permanent block on an install that stops rendering (a successful
+// render clears it immediately, but nothing forces one to happen).
+const UNKNOWN_BLOCK_TTL_MS = 60 * 60 * 1000;
// 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
@@ -82,11 +85,14 @@ async function readLedger() {
* 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 parseAbsoluteReset = (text, now) => {
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();
+ const at = new Date(m[1]).getTime();
+ // Narration also carries log lines and session stamps. A timestamp in the
+ // past is not a reset time — accepting one would set `blockedUntil` to an
+ // already-elapsed instant, which reads as "not blocked" downstream.
+ return Number.isNaN(at) || at <= now ? null : at;
};
/**
@@ -100,51 +106,51 @@ const parseRelativeReset = (text, now) => {
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`.
+/**
+ * Phrases that mean "the image backend refused because you are out of quota".
+ *
+ * EVERY pattern here must be anchored to quota context, because the text being
+ * classified is the model's own narration — which routinely quotes the image
+ * prompt back. A bare `\b429\b` matched "I will not draw route 429 signage";
+ * a bare "credit" would match "a wizard holding a credit card". A prompt is
+ * user content, so any pattern a prompt can satisfy by accident paints a
+ * phantom 0%-left meter on an ordinary content decline.
+ *
+ * These deliberately do NOT delegate to the toolkit's `analyzeError`. That
+ * classifier is first-match-wins and its `/billing|payment|credit|insufficient
+ * funds/` rule sits ABOVE its rate-limit rule, so "rate limit exceeded; prompt
+ * was: a wizard holding a credit card" classifies as QUOTA_EXCEEDED — meaning
+ * you cannot filter out the prompt-echo false positive by dropping that
+ * category without also dropping the real rate limit underneath it. Matching
+ * the phrases directly is order-independent and says what it means.
+ */
const IMAGE_QUOTA_PATTERNS = [
- /\b429\b/,
+ /(?:error|status|code|http)\W{0,12}429\b/i,
+ /\b429\b\W{0,40}(?:resource[\s_-]*exhausted|too many requests|rate.?limit|quota)/i,
/resource[\s_-]*exhausted/i,
/exhausted your (?:capacity|quota)/i,
/quota (?:will reset|exceeded|exhausted)/i,
/out of (?:quota|credits)/i,
/insufficient[\s_-]*quota/i,
+ /rate.?limit(?:ed|s)?\b/i,
+ /too many requests/i,
+ /hit your (?:usage )?limit/i,
];
-// Categories from the shared classifier that mean "refused for quota reasons".
-//
-// QUOTA_EXCEEDED is deliberately EXCLUDED despite the name: its pattern is
-// /billing|payment|credit|insufficient funds/, and the text classified here is
-// the model's own narration, which routinely quotes the image prompt back. A
-// render of "a wizard holding a credit card" that gets declined on content
-// grounds would match on the bare word "credit" and paint a phantom 0%-left
-// meter with no reset. RATE_LIMIT and USAGE_LIMIT key on phrases no image
-// prompt produces by accident ("429", "rate limit", "hit your usage limit").
-// The genuinely-billing image phrasings are covered precisely by
-// IMAGE_QUOTA_PATTERNS above, which requires "out of credits", not "credit".
-const QUOTA_CATEGORIES = new Set([
- ERROR_CATEGORIES.RATE_LIMIT,
- ERROR_CATEGORIES.USAGE_LIMIT,
-]);
-
/**
* 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 };
+ if (!IMAGE_QUOTA_PATTERNS.some((re) => re.test(s))) 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) };
+ // Both parsers reject an instant that isn't in the future — narration carries
+ // log/session timestamps too, and a PAST "reset" would read as "not blocked".
+ const resetsAt = parseAbsoluteReset(s, now) ?? parseRelativeReset(s, now);
+ return { exhausted: true, resetsAt };
}
/**
@@ -165,10 +171,21 @@ export async function recordImageGenOutcome({ mode, ok, error = '', at = Date.no
if (ok) {
// A render that succeeded proves the backend is serving again — clear a
// block that outlived its stated reset (providers round "approximately").
+ entry.blockedAt = null;
entry.blockedUntil = null;
} else {
const signal = parseImageQuotaSignal(error, { now: at });
- if (signal.exhausted) entry.blockedUntil = signal.resetsAt;
+ if (signal.exhausted) {
+ // `blockedAt` is what marks the backend blocked; `blockedUntil` only
+ // says WHEN it lifts and is legitimately unknown (a refusal need not
+ // state a reset). Keying "blocked" off blockedUntil alone collapsed
+ // "blocked, reset unknown" into "not blocked".
+ entry.blockedAt = at;
+ // Never downgrade a known reset to unknown: a repeat attempt during an
+ // active block typically returns a bare 429 without restating the reset
+ // the first one gave us, which would otherwise erase it.
+ entry.blockedUntil = signal.resetsAt ?? entry.blockedUntil ?? null;
+ }
}
await atomicWrite(STATE_FILE(), ledger);
});
@@ -239,10 +256,16 @@ export async function getImageGenQuota({ enabledModes = [], now = Date.now() } =
const limits = [];
const metrics = [];
for (const mode of tracked) {
- const entry = ledger?.modes?.[mode] || { renders: [], blockedUntil: null };
+ const entry = ledger.modes?.[mode] || { renders: [], blockedAt: null, blockedUntil: null };
const key = `imagegen-${mode}`;
const label = rowLabel(mode);
- if (entry.blockedUntil > now) {
+ // Blocked while the stated reset is still ahead, or — when the refusal
+ // never stated one — for a bounded window after we observed it, so an
+ // unknown-reset block still shows but can't stick forever on an install
+ // that stops rendering. A success clears it either way.
+ const blocked = entry.blockedAt
+ && (entry.blockedUntil ? entry.blockedUntil > now : now - entry.blockedAt < UNKNOWN_BLOCK_TTL_MS);
+ if (blocked) {
limits.push({
key,
label,
@@ -250,7 +273,9 @@ export async function getImageGenQuota({ enabledModes = [], now = Date.now() } =
model: MODE_LABELS[mode] || mode,
percentUsed: 100,
percentRemaining: 0,
- resetsAt: new Date(entry.blockedUntil).toISOString(),
+ // Null when the provider didn't state one — the meter renders without a
+ // "resets" line rather than showing a time we made up.
+ resetsAt: entry.blockedUntil ? new Date(entry.blockedUntil).toISOString() : null,
timezone: null,
});
continue;
diff --git a/server/services/imageGenQuota.test.js b/server/services/imageGenQuota.test.js
index e0958ce1ff..f03a90230c 100644
--- a/server/services/imageGenQuota.test.js
+++ b/server/services/imageGenQuota.test.js
@@ -19,6 +19,12 @@ const {
__resetImageGenQuotaHookForTests,
} = await import('./imageGenQuota.js');
const { imageGenEvents } = await import('./imageGenEvents.js');
+const { checkFabrication } = await import('./imageGen/fabricationGuard.js');
+
+// A real scratch dir with drawing-script residue, so the guard's actual message
+// (not a copy of it) is what gets fed to the quota classifier below.
+const FAB_DIR = await mkdtemp(join(tmpdir(), 'portos-igquota-fab-'));
+await writeFile(join(FAB_DIR, 'render_sheet.py'), 'import matplotlib');
// 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."';
@@ -57,6 +63,27 @@ describe('parseImageQuotaSignal', () => {
expect(signal.exhausted).toBe(false);
});
+ it('catches a real rate limit even when the prompt echo contains "credit"', () => {
+ // The toolkit's shared classifier is first-match-wins with its billing rule
+ // ABOVE its rate-limit rule, so filtering the prompt-echo false positive by
+ // category would have suppressed this real refusal. Match phrases directly.
+ const s = 'rate limit exceeded for image_gen; prompt was: a wizard holding a credit card';
+ expect(parseImageQuotaSignal(s).exhausted).toBe(true);
+ });
+
+ it('does not treat a bare number in the prompt as a 429', () => {
+ // `\b429\b` unanchored matched artwork descriptions.
+ expect(parseImageQuotaSignal('Agy said: "I will not draw route 429 signage."').exhausted).toBe(false);
+ });
+
+ it('ignores a past timestamp in the narration', () => {
+ // Narration carries log/session stamps. Accepting one as the reset would
+ // set blockedUntil to an elapsed instant, which reads as "not blocked".
+ const now = Date.parse('2026-07-31T17:00:00Z');
+ const s = 'Agy said: "429 Resource Exhausted. [log 2026-07-30T09:00:00Z] retry later."';
+ expect(parseImageQuotaSignal(s, { now })).toEqual({ exhausted: true, resetsAt: null });
+ });
+
it('does not treat prompt content echoed in a decline as a quota block', () => {
// The classified text is the model's own narration, which quotes the image
// prompt back. A bare "credit"/"payment" in the artwork description must
@@ -70,7 +97,7 @@ describe('parseImageQuotaSignal', () => {
expect(parseImageQuotaSignal('Render failed: you are out of credits.').exhausted).toBe(true);
});
- it('inherits rate-limit phrasings the shared CLI classifier already knows', () => {
+ it('catches the rate-limit phrasings the shared CLI classifier also knows', () => {
expect(parseImageQuotaSignal('Grok said: "too many requests, slow down"').exhausted).toBe(true);
});
@@ -165,6 +192,39 @@ describe('getImageGenQuota', () => {
expect(card.metrics[0].detail).toContain('quota not reported');
});
+ it('shows a block whose refusal stated no reset time', async () => {
+ // "blocked, reset unknown" must not collapse into "not blocked" — keying
+ // blocked-ness off blockedUntil alone did exactly that.
+ await recordImageGenOutcome({ mode: 'agy', ok: false, error: 'RESOURCE_EXHAUSTED', at: now });
+ const card = await getImageGenQuota({ enabledModes: ['agy'], now });
+ expect(card.limits).toHaveLength(1);
+ expect(card.limits[0]).toMatchObject({ percentRemaining: 0, resetsAt: null });
+ });
+
+ it('expires an unknown-reset block instead of sticking forever', async () => {
+ await recordImageGenOutcome({ mode: 'agy', ok: false, error: 'RESOURCE_EXHAUSTED', at: now });
+ const card = await getImageGenQuota({ enabledModes: ['agy'], now: now + 2 * 60 * 60 * 1000 });
+ expect(card.limits).toEqual([]);
+ });
+
+ it('does not let a repeat refusal erase the reset the first one stated', async () => {
+ // A retry during an active block returns a bare 429 without restating the
+ // reset; overwriting with null would drop the meter mid-block.
+ await recordImageGenOutcome({ mode: 'agy', ok: false, error: AGY_429, at: now });
+ await recordImageGenOutcome({ mode: 'agy', ok: false, error: '429 RESOURCE_EXHAUSTED, please try later', at: now + 60_000 });
+ const card = await getImageGenQuota({ enabledModes: ['agy'], now: now + 120_000 });
+ expect(card.limits).toHaveLength(1);
+ expect(card.limits[0].resetsAt).toBe('2026-07-31T21:38:09.000Z');
+ });
+
+ it('does not let our own fabrication message register as a provider quota block', async () => {
+ // The guard's prose is PortOS's inference, not the provider's words. If it
+ // self-classifies, every fabrication rejection fakes a quota block — and
+ // overwrites a real one.
+ const guardMsg = await checkFabrication(FAB_DIR, 'generate_image');
+ expect(parseImageQuotaSignal(guardMsg).exhausted).toBe(false);
+ });
+
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');
diff --git a/server/services/providerUsage.js b/server/services/providerUsage.js
index 4fcad99fd7..0613388f4d 100644
--- a/server/services/providerUsage.js
+++ b/server/services/providerUsage.js
@@ -545,7 +545,13 @@ export async function getProviderQuotas({ refresh = false } = {}) {
* is a better answer than a card asserting a quota state we failed to read.
*/
const fetchImageGenQuota = async () => {
- const settings = await getSettings().catch(() => null);
+ // A settings read that FAILS is not "no cloud backend enabled" — without it
+ // we can't tell which backends to report, and silently dropping the card is
+ // indistinguishable from the user running local-only. Say so in the log.
+ const settings = await getSettings().catch((err) => {
+ console.error(`❌ Image-gen quota card: could not read settings (${err?.message || err}) — card omitted`);
+ return null;
+ });
const enabledModes = enabledCloudImageModes(settings);
if (!enabledModes.length) return null; // no cloud image backend → no card
return getImageGenQuota({ enabledModes }).catch((err) => {
diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.js
index 88a4c67398..a8ba3bf736 100644
--- a/server/services/quotaBurn.js
+++ b/server/services/quotaBurn.js
@@ -159,6 +159,11 @@ export function selectBurnCandidates(quotas, config, { now = Date.now(), dispatc
.map((family) => {
const card = cards.get(family.id);
if (!card || card.supported === false || card.error) return null;
+ // A card can declare it carries no spendable headroom (`burnable: false`)
+ // — e.g. the Image Gen card, whose 0%-left meter is an OBSERVED refusal,
+ // not a measured allowance. Burning against it would dispatch work to a
+ // backend that just refused. Opt-out only: absent means burnable.
+ if (card.burnable === false) return null;
const selected = selectLimit(card, family, now);
if (!selected || selected.hours < 0 || selected.hours > family.resetWithinHours) return null;
const dispatchKey = `${family.id}:${normalizeResetAt(selected.limit, { now, timeZone: family.timeZone }).epochMs}`;
diff --git a/server/services/quotaBurn.test.js b/server/services/quotaBurn.test.js
index b329395f1c..a3ac9e270f 100644
--- a/server/services/quotaBurn.test.js
+++ b/server/services/quotaBurn.test.js
@@ -14,6 +14,20 @@ const quota = (family, resetsAt, percentRemaining = 50, extras = {}) => ({
});
describe('selectBurnCandidates', () => {
+ it('skips a card that declares itself unburnable', () => {
+ // A card can carry a 0%-left limit that is an OBSERVED refusal rather than
+ // a measured allowance (the Image Gen card) — burning against it would
+ // dispatch work to a backend that just refused. Opt-out only.
+ const candidates = selectBurnCandidates(
+ [quota('grok', '2026-07-26T18:00:00.000Z', 50, { burnable: false })],
+ config,
+ { now: NOW },
+ );
+ expect(candidates).toEqual([]);
+ // Absent `burnable` still means burnable — this must not regress every card.
+ expect(selectBurnCandidates([quota('grok', '2026-07-26T18:00:00.000Z')], config, { now: NOW })).toHaveLength(1);
+ });
+
it('selects burnable windows by reset time then priority', () => {
const candidates = selectBurnCandidates([
quota('codex', '2026-07-27T00:00:00.000Z'),