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
HTML agent-harnessagent-orchestrationagentsai-agentsautonomous-agentsclaude-codecodexcoding-agentsdesktop-appdeveloper-toolselectrongemini-cliharnessharness-engineeringlocal-firstmemorymulti-agentopencodeorchestrationtypescript
fix(terminal): act on expired automation blocks instead of typing through them
Vyapak Goyal97dc53320baa
diff --git a/src/main/hive.ts b/src/main/hive.tsindex 34083766..e9d2b1c7 100644--- a/src/main/hive.ts+++ b/src/main/hive.ts@@ -452,7 +452,11 @@ export class HiveManager {try {const reg = this.registry();const agent = reg.agents[id];- if (!agent || agent.name === next) return false;+ if (!agent) return false;+ // Already called that ⇒ nothing to do, but the CALLER asked for a state,+ // not an edit, and that state holds. Reporting false here made a no-op+ // rename indistinguishable from a failed one at the IPC boundary.+ if (agent.name === next) return true;const previous = agent.name;agent.name = next;agent.lastSeen = Date.now();@@ -466,6 +470,23 @@ export class HiveManager {} catch { /* identity refresh is best-effort */ }this.appendLog({ kind: 'rename', agentId: id, name: next, previous });this.commit(`hive: rename ${id} → ${next}`);+ // A RUNNING agent was told its name in the system prompt injected at spawn,+ // and in AGENT_NAME — neither of which can be rewritten under a live+ // process. Rewriting identity.md alone leaves it introducing itself by the+ // old name until it restarts, and nothing would ever tell it to reread the+ // file. Mail is the one channel a running agent already drains, so use it.+ try {+ this.send({+ to: id,+ act: 'inform',+ subject: `You are now called ${next}`,+ body: [+ `You have been renamed from "${previous}" to "${next}".`,+ 'Your agent id is unchanged, so your workspace, inbox, memory and task assignments all stay exactly as they are — nothing to migrate.',+ 'Use the new name from now on. Your identity.md has been updated; the name in your original system prompt is stale.'+ ].join(' ')+ }, 'system');+ } catch { /* the rename itself succeeded; the courtesy note is best-effort */ }return true;} catch {return false; // best-effort — never crash a lifecycle handlerdiff --git a/src/main/index.ts b/src/main/index.tsindex 55f007a0..a1e14db1 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1997,7 +1997,12 @@ ipcMain.handle('hive:rename', (_evt, id: unknown, name: unknown) => {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);+ // Propagate the outcome. Swallowing a false here let the UI keep a name the+ // registry had rejected, so the roster every SIBLING agent reads still had the+ // old one — two names for one agent, with nothing on screen to say so.+ if (!hive.rename(id, next)) {+ return { ok: false, error: 'no such agent in the hive registry, or the registry could not be written' };+ }return { ok: true };});diff --git a/src/renderer/src/components/CommandCenterPanel.tsx b/src/renderer/src/components/CommandCenterPanel.tsxindex 2fbc439c..60a48d75 100644--- a/src/renderer/src/components/CommandCenterPanel.tsx+++ b/src/renderer/src/components/CommandCenterPanel.tsx@@ -349,9 +349,21 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {throw new Error('Resume was refused; no replacement session was accepted.');}if (res.ok) {- // On a pure resume the model is unchanged — don't overwrite it.+ // Record the model even on a resume. A same-provider model change now+ // RESUMES the session (that is the point — you keep the conversation and+ // just swap the model), so "resume ⇒ the model is unchanged" stopped+ // being true. Skipping the patch left the live process on the new model+ // while the selector and the persisted agent kept the old one, and the+ // next restore relaunched the old command. `command` is rebuilt from the+ // selected model above, so on a genuine no-change restart this is a no-op.const patch = resume- ? { status: 'idle' as const, action: 'continuing…' }+ ? {+ command: command.trim(),+ provider,+ model,+ status: 'idle' as const,+ action: 'continuing…'+ }: {command: command.trim(),provider,diff --git a/src/renderer/src/components/FullscreenTerminal.tsx b/src/renderer/src/components/FullscreenTerminal.tsxindex 912c80fa..bd0ee063 100644--- a/src/renderer/src/components/FullscreenTerminal.tsx+++ b/src/renderer/src/components/FullscreenTerminal.tsx@@ -37,7 +37,10 @@ function rosterScale(zoom: number) {}function basename(path: string): string {- return path.split('/').filter(Boolean).pop() ?? path;+ // Split on BOTH separators: `git:mainRepo` hands back whatever the platform+ // uses, and a Windows `C:\work\repo` contains no '/' at all — so a '/'-only+ // split returned the whole absolute path as the group's "name".+ return path.split(/[\\/]/).filter(Boolean).pop() ?? path;}/** cwd → main-repo basename, resolved once per path and shared by every mount.diff --git a/src/renderer/src/components/terminalAutomation.ts b/src/renderer/src/components/terminalAutomation.tsindex 0d136a6b..86e16fa6 100644--- a/src/renderer/src/components/terminalAutomation.ts+++ b/src/renderer/src/components/terminalAutomation.ts@@ -96,6 +96,32 @@ export function terminalAutomationBlock(return null;}+/** What an automatic writer must DO before it may type into this terminal.+ *+ * `terminalAutomationBlock` answers "may I type?", and reports an EXPIRED block+ * as no block at all. That answer is a guess: an expiry only means nobody has+ * touched the picker/draft for a while, not that it is gone. Every caller that+ * acted on the guess by typing was a bug — a queued message typed into a live+ * menu and acknowledged as delivered, or an inbox nudge fused onto the user's+ * half-written line. So expiries resolve to an ACTION that frees the prompt+ * ('dismiss-picker' ⇒ send Escape, 'clear-draft' ⇒ send Ctrl-U and keep the+ * text), after which the caller retries once the TUI has repainted. */+export type TerminalAutomationAction = 'go' | 'dismiss-picker' | 'clear-draft' | 'wait';++export function nextTerminalAutomationAction(+ state: TerminalAutomationState,+ now = Date.now()+): TerminalAutomationAction {+ // A dead pty cannot be freed by typing into it.+ if (state.exited) return 'wait';+ // Picker outranks draft: both flags are set while a slash menu is open, and+ // Ctrl-U into a menu edits the menu's filter rather than freeing the prompt.+ if (state.pickerOpen) return isStaleTerminalPicker(state, now) ? 'dismiss-picker' : 'wait';+ if (state.inputDirty) return isStaleTerminalDraft(state, now) ? 'clear-draft' : 'wait';+ if (now < state.settleUntil) return 'wait';+ return 'go';+}+/** Automatic writes may own the prompt only when no user draft or picker does. */export function canAutomateTerminal(state: TerminalAutomationState,diff --git a/src/renderer/src/components/terminalPool.ts b/src/renderer/src/components/terminalPool.tsindex b82c89e4..cf435d2f 100644--- a/src/renderer/src/components/terminalPool.ts+++ b/src/renderer/src/components/terminalPool.ts@@ -26,7 +26,7 @@ import {} from './terminalRecovery';import {canAutomateTerminal,- isStaleTerminalDraft,+ nextTerminalAutomationAction,opensInteractiveTerminalUi,shouldFollowTerminalOutput,terminalAutomationBlock,@@ -318,8 +318,6 @@ export function clearTerminalDraft(ptyId: string): string {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. *//** 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@@ -331,12 +329,47 @@ export function dismissTerminalPicker(ptyId: string): void {releasePickerBlock(entry);}-export function clearStaleTerminalDraft(ptyId: string, now = Date.now()): string | null {+export interface AutomationPreparation {+ /** True only when the prompt is free RIGHT NOW and safe to type into. */+ ready: boolean;+ /** Draft text taken off the prompt, so the caller can park it somewhere the+ * user can find it again. Null when nothing was discarded. */+ discardedDraft: string | null;+}++/** Make this terminal's prompt safe for automation, and say whether it now is.+ *+ * EVERY automatic writer must go through this — not just the queue drain. A+ * block that has expired is only a GUESS that the UI it was guarding is gone:+ * the picker latch is cleared by an Enter/Escape/Ctrl-C in that terminal, and a+ * picker closed any other way (or still genuinely open) leaves it set. Acting+ * on that guess by typing is how a queued message got typed into a live menu+ * and acknowledged as delivered — lost, with the queue reporting success.+ *+ * So an expired block is acted on by CLOSING the thing it described and+ * reporting not-ready. The caller retries on its next tick, by which time the+ * Escape (or Ctrl-U) has landed and the TUI has repainted the freed line. */+export function prepareTerminalForAutomation(+ ptyId: string,+ now = Date.now()+): AutomationPreparation {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);+ // No pooled terminal ⇒ no local picker and no draft we could be fusing with.+ if (!entry) return { ready: true, discardedDraft: null };+ switch (nextTerminalAutomationAction(automationStateOf(entry), now)) {+ case 'go':+ return { ready: true, discardedDraft: null };+ case 'dismiss-picker':+ dismissTerminalPicker(ptyId);+ return { ready: false, discardedDraft: null };+ case 'clear-draft':+ // "Abandoned" is only a guess (a minute of no keystrokes), and it is wrong+ // whenever the user paused to think or switched windows — so hand the text+ // back instead of destroying it with a Ctrl-U they never asked for.+ return { ready: false, discardedDraft: clearTerminalDraft(ptyId) };+ default:+ return { ready: false, discardedDraft: null };+ }}/** Give this terminal a WebGL renderer for as long as it is on screen.diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.tsindex 252122c9..17312390 100644--- a/src/renderer/src/hooks/useHive.ts+++ b/src/renderer/src/hooks/useHive.ts@@ -13,7 +13,7 @@ import {terminalReadyToReceive} from '../../../shared/providerAutomation';import type { AgentProvider } from '../../../shared/agentProvider';-import { clearStaleTerminalDraft, isTerminalAutomationSafe } from '@/components/terminalPool';+import { prepareTerminalForAutomation } from '@/components/terminalPool';import { deliverWithAcknowledgement } from './queueDelivery';const GOD_ID = 'god';@@ -35,6 +35,17 @@ const INITIAL_GOD_PROMPT = ['Then begin orchestrating: triage requests, delegate work to the team, and keep everyone unblocked. You are fully autonomous — there is no approval queue, so handle tool-permission prompts in this session yourself (the human can approve them remotely from their phone).'].join('\n');+/** Park text automation took off an agent's prompt into that agent's composer+ * draft. A draft is only ever cleared on a GUESS that it was abandoned, so the+ * text has to land somewhere the user can get it back from — a Ctrl-U in a TUI+ * is not undoable, and every automatic writer shares this hazard. */+function parkDiscardedDraft(agentId: string, discarded: string | null): void {+ if (!discarded || !discarded.trim()) return;+ const { drafts, setDraft } = useStore.getState();+ const existing = drafts[agentId] ?? '';+ setDraft(agentId, existing ? `${existing}\n${discarded}` : discarded);+}+// Per-pty submission chain. Every submitToPty for a given pty is appended here so// two callers (e.g. the boot sequence's /remote-control and the inbox-wake nudge)// can NEVER interleave their text + Enter — which jammed them onto one line and@@ -471,7 +482,14 @@ export function useHive(config: HarnessConfig | null): void {try {const control = await window.cth.controlSnapshot(a.id);if (control?.autoDeliveryPaused) continue;- if (!isTerminalAutomationSafe(a.ptyId!, now)) continue;+ // Same gate as the queue drain, and for the same reason: this loop+ // types a nudge into the prompt. It used to check only "is it safe?",+ // which goes true the moment an abandoned draft expires — so the nudge+ // fused onto the user's half-typed line and submitted both as one+ // corrupted prompt. Preparing (and parking the draft) is the fix.+ const prep = prepareTerminalForAutomation(a.ptyId!, now);+ parkDiscardedDraft(a.id, prep.discardedDraft);+ if (!prep.ready) continue;const inbox = await window.cth.hiveInbox(a.id);// Dedup by the newest message id, not the count — a count can oscillate// as messages drain and re-arrive, which would re-nudge for the same set.@@ -520,20 +538,13 @@ export function useHive(config: HarnessConfig | null): void {if (control?.autoDeliveryPaused) return { sent: false };// Hold queued messages until the target finishes its boot sequence.if ((bootGraceUntil.current[target.id] ?? 0) >= now) return { sent: false };- if (!isTerminalAutomationSafe(target.ptyId, now)) return { sent: false };+ // Clears an abandoned draft / closes an expired picker and parks anything+ // it took off the prompt. Not ready yet means the TUI was just sent the+ // key that frees the line; we come back for it on the next tick.+ const prep = prepareTerminalForAutomation(target.ptyId, now);+ parkDiscardedDraft(target.id, prep.discardedDraft);+ if (!prep.ready) 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 —- // 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/store/store.ts b/src/renderer/src/store/store.tsindex 90daa7e6..f3f830fd 100644--- a/src/renderer/src/store/store.ts+++ b/src/renderer/src/store/store.ts@@ -382,7 +382,7 @@ function newQueuedId(): string {return `q-${Date.now()}-${queuedSeq}`;}-export const useStore = create<State>((set) => ({+export const useStore = create<State>((set, get) => ({agents: initialAgents,archivedAgents: initialArchivedAgents,restorableAgents: initialRestorableAgents,@@ -414,17 +414,28 @@ export const useStore = create<State>((set) => ({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 */ });+ const applyName = (value: string): void => {+ set((s) => {+ const agents = s.agents.map((a) => a.id === id ? { ...a, name: value } : 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: value } : a);+ persistAgents(agents, s.selectedId);+ persistRestorable(restorable);+ return { agents, restorableAgents: restorable };+ });+ };+ const previous = get().agents.find((a) => a.id === id)?.name+ ?? get().restorableAgents.find((a) => a.id === id)?.name;+ applyName(next);+ // The registry is the roster every OTHER agent reads. If it refuses the+ // rename there is no such thing as a local-only success — keeping the new+ // name here would mean this agent answers to two different names depending+ // on who is asking. Put it back and let the user see the rename didn't take.+ const rollBack = (): void => { if (previous !== undefined) applyName(previous); };+ void window.cth.hiveRename(id, next)+ .then((res) => { if (!res?.ok) rollBack(); })+ .catch(rollBack);},pushFeed: (id, line) =>set((s) => ({ feeds: { ...s.feeds, [id]: [...(s.feeds[id] ?? []), line] } })),diff --git a/test/terminal-automation.test.cjs b/test/terminal-automation.test.cjsindex 07b0c28d..573db493 100644--- a/test/terminal-automation.test.cjs+++ b/test/terminal-automation.test.cjs@@ -11,6 +11,7 @@ const {shouldFollowTerminalOutput,terminalAutomationBlock,isStaleTerminalPicker,+ nextTerminalAutomationAction,STALE_INPUT_MS,STALE_PICKER_MS} = loadTs('src/renderer/src/components/terminalAutomation.ts');@@ -92,6 +93,43 @@ test('automation block reports why delivery is held', () => {);});+test('an expired block is closed, never typed through', () => {+ const at = 1_000_000;+ const ready = { exited: false, pickerOpen: false, inputDirty: false, settleUntil: 0 };+ assert.equal(nextTerminalAutomationAction(ready, at), 'go');++ // Fresh picker / draft: wait, exactly as before.+ const picker = { ...ready, pickerOpen: true, pickerOpenedAt: at };+ const draft = { ...ready, inputDirty: true, inputDirtyAt: at };+ assert.equal(nextTerminalAutomationAction(picker, at + 1), 'wait');+ assert.equal(nextTerminalAutomationAction(draft, at + 1), 'wait');++ // Expired: the caller must FREE the prompt, not assume it is free. Letting an+ // expiry read as 'go' typed queued messages into a still-open menu (and marked+ // them delivered) and fused inbox nudges onto the user's half-written line.+ assert.equal(nextTerminalAutomationAction(picker, at + STALE_PICKER_MS), 'dismiss-picker');+ assert.equal(nextTerminalAutomationAction(draft, at + STALE_INPUT_MS), 'clear-draft');++ // Both expired: close the menu first — Ctrl-U inside a picker edits its filter+ // instead of clearing the prompt.+ assert.equal(+ nextTerminalAutomationAction(+ { ...ready, pickerOpen: true, pickerOpenedAt: at, inputDirty: true, inputDirtyAt: at },+ at + STALE_PICKER_MS+ ),+ 'dismiss-picker'+ );++ // No timestamp ⇒ never expires, so nothing silently changes for a state+ // recorded before these fields existed.+ assert.equal(nextTerminalAutomationAction({ ...ready, pickerOpen: true }, at + 1e9), 'wait');+ assert.equal(nextTerminalAutomationAction({ ...ready, inputDirty: true }, at + 1e9), 'wait');++ // A dead pty cannot be freed by typing into it, and settling just waits.+ assert.equal(nextTerminalAutomationAction({ ...ready, exited: true }, at), 'wait');+ assert.equal(nextTerminalAutomationAction({ ...ready, settleUntil: at + 1 }, at), 'wait');+});+test('terminal output follows only when already at the bottom', () => {assert.equal(shouldFollowTerminalOutput(100, 100), true);assert.equal(shouldFollowTerminalOutput(99, 100), true);