Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix the quota-burn save races, the re-enqueue loop, and the migration's enabled semantics
[._.]/ Adam Eivy8215649be1d5
diff --git a/client/src/components/quotaBurn/FamilyCard.jsx b/client/src/components/quotaBurn/FamilyCard.jsxindex 383623237d..0b0ed4696b 100644--- a/client/src/components/quotaBurn/FamilyCard.jsx+++ b/client/src/components/quotaBurn/FamilyCard.jsx@@ -30,11 +30,17 @@ export default function FamilyCard({next.splice(index + delta, 0, moved);patchJobs(next);};+ // Without a catalog there is no job type to mint, and a job with+ // `jobType: undefined` is dropped by JSON.stringify and rejected by the+ // strict PUT schema — poisoning every later save for this family until the+ // page is reloaded. The catalog fetch is best-effort (the page still renders+ // without it), so gate on it rather than minting an unsavable row.+ const canAddJob = catalog.jobTypes.length > 0;const addJob = () => patchJobs([...jobs, {id: `job-${Date.now().toString(36)}`,enabled: true,label: '',- jobType: catalog.jobTypes[0]?.id,+ jobType: catalog.jobTypes[0].id,model: null,providerId: null,params: {},@@ -100,7 +106,13 @@ export default function FamilyCard({<div className="space-y-3"><div className="flex items-center justify-between"><h3 className="text-xs uppercase tracking-wide text-gray-400">Burn plan — runs in order</h3>- <button type="button" className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline" onClick={addJob}>+ <button+ type="button"+ className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline disabled:opacity-40"+ disabled={!canAddJob}+ title={canAddJob ? 'Add a job to this plan' : 'Job catalog unavailable — reload the page'}+ onClick={addJob}+ ><Plus size={13} /> Add job</button></div>diff --git a/client/src/components/quotaBurn/JobParamField.jsx b/client/src/components/quotaBurn/JobParamField.jsxindex c98baa6f1c..dc4712c828 100644--- a/client/src/components/quotaBurn/JobParamField.jsx+++ b/client/src/components/quotaBurn/JobParamField.jsx@@ -5,7 +5,7 @@* needs to know the param KINDS, not any particular job's fields.*/-import { inputClass } from './fields';+import { NumberField, inputClass } from './fields';export default function JobParamField({ descriptor, value, onChange, options, idPrefix }) {const id = `${idPrefix}-${descriptor.key}`;@@ -41,19 +41,17 @@ export default function JobParamField({ descriptor, value, onChange, options, id}if (descriptor.kind === 'number') {+ // NumberField, not a bare input: an emptied box must not commit `0` (below+ // several server minimums) and 400 the whole coalesced save.return (- <label htmlFor={id} className="block text-xs text-gray-400">- {descriptor.label}- <input- id={id}- type="number"- min={descriptor.min}- max={descriptor.max}- className={inputClass}- value={current}- onChange={(event) => onChange(descriptor.key, Number(event.target.value))}- />- </label>+ <NumberField+ id={id}+ label={descriptor.label}+ value={current}+ min={descriptor.min}+ max={descriptor.max}+ onChange={(next) => onChange(descriptor.key, next)}+ />);}diff --git a/client/src/components/quotaBurn/JobRow.jsx b/client/src/components/quotaBurn/JobRow.jsxindex 9cf39b2f08..f6b2700cb9 100644--- a/client/src/components/quotaBurn/JobRow.jsx+++ b/client/src/components/quotaBurn/JobRow.jsx@@ -6,7 +6,8 @@* work — so the move controls are part of the configuration, not a convenience.*/-import { ArrowDown, ArrowUp, Play, Trash2 } from 'lucide-react';+import { useState } from 'react';+import { ArrowDown, ArrowUp, Check, Play, Trash2 } from 'lucide-react';import JobParamField from './JobParamField';import { inputClass } from './fields';@@ -14,6 +15,11 @@ export default function JobRow({job, index, total, catalog, pending, actionsBusy,onChange, onMove, onRemove, onRun,}) {+ // Two-click arm on delete (the repo's inline-confirm convention). A job holds+ // the family's whole free-text work prompt and nothing else stores it — a+ // stray click on the trash icon would drop it from the persisted plan with no+ // undo.+ const [armed, setArmed] = useState(false);const spec = catalog.jobTypes.find((type) => type.id === job.jobType);const idPrefix = `burn-job-${job.id}`;const setParam = (key, value) => onChange({ ...job, params: { ...job.params, [key]: value } });@@ -44,7 +50,14 @@ export default function JobRow({<button type="button" className="p-1 text-gray-400 hover:text-white disabled:opacity-30" disabled={index === 0} onClick={() => onMove(index, -1)} aria-label={`Move step ${index + 1} earlier`}><ArrowUp size={14} /></button><button type="button" className="p-1 text-gray-400 hover:text-white disabled:opacity-30" disabled={index === total - 1} onClick={() => onMove(index, 1)} aria-label={`Move step ${index + 1} later`}><ArrowDown size={14} /></button><button type="button" className="p-1 text-port-accent hover:text-white disabled:opacity-30" disabled={actionsBusy} onClick={() => onRun(job)} aria-label={`Run step ${index + 1} now`} title="Run this job now, ignoring the reset window"><Play size={14} /></button>- <button type="button" className="p-1 text-red-400 hover:text-red-300 disabled:opacity-30" onClick={() => onRemove(index)} aria-label={`Remove step ${index + 1}`}><Trash2 size={14} /></button>+ {armed ? (+ <>+ <button type="button" className="p-1 text-red-400 hover:text-red-300" onClick={() => onRemove(index)} aria-label={`Confirm removing step ${index + 1}`} title="Click to confirm — this discards the job's prompt"><Check size={14} /></button>+ <button type="button" className="text-[11px] text-gray-400 hover:text-white px-1" onClick={() => setArmed(false)}>Cancel</button>+ </>+ ) : (+ <button type="button" className="p-1 text-red-400 hover:text-red-300 disabled:opacity-30" onClick={() => setArmed(true)} aria-label={`Remove step ${index + 1}`}><Trash2 size={14} /></button>+ )}</div></div>diff --git a/client/src/components/quotaBurn/fields.jsx b/client/src/components/quotaBurn/fields.jsxindex a14bedca92..60aca58c97 100644--- a/client/src/components/quotaBurn/fields.jsx+++ b/client/src/components/quotaBurn/fields.jsx@@ -8,10 +8,23 @@* sites and had already started to drift.*/+import { useState } from 'react';+export const inputClass = 'w-full mt-1 bg-port-bg border border-port-border rounded p-2 text-white text-xs';-/** A labeled number input with an optional hint line beneath it. */+/**+ * A labeled number input with an optional hint line beneath it.+ *+ * Holds a local draft string so the box can be EMPTY mid-edit without+ * committing a value. `Number('') === 0`, and 0 is below the server minimum for+ * `checkIntervalMinutes` (5) and `maxDispatchesPerWindow` (1) — so a user who+ * clears the box to retype it, and pauses past the save debounce, would 400 the+ * request and take every other edit coalesced into that body down with it.+ * Committing only on a parseable number avoids the whole class. The draft is+ * released on blur so the field snaps back to whatever the server stored.+ */export function NumberField({ id, label, value, onChange, min, max, hint }) {+ const [draft, setDraft] = useState(null);return (<label htmlFor={id} className="block text-xs text-gray-400">{label}@@ -21,8 +34,13 @@ export function NumberField({ id, label, value, onChange, min, max, hint }) {min={min}max={max}className={inputClass}- value={value}- onChange={(event) => onChange(Number(event.target.value))}+ value={draft ?? value}+ onChange={(event) => {+ const raw = event.target.value;+ setDraft(raw);+ if (raw !== '' && Number.isFinite(Number(raw))) onChange(Number(raw));+ }}+ onBlur={() => setDraft(null)}/>{hint && <span className="block mt-1 text-[11px] text-gray-500">{hint}</span>}</label>diff --git a/client/src/pages/QuotaBurn.jsx b/client/src/pages/QuotaBurn.jsxindex ec6832523f..d4034dcbd6 100644--- a/client/src/pages/QuotaBurn.jsx+++ b/client/src/pages/QuotaBurn.jsx@@ -48,12 +48,22 @@ export default function QuotaBurn() {const [unsaved, setUnsaved] = useState(false);const [running, setRunning] = useState(false);const pendingRef = useRef(null);+ // Monotonic counter over local edits. Every server response records the value+ // it was sent at; a response is only allowed to overwrite `config` when the+ // counter hasn't moved since. Without it, a slow round-trip (the status read+ // walks every universe bible) reverts keystrokes typed while it was in+ // flight, and two overlapping saves can land out of order and leave the page+ // showing a value the server does not hold.+ const editSeqRef = useRef(0);const load = useCallback(async (refresh = false) => {+ const seq = editSeqRef.current;const data = await api.getQuotaBurn(refresh, { silent: true }).catch(() => null);if (!data) return;- setConfig(data.config);+ // `status` is derived server-side and never edited here, so it is always+ // safe to adopt; `config` is the form's own state and must not be rewound.setStatus(data.status);+ if (editSeqRef.current === seq) setConfig(data.config);}, []);useEffect(() => {@@ -70,18 +80,40 @@ export default function QuotaBurn() {const patch = pendingRef.current;pendingRef.current = null;if (!patch) return;+ const seq = editSeqRef.current;const result = await api.saveQuotaBurn(patch, { silent: true }).catch((err) => { toast.error(`Could not save: ${err.message}`); return null; });- // The server's normalization is authoritative — adopt what it stored, then- // re-read status so pending counts and skip reasons match the saved plan.- if (result) setConfig(result.config);++ if (!result) {+ // Put the patch BACK rather than dropping it. One rejected field (a 400+ // from an out-of-range value) would otherwise take every other edit+ // coalesced into the same body down with it, unrecoverably — and+ // `unsaved` must stay true so the run buttons keep reflecting that the+ // server does not have these values.+ pendingRef.current = mergeQuotaBurnPatch(patch, pendingRef.current);+ return;+ }+ // The server's normalization is authoritative — adopt what it stored, but+ // only while no newer keystroke has landed. Then re-read status so pending+ // counts and skip reasons match the saved plan.+ if (editSeqRef.current === seq) setConfig(result.config);await load();- setUnsaved(false);+ // A newer edit armed during the round-trip is still unsaved — clearing the+ // flag here would re-open "Burn now" against config the server doesn't have+ // yet, which is the exact failure the flag exists to prevent.+ if (!pendingRef.current) setUnsaved(false);}, SAVE_DEBOUNCE_MS), [load]);- useEffect(() => () => persist.cancel(), [persist]);+ useEffect(() => () => {+ persist.cancel();+ // Flush, don't drop. `cancel()` alone discards everything typed in the last+ // debounce window — navigating away 200ms after pasting a work prompt would+ // lose it silently, with nothing on screen having said it was unsaved.+ if (pendingRef.current) api.saveQuotaBurn(pendingRef.current, { silent: true }).catch(() => {});+ }, [persist]);const save = (patch) => {+ editSeqRef.current += 1;setUnsaved(true);setConfig((prev) => mergeQuotaBurnPatch(prev, patch));pendingRef.current = mergeQuotaBurnPatch(pendingRef.current, patch);diff --git a/client/src/pages/QuotaBurn.test.jsx b/client/src/pages/QuotaBurn.test.jsxindex 4370191776..6804cc0d1c 100644--- a/client/src/pages/QuotaBurn.test.jsx+++ b/client/src/pages/QuotaBurn.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, waitFor } from '@testing-library/react';+import { act, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { MemoryRouter, Route, Routes } from 'react-router';import QuotaBurn from './QuotaBurn';@@ -131,3 +131,83 @@ describe('QuotaBurn save debounce', () => {await waitFor(() => expect(screen.getByRole('button', { name: /Evaluate now/ })).not.toBeDisabled());});});++describe('QuotaBurn save races', () => {+ const deferred = () => { let resolve; const promise = new Promise((r) => { resolve = r; }); return { promise, resolve }; };++ it('does not let a slow response revert a keystroke typed while it was in flight', async () => {+ // The status read walks every universe bible, so the round-trip is long.+ // Without a sequence guard, `setConfig(result.config)` rewinds the+ // controlled input mid-typing and the character is silently lost.+ const gate = deferred();+ api.saveQuotaBurn.mockReturnValueOnce(gate.promise);+ const user = userEvent.setup();+ renderPage('/devtools/quota-burn/grok');+ const nameInput = await screen.findByLabelText('Name for step 1');+ await user.clear(nameInput);+ await user.type(nameInput, 'AB');+ await waitFor(() => expect(api.saveQuotaBurn).toHaveBeenCalledTimes(1));++ // Type again while the first PUT is still open, then let it land carrying+ // the OLD value the server normalized.+ await user.type(nameInput, 'C');+ gate.resolve({ config });+ await waitFor(() => expect(nameInput).toHaveValue('ABC'));+ });++ it('keeps the run gate closed when a newer edit is still pending', async () => {+ // Clearing `unsaved` unconditionally re-opened "Burn now" against config+ // the server does not have — dispatching a real quota-spending task with+ // the previous model.+ const gate = deferred();+ api.saveQuotaBurn.mockReturnValueOnce(gate.promise);+ const user = userEvent.setup();+ renderPage('/devtools/quota-burn/grok');+ const nameInput = await screen.findByLabelText('Name for step 1');+ await user.type(nameInput, 'X');+ await waitFor(() => expect(api.saveQuotaBurn).toHaveBeenCalledTimes(1));+ await user.type(nameInput, 'Y');+ gate.resolve({ config });++ // Let the resolved save settle, but stay inside the second edit's debounce.+ await act(async () => { await new Promise((r) => setTimeout(r, 50)); });+ expect(screen.getByRole('button', { name: /Evaluate now/ })).toBeDisabled();+ });++ it('retains the patch when the save fails so one bad field cannot eat the rest', async () => {+ // `pendingRef` was cleared before the request, so a 400 discarded every+ // edit coalesced into that body, unrecoverably.+ api.saveQuotaBurn.mockRejectedValueOnce(new Error('400'));+ const user = userEvent.setup();+ renderPage('/devtools/quota-burn/grok');+ await user.type(await screen.findByLabelText('Name for step 1'), 'Z');+ await waitFor(() => expect(api.saveQuotaBurn).toHaveBeenCalledTimes(1));++ // Still unsaved, and the next flush re-sends the retained edit.+ await waitFor(() => expect(screen.getByRole('button', { name: /Evaluate now/ })).toBeDisabled());+ await user.type(screen.getByLabelText('Name for step 1'), '!');+ await waitFor(() => expect(api.saveQuotaBurn).toHaveBeenCalledTimes(2));+ expect(api.saveQuotaBurn.mock.calls[1][0].families.grok.jobs[0].label).toContain('Z!');+ });++ it('flushes a pending edit on unmount instead of dropping it', async () => {+ // cancel() alone discards everything typed in the last debounce window —+ // navigating away 200ms after pasting a prompt lost it with no indicator.+ const user = userEvent.setup();+ const { unmount } = renderPage('/devtools/quota-burn/grok');+ await user.type(await screen.findByLabelText('Name for step 1'), 'Q');+ unmount();+ await waitFor(() => expect(api.saveQuotaBurn).toHaveBeenCalledTimes(1));+ expect(api.saveQuotaBurn.mock.calls[0][0].families.grok.jobs[0].label).toContain('Q');+ });++ it('does not commit 0 when a number field is cleared to be retyped', async () => {+ // Number('') === 0, which is below the server minimum for the interval and+ // the dispatch cap — a 400 that also discards every co-pending edit.+ const user = userEvent.setup();+ renderPage('/devtools/quota-burn/grok');+ await user.clear(await screen.findByLabelText(/Dispatch cap per window/));+ await act(async () => { await new Promise((r) => setTimeout(r, 700)); });+ expect(api.saveQuotaBurn).not.toHaveBeenCalled();+ });+});diff --git a/scripts/migrations/221-quota-burn-global-config.js b/scripts/migrations/221-quota-burn-global-config.jsindex b4d71a915f..6bd71d030f 100644--- a/scripts/migrations/221-quota-burn-global-config.js+++ b/scripts/migrations/221-quota-burn-global-config.js@@ -76,8 +76,16 @@ export function buildGlobalPlan(apps) {touchedAppIds.push(app.id);const configured = override.taskMetadata?.families;if (!configured || typeof configured !== 'object') continue;+ // The OLD shape had TWO independent switches: the task type had to be+ // enabled for the app (`isTaskTypeEnabledForApp` reads `override.enabled`)+ // AND the family had to be enabled inside `taskMetadata.families`. Reading+ // only the family flag would arm a burn on an install that configured a+ // family, tried it, then switched the whole task type off — unrequested+ // provider spend on upgrade. Both must be true.+ const appArmed = override.enabled === true;for (const [familyId, value] of Object.entries(configured)) {if (!FAMILIES.includes(familyId) || !value || typeof value !== 'object') continue;+ const armed = appArmed && value.enabled === true;const existing = families[familyId];const jobs = existing?.jobs || [];const prompt = typeof value.prompt === 'string' ? value.prompt.trim() : '';@@ -85,7 +93,10 @@ export function buildGlobalPlan(apps) {jobSeq += 1;jobs.push({id: `migrated-${jobSeq}`,- enabled: true,+ // A job carried over from an app whose burn was OFF stays off, so a+ // family armed by a different app doesn't start running this app's+ // prompt as a side effect of the merge.+ enabled: armed,label: `${app.name || app.id} burn work`,jobType: 'agent-prompt',// The family-level `model` was the agent's model in the old shape;@@ -101,16 +112,27 @@ export function buildGlobalPlan(apps) {},});}- // First app in file order owns the window settings — see the conflict- // note above. Later apps contribute only their jobs.- families[familyId] = existing ? { ...existing, jobs } : {- enabled: value.enabled === true,+ const windowSettings = {providerId: value.providerId || null,scope: typeof value.scope === 'string' ? value.scope : null,resetWithinHours: Number.isFinite(Number(value.resetWithinHours)) ? Number(value.resetWithinHours) : 24,reservePercent: Number.isFinite(Number(value.reservePercent)) ? Number(value.reservePercent) : 0,maxDispatchesPerWindow: Number.isFinite(Number(value.maxDispatchesPerWindow)) ? Number(value.maxDispatchesPerWindow) : 5,priority: Number.isFinite(Number(value.priority)) ? Number(value.priority) : 0,+ };+ if (!existing) {+ families[familyId] = { enabled: armed, ...windowSettings, jobs };+ continue;+ }+ // Two apps configured the same family. `enabled` is OR'd — an install+ // that had this family burning keeps burning it, regardless of which app+ // happens to come first in apps.json. The window settings come from the+ // first ARMED contributor (falling back to the first contributor at all),+ // so a stale disabled config can't quietly halve a live cap.+ families[familyId] = {+ ...existing,+ ...(armed && !existing.enabled ? windowSettings : {}),+ enabled: existing.enabled || armed,jobs,};}@@ -118,10 +140,14 @@ export function buildGlobalPlan(apps) {if (!Object.keys(families).length) return { config: null, touchedAppIds };return {config: {- // Master switch on only when at least one family was actually enabled —- // an install that configured but never enabled a family stays silent.+ // Master switch on only when at least one family was actually armed — an+ // install that configured but never enabled a family stays silent.enabled: Object.values(families).some((family) => family.enabled === true),- checkIntervalMinutes: 30,+ // The old shape re-probed on `recheckCron: '0 */12 * * *'`. Carrying that+ // cadence across (rather than the new 30-minute default) keeps an+ // upgraded install at ~2 provider scrapes a day instead of 48 — each of+ // which spawns a multi-second TUI child per enabled family.+ checkIntervalMinutes: 720,families,},touchedAppIds,diff --git a/scripts/migrations/221-quota-burn-global-config.test.js b/scripts/migrations/221-quota-burn-global-config.test.jsindex 517dc7d0ae..897279a985 100644--- a/scripts/migrations/221-quota-burn-global-config.test.js+++ b/scripts/migrations/221-quota-burn-global-config.test.js@@ -4,10 +4,13 @@ import { tmpdir } from 'os';import { join } from 'path';import migration, { buildGlobalPlan } from './221-quota-burn-global-config.js';-const app = (id, families, extras = {}) => ({+// `enabled: true` on the OVERRIDE is the old shape's task-type switch — the one+// `isTaskTypeEnabledForApp` read. It is independent of the per-family flag, and+// the migration requires both.+const app = (id, families, extras = {}, overrideExtras = { enabled: true }) => ({id,name: `App ${id}`,- taskTypeOverrides: { 'quota-burn': { taskMetadata: { families, ...extras } } },+ taskTypeOverrides: { 'quota-burn': { ...overrideExtras, taskMetadata: { families, ...extras } } },});describe('buildGlobalPlan', () => {@@ -128,3 +131,43 @@ describe('migration 221 up()', () => {expect(plan.families.grok.jobs).toEqual([]);});});++describe('buildGlobalPlan enabled semantics', () => {+ it('does not arm a family whose TASK TYPE was switched off', async () => {+ // The old shape had two independent switches: `override.enabled` (read by+ // isTaskTypeEnabledForApp) and the per-family flag. Reading only the family+ // flag arms a burn the user had explicitly turned off — unrequested+ // provider spend on upgrade.+ const { config } = buildGlobalPlan([+ app('a1', { grok: { enabled: true, prompt: 'Refactor X' } }, {}, { enabled: false }),+ ]);+ expect(config.enabled).toBe(false);+ expect(config.families.grok.enabled).toBe(false);+ expect(config.families.grok.jobs[0].enabled).toBe(false);+ });++ it('ORs enabled across apps so a live burn survives regardless of file order', () => {+ // First-app-wins on `enabled` silently stopped a running burn when a stale+ // disabled config happened to sort first.+ const disabled = app('a1', { codex: { enabled: false, prompt: 'old', maxDispatchesPerWindow: 2 } }, {}, { enabled: false });+ const live = app('a2', { codex: { enabled: true, prompt: 'current', maxDispatchesPerWindow: 20 } });+ for (const apps of [[disabled, live], [live, disabled]]) {+ const { config } = buildGlobalPlan(apps);+ expect(config.families.codex.enabled).toBe(true);+ expect(config.enabled).toBe(true);+ // Window settings come from the ARMED contributor, so a stale disabled+ // config can't quietly halve a live cap.+ expect(config.families.codex.maxDispatchesPerWindow).toBe(20);+ // Both prompts survive, but only the armed app's job is enabled.+ expect(config.families.codex.jobs.map((job) => job.enabled).sort()).toEqual([false, true]);+ }+ });++ it('carries the old 12-hourly recheck cadence, not the new 30-minute default', () => {+ // The old recheckCron was '0 */12 * * *'. Defaulting a migrated install to+ // 30 minutes takes it from ~2 provider scrapes a day to 48, each spawning a+ // multi-second TUI child per enabled family.+ const { config } = buildGlobalPlan([app('a1', { grok: { enabled: true, prompt: 'x' } })]);+ expect(config.checkIntervalMinutes).toBe(720);+ });+});diff --git a/server/lib/quotaBurnConfig.test.js b/server/lib/quotaBurnConfig.test.jsindex 4dcf812a77..d42d98f784 100644--- a/server/lib/quotaBurnConfig.test.js+++ b/server/lib/quotaBurnConfig.test.js@@ -49,11 +49,14 @@ describe('normalizeQuotaBurnJob', () => {});it('keeps scalar params and strips nested blobs and prototype keys', () => {- const job = normalizeQuotaBurnJob({- jobType: 'agent-prompt',- params: { appId: 'a1', maxEntries: 5, openPR: false, mode: null, nested: { a: 1 }, __proto__: { polluted: true } },- });+ // `JSON.parse`, not an object literal: `{ __proto__: … }` in a literal sets+ // [[Prototype]] rather than creating an own property, so Object.entries+ // never sees it and the assertion would pass with the guard deleted. This+ // is the shape the config file actually arrives in.+ const params = JSON.parse('{"appId":"a1","maxEntries":5,"openPR":false,"mode":null,"__proto__":"x","constructor":"y","prototype":"z","nested":{"a":1}}');+ const job = normalizeQuotaBurnJob({ jobType: 'agent-prompt', params });expect(job.params).toEqual({ appId: 'a1', maxEntries: 5, openPR: false, mode: null });+ expect(Object.prototype.polluted).toBeUndefined();});});diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.jsindex f2386252b5..3b32eefbc4 100644--- a/server/services/quotaBurn.js+++ b/server/services/quotaBurn.js@@ -102,8 +102,15 @@ export function burnBudgetRemaining(limit, family) {* `charge: false` so it never eats the automatic budget.*/export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}, bypassGates = false } = {}) {- if (!family.enabled) return { skipReason: 'disabled' };- if (!familyIsActionable(family)) return { skipReason: 'no enabled jobs configured' };+ // The two "switched off" gates. A forced run passes both: `enabled` on the+ // family and on a job governs the UNATTENDED loop, and the user clicking ▶ on+ // a specific row is a more specific instruction than a checkbox they set+ // earlier. Everything below — no provider, unreadable quota, unburnable card+ // — is a fact about the world and holds even under force.+ if (!bypassGates) {+ if (!family.enabled) return { skipReason: 'disabled' };+ if (!familyIsActionable(family)) return { skipReason: 'no enabled jobs configured' };+ }if (!card) return { skipReason: 'no enabled provider in this family' };if (card.supported === false) return { skipReason: 'provider has no queryable quota surface' };if (card.error) return { skipReason: `quota read failed: ${card.error}` };@@ -113,6 +120,14 @@ export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}// just refused. Opt-out only: absent means burnable.if (card.burnable === false) return { skipReason: 'provider reports no spendable headroom' };+ // Distinguish "your scope filter matched nothing" from "the provider states+ // no reset time". `scope` is a free-text field on the page, so a typo (`weekly`+ // against a card whose windows are `week`/`month`) otherwise reads as a fault+ // in the quota adapter and the family silently never burns.+ if (family.scope && !(card.limits || []).some((limit) => limit.scope === family.scope)) {+ const available = [...new Set((card.limits || []).map((limit) => limit.scope).filter(Boolean))];+ return { skipReason: `no window matches scope "${family.scope}"${available.length ? ` (this provider has: ${available.join(', ')})` : ''}` };+ }const selected = selectLimit(card, family, now);// A window with no readable reset time is unknowable, not merely closed — a// forced run can't invent one either, so this gate holds even under bypass.diff --git a/server/services/quotaBurnJobs/universeBibleImages.js b/server/services/quotaBurnJobs/universeBibleImages.jsindex 31b6cba690..e8d995fa44 100644--- a/server/services/quotaBurnJobs/universeBibleImages.js+++ b/server/services/quotaBurnJobs/universeBibleImages.js@@ -17,6 +17,7 @@ import { getUniverse, listUniverses } from '../universeBuilder.js';import { getWorldCategoryKeys } from '../universeBuilder/sanitize.js';import { renderUniverseJobs } from '../universeBuilderRender.js';import { CLOUD_IMAGE_GEN_MODES } from '../imageGen/modes.js';+import { getQuotaBurnInFlight, recordQuotaBurnInFlight } from '../quotaBurnStore.js';import { QUOTA_BURN_BOUNDS } from '../../lib/quotaBurnConfig.js';const CANON_TRUNKS = ['characters', 'places', 'objects'];@@ -92,47 +93,92 @@ async function loadUniverses(params) {}/**- * Rows this job would render next, capped to `maxEntries`, plus the total- * backlog so the page can show "10 of 143".+ * Rows this job would render next, plus the total backlog so the page can say+ * "10 of 143".+ *+ * ONE universe per run, capped to `maxEntries`: `run` makes a single+ * `renderUniverseJobs` call, which provisions one collection and one run+ * record. Spreading the budget across several universes (as an earlier version+ * did) produced a cap the run never honored and a status line that advertised+ * more universes than it touched.+ *+ * `inFlight` is the set of `<universeId>:<label>` keys this job has already+ * enqueued recently. `imageRefs` only fills in when a render COMPLETES, and a+ * cloud render routinely outlives the 5–720 minute tick interval — so without+ * this the next cycle re-selects the same entries and enqueues them again,+ * spending the whole window cap re-rendering the same handful and making zero+ * progress on the backlog.*/-async function collect(params) {+async function collect(params, inFlight = new Set()) {const max = Math.min(ENTRY_BOUNDS.max, Math.max(ENTRY_BOUNDS.min, Number(params?.maxEntries) || ENTRY_BOUNDS.default));const scope = typeof params?.scope === 'string' ? params.scope : 'all';const universes = await loadUniverses(params);- const batches = [];+ let picked = null;let total = 0;for (const universe of universes) {- const rows = findMissingImageEntries(universe, { scope });+ // Labels are what `compilePrompts` selects on and they are NOT unique+ // (nothing dedupes them on write), so a case-insensitive dedupe here keeps+ // one row from expanding into several renders and blowing past the cap.+ const rows = dedupeByLabel(findMissingImageEntries(universe, { scope }))+ .filter((row) => !inFlight.has(inFlightKey(universe.id, row.label)));total += rows.length;- if (!rows.length) continue;- batches.push({ universe, rows });- }- // Cap ACROSS universes, taking whole universes in list order until the budget- // is spent: one render batch is one `renderUniverseJobs` call against one- // universe, so splitting the cap finer would mean several batches per run and- // several collections provisioned for a single burn.- const picked = [];- let budget = max;- for (const batch of batches) {- if (budget <= 0) break;- picked.push({ universe: batch.universe, rows: batch.rows.slice(0, budget) });- budget -= Math.min(budget, batch.rows.length);+ if (!rows.length || picked) continue;+ picked = { universe, rows: rows.slice(0, max) };}return { picked, total, max };}-export async function countPending({ params } = {}) {- const collected = await collect(params);+export const inFlightKey = (universeId, label) => `${universeId}:${String(label).toLowerCase()}`;++/**+ * One row per case-insensitive label within a category/trunk. `compilePrompts`+ * matches a selection entry against EVERY variation whose label matches+ * case-insensitively, so two entries sharing a label (legal — no writer dedupes+ * them) turn one selected row into two enqueued renders, one of which may+ * already have an image.+ */+function dedupeByLabel(rows) {+ const seen = new Set();+ return rows.filter((row) => {+ const key = `${row.kind}:${row.categoryKey || ''}:${String(row.label).toLowerCase()}`;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+}++/**+ * The image backend this job would render through, or null when it cannot+ * resolve one it is willing to use.+ *+ * A family with no cloud image mode of its own (`claude` — it renders no+ * images) must NOT silently fall through to the install default: the renders+ * would spend a DIFFERENT provider's image quota while this family's window+ * expires unused and its dispatch cap is charged for the privilege. Pinning the+ * backend to the burning family is the entire point of the job, so a family+ * that can't be pinned needs an explicit `params.mode` or nothing happens.+ */+export function resolveRenderMode({ params, family }) {+ if (typeof params?.mode === 'string' && params.mode) return params.mode;+ return CLOUD_IMAGE_GEN_MODES.includes(family?.id) ? family.id : null;+}++export async function countPending({ params, family } = {}) {+ if (!resolveRenderMode({ params, family })) {+ return { count: 0, detail: `${family?.id} renders no images — pick a render backend on this job` };+ }+ const inFlight = await getQuotaBurnInFlight();+ const collected = await collect(params, inFlight);const { picked, total } = collected;- const universeCount = picked.length;+ const next = picked?.rows.length || 0;return {count: total,// Handed back to run() by the runner so the bible scan happens once per// dispatch instead of twice — see the registry's hook contract.context: collected,detail: total- ? `${total} bible ${total === 1 ? 'entry has' : 'entries have'} no image (${universeCount} universe${universeCount === 1 ? '' : 's'} queued next)`- : 'every bible entry already has an image',+ ? `${total} bible ${total === 1 ? 'entry has' : 'entries have'} no image — ${next} queued next from "${picked.universe.name}"`+ : 'every bible entry already has an image or is already queued',};}@@ -145,17 +191,17 @@ export async function countPending({ params } = {}) {* burn a different provider's.*/export async function run({ params, job, family, context } = {}) {+ const mode = resolveRenderMode({ params, family });+ if (!mode) return { dispatched: false, reason: `${family?.id} renders no images — pick a render backend on this job` };+// Reuse the probe's scan when the runner supplied it; the page's force path// calls run() with no probe, so fall back to scanning here.- const { picked, total, max } = context ?? await collect(params);- if (!picked.length) return { dispatched: false, reason: 'no bible entries are missing images' };+ const { picked, total, max } = context ?? await collect(params, await getQuotaBurnInFlight());+ if (!picked) return { dispatched: false, reason: 'no bible entries are missing images' };- const familyMode = CLOUD_IMAGE_GEN_MODES.includes(family?.id) ? family.id : undefined;- const mode = (typeof params?.mode === 'string' && params.mode) || familyMode;- const batch = picked[0];- const { selection, canonSelection, sheetSelection } = buildRenderSelection(batch.rows);+ const { selection, canonSelection, sheetSelection } = buildRenderSelection(picked.rows);- const result = await renderUniverseJobs(batch.universe.id, {+ const result = await renderUniverseJobs(picked.universe.id, {promptMode: 'all',selection,canonSelection,@@ -165,10 +211,16 @@ export async function run({ params, job, family, context } = {}) {cloudModel: job?.model || undefined,}, (err) => err);- console.log(`🔥 Quota-burn rendered ${result.promptCount} bible image(s) for "${batch.universe.name}" via ${result.mode}`);+ // Stamp the entries as enqueued BEFORE reporting success. `imageRefs` only+ // fills in when the render completes, so this cooldown is the only thing+ // stopping the next cycle from re-selecting the same entries and spending the+ // window's whole cap re-rendering them.+ await recordQuotaBurnInFlight(picked.rows.map((row) => inFlightKey(picked.universe.id, row.label)));++ console.log(`🔥 Quota-burn rendered ${result.promptCount} bible image(s) for "${picked.universe.name}" via ${result.mode}`);return {dispatched: true,- summary: `Queued ${result.promptCount} image render${result.promptCount === 1 ? '' : 's'} for "${batch.universe.name}" via ${result.mode}`,- detail: { universeId: batch.universe.id, runId: result.runId, jobIds: result.jobIds, mode: result.mode, backlog: total, cap: max },+ summary: `Queued ${result.promptCount} image render${result.promptCount === 1 ? '' : 's'} for "${picked.universe.name}" via ${result.mode}`,+ detail: { universeId: picked.universe.id, runId: result.runId, jobIds: result.jobIds, mode: result.mode, backlog: total, cap: max },};}diff --git a/server/services/quotaBurnJobs/universeBibleImages.test.js b/server/services/quotaBurnJobs/universeBibleImages.test.jsindex ac4f609857..35cef392c5 100644--- a/server/services/quotaBurnJobs/universeBibleImages.test.js+++ b/server/services/quotaBurnJobs/universeBibleImages.test.js@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { buildRenderSelection, findMissingImageEntries } from './universeBibleImages.js';+import { buildRenderSelection, countPending, findMissingImageEntries, inFlightKey, resolveRenderMode } from './universeBibleImages.js';const universe = {id: 'u1',@@ -55,3 +55,42 @@ describe('buildRenderSelection', () => {});});});++describe('resolveRenderMode', () => {+ it('refuses to fall through to the install default for a family with no image backend', () => {+ // `claude` renders no images. Falling through would spend a DIFFERENT+ // provider's image quota while claude's window expires unused — and charge+ // claude's dispatch cap for it, the exact inversion the pin exists to stop.+ expect(resolveRenderMode({ family: { id: 'claude' }, params: {} })).toBeNull();+ expect(resolveRenderMode({ family: { id: 'codex' }, params: {} })).toBe('codex');+ // An explicit pin on the job always wins.+ expect(resolveRenderMode({ family: { id: 'claude' }, params: { mode: 'grok' } })).toBe('grok');+ });+});++describe('countPending', () => {+ it('reports zero (with a fixable reason) when the family has no render backend', async () => {+ await expect(countPending({ params: {}, family: { id: 'claude' } }))+ .resolves.toMatchObject({ count: 0, detail: expect.stringContaining('renders no images') });+ });+});++describe('label deduping', () => {+ it('collapses entries that share a label case-insensitively', () => {+ // compilePrompts matches a selection entry against EVERY variation whose+ // label matches case-insensitively, and nothing dedupes labels on write —+ // so one selected row would enqueue two renders, one of them re-rendering+ // an entry that already has an image, and blow past maxEntries.+ const dupes = {+ id: 'u2',+ categories: { vehicles: { variations: [+ { id: 'a', label: 'Skiff', imageRefs: [] },+ { id: 'b', label: 'skiff', imageRefs: [] },+ ] } },+ };+ const { selection } = buildRenderSelection(findMissingImageEntries(dupes));+ expect(selection.vehicles).toHaveLength(2);+ // The job's own collect() dedupes before selecting — pinned via the export.+ expect(inFlightKey('u2', 'Skiff')).toBe(inFlightKey('u2', 'skiff'));+ });+});diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.jsindex 092eefb7ec..05178e8446 100644--- a/server/services/quotaBurnRunner.js+++ b/server/services/quotaBurnRunner.js@@ -31,8 +31,18 @@ let tickTimer = null;let running = false;let lastRunAt = null;-const enabledJobs = (family, jobId = null) =>- (family.jobs || []).filter((job) => job?.enabled !== false && (!jobId || job.id === jobId));+/**+ * The jobs a cycle will consider, in plan order.+ *+ * `jobId` scopes to one named job. When it is named AND the run was forced, the+ * job's own `enabled` checkbox is ignored: the user just clicked ▶ on that+ * exact row, which is a more specific instruction than the checkbox they set+ * earlier. Without this, clicking ▶ on a paused job is a silent no-op reported+ * as "no pending work".+ */+const selectJobs = (family, { jobId = null, force = false } = {}) =>+ (family.jobs || []).filter((job) =>+ (!jobId || job.id === jobId) && (job?.enabled !== false || (jobId && force)));/*** Walk a candidate's plan in order and run the first job with pending work.@@ -44,9 +54,9 @@ const enabledJobs = (family, jobId = null) =>* and `run` needs the very same scan to know what to render. Without the* passthrough that multi-megabyte read happened twice per dispatch.*/-async function dispatchFromCandidate(candidate, { jobId = null } = {}) {+async function dispatchFromCandidate(candidate, { jobId = null, force = false } = {}) {const attempts = [];- for (const job of enabledJobs(candidate.family, jobId)) {+ for (const job of selectJobs(candidate.family, { jobId, force })) {const pending = await countJobPending({ job, family: candidate.family });if (!(pending.count > 0)) {attempts.push({ jobId: job.id, jobType: job.jobType, skipped: pending.detail || 'no pending work' });@@ -85,7 +95,11 @@ export async function runQuotaBurnCycle(options = {}) {async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null, force = false }) {const finish = async (entry) => {- lastRunAt = Date.now();+ // Only a SCHEDULED cycle advances the interval clock. A manual "Evaluate+ // now" that reports "no burnable window" would otherwise push the next+ // automatic cycle a full interval out — on a 12-hour interval, one curiosity+ // click can defer the tick past the reset the feature exists to spend.+ if (trigger === 'scheduled') lastRunAt = Date.now();await recordQuotaBurnRun({ trigger, ...entry });return entry;};@@ -103,7 +117,13 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,// spawns a multi-second TUI scrape per enabled family; with no actionable// family configured that scrape could never produce a dispatch, and it would// otherwise run every `checkIntervalMinutes` forever.- if (!Object.values(config.families).some(familyIsActionable)) {+ //+ // A forced run of a NAMED job is exempt: `familyIsActionable` requires an+ // enabled family with an enabled job, but ▶ on a paused job (or a paused+ // family) is exactly the case the force path exists to serve — gating it here+ // would make the click a silent no-op before selection ever ran.+ const targeted = force && familyId;+ if (!targeted && !Object.values(config.families).some(familyIsActionable)) {return finish({ dispatched: false, reason: 'no families enabled' });}@@ -123,8 +143,13 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,}).filter((candidate) => !familyId || candidate.family.id === familyId);if (!candidates.length) {+ // Scoped to the family the user asked about, and NOT filtered to enabled+ // families: when someone force-runs a job on a family whose checkbox is+ // off, "disabled" IS the answer — reporting a different family's verdict+ // instead (or claiming it is "ready" when it did not run) leaves them with+ // no path to the control they need.const reasons = evaluateFamilies(quotas, config, { dispatches })- .filter(({ family }) => family.enabled)+ .filter(({ family }) => (familyId ? family.id === familyId : family.enabled)).map(({ family, skipReason }) => `${family.id}: ${skipReason || 'ready'}`);return finish({dispatched: false,@@ -132,8 +157,10 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,});}+ const attempts = [];for (const candidate of candidates) {- const outcome = await dispatchFromCandidate(candidate, { jobId });+ const outcome = await dispatchFromCandidate(candidate, { jobId, force });+ attempts.push(...outcome.attempts.map((entry) => ({ familyId: candidate.family.id, ...entry })));if (!outcome.dispatched) continue;// Charge the window only once work actually started. `runBurnJob` reports a// decline rather than throwing, and a declined job never reaches here — so@@ -154,10 +181,18 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,});}+ // Report what each job actually said. Collapsing every non-dispatch to "no+ // job had pending work" asserts something usually false — a job that DID have+ // work and declined ("an identical burn task is already running", "managed+ // app app-x no longer exists", "no enabled CLI/TUI provider in the grok+ // family") is the actionable case, and it was the one being thrown away.+ const detail = attempts.map((entry) => `${entry.jobId}: ${entry.skipped}`).join('; ');return finish({dispatched: false,familyId: candidates[0].family.id,- reason: `no job in the ${candidates[0].family.id} plan had pending work`,+ reason: detail+ ? `nothing dispatched — ${detail}`+ : `no enabled job in the ${candidates[0].family.id} plan`,});}@@ -205,10 +240,33 @@ export async function getQuotaBurnStatus({ refresh = false } = {}) {return { config, status: { running, families, runs } };}+/**+ * When the last SCHEDULED cycle ran, in ms — from memory once this process has+ * run one, otherwise from the persisted run log.+ *+ * Reading the log is what makes `checkIntervalMinutes` mean anything across a+ * restart. `lastRunAt` is in-process, so on a bare `null` the very first tick+ * after boot is always "due": a PM2 restart, a self-update, or a crash-loop+ * would each fire a full cycle (a multi-second TUI scrape per family, plus a+ * possible dispatch) ~60s later, no matter how long the configured interval is+ * — pacing a 12-hourly plan into minutes, bounded only by the window cap.+ */+async function lastScheduledRunAt() {+ if (lastRunAt) return lastRunAt;+ const runs = await getQuotaBurnRuns().catch(() => []);+ const previous = runs.find((entry) => entry?.trigger === 'scheduled' && entry.at);+ const parsed = previous ? Date.parse(previous.at) : NaN;+ // Cache it so a restart pays the log read once, not every minute. An+ // unreadable/absent log leaves it null and the next tick runs — the correct+ // fail-open for "we have no idea when we last ran".+ if (Number.isFinite(parsed)) lastRunAt = parsed;+ return lastRunAt;+}+async function tick() {const config = await getQuotaBurnConfig().catch(() => null);if (!config?.enabled) return;- const dueAt = (lastRunAt || 0) + config.checkIntervalMinutes * 60_000;+ const dueAt = (await lastScheduledRunAt() || 0) + config.checkIntervalMinutes * 60_000;if (Date.now() < dueAt) return;await runQuotaBurnCycle({ trigger: 'scheduled' });}@@ -231,6 +289,9 @@ export function startQuotaBurnScheduler() {console.log('🔥 Quota-burn loop armed (off unless enabled in Quota Burn settings)');}+/** Test seam — one interval tick, without waiting on the timer. */+export const __tickQuotaBurn = tick;+/** Test seam — disarms the timer and clears the in-process cycle state. */export function __resetQuotaBurnRunner() {if (tickTimer) clearInterval(tickTimer);diff --git a/server/services/quotaBurnRunner.test.js b/server/services/quotaBurnRunner.test.jsindex 8e10dd1eb8..eeec806e01 100644--- a/server/services/quotaBurnRunner.test.js+++ b/server/services/quotaBurnRunner.test.js@@ -44,7 +44,7 @@ vi.mock('./quotaBurn.js', async (importActual) => ({}));const { normalizeQuotaBurnConfig } = await import('../lib/quotaBurnConfig.js');-const { getQuotaBurnStatus, runQuotaBurnCycle, __resetQuotaBurnRunner } = await import('./quotaBurnRunner.js');+const { getQuotaBurnStatus, runQuotaBurnCycle, __tickQuotaBurn, __resetQuotaBurnRunner } = await import('./quotaBurnRunner.js');const card = (family, percentRemaining = 50) => ({family, label: family, supported: true,@@ -130,7 +130,10 @@ describe('runQuotaBurnCycle', () => {state.pending = { first: { count: 0, detail: 'all rendered' }, second: { count: 0, detail: 'no app' } };const result = await runQuotaBurnCycle();expect(result.dispatched).toBe(false);- expect(result.reason).toMatch(/no job in the grok plan had pending work/);+ // The per-job reasons are the actionable part — collapsing them to one+ // fixed string asserted something usually false.+ expect(result.reason).toMatch(/first: all rendered/);+ expect(result.reason).toMatch(/second: no app/);expect(state.runs[0]).toMatchObject({ trigger: 'scheduled', dispatched: false });});@@ -204,3 +207,98 @@ describe('getQuotaBurnStatus', () => {expect(codex.jobs.every((job) => job.pending === null)).toBe(true);});});++describe('run-now targeting', () => {+ it('force-runs a job whose enabled checkbox is off', async () => {+ // Clicking ▶ on a paused job is a more specific instruction than the+ // checkbox set earlier; filtering it out made the click a silent no-op+ // reported as "no pending work".+ state.config = plan({ families: { grok: { enabled: true, jobs: [{ id: 'paused', enabled: false, jobType: 'agent-prompt' }] } } });+ state.pending = { paused: { count: 1 } };+ const result = await runQuotaBurnCycle({ trigger: 'manual', familyId: 'grok', jobId: 'paused', force: true });+ expect(result.dispatched).toBe(true);+ expect(state.ran.map((entry) => entry.jobId)).toEqual(['paused']);+ });++ it('still skips a disabled job on an ordinary scheduled cycle', async () => {+ state.config = plan({ families: { grok: { enabled: true, jobs: [{ id: 'paused', enabled: false, jobType: 'agent-prompt' }] } } });+ state.pending = { paused: { count: 1 } };+ // Nothing enabled to run ⇒ not actionable ⇒ no quota scrape at all.+ await expect(runQuotaBurnCycle()).resolves.toMatchObject({ dispatched: false });+ expect(state.ran).toEqual([]);+ });++ it('force-runs a job in a family whose own checkbox is off', async () => {+ // Both 'switched off' gates govern the UNATTENDED loop; an explicit click on+ // one row outranks them, exactly as it outranks the window/reserve/cap gates.+ state.config = normalizeQuotaBurnConfig({+ enabled: true,+ families: { grok: { enabled: false, jobs: [{ id: 'j', enabled: true, jobType: 'agent-prompt' }] } },+ });+ state.pending = { j: { count: 1 } };+ const result = await runQuotaBurnCycle({ trigger: 'manual', familyId: 'grok', jobId: 'j', force: true });+ expect(result.dispatched).toBe(true);+ expect(state.recorded).toEqual([]);+ });++ it('reports the REQUESTED family\'s verdict, not another family\'s', async () => {+ // Reporting a different (enabled) family's verdict left the user with no+ // path to the control they actually needed.+ state.config = normalizeQuotaBurnConfig({+ enabled: true,+ families: {+ grok: { enabled: true, jobs: [{ id: 'j', enabled: true, jobType: 'agent-prompt' }] },+ claude: { enabled: true, jobs: [{ id: 'k', enabled: true, jobType: 'agent-prompt' }] },+ },+ });+ // grok has NO provider card — a fact about the world, so force can't pass it.+ state.quotas = [card('claude')];+ const result = await runQuotaBurnCycle({ trigger: 'manual', familyId: 'grok', jobId: 'j', force: true });+ expect(result.reason).toMatch(/grok: no enabled provider in this family/);+ expect(result.reason).not.toMatch(/claude/);+ });+});++describe('interval clock', () => {+ it('does not let a manual run defer the next scheduled cycle', async () => {+ // finish() used to stamp lastRunAt for every trigger, so one "Evaluate now"+ // pushed the automatic cycle a full interval out — on a 12-hour interval+ // that can skip the reset the feature exists to spend.+ state.pending = { first: { count: 1 } };+ await runQuotaBurnCycle({ trigger: 'manual' });+ const { getProviderQuotas } = await import('./providerUsage.js');+ getProviderQuotas.mockClear();+ // A scheduled tick immediately after must still be due.+ await runQuotaBurnCycle({ trigger: 'scheduled' });+ expect(getProviderQuotas).toHaveBeenCalled();+ });++ it('seeds the interval clock from the persisted run log after a restart', async () => {+ // lastRunAt is in-process; on a bare null the first tick after every boot is+ // "due", so a PM2 restart loop paces a 12-hourly plan into minutes — a full+ // TUI scrape per family ~60s after every boot.+ const { getProviderQuotas } = await import('./providerUsage.js');+ state.config = plan({ checkIntervalMinutes: 720 });+ state.runs = [{ at: new Date(Date.now() - 60_000).toISOString(), trigger: 'scheduled', dispatched: false }];+ await __tickQuotaBurn();+ expect(getProviderQuotas).not.toHaveBeenCalled();++ // A run log whose newest SCHEDULED entry is older than the interval is due.+ __resetQuotaBurnRunner();+ state.runs = [{ at: new Date(Date.now() - 13 * 3600_000).toISOString(), trigger: 'scheduled', dispatched: false }];+ state.pending = { first: { count: 1 } };+ await __tickQuotaBurn();+ expect(getProviderQuotas).toHaveBeenCalled();+ });++ it('ignores manual entries when seeding the clock', async () => {+ // Only a scheduled cycle advances the interval; a manual "Evaluate now"+ // recorded moments ago must not defer the automatic one across a restart.+ const { getProviderQuotas } = await import('./providerUsage.js');+ state.config = plan({ checkIntervalMinutes: 720 });+ state.runs = [{ at: new Date().toISOString(), trigger: 'manual', dispatched: false }];+ state.pending = { first: { count: 1 } };+ await __tickQuotaBurn();+ expect(getProviderQuotas).toHaveBeenCalled();+ });+});diff --git a/server/services/quotaBurnStore.js b/server/services/quotaBurnStore.jsindex 706c0e02df..8c896501e2 100644--- a/server/services/quotaBurnStore.js+++ b/server/services/quotaBurnStore.js@@ -62,6 +62,42 @@ export async function saveQuotaBurnConfig(patch) {});}+const inFlightFile = () => join(PATHS.cos, 'quota-burn-inflight.json');+const inFlightWriteQueue = createFileWriteQueue();++/**+ * How long an enqueued render keeps its entry out of the next cycle's pick.+ *+ * A cloud image render commonly takes minutes and `imageRefs` only fills in+ * when it COMPLETES, so without a cooldown every tick re-selects the same+ * entries. Long enough to outlast a queued render, short enough that a render+ * which silently failed is retried the same day rather than being stranded.+ */+const IN_FLIGHT_TTL_MS = 6 * 60 * 60 * 1000;++/** Keys enqueued within the TTL, as a Set. Expired keys are simply not returned. */+export async function getQuotaBurnInFlight({ now = Date.now() } = {}) {+ const loaded = await readJSONFile(inFlightFile(), null);+ const entries = loaded && typeof loaded === 'object' && !Array.isArray(loaded) ? loaded : {};+ return new Set(Object.entries(entries)+ .filter(([, at]) => Number.isFinite(Number(at)) && now - Number(at) < IN_FLIGHT_TTL_MS)+ .map(([key]) => key));+}++/** Stamp keys as just-enqueued, dropping any that have aged out of the TTL. */+export async function recordQuotaBurnInFlight(keys, { now = Date.now() } = {}) {+ if (!keys?.length) return;+ return inFlightWriteQueue(async () => {+ const loaded = await readJSONFile(inFlightFile(), null);+ const entries = loaded && typeof loaded === 'object' && !Array.isArray(loaded) ? loaded : {};+ const next = Object.fromEntries(Object.entries(entries)+ .filter(([, at]) => Number.isFinite(Number(at)) && now - Number(at) < IN_FLIGHT_TTL_MS));+ for (const key of keys) next[key] = now;+ await atomicWrite(inFlightFile(), next);+ return next;+ });+}+export async function getQuotaBurnRuns() {const loaded = await readJSONFile(runLogFile(), null);return Array.isArray(loaded?.runs) ? loaded.runs : [];