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(queue): deliver to a breaker-pinned agent once its terminal falls silent
Ed Chancfa59f70fc69
diff --git a/src/renderer/src/hooks/queueDelivery.ts b/src/renderer/src/hooks/queueDelivery.tsindex 760d92d6..83fb150f 100644--- a/src/renderer/src/hooks/queueDelivery.ts+++ b/src/renderer/src/hooks/queueDelivery.ts@@ -12,3 +12,45 @@ export async function deliverWithAcknowledgement(return false;}}++/**+ * May the drain type into this agent's terminal right now?+ *+ * The gate used to be `status === 'idle'`, full stop, and that stranded mail+ * indefinitely. `looping` is not a terminal state the agent recovers from on its+ * own — it is the circuit breaker's PIN, re-asserted on every beat for as long+ * as the agent is `constrained` or `stopped`. The PTY-quiescence fallback only+ * un-pins `working`, so a breaker-armed agent never returned to `idle` and its+ * queue never drained. Observed live: an agent over its token cap sat pinned+ * while a nudge enqueued two seconds after the message landed went undelivered+ * for minutes, until something outside the app woke it.+ *+ * That is self-defeating, because the breaker STEERS by mailing the agent it+ * armed ("stop, write a plan, send it to god"). Under the old gate the one+ * message meant to unwedge a wedged agent was exactly the message that could+ * never arrive.+ *+ * So a pinned agent is deliverable once its terminal has been silent for+ * `quiesceMs` — the same evidence the idle fallback already trusts to decide a+ * turn is over. The pin stays on the avatar and the badge; it just stops+ * doubling as a delivery lock.+ *+ * Everything else still holds the prompt:+ * - `working` / `thinking`: mid-turn. The quiescence fallback flips a genuinely+ * finished turn to `idle`, and then the ordinary gate applies.+ * - `waiting` / `blocked`: an interactive prompt is on screen. The drain ends+ * every delivery with Enter, which would ANSWER it — the same reason the+ * one-time TUI seed refuses to type at those two statuses.+ *+ * Fails CLOSED on an unknown `ptyQuietMs` (no reading, or a PTY that has never+ * emitted): silence we cannot measure is not evidence of silence.+ */+export function canDeliverToAgent(+ status: string,+ ptyQuietMs: number | null,+ quiesceMs: number+): boolean {+ if (status === 'idle') return true;+ if (status !== 'looping') return false;+ return ptyQuietMs !== null && ptyQuietMs >= quiesceMs;+}diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.tsindex c7b10fd3..ae45fcb5 100644--- a/src/renderer/src/hooks/useHive.ts+++ b/src/renderer/src/hooks/useHive.ts@@ -17,7 +17,7 @@ import {import { DEFAULT_CONTEXT_TRIGGER, type ContextRule } from '../../../shared/triggers';import type { AgentProvider } from '../../../shared/agentProvider';import { acquireTerminal, resetTerminal, isTerminalAutomationSafe } from '@/components/terminalPool';-import { deliverWithAcknowledgement } from './queueDelivery';+import { canDeliverToAgent, deliverWithAcknowledgement } from './queueDelivery';import { OFFICE_CAST, DEFAULT_CHARACTER } from '@/scene/office/cast';const GOD_ID = 'god';@@ -287,6 +287,12 @@ export function useHive(config: HarnessConfig | null): void {const reviving = useRef<Record<string, number>>({});// Reactive so the assistant bootstrap (effect #1b) re-runs once Michael is ready.const godStatus = useStore((s) => s.godStatus);+ // Per-pty `lastOutputAt`, refreshed by the quiescence sweep (#2e) and read by+ // the queue drain (#4) so it can tell a terminal parked at its prompt from one+ // mid-turn. Kept here rather than fetched again in #4 — #2e already polls+ // listPtys on exactly the cadence the drain needs, and one reading keeps the+ // two loops from disagreeing about whether an agent is quiet.+ const ptyLastOutput = useRef<Record<string, number>>({});// #5C/#7C.4 — latest circuit-breaker level per agent. When 'constrained'/// 'stopped' the avatar is pinned to 'looping' and hook events must NOT flip it// back to 'working' (the flicker the spec calls out); only a genuine Stop clears it.@@ -563,9 +569,13 @@ export function useHive(config: HarnessConfig | null): void {if (!config?.onboardingComplete) return;const iv = setInterval(async () => {const ptys = await window.cth.listPtys().catch(() => []);- if (!ptys.length) return;const lastOut: Record<string, number> = {};for (const p of ptys) lastOut[p.id] = p.lastOutputAt;+ // Publish BEFORE the early return and before the 'working' filter below,+ // so the drain (#4) also gets a reading for breaker-pinned agents — and so+ // a vanished PTY clears its entry instead of leaving a stale one.+ ptyLastOutput.current = lastOut;+ if (!ptys.length) return;const now = Date.now();const { agents, updateAgent } = useStore.getState();for (const a of agents) {@@ -679,6 +689,14 @@ export function useHive(config: HarnessConfig | null): void {const inFlight = new Set<string>();const sendFailures: Record<string, number> = {};+ /** How long this terminal has been silent, or null when we have no reading+ * (never polled, PTY gone, or it has emitted nothing at all). canDeliverToAgent+ * fails closed on null — unmeasured silence is not evidence of silence. */+ const ptyQuietMs = (ptyId: string, now: number): number | null => {+ const last = ptyLastOutput.current[ptyId];+ return typeof last === 'number' && last > 0 ? now - last : null;+ };+// Send the front of `srcId`'s queue into `target`'s pty (verbatim or wrapped),// gated on the target being idle, free of interactive menus, and off// cooldown. The queue item is acknowledged only after BOTH PTY writes@@ -691,8 +709,14 @@ export function useHive(config: HarnessConfig | null): void {): Promise<{ sent: boolean; message?: QueuedMessage }> => {const { messageQueues, removeQueuedMessage } = useStore.getState();const next = messageQueues[srcId]?.[0];- if (!next || !target?.ptyId || target.status !== 'idle') return { sent: false };+ if (!next || !target?.ptyId) return { sent: false };const now = Date.now();+ // Idle, or breaker-pinned with a terminal that has genuinely gone quiet.+ // This gate is a don't-type-mid-stream safety check, so `manual` does NOT+ // bypass it — "send now" releases the auto-delivery PAUSE below, not this.+ if (!canDeliverToAgent(target.status, ptyQuietMs(target.ptyId, now), QUIESCE_IDLE_MS)) {+ return { sent: false };+ }const control = await window.cth.controlSnapshot(target.id);// The pause gate holds everything EXCEPT messages the user explicitly// released with "send now" (m.manual) — otherwise a paused floor leaves@@ -793,9 +817,12 @@ export function useHive(config: HarnessConfig | null): void {const flush = () => {const { agents, messageQueues } = useStore.getState();const byId = (id: string) => agents.find((a) => a.id === id);+ const now = Date.now();for (const a of agents) {- if (!a.ptyId || a.status !== 'idle') continue;+ // Same gate as dispatch() — this pre-filter runs first, so relaxing only+ // the one inside dispatch would have changed nothing.+ if (!a.ptyId || !canDeliverToAgent(a.status, ptyQuietMs(a.ptyId, now), QUIESCE_IDLE_MS)) continue;if (!messageQueues[a.id]?.length) continue;void dispatch(a.id, a).then(({ sent, message }) => {if (sent && message?.slack) void ensureSlackCard(message);diff --git a/test/queue-delivery.test.cjs b/test/queue-delivery.test.cjsindex bf4000cd..e6819242 100644--- a/test/queue-delivery.test.cjs+++ b/test/queue-delivery.test.cjs@@ -4,9 +4,11 @@ const test = require('node:test');const assert = require('node:assert/strict');const loadTs = require('./load-ts.cjs');-const { deliverWithAcknowledgement } =+const { deliverWithAcknowledgement, canDeliverToAgent } =loadTs('src/renderer/src/hooks/queueDelivery.ts');+const QUIESCE_MS = 12_000; // mirrors QUIESCE_IDLE_MS in useHive+test('queue item is acknowledged only after delivery succeeds', async () => {let finish;let acknowledged = false;@@ -31,3 +33,38 @@ test('failed delivery remains unacknowledged for retry', async () => {assert.equal(sent, false);assert.equal(acknowledged, false);});++test('an idle agent is deliverable without needing a quiescence reading', () => {+ assert.equal(canDeliverToAgent('idle', null, QUIESCE_MS), true);+ assert.equal(canDeliverToAgent('idle', 0, QUIESCE_MS), true);+});++test('a breaker-pinned agent drains once its terminal has genuinely gone quiet', () => {+ // The live stall: an agent over its token cap is pinned 'looping' by the+ // breaker on every beat, the quiescence fallback only un-pins 'working', so+ // under the old idle-only gate its queue never drained — including the+ // breaker's own steer message, the one thing meant to unwedge it.+ assert.equal(canDeliverToAgent('looping', QUIESCE_MS, QUIESCE_MS), true);+ assert.equal(canDeliverToAgent('looping', QUIESCE_MS + 5000, QUIESCE_MS), true);+ assert.equal(canDeliverToAgent('looping', QUIESCE_MS - 1, QUIESCE_MS), false,+ 'still emitting bytes — do not type into a live stream');+});++test('unmeasured silence fails closed', () => {+ assert.equal(canDeliverToAgent('looping', null, QUIESCE_MS), false,+ 'no reading is not evidence of quiet');+});++test('an agent sitting on an interactive prompt is never typed into', () => {+ // The drain submits with Enter, which would ANSWER a permission prompt that+ // nobody has read. No amount of silence makes that safe.+ for (const status of ['waiting', 'blocked']) {+ assert.equal(canDeliverToAgent(status, QUIESCE_MS * 100, QUIESCE_MS), false, status);+ }+});++test('a mid-turn agent still holds the prompt', () => {+ assert.equal(canDeliverToAgent('working', QUIESCE_MS * 100, QUIESCE_MS), false,+ 'the quiescence fallback flips a finished turn to idle — the drain does not second-guess it');+ assert.equal(canDeliverToAgent('thinking', QUIESCE_MS * 100, QUIESCE_MS), false);+});