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(renderer): never type into a prompted agent; stop the queue drain destroying mail (#113)
Quentin Schmick0ac16850f512
diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.tsindex 37c85f9a..3f9959a9 100644--- a/src/renderer/src/hooks/useHive.ts+++ b/src/renderer/src/hooks/useHive.ts@@ -91,9 +91,16 @@ function submitToPty(ptyId: string, text: string, settleMs = 250): Promise<void>// commands) is sent raw — some TUIs (Antigravity's agy) treat the paste// markers as literal input and never submit, so skipping them is more robust.const payload = text.includes('\n') ? `\x1b[200~${text}\x1b[201~` : text;- await window.cth.writePty(ptyId, payload);+ // writePty NEVER rejects for a dead pty — it resolves { ok:false, error:+ // 'no pty: …' } — so an unchecked await here made every failed delivery look+ // successful (the queue-drain then destroyed the message it had already+ // popped, #36). Surface the failure as a rejection; the chain itself is+ // immune (the prev.catch above absorbs it for the next writer).+ const wrote = await window.cth.writePty(ptyId, payload);+ if (!wrote?.ok) throw new Error(wrote?.error ?? `pty write failed: ${ptyId}`);await new Promise((r) => setTimeout(r, 140));- await window.cth.writePty(ptyId, '\r');+ const submitted = await window.cth.writePty(ptyId, '\r');+ if (!submitted?.ok) throw new Error(submitted?.error ?? `pty write failed: ${ptyId}`);await new Promise((r) => setTimeout(r, settleMs));});writeChains.set(ptyId, next);@@ -186,6 +193,13 @@ export function useHive(config: HarnessConfig | null): void {// 'working' (there's a short window where it still reads 'idle' right after we// type into it). One message per cooldown keeps delivery strictly one-by-one.const lastFlush = useRef<Record<string, number>>({});+ // Queue-drain delivery tracking (#36): a message now stays IN the queue until+ // its PTY write chain resolves, so `inFlightSends` (message ids mid-write)+ // stops a store-update burst from double-sending the head, and `sendFailures`+ // bounds retries — after MAX_SEND_ATTEMPTS failed writes the message is+ // dropped WITH a console.warn instead of being silently destroyed.+ const inFlightSends = useRef<Set<string>>(new Set());+ const sendFailures = useRef<Record<string, number>>({});// In-flight spawn guard so a re-render / StrictMode double-mount can't spawn// Michael twice (the window between the listPtys check and spawnPty is racy).const godSpawning = useRef(false);@@ -503,8 +517,16 @@ export function useHive(config: HarnessConfig | null): void {if (!config?.onboardingComplete) return;const iv = setInterval(async () => {const now = Date.now();+ // STRICTLY idle (#5 — permission-prompt safety). 'waiting'/'blocked' mean a+ // real approval/notification prompt is on screen (hook Notification+ // needs-human → effect #2; BLOCK_HINTS like "❯ 1. Yes" → usePtyParser), and+ // submitToPty always follows its text with a bare '\r' — at a Claude Code+ // menu that Enter SILENTLY CONFIRMS the highlighted "1. Yes". So the nudge+ // never types into a prompted agent; it simply defers (nudged is only+ // stamped when we actually type) and fires once the prompt clears and the+ // agent drifts idle. This matches the queue-drain's idle-only gate (#4).const agents = useStore.getState().agents.filter(- (a) => a.ptyId && (a.status === 'idle' || a.status === 'waiting')+ (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@@ -554,6 +576,18 @@ export function useHive(config: HarnessConfig | null): void {// Clear the record now so it isn't re-seen (the ref also guards) or persisted.updateAgent(a.id, { seedPrompt: undefined });setTimeout(() => {+ // Permission-prompt safety (#5): if the worker surfaced an approval /+ // needs-human prompt while its TUI booted ('waiting'/'blocked'), the+ // seed's trailing Enter would confirm it. Put the seed back and let a+ // later tick retry once the prompt clears; if the agent vanished+ // (killed mid-boot), don't type into its orphaned pty at all.+ const live = useStore.getState().agents.find((x) => x.id === a.id);+ if (!live) return;+ if (live.status === 'waiting' || live.status === 'blocked') {+ seeded.current.delete(a.id);+ useStore.getState().updateAgent(a.id, { seedPrompt: seed });+ return;+ }submitToPty(ptyId, seed).catch(() => { /* pty may have died */ });}, GOD_BOOT_MS);}@@ -568,32 +602,65 @@ export function useHive(config: HarnessConfig | null): void {useEffect(() => {if (!config?.onboardingComplete) return;const FLUSH_COOLDOWN_MS = 4500;+ // A message that fails this many PTY writes (dead/crashed pty that the store+ // still thinks is idle) is dropped WITH a console.warn — bounded so the drain+ // never spins forever on a corpse, loud so the loss is diagnosable.+ const MAX_SEND_ATTEMPTS = 3;// Send the front of `srcId`'s queue into `target`'s pty (verbatim or wrapped),// gated on the target being idle + off cooldown. Keyed cooldown per target so- // strict one-by-one delivery holds. Returns true if it dispatched.+ // strict one-by-one delivery holds. Returns true if it INITIATED a send (the+ // message is only removed from the queue once the write chain resolves).const dispatch = (srcId: string, target: Agent | undefined, wrap?: (m: QueuedMessage) => string): boolean => {- const { messageQueues, removeQueuedMessage } = useStore.getState();+ const { messageQueues } = useStore.getState();const next = messageQueues[srcId]?.[0];if (!next || !target?.ptyId || target.status !== 'idle') return false;+ // Already mid-write — the head hasn't been confirmed delivered yet.+ if (inFlightSends.current.has(next.id)) return false;const now = Date.now();// Hold queued messages until the target finishes its boot sequence.if ((bootGraceUntil.current[target.id] ?? 0) >= now) return false;if (now - (lastFlush.current[target.id] ?? 0) < FLUSH_COOLDOWN_MS) return false;lastFlush.current[target.id] = now;- // Remove first so a burst of store updates can't double-send the same one.- removeQueuedMessage(srcId, next.id);- // Zero the gauge instantly on /clear — the new session's context isn't- // known until statusLine fires after the first post-clear response, so- // leaving it at the old value shows a stale-full bar during that window.- if (next.text.trim().toLowerCase() === '/clear') {- useStore.getState().updateAgent(target.id, { contextTokens: 0, contextLimit: undefined, progress: 0 });- }+ // Remove only AFTER the write chain confirms delivery (#36). The old+ // remove-first ordering + writePty's resolve-on-{ok:false} contract meant a+ // message to a crashed-but-'idle' agent was popped, the write failed, and+ // nothing ever heard about it — one message silently destroyed per cooldown.+ // Double-send safety now comes from inFlightSends + the cooldown above.+ inFlightSends.current.add(next.id);+ const ptyId = target.ptyId;+ const targetId = target.id;// `instruction` (when present) is the authoritative text to type into the// PTY — e.g. Slack-origin work carries the autonomy preamble there while the// kanban card keeps `text` (raw) as its readable title. UI/card surfaces// never read `instruction`, so this stays invisible to the human board.- submitToPty(target.ptyId, wrap ? wrap(next) : (next.instruction ?? next.text)).catch(() => { /* pty may have died */ });+ submitToPty(ptyId, wrap ? wrap(next) : (next.instruction ?? next.text))+ .then(() => {+ inFlightSends.current.delete(next.id);+ delete sendFailures.current[next.id];+ useStore.getState().removeQueuedMessage(srcId, next.id);+ // Zero the gauge on a DELIVERED /clear — the new session's context isn't+ // known until statusLine fires after the first post-clear response, so+ // leaving it at the old value shows a stale-full bar during that window.+ if (next.text.trim().toLowerCase() === '/clear') {+ useStore.getState().updateAgent(targetId, { contextTokens: 0, contextLimit: undefined, progress: 0 });+ }+ })+ .catch((err) => {+ inFlightSends.current.delete(next.id);+ const attempts = (sendFailures.current[next.id] ?? 0) + 1;+ sendFailures.current[next.id] = attempts;+ if (attempts >= MAX_SEND_ATTEMPTS) {+ delete sendFailures.current[next.id];+ useStore.getState().removeQueuedMessage(srcId, next.id);+ console.warn(+ `[queue-drain] dropping message ${next.id} for ${targetId} after ${attempts} failed pty writes ` ++ `("${next.text.slice(0, 80)}${next.text.length > 80 ? '…' : ''}")`,+ err+ );+ }+ // else: still queued — the cooldown-spaced flush retries it.+ });return true;};