Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(messaging): deliver-on-idle — a bounded queue with a TTL, and never a silent drop

Claude Code0c5d6be97aa7
diff --git a/src/core/agents/delivery-queue.test.ts b/src/core/agents/delivery-queue.test.ts
new file mode 100644
index 000000000..1cbdea182
--- /dev/null
+++ b/src/core/agents/delivery-queue.test.ts
@@ -0,0 +1,226 @@
+import { describe, it, expect } from 'vitest'
+import {
+ DeliveryQueue,
+ DELIVERY_QUEUE_CAPACITY,
+ DELIVERY_QUEUE_TTL_MS,
+ type DeliveryQueueDeps,
+ type QueuedDeliveryRequest,
+ type CancelTimer
+} from './delivery-queue'
+import type { AgentMessageOutcome } from './agent-message-decide'
+
+/**
+ * The bounded per-target queue, every rule driven with a fake clock, a fake scheduler and a
+ * programmable `deliver` — so TTL expiry and flush-time re-validation are deterministic rather than
+ * timing-dependent. The load-bearing test is the third-from-last: a grant revoked WHILE a message is
+ * queued is dropped, not delivered, because the flush re-runs the whole delivery instead of trusting
+ * the decision that queued it.
+ */
+
+interface FakeTimer {
+ ms: number
+ fn: () => void
+ cancelled: boolean
+}
+
+function harness(over: Partial<DeliveryQueueDeps> = {}) {
+ let clock = 1000
+ const traced: { outcome: string; sourceNodeId: string; targetNodeId: string }[] = []
+ const expired: { req: QueuedDeliveryRequest; info: { traceId: string; queuedForMs: number } }[] = []
+ const flushed: { req: QueuedDeliveryRequest; outcome: AgentMessageOutcome }[] = []
+ const woken: string[] = []
+ const timers: FakeTimer[] = []
+ let nextOutcome: AgentMessageOutcome = { kind: 'delivered', traceId: 'd', traced: 'memory', receipt: 'observed', signal: 'newTurn' }
+ const delivered: QueuedDeliveryRequest[] = []
+
+ const deps: DeliveryQueueDeps = {
+ now: () => clock,
+ deliver: async (req) => {
+ delivered.push(req)
+ return nextOutcome
+ },
+ trace: async (input) => {
+ traced.push({ outcome: input.outcome, sourceNodeId: input.sourceNodeId, targetNodeId: input.targetNodeId })
+ return { traceId: `trace-${traced.length}`, traced: 'memory' }
+ },
+ wake: (id) => woken.push(id),
+ onExpired: (req, info) => expired.push({ req, info }),
+ onFlushed: (req, outcome) => flushed.push({ req, outcome }),
+ schedule: (ms, fn): CancelTimer => {
+ const t: FakeTimer = { ms, fn, cancelled: false }
+ timers.push(t)
+ return () => {
+ t.cancelled = true
+ }
+ },
+ ...over
+ }
+
+ return {
+ deps,
+ traced,
+ expired,
+ flushed,
+ woken,
+ timers,
+ delivered,
+ setClock: (n: number): void => {
+ clock = n
+ },
+ setOutcome: (o: AgentMessageOutcome): void => {
+ nextOutcome = o
+ },
+ /** Fire the most recently armed (not-yet-cancelled) timer — a TTL lapse. */
+ fireLatestTimer: (): void => {
+ const live = timers.filter((t) => !t.cancelled)
+ live[live.length - 1].fn()
+ }
+ }
+}
+
+const req = (over: Partial<QueuedDeliveryRequest> = {}): QueuedDeliveryRequest => ({
+ sourceNodeId: 'src',
+ targetNodeId: 'dst',
+ sourceTitle: 'Alpha',
+ body: 'ping',
+ ...over
+})
+
+describe('DeliveryQueue', () => {
+ it('enqueue returns a queued receipt with position + TTL, and traces `queued`', async () => {
+ const h = harness()
+ const q = new DeliveryQueue(h.deps)
+ const out = await q.enqueue(req())
+ expect(out).toEqual({ kind: 'queued', traceId: 'trace-1', position: 1, ttlMs: DELIVERY_QUEUE_TTL_MS })
+ expect(q.depth('dst')).toBe(1)
+ expect(h.traced).toEqual([{ outcome: 'queued', sourceNodeId: 'src', targetNodeId: 'dst' }])
+ })
+
+ it('positions count up per target', async () => {
+ const h = harness()
+ const q = new DeliveryQueue(h.deps)
+ const a = await q.enqueue(req({ body: 'a' }))
+ const b = await q.enqueue(req({ body: 'b' }))
+ expect(a).toMatchObject({ kind: 'queued', position: 1 })
+ expect(b).toMatchObject({ kind: 'queued', position: 2 })
+ expect(q.depth('dst')).toBe(2)
+ })
+
+ it('refuses with `queueFull` at capacity — never drops an accepted message', async () => {
+ const h = harness()
+ const q = new DeliveryQueue(h.deps, { capacity: 2 })
+ await q.enqueue(req({ body: 'a' }))
+ await q.enqueue(req({ body: 'b' }))
+ const out = await q.enqueue(req({ body: 'c' }))
+ expect(out).toEqual({ kind: 'queueFull', capacity: 2 })
+ // The two already queued are untouched — capacity refuses the new one, it does not evict.
+ expect(q.depth('dst')).toBe(2)
+ })
+
+ it('flushes on idle: delivers oldest-first and empties the queue', async () => {
+ const h = harness()
+ const q = new DeliveryQueue(h.deps)
+ await q.enqueue(req({ body: 'first' }))
+ await q.enqueue(req({ body: 'second' }))
+ await q.onTargetIdle('dst')
+ expect(h.delivered.map((r) => r.body)).toEqual(['first', 'second'])
+ expect(q.depth('dst')).toBe(0)
+ expect(h.flushed.map((f) => f.outcome.kind)).toEqual(['delivered', 'delivered'])
+ })
+
+ it('a hibernated target is WOKEN on enqueue, before it is idle', async () => {
+ const h = harness()
+ const q = new DeliveryQueue(h.deps)
+ await q.enqueue(req(), { hibernated: true })
+ expect(h.woken).toEqual(['dst'])
+ // A merely-busy target is not woken.
+ await q.enqueue(req({ targetNodeId: 'busy' }))
+ expect(h.woken).toEqual(['dst'])
+ })
+
+ // ── THE LOAD-BEARING PROPERTY: flush-time re-validation ────────────────────────────────────────
+ it('DROPS a message whose grant was revoked while it was queued — never delivers it', async () => {
+ const h = harness()
+ const q = new DeliveryQueue(h.deps)
+ // Enqueued while the target was busy…
+ await q.enqueue(req({ body: 'secret' }))
+ expect(q.depth('dst')).toBe(1)
+ // …and by flush time the grant is gone: `deliver` (the full re-validated path) now refuses.
+ h.setOutcome({ kind: 'notPermitted', reason: 'switch-off' })
+ await q.onTargetIdle('dst')
+ // It was attempted through the real delivery (which is where the grant is checked) and DROPPED —
+ // not re-queued, not delivered.
+ expect(h.delivered.map((r) => r.body)).toEqual(['secret'])
+ expect(q.depth('dst')).toBe(0)
+ expect(h.flushed).toHaveLength(1)
+ expect(h.flushed[0].outcome).toEqual({ kind: 'notPermitted', reason: 'switch-off' })
+ // Never reported as delivered.
+ expect(h.flushed.some((f) => f.outcome.kind === 'delivered')).toBe(false)
+ })
+
+ it('a still-busy target at flush keeps the message queued (TTL from the original enqueue)', async () => {
+ const h = harness()
+ const q = new DeliveryQueue(h.deps)
+ await q.enqueue(req())
+ h.setOutcome({ kind: 'targetBusy', state: 'working' })
+ await q.onTargetIdle('dst')
+ // Attempted, found busy again, put back — not lost, not delivered.
+ expect(h.delivered).toHaveLength(1)
+ expect(q.depth('dst')).toBe(1)
+ expect(h.flushed).toHaveLength(0)
+ // A later idle when it is truly free delivers it.
+ h.setOutcome({ kind: 'delivered', traceId: 'd', traced: 'memory', receipt: 'observed', signal: 'newTurn' })
+ await q.onTargetIdle('dst')
+ expect(q.depth('dst')).toBe(0)
+ expect(h.flushed.map((f) => f.outcome.kind)).toEqual(['delivered'])
+ })
+
+ // ── TTL expiry — never a silent drop ──────────────────────────────────────────────────────────
+ it('a TTL lapse traces `expired` AND tells the sender, then removes the entry', async () => {
+ const h = harness()
+ const q = new DeliveryQueue(h.deps, { ttlMs: 1000 })
+ await q.enqueue(req())
+ expect(q.depth('dst')).toBe(1)
+ h.setClock(1000 + 1000) // the TTL has elapsed
+ h.fireLatestTimer()
+ await Promise.resolve() // let the async expiry settle
+ await Promise.resolve()
+ expect(q.depth('dst')).toBe(0)
+ // Both legs: the durable trace and the live notify.
+ expect(h.traced.map((t) => t.outcome)).toContain('expired')
+ expect(h.expired).toHaveLength(1)
+ expect(h.expired[0].info.queuedForMs).toBe(1000)
+ expect(h.expired[0].info.traceId).toBeTruthy()
+ })
+
+ it('an expiry timer that fires AFTER the entry already flushed is a no-op (no double drop)', async () => {
+ const h = harness()
+ const q = new DeliveryQueue(h.deps, { ttlMs: 1000 })
+ await q.enqueue(req())
+ await q.onTargetIdle('dst') // delivered — the entry is gone, its timer cancelled
+ expect(q.depth('dst')).toBe(0)
+ // A stale timer fire (belt-and-braces: the entry is no longer in any list) must not expire.
+ const before = h.expired.length
+ h.timers[0].fn()
+ await Promise.resolve()
+ expect(h.expired.length).toBe(before)
+ })
+
+ it('forget() expires every queued message for an ending session — not a silent drop', async () => {
+ const h = harness()
+ const q = new DeliveryQueue(h.deps)
+ await q.enqueue(req({ body: 'a' }))
+ await q.enqueue(req({ body: 'b' }))
+ await q.forget('dst')
+ expect(q.depth('dst')).toBe(0)
+ expect(h.expired.map((e) => e.req.body)).toEqual(['a', 'b'])
+ expect(h.timers.every((t) => t.cancelled)).toBe(true)
+ })
+
+ it('the constants are finite and positive — a real bound and a real TTL', () => {
+ expect(DELIVERY_QUEUE_CAPACITY).toBeGreaterThan(0)
+ expect(Number.isFinite(DELIVERY_QUEUE_CAPACITY)).toBe(true)
+ expect(DELIVERY_QUEUE_TTL_MS).toBeGreaterThan(0)
+ expect(Number.isFinite(DELIVERY_QUEUE_TTL_MS)).toBe(true)
+ })
+})
diff --git a/src/core/agents/delivery-queue.ts b/src/core/agents/delivery-queue.ts
new file mode 100644
index 000000000..6e008f1d7
--- /dev/null
+++ b/src/core/agents/delivery-queue.ts
@@ -0,0 +1,295 @@
+import type { AgentMessageOutcome } from './agent-message-decide'
+import { RETRYABLE } from './agent-message-decide'
+import type { DeliveryTraceInput } from './agent-message-trace'
+
+/**
+ * DELIVER-ON-IDLE — a bounded, per-target queue with a TTL, and never a silent drop.
+ *
+ * ── WHY THIS EXISTS ─────────────────────────────────────────────────────────────────────────────
+ *
+ * Gate 2 refuses a BUSY target (`targetBusy`) and a target between sessions
+ * (`targetNotIdleUnknown`), and Eco hibernation leaves an idle node's pane on a SHELL — so
+ * `targetNotAgentPane` refuses it *forever* on exactly the nodes an orchestration is most likely to
+ * message (the ones sitting idle). "Retry in a moment" pushes that onto a language model with a rate
+ * limiter in front of it: a busy-loop that burns tokens. Wake-then-deliver is therefore not a
+ * nicety — it is what makes messaging usable across a long-running canvas.
+ *
+ * So a `targetBusy` / hibernated target with queueing on is ENQUEUED, and delivered when the target
+ * next goes idle. `queued` is NOT `delivered`: the bytes have not reached the pane, and the receipt
+ * (Task 3.4) is what will close the loop once they do. A queue full stops the sender loudly
+ * (`queueFull`), and a message that waits out its TTL EXPIRES loudly — to the trace and to the
+ * sender — because a silent drop is the one outcome a security core may never have.
+ *
+ * ── THE DECSET-2004 MEASUREMENT MADE THIS SAFE (2026-08-15, this host) ───────────────────────────
+ *
+ * Deliver-on-idle only works if a queued message can be framed into the target's pane WITHOUT a
+ * per-delivery bracketed-paste probe. Measured: all four agent CLIs (claude, codex, gemini,
+ * opencode) keep DECSET 2004 ON at idle AND during startup, twice each, no flapping — so
+ * `paste-buffer -p` frames every flush, including one into a still-starting agent after a wake. The
+ * ONE unsafe surface is a NON-agent pane (a plain REPL/terminal): 2004 OFF ⇒ the payload lands as
+ * raw keystrokes, one submit per newline. This queue therefore gates on NODE TYPE, not on a runtime
+ * probe: it only ever enqueues for a target whose delivery attempt refused as `targetBusy` /
+ * `hibernated` — i.e. a pane gate 1 already judged an AGENT pane — and the flush re-runs the whole
+ * delivery (gate 1 included), so a pane that became a terminal while queued is refused, never
+ * sprayed with unframed lines.
+ *
+ * ── FLUSH-TIME RE-VALIDATION IS THE LOAD-BEARING PROPERTY ───────────────────────────────────────
+ *
+ * A message queued for a busy agent must NOT trust the decision that queued it. Ownership can change
+ * (the pane is respawned by another project), the grant can be revoked (the switch turned off, the
+ * clone notice declined), the flow budget can move — all while the message waits. So the flush does
+ * not cache anything: it calls `deps.deliver(req)` again, which is the SAME end-to-end path the verb
+ * took (scope → ownership → grant → flow → `deliverAgentMessage`). A grant revoked while queued
+ * therefore comes back `notPermitted` at flush and the message is DROPPED, never delivered — pinned
+ * by `delivery-queue.test.ts`, which flips the injected `deliver` from `targetBusy` to
+ * `notPermitted` between enqueue and flush and asserts nothing reached the pane.
+ *
+ * ── SHIPS ON BOTH SHELLS, USED ON ONE ──────────────────────────────────────────────────────────
+ *
+ * Pure `src/core`: no electron, no main import (`no-electron.test.ts`). Every side effect — the
+ * clock, the delivery, the wake, the trace, the sender-notify, the timer — is injected, so the whole
+ * lifecycle is driven without a pty or a window. The desktop is the only shell that wires a consumer
+ * (messaging does not exist on the Server Edition, Task 5.3); the module still compiles and ships
+ * there, like everything else in this directory.
+ */
+
+/** How long a message waits queued before it expires. Long enough for an orchestration turn (which
+ * can run minutes), bounded so a target that never goes idle cannot pin a message forever. */
+export const DELIVERY_QUEUE_TTL_MS = 5 * 60_000
+
+/** How many messages one target may have queued at once. Small and per-target: an unbounded queue
+ * is a memory-DoS surface, and refusing at the bound (rather than dropping the oldest) keeps FIFO
+ * fairness and tells the sender loudly instead of silently discarding a message already accepted. */
+export const DELIVERY_QUEUE_CAPACITY = 16
+
+/** The request the queue carries — opaque to the queue, handed straight back to `deps.deliver`. The
+ * queue keys everything on `targetNodeId` (the flush trigger and the per-target bound) and
+ * `sourceNodeId` (so an expiry can name who to tell); the rest travels untouched. */
+export interface QueuedDeliveryRequest {
+ sourceNodeId: string
+ targetNodeId: string
+ sourceTitle: string
+ /** For the expiry trace's `bodyChars` — the body itself is never traced (see agent-message-trace). */
+ body: string
+ [k: string]: unknown
+}
+
+/** Cancels a scheduled timer. Returned by `schedule`. */
+export type CancelTimer = () => void
+
+export interface DeliveryQueueDeps {
+ now(): number
+ /**
+ * The FULL, re-validated delivery — in production `deliverFromControl`. Called on every flush, so
+ * the whole gate chain (scope, ownership, grant, flow, `deliverAgentMessage`) runs again against
+ * live state. This is what makes the queue safe: it caches no authorization decision.
+ */
+ deliver(req: QueuedDeliveryRequest): Promise<AgentMessageOutcome>
+ /** Record an outcome (`recordDelivery`). The queue traces `queued` on enqueue and `expired` on a
+ * TTL lapse; the flush's own outcomes are traced inside `deliver`. */
+ trace(input: DeliveryTraceInput): Promise<{ traceId: string; traced: string }>
+ /**
+ * Wake a hibernated target through the existing registry (`agent-restart.ts` hibernate/wake
+ * pair). Optional: a target that is merely busy (not hibernated) needs no wake, and a shell with
+ * no registry (the Server Edition) wires nothing. A wake is fire-and-forget here — the target's
+ * eventual idle event is what triggers the flush, not this call's resolution.
+ */
+ wake?(nodeId: string): void
+ /**
+ * Tell the SENDER a queued message expired. The trace is the durable leg (always written); this
+ * is the live leg — the shell surfaces it (a board-log line for the sender, a push). Optional so
+ * the core can be tested without a notify channel, but a production wiring that omits it turns the
+ * "never a silent drop" guarantee into "durable-only", so the desktop always supplies it.
+ */
+ onExpired?(req: QueuedDeliveryRequest, info: { traceId: string; queuedForMs: number }): void
+ /** Tell the sender how a flush ended (delivered, or refused because the world changed under it).
+ * Same optionality reasoning as `onExpired`. */
+ onFlushed?(req: QueuedDeliveryRequest, outcome: AgentMessageOutcome): void
+ /** Arm a one-shot timer, returning its cancel. Injected so tests drive TTL expiry deterministically
+ * instead of waiting real milliseconds; defaults to `setTimeout`/`clearTimeout`. */
+ schedule?(ms: number, fn: () => void): CancelTimer
+}
+
+interface QueueEntry {
+ req: QueuedDeliveryRequest
+ enqueuedAt: number
+ ttlMs: number
+ cancelTimer: CancelTimer
+ /** The traceId minted when this was queued, reused on its expiry so the two entries correlate. */
+ queuedTraceId: string
+}
+
+/** Outcomes that mean "the target still is not ready, come back" — a flush that gets one of these
+ * RE-QUEUES the entry at the front (its TTL keeps counting from the original enqueue) and STOPS
+ * draining, because one idle event does not promise the target stays idle. Derived from `RETRYABLE`
+ * minus the two outcomes the queue itself produces (`queueFull`, `expired`) — so `deliver`'s
+ * retryable outcomes (`rateLimited`, `targetBusy`, `targetNotIdleUnknown`, `targetStatusStale`) all
+ * wait for the NEXT idle, and a new retryable outcome added upstream is handled here the moment it
+ * exists rather than silently dropped. `rateLimited` waiting for the next idle (not re-flushing on a
+ * timer) is what keeps the queue from spinning against the very limiter that refused it. */
+const REQUEUE_ON: ReadonlySet<AgentMessageOutcome['kind']> = new Set(
+ (Object.keys(RETRYABLE) as AgentMessageOutcome['kind'][]).filter(
+ (k) => RETRYABLE[k] && k !== 'queueFull' && k !== 'expired'
+ )
+)
+
+export class DeliveryQueue {
+ private readonly queues = new Map<string, QueueEntry[]>()
+ private readonly capacity: number
+ private readonly ttlMs: number
+ private readonly schedule: (ms: number, fn: () => void) => CancelTimer
+
+ constructor(
+ private readonly deps: DeliveryQueueDeps,
+ opts: { capacity?: number; ttlMs?: number } = {}
+ ) {
+ this.capacity = opts.capacity ?? DELIVERY_QUEUE_CAPACITY
+ this.ttlMs = opts.ttlMs ?? DELIVERY_QUEUE_TTL_MS
+ this.schedule =
+ deps.schedule ??
+ ((ms, fn): CancelTimer => {
+ const t = setTimeout(fn, ms)
+ return () => clearTimeout(t)
+ })
+ }
+
+ /** How many messages are queued for a target right now — for assertions and a position count. */
+ depth(nodeId: string): number {
+ return this.queues.get(nodeId)?.length ?? 0
+ }
+
+ /**
+ * Enqueue a message whose initial delivery refused as `targetBusy` (or whose target is
+ * hibernated). Returns the `queued` receipt (with its position and TTL) or `queueFull` at the
+ * bound — never enqueues past capacity. A `hibernated` target is woken here, before it is idle;
+ * the wake's eventual idle event is what triggers the flush.
+ */
+ async enqueue(
+ req: QueuedDeliveryRequest,
+ opts: { hibernated?: boolean } = {}
+ ): Promise<
+ Extract<AgentMessageOutcome, { kind: 'queued' } | { kind: 'queueFull' }>
+ > {
+ const list = this.queues.get(req.targetNodeId) ?? []
+ if (list.length >= this.capacity) {
+ // Refused, not dropped-oldest: an accepted message is never silently discarded to make room.
+ return { kind: 'queueFull', capacity: this.capacity }
+ }
+ const now = this.deps.now()
+ const t = await this.deps.trace({
+ sourceNodeId: req.sourceNodeId,
+ sourceTitle: req.sourceTitle,
+ targetNodeId: req.targetNodeId,
+ outcome: 'queued',
+ bodyChars: req.body.length
+ })
+ const entry: QueueEntry = {
+ req,
+ enqueuedAt: now,
+ ttlMs: this.ttlMs,
+ queuedTraceId: t.traceId,
+ cancelTimer: this.schedule(this.ttlMs, () => void this.expire(req.targetNodeId, entry))
+ }
+ list.push(entry)
+ this.queues.set(req.targetNodeId, list)
+ // Kick the wake for a hibernated target so it starts its resume; the flush waits on the idle
+ // event, not on the wake. A busy (non-hibernated) target needs nothing — it will go idle on its
+ // own turn end.
+ if (opts.hibernated) this.deps.wake?.(req.targetNodeId)
+ return { kind: 'queued', traceId: t.traceId, position: list.length, ttlMs: this.ttlMs }
+ }
+
+ /**
+ * The target went idle — flush its queue, oldest first. Each entry is delivered through
+ * `deps.deliver`, which RE-RUNS the whole gate chain against live state (the flush-time
+ * re-validation). An entry whose flush says "still not ready" is put back (its TTL unchanged); any
+ * other outcome is terminal and the entry is gone. Draining stops the moment the target is not
+ * ready again — one idle event does not promise the target stays idle across N deliveries.
+ */
+ async onTargetIdle(nodeId: string): Promise<void> {
+ for (;;) {
+ const list = this.queues.get(nodeId)
+ if (!list || list.length === 0) return
+ const entry = list[0]
+ // Take it off before delivering: a re-entrant idle event (deliver can await a real round-trip)
+ // must not flush the same entry twice. It goes back on failure, at the FRONT, preserving order.
+ list.shift()
+ entry.cancelTimer()
+ const outcome = await this.deps.deliver(entry.req)
+ if (REQUEUE_ON.has(outcome.kind)) {
+ // Not ready yet (busy again, still unverified, or rate-limited): keep it, TTL counting from
+ // its ORIGINAL enqueue, and stop draining — the target is evidently not idle after all.
+ this.requeueFront(nodeId, entry)
+ return
+ }
+ // Terminal: delivered, or a refusal waiting will not fix (notPermitted from a revoked grant,
+ // targetGone, targetNotAgentPane…). The entry is done; tell the sender and move to the next.
+ if (this.queues.get(nodeId)?.length === 0) this.queues.delete(nodeId)
+ this.deps.onFlushed?.(entry.req, outcome)
+ }
+ }
+
+ /** Put an entry back at the front with its TTL re-armed for the time it has LEFT (never reset to a
+ * full TTL — the wait it has already served counts). A lapsed remainder expires it immediately. */
+ private requeueFront(nodeId: string, entry: QueueEntry): void {
+ const remaining = Math.max(0, entry.ttlMs - (this.deps.now() - entry.enqueuedAt))
+ entry.cancelTimer = this.schedule(remaining, () => void this.expire(nodeId, entry))
+ const list = this.queues.get(nodeId) ?? []
+ list.unshift(entry)
+ this.queues.set(nodeId, list)
+ }
+
+ /**
+ * A queued message waited out its TTL. Remove it, trace `expired`, and tell the sender — both
+ * legs, because a dropped message with no record anywhere is the failure this module refuses to
+ * have. Idempotent against a flush that already removed the entry (the timer can fire in the seam
+ * before its cancel runs).
+ */
+ private async expire(nodeId: string, entry: QueueEntry): Promise<void> {
+ const list = this.queues.get(nodeId)
+ if (!list) return
+ const i = list.indexOf(entry)
+ if (i < 0) return // already delivered/re-queued with a fresh timer — this fire is stale
+ list.splice(i, 1)
+ if (list.length === 0) this.queues.delete(nodeId)
+ entry.cancelTimer()
+ const queuedForMs = this.deps.now() - entry.enqueuedAt
+ const t = await this.deps.trace({
+ sourceNodeId: entry.req.sourceNodeId,
+ sourceTitle: entry.req.sourceTitle,
+ targetNodeId: entry.req.targetNodeId,
+ outcome: 'expired',
+ bodyChars: entry.req.body.length
+ })
+ this.deps.onExpired?.(entry.req, { traceId: t.traceId, queuedForMs })
+ }
+
+ /** Drop everything for a node whose session is ending (delete/recycle) — its queued messages can
+ * never land in the pane that is going away. Traces each as `expired` so the drop is not silent. */
+ async forget(nodeId: string): Promise<void> {
+ const list = this.queues.get(nodeId)
+ if (!list) return
+ this.queues.delete(nodeId)
+ for (const entry of list) await this.expireDetached(entry)
+ }
+
+ private async expireDetached(entry: QueueEntry): Promise<void> {
+ entry.cancelTimer()
+ const queuedForMs = this.deps.now() - entry.enqueuedAt
+ const t = await this.deps.trace({
+ sourceNodeId: entry.req.sourceNodeId,
+ sourceTitle: entry.req.sourceTitle,
+ targetNodeId: entry.req.targetNodeId,
+ outcome: 'expired',
+ bodyChars: entry.req.body.length
+ })
+ this.deps.onExpired?.(entry.req, { traceId: t.traceId, queuedForMs })
+ }
+
+ /** Test seam / shutdown: cancel every timer and drop every queue WITHOUT tracing (a teardown is
+ * not an expiry the sender needs to hear about). */
+ resetForTests(): void {
+ for (const list of this.queues.values()) for (const e of list) e.cancelTimer()
+ this.queues.clear()
+ }
+}
diff --git a/src/main/agent-messaging.test.ts b/src/main/agent-messaging.test.ts
index 2f70f467d..abb386b4c 100644
--- a/src/main/agent-messaging.test.ts
+++ b/src/main/agent-messaging.test.ts
@@ -20,6 +20,7 @@ import { resetMessageFlow, FANOUT_PER_TURN } from '../core/agents/agent-message-
import { NOTIFY_BODY } from '../shared/agents/agent-messaging'
import { resetAgentMessageTraceForTests } from '../core/agents/agent-message-trace'
import { MANAGED_SCRIPT_REVISION } from '../core/agents/hooks/managed-script'
+import { DeliveryQueue } from '../core/agents/delivery-queue'
import type { MirrorEntry } from '../core/agent-status-mirror'
const idle: MirrorEntry = {
@@ -332,3 +333,54 @@ describe('notify (folded in from #98)', () => {
expect(deps.rec.sent).toHaveLength(1)
})
})
+
+describe('deliver-on-idle wiring (PR 7)', () => {
+ /** A queue whose `deliver` is never reached on these paths (enqueue does not call it) — we only
+ * need to observe enqueue + wake. Timers are inert so no TTL fires mid-test. */
+ function fakeQueue(): { queue: DeliveryQueue; woken: string[] } {
+ const woken: string[] = []
+ const queue = new DeliveryQueue({
+ now: () => 0,
+ deliver: async () => ({ kind: 'delivered', traceId: 'd', traced: 'memory', receipt: 'observed', signal: 'newTurn' }),
+ trace: async () => ({ traceId: 'q', traced: 'memory' }),
+ wake: (id) => woken.push(id),
+ schedule: () => () => {}
+ })
+ return { queue, woken }
+ }
+
+ it('a BUSY target is ENQUEUED, not refused — and nothing reaches the pane', async () => {
+ const { queue } = fakeQueue()
+ const busy: MirrorEntry = { state: 'working', updatedAt: 1, stateVerified: true, clientRevision: MANAGED_SCRIPT_REVISION }
+ const deps = fakeDeps({ mirrorEntry: () => busy, queue })
+ const { outcome } = await deliverFromControl(req(), deps)
+ expect(outcome.kind).toBe('queued')
+ expect(queue.depth('b1')).toBe(1)
+ expect(deps.rec.sent).toEqual([]) // queued is NOT delivered — no bytes yet
+ })
+
+ it('without a queue, the same busy target is refused `targetBusy` (old behaviour intact)', async () => {
+ const busy: MirrorEntry = { state: 'working', updatedAt: 1, stateVerified: true, clientRevision: MANAGED_SCRIPT_REVISION }
+ const deps = fakeDeps({ mirrorEntry: () => busy })
+ const { outcome } = await deliverFromControl(req(), deps)
+ expect(outcome).toEqual({ kind: 'targetBusy', state: 'working' })
+ })
+
+ it('a HIBERNATED target (shell pane) is enqueued AND woken; a real non-agent pane is not', async () => {
+ const { queue, woken } = fakeQueue()
+ // Its pane is on a shell (Eco left it there) — runDelivery refuses `targetNotAgentPane`.
+ const shellPane = {
+ tty: '/dev/pts/9', panePid: 100, paneId: '%1', command: 'bash', argv: ['bash'], pids: [200]
+ }
+ const hib = fakeDeps({ paneOwner: async () => shellPane, queue, isHibernated: () => true })
+ const { outcome } = await deliverFromControl(req(), hib)
+ expect(outcome.kind).toBe('queued')
+ expect(woken).toEqual(['b1']) // woken through the registry before delivery
+ expect(hib.rec.sent).toEqual([])
+
+ // The SAME shell pane that is NOT hibernated stays refused — the node-type gate, not a probe.
+ const notHib = fakeDeps({ paneOwner: async () => shellPane, queue: fakeQueue().queue, isHibernated: () => false })
+ const plain = await deliverFromControl(req(), notHib)
+ expect(plain.outcome.kind).toBe('targetNotAgentPane')
+ })
+})
diff --git a/src/main/agent-messaging.ts b/src/main/agent-messaging.ts
index dda80a1a5..0e555ebb3 100644
--- a/src/main/agent-messaging.ts
+++ b/src/main/agent-messaging.ts
@@ -39,6 +39,7 @@ import {
import { noteNewTurn, noteSent, reserveFlow } from '../core/agents/agent-message-flow'
import { recordDelivery } from '../core/agents/agent-message-trace'
import { resolveDeliveryScope, scopeRefusal } from '../core/agents/agent-message-scope'
+import type { DeliveryQueue } from '../core/agents/delivery-queue'
import { nodeTokenFilePresent } from '../core/agents/node-token-files'
import { mirrorEntry as coreMirrorEntry, type MirrorEntry } from '../core/agent-status-mirror'
import {
@@ -88,6 +89,24 @@ export interface AgentMessagingDeps {
/** Test seam: override the receipt subscription. Production uses the module bus below. */
subscribeReceipts?(cb: (e: ReceiptEvent) => void): () => void
now?(): number
+ /**
+ * Deliver-on-idle (PR 7): the process-lifetime bounded queue. Absent ⇒ no queueing, and a busy or
+ * hibernated target is refused exactly as before. Present ⇒ a PERMITTED delivery that refuses only
+ * because the target is BUSY (or is hibernated, its pane sitting on a shell) is enqueued and
+ * answered `queued`; the queue flushes it when the target next goes idle (wired through
+ * `onMessagingAgentEvent` → `onTargetIdle`). The queue's own `deliver` dep is `runDelivery` below,
+ * so a flush re-runs the whole gate chain against live state — the flush-time re-validation.
+ */
+ queue?: DeliveryQueue
+ /**
+ * Is the target node hibernated (Eco)? A hibernated node's pane is on a SHELL, so a direct
+ * delivery refuses `targetNotAgentPane` FOREVER (gate 1) — the DECSET-2004 measurement's one unsafe
+ * surface, a non-agent pane, which is exactly why the queue gates on node type and never sprays it.
+ * When the target is hibernated the queue enqueues on that refusal and WAKES it first, rather than
+ * treating a real non-agent pane the same way. Renderer-known (the `useAgentStatus` store),
+ * injected. Absent ⇒ never hibernated, and only a `targetBusy` refusal queues.
+ */
+ isHibernated?(nodeId: string): boolean
}
/**
@@ -124,6 +143,21 @@ function subscribeBus(cb: (e: ReceiptEvent) => void): () => void {
return () => receiptSubs.delete(cb)
}
+/**
+ * The process-lifetime deliver-on-idle queue (PR 7), wired once by the desktop shell. Held at module
+ * scope — not threaded through `AgentMessagingDeps` on the event path — because the flush trigger is
+ * the SAME normalized event stream `onMessagingAgentEvent` already taps, and a target going idle is
+ * what a flush waits for. Null on the Server Edition and until wired (messaging does not exist
+ * there). The verb path still takes the queue through `deps.queue` so a test can drive enqueue in
+ * isolation.
+ */
+let deliveryQueue: DeliveryQueue | null = null
+
+/** Wire (or clear) the deliver-on-idle queue. Called once from main; absent ⇒ no queueing. */
+export function setDeliveryQueue(q: DeliveryQueue | null): void {
+ deliveryQueue = q
+}
+
/**
* Feed one normalized agent event into messaging: the sender's own `newTurn` resets its fan-out
* budget (the same edge normalize.ts flags so the renderer can clear per-turn fan-out), and every
@@ -143,6 +177,11 @@ export function onMessagingAgentEvent(
verified: e.verified
}
for (const cb of [...receiptSubs]) cb(ev)
+ // Deliver-on-idle flush trigger: the target finished a turn, so it is idle NOW. `onTargetIdle`
+ // re-runs the whole delivery per queued message (the flush-time re-validation), so a `done` that
+ // is actually still-not-deliverable (an unverified or inferred idle) simply re-queues — this only
+ // needs to be a cheap "maybe now" nudge, not a precise idle verdict.
+ if (e.state === 'done') void deliveryQueue?.onTargetIdle(e.nodeId)
}
// ── The per-node delivery lock ────────────────────────────────────────────────────────────────
@@ -318,20 +357,18 @@ const WROTE: ReadonlySet<AgentMessageOutcome['kind']> = new Set([
])
/**
- * One control-verb delivery, end to end: scope → switch → flow → `deliverAgentMessage` → budget →
- * rendered reply.
+ * One control-verb delivery attempt, end to end: scope → switch → ownership → flow →
+ * `deliverAgentMessage` → budget. Returns the raw typed outcome and does NOT queue — this is both
+ * the verb's first attempt AND the queue's flush-time `deliver` callback, so the queue re-runs the
+ * ENTIRE chain (ownership, grant and flow included) against live state every time it flushes. That
+ * is the flush-time re-validation the queue depends on: a grant revoked while a message was queued
+ * comes back `notPermitted` here and the queue drops it.
*/
-export async function deliverFromControl(
+export async function runDelivery(
req: AgentMessageDeliverRequest,
deps: AgentMessagingDeps
-): Promise<{ outcome: AgentMessageOutcome; reply: AgentMessageReply }> {
+): Promise<AgentMessageOutcome> {
const now = deps.now ?? ((): number => Date.now())
- const answer = (
- outcome: AgentMessageOutcome
- ): { outcome: AgentMessageOutcome; reply: AgentMessageReply } => ({
- outcome,
- reply: renderMessageOutcome(outcome)
- })
const projects = deps.projects()
// WHO MAY BE ADDRESSED — the serialized store, never a live canvas (there is nothing to travel
@@ -427,12 +464,68 @@ export async function deliverFromControl(
// No await between the record and the release: the recorded send replaces the hold in the
// same tick, so no concurrent reservation can slip through the seam between them.
if (WROTE.has(outcome.kind)) noteSent(req.sourceNodeId, req.targetNodeId, now())
- return answer(outcome)
+ return outcome
} finally {
reservation?.release()
}
}
+/** The `AgentMessageOutcome` kinds a permitted-but-not-ready target produces — a busy agent, or a
+ * node between sessions. Only these are enqueued (and only with a queue wired): the target passed
+ * scope/ownership/grant, and its non-readiness is a turn it happens to be in, not a boundary. */
+const QUEUE_ON_BUSY: ReadonlySet<AgentMessageOutcome['kind']> = new Set([
+ 'targetBusy',
+ 'targetNotIdleUnknown'
+])
+
+/**
+ * One control-verb delivery, end to end, WITH deliver-on-idle: attempt it (`runDelivery`), and when
+ * a queue is wired, enqueue a permitted-but-not-ready target instead of refusing it.
+ *
+ * - a BUSY target (or one between sessions) ⇒ `queued`, flushed on its next idle;
+ * - a HIBERNATED target — whose pane is on a shell, so `runDelivery` refuses `targetNotAgentPane`
+ * (the DECSET measurement's one unsafe surface) — ⇒ `queued` AND woken. A genuine non-agent pane
+ * that is NOT hibernated stays refused: the node-type gate, not a probe, is what tells them apart;
+ * - everything else (delivered, stalled, every refusal that waiting will not fix) is answered as-is.
+ *
+ * `queued` is not `delivered`: the bytes have not reached the pane, and the receipt closes the loop
+ * once the flush delivers them.
+ */
+export async function deliverFromControl(
+ req: AgentMessageDeliverRequest,
+ deps: AgentMessagingDeps
+): Promise<{ outcome: AgentMessageOutcome; reply: AgentMessageReply }> {
+ const answer = (
+ outcome: AgentMessageOutcome
+ ): { outcome: AgentMessageOutcome; reply: AgentMessageReply } => ({
+ outcome,
+ reply: renderMessageOutcome(outcome)
+ })
+ const outcome = await runDelivery(req, deps)
+ const queue = deps.queue
+ if (queue) {
+ const queued = (hibernated: boolean): Promise<AgentMessageOutcome> =>
+ queue.enqueue(
+ {
+ verb: req.verb,
+ sourceNodeId: req.sourceNodeId,
+ targetNodeId: req.targetNodeId,
+ // For the trace's `sourceTitle`; the flush re-resolves it from the store like the first
+ // attempt did, so this is only ever a label on the queued/expired trace lines.
+ sourceTitle: req.sourceNodeId,
+ body: req.body
+ },
+ { hibernated }
+ )
+ if (QUEUE_ON_BUSY.has(outcome.kind)) return answer(await queued(false))
+ // A hibernated target reads as `targetNotAgentPane` (its pane is a shell) — enqueue+wake ONLY
+ // then, never for a real non-agent pane.
+ if (outcome.kind === 'targetNotAgentPane' && deps.isHibernated?.(req.targetNodeId))
+ return answer(await queued(true))
+ }
+ return answer(outcome)
+}
+
/** Guard for the IPC boundary: the request came over a channel, so its shape is asserted here. */
export function isDeliverRequest(x: unknown): x is AgentMessageDeliverRequest {
const r = x as AgentMessageDeliverRequest | null
diff --git a/src/main/index.ts b/src/main/index.ts
index e1612db84..74e31c9df 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -19,8 +19,14 @@ import {
deliverFromControl,
isDeliverRequest,
messagingEnabledVia,
- onMessagingAgentEvent
+ onMessagingAgentEvent,
+ runDelivery,
+ setDeliveryQueue,
+ type AgentMessagingDeps
} from './agent-messaging'
+import { DeliveryQueue } from '../core/agents/delivery-queue'
+import { recordDelivery } from '../core/agents/agent-message-trace'
+import type { AgentMessageDeliverRequest } from '../shared/agents/agent-messaging'
import type { RemoteLogExec } from '../core/board-log'
import { boardLogRemotePath } from '../core/board-log'
import { PtyManager } from '../core/pty-manager'
@@ -921,28 +927,54 @@ app.whenReady().then(async () => {
// Agent messaging (the `send`/`reply` control verbs). Canvas.tsx forwards the validated verb
// here; everything that authorizes or performs the delivery reads MAIN's stores. See
// src/main/agent-messaging.ts for the whole map.
+ const messagingDeps: AgentMessagingDeps = {
+ paneOwner: (id) => ptyManager.paneOwner(id),
+ sendFramedPayload: (id, payload) => ptyManager.sendFramedPayload(id, payload),
+ hasLiveSession: (id) => ptyManager.hasLiveSession(id),
+ projects: () => workspaceStore.persistedCanvases(),
+ isRemoteNode: (id) => !!ptyManager.sshRemoteForNode(id),
+ // GLOBAL CONSTRAINT 11: every delivery path is gated behind the per-project switch, OFF by
+ // default. The switch is the `agentMessaging` capability GRANT: the strict `=== true` flag
+ // in the hostile git-shared project.json AND this machine's recorded 'kept' answer to the
+ // clone notice (projectCapabilityGrantedFor — never the raw file bit). Read per call off
+ // the store's index, so a decline or an off-toggle refuses the very next delivery.
+ messagingEnabled: messagingEnabledVia((id) => workspaceStore.capabilityProjectFor(id)),
+ // Runtime pane ownership: which project actually SPAWNED the target's pane this run
+ // (core/agents/pane-ownership.ts). The gate trusts this over the attacker-writable store to
+ // decide whose grant applies; unproven ⇒ refused (PR #237 fix round 2).
+ paneOwnerProject: (id) => paneOwnerProject(id),
+ customAgents: () => settingsStore.get().customAgents,
+ appendBoardLog: (projectId, entry) => appendBoardLogVia(boardLogRouter, projectId, entry)
+ }
+ // Deliver-on-idle (PR 7): the process-lifetime bounded queue. Its `deliver` is `runDelivery`
+ // against these SAME deps, so a flush re-runs the whole gate chain (ownership, grant, flow)
+ // against live state — the flush-time re-validation. The flush trigger is the target's own `done`
+ // event, already fed to `onMessagingAgentEvent` below. `wake`/`isHibernated` are RENDERER state
+ // (Eco lives in `useAgentStatus`, the wake registry in the renderer's agent-restart) with no
+ // main-side signal today; the BUSY-target leg is fully wired here, and the hibernated leg's
+ // renderer→main wiring is owed to device verification (see the PR body).
+ messagingDeps.queue = new DeliveryQueue({
+ now: () => Date.now(),
+ deliver: (qreq) =>
+ runDelivery(
+ {
+ verb: qreq.verb as AgentMessageDeliverRequest['verb'],
+ sourceNodeId: qreq.sourceNodeId,
+ targetNodeId: qreq.targetNodeId,
+ body: qreq.body
+ },
+ messagingDeps
+ ),
+ // The queue's own `queued`/`expired` lines land in the in-memory trace ring (no project is
+ // resolved at this level — the flush's real outcome traces to the project's board log inside
+ // `runDelivery`). Ring-only is honest: `traced: 'memory'`.
+ trace: (input) => recordDelivery(input, { appendBoardLog: async () => false, now: () => Date.now() })
+ })
+ setDeliveryQueue(messagingDeps.queue)
ipcMain.handle(IPC.agentMessageDeliver, async (_e, raw: unknown) => {
if (!isDeliverRequest(raw))
return { ok: false, error: 'malformed agent-message request. Do not retry.' }
- const { reply } = await deliverFromControl(raw, {
- paneOwner: (id) => ptyManager.paneOwner(id),
- sendFramedPayload: (id, payload) => ptyManager.sendFramedPayload(id, payload),
- hasLiveSession: (id) => ptyManager.hasLiveSession(id),
- projects: () => workspaceStore.persistedCanvases(),
- isRemoteNode: (id) => !!ptyManager.sshRemoteForNode(id),
- // GLOBAL CONSTRAINT 11: every delivery path is gated behind the per-project switch, OFF by
- // default. The switch is the `agentMessaging` capability GRANT: the strict `=== true` flag
- // in the hostile git-shared project.json AND this machine's recorded 'kept' answer to the
- // clone notice (projectCapabilityGrantedFor — never the raw file bit). Read per call off
- // the store's index, so a decline or an off-toggle refuses the very next delivery.
- messagingEnabled: messagingEnabledVia((id) => workspaceStore.capabilityProjectFor(id)),
- // Runtime pane ownership: which project actually SPAWNED the target's pane this run
- // (core/agents/pane-ownership.ts). The gate trusts this over the attacker-writable store to
- // decide whose grant applies; unproven ⇒ refused (PR #237 fix round 2).
- paneOwnerProject: (id) => paneOwnerProject(id),
- customAgents: () => settingsStore.get().customAgents,
- appendBoardLog: (projectId, entry) => appendBoardLogVia(boardLogRouter, projectId, entry)
- })
+ const { reply } = await deliverFromControl(raw, messagingDeps)
return reply
})