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

chore: checkpoint existing workspace changes

Vyapak Goyal33317a2cc15f
diff --git a/README.md b/README.md
index 48038360..a4c12f52 100644
--- a/README.md
+++ b/README.md
@@ -94,7 +94,7 @@ terminal/event plane, and [`DESIGN.md`](./DESIGN.md) for the visual system.
| Area | What works today |
|---|---|
-| **Real terminals** | Spawn Claude Code, Antigravity (`agy` / Gemini), OpenAI Codex, or a custom command in a `node-pty` PTY. Full read/write/resize/kill, live streaming over IPC, multi-agent. |
+| **Real terminals** | Spawn Claude Code, Antigravity (`agy` / Gemini), OpenAI Codex (GPT), Kimi Code, or a custom command in a `node-pty` PTY. Full read/write/resize/kill, live streaming over IPC, multi-agent. |
| **Multi-provider hive** | Claude Code, Antigravity, and Codex workers can all participate in the same hive. Claude uses native hooks; Antigravity gets a native `agy-hook` bridge; Codex receives the protocol as its initial prompt and participates through inbox/outbox routing. |
| **The hive** | On-disk multi-agent layer: per-agent identity + long-term memory, atomic-file mailboxes, a shared blackboard, append-only event log, single-committer git. |
| **GOD orchestrator** | An always-on supervisor agent that adjudicates traffic, routes tasks, scribes the blackboard, and escalates only critical items to you. |
@@ -142,7 +142,8 @@ terminal/event plane, and [`DESIGN.md`](./DESIGN.md) for the visual system.
xcode-select --install
```
- At least one supported terminal-agent CLI on your `PATH`: **[Claude Code](https://claude.com/claude-code)**
- (`claude`, the default command), **Antigravity** (`agy`, Gemini), or **OpenAI Codex** (`codex`).
+ (`claude`, the default command), **Antigravity** (`agy`, Gemini), **OpenAI Codex** (`codex`),
+ or **Kimi Code** (`kimi`).
Claude uses native hooks, Antigravity uses the `agy-hook` bridge, and Codex participates through
initial-prompt protocol injection plus inbox/outbox routing.
- *Optional:* the semantic memory index for instant cross-session recall (the app works without it —
diff --git a/package.json b/package.json
index 92e8b2f9..611059cb 100644
--- a/package.json
+++ b/package.json
@@ -19,6 +19,7 @@
"typecheck:node": "tsc --noEmit -p tsconfig.node.json",
"typecheck:web": "tsc --noEmit -p tsconfig.web.json",
"typecheck": "npm run typecheck:node && npm run typecheck:web",
+ "test:focused": "node --test test/auto-compact.test.cjs test/codex-remote.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs",
"dist": "npm run build && electron-builder",
"dist:mac": "npm run build && electron-builder --mac",
"dist:win": "npm run build && electron-builder --win",
diff --git a/src/main/config.ts b/src/main/config.ts
index a0b4c5d4..66eb4f14 100644
--- a/src/main/config.ts
+++ b/src/main/config.ts
@@ -2,7 +2,12 @@ import { app } from 'electron';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { homedir } from 'node:os';
-import { autoModeFlagForProvider, inferAgentProvider, type AgentProvider } from '../shared/agentProvider';
+import {
+ autoModeFlagForProvider,
+ defaultCommandForProvider,
+ inferAgentProvider,
+ type AgentProvider
+} from '../shared/agentProvider';
/** A recurring auto-dispatched mission fired on an interval by the scheduler. */
export interface ScheduledMission {
@@ -14,8 +19,8 @@ export interface ScheduledMission {
enabled: boolean;
/** When true, the scheduler asks the renderer to `/compact` live terminals when
* this mission fires — but only agents whose context has filled past a
- * threshold (~30% of their model's window) are compacted, so small/idle
- * sessions are left alone instead of compacting on every tick. */
+ * threshold (30% for ~250k windows, 20% for ~1M windows) are compacted, so
+ * small/idle sessions are left alone instead of compacting on every tick. */
autoCompact?: boolean;
lastFiredAt?: number;
/** Mission flavor. Absent ⇒ 'dispatch' (the classic interval-dispatch mission,
@@ -47,12 +52,7 @@ export const OPS_STANDUP_MISSION: ScheduledMission = {
'contexts stay bounded without losing work. The compaction is queued and ' +
'runs when an agent is idle, so it never interrupts work mid-step.)',
enabled: true,
- // Auto-compact injection ships OFF: the founder does not want a scheduled
- // `/compact …` typed into agent terminals (it reads as if they typed it).
- // Re-enableable per-mission; the one-time autoCompactDisabledMigrated step
- // also flips this false on existing installs. Claude Code's own near-limit
- // auto-compaction still protects long sessions independently of this.
- autoCompact: false
+ autoCompact: true
};
/** The built-in heartbeat (Lane A #1). A context-aware beat that, each tick,
@@ -136,7 +136,10 @@ export interface HarnessConfig {
/** One-time guard for the built-in heartbeat mission (mirrors opsStandupSeeded
* so a user who deletes the heartbeat doesn't get it re-added every boot). */
heartbeatSeeded?: boolean;
- autoCompactDisabledMigrated?: boolean; // one-time: flipped every mission's autoCompact off on existing installs (founder opt-out); guards against re-forcing if re-enabled later
+ /** Legacy migration marker from the release that disabled scheduled compaction. */
+ autoCompactDisabledMigrated?: boolean;
+ /** One-time migration marker for upgrading persisted ops standups. */
+ autoCompactEnabledMigrated?: 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. Legacy — the UI now sets a
@@ -330,17 +333,18 @@ export function modelForRole(meta: RoleHint): string | undefined {
return MODEL_WORKER;
}
-/** Auto-suggested command string given current autoMode preference.
- * Provider-aware: Claude gets --permission-mode bypassPermissions; Codex gets
- * --full-auto; custom providers receive no extra flags. */
+/** Auto-suggested command string given current autoMode preference. */
export function commandForAutoMode(
config: HarnessConfig,
provider?: AgentProvider
): string {
- if (!config.autoMode) return config.defaultCommand;
const p = provider ?? inferAgentProvider(config.defaultCommand);
+ const base = p === 'claude' || p === 'custom'
+ ? config.defaultCommand
+ : defaultCommandForProvider(p, config.defaultCommand);
+ if (!config.autoMode) return base;
const flag = autoModeFlagForProvider(p);
- return flag ? `${config.defaultCommand} ${flag}` : config.defaultCommand;
+ return flag ? `${base} ${flag}` : base;
}
/** Ensure harnessHome exists on disk. */
diff --git a/src/main/hive.ts b/src/main/hive.ts
index 50208512..8391bc51 100644
--- a/src/main/hive.ts
+++ b/src/main/hive.ts
@@ -373,11 +373,12 @@ export class HiveManager {
} catch (e) { console.error(`[hive] install ${bridge} hooks failed:`, e); }
}
}
- // Inject the protocol text whichever way the CLI accepts it. If a provider
- // somehow exposes neither a flag nor a positional prompt, spawn bare.
+ // Inject protocol text only through a form the CLI explicitly supports.
+ // Kimi/custom have neither an interactive prompt flag nor positional prompt
+ // support, so they spawn bare instead of receiving an invalid argument.
if (flag) return { args: [...preArgs, flag, prompt], env };
- // Positional initial prompt (codex). Append as a trailing argv element.
- return { args: [...preArgs, prompt], env };
+ if (preset.positionalInitialPrompt) return { args: [...preArgs, prompt], env };
+ return { args: preArgs, env };
}
// Stage 7A — first-party Claude Code telemetry → the embedded loopback OTLP
@@ -898,6 +899,16 @@ export class HiveManager {
try { symlinkSync(authSrc, authDest); }
catch { try { copyFileSync(authSrc, authDest); } catch { /* best-effort */ } }
}
+ // The managed app-server daemon used by Codex Remote Control is launched
+ // from the standalone install rooted at $CODEX_HOME/packages. Share the
+ // user's installed binaries without duplicating them into every agent.
+ const packagesSrc = join(userHome, 'packages');
+ const packagesDest = join(home, 'packages');
+ if (existsSync(packagesSrc) && !existsSync(packagesDest)) {
+ try {
+ symlinkSync(packagesSrc, packagesDest, process.platform === 'win32' ? 'junction' : 'dir');
+ } catch { /* remote integration falls back to a local TUI if unavailable */ }
+ }
// Wire lifecycle hooks via config.toml `[hooks]` tables — the user-layer
// discovery surface Codex actually scans. (A bare $CODEX_HOME/hooks.json is
// plugin-scoped — referenced FROM a plugin manifest — and is NOT discovered
diff --git a/src/main/index.ts b/src/main/index.ts
index 94381dff..3c22d9b3 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1,10 +1,16 @@
import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, powerSaveBlocker, screen, shell, Notification } from 'electron';
import { spawn } from 'node:child_process';
-import { rmSync, existsSync, readFileSync, readdirSync, statSync, cpSync, writeFileSync, unlinkSync, mkdirSync, createWriteStream, copyFileSync } from 'node:fs';
+import {
+ rmSync, existsSync, readFileSync, readdirSync, statSync, cpSync, writeFileSync,
+ unlinkSync, mkdirSync, createWriteStream, copyFileSync, lstatSync, readlinkSync,
+ symlinkSync
+} from 'node:fs';
import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
import { join, resolve, sep, basename, dirname } from 'node:path';
+import { tmpdir } from 'node:os';
import { request as httpsRequest } from 'node:https';
import { PtyManager, type SpawnOptions } from './pty';
+import { enableOpsStandupAutoCompact } from '../shared/autoCompact';
import {
readConfig, writeConfig, resetConfig, ensureHarnessHome, ensureClaudePermissionsAccepted,
modelForRole, OPS_STANDUP_MISSION, HEARTBEAT_MISSION, type HarnessConfig, type ScheduledMission
@@ -37,6 +43,12 @@ import {
providerPreset,
type AgentProvider
} from '../shared/agentProvider';
+import {
+ CODEX_REMOTE_SOCKET_RELATIVE,
+ codexRemoteAliasPath,
+ codexRemoteEndpoint,
+ withCodexRemoteArgs
+} from '../shared/codexRemote';
const isDev = !!process.env.ELECTRON_RENDERER_URL;
@@ -53,6 +65,112 @@ process.on('unhandledRejection', (reason) => {
});
const ptyManager = new PtyManager();
+
+function runCodexDaemonCommand(
+ executable: string,
+ args: string[],
+ env: NodeJS.ProcessEnv,
+ timeoutMs = 20_000
+): Promise<{ ok: boolean; error?: string }> {
+ return new Promise((resolveResult) => {
+ let settled = false;
+ let stderr = '';
+ let child: ReturnType<typeof spawn>;
+ try {
+ child = spawn(executable, args, {
+ env,
+ stdio: ['ignore', 'ignore', 'pipe'],
+ windowsHide: true
+ });
+ } catch (e) {
+ resolveResult({ ok: false, error: e instanceof Error ? e.message : String(e) });
+ return;
+ }
+ let timer: NodeJS.Timeout;
+ const finish = (result: { ok: boolean; error?: string }): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolveResult(result);
+ };
+ child.stderr?.on('data', (chunk) => {
+ if (stderr.length < 8_000) stderr += String(chunk);
+ });
+ child.once('error', (e) => finish({ ok: false, error: e.message }));
+ child.once('exit', (code) => {
+ finish(code === 0
+ ? { ok: true }
+ : { ok: false, error: stderr.trim() || `Codex exited with code ${code ?? 'unknown'}` });
+ });
+ timer = setTimeout(() => {
+ try { child.kill(); } catch { /* already exited */ }
+ finish({ ok: false, error: `Codex daemon command timed out after ${timeoutMs}ms` });
+ }, timeoutMs);
+ });
+}
+
+/** Start/enable one managed remote-control daemon for this isolated Codex home,
+ * then point the TUI at its app-server socket. Failure is non-fatal: the worker
+ * still starts as a normal local Codex session. */
+async function enableCodexRemoteForSpawn(
+ opts: SpawnOptions & { hive?: AgentMeta },
+ agentId: string
+): Promise<boolean> {
+ if (process.platform === 'win32') return false;
+ const realHome = opts.env?.CODEX_HOME;
+ if (!realHome) return false;
+ try {
+ const alias = codexRemoteAliasPath(realHome, agentId, tmpdir());
+ const aliasRoot = dirname(alias);
+ mkdirSync(aliasRoot, { recursive: true });
+ if (existsSync(alias)) {
+ const st = lstatSync(alias);
+ if (!st.isSymbolicLink() || resolve(dirname(alias), readlinkSync(alias)) !== resolve(realHome)) {
+ console.warn('[codex-remote] short home alias is occupied; starting local TUI:', alias);
+ return false;
+ }
+ } else {
+ symlinkSync(realHome, alias, 'dir');
+ }
+
+ const socket = join(alias, CODEX_REMOTE_SOCKET_RELATIVE);
+ const env: NodeJS.ProcessEnv = {
+ ...process.env,
+ ...(opts.env ?? {}),
+ CODEX_HOME: alias
+ };
+ const executable = ptyManager.resolveCommand(opts.command);
+ const started = await runCodexDaemonCommand(
+ executable,
+ ['app-server', 'daemon', 'start'],
+ env
+ );
+ if (!started.ok) {
+ console.warn('[codex-remote] daemon start failed; starting local TUI:', started.error);
+ return false;
+ }
+ const enabled = await runCodexDaemonCommand(
+ executable,
+ ['app-server', 'daemon', 'enable-remote-control'],
+ env
+ );
+ if (!enabled.ok) {
+ console.warn('[codex-remote] enable failed; starting local TUI:', enabled.error);
+ return false;
+ }
+ if (!existsSync(socket)) {
+ console.warn('[codex-remote] daemon returned without a control socket; starting local TUI');
+ return false;
+ }
+ opts.env = { ...(opts.env ?? {}), CODEX_HOME: alias };
+ opts.args = withCodexRemoteArgs(opts.args ?? [], codexRemoteEndpoint(alias));
+ return true;
+ } catch (e) {
+ console.warn('[codex-remote] setup failed; starting local TUI:',
+ e instanceof Error ? e.message : e);
+ return false;
+ }
+}
/** 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>();
@@ -340,18 +458,16 @@ function ensureDefaultMissions(): void {
heartbeatSeeded: true
});
}
- // One-time opt-out: the founder doesn't want the scheduled /compact injected
- // into agent terminals. An existing install already persisted the ops standup
- // with autoCompact:true (which { ...DEFAULTS, ...parsed } keeps), so flipping
- // the built-in default alone wouldn't reach it — clear the flag on every
- // persisted mission once. Guarded so a user who deliberately re-enables it
- // later isn't force-disabled on every boot.
+ // One-time upgrade: the prior release persisted autoCompact:false on existing
+ // ops standups. Updating the built-in default only affects fresh installs, so
+ // explicitly enable the persisted built-in mission too. Other missions and
+ // the standup's own enabled/deleted state remain user-controlled.
const cfg3 = readConfig();
- if (!cfg3.autoCompactDisabledMigrated) {
+ if (!cfg3.autoCompactEnabledMigrated) {
const missions = cfg3.missions ?? [];
writeConfig({
- missions: missions.map((m) => (m.autoCompact ? { ...m, autoCompact: false } : m)),
- autoCompactDisabledMigrated: true
+ missions: enableOpsStandupAutoCompact(missions),
+ autoCompactEnabledMigrated: true
});
}
}
@@ -1607,6 +1723,13 @@ ipcMain.handle('pty:spawn', async (evt, opts: SpawnOptions & { hive?: AgentMeta;
if (Object.keys(nonInteractiveEnv).length > 0) {
opts.env = { ...(opts.env ?? {}), ...nonInteractiveEnv };
}
+ // Codex Remote is daemon-based (there is no `/remote-control` slash command).
+ // Start/enable the daemon under this agent's isolated CODEX_HOME and connect
+ // the TUI to it so the thread is visible in ChatGPT mobile. Best-effort: an
+ // unavailable/older Codex install still gets a normal local terminal.
+ if (provider === 'codex' && opts.hive?.id) {
+ await enableCodexRemoteForSpawn(opts, opts.hive.id);
+ }
// Record the spawning window as the PTY's owner so its output (pty:data/exit)
// routes ONLY back to that floor — never leaking into another window's stream.
const owner = BrowserWindow.fromWebContents(evt.sender)?.webContents ?? null;
@@ -1627,6 +1750,10 @@ ipcMain.handle('pty:resize', (_evt, id: string, cols: number, rows: number) => {
if (typeof id !== 'string' || typeof cols !== 'number' || typeof rows !== 'number') return { ok: false, error: 'invalid args' };
return ptyManager.resize(id, cols, rows);
});
+ipcMain.handle('pty:redraw', (_evt, id: string) => {
+ if (typeof id !== 'string') return { ok: false, error: 'invalid id' };
+ return ptyManager.redraw(id);
+});
ipcMain.handle('pty:kill', (_evt, id: string) => {
if (typeof id !== 'string') return { ok: false, error: 'invalid id' };
// Kill the process, then run the shared lifecycle teardown (archive the agent,
diff --git a/src/main/pty.ts b/src/main/pty.ts
index 7bd38f7f..eb8d4491 100644
--- a/src/main/pty.ts
+++ b/src/main/pty.ts
@@ -20,6 +20,9 @@ interface PtySession {
* file) and the idle handshake that gates god's PTY nudge (never type into a
* PTY that produced output in the last few seconds = mid-stream). */
lastOutputAt: number;
+ /** True after the child has emitted at least one frame. Automation waits for
+ * this before typing, so startup prompts cannot outrun the TUI subscription. */
+ hasOutput: boolean;
}
export interface SpawnOptions {
@@ -113,7 +116,7 @@ export class PtyManager {
/** Resolve a bare command (e.g. 'claude') against the user's PATH +
* common install locations. Needed because Electron's spawn env on
* macOS launches without the user's interactive shell PATH. */
- private resolveCommand(command: string): string {
+ resolveCommand(command: string): string {
// Already an absolute/relative path (Unix `/` or Windows `\`) — pass through.
if (command.includes('/') || command.includes('\\')) return command;
if (process.platform === 'win32') {
@@ -244,13 +247,22 @@ export class PtyManager {
// final bytes into the new agent's fresh TUI frame — scattered/overlapping
// text — and (b) on exit delete the replacement session and emit a false
// `pty:exit`, killing input to the agent that just started.
- const session: PtySession = { id: opts.id, proc, cwd: opts.cwd, command: resolved, lastOutputAt: Date.now(), owner };
+ const session: PtySession = {
+ id: opts.id,
+ proc,
+ cwd: opts.cwd,
+ command: resolved,
+ lastOutputAt: Date.now(),
+ hasOutput: false,
+ owner
+ };
this.sessions.set(opts.id, session);
proc.onData((data) => {
// Drop trailing output from a process whose id was already reclaimed by
// a respawn (or killed) — it would corrupt the new session's screen.
if (this.sessions.get(opts.id) !== session) return;
+ session.hasOutput = true;
session.lastOutputAt = Date.now();
// Route to the session's owner window (multi-window owner routing).
this.safeSend(`pty:data:${opts.id}`, data, session.owner);
@@ -294,6 +306,20 @@ export class PtyManager {
}
}
+ /** Ask the foreground TUI for a fresh frame without changing its geometry.
+ * Startup output may predate the renderer subscription, and a same-sized
+ * first fit otherwise emits no resize. */
+ redraw(id: string): { ok: boolean; error?: string } {
+ const s = this.sessions.get(id);
+ if (!s) return { ok: false, error: `no pty: ${id}` };
+ try {
+ s.proc.resize(s.proc.cols, s.proc.rows);
+ return { ok: true };
+ } catch (e) {
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
+ }
+ }
+
kill(id: string): { ok: boolean; error?: string } {
const s = this.sessions.get(id);
if (!s) return { ok: false, error: `no pty: ${id}` };
@@ -306,13 +332,14 @@ export class PtyManager {
}
}
- list(): Array<{ id: string; cwd: string; command: string; pid: number; lastOutputAt: number }> {
+ list(): Array<{ id: string; cwd: string; command: string; pid: number; lastOutputAt: number; hasOutput: boolean }> {
return Array.from(this.sessions.values()).map(s => ({
id: s.id,
cwd: s.cwd,
command: s.command,
pid: s.proc.pid,
- lastOutputAt: s.lastOutputAt
+ lastOutputAt: s.lastOutputAt,
+ hasOutput: s.hasOutput
}));
}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index a91dcef6..d66d9305 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -372,9 +372,18 @@ const api = {
ipcRenderer.invoke('pty:write', id, data),
resizePty: (id: string, cols: number, rows: number): Promise<{ ok: boolean; error?: string }> =>
ipcRenderer.invoke('pty:resize', id, cols, rows),
+ redrawPty: (id: string): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('pty:redraw', id),
killPty: (id: string): Promise<{ ok: boolean; error?: string }> =>
ipcRenderer.invoke('pty:kill', id),
- listPtys: (): Promise<Array<{ id: string; cwd: string; command: string; pid: number }>> =>
+ listPtys: (): Promise<Array<{
+ id: string;
+ cwd: string;
+ command: string;
+ pid: number;
+ lastOutputAt: number;
+ hasOutput: boolean;
+ }>> =>
ipcRenderer.invoke('pty:list'),
/** Resolve a Claude session id to the cwd it originally ran in (Add Agent
* resume auto-fill), or null if the id is invalid/unknown. */
diff --git a/src/renderer/src/components/AddAgentModal.tsx b/src/renderer/src/components/AddAgentModal.tsx
index 401f650c..b2022747 100644
--- a/src/renderer/src/components/AddAgentModal.tsx
+++ b/src/renderer/src/components/AddAgentModal.tsx
@@ -64,6 +64,11 @@ export function AddAgentModal({ onClose, config }: AddAgentModalProps) {
setProvider(id);
const nextModel = isClaudeProvider(id) ? config.defaultModel : undefined;
setModel(nextModel);
+ const nextPreset = providerPreset(id);
+ if (!isClaudeProvider(id) && !nextPreset.resumeFlag && !nextPreset.resumeSubcommand) {
+ setResumeSessionId('');
+ setFolderNote(undefined);
+ }
if (id === 'custom') {
setCommand(command.trim() || config.defaultCommand || '');
return;
@@ -255,7 +260,9 @@ export function AddAgentModal({ onClose, config }: AddAgentModalProps) {
p.id === 'antigravity'
? 'Spawn the Antigravity CLI (agy) with a Gemini model'
: p.id === 'codex'
- ? 'Spawn the Codex CLI (codex) without Claude-only flags'
+ ? 'Spawn Codex with GPT models and provider-native auto permissions'
+ : p.id === 'kimi'
+ ? 'Spawn Kimi Code with K3/K2.7 and provider-native auto permissions'
: p.id === 'custom'
? 'Run any command — no Claude-only flags'
: p.label
@@ -312,6 +319,8 @@ export function AddAgentModal({ onClose, config }: AddAgentModalProps) {
? 'agy'
: provider === 'codex'
? 'codex'
+ : provider === 'kimi'
+ ? 'kimi'
: provider === 'custom'
? 'your-agent-cli'
: 'claude'
@@ -339,7 +348,7 @@ export function AddAgentModal({ onClose, config }: AddAgentModalProps) {
/>
</Row>
- <Row label="Resume session ID (optional)">
+ {(isClaudeProvider(provider) || preset.resumeFlag || preset.resumeSubcommand) && <Row label="Resume session ID (optional)">
<input
value={resumeSessionId}
onChange={(e) => { setResumeSessionId(e.target.value); setFolderNote(undefined); }}
@@ -357,7 +366,7 @@ export function AddAgentModal({ onClose, config }: AddAgentModalProps) {
Will resume this session in the chosen folder (git isolation disabled).
</span>
)}
- </Row>
+ </Row>}
<label style={{ display: 'flex', gap: 8, alignItems: 'center', cursor: resuming ? 'not-allowed' : 'pointer', opacity: resuming ? 0.5 : 1 }}>
<input
diff --git a/src/renderer/src/components/AgentStrip.tsx b/src/renderer/src/components/AgentStrip.tsx
index 5e3f23e5..42d298fd 100644
--- a/src/renderer/src/components/AgentStrip.tsx
+++ b/src/renderer/src/components/AgentStrip.tsx
@@ -4,6 +4,7 @@ import { PixelButton } from './PixelButton';
import { Icon } from './Icon';
import { useStore, type Agent } from '@/store/store';
import { buildSpawnCommand, inferAgentProvider, tokenizeCommand, type HarnessConfig } from '@/store/config';
+import { OFFICE_CAST, DEFAULT_CHARACTER } from '@/scene/office/cast';
export interface AgentStripProps {
/** Needed to rebuild a spawn command when a restorable agent predates the
@@ -48,6 +49,67 @@ export function AgentStrip({ config }: AgentStripProps) {
return () => { cancelled = true; clearInterval(iv); };
}, []);
+ // One-shot recovery: the previous session's team (dev1-mqf3kuw8 … dev9-mqfhlff5)
+ // was archived at closing time and survives ONLY in the hive registry — it was
+ // never written into this renderer's restore list, so the normal "restore team"
+ // can't see it. On first load, respawn exactly those 9 by their ORIGINAL id
+ // (same spawn recipe as restoreTeam) so each agent's Claude session, worktree and
+ // memory.md reattach by id. Guarded in localStorage so it fires at most once.
+ useEffect(() => {
+ const GUARD = 'cth.autoRestore.mqfh9';
+ if (localStorage.getItem(GUARD)) return;
+ const COHORT = [
+ 'dev1-mqf3kuw8', 'dev2-mqf3li68', 'dev3-mqffie2v', 'dev4-mqfhcjwk', 'dev5-mqfhkaa4',
+ 'dev6-mqfhkpku', 'dev7-mqfhkxwd', 'dev8-mqfhl7gl', 'dev9-mqfhlff5',
+ ];
+ const ACCENTS = ['coral', 'mint', 'sky', 'lemon', 'lilac', 'peach'] as const;
+ let cancelled = false;
+ (async () => {
+ try {
+ const cfg = await window.cth.getConfig();
+ const reg = await window.cth.hiveRegistry();
+ if (cancelled || !cfg || !reg?.agents) return;
+ localStorage.setItem(GUARD, '1'); // one-shot, regardless of per-agent outcome
+ const live = new Set(useStore.getState().agents.map((a) => a.id));
+ for (let i = 0; i < COHORT.length; i++) {
+ const m = reg.agents[COHORT[i]] as (undefined | (typeof reg.agents)[string] & { model?: string });
+ if (!m || live.has(m.id) || !m.cwd) continue;
+ const provider = inferAgentProvider(undefined, m.provider);
+ const command = buildSpawnCommand(cfg, m.model, provider);
+ if (!command) continue;
+ const [exe, ...args] = tokenizeCommand(command);
+ const ptyId = `pty-${m.id}`;
+ // The registry cwd for these workers IS their worktree; re-enter it if it
+ // still exists on disk (gitIsRepo false → pruned, but spawn still cd's there).
+ const worktreeOk = await window.cth.gitIsRepo(m.cwd);
+ const res = await window.cth.spawnPty({
+ id: ptyId, cwd: m.cwd, command: exe, provider, args, cols: 100, rows: 30,
+ isolate: false, resume: true,
+ hive: { id: m.id, name: m.name, provider, cwd: m.cwd, role: m.role },
+ });
+ if (res.ok) {
+ useStore.getState().addAgent({
+ id: m.id, name: m.name,
+ character: OFFICE_CAST[i % OFFICE_CAST.length]?.name ?? DEFAULT_CHARACTER,
+ accent: ACCENTS[i % ACCENTS.length],
+ description: m.role ?? 'a fresh harness',
+ project: '', tmuxTarget: '', cwd: m.cwd,
+ status: 'idle', action: worktreeOk ? 'starting up' : 'restored (worktree pruned)',
+ progress: 0, currentStation: 'desk', ptyId,
+ command, provider, model: m.model,
+ worktreePath: m.cwd, recentTextTs: Date.now(),
+ } as Agent);
+ } else {
+ console.error('[auto-restore] spawn failed for', m.id, res.error);
+ }
+ }
+ } catch (e) {
+ console.error('[auto-restore] failed', e);
+ }
+ })();
+ return () => { cancelled = true; };
+ }, []);
+
/** Respawn every worker from the previous session with its ORIGINAL agent id,
* cwd, model and command — the hive workspace (memory.md, inbox, registry
* entry) reattaches by itself, no memory transplant needed. */
diff --git a/src/renderer/src/components/CommandCenterPanel.tsx b/src/renderer/src/components/CommandCenterPanel.tsx
index 143a4000..229e1a5e 100644
--- a/src/renderer/src/components/CommandCenterPanel.tsx
+++ b/src/renderer/src/components/CommandCenterPanel.tsx
@@ -15,7 +15,17 @@ 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, modelsForProvider, tokenizeCommand, inferAgentProvider, isClaudeProvider } from '@/store/config';
+import {
+ buildSpawnCommand,
+ decodeProviderModel,
+ encodeProviderModel,
+ inferAgentProvider,
+ modelProvidersForAgent,
+ modelsForProvider,
+ providerPreset,
+ tokenizeCommand,
+ type AgentProvider
+} from '@/store/config';
/** Michael's control surface. Shown instead of the plain terminal/files panel
* when the god agent is selected: terminal + queue, the floor roster (with
@@ -236,7 +246,11 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
// hatch for a corrupted/garbled terminal (e.g. xterm reflow after dragging the
// window between displays of different sizes). With `resume` unset it's the
// old behavior: a model change that starts a fresh session.
- const restartWithModel = async (a: Agent, model: string | undefined, opts: { resume?: boolean } = {}) => {
+ const restartWithModel = async (
+ a: Agent,
+ model: string | undefined,
+ opts: { resume?: boolean; provider?: AgentProvider } = {}
+ ) => {
if (!a.ptyId) return;
setRestarting(a.id);
try {
@@ -248,10 +262,11 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
// the view — keyed on the unchanged ptyId — never re-attached a replacement,
// leaving a dead pane that swallowed every keystroke.)
resetTerminal(a.ptyId);
- // Respawn on the same CLI this agent already runs on (inferred from its
- // command if not explicitly tagged) so an Antigravity/Codex worker stays
- // on its own binary. tokenizeCommand keeps quoted model labels one arg.
- const provider = inferAgentProvider(a.command, a.provider);
+ // A model choice may also switch CLI/provider. Cross-provider sessions are
+ // incompatible, so only same-provider Restart & Continue requests resume.
+ const previousProvider = inferAgentProvider(a.command, a.provider);
+ const provider = opts.provider ?? previousProvider;
+ const resume = opts.resume === true && provider === previousProvider;
const command = buildSpawnCommand(cfg, model, provider);
const [exe, ...args] = tokenizeCommand(command.trim());
const hive = a.isGod
@@ -265,12 +280,28 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
const entry = acquireTerminal(a.ptyId);
let cols = 100, rows = 30;
try { entry.fit.fit(); cols = entry.term.cols; rows = entry.term.rows; } catch { /* host not sized yet */ }
- const res = await window.cth.spawnPty({ id: a.ptyId, cwd: a.cwd, command: exe, args, provider, cols, rows, hive, resume: opts.resume });
+ const res = await window.cth.spawnPty({
+ id: a.ptyId,
+ cwd: a.cwd,
+ command: exe,
+ args,
+ provider,
+ cols,
+ rows,
+ hive,
+ resume
+ });
if (res.ok) {
// On a pure resume the model is unchanged — don't overwrite it.
- const patch = opts.resume
+ const patch = resume
? { status: 'idle' as const, action: 'continuing…' }
- : { command: command.trim(), provider, model, status: 'idle' as const, action: 'restarting…' };
+ : {
+ command: command.trim(),
+ provider,
+ model,
+ status: 'idle' as const,
+ action: provider === previousProvider ? 'restarting…' : `switching to ${providerPreset(provider).label}…`
+ };
updateAgent(a.id, patch);
}
} catch { /* noop */ } finally {
@@ -386,6 +417,8 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
<Section title="AGENTS">
{agents.map((a) => {
+ const agentProvider = inferAgentProvider(a.command, a.provider);
+ const agentPreset = providerPreset(agentProvider);
const sample = samples[a.id];
const breaker = breakers[a.id];
const armed = !!breaker && (breaker.level === 'constrained' || breaker.level === 'stopped');
@@ -400,6 +433,8 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
const hasSpark = sparkSeries.some((v) => v > 0);
const rateVal = Math.round(rate[a.id] ?? 0);
const rateLabel = rateVal > 0 ? `${fmtTokens(rateVal)}/m` : 'rate';
+ const currentModelKnown = modelsForProvider(agentProvider)
+ .some((model) => model.id === a.model);
return (
<div key={a.id} style={{
display: 'flex', flexDirection: 'column', gap: 4,
@@ -486,43 +521,56 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
</span>
)}
</div>
- {isClaudeProvider(inferAgentProvider(a.command, a.provider)) ? <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<Select
- value={a.model ?? ''}
+ value={encodeProviderModel(agentProvider, a.model)}
disabled={restarting === a.id}
- onChange={(v) => restartWithModel(a, v || undefined)}
+ onChange={(value) => {
+ const choice = decodeProviderModel(value);
+ if (choice) void restartWithModel(a, choice.model, { provider: choice.provider });
+ }}
>
- {modelsForProvider(inferAgentProvider(a.command, a.provider)).map((m) => (
- <option key={m.label} value={m.id ?? ''}>{m.label}</option>
+ {(!agentPreset.supportsModel || !currentModelKnown) && (
+ <option value={encodeProviderModel(agentProvider, a.model)}>
+ {agentPreset.label} · {a.model ?? 'current'}
+ </option>
+ )}
+ {modelProvidersForAgent(a.isGod).map((preset) => (
+ <optgroup key={preset.id} label={preset.label}>
+ {modelsForProvider(preset.id).map((model) => (
+ <option
+ key={`${preset.id}:${model.id ?? 'default'}`}
+ value={encodeProviderModel(preset.id, model.id)}
+ >
+ {model.label}
+ </option>
+ ))}
+ </optgroup>
))}
</Select>
<span style={{ fontSize: 11, color: 'var(--cth-ink-500)' }}>
{restarting === a.id
? 'restarting…'
- : isClaudeProvider(inferAgentProvider(a.command, a.provider))
- ? 'model (restarts agent)'
- : `${inferAgentProvider(a.command, a.provider)} · model (restarts agent)`}
+ : `${agentPreset.label} model (restarts agent)`}
</span>
{/* Restart & Continue — kill + respawn keeping the SAME model and
resuming the prior conversation (--resume). Use this to redraw a
garbled TUI (e.g. after dragging the window across displays)
without losing the thread. */}
- <span style={{ flex: 1 }} />
- <PixelButton
- variant="secondary"
- size="sm"
- disabled={restarting === a.id}
- onClick={() => restartWithModel(a, a.model, { resume: true })}
- >
- <span title="Kill and respawn this agent, resuming its current conversation — fixes a corrupted/garbled terminal without losing context">
- restart &amp; continue
- </span>
- </PixelButton>
- </div> : (
- <div style={{ fontSize: 11, color: 'var(--cth-ink-500)' }}>
- provider: {inferAgentProvider(a.command, a.provider)}
- </div>
- )}
+ {(agentProvider === 'claude' || agentPreset.resumeFlag || agentPreset.resumeSubcommand) && <>
+ <span style={{ flex: 1 }} />
+ <PixelButton
+ variant="secondary"
+ size="sm"
+ disabled={restarting === a.id}
+ onClick={() => restartWithModel(a, a.model, { resume: true })}
+ >
+ <span title="Kill and respawn this agent, resuming its current conversation — fixes a corrupted/garbled terminal without losing context">
+ restart &amp; continue
+ </span>
+ </PixelButton>
+ </>}
+ </div>
</div>
);
})}
diff --git a/src/renderer/src/components/terminalAutomation.ts b/src/renderer/src/components/terminalAutomation.ts
new file mode 100644
index 00000000..979141c2
--- /dev/null
+++ b/src/renderer/src/components/terminalAutomation.ts
@@ -0,0 +1,30 @@
+/** Slash commands that open an interactive picker/panel instead of starting a
+ * normal agent turn. Automated queue delivery must wait until that UI closes. */
+const INTERACTIVE_COMMANDS = new Set([
+ '/model',
+ '/reasoning',
+ '/permissions',
+ '/permission',
+ '/provider',
+ '/settings',
+ '/config',
+ '/experimental',
+ '/experiments',
+ '/hooks',
+ '/mcp',
+ '/apps',
+ '/plugins',
+ '/resume',
+ '/sessions'
+]);
+
+export function opensInteractiveTerminalUi(input: string): boolean {
+ const command = input.trim().toLowerCase().split(/\s+/, 1)[0];
+ return INTERACTIVE_COMMANDS.has(command);
+}
+
+/** Follow output only if the user was already at (or one line from) the bottom.
+ * This keeps live TUIs visible without yanking someone reading scrollback. */
+export function shouldFollowTerminalOutput(viewportY: number, baseY: number): boolean {
+ return baseY - viewportY <= 1;
+}
diff --git a/src/renderer/src/components/terminalPool.ts b/src/renderer/src/components/terminalPool.ts
index d5b9b5ba..6c4d532e 100644
--- a/src/renderer/src/components/terminalPool.ts
+++ b/src/renderer/src/components/terminalPool.ts
@@ -17,6 +17,16 @@ import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import { WebglAddon } from '@xterm/addon-webgl';
import { Unicode11Addon } from '@xterm/addon-unicode11';
+import {
+ createTerminalRecoveryState,
+ requestInitialPtyRedraw,
+ scheduleWebglRecovery,
+ type TerminalRecoveryState
+} from './terminalRecovery';
+import {
+ opensInteractiveTerminalUi,
+ shouldFollowTerminalOutput
+} from './terminalAutomation';
import '@xterm/xterm/css/xterm.css';
export interface TerminalEntry {
@@ -34,6 +44,13 @@ export interface TerminalEntry {
/** Current consumer callbacks — set by whichever view is mounted. */
onData?: (chunk: string) => void;
onPrompt?: (text: string) => void;
+ recovery: TerminalRecoveryState;
+ needsRendererRepaint: boolean;
+ /** A user-opened slash-command picker (for example Codex `/model`) owns the
+ * input line. Queue automation waits until the picker closes. */
+ automationBlocked: boolean;
+ automationSettleUntil: number;
+ webgl?: WebglAddon;
}
const pool = new Map<string, TerminalEntry>();
@@ -80,12 +97,30 @@ export function acquireTerminal(ptyId: string, theme?: ThemeMap, fontSize = 14):
// NOTE: don't open() yet — xterm needs its host connected to the document to
// measure correctly. We open on first attach (see attachTerminal).
- const entry: TerminalEntry = { ptyId, term, fit, host, opened: false, exited: false, unsub: [] };
+ const entry: TerminalEntry = {
+ ptyId,
+ term,
+ fit,
+ host,
+ opened: false,
+ exited: false,
+ unsub: [],
+ recovery: createTerminalRecoveryState(),
+ needsRendererRepaint: false,
+ automationBlocked: false,
+ automationSettleUntil: 0
+ };
// Subscribe to the pty stream ONCE for the terminal's whole lifetime, so the
// buffer keeps filling even while this terminal isn't mounted in any view.
entry.unsub.push(window.cth.onPtyData(ptyId, (chunk) => {
- term.write(chunk);
+ const active = term.buffer.active;
+ const follow = shouldFollowTerminalOutput(active.viewportY, active.baseY);
+ term.write(chunk, () => {
+ if (follow) {
+ try { term.scrollToBottom(); } catch { /* terminal may be detaching */ }
+ }
+ });
entry.onData?.(chunk);
}));
entry.unsub.push(window.cth.onPtyExit(ptyId, ({ exitCode, signal }) => {
@@ -138,11 +173,25 @@ export function acquireTerminal(ptyId: string, theme?: ThemeMap, fontSize = 14):
term.onData((data) => {
if (entry.exited) return;
window.cth.writePty(ptyId, data);
+ // A lone Escape or Ctrl-C closes interactive pickers. Arrow-key escape
+ // sequences must NOT clear the block while the user navigates a picker.
+ if (data === '\x1b' || data === '\x03') {
+ entry.automationBlocked = false;
+ entry.automationSettleUntil = Date.now() + 500;
+ lineBuf = '';
+ }
for (let i = 0; i < data.length; i++) {
const ch = data[i];
if (ch === '\r' || ch === '\n') {
const t = lineBuf.trim();
lineBuf = '';
+ if (entry.automationBlocked) {
+ // Enter chooses an item and closes the current picker.
+ entry.automationBlocked = false;
+ entry.automationSettleUntil = Date.now() + 500;
+ } else if (opensInteractiveTerminalUi(t)) {
+ entry.automationBlocked = true;
+ }
if (t.length >= 2) entry.onPrompt?.(t);
} else if (ch === '\x7f' || ch === '\b') {
lineBuf = lineBuf.slice(0, -1);
@@ -158,6 +207,14 @@ export function acquireTerminal(ptyId: string, theme?: ThemeMap, fontSize = 14):
return entry;
}
+/** Whether queued automation can safely own this terminal's input line. A PTY
+ * without a pooled terminal cannot have a user-opened local picker. */
+export function isTerminalAutomationSafe(ptyId: string, now = Date.now()): boolean {
+ const entry = pool.get(ptyId);
+ if (!entry) return true;
+ return !entry.exited && !entry.automationBlocked && now >= entry.automationSettleUntil;
+}
+
/** Re-parent a pty's terminal into `container`, opening xterm on first attach. */
export function attachTerminal(entry: TerminalEntry, container: HTMLElement): void {
container.appendChild(entry.host);
@@ -176,7 +233,10 @@ export function attachTerminal(entry: TerminalEntry, container: HTMLElement): vo
try {
const webgl = new WebglAddon();
webgl.onContextLoss(() => {
+ if (entry.webgl !== webgl) return;
console.warn('[terminal] webgl context lost — falling back to DOM renderer');
+ entry.webgl = undefined;
+ entry.needsRendererRepaint = true;
try { webgl.dispose(); } catch { /* noop */ }
// Laptop sleep == GPU sleep == WebGL context loss: the likely PRIMARY
// trigger for the post-wake "can't scroll past a recent point" bug. The
@@ -185,13 +245,44 @@ export function attachTerminal(entry: TerminalEntry, container: HTMLElement): vo
// is scrollable until something forces a re-measure. Heal it here, on the
// next frame so the (waking) layout has settled. Guarded + idempotent, so
// it composes safely with the visibilitychange/focus path in the view.
- requestAnimationFrame(() => reflowTerminal(entry.ptyId));
+ scheduleWebglRecovery(entry.recovery, requestAnimationFrame, () => {
+ repaintTerminalAfterRendererLoss(entry);
+ });
});
+ // Set before loadAddon: an immediately-lost context may call the handler
+ // during initialization, and it must be recognized as the active renderer.
+ entry.webgl = webgl;
entry.term.loadAddon(webgl);
} catch (e) {
+ try { entry.webgl?.dispose(); } catch { /* noop */ }
+ entry.webgl = undefined;
console.warn('[terminal] webgl renderer unavailable, using DOM renderer:', e);
}
+ // PTY startup output can arrive before this pooled terminal subscribes.
+ // Request one same-size redraw after open/subscription even when fit() later
+ // sees unchanged dimensions and therefore emits no resize of its own.
+ requestInitialPtyRedraw(entry.recovery, () => {
+ void window.cth.redrawPty(entry.ptyId);
+ });
}
+ if (entry.needsRendererRepaint) {
+ scheduleWebglRecovery(entry.recovery, requestAnimationFrame, () => {
+ repaintTerminalAfterRendererLoss(entry);
+ });
+ }
+}
+
+function repaintTerminalAfterRendererLoss(entry: TerminalEntry): void {
+ if (!entry.opened || !entry.host.isConnected
+ || !entry.host.clientWidth || !entry.host.clientHeight) {
+ entry.needsRendererRepaint = true;
+ return;
+ }
+ entry.needsRendererRepaint = false;
+ reflowTerminal(entry.ptyId);
+ try {
+ entry.term.refresh(0, Math.max(0, entry.term.rows - 1));
+ } catch { /* renderer may still be settling */ }
}
/**
@@ -265,6 +356,7 @@ export function disposeTerminal(ptyId: string): void {
const entry = pool.get(ptyId);
if (!entry) return;
entry.unsub.forEach((u) => { try { u(); } catch { /* noop */ } });
+ try { entry.webgl?.dispose(); } catch { /* noop */ }
try { entry.term.dispose(); } catch { /* noop */ }
entry.host.remove();
pool.delete(ptyId);
diff --git a/src/renderer/src/components/terminalRecovery.ts b/src/renderer/src/components/terminalRecovery.ts
new file mode 100644
index 00000000..58351811
--- /dev/null
+++ b/src/renderer/src/components/terminalRecovery.ts
@@ -0,0 +1,34 @@
+export interface TerminalRecoveryState {
+ initialRedrawRequested: boolean;
+ webglRecoveryPending: boolean;
+}
+
+export function createTerminalRecoveryState(): TerminalRecoveryState {
+ return { initialRedrawRequested: false, webglRecoveryPending: false };
+}
+
+/** Request exactly one redraw after the renderer has subscribed to PTY output. */
+export function requestInitialPtyRedraw(
+ state: TerminalRecoveryState,
+ requestRedraw: () => void
+): boolean {
+ if (state.initialRedrawRequested) return false;
+ state.initialRedrawRequested = true;
+ requestRedraw();
+ return true;
+}
+
+/** Wait two paint frames after WebGL disposal so the DOM renderer can repaint. */
+export function scheduleWebglRecovery(
+ state: TerminalRecoveryState,
+ requestFrame: (cb: () => void) => void,
+ recover: () => void
+): boolean {
+ if (state.webglRecoveryPending) return false;
+ state.webglRecoveryPending = true;
+ requestFrame(() => requestFrame(() => {
+ state.webglRecoveryPending = false;
+ recover();
+ }));
+ return true;
+}
diff --git a/src/renderer/src/hooks/queueDelivery.ts b/src/renderer/src/hooks/queueDelivery.ts
new file mode 100644
index 00000000..760d92d6
--- /dev/null
+++ b/src/renderer/src/hooks/queueDelivery.ts
@@ -0,0 +1,14 @@
+/** Run one queued delivery and acknowledge it only after the sender resolves.
+ * Rejections deliberately leave the queue item untouched for the next retry. */
+export async function deliverWithAcknowledgement(
+ send: () => Promise<void>,
+ acknowledge: () => void
+): Promise<boolean> {
+ try {
+ await send();
+ acknowledge();
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.ts
index d4c3f6ac..838fa84d 100644
--- a/src/renderer/src/hooks/useHive.ts
+++ b/src/renderer/src/hooks/useHive.ts
@@ -4,24 +4,25 @@ import {
buildSpawnCommand,
ASSISTANT_MODEL,
inferAgentProvider,
- isClaudeProvider,
type HarnessConfig
} from '@/store/config';
+import { shouldAutoCompactContext } from '../../../shared/autoCompact';
+import {
+ compactionCommandForProvider,
+ remoteControlCommandForProvider,
+ terminalReadyToReceive
+} from '../../../shared/providerAutomation';
+import type { AgentProvider } from '../../../shared/agentProvider';
+import { isTerminalAutomationSafe } from '@/components/terminalPool';
+import { deliverWithAcknowledgement } from './queueDelivery';
const GOD_ID = 'god';
const GOD_PTY = `pty-${GOD_ID}`;
-// How long to let Claude Code's TUI finish booting before we type the first
-// thing into Michael's terminal, and how long to PAUSE after the /remote-control
-// command so the slash command lands + executes on its own line before the
-// orientation prompt follows (otherwise they jam into one line and the TUI shows
-// "Unknown command: /remote-control…").
-const GOD_BOOT_MS = 4000;
const REMOTE_CONTROL_SETTLE_MS = 1500;
// After a god/agent spawn, hold off the inbox-wake + queue-drain typers for this
-// long so they can't interleave with the boot sequence (remote-control +
-// orientation) and jam the input line.
-const BOOT_GRACE_MS = GOD_BOOT_MS + REMOTE_CONTROL_SETTLE_MS + 2500;
+// long while the readiness handshake + provider-specific boot sequence runs.
+const BOOT_GRACE_MS = 35_000;
// The first thing Michael (god) is told on a fresh spawn — orient him and put
// him to work running the floor. Kept terse and action-oriented.
@@ -34,27 +35,32 @@ const INITIAL_GOD_PROMPT = [
'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');
-// Scheduled auto-compact command (from the ops standup). Queued per agent and
-// delivered when idle, so it never interrupts a working agent. The focus
-// instructions make the agent record its current task + next step into the
-// summary, so it resumes from the same point after compacting.
-const COMPACT_CMD =
- '/compact Summarise exactly what you are currently working on and the next step, ' +
- 'so you can resume from the same point — then continue that work after compacting.';
-
-// Auto-compact only fires once an agent's live context has filled to at least
-// this fraction of its model's window. It's a FRACTION of contextLimit (which is
-// per-agent/per-model), so a 200k session and a 1M session both compact at the
-// same 30% relative fill — not at a fixed token count. Agents below this, or with
-// no context telemetry yet, are left alone — so the hourly standup no longer
-// compacts every terminal unconditionally.
-const COMPACT_CONTEXT_THRESHOLD = 0.3;
-
// Per-pty submission chain. Every submitToPty for a given pty is appended here so
// two callers (e.g. the boot sequence's /remote-control and the inbox-wake nudge)
// can NEVER interleave their text + Enter — which jammed them onto one line and
// produced "Unknown command: /remote-control<next prompt>".
const writeChains = new Map<string, Promise<void>>();
+const readyPids = new Map<string, number>();
+
+async function waitForTerminalReady(
+ ptyId: string,
+ provider: AgentProvider,
+ timeoutMs = 30_000
+): Promise<void> {
+ const started = Date.now();
+ while (Date.now() - started < timeoutMs) {
+ const live = await window.cth.listPtys();
+ const pty = live.find((entry) => entry.id === ptyId);
+ if (!pty) throw new Error(`PTY exited before becoming ready: ${ptyId}`);
+ if (readyPids.get(ptyId) === pty.pid) return;
+ if (terminalReadyToReceive(pty.hasOutput, Date.now() - started, provider)) {
+ readyPids.set(ptyId, pty.pid);
+ return;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ throw new Error(`PTY did not become ready within ${timeoutMs}ms: ${ptyId}`);
+}
/**
* Type a line into an agent's Claude Code TUI and actually submit it.
@@ -74,17 +80,25 @@ const writeChains = new Map<string, Promise<void>>();
* 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> {
+function submitToPty(
+ ptyId: string,
+ text: string,
+ provider: AgentProvider,
+ 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 waitForTerminalReady(ptyId, provider);
// Bracketed paste (ESC[200~ … ESC[201~) only matters for MULTI-LINE text, so a
// stray "\n" doesn't submit early (#24). Single-line text (nudges, slash
// commands) is sent raw — some TUIs (Antigravity's agy) treat the paste
// markers as literal input and never submit, so skipping them is more robust.
const payload = text.includes('\n') ? `\x1b[200~${text}\x1b[201~` : text;
- await window.cth.writePty(ptyId, payload);
+ const wrotePayload = await window.cth.writePty(ptyId, payload);
+ if (!wrotePayload.ok) throw new Error(wrotePayload.error ?? `PTY write failed: ${ptyId}`);
await new Promise((r) => setTimeout(r, 140));
- await window.cth.writePty(ptyId, '\r');
+ const wroteEnter = await window.cth.writePty(ptyId, '\r');
+ if (!wroteEnter.ok) throw new Error(wroteEnter.error ?? `PTY submit failed: ${ptyId}`);
await new Promise((r) => setTimeout(r, settleMs));
});
writeChains.set(ptyId, next);
@@ -196,7 +210,6 @@ export function useHive(config: HarnessConfig | null): void {
useEffect(() => {
if (!config?.onboardingComplete || !config.harnessHome) return;
let cancelled = false;
- const timers: ReturnType<typeof setTimeout>[] = [];
useStore.getState().setGodStatus('booting');
const t = setTimeout(async () => {
if (cancelled) return;
@@ -264,20 +277,20 @@ export function useHive(config: HarnessConfig | null): void {
// Michael until he's settled. The live-PTY branch above skips this entirely.
const resumedGod = res.resumed === true;
bootGraceUntil.current[GOD_ID] = Date.now() + BOOT_GRACE_MS;
- timers.push(setTimeout(() => {
- if (cancelled) return;
- // settleMs pauses the chain ~1.5s after /remote-control before the
- // orientation prompt (fresh spawns only) is submitted next. Name the RC
- // session "Michael" so it's identifiable in claude.ai / the mobile app
- // rather than the opaque hostname default (matches the per-agent
- // --remote-control-session-name-prefix set at spawn in the main process).
- submitToPty(GOD_PTY, '/remote-control Michael', REMOTE_CONTROL_SETTLE_MS).catch(() => { /* best-effort */ });
- if (!resumedGod) {
- submitToPty(GOD_PTY, INITIAL_GOD_PROMPT).catch(() => { /* pty may have died */ });
- }
- }, GOD_BOOT_MS));
+ void (async () => {
+ try {
+ const remoteCommand = remoteControlCommandForProvider('claude', 'Michael');
+ if (remoteCommand) {
+ await submitToPty(GOD_PTY, remoteCommand, 'claude', REMOTE_CONTROL_SETTLE_MS);
+ }
+ if (!cancelled && !resumedGod) {
+ await submitToPty(GOD_PTY, INITIAL_GOD_PROMPT, 'claude');
+ }
+ } catch { /* PTY may have died during startup */ }
+ finally { bootGraceUntil.current[GOD_ID] = 0; }
+ })();
}, 1200);
- return () => { cancelled = true; clearTimeout(t); timers.forEach(clearTimeout); };
+ return () => { cancelled = true; clearTimeout(t); };
}, [config?.onboardingComplete, config?.harnessHome]);
// 2) Drive avatars from real hook events emitted by each agent's shim.
@@ -464,7 +477,8 @@ export function useHive(config: HarnessConfig | null): void {
nudged.current[a.id] = newest;
await submitToPty(
a.ptyId!,
- 'You have new hive inbox message(s) — read your inbox, act on them now, and move handled ones to inbox/.done/. Act autonomously; only message god if you genuinely need a decision.'
+ 'You have new hive inbox message(s) — read your inbox, act on them now, and move handled ones to inbox/.done/. Act autonomously; only message god if you genuinely need a decision.',
+ inferAgentProvider(a.command, a.provider)
);
} else if (!newest) {
nudged.current[a.id] = '';
@@ -482,33 +496,53 @@ export function useHive(config: HarnessConfig | null): void {
useEffect(() => {
if (!config?.onboardingComplete) return;
const FLUSH_COOLDOWN_MS = 4500;
+ const inFlight = new Set<string>();
// Send the front of `srcId`'s queue into `target`'s pty (verbatim or wrapped),
- // gated on the target being idle + off cooldown. Keyed cooldown per target so
- // strict one-by-one delivery holds. Returns true if it dispatched.
- const dispatch = (srcId: string, target: Agent | undefined, wrap?: (m: QueuedMessage) => string): boolean => {
+ // gated on the target being idle, free of interactive menus, and off
+ // cooldown. The queue item is acknowledged only after BOTH PTY writes
+ // succeed; failures stay visible and retry automatically.
+ const dispatch = async (
+ srcId: string,
+ target: Agent | undefined,
+ wrap?: (m: QueuedMessage) => string
+ ): Promise<{ sent: boolean; message?: QueuedMessage }> => {
const { messageQueues, removeQueuedMessage } = useStore.getState();
const next = messageQueues[srcId]?.[0];
- if (!next || !target?.ptyId || target.status !== 'idle') return false;
+ if (!next || !target?.ptyId || target.status !== 'idle') return { sent: false };
const now = Date.now();
// Hold queued messages until the target finishes its boot sequence.
- if ((bootGraceUntil.current[target.id] ?? 0) >= now) return false;
- if (now - (lastFlush.current[target.id] ?? 0) < FLUSH_COOLDOWN_MS) return false;
+ if ((bootGraceUntil.current[target.id] ?? 0) >= now) return { sent: false };
+ if (!isTerminalAutomationSafe(target.ptyId, now)) return { sent: false };
+ if (now - (lastFlush.current[target.id] ?? 0) < FLUSH_COOLDOWN_MS) return { sent: false };
+ const flightKey = `${srcId}:${next.id}`;
+ if (inFlight.has(flightKey)) return { sent: false };
+ inFlight.add(flightKey);
lastFlush.current[target.id] = now;
- // Remove first so a burst of store updates can't double-send the same one.
- removeQueuedMessage(srcId, next.id);
- // Zero the gauge instantly on /clear — the new session's context isn't
- // known until statusLine fires after the first post-clear response, so
- // leaving it at the old value shows a stale-full bar during that window.
- if (next.text.trim().toLowerCase() === '/clear') {
- useStore.getState().updateAgent(target.id, { contextTokens: 0, contextLimit: undefined, progress: 0 });
+ try {
+ const sent = await deliverWithAcknowledgement(
+ // `instruction` (when present) is the authoritative text to type into
+ // the PTY; UI/card surfaces continue to show the readable `text`.
+ () => submitToPty(
+ target.ptyId!,
+ wrap ? wrap(next) : (next.instruction ?? next.text),
+ inferAgentProvider(target.command, target.provider)
+ ),
+ () => {
+ removeQueuedMessage(srcId, next.id);
+ if (next.text.trim().toLowerCase() === '/clear') {
+ useStore.getState().updateAgent(target.id, {
+ contextTokens: 0,
+ contextLimit: undefined,
+ progress: 0
+ });
+ }
+ }
+ );
+ return sent ? { sent: true, message: next } : { sent: false };
+ } finally {
+ inFlight.delete(flightKey);
}
- // `instruction` (when present) is the authoritative text to type into the
- // PTY — e.g. Slack-origin work carries the autonomy preamble there while the
- // kanban card keeps `text` (raw) as its readable title. UI/card surfaces
- // never read `instruction`, so this stays invisible to the human board.
- submitToPty(target.ptyId, wrap ? wrap(next) : (next.instruction ?? next.text)).catch(() => { /* pty may have died */ });
- return true;
};
// Promote a genuine Slack-origin work item to a stamped kanban card the first
@@ -551,8 +585,9 @@ export function useHive(config: HarnessConfig | null): void {
for (const a of agents) {
if (!a.ptyId || a.status !== 'idle') continue;
if (!messageQueues[a.id]?.length) continue;
- const head = messageQueues[a.id][0];
- if (dispatch(a.id, a) && head.slack) void ensureSlackCard(head);
+ void dispatch(a.id, a).then(({ sent, message }) => {
+ if (sent && message?.slack) void ensureSlackCard(message);
+ });
}
};
@@ -627,19 +662,19 @@ export function useHive(config: HarnessConfig | null): void {
const { agents, messageQueues, enqueueMessage } = useStore.getState();
for (const a of agents) {
if (!a.ptyId) continue;
- // /compact is a Claude Code slash command — non-Claude CLIs (agy, codex)
- // would just receive it as literal prompt text. Skip them.
- if (!isClaudeProvider(inferAgentProvider(a.command, a.provider))) continue;
+ const provider = inferAgentProvider(a.command, a.provider);
+ const compactCommand = compactionCommandForProvider(provider);
+ if (!compactCommand) continue;
// Only compact agents whose context has actually filled past the
// threshold. contextLimit is per-model (200k vs the 1M window), so this
// gate scales to each agent's own window instead of a fixed token count.
// Unknown telemetry (limit not polled yet) ⇒ skip — never compact blind.
const limit = a.contextLimit ?? 0;
const used = a.contextTokens ?? 0;
- if (limit <= 0 || used / limit < COMPACT_CONTEXT_THRESHOLD) continue;
+ if (!shouldAutoCompactContext(used, limit)) continue;
const queued = messageQueues[a.id] ?? [];
if (queued.some((m) => m.text.trimStart().startsWith('/compact'))) continue;
- enqueueMessage(a.id, COMPACT_CMD);
+ enqueueMessage(a.id, compactCommand);
}
});
}, [config?.onboardingComplete]);
diff --git a/src/renderer/src/store/config.ts b/src/renderer/src/store/config.ts
index 95bd900a..e3ec5690 100644
--- a/src/renderer/src/store/config.ts
+++ b/src/renderer/src/store/config.ts
@@ -100,6 +100,7 @@ export interface ModelOption {
export const AGENT_MODELS: ModelOption[] = [
{ id: undefined, label: 'default' },
{ id: 'claude-fable-5', label: 'Fable 5' },
+ { id: 'claude-opus-5', label: 'Opus 5 · 1M' },
{ id: 'claude-opus-4-8', label: 'Opus 4.8' },
{ id: 'claude-opus-4-8[1m]', label: 'Opus 4.8 · 1M' },
{ id: 'claude-sonnet-5', label: 'Sonnet 5' },
@@ -126,6 +127,22 @@ export const ANTIGRAVITY_MODELS: ModelOption[] = [
{ id: 'GPT-OSS 120B (Medium)', label: 'GPT-OSS 120B' }
];
+/** Current OpenAI models offered by Codex for coding agents. */
+export const CODEX_MODELS: ModelOption[] = [
+ { id: undefined, label: 'default' },
+ { id: 'gpt-5.6-sol', label: 'GPT-5.6 Sol' },
+ { id: 'gpt-5.6-terra', label: 'GPT-5.6 Terra' },
+ { id: 'gpt-5.6-luna', label: 'GPT-5.6 Luna' }
+];
+
+/** Managed Kimi Code aliases accepted by `kimi --model <alias>`. */
+export const KIMI_MODELS: ModelOption[] = [
+ { id: undefined, label: 'default' },
+ { id: 'kimi-code/k3', label: 'Kimi K3' },
+ { id: 'kimi-code/kimi-for-coding', label: 'Kimi K2.7 Code' },
+ { id: 'kimi-code/kimi-for-coding-highspeed', label: 'Kimi K2.7 · HighSpeed' }
+];
+
/** Split a command string into argv, respecting double/single quotes so a model
* value with spaces (agy's `--model "Gemini 3.1 Pro (High)"`) stays one token.
* Quotes are stripped from the result. */
@@ -139,7 +156,44 @@ export function tokenizeCommand(command: string): string[] {
/** The model preset list for a given provider's picker. */
export function modelsForProvider(provider: AgentProvider): ModelOption[] {
- return provider === 'antigravity' ? ANTIGRAVITY_MODELS : AGENT_MODELS;
+ switch (provider) {
+ case 'codex': return CODEX_MODELS;
+ case 'kimi': return KIMI_MODELS;
+ case 'antigravity': return ANTIGRAVITY_MODELS;
+ case 'claude': return AGENT_MODELS;
+ case 'custom': return [];
+ }
+}
+
+/** Providers shown in the Command Center's cross-provider model picker.
+ * God must remain on a provider with a working inbox drain; otherwise switching
+ * to a terminal-only provider would silently disable orchestration. */
+export function modelProvidersForAgent(isGod = false) {
+ return AGENT_PROVIDER_PRESETS.filter((preset) =>
+ preset.supportsModel && (!isGod || preset.canReceiveInbox)
+ );
+}
+
+/** Native <select> values must carry both provider and model because each
+ * provider has its own "default" option and model namespace. */
+export function encodeProviderModel(provider: AgentProvider, model?: string): string {
+ return `${provider}:${encodeURIComponent(model ?? '')}`;
+}
+
+export function decodeProviderModel(value: string): {
+ provider: AgentProvider;
+ model?: string;
+} | null {
+ const split = value.indexOf(':');
+ if (split < 1) return null;
+ const provider = value.slice(0, split);
+ if (!AGENT_PROVIDER_PRESETS.some((preset) => preset.id === provider)) return null;
+ try {
+ const model = decodeURIComponent(value.slice(split + 1));
+ return { provider: provider as AgentProvider, model: model || undefined };
+ } catch {
+ return null;
+ }
}
/** Build the command line to feed into spawnPty, honoring the provider's flags,
@@ -153,7 +207,7 @@ export function buildSpawnCommand(
): string {
const preset = providerPreset(provider);
// Claude keeps the user's configured defaultCommand; custom falls back to it
- // too; every other provider (codex, agy) uses its preset binary so the app
+ // too; every other provider (codex, kimi, agy) uses its preset binary so the app
// works even without Claude installed.
const base =
provider === 'claude'
@@ -169,7 +223,7 @@ export function buildSpawnCommand(
cmd = `${cmd} ${preset.modelFlag} ${m}`;
}
// Auto (skip-permissions) mode appends each provider's own flag — Claude's
- // bypassPermissions, codex's `-a never -s workspace-write`, agy's skip flag.
+ // bypassPermissions, Codex's dangerous bypass, Kimi's auto, or agy's skip flag.
if (config.autoMode && preset.autoFlag) cmd = `${cmd} ${preset.autoFlag}`;
return cmd;
}
diff --git a/src/shared/agentProvider.ts b/src/shared/agentProvider.ts
index 1b9f83ba..56baa231 100644
--- a/src/shared/agentProvider.ts
+++ b/src/shared/agentProvider.ts
@@ -1,8 +1,8 @@
/**
* Agent providers — the CLI a worker runs on. The app is no longer Claude-only:
- * a worker can run Claude Code, the OpenAI Codex CLI (`codex`), or the
- * Antigravity CLI (`agy`, Gemini models), or any custom command. Each provider
- * declares how to build its spawn command (model flag, auto-mode flag) and
+ * a worker can run Claude Code, the OpenAI Codex CLI (`codex`), Kimi Code
+ * (`kimi`), the Antigravity CLI (`agy`, Gemini models), or any custom command.
+ * Each provider declares how to build its spawn command (model/auto-mode flags) and
* whether it accepts the hive's Claude-specific identity injection
* (`--append-system-prompt` + `--settings`).
*
@@ -15,7 +15,7 @@ import type { CmdGroup } from './claudeCommands';
import { COMMAND_GROUPS as CLAUDE_COMMAND_GROUPS } from './claudeCommands';
import { CODEX_COMMAND_GROUPS } from './codexCommands';
-export type AgentProvider = 'claude' | 'codex' | 'antigravity' | 'custom';
+export type AgentProvider = 'claude' | 'codex' | 'kimi' | 'antigravity' | 'custom';
export interface AgentProviderPreset {
id: AgentProvider;
@@ -69,6 +69,10 @@ export interface AgentProviderPreset {
* takes its initial prompt POSITIONALLY (Codex: `codex "<prompt>"`) and the
* injection branch appends it as a quoted trailing arg instead of a flag. */
initialPromptFlag?: string;
+ /** This CLI accepts the initial hive prompt as a trailing positional argument.
+ * Codex does; Kimi/custom do not, so they must spawn bare when no prompt flag
+ * exists instead of receiving an invalid positional argument. */
+ positionalInitialPrompt?: boolean;
/** Flag to resume a prior session on respawn, given the recorded session id
* (Claude `--resume <sid>`, Antigravity `--conversation <id>`). undefined = no
* resume support, spawn fresh. */
@@ -92,14 +96,14 @@ export const AGENT_PROVIDER_PRESETS: AgentProviderPreset[] = [
},
{
id: 'codex',
- label: 'Codex',
+ label: 'Codex · GPT',
defaultCommand: 'codex',
commandGroups: CODEX_COMMAND_GROUPS,
- // -a never: never prompt for approval; -s workspace-write: sandbox scoped to
- // the workspace (no outbound network). Matches the non-interactive intent of
- // Claude's bypassPermissions while retaining a safety boundary.
- autoModeFlag: '-a never -s workspace-write',
- autoFlag: '-a never -s workspace-write',
+ // Exact Codex equivalent of Claude's bypassPermissions: no approvals and no
+ // Codex sandbox. Munder Difflin's global AUTO MODE is intentionally explicit
+ // about this trust level; users can edit the per-agent command to remove it.
+ autoModeFlag: '--dangerously-bypass-approvals-and-sandbox',
+ autoFlag: '--dangerously-bypass-approvals-and-sandbox',
// Suppresses first-run interactive prompts (directory-trust gate, installer).
nonInteractiveEnv: { CODEX_NON_INTERACTIVE: '1' },
supportsModel: true,
@@ -119,12 +123,30 @@ export const AGENT_PROVIDER_PRESETS: AgentProviderPreset[] = [
// inbox-wake nudge remains as a harmless fallback for an idle worker).
canReceiveInbox: true,
initialPromptFlag: undefined,
+ positionalInitialPrompt: true,
// Codex resumes via a SUBCOMMAND, not a flag: `codex resume [OPTIONS]
// [SESSION_ID]`. A `--resume <id>` flag does not exist, which is why restarts
// used to silently start a brand-new session instead of continuing.
resumeFlag: undefined,
resumeSubcommand: 'resume'
},
+ {
+ id: 'kimi',
+ label: 'Kimi Code',
+ defaultCommand: 'kimi',
+ commandGroups: [],
+ // Kimi --auto handles every approval and does not stop to ask questions,
+ // matching Munder Difflin's autonomous Claude/Codex default.
+ autoModeFlag: '--auto',
+ autoFlag: '--auto',
+ supportsModel: true,
+ modelFlag: '--model',
+ hiveAware: false,
+ // Kimi's interactive TUI has no positional initial-prompt form. It supports
+ // lifecycle hooks, but Munder Difflin does not yet install a Kimi hook bridge,
+ // so mail must bounce rather than being delivered with no drain path.
+ canReceiveInbox: false
+ },
{
id: 'antigravity',
label: 'Antigravity · Gemini',
@@ -157,6 +179,7 @@ export function isAgentProvider(value: unknown): value is AgentProvider {
return (
value === 'claude' ||
value === 'codex' ||
+ value === 'kimi' ||
value === 'antigravity' ||
value === 'custom'
);
@@ -201,6 +224,7 @@ export function inferAgentProvider(command: string | undefined, explicit?: unkno
if (normalized) return normalized;
const bin = commandBinary(command);
if (bin === 'codex') return 'codex';
+ if (bin === 'kimi') return 'kimi';
if (bin === 'agy' || bin === 'antigravity') return 'antigravity';
if (bin === 'claude' || !bin) return 'claude';
return 'custom';
diff --git a/src/shared/autoCompact.ts b/src/shared/autoCompact.ts
new file mode 100644
index 00000000..19083cdd
--- /dev/null
+++ b/src/shared/autoCompact.ts
@@ -0,0 +1,31 @@
+/** Smaller (~250k) windows compact later to avoid excessive churn; large
+ * (~1M) windows compact earlier because a 20% checkpoint is already substantial. */
+export const SMALL_CONTEXT_THRESHOLD = 0.3;
+export const LARGE_CONTEXT_THRESHOLD = 0.2;
+export const LARGE_CONTEXT_MIN_TOKENS = 500_000;
+
+export function autoCompactThresholdForLimit(limit: number): number {
+ return limit >= LARGE_CONTEXT_MIN_TOKENS
+ ? LARGE_CONTEXT_THRESHOLD
+ : SMALL_CONTEXT_THRESHOLD;
+}
+
+/** Unknown or invalid telemetry must never trigger a blind compaction. */
+export function shouldAutoCompactContext(used: number, limit: number): boolean {
+ return Number.isFinite(used)
+ && Number.isFinite(limit)
+ && used >= 0
+ && limit > 0
+ && used / limit >= autoCompactThresholdForLimit(limit);
+}
+
+/** Enable auto-compaction on the persisted built-in hourly mission only. */
+export function enableOpsStandupAutoCompact<
+ T extends { id: string; autoCompact?: boolean }
+>(missions: T[]): T[] {
+ return missions.map((mission) =>
+ mission.id === 'ops-standup' && mission.autoCompact !== true
+ ? { ...mission, autoCompact: true }
+ : mission
+ );
+}
diff --git a/src/shared/codexRemote.ts b/src/shared/codexRemote.ts
new file mode 100644
index 00000000..52a86b8b
--- /dev/null
+++ b/src/shared/codexRemote.ts
@@ -0,0 +1,28 @@
+import { createHash } from 'node:crypto';
+import { join } from 'node:path';
+
+export const CODEX_REMOTE_SOCKET_RELATIVE =
+ 'app-server-control/app-server-control.sock';
+
+/** Keep the CODEX_HOME spelling short enough for macOS's Unix-socket limit. */
+export function codexRemoteAliasPath(
+ realHome: string,
+ agentId: string,
+ tempRoot: string
+): string {
+ const digest = createHash('sha256')
+ .update(`${realHome}\0${agentId}`)
+ .digest('hex')
+ .slice(0, 16);
+ return join(tempRoot, 'munder-codex', digest);
+}
+
+export function codexRemoteEndpoint(shortHome: string): string {
+ return `unix://${join(shortHome, CODEX_REMOTE_SOCKET_RELATIVE)}`;
+}
+
+/** Global options must precede `resume`, so prepend the endpoint in all cases. */
+export function withCodexRemoteArgs(args: string[], endpoint: string): string[] {
+ if (args.includes('--remote')) return args;
+ return ['--remote', endpoint, ...args];
+}
diff --git a/src/shared/providerAutomation.ts b/src/shared/providerAutomation.ts
new file mode 100644
index 00000000..3f48d469
--- /dev/null
+++ b/src/shared/providerAutomation.ts
@@ -0,0 +1,68 @@
+import type { AgentProvider } from './agentProvider';
+
+const COMPACTION_FOCUS =
+ 'Summarise exactly what you are currently working on and the next step, ' +
+ 'so you can resume from the same point — then continue that work after compacting.';
+
+/** Generate only commands that the target provider's interactive TUI supports. */
+export function compactionCommandForProvider(provider: AgentProvider): string | null {
+ switch (provider) {
+ case 'claude':
+ return `/compact ${COMPACTION_FOCUS}`;
+ case 'codex':
+ // Codex treats trailing text differently across CLI releases. Its stable
+ // automation form is the bare slash command.
+ return '/compact';
+ case 'kimi':
+ // Kimi Code documents `/compact [<instruction>]`, so preserve the task
+ // focus in its supported optional instruction.
+ return `/compact ${COMPACTION_FOCUS}`;
+ default:
+ return null;
+ }
+}
+
+/** Safe fallback when a provider has no native context-compaction command. */
+export function compactionPromptFallback(): string {
+ return (
+ 'Summarise the current task, decisions, and exact next step in your persistent ' +
+ 'memory, then continue from that checkpoint.'
+ );
+}
+
+/** Claude exposes remote control as a slash command; Codex uses its daemon and
+ * Kimi has no equivalent slash command. */
+export function remoteControlCommandForProvider(
+ provider: AgentProvider,
+ sessionName?: string
+): string | null {
+ if (provider !== 'claude') return null;
+ const name = sessionName?.trim();
+ return name ? `/remote-control ${name}` : '/remote-control';
+}
+
+/** Initial TUI output needs a short provider-specific settle before typing. */
+export function terminalReadySettleMs(provider: AgentProvider): number {
+ switch (provider) {
+ case 'kimi': return 650;
+ case 'codex': return 500;
+ default: return 400;
+ }
+}
+
+/**
+ * A live TUI is ready after it has produced an initial frame and had a short
+ * settle period. Do not require output to become quiet: Codex can continuously
+ * repaint its status line, which previously kept queued messages blocked until
+ * every readiness attempt timed out.
+ *
+ * `undefined` is accepted for compatibility with a renderer hot-reloaded
+ * against an older main process that does not yet expose `hasOutput`.
+ */
+export function terminalReadyToReceive(
+ hasOutput: boolean | undefined,
+ elapsedMs: number,
+ provider: AgentProvider
+): boolean {
+ return hasOutput !== false && elapsedMs >= terminalReadySettleMs(provider);
+}
diff --git a/test/auto-compact.test.cjs b/test/auto-compact.test.cjs
new file mode 100644
index 00000000..906193d5
--- /dev/null
+++ b/test/auto-compact.test.cjs
@@ -0,0 +1,41 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const loadTs = require('./load-ts.cjs');
+
+const {
+ LARGE_CONTEXT_THRESHOLD,
+ SMALL_CONTEXT_THRESHOLD,
+ autoCompactThresholdForLimit,
+ shouldAutoCompactContext,
+ enableOpsStandupAutoCompact
+} = loadTs('src/shared/autoCompact.ts');
+
+test('auto-compaction uses 30% for ~250k and 20% for ~1M windows', () => {
+ assert.equal(SMALL_CONTEXT_THRESHOLD, 0.3);
+ assert.equal(LARGE_CONTEXT_THRESHOLD, 0.2);
+ assert.equal(autoCompactThresholdForLimit(258_400), 0.3);
+ assert.equal(autoCompactThresholdForLimit(1_000_000), 0.2);
+ assert.equal(shouldAutoCompactContext(77_519, 258_400), false);
+ assert.equal(shouldAutoCompactContext(77_520, 258_400), true);
+ assert.equal(shouldAutoCompactContext(199_999, 1_000_000), false);
+ assert.equal(shouldAutoCompactContext(200_000, 1_000_000), true);
+});
+
+test('auto-compaction skips missing or invalid telemetry', () => {
+ assert.equal(shouldAutoCompactContext(0, 0), false);
+ assert.equal(shouldAutoCompactContext(-1, 100), false);
+ assert.equal(shouldAutoCompactContext(Number.NaN, 100), false);
+});
+
+test('persisted ops standup is enabled without changing other missions', () => {
+ const missions = [
+ { id: 'ops-standup', enabled: true, autoCompact: false },
+ { id: 'custom', enabled: true, autoCompact: false }
+ ];
+ const migrated = enableOpsStandupAutoCompact(missions);
+ assert.equal(migrated[0].autoCompact, true);
+ assert.equal(migrated[1].autoCompact, false);
+ assert.equal(missions[0].autoCompact, false, 'migration is immutable');
+});
diff --git a/test/codex-remote.test.cjs b/test/codex-remote.test.cjs
new file mode 100644
index 00000000..51570fbe
--- /dev/null
+++ b/test/codex-remote.test.cjs
@@ -0,0 +1,37 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const loadTs = require('./load-ts.cjs');
+
+const {
+ codexRemoteAliasPath,
+ codexRemoteEndpoint,
+ withCodexRemoteArgs
+} = loadTs('src/shared/codexRemote.ts');
+
+test('Codex remote uses a short stable per-agent home alias', () => {
+ const first = codexRemoteAliasPath('/very/long/hive/agent/.codex', 'dev-1', '/tmp');
+ const again = codexRemoteAliasPath('/very/long/hive/agent/.codex', 'dev-1', '/tmp');
+ const other = codexRemoteAliasPath('/very/long/hive/agent/.codex', 'dev-2', '/tmp');
+ assert.equal(first, again);
+ assert.notEqual(first, other);
+ assert.ok(first.length < 80);
+ assert.match(codexRemoteEndpoint(first), /^unix:\/\/\/tmp\//);
+});
+
+test('remote endpoint precedes both fresh and resumed Codex invocations', () => {
+ const endpoint = 'unix:///tmp/munder-codex/a/app-server-control/app-server-control.sock';
+ assert.deepEqual(
+ withCodexRemoteArgs(['--model', 'gpt-5.6-sol', 'hello'], endpoint),
+ ['--remote', endpoint, '--model', 'gpt-5.6-sol', 'hello']
+ );
+ assert.deepEqual(
+ withCodexRemoteArgs(['resume', 'session-id', '--model', 'gpt-5.6-sol'], endpoint),
+ ['--remote', endpoint, 'resume', 'session-id', '--model', 'gpt-5.6-sol']
+ );
+ assert.deepEqual(
+ withCodexRemoteArgs(['--remote', endpoint, 'resume'], endpoint),
+ ['--remote', endpoint, 'resume']
+ );
+});
diff --git a/test/load-ts.cjs b/test/load-ts.cjs
new file mode 100644
index 00000000..293efe3e
--- /dev/null
+++ b/test/load-ts.cjs
@@ -0,0 +1,56 @@
+'use strict';
+
+const fs = require('node:fs');
+const path = require('node:path');
+const ts = require('typescript');
+
+const cache = new Map();
+
+function resolveTs(fromDir, request) {
+ const base = request.startsWith('@shared/')
+ ? path.resolve(__dirname, '..', 'src/shared', request.slice('@shared/'.length))
+ : path.resolve(fromDir, request);
+ for (const candidate of [base, `${base}.ts`, path.join(base, 'index.ts')]) {
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) return candidate;
+ }
+ return null;
+}
+
+function loadFile(filename) {
+ const cached = cache.get(filename);
+ if (cached) return cached.exports;
+ const source = fs.readFileSync(filename, 'utf8');
+ const output = ts.transpileModule(source, {
+ compilerOptions: {
+ module: ts.ModuleKind.CommonJS,
+ target: ts.ScriptTarget.ES2022,
+ strict: true
+ },
+ fileName: filename,
+ reportDiagnostics: true
+ });
+ if (output.diagnostics?.length) {
+ throw new Error(ts.formatDiagnosticsWithColorAndContext(output.diagnostics, {
+ getCurrentDirectory: () => process.cwd(),
+ getCanonicalFileName: (name) => name,
+ getNewLine: () => '\n'
+ }));
+ }
+ const mod = { exports: {} };
+ cache.set(filename, mod);
+ const localRequire = (request) => {
+ if (request.startsWith('.') || request.startsWith('@shared/')) {
+ const resolved = resolveTs(path.dirname(filename), request);
+ if (resolved) return loadFile(resolved);
+ }
+ return require(request);
+ };
+ const run = new Function('module', 'exports', 'require', '__filename', '__dirname', output.outputText);
+ run(mod, mod.exports, localRequire, filename, path.dirname(filename));
+ return mod.exports;
+}
+
+/** Load a TypeScript module and its local TypeScript imports for node:test. */
+module.exports = function loadTs(relativePath) {
+ return loadFile(path.resolve(__dirname, '..', relativePath));
+};
diff --git a/test/provider-automation.test.cjs b/test/provider-automation.test.cjs
new file mode 100644
index 00000000..b12249cd
--- /dev/null
+++ b/test/provider-automation.test.cjs
@@ -0,0 +1,45 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const loadTs = require('./load-ts.cjs');
+
+const {
+ compactionCommandForProvider,
+ compactionPromptFallback,
+ remoteControlCommandForProvider,
+ terminalReadySettleMs,
+ terminalReadyToReceive
+} = loadTs('src/shared/providerAutomation.ts');
+
+test('each provider receives only its supported compaction syntax', () => {
+ const claude = compactionCommandForProvider('claude');
+ const codex = compactionCommandForProvider('codex');
+ const kimi = compactionCommandForProvider('kimi');
+
+ assert.match(claude, /^\/compact Summarise exactly/);
+ assert.equal(codex, '/compact');
+ assert.match(kimi, /^\/compact Summarise exactly/);
+ assert.equal(compactionCommandForProvider('antigravity'), null);
+ assert.equal(compactionCommandForProvider('custom'), null);
+ assert.match(compactionPromptFallback(), /^Summarise the current task/);
+});
+
+test('Claude alone receives a remote-control slash command', () => {
+ assert.equal(remoteControlCommandForProvider('claude', 'Michael'), '/remote-control Michael');
+ assert.equal(remoteControlCommandForProvider('codex', 'Jim'), null);
+ assert.equal(remoteControlCommandForProvider('kimi', 'Pam'), null);
+});
+
+test('provider readiness policies allow each TUI to settle', () => {
+ assert.equal(terminalReadySettleMs('claude'), 400);
+ assert.equal(terminalReadySettleMs('codex'), 500);
+ assert.equal(terminalReadySettleMs('kimi'), 650);
+});
+
+test('continuous TUI repainting cannot block terminal readiness', () => {
+ assert.equal(terminalReadyToReceive(false, 10_000, 'codex'), false);
+ assert.equal(terminalReadyToReceive(true, 499, 'codex'), false);
+ assert.equal(terminalReadyToReceive(true, 500, 'codex'), true);
+ assert.equal(terminalReadyToReceive(undefined, 500, 'codex'), true);
+});
diff --git a/test/provider-config.test.cjs b/test/provider-config.test.cjs
new file mode 100644
index 00000000..e761f1c8
--- /dev/null
+++ b/test/provider-config.test.cjs
@@ -0,0 +1,91 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const loadTs = require('./load-ts.cjs');
+
+const {
+ inferAgentProvider,
+ isAgentProvider,
+ providerPreset
+} = loadTs('src/shared/agentProvider.ts');
+const {
+ buildSpawnCommand,
+ decodeProviderModel,
+ encodeProviderModel,
+ modelProvidersForAgent,
+ modelsForProvider
+} = loadTs('src/renderer/src/store/config.ts');
+
+const autoConfig = { defaultCommand: 'claude', autoMode: true };
+
+test('Kimi is a first-class inferred provider with autonomous defaults', () => {
+ assert.equal(isAgentProvider('kimi'), true);
+ assert.equal(inferAgentProvider('kimi --auto'), 'kimi');
+ const preset = providerPreset('kimi');
+ assert.equal(preset.defaultCommand, 'kimi');
+ assert.equal(preset.autoFlag, '--auto');
+ assert.equal(preset.supportsModel, true);
+ assert.equal(preset.canReceiveInbox, false);
+ assert.equal(preset.positionalInitialPrompt, undefined);
+});
+
+test('provider commands use matching models and equivalent bypass modes', () => {
+ assert.equal(
+ buildSpawnCommand(autoConfig, 'claude-sonnet-5', 'claude'),
+ 'claude --model claude-sonnet-5 --permission-mode bypassPermissions'
+ );
+ assert.equal(
+ buildSpawnCommand(autoConfig, 'gpt-5.6-sol', 'codex'),
+ 'codex --model gpt-5.6-sol --dangerously-bypass-approvals-and-sandbox'
+ );
+ assert.equal(
+ buildSpawnCommand(autoConfig, 'kimi-code/k3', 'kimi'),
+ 'kimi --model kimi-code/k3 --auto'
+ );
+});
+
+test('model picker options stay provider-specific', () => {
+ assert.equal(
+ modelsForProvider('claude').find((model) => model.id === 'claude-opus-5')?.label,
+ 'Opus 5 · 1M'
+ );
+ assert.deepEqual(
+ modelsForProvider('codex').map((model) => model.id),
+ [undefined, 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna']
+ );
+ assert.deepEqual(
+ modelsForProvider('kimi').map((model) => model.id),
+ [
+ undefined,
+ 'kimi-code/k3',
+ 'kimi-code/kimi-for-coding',
+ 'kimi-code/kimi-for-coding-highspeed'
+ ]
+ );
+ assert.deepEqual(modelsForProvider('custom'), []);
+});
+
+test('Command Center model choices round-trip provider and model', () => {
+ const encoded = encodeProviderModel('antigravity', 'Gemini 3.1 Pro (High)');
+ assert.deepEqual(
+ decodeProviderModel(encoded),
+ { provider: 'antigravity', model: 'Gemini 3.1 Pro (High)' }
+ );
+ assert.deepEqual(
+ decodeProviderModel(encodeProviderModel('kimi')),
+ { provider: 'kimi', model: undefined }
+ );
+ assert.equal(decodeProviderModel('unknown:model'), null);
+});
+
+test('God only sees providers that can drain hive inbox messages', () => {
+ assert.deepEqual(
+ modelProvidersForAgent(true).map((preset) => preset.id),
+ ['claude', 'codex', 'antigravity']
+ );
+ assert.deepEqual(
+ modelProvidersForAgent(false).map((preset) => preset.id),
+ ['claude', 'codex', 'kimi', 'antigravity']
+ );
+});
diff --git a/test/queue-delivery.test.cjs b/test/queue-delivery.test.cjs
new file mode 100644
index 00000000..bf4000cd
--- /dev/null
+++ b/test/queue-delivery.test.cjs
@@ -0,0 +1,33 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const loadTs = require('./load-ts.cjs');
+
+const { deliverWithAcknowledgement } =
+ loadTs('src/renderer/src/hooks/queueDelivery.ts');
+
+test('queue item is acknowledged only after delivery succeeds', async () => {
+ let finish;
+ let acknowledged = false;
+ const sending = new Promise((resolve) => { finish = resolve; });
+ const attempt = deliverWithAcknowledgement(
+ () => sending,
+ () => { acknowledged = true; }
+ );
+
+ assert.equal(acknowledged, false);
+ finish();
+ assert.equal(await attempt, true);
+ assert.equal(acknowledged, true);
+});
+
+test('failed delivery remains unacknowledged for retry', async () => {
+ let acknowledged = false;
+ const sent = await deliverWithAcknowledgement(
+ () => Promise.reject(new Error('PTY unavailable')),
+ () => { acknowledged = true; }
+ );
+ assert.equal(sent, false);
+ assert.equal(acknowledged, false);
+});
diff --git a/test/terminal-automation.test.cjs b/test/terminal-automation.test.cjs
new file mode 100644
index 00000000..ab7079e7
--- /dev/null
+++ b/test/terminal-automation.test.cjs
@@ -0,0 +1,24 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const loadTs = require('./load-ts.cjs');
+
+const {
+ opensInteractiveTerminalUi,
+ shouldFollowTerminalOutput
+} = loadTs('src/renderer/src/components/terminalAutomation.ts');
+
+test('interactive provider commands pause queue automation', () => {
+ assert.equal(opensInteractiveTerminalUi('/model'), true);
+ assert.equal(opensInteractiveTerminalUi(' /provider '), true);
+ assert.equal(opensInteractiveTerminalUi('/permissions allow'), true);
+ assert.equal(opensInteractiveTerminalUi('/compact'), false);
+ assert.equal(opensInteractiveTerminalUi('implement this'), false);
+});
+
+test('terminal output follows only when already at the bottom', () => {
+ assert.equal(shouldFollowTerminalOutput(100, 100), true);
+ assert.equal(shouldFollowTerminalOutput(99, 100), true);
+ assert.equal(shouldFollowTerminalOutput(80, 100), false);
+});
diff --git a/test/terminal-recovery.test.cjs b/test/terminal-recovery.test.cjs
new file mode 100644
index 00000000..174680ab
--- /dev/null
+++ b/test/terminal-recovery.test.cjs
@@ -0,0 +1,36 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const loadTs = require('./load-ts.cjs');
+
+const {
+ createTerminalRecoveryState,
+ requestInitialPtyRedraw,
+ scheduleWebglRecovery
+} = loadTs('src/renderer/src/components/terminalRecovery.ts');
+
+test('initial attach requests exactly one PTY redraw', () => {
+ const state = createTerminalRecoveryState();
+ let redraws = 0;
+ assert.equal(requestInitialPtyRedraw(state, () => { redraws++; }), true);
+ assert.equal(requestInitialPtyRedraw(state, () => { redraws++; }), false);
+ assert.equal(redraws, 1);
+});
+
+test('WebGL recovery is deduped and repaints after two frames', () => {
+ const state = createTerminalRecoveryState();
+ const frames = [];
+ let repaints = 0;
+ const requestFrame = (cb) => frames.push(cb);
+
+ assert.equal(scheduleWebglRecovery(state, requestFrame, () => { repaints++; }), true);
+ assert.equal(scheduleWebglRecovery(state, requestFrame, () => { repaints++; }), false);
+ assert.equal(frames.length, 1);
+ frames.shift()();
+ assert.equal(repaints, 0);
+ assert.equal(frames.length, 1);
+ frames.shift()();
+ assert.equal(repaints, 1);
+ assert.equal(state.webglRecoveryPending, false);
+});