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

test(hive): cover the delivery-time precondition gate

Chaitanya Giri1320d7e59640
diff --git a/src/renderer/src/hooks/queueDelivery.ts b/src/renderer/src/hooks/queueDelivery.ts
index 83fb150f..cf89064f 100644
--- a/src/renderer/src/hooks/queueDelivery.ts
+++ b/src/renderer/src/hooks/queueDelivery.ts
@@ -54,3 +54,39 @@ export function canDeliverToAgent(
if (status !== 'looping') return false;
return ptyQuietMs !== null && ptyQuietMs >= quiesceMs;
}
+
+/** The subset of a QueuedMessage this module needs. Kept structural so the
+ * gate is testable without dragging the store (and zustand) into the test. */
+export interface DeliveryGateMessage {
+ precondition?: 'inbox-nonempty';
+}
+
+export type PreconditionVerdict = 'send' | 'drop';
+
+/** Re-check a queued message's delivery-time precondition, immediately before it
+ * is typed into a PTY.
+ *
+ * A queue item is decided at enqueue time and delivered an arbitrary interval
+ * later, so some messages describe a world that may no longer exist by the time
+ * their turn comes. The inbox-wake nudge is the motivating case: an agent that
+ * is already awake routinely drains its whole inbox during the same turn the
+ * nudge was queued from, and delivering it afterwards spends a full turn
+ * discovering there is nothing to read.
+ *
+ * Returns 'drop', never 'defer': a stale message left at the head of the queue
+ * would block every message behind it forever.
+ *
+ * Fails OPEN. If the inbox cannot be read we send, because a spurious nudge
+ * costs one turn whereas a swallowed one can leave real mail unread
+ * indefinitely. */
+export async function checkPrecondition(
+ message: DeliveryGateMessage,
+ readInbox: () => Promise<{ id?: string }[]>
+): Promise<PreconditionVerdict> {
+ if (message.precondition !== 'inbox-nonempty') return 'send';
+ try {
+ return (await readInbox()).length > 0 ? 'send' : 'drop';
+ } catch {
+ return 'send';
+ }
+}
diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.ts
index f237d332..139fbd85 100644
--- a/src/renderer/src/hooks/useHive.ts
+++ b/src/renderer/src/hooks/useHive.ts
@@ -20,7 +20,7 @@ import { bridgeOf, providerPreset } from '../../../shared/agentProvider';
import { isDurableRole, preferredAgentRole, roleForHiveSpawn } from '../../../shared/agentRole';
import { inboxNudgeText } from '../../../shared/hiveNudge';
import { acquireTerminal, resetTerminal, isTerminalAutomationSafe } from '@/components/terminalPool';
-import { canDeliverToAgent, deliverWithAcknowledgement } from './queueDelivery';
+import { canDeliverToAgent, deliverWithAcknowledgement, checkPrecondition } from './queueDelivery';
import { OFFICE_CAST, DEFAULT_CHARACTER } from '@/scene/office/cast';
const GOD_ID = 'god';
@@ -820,18 +820,9 @@ export function useHive(config: HarnessConfig | null): void {
// there is still something in the inbox — the agent routinely drains it in
// the very turn the nudge was queued from. Stale ones are DROPPED, not
// deferred, so they cannot park at the queue head and starve the rest.
- if (next.precondition === 'inbox-nonempty') {
- let stillPending = true;
- try {
- stillPending = (await window.cth.hiveInbox(srcId)).length > 0;
- } catch {
- // Can't tell — let it through. A spurious nudge costs a turn; a
- // swallowed one can leave real mail sitting unread indefinitely.
- }
- if (!stillPending) {
- removeQueuedMessage(srcId, next.id);
- return { sent: false };
- }
+ if (await checkPrecondition(next, () => window.cth.hiveInbox(srcId)) === 'drop') {
+ removeQueuedMessage(srcId, next.id);
+ return { sent: false };
}
const flightKey = `${srcId}:${next.id}`;
if (inFlight.has(flightKey)) return { sent: false };
diff --git a/test/queue-delivery.test.cjs b/test/queue-delivery.test.cjs
index e6819242..c92125ea 100644
--- a/test/queue-delivery.test.cjs
+++ b/test/queue-delivery.test.cjs
@@ -4,7 +4,7 @@ const test = require('node:test');
const assert = require('node:assert/strict');
const loadTs = require('./load-ts.cjs');
-const { deliverWithAcknowledgement, canDeliverToAgent } =
+const { deliverWithAcknowledgement, canDeliverToAgent, checkPrecondition } =
loadTs('src/renderer/src/hooks/queueDelivery.ts');
const QUIESCE_MS = 12_000; // mirrors QUIESCE_IDLE_MS in useHive
@@ -68,3 +68,40 @@ test('a mid-turn agent still holds the prompt', () => {
'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);
});
+
+// --- delivery-time preconditions -------------------------------------------
+// A queued message is decided at enqueue time and typed an arbitrary interval
+// later. The inbox-wake nudge is only worth sending if the inbox is STILL
+// non-empty when its turn comes: an already-awake agent routinely drains the
+// whole inbox during the same turn the nudge was queued from, and delivering it
+// afterwards burns a full turn discovering there is nothing to read.
+
+const nudge = { precondition: 'inbox-nonempty' };
+const inboxOf = (...ids) => () => Promise.resolve(ids.map((id) => ({ id })));
+
+test('nudge is sent while its inbox still holds mail', async () => {
+ assert.equal(await checkPrecondition(nudge, inboxOf('m1')), 'send');
+});
+
+test('nudge is DROPPED when the inbox was drained before delivery', async () => {
+ // The regression: this is the state after the agent read and .done-ed its
+ // whole inbox in the same turn the nudge was queued from.
+ assert.equal(await checkPrecondition(nudge, inboxOf()), 'drop');
+});
+
+test('nudge is sent when the inbox cannot be read', async () => {
+ // Fails OPEN on purpose: a spurious nudge costs one turn, a swallowed one can
+ // leave real mail unread indefinitely.
+ const unreadable = () => Promise.reject(new Error('ipc down'));
+ assert.equal(await checkPrecondition(nudge, unreadable), 'send');
+});
+
+test('messages without a precondition never consult the inbox', async () => {
+ let consulted = false;
+ const verdict = await checkPrecondition({}, () => {
+ consulted = true;
+ return Promise.resolve([]);
+ });
+ assert.equal(verdict, 'send');
+ assert.equal(consulted, false);
+});