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(hire): preserve token caps across batch reviews

HaningZSd41eee90e886
diff --git a/package.json b/package.json
index a5f9cace..7d46220d 100644
--- a/package.json
+++ b/package.json
@@ -19,7 +19,7 @@
"typecheck:node": "tsc --noEmit -p tsconfig.node.json",
"typecheck:web": "tsc --noEmit -p tsconfig.web.json",
"typecheck": "npm run typecheck:node && npm run typecheck:web",
- "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/terminal-selection.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-task-mutation.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs test/node-install.test.cjs test/office-gl-recovery.test.cjs test/update-state.test.cjs test/release-notes.test.cjs test/transcript-project-dir.test.cjs test/commit-graph.test.cjs test/ide-image.test.cjs test/win-cmd-shim.test.cjs test/hive-windows-prompt.test.cjs test/release-drop.test.cjs test/skills.test.cjs test/skills-install.test.cjs test/hero-payload.test.cjs test/hire-import.test.cjs test/hire-queue.test.cjs",
+ "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/terminal-selection.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-task-mutation.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs test/node-install.test.cjs test/office-gl-recovery.test.cjs test/update-state.test.cjs test/release-notes.test.cjs test/transcript-project-dir.test.cjs test/commit-graph.test.cjs test/ide-image.test.cjs test/win-cmd-shim.test.cjs test/hive-windows-prompt.test.cjs test/release-drop.test.cjs test/skills.test.cjs test/skills-install.test.cjs test/hero-payload.test.cjs test/hire-import.test.cjs test/hire-queue.test.cjs test/agent-token-cap.test.cjs",
"check:links": "node tools/check-release-links.cjs",
"dist": "npm run build && electron-builder",
"dist:mac": "npm run build && electron-builder --mac",
diff --git a/src/main/config.ts b/src/main/config.ts
index e2a3b597..f0fca4d7 100644
--- a/src/main/config.ts
+++ b/src/main/config.ts
@@ -618,6 +618,31 @@ export function writeConfig(patch: Partial<HarnessConfig>): HarnessConfig {
return persistConfig(next);
}
+/** Persist 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
+ * while reviewing a batch of imported hires). Keep the read-modify-write in the
+ * 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
+ ) {
+ throw new Error('invalid agent token cap');
+ }
+ const current = readConfig();
+ return persistConfig({
+ ...current,
+ agentTokenCaps: { ...(current.agentTokenCaps ?? {}), [agentId]: tokenCap }
+ });
+}
+
/** Wipe the persisted config back to first-run defaults so the app boots into
* onboarding again. Used by the "reset & start over" flow. */
export function resetConfig(): HarnessConfig {
diff --git a/src/main/index.ts b/src/main/index.ts
index 6628a599..3b3eea8e 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -14,7 +14,7 @@ import { resolveCommand as resolveCliCommand } from './shellEnv';
import { initAutoUpdater } from './updater';
import { RealtimeFloorWatcher } from './realtimeFloorWatcher';
import {
- readConfig, writeConfig, resetConfig, ensureHarnessHome, ensureClaudePermissionsAccepted,
+ readConfig, writeConfig, setAgentTokenCap, resetConfig, ensureHarnessHome, ensureClaudePermissionsAccepted,
modelForRole, OPS_STANDUP_MISSION, HEARTBEAT_MISSION, COMPACT_MAINTENANCE_MISSION, type HarnessConfig, type ScheduledMission
} from './config';
import { listDir, readFileText, readFileBinary, writeFileText, statAbs, expandTilde } from './fs';
@@ -2948,6 +2948,9 @@ ipcMain.handle('config:update', (_evt, patch: Partial<HarnessConfig>) => {
}
return next;
});
+ipcMain.handle('config:setAgentTokenCap', (_evt, agentId: unknown, tokenCap: unknown) =>
+ setAgentTokenCap(agentId, tokenCap)
+);
ipcMain.handle('config:ensureHome', (_evt, path: unknown) => {
if (typeof path !== 'string' || path.length === 0) return { ok: false, error: 'invalid path' };
return ensureHarnessHome(path);
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 2e447206..33c4a6ed 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -646,6 +646,9 @@ 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> =>
+ ipcRenderer.invoke('config:setAgentTokenCap', agentId, tokenCap),
ensureHarnessHome: (path: string): Promise<{ ok: boolean; error?: string }> =>
ipcRenderer.invoke('config:ensureHome', path),
/** Change the harness home folder. 'move' copies the existing hive + palace
diff --git a/src/renderer/src/components/AddAgentModal.tsx b/src/renderer/src/components/AddAgentModal.tsx
index 22d5bd64..abea052c 100644
--- a/src/renderer/src/components/AddAgentModal.tsx
+++ b/src/renderer/src/components/AddAgentModal.tsx
@@ -438,16 +438,19 @@ export function AddAgentModal({ onClose, config, onConfigChange }: AddAgentModal
// hires land in the same project without re-picking.
if (spawnedCwd && repos[0] !== spawnedCwd) {
const nextRepos = [spawnedCwd, ...repos.filter((r) => r !== spawnedCwd && r !== cwd)];
- void window.cth.updateConfig({ registeredRepos: nextRepos })
- .then((updated) => onConfigChange?.(updated))
- .catch(() => { /* best-effort */ });
+ try {
+ const updated = await window.cth.updateConfig({ registeredRepos: nextRepos });
+ onConfigChange?.(updated);
+ } catch { /* best-effort */ }
}
// A hire manifest may carry a per-agent token budget — apply it to the
- // same agentTokenCaps map the Command Center card writes.
+ // latest agentTokenCaps map in main. Await it before advancing a batch: the
+ // next hire reuses this mounted modal and must not race a stale config write.
if (hireMeta?.tokenCap) {
- void window.cth
- .updateConfig({ agentTokenCaps: { ...(config.agentTokenCaps ?? {}), [id]: hireMeta.tokenCap } })
- .catch(() => { /* best-effort */ });
+ try {
+ const updated = await window.cth.setAgentTokenCap(id, hireMeta.tokenCap);
+ onConfigChange?.(updated);
+ } catch { /* best-effort */ }
}
setBusy(false);
if (pendingHire) {
diff --git a/test/agent-token-cap.test.cjs b/test/agent-token-cap.test.cjs
new file mode 100644
index 00000000..b31c6a4e
--- /dev/null
+++ b/test/agent-token-cap.test.cjs
@@ -0,0 +1,57 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const loadTs = require('./load-ts.cjs');
+
+// 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
+// application config.
+const userData = fs.mkdtempSync(path.join(os.tmpdir(), 'md-agent-cap-'));
+const electron = require.resolve('electron');
+require.cache[electron] = {
+ id: electron,
+ filename: electron,
+ loaded: true,
+ exports: { app: { getPath: () => userData } }
+};
+
+const { readConfig, setAgentTokenCap, writeConfig } = loadTs('src/main/config.ts');
+
+test.after(() => fs.rmSync(userData, { recursive: true, force: true }));
+
+test('consecutive agent caps survive an interleaved config update', () => {
+ writeConfig({ agentTokenCaps: { existing: 50 } });
+
+ setAgentTokenCap('jim', 100);
+ writeConfig({ registeredRepos: ['/workspace/project'] });
+ setAgentTokenCap('pam', 200);
+
+ const config = readConfig();
+ assert.deepEqual(config.agentTokenCaps, {
+ existing: 50,
+ jim: 100,
+ pam: 200
+ });
+ assert.deepEqual(config.registeredRepos, ['/workspace/project']);
+});
+
+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', 0],
+ ['jim', -1],
+ ['jim', 1.5],
+ ['jim', Number.NaN],
+ ['jim', 1e10 + 1]
+ ]) {
+ assert.throws(() => setAgentTokenCap(agentId, tokenCap), /invalid agent token cap/i);
+ }
+ assert.deepEqual(readConfig().agentTokenCaps, baseline);
+});
diff --git a/test/hire-import.test.cjs b/test/hire-import.test.cjs
index 765ba58e..cb11153d 100644
--- a/test/hire-import.test.cjs
+++ b/test/hire-import.test.cjs
@@ -75,3 +75,19 @@ test('review UI exposes progress and an explicit skip without auto-spawn', () =>
assert.match(importFlow, /enqueuePendingHires\(res\.manifests\)/);
assert.doesNotMatch(importFlow, /spawnPty/);
});
+
+test('batch token caps persist atomically before review advances', () => {
+ const modal = readFileSync('src/renderer/src/components/AddAgentModal.tsx', 'utf8');
+ const start = modal.indexOf('const submit = async');
+ const end = modal.indexOf('\n return (', start);
+ const submitFlow = modal.slice(start, end);
+ const persistCap = submitFlow.indexOf('await window.cth.setAgentTokenCap');
+ const advance = submitFlow.indexOf('advanceHireReview()');
+
+ assert.ok(persistCap >= 0, 'submit must use the atomic single-agent config IPC');
+ assert.ok(advance > persistCap, 'the current cap must persist before the batch advances');
+ assert.match(submitFlow.slice(persistCap, advance), /onConfigChange\?\.\(updated\)/,
+ 'the latest config must be returned to App before the next review');
+ assert.doesNotMatch(submitFlow, /agentTokenCaps:\s*\{\s*\.\.\.\(config\.agentTokenCaps/,
+ 'renderer must never replace the cap map from a stale config snapshot');
+});