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

fix(terminal): stop the blank pane and the wedged message queue

Vyapak Goyal460153ac1645
diff --git a/src/main/hive.ts b/src/main/hive.ts
index ff2551fa..34083766 100644
--- a/src/main/hive.ts
+++ b/src/main/hive.ts
@@ -436,6 +436,42 @@ export class HiveManager {
} catch { /* best-effort — never crash a lifecycle handler */ }
}
+ /**
+ * Rename an agent, keeping its id. The id is the identity everything else is
+ * keyed on — workspace directory, inbox, memory.md, task assignees — so a
+ * rename is purely cosmetic and nothing has to be migrated. Only the registry
+ * (which feeds the roster other agents read) needs updating, plus the identity
+ * card so the agent itself knows what it is now called. Best-effort; returns
+ * whether anything changed.
+ */
+ rename(id: string, name: string): boolean {
+ const root = this.root();
+ if (!root) return false;
+ const next = name.trim();
+ if (!next) return false;
+ try {
+ const reg = this.registry();
+ const agent = reg.agents[id];
+ if (!agent || agent.name === next) return false;
+ const previous = agent.name;
+ agent.name = next;
+ agent.lastSeen = Date.now();
+ this.writeJson(join(root, 'registry.json'), reg);
+ // Refresh the identity card so the agent's own prompt stops calling it by
+ // the old name. Written on every spawn anyway, but a rename shouldn't have
+ // to wait for a restart to take effect.
+ try {
+ const dir = join(root, 'agents', id);
+ if (existsSync(dir)) writeFileSync(join(dir, 'identity.md'), this.identityText(agent), 'utf8');
+ } catch { /* identity refresh is best-effort */ }
+ this.appendLog({ kind: 'rename', agentId: id, name: next, previous });
+ this.commit(`hive: rename ${id} → ${next}`);
+ return true;
+ } catch {
+ return false; // best-effort — never crash a lifecycle handler
+ }
+ }
+
/**
* Persist the agent's Claude Code session_id (Lane A #6.6a). Captured from hook
* payloads; written only when it actually changes (a new session), so this is a
diff --git a/src/main/index.ts b/src/main/index.ts
index 36eac6eb..55f007a0 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1987,6 +1987,20 @@ ipcMain.handle('hive:setArchived', (_evt, id: unknown, archived: unknown) => {
return { ok: true };
});
+// Rename an agent. Cosmetic only — the agent id stays put, so its workspace,
+// inbox, memory and any task assigned to it are untouched.
+ipcMain.handle('hive:rename', (_evt, id: unknown, name: unknown) => {
+ if (typeof id !== 'string' || typeof name !== 'string') {
+ return { ok: false, error: 'invalid id or name' };
+ }
+ const next = name.trim();
+ if (!next) return { ok: false, error: 'name cannot be empty' };
+ if (next.length > 40) return { ok: false, error: 'name is too long (max 40)' };
+ if (!hive.enabled()) return { ok: false, error: 'hive disabled (no harnessHome)' };
+ hive.rename(id, next);
+ return { ok: true };
+});
+
// ─── 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/preload/index.ts b/src/preload/index.ts
index ff832f6a..69e42790 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -719,6 +719,10 @@ const api = {
* archives it automatically via pty:kill; this is the explicit primitive. */
hiveSetArchived: (id: string, archived: boolean): Promise<{ ok: boolean; error?: string }> =>
ipcRenderer.invoke('hive:setArchived', id, archived),
+ /** Rename an agent in the hive registry. The agent id is unchanged, so its
+ * workspace, inbox, memory and task assignments all follow the rename. */
+ hiveRename: (id: string, name: string): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('hive:rename', id, name),
// ─── Slack integration (Slack message → Michael's queue) ─────────────────────
/** Register a listener for inbound Slack messages; returns an unsubscribe fn.
diff --git a/src/renderer/src/components/CommandCenterPanel.tsx b/src/renderer/src/components/CommandCenterPanel.tsx
index e7af8496..2fbc439c 100644
--- a/src/renderer/src/components/CommandCenterPanel.tsx
+++ b/src/renderer/src/components/CommandCenterPanel.tsx
@@ -256,7 +256,16 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
const restartWithModel = async (
a: Agent,
model: string | undefined,
- opts: { resume?: boolean; provider?: AgentProvider } = {}
+ opts: {
+ resume?: boolean;
+ provider?: AgentProvider;
+ /** Resume if we can, start fresh if we can't, instead of refusing.
+ * "Restart & Continue" wants the hard failure — continuing is the entire
+ * point, so silently starting a blank session would be worse than an
+ * error. A model change wants the soft one: the user asked to change
+ * model, and an agent with no recorded session still has to get one. */
+ resumeOptional?: boolean;
+ } = {}
) => {
if (!a.ptyId) return;
setRestarting(a.id);
@@ -265,19 +274,25 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
const cfg = await window.cth.getConfig();
const previousProvider = inferAgentProvider(a.command, a.provider);
const provider = opts.provider ?? previousProvider;
- const resume = opts.resume === true && provider === previousProvider;
- if (opts.resume && !resume) {
+ let resume = opts.resume === true && provider === previousProvider;
+ if (opts.resume && !resume && !opts.resumeOptional) {
throw new Error('Cannot resume a session through a different provider.');
}
let resumeSessionId: string | undefined;
if (resume) {
+ // A precondition miss is fatal for an explicit "continue", and merely
+ // means "start fresh" for an opportunistic one (see resumeOptional).
+ const giveUpOnResume = (reason: string) => {
+ if (!opts.resumeOptional) throw new Error(reason);
+ resume = false;
+ resumeSessionId = undefined;
+ };
const registry = await window.cth.hiveRegistry();
resumeSessionId = registry.agents[a.id]?.sessionId;
if (!resumeSessionId) {
- throw new Error('No recorded session ID; current process was left running.');
- }
- if (provider === 'claude' && !(await window.cth.resolveSessionCwd(resumeSessionId))) {
- throw new Error('Session transcript not found; current process was left running.');
+ giveUpOnResume('No recorded session ID; current process was left running.');
+ } else if (provider === 'claude' && !(await window.cth.resolveSessionCwd(resumeSessionId))) {
+ giveUpOnResume('Session transcript not found; current process was left running.');
}
}
// Capture the live grid before replacing anything. Restart & Continue
@@ -574,7 +589,19 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
disabled={restarting === a.id}
onChange={(value) => {
const choice = decodeProviderModel(value);
- if (choice) void restartWithModel(a, choice.model, { provider: choice.provider });
+ if (!choice) return;
+ // Switching model within the SAME provider continues the
+ // conversation — that's the whole point of switching mid-task
+ // ("this got hard, go up a tier"), and starting fresh threw
+ // away the context that made the switch necessary.
+ // `resume` is best-effort: restartWithModel already refuses it
+ // across providers, and falls back to a fresh session when no
+ // session id or transcript is recorded.
+ void restartWithModel(a, choice.model, {
+ provider: choice.provider,
+ resume: choice.provider === agentProvider,
+ resumeOptional: true
+ });
}}
>
{(!agentPreset.supportsModel || !currentModelKnown) && (
diff --git a/src/renderer/src/components/FullscreenTerminal.tsx b/src/renderer/src/components/FullscreenTerminal.tsx
index 6456c0d3..912c80fa 100644
--- a/src/renderer/src/components/FullscreenTerminal.tsx
+++ b/src/renderer/src/components/FullscreenTerminal.tsx
@@ -45,33 +45,57 @@ function basename(path: string): string {
* so naming the group after that path buckets each such agent under its own id
* instead of the repository the user actually picked. `git:mainRepo` follows a
* linked worktree back to its main checkout. */
-const repoNameByCwd = new Map<string, string>();
-
-/** Which repository an agent belongs to. Falls back to `project` (the basename
- * of the cwd chosen in Add Agent) until the async resolution lands, and for
- * agents whose directory isn't a git repo at all. */
-function repoOf(agent: Agent): string {
- const resolved = repoNameByCwd.get(agent.cwd);
- if (resolved) return resolved;
+const repoRootByCwd = new Map<string, string | null>();
+/** cwds with a lookup in flight, so a re-render can't start a second one. */
+const repoLookupsInFlight = new Set<string>();
+
+/** Which repository an agent belongs to — the ABSOLUTE root, so it is a real
+ * identity. Two unrelated checkouts can share a basename (`~/client-a/app` and
+ * `~/client-b/app`); keying groups on the name merged them into one section and
+ * let agents be dragged between two different repositories.
+ *
+ * Falls back to the cwd itself until the async resolution lands, and for
+ * directories that aren't git repos at all. */
+function repoKeyOf(agent: Agent): string {
+ return repoRootByCwd.get(agent.cwd) || agent.cwd || 'unknown';
+}
+
+/** What that group is CALLED — the basename, or the project the user picked. */
+function repoLabelOf(agent: Agent): string {
+ const root = repoRootByCwd.get(agent.cwd);
+ if (root) return basename(root);
const project = agent.project?.trim();
if (project) return project;
return basename(agent.cwd) || 'unknown';
}
-/** Resolve every distinct cwd's repository name, then re-render. Cheap: one git
- * call per NEW path, and results are cached for the process lifetime. */
+/** Resolve every distinct cwd's repository root, then re-render. Exactly one git
+ * call per distinct path, ever. */
function useResolvedRepoNames(agents: Agent[]): number {
const [version, setVersion] = useState(0);
useEffect(() => {
let cancelled = false;
const pending = [...new Set(agents.map(a => a.cwd).filter(Boolean))]
- .filter(cwd => !repoNameByCwd.has(cwd));
+ // `has` (not a truthiness check) so a resolved-to-null path — a cwd that
+ // is not a git repo — counts as answered. Caching only successes meant
+ // every agent outside a repo re-asked on each pass, and this effect
+ // depends on `agents`, which the pty parser replaces on every chunk of
+ // terminal output: one such agent spawned `git rev-parse` continuously
+ // for as long as it was talking. In-flight paths are skipped too, so a
+ // re-render mid-lookup doesn't stack a second round of subprocesses.
+ .filter(cwd => !repoRootByCwd.has(cwd) && !repoLookupsInFlight.has(cwd));
if (pending.length === 0) return;
+ pending.forEach(cwd => repoLookupsInFlight.add(cwd));
void Promise.all(pending.map(async (cwd) => {
try {
- const root = await window.cth.gitMainRepo(cwd);
- if (root) repoNameByCwd.set(cwd, basename(root));
- } catch { /* leave unresolved — the `project` fallback still names it */ }
+ repoRootByCwd.set(cwd, (await window.cth.gitMainRepo(cwd)) || null);
+ } catch {
+ // Record the failure as answered as well — retrying a path that throws
+ // is what the unbounded-subprocess bug was made of.
+ repoRootByCwd.set(cwd, null);
+ } finally {
+ repoLookupsInFlight.delete(cwd);
+ }
})).then(() => { if (!cancelled) setVersion(v => v + 1); });
return () => { cancelled = true; };
}, [agents]);
@@ -81,7 +105,7 @@ function useResolvedRepoNames(agents: Agent[]): number {
/** The roster section an agent lives in — god agents share one ungrouped
* section, everyone else groups by repository. */
function groupKey(agent: Agent): string {
- return agent.isGod ? '__god__' : repoOf(agent);
+ return agent.isGod ? '__god__' : repoKeyOf(agent);
}
/** Drag-reorder wiring handed down to each row. */
@@ -110,6 +134,7 @@ export function FullscreenTerminal({ config }: FullscreenTerminalProps) {
const setAddAgentOpen = useStore(s => s.setAddAgentOpen);
const addAgentOpen = useStore(s => s.addAgentOpen);
const setAgentNote = useStore(s => s.setAgentNote);
+ const renameAgent = useStore(s => s.renameAgent);
const updateAgent = useStore(s => s.updateAgent);
// The floor strip (and with it the restore button) is hidden behind the
// overlay, so the roster carries restore too.
@@ -153,13 +178,15 @@ export function FullscreenTerminal({ config }: FullscreenTerminalProps) {
// so the list doesn't reshuffle as statuses change.
const { gods, groups } = useMemo(() => {
const godList: Agent[] = [];
- const byRepo = new Map<string, Agent[]>();
+ // Keyed by absolute repo root (identity); the label is carried alongside so
+ // two same-named repos stay two groups but still read by name.
+ const byRepo = new Map<string, { label: string; members: Agent[] }>();
for (const a of agents) {
if (a.isGod) { godList.push(a); continue; }
- const repo = repoOf(a);
- const bucket = byRepo.get(repo);
- if (bucket) bucket.push(a);
- else byRepo.set(repo, [a]);
+ const key = repoKeyOf(a);
+ const bucket = byRepo.get(key);
+ if (bucket) bucket.members.push(a);
+ else byRepo.set(key, { label: repoLabelOf(a), members: [a] });
}
return { gods: godList, groups: [...byRepo.entries()] };
// repoVersion: rebucket once the async main-repo lookups land.
@@ -259,16 +286,17 @@ export function FullscreenTerminal({ config }: FullscreenTerminalProps) {
active={a.id === agent.id}
onClick={() => { select(a.id); setFullscreen(a.id); }}
onNoteChange={(note) => setAgentNote(a.id, note)}
+ onRename={(name) => renameAgent(a.id, name)}
drag={drag}
scale={scale}
/>
))}
- {groups.map(([repo, members]) => (
+ {groups.map(([repoKey, { label, members }]) => (
// Repos are the roster's real structure, so they get real
// separation — a hairline plus air above, not just a label.
- <div key={repo} style={{ marginTop: 16, paddingTop: 10, borderTop: '1px solid var(--cth-ink-300)' }}>
+ <div key={repoKey} style={{ marginTop: 16, paddingTop: 10, borderTop: '1px solid var(--cth-ink-300)' }}>
<div
- title={repo}
+ title={repoKey}
style={{
display: 'flex', alignItems: 'center', gap: 6,
padding: '0 10px 6px',
@@ -286,7 +314,7 @@ export function FullscreenTerminal({ config }: FullscreenTerminalProps) {
<span style={{
minWidth: 0,
whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'
- }}>{repo.toUpperCase()}</span>
+ }}>{label.toUpperCase()}</span>
</div>
{members.map(a => (
<SidebarRow
@@ -295,6 +323,7 @@ export function FullscreenTerminal({ config }: FullscreenTerminalProps) {
active={a.id === agent.id}
onClick={() => { select(a.id); setFullscreen(a.id); }}
onNoteChange={(note) => setAgentNote(a.id, note)}
+ onRename={(name) => renameAgent(a.id, name)}
drag={drag}
scale={scale}
/>
@@ -423,6 +452,7 @@ function SidebarRow({
active,
onClick,
onNoteChange,
+ onRename,
drag,
scale
}: {
@@ -430,6 +460,7 @@ function SidebarRow({
active: boolean;
onClick: () => void;
onNoteChange: (note: string) => void;
+ onRename: (name: string) => void;
drag: RowDrag;
scale: ReturnType<typeof rosterScale>;
}) {
@@ -445,10 +476,23 @@ function SidebarRow({
const noteLabelSize = Math.max(8, Math.round(noteFontSize * 0.6));
const noteWidth = Math.min(300, Math.round(noteFontSize * 20));
const noteHeight = Math.round(noteFontSize * 9);
+ // Total popover height, used only to keep it on screen near the bottom edge:
+ // the note textarea plus the name field, two labels, the hint and the padding.
+ const popoverHeight = noteHeight + Math.round(noteFontSize * 1.9) + noteLabelSize * 3 + 48;
// One line of the note = one bullet on the row.
const bullets = (agent.note ?? '').split('\n').map(s => s.trim()).filter(Boolean);
+ // Rename is local-until-committed: typing straight into the store would rename
+ // the agent on every keystroke and write the registry each time.
+ const [draftName, setDraftName] = useState(agent.name);
+ useEffect(() => { setDraftName(agent.name); }, [agent.name]);
+ const commitName = () => {
+ const next = draftName.trim();
+ if (!next || next === agent.name) { setDraftName(agent.name); return; }
+ onRename(next);
+ };
+
useEffect(() => () => {
if (hideTimer.current !== null) window.clearTimeout(hideTimer.current);
}, []);
@@ -465,7 +509,7 @@ function SidebarRow({
// Clamp so rows near an edge stay fully on screen.
setNotePosition({
left: Math.min(rect.right + 6, window.innerWidth - noteWidth - 8),
- top: Math.max(8, Math.min(rect.top, window.innerHeight - noteHeight - 8))
+ top: Math.max(8, Math.min(rect.top, window.innerHeight - popoverHeight - 8))
});
};
@@ -590,15 +634,52 @@ function SidebarRow({
boxSizing: 'border-box'
}}
>
+ {/* Rename lives here rather than on the row: the row is a <button>,
+ and an input nested inside one swallows its own clicks. */}
+ <div style={{
+ marginBottom: 3,
+ fontFamily: 'var(--cth-font-display)',
+ fontSize: noteLabelSize,
+ lineHeight: `${Math.round(noteLabelSize * 1.5)}px`,
+ color: 'var(--cth-ink-700)'
+ }}>NAME</div>
+ <input
+ value={draftName}
+ onChange={(e) => setDraftName(e.target.value)}
+ onFocus={() => {
+ if (hideTimer.current !== null) window.clearTimeout(hideTimer.current);
+ }}
+ // Commit on blur as well as Enter — a rename typed and then clicked
+ // away from should not be silently discarded.
+ onBlur={() => { commitName(); scheduleClose(); }}
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (e.key === 'Enter') { e.preventDefault(); commitName(); }
+ // Escape abandons the edit and restores the current name.
+ if (e.key === 'Escape') { setDraftName(agent.name); setNotePosition(null); }
+ }}
+ aria-label={`Rename ${agent.name}`}
+ maxLength={40}
+ style={{
+ width: '100%',
+ height: Math.round(noteFontSize * 1.9),
+ marginBottom: 8,
+ padding: '2px 8px',
+ border: 'none', outline: 'none', boxSizing: 'border-box',
+ background: 'var(--cth-cream-100)',
+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',
+ fontFamily: 'var(--cth-font-mono)',
+ fontSize: noteFontSize,
+ color: 'var(--cth-ink-900)'
+ }}
+ />
<div style={{
marginBottom: 6,
fontFamily: 'var(--cth-font-display)',
fontSize: noteLabelSize,
lineHeight: `${Math.round(noteLabelSize * 1.5)}px`,
color: 'var(--cth-ink-700)'
- }}>
- {agent.name.toUpperCase()} · PRIVATE NOTE
- </div>
+ }}>PRIVATE NOTE</div>
{/* A textarea, not an input: the note is a bullet list, so Enter has
to make a new line rather than doing nothing. */}
{/* No autoFocus — the editor opens on hover, and stealing focus every
diff --git a/src/renderer/src/components/MessageQueueComposer.tsx b/src/renderer/src/components/MessageQueueComposer.tsx
index 972d44f2..279a264a 100644
--- a/src/renderer/src/components/MessageQueueComposer.tsx
+++ b/src/renderer/src/components/MessageQueueComposer.tsx
@@ -2,7 +2,7 @@ import { ClipboardEvent, DragEvent, KeyboardEvent, useEffect, useLayoutEffect, u
import { PixelButton } from './PixelButton';
import { Icon } from './Icon';
import { useStore, type Agent, type QueuedMessage } from '@/store/store';
-import { clearTerminalDraft, terminalAutomationBlockFor } from './terminalPool';
+import { clearTerminalDraft, dismissTerminalPicker, terminalAutomationBlockFor } from './terminalPool';
import type { TerminalAutomationBlock } from './terminalAutomation';
import { freeflowRecorder, useFreeflow } from '@/freeflow/recorder';
import { useTerminalFontSize } from './terminalFontSize';
@@ -214,14 +214,27 @@ export function MessageQueueComposer({ agent }: MessageQueueComposerProps) {
)}
{(block === 'draft' || block === 'picker') && agent.ptyId && (
<button
- onClick={() => clearTerminalDraft(agent.ptyId!)}
- title="Clear the leftover text on this agent's terminal prompt so queued messages can be delivered"
+ onClick={() => {
+ // A picker and a draft are unblocked by different keys: Escape
+ // closes the picker, Ctrl-U kills the input line. Sending Ctrl-U
+ // at a picker leaves it open while telling automation the prompt
+ // is free, which is how a queued message ends up typed into a
+ // menu and marked delivered.
+ if (block === 'picker') { dismissTerminalPicker(agent.ptyId!); return; }
+ // Keep whatever was on the prompt — it lands in this composer so
+ // the user can send it properly instead of losing it to Ctrl-U.
+ const discarded = clearTerminalDraft(agent.ptyId!);
+ if (discarded.trim()) setText(text ? `${text}\n${discarded}` : discarded);
+ }}
+ title={block === 'picker'
+ ? "Close the picker this agent has open so queued messages can be delivered"
+ : "Move the leftover text on this agent's prompt into this box so queued messages can be delivered"}
style={{
border: 'none', background: 'transparent', cursor: 'pointer', padding: 0,
fontFamily: 'var(--cth-font-ui)', fontSize: 12,
color: 'var(--cth-ink-900)', textDecoration: 'underline'
}}
- >clear prompt</button>
+ >{block === 'picker' ? 'close picker' : 'recover prompt'}</button>
)}
{queue.length > 1 && (
<button
diff --git a/src/renderer/src/components/PtyTerminalView.tsx b/src/renderer/src/components/PtyTerminalView.tsx
index a36b4479..84fd064e 100644
--- a/src/renderer/src/components/PtyTerminalView.tsx
+++ b/src/renderer/src/components/PtyTerminalView.tsx
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react';
import type { CSSProperties } from 'react';
import '@xterm/xterm/css/xterm.css';
import { Icon } from './Icon';
-import { acquireTerminal, attachTerminal, reflowTerminal } from './terminalPool';
+import { acquireTerminal, attachTerminal, detachTerminal, reflowTerminal } from './terminalPool';
import {
DEFAULT_TERMINAL_FONT_SIZE,
MAX_TERMINAL_FONT_SIZE,
@@ -265,9 +265,11 @@ export function PtyTerminalView({ ptyId, onStreamData, onUserPrompt, onToggleFul
document.removeEventListener('visibilitychange', onWake);
window.removeEventListener('focus', onWake);
// Detach (but DON'T dispose) the terminal — it keeps running in the pool.
+ // detachTerminal also releases the WebGL lease, so a terminal nobody is
+ // looking at stops holding a GPU context that an on-screen one needs.
entry.onData = undefined;
entry.onPrompt = undefined;
- if (entry.host.parentElement === container) container.removeChild(entry.host);
+ detachTerminal(entry, container);
};
}, [ptyId]);
diff --git a/src/renderer/src/components/terminalAutomation.ts b/src/renderer/src/components/terminalAutomation.ts
index d9c169e1..0d136a6b 100644
--- a/src/renderer/src/components/terminalAutomation.ts
+++ b/src/renderer/src/components/terminalAutomation.ts
@@ -19,8 +19,14 @@ const INTERACTIVE_COMMANDS = new Set([
]);
export function opensInteractiveTerminalUi(input: string): boolean {
- const command = input.trim().toLowerCase().split(/\s+/, 1)[0];
- return INTERACTIVE_COMMANDS.has(command);
+ // Only a BARE command opens a picker. `/model` prompts you to choose;
+ // `/model sonnet` applies the argument and returns to the prompt with no UI
+ // to close. Matching on the first token alone latched the block on the second
+ // form too, and nothing could ever clear it — the agent's message queue then
+ // silently stopped delivering for the rest of the session.
+ const trimmed = input.trim().toLowerCase();
+ if (/\s/.test(trimmed)) return false;
+ return INTERACTIVE_COMMANDS.has(trimmed);
}
/** Follow output only if the user was already at (or one line from) the bottom.
@@ -37,12 +43,33 @@ export function shouldFollowTerminalOutput(viewportY: number, baseY: number): bo
* agent's queue permanently with the composer still claiming it was sending. */
export const STALE_INPUT_MS = 60_000;
+/** How long an untouched picker keeps blocking queue delivery.
+ * Like the draft block, this MUST expire. The picker latch is set when the user
+ * submits a bare `/model`-style command and is only cleared by an Enter, Escape
+ * or Ctrl-C typed into that same terminal — so a picker the AGENT closes, or one
+ * dismissed any other way, left the flag set with no path back. That wedged the
+ * agent's queue permanently, which is exactly the failure this expiry ends.
+ * Longer than the draft window: a human picking from a menu is slower than a
+ * human typing, and re-latching costs nothing. */
+export const STALE_PICKER_MS = 180_000;
+
export interface TerminalAutomationState {
exited: boolean;
pickerOpen: boolean;
inputDirty: boolean;
settleUntil: number;
inputDirtyAt?: number; // last keystroke that left a draft; absent ⇒ never expires
+ pickerOpenedAt?: number; // when the picker latched; absent ⇒ never expires
+}
+
+/** A picker nobody has interacted with for STALE_PICKER_MS is treated as gone. */
+export function isStaleTerminalPicker(
+ state: TerminalAutomationState,
+ now = Date.now()
+): boolean {
+ return state.pickerOpen
+ && state.pickerOpenedAt !== undefined
+ && now - state.pickerOpenedAt >= STALE_PICKER_MS;
}
/** Why automation may not own the prompt right now, or null when it may. */
@@ -63,7 +90,7 @@ export function terminalAutomationBlock(
now = Date.now()
): TerminalAutomationBlock {
if (state.exited) return 'exited';
- if (state.pickerOpen) return 'picker';
+ if (state.pickerOpen && !isStaleTerminalPicker(state, now)) return 'picker';
if (state.inputDirty && !isStaleTerminalDraft(state, now)) return 'draft';
if (now < state.settleUntil) return 'settling';
return null;
diff --git a/src/renderer/src/components/terminalPool.ts b/src/renderer/src/components/terminalPool.ts
index b4907bcb..b82c89e4 100644
--- a/src/renderer/src/components/terminalPool.ts
+++ b/src/renderer/src/components/terminalPool.ts
@@ -54,10 +54,21 @@ export interface TerminalEntry {
/** A user-opened slash-command picker (for example Codex `/model`) owns the
* input line. Queue automation waits until the picker closes. */
automationBlocked: boolean;
+ /** When the picker latch was set — the block expires, see PICKER_BLOCK_MS. */
+ automationBlockedAt: number;
/** True while the user has unsubmitted text in the live TUI prompt. */
inputDirty: boolean;
inputDirtyAt: number; // when the draft was last typed into; drives staleness expiry
automationSettleUntil: number;
+ /** Our model of the text on the live prompt line. On the ENTRY, not a closure
+ * variable: `inputDirty` is derived from it, so anything that clears the
+ * prompt (Ctrl-U, a respawn reset) has to clear both or the next keystroke
+ * resurrects the deleted text as a phantom draft. */
+ lineBuf: string;
+ /** Bumped every time this pty is respawned under the same id. Late events from
+ * the OLD process carry the generation they were registered under, so they can
+ * be recognised and dropped instead of corrupting the replacement. */
+ generation: number;
webgl?: WebglAddon;
}
@@ -116,9 +127,12 @@ export function acquireTerminal(ptyId: string, theme?: ThemeMap, fontSize = 14):
recovery: createTerminalRecoveryState(),
needsRendererRepaint: false,
automationBlocked: false,
+ automationBlockedAt: 0,
inputDirty: false,
inputDirtyAt: 0,
- automationSettleUntil: 0
+ automationSettleUntil: 0,
+ lineBuf: '',
+ generation: 0
};
// Subscribe to the pty stream ONCE for the terminal's whole lifetime, so the
@@ -135,6 +149,12 @@ export function acquireTerminal(ptyId: string, theme?: ThemeMap, fontSize = 14):
});
entry.onData?.(chunk);
}));
+ // A restart does killPty() then spawnPty() under the SAME pty id, so a stale
+ // exit from the killed process could in principle latch `exited` on its
+ // replacement (which would silently drop every keystroke). It can't: kill()
+ // removes the session from the map synchronously (main/pty.ts kill), and the
+ // process's own onExit checks it still owns that id before emitting — so the
+ // stale event is suppressed in the main process and never reaches here.
entry.unsub.push(window.cth.onPtyExit(ptyId, ({ exitCode, signal }) => {
entry.exited = true;
term.writeln(`\r\n\x1b[2m─ process exited (code ${exitCode}${signal ? `, signal ${signal}` : ''}) ─\x1b[0m`);
@@ -181,42 +201,50 @@ export function acquireTerminal(ptyId: string, theme?: ThemeMap, fontSize = 14):
});
// Keystrokes → pty. A small line buffer surfaces the last submitted prompt.
- let lineBuf = '';
+ // It lives on the entry (see TerminalEntry.lineBuf) so every prompt-clearing
+ // path resets it too.
term.onData((data) => {
if (entry.exited) return;
window.cth.writePty(ptyId, data);
// A lone Escape or Ctrl-C closes interactive pickers. Arrow-key escape
// sequences must NOT clear the block while the user navigates a picker.
if (data === '\x1b' || data === '\x03') {
- entry.automationBlocked = false;
- entry.automationSettleUntil = Date.now() + 500;
- lineBuf = '';
+ releasePickerBlock(entry);
+ entry.lineBuf = '';
}
+ // The user's own Ctrl-U (kill-line) clears the prompt exactly like ours does.
+ if (data === '\x15') entry.lineBuf = '';
// Bracketed paste is still user-owned draft text; remove only its wrapper so
// pasted content marks the prompt dirty instead of looking automation-safe.
const input = data.replace(/\x1b\[200~/g, '').replace(/\x1b\[201~/g, '');
for (let i = 0; i < input.length; i++) {
const ch = input[i];
if (ch === '\r' || ch === '\n') {
- const t = lineBuf.trim();
- lineBuf = '';
+ const t = entry.lineBuf.trim();
+ entry.lineBuf = '';
if (entry.automationBlocked) {
// Enter chooses an item and closes the current picker.
- entry.automationBlocked = false;
- entry.automationSettleUntil = Date.now() + 500;
- } else if (opensInteractiveTerminalUi(t)) {
+ releasePickerBlock(entry);
+ }
+ // NOT an `else`: this Enter is the one that SUBMITTED the command, so it
+ // must both close any picker that was already open and latch a new one
+ // for the command it just submitted. As an `else if`, a line like
+ // `/model sonnet` latched the block and then had no later Enter to clear
+ // it — every queued message to that agent was skipped forever.
+ if (opensInteractiveTerminalUi(t)) {
entry.automationBlocked = true;
+ entry.automationBlockedAt = Date.now();
}
if (t.length >= 2) entry.onPrompt?.(t);
} else if (ch === '\x7f' || ch === '\b') {
- lineBuf = lineBuf.slice(0, -1);
+ entry.lineBuf = entry.lineBuf.slice(0, -1);
} else if (ch === '\x1b') {
break; // skip escape sequences (arrow keys, etc.)
} else if (ch >= ' ') {
- lineBuf += ch;
+ entry.lineBuf += ch;
}
}
- entry.inputDirty = lineBuf.length > 0;
+ entry.inputDirty = entry.lineBuf.length > 0;
// Re-stamped on every keystroke, so the staleness clock measures time since
// the user last touched the draft — not since they started it.
if (entry.inputDirty) entry.inputDirtyAt = Date.now();
@@ -238,12 +266,20 @@ function automationStateOf(entry: TerminalEntry) {
return {
exited: entry.exited,
pickerOpen: entry.automationBlocked,
+ pickerOpenedAt: entry.automationBlocked ? entry.automationBlockedAt : undefined,
inputDirty: entry.inputDirty,
inputDirtyAt: entry.inputDirty ? entry.inputDirtyAt : undefined,
settleUntil: entry.automationSettleUntil
};
}
+/** Drop the picker latch and give the TUI a moment to repaint the freed line. */
+function releasePickerBlock(entry: TerminalEntry): void {
+ entry.automationBlocked = false;
+ entry.automationBlockedAt = 0;
+ entry.automationSettleUntil = Date.now() + 500;
+}
+
/** Why queue delivery is currently held back for this pty, or null if it isn't.
* The composer shows this instead of claiming it is sending. */
export function terminalAutomationBlockFor(
@@ -258,94 +294,168 @@ export function terminalAutomationBlockFor(
/** Wipe the TUI prompt's current line and re-arm automation. Ctrl-U is the
* readline kill-to-start binding every supported CLI's input honors. */
-export function clearTerminalDraft(ptyId: string): void {
+export function clearTerminalDraft(ptyId: string): string {
const entry = pool.get(ptyId);
- if (!entry) return;
+ if (!entry) return '';
+ // Hand the text back so the caller can park it somewhere the user can find it
+ // again. Ctrl-U is not undoable in a TUI, so silently discarding it was data
+ // loss every time an abandoned-looking draft turned out to be a real one.
+ const discarded = entry.lineBuf;
void window.cth.writePty(ptyId, '\x15');
entry.inputDirty = false;
entry.inputDirtyAt = 0;
- entry.automationBlocked = false;
+ // Reset our model of the line too. Leaving it set made the very next keystroke
+ // recompute `inputDirty` from the text we just deleted, so the draft block
+ // came straight back and the deleted text corrupted the next parsed command.
+ entry.lineBuf = '';
+ // NOT cleared: `automationBlocked`. Ctrl-U kills the input line; it does not
+ // close an open picker. Clearing the latch here told automation the prompt was
+ // free while a picker still owned it, so the queued message was typed into the
+ // picker and acknowledged as delivered — the message was lost and the picker
+ // got garbage. The latch is released by a real Enter/Esc/Ctrl-C, or it expires.
// Let the TUI repaint the cleared line before automation types into it.
entry.automationSettleUntil = Date.now() + 300;
+ return discarded;
}
/** Drop a draft nobody has touched for STALE_INPUT_MS so it cannot fuse with the
* text automation is about to type. No-op while the draft is still fresh. */
-export function clearStaleTerminalDraft(ptyId: string, now = Date.now()): boolean {
+/** Close an open picker by sending the key that actually closes one.
+ * The Escape round-trips through xterm's own onData handler, so the latch is
+ * released by the same path a user pressing Escape would take — we never just
+ * assert the picker is gone without telling the TUI to close it. */
+export function dismissTerminalPicker(ptyId: string): void {
const entry = pool.get(ptyId);
- if (!entry || !isStaleTerminalDraft(automationStateOf(entry), now)) return false;
- clearTerminalDraft(ptyId);
- return true;
+ if (!entry || entry.exited) return;
+ void window.cth.writePty(ptyId, '\x1b');
+ releasePickerBlock(entry);
+}
+
+export function clearStaleTerminalDraft(ptyId: string, now = Date.now()): string | null {
+ const entry = pool.get(ptyId);
+ if (!entry || !isStaleTerminalDraft(automationStateOf(entry), now)) return null;
+ // Returns the discarded text so the caller can preserve it; '' when the draft
+ // turned out to be empty.
+ return clearTerminalDraft(ptyId);
+}
+
+/** Give this terminal a WebGL renderer for as long as it is on screen.
+ *
+ * The DOM renderer assumes a perfectly monospace font, but VT323 is missing
+ * glyphs (↔, arrows, some box-drawing) and has no real bold — the browser
+ * substitutes fallback glyphs with different advance widths, so box-drawing
+ * tables shear apart and the cursor drifts. WebGL draws every glyph into its
+ * own fixed cell, keeping the grid aligned. NOT the deprecated canvas addon
+ * (its dirty-region tracking garbles scrollback).
+ *
+ * It is a LEASE, taken on attach and released on detach (see detachTerminal),
+ * because a browser allows only a limited number of live WebGL contexts —
+ * around 16 in Chromium — and silently discards the oldest when a new one
+ * pushes past the cap. Terminals used to hold their context for the whole
+ * session even while detached, so restoring a team (which opens one terminal
+ * per agent in quick succession) blew the cap and the browser killed a
+ * background terminal's context. Its pty, buffer and subscription all stayed
+ * healthy — only the renderer was dead — which is exactly the reported
+ * "terminal is black and typing does nothing": the keystrokes were delivered
+ * and the replies arrived, with nothing left alive to paint them.
+ *
+ * Best-effort: on init failure or context loss, fall back to the DOM renderer
+ * rather than leave a black terminal. */
+function leaseWebglRenderer(entry: TerminalEntry): void {
+ if (entry.webgl) return;
+ try {
+ const webgl = new WebglAddon();
+ webgl.onContextLoss(() => {
+ if (entry.webgl !== webgl) return;
+ console.warn('[terminal] webgl context lost — falling back to DOM renderer');
+ entry.webgl = undefined;
+ entry.needsRendererRepaint = true;
+ try { webgl.dispose(); } catch { /* noop */ }
+ // Laptop sleep == GPU sleep == WebGL context loss: the likely PRIMARY
+ // trigger for the post-wake "can't scroll past a recent point" bug. The
+ // renderer swap leaves xterm's cached cell-height (and the viewport
+ // scroll-area derived from it) stale, so only part of the intact buffer
+ // is scrollable until something forces a re-measure. Heal it here, on the
+ // next frame so the (waking) layout has settled. Guarded + idempotent, so
+ // it composes safely with the visibilitychange/focus path in the view.
+ scheduleWebglRecovery(entry.recovery, requestAnimationFrame, () =>
+ repaintTerminalAfterRendererLoss(entry));
+ });
+ // Set before loadAddon: an immediately-lost context may call the handler
+ // during initialization, and it must be recognized as the active renderer.
+ entry.webgl = webgl;
+ entry.term.loadAddon(webgl);
+ } catch (e) {
+ try { entry.webgl?.dispose(); } catch { /* noop */ }
+ entry.webgl = undefined;
+ console.warn('[terminal] webgl renderer unavailable, using DOM renderer:', e);
+ }
+}
+
+/** Release the WebGL lease so an off-screen terminal isn't holding a GPU context
+ * that an on-screen one needs. xterm falls back to the DOM renderer, which is
+ * fine for a terminal nobody is looking at; the next attach takes a fresh
+ * lease. The buffer and pty subscription are untouched. */
+function releaseWebglRenderer(entry: TerminalEntry): void {
+ const webgl = entry.webgl;
+ if (!webgl) return;
+ entry.webgl = undefined;
+ try { webgl.dispose(); } catch { /* noop */ }
+ // The DOM renderer that takes over inherits xterm's cached cell metrics, which
+ // may be stale by the time this terminal is shown again.
+ entry.needsRendererRepaint = true;
}
/** Re-parent a pty's terminal into `container`, opening xterm on first attach. */
export function attachTerminal(entry: TerminalEntry, container: HTMLElement): void {
container.appendChild(entry.host);
if (!entry.opened) {
+ // open() must come first — the WebGL addon can only load onto an opened
+ // terminal, and xterm needs its host in the document to measure the cell.
entry.term.open(entry.host);
entry.opened = true;
- // Switch from the DOM renderer to WebGL (must load after open()). The DOM
- // renderer assumes a perfectly monospace font, but VT323 is missing glyphs
- // (↔, arrows, some box-drawing) and has no real bold — the browser
- // substitutes fallback glyphs with different advance widths, so box-drawing
- // tables shear apart and the cursor drifts. WebGL draws every glyph into its
- // own fixed cell, keeping the grid aligned. NOT the deprecated canvas addon
- // (its dirty-region tracking garbles scrollback). Best-effort: on init
- // failure or GPU context loss, dispose → fall back to the DOM renderer
- // rather than leave a black terminal.
- try {
- const webgl = new WebglAddon();
- webgl.onContextLoss(() => {
- if (entry.webgl !== webgl) return;
- console.warn('[terminal] webgl context lost — falling back to DOM renderer');
- entry.webgl = undefined;
- entry.needsRendererRepaint = true;
- try { webgl.dispose(); } catch { /* noop */ }
- // Laptop sleep == GPU sleep == WebGL context loss: the likely PRIMARY
- // trigger for the post-wake "can't scroll past a recent point" bug. The
- // renderer swap leaves xterm's cached cell-height (and the viewport
- // scroll-area derived from it) stale, so only part of the intact buffer
- // is scrollable until something forces a re-measure. Heal it here, on the
- // next frame so the (waking) layout has settled. Guarded + idempotent, so
- // it composes safely with the visibilitychange/focus path in the view.
- scheduleWebglRecovery(entry.recovery, requestAnimationFrame, () => {
- repaintTerminalAfterRendererLoss(entry);
- });
- });
- // Set before loadAddon: an immediately-lost context may call the handler
- // during initialization, and it must be recognized as the active renderer.
- entry.webgl = webgl;
- entry.term.loadAddon(webgl);
- } catch (e) {
- try { entry.webgl?.dispose(); } catch { /* noop */ }
- entry.webgl = undefined;
- console.warn('[terminal] webgl renderer unavailable, using DOM renderer:', e);
- }
- // PTY startup output can arrive before this pooled terminal subscribes.
- // Request one same-size redraw after open/subscription even when fit() later
- // sees unchanged dimensions and therefore emits no resize of its own.
- requestInitialPtyRedraw(entry.recovery, () => {
- void window.cth.redrawPty(entry.ptyId);
- });
}
+ leaseWebglRenderer(entry);
+ // PTY startup output can arrive before this pooled terminal subscribes.
+ // Request one same-size redraw after open/subscription even when fit() later
+ // sees unchanged dimensions and therefore emits no resize of its own.
+ requestInitialPtyRedraw(entry.recovery, () => window.cth.redrawPty(entry.ptyId));
if (entry.needsRendererRepaint) {
- scheduleWebglRecovery(entry.recovery, requestAnimationFrame, () => {
- repaintTerminalAfterRendererLoss(entry);
- });
+ scheduleWebglRecovery(entry.recovery, requestAnimationFrame, () =>
+ repaintTerminalAfterRendererLoss(entry));
}
}
+/** Take the terminal off screen: drop the WebGL lease and unparent the host.
+ * Everything that makes the terminal a terminal — buffer, scrollback, pty
+ * subscription — stays in the pool, so re-attaching shows it fully rendered. */
+export function detachTerminal(entry: TerminalEntry, container: HTMLElement): void {
+ // Guard: another view may have already taken the host (React can mount the new
+ // owner before the old one's cleanup runs). Releasing the renderer then would
+ // blank the terminal that just legitimately claimed it.
+ if (entry.host.parentElement !== container) return;
+ releaseWebglRenderer(entry);
+ container.removeChild(entry.host);
+}
+
function repaintTerminalAfterRendererLoss(entry: TerminalEntry): void {
if (!entry.opened || !entry.host.isConnected
|| !entry.host.clientWidth || !entry.host.clientHeight) {
entry.needsRendererRepaint = true;
return;
}
- entry.needsRendererRepaint = false;
reflowTerminal(entry.ptyId);
try {
entry.term.refresh(0, Math.max(0, entry.term.rows - 1));
- } catch { /* renderer may still be settling */ }
+ // Only NOW is the repaint confirmed. Clearing the marker before the refresh
+ // meant a throw here (the renderer still settling) discarded the last record
+ // that this terminal needed repainting — so it stayed black until something
+ // unrelated happened to resize it, which is why Cmd +/- fixed it only some
+ // of the time.
+ entry.needsRendererRepaint = false;
+ } catch {
+ entry.needsRendererRepaint = true;
+ }
}
/**
@@ -414,6 +524,12 @@ export function resetTerminal(
entry.exited = false;
entry.inputDirty = false;
entry.inputDirtyAt = 0;
+ // The old process's prompt is gone with it — drop our model of that line and
+ // any picker it had open, or the replacement inherits a phantom draft and a
+ // block that nothing can clear.
+ entry.lineBuf = '';
+ entry.automationBlocked = false;
+ entry.automationBlockedAt = 0;
try {
if (opts.preserveScrollback) {
entry.term.writeln('\r\n\x1b[2m─ resuming existing session ─\x1b[0m');
diff --git a/src/renderer/src/components/terminalRecovery.ts b/src/renderer/src/components/terminalRecovery.ts
index 10018445..1741f5bc 100644
--- a/src/renderer/src/components/terminalRecovery.ts
+++ b/src/renderer/src/components/terminalRecovery.ts
@@ -23,18 +23,43 @@ export function normalizePtyChunk(value: unknown): string {
return '';
}
-/** Request exactly one redraw after the renderer has subscribed to PTY output. */
+/** Request exactly one redraw after the renderer has subscribed to PTY output.
+ *
+ * The latch is only set once the redraw has actually SUCCEEDED. It used to be
+ * set up front, before the fire-and-forget IPC resolved — so a redraw that
+ * failed or raced left a terminal that had already consumed its one chance,
+ * with no output to repaint it and no retry path. That is a blank pane with a
+ * perfectly healthy pty behind it. A rejected redraw now leaves the latch clear
+ * so the next attach tries again. */
export function requestInitialPtyRedraw(
state: TerminalRecoveryState,
- requestRedraw: () => void
+ requestRedraw: () => void | Promise<unknown>
): boolean {
if (state.initialRedrawRequested) return false;
+ // Set before awaiting so two attaches in the same tick can't both fire; a
+ // failure clears it again below.
state.initialRedrawRequested = true;
- requestRedraw();
+ try {
+ const result = requestRedraw();
+ if (result && typeof (result as Promise<unknown>).then === 'function') {
+ void (result as Promise<unknown>).catch(() => {
+ state.initialRedrawRequested = false;
+ });
+ }
+ } catch {
+ state.initialRedrawRequested = false;
+ }
return true;
}
-/** Wait two paint frames after WebGL disposal so the DOM renderer can repaint. */
+/** Wait two paint frames after WebGL disposal so the DOM renderer can repaint.
+ *
+ * `recover` reports whether it actually repainted. When it could not (the host
+ * is detached or still unsized), the pending flag is cleared AND the caller
+ * keeps its needs-repaint marker, so a later attach can schedule another
+ * attempt. Clearing the flag unconditionally before the repaint was confirmed
+ * is what made the blank terminal recover "sometimes" — whether a later resize
+ * happened to rebuild the renderer was pure luck. */
export function scheduleWebglRecovery(
state: TerminalRecoveryState,
requestFrame: (cb: () => void) => void,
diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.ts
index c3e9fc7c..252122c9 100644
--- a/src/renderer/src/hooks/useHive.ts
+++ b/src/renderer/src/hooks/useHive.ts
@@ -523,8 +523,17 @@ export function useHive(config: HarnessConfig | null): void {
if (!isTerminalAutomationSafe(target.ptyId, now)) return { sent: false };
if (now - (lastFlush.current[target.id] ?? 0) < FLUSH_COOLDOWN_MS) return { sent: false };
// The gate above lets an ABANDONED draft through. Wipe the prompt first so
- // the leftover half-line can't fuse with the message we're about to type.
- clearStaleTerminalDraft(target.ptyId, now);
+ // the leftover half-line can't fuse with the message we're about to type —
+ // but "abandoned" is only a guess (a minute of no keystrokes), and it is
+ // wrong whenever the user paused to think or switched windows. Park the
+ // text in that agent's composer draft so it is recoverable instead of
+ // destroyed by a Ctrl-U they never asked for.
+ const discarded = clearStaleTerminalDraft(target.ptyId, now);
+ if (discarded && discarded.trim()) {
+ const { drafts, setDraft } = useStore.getState();
+ const existing = drafts[target.id] ?? '';
+ setDraft(target.id, existing ? `${existing}\n${discarded}` : discarded);
+ }
const flightKey = `${srcId}:${next.id}`;
if (inFlight.has(flightKey)) return { sent: false };
inFlight.add(flightKey);
diff --git a/src/renderer/src/hooks/useRestoreTeam.ts b/src/renderer/src/hooks/useRestoreTeam.ts
index 9adb76db..0c842bbf 100644
--- a/src/renderer/src/hooks/useRestoreTeam.ts
+++ b/src/renderer/src/hooks/useRestoreTeam.ts
@@ -1,5 +1,5 @@
import { useSyncExternalStore } from 'react';
-import { useStore } from '@/store/store';
+import { useStore, type Agent } from '@/store/store';
import { buildSpawnCommand, inferAgentProvider, tokenizeCommand, type HarnessConfig } from '@/store/config';
/** "Restore team" — respawn every worker from the previous session.
@@ -66,7 +66,12 @@ export function useRestoreTeam(config?: HarnessConfig | null): RestoreTeamState
// synchronously between awaits, so concurrent handlers can't interleave
// mid-update. Serially this cost the sum of every agent's git probe + spawn;
// a 6-agent team took ~6× one agent for no reason.
- await Promise.all([...restorableAgents].map(async (a) => {
+ // Spawns run concurrently but agents are ADDED in roster order afterwards.
+ // Calling addAgent from inside each spawn made completion timing decide
+ // the roster order — and that order is persisted, so a slow provider or a
+ // slow git probe silently overwrote the sequence the user had dragged the
+ // cards into.
+ const restoredInOrder = await Promise.all([...restorableAgents].map(async (a): Promise<Agent | null> => {
// Per-agent guard: one agent's failure (or a rejected IPC call) must NEVER
// abort the others — an unhandled rejection here used to make the
// entire restore a silent no-op after the first bad agent.
@@ -78,7 +83,7 @@ export function useRestoreTeam(config?: HarnessConfig | null): RestoreTeamState
// config to rebuild one). Keep it restorable and SAY why rather than
// silently dropping it — silent removal read as "nothing happened".
failures.push(`${a.name}: no saved command`);
- return;
+ return null;
}
const [exe, ...args] = tokenizeCommand(command);
const ptyId = a.ptyId ?? `pty-${a.id}`;
@@ -123,22 +128,22 @@ export function useRestoreTeam(config?: HarnessConfig | null): RestoreTeamState
});
if (res.ok) {
restored++;
- useStore.getState().addAgent({
- ...a,
- provider,
- ptyId,
- archived: false,
- status: 'idle',
- // Surface the worktree fallback on the floor card; otherwise normal.
- action: worktreeGone ? 'worktree gone — using base repo' : 'starting up',
- // The worktree is no longer on disk — drop it so this agent is treated
- // as a plain base-cwd agent going forward (a future restore won't keep
- // re-probing a dead path).
- worktreePath: worktreeGone ? undefined : a.worktreePath,
- carrying: undefined,
- currentStation: 'desk',
- recentTextTs: Date.now()
- });
+ return {
+ ...a,
+ provider,
+ ptyId,
+ archived: false,
+ status: 'idle',
+ // Surface the worktree fallback on the floor card; otherwise normal.
+ action: worktreeGone ? 'worktree gone — using base repo' : 'starting up',
+ // The worktree is no longer on disk — drop it so this agent is treated
+ // as a plain base-cwd agent going forward (a future restore won't keep
+ // re-probing a dead path).
+ worktreePath: worktreeGone ? undefined : a.worktreePath,
+ carrying: undefined,
+ currentStation: 'desk',
+ recentTextTs: Date.now()
+ };
} else if ((res.error ?? '').includes('already exists')) {
// A live PTY with this id is already running (e.g. respawned at boot or
// by another path) — the agent isn't actually missing, so retire it from
@@ -155,7 +160,12 @@ export function useRestoreTeam(config?: HarnessConfig | null): RestoreTeamState
failures.push(`${a.name}: ${e instanceof Error ? e.message : String(e)}`);
console.error('[restore] error for', a.id, e);
}
+ return null;
}));
+ // Add in the ORIGINAL roster order, not completion order.
+ for (const restoredAgent of restoredInOrder) {
+ if (restoredAgent) useStore.getState().addAgent(restoredAgent);
+ }
} finally {
// addAgent auto-selects each spawn; put the user back where they were.
const sel = useStore.getState();
diff --git a/src/renderer/src/store/store.ts b/src/renderer/src/store/store.ts
index 05d43e56..90daa7e6 100644
--- a/src/renderer/src/store/store.ts
+++ b/src/renderer/src/store/store.ts
@@ -149,6 +149,10 @@ interface State {
select: (id: string) => void;
updateAgent: (id: string, patch: Partial<Agent>) => void;
setAgentNote: (id: string, note: string) => void;
+ /** Rename an agent everywhere it is shown, and in the hive registry so its
+ * siblings and its own identity card agree. The agent id never changes — it
+ * is what the workspace, inbox, memory and task assignees are keyed on. */
+ renameAgent: (id: string, name: string) => void;
pushFeed: (id: string, line: string) => void;
addAgent: (agent: Agent) => void;
removeAgent: (id: string) => void;
@@ -407,6 +411,21 @@ export const useStore = create<State>((set) => ({
persistAgents(agents, s.selectedId);
return { agents };
}),
+ renameAgent: (id, name) => {
+ const next = name.trim();
+ if (!next) return;
+ set((s) => {
+ const agents = s.agents.map((a) => a.id === id ? { ...a, name: next } : a);
+ // Restorable entries carry their own copy of the roster; rename there too
+ // or a restart would resurrect the agent under its old name.
+ const restorable = s.restorableAgents.map((a) => a.id === id ? { ...a, name: next } : a);
+ persistAgents(agents, s.selectedId);
+ persistRestorable(restorable);
+ return { agents, restorableAgents: restorable };
+ });
+ // Best-effort: the registry is what other agents read the roster from.
+ void window.cth.hiveRename(id, next).catch(() => { /* local rename stands */ });
+ },
pushFeed: (id, line) =>
set((s) => ({ feeds: { ...s.feeds, [id]: [...(s.feeds[id] ?? []), line] } })),
addAgent: (agent) =>
diff --git a/test/terminal-automation.test.cjs b/test/terminal-automation.test.cjs
index a8fbb2c1..07b0c28d 100644
--- a/test/terminal-automation.test.cjs
+++ b/test/terminal-automation.test.cjs
@@ -10,17 +10,29 @@ const {
opensInteractiveTerminalUi,
shouldFollowTerminalOutput,
terminalAutomationBlock,
- STALE_INPUT_MS
+ isStaleTerminalPicker,
+ STALE_INPUT_MS,
+ STALE_PICKER_MS
} = loadTs('src/renderer/src/components/terminalAutomation.ts');
test('interactive provider commands pause queue automation', () => {
assert.equal(opensInteractiveTerminalUi('/model'), true);
assert.equal(opensInteractiveTerminalUi(' /provider '), true);
- assert.equal(opensInteractiveTerminalUi('/permissions allow'), true);
assert.equal(opensInteractiveTerminalUi('/compact'), false);
assert.equal(opensInteractiveTerminalUi('implement this'), false);
});
+test('a command with an argument opens no picker to wait for', () => {
+ // Only the BARE command opens a picker. `/model sonnet` applies the argument
+ // and returns to the prompt, leaving no UI to close — but the picker latch is
+ // cleared only by an Enter/Escape/Ctrl-C in that terminal, so latching here
+ // wedged the agent's message queue permanently. Matching on the first token
+ // alone is what caused it.
+ assert.equal(opensInteractiveTerminalUi('/model sonnet'), false);
+ assert.equal(opensInteractiveTerminalUi('/permissions allow'), false);
+ assert.equal(opensInteractiveTerminalUi(' /provider anthropic '), false);
+});
+
test('terminal automation waits for user drafts and interactive states', () => {
const ready = { exited: false, pickerOpen: false, inputDirty: false, settleUntil: 0 };
assert.equal(canAutomateTerminal(ready, 100), true);
@@ -46,6 +58,26 @@ test('an abandoned draft stops blocking delivery once it goes stale', () => {
assert.equal(canAutomateTerminal({ ...draft, inputDirtyAt: undefined }, typedAt + 1e9), false);
});
+test('an abandoned picker stops blocking delivery once it goes stale', () => {
+ const openedAt = 1_000_000;
+ const picker = {
+ exited: false, pickerOpen: true, inputDirty: false,
+ settleUntil: 0, pickerOpenedAt: openedAt
+ };
+ // While it is plausibly still open, automation must not type into the menu.
+ assert.equal(canAutomateTerminal(picker, openedAt + 1), false);
+ assert.equal(isStaleTerminalPicker(picker, openedAt + 1), false);
+ // The latch is cleared only by Enter/Escape/Ctrl-C typed into that terminal.
+ // A picker closed any other way left it set forever and the agent's queue
+ // never drained again, so the block HAS to expire.
+ assert.equal(isStaleTerminalPicker(picker, openedAt + STALE_PICKER_MS), true);
+ assert.equal(canAutomateTerminal(picker, openedAt + STALE_PICKER_MS), true);
+ assert.equal(terminalAutomationBlock(picker, openedAt + STALE_PICKER_MS), null);
+ // No timestamp ⇒ the old never-expires behavior, so nothing silently changes
+ // for a state recorded before this field existed.
+ assert.equal(canAutomateTerminal({ ...picker, pickerOpenedAt: undefined }, openedAt + 1e9), false);
+});
+
test('automation block reports why delivery is held', () => {
const ready = { exited: false, pickerOpen: false, inputDirty: false, settleUntil: 0 };
assert.equal(terminalAutomationBlock(ready, 100), null);