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

feat(v0.2.0): Command Center overhaul, token budgets, fleet monitoring + UX fixes

Chaitanya Girifc3af94546b5
diff --git a/electron.vite.config.ts b/electron.vite.config.ts
index dc1fdcca..b6bb92b0 100644
--- a/electron.vite.config.ts
+++ b/electron.vite.config.ts
@@ -30,7 +30,8 @@ export default defineConfig({
resolve: {
alias: {
'@': resolve(__dirname, 'src/renderer/src'),
- '@brand': resolve(__dirname, 'docs')
+ '@brand': resolve(__dirname, 'docs'),
+ '@shared': resolve(__dirname, 'src/shared')
}
}
}
diff --git a/package-lock.json b/package-lock.json
index e10e6d8b..1c0d0574 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -22,6 +22,7 @@
"@lezer/highlight": "^1.2.3",
"@uiw/react-codemirror": "^4.25.10",
"@xterm/addon-fit": "^0.10.0",
+ "@xterm/addon-webgl": "^0.19.0",
"@xterm/xterm": "^5.5.0",
"better-sqlite3": "^11.10.0",
"commit-graph": "^2.4.0",
@@ -2492,6 +2493,12 @@
"@xterm/xterm": "^5.0.0"
}
},
+ "node_modules/@xterm/addon-webgl": {
+ "version": "0.19.0",
+ "resolved": "https://registry.npmjs.org/@xterm/addon-webgl/-/addon-webgl-0.19.0.tgz",
+ "integrity": "sha512-b3fMOsyLVuCeNJWxolACEUED0vm7qC0cy4wRvf3oURSzDTYVQiGPhTnhWZwIHdvC48Y+oLhvYXnY4XDXPoJo6A==",
+ "license": "MIT"
+ },
"node_modules/@xterm/xterm": {
"version": "5.5.0",
"resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-5.5.0.tgz",
diff --git a/package.json b/package.json
index dbdcd621..80869a6d 100644
--- a/package.json
+++ b/package.json
@@ -37,6 +37,7 @@
"@lezer/highlight": "^1.2.3",
"@uiw/react-codemirror": "^4.25.10",
"@xterm/addon-fit": "^0.10.0",
+ "@xterm/addon-webgl": "^0.19.0",
"@xterm/xterm": "^5.5.0",
"better-sqlite3": "^11.10.0",
"commit-graph": "^2.4.0",
diff --git a/src/main/breaker.ts b/src/main/breaker.ts
index 0c924ced..71153905 100644
--- a/src/main/breaker.ts
+++ b/src/main/breaker.ts
@@ -61,6 +61,10 @@ const rank = (l: BreakerLevel): number => LEVELS.indexOf(l);
const actionFor = (l: BreakerLevel): BreakerAction =>
l === 'steering' ? 'steer' : l === 'constrained' ? 'constrain' : l === 'stopped' ? 'stop' : 'none';
+/** Total tokens in a cumulative sample (all kinds), 0 when unknown. */
+const tokensOf = (s: AgentUsageSample | null): number =>
+ s ? s.input + s.output + s.cacheRead + s.cacheCreation : 0;
+
const DEFAULTS = {
enabled: true,
hardStop: false,
@@ -83,7 +87,7 @@ interface AgentBreakerState {
export class CircuitBreaker {
private agents = new Map<string, AgentBreakerState>();
- constructor(private getConfig: () => CircuitBreakerConfig & { costCapUsd?: number }) {}
+ constructor(private getConfig: () => CircuitBreakerConfig & { costCapUsd?: number; costCapTokens?: number; agentTokenCaps?: Record<string, number> }) {}
private cfg() {
const c = this.getConfig() ?? {};
@@ -93,7 +97,9 @@ export class CircuitBreaker {
repeatedToolLimit: c.repeatedToolLimit ?? DEFAULTS.repeatedToolLimit,
errorStormLimit: c.errorStormLimit ?? DEFAULTS.errorStormLimit,
tokenVelocityPerMin: c.tokenVelocityPerMin ?? DEFAULTS.tokenVelocityPerMin,
- costCapUsd: c.costCapUsd
+ costCapUsd: c.costCapUsd,
+ costCapTokens: c.costCapTokens,
+ agentTokenCaps: c.agentTokenCaps
};
}
@@ -111,6 +117,11 @@ export class CircuitBreaker {
this.agents.delete(agentId);
}
+ /** Current breaker level for an agent (for the live fleet snapshot). */
+ levelFor(agentId: string): BreakerLevel {
+ return this.agents.get(agentId)?.level ?? 'healthy';
+ }
+
// ── event-driven inputs (fed by HookServer) ──────────────────────────────
/** A tool call ran. A NEW (name+input) key counts as forward progress (resets
@@ -170,9 +181,25 @@ export class CircuitBreaker {
if (total <= cfg.costCapUsd) topSpender = null; // under cap — nobody blamed
}
+ // Token cap (the user-facing budget): same floor-wide logic on total tokens.
+ let topTokenSpender: string | null = null;
+ if (typeof cfg.costCapTokens === 'number' && cfg.costCapTokens > 0) {
+ let total = 0; let max = -1;
+ for (const i of inputs) {
+ const tok = tokensOf(i.sample);
+ total += tok;
+ if (tok > max) { max = tok; topTokenSpender = i.agentId; }
+ }
+ if (total <= cfg.costCapTokens) topTokenSpender = null; // under cap
+ }
+
for (const input of inputs) {
const s = this.get(input.agentId);
- const trip = this.evaluate(input, s, cfg, input.agentId === topSpender, cfg.costCapUsd);
+ const trip = this.evaluate(
+ input, s, cfg,
+ input.agentId === topSpender, cfg.costCapUsd,
+ input.agentId === topTokenSpender, cfg.costCapTokens
+ );
// remember the cumulative baseline for next beat's velocity diff
if (input.sample) s.lastSample = input.sample;
@@ -203,7 +230,9 @@ export class CircuitBreaker {
s: AgentBreakerState,
cfg: ReturnType<CircuitBreaker['cfg']>,
isTopSpender: boolean,
- costCapUsd: number | undefined
+ costCapUsd: number | undefined,
+ isTopTokenSpender: boolean,
+ costCapTokens: number | undefined
): { tripping: boolean; reason: string } {
// (b) repeated identical tool calls
if (s.repeatCount >= cfg.repeatedToolLimit) {
@@ -213,10 +242,19 @@ export class CircuitBreaker {
if (s.errorCount >= cfg.errorStormLimit) {
return { tripping: true, reason: `error storm: ${s.errorCount} consecutive api errors/retries` };
}
+ // (a) per-agent token limit — this agent's own total over its configured cap
+ const perAgentCap = cfg.agentTokenCaps?.[input.agentId];
+ if (typeof perAgentCap === 'number' && perAgentCap > 0 && tokensOf(input.sample) > perAgentCap) {
+ return { tripping: true, reason: `token limit: ${tokensOf(input.sample).toLocaleString()} over the agent cap of ${perAgentCap.toLocaleString()}` };
+ }
// (a) cost cap — floor total over cap, this agent is the biggest spender
if (isTopSpender && typeof costCapUsd === 'number') {
return { tripping: true, reason: `cost cap: floor total over $${costCapUsd} (top spender $${(input.sample?.usd ?? 0).toFixed(2)})` };
}
+ // (a) token cap — floor total tokens over cap, this agent is the biggest spender
+ if (isTopTokenSpender && typeof costCapTokens === 'number') {
+ return { tripping: true, reason: `token cap: floor total over ${costCapTokens.toLocaleString()} tokens (top spender ${tokensOf(input.sample).toLocaleString()})` };
+ }
// (a) token-velocity spike — diff cumulative output across consecutive beats
if (input.sample && s.lastSample) {
const dOut = input.sample.output - s.lastSample.output;
diff --git a/src/main/config.ts b/src/main/config.ts
index 397d5668..44e30141 100644
--- a/src/main/config.ts
+++ b/src/main/config.ts
@@ -115,8 +115,18 @@ export interface HarnessConfig {
heartbeatSeeded?: boolean;
/** Hard dollar ceiling across all active agents before the circuit breaker
* trips. UNSET by default (Lane A #6.6b decision): the breaker trips on
- * behavioral signals; the $-cap is purely opt-in. */
+ * behavioral signals; the $-cap is purely opt-in. Legacy — the UI now sets a
+ * token cap instead (see costCapTokens); both are enforced if present. */
costCapUsd?: number;
+ /** Hard TOKEN ceiling (total tokens across all active agents) before the
+ * breaker trips. The user-facing budget — set in Settings. Opt-in like the
+ * $-cap; total = input + output + cacheRead + cacheCreation, summed across the
+ * floor (the biggest token spender is blamed). */
+ costCapTokens?: number;
+ /** Per-agent total-token ceiling, keyed by agent id. When an agent's own total
+ * tokens exceed its cap the breaker trips that agent alone (independent of the
+ * floor budget). Set from each agent's card in the Command Center. */
+ agentTokenCaps?: Record<string, number>;
/** Passed to every spawned agent as `--max-turns <n>` when set; unset = no cap
* (Claude Code's default). A coarse runaway guard independent of the breaker. */
maxTurns?: number;
diff --git a/src/main/hive.ts b/src/main/hive.ts
index 2ca42418..0cc287e8 100644
--- a/src/main/hive.ts
+++ b/src/main/hive.ts
@@ -25,6 +25,7 @@ import { join } from 'node:path';
import { spawnSync } from 'node:child_process';
import { randomBytes, createHash } from 'node:crypto';
import type { AgentUsageSample } from './usage';
+import { COMMAND_GROUPS } from '../shared/claudeCommands';
// ─── Types ──────────────────────────────────────────────────────────────────
@@ -212,6 +213,18 @@ export class HiveManager {
const log = join(root, 'log.jsonl');
if (!existsSync(log)) writeFileSync(log, '', 'utf8');
+ // The Claude Code command reference Michael consults (refreshed each bootstrap
+ // so it tracks the bundled list).
+ writeFileSync(join(root, 'COMMANDS.md'), COMMANDS_MD, 'utf8');
+
+ // Keep the churny/ephemeral live files out of the hive git repo.
+ const gitignore = join(root, '.gitignore');
+ const want = ['fleet.json', 'hooks.sock', '.DS_Store'];
+ let lines: string[] = [];
+ if (existsSync(gitignore)) { try { lines = readFileSync(gitignore, 'utf8').split('\n'); } catch { lines = []; } }
+ const missing = want.filter((w) => !lines.includes(w));
+ if (missing.length) writeFileSync(gitignore, [...lines.filter(Boolean), ...missing].join('\n') + '\n', 'utf8');
+
// The hook shim: a dumb pipe between a `claude` hook and our UDS. Refreshed
// on every bootstrap so it tracks code changes.
mkdirSync(join(root, 'bin'), { recursive: true });
@@ -415,6 +428,7 @@ export class HiveManager {
`- Capabilities: ${caps}`,
`- Working directory: ${meta.cwd}`,
meta.isGod ? '- You are the **god / orchestrator**. You run the floor — keep awareness of the whole team, delegate execution, and personally own only the important calls (decomposition, sign-offs, conflicts, integration), not the grunt work.' : '',
+ meta.isGod ? '- Monitor the team with `fleet.json` (live per-agent status/tokens/cost/breaker) and `registry.json`; full command reference in `COMMANDS.md`. `claude agents` does NOT list your hive siblings.' : '',
''
].filter(Boolean).join('\n');
}
@@ -436,9 +450,11 @@ export class HiveManager {
: '';
const godLine = meta.isGod
? 'You are the GOD / ORCHESTRATOR of this hive — your job is to ORCHESTRATE, not to implement: maintain live situational awareness and delegate the work. (1) AWARENESS — always know what is going on: keep an accurate picture of every agent (active vs archived/idle), the task board, and all in-flight work; drain your inbox continually and triage every other agent\'s requests, answering clarifications so the team runs autonomously. (2) DELEGATE — decompose work and fan it out to the hive agents via their inboxes (route messages and assign owners; do not do their jobs); do NOT take on grunt implementation yourself. (3) OWN ONLY THE IMPORTANT, high-leverage things — task decomposition, dispatch decisions, sign-offs, conflict resolution, branch integration, and final QA — and remain the sole scribe of board.md. You are otherwise fully autonomous — there is NO separate approval queue. For the genuinely critical (destructive actions, spending real money, scope changes, unresolvable conflicts), ask the human directly in your own session and let the tool-permission prompt gate the action; the human approves natively, including remotely from their phone via /remote-control. Keep the team unblocked. When you DISPATCH a task, write it as a 4-part contract so the agent can run autonomously: (1) OBJECTIVE — the concrete goal; (2) OUTPUT — the expected deliverable/format; (3) TOOLS — what to use or avoid, and any references to read instead of re-deriving; (4) BOUNDARIES — scope limits + the definition of done. Pass references (file paths, message ids, board sections), not pasted content — keep dispatches short.'
+ + ` MONITOR the floor by reading ${root}/fleet.json (live per-agent tokens, cost, status, last tool, breaker level, inbox backlog) and ${root}/registry.json — note that running 'claude agents' will NOT list your hive's sibling agents. A full Claude Code command reference is at ${root}/COMMANDS.md (slash commands act ONLY on your own session; CLI commands run in your shell and can target the fleet). You periodically receive scheduler / "Heartbeat" standup requests — on each, review every agent via fleet.json, re-engage anyone stalled, over-budget, or breaker-armed, and keep board.md and tasks.json accurate. Steward the token budget.`
: meta.isAssistant
? 'You are Michael\'s PREP ASSISTANT. You will be handed short, possibly vague instructions (each begins with "ENRICH TASK:"). For each one: (1) figure out which project it concerns and cd into the most relevant repo — you start in Michael\'s home directory; (2) gather concrete context READ-ONLY (exact file paths, current state, relevant code, conventions, active branch, gotchas) — NEVER modify, create, or delete files; (3) rewrite the instruction into ONE clear, self-contained prompt that Michael can execute autonomously, preserving the user\'s original intent without inventing scope. Then deliver it: write ONE message JSON into your outbox with "to":"god", "act":"request", a short subject, and the finished prompt as the body. Do NOT perform the task yourself — your only output is the improved prompt sent to Michael.'
: 'For anything ambiguous, cross-cutting, or needing sign-off, address a message to "god".';
+ const guardrailsLine = 'Guardrails: a circuit breaker watches the floor — a "Circuit breaker: steer/constrain" message means you are looping or overspending, so STOP repeating, summarize what you tried, and follow it. Be token-frugal (a floor-wide or per-agent token budget can pause you). The shared plan has two parts: board.md (freeform; god is the sole scribe) and tasks.json (structured kanban — todo/doing/blocked/done).';
return [
`You are "${meta.name}" (${meta.id}), an autonomous agent in a collaborating hive of Claude agents.`,
`Your private workspace is ${dir}. The shared hive is ${root}. Full protocol: ${root}/PROTOCOL.md.`,
@@ -448,6 +464,7 @@ export class HiveManager {
`2. Record durable facts, decisions, and context by appending to ${dir}/memory.md.`,
`3. To ask another agent for something or share information, write ONE message JSON into ${dir}/outbox/ (schema in PROTOCOL.md). NEVER write into another agent's folder — the orchestrator delivers your outbox.`,
'4. At the END of a task, append what you learned to memory.md so future-you remembers.',
+ guardrailsLine,
memoryLine,
godLine,
`Env vars available to you: AGENT_ID, AGENT_NAME, HIVE_ROOT, AGENT_DIR.`
@@ -606,6 +623,19 @@ export class HiveManager {
inbox(id: string): HiveMessage[] {
return this.listMessages(join(this.agentDir(id), 'inbox'));
}
+ /** Count undrained inbox messages for an agent (cheap — for the fleet snapshot). */
+ inboxBacklog(id: string): number {
+ const dir = join(this.agentDir(id), 'inbox');
+ if (!existsSync(dir)) return 0;
+ try { return readdirSync(dir).filter((f) => f.endsWith('.json')).length; } catch { return 0; }
+ }
+ /** Write the live fleet snapshot Michael reads (`fleet.json`, gitignored).
+ * Best-effort — called from a timer, must never throw. */
+ writeFleetSnapshot(snapshot: unknown): void {
+ const root = this.root();
+ if (!root) return;
+ try { writeFileSync(join(root, 'fleet.json'), JSON.stringify(snapshot, null, 2), 'utf8'); } catch { /* noop */ }
+ }
logTail(n = 200): unknown[] {
const root = this.root();
if (!root || !existsSync(join(root, 'log.jsonl'))) return [];
@@ -712,6 +742,32 @@ export class HiveManager {
// ─── PROTOCOL.md (written into the hive, readable by every agent) ────────────
+/** The Claude Code command reference written to <hive>/COMMANDS.md, rendered from
+ * the SAME source as the UI "commands" tab so they never drift. Leads with the
+ * orchestrator note: slash = own session only, cli = shell/fleet; monitor
+ * siblings via fleet.json (claude agents does NOT see them). */
+function renderCommandsMd(): string {
+ const lines: string[] = [
+ '# Claude Code commands',
+ '',
+ 'Reference of the Claude Code commands available to you. Two kinds:',
+ '- **slash** commands act ONLY on your own session — you CANNOT run them on another agent\'s terminal.',
+ '- **cli** commands run in your shell (Bash) and can target the fleet, spawn, or query.',
+ '',
+ 'To MONITOR the other agents in this hive, read `fleet.json` in the hive root (live per-agent tokens, cost, status, last tool, breaker level, inbox backlog) plus `registry.json` — `claude agents` does NOT list your hive siblings. Use `claude -p "..." --output-format json` for a one-off headless query.',
+ ''
+ ];
+ for (const g of COMMAND_GROUPS) {
+ lines.push(`## ${g.title}`, '');
+ for (const it of g.items) {
+ lines.push(`- \`${it.cmd.trim()}\` _(${it.kind})_ — ${it.desc}${it.usage ? ` e.g. \`${it.usage}\`` : ''}`);
+ }
+ lines.push('');
+ }
+ return lines.join('\n');
+}
+const COMMANDS_MD = renderCommandsMd();
+
const PROTOCOL_MD = `# Hive protocol
You are one of several Claude agents sharing this hive. Coordination is entirely
@@ -758,6 +814,31 @@ The harness fills in \`id\`, \`from\`, \`hops\`, and timestamps.
who is its sole scribe.
- Re-reading a message you already moved to \`.done/\` is a no-op. Don't reprocess.
+## The work: board.md vs tasks.json
+There are two shared surfaces, both in the hive root:
+- \`board.md\` — the freeform narrative plan. The god agent is its sole scribe; others \`propose\` edits.
+- \`tasks.json\` — the structured task ledger (a kanban: \`todo / doing / blocked / done\`, with title,
+ assignee, priority, deps). Keep the task you're working reflected in its status.
+
+## Guardrails: circuit breaker & token budgets
+A circuit breaker watches every agent for runaway behavior (looping on the same tool, error storms,
+overspending). It escalates gently: \`steer\` → \`constrain\` → \`stop\`. If a \`Circuit breaker: steer\`
+or \`Circuit breaker: constrain\` message lands in your inbox, you ARE the problem it caught — stop
+repeating, summarize what you've tried, and do exactly what the message says (constrain = go read-only
+and get god's sign-off before more tool calls). Be **token-frugal**: the floor has a token budget and
+each agent can have its own token limit; crossing it trips the breaker. Prefer references over pasted
+content, and \`/compact\` your own session when context gets heavy.
+
+## Fleet monitoring (orchestrator)
+You (god) are responsible for situational awareness. To see the live state of every agent, read
+\`fleet.json\` in the hive root — it is refreshed continuously with each agent's tokens, cost, status,
+breaker level, last tool, last-active time, and inbox backlog. Pair it with \`registry.json\` (the roster)
+and \`log.jsonl\` (the event feed). IMPORTANT: \`claude agents\` will NOT show your hive's sibling
+sessions (they're spawned independently) — \`fleet.json\` is your source of truth for them. For a deeper
+look at one agent, read its \`agents/<id>/memory.md\` and \`inbox/\`, or send it a \`query\`. A full
+Claude Code command reference (slash = your own session only; CLI = your shell, can target the fleet)
+is in \`COMMANDS.md\` in the hive root.
+
## Semantic memory (optional — when \`mempalace\` is installed)
When \`MEMPALACE_PALACE_PATH\` is set in your environment, the hive shares a
searchable MemPalace and you have the \`mempalace\` CLI:
diff --git a/src/main/index.ts b/src/main/index.ts
index c252f570..aed82c82 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -56,8 +56,13 @@ const usageProvider: UsageProvider = telemetry;
// enforces its decisions. Config read live so a settings change applies next beat.
const breaker = new CircuitBreaker(() => {
const c = readConfig();
- return { ...(c.circuitBreaker ?? {}), costCapUsd: c.costCapUsd };
+ return { ...(c.circuitBreaker ?? {}), costCapUsd: c.costCapUsd, costCapTokens: c.costCapTokens, agentTokenCaps: c.agentTokenCaps };
});
+// Always-on beats (decoupled from the optional heartbeat): the live fleet snapshot
+// Michael reads + the breaker beat, so guardrails + monitoring work even when the
+// heartbeat mission is disabled (it ships off).
+let fleetTimer: ReturnType<typeof setInterval> | null = null;
+let breakerBeatTimer: ReturnType<typeof setInterval> | null = null;
// Feed the breaker's api_error-storm trip from Oscar's OTel api_error spans —
// Jim's one breaker input with no on-branch source (telemetry.onApiError seam).
telemetry.onApiError((agentId) => breaker.recordError(agentId));
@@ -418,6 +423,43 @@ function runBreakerBeat(progressWindowMs: number): void {
}
}
+/** Build + write the live fleet snapshot Michael reads (`<hive>/fleet.json`).
+ * Always-on (independent of the heartbeat) since `claude agents` can't see the
+ * hive's sibling sessions. PII-free; never throws (called from a timer). */
+function writeFleetSnapshot(): void {
+ if (!hive.enabled()) return;
+ try {
+ const reg = hive.registry();
+ const snap = telemetry.snapshot();
+ const usageById = new Map(snap.usage.map((u) => [u.agentId, u]));
+ const now = Date.now();
+ const agents = Object.entries(reg.agents)
+ .filter(([, a]) => !a.archived)
+ .map(([id, a]) => {
+ const u = usageById.get(id);
+ const spans = snap.spans[id] ?? [];
+ const tokens = u ? u.input + u.output + u.cacheRead + u.cacheCreation : 0;
+ return {
+ id,
+ name: a.name,
+ role: a.role ?? (a.isGod ? 'orchestrator' : a.isAssistant ? 'assistant' : 'agent'),
+ cwd: a.cwd,
+ isGod: !!a.isGod,
+ isAssistant: !!a.isAssistant,
+ breaker: breaker.levelFor(id),
+ tokens,
+ usd: u ? Number(u.usd.toFixed(4)) : 0,
+ lastTool: spans.length ? spans[spans.length - 1].tool : null,
+ lastActiveSecAgo: u ? Math.round((now - u.ts) / 1000) : null,
+ inboxBacklog: hive.inboxBacklog(id)
+ };
+ });
+ hive.writeFleetSnapshot({ ts: now, agents });
+ } catch (e) {
+ console.error('[fleet] snapshot failed:', e);
+ }
+}
+
/** Arm the heartbeat with an adaptive, self-rescheduling cadence (recursive
* setTimeout instead of a fixed setInterval). Each beat runs the cost/breaker
* pass, re-engages a quiet floor, stamps lastFiredAt, then re-arms: ~base on a
@@ -429,7 +471,7 @@ function armHeartbeat(m: ScheduledMission): void {
const beat = (): void => {
let next = base;
try {
- runBreakerBeat(quiet); // cost ledger + breaker every beat (fresh snapshot)
+ // (the breaker beat + cost ledger now run on their own always-on timer)
if (isFloorQuiet(quiet)) {
reengageGod(buildHeartbeatDigest(quiet));
next = Math.round(base * 2.5); // back off after re-engaging
@@ -713,6 +755,9 @@ ipcMain.handle('app:copyToClipboard', (_evt, text: unknown) => {
try { clipboard.writeText(text); return { ok: true }; }
catch (e) { return { ok: false, error: e instanceof Error ? e.message : String(e) }; }
});
+ipcMain.handle('app:readClipboard', () => {
+ try { return clipboard.readText(); } catch { return ''; }
+});
// ─── IPC: folder picker ─────────────────────────────────────────────────────
ipcMain.handle('dialog:chooseFolder', async (evt) => {
@@ -1157,6 +1202,15 @@ function bootstrapHiveServices(): void {
});
memory.start(); // init shared palace + mine loop (no-op without mempalace)
reflector.start(); // bound oversized memory.md files on a timer (no-op until threshold)
+
+ // Always-on beats (decoupled from the optional heartbeat): the live fleet
+ // snapshot Michael reads (~8s) + the breaker/cost-ledger beat (~30s). Guarded so
+ // a re-bootstrap (changeHome recovery) can't stack duplicate timers.
+ if (fleetTimer) clearInterval(fleetTimer);
+ writeFleetSnapshot();
+ fleetTimer = setInterval(writeFleetSnapshot, 8_000);
+ if (breakerBeatTimer) clearInterval(breakerBeatTimer);
+ breakerBeatTimer = setInterval(() => { try { runBreakerBeat(300_000); } catch (e) { console.error('[breaker beat]', e); } }, 30_000);
}
app.whenReady().then(() => {
diff --git a/src/preload/index.ts b/src/preload/index.ts
index d02b7252..5cdabcc8 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -117,6 +117,8 @@ export interface HarnessConfig {
slackChannelId?: string;
slackPort?: number;
costCapUsd?: number;
+ costCapTokens?: number;
+ agentTokenCaps?: Record<string, number>;
maxTurns?: number;
circuitBreaker?: CircuitBreakerConfig;
}
@@ -282,6 +284,9 @@ const api = {
// ─── Clipboard ─────────────────────────────────────────────────────────────
copyToClipboard: (text: string): Promise<{ ok: boolean; error?: string }> =>
ipcRenderer.invoke('app:copyToClipboard', text),
+ /** Read the system clipboard as plain text ('' when empty/unreadable). */
+ readClipboard: (): Promise<string> =>
+ ipcRenderer.invoke('app:readClipboard'),
// ─── Config ──────────────────────────────────────────────────────────────
getConfig: (): Promise<HarnessConfig> =>
diff --git a/src/renderer/src/components/CommandCenterPanel.tsx b/src/renderer/src/components/CommandCenterPanel.tsx
index 123ae0bf..b822479a 100644
--- a/src/renderer/src/components/CommandCenterPanel.tsx
+++ b/src/renderer/src/components/CommandCenterPanel.tsx
@@ -9,7 +9,8 @@ import { TasksKanban } from './TasksKanban';
import { disposeTerminal } from './terminalPool';
import { Icon } from './Icon';
import { MemoryGraphPanel } from './MemoryGraphPanel';
-import { FleetGrid } from './FleetGrid';
+import { useFleetTelemetry } from '@/hooks/useTelemetry';
+import { COMMAND_GROUPS } from '@shared/claudeCommands';
import { useStore, type Agent } from '@/store/store';
import { usePtyParser } from '@/hooks/usePtyParser';
import { buildSpawnCommand, AGENT_MODELS } from '@/store/config';
@@ -19,7 +20,7 @@ import { buildSpawnCommand, AGENT_MODELS } from '@/store/config';
* per-agent model + dispatch + assistant access), a memory view, and a live
* activity feed / board / usage meter. */
-type CCTab = 'terminal' | 'floor' | 'fleet' | 'tasks' | 'memory' | 'graph' | 'activity' | 'handbook';
+type CCTab = 'terminal' | 'floor' | 'tasks' | 'memory' | 'graph' | 'activity' | 'handbook';
/** A recurring auto-dispatched mission (mirrors the main-process config type). */
interface ScheduledMission {
@@ -47,6 +48,11 @@ function relTime(ms: number): string {
return past ? `${unit} ago` : `in ${unit}`;
}
+/** Fallback denominator for the per-agent token meter when no floor token budget
+ * is configured — so the bar reads as a budget estimate (filled + remaining)
+ * rather than being pinned to 100% for whichever agent burns the most tokens. */
+const DEFAULT_TOKEN_CAP = 1_000_000;
+
/** Interval presets offered in the SCHEDULES form / shown as badges. */
const INTERVAL_OPTS: { ms: number; label: string }[] = [
{ ms: 3600000, label: '1h' },
@@ -65,18 +71,9 @@ interface GHIssue {
assignees: string[];
}
-/** A CI run as returned by `window.cth.githubCIRuns` (GitHub Actions workflow runs). */
-interface CIRun {
- name: string;
- status: string;
- conclusion: string | null;
- url: string;
-}
-
const TABS: { key: CCTab; label: string; icon: Parameters<typeof Icon>[0]['name'] }[] = [
{ key: 'terminal', label: 'terminal', icon: 'terminal' },
- { key: 'floor', label: 'floor', icon: 'mcp' },
- { key: 'fleet', label: 'fleet', icon: 'gear' },
+ { key: 'floor', label: 'monitor', icon: 'mcp' },
{ key: 'tasks', label: 'tasks', icon: 'check' },
{ key: 'memory', label: 'memory', icon: 'sparkle' },
{ key: 'graph', label: 'graph', icon: 'web' },
@@ -181,7 +178,6 @@ export function CommandCenterPanel({ agent }: { agent: Agent }) {
)
)}
{tab === 'floor' && <FloorTab seed={dispatchSeed} />}
- {tab === 'fleet' && <FleetTab />}
{tab === 'tasks' && (
<TasksKanban
onAssign={(prefill) => {
@@ -215,7 +211,15 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
const enrichEnabled = useStore((s) => s.enrichEnabled);
const setEnrichEnabled = useStore((s) => s.setEnrichEnabled);
const toolCounts = useStore((s) => s.toolCounts);
+ // Live OpenTelemetry per agent — merged into each agent card below (the old
+ // standalone Fleet tab folded in here so the roster shows identity + controls
+ // AND live cost/usage in one place).
+ const { samples, spark, rate, lastTool, breakers } = useFleetTelemetry();
const [repos, setRepos] = useState<string[]>([]);
+ // Floor-wide token budget (drives the breaker); also the token-meter denominator.
+ const [tokenCap, setTokenCap] = useState<number | undefined>(undefined);
+ // Per-agent token limit (overrides the floor budget for that agent), keyed by id.
+ const [agentTokenCaps, setAgentTokenCaps] = useState<Record<string, number>>({});
const [restarting, setRestarting] = useState<string | null>(null);
const [dispatchTo, setDispatchTo] = useState<string>('broadcast');
const [dispatchText, setDispatchText] = useState('');
@@ -234,7 +238,11 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
const [mBody, setMBody] = useState('');
useEffect(() => {
- window.cth.getConfig().then((c) => setRepos(c.registeredRepos ?? [])).catch(() => { /* noop */ });
+ window.cth.getConfig().then((c) => {
+ setRepos(c.registeredRepos ?? []);
+ setTokenCap(c.costCapTokens);
+ setAgentTokenCaps(c.agentTokenCaps ?? {});
+ }).catch(() => { /* noop */ });
window.cth.listMissions().then(setMissions).catch(() => { /* noop */ });
// Refresh "last fired" when the scheduler stamps a beat/dispatch (#2.3).
const off = window.cth.onMissionsUpdated(() => {
@@ -336,6 +344,33 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
setDispatchTo('broadcast');
};
+ // 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.
+ 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 */ });
+ };
+
+ // The token meter is scaled to the agent's own limit when set, else the floor
+ // token budget — so each bar reads as "tokens used vs budget" with the remaining
+ // headroom visible, never pinned to a useless 100%.
+ const floorCap = tokenCap && tokenCap > 0 ? tokenCap : DEFAULT_TOKEN_CAP;
+ // Fleet totals across the roster (for the AGENTS summary band).
+ let sumTokens = 0, sumInput = 0, sumCacheRead = 0, sumRate = 0;
+ for (const a of agents) {
+ const s = samples[a.id];
+ if (s) {
+ sumTokens += s.input + s.output + s.cacheRead + s.cacheCreation;
+ sumInput += s.input + s.cacheRead + s.cacheCreation;
+ sumCacheRead += s.cacheRead;
+ }
+ sumRate += rate[a.id] ?? 0;
+ }
+ const fleetCachePct = sumInput > 0 ? Math.round((sumCacheRead / sumInput) * 100) : 0;
+
return (
<Scroll>
<Section title="DISPATCH">
@@ -364,11 +399,26 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
</Section>
<Section title="AGENTS">
- {agents.map((a) => (
+ {agents.map((a) => {
+ const sample = samples[a.id];
+ const breaker = breakers[a.id];
+ const armed = !!breaker && (breaker.level === 'constrained' || breaker.level === 'stopped');
+ const tokens = sample ? sample.input + sample.output + sample.cacheRead + sample.cacheCreation : 0;
+ const agentCap = agentTokenCaps[a.id]; // per-agent limit, if set
+ const denom = agentCap && agentCap > 0 ? agentCap : floorCap;
+ const pct = Math.min(100, Math.round((tokens / denom) * 100));
+ const meterColor = armed || pct >= 90 ? 'var(--cth-coral)' : pct >= 60 ? 'var(--cth-lemon)' : 'var(--cth-mint)';
+ // Sparkline only when the agent is actually burning tokens; otherwise the
+ // flat baseline is just a mystery line. Label it with the live rate.
+ const sparkSeries = spark[a.id] ?? [];
+ const hasSpark = sparkSeries.some((v) => v > 0);
+ const rateVal = Math.round(rate[a.id] ?? 0);
+ const rateLabel = rateVal > 0 ? `${fmtTokens(rateVal)}/m` : 'rate';
+ return (
<div key={a.id} style={{
display: 'flex', flexDirection: 'column', gap: 4,
padding: 6, marginBottom: 6,
- background: 'var(--cth-paper-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)'
+ background: armed ? 'var(--cth-coral-light)' : 'var(--cth-paper-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<div style={{
@@ -385,12 +435,39 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
fontFamily: 'var(--cth-font-ui)', fontSize: 13, color: 'var(--cth-ink-900)'
}}
>{a.name}{a.isGod ? ' (god)' : a.isAssistant ? ' (assistant)' : ''}</button>
- <PixelBadge status={a.status} />
+ <PixelBadge status={armed ? 'looping' : a.status} />
+ {armed && <span title={breaker?.reason} style={{ color: 'var(--cth-coral)', fontSize: 12 }}>⚠</span>}
<span style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--cth-ink-500)' }}>
{(toolCounts[a.id] ?? 0)} tool calls
</span>
+ <TokenLimitEditor value={agentCap} onSet={(t) => setAgentCap(a.id, t)} />
</div>
<div style={{ fontSize: 11, color: 'var(--cth-ink-500)', wordBreak: 'break-all' }}>{a.cwd}</div>
+ {/* Live telemetry (folded in from the old Fleet tab) */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
+ {hasSpark ? (
+ <span style={{ flex: 1, minWidth: 0, display: 'inline-flex', alignItems: 'center', gap: 5 }}>
+ <span style={{ fontFamily: 'var(--cth-font-mono)', fontSize: 10, color: 'var(--cth-ink-500)', flexShrink: 0 }}>{rateLabel}</span>
+ <Sparkline series={sparkSeries} />
+ </span>
+ ) : (
+ <span style={{ flex: 1 }} />
+ )}
+ {lastTool[a.id] && (
+ <span style={{
+ fontSize: 10, lineHeight: '14px', padding: '0 5px', flexShrink: 0,
+ background: 'var(--cth-paper-200)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)', color: 'var(--cth-ink-700)'
+ }}>{lastTool[a.id]}</span>
+ )}
+ <span style={{ fontFamily: 'var(--cth-font-mono)', fontSize: 11, color: 'var(--cth-ink-900)', width: 56, textAlign: 'right' }}>{fmtTokens(tokens)}</span>
+ <div
+ title={`${tokens.toLocaleString()} of ${denom.toLocaleString()} tokens${agentCap ? ' (agent limit)' : ' (floor budget)'}`}
+ style={{ width: 96, height: 8, background: 'var(--cth-cream-200)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)', flexShrink: 0 }}
+ >
+ <div style={{ width: `${pct}%`, height: '100%', background: meterColor }} />
+ </div>
+ <span style={{ fontFamily: 'var(--cth-font-mono)', fontSize: 11, color: 'var(--cth-ink-500)', width: 30, textAlign: 'right' }}>{pct}%</span>
+ </div>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<Select
value={a.model ?? ''}
@@ -406,7 +483,24 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
</span>
</div>
</div>
- ))}
+ );
+ })}
+ {/* Fleet summary band */}
+ <div style={{
+ display: 'flex', gap: 14, marginTop: 2, padding: '6px 8px',
+ background: 'var(--cth-cream-200)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',
+ fontFamily: 'var(--cth-font-mono)', fontSize: 11, color: 'var(--cth-ink-900)', flexWrap: 'wrap'
+ }}>
+ <span>Σ <strong>{fmtTokens(sumTokens)}</strong> tok</span>
+ <span style={{ color: 'var(--cth-ink-700)' }}>inputs {fmtTokens(sumInput)} (cache {fleetCachePct}%)</span>
+ <span style={{ color: 'var(--cth-ink-700)' }}>{Math.round(sumRate).toLocaleString()} tok/min</span>
+ </div>
+ <div style={{ marginTop: 6 }}>
+ <Muted>
+ live from each agent&apos;s OpenTelemetry · bars show tokens used vs each agent&apos;s limit, else the {fmtTokens(floorCap)} floor budget
+ {tokenCap && tokenCap > 0 ? '' : ' (default — set a floor token budget in Settings)'}
+ </Muted>
+ </div>
</Section>
<ArchivedSection />
@@ -717,35 +811,91 @@ function MemoryTab({ godId, who: controlledWho, onWho }: { godId: string; who?:
);
}
-// ─── Fleet tab — the live control-room overview (#7B.1) ──────────────────────
+// ─── Fleet telemetry bits (folded into the Floor AGENTS cards) ───────────────
-function FleetTab() {
+/** Block-character sparkline of recent token deltas — neo-brutalist mono. */
+function Sparkline({ series }: { series: number[] }) {
+ const blocks = '▁▂▃▄▅▆▇█';
+ const max = Math.max(1, ...series);
+ const text = series.length
+ ? series.map((v) => blocks[Math.min(blocks.length - 1, Math.round((v / max) * (blocks.length - 1)))]).join('')
+ : '▁▁▁▁▁▁';
return (
- <Scroll>
- <Section title="FLEET (live telemetry)">
- <FleetGrid />
- <div style={{ marginTop: 6 }}>
- <Muted>live from each agent&apos;s OpenTelemetry · cost is Claude&apos;s own per-model figure</Muted>
- </div>
- </Section>
- </Scroll>
+ <span style={{ flex: 1, fontFamily: 'var(--cth-font-mono)', fontSize: 12, lineHeight: '12px', color: 'var(--cth-sky)', whiteSpace: 'nowrap', overflow: 'hidden', minWidth: 0 }}>
+ {text}
+ </span>
+ );
+}
+
+/** Compact token count: 1K / 10K / 100K / 1M / 100M / 1B (trailing .0 trimmed). */
+function fmtTokens(n: number): string {
+ if (n >= 1e9) return `${+(n / 1e9).toFixed(2)}B`;
+ if (n >= 1e6) return `${+(n / 1e6).toFixed(1)}M`;
+ if (n >= 1e3) return `${+(n / 1e3).toFixed(1)}K`;
+ return String(Math.round(n));
+}
+
+/** Per-agent token-limit control (top-right of each agent card). Shows the
+ * current limit as a lemon chip, or "set limit"; click to edit a token number.
+ * Enter / ✓ / blur commit; Escape cancels. */
+function TokenLimitEditor({ value, onSet }: { value?: number; onSet: (tokens: number | undefined) => void }) {
+ const [editing, setEditing] = useState(false);
+ const [text, setText] = useState(value != null ? String(value) : '');
+ const skipBlur = useRef(false);
+ const commit = () => {
+ const raw = text.trim();
+ const n = raw === '' ? undefined : Number(raw);
+ onSet(typeof n === 'number' && Number.isFinite(n) && n > 0 ? n : undefined);
+ setEditing(false);
+ };
+ if (!editing) {
+ return (
+ <button
+ onClick={() => { setText(value != null ? String(value) : ''); setEditing(true); }}
+ title="Set this agent's total token limit"
+ style={{
+ flexShrink: 0, padding: '1px 6px', border: 'none', cursor: 'pointer',
+ background: value && value > 0 ? 'var(--cth-lemon)' : 'var(--cth-cream-200)',
+ boxShadow: `inset 0 0 0 1px ${value && value > 0 ? 'var(--cth-ink-900)' : 'var(--cth-ink-700)'}`,
+ fontFamily: 'var(--cth-font-ui)', fontSize: 11, color: 'var(--cth-ink-900)'
+ }}
+ >{value && value > 0
+ ? <>limit <span style={{ fontFamily: 'var(--cth-font-mono)' }}>{fmtTokens(value)}</span></>
+ : 'set limit'}</button>
+ );
+ }
+ return (
+ <span style={{ flexShrink: 0, display: 'inline-flex', alignItems: 'center', gap: 3 }}>
+ <input
+ type="number" min="0" step="100000" value={text} autoFocus
+ onChange={(e) => setText(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') commit();
+ else if (e.key === 'Escape') { skipBlur.current = true; setEditing(false); }
+ }}
+ onBlur={() => { if (skipBlur.current) { skipBlur.current = false; return; } commit(); }}
+ placeholder="tokens"
+ style={{
+ width: 84, padding: '2px 4px', background: 'var(--cth-paper-100)', border: 'none',
+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)', fontFamily: 'var(--cth-font-mono)',
+ fontSize: 11, color: 'var(--cth-ink-900)', outline: 'none'
+ }}
+ />
+ <button
+ onMouseDown={(e) => e.preventDefault()} onClick={commit} title="Save limit"
+ style={{ flexShrink: 0, padding: '1px 5px', border: 'none', cursor: 'pointer', background: 'var(--cth-mint)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-900)', fontSize: 11, color: 'var(--cth-ink-900)' }}
+ >✓</button>
+ </span>
);
}
-// ─── Activity tab — log feed + board + usage ─────────────────────────────────
+// ─── Activity tab — hive event log + board ───────────────────────────────────
interface LogEntry { ts?: number; kind?: string; [k: string]: unknown }
function ActivityTab() {
- const agents = useStore((s) => s.agents);
const [log, setLog] = useState<LogEntry[]>([]);
const [board, setBoard] = useState('');
- // Per-agent estimated cost, reported up by each UsageRow so the bars can be
- // normalized against the most-expensive agent in the office.
- const [costs, setCosts] = useState<Record<string, number>>({});
- const reportCost = (id: string) => (cost: number) =>
- setCosts((prev) => (prev[id] === cost ? prev : { ...prev, [id]: cost }));
- const maxCost = Math.max(0.0001, ...agents.map((a) => costs[a.id] ?? 0));
const timer = useRef<ReturnType<typeof setInterval> | null>(null);
useEffect(() => {
@@ -771,15 +921,6 @@ function ActivityTab() {
return (
<Scroll>
- <CIStatusSection />
-
- <Section title="USAGE (this session)">
- {agents.map((a) => (
- <UsageRow key={a.id} name={a.name} cwd={a.cwd} maxCost={maxCost} onCost={reportCost(a.id)} />
- ))}
- <Muted>tokens from ~/.claude/projects/ transcripts</Muted>
- </Section>
-
<Section title="ACTIVITY">
{log.length === 0 && <Muted>Nothing yet.</Muted>}
{[...log].reverse().map((e, i) => (
@@ -797,239 +938,8 @@ function ActivityTab() {
);
}
-/** One agent's real token usage, polled from its Claude Code transcripts on
- * mount and every 10s. Renders: name | input Kt | output Kt | est $X.XX, with
- * a bar normalized to the most-expensive agent (via the lifted-up cost). */
-function UsageRow({ name, cwd, maxCost, onCost }: {
- name: string; cwd: string; maxCost: number; onCost: (cost: number) => void;
-}) {
- const [usage, setUsage] = useState<{ inputTokens: number; outputTokens: number; estimatedCostUsd: number } | null>(null);
-
- useEffect(() => {
- let alive = true;
- const refresh = async () => {
- try {
- const u = await window.cth.agentUsage(cwd);
- if (!alive || !u) return;
- setUsage(u);
- onCost(u.estimatedCostUsd);
- } catch { /* noop */ }
- };
- refresh();
- const id = setInterval(refresh, 10000);
- return () => { alive = false; clearInterval(id); };
- // onCost is recreated each render but stable in behavior; cwd is the real key.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [cwd]);
-
- const inK = usage ? (usage.inputTokens / 1000).toFixed(1) : '0.0';
- const outK = usage ? (usage.outputTokens / 1000).toFixed(1) : '0.0';
- const cost = usage?.estimatedCostUsd ?? 0;
-
- return (
- <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2 }}>
- <span style={{ fontSize: 12, color: 'var(--cth-ink-700)', width: 90 }}>{name}</span>
- <Bar value={cost} max={maxCost} />
- <span style={{ fontSize: 11, color: 'var(--cth-ink-500)', width: 56, textAlign: 'right' }}>{inK}/{outK}Kt</span>
- <span style={{ fontSize: 11, color: 'var(--cth-ink-700)', width: 52, textAlign: 'right' }}>${cost.toFixed(2)}</span>
- </div>
- );
-}
-
-// ─── CI status — per-repo latest workflow run, polled every 30s ──────────────
-
-/** Per-repo CI poll result: the latest run plus any error surfaced by the IPC. */
-interface RepoCIState {
- run: CIRun | null;
- error: string | null;
-}
-
-/** A run failed if it completed with a non-success conclusion. */
-function ciFailed(run: CIRun): boolean {
- return run.status === 'completed' && run.conclusion !== null && run.conclusion !== 'success';
-}
-
-/** Status chip: green=success, red=failure, yellow=in_progress/queued. */
-function CIChip({ run }: { run: CIRun }) {
- let bg = 'var(--cth-lemon)';
- let label = run.status || 'queued';
- if (run.status === 'completed') {
- if (run.conclusion === 'success') { bg = 'var(--cth-mint)'; label = 'success'; }
- else { bg = 'var(--cth-coral)'; label = run.conclusion || 'failed'; }
- }
- return (
- <span style={{
- fontSize: 10, lineHeight: '14px', padding: '0 6px', flexShrink: 0,
- background: bg, boxShadow: 'inset 0 0 0 1px var(--cth-ink-900)', color: 'var(--cth-ink-900)'
- }}>{label}</span>
- );
-}
-
-/** Polls `githubCIRuns` for every registered repo every 30s. gh being missing
- * or unauthenticated surfaces as a muted per-repo error — never a crash. */
-function CIStatusSection() {
- const [repos, setRepos] = useState<string[]>([]);
- const [states, setStates] = useState<Record<string, RepoCIState>>({});
- const [copied, setCopied] = useState<string | null>(null);
- const timer = useRef<ReturnType<typeof setInterval> | null>(null);
-
- useEffect(() => {
- window.cth.getConfig().then((c) => setRepos(c.registeredRepos ?? [])).catch(() => { /* noop */ });
- }, []);
-
- useEffect(() => {
- if (repos.length === 0) return;
- let cancelled = false;
- const refresh = async () => {
- const next: Record<string, RepoCIState> = {};
- for (const repo of repos) {
- try {
- const res = await window.cth.githubCIRuns(repo);
- next[repo] = res.ok
- ? { run: (res.runs ?? [])[0] ?? null, error: null }
- : { run: null, error: res.error ?? 'Failed to fetch CI runs.' };
- } catch (e) {
- next[repo] = { run: null, error: e instanceof Error ? e.message : String(e) };
- }
- }
- if (!cancelled) setStates(next);
- };
- refresh();
- timer.current = setInterval(refresh, 30000);
- return () => { cancelled = true; if (timer.current) clearInterval(timer.current); };
- }, [repos]);
-
- const copyUrl = async (url: string) => {
- try {
- await window.cth.copyToClipboard(url);
- setCopied(url);
- setTimeout(() => setCopied((c) => (c === url ? null : c)), 1300);
- } catch { /* noop */ }
- };
-
- if (repos.length === 0) return null;
-
- return (
- <Section title="CI STATUS">
- {repos.map((repo) => {
- const st = states[repo];
- const short = repo.split('/').filter(Boolean).pop() || repo;
- const run = st?.run ?? null;
- return (
- <div key={repo} style={{
- display: 'flex', flexDirection: 'column', gap: 4,
- padding: 6, marginBottom: 6,
- background: 'var(--cth-paper-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)'
- }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
- <span style={{ flex: 1, fontSize: 12, color: 'var(--cth-ink-900)', wordBreak: 'break-word' }}>{short}</span>
- {run && <CIChip run={run} />}
- </div>
- {run && (
- <div style={{ fontSize: 11, color: 'var(--cth-ink-500)', wordBreak: 'break-word' }}>
- {run.name || 'workflow'}
- </div>
- )}
- {!st && <Muted>checking…</Muted>}
- {st && !run && !st.error && <Muted>No runs yet.</Muted>}
- {st?.error && (
- <div style={{ fontSize: 11, color: 'var(--cth-ink-500)', wordBreak: 'break-word' }}>{st.error}</div>
- )}
- {run && ciFailed(run) && run.url && (
- <button
- onClick={() => copyUrl(run.url)}
- title="Copy the failing run's URL"
- style={{
- alignSelf: 'flex-start', display: 'inline-flex', alignItems: 'center', gap: 4,
- padding: '2px 7px 1px', border: 'none', cursor: 'pointer',
- background: copied === run.url ? 'var(--cth-mint)' : 'var(--cth-cream-200)',
- boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',
- fontFamily: 'var(--cth-font-ui)', fontSize: 11, color: 'var(--cth-ink-900)'
- }}
- ><Icon name={copied === run.url ? 'check' : 'code'} /> {copied === run.url ? 'copied' : 'copy run URL'}</button>
- )}
- </div>
- );
- })}
- </Section>
- );
-}
-
// ─── Handbook tab — copyable Claude command reference ────────────────────────
-interface Cmd { cmd: string; kind: 'slash' | 'cli'; desc: string; usage?: string }
-interface CmdGroup { title: string; items: Cmd[] }
-
-const HANDBOOK: CmdGroup[] = [
- {
- title: 'SESSION',
- items: [
- { cmd: '/clear', kind: 'slash', desc: 'Wipe the conversation and reclaim the full context window. Start fresh.' },
- { cmd: '/compact', kind: 'slash', desc: 'Summarize the conversation so far to free up context without losing the thread.', usage: '/compact focus on the auth refactor' },
- { cmd: '/cost', kind: 'slash', desc: 'Show token usage and dollar cost for the current session.' },
- { cmd: '/status', kind: 'slash', desc: 'Show account, active model, and connection status.' },
- { cmd: 'claude -c', kind: 'cli', desc: 'Continue the most recent session in this directory.' },
- { cmd: 'claude -r', kind: 'cli', desc: 'Resume — pick a past session to continue.' }
- ]
- },
- {
- title: 'MODELS',
- items: [
- { cmd: '/model', kind: 'slash', desc: 'Switch the model for this session.', usage: '/model opus · /model sonnet' },
- { cmd: 'claude --model claude-sonnet-4-6[1m]', kind: 'cli', desc: 'Launch on a specific model. The [1m] suffix selects the 1M-token context window (used by Dwight).' }
- ]
- },
- {
- title: 'CONTEXT & MEMORY',
- items: [
- { cmd: '/init', kind: 'slash', desc: 'Scan the repo and generate a CLAUDE.md capturing its conventions.' },
- { cmd: '/memory', kind: 'slash', desc: 'Open the project & user memory files for editing.' },
- { cmd: '# ', kind: 'slash', desc: 'Quick memory: start a message with # to append a durable note to memory.', usage: '# always run prettier before committing' },
- { cmd: 'claude --add-dir ../other-repo', kind: 'cli', desc: 'Grant the session read/write access to an extra directory.' }
- ]
- },
- {
- title: 'TOOLS & PERMISSIONS',
- items: [
- { cmd: '/permissions', kind: 'slash', desc: 'View and edit which tools are allowed or denied.' },
- { cmd: '/hooks', kind: 'slash', desc: 'Configure lifecycle hooks (PreToolUse, Stop, etc.).' },
- { cmd: 'claude --permission-mode bypassPermissions', kind: 'cli', desc: 'Run without per-tool approval prompts (this is what "auto mode" uses).' }
- ]
- },
- {
- title: 'MCP',
- items: [
- { cmd: '/mcp', kind: 'slash', desc: 'List/manage connected MCP servers and authenticate.' },
- { cmd: 'claude mcp list', kind: 'cli', desc: 'List configured MCP servers.' },
- { cmd: 'claude mcp add <name> <command>', kind: 'cli', desc: 'Register a new MCP server.' }
- ]
- },
- {
- title: 'AUTOMATION (HEADLESS)',
- items: [
- { cmd: 'claude -p "your prompt"', kind: 'cli', desc: 'Print mode: run one prompt non-interactively and exit.' },
- { cmd: 'claude -p "your prompt" --output-format json', kind: 'cli', desc: 'Headless with structured JSON output (result, usage, cost) — the mechanism behind enrichment.' },
- { cmd: 'claude -c -p "follow-up"', kind: 'cli', desc: 'Continue the last session headlessly with a follow-up prompt.' }
- ]
- },
- {
- title: 'REVIEW · GIT · AGENTS',
- items: [
- { cmd: '/review', kind: 'slash', desc: 'Review the current diff / PR for issues.' },
- { cmd: '/pr-comments', kind: 'slash', desc: 'Fetch and work through PR review comments.' },
- { cmd: '/agents', kind: 'slash', desc: 'Create and manage subagents for delegated work.' }
- ]
- },
- {
- title: 'HELP',
- items: [
- { cmd: '/help', kind: 'slash', desc: 'List every available slash command.' },
- { cmd: '/doctor', kind: 'slash', desc: 'Diagnose installation / health issues.' },
- { cmd: '/vim', kind: 'slash', desc: 'Toggle vim keybindings in the prompt box.' }
- ]
- }
-];
-
function HandbookTab() {
const [copied, setCopied] = useState<string | null>(null);
const copy = async (cmd: string) => {
@@ -1040,7 +950,7 @@ function HandbookTab() {
<Scroll>
<Muted>Click any command to copy it. Slash commands run inside Claude Code; CLI commands run in a shell.</Muted>
<div style={{ height: 8 }} />
- {HANDBOOK.map((g) => (
+ {COMMAND_GROUPS.map((g) => (
<Section key={g.title} title={g.title}>
{g.items.map((it) => (
<div key={it.cmd} style={{
@@ -1125,15 +1035,6 @@ function Pre({ children }: { children: React.ReactNode }) {
);
}
-function Bar({ value, max }: { value: number; max: number }) {
- const pct = Math.round((value / max) * 100);
- return (
- <div style={{ flex: 1, height: 8, background: 'var(--cth-cream-200)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)' }}>
- <div style={{ width: `${pct}%`, height: '100%', background: 'var(--cth-mint)' }} />
- </div>
- );
-}
-
const textareaStyle: React.CSSProperties = {
flex: 1, width: '100%', resize: 'none', padding: '6px 8px',
background: 'var(--cth-paper-100)', border: 'none',
diff --git a/src/renderer/src/components/FleetGrid.tsx b/src/renderer/src/components/FleetGrid.tsx
deleted file mode 100644
index 55aef847..00000000
--- a/src/renderer/src/components/FleetGrid.tsx
+++ /dev/null
@@ -1,146 +0,0 @@
-import { useStore } from '@/store/store';
-import { SpritePortrait } from './SpritePortrait';
-import { PixelBadge } from './PixelBadge';
-import {
- useFleetTelemetry,
- type AgentUsageSample, type BreakerState
-} from '@/hooks/useTelemetry';
-
-/**
- * FLEET — the control-room overview (#7B.1). One cell per live agent: sprite,
- * status, live cost, a tokens-burned sparkline, the last tool, and a budget
- * meter normalized to the priciest agent and colored by headroom. A circuit
- * breaker (Lane A #6) flips the row to a coral ⚠ state. All styling derives from
- * the design tokens — no new palette.
- */
-export function FleetGrid() {
- const agents = useStore((s) => s.agents);
- const live = agents.filter((a) => a.ptyId);
- const { samples, spark, rate, lastTool, breakers } = useFleetTelemetry();
-
- const maxCost = Math.max(0.0001, ...live.map((a) => samples[a.id]?.usd ?? 0));
-
- // Fleet totals.
- let sumCost = 0;
- let sumInput = 0;
- let sumCacheRead = 0;
- let sumRate = 0;
- for (const a of live) {
- const s = samples[a.id];
- if (s) { sumCost += s.usd; sumInput += s.input + s.cacheRead + s.cacheCreation; sumCacheRead += s.cacheRead; }
- sumRate += rate[a.id] ?? 0;
- }
- const fleetCachePct = sumInput > 0 ? Math.round((sumCacheRead / sumInput) * 100) : 0;
-
- if (live.length === 0) {
- return (
- <div style={{ fontSize: 12, color: 'var(--cth-ink-500)', padding: 8 }}>
- No live agents. Spawn one and its telemetry appears here in real time.
- </div>
- );
- }
-
- return (
- <div>
- <div style={{
- display: 'grid', gridTemplateColumns: '24px 1fr auto', gap: 0,
- boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)', background: 'var(--cth-paper-100)'
- }}>
- {live.map((a) => (
- <FleetCell
- key={a.id}
- name={a.name}
- character={a.character}
- status={a.status}
- sample={samples[a.id]}
- maxCost={maxCost}
- spark={spark[a.id] ?? []}
- tool={lastTool[a.id]}
- breaker={breakers[a.id]}
- />
- ))}
- </div>
- {/* Fleet summary band */}
- <div style={{
- display: 'flex', gap: 14, marginTop: 8, padding: '6px 8px',
- background: 'var(--cth-cream-200)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',
- fontFamily: 'var(--cth-font-mono)', fontSize: 11, color: 'var(--cth-ink-900)', flexWrap: 'wrap'
- }}>
- <span>Σ <strong>${sumCost.toFixed(2)}</strong></span>
- <span style={{ color: 'var(--cth-ink-700)' }}>inputs {fmtTokens(sumInput)} (cache {fleetCachePct}%)</span>
- <span style={{ color: 'var(--cth-ink-700)' }}>{Math.round(sumRate).toLocaleString()} tok/min</span>
- </div>
- </div>
- );
-}
-
-function FleetCell({ name, character, status, sample, maxCost, spark, tool, breaker }: {
- name: string;
- character: Parameters<typeof SpritePortrait>[0]['character'];
- status: Parameters<typeof PixelBadge>[0]['status'];
- sample?: AgentUsageSample;
- maxCost: number;
- spark: number[];
- tool?: string;
- breaker?: BreakerState;
-}) {
- const cost = sample?.usd ?? 0;
- const pct = Math.min(100, Math.round((cost / maxCost) * 100));
- const armed = breaker && (breaker.level === 'constrained' || breaker.level === 'stopped');
- const meterColor = armed
- ? 'var(--cth-coral)'
- : pct >= 90 ? 'var(--cth-coral)' : pct >= 60 ? 'var(--cth-lemon)' : 'var(--cth-mint)';
-
- const cellBg = armed ? 'var(--cth-coral-light)' : 'transparent';
- const rowBorder = 'inset 0 -1px 0 var(--cth-ink-300)';
-
- return (
- <>
- {/* sprite */}
- <div style={{ boxShadow: rowBorder, background: cellBg, display: 'flex', alignItems: 'center', justifyContent: 'center', height: 30, overflow: 'hidden' }}>
- <SpritePortrait character={character} scale={1} />
- </div>
- {/* name + status + sparkline + tool */}
- <div style={{ boxShadow: rowBorder, background: cellBg, display: 'flex', alignItems: 'center', gap: 6, padding: '0 8px', minWidth: 0 }}>
- <span style={{ fontSize: 12, color: 'var(--cth-ink-900)', width: 64, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{name}</span>
- <PixelBadge status={armed ? 'looping' : status} />
- <Sparkline series={spark} />
- {tool && (
- <span style={{
- fontSize: 10, lineHeight: '14px', padding: '0 5px', flexShrink: 0,
- background: 'var(--cth-paper-200)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)', color: 'var(--cth-ink-700)'
- }}>{tool}</span>
- )}
- {armed && <span title={breaker?.reason} style={{ color: 'var(--cth-coral)', fontSize: 12 }}>⚠</span>}
- </div>
- {/* cost + budget meter */}
- <div style={{ boxShadow: rowBorder, background: cellBg, display: 'flex', alignItems: 'center', gap: 6, padding: '0 8px' }}>
- <span style={{ fontFamily: 'var(--cth-font-mono)', fontSize: 11, color: 'var(--cth-ink-900)', width: 52, textAlign: 'right' }}>${cost.toFixed(2)}</span>
- <div style={{ width: 70, height: 8, background: 'var(--cth-cream-200)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)' }}>
- <div style={{ width: `${pct}%`, height: '100%', background: meterColor }} />
- </div>
- <span style={{ fontSize: 10, color: 'var(--cth-ink-500)', width: 28, textAlign: 'right' }}>{pct}%</span>
- </div>
- </>
- );
-}
-
-/** Block-character sparkline — matches the neo-brutalist mono aesthetic. */
-function Sparkline({ series }: { series: number[] }) {
- const blocks = '▁▂▃▄▅▆▇█';
- const max = Math.max(1, ...series);
- const text = series.length
- ? series.map((v) => blocks[Math.min(blocks.length - 1, Math.round((v / max) * (blocks.length - 1)))]).join('')
- : '▁▁▁▁▁▁';
- return (
- <span style={{ flex: 1, fontFamily: 'var(--cth-font-mono)', fontSize: 12, lineHeight: '12px', color: 'var(--cth-sky)', whiteSpace: 'nowrap', overflow: 'hidden', minWidth: 0 }}>
- {text}
- </span>
- );
-}
-
-function fmtTokens(n: number): string {
- if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
- if (n >= 1_000) return `${(n / 1_000).toFixed(0)}K`;
- return String(n);
-}
diff --git a/src/renderer/src/components/MessageQueueComposer.tsx b/src/renderer/src/components/MessageQueueComposer.tsx
index e44faea4..9382fc03 100644
--- a/src/renderer/src/components/MessageQueueComposer.tsx
+++ b/src/renderer/src/components/MessageQueueComposer.tsx
@@ -1,4 +1,4 @@
-import { useState, KeyboardEvent } from 'react';
+import { KeyboardEvent } from 'react';
import { PixelButton } from './PixelButton';
import { Icon } from './Icon';
import { useStore, type Agent, type QueuedMessage } from '@/store/store';
@@ -26,7 +26,11 @@ export function MessageQueueComposer({ agent }: MessageQueueComposerProps) {
const enrichEnabled = useStore((s) => s.enrichEnabled);
const setEnrichEnabled = useStore((s) => s.setEnrichEnabled);
- const [text, setText] = useState('');
+ // Draft lives in the store, keyed by agent — switching agents remounts this
+ // component, and component-local state would silently eat the typed text.
+ const text = useStore((s) => s.drafts[agent.id] ?? '');
+ const setDraft = useStore((s) => s.setDraft);
+ const setText = (t: string) => setDraft(agent.id, t);
// The enrich toggle governs Michael's queue (it routes through the assistant).
const showEnrichToggle = !!agent.isGod;
diff --git a/src/renderer/src/components/SettingsModal.tsx b/src/renderer/src/components/SettingsModal.tsx
index 32057287..b4224d5b 100644
--- a/src/renderer/src/components/SettingsModal.tsx
+++ b/src/renderer/src/components/SettingsModal.tsx
@@ -1,4 +1,4 @@
-import { useState, type CSSProperties } from 'react';
+import { useState, useEffect, type CSSProperties } from 'react';
import type { HarnessConfig } from '@/store/config';
import { PixelPanel } from './PixelPanel';
import { PixelButton } from './PixelButton';
@@ -74,23 +74,23 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {
};
// ─── circuit-breaker config (Lane A #6 canonical fields, widened view) ───────
- // Drives Jim's real breaker: floor-wide cost cap (costCapUsd) + output-token
- // velocity ceiling (circuitBreaker.tokenVelocityPerMin). The interim Lane C
- // knobs were dropped at integration.
+ // Drives Jim's real breaker: floor-wide TOKEN budget (costCapTokens) + output-
+ // token velocity ceiling (circuitBreaker.tokenVelocityPerMin). The token cap
+ // replaced the old dollar cap as the user-facing budget.
type BreakerCfgView = HarnessConfig & {
- costCapUsd?: number;
+ costCapTokens?: number;
circuitBreaker?: { tokenVelocityPerMin?: number; enabled?: boolean; hardStop?: boolean; repeatedToolLimit?: number; errorStormLimit?: number };
};
const breakerCfg = config as BreakerCfgView;
- const [agentBudget, setAgentBudget] = useState(breakerCfg.costCapUsd != null ? String(breakerCfg.costCapUsd) : '');
+ const [agentBudget, setAgentBudget] = useState(breakerCfg.costCapTokens != null ? String(breakerCfg.costCapTokens) : '');
const [velocityCeiling, setVelocityCeiling] = useState(breakerCfg.circuitBreaker?.tokenVelocityPerMin != null ? String(breakerCfg.circuitBreaker.tokenVelocityPerMin) : '');
const [budgetNote, setBudgetNote] = useState('');
const saveBudget = async () => {
// Empty input clears the cap (undefined = off).
- const usd = agentBudget.trim() === '' ? undefined : Number(agentBudget);
+ const tokens = agentBudget.trim() === '' ? undefined : Number(agentBudget);
const vel = velocityCeiling.trim() === '' ? undefined : Number(velocityCeiling);
await window.cth.updateConfig({
- costCapUsd: Number.isFinite(usd as number) ? (usd as number) : undefined,
+ costCapTokens: Number.isFinite(tokens as number) ? (tokens as number) : undefined,
circuitBreaker: {
...(breakerCfg.circuitBreaker ?? {}),
tokenVelocityPerMin: Number.isFinite(vel as number) ? (vel as number) : undefined
@@ -99,6 +99,15 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {
setBudgetNote('saved');
setTimeout(() => setBudgetNote(''), 1500);
};
+ // Live token-count formatting for the budget input hint (1K / 1M / 1B).
+ const fmtBudgetTokens = (raw: string): string => {
+ const n = Number(raw);
+ if (!raw.trim() || !Number.isFinite(n) || n <= 0) return '';
+ if (n >= 1e9) return `${+(n / 1e9).toFixed(2)}B`;
+ if (n >= 1e6) return `${+(n / 1e6).toFixed(2)}M`;
+ if (n >= 1e3) return `${+(n / 1e3).toFixed(1)}K`;
+ return String(n);
+ };
// ─── Slack integration ─────────────────────────────────────────────────────
const slackCfg = config as SlackConfig;
@@ -110,6 +119,25 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {
const [slackBusy, setSlackBusy] = useState(false);
const [slackNote, setSlackNote] = useState('');
+ // Re-seed every editable field from the on-disk config when the modal opens.
+ // App's `config` prop is loaded once and never refreshed after a save, so
+ // without this the saved budget / velocity / slack values show blank on reopen.
+ useEffect(() => {
+ let alive = true;
+ window.cth.getConfig().then((c) => {
+ if (!alive) return;
+ const cc = c as BreakerCfgView & SlackConfig & { notifications?: boolean };
+ setNotifications(cc.notifications === true);
+ setAgentBudget(cc.costCapTokens != null ? String(cc.costCapTokens) : '');
+ setVelocityCeiling(cc.circuitBreaker?.tokenVelocityPerMin != null ? String(cc.circuitBreaker.tokenVelocityPerMin) : '');
+ setSlackEnabled(cc.slackEnabled ?? false);
+ setSlackSecret(cc.slackSigningSecret ?? '');
+ setSlackChannel(cc.slackChannelId ?? '');
+ setSlackPort(String(cc.slackPort ?? 3847));
+ }).catch(() => { /* keep prop-seeded values */ });
+ return () => { alive = false; };
+ }, []);
+
/** Persist the current Slack inputs. Returns the resolved config patch. */
const slackPatch = (enabled: boolean) => ({
signingSecret: slackSecret,
@@ -325,13 +353,16 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {
</div>
<div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
<label style={{ display: 'flex', flexDirection: 'column', gap: 4, ...slackLabelStyle }}>
- floor cost cap (USD)
+ floor token budget
<input
- type="number" min="0" step="0.5" value={agentBudget}
+ type="number" min="0" step="100000" value={agentBudget}
onChange={(e) => setAgentBudget(e.target.value)}
- placeholder="e.g. 5"
- style={{ ...slackInputStyle, width: 140 }}
+ placeholder="e.g. 1000000"
+ style={{ ...slackInputStyle, width: 160 }}
/>
+ <span style={{ fontSize: 11, color: 'var(--cth-ink-500)' }}>
+ {fmtBudgetTokens(agentBudget) ? `= ${fmtBudgetTokens(agentBudget)} tokens` : 'total tokens across the floor'}
+ </span>
</label>
<label style={{ display: 'flex', flexDirection: 'column', gap: 4, ...slackLabelStyle }}>
token velocity (tok/min)
diff --git a/src/renderer/src/components/terminalPool.ts b/src/renderer/src/components/terminalPool.ts
index 8f9e4602..861478d8 100644
--- a/src/renderer/src/components/terminalPool.ts
+++ b/src/renderer/src/components/terminalPool.ts
@@ -15,6 +15,7 @@
*/
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
+import { WebglAddon } from '@xterm/addon-webgl';
import '@xterm/xterm/css/xterm.css';
export interface TerminalEntry {
@@ -83,6 +84,46 @@ export function acquireTerminal(ptyId: string, theme?: ThemeMap, fontSize = 14):
term.writeln(`\r\n\x1b[2m─ process exited (code ${exitCode}${signal ? `, signal ${signal}` : ''}) ─\x1b[0m`);
}));
+ // ── Copy / paste ──────────────────────────────────────────────────────────
+ // With an accelerated renderer there is no DOM text, so the browser's native
+ // copy can't see the terminal — the selection lives inside xterm. Wire the
+ // usual terminal conventions:
+ // Ctrl/Cmd+C with a selection → copy (without one it stays SIGINT)
+ // Ctrl/Cmd+Shift+C → copy ; Ctrl/Cmd+Shift+V → paste
+ // right-click → copy the selection, else paste (console style)
+ const copySelection = (): boolean => {
+ if (!term.hasSelection()) return false;
+ void window.cth.copyToClipboard(term.getSelection());
+ return true;
+ };
+ const pasteClipboard = (): void => {
+ if (entry.exited) return;
+ void window.cth.readClipboard().then((t) => { if (t) term.paste(t); });
+ };
+ term.attachCustomKeyEventHandler((ev) => {
+ if (ev.type !== 'keydown') return true;
+ if (!(ev.ctrlKey || ev.metaKey)) return true;
+ const key = ev.key.toLowerCase();
+ if (key === 'c' && (ev.shiftKey || term.hasSelection())) {
+ // Copy-on-Ctrl+C only while a selection exists; clear it after, so a
+ // second Ctrl+C still interrupts the agent as usual.
+ if (copySelection() && !ev.shiftKey) term.clearSelection();
+ ev.preventDefault();
+ return false;
+ }
+ if (key === 'v' && ev.shiftKey) {
+ pasteClipboard();
+ ev.preventDefault();
+ return false;
+ }
+ return true;
+ });
+ host.addEventListener('contextmenu', (ev) => {
+ ev.preventDefault();
+ if (copySelection()) { term.clearSelection(); return; }
+ pasteClipboard();
+ });
+
// Keystrokes → pty. A small line buffer surfaces the last submitted prompt.
let lineBuf = '';
term.onData((data) => {
@@ -114,6 +155,25 @@ export function attachTerminal(entry: TerminalEntry, container: HTMLElement): vo
if (!entry.opened) {
entry.term.open(entry.host);
entry.opened = true;
+ // Switch from the DOM renderer to WebGL (must load after open()). The DOM
+ // renderer assumes a perfectly monospace font, but VT323 is missing glyphs
+ // (↔, arrows, some box-drawing) and has no real bold — the browser
+ // substitutes fallback glyphs with different advance widths, so box-drawing
+ // tables shear apart and the cursor drifts. WebGL draws every glyph into its
+ // own fixed cell, keeping the grid aligned. NOT the deprecated canvas addon
+ // (its dirty-region tracking garbles scrollback). Best-effort: on init
+ // failure or GPU context loss, dispose → fall back to the DOM renderer
+ // rather than leave a black terminal.
+ try {
+ const webgl = new WebglAddon();
+ webgl.onContextLoss(() => {
+ console.warn('[terminal] webgl context lost — falling back to DOM renderer');
+ try { webgl.dispose(); } catch { /* noop */ }
+ });
+ entry.term.loadAddon(webgl);
+ } catch (e) {
+ console.warn('[terminal] webgl renderer unavailable, using DOM renderer:', e);
+ }
}
}
diff --git a/src/renderer/src/design/global.css b/src/renderer/src/design/global.css
index a8197b87..df4613f1 100644
--- a/src/renderer/src/design/global.css
+++ b/src/renderer/src/design/global.css
@@ -2,6 +2,11 @@
*, *::before, *::after { box-sizing: border-box; }
+/* The app is a fixed cream/light design. Without declaring it, Chromium on a
+ dark-mode OS styles form controls with the DARK UA scheme — most visibly a
+ white (invisible) text caret on our cream textareas. */
+:root { color-scheme: light; }
+
html, body, #root {
margin: 0;
height: 100%;
@@ -29,6 +34,9 @@ button, input, textarea, select {
color: inherit;
}
+/* Belt + suspenders for the caret: follow the ink, never the UA scheme. */
+input, textarea { caret-color: var(--cth-ink-900); }
+
/* Pixel-snapping for any rasterised content */
canvas, img, svg { image-rendering: pixelated; image-rendering: crisp-edges; }
diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.ts
index 5f667462..333b0b74 100644
--- a/src/renderer/src/hooks/useHive.ts
+++ b/src/renderer/src/hooks/useHive.ts
@@ -24,8 +24,9 @@ const BOOT_GRACE_MS = GOD_BOOT_MS + REMOTE_CONTROL_SETTLE_MS + 2500;
const INITIAL_GOD_PROMPT = [
"You're online as Michael, the orchestrator of the hive. Get oriented, then start running the floor:",
'1. Read your memory.md and drain every message in your inbox.',
- '2. Review board.md and the current roster of agents (active vs archived).',
- '3. Run `mempalace wake-up` for a memory digest if the CLI is available.',
+ '2. Review board.md + tasks.json and the current roster of agents (active vs archived).',
+ '3. Check fleet health: read fleet.json in the hive root for every agent\'s live tokens, cost, status, breaker level, and inbox backlog (`claude agents` will NOT show your hive\'s agents). Flag anyone stalled, over-budget, or breaker-armed.',
+ '4. Skim COMMANDS.md (hive root) for the Claude Code commands you can use — and run `mempalace wake-up` for a memory digest if the CLI is available.',
'Then begin orchestrating: triage requests, delegate work to the team, and keep everyone unblocked. You are fully autonomous — there is no approval queue, so handle tool-permission prompts in this session yourself (the human can approve them remotely from their phone).'
].join('\n');
@@ -46,11 +47,17 @@ const writeChains = new Map<string, Promise<void>>();
* dispatched instruction on their own.
*
* Submissions to the same pty are serialized (and each settles for `settleMs`
- * after Enter) so concurrent callers can't jam their input together. */
+ * after Enter) so concurrent callers can't jam their input together.
+ *
+ * The text is wrapped in bracketed-paste markers (ESC[200~ … ESC[201~) so the
+ * TUI treats it as ONE paste: embedded newlines land as literal newlines in the
+ * input box. Without them, every "\n" in a multi-line message acted as Enter —
+ * the message submitted line-by-line in fragments (the agent saw only the last
+ * chunk). The closing Enter, sent a tick later, submits the whole block. (#24) */
function submitToPty(ptyId: string, text: string, settleMs = 250): Promise<void> {
const prev = writeChains.get(ptyId) ?? Promise.resolve();
const next = prev.catch(() => { /* a failed prior write must not stall the chain */ }).then(async () => {
- await window.cth.writePty(ptyId, text);
+ await window.cth.writePty(ptyId, `\x1b[200~${text}\x1b[201~`);
await new Promise((r) => setTimeout(r, 140));
await window.cth.writePty(ptyId, '\r');
await new Promise((r) => setTimeout(r, settleMs));
diff --git a/src/renderer/src/store/config.ts b/src/renderer/src/store/config.ts
index 6c9b892d..6f77596c 100644
--- a/src/renderer/src/store/config.ts
+++ b/src/renderer/src/store/config.ts
@@ -44,6 +44,11 @@ export interface HarnessConfig {
slackChannelId?: string;
slackPort?: number;
costCapUsd?: number;
+ /** Hard total-token ceiling across active agents (the user-facing budget). */
+ costCapTokens?: number;
+ /** Per-agent total-token ceiling, keyed by agent id. Overrides the floor budget
+ * for that agent's meter and trips the breaker for it alone. */
+ agentTokenCaps?: Record<string, number>;
maxTurns?: number;
circuitBreaker?: CircuitBreakerConfig;
}
diff --git a/src/renderer/src/store/store.ts b/src/renderer/src/store/store.ts
index 126dbc4f..4ff3d51e 100644
--- a/src/renderer/src/store/store.ts
+++ b/src/renderer/src/store/store.ts
@@ -147,6 +147,10 @@ interface State {
removeArchivedAgent: (id: string) => void;
/** Drop one agent from the restorable list (it was respawned or dismissed). */
removeRestorableAgent: (id: string) => void;
+ /** Unsent composer drafts, per agent — so switching agents (which remounts the
+ * composer) doesn't eat what the user was typing. */
+ drafts: Record<string, string>;
+ setDraft: (agentId: string, text: string) => void;
/** Park a message for an agent. Returns nothing; the flush loop delivers it. */
enqueueMessage: (agentId: string, text: string) => void;
/** Drop a single queued message (user removed it, or it was just delivered). */
@@ -427,6 +431,9 @@ export const useStore = create<State>((set) => ({
persistRestorable(restorableAgents);
return { restorableAgents };
}),
+ drafts: {},
+ setDraft: (agentId, text) =>
+ set((s) => ({ drafts: { ...s.drafts, [agentId]: text } })),
enqueueMessage: (agentId, text) =>
set((s) => {
const trimmed = text.trim();
diff --git a/src/shared/claudeCommands.ts b/src/shared/claudeCommands.ts
new file mode 100644
index 00000000..6cff8afa
--- /dev/null
+++ b/src/shared/claudeCommands.ts
@@ -0,0 +1,153 @@
+/**
+ * Single source of truth for the Claude Code command reference.
+ *
+ * Consumed by BOTH the renderer (the Command Center "commands" tab) and the main
+ * process (rendered to `<hive>/COMMANDS.md`, which the orchestrator agent reads),
+ * so the human's cheat-sheet and the agent's reference never drift.
+ *
+ * Web-verified against the Claude Code docs (slash + CLI reference) for v2.1.x.
+ * Curated to the broadly-useful set — aliases and trivia are intentionally omitted.
+ *
+ * `kind` doubles as the scope hint an orchestrator needs:
+ * - `slash` acts ONLY on the session it's typed into (you cannot run it on
+ * another agent's terminal).
+ * - `cli` runs in a shell and can target the fleet / spawn / query.
+ */
+export type CmdKind = 'slash' | 'cli';
+
+export interface Cmd {
+ cmd: string;
+ kind: CmdKind;
+ desc: string;
+ usage?: string;
+}
+
+export interface CmdGroup {
+ title: string;
+ items: Cmd[];
+}
+
+export const COMMAND_GROUPS: CmdGroup[] = [
+ {
+ title: 'SESSION',
+ items: [
+ { cmd: '/clear', kind: 'slash', desc: 'Start a fresh conversation and reclaim the full context window. The old one stays in /resume.' },
+ { cmd: '/resume', kind: 'slash', desc: 'Pick or search a past session to continue.', usage: '/resume auth refactor' },
+ { cmd: '/rewind', kind: 'slash', desc: 'Roll code AND conversation back to an earlier checkpoint.' },
+ { cmd: '/compact', kind: 'slash', desc: 'Summarize the conversation so far to free context without losing the thread.', usage: '/compact keep the auth decisions' },
+ { cmd: 'claude -c', kind: 'cli', desc: 'Continue the most recent session in this directory.' },
+ { cmd: 'claude -r', kind: 'cli', desc: 'Resume — pick or search a past session.', usage: 'claude -r auth' },
+ { cmd: 'claude --fork-session', kind: 'cli', desc: 'When resuming, branch into a new session id instead of reusing the original.' }
+ ]
+ },
+ {
+ title: 'CONTEXT & MEMORY',
+ items: [
+ { cmd: '/context', kind: 'slash', desc: 'Visualize what is filling the context window, with optimization hints.' },
+ { cmd: '/memory', kind: 'slash', desc: 'Open the project & user CLAUDE.md memory files for editing.' },
+ { cmd: '/init', kind: 'slash', desc: 'Scan the repo and generate a CLAUDE.md capturing its conventions.' },
+ { cmd: '# ', kind: 'slash', desc: 'Quick memory: start a line with # to append a durable note to memory.', usage: '# always run prettier before committing' },
+ { cmd: 'claude --add-dir ../other-repo', kind: 'cli', desc: 'Grant the session read/write access to an extra directory.' }
+ ]
+ },
+ {
+ title: 'MODELS & EFFORT',
+ items: [
+ { cmd: '/model', kind: 'slash', desc: 'Switch the model for this session (saved as default); arrows tune effort.', usage: '/model opus' },
+ { cmd: '/effort', kind: 'slash', desc: 'Set reasoning effort: low / medium / high / xhigh / max.', usage: '/effort high' },
+ { cmd: '/fast', kind: 'slash', desc: 'Toggle fast mode — Opus with faster output, no model downgrade.' },
+ { cmd: 'claude --model claude-sonnet-4-6[1m]', kind: 'cli', desc: 'Launch on a specific model. The [1m] suffix selects the 1M-token window (Dwight).' },
+ { cmd: 'claude --fallback-model sonnet', kind: 'cli', desc: 'Auto-fall back to another model when the primary is unavailable.' }
+ ]
+ },
+ {
+ title: 'PLAN & EXECUTE',
+ items: [
+ { cmd: '/plan', kind: 'slash', desc: 'Enter plan mode — design the change before any edits.', usage: '/plan refactor the auth module' },
+ { cmd: '/goal', kind: 'slash', desc: 'Set a goal condition; Claude keeps working across turns until it is met.', usage: '/goal all tests pass' },
+ { cmd: '/batch', kind: 'slash', desc: 'Decompose a large change into parallel units in git worktrees.', usage: '/batch migrate components to v2' },
+ { cmd: '/diff', kind: 'slash', desc: 'Open the interactive diff viewer for the current changes.' },
+ { cmd: '/run', kind: 'slash', desc: 'Launch and drive the project app to see a change actually working.' },
+ { cmd: '/verify', kind: 'slash', desc: 'Build, run, and observe to confirm a change does what it should.' },
+ { cmd: 'claude --worktree feat/x', kind: 'cli', desc: 'Start the session in an isolated git worktree.' }
+ ]
+ },
+ {
+ title: 'REVIEW & GIT',
+ items: [
+ { cmd: '/code-review', kind: 'slash', desc: 'Hunt correctness bugs in the diff. --fix applies them, --comment posts inline; "ultra" runs a cloud deep review.', usage: '/code-review high --fix' },
+ { cmd: '/simplify', kind: 'slash', desc: 'Cleanup-only pass over changed code (reuse/simplify) — no bug hunt.' },
+ { cmd: '/review', kind: 'slash', desc: 'Review a pull request in this session.', usage: '/review 123' },
+ { cmd: '/security-review', kind: 'slash', desc: 'Scan pending changes for security vulnerabilities.' },
+ { cmd: '/ultrareview', kind: 'slash', desc: 'Multi-agent cloud review of the current branch / a PR.' }
+ ]
+ },
+ {
+ title: 'SUBAGENTS & BACKGROUND',
+ items: [
+ { cmd: 'claude agents', kind: 'cli', desc: 'Open the agent view across your live + background Claude sessions.' },
+ { cmd: 'claude agents --json', kind: 'cli', desc: 'Print live sessions as JSON — scriptable fleet status.' },
+ { cmd: '/agents', kind: 'slash', desc: 'Create and manage custom subagents for delegated work.' },
+ { cmd: '/fork', kind: 'slash', desc: 'Spawn a background subagent that inherits the full conversation.', usage: '/fork implement the perf fix' },
+ { cmd: '/background', kind: 'slash', desc: 'Detach the current session so it keeps running in the background.' },
+ { cmd: '/tasks', kind: 'slash', desc: 'View and manage everything running in the background.' },
+ { cmd: '/stop', kind: 'slash', desc: 'Stop the current background session (when attached).' },
+ { cmd: 'claude --agent reviewer', kind: 'cli', desc: 'Start the session using a specific agent configuration.' }
+ ]
+ },
+ {
+ title: 'TOOLS & PERMISSIONS',
+ items: [
+ { cmd: '/permissions', kind: 'slash', desc: 'View and edit which tools are allowed / asked / denied.' },
+ { cmd: '/hooks', kind: 'slash', desc: 'View the configured lifecycle hooks (PreToolUse, Stop, etc.).' },
+ { cmd: 'claude --permission-mode bypassPermissions', kind: 'cli', desc: 'Run without per-tool approval prompts (this is what "auto mode" uses).' },
+ { cmd: 'claude --allowedTools "Bash(git *) Edit Read"', kind: 'cli', desc: 'Pre-allow specific tools so they never prompt.' }
+ ]
+ },
+ {
+ title: 'MCP & PLUGINS',
+ items: [
+ { cmd: '/mcp', kind: 'slash', desc: 'List/manage connected MCP servers and authenticate (OAuth).' },
+ { cmd: '/plugin', kind: 'slash', desc: 'Manage plugins (list, install, enable, disable).' },
+ { cmd: 'claude mcp list', kind: 'cli', desc: 'List configured MCP servers and their health.' },
+ { cmd: 'claude mcp add <name> <command>', kind: 'cli', desc: 'Register a new MCP server (stdio or HTTP).' }
+ ]
+ },
+ {
+ title: 'USAGE & COST',
+ items: [
+ { cmd: '/usage', kind: 'slash', desc: 'Session cost, plan limits, and a breakdown by skill / subagent / MCP.' },
+ { cmd: '/status', kind: 'slash', desc: 'Account, active model, version, and connection status.' },
+ { cmd: 'claude -p "..." --max-budget-usd 5', kind: 'cli', desc: 'Cap the dollar spend for a headless run.' },
+ { cmd: 'claude --max-turns 20', kind: 'cli', desc: 'Limit agentic turns (a coarse runaway guard).' }
+ ]
+ },
+ {
+ title: 'AUTOMATION (HEADLESS)',
+ items: [
+ { cmd: 'claude -p "your prompt"', kind: 'cli', desc: 'Print mode: run one prompt non-interactively and exit.', usage: 'cat log | claude -p "summarize"' },
+ { cmd: 'claude -p "..." --output-format json', kind: 'cli', desc: 'Headless with structured JSON (result, usage, cost) — powers enrichment.' },
+ { cmd: 'claude -p "..." --output-format stream-json', kind: 'cli', desc: 'Streaming JSON events for live consumption.' },
+ { cmd: 'claude -p "..." --json-schema <schema>', kind: 'cli', desc: 'Force the headless result to match a JSON Schema.' },
+ { cmd: 'claude --append-system-prompt "..."', kind: 'cli', desc: 'Append extra instructions to the default system prompt.' }
+ ]
+ },
+ {
+ title: 'CONFIG',
+ items: [
+ { cmd: '/config', kind: 'slash', desc: 'Open Settings: theme, model, output style, preferences.' },
+ { cmd: '/theme', kind: 'slash', desc: 'Change the color theme (auto / light / dark / colorblind / custom).' },
+ { cmd: '/statusline', kind: 'slash', desc: 'Configure the Claude Code status line.' }
+ ]
+ },
+ {
+ title: 'HELP & DIAGNOSTICS',
+ items: [
+ { cmd: '/help', kind: 'slash', desc: 'List every available slash command.' },
+ { cmd: '/doctor', kind: 'slash', desc: 'Diagnose installation / health issues (press f to auto-fix).' },
+ { cmd: '/debug', kind: 'slash', desc: 'Enable debug logging and troubleshoot the current session.' },
+ { cmd: '/release-notes', kind: 'slash', desc: 'Browse the Claude Code changelog by version.' },
+ { cmd: '/remote-control', kind: 'slash', desc: 'Expose this session for control from claude.ai / your phone.' }
+ ]
+ }
+];
diff --git a/tsconfig.node.json b/tsconfig.node.json
index 2d3f0ce6..061e2c21 100644
--- a/tsconfig.node.json
+++ b/tsconfig.node.json
@@ -10,5 +10,5 @@
"isolatedModules": true,
"types": ["node", "electron-vite/node"]
},
- "include": ["src/main/**/*", "src/preload/**/*", "electron.vite.config.ts"]
+ "include": ["src/main/**/*", "src/preload/**/*", "src/shared/**/*", "electron.vite.config.ts"]
}
diff --git a/tsconfig.web.json b/tsconfig.web.json
index 26e908ac..9247f630 100644
--- a/tsconfig.web.json
+++ b/tsconfig.web.json
@@ -17,8 +17,9 @@
"baseUrl": ".",
"paths": {
"@/*": ["src/renderer/src/*"],
- "@brand/*": ["docs/*"]
+ "@brand/*": ["docs/*"],
+ "@shared/*": ["src/shared/*"]
}
},
- "include": ["src/renderer/**/*", "src/preload/index.d.ts"]
+ "include": ["src/renderer/**/*", "src/preload/index.d.ts", "src/shared/**/*"]
}