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(queue): one gate for every automatic writer, and stop guessing at the prompt

Vyapak Goyal50e8f94d6dba
diff --git a/src/renderer/src/components/AgentCard.tsx b/src/renderer/src/components/AgentCard.tsx
index 0c2631bc..e8010b4b 100644
--- a/src/renderer/src/components/AgentCard.tsx
+++ b/src/renderer/src/components/AgentCard.tsx
@@ -1,5 +1,6 @@
import { PixelPanel } from './PixelPanel';
import { PixelBadge, StatusKind } from './PixelBadge';
+import { useHasTerminalDraft } from './terminalPool';
import { SpritePortrait } from './SpritePortrait';
import { AccentColorName } from '@/design/tokens';
import { OfficeCharacterName } from '@/scene/office/cast';
@@ -9,6 +10,10 @@ export interface AgentCardProps {
character: OfficeCharacterName;
accent: AccentColorName;
status: StatusKind;
+ /** This agent's pty, if it has one. Only used to notice that the USER has
+ * unsent text on its prompt — which holds the agent's queue, and otherwise
+ * looks identical to an idle agent with nothing to do. */
+ ptyId?: string;
project: string;
action?: string;
/** Context gauge: 0..8 segments filled (session context ÷ context limit). */
@@ -31,10 +36,11 @@ export interface AgentCardProps {
const fmtK = (n: number): string => `${Math.round(n / 1000)}k`;
export function AgentCard({
- name, character, accent, status, project, action, progress = 0,
+ name, character, accent, status, ptyId, project, action, progress = 0,
contextTokens, contextLimit, selected, isGod, onClick,
doingCount = 0, onTaskNoteClick, draggable
}: AgentCardProps) {
+ const typing = useHasTerminalDraft(ptyId);
// The god is always framed (stands out from the row); others only when selected.
const framed = isGod || selected;
@@ -96,7 +102,7 @@ export function AgentCard({
overflow: 'hidden',
textOverflow: 'ellipsis'
}}>{name.toUpperCase()}</span>
- <PixelBadge status={status} />
+ <PixelBadge status={typing ? 'typing' : status} />
</div>
<div style={{
diff --git a/src/renderer/src/components/AgentStrip.tsx b/src/renderer/src/components/AgentStrip.tsx
index 26b70cab..4dacdd89 100644
--- a/src/renderer/src/components/AgentStrip.tsx
+++ b/src/renderer/src/components/AgentStrip.tsx
@@ -168,6 +168,7 @@ export function AgentStrip({ config }: AgentStripProps) {
character={a.character}
accent={a.accent}
status={a.status}
+ ptyId={a.ptyId}
project={a.project}
action={a.action}
progress={a.progress}
diff --git a/src/renderer/src/components/FullscreenTerminal.tsx b/src/renderer/src/components/FullscreenTerminal.tsx
index e7195043..491aca41 100644
--- a/src/renderer/src/components/FullscreenTerminal.tsx
+++ b/src/renderer/src/components/FullscreenTerminal.tsx
@@ -13,6 +13,7 @@ import { useStore, type Agent } from '@/store/store';
import { usePtyParser } from '@/hooks/usePtyParser';
import { useRestoreTeam } from '@/hooks/useRestoreTeam';
import { useTerminalFontSize } from './terminalFontSize';
+import { useHasTerminalDraft } from './terminalPool';
import type { HarnessConfig } from '@/store/config';
/** Roster rail width. A fixed 232px is right on a 14" laptop but reads as a
@@ -481,6 +482,8 @@ function SidebarRow({
// One line of the note = one bullet on the row.
const bullets = (agent.note ?? '').split('\n').map(s => s.trim()).filter(Boolean);
+ const typing = useHasTerminalDraft(agent.ptyId);
+
useEffect(() => () => {
if (hideTimer.current !== null) window.clearTimeout(hideTimer.current);
}, []);
@@ -571,7 +574,10 @@ function SidebarRow({
fontFamily: 'var(--cth-font-display)',
fontSize: scale.name, lineHeight: 1.5
}}>{agent.name.toUpperCase()}</span>
- <PixelBadge status={agent.status} />
+ {/* Your unsent text outranks the agent's own state here: an idle
+ agent with a draft on its prompt is not idle-and-free, it is
+ idle-and-held, and nothing else on screen said so. */}
+ <PixelBadge status={typing ? 'typing' : agent.status} />
</div>
{/* Every line of every agent, always on screen — the roster's job is
to answer "who is on what" without a single interaction. */}
@@ -677,6 +683,7 @@ function SidebarRow({
}
function Header({ agent }: { agent: Agent }) {
+ const typing = useHasTerminalDraft(agent.ptyId);
return (
<div style={{
display: 'flex', alignItems: 'center', gap: 12,
@@ -698,7 +705,7 @@ function Header({ agent }: { agent: Agent }) {
fontStyle: 'italic'
}}>“{agent.description}”</span>
<div style={{ marginLeft: 'auto' }}>
- <PixelBadge status={agent.status} />
+ <PixelBadge status={typing ? 'typing' : agent.status} />
</div>
</div>
);
diff --git a/src/renderer/src/components/PixelBadge.tsx b/src/renderer/src/components/PixelBadge.tsx
index f04d4acb..5ee069f3 100644
--- a/src/renderer/src/components/PixelBadge.tsx
+++ b/src/renderer/src/components/PixelBadge.tsx
@@ -4,7 +4,12 @@ export type StatusKind =
| 'idle' | 'thinking' | 'working' | 'waiting' | 'blocked' | 'success' | 'ghost'
// #5C — richer states driven by real events: PreCompact/PostCompact hooks and
// the Lane A circuit breaker (#6) respectively.
- | 'compacting' | 'looping';
+ | 'compacting' | 'looping'
+ // Not an agent state at all — the USER has unsubmitted text on that agent's
+ // prompt, which holds its queue. Never stored on the agent (the pty parser
+ // would overwrite it); derived at render, see `hasTerminalDraft`. Without it
+ // a held queue looked identical to an idle agent doing nothing.
+ | 'typing';
export interface PixelBadgeProps {
status: StatusKind;
@@ -21,7 +26,8 @@ const colorByStatus: Record<StatusKind, string> = {
success: 'var(--cth-status-success)',
ghost: 'var(--cth-status-ghost)',
compacting: 'var(--cth-status-compacting)',
- looping: 'var(--cth-status-looping)'
+ looping: 'var(--cth-status-looping)',
+ typing: 'var(--cth-status-typing)'
};
// Human-readable labels. "blocked" is reserved for the god agent waiting on YOU,
@@ -36,7 +42,10 @@ const labelByStatus: Record<StatusKind, string> = {
success: 'done',
ghost: 'gone',
compacting: 'compacting',
- looping: 'looping'
+ looping: 'looping',
+ // Reads as "you are typing", not "the agent is typing" — it is your text
+ // sitting on the prompt, and it is why nothing is being delivered.
+ typing: 'your draft'
};
export function PixelBadge({ status, label, style }: PixelBadgeProps) {
diff --git a/src/renderer/src/components/terminalAutomation.ts b/src/renderer/src/components/terminalAutomation.ts
index 86e16fa6..a43a71db 100644
--- a/src/renderer/src/components/terminalAutomation.ts
+++ b/src/renderer/src/components/terminalAutomation.ts
@@ -36,22 +36,27 @@ export function shouldFollowTerminalOutput(viewportY: number, baseY: number): bo
}
/** How long an untouched draft on the prompt keeps blocking queue delivery.
- * A draft blocks so automation can't fuse its text with the user's, but the
- * block MUST expire: the renderer's line buffer is only a model of the real
- * input line, and a TUI that swallows keystrokes for its own UI can leave the
- * buffer non-empty while the prompt looks clear — which used to wedge an
- * agent's queue permanently with the composer still claiming it was sending. */
-export const STALE_INPUT_MS = 60_000;
+ *
+ * The block exists so automation can't fuse its text onto a half-written line.
+ * It still has to expire, because the flag is set from KEYSTROKES and a TUI that
+ * swallows keys for its own UI can leave it set while the prompt is visibly
+ * empty — a phantom draft, which wedged the queue for the rest of the session.
+ *
+ * Half an hour, not a minute. The old 60s window fired while the user had merely
+ * paused to think, and treating a real draft as abandoned is the expensive
+ * mistake; leaving a queued message parked a while longer is the cheap one. When
+ * it does fire, delivery simply types after the existing text (the two fuse into
+ * one prompt) — automation never deletes what the user wrote. */
+export const STALE_INPUT_MS = 1_800_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;
+ * The picker latch is set when the user submits a bare `/model`-style command
+ * and is cleared by an Enter, Escape or Ctrl-C typed into that terminal — so a
+ * picker closed any other way leaves it set with no path back. Same half hour,
+ * same reason: it is the user's menu, so wait a long time, then deliver. We
+ * never send Escape ourselves; closing someone's open menu to make room for a
+ * queued message is not ours to do. */
+export const STALE_PICKER_MS = 1_800_000;
export interface TerminalAutomationState {
exited: boolean;
@@ -96,32 +101,6 @@ 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.ts
index cf435d2f..1c5d8be0 100644
--- a/src/renderer/src/components/terminalPool.ts
+++ b/src/renderer/src/components/terminalPool.ts
@@ -13,6 +13,7 @@
* unmount — the rendered content moves with it, so the terminal is always
* visible immediately, no repaint required.
*/
+import { useEffect, useState } from 'react';
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import { WebglAddon } from '@xterm/addon-webgl';
@@ -26,7 +27,6 @@ import {
} from './terminalRecovery';
import {
canAutomateTerminal,
- nextTerminalAutomationAction,
opensInteractiveTerminalUi,
shouldFollowTerminalOutput,
terminalAutomationBlock,
@@ -262,13 +262,73 @@ export function isTerminalAutomationSafe(ptyId: string, now = Date.now()): boole
return canAutomateTerminal(automationStateOf(entry), now);
}
+/** Characters a TUI paints around its input line that are not the user's text:
+ * the box the prompt sits in and the prompt marker itself. */
+const PROMPT_CHROME = /[─-╿\s>❯$#|]/g;
+
+/** Does the terminal's rendered prompt line actually hold text right now?
+ *
+ * `inputDirty` is inferred by counting keystrokes, and that model DRIFTS: a TUI
+ * that swallows keys for its own UI (a menu, a confirm) leaves the count above
+ * zero while the visible prompt is empty. Nothing ever corrected it, so the
+ * queue stayed blocked by a draft that did not exist — the "messages never
+ * arrive" bug. xterm already holds the rendered screen, so read it instead of
+ * trusting the count.
+ *
+ * Returns null when the screen cannot be read (the terminal has not been opened
+ * yet, or the row is missing). Deliberately only ever used to CLEAR a phantom,
+ * never to invent a draft: if this says "empty" we believe it, and if it says
+ * "has text" or "don't know" we fall back to the keystroke model. Being wrong
+ * the other way would type over something the user really did write. */
+function promptLineHasText(entry: TerminalEntry): boolean | null {
+ if (!entry.opened || entry.exited) return null;
+ try {
+ const buf = entry.term.buffer.active;
+ const line = buf.getLine(buf.baseY + buf.cursorY);
+ if (!line) return null;
+ // `true` trims trailing whitespace cells, which a TUI pads its box with.
+ return line.translateToString(true).replace(PROMPT_CHROME, '').length > 0;
+ } catch {
+ return null; // never let a buffer read break delivery
+ }
+}
+
+/** Whether the user has unsubmitted text sitting on this terminal's prompt.
+ * Drives both the automation gate and the roster's "typing" badge, so the badge
+ * can never disagree with the reason delivery is being held. */
+export function hasTerminalDraft(ptyId: string | undefined): boolean {
+ if (!ptyId) return false;
+ const entry = pool.get(ptyId);
+ if (!entry) return false;
+ return entry.inputDirty && promptLineHasText(entry) !== false;
+}
+
+/** `hasTerminalDraft` as React state. The flag lives on a mutable pool entry
+ * that no component subscribes to, so poll it — cheap (one buffer row read) and
+ * a second of lag on a badge is invisible. */
+export function useHasTerminalDraft(ptyId: string | undefined): boolean {
+ const [dirty, setDirty] = useState(() => hasTerminalDraft(ptyId));
+ useEffect(() => {
+ // An agent with no pty has no prompt to hold anything — don't run a timer
+ // per card for it (the floor renders one card per agent).
+ if (!ptyId) { setDirty(false); return; }
+ const read = () => setDirty(hasTerminalDraft(ptyId));
+ read();
+ const iv = setInterval(read, 1000);
+ return () => clearInterval(iv);
+ }, [ptyId]);
+ return dirty;
+}
+
function automationStateOf(entry: TerminalEntry) {
+ // The screen wins over the keystroke count, but only when it says "empty".
+ const inputDirty = entry.inputDirty && promptLineHasText(entry) !== false;
return {
exited: entry.exited,
pickerOpen: entry.automationBlocked,
pickerOpenedAt: entry.automationBlocked ? entry.automationBlockedAt : undefined,
- inputDirty: entry.inputDirty,
- inputDirtyAt: entry.inputDirty ? entry.inputDirtyAt : undefined,
+ inputDirty,
+ inputDirtyAt: inputDirty ? entry.inputDirtyAt : undefined,
settleUntil: entry.automationSettleUntil
};
}
@@ -318,10 +378,12 @@ export function clearTerminalDraft(ptyId: string): string {
return discarded;
}
-/** 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. */
+/** Close an open picker by sending Escape, the key that actually closes one.
+ *
+ * ONLY ever called from the composer's own button — i.e. because the user asked
+ * for it. Automation must never do this on its own: the menu belongs to the
+ * user, and we cannot see whether Escape actually closed it, so closing one to
+ * make room for a queued message is both rude and unverifiable. */
export function dismissTerminalPicker(ptyId: string): void {
const entry = pool.get(ptyId);
if (!entry || entry.exited) return;
@@ -329,49 +391,6 @@ export function dismissTerminalPicker(ptyId: string): void {
releasePickerBlock(entry);
}
-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);
- // 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.
*
* The DOM renderer assumes a perfectly monospace font, but VT323 is missing
diff --git a/src/renderer/src/design/tokens.css b/src/renderer/src/design/tokens.css
index eb33f3e8..ceb2b3fd 100644
--- a/src/renderer/src/design/tokens.css
+++ b/src/renderer/src/design/tokens.css
@@ -33,6 +33,7 @@
--cth-status-ghost: #D9CFE0;
--cth-status-compacting: #9B7EDE; /* #5C — mid-/compact, "boxing up context" */
--cth-status-looping: #FF9F43; /* #5C — circuit-breaker armed (runaway) */
+ --cth-status-typing: #E8A33D; /* unsent text on the prompt — queue is held */
/* Spacing */
--cth-space-0: 0px;
diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.ts
index 17312390..3184bba3 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 { prepareTerminalForAutomation } from '@/components/terminalPool';
+import { isTerminalAutomationSafe } from '@/components/terminalPool';
import { deliverWithAcknowledgement } from './queueDelivery';
const GOD_ID = 'god';
@@ -35,17 +35,6 @@ 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
@@ -464,32 +453,24 @@ export function useHive(config: HarnessConfig | null): void {
});
}, [config?.onboardingComplete]);
- // 3) Wake idle agents holding unread inbox messages. The assistant is
- // send-only (it never receives inbox mail), so it's excluded.
+ // 3) Wake agents holding unread inbox messages. The assistant is send-only
+ // (it never receives inbox mail), so it's excluded.
+ //
+ // QUEUES the nudge rather than typing it. This loop used to write straight
+ // into the terminal, which made it the one automatic writer that could land
+ // on top of whatever the user was typing — its text fused onto the user's
+ // half-written line and the pair got submitted as one garbled prompt. Going
+ // through the queue means effect #4 owns every decision about when a
+ // terminal may be typed into: idle, off cooldown, past boot grace, delivery
+ // not paused, and no user draft in the way. One gate, one place, and this
+ // loop stops needing prompt logic of its own. /compact (effect #6) has
+ // always worked this way.
useEffect(() => {
if (!config?.onboardingComplete) return;
const iv = setInterval(async () => {
- const now = Date.now();
- const agents = useStore.getState().agents.filter(
- // Never type into an explicit human/permission wait. A worker waiting on
- // the user must stay parked until the user answers or resumes delivery.
- (a) => a.ptyId && a.status === 'idle'
- // Don't type into an agent still running its boot sequence — the nudge
- // would collide with /remote-control + the orientation prompt.
- && (bootGraceUntil.current[a.id] ?? 0) < now
- );
+ const agents = useStore.getState().agents.filter((a) => a.ptyId);
for (const a of agents) {
try {
- const control = await window.cth.controlSnapshot(a.id);
- if (control?.autoDeliveryPaused) 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.
@@ -497,10 +478,9 @@ export function useHive(config: HarnessConfig | null): void {
? inbox.map((m) => m.id).sort().slice(-1)[0]
: '';
if (newest && nudged.current[a.id] !== newest) {
- await submitToPty(
- a.ptyId!,
- 'You have new hive inbox message(s) — read your inbox, act on them now, and move handled ones to inbox/.done/. Act autonomously; only message god if you genuinely need a decision.',
- inferAgentProvider(a.command, a.provider)
+ useStore.getState().enqueueMessage(
+ a.id,
+ '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.'
);
nudged.current[a.id] = newest;
} else if (!newest) {
@@ -538,12 +518,11 @@ 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 };
- // 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 };
+ // The user owns the prompt: a draft they are writing, or a menu they
+ // opened, holds delivery. Both blocks expire after half an hour, and when
+ // one does we simply type after whatever is there — automation never
+ // erases the user's text and never closes the user's menu.
+ if (!isTerminalAutomationSafe(target.ptyId, now)) return { sent: false };
if (now - (lastFlush.current[target.id] ?? 0) < FLUSH_COOLDOWN_MS) return { sent: false };
const flightKey = `${srcId}:${next.id}`;
if (inFlight.has(flightKey)) return { sent: false };
diff --git a/src/renderer/src/store/store.ts b/src/renderer/src/store/store.ts
index 05d43e56..954054cd 100644
--- a/src/renderer/src/store/store.ts
+++ b/src/renderer/src/store/store.ts
@@ -233,6 +233,20 @@ function persistAgents(agents: Agent[], selectedId: string | null): void {
} catch { /* noop */ }
}
+/** Run-state an agent recomputes from its live pty on every reload. A patch made
+ * only of these is not worth a localStorage write; anything else is. Listed as
+ * the volatile set rather than the durable set on purpose — a new durable field
+ * then persists by default instead of being silently dropped. */
+const VOLATILE_AGENT_FIELDS = new Set<keyof Agent>([
+ 'status', 'action', 'progress', 'currentStation', 'carrying',
+ 'recentAssistantText', 'recentTextTs', 'blockReason',
+ 'contextTokens', 'contextLimit', 'lastPrompt'
+]);
+
+function touchesDurableAgentField(patch: Partial<Agent>): boolean {
+ return Object.keys(patch).some((k) => !VOLATILE_AGENT_FIELDS.has(k as keyof Agent));
+}
+
function loadPersistedAgents(): Agent[] {
try {
const raw = window.localStorage.getItem(LS_AGENTS);
@@ -400,7 +414,17 @@ export const useStore = create<State>((set) => ({
setGodStatus: (status) => set({ godStatus: status }),
select: (id) => set((s) => { persistAgents(s.agents, id); return { selectedId: id, ccTabRequest: null }; }),
updateAgent: (id, patch) =>
- set((s) => ({ agents: s.agents.map(a => a.id === id ? { ...a, ...patch } : a) })),
+ set((s) => {
+ const agents = s.agents.map(a => a.id === id ? { ...a, ...patch } : a);
+ // Persist only when something DURABLE changed. `updateAgent` is also the
+ // pty parser's per-chunk write (status/action/progress), so persisting
+ // unconditionally would rewrite localStorage on every burst of terminal
+ // output. Persisting nothing was worse: a model or command change lived
+ // only in memory, so the selector snapped back to the old model on reload
+ // and restore relaunched the old command.
+ if (touchesDurableAgentField(patch)) persistAgents(agents, s.selectedId);
+ return { agents };
+ }),
setAgentNote: (id, note) =>
set((s) => {
const agents = s.agents.map((a) => a.id === id ? { ...a, note } : a);
diff --git a/test/terminal-automation.test.cjs b/test/terminal-automation.test.cjs
index 573db493..69434dcb 100644
--- a/test/terminal-automation.test.cjs
+++ b/test/terminal-automation.test.cjs
@@ -11,7 +11,6 @@ const {
shouldFollowTerminalOutput,
terminalAutomationBlock,
isStaleTerminalPicker,
- nextTerminalAutomationAction,
STALE_INPUT_MS,
STALE_PICKER_MS
} = loadTs('src/renderer/src/components/terminalAutomation.ts');
@@ -93,41 +92,27 @@ test('automation block reports why delivery is held', () => {
);
});
-test('an expired block is closed, never typed through', () => {
+test('the user owns the prompt for a long time before automation takes it', () => {
+ // Half an hour, both blocks. A 60s window fired while the user had merely
+ // paused to think; treating a live draft as abandoned is the expensive
+ // mistake, and parking a queued message a while longer is the cheap one.
+ assert.equal(STALE_INPUT_MS, 1_800_000);
+ assert.equal(STALE_PICKER_MS, 1_800_000);
+
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'
- );
+ const picker = { ...ready, pickerOpen: true, pickerOpenedAt: at };
- // 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');
+ // Ten minutes in, both still belong to the user.
+ assert.equal(canAutomateTerminal(draft, at + 600_000), false);
+ assert.equal(canAutomateTerminal(picker, at + 600_000), false);
- // 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');
+ // Past the window delivery proceeds — it types AFTER whatever is on the line
+ // (the two fuse into one prompt). Automation never erases the user's text and
+ // never closes the user's menu, so there is nothing to undo either way.
+ assert.equal(canAutomateTerminal(draft, at + STALE_INPUT_MS), true);
+ assert.equal(canAutomateTerminal(picker, at + STALE_PICKER_MS), true);
});
test('terminal output follows only when already at the bottom', () => {