Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

feat(agents): make resume and delivery safe

Vyapak Goyal6d1a73bd971a
diff --git a/package.json b/package.json
index 611059cb..96c6e923 100644
--- a/package.json
+++ b/package.json
@@ -19,7 +19,7 @@
"typecheck:node": "tsc --noEmit -p tsconfig.node.json",
"typecheck:web": "tsc --noEmit -p tsconfig.web.json",
"typecheck": "npm run typecheck:node && npm run typecheck:web",
- "test:focused": "node --test test/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",
+ "test:focused": "node --test test/auto-compact.test.cjs test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs",
"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 66eb4f14..edbaa173 100644
--- a/src/main/config.ts
+++ b/src/main/config.ts
@@ -154,6 +154,9 @@ export interface HarnessConfig {
* tokens exceed its cap the breaker trips that agent alone (independent of the
* floor budget). Set from each agent's card in the Command Center. */
agentTokenCaps?: Record<string, number>;
+ /** Agent ids whose automatic inbox/queue delivery is paused. Pending messages
+ * stay durable until the operator explicitly resumes delivery. */
+ autoDeliveryPausedAgents?: string[];
/** Passed to every spawned agent as `--max-turns <n>` when set; unset = no cap
* (Claude Code's default). A coarse runaway guard independent of the breaker. */
maxTurns?: number;
diff --git a/src/main/control.ts b/src/main/control.ts
index 94c058a3..fcb47a4e 100644
--- a/src/main/control.ts
+++ b/src/main/control.ts
@@ -20,6 +20,7 @@
export interface AgentControlSnapshot {
paused: boolean;
halted: boolean;
+ autoDeliveryPaused: boolean;
gatedTools: string[];
pendingSteers: number;
}
@@ -27,6 +28,7 @@ export interface AgentControlSnapshot {
interface AgentControl {
paused: boolean;
halted: boolean;
+ autoDeliveryPaused: boolean;
gatedTools: Set<string>;
steerQueue: string[];
}
@@ -36,13 +38,32 @@ export class ControlRegistry {
private ensure(id: string): AgentControl {
let c = this.map.get(id);
- if (!c) { c = { paused: false, halted: false, gatedTools: new Set(), steerQueue: [] }; this.map.set(id, c); }
+ if (!c) {
+ c = {
+ paused: false,
+ halted: false,
+ autoDeliveryPaused: false,
+ gatedTools: new Set(),
+ steerQueue: []
+ };
+ this.map.set(id, c);
+ }
return c;
}
// ─── Operator actions (wired to IPC) ───────────────────────────────────────
pause(id: string, on: boolean): void { this.ensure(id).paused = on; }
+ pauseAutoDelivery(id: string, on: boolean): void {
+ this.ensure(id).autoDeliveryPaused = on;
+ }
+ replaceAutoDeliveryPauses(ids: Iterable<string>): void {
+ const paused = new Set(ids);
+ for (const [id, control] of this.map) {
+ control.autoDeliveryPaused = paused.has(id);
+ }
+ for (const id of paused) this.ensure(id).autoDeliveryPaused = true;
+ }
gateTool(id: string, tool: string, on: boolean): void {
const c = this.ensure(id);
if (on) c.gatedTools.add(tool); else c.gatedTools.delete(tool);
@@ -62,6 +83,9 @@ export class ControlRegistry {
// ─── Reads (used by HookServer) ────────────────────────────────────────────
shouldHalt(id: string): boolean { return this.map.get(id)?.halted ?? false; }
+ isAutoDeliveryPaused(id: string): boolean {
+ return this.map.get(id)?.autoDeliveryPaused ?? false;
+ }
/** Whether a tool call should be denied (paused agent, or this tool gated). */
toolDecision(id: string, tool: string): { deny: boolean; reason?: string } {
@@ -80,6 +104,7 @@ export class ControlRegistry {
return {
paused: c?.paused ?? false,
halted: c?.halted ?? false,
+ autoDeliveryPaused: c?.autoDeliveryPaused ?? false,
gatedTools: c ? Array.from(c.gatedTools) : [],
pendingSteers: c?.steerQueue.length ?? 0
};
diff --git a/src/main/hive.ts b/src/main/hive.ts
index 8391bc51..5b2b537d 100644
--- a/src/main/hive.ts
+++ b/src/main/hive.ts
@@ -641,10 +641,9 @@ export class HiveManager {
const targets = msg.to === 'broadcast'
// The roster for fan-out is the ACTIVE registry: skip the send-only prep
// assistant, any archived agent (closed tab), and providers that can't
- // drain an inbox (hookless custom commands) so mail never piles into a dead
- // inbox no one reads. Claude, Codex AND Antigravity workers ARE included —
- // each can drain its inbox on Stop: Claude via its native Stop hook, and
- // Antigravity/Codex via their `hookBridge` Stop→drain (agy-hook / codex-hook).
+ // expose safe-idle lifecycle state (hookless custom commands), so mail never
+ // piles into a dead inbox. Claude, Codex and Antigravity are included; their
+ // hooks let the renderer wake them only after a safe idle boundary.
? Object.keys(reg.agents).filter((a) =>
a !== msg.from
&& !reg.agents[a]?.isAssistant
@@ -666,10 +665,9 @@ export class HiveManager {
}, godId);
continue;
}
- // A provider that can't drain its own inbox (a hookless custom command)
- // would let direct mail rot unread. Claude (native Stop hook) and
- // Antigravity/Codex (their `hookBridge` Stop→drain) all drain their inbox,
- // so they receive directly into their inbox/. For a provider that can't, try
+ // A provider without safe-idle lifecycle state (a hookless custom command)
+ // would let direct mail rot unread. Claude and bridged Antigravity/Codex
+ // receive directly into inbox/ for guarded renderer delivery. Otherwise try
// a terminal work-order handoff to its REPL (#53);
// if the renderer is unavailable, bounce to god to relay. God is exempt
// (the bounce target).
@@ -824,7 +822,7 @@ export class HiveManager {
/** Install the Antigravity (`agy`) lifecycle-hook bridge: write the normalizer
* shim and merge a `munder-hive` hook group into agy's global hooks.json so a
* Gemini worker reports PreToolUse/PostToolUse/Stop/PreInvocation/PostInvocation
- * to this HookServer (live status + inbox-drain), reusing the Claude pipeline.
+ * to this HookServer (live status + guarded idle delivery), reusing the Claude pipeline.
*
* Two agy-isms handled: (1) antigravity-cli#49 — agy LOADS hooks from
* `~/.gemini/antigravity-cli/hooks.json` but TRIGGERS from `~/.gemini/config/
diff --git a/src/main/hooks.ts b/src/main/hooks.ts
index 4ed79aed..311a452f 100644
--- a/src/main/hooks.ts
+++ b/src/main/hooks.ts
@@ -5,9 +5,8 @@
* shim (see HOOK_SHIM in hive.ts) that forwards the hook payload to the Unix
* domain socket this server listens on. We then:
* - drive avatar state from PreToolUse/PostToolUse/Notification/etc., and
- * - implement the autonomous loop: on Stop, drain the agent's inbox and return
- * {"decision":"block", reason} so the agent keeps working — guarded by
- * `stop_hook_active` so it can never loop forever.
+ * - report lifecycle boundaries while renderer-side guarded queues deliver
+ * inbox work only after the session reaches a safe idle prompt.
*
* Runs in the Electron main process.
*/
@@ -141,18 +140,12 @@ export class HookServer {
}
if ((event === 'Stop' || event === 'SubagentStop') && agentId) {
- // Loop guard: a previous Stop hook already blocked this turn → let it stop.
+ // Respect any upstream Stop hook that already re-entered this boundary.
if (p.stop_hook_active) { this.emit(agentId, event, p); return {}; }
- const drain = this.hive.drainForStop(agentId);
- if (drain.block) {
- // The agent is NOT idle — we're forcing it to keep working to process
- // its inbox. Tell the renderer that (blocked: true) so it doesn't flash
- // 'idle' on a Stop that never actually stops. Without this, an agent
- // re-engaged by a queued/dispatched message reads as idle while working.
- this.emit(agentId, event, p, true);
- return { decision: 'block', reason: drain.reason };
- }
- // A genuine stop with nothing queued → idle. Surface it as a desktop toast.
+ // Never turn unread hive mail into a forced continuation at Stop. That old
+ // path bypassed terminal-draft/HITL safety and could spend credits while a
+ // user was answering a question. Inbox files remain durable; the renderer
+ // wakes the agent later through its guarded idle-only delivery path.
this.notify(agentId ?? 'Agent', 'finished — idle');
this.emit(agentId, event, p);
return {};
diff --git a/src/main/index.ts b/src/main/index.ts
index 3c22d9b3..20135bd4 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -458,15 +458,19 @@ function ensureDefaultMissions(): void {
heartbeatSeeded: true
});
}
- // 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.
+ // Repair the built-in mission on every main-process boot. An older long-lived
+ // build persisted autoCompact:false without exposing any UI to turn it back on;
+ // a one-shot marker alone left that broken value durable across upgrades.
+ // Other missions and the standup's enabled/deleted state remain user-controlled.
const cfg3 = readConfig();
- if (!cfg3.autoCompactEnabledMigrated) {
- const missions = cfg3.missions ?? [];
+ const missions = cfg3.missions ?? [];
+ const repaired = enableOpsStandupAutoCompact(missions);
+ const needsRepair = repaired.some((mission, index) =>
+ mission.autoCompact !== missions[index]?.autoCompact
+ );
+ if (needsRepair || !cfg3.autoCompactEnabledMigrated) {
writeConfig({
- missions: enableOpsStandupAutoCompact(missions),
+ missions: repaired,
autoCompactEnabledMigrated: true
});
}
@@ -1530,7 +1534,14 @@ function findCodexHomeForSession(sessionId: string, siblingsRoot: string): strin
}
}
-ipcMain.handle('pty:spawn', async (evt, opts: SpawnOptions & { hive?: AgentMeta; isolate?: boolean; resume?: boolean; resumeSessionId?: string; provider?: AgentProvider }) => {
+ipcMain.handle('pty:spawn', async (evt, opts: SpawnOptions & {
+ hive?: AgentMeta;
+ isolate?: boolean;
+ resume?: boolean;
+ requireResume?: boolean;
+ resumeSessionId?: string;
+ provider?: AgentProvider;
+}) => {
if (!opts || typeof opts.id !== 'string' || typeof opts.cwd !== 'string' || typeof opts.command !== 'string') {
return { ok: false, error: 'invalid SpawnOptions' };
}
@@ -1706,6 +1717,13 @@ ipcMain.handle('pty:spawn', async (evt, opts: SpawnOptions & { hive?: AgentMeta;
}
}
}
+ if (opts.requireResume === true && !didResume) {
+ return {
+ ok: false,
+ error: 'Existing session could not be resumed; no replacement process was started.',
+ ...(resumeNotFound ? { resumeNotFound: true } : {})
+ };
+ }
// Remember which agent owns this PTY so closing the tab can archive it. A
// live terminal means active — ensureAgent above already cleared `archived`.
if (opts.hive?.id) ptyToAgent.set(opts.id, opts.hive.id);
@@ -2195,6 +2213,15 @@ ipcMain.handle('control:pause', (_evt, agentId: unknown, on: unknown) => {
control.pause(agentId, on === true);
return control.snapshot(agentId);
});
+ipcMain.handle('control:autoDelivery', (_evt, agentId: unknown, paused: unknown) => {
+ if (typeof agentId !== 'string') return null;
+ const on = paused === true;
+ control.pauseAutoDelivery(agentId, on);
+ const current = new Set(readConfig().autoDeliveryPausedAgents ?? []);
+ if (on) current.add(agentId); else current.delete(agentId);
+ writeConfig({ autoDeliveryPausedAgents: Array.from(current).sort() });
+ return control.snapshot(agentId);
+});
ipcMain.handle('control:resume', (_evt, agentId: unknown) => {
if (typeof agentId !== 'string') return null;
control.resume(agentId);
@@ -2397,6 +2424,7 @@ ipcMain.handle('freeflow:transcribe', async (_evt, arg: unknown) => {
function bootstrapHiveServices(): void {
if (!hive.enabled()) return;
hive.ensureHive();
+ control.replaceAutoDeliveryPauses(readConfig().autoDeliveryPausedAgents ?? []);
archiveOrphanedAgents(); // #57/#58: archive stale archived:false entries with no live PTY
hive.startRouter();
ensureDefaultMissions(); // one-time: seed the built-in hourly ops standup
diff --git a/src/preload/index.ts b/src/preload/index.ts
index d66d9305..7fe04945 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -36,7 +36,12 @@ export interface HiveRegistry {
godId: string | null;
/** `archived` agents have had their terminal closed — retained + flagged, not
* deleted; only live-PTY agents are 'active'. */
- agents: Record<string, HiveAgentMeta & { status: string; lastSeen: number; archived?: boolean }>;
+ agents: Record<string, HiveAgentMeta & {
+ status: string;
+ lastSeen: number;
+ archived?: boolean;
+ sessionId?: string;
+ }>;
}
/** One question→answer exchange with the human, recorded ON the task card. */
@@ -114,6 +119,8 @@ export interface SpawnPtyOptions {
* Claude the main process looks up the session id from the hive registry and
* seeds its transcript into the cwd's project dir (#1 — restore on restart). */
resume?: boolean;
+ /** Fail before spawning when a requested resume cannot be attached. */
+ requireResume?: boolean;
/** Explicit Claude session id to resume (#2 — Add Agent "resume session"). The
* main process seeds that session's `.jsonl` into the target cwd's project dir
* (copying it from wherever it lives) and launches `claude --resume <id>`. */
@@ -181,6 +188,7 @@ export interface HarnessConfig {
costCapUsd?: number;
costCapTokens?: number;
agentTokenCaps?: Record<string, number>;
+ autoDeliveryPausedAgents?: string[];
maxTurns?: number;
circuitBreaker?: CircuitBreakerConfig;
/** Enterprise Knowledge Graph (multimodal context for agents). Default OFF. */
@@ -311,6 +319,7 @@ export interface ClosingTimeEvent {
export interface AgentControlSnapshot {
paused: boolean;
halted: boolean;
+ autoDeliveryPaused: boolean;
gatedTools: string[];
pendingSteers: number;
}
@@ -631,6 +640,9 @@ const api = {
/** Pause/unpause an agent — paused → its tool calls are denied at PreToolUse. */
controlPause: (agentId: string, on: boolean): Promise<AgentControlSnapshot | null> =>
ipcRenderer.invoke('control:pause', agentId, on),
+ /** Pause/resume automatic inbox and queued-message delivery for one agent. */
+ controlAutoDelivery: (agentId: string, paused: boolean): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:autoDelivery', agentId, paused),
/** Clear pause + halt so the agent can run again. */
controlResume: (agentId: string): Promise<AgentControlSnapshot | null> =>
ipcRenderer.invoke('control:resume', agentId),
diff --git a/src/renderer/src/components/AgentControlStrip.tsx b/src/renderer/src/components/AgentControlStrip.tsx
index 972150dc..d4e14716 100644
--- a/src/renderer/src/components/AgentControlStrip.tsx
+++ b/src/renderer/src/components/AgentControlStrip.tsx
@@ -5,7 +5,13 @@ import { PixelButton } from './PixelButton';
* boundary), graceful halt (clean stop), and mid-run steering (inject context
* without typing into the TUI). All ride Claude Code's hook-return protocol; no
* PTY keystrokes. A thin strip under the agent header. */
-interface Snapshot { paused: boolean; halted: boolean; gatedTools: string[]; pendingSteers: number }
+interface Snapshot {
+ paused: boolean;
+ halted: boolean;
+ autoDeliveryPaused: boolean;
+ gatedTools: string[];
+ pendingSteers: number;
+}
export function AgentControlStrip({ agentId }: { agentId: string }) {
const [snap, setSnap] = useState<Snapshot | null>(null);
@@ -35,6 +41,12 @@ export function AgentControlStrip({ agentId }: { agentId: string }) {
if (s) setSnap(s);
flash('halt requested — stops cleanly at next hook');
};
+ const toggleAutoDelivery = async () => {
+ const paused = !(snap?.autoDeliveryPaused ?? false);
+ const s = await window.cth.controlAutoDelivery(agentId, paused);
+ if (s) setSnap(s);
+ flash(paused ? 'auto-delivery paused — messages stay queued' : 'auto-delivery resumed');
+ };
const sendSteer = async () => {
const t = steer.trim();
if (!t) return;
@@ -56,6 +68,13 @@ export function AgentControlStrip({ agentId }: { agentId: string }) {
{snap?.paused ? 'resume' : 'pause'}
</PixelButton>
<PixelButton variant="destructive" size="sm" onClick={halt}>halt</PixelButton>
+ <PixelButton
+ variant={snap?.autoDeliveryPaused ? 'primary' : 'secondary'}
+ size="sm"
+ onClick={toggleAutoDelivery}
+ >
+ {snap?.autoDeliveryPaused ? 'delivery paused' : 'auto-delivery on'}
+ </PixelButton>
{snap?.halted && <span style={{ fontSize: 11, color: 'var(--cth-coral)' }}>halting…</span>}
{!!snap?.pendingSteers && <span style={{ fontSize: 11, color: 'var(--cth-ink-500)' }}>{snap.pendingSteers} steer queued</span>}
</div>
diff --git a/src/renderer/src/components/AgentStrip.tsx b/src/renderer/src/components/AgentStrip.tsx
index 42d298fd..fe0ac713 100644
--- a/src/renderer/src/components/AgentStrip.tsx
+++ b/src/renderer/src/components/AgentStrip.tsx
@@ -20,12 +20,14 @@ export function AgentStrip({ config }: AgentStripProps) {
const setAddAgentOpen = useStore(s => s.setAddAgentOpen);
const openTaskDetail = useStore(s => s.openTaskDetail);
const reorderAgents = useStore(s => s.reorderAgents);
+ const setAgentNote = useStore(s => s.setAgentNote);
const [restoring, setRestoring] = useState(false);
const [restoreNote, setRestoreNote] = useState<string | null>(null);
// Drag-to-reorder the roster: dragId = the card being dragged, overId = the card
// currently hovered as a drop target (drives the insertion-line cue).
const [dragId, setDragId] = useState<string | null>(null);
const [overId, setOverId] = useState<string | null>(null);
+ const [noteHoverId, setNoteHoverId] = useState<string | null>(null);
// Each worker's actively-DOING ledger tasks, polled from hive/tasks.json —
// rendered as a sticky note on the avatar card (click → task detail).
const [doingByAgent, setDoingByAgent] = useState<Record<string, string[]>>({});
@@ -264,7 +266,10 @@ export function AgentStrip({ config }: AgentStripProps) {
setOverId(null);
}}
onDragEnd={() => { setDragId(null); setOverId(null); }}
+ onMouseEnter={() => setNoteHoverId(a.id)}
+ onMouseLeave={() => setNoteHoverId((id) => id === a.id ? null : id)}
style={{
+ position: 'relative',
flexShrink: 0,
cursor: 'grab',
opacity: dragId === a.id ? 0.4 : 1,
@@ -295,6 +300,38 @@ export function AgentStrip({ config }: AgentStripProps) {
if (first) openTaskDetail(first);
}}
/>
+ {noteHoverId === a.id && !dragId && (
+ <div
+ onClick={(e) => e.stopPropagation()}
+ onMouseDown={(e) => e.stopPropagation()}
+ style={{
+ position: 'absolute', left: 60, right: 7, bottom: 7, height: 25, zIndex: 5,
+ display: 'flex', alignItems: 'center', gap: 4, padding: '3px 4px',
+ background: 'var(--cth-paper-100)',
+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-900), 2px 2px 0 rgba(26,19,32,0.2)',
+ boxSizing: 'border-box'
+ }}
+ >
+ <span style={{
+ flexShrink: 0, fontFamily: 'var(--cth-font-mono)', fontSize: 9,
+ lineHeight: '18px', color: 'var(--cth-ink-700)'
+ }}>NOTE</span>
+ <input
+ draggable={false}
+ value={a.note ?? ''}
+ onChange={(e) => setAgentNote(a.id, e.target.value)}
+ placeholder="private note…"
+ aria-label={`Note for ${a.name}`}
+ style={{
+ flex: 1, minWidth: 0, height: 17, padding: '0 4px',
+ border: 'none', outline: 'none', boxSizing: 'border-box',
+ background: 'var(--cth-cream-100)',
+ fontFamily: 'var(--cth-font-mono)', fontSize: 10,
+ lineHeight: '17px', color: 'var(--cth-ink-900)'
+ }}
+ />
+ </div>
+ )}
</div>
))}
{restorableAgents.length > 0 && (
diff --git a/src/renderer/src/components/CommandCenterPanel.tsx b/src/renderer/src/components/CommandCenterPanel.tsx
index 229e1a5e..f03a931a 100644
--- a/src/renderer/src/components/CommandCenterPanel.tsx
+++ b/src/renderer/src/components/CommandCenterPanel.tsx
@@ -216,6 +216,7 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
// Per-agent token limit (overrides the floor budget for that agent), keyed by id.
const [agentTokenCaps, setAgentTokenCaps] = useState<Record<string, number>>({});
const [restarting, setRestarting] = useState<string | null>(null);
+ const [restartErrors, setRestartErrors] = useState<Record<string, string>>({});
const [dispatchTo, setDispatchTo] = useState<string>(''); // '' = Michael decides
const [dispatchText, setDispatchText] = useState('');
const [dispatchMsg, setDispatchMsg] = useState<string | null>(null);
@@ -253,20 +254,34 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
) => {
if (!a.ptyId) return;
setRestarting(a.id);
+ setRestartErrors((errors) => ({ ...errors, [a.id]: '' }));
try {
const cfg = await window.cth.getConfig();
- await window.cth.killPty(a.ptyId);
+ const previousProvider = inferAgentProvider(a.command, a.provider);
+ const provider = opts.provider ?? previousProvider;
+ const resume = opts.resume === true && provider === previousProvider;
+ if (opts.resume && !resume) {
+ throw new Error('Cannot resume a session through a different provider.');
+ }
+ let resumeSessionId: string | undefined;
+ if (resume) {
+ const registry = await window.cth.hiveRegistry();
+ resumeSessionId = registry.agents[a.id]?.sessionId;
+ if (!resumeSessionId) {
+ throw new Error('No recorded session ID; current process was left running.');
+ }
+ if (provider === 'claude' && !(await window.cth.resolveSessionCwd(resumeSessionId))) {
+ throw new Error('Session transcript not found; current process was left running.');
+ }
+ }
+ const killed = await window.cth.killPty(a.ptyId);
+ if (!killed.ok) throw new Error(killed.error ?? 'Could not stop the current process.');
// Soft-reset the pooled terminal in place rather than disposing it: the
// same ptyId is reused, so its data subscription, opened xterm and keyboard
// wiring all survive the restart. (Disposing dropped the live terminal while
// the view — keyed on the unchanged ptyId — never re-attached a replacement,
// leaving a dead pane that swallowed every keystroke.)
- resetTerminal(a.ptyId);
- // 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;
+ resetTerminal(a.ptyId, { preserveScrollback: resume });
const command = buildSpawnCommand(cfg, model, provider);
const [exe, ...args] = tokenizeCommand(command.trim());
const hive = a.isGod
@@ -289,8 +304,14 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
cols,
rows,
hive,
- resume
+ resume,
+ resumeSessionId,
+ requireResume: resume
});
+ if (!res.ok) throw new Error(res.error ?? 'Restart failed.');
+ if (resume && res.resumed !== true) {
+ throw new Error('Resume was refused; no replacement session was accepted.');
+ }
if (res.ok) {
// On a pure resume the model is unchanged — don't overwrite it.
const patch = resume
@@ -304,7 +325,12 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
};
updateAgent(a.id, patch);
}
- } catch { /* noop */ } finally {
+ } catch (error) {
+ setRestartErrors((errors) => ({
+ ...errors,
+ [a.id]: error instanceof Error ? error.message : String(error)
+ }));
+ } finally {
setRestarting(null);
}
};
@@ -571,6 +597,11 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
</PixelButton>
</>}
</div>
+ {restartErrors[a.id] && (
+ <div style={{ fontSize: 11, color: 'var(--cth-coral)' }}>
+ {restartErrors[a.id]}
+ </div>
+ )}
</div>
);
})}
diff --git a/src/renderer/src/components/terminalAutomation.ts b/src/renderer/src/components/terminalAutomation.ts
index 979141c2..620d3123 100644
--- a/src/renderer/src/components/terminalAutomation.ts
+++ b/src/renderer/src/components/terminalAutomation.ts
@@ -28,3 +28,21 @@ export function opensInteractiveTerminalUi(input: string): boolean {
export function shouldFollowTerminalOutput(viewportY: number, baseY: number): boolean {
return baseY - viewportY <= 1;
}
+
+export interface TerminalAutomationState {
+ exited: boolean;
+ pickerOpen: boolean;
+ inputDirty: boolean;
+ settleUntil: number;
+}
+
+/** Automatic writes may own the prompt only when no user draft or picker does. */
+export function canAutomateTerminal(
+ state: TerminalAutomationState,
+ now = Date.now()
+): boolean {
+ return !state.exited
+ && !state.pickerOpen
+ && !state.inputDirty
+ && now >= state.settleUntil;
+}
diff --git a/src/renderer/src/components/terminalPool.ts b/src/renderer/src/components/terminalPool.ts
index 6c4d532e..09900884 100644
--- a/src/renderer/src/components/terminalPool.ts
+++ b/src/renderer/src/components/terminalPool.ts
@@ -24,6 +24,7 @@ import {
type TerminalRecoveryState
} from './terminalRecovery';
import {
+ canAutomateTerminal,
opensInteractiveTerminalUi,
shouldFollowTerminalOutput
} from './terminalAutomation';
@@ -49,6 +50,8 @@ export interface TerminalEntry {
/** A user-opened slash-command picker (for example Codex `/model`) owns the
* input line. Queue automation waits until the picker closes. */
automationBlocked: boolean;
+ /** True while the user has unsubmitted text in the live TUI prompt. */
+ inputDirty: boolean;
automationSettleUntil: number;
webgl?: WebglAddon;
}
@@ -108,6 +111,7 @@ export function acquireTerminal(ptyId: string, theme?: ThemeMap, fontSize = 14):
recovery: createTerminalRecoveryState(),
needsRendererRepaint: false,
automationBlocked: false,
+ inputDirty: false,
automationSettleUntil: 0
};
@@ -180,8 +184,11 @@ export function acquireTerminal(ptyId: string, theme?: ThemeMap, fontSize = 14):
entry.automationSettleUntil = Date.now() + 500;
lineBuf = '';
}
- for (let i = 0; i < data.length; i++) {
- const ch = data[i];
+ // Bracketed paste is still user-owned draft text; remove only its wrapper so
+ // pasted content marks the prompt dirty instead of looking automation-safe.
+ const input = data.replace(/\x1b\[200~/g, '').replace(/\x1b\[201~/g, '');
+ for (let i = 0; i < input.length; i++) {
+ const ch = input[i];
if (ch === '\r' || ch === '\n') {
const t = lineBuf.trim();
lineBuf = '';
@@ -201,6 +208,7 @@ export function acquireTerminal(ptyId: string, theme?: ThemeMap, fontSize = 14):
lineBuf += ch;
}
}
+ entry.inputDirty = lineBuf.length > 0;
});
pool.set(ptyId, entry);
@@ -212,7 +220,12 @@ export function acquireTerminal(ptyId: string, theme?: ThemeMap, fontSize = 14):
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;
+ return canAutomateTerminal({
+ exited: entry.exited,
+ pickerOpen: entry.automationBlocked,
+ inputDirty: entry.inputDirty,
+ settleUntil: entry.automationSettleUntil
+ }, now);
}
/** Re-parent a pty's terminal into `container`, opening xterm on first attach. */
@@ -340,15 +353,24 @@ export function reflowTerminal(ptyId: string): void {
* replacement terminal. Disposing therefore left a dead, detached pane that
* swallowed every keystroke. Resetting in place avoids that entirely.
*/
-export function resetTerminal(ptyId: string): void {
+export function resetTerminal(
+ ptyId: string,
+ opts: { preserveScrollback?: boolean } = {}
+): void {
const entry = pool.get(ptyId);
if (!entry) return;
// Re-arm input — a prior exit (or the kill that precedes the respawn) may have
// latched `exited`, which otherwise makes onData drop keystrokes silently.
entry.exited = false;
- // Wipe the old frame + the "process exited" line so the restarted TUI paints
- // onto a clean grid instead of overlapping stale content.
- try { entry.term.reset(); } catch { /* not yet open */ }
+ entry.inputDirty = false;
+ try {
+ if (opts.preserveScrollback) {
+ entry.term.writeln('\r\n\x1b[2m─ resuming existing session ─\x1b[0m');
+ } else {
+ // Fresh sessions need a clean grid; resume keeps the existing scrollback.
+ entry.term.reset();
+ }
+ } catch { /* not yet open */ }
}
/** Tear down a pty's terminal (call when the agent/pty is gone for good). */
diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.ts
index 838fa84d..e1d6aa8a 100644
--- a/src/renderer/src/hooks/useHive.ts
+++ b/src/renderer/src/hooks/useHive.ts
@@ -460,13 +460,18 @@ export function useHive(config: HarnessConfig | null): void {
const iv = setInterval(async () => {
const now = Date.now();
const agents = useStore.getState().agents.filter(
- (a) => a.ptyId && (a.status === 'idle' || a.status === 'waiting')
+ // Never type into an explicit human/permission wait. A worker waiting on
+ // the user must stay parked until the user answers or resumes delivery.
+ (a) => a.ptyId && a.status === 'idle'
// Don't type into an agent still running its boot sequence — the nudge
// would collide with /remote-control + the orientation prompt.
&& (bootGraceUntil.current[a.id] ?? 0) < now
);
for (const a of agents) {
try {
+ const control = await window.cth.controlSnapshot(a.id);
+ if (control?.autoDeliveryPaused) continue;
+ if (!isTerminalAutomationSafe(a.ptyId!, now)) continue;
const inbox = await window.cth.hiveInbox(a.id);
// Dedup by the newest message id, not the count — a count can oscillate
// as messages drain and re-arrive, which would re-nudge for the same set.
@@ -474,12 +479,12 @@ export function useHive(config: HarnessConfig | null): void {
? inbox.map((m) => m.id).sort().slice(-1)[0]
: '';
if (newest && nudged.current[a.id] !== newest) {
- 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.',
inferAgentProvider(a.command, a.provider)
);
+ nudged.current[a.id] = newest;
} else if (!newest) {
nudged.current[a.id] = '';
}
@@ -511,6 +516,8 @@ export function useHive(config: HarnessConfig | null): void {
const next = messageQueues[srcId]?.[0];
if (!next || !target?.ptyId || target.status !== 'idle') return { sent: false };
const now = Date.now();
+ const control = await window.cth.controlSnapshot(target.id);
+ if (control?.autoDeliveryPaused) return { sent: false };
// Hold queued messages until the target finishes its boot sequence.
if ((bootGraceUntil.current[target.id] ?? 0) >= now) return { sent: false };
if (!isTerminalAutomationSafe(target.ptyId, now)) return { sent: false };
diff --git a/src/renderer/src/store/config.ts b/src/renderer/src/store/config.ts
index e3ec5690..a94f7c68 100644
--- a/src/renderer/src/store/config.ts
+++ b/src/renderer/src/store/config.ts
@@ -74,6 +74,7 @@ export interface HarnessConfig {
/** Per-agent total-token ceiling, keyed by agent id. Overrides the floor budget
* for that agent's meter and trips the breaker for it alone. */
agentTokenCaps?: Record<string, number>;
+ autoDeliveryPausedAgents?: string[];
maxTurns?: number;
circuitBreaker?: CircuitBreakerConfig;
/** Enterprise Knowledge Graph (multimodal context for agents). Default OFF. */
diff --git a/src/renderer/src/store/store.ts b/src/renderer/src/store/store.ts
index 418287ae..e081b81c 100644
--- a/src/renderer/src/store/store.ts
+++ b/src/renderer/src/store/store.ts
@@ -37,6 +37,8 @@ export interface Agent {
tmuxTarget: string;
cwd: string;
goal?: string;
+ /** User-authored private note shown and edited from the roster-card hover. */
+ note?: string;
status: StatusKind;
action: string;
progress: number;
@@ -143,6 +145,7 @@ interface State {
setGodStatus: (status: GodStatus) => void;
select: (id: string) => void;
updateAgent: (id: string, patch: Partial<Agent>) => void;
+ setAgentNote: (id: string, note: string) => void;
pushFeed: (id: string, line: string) => void;
addAgent: (agent: Agent) => void;
removeAgent: (id: string) => void;
@@ -395,6 +398,12 @@ export const useStore = create<State>((set) => ({
select: (id) => set((s) => { persistAgents(s.agents, id); return { selectedId: id, ccTabRequest: null }; }),
updateAgent: (id, patch) =>
set((s) => ({ agents: s.agents.map(a => a.id === id ? { ...a, ...patch } : a) })),
+ setAgentNote: (id, note) =>
+ set((s) => {
+ const agents = s.agents.map((a) => a.id === id ? { ...a, note } : a);
+ persistAgents(agents, s.selectedId);
+ return { agents };
+ }),
pushFeed: (id, line) =>
set((s) => ({ feeds: { ...s.feeds, [id]: [...(s.feeds[id] ?? []), line] } })),
addAgent: (agent) =>
diff --git a/src/shared/agentProvider.ts b/src/shared/agentProvider.ts
index 56baa231..bdfe6231 100644
--- a/src/shared/agentProvider.ts
+++ b/src/shared/agentProvider.ts
@@ -42,10 +42,10 @@ export interface AgentProviderPreset {
* env only. Gates the Claude-specific spawn injection in hive.ensureAgent.
* NOTE: this gates the *Claude-only* flag path specifically — it is NOT the
* same as "participates in the hive". A non-hiveAware provider can still be a
- * full hive citizen (live status + Stop→inbox-drain) via a `hookBridge`. */
+ * full hive citizen (live status + guarded idle delivery) via a `hookBridge`. */
hiveAware: boolean;
/** Which config-file lifecycle-hook bridge a NON-hiveAware provider uses to get
- * the same live status + Stop→inbox-drain that Claude gets from `--settings`:
+ * the same live status that Claude gets from `--settings`:
* - 'agy' → installAgyHooks() writes ~/.gemini/.../hooks.json (translating
* shim, because agy's stdin/stdout shape differs from Claude's).
* - 'codex' → installCodexHooks() writes a per-agent CODEX_HOME/hooks.json and
@@ -56,9 +56,9 @@ export interface AgentProviderPreset {
* single switch hive.ensureAgent dispatches on to wire the bridge. */
hookBridge?: 'agy' | 'codex';
/** Whether the router may DELIVER inbox mail to this provider (vs bouncing it
- * to the god). Requires a way for the agent to actually drain its inbox: Claude
- * via its Stop hook, and Antigravity/Codex via their `hookBridge` Stop→drain.
- * A provider with no inbox-drain path (custom) can't, so its mail still bounces.
+ * to the god). Requires lifecycle status so the renderer can deliver only at a
+ * safe idle prompt: Claude natively, Antigravity/Codex via their hookBridge.
+ * A hookless custom provider cannot expose safe-idle state, so mail bounces.
* Distinct from hiveAware: agy/codex are NOT hiveAware (no Claude injection)
* but CAN receive inbox via their bridge. */
canReceiveInbox: boolean;
@@ -203,9 +203,8 @@ export function isHiveAwareProvider(provider: AgentProvider | undefined): boolea
}
/** Whether the router may deliver inbox mail to this provider (else bounce to
- * the god). True for any provider that can actually drain its inbox — Claude
- * (Stop hook), Antigravity and Codex (their `hookBridge` Stop→drain); false for
- * hookless custom commands. */
+ * the god). True when lifecycle status supports guarded idle delivery; false
+ * for hookless custom commands. */
export function canReceiveInbox(provider: AgentProvider | undefined): boolean {
return providerPreset(provider ?? 'claude').canReceiveInbox;
}
diff --git a/test/control.test.cjs b/test/control.test.cjs
new file mode 100644
index 00000000..d9758ddf
--- /dev/null
+++ b/test/control.test.cjs
@@ -0,0 +1,32 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const loadTs = require('./load-ts.cjs');
+
+const { ControlRegistry } = loadTs('src/main/control.ts');
+
+test('auto-delivery pause is independent from tool pause and halt', () => {
+ const control = new ControlRegistry();
+ control.pauseAutoDelivery('dev1', true);
+
+ assert.equal(control.isAutoDeliveryPaused('dev1'), true);
+ assert.equal(control.snapshot('dev1').autoDeliveryPaused, true);
+ assert.equal(control.snapshot('dev1').paused, false);
+ assert.equal(control.snapshot('dev1').halted, false);
+
+ control.resume('dev1');
+ assert.equal(control.isAutoDeliveryPaused('dev1'), true, 'normal resume must not spend queued work');
+ control.pauseAutoDelivery('dev1', false);
+ assert.equal(control.isAutoDeliveryPaused('dev1'), false);
+});
+
+test('persisted delivery pauses replace stale in-memory state', () => {
+ const control = new ControlRegistry();
+ control.pauseAutoDelivery('old', true);
+ control.replaceAutoDeliveryPauses(['dev2', 'dev3']);
+
+ assert.equal(control.isAutoDeliveryPaused('old'), false);
+ assert.equal(control.isAutoDeliveryPaused('dev2'), true);
+ assert.equal(control.isAutoDeliveryPaused('dev3'), true);
+});
diff --git a/test/terminal-automation.test.cjs b/test/terminal-automation.test.cjs
index ab7079e7..8018f47b 100644
--- a/test/terminal-automation.test.cjs
+++ b/test/terminal-automation.test.cjs
@@ -5,6 +5,7 @@ const assert = require('node:assert/strict');
const loadTs = require('./load-ts.cjs');
const {
+ canAutomateTerminal,
opensInteractiveTerminalUi,
shouldFollowTerminalOutput
} = loadTs('src/renderer/src/components/terminalAutomation.ts');
@@ -17,6 +18,15 @@ test('interactive provider commands pause queue automation', () => {
assert.equal(opensInteractiveTerminalUi('implement this'), false);
});
+test('terminal automation waits for user drafts and interactive states', () => {
+ const ready = { exited: false, pickerOpen: false, inputDirty: false, settleUntil: 0 };
+ assert.equal(canAutomateTerminal(ready, 100), true);
+ assert.equal(canAutomateTerminal({ ...ready, inputDirty: true }, 100), false);
+ assert.equal(canAutomateTerminal({ ...ready, pickerOpen: true }, 100), false);
+ assert.equal(canAutomateTerminal({ ...ready, exited: true }, 100), false);
+ assert.equal(canAutomateTerminal({ ...ready, settleUntil: 101 }, 100), false);
+});
+
test('terminal output follows only when already at the bottom', () => {
assert.equal(shouldFollowTerminalOutput(100, 100), true);
assert.equal(shouldFollowTerminalOutput(99, 100), true);