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(app): prep assistant "Dwight" + enrich pipeline + Michael's Command Center

Chaitanya Giri18013384be10
diff --git a/src/main/assistant.ts b/src/main/assistant.ts
new file mode 100644
index 00000000..ffe1ba15
--- /dev/null
+++ b/src/main/assistant.ts
@@ -0,0 +1,164 @@
+import { spawn } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { resolveCommand, userShellPath } from './shellEnv';
+
+/**
+ * Michael's silent prep assistant.
+ *
+ * Runs a one-shot, headless `claude -p` session (Sonnet, 1M context) that NEVER
+ * appears on the office floor or in the agent list. Given a short, possibly
+ * vague instruction the user parked for Michael, it locates the relevant project
+ * directory (it starts in Michael's home and can read every registered repo),
+ * gathers concrete context read-only, and rewrites the instruction into a
+ * single self-contained prompt Michael can execute autonomously.
+ *
+ * The result text replaces the queued message, so the existing queue→PTY flush
+ * delivers the enriched prompt to Michael with no extra plumbing.
+ */
+
+/** Sonnet with the 1M-token context window — chosen for cheap, large-context
+ * context-gathering that won't compete with Michael's own (Opus) session. */
+const ASSISTANT_MODEL = 'claude-sonnet-4-6[1m]';
+
+const DEFAULT_TIMEOUT_MS = 180_000;
+
+export interface EnrichRequest {
+ /** The raw instruction the user wants enriched. */
+ message: string;
+ /** Michael's working directory — the assistant's default cwd. */
+ cwd: string;
+ /** Registered project repos the assistant may read to gather context. */
+ repos?: string[];
+ /** Base claude command from config (only its binary name is used). */
+ command?: string;
+ /** Model override; defaults to Sonnet 1M. */
+ model?: string;
+ /** Hard cap so a runaway run can't wedge the queue. */
+ timeoutMs?: number;
+ /** Extra env merged over the resolved shell env (e.g. the shared MemPalace). */
+ env?: Record<string, string>;
+}
+
+export interface EnrichResult {
+ ok: boolean;
+ /** The enriched, self-contained prompt for Michael. */
+ prompt?: string;
+ error?: string;
+}
+
+function buildTaskPrompt(message: string, cwd: string, repos: string[]): string {
+ const repoList = repos.length
+ ? repos.map((r) => ` - ${r}`).join('\n')
+ : ' (none registered — work from the home directory above)';
+ return [
+ "You are Michael's silent prep assistant inside the Munder Difflin agent harness.",
+ 'Michael is the orchestrator who will act on the prompt you produce — autonomously, with no human in the loop.',
+ 'You are NOT visible to the user and you do NOT perform the task yourself. Your only job is to turn a short,',
+ 'possibly vague instruction into a single, self-contained, context-rich prompt that Michael can execute immediately.',
+ '',
+ `Your working directory is Michael's home: ${cwd}`,
+ 'Project repositories you may read to gather context (cd into the relevant one):',
+ repoList,
+ '',
+ 'Do this:',
+ '1. Decide which project/directory this instruction concerns and cd into the most relevant repo',
+ ' (or stay in the home directory if it is a hive/coordination task).',
+ '2. Explore READ-ONLY to gather the concrete context Michael needs: exact file paths, current state,',
+ ' relevant code, conventions, the active branch, and any constraints or gotchas. NEVER modify, create,',
+ ' or delete files, and never run destructive or write commands.',
+ "3. Rewrite the instruction into ONE clear prompt for Michael. Preserve the user's original intent exactly —",
+ ' do not invent new scope. State the target directory, the specific files/symbols involved, the concrete',
+ ' goal, and anything you discovered that Michael should know before starting.',
+ '',
+ 'Output ONLY the final prompt text for Michael. No preamble, no explanation, no markdown code fences,',
+ 'no "Here is the prompt". Just the prompt itself.',
+ '',
+ '--- ORIGINAL INSTRUCTION FROM THE USER ---',
+ message
+ ].join('\n');
+}
+
+/** Pull the final assistant text out of `claude -p --output-format json`. */
+function parsePrompt(stdout: string): string | null {
+ const raw = stdout.trim();
+ if (!raw) return null;
+ try {
+ const obj = JSON.parse(raw) as { result?: unknown; text?: unknown };
+ const text = typeof obj.result === 'string' ? obj.result
+ : typeof obj.text === 'string' ? obj.text
+ : null;
+ if (text && text.trim()) return text.trim();
+ } catch { /* not JSON — fall back to the raw stdout below */ }
+ return raw;
+}
+
+export function enrichMessage(req: EnrichRequest): Promise<EnrichResult> {
+ return new Promise((resolve) => {
+ const message = (req.message ?? '').trim();
+ if (!message) { resolve({ ok: false, error: 'empty message' }); return; }
+ if (!req.cwd || !existsSync(req.cwd)) {
+ resolve({ ok: false, error: `working directory does not exist: ${req.cwd}` });
+ return;
+ }
+
+ const binary = (req.command || 'claude').trim().split(/\s+/)[0] || 'claude';
+ const exe = resolveCommand(binary);
+ const repos = (req.repos ?? []).filter((r) => r && existsSync(r) && r !== req.cwd);
+ const taskPrompt = buildTaskPrompt(message, req.cwd, req.repos ?? []);
+
+ // We build the flag set ourselves (rather than reusing config's command
+ // string) so the assistant's behaviour is fixed regardless of the user's
+ // autoMode / defaultCommand: headless print mode, Sonnet 1M, read-only.
+ const args = [
+ '-p', taskPrompt,
+ '--model', req.model || ASSISTANT_MODEL,
+ '--output-format', 'json',
+ '--permission-mode', 'bypassPermissions',
+ // Context gathering only — the assistant must never mutate a repo. These
+ // are passed as separate args because the CLI flag is variadic (<tools...>).
+ '--disallowedTools', 'Edit', 'Write', 'NotebookEdit'
+ ];
+ // --add-dir comes last so it terminates the variadic --disallowedTools list.
+ for (const r of repos) { args.push('--add-dir', r); }
+
+ let child;
+ try {
+ child = spawn(exe, args, {
+ cwd: req.cwd,
+ env: {
+ ...process.env,
+ PATH: userShellPath(),
+ ...(req.env ?? {})
+ } as Record<string, string>,
+ stdio: ['ignore', 'pipe', 'pipe']
+ });
+ } catch (e) {
+ resolve({ ok: false, error: e instanceof Error ? e.message : String(e) });
+ return;
+ }
+
+ let stdout = '';
+ let stderr = '';
+ let settled = false;
+ const finish = (r: EnrichResult) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve(r);
+ };
+
+ const timer = setTimeout(() => {
+ try { child.kill('SIGKILL'); } catch { /* noop */ }
+ finish({ ok: false, error: 'enrichment timed out' });
+ }, req.timeoutMs ?? DEFAULT_TIMEOUT_MS);
+
+ child.stdout?.on('data', (d) => { stdout += d.toString(); });
+ child.stderr?.on('data', (d) => { stderr += d.toString(); });
+ child.on('error', (e) => finish({ ok: false, error: e.message }));
+ child.on('close', (code) => {
+ const prompt = parsePrompt(stdout);
+ if (prompt) { finish({ ok: true, prompt }); return; }
+ finish({ ok: false, error: stderr.trim() || `assistant exited ${code ?? '?'} with no output` });
+ });
+ });
+}
diff --git a/src/main/config.ts b/src/main/config.ts
index 3866bfee..d4df2874 100644
--- a/src/main/config.ts
+++ b/src/main/config.ts
@@ -13,6 +13,8 @@ export interface HarnessConfig {
autoMode: boolean;
/** The command we run when spawning a new agent. */
defaultCommand: string;
+ /** Default model for newly spawned agents (e.g. 'claude-sonnet-4-6[1m]'); unset = CLI default. */
+ defaultModel?: string;
/** Enable semantic memory (MemPalace CLI). No-op if mempalace isn't installed. */
semanticMemory: boolean;
/** Embedding model for the palace: lightweight 'minilm' or multilingual 'embeddinggemma'. */
diff --git a/src/main/hive.ts b/src/main/hive.ts
index d2b3f01c..39c4cfac 100644
--- a/src/main/hive.ts
+++ b/src/main/hive.ts
@@ -46,6 +46,9 @@ export interface AgentMeta {
capabilities?: string[];
cwd: string;
isGod?: boolean;
+ /** Michael's prep assistant — enriches prompts and forwards them to Michael.
+ * Send-only: excluded from broadcast fan-out so it never drains an inbox. */
+ isAssistant?: boolean;
}
export interface RegistryAgent extends AgentMeta {
@@ -281,6 +284,8 @@ export class HiveManager {
: '';
const godLine = meta.isGod
? 'You are the GOD / ORCHESTRATOR of this hive. Drain your inbox continually and triage every other agent\'s requests: answer clarifications and route work yourself so the team runs autonomously. ONLY escalate genuinely critical items — destructive actions, spending real money, scope changes, or unresolvable conflicts — to the human by sending a message with "to":"human" (or "needs_human":true); it queues for human approval and their reply returns to you. Keep the team unblocked, maintain registry/tasks awareness, and be the sole scribe of board.md.'
+ : meta.isAssistant
+ ? 'You are Michael\'s PREP ASSISTANT. You will be handed short, possibly vague instructions (each begins with "ENRICH TASK:"). For each one: (1) figure out which project it concerns and cd into the most relevant repo — you start in Michael\'s home directory; (2) gather concrete context READ-ONLY (exact file paths, current state, relevant code, conventions, active branch, gotchas) — NEVER modify, create, or delete files; (3) rewrite the instruction into ONE clear, self-contained prompt that Michael can execute autonomously, preserving the user\'s original intent without inventing scope. Then deliver it: write ONE message JSON into your outbox with "to":"god", "act":"request", a short subject, and the finished prompt as the body. Do NOT perform the task yourself — your only output is the improved prompt sent to Michael.'
: 'For anything ambiguous, cross-cutting, or needing sign-off, address a message to "god".';
return [
`You are "${meta.name}" (${meta.id}), an autonomous agent in a collaborating hive of Claude agents.`,
@@ -348,7 +353,8 @@ export class HiveManager {
}
const reg = this.registry();
const targets = msg.to === 'broadcast'
- ? Object.keys(reg.agents).filter((a) => a !== msg.from)
+ // The prep assistant is send-only — never fan broadcasts into its inbox.
+ ? Object.keys(reg.agents).filter((a) => a !== msg.from && !reg.agents[a]?.isAssistant)
: [msg.to === 'god' ? (reg.godId ?? 'god') : msg.to];
for (const t of targets) this.deliver(msg, t);
this.appendLog({ kind: 'message', from: msg.from, to: msg.to, act: msg.act, subject: msg.subject, id: msg.id });
diff --git a/src/main/hooks.ts b/src/main/hooks.ts
index f33a3eeb..71ae6ebf 100644
--- a/src/main/hooks.ts
+++ b/src/main/hooks.ts
@@ -75,30 +75,37 @@ export class HookServer {
const agentId = p.agent_id ?? undefined;
const event = p.hook_event_name ?? 'Unknown';
- // Forward everything to the renderer so avatars reflect real activity.
- this.emit(agentId, event, p);
-
if ((event === 'Stop' || event === 'SubagentStop') && agentId) {
// Loop guard: a previous Stop hook already blocked this turn → let it stop.
- if (p.stop_hook_active) return {};
+ 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.
+ this.emit(agentId, event, p);
return {};
}
+ // Forward everything else to the renderer so avatars reflect real activity.
+ this.emit(agentId, event, p);
return {};
}
- private emit(agentId: string | undefined, event: string, p: HookPayload): void {
+ private emit(agentId: string | undefined, event: string, p: HookPayload, blocked = false): void {
this.getWebContents()?.send('hive:hookEvent', {
agentId,
event,
tool: p.tool_name,
notificationType: p.notification_type,
source: p.source,
- message: p.message
+ message: p.message,
+ blocked
});
}
}
diff --git a/src/main/index.ts b/src/main/index.ts
index 214bb2a7..b8771c77 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1,4 +1,4 @@
-import { app, BrowserWindow, dialog, ipcMain, shell } from 'electron';
+import { app, BrowserWindow, clipboard, dialog, ipcMain, shell } from 'electron';
import { spawn } from 'node:child_process';
import { rmSync } from 'node:fs';
import { join } from 'node:path';
@@ -14,6 +14,7 @@ import {
import { HiveManager, type AgentMeta, type HiveMessage } from './hive';
import { HookServer } from './hooks';
import { MemoryManager } from './memory';
+import { enrichMessage } from './assistant';
const isDev = !!process.env.ELECTRON_RENDERER_URL;
const ptyManager = new PtyManager();
@@ -127,6 +128,13 @@ ipcMain.handle('pty:kill', (_evt, id: string) => {
});
ipcMain.handle('pty:list', () => ptyManager.list());
+// ─── IPC: clipboard ─────────────────────────────────────────────────────────
+ipcMain.handle('app:copyToClipboard', (_evt, text: unknown) => {
+ if (typeof text !== 'string') return { ok: false, error: 'invalid text' };
+ try { clipboard.writeText(text); return { ok: true }; }
+ catch (e) { return { ok: false, error: e instanceof Error ? e.message : String(e) }; }
+});
+
// ─── IPC: folder picker ─────────────────────────────────────────────────────
ipcMain.handle('dialog:chooseFolder', async (evt) => {
const win = BrowserWindow.fromWebContents(evt.sender);
@@ -224,6 +232,28 @@ ipcMain.handle('hive:send', (_evt, partial: Partial<HiveMessage>, from: unknown)
return { ok: true, message: msg };
});
+// ─── IPC: enrichment assistant (headless Sonnet 1M prompt prep) ─────────────
+ipcMain.handle('assistant:enrich', async (_evt, payload: unknown) => {
+ const p = (payload ?? {}) as { message?: unknown; cwd?: unknown };
+ if (typeof p.message !== 'string' || !p.message.trim()) {
+ return { ok: false, error: 'empty message' };
+ }
+ const cfg = readConfig();
+ const cwd = typeof p.cwd === 'string' && p.cwd ? p.cwd : cfg.harnessHome;
+ if (!cwd) return { ok: false, error: 'no working directory available' };
+ try {
+ return await enrichMessage({
+ message: p.message,
+ cwd,
+ repos: cfg.registeredRepos ?? [],
+ command: cfg.defaultCommand,
+ env: memory.env()
+ });
+ } catch (e) {
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
+ }
+});
+
// ─── IPC: semantic memory (MemPalace CLI) ───────────────────────────────────
ipcMain.handle('hive:memoryStatus', () => { memory.resetBinCache(); return memory.status(); });
ipcMain.handle('hive:searchMemory', (_evt, query: unknown, wing: unknown) => {
diff --git a/src/main/shellEnv.ts b/src/main/shellEnv.ts
new file mode 100644
index 00000000..2bda40a1
--- /dev/null
+++ b/src/main/shellEnv.ts
@@ -0,0 +1,47 @@
+import { existsSync } from 'node:fs';
+import { spawnSync } from 'node:child_process';
+
+// These helpers mirror the resolution logic in pty.ts. They exist separately so
+// headless child processes (e.g. the enrichment assistant) can launch `claude`
+// with the same PATH the user's interactive shell sees — Electron on macOS
+// starts without the login-shell PATH, so a bare `claude` would otherwise fail
+// with ENOENT in a packaged build.
+
+let cachedPath: string | null = null;
+
+/** The user's interactive-shell PATH, queried once and cached for the session. */
+export function userShellPath(): string {
+ if (cachedPath !== null) return cachedPath;
+ try {
+ const res = spawnSync(process.env.SHELL ?? '/bin/zsh', ['-ilc', 'echo -n "$PATH"'], {
+ encoding: 'utf8',
+ timeout: 3000
+ });
+ cachedPath = res.stdout.trim() || process.env.PATH || '';
+ } catch {
+ cachedPath = process.env.PATH || '';
+ }
+ return cachedPath;
+}
+
+/** Resolve a bare command (e.g. 'claude') against the user's PATH + common
+ * install locations. Returns the input unchanged if it already looks like a path. */
+export function resolveCommand(command: string): string {
+ if (command.includes('/')) return command;
+ try {
+ const res = spawnSync(process.env.SHELL ?? '/bin/zsh', ['-ilc', `which ${command}`], {
+ encoding: 'utf8',
+ timeout: 3000
+ });
+ const path = res.stdout.trim().split('\n').pop();
+ if (path && existsSync(path)) return path;
+ } catch { /* fall through */ }
+ const candidates = [
+ `/opt/homebrew/bin/${command}`,
+ `/usr/local/bin/${command}`,
+ `${process.env.HOME ?? ''}/.local/bin/${command}`,
+ `${process.env.HOME ?? ''}/.claude/local/${command}`
+ ];
+ for (const c of candidates) if (existsSync(c)) return c;
+ return command;
+}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 88ded44d..42e5960a 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -7,6 +7,7 @@ export interface HiveAgentMeta {
capabilities?: string[];
cwd: string;
isGod?: boolean;
+ isAssistant?: boolean;
}
export interface HiveMessage {
@@ -61,6 +62,7 @@ export interface HarnessConfig {
registeredRepos: string[];
autoMode: boolean;
defaultCommand: string;
+ defaultModel?: string;
semanticMemory: boolean;
embeddingModel: 'minilm' | 'embeddinggemma';
}
@@ -129,6 +131,10 @@ const api = {
openTerminalAt: (cwd: string): Promise<{ ok: boolean; error?: string }> =>
ipcRenderer.invoke('terminal:openAtFolder', cwd),
+ // ─── Clipboard ─────────────────────────────────────────────────────────────
+ copyToClipboard: (text: string): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('app:copyToClipboard', text),
+
// ─── Config ──────────────────────────────────────────────────────────────
getConfig: (): Promise<HarnessConfig> =>
ipcRenderer.invoke('config:get'),
@@ -181,10 +187,17 @@ const api = {
mineNow: (): Promise<{ ok: boolean }> => ipcRenderer.invoke('hive:mineNow'),
hiveSend: (msg: Partial<HiveMessage>, from?: string): Promise<{ ok: boolean; error?: string; message?: HiveMessage }> =>
ipcRenderer.invoke('hive:send', msg, from),
+
+ // ─── Enrichment assistant (headless Sonnet 1M prompt prep for Michael) ─────
+ /** Run Michael's silent assistant on a raw message and return an enriched,
+ * context-rich prompt. `cwd` is the agent's working directory (its default
+ * context); the assistant may read every registered repo to gather more. */
+ enrichMessage: (req: { message: string; cwd: string }): Promise<{ ok: boolean; prompt?: string; error?: string }> =>
+ ipcRenderer.invoke('assistant:enrich', req),
onHiveHookEvent: (
- cb: (e: { agentId?: string; event: string; tool?: string; notificationType?: string; source?: string; message?: string }) => void
+ cb: (e: { agentId?: string; event: string; tool?: string; notificationType?: string; source?: string; message?: string; blocked?: boolean }) => void
): (() => void) => {
- const listener = (_e: IpcRendererEvent, payload: { agentId?: string; event: string; tool?: string; notificationType?: string; source?: string; message?: string }) => cb(payload);
+ const listener = (_e: IpcRendererEvent, payload: { agentId?: string; event: string; tool?: string; notificationType?: string; source?: string; message?: string; blocked?: boolean }) => cb(payload);
ipcRenderer.on('hive:hookEvent', listener);
return () => ipcRenderer.removeListener('hive:hookEvent', listener);
},
diff --git a/src/renderer/src/components/AddAgentModal.tsx b/src/renderer/src/components/AddAgentModal.tsx
index e66b2e49..560a3e20 100644
--- a/src/renderer/src/components/AddAgentModal.tsx
+++ b/src/renderer/src/components/AddAgentModal.tsx
@@ -6,7 +6,7 @@ import { Icon } from './Icon';
import { useStore, type Agent } from '@/store/store';
import { OFFICE_CAST, DEFAULT_CHARACTER, type OfficeCharacterName } from '@/scene/office/cast';
import { type AccentColorName } from '@/design/tokens';
-import { type HarnessConfig, buildSpawnCommand } from '@/store/config';
+import { type HarnessConfig, buildSpawnCommand, AGENT_MODELS } from '@/store/config';
const ACCENTS: AccentColorName[] = ['coral', 'mint', 'sky', 'lemon', 'lilac', 'peach'];
@@ -30,8 +30,16 @@ export function AddAgentModal({ onClose, config }: AddAgentModalProps) {
const [character, setCharacter] = useState<OfficeCharacterName>(DEFAULT_CHARACTER);
const [accent, setAccent] = useState<AccentColorName>('sky');
const [cwd, setCwd] = useState<string>(config.registeredRepos[0] ?? '');
- const [command, setCommand] = useState(buildSpawnCommand(config));
+ const [model, setModel] = useState<string | undefined>(config.defaultModel);
+ const [command, setCommand] = useState(buildSpawnCommand(config, config.defaultModel));
const [description, setDescription] = useState('a fresh harness');
+
+ // Picking a model rebuilds the command; the command field stays editable for
+ // power users (it's the source of truth for the actual spawn).
+ const pickModel = (id?: string) => {
+ setModel(id);
+ setCommand(buildSpawnCommand(config, id));
+ };
const [goal, setGoal] = useState('');
const [error, setError] = useState<string | undefined>();
const [busy, setBusy] = useState(false);
@@ -92,6 +100,7 @@ export function AddAgentModal({ onClose, config }: AddAgentModalProps) {
currentStation: 'desk',
ptyId,
command: command.trim(),
+ model,
recentTextTs: Date.now()
};
addAgent(agent);
@@ -166,6 +175,32 @@ export function AddAgentModal({ onClose, config }: AddAgentModalProps) {
</div>
</Row>
+ <Row label="Model">
+ <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
+ {AGENT_MODELS.map((m) => {
+ const active = (model ?? '') === (m.id ?? '');
+ return (
+ <button
+ key={m.label}
+ onClick={() => pickModel(m.id)}
+ title={m.id ?? 'CLI default model'}
+ style={{
+ padding: '3px 8px 1px',
+ background: active ? `var(--cth-${accent}-light)` : 'var(--cth-cream-100)',
+ boxShadow: active
+ ? 'inset 0 0 0 2px var(--cth-ink-900)'
+ : 'inset 0 0 0 1px var(--cth-ink-700)',
+ fontFamily: 'var(--cth-font-ui)', fontSize: 13,
+ color: 'var(--cth-ink-900)', cursor: 'pointer', border: 'none'
+ }}
+ >
+ {m.label}
+ </button>
+ );
+ })}
+ </div>
+ </Row>
+
<Row label={config.autoMode ? 'Command (auto mode on)' : 'Command'}>
<input
value={command}
diff --git a/src/renderer/src/components/AgentCard.tsx b/src/renderer/src/components/AgentCard.tsx
index 0da75285..7721f4be 100644
--- a/src/renderer/src/components/AgentCard.tsx
+++ b/src/renderer/src/components/AgentCard.tsx
@@ -13,12 +13,19 @@ export interface AgentCardProps {
action?: string;
progress?: number; // 0..8 segments filled
selected?: boolean;
+ /** The orchestrator — gets a persistent accent frame + GOD tag so it stands out. */
+ isGod?: boolean;
+ /** The prep assistant. Same size as every other card (no special sizing). */
+ isAssistant?: boolean;
onClick?: () => void;
}
export function AgentCard({
- name, character, accent, status, project, action, progress = 0, selected, onClick
+ name, character, accent, status, project, action, progress = 0, selected, isGod, onClick
}: AgentCardProps) {
+ // The god is always framed (stands out from the row); others only when selected.
+ const framed = isGod || selected;
+
return (
<button
onClick={onClick}
@@ -29,8 +36,8 @@ export function AgentCard({
}}
>
<PixelPanel
- variant={selected ? 'active' : 'default'}
- accent={selected ? accent : undefined}
+ variant={framed ? 'active' : 'default'}
+ accent={framed ? accent : undefined}
style={{ height: '100%', padding: 8 }}
noPadding
>
@@ -39,7 +46,8 @@ export function AgentCard({
width: 44, height: 64,
background: `var(--cth-${accent}-light)`,
boxShadow: 'inset 0 0 0 1px var(--cth-ink-900)',
- display: 'flex', alignItems: 'flex-end', justifyContent: 'center', overflow: 'hidden'
+ display: 'flex', alignItems: 'flex-end', justifyContent: 'center', overflow: 'hidden',
+ flexShrink: 0
}}>
<SpritePortrait character={character} scale={2} />
</div>
@@ -56,14 +64,24 @@ export function AgentCard({
}}>{name.toUpperCase()}</span>
<PixelBadge status={status} />
</div>
+
<div style={{
+ display: 'flex', alignItems: 'center', gap: 5,
fontSize: 'var(--cth-text-body-sm)',
lineHeight: '16px',
color: 'var(--cth-ink-500)',
- whiteSpace: 'nowrap',
- overflow: 'hidden',
- textOverflow: 'ellipsis'
- }}>{project}</div>
+ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'
+ }}>
+ {isGod && (
+ <span style={{
+ fontFamily: 'var(--cth-font-display)', fontSize: 8, lineHeight: '12px',
+ background: `var(--cth-${accent})`, color: 'var(--cth-ink-900)',
+ padding: '1px 5px 0', boxShadow: 'inset 0 0 0 1px var(--cth-ink-900)', flexShrink: 0
+ }}>GOD</span>
+ )}
+ <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{project}</span>
+ </div>
+
<div style={{
fontSize: 'var(--cth-text-body-sm)',
lineHeight: '16px',
@@ -71,7 +89,9 @@ export function AgentCard({
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis'
- }}>{action ?? ' '}</div>
+ }}>{/* The "idle" badge already conveys idle — don't echo "awaiting". */
+ (status === 'idle' ? '' : action) || ' '}</div>
+
<div style={{ display: 'flex', gap: 2, marginTop: 2 }}>
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} style={{
diff --git a/src/renderer/src/components/AgentDetailPanel.tsx b/src/renderer/src/components/AgentDetailPanel.tsx
index f073a972..0c95fef0 100644
--- a/src/renderer/src/components/AgentDetailPanel.tsx
+++ b/src/renderer/src/components/AgentDetailPanel.tsx
@@ -4,6 +4,9 @@ import { PixelBadge } from './PixelBadge';
import { PixelButton } from './PixelButton';
import { SpritePortrait } from './SpritePortrait';
import { PtyTerminalView } from './PtyTerminalView';
+import { MessageQueueComposer } from './MessageQueueComposer';
+import { AssistantRoleNote } from './AssistantRoleNote';
+import { CommandCenterPanel } from './CommandCenterPanel';
import { disposeTerminal } from './terminalPool';
import { SidebarTabs } from './SidebarTabs';
import { FilesTab } from './FilesTab';
@@ -34,6 +37,9 @@ export function AgentDetailPanel({ agent }: AgentDetailPanelProps) {
const onPtyStream = usePtyParser(agent.id);
+ // Michael gets the full command-center dashboard instead of the plain panel.
+ if (agent.isGod) return <CommandCenterPanel agent={agent} />;
+
const openTerminal = async () => {
setOpenTerminalState('opening');
setOpenTerminalError(undefined);
@@ -142,15 +148,20 @@ export function AgentDetailPanel({ agent }: AgentDetailPanelProps) {
This terminal is open in fullscreen. Press Esc or exit fullscreen to bring it back here.
</EmptyTab>
) : (
- <PtyTerminalView
- key={agent.ptyId}
- ptyId={agent.ptyId}
- onStreamData={onPtyStream}
- onUserPrompt={(t) => updateAgent(agent.id, { lastPrompt: t })}
- onToggleFullscreen={() => setFullscreen(agent.id)}
- fullscreen={false}
- embedded
- />
+ <div style={{ flex: 1, minWidth: 0, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
+ <div style={{ flex: 1, minHeight: 0, display: 'flex' }}>
+ <PtyTerminalView
+ key={agent.ptyId}
+ ptyId={agent.ptyId}
+ onStreamData={onPtyStream}
+ onUserPrompt={(t) => updateAgent(agent.id, { lastPrompt: t })}
+ onToggleFullscreen={() => setFullscreen(agent.id)}
+ fullscreen={false}
+ embedded
+ />
+ </div>
+ {agent.isAssistant ? <AssistantRoleNote /> : <MessageQueueComposer agent={agent} />}
+ </div>
)
) : (
<EmptyTab title="No PTY">
diff --git a/src/renderer/src/components/AgentStrip.tsx b/src/renderer/src/components/AgentStrip.tsx
index 4ea20be3..6f50d7ee 100644
--- a/src/renderer/src/components/AgentStrip.tsx
+++ b/src/renderer/src/components/AgentStrip.tsx
@@ -33,6 +33,8 @@ export function AgentStrip() {
action={a.action}
progress={a.progress}
selected={a.id === selectedId}
+ isGod={a.isGod}
+ isAssistant={a.isAssistant}
onClick={() => select(a.id)}
/>
))}
diff --git a/src/renderer/src/components/AssistantRoleNote.tsx b/src/renderer/src/components/AssistantRoleNote.tsx
new file mode 100644
index 00000000..135c8d5b
--- /dev/null
+++ b/src/renderer/src/components/AssistantRoleNote.tsx
@@ -0,0 +1,34 @@
+import { Icon } from './Icon';
+import { useStore } from '@/store/store';
+
+/** Footer shown under the assistant's terminal in place of a message composer.
+ * The assistant isn't messaged directly — it's fed by Michael's enrich queue —
+ * so this explains its role and points to the toggle in Michael's panel. */
+export function AssistantRoleNote() {
+ const enrichEnabled = useStore((s) => s.enrichEnabled);
+ const select = useStore((s) => s.select);
+
+ return (
+ <div style={{
+ flexShrink: 0,
+ borderTop: '1px solid var(--cth-ink-700)',
+ background: 'var(--cth-cream-100)',
+ padding: 8,
+ display: 'flex', alignItems: 'center', gap: 8
+ }}>
+ <Icon name="sparkle" />
+ <div style={{ flex: 1, minWidth: 0, fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-700)' }}>
+ Dwight is Michael's assistant, he helps him enrich context before he executes a task.<strong>{enrichEnabled ? 'on' : 'off'}</strong>.
+ </div>
+ <button
+ onClick={() => select('god')}
+ style={{
+ flexShrink: 0,
+ padding: '3px 8px 2px', border: 'none', cursor: 'pointer',
+ background: 'var(--cth-cream-200)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',
+ fontFamily: 'var(--cth-font-ui)', fontSize: 12, color: 'var(--cth-ink-900)'
+ }}
+ >open Michael</button>
+ </div>
+ );
+}
diff --git a/src/renderer/src/components/CommandCenterPanel.tsx b/src/renderer/src/components/CommandCenterPanel.tsx
new file mode 100644
index 00000000..a71ff27a
--- /dev/null
+++ b/src/renderer/src/components/CommandCenterPanel.tsx
@@ -0,0 +1,598 @@
+import { useEffect, useRef, useState } from 'react';
+import { PixelPanel } from './PixelPanel';
+import { PixelBadge } from './PixelBadge';
+import { PixelButton } from './PixelButton';
+import { SpritePortrait } from './SpritePortrait';
+import { PtyTerminalView } from './PtyTerminalView';
+import { MessageQueueComposer } from './MessageQueueComposer';
+import { disposeTerminal } from './terminalPool';
+import { Icon } from './Icon';
+import { useStore, type Agent } from '@/store/store';
+import { usePtyParser } from '@/hooks/usePtyParser';
+import { buildSpawnCommand, AGENT_MODELS } 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
+ * per-agent model + dispatch + assistant access), a memory view, and a live
+ * activity feed / board / usage meter. */
+
+type CCTab = 'terminal' | 'floor' | 'memory' | 'activity' | 'handbook';
+
+const TABS: { key: CCTab; label: string; icon: Parameters<typeof Icon>[0]['name'] }[] = [
+ { key: 'terminal', label: 'terminal', icon: 'terminal' },
+ { key: 'floor', label: 'floor', icon: 'mcp' },
+ { key: 'memory', label: 'memory', icon: 'sparkle' },
+ { key: 'activity', label: 'activity', icon: 'bell' },
+ { key: 'handbook', label: 'commands', icon: 'code' }
+];
+
+export function CommandCenterPanel({ agent }: { agent: Agent }) {
+ const [tab, setTab] = useState<CCTab>('terminal');
+ const updateAgent = useStore((s) => s.updateAgent);
+ const setFullscreen = useStore((s) => s.setFullscreen);
+ const fullscreenAgentId = useStore((s) => s.fullscreenAgentId);
+ const onPtyStream = usePtyParser(agent.id);
+ const isFullscreenedHere = fullscreenAgentId === agent.id;
+
+ return (
+ <PixelPanel
+ variant="default"
+ noPadding
+ style={{ display: 'flex', flexDirection: 'column', height: '100%', padding: 0, overflow: 'hidden' }}
+ >
+ {/* Header */}
+ <div style={{
+ display: 'flex', alignItems: 'center', gap: 8,
+ padding: '6px 8px', background: 'var(--cth-cream-100)',
+ borderBottom: '1px solid var(--cth-ink-700)', flexShrink: 0
+ }}>
+ <div style={{
+ width: 32, height: 32, background: `var(--cth-${agent.accent}-light)`,
+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-900)',
+ display: 'flex', alignItems: 'flex-end', justifyContent: 'center', overflow: 'hidden', flexShrink: 0
+ }}>
+ <SpritePortrait character={agent.character} scale={1} />
+ </div>
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <div style={{
+ fontFamily: 'var(--cth-font-display)', fontSize: 10, lineHeight: '14px', color: 'var(--cth-ink-900)'
+ }}>MICHAEL · COMMAND CENTER</div>
+ <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginTop: 1 }}>
+ <PixelBadge status={agent.status} />
+ <span style={{ fontSize: 12, color: 'var(--cth-ink-500)' }}>runs the floor</span>
+ </div>
+ </div>
+ </div>
+
+ {/* Tab bar */}
+ <div style={{
+ display: 'flex', gap: 4, padding: '6px 8px 0',
+ background: 'var(--cth-cream-100)', borderBottom: '1px solid var(--cth-ink-700)', flexShrink: 0
+ }}>
+ {TABS.map((t) => (
+ <button
+ key={t.key}
+ onClick={() => setTab(t.key)}
+ style={{
+ display: 'inline-flex', alignItems: 'center', gap: 4,
+ padding: '4px 9px 3px', border: 'none', cursor: 'pointer',
+ background: tab === t.key ? `var(--cth-${agent.accent})` : 'var(--cth-cream-200)',
+ color: 'var(--cth-ink-900)',
+ boxShadow: tab === t.key
+ ? 'inset 0 0 0 1px var(--cth-ink-900)'
+ : 'inset 0 0 0 1px var(--cth-ink-700)',
+ fontFamily: 'var(--cth-font-ui)', fontSize: 13
+ }}
+ >
+ <Icon name={t.icon} /> {t.label}
+ </button>
+ ))}
+ </div>
+
+ {/* Body */}
+ <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
+ {tab === 'terminal' && (
+ isFullscreenedHere ? (
+ <Centered>Terminal is open in fullscreen. Press Esc to bring it back.</Centered>
+ ) : agent.ptyId ? (
+ <>
+ <div style={{ flex: 1, minHeight: 0, display: 'flex' }}>
+ <PtyTerminalView
+ key={agent.ptyId}
+ ptyId={agent.ptyId}
+ onStreamData={onPtyStream}
+ onUserPrompt={(t) => updateAgent(agent.id, { lastPrompt: t })}
+ onToggleFullscreen={() => setFullscreen(agent.id)}
+ fullscreen={false}
+ embedded
+ />
+ </div>
+ <MessageQueueComposer agent={agent} />
+ </>
+ ) : (
+ <Centered>Michael has no live terminal.</Centered>
+ )
+ )}
+ {tab === 'floor' && <FloorTab />}
+ {tab === 'memory' && <MemoryTab godId={agent.id} />}
+ {tab === 'activity' && <ActivityTab />}
+ {tab === 'handbook' && <HandbookTab />}
+ </div>
+ </PixelPanel>
+ );
+}
+
+// ─── Floor tab — roster, model, dispatch, dirs, assistant ────────────────────
+
+function FloorTab() {
+ const agents = useStore((s) => s.agents);
+ const select = useStore((s) => s.select);
+ const updateAgent = useStore((s) => s.updateAgent);
+ const enrichEnabled = useStore((s) => s.enrichEnabled);
+ const setEnrichEnabled = useStore((s) => s.setEnrichEnabled);
+ const toolCounts = useStore((s) => s.toolCounts);
+ const [repos, setRepos] = useState<string[]>([]);
+ const [restarting, setRestarting] = useState<string | null>(null);
+ const [dispatchTo, setDispatchTo] = useState<string>('broadcast');
+ const [dispatchText, setDispatchText] = useState('');
+ const [dispatchMsg, setDispatchMsg] = useState<string | null>(null);
+
+ useEffect(() => {
+ window.cth.getConfig().then((c) => setRepos(c.registeredRepos ?? [])).catch(() => { /* noop */ });
+ }, []);
+
+ const restartWithModel = async (a: Agent, model: string | undefined) => {
+ if (!a.ptyId) return;
+ setRestarting(a.id);
+ try {
+ const cfg = await window.cth.getConfig();
+ await window.cth.killPty(a.ptyId);
+ disposeTerminal(a.ptyId);
+ const command = buildSpawnCommand(cfg, model);
+ const [exe, ...args] = command.trim().split(/\s+/);
+ const hive = a.isGod
+ ? { id: a.id, name: a.name, cwd: a.cwd, isGod: true, role: 'orchestrator (god)' }
+ : a.isAssistant
+ ? { id: a.id, name: a.name, cwd: a.cwd, isAssistant: true, role: "Michael's prep assistant" }
+ : { id: a.id, name: a.name, cwd: a.cwd, role: a.description };
+ const res = await window.cth.spawnPty({ id: a.ptyId, cwd: a.cwd, command: exe, args, cols: 100, rows: 30, hive });
+ if (res.ok) updateAgent(a.id, { command: command.trim(), model, status: 'idle', action: 'restarting…' });
+ } catch { /* noop */ } finally {
+ setRestarting(null);
+ }
+ };
+
+ const dispatch = async () => {
+ const body = dispatchText.trim();
+ if (!body) return;
+ const res = await window.cth.hiveSend(
+ { to: dispatchTo, act: 'request', subject: 'Task from you', body },
+ 'human'
+ );
+ setDispatchText('');
+ setDispatchMsg(res.ok ? `sent to ${dispatchTo}` : `failed: ${res.error ?? '?'}`);
+ setTimeout(() => setDispatchMsg(null), 4000);
+ };
+
+ return (
+ <Scroll>
+ <Section title="DISPATCH">
+ <div style={{ display: 'flex', gap: 6, marginBottom: 6 }}>
+ <Select value={dispatchTo} onChange={setDispatchTo}>
+ <option value="broadcast">everyone (broadcast)</option>
+ <option value="god">Michael</option>
+ {agents.filter((a) => !a.isGod).map((a) => (
+ <option key={a.id} value={a.id}>{a.name}</option>
+ ))}
+ </Select>
+ </div>
+ <textarea
+ value={dispatchText}
+ onChange={(e) => setDispatchText(e.target.value)}
+ rows={2}
+ placeholder="Assign a task… (delivered to the chosen agent's inbox)"
+ style={textareaStyle}
+ />
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}>
+ <PixelButton variant="primary" size="sm" onClick={dispatch} disabled={!dispatchText.trim()}>
+ dispatch
+ </PixelButton>
+ {dispatchMsg && <span style={{ fontSize: 12, color: 'var(--cth-ink-500)' }}>{dispatchMsg}</span>}
+ </div>
+ </Section>
+
+ <Section title="AGENTS">
+ {agents.map((a) => (
+ <div key={a.id} style={{
+ display: 'flex', flexDirection: 'column', gap: 4,
+ padding: 6, marginBottom: 6,
+ background: 'var(--cth-paper-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
+ <div style={{
+ width: 24, height: 24, background: `var(--cth-${a.accent}-light)`,
+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-900)',
+ display: 'flex', alignItems: 'flex-end', justifyContent: 'center', overflow: 'hidden', flexShrink: 0
+ }}>
+ <SpritePortrait character={a.character} scale={1} />
+ </div>
+ <button
+ onClick={() => select(a.id)}
+ style={{
+ border: 'none', background: 'transparent', cursor: 'pointer', padding: 0,
+ fontFamily: 'var(--cth-font-ui)', fontSize: 13, color: 'var(--cth-ink-900)'
+ }}
+ >{a.name}{a.isGod ? ' (god)' : a.isAssistant ? ' (assistant)' : ''}</button>
+ <PixelBadge status={a.status} />
+ <span style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--cth-ink-500)' }}>
+ {(toolCounts[a.id] ?? 0)} tool calls
+ </span>
+ </div>
+ <div style={{ fontSize: 11, color: 'var(--cth-ink-500)', wordBreak: 'break-all' }}>{a.cwd}</div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
+ <Select
+ value={a.model ?? ''}
+ disabled={restarting === a.id}
+ onChange={(v) => restartWithModel(a, v || undefined)}
+ >
+ {AGENT_MODELS.map((m) => (
+ <option key={m.label} value={m.id ?? ''}>{m.label}</option>
+ ))}
+ </Select>
+ <span style={{ fontSize: 11, color: 'var(--cth-ink-500)' }}>
+ {restarting === a.id ? 'restarting…' : 'model (restarts agent)'}
+ </span>
+ </div>
+ </div>
+ ))}
+ </Section>
+
+ <Section title="ASSISTANT">
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
+ <span style={{ fontSize: 13, color: 'var(--cth-ink-700)' }}>Route Michael's queue through Dwight</span>
+ <button
+ onClick={() => setEnrichEnabled(!enrichEnabled)}
+ style={{
+ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 4,
+ padding: '2px 8px 1px', border: 'none', cursor: 'pointer',
+ background: enrichEnabled ? 'var(--cth-lemon)' : 'var(--cth-cream-200)',
+ boxShadow: `inset 0 0 0 1px ${enrichEnabled ? 'var(--cth-ink-900)' : 'var(--cth-ink-700)'}`,
+ fontFamily: 'var(--cth-font-ui)', fontSize: 12, color: 'var(--cth-ink-900)'
+ }}
+ ><Icon name="sparkle" /> enrich {enrichEnabled ? 'on' : 'off'}</button>
+ </div>
+ </Section>
+
+ <Section title="DIRECTORIES">
+ {repos.length === 0 && <Muted>No registered repos.</Muted>}
+ {repos.map((r) => (
+ <div key={r} style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 3 }}>
+ <span style={{ flex: 1, fontSize: 12, color: 'var(--cth-ink-700)', wordBreak: 'break-all' }}>{r}</span>
+ <button
+ onClick={() => window.cth.openTerminalAt(r)}
+ title="Open in Terminal.app"
+ style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--cth-ink-500)' }}
+ ><Icon name="terminal" /></button>
+ </div>
+ ))}
+ </Section>
+ </Scroll>
+ );
+}
+
+// ─── Memory tab ──────────────────────────────────────────────────────────────
+
+function MemoryTab({ godId }: { godId: string }) {
+ const agents = useStore((s) => s.agents);
+ const [who, setWho] = useState<string>(godId);
+ const [mem, setMem] = useState('');
+ const [query, setQuery] = useState('');
+ const [searchOut, setSearchOut] = useState('');
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ window.cth.hiveMemory(who).then(setMem).catch(() => setMem(''));
+ }, [who]);
+
+ const search = async () => {
+ if (!query.trim()) return;
+ setBusy(true);
+ try {
+ const res = await window.cth.searchMemory(query.trim());
+ setSearchOut(res.ok ? (res.output || 'Nothing matched yet.') : `Couldn't search: ${res.error}`);
+ } finally { setBusy(false); }
+ };
+
+ return (
+ <Scroll>
+ <Section title="SEMANTIC SEARCH (MemPalace)">
+ <div style={{ display: 'flex', gap: 6 }}>
+ <input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ onKeyDown={(e) => { if (e.key === 'Enter') search(); }}
+ placeholder="What does the hive know about…"
+ style={{ ...textareaStyle, height: 30 }}
+ />
+ <PixelButton variant="primary" size="sm" onClick={search} disabled={busy || !query.trim()}>
+ {busy ? '…' : 'search'}
+ </PixelButton>
+ </div>
+ {searchOut && <Pre>{searchOut}</Pre>}
+ </Section>
+
+ <Section title="MEMORY FILE">
+ <Select value={who} onChange={setWho}>
+ {agents.map((a) => (<option key={a.id} value={a.id}>{a.name}</option>))}
+ </Select>
+ <Pre>{mem || 'No memory recorded yet.'}</Pre>
+ </Section>
+ </Scroll>
+ );
+}
+
+// ─── Activity tab — log feed + board + usage ─────────────────────────────────
+
+interface LogEntry { ts?: number; kind?: string; [k: string]: unknown }
+
+function ActivityTab() {
+ const agents = useStore((s) => s.agents);
+ const toolCounts = useStore((s) => s.toolCounts);
+ const [log, setLog] = useState<LogEntry[]>([]);
+ const [board, setBoard] = useState('');
+ const timer = useRef<ReturnType<typeof setInterval> | null>(null);
+
+ useEffect(() => {
+ const refresh = async () => {
+ try { setLog((await window.cth.hiveLog(60)) as LogEntry[]); } catch { /* noop */ }
+ try { setBoard(await window.cth.hiveBoard()); } catch { /* noop */ }
+ };
+ refresh();
+ timer.current = setInterval(refresh, 3000);
+ return () => { if (timer.current) clearInterval(timer.current); };
+ }, []);
+
+ const fmt = (e: LogEntry): string => {
+ switch (e.kind) {
+ case 'spawn': return `spawned ${e.name ?? e.agentId}`;
+ case 'message': return `${e.from} → ${e.to}: ${e.subject || e.act}`;
+ case 'drain': return `${e.agentId} drained ${e.count} msg(s)`;
+ case 'escalate': return `escalated to human: ${e.subject ?? ''}`;
+ case 'approval': return `approval ${e.approve ? 'granted' : 'denied'}`;
+ default: return JSON.stringify(e);
+ }
+ };
+
+ return (
+ <Scroll>
+ <Section title="USAGE (this session)">
+ {agents.map((a) => (
+ <div key={a.id} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2 }}>
+ <span style={{ fontSize: 12, color: 'var(--cth-ink-700)', width: 90 }}>{a.name}</span>
+ <Bar value={toolCounts[a.id] ?? 0} max={Math.max(1, ...agents.map((x) => toolCounts[x.id] ?? 0))} />
+ <span style={{ fontSize: 11, color: 'var(--cth-ink-500)' }}>{toolCounts[a.id] ?? 0}</span>
+ </div>
+ ))}
+ <Muted>tool calls this session (not billed $ — interactive sessions don't expose cost)</Muted>
+ </Section>
+
+ <Section title="ACTIVITY">
+ {log.length === 0 && <Muted>Nothing yet.</Muted>}
+ {[...log].reverse().map((e, i) => (
+ <div key={i} style={{ fontSize: 12, color: 'var(--cth-ink-700)', padding: '2px 0', display: 'flex', gap: 6 }}>
+ <span style={{ color: 'var(--cth-ink-300)', flexShrink: 0 }}>{e.kind ?? '·'}</span>
+ <span style={{ minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{fmt(e)}</span>
+ </div>
+ ))}
+ </Section>
+
+ <Section title="BOARD">
+ <Pre>{board || 'The board is empty.'}</Pre>
+ </Section>
+ </Scroll>
+ );
+}
+
+// ─── Handbook tab — copyable Claude command reference ────────────────────────
+
+interface Cmd { cmd: string; kind: 'slash' | 'cli'; desc: string; usage?: string }
+interface CmdGroup { title: string; items: Cmd[] }
+
+const HANDBOOK: CmdGroup[] = [
+ {
+ title: 'SESSION',
+ items: [
+ { cmd: '/clear', kind: 'slash', desc: 'Wipe the conversation and reclaim the full context window. Start fresh.' },
+ { cmd: '/compact', kind: 'slash', desc: 'Summarize the conversation so far to free up context without losing the thread.', usage: '/compact focus on the auth refactor' },
+ { cmd: '/cost', kind: 'slash', desc: 'Show token usage and dollar cost for the current session.' },
+ { cmd: '/status', kind: 'slash', desc: 'Show account, active model, and connection status.' },
+ { cmd: 'claude -c', kind: 'cli', desc: 'Continue the most recent session in this directory.' },
+ { cmd: 'claude -r', kind: 'cli', desc: 'Resume — pick a past session to continue.' }
+ ]
+ },
+ {
+ title: 'MODELS',
+ items: [
+ { cmd: '/model', kind: 'slash', desc: 'Switch the model for this session.', usage: '/model opus · /model sonnet' },
+ { cmd: 'claude --model claude-sonnet-4-6[1m]', kind: 'cli', desc: 'Launch on a specific model. The [1m] suffix selects the 1M-token context window (used by Dwight).' }
+ ]
+ },
+ {
+ title: 'CONTEXT & MEMORY',
+ items: [
+ { cmd: '/init', kind: 'slash', desc: 'Scan the repo and generate a CLAUDE.md capturing its conventions.' },
+ { cmd: '/memory', kind: 'slash', desc: 'Open the project & user memory files for editing.' },
+ { cmd: '# ', kind: 'slash', desc: 'Quick memory: start a message with # to append a durable note to memory.', usage: '# always run prettier before committing' },
+ { cmd: 'claude --add-dir ../other-repo', kind: 'cli', desc: 'Grant the session read/write access to an extra directory.' }
+ ]
+ },
+ {
+ title: 'TOOLS & PERMISSIONS',
+ items: [
+ { cmd: '/permissions', kind: 'slash', desc: 'View and edit which tools are allowed or denied.' },
+ { cmd: '/hooks', kind: 'slash', desc: 'Configure lifecycle hooks (PreToolUse, Stop, etc.).' },
+ { cmd: 'claude --permission-mode bypassPermissions', kind: 'cli', desc: 'Run without per-tool approval prompts (this is what "auto mode" uses).' }
+ ]
+ },
+ {
+ title: 'MCP',
+ items: [
+ { cmd: '/mcp', kind: 'slash', desc: 'List/manage connected MCP servers and authenticate.' },
+ { cmd: 'claude mcp list', kind: 'cli', desc: 'List configured MCP servers.' },
+ { cmd: 'claude mcp add <name> <command>', kind: 'cli', desc: 'Register a new MCP server.' }
+ ]
+ },
+ {
+ title: 'AUTOMATION (HEADLESS)',
+ items: [
+ { cmd: 'claude -p "your prompt"', kind: 'cli', desc: 'Print mode: run one prompt non-interactively and exit.' },
+ { cmd: 'claude -p "your prompt" --output-format json', kind: 'cli', desc: 'Headless with structured JSON output (result, usage, cost) — the mechanism behind enrichment.' },
+ { cmd: 'claude -c -p "follow-up"', kind: 'cli', desc: 'Continue the last session headlessly with a follow-up prompt.' }
+ ]
+ },
+ {
+ title: 'REVIEW · GIT · AGENTS',
+ items: [
+ { cmd: '/review', kind: 'slash', desc: 'Review the current diff / PR for issues.' },
+ { cmd: '/pr-comments', kind: 'slash', desc: 'Fetch and work through PR review comments.' },
+ { cmd: '/agents', kind: 'slash', desc: 'Create and manage subagents for delegated work.' }
+ ]
+ },
+ {
+ title: 'HELP',
+ items: [
+ { cmd: '/help', kind: 'slash', desc: 'List every available slash command.' },
+ { cmd: '/doctor', kind: 'slash', desc: 'Diagnose installation / health issues.' },
+ { cmd: '/vim', kind: 'slash', desc: 'Toggle vim keybindings in the prompt box.' }
+ ]
+ }
+];
+
+function HandbookTab() {
+ const [copied, setCopied] = useState<string | null>(null);
+ const copy = async (cmd: string) => {
+ try { await window.cth.copyToClipboard(cmd); setCopied(cmd); setTimeout(() => setCopied((c) => (c === cmd ? null : c)), 1300); }
+ catch { /* noop */ }
+ };
+ return (
+ <Scroll>
+ <Muted>Click any command to copy it. Slash commands run inside Claude Code; CLI commands run in a shell.</Muted>
+ <div style={{ height: 8 }} />
+ {HANDBOOK.map((g) => (
+ <Section key={g.title} title={g.title}>
+ {g.items.map((it) => (
+ <div key={it.cmd} style={{
+ padding: 6, marginBottom: 6,
+ background: 'var(--cth-paper-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
+ <span style={{
+ fontFamily: 'var(--cth-font-display)', fontSize: 7, lineHeight: '12px',
+ padding: '1px 4px 0', flexShrink: 0,
+ background: it.kind === 'slash' ? 'var(--cth-sky-light)' : 'var(--cth-mint-light)',
+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)', color: 'var(--cth-ink-900)'
+ }}>{it.kind === 'slash' ? 'SLASH' : 'CLI'}</span>
+ <code style={{
+ flex: 1, minWidth: 0, fontFamily: 'var(--cth-font-mono)', fontSize: 13,
+ color: 'var(--cth-ink-900)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'
+ }}>{it.cmd.trim() || '#'}</code>
+ <button
+ onClick={() => copy(it.cmd)}
+ title="Copy command"
+ style={{
+ flexShrink: 0, display: 'inline-flex', alignItems: 'center', gap: 4,
+ padding: '2px 7px 1px', border: 'none', cursor: 'pointer',
+ background: copied === it.cmd ? 'var(--cth-mint)' : 'var(--cth-cream-200)',
+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',
+ fontFamily: 'var(--cth-font-ui)', fontSize: 11, color: 'var(--cth-ink-900)'
+ }}
+ >
+ <Icon name={copied === it.cmd ? 'check' : 'code'} /> {copied === it.cmd ? 'copied' : 'copy'}
+ </button>
+ </div>
+ <div style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-700)', marginTop: 4 }}>{it.desc}</div>
+ {it.usage && (
+ <div style={{
+ marginTop: 3, fontFamily: 'var(--cth-font-mono)', fontSize: 11,
+ color: 'var(--cth-ink-500)'
+ }}>e.g. {it.usage}</div>
+ )}
+ </div>
+ ))}
+ </Section>
+ ))}
+ </Scroll>
+ );
+}
+
+// ─── small shared bits ───────────────────────────────────────────────────────
+
+function Scroll({ children }: { children: React.ReactNode }) {
+ return <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: 10, background: 'var(--cth-paper-200)' }}>{children}</div>;
+}
+
+function Section({ title, children }: { title: string; children: React.ReactNode }) {
+ return (
+ <div style={{ marginBottom: 14 }}>
+ <div style={{ fontFamily: 'var(--cth-font-display)', fontSize: 9, lineHeight: '12px', color: 'var(--cth-ink-500)', marginBottom: 6 }}>{title}</div>
+ {children}
+ </div>
+ );
+}
+
+function Centered({ children }: { children: React.ReactNode }) {
+ return (
+ <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16, textAlign: 'center', color: 'var(--cth-ink-700)', fontSize: 14, background: 'var(--cth-paper-200)' }}>
+ {children}
+ </div>
+ );
+}
+
+function Muted({ children }: { children: React.ReactNode }) {
+ return <div style={{ fontSize: 12, color: 'var(--cth-ink-500)' }}>{children}</div>;
+}
+
+function Pre({ children }: { children: React.ReactNode }) {
+ return (
+ <pre style={{
+ margin: '6px 0 0', padding: 8, maxHeight: 200, overflow: 'auto',
+ background: 'var(--cth-paper-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)',
+ fontFamily: 'var(--cth-font-mono)', fontSize: 12, lineHeight: '16px',
+ color: 'var(--cth-ink-900)', whiteSpace: 'pre-wrap', wordBreak: 'break-word'
+ }}>{children}</pre>
+ );
+}
+
+function Bar({ value, max }: { value: number; max: number }) {
+ const pct = Math.round((value / max) * 100);
+ return (
+ <div style={{ flex: 1, height: 8, background: 'var(--cth-cream-200)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)' }}>
+ <div style={{ width: `${pct}%`, height: '100%', background: 'var(--cth-mint)' }} />
+ </div>
+ );
+}
+
+const textareaStyle: React.CSSProperties = {
+ flex: 1, width: '100%', resize: 'none', padding: '6px 8px',
+ background: 'var(--cth-paper-100)', border: 'none',
+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',
+ fontFamily: 'var(--cth-font-mono)', fontSize: 13, lineHeight: '17px',
+ color: 'var(--cth-ink-900)', outline: 'none', boxSizing: 'border-box'
+};
+
+function Select({ value, onChange, disabled, children }: {
+ value: string; onChange: (v: string) => void; disabled?: boolean; children: React.ReactNode;
+}) {
+ return (
+ <select
+ value={value}
+ disabled={disabled}
+ onChange={(e) => onChange(e.target.value)}
+ style={{
+ padding: '3px 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)', cursor: 'pointer'
+ }}
+ >{children}</select>
+ );
+}
diff --git a/src/renderer/src/components/FullscreenTerminal.tsx b/src/renderer/src/components/FullscreenTerminal.tsx
index 0ee2193b..a49eb458 100644
--- a/src/renderer/src/components/FullscreenTerminal.tsx
+++ b/src/renderer/src/components/FullscreenTerminal.tsx
@@ -2,6 +2,8 @@ import { useEffect } from 'react';
import { PixelBadge } from './PixelBadge';
import { PixelButton } from './PixelButton';
import { PtyTerminalView } from './PtyTerminalView';
+import { MessageQueueComposer } from './MessageQueueComposer';
+import { AssistantRoleNote } from './AssistantRoleNote';
import { disposeTerminal } from './terminalPool';
import { Icon } from './Icon';
import { SpritePortrait } from './SpritePortrait';
@@ -128,15 +130,18 @@ export function FullscreenTerminal() {
}}>
<Header agent={agent} />
- <div style={{ flex: 1, minHeight: 0, display: 'flex' }}>
- <PtyTerminalView
- key={agent.ptyId}
- ptyId={agent.ptyId}
- onStreamData={parser}
- onUserPrompt={(t) => updateAgent(agent.id, { lastPrompt: t })}
- onToggleFullscreen={() => setFullscreen(null)}
- fullscreen
- />
+ <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
+ <div style={{ flex: 1, minHeight: 0, display: 'flex' }}>
+ <PtyTerminalView
+ key={agent.ptyId}
+ ptyId={agent.ptyId}
+ onStreamData={parser}
+ onUserPrompt={(t) => updateAgent(agent.id, { lastPrompt: t })}
+ onToggleFullscreen={() => setFullscreen(null)}
+ fullscreen
+ />
+ </div>
+ {agent.isAssistant ? <AssistantRoleNote /> : <MessageQueueComposer agent={agent} />}
</div>
</div>
</div>
diff --git a/src/renderer/src/components/MessageQueueComposer.tsx b/src/renderer/src/components/MessageQueueComposer.tsx
new file mode 100644
index 00000000..e44faea4
--- /dev/null
+++ b/src/renderer/src/components/MessageQueueComposer.tsx
@@ -0,0 +1,204 @@
+import { useState, KeyboardEvent } from 'react';
+import { PixelButton } from './PixelButton';
+import { Icon } from './Icon';
+import { useStore, type Agent, type QueuedMessage } from '@/store/store';
+
+const EMPTY_QUEUE: QueuedMessage[] = [];
+
+export interface MessageQueueComposerProps {
+ agent: Agent;
+}
+
+/**
+ * Lets the user keep messaging an agent whose terminal is mid-run. Typed
+ * messages park in a per-agent queue and are submitted to the agent's Claude
+ * TUI one-by-one as soon as it goes idle (see useHive's flush loop).
+ *
+ * For Michael, a global "enrich" toggle decides routing: OFF → messages type
+ * straight into Michael; ON → they're routed through the assistant ("Dwight"),
+ * which gathers repo context and forwards an improved prompt to Michael.
+ */
+export function MessageQueueComposer({ agent }: MessageQueueComposerProps) {
+ const queue = useStore((s) => s.messageQueues[agent.id]) ?? EMPTY_QUEUE;
+ const enqueueMessage = useStore((s) => s.enqueueMessage);
+ const removeQueuedMessage = useStore((s) => s.removeQueuedMessage);
+ const clearQueue = useStore((s) => s.clearQueue);
+ const enrichEnabled = useStore((s) => s.enrichEnabled);
+ const setEnrichEnabled = useStore((s) => s.setEnrichEnabled);
+
+ const [text, setText] = useState('');
+
+ // The enrich toggle governs Michael's queue (it routes through the assistant).
+ const showEnrichToggle = !!agent.isGod;
+
+ const idle = agent.status === 'idle';
+
+ const queueIt = () => {
+ if (!text.trim()) return;
+ enqueueMessage(agent.id, text);
+ setText('');
+ };
+
+ const onKey = (e: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ queueIt();
+ }
+ };
+
+ const statusHint = queue.length === 0
+ ? null
+ : showEnrichToggle && enrichEnabled
+ ? `→ Dwight (enrich) → Michael · ${queue.length} queued`
+ : idle
+ ? `sending to ${agent.name} one-by-one…`
+ : `${agent.name} is busy — ${queue.length} queued`;
+
+ return (
+ <div style={{
+ flexShrink: 0,
+ borderTop: '1px solid var(--cth-ink-700)',
+ background: 'var(--cth-cream-100)',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 6,
+ padding: 8
+ }}>
+ {/* Header: label, count, status, enrich toggle (Michael only), clear-all */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
+ <span style={{
+ fontFamily: 'var(--cth-font-display)',
+ fontSize: 9, lineHeight: '12px',
+ color: 'var(--cth-ink-700)'
+ }}>QUEUE</span>
+ {queue.length > 0 && (
+ <span style={{
+ fontSize: 11, padding: '1px 6px 0',
+ background: 'var(--cth-cream-200)',
+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',
+ fontFamily: 'var(--cth-font-ui)', color: 'var(--cth-ink-900)'
+ }}>{queue.length}</span>
+ )}
+ {statusHint && (
+ <span style={{
+ fontSize: 12,
+ color: showEnrichToggle && enrichEnabled ? 'var(--cth-ink-900)' : idle ? 'var(--cth-ink-700)' : 'var(--cth-ink-500)',
+ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'
+ }}>{statusHint}</span>
+ )}
+ {queue.length > 1 && (
+ <button
+ onClick={() => clearQueue(agent.id)}
+ title="Clear all queued messages"
+ style={{
+ marginLeft: 'auto',
+ border: 'none', background: 'transparent', cursor: 'pointer',
+ fontFamily: 'var(--cth-font-ui)', fontSize: 12,
+ color: 'var(--cth-ink-500)'
+ }}
+ >clear all</button>
+ )}
+ </div>
+
+ {/* Pending list */}
+ {queue.length > 0 && (
+ <div style={{
+ display: 'flex', flexDirection: 'column', gap: 4,
+ maxHeight: 132, overflowY: 'auto'
+ }}>
+ {queue.map((m, i) => (
+ <div key={m.id} style={{
+ display: 'flex', alignItems: 'flex-start', gap: 6,
+ padding: '4px 6px',
+ background: 'var(--cth-paper-100)',
+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)'
+ }}>
+ <span style={{
+ fontFamily: 'var(--cth-font-mono)', fontSize: 12,
+ color: 'var(--cth-ink-500)', lineHeight: '18px', flexShrink: 0
+ }}>{i + 1}.</span>
+ <div
+ title={m.text}
+ style={{
+ flex: 1, minWidth: 0,
+ fontSize: 13, lineHeight: '18px', color: 'var(--cth-ink-900)',
+ display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
+ overflow: 'hidden', whiteSpace: 'pre-wrap', wordBreak: 'break-word'
+ }}
+ >{m.text}</div>
+ <button
+ onClick={() => removeQueuedMessage(agent.id, m.id)}
+ title="Remove from queue"
+ style={{
+ flexShrink: 0, border: 'none', background: 'transparent',
+ cursor: 'pointer', color: 'var(--cth-ink-500)', padding: 0,
+ display: 'inline-flex', alignItems: 'center'
+ }}
+ >
+ <Icon name="x" />
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* Composer. Michael gets a right-hand control column with the enrich
+ toggle stacked directly above send; other agents get a plain send. */}
+ <div style={{ display: 'flex', gap: 6, alignItems: showEnrichToggle ? 'stretch' : 'flex-end' }}>
+ <textarea
+ value={text}
+ onChange={(e) => setText(e.target.value)}
+ onKeyDown={onKey}
+ rows={2}
+ placeholder={idle ? `Message ${agent.name}` : `${agent.name} is busy — queue a message`}
+ style={{
+ flex: 1,
+ resize: 'none',
+ padding: '6px 8px',
+ background: 'var(--cth-paper-100)',
+ border: 'none',
+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',
+ fontFamily: 'var(--cth-font-mono)',
+ fontSize: 14, lineHeight: '18px',
+ color: 'var(--cth-ink-900)',
+ outline: 'none'
+ }}
+ />
+ {showEnrichToggle ? (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 5, width: 120, flexShrink: 0 }}>
+ <button
+ onClick={() => setEnrichEnabled(!enrichEnabled)}
+ title={enrichEnabled
+ ? 'Enrich ON — messages route through Dwight (adds repo context) before Michael'
+ : 'Enrich OFF — messages go straight to Michael'}
+ style={{
+ height: 30, width: '100%',
+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 5,
+ border: 'none', cursor: 'pointer',
+ background: enrichEnabled ? 'var(--cth-lemon)' : 'var(--cth-cream-100)',
+ color: 'var(--cth-ink-900)',
+ boxShadow: enrichEnabled
+ ? 'inset 0 0 0 2px var(--cth-ink-900), 0 2px 0 var(--cth-ink-900)'
+ : 'inset 0 0 0 2px var(--cth-ink-700), 0 2px 0 var(--cth-ink-700)',
+ fontFamily: 'var(--cth-font-ui)', fontSize: 13
+ }}
+ >
+ <Icon name="sparkle" /> enrich {enrichEnabled ? 'on' : 'off'}
+ </button>
+ <PixelButton variant="primary" size="md" fullWidth onClick={queueIt} disabled={!text.trim()}>
+ <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center', justifyContent: 'center' }}>
+ send <Icon name="arrow-right" />
+ </span>
+ </PixelButton>
+ </div>
+ ) : (
+ <PixelButton variant="primary" size="md" onClick={queueIt} disabled={!text.trim()}>
+ <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}>
+ send <Icon name="arrow-right" />
+ </span>
+ </PixelButton>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/src/renderer/src/components/PtyTerminalView.tsx b/src/renderer/src/components/PtyTerminalView.tsx
index fe28d0d4..cc7eddfa 100644
--- a/src/renderer/src/components/PtyTerminalView.tsx
+++ b/src/renderer/src/components/PtyTerminalView.tsx
@@ -141,23 +141,30 @@ export function PtyTerminalView({ ptyId, onStreamData, onUserPrompt, onToggleFul
entry.onData = (chunk) => onStreamDataRef.current?.(chunk);
entry.onPrompt = (text) => onUserPromptRef.current?.(text);
- const tryFit = () => {
+ // `scrollToEnd` is true only for the initial attach (switching agents /
+ // toggling fullscreen) so we land on the most recent output. Re-parenting
+ // the pooled terminal resets its viewport to the top otherwise. Later
+ // resize-driven fits pass false so they don't yank a user who has scrolled
+ // up to read history back down to the bottom.
+ const tryFit = (scrollToEnd = false) => {
try {
entry.fit.fit();
window.cth.resizePty(ptyId, entry.term.cols, entry.term.rows);
entry.term.refresh(0, Math.max(0, entry.term.rows - 1));
+ if (scrollToEnd) entry.term.scrollToBottom();
} catch { /* host may not be sized yet */ }
};
- // Fit once layout has settled and again once the web font has loaded.
- requestAnimationFrame(() => requestAnimationFrame(tryFit));
- const retries = [setTimeout(tryFit, 60), setTimeout(tryFit, 240)];
+ // Fit once layout has settled and again once the web font has loaded —
+ // these are the initial-attach fits, so snap to the bottom.
+ requestAnimationFrame(() => requestAnimationFrame(() => tryFit(true)));
+ const retries = [setTimeout(() => tryFit(true), 60), setTimeout(() => tryFit(true), 240)];
if (typeof document !== 'undefined' && document.fonts?.ready) {
- document.fonts.ready.then(tryFit).catch(() => { /* noop */ });
+ document.fonts.ready.then(() => tryFit(true)).catch(() => { /* noop */ });
}
- const ro = new ResizeObserver(tryFit);
+ const ro = new ResizeObserver(() => tryFit(false));
ro.observe(container);
- const onWinResize = () => tryFit();
+ const onWinResize = () => tryFit(false);
window.addEventListener('resize', onWinResize);
return () => {
diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.ts
index 154419b7..7cc08dba 100644
--- a/src/renderer/src/hooks/useHive.ts
+++ b/src/renderer/src/hooks/useHive.ts
@@ -1,9 +1,11 @@
import { useEffect, useRef } from 'react';
import { useStore, type Agent, type StationKind, type ToolKind } from '@/store/store';
-import { buildSpawnCommand, type HarnessConfig } from '@/store/config';
+import { buildSpawnCommand, ASSISTANT_MODEL, type HarnessConfig } from '@/store/config';
const GOD_ID = 'god';
const GOD_PTY = `pty-${GOD_ID}`;
+const ASSISTANT_ID = 'assistant';
+const ASSISTANT_PTY = `pty-${ASSISTANT_ID}`;
/**
* Type a line into an agent's Claude Code TUI and actually submit it.
@@ -20,6 +22,17 @@ async function submitToPty(ptyId: string, text: string): Promise<void> {
await window.cth.writePty(ptyId, '\r');
}
+/** Wrap a user message as an enrich task for the assistant. The assistant's
+ * system prompt has the full instructions; this just frames the one task. */
+function enrichTaskPrompt(text: string): string {
+ return [
+ `ENRICH TASK: ${text}`,
+ '',
+ '(Identify the relevant project, cd in, gather READ-ONLY context, then send the improved,',
+ 'self-contained prompt to Michael via an outbox message with "to":"god". Do not do the task yourself.)'
+ ].join('\n');
+}
+
/** Tool name → where the avatar walks + what it carries. */
const TOOL_STATION: Record<string, { station: StationKind; carry?: ToolKind }> = {
Read: { station: 'shelf', carry: 'Read' },
@@ -41,7 +54,22 @@ const TOOL_STATION: Record<string, { station: StationKind; carry?: ToolKind }> =
* doesn't stall while an agent sits at its prompt.
*/
export function useHive(config: HarnessConfig | null): void {
- const nudged = useRef<Record<string, number>>({});
+ // Per-agent dedup key for the inbox-wake nudge: the newest inbox message id we
+ // last nudged about. Keyed by id (not count) so an oscillating count after a
+ // drain doesn't re-nudge for the same message set.
+ const nudged = useRef<Record<string, string>>({});
+ // Per-agent timestamp of the last queued-message we submitted. Guards against
+ // re-sending the next message before the agent's hooks have flipped it to
+ // 'working' (there's a short window where it still reads 'idle' right after we
+ // type into it). One message per cooldown keeps delivery strictly one-by-one.
+ const lastFlush = useRef<Record<string, number>>({});
+ // In-flight spawn guards so a re-render / StrictMode double-mount can't spawn
+ // Michael or the assistant twice (the window between the listPtys check and
+ // the spawnPty call is otherwise racy).
+ const godSpawning = useRef(false);
+ const assistantSpawning = useRef(false);
+ // Reactive so the assistant bootstrap (effect #1b) re-runs once Michael is ready.
+ const godStatus = useStore((s) => s.godStatus);
// 1) Bootstrap the god agent (source of truth = live PTYs, to dodge restarts).
useEffect(() => {
@@ -55,10 +83,12 @@ export function useHive(config: HarnessConfig | null): void {
if (!cancelled) useStore.getState().setGodStatus('ready');
return;
}
- if (cancelled) return;
+ // Synchronous guard (no await between check and set) → exactly one spawn.
+ if (cancelled || godSpawning.current) return;
+ godSpawning.current = true;
useStore.getState().removeAgent(GOD_ID); // clear any stale restored entry
- const command = buildSpawnCommand(config);
+ const command = buildSpawnCommand(config, config.defaultModel);
const [exe, ...args] = command.trim().split(/\s+/);
const res = await window.cth.spawnPty({
id: GOD_PTY,
@@ -69,8 +99,8 @@ export function useHive(config: HarnessConfig | null): void {
rows: 30,
hive: { id: GOD_ID, name: 'Michael', cwd: config.harnessHome!, isGod: true, role: 'orchestrator (god)' }
});
- if (cancelled) return;
- if (!res.ok) { useStore.getState().setGodStatus('failed'); return; }
+ if (cancelled) { godSpawning.current = false; return; }
+ if (!res.ok) { godSpawning.current = false; useStore.getState().setGodStatus('failed'); return; }
const god: Agent = {
id: GOD_ID,
name: 'Michael',
@@ -86,6 +116,7 @@ export function useHive(config: HarnessConfig | null): void {
currentStation: 'desk',
ptyId: GOD_PTY,
command: command.trim(),
+ model: config.defaultModel,
isGod: true,
recentTextTs: Date.now()
};
@@ -95,6 +126,60 @@ export function useHive(config: HarnessConfig | null): void {
return () => { cancelled = true; clearTimeout(t); };
}, [config?.onboardingComplete, config?.harnessHome]);
+ // 1b) Bootstrap Michael's prep assistant ("Dwight") — only after Michael is
+ // ready, and only once. Same live-PTY idempotency + spawn-guard as #1.
+ useEffect(() => {
+ if (!config?.onboardingComplete || !config.harnessHome) return;
+ if (godStatus !== 'ready') return;
+ let cancelled = false;
+ const t = setTimeout(async () => {
+ if (cancelled) return;
+ const live = await window.cth.listPtys().catch(() => []);
+ if (live.some((p) => p.id === ASSISTANT_PTY)) return; // already running
+ if (cancelled || assistantSpawning.current) return;
+ assistantSpawning.current = true;
+ useStore.getState().removeAgent(ASSISTANT_ID); // clear any stale restored entry
+
+ const command = buildSpawnCommand(config, ASSISTANT_MODEL);
+ const [exe, ...args] = command.trim().split(/\s+/);
+ const res = await window.cth.spawnPty({
+ id: ASSISTANT_PTY,
+ cwd: config.harnessHome!,
+ command: exe,
+ args,
+ cols: 100,
+ rows: 30,
+ hive: { id: ASSISTANT_ID, name: 'Dwight', cwd: config.harnessHome!, isAssistant: true, role: "Michael's prep assistant" }
+ });
+ if (cancelled || !res.ok) { assistantSpawning.current = false; return; }
+ const assistant: Agent = {
+ id: ASSISTANT_ID,
+ name: 'Dwight',
+ character: 'dwight',
+ accent: 'sky',
+ description: "assistant — enriches prompts with repo context, forwards them to Michael",
+ project: 'hive',
+ tmuxTarget: '',
+ cwd: config.harnessHome!,
+ status: 'idle',
+ action: 'standing by',
+ progress: 0,
+ currentStation: 'desk',
+ ptyId: ASSISTANT_PTY,
+ command: command.trim(),
+ model: ASSISTANT_MODEL,
+ isAssistant: true,
+ recentTextTs: Date.now()
+ };
+ // addAgent auto-selects the new agent; restore the prior selection so the
+ // assistant booting in the background doesn't yank focus off Michael.
+ const prevSel = useStore.getState().selectedId;
+ useStore.getState().addAgent(assistant);
+ useStore.getState().select(prevSel ?? GOD_ID);
+ }, 400);
+ return () => { cancelled = true; clearTimeout(t); };
+ }, [config?.onboardingComplete, config?.harnessHome, godStatus]);
+
// 2) Drive avatars from real hook events emitted by each agent's shim.
useEffect(() => {
return window.cth.onHiveHookEvent((e) => {
@@ -107,12 +192,19 @@ export function useHive(config: HarnessConfig | null): void {
if (e.event === 'PreToolUse' && e.tool) {
const m = TOOL_STATION[e.tool] ?? { station: 'desk' as StationKind };
updateAgent(e.agentId, { status: 'working', currentStation: m.station, carrying: m.carry, action: `using ${e.tool}` });
+ useStore.getState().bumpToolCount(e.agentId); // usage proxy for the command center
} else if (e.event === 'PostToolUse' || e.event === 'UserPromptSubmit') {
// A turn is in progress (prompt submitted / tool just finished) — keep
// it working so it doesn't flicker idle between tool calls.
updateAgent(e.agentId, { status: 'working' });
} else if (e.event === 'Stop' || e.event === 'SubagentStop') {
- updateAgent(e.agentId, { status: 'idle', action: 'idle', carrying: undefined });
+ // A blocked Stop means the agent is being re-engaged to process its
+ // inbox — it's NOT idle, so keep it working until it genuinely stops.
+ if (e.blocked) {
+ updateAgent(e.agentId, { status: 'working', action: 'reading inbox', carrying: undefined });
+ } else {
+ updateAgent(e.agentId, { status: 'idle', action: 'idle', carrying: undefined });
+ }
} else if (e.event === 'Notification') {
// Claude Code fires Notification for two very different situations:
// 1. it genuinely needs the human (a permission / approval prompt), or
@@ -142,28 +234,92 @@ export function useHive(config: HarnessConfig | null): void {
});
}, []);
- // 3) Wake idle agents holding unread inbox messages.
+ // 3) Wake idle agents holding unread inbox messages. The assistant is
+ // send-only (it never receives inbox mail), so it's excluded.
useEffect(() => {
if (!config?.onboardingComplete) return;
const iv = setInterval(async () => {
const agents = useStore.getState().agents.filter(
- (a) => a.ptyId && (a.status === 'idle' || a.status === 'waiting')
+ (a) => a.ptyId && !a.isAssistant && (a.status === 'idle' || a.status === 'waiting')
);
for (const a of agents) {
try {
- const count = (await window.cth.hiveInbox(a.id)).length;
- if (count > 0 && nudged.current[a.id] !== count) {
- nudged.current[a.id] = count;
+ 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.
+ const newest = inbox.length
+ ? 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.'
);
- } else if (count === 0) {
- nudged.current[a.id] = 0;
+ } else if (!newest) {
+ nudged.current[a.id] = '';
}
} catch { /* ignore */ }
}
}, 4000);
return () => clearInterval(iv);
}, [config?.onboardingComplete]);
+
+ // 4) Drain each agent's queued messages to its terminal, one at a time, the
+ // moment the agent goes idle. This is what lets the user keep sending
+ // messages while the agent's "cloud terminal" is mid-run: the messages
+ // park in the store and get typed in (and submitted) as soon as it's free.
+ useEffect(() => {
+ if (!config?.onboardingComplete) return;
+ const FLUSH_COOLDOWN_MS = 4500;
+
+ // 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?: (t: string) => string): boolean => {
+ const { messageQueues, removeQueuedMessage } = useStore.getState();
+ const next = messageQueues[srcId]?.[0];
+ if (!next || !target?.ptyId || target.status !== 'idle') return false;
+ const now = Date.now();
+ if (now - (lastFlush.current[target.id] ?? 0) < FLUSH_COOLDOWN_MS) return false;
+ lastFlush.current[target.id] = now;
+ // Remove first so a burst of store updates can't double-send the same one.
+ removeQueuedMessage(srcId, next.id);
+ submitToPty(target.ptyId, wrap ? wrap(next.text) : next.text).catch(() => { /* pty may have died */ });
+ return true;
+ };
+
+ const flush = () => {
+ const { agents, messageQueues, enrichEnabled } = useStore.getState();
+ const byId = (id: string) => agents.find((a) => a.id === id);
+
+ // Sub-agents (and the assistant's own direct queue): flush verbatim into
+ // their own terminal. Michael's queue is handled specially below.
+ for (const a of agents) {
+ if (a.id === GOD_ID) continue;
+ if (!a.ptyId || a.status !== 'idle') continue;
+ if (!messageQueues[a.id]?.length) continue;
+ dispatch(a.id, a);
+ }
+
+ // Michael's queue: enrich OFF → straight to Michael; enrich ON → wrap as an
+ // ENRICH TASK and route to the assistant, which forwards to Michael's inbox.
+ if (messageQueues[GOD_ID]?.length) {
+ if (enrichEnabled) dispatch(GOD_ID, byId(ASSISTANT_ID), enrichTaskPrompt);
+ else dispatch(GOD_ID, byId(GOD_ID));
+ }
+ };
+
+ // Run on every store change (status flips, new queue items) — debounced so a
+ // burst of pty-stream updates coalesces — plus a periodic backstop.
+ let debounce: ReturnType<typeof setTimeout> | null = null;
+ const schedule = () => {
+ if (debounce) return;
+ debounce = setTimeout(() => { debounce = null; flush(); }, 200);
+ };
+ const unsub = useStore.subscribe(schedule);
+ const iv = setInterval(flush, 3000);
+ schedule();
+ return () => { unsub(); if (debounce) clearTimeout(debounce); clearInterval(iv); };
+ }, [config?.onboardingComplete]);
}
diff --git a/src/renderer/src/scene/office/OfficeFloor.tsx b/src/renderer/src/scene/office/OfficeFloor.tsx
index 77b26959..0b38d4a9 100644
--- a/src/renderer/src/scene/office/OfficeFloor.tsx
+++ b/src/renderer/src/scene/office/OfficeFloor.tsx
@@ -217,12 +217,16 @@ export function OfficeFloor() {
if (waitTiles.length === 0) waitTiles.push(entrance);
// Seat 0 is desk-ceo — "Michael's room" — reserved for the god agent.
- // Everyone else claims from seat 1 onward so the corner office stays the
- // orchestrator's throne even if it spawns after other agents.
+ // Seat 1 is reserved for his prep assistant ("Dwight") so it always sits in
+ // the desk next to him. Everyone else claims from seat 2 onward.
const GOD_SEAT = 0;
+ const ASSISTANT_SEAT = 1;
const claimSeat = (agent: Agent): number | null => {
if (agent.isGod) { seatClaims.add(GOD_SEAT); return GOD_SEAT; }
- for (let i = 1; i < seatTiles.length; i++) {
+ if (agent.isAssistant && seatTiles.length > ASSISTANT_SEAT) {
+ seatClaims.add(ASSISTANT_SEAT); return ASSISTANT_SEAT;
+ }
+ for (let i = 2; i < seatTiles.length; i++) {
if (!seatClaims.has(i)) { seatClaims.add(i); return i; }
}
return null;
diff --git a/src/renderer/src/store/config.ts b/src/renderer/src/store/config.ts
index b71b9a65..5383c647 100644
--- a/src/renderer/src/store/config.ts
+++ b/src/renderer/src/store/config.ts
@@ -7,12 +7,41 @@ export interface HarnessConfig {
registeredRepos: string[];
autoMode: boolean;
defaultCommand: string;
+ /** Default model for newly spawned agents (e.g. 'claude-sonnet-4-6[1m]'); unset = CLI default. */
+ defaultModel?: string;
semanticMemory: boolean;
embeddingModel: 'minilm' | 'embeddinggemma';
}
-/** Build the command line to feed into spawnPty, honoring autoMode. */
-export function buildSpawnCommand(config: Pick<HarnessConfig, 'defaultCommand' | 'autoMode'>): string {
+/** The Sonnet model with the 1M-token context window — used for Michael's prep
+ * assistant (cheap, large-context context gathering). Mirrors ASSISTANT_MODEL
+ * in src/main/assistant.ts; keep the two in sync. */
+export const ASSISTANT_MODEL = 'claude-sonnet-4-6[1m]';
+
+export interface ModelOption {
+ /** undefined = use the CLI default (no --model flag) */
+ id?: string;
+ label: string;
+}
+
+/** The models offered in the "add agent" picker and the per-agent selector.
+ * `[1m]` selects the 1M-token context window variant. */
+export const AGENT_MODELS: ModelOption[] = [
+ { id: undefined, label: 'default' },
+ { id: 'claude-opus-4-8', label: 'Opus 4.8' },
+ { id: 'claude-opus-4-8[1m]', label: 'Opus 4.8 · 1M' },
+ { id: 'claude-sonnet-4-6', label: 'Sonnet 4.6' },
+ { id: ASSISTANT_MODEL, label: 'Sonnet 4.6 · 1M' },
+ { id: 'claude-haiku-4-5-20251001', label: 'Haiku 4.5' }
+];
+
+/** Build the command line to feed into spawnPty, honoring autoMode and an
+ * optional per-agent model override (injected as `--model <model>`). */
+export function buildSpawnCommand(
+ config: Pick<HarnessConfig, 'defaultCommand' | 'autoMode'>,
+ model?: string
+): string {
const base = config.defaultCommand || 'claude';
- return config.autoMode ? `${base} --permission-mode bypassPermissions` : base;
+ const withModel = model ? `${base} --model ${model}` : base;
+ return config.autoMode ? `${withModel} --permission-mode bypassPermissions` : withModel;
}
diff --git a/src/renderer/src/store/store.ts b/src/renderer/src/store/store.ts
index f4161467..3179674d 100644
--- a/src/renderer/src/store/store.ts
+++ b/src/renderer/src/store/store.ts
@@ -50,11 +50,17 @@ export interface Agent {
ptyId?: string;
/** the command being run in the PTY (e.g. 'claude') */
command?: string;
+ /** the model this agent runs on (e.g. 'claude-sonnet-4-6[1m]'); drives the
+ * model selector + the --model arg used when (re)spawning the agent */
+ model?: string;
/** the last prompt the user submitted to this agent in Claude Code —
* shown on the floor as a card above the seated avatar */
lastPrompt?: string;
/** the orchestrator ("god") agent — seated in Michael's room, runs the floor */
isGod?: boolean;
+ /** Michael's prep assistant ("Dwight") — enriches prompts and forwards them to
+ * Michael via the hive. Send-only: never receives inbox/broadcast mail. */
+ isAssistant?: boolean;
}
export interface FeedEntry {
@@ -63,6 +69,17 @@ export interface FeedEntry {
ts: number;
}
+/** A message the user has parked for an agent while its terminal was busy.
+ * Queued messages are drained one at a time when the agent next goes idle (see
+ * useHive's flush loop). For Michael's queue the enrich toggle decides whether
+ * each one is typed into Michael directly or routed through the assistant. */
+export interface QueuedMessage {
+ id: string;
+ text: string;
+ /** epoch ms the message was queued — drives ordering and the "queued 2m ago" hint */
+ ts: number;
+}
+
export type SidebarTab = 'terminal' | 'files';
/** Lifecycle of the god agent ("Michael") bootstrap on launch.
@@ -81,12 +98,31 @@ interface State {
sidebarWidth: number;
sidebarTab: SidebarTab;
godStatus: GodStatus;
+ /** Per-agent outgoing message queue (agent id → messages awaiting delivery).
+ * Lets the user keep "talking" to a busy agent: messages park here and are
+ * drained to the terminal one-by-one once the agent is free. */
+ messageQueues: Record<string, QueuedMessage[]>;
+ /** Global toggle: when on, messages queued for Michael are routed through the
+ * assistant ("Dwight") to be enriched with context before reaching Michael;
+ * when off, they're typed straight into Michael. */
+ enrichEnabled: boolean;
+ setEnrichEnabled: (on: boolean) => void;
+ /** Per-agent tool-call count this session — a lightweight activity/usage proxy
+ * shown in the command center (interactive sessions don't expose billed $). */
+ toolCounts: Record<string, number>;
+ bumpToolCount: (id: string) => void;
setGodStatus: (status: GodStatus) => void;
select: (id: string) => void;
updateAgent: (id: string, patch: Partial<Agent>) => void;
pushFeed: (id: string, line: string) => void;
addAgent: (agent: Agent) => void;
removeAgent: (id: string) => void;
+ /** Park a message for an agent. Returns nothing; the flush loop delivers it. */
+ enqueueMessage: (agentId: string, text: string) => void;
+ /** Drop a single queued message (user removed it, or it was just delivered). */
+ removeQueuedMessage: (agentId: string, messageId: string) => void;
+ /** Clear an agent's entire pending queue. */
+ clearQueue: (agentId: string) => void;
setAddAgentOpen: (open: boolean) => void;
setFullscreen: (id: string | null) => void;
setFullscreenFile: (path: string | null) => void;
@@ -102,6 +138,8 @@ const LS_SIDEBAR_WIDTH = 'cth.sidebarWidth';
const LS_SIDEBAR_TAB = 'cth.sidebarTab';
const LS_AGENTS = 'cth.agents';
const LS_SELECTED = 'cth.selectedId';
+const LS_QUEUES = 'cth.messageQueues';
+const LS_ENRICH = 'cth.enrichEnabled';
// Fields that are large or transient — not worth persisting across reloads.
type PersistedAgent = Omit<Agent, 'recentAssistantText' | 'recentTextTs' | 'blockReason'>;
@@ -137,6 +175,34 @@ function loadPersistedAgents(): Agent[] {
}
}
+function persistQueues(queues: Record<string, QueuedMessage[]>): void {
+ try {
+ // Only keep non-empty queues so the key stays small.
+ const slim: Record<string, QueuedMessage[]> = {};
+ for (const [id, q] of Object.entries(queues)) if (q.length) slim[id] = q;
+ window.localStorage.setItem(LS_QUEUES, JSON.stringify(slim));
+ } catch { /* noop */ }
+}
+
+function loadPersistedQueues(): Record<string, QueuedMessage[]> {
+ try {
+ const raw = window.localStorage.getItem(LS_QUEUES);
+ if (!raw) return {};
+ const parsed = JSON.parse(raw) as Record<string, QueuedMessage[]>;
+ if (!parsed || typeof parsed !== 'object') return {};
+ // Defensively keep only well-formed entries.
+ const out: Record<string, QueuedMessage[]> = {};
+ for (const [id, q] of Object.entries(parsed)) {
+ if (Array.isArray(q)) {
+ out[id] = q.filter((m) => m && typeof m.text === 'string' && typeof m.id === 'string');
+ }
+ }
+ return out;
+ } catch {
+ return {};
+ }
+}
+
function loadPersistedSelectedId(agents: Agent[]): string | null {
try {
const id = window.localStorage.getItem(LS_SELECTED);
@@ -163,6 +229,18 @@ const initialSidebarTab: SidebarTab = (() => {
const initialAgents = loadPersistedAgents();
const initialSelectedId = loadPersistedSelectedId(initialAgents);
+const initialQueues = loadPersistedQueues();
+const initialEnrichEnabled: boolean = (() => {
+ try { return window.localStorage.getItem(LS_ENRICH) === '1'; } catch { return false; }
+})();
+
+let queuedSeq = 0;
+/** Process-unique id for a queued message (timestamp + counter avoids collisions
+ * when several are queued within the same millisecond). */
+function newQueuedId(): string {
+ queuedSeq += 1;
+ return `q-${Date.now()}-${queuedSeq}`;
+}
export const useStore = create<State>((set) => ({
agents: initialAgents,
@@ -174,6 +252,15 @@ export const useStore = create<State>((set) => ({
sidebarWidth: initialSidebarWidth,
sidebarTab: initialSidebarTab,
godStatus: 'booting',
+ messageQueues: initialQueues,
+ enrichEnabled: initialEnrichEnabled,
+ setEnrichEnabled: (on) => {
+ try { window.localStorage.setItem(LS_ENRICH, on ? '1' : '0'); } catch { /* noop */ }
+ set({ enrichEnabled: on });
+ },
+ toolCounts: {},
+ bumpToolCount: (id) =>
+ set((s) => ({ toolCounts: { ...s.toolCounts, [id]: (s.toolCounts[id] ?? 0) + 1 } })),
setGodStatus: (status) => set({ godStatus: status }),
select: (id) => set((s) => { persistAgents(s.agents, id); return { selectedId: id }; }),
updateAgent: (id, patch) =>
@@ -194,9 +281,36 @@ export const useStore = create<State>((set) => ({
set((s) => {
const agents = s.agents.filter(a => a.id !== id);
const { [id]: _gone, ...feeds } = s.feeds;
+ const { [id]: _queueGone, ...messageQueues } = s.messageQueues;
const selectedId = s.selectedId === id ? (agents[0]?.id ?? null) : s.selectedId;
persistAgents(agents, selectedId);
- return { agents, feeds, selectedId };
+ if (_queueGone) persistQueues(messageQueues);
+ return { agents, feeds, selectedId, messageQueues };
+ }),
+ enqueueMessage: (agentId, text) =>
+ set((s) => {
+ const trimmed = text.trim();
+ if (!trimmed) return s;
+ const msg: QueuedMessage = { id: newQueuedId(), text: trimmed, ts: Date.now() };
+ const messageQueues = { ...s.messageQueues, [agentId]: [...(s.messageQueues[agentId] ?? []), msg] };
+ persistQueues(messageQueues);
+ return { messageQueues };
+ }),
+ removeQueuedMessage: (agentId, messageId) =>
+ set((s) => {
+ const current = s.messageQueues[agentId];
+ if (!current) return s;
+ const next = current.filter((m) => m.id !== messageId);
+ const messageQueues = { ...s.messageQueues, [agentId]: next };
+ persistQueues(messageQueues);
+ return { messageQueues };
+ }),
+ clearQueue: (agentId) =>
+ set((s) => {
+ if (!s.messageQueues[agentId]?.length) return s;
+ const messageQueues = { ...s.messageQueues, [agentId]: [] };
+ persistQueues(messageQueues);
+ return { messageQueues };
}),
reconcileWithLivePtys: (livePtyIds) =>
set((s) => {