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
HTML agent-harnessagent-orchestrationagentsai-agentsautonomous-agentsclaude-codecodexcoding-agentsdesktop-appdeveloper-toolselectrongemini-cliharnessharness-engineeringlocal-firstmemorymulti-agentopencodeorchestrationtypescript
fix(cli-agents): auto restart-and-continue after first-time CLI install (ondev-a)
Chaitanya Girice1b6c1e18e2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9d619115..f4ad2623 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -55,6 +55,7 @@ sleep-frozen message router and Codex workers' filesystem permissions.### Fixed- **Codex hive workers get full filesystem + auto-approval from spawn (parity with Claude).** A Codex-engine agent in auto mode launched with `-a never -s workspace-write`, whose sandbox scopes writes to the PTY cwd (the user's project). But a hive worker must also write to its agent folder at `<harnessHome>/hive/agents/<id>/` (move `inbox/` → `.done/`, append `memory.md`, drop outbox JSON, write deliverables) — a **different path tree from cwd**, which `workspace-write` blocked. So a freshly spawned Codex worker couldn't complete HIVE PROTOCOL housekeeping and reported "it does not have permissions … grant write permission to the agent folder." Codex's auto-mode flag is now `--dangerously-bypass-approvals-and-sandbox` — the documented equivalent of Claude's `bypassPermissions` / Antigravity's `--dangerously-skip-permissions` (skip all approval prompts **and** drop the OS sandbox), so a Codex worker has the same filesystem access and auto-approval as a Claude worker from the get-go (`src/shared/agentProvider.ts`; reference/copy updated in `src/shared/codexCommands.ts`, `OnboardingWizard.tsx`, `renderer/store/config.ts`). Claude/agy/antigravity behavior is unchanged.- **Re-arm the hive message router on wake (god→worker delivery survives sleep).** The outbox→inbox router is a `setInterval` (`hive.routeOnce` every ~1.5s) that, like the always-on beats, freezes during true macOS system sleep. `onSystemResume()` already re-armed the mission scheduler, the fleet/breaker beats, and keep-awake on `powerMonitor` `resume`/`unlock-screen` — but it never re-armed the router. So after a long sleep (e.g. laptop closed overnight) the scheduler→god path recovered while **every agent's outbox silently stopped draining**: god→worker, worker↔worker, and broadcast mail piled up undelivered, and no `message` event was logged. The resume handler now re-arms the router (clear-then-set, idempotent) **and** immediately drains the accumulated backlog instead of waiting for the first post-wake tick; the renderer's idle inbox-wake nudge then wakes each parked recipient once its mail lands (`src/main/index.ts`). Verified by `scripts/verify-keepalive-catchup.mjs` (now also reproduces the pre-fix backlog stall and proves the re-arm + flush).+- **Auto restart-and-continue after a first-time engine-CLI install (no dead-end).** When an agent's engine binary (OpenCode/Crush/pi.dev/Codex/…) wasn't installed, the missing-CLI short-circuit ran the provider's installer in the PTY, then printed *"click restart & continue to launch the agent"* — but no such button exists for a not-yet-started agent, so the PTY just sat at `process exited (code 0)` and the agent dead-ended. Now, on a **clean install exit**, the PTY-exit handler auto restart-and-continues: it re-runs the *same* spawn into the *same* pty/window (carrying a `noAutoInstall` flag) so the freshly-installed CLI launches with no user click, and the renderer re-arms that terminal in place (clears the "process exited" line, re-enables input) via a new `pty:relaunch` signal. Provider-agnostic (every engine's installer path) and idempotent by construction — `noAutoInstall` guarantees the installer can never fire twice, and providers with no bundled installer (manual-hint-only) are never armed for relaunch. The install banner copy is now honest ("Installed — launching the agent…") (`src/main/index.ts`, `src/main/pty.ts`, `src/preload/index.ts`, `src/renderer/src/components/terminalPool.ts`).## [0.3.0] — 2026-06-21diff --git a/src/main/index.ts b/src/main/index.tsindex 441b97a1..7d6bfc39 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -64,6 +64,12 @@ const ptyManager = new PtyManager();/** Live PTY id → its hive agent id, recorded at spawn. The pty:kill handler only* gets the PTY id, so this lets a closed tab archive the right registry agent. */const ptyToAgent = new Map<string, string>();+/** PTY id → the spawn it should auto restart-and-continue into once a first-time+ * CLI install finishes. The missing-CLI short-circuit runs the engine's installer+ * in this PTY; when it exits cleanly the exit handler re-runs the SAME spawn (with+ * install disabled) so the freshly-installed CLI launches in the SAME pty/window —+ * no user click. Cleared the moment it's consumed, so it can never loop installs. */+const pendingInstallRelaunch = new Map<string, { opts: AgentSpawnOptions; owner: Electron.WebContents | null; bin: string }>();const hive = new HiveManager(() => readConfig().harnessHome,(channel, payload) => {@@ -352,8 +358,29 @@ function removeWorkerScratch(workerId: string): void {try { rmSync(dir, { recursive: true, force: true }); }catch (e) { console.error('[worker] removeWorkerScratch failed:', e); }}-// A natural PTY exit must run the same teardown as an explicit kill.-ptyManager.setExitHandler(teardownPty);+// A natural PTY exit must run the same teardown as an explicit kill — EXCEPT when+// the PTY was the missing-CLI installer: a clean exit there means the engine CLI was+// just installed, so auto restart-and-continue by re-running the SAME spawn into the+// SAME pty/window (no user click). Provider-agnostic. Idempotent by construction: the+// relaunch carries `noAutoInstall`, so the installer can never fire (let alone loop) a+// second time — a binary that's somehow still missing just spawns and exits normally.+ptyManager.setExitHandler((id, exitCode) => {+ const pending = pendingInstallRelaunch.get(id);+ if (pending) {+ pendingInstallRelaunch.delete(id);+ if (exitCode === 0) {+ // Re-arm the renderer's pooled terminal (clear the "process exited" line ++ // re-enable input) so the freshly-spawned CLI paints onto a clean, typeable+ // grid, then re-run the normal spawn — which now finds the installed binary.+ const wc = (pending.owner && !pending.owner.isDestroyed()) ? pending.owner : liveWebContents();+ try { wc?.send(`pty:relaunch:${id}`); } catch { /* window gone */ }+ void spawnAgentCore({ ...pending.opts, noAutoInstall: true }, pending.owner);+ return; // an install PTY has no agent/worktree to tear down+ }+ // Non-zero exit = install failed; leave its honest manual-fix message on screen.+ }+ teardownPty(id);+});/** Keep the system from suspending the harness while agents are running.* Windows Modern Standby suspends desktop apps (and their child `claude`@@ -1654,13 +1681,13 @@ function buildMissingCliScript(bin: string, provider: AgentProvider): string {'echo.',cmd,'echo.',- 'echo If it succeeded, click restart ^& continue to launch the agent.',- 'echo If it failed, run the command above manually, then restart ^& continue.'+ 'echo [done] If it succeeded, the agent launches automatically.',+ 'echo If it failed, run the command above manually, then restart the agent.');} else {parts.push(`echo No bundled installer for the ${label} provider.`,- 'echo Install it manually, then click restart ^& continue.'+ 'echo Install it manually, then restart the agent to launch it.');if (docs) parts.push(`echo Docs: ${docs}`);parts.push(`echo ${rule}`);@@ -1689,18 +1716,18 @@ function buildMissingCliScript(bin: string, provider: AgentProvider): string {`__clirc=$?`,`echo ''`,`if [ $__clirc -eq 0 ]; then`,- ` echo ' [done] Installed. Click restart & continue to launch the agent.'`,+ ` echo ' [done] Installed — launching the agent…'`,`else`,` echo " [x] Install exited with code $__clirc — finish it manually:"`,` echo ' ${cmd}'`,...(docs ? [` echo ' Docs: ${docs}'`] : []),- ` echo ' Then click restart & continue.'`,+ ` echo ' Then restart the agent to launch it.'`,`fi`);} else {lines.push(`echo ' No bundled installer for the ${label} provider.'`,- `echo ' Install it manually, then click restart & continue.'`,+ `echo ' Install it manually, then restart the agent to launch it.'`,...(docs ? [`echo ' Docs: ${docs}'`] : []),`echo '${rule}'`);@@ -1711,7 +1738,7 @@ function buildMissingCliScript(bin: string, provider: AgentProvider): string {// ─── IPC: pty lifecycle ─────────────────────────────────────────────────────/** Spawn options shared by the `pty:spawn` IPC handler and the god-triggered* ephemeral-worker watcher. */-type AgentSpawnOptions = SpawnOptions & { hive?: AgentMeta; isolate?: boolean; resume?: boolean; resumeSessionId?: string; provider?: AgentProvider };+type AgentSpawnOptions = SpawnOptions & { hive?: AgentMeta; isolate?: boolean; resume?: boolean; resumeSessionId?: string; provider?: AgentProvider; noAutoInstall?: boolean };ipcMain.handle('pty:spawn', async (evt, opts: AgentSpawnOptions) => {if (!opts || typeof opts.id !== 'string' || typeof opts.cwd !== 'string' || typeof opts.command !== 'string') {@@ -1743,16 +1770,19 @@ async function spawnAgentCore(opts: AgentSpawnOptions, owner: Electron.WebConten// just dies with "— process exited (code 1) —" and the user has no idea why.// Detect the absent binary BEFORE spawning and, in this SAME terminal, print a// banner + RUN the provider's install command so the user can watch it (and- // complete any interactive sign-in), then restart the agent. STRICTLY pre-spawn:- // a non-zero exit from a CLI that DID start never reaches here, so there is no- // install loop. Providers with no known installer get a manual hint only —- // nothing arbitrary is ever auto-run. We short-circuit BEFORE worktree/hive/- // Claude-flag setup: ptyToAgent + worktreePaths stay unset for this id, so when- // the install PTY exits teardownPty is a harmless no-op (the agent isn't archived- // and no worktree is torn down) — the user just clicks "restart & continue".+ // complete any interactive sign-in). On a CLEAN install exit the PTY-exit handler+ // auto restart-and-continues — it re-runs THIS spawn (with noAutoInstall) so the+ // freshly-installed CLI launches in the SAME pty/window, no user click. STRICTLY+ // pre-spawn: a non-zero exit from a CLI that DID start never reaches here, so there+ // is no install loop; and the relaunch's noAutoInstall guarantees the installer+ // can't fire twice. Providers with no known installer get a manual hint only (and+ // are NOT armed for relaunch) — nothing arbitrary is ever auto-run. We short-circuit+ // BEFORE worktree/hive/Claude-flag setup: ptyToAgent + worktreePaths stay unset for+ // this id, so when the install PTY exits teardownPty is a harmless no-op (the agent+ // isn't archived and no worktree is torn down) before the relaunch takes over.{const bin = opts.command.trim().split(/\s+/)[0] || opts.command;- if (bin && !ptyManager.isCommandAvailable(bin)) {+ if (bin && !opts.noAutoInstall && !ptyManager.isCommandAvailable(bin)) {const res = ptyManager.spawn({id: opts.id,@@ -1764,6 +1794,14 @@ async function spawnAgentCore(opts: AgentSpawnOptions, owner: Electron.WebConten},owner);+ // Arm auto restart-and-continue: when this installer PTY exits cleanly, the+ // exit handler re-runs the spawn so the just-installed CLI launches in place+ // (no user click). Only when an installer actually RAN (a provider with no+ // bundled installer just prints a manual hint and exits 0 — relaunching there+ // would spawn the still-missing binary and die) and the PTY actually started.+ if (res.ok && installInfoForProvider(provider).command) {+ pendingInstallRelaunch.set(opts.id, { opts, owner, bin });+ }syncKeepAwake();return res;}diff --git a/src/main/pty.ts b/src/main/pty.tsindex 028d3b56..278652d7 100644--- a/src/main/pty.ts+++ b/src/main/pty.ts@@ -78,7 +78,7 @@ export class PtyManager {* externally), so the main process can run the SAME lifecycle teardown* (archive, worktree removal, map cleanup) that the explicit kill() path* runs. Best-effort — set once by the main process. */- private exitHandler: ((id: string) => void) | null = null;+ private exitHandler: ((id: string, exitCode?: number) => void) | null = null;/** The default/fallback output sink — set to the PRIMARY window. Used only for* sessions with no recorded owner; owned sessions route to their owner. */@@ -104,8 +104,10 @@ export class PtyManager {}/** Register the natural-exit teardown callback. Invoked from inside node-pty's- * onExit after the session is cleaned up. */- setExitHandler(handler: (id: string) => void): void {+ * onExit after the session is cleaned up. The exit code is forwarded so the+ * handler can distinguish a clean exit (e.g. a successful first-time CLI+ * install → auto restart-and-continue) from a crash. */+ setExitHandler(handler: (id: string, exitCode?: number) => void): void {this.exitHandler = handler;}@@ -309,7 +311,7 @@ export class PtyManager {this.sessions.delete(opts.id);// Natural exit must run the same lifecycle teardown as an explicit kill.// Guarded so a teardown error can never crash node-pty's exit callback.- try { this.exitHandler?.(opts.id); } catch { /* never throw out of onExit */ }+ try { this.exitHandler?.(opts.id, exitCode); } catch { /* never throw out of onExit */ }});return { ok: true };diff --git a/src/preload/index.ts b/src/preload/index.tsindex 26cfe625..ea3265c6 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -456,6 +456,15 @@ const api = {ipcRenderer.on(channel, listener);return () => ipcRenderer.removeListener(channel, listener);},+ /** Fires when an agent is auto restart-and-continued into this SAME pty after a+ * first-time engine-CLI install. The terminal should re-arm in place (clear the+ * "process exited" line + re-enable input) so the relaunched CLI paints clean. */+ onPtyRelaunch: (id: string, cb: () => void): (() => void) => {+ const channel = `pty:relaunch:${id}`;+ const listener = () => cb();+ ipcRenderer.on(channel, listener);+ return () => ipcRenderer.removeListener(channel, listener);+ },// ─── Dialog ──────────────────────────────────────────────────────────────chooseFolder: (): Promise<{ ok: true; path: string } | { ok: false; error: string }> =>diff --git a/src/renderer/src/components/terminalPool.ts b/src/renderer/src/components/terminalPool.tsindex e9b35b56..8bf86f52 100644--- a/src/renderer/src/components/terminalPool.ts+++ b/src/renderer/src/components/terminalPool.ts@@ -90,6 +90,15 @@ export function acquireTerminal(ptyId: string, theme?: ThemeMap, fontSize = 14):entry.exited = true;term.writeln(`\r\n\x1b[2m─ process exited (code ${exitCode}${signal ? `, signal ${signal}` : ''}) ─\x1b[0m`);}));+ // A first-time engine-CLI install just finished and the agent is auto+ // restart-and-continuing into THIS same pty (main re-ran the spawn). Re-arm the+ // terminal in place — clear the latched exit (so keystrokes flow again) and wipe+ // the install banner + "process exited" line — so the relaunched CLI's TUI paints+ // onto a clean, typeable grid. Mirrors resetTerminal but works on this closure.+ entry.unsub.push(window.cth.onPtyRelaunch(ptyId, () => {+ entry.exited = false;+ try { term.reset(); } catch { /* not yet open */ }+ }));// ── Copy / paste ──────────────────────────────────────────────────────────// With an accelerated renderer there is no DOM text, so the browser's native