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.

fix(messaging): the fan-out cap survives concurrency, and the service suite survives grep

enes769ae11cf1be
diff --git a/src/core/agents/agent-message-flow.test.ts b/src/core/agents/agent-message-flow.test.ts
index 715a67bf0..137979e74 100644
--- a/src/core/agents/agent-message-flow.test.ts
+++ b/src/core/agents/agent-message-flow.test.ts
@@ -11,6 +11,7 @@ import {
noteNewTurn,
noteSent,
pairKey,
+ reserveFlow,
resetMessageFlow,
type FlowVerdict
} from './agent-message-flow'
@@ -407,3 +408,77 @@ describe('the limiter is consulted BEFORE any pane probe', () => {
expect(writes).toEqual([])
})
})
+
+/**
+ * The RESERVATION — what makes check+record atomic across a sender's CONCURRENT deliveries.
+ *
+ * `checkFlowLimits` is a pure read and `noteSent` records only after the pane write, so N parallel
+ * sends to N DISTINCT targets all used to pass the fan-out cap before any of them recorded — the
+ * cap held only for a sender polite enough to send sequentially. `reserveFlow` closes that: the
+ * check and the provisional hold happen in one synchronous step (no await between them, which in a
+ * single-threaded runtime IS the critical section), and a delivery that never reaches the pane
+ * releases its hold.
+ */
+describe('reserveFlow — check + provisional hold, atomically', () => {
+ const NOW = 1_000_000
+
+ it('N reservations to distinct targets consume the fan-out budget BEFORE any noteSent', () => {
+ const held: { release(): void }[] = []
+ for (let i = 0; i < FANOUT_PER_TURN; i++) {
+ const r = reserveFlow('src', `t${i}`, NOW)
+ expect(r.ok, `reservation ${i}`).toBe(true)
+ if (r.ok) held.push(r)
+ }
+ // The (N+1)th concurrent send is refused although NOTHING has been recorded yet.
+ const over = reserveFlow('src', 'tN', NOW)
+ expect(over.ok).toBe(false)
+ if (!over.ok) {
+ expect(over.limit).toBe('fan-out')
+ expect(over.outcome).toEqual({ kind: 'rateLimited', retryAfterMs: FANOUT_RETRY_AFTER_MS })
+ }
+ for (const r of held) r.release()
+ })
+
+ it('a released reservation restores the budget — a refused delivery costs nothing', () => {
+ const rs = Array.from({ length: FANOUT_PER_TURN }, (_, i) => reserveFlow('src', `t${i}`, NOW))
+ for (const r of rs) if (r.ok) r.release()
+ expect(reserveFlow('src', 'late', NOW).ok).toBe(true)
+ })
+
+ it('reservations and recorded sends SHARE the budget', () => {
+ noteSent('src', 'a', NOW)
+ noteSent('src', 'b', NOW)
+ const r1 = reserveFlow('src', 'c', NOW)
+ const r2 = reserveFlow('src', 'd', NOW)
+ expect(r1.ok && r2.ok).toBe(true)
+ expect(reserveFlow('src', 'e', NOW).ok).toBe(false)
+ })
+
+ it('an in-flight delivery holds its PAIR shut too — a concurrent same-pair send is rateLimited', () => {
+ const r = reserveFlow('src', 'dst', NOW)
+ expect(r.ok).toBe(true)
+ const second = reserveFlow('src', 'dst', NOW)
+ expect(second.ok).toBe(false)
+ if (!second.ok) expect(second.limit).toBe('pair')
+ // …and B→A stays open: a reply is never throttled by the message it answers.
+ expect(reserveFlow('dst', 'src', NOW).ok).toBe(true)
+ })
+
+ it('release is idempotent — a finally block calling it twice cannot free a stranger\'s slot', () => {
+ const a = reserveFlow('src', 'a', NOW)
+ const b = reserveFlow('src', 'b', NOW)
+ expect(a.ok && b.ok).toBe(true)
+ if (a.ok) {
+ a.release()
+ a.release()
+ }
+ // Only ONE slot came back (b still holds): three more fill the cap of FANOUT_PER_TURN = 4,
+ // and the next refuses. A double release that freed two would let the fifth through.
+ const c = reserveFlow('src', 'c', NOW)
+ const d = reserveFlow('src', 'd', NOW)
+ const e = reserveFlow('src', 'e', NOW)
+ expect(c.ok && d.ok && e.ok).toBe(true)
+ expect(reserveFlow('src', 'f', NOW).ok).toBe(false)
+ for (const r of [b, c, d, e]) if (r.ok) r.release()
+ })
+})
diff --git a/src/core/agents/agent-message-flow.ts b/src/core/agents/agent-message-flow.ts
index ca5744755..48c5663c2 100644
--- a/src/core/agents/agent-message-flow.ts
+++ b/src/core/agents/agent-message-flow.ts
@@ -254,6 +254,86 @@ export function checkFlowLimits(src: string, dst: string, now: number): FlowChec
return { ok: true }
}
+/**
+ * IN-FLIGHT RESERVATIONS — what makes check + record atomic across a sender's CONCURRENT sends.
+ *
+ * `checkFlowLimits` is a pure read and `noteSent` records only after the pane write, so between
+ * the two sits the whole delivery (probes, the framed write — and on SSH a real round-trip). N
+ * parallel sends to N DISTINCT targets therefore all passed the fan-out cap before any of them
+ * recorded: the plan's blast-radius limit held only for a sender polite enough to send
+ * sequentially, and a language model firing tool calls in parallel is not that sender. The pair
+ * limiter had the narrower version of the same hole (two same-pair sends serialized at the target
+ * lock, but the second delivered with the verdict it read before waiting).
+ *
+ * `reserveFlow` closes both: the check and a provisional hold happen with NO await between them —
+ * which, single-threaded, IS the critical section — and the hold is released when the delivery
+ * ends. A hold counts against the fan-out budget exactly like a recorded send, and holds a pair
+ * shut exactly like a fresh `noteSent`; a delivery that never reaches the pane releases its hold
+ * and costs nothing, preserving `noteSent`'s contract. The maps cannot leak holds: every release
+ * runs in the caller's `finally`, and a process that dies loses the maps with the process.
+ */
+const pendingPairs = new Set<string>()
+const pendingBySender = new Map<string, number>()
+
+export interface FlowReservation {
+ ok: true
+ /** Give the slot back. Idempotent — a double release must not free a sibling's hold. */
+ release(): void
+}
+
+/**
+ * Check BOTH budgets and take a provisional hold in one synchronous step.
+ *
+ * A refused reservation reports the same `rateLimited` shape `checkFlowLimits` does. A pair held
+ * by an in-flight delivery reports the full `PAIR_MIN_INTERVAL_MS` — a floor, same reasoning as
+ * `FANOUT_RETRY_AFTER_MS`: if the in-flight send lands, that is the real wait; if it fails, the
+ * caller retries early and merely gets refused zero times instead of once.
+ */
+export type FlowReserve = { ok: false; limit: FlowLimit; outcome: RateLimited } | FlowReservation
+
+export function reserveFlow(src: string, dst: string, now: number): FlowReserve {
+ sweep(now)
+ const sent = senderTurns.get(src)?.sent ?? 0
+ const pending = pendingBySender.get(src) ?? 0
+ if (sent + pending >= FANOUT_PER_TURN) {
+ return {
+ ok: false,
+ limit: 'fan-out',
+ outcome: { kind: 'rateLimited', retryAfterMs: FANOUT_RETRY_AFTER_MS }
+ }
+ }
+ const key = pairKey(src, dst)
+ const last = pairLastSentAt.get(key)
+ if (last !== undefined) {
+ return {
+ ok: false,
+ limit: 'pair',
+ outcome: { kind: 'rateLimited', retryAfterMs: PAIR_MIN_INTERVAL_MS - (now - last) }
+ }
+ }
+ if (pendingPairs.has(key)) {
+ return {
+ ok: false,
+ limit: 'pair',
+ outcome: { kind: 'rateLimited', retryAfterMs: PAIR_MIN_INTERVAL_MS }
+ }
+ }
+ pendingPairs.add(key)
+ pendingBySender.set(src, pending + 1)
+ let released = false
+ return {
+ ok: true,
+ release(): void {
+ if (released) return
+ released = true
+ pendingPairs.delete(key)
+ const n = (pendingBySender.get(src) ?? 1) - 1
+ if (n <= 0) pendingBySender.delete(src)
+ else pendingBySender.set(src, n)
+ }
+ }
+}
+
/**
* Record a delivery that ACTUALLY reached the pane — the single write path for both budgets.
*
@@ -301,4 +381,6 @@ export function flowStats(): { pairs: number; senders: number } {
export function resetMessageFlow(): void {
pairLastSentAt.clear()
senderTurns.clear()
+ pendingPairs.clear()
+ pendingBySender.clear()
}
diff --git a/src/main/agent-messaging.test.ts b/src/main/agent-messaging.test.ts
index 3ae772a93..e9f10043c 100644
Binary files a/src/main/agent-messaging.test.ts and b/src/main/agent-messaging.test.ts differ
diff --git a/src/main/agent-messaging.ts b/src/main/agent-messaging.ts
index dcf393654..dccde560c 100644
--- a/src/main/agent-messaging.ts
+++ b/src/main/agent-messaging.ts
@@ -36,7 +36,7 @@ import {
type AgentMessageOutcome,
type NotPermittedReason
} from '../core/agents/agent-message-decide'
-import { checkFlowLimits, noteNewTurn, noteSent } from '../core/agents/agent-message-flow'
+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 { nodeTokenFilePresent } from '../core/agents/node-token-files'
@@ -297,11 +297,19 @@ export async function deliverFromControl(
if (!notPermitted && (!projectId || !deps.messagingEnabled(projectId)))
notPermitted = 'switch-off'
- // Flow control (PR #208): a pure read here; only a write that reaches the pane records.
+ // Flow control (PR #208), taken as a RESERVATION rather than a pure read: `checkFlowLimits`
+ // followed later by `noteSent` is not atomic, and N parallel sends to N distinct targets would
+ // all pass the fan-out cap before any of them recorded — the cap would hold only for a sender
+ // polite enough to send sequentially. `reserveFlow` checks and holds in one synchronous step;
+ // the hold is released in the `finally` below, so a delivery that never reaches the pane still
+ // costs nothing (noteSent's own contract). The parallel-sends test in agent-messaging.test.ts
+ // is the one that fails if this goes back to a bare check.
let retryAfterMs: number | undefined
+ let reservation: { release(): void } | null = null
if (!notPermitted) {
- const flow = checkFlowLimits(req.sourceNodeId, req.targetNodeId, now())
+ const flow = reserveFlow(req.sourceNodeId, req.targetNodeId, now())
if (!flow.ok) retryAfterMs = flow.outcome.retryAfterMs
+ else reservation = flow
}
const owner = projects.find((p) => p.id === projectId)
@@ -338,29 +346,35 @@ export async function deliverFromControl(
subscribeEvents: deps.subscribeReceipts ?? subscribeBus
}
- const outcome = await deliverAgentMessage(
- {
- targetNodeId: req.targetNodeId,
- sourceNodeId: req.sourceNodeId,
- // The from-line is composed HERE from the store's title (oneLine'd inside buildEnvelope);
- // the renderer never supplies a string that ends up inside the frame.
- sourceTitle: sourceNode?.title || req.sourceNodeId,
- // notify's body is APP-OWNED (#98): substituted here, in main, whatever the request
- // carried — the renderer's `--text` refusal is UX, this line is the boundary. The test
- // sends a hostile body over the IPC shape and asserts it never reaches the envelope.
- body: req.verb === 'notify' ? NOTIFY_BODY : req.body,
- targetAgentId,
- targetBinaries: binariesFor(targetAgentId, deps.customAgents()),
- targetIsRemote: deps.isRemoteNode(req.targetNodeId),
- notPermitted,
- retryAfterMs,
- targetLive: deps.hasLiveSession(req.targetNodeId)
- },
- delivery
- )
+ try {
+ const outcome = await deliverAgentMessage(
+ {
+ targetNodeId: req.targetNodeId,
+ sourceNodeId: req.sourceNodeId,
+ // The from-line is composed HERE from the store's title (oneLine'd inside buildEnvelope);
+ // the renderer never supplies a string that ends up inside the frame.
+ sourceTitle: sourceNode?.title || req.sourceNodeId,
+ // notify's body is APP-OWNED (#98): substituted here, in main, whatever the request
+ // carried — the renderer's `--text` refusal is UX, this line is the boundary. The test
+ // sends a hostile body over the IPC shape and asserts it never reaches the envelope.
+ body: req.verb === 'notify' ? NOTIFY_BODY : req.body,
+ targetAgentId,
+ targetBinaries: binariesFor(targetAgentId, deps.customAgents()),
+ targetIsRemote: deps.isRemoteNode(req.targetNodeId),
+ notPermitted,
+ retryAfterMs,
+ targetLive: deps.hasLiveSession(req.targetNodeId)
+ },
+ delivery
+ )
- if (WROTE.has(outcome.kind)) noteSent(req.sourceNodeId, req.targetNodeId, now())
- return answer(outcome)
+ // 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)
+ } finally {
+ reservation?.release()
+ }
}
/** Guard for the IPC boundary: the request came over a channel, so its shape is asserted here. */