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(workers): reliable spawn, teardown and floor cards for god-hired workers

Gastón Péchieudabb009cbe00
diff --git a/src/main/index.ts b/src/main/index.ts
index cb30da18..487857f2 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -382,11 +382,21 @@ const preservedWorktrees = new Map<string, PreservedWorktree>();
* per dead PTY.
*
* Idempotent: guarded on map presence and the already-idempotent
- * `hive.setArchived`, so the second call (kill() also makes node-pty fire
- * onExit) is a harmless no-op. Best-effort — every step is wrapped so a teardown
- * error can never crash the caller (an IPC handler or node-pty's onExit).
+ * `hive.setArchived`, so a double call is a harmless no-op. NOTE: an explicit
+ * `ptyManager.kill()` does NOT reach here via onExit — kill() deletes the
+ * session synchronously, so node-pty's later async exit callback fails the
+ * session-identity guard and is swallowed. Every kill site must therefore call
+ * teardownPty itself right after the kill (all of them do). Best-effort — every
+ * step is wrapped so a teardown error can never crash the caller (an IPC
+ * handler or node-pty's onExit).
*/
function teardownPty(id: string): void {
+ // Ephemeral-worker flag, read BEFORE the cleanup below deletes the entry. All
+ // worker deaths (done-release, idle/token reap, crash) funnel through here,
+ // so this is the one place their floor card gets archived (workers now card
+ // via the hive:agentSpawned broadcast in processSpawnRequest). pty id ==
+ // worker id == agent id for workers.
+ const wasWorker = liveWorkers.has(id);
// 0) Revoke this id's broker capability (if any). Idempotent + harmless for a
// non-worker PTY; ensures a dead worker's token can never reach an integration.
try { integrationBroker.revoke(id); } catch { /* best-effort */ }
@@ -426,6 +436,12 @@ function teardownPty(id: string): void {
// A worker whose isolation failed (non-repo cwd) has no worktree to gate above —
// still clear its tracking entry so the controller stops watching a dead PTY.
if (liveWorkers.has(id)) liveWorkers.delete(id);
+ // Archive the dead worker's floor card (mirrors killAgent's voice-kill path;
+ // the renderer's archiveAgent is a no-op if the card is already gone). NOT
+ // done for regular agents: their kill flows already manage their own card.
+ if (wasWorker) {
+ try { liveWebContents()?.send('hive:agentArchived', { id }); } catch { /* window torn down */ }
+ }
syncKeepAwake();
}
@@ -4099,8 +4115,29 @@ async function processSpawnRequest(filePath: string): Promise<void> {
const cwd = typeof raw.cwd === 'string' && raw.cwd.trim() ? expandTilde(raw.cwd) : '';
if (!cwd || !existsSync(cwd)) { fail(`"cwd" missing or not found (${cwd || 'unset'})`); return; }
- const command = typeof raw.command === 'string' && raw.command.trim() ? raw.command.trim() : (readConfig().defaultCommand ?? 'claude');
- const bin = command.split(/\s+/)[0] || command;
+ const cfgSpawn = readConfig();
+ let command = typeof raw.command === 'string' && raw.command.trim() ? raw.command.trim() : (cfgSpawn.defaultCommand ?? 'claude');
+ // Inherit the app's auto (skip-permissions) mode when the request takes no
+ // stance of its own: a headless worker has no human to click through tool
+ // prompts, so without the flag it stalls at the first ask until the idle
+ // reaper kills it. An explicit --permission-mode in the request always wins,
+ // and non-claude commands are left untouched.
+ if (cfgSpawn.autoMode && inferAgentProvider(command, raw.provider) === 'claude' && !command.includes('--permission-mode')) {
+ command += ' --permission-mode bypassPermissions';
+ }
+ // god authors `command` as a full command LINE ("claude --model … --permission-mode …"),
+ // but the PTY layer takes ONE executable name (resolveCommand) plus argv — the
+ // unsplit line made node-pty exec a binary literally named like the whole
+ // string → ENOENT → the worker died within ~1s of spawning while its request
+ // archived as .done (this killed both flag-carrying Ryan spawns on 2026-08-16;
+ // only the bare-`claude` one lived). Split it here — same quoting rules as the
+ // renderer's tokenizeCommand — and hand the flags over as argv.
+ const tokens: string[] = [];
+ const tokenRe = /"([^"]*)"|'([^']*)'|(\S+)/g;
+ let tok: RegExpExecArray | null;
+ while ((tok = tokenRe.exec(command)) !== null) tokens.push(tok[1] ?? tok[2] ?? tok[3]);
+ const bin = tokens[0] || command;
+ const cmdFlags = tokens.slice(1);
// Missing-CLI → FAIL FAST. A headless worker has no human to watch an installer,
// so we never run the cc49e1e install banner here — we reject and tell god.
if (!ptyManager.isCommandAvailable(bin)) { fail(`engine CLI "${bin}" is not installed`); return; }
@@ -4129,21 +4166,39 @@ async function processSpawnRequest(filePath: string): Promise<void> {
brokerEnv.MD_BROKER_TOKEN = token;
}
const spawnOpts: AgentSpawnOptions = {
- id: workerId, cwd, command, cols: 120, rows: 32,
- args: raw.model ? ['--model', raw.model] : [],
+ id: workerId, cwd, command: bin, cols: 120, rows: 32,
+ // A separate `model` field only applies when the command line didn't pick a
+ // model itself (spawnAgentCore likewise skips its default-model injection
+ // when argv already carries --model).
+ args: [...cmdFlags, ...(raw.model && !cmdFlags.includes('--model') ? ['--model', raw.model] : [])],
hive: meta, isolate, provider: raw.provider, env: brokerEnv
};
- let res: { ok: boolean; error?: string };
+ let res: { ok: boolean; error?: string; worktreePath?: string };
try {
- // Output routes to the primary window (no renderer evt here). Workers are
- // headless-by-design — they reply to Slack + report to god, not a watching human.
res = await spawnAgentCore(spawnOpts, liveWebContents());
} catch (e) {
res = { ok: false, error: String(e) };
}
if (!res.ok) { integrationBroker.revoke(workerId); fail(`spawn failed — ${res.error ?? 'unknown error'}`); return; }
+ // A god-hired worker is a MAIN-initiated spawn, so the renderer would never
+ // card it on its own (same reason as the voice-spawn broadcast): without this
+ // the worker is invisible on the floor, never enters the roster, and after a
+ // restart nothing offers to restore it. The card rides the normal agent
+ // lifecycle from here — teardownPty broadcasts the matching archive.
+ try {
+ liveWebContents()?.send('hive:agentSpawned', {
+ id: workerId,
+ name: meta.name,
+ provider: raw.provider ?? 'claude',
+ cwd: res.worktreePath ?? cwd,
+ command,
+ role: meta.role,
+ worktreePath: res.worktreePath
+ });
+ } catch { /* window torn down */ }
+
// Register for done-scan / idle-reap / token-cap / safe teardown (pty id == workerId).
// tokenCap is optional plumbing (default unlimited) — only a positive finite cap is kept.
const tokenCap = typeof raw.tokenCap === 'number' && Number.isFinite(raw.tokenCap) && raw.tokenCap > 0
@@ -4239,8 +4294,14 @@ async function ephemeralWorkerTick(): Promise<void> {
const defaultTokenCap = typeof cfg.defaultWorkerTokenCap === 'number' && cfg.defaultWorkerTokenCap > 0
? cfg.defaultWorkerTokenCap : 0;
- // (1) Finish or reap. ptyManager.kill → teardownPty → gated worktree + archive
- // + liveWorkers.delete. `releasing` guards the gap before onExit fires.
+ // (1) Finish or reap. Each release calls teardownPty EXPLICITLY after the
+ // kill, like every other kill site: ptyManager.kill() deletes the session
+ // synchronously, so when node-pty's async onExit later fires it fails the
+ // session-identity guard and the global exit handler (→ teardownPty)
+ // never runs. Relying on onExit here left released workers un-torn-down:
+ // no hive archive, no hive:agentArchived, frozen floor cards, and god
+ // kept mailing dead agents (seen live 2026-08-16 with worker-business/
+ // worker-qa/worker-bizreview). A double teardown is a harmless no-op.
for (const [workerId, rec] of [...liveWorkers]) {
if (rec.releasing) continue;
if (workerSignaledDone(workerId, rec.spawnedAt)) {
@@ -4248,6 +4309,7 @@ async function ephemeralWorkerTick(): Promise<void> {
rec.releasing = true;
console.log(`[worker] ${workerId} signaled done — releasing`);
ptyManager.kill(workerId);
+ teardownPty(workerId);
continue;
}
// Token-cap reap (default-off plumbing). An effective cap > 0 → reap when the
@@ -4264,6 +4326,7 @@ async function ephemeralWorkerTick(): Promise<void> {
rec.slack
);
ptyManager.kill(workerId);
+ teardownPty(workerId);
continue;
}
}
@@ -4278,6 +4341,7 @@ async function ephemeralWorkerTick(): Promise<void> {
rec.slack
);
ptyManager.kill(workerId);
+ teardownPty(workerId);
}
}