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(7C.1-3): HITL gate + mid-run steer + graceful stop via hook returns

Chaitanya Giri4a652d23ff81
diff --git a/src/main/control.ts b/src/main/control.ts
new file mode 100644
index 00000000..7864df4e
--- /dev/null
+++ b/src/main/control.ts
@@ -0,0 +1,84 @@
+/**
+ * ControlRegistry — operator control over running agents (#7C.1–7C.3).
+ *
+ * Holds per-agent control state that the HookServer reads when deciding what to
+ * return from a hook. This is how the floor exerts control WITHOUT typing into
+ * the PTY: the decision rides Claude Code's own hook-return protocol.
+ *
+ * - pause / gateTool (#7C.1) → PreToolUse returns permissionDecision:'deny'
+ * (race-free, immediate — no renderer round-trip, so it can't hit the shim
+ * timeout). Slow human APPROVAL deliberately rides Claude's native prompt
+ * instead, per the spec's latency mitigation.
+ * - steer (#7C.2) → the next UserPromptSubmit/PostToolUse returns
+ * additionalContext, injecting guidance into the agent's context once.
+ * - halt (#7C.3) → the next hook boundary returns { continue:false } so the
+ * agent stops CLEANLY (vs killing the PTY). Overrides the inbox-drain.
+ *
+ * Runs in the Electron main process; no electron import (unit-testable).
+ */
+
+export interface AgentControlSnapshot {
+ paused: boolean;
+ halted: boolean;
+ gatedTools: string[];
+ pendingSteers: number;
+}
+
+interface AgentControl {
+ paused: boolean;
+ halted: boolean;
+ gatedTools: Set<string>;
+ steerQueue: string[];
+}
+
+export class ControlRegistry {
+ private readonly map = new Map<string, AgentControl>();
+
+ 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); }
+ return c;
+ }
+
+ // ─── Operator actions (wired to IPC) ───────────────────────────────────────
+
+ pause(id: string, on: boolean): void { this.ensure(id).paused = on; }
+ gateTool(id: string, tool: string, on: boolean): void {
+ const c = this.ensure(id);
+ if (on) c.gatedTools.add(tool); else c.gatedTools.delete(tool);
+ }
+ steer(id: string, text: string): void {
+ const t = text.trim();
+ if (t) this.ensure(id).steerQueue.push(t.slice(0, 10000)); // hook additionalContext cap
+ }
+ /** Request a graceful stop at the next hook boundary. */
+ halt(id: string): void { this.ensure(id).halted = true; }
+ /** Clear pause + halt (lets a paused/halted agent run again). Keeps gates. */
+ resume(id: string): void { const c = this.ensure(id); c.paused = false; c.halted = false; }
+
+ // ─── Reads (used by HookServer) ────────────────────────────────────────────
+
+ shouldHalt(id: string): boolean { return this.map.get(id)?.halted ?? false; }
+
+ /** Whether a tool call should be denied (paused agent, or this tool gated). */
+ toolDecision(id: string, tool: string): { deny: boolean; reason?: string } {
+ const c = this.map.get(id);
+ if (!c) return { deny: false };
+ if (c.paused) return { deny: true, reason: 'Paused by operator — resume from the floor to continue.' };
+ if (tool && c.gatedTools.has(tool)) return { deny: true, reason: `Tool ${tool} is gated by the operator.` };
+ return { deny: false };
+ }
+
+ /** Dequeue one pending steer note for delivery, or undefined. */
+ takeSteer(id: string): string | undefined { return this.map.get(id)?.steerQueue.shift(); }
+
+ snapshot(id: string): AgentControlSnapshot {
+ const c = this.map.get(id);
+ return {
+ paused: c?.paused ?? false,
+ halted: c?.halted ?? false,
+ gatedTools: c ? Array.from(c.gatedTools) : [],
+ pendingSteers: c?.steerQueue.length ?? 0
+ };
+ }
+}
diff --git a/src/main/hooks.ts b/src/main/hooks.ts
index 966dd0e0..851306ef 100644
--- a/src/main/hooks.ts
+++ b/src/main/hooks.ts
@@ -16,6 +16,7 @@ import { existsSync, rmSync } from 'node:fs';
import { Notification, type WebContents } from 'electron';
import type { HiveManager } from './hive';
import type { HarnessConfig } from './config';
+import type { ControlRegistry } from './control';
interface HookPayload {
hook_event_name?: string;
@@ -39,7 +40,9 @@ export class HookServer {
constructor(
private hive: HiveManager,
private getWebContents: () => WebContents | null,
- private getConfig: () => HarnessConfig
+ private getConfig: () => HarnessConfig,
+ /** #7C — operator control state. Optional so tests can omit it. */
+ private control?: ControlRegistry
) {}
start(): void {
@@ -77,6 +80,14 @@ export class HookServer {
const agentId = p.agent_id ?? undefined;
const event = p.hook_event_name ?? 'Unknown';
+ // 7C.3 — a graceful operator HALT overrides everything (incl. the inbox
+ // drain below): stop the agent CLEANLY at this hook boundary rather than
+ // killing the PTY. session_id is in the payload for a later --resume.
+ if (agentId && this.control?.shouldHalt(agentId)) {
+ this.emit(agentId, event, p);
+ return { continue: false, stopReason: 'Halted by the operator from the floor.' };
+ }
+
if ((event === 'Stop' || event === 'SubagentStop') && agentId) {
// Loop guard: a previous Stop hook already blocked this turn → let it stop.
if (p.stop_hook_active) { this.emit(agentId, event, p); return {}; }
@@ -95,6 +106,35 @@ export class HookServer {
return {};
}
+ // 7C.1 — HITL gate: deny a tool call at the PreToolUse boundary when the
+ // agent is paused or this tool is gated. Race-free (immediate return, no
+ // renderer round-trip → can't hit the shim timeout). Slow human APPROVAL is
+ // deliberately left to Claude's native permission prompt.
+ if (event === 'PreToolUse' && agentId && this.control) {
+ const d = this.control.toolDecision(agentId, p.tool_name ?? '');
+ if (d.deny) {
+ this.emitControl(agentId, p.tool_name, d.reason);
+ this.emit(agentId, event, p);
+ return {
+ hookSpecificOutput: {
+ hookEventName: 'PreToolUse',
+ permissionDecision: 'deny',
+ permissionDecisionReason: d.reason ?? 'Denied by operator.'
+ }
+ };
+ }
+ }
+
+ // 7C.2 — mid-run steering: inject queued operator guidance as context on the
+ // next eligible hook (no fragile typing into the TUI). Delivered once.
+ if ((event === 'UserPromptSubmit' || event === 'PostToolUse') && agentId && this.control) {
+ const steer = this.control.takeSteer(agentId);
+ if (steer) {
+ this.emit(agentId, event, p);
+ return { hookSpecificOutput: { hookEventName: event, additionalContext: steer } };
+ }
+ }
+
// A Notification hook that means "the agent is blocked waiting for the user"
// (idle prompt) deserves a desktop toast too — distinct from a permission
// request, which surfaces natively in the agent's own Claude Code session
@@ -123,6 +163,12 @@ export class HookServer {
} catch { /* notifications unsupported on this platform — ignore */ }
}
+ /** Tell the renderer a tool call was gated/denied (#7C.1) so it can surface it
+ * (toast / control strip) — distinct from the avatar hook stream. */
+ private emitControl(agentId: string, tool: string | undefined, reason: string | undefined): void {
+ this.getWebContents()?.send('control:approvalRequest', { agentId, tool, reason });
+ }
+
private emit(agentId: string | undefined, event: string, p: HookPayload, blocked = false): void {
this.getWebContents()?.send('hive:hookEvent', {
agentId,
diff --git a/src/main/index.ts b/src/main/index.ts
index abe59d23..9dabaf36 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -21,6 +21,7 @@ import { listIssues, listCIRuns } from './github';
import { SlackWebhookServer } from './slack';
import { TelemetryCollector } from './telemetry';
import { CircuitBreaker } from './breaker';
+import { ControlRegistry } from './control';
const isDev = !!process.env.ELECTRON_RENDERER_URL;
const ptyManager = new PtyManager();
@@ -31,7 +32,10 @@ const hive = new HiveManager(
() => readConfig().harnessHome,
(channel, payload) => { try { liveWebContents()?.send(channel, payload); } catch { /* window tore down */ } }
);
-const hookServer = new HookServer(hive, () => liveWebContents(), () => readConfig());
+// #7C — operator control state (pause/gate/steer/halt), read by the HookServer
+// when deciding hook returns.
+const control = new ControlRegistry();
+const hookServer = new HookServer(hive, () => liveWebContents(), () => readConfig(), control);
// Stage 7A — the live observability tap. Receives Claude Code's first-party OTel
// over loopback OTLP/JSON and exposes the locked usage-provider seam. resolveCwd
// lets the transcript fallback find an agent's cwd from the hive registry.
@@ -580,6 +584,36 @@ ipcMain.handle('control:setBreakerState', (_evt, state: unknown) => {
return { ok: true };
});
+// ─── IPC: operator control over agents (#7C.1–7C.3) ─────────────────────────
+// All return the agent's fresh control snapshot so the UI can reflect state.
+ipcMain.handle('control:pause', (_evt, agentId: unknown, on: unknown) => {
+ if (typeof agentId !== 'string') return null;
+ control.pause(agentId, on === true);
+ return control.snapshot(agentId);
+});
+ipcMain.handle('control:resume', (_evt, agentId: unknown) => {
+ if (typeof agentId !== 'string') return null;
+ control.resume(agentId);
+ return control.snapshot(agentId);
+});
+ipcMain.handle('control:gateTool', (_evt, agentId: unknown, tool: unknown, on: unknown) => {
+ if (typeof agentId !== 'string' || typeof tool !== 'string') return null;
+ control.gateTool(agentId, tool, on === true);
+ return control.snapshot(agentId);
+});
+ipcMain.handle('control:steer', (_evt, agentId: unknown, text: unknown) => {
+ if (typeof agentId !== 'string' || typeof text !== 'string') return null;
+ control.steer(agentId, text);
+ return control.snapshot(agentId);
+});
+ipcMain.handle('control:halt', (_evt, agentId: unknown) => {
+ if (typeof agentId !== 'string') return null;
+ control.halt(agentId);
+ return control.snapshot(agentId);
+});
+ipcMain.handle('control:snapshot', (_evt, agentId: unknown) =>
+ typeof agentId === 'string' ? control.snapshot(agentId) : null);
+
// ─── IPC: scheduled missions (recurring auto-dispatch) ──────────────────────
ipcMain.handle('missions:list', () => readConfig().missions ?? []);
ipcMain.handle('missions:save', (_evt, missions) => {
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 9b10d7ab..37368e15 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -169,6 +169,14 @@ export interface ToolSpan {
error?: string;
}
+/** Per-agent operator-control state (#7C.1–7C.3). */
+export interface AgentControlSnapshot {
+ paused: boolean;
+ halted: boolean;
+ gatedTools: string[];
+ pendingSteers: number;
+}
+
/** Circuit-breaker state (Lane A #6 → this lane's avatars/meter). */
export interface BreakerState {
agentId: string;
@@ -363,6 +371,32 @@ const api = {
setBreakerState: (state: BreakerState): Promise<{ ok: boolean }> =>
ipcRenderer.invoke('control:setBreakerState', state),
+ // ─── Operator control over agents (#7C.1–7C.3) ──────────────────────────────
+ /** 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),
+ /** Clear pause + halt so the agent can run again. */
+ controlResume: (agentId: string): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:resume', agentId),
+ /** Gate/ungate a specific tool for an agent (denied at PreToolUse). */
+ controlGateTool: (agentId: string, tool: string, on: boolean): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:gateTool', agentId, tool, on),
+ /** Queue a steer note — injected as context on the agent's next hook (#7C.2). */
+ controlSteer: (agentId: string, text: string): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:steer', agentId, text),
+ /** Request a graceful stop at the next hook boundary (#7C.3). */
+ controlHalt: (agentId: string): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:halt', agentId),
+ /** Read an agent's current control snapshot. */
+ controlSnapshot: (agentId: string): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:snapshot', agentId),
+ /** Subscribe to gate/deny events (a tool was blocked); returns unsubscribe fn. */
+ onApprovalRequest: (cb: (e: { agentId: string; tool?: string; reason?: string }) => void): (() => void) => {
+ const listener = (_e: IpcRendererEvent, payload: { agentId: string; tool?: string; reason?: string }) => cb(payload);
+ ipcRenderer.on('control:approvalRequest', listener);
+ return () => ipcRenderer.removeListener('control:approvalRequest', listener);
+ },
+
// ─── Task kanban (hive/tasks.json) ───────────────────────────────────────
/** Overwrite the hive task ledger with the full task list and commit it. */
hiveWriteTasks: (tasks: HiveTask[]): Promise<{ ok: boolean; error?: string }> =>
diff --git a/src/renderer/src/components/AgentControlStrip.tsx b/src/renderer/src/components/AgentControlStrip.tsx
new file mode 100644
index 00000000..972150dc
--- /dev/null
+++ b/src/renderer/src/components/AgentControlStrip.tsx
@@ -0,0 +1,79 @@
+import { useEffect, useRef, useState } from 'react';
+import { PixelButton } from './PixelButton';
+
+/** Operator control for one agent (#7C.1–7C.3) — pause (deny tools at the next
+ * 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 }
+
+export function AgentControlStrip({ agentId }: { agentId: string }) {
+ const [snap, setSnap] = useState<Snapshot | null>(null);
+ const [steer, setSteer] = useState('');
+ const [note, setNote] = useState('');
+ const noteTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ useEffect(() => {
+ let alive = true;
+ window.cth.controlSnapshot(agentId).then((s) => { if (alive && s) setSnap(s); }).catch(() => { /* none */ });
+ return () => { alive = false; };
+ }, [agentId]);
+
+ const flash = (m: string) => {
+ setNote(m);
+ if (noteTimer.current) clearTimeout(noteTimer.current);
+ noteTimer.current = setTimeout(() => setNote(''), 1800);
+ };
+
+ const togglePause = async () => {
+ const s = snap?.paused ? await window.cth.controlResume(agentId) : await window.cth.controlPause(agentId, true);
+ if (s) setSnap(s);
+ flash(snap?.paused ? 'resumed' : 'paused — tool calls will be denied');
+ };
+ const halt = async () => {
+ const s = await window.cth.controlHalt(agentId);
+ if (s) setSnap(s);
+ flash('halt requested — stops cleanly at next hook');
+ };
+ const sendSteer = async () => {
+ const t = steer.trim();
+ if (!t) return;
+ const s = await window.cth.controlSteer(agentId, t);
+ if (s) setSnap(s);
+ setSteer('');
+ flash('steer queued — delivered on next turn');
+ };
+
+ return (
+ <div style={{
+ display: 'flex', flexDirection: 'column', gap: 6,
+ padding: '6px 8px', background: 'var(--cth-paper-100)',
+ borderBottom: '1px solid var(--cth-ink-300)', flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
+ <span style={{ fontFamily: 'var(--cth-font-display)', fontSize: 9, color: 'var(--cth-ink-500)', marginRight: 2 }}>CONTROL</span>
+ <PixelButton variant={snap?.paused ? 'primary' : 'secondary'} size="sm" onClick={togglePause}>
+ {snap?.paused ? 'resume' : 'pause'}
+ </PixelButton>
+ <PixelButton variant="destructive" size="sm" onClick={halt}>halt</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>
+ <div style={{ display: 'flex', gap: 6 }}>
+ <input
+ value={steer}
+ onChange={(e) => setSteer(e.target.value)}
+ onKeyDown={(e) => { if (e.key === 'Enter') sendSteer(); }}
+ placeholder="steer this agent (injected as context, no typing into its terminal)…"
+ style={{
+ flex: 1, padding: '4px 6px', background: 'var(--cth-paper-100)', border: 'none',
+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)', fontFamily: 'var(--cth-font-ui)',
+ fontSize: 12, color: 'var(--cth-ink-900)', outline: 'none'
+ }}
+ />
+ <PixelButton variant="secondary" size="sm" onClick={sendSteer} disabled={!steer.trim()}>steer</PixelButton>
+ </div>
+ {note && <span style={{ fontSize: 11, color: 'var(--cth-ink-500)' }}>{note}</span>}
+ </div>
+ );
+}
diff --git a/src/renderer/src/components/AgentDetailPanel.tsx b/src/renderer/src/components/AgentDetailPanel.tsx
index 4de150ab..00dd9734 100644
--- a/src/renderer/src/components/AgentDetailPanel.tsx
+++ b/src/renderer/src/components/AgentDetailPanel.tsx
@@ -12,6 +12,7 @@ import { SidebarTabs } from './SidebarTabs';
import { FilesTab } from './FilesTab';
import { ThreadsPanel } from './ThreadsPanel';
import { ToolWaterfall } from './ToolWaterfall';
+import { AgentControlStrip } from './AgentControlStrip';
import { Icon } from './Icon';
import { useStore, type Agent } from '@/store/store';
import { usePtyParser } from '@/hooks/usePtyParser';
@@ -138,6 +139,9 @@ export function AgentDetailPanel({ agent }: AgentDetailPanelProps) {
}}>{openTerminalError}</div>
)}
+ {/* #7C — operator control (pause / halt / steer) for live agents */}
+ {isReal && <AgentControlStrip agentId={agent.id} />}
+
{/* Tabs */}
<SidebarTabs current={sidebarTab} accent={agent.accent} onChange={setSidebarTab} />