Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

fix(hires): clear cancelled batches and update caps atomically

HaningZSe1b715979fcc
diff --git a/src/main/config.ts b/src/main/config.ts
index 484cb3f1..423a2940 100644
--- a/src/main/config.ts
+++ b/src/main/config.ts
@@ -10,6 +10,7 @@ import {
type AgentProvider
} from '../shared/agentProvider';
import { defaultMcpDefaults } from '../shared/mcpCatalog';
+import { MAX_AGENT_TOKEN_CAP } from '../shared/tokenCaps';
import { expandTilde, normalizeHiveHome } from './fs';
import type { IntegrationRecord } from '../shared/integrations';
import {
@@ -618,7 +619,7 @@ export function writeConfig(patch: Partial<HarnessConfig>): HarnessConfig {
return persistConfig(next);
}
-/** Persist one agent's token ceiling against the latest config on disk.
+/** Set or clear one agent's token ceiling against the latest config on disk.
*
* Renderer config objects are snapshots. Replacing `agentTokenCaps` from one of
* those snapshots loses caps written since the snapshot was read (most visibly
@@ -626,20 +627,26 @@ export function writeConfig(patch: Partial<HarnessConfig>): HarnessConfig {
* synchronous main process so each call merges with the result of the previous
* one before returning the updated config to the renderer. */
export function setAgentTokenCap(agentId: unknown, tokenCap: unknown): HarnessConfig {
- if (
- typeof agentId !== 'string'
- || agentId.trim().length === 0
- || typeof tokenCap !== 'number'
- || !Number.isInteger(tokenCap)
- || tokenCap <= 0
- || tokenCap > 1e10
- ) {
+ if (typeof agentId !== 'string' || agentId.trim().length === 0) {
throw new Error('invalid agent token cap');
}
+ if (
+ tokenCap !== undefined
+ && (
+ typeof tokenCap !== 'number'
+ || !Number.isInteger(tokenCap)
+ || tokenCap <= 0
+ || tokenCap > MAX_AGENT_TOKEN_CAP
+ )
+ ) throw new Error('invalid agent token cap');
+
const current = readConfig();
+ const agentTokenCaps = { ...(current.agentTokenCaps ?? {}) };
+ if (tokenCap === undefined) delete agentTokenCaps[agentId];
+ else agentTokenCaps[agentId] = tokenCap;
return persistConfig({
...current,
- agentTokenCaps: { ...(current.agentTokenCaps ?? {}), [agentId]: tokenCap }
+ agentTokenCaps
});
}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 5432c5c6..5f8b80a1 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -646,8 +646,8 @@ const api = {
ipcRenderer.invoke('config:get'),
updateConfig: (patch: Partial<HarnessConfig>): Promise<HarnessConfig> =>
ipcRenderer.invoke('config:update', patch),
- /** Merge one per-agent token ceiling against main's latest persisted config. */
- setAgentTokenCap: (agentId: string, tokenCap: number): Promise<HarnessConfig> =>
+ /** Set or clear one per-agent token ceiling against main's latest config. */
+ setAgentTokenCap: (agentId: string, tokenCap?: number): Promise<HarnessConfig> =>
ipcRenderer.invoke('config:setAgentTokenCap', agentId, tokenCap),
ensureHarnessHome: (path: string): Promise<{ ok: boolean; error?: string }> =>
ipcRenderer.invoke('config:ensureHome', path),
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx
index c59f7de5..d492335e 100644
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@ -39,6 +39,7 @@ export function App() {
const agentCount = agents.length;
const addAgentOpen = useStore(s => s.addAgentOpen);
const setAddAgentOpen = useStore(s => s.setAddAgentOpen);
+ const clearPendingHires = useStore(s => s.clearPendingHires);
const godStatus = useStore(s => s.godStatus);
const fullscreenAgentId = useStore(s => s.fullscreenAgentId);
const appThemeNow = useAppTheme();
@@ -132,6 +133,10 @@ export function App() {
// Shareable hires: a validated manifest arriving via the munderdifflin://
// deep link (or file import) pre-fills the Add-Agent modal. Never spawns by itself.
const enqueuePendingHires = useStore(s => s.enqueuePendingHires);
+ const closeAddAgentReview = () => {
+ clearPendingHires();
+ setAddAgentOpen(false);
+ };
useEffect(() => {
const unsub = window.cth.onHireImport?.((m) => {
enqueuePendingHires([m]);
@@ -442,7 +447,7 @@ export function App() {
{addAgentOpen && (
<AddAgentModal
- onClose={() => setAddAgentOpen(false)}
+ onClose={closeAddAgentReview}
config={config}
onConfigChange={setConfig}
/>
diff --git a/src/renderer/src/components/AddAgentModal.tsx b/src/renderer/src/components/AddAgentModal.tsx
index 1e724e7d..ddd0ff85 100644
--- a/src/renderer/src/components/AddAgentModal.tsx
+++ b/src/renderer/src/components/AddAgentModal.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState, type CSSProperties } from 'react';
+import { useEffect, useLayoutEffect, useState, type CSSProperties } from 'react';
import { PixelPanel } from './PixelPanel';
import { PixelButton } from './PixelButton';
import { SpritePortrait } from './SpritePortrait';
@@ -317,7 +317,7 @@ export function AddAgentModal({ onClose, config, onConfigChange }: AddAgentModal
// Advancing a batch keeps this modal mounted. Re-seed every form field when
// the queue head changes so edits made while reviewing one hire cannot leak
// into the next.
- useEffect(() => {
+ useLayoutEffect(() => {
if (pendingHire) applyManifest(pendingHire);
// applyManifest intentionally closes over the config snapshot used by this
// open modal; queue advances do not replace that snapshot.
@@ -326,9 +326,7 @@ export function AddAgentModal({ onClose, config, onConfigChange }: AddAgentModal
const advanceHireReview = () => {
const next = hireQueue.pending[1];
- // Seed the next manifest in the same React update as the queue advance, so
- // the banner/progress can never paint with the previous hire's edited form.
- if (next) applyManifest(next);
+ // The pendingHire effect re-seeds every form field from the new queue head.
finishPendingHire();
if (!next) onClose();
};
diff --git a/src/renderer/src/components/CommandCenterPanel.tsx b/src/renderer/src/components/CommandCenterPanel.tsx
index 1a1db48a..2883eca6 100644
--- a/src/renderer/src/components/CommandCenterPanel.tsx
+++ b/src/renderer/src/components/CommandCenterPanel.tsx
@@ -581,14 +581,24 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
setDispatchTo(''); // Michael decomposes and assigns — no more broadcast blasts
};
- // Set/clear one agent's token limit; persist the whole map (writeConfig replaces
- // the top-level key, so we send the full merged map). Drives that agent's meter
- // and the breaker's per-agent trip.
+ // Set/clear one agent's token limit atomically in main. Renderer config objects
+ // are snapshots, so persisting this whole map could clobber a cap added by the
+ // hire flow after this panel loaded.
const setAgentCap = (id: string, tokens: number | undefined) => {
- const next = { ...agentTokenCaps };
- if (tokens && tokens > 0) next[id] = tokens; else delete next[id];
- setAgentTokenCaps(next);
- void window.cth.updateConfig({ agentTokenCaps: next }).catch(() => { /* noop */ });
+ setAgentTokenCaps((current) => {
+ const optimistic = { ...current };
+ if (tokens && tokens > 0) optimistic[id] = tokens;
+ else delete optimistic[id];
+ return optimistic;
+ });
+ void window.cth.setAgentTokenCap(id, tokens).then((updated) => {
+ setAgentTokenCaps(updated.agentTokenCaps ?? {});
+ }).catch(() => {
+ // Reconcile a failed optimistic edit with the persisted source of truth.
+ void window.cth.getConfig().then((current) => {
+ setAgentTokenCaps(current.agentTokenCaps ?? {});
+ }).catch(() => { /* noop */ });
+ });
};
// The token meter is scaled to the agent's own limit when set, else the floor
diff --git a/src/renderer/src/store/store.ts b/src/renderer/src/store/store.ts
index 4b1ba5a1..4a4c8781 100644
--- a/src/renderer/src/store/store.ts
+++ b/src/renderer/src/store/store.ts
@@ -7,6 +7,7 @@ import type { AgentProvider } from '@shared/agentProvider';
import type { HireManifest } from '@shared/hire';
import {
EMPTY_HIRE_QUEUE,
+ clearHireQueue,
enqueueHires,
finishCurrentHire,
type HireReviewQueue
@@ -282,6 +283,7 @@ interface State {
hireQueue: HireReviewQueue;
enqueuePendingHires: (manifests: readonly HireManifest[]) => void;
finishPendingHire: () => void;
+ clearPendingHires: () => void;
setFullscreen: (id: string | null) => void;
setFullscreenFile: (path: string | null, view?: 'edit' | 'preview') => void;
/** Open/close the IDE. `agentId` names the agent whose workspace it should
@@ -871,6 +873,9 @@ export const useStore = create<State>((set) => ({
finishPendingHire: () => set((s) => ({
hireQueue: finishCurrentHire(s.hireQueue)
})),
+ clearPendingHires: () => set((s) => ({
+ hireQueue: clearHireQueue(s.hireQueue)
+ })),
setFullscreen: (id) => set({ fullscreenAgentId: id }),
setFullscreenFile: (path, view) => set({ fullscreenFilePath: path, fullscreenFileView: view ?? 'edit' }),
// Closing CLEARS the target: the id is scoped to one IDE session, and a stale
diff --git a/src/shared/hire.ts b/src/shared/hire.ts
index 7d2ef4fe..93422517 100644
--- a/src/shared/hire.ts
+++ b/src/shared/hire.ts
@@ -22,6 +22,7 @@
*/
import { mcpCatalogEntry } from './mcpCatalog';
+import { MAX_AGENT_TOKEN_CAP } from './tokenCaps';
export const HIRE_SPEC_V1 = 'munder-difflin/hire@1';
@@ -258,7 +259,7 @@ export function validateHireManifest(raw: unknown): HireValidation {
let tokenCap: number | undefined;
if (o.tokenCap !== undefined) {
- if (typeof o.tokenCap === 'number' && Number.isInteger(o.tokenCap) && o.tokenCap > 0 && o.tokenCap <= 1e10) tokenCap = o.tokenCap;
+ if (typeof o.tokenCap === 'number' && Number.isInteger(o.tokenCap) && o.tokenCap > 0 && o.tokenCap <= MAX_AGENT_TOKEN_CAP) tokenCap = o.tokenCap;
else errors.push('"tokenCap" must be a positive integer (max 1e10)');
}
diff --git a/src/shared/hireQueue.ts b/src/shared/hireQueue.ts
index aca2e48a..76bf179a 100644
--- a/src/shared/hireQueue.ts
+++ b/src/shared/hireQueue.ts
@@ -32,6 +32,11 @@ export function finishCurrentHire(queue: HireReviewQueue): HireReviewQueue {
return { pending: queue.pending.slice(1), reviewed: queue.reviewed + 1 };
}
+/** Cancel the current human-review run; unfinished manifests do not resume later. */
+export function clearHireQueue(_queue: HireReviewQueue): HireReviewQueue {
+ return EMPTY_HIRE_QUEUE;
+}
+
export function hireQueueProgress(
queue: HireReviewQueue
): { current: number; total: number } | null {
diff --git a/src/shared/tokenCaps.ts b/src/shared/tokenCaps.ts
new file mode 100644
index 00000000..7f92c8b2
--- /dev/null
+++ b/src/shared/tokenCaps.ts
@@ -0,0 +1,2 @@
+/** Highest accepted per-agent token ceiling across manifests and config IPC. */
+export const MAX_AGENT_TOKEN_CAP = 10_000_000_000;
diff --git a/test/agent-token-cap.test.cjs b/test/agent-token-cap.test.cjs
index b31c6a4e..b2d03cec 100644
--- a/test/agent-token-cap.test.cjs
+++ b/test/agent-token-cap.test.cjs
@@ -6,6 +6,7 @@ const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const loadTs = require('./load-ts.cjs');
+const { MAX_AGENT_TOKEN_CAP } = loadTs('src/shared/tokenCaps.ts');
// config.ts resolves its file through Electron's app.getPath(). Point that one
// dependency at a throwaway userData root so this test never touches the real
@@ -39,17 +40,32 @@ test('consecutive agent caps survive an interleaved config update', () => {
assert.deepEqual(config.registeredRepos, ['/workspace/project']);
});
+test('setting and clearing caps use the latest persisted map', () => {
+ writeConfig({ agentTokenCaps: { existing: 50, obsolete: 75 } });
+
+ setAgentTokenCap('jim', 100);
+ setAgentTokenCap('obsolete', undefined);
+ setAgentTokenCap('pam', 200);
+
+ assert.deepEqual(readConfig().agentTokenCaps, {
+ existing: 50,
+ jim: 100,
+ pam: 200
+ });
+});
+
test('invalid agent-cap IPC values cannot reach persisted config', () => {
const baseline = { existing: 50 };
writeConfig({ agentTokenCaps: baseline });
for (const [agentId, tokenCap] of [
['', 100],
[null, 100],
+ ['jim', null],
['jim', 0],
['jim', -1],
['jim', 1.5],
['jim', Number.NaN],
- ['jim', 1e10 + 1]
+ ['jim', MAX_AGENT_TOKEN_CAP + 1]
]) {
assert.throws(() => setAgentTokenCap(agentId, tokenCap), /invalid agent token cap/i);
}
diff --git a/test/hire-import.test.cjs b/test/hire-import.test.cjs
index cb11153d..2216b613 100644
--- a/test/hire-import.test.cjs
+++ b/test/hire-import.test.cjs
@@ -64,6 +64,12 @@ test('renderer wiring appends every cold-start and runtime arrival', () => {
assert.doesNotMatch(app, /queued\[queued\.length\s*-\s*1\]/);
});
+test('closing a hire review clears the remaining batch', () => {
+ const app = readFileSync('src/renderer/src/App.tsx', 'utf8');
+ assert.match(app, /const closeAddAgentReview = \(\) => \{[\s\S]*?clearPendingHires\(\);[\s\S]*?setAddAgentOpen\(false\);[\s\S]*?\}/);
+ assert.match(app, /<AddAgentModal[\s\S]*?onClose=\{closeAddAgentReview\}/);
+});
+
test('review UI exposes progress and an explicit skip without auto-spawn', () => {
const modal = readFileSync('src/renderer/src/components/AddAgentModal.tsx', 'utf8');
assert.match(modal, /hireQueueProgress\(hireQueue\)/);
@@ -91,3 +97,14 @@ test('batch token caps persist atomically before review advances', () => {
assert.doesNotMatch(submitFlow, /agentTokenCaps:\s*\{\s*\.\.\.\(config\.agentTokenCaps/,
'renderer must never replace the cap map from a stale config snapshot');
});
+
+test('Command Center sets and clears one cap through the atomic IPC', () => {
+ const panel = readFileSync('src/renderer/src/components/CommandCenterPanel.tsx', 'utf8');
+ const start = panel.indexOf('const setAgentCap =');
+ const end = panel.indexOf('\n\n // The token meter', start);
+ const capFlow = panel.slice(start, end);
+
+ assert.ok(start >= 0 && end > start, 'Command Center cap handler is present');
+ assert.match(capFlow, /window\.cth\.setAgentTokenCap\(id, tokens\)/);
+ assert.doesNotMatch(capFlow, /updateConfig\(\{\s*agentTokenCaps/);
+});
diff --git a/test/hire-queue.test.cjs b/test/hire-queue.test.cjs
index ba11232c..eabbcb88 100644
--- a/test/hire-queue.test.cjs
+++ b/test/hire-queue.test.cjs
@@ -6,6 +6,7 @@ const loadTs = require('./load-ts.cjs');
const {
EMPTY_HIRE_QUEUE,
+ clearHireQueue,
enqueueHires,
finishCurrentHire,
hireQueueProgress
@@ -44,6 +45,18 @@ test('draining the queue resets progress for the next independent import', () =>
assert.deepEqual(hireQueueProgress(next), { current: 1, total: 2 });
});
+test('cancelling review discards the remaining batch and resets later progress', () => {
+ let queue = enqueueHires(EMPTY_HIRE_QUEUE, [hire('Jim'), hire('Pam'), hire('Dwight')]);
+ queue = finishCurrentHire(queue);
+
+ const cancelled = clearHireQueue(queue);
+ const fresh = enqueueHires(cancelled, [hire('Angela'), hire('Kevin')]);
+
+ assert.deepEqual(cancelled, EMPTY_HIRE_QUEUE);
+ assert.deepEqual(fresh.pending.map((m) => m.name), ['Angela', 'Kevin']);
+ assert.deepEqual(hireQueueProgress(fresh), { current: 1, total: 2 });
+});
+
test('empty arrivals and advances do not invent queue state', () => {
assert.deepEqual(enqueueHires(EMPTY_HIRE_QUEUE, []), EMPTY_HIRE_QUEUE);
assert.deepEqual(finishCurrentHire(EMPTY_HIRE_QUEUE), EMPTY_HIRE_QUEUE);