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): wire the sender-facing expiry channel, and drop the unwired forget()

Claude Codecb30768219ec
diff --git a/src/core/agents/delivery-queue.test.ts b/src/core/agents/delivery-queue.test.ts
index 1cbdea182..42b10b487 100644
--- a/src/core/agents/delivery-queue.test.ts
+++ b/src/core/agents/delivery-queue.test.ts
@@ -206,17 +206,6 @@ describe('DeliveryQueue', () => {
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)
diff --git a/src/core/agents/delivery-queue.ts b/src/core/agents/delivery-queue.ts
index 6e008f1d7..3da55afff 100644
--- a/src/core/agents/delivery-queue.ts
+++ b/src/core/agents/delivery-queue.ts
@@ -264,28 +264,6 @@ export class DeliveryQueue {
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 {
diff --git a/src/main/agent-messaging.test.ts b/src/main/agent-messaging.test.ts
index abb386b4c..ff1ab8b67 100644
--- a/src/main/agent-messaging.test.ts
+++ b/src/main/agent-messaging.test.ts
@@ -13,8 +13,10 @@ import {
deliverFromControl,
renderMessageOutcome,
onMessagingAgentEvent,
+ createDeliveryQueue,
type AgentMessagingDeps
} from './agent-messaging'
+import type { BoardLogEntry } from '../shared/types'
import { RETRYABLE, type AgentMessageOutcome } from '../core/agents/agent-message-decide'
import { resetMessageFlow, FANOUT_PER_TURN } from '../core/agents/agent-message-flow'
import { NOTIFY_BODY } from '../shared/agents/agent-messaging'
@@ -383,4 +385,54 @@ describe('deliver-on-idle wiring (PR 7)', () => {
const plain = await deliverFromControl(req(), notHib)
expect(plain.outcome.kind).toBe('targetNotAgentPane')
})
+
+ // I1: the production factory wires the sender-facing expiry channel. Without it a busy-queued
+ // message that TTL-expires would land only in the trace ring, never where the sender looks.
+ it('a TTL-expired busy-queued message is board-logged to the sender (expiry channel wired)', async () => {
+ const appended: { projectId: string; entry: BoardLogEntry }[] = []
+ let fire: (() => void) | null = null
+ const deps = fakeDeps({
+ appendBoardLog: async (projectId, entry) => {
+ appended.push({ projectId, entry })
+ return true
+ },
+ // By expiry the target's runtime ownership is often gone, so the TRACE leg (routed to the
+ // TARGET's owning project) cannot board-log — leaving the SENDER-facing `onExpired` leg
+ // (routed to the sender's project) as the ONLY board-log writer. That isolation is the point:
+ // it is `onExpired`, not the trace, that this test pins.
+ paneOwnerProject: () => undefined
+ })
+ // `createDeliveryQueue` is the SAME builder main uses — a fake scheduler makes the TTL lapse
+ // deterministic, and a short ttl is irrelevant since the scheduler never really waits.
+ const queue = createDeliveryQueue(deps, {
+ ttlMs: 1000,
+ schedule: (_ms, fn) => {
+ fire = fn
+ return () => {
+ fire = null
+ }
+ }
+ })
+ await queue.enqueue({
+ verb: 'send',
+ sourceNodeId: 'a1',
+ targetNodeId: 'b1',
+ sourceTitle: 'Alpha',
+ body: 'hi'
+ })
+ expect(fire).toBeTruthy()
+ fire!() // the TTL lapses
+ await Promise.resolve()
+ await Promise.resolve()
+ // A board-log line naming the expiry landed in the SENDER's project (a1 ∈ p1), from a1 to b1.
+ const expiredLine = appended.find(
+ (a) =>
+ a.entry.kind === 'event' &&
+ a.entry.event?.type === 'agent-message' &&
+ a.entry.event.title === 'expired' &&
+ a.entry.event.from === 'a1'
+ )
+ expect(expiredLine, 'no expired board-log line reached the sender').toBeTruthy()
+ expect(expiredLine?.projectId).toBe('p1')
+ })
})
diff --git a/src/main/agent-messaging.ts b/src/main/agent-messaging.ts
index 0e555ebb3..941ec9ac4 100644
--- a/src/main/agent-messaging.ts
+++ b/src/main/agent-messaging.ts
@@ -39,7 +39,12 @@ 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 {
+ DeliveryQueue,
+ type DeliveryQueueDeps,
+ type QueuedDeliveryRequest
+} from '../core/agents/delivery-queue'
+import { randomUUID } from 'crypto'
import { nodeTokenFilePresent } from '../core/agents/node-token-files'
import { mirrorEntry as coreMirrorEntry, type MirrorEntry } from '../core/agent-status-mirror'
import {
@@ -158,6 +163,84 @@ export function setDeliveryQueue(q: DeliveryQueue | null): void {
deliveryQueue = q
}
+/** The board-log author for a queue-level record (an app action, not a person's) — the same stamp
+ * `recordDelivery` uses. */
+const QUEUE_TRACE_AUTHOR = { name: 'nodeterm', color: '#8b8b8b' } as const
+
+/**
+ * Build the deliver-on-idle queue against a messaging deps record, WIRING both trace legs required
+ * by Task 7.2 ("emits `expired` to the sender AND to the trace — never a silent drop"):
+ *
+ * - the TRACE leg is `deps.trace`/`recordDelivery`: `queued` and `expired` go into the in-memory
+ * ring Settings → Agents reads, and — for a resolvable owning project — the board log too;
+ * - the SENDER leg is `onExpired` / `onFlushed`: a board-log line in the SENDER's own project, so
+ * the operator watching the sender learns a queued message expired, was dropped by a grant that
+ * changed under it, or finally landed. Without this, a busy-queued message that TTL-expires would
+ * be recorded only where nobody looking at the sender would see it — the exact half-wiring the
+ * PR 7 review flagged (I1).
+ *
+ * `deliver` is `runDelivery` against these same deps, so a flush re-runs the whole gate chain
+ * against live state (the flush-time re-validation). `wake`/`isHibernated` are RENDERER state with
+ * no main-side signal yet and are deliberately NOT supplied here — the busy-target leg is fully
+ * wired, the hibernated leg's main→renderer wake is an explicitly-recorded residual (see
+ * `delivery-queue.ts` and the PR body). `opts` exists only so a test can pin the TTL and scheduler.
+ */
+export function createDeliveryQueue(
+ deps: AgentMessagingDeps,
+ opts: { capacity?: number; ttlMs?: number; schedule?: DeliveryQueueDeps['schedule'] } = {}
+): DeliveryQueue {
+ const now = deps.now ?? ((): number => Date.now())
+ /** The project that lists a node id, for a board-log write. A trace is not an authorization, so
+ * the first match is fine — unlike the delivery gate, which proves ownership. */
+ const projectFor = (nodeId: string): string | undefined =>
+ deps.projects().find((p) => p.nodes.some((n) => n.id === nodeId))?.id
+ /** Append one messaging record to a project's board log. No-ops when the project cannot be
+ * resolved (an inline/cwd-less project has no log — Constraint 10 — the ring still holds it). */
+ const senderBoardLog = (req: QueuedDeliveryRequest, title: string): void => {
+ const projectId = projectFor(req.sourceNodeId)
+ if (!projectId) return
+ const entry: BoardLogEntry = {
+ id: randomUUID(),
+ ts: now(),
+ author: QUEUE_TRACE_AUTHOR,
+ nodeId: req.targetNodeId,
+ kind: 'event',
+ event: { type: 'agent-message', from: req.sourceNodeId, to: req.targetNodeId, title }
+ }
+ void deps.appendBoardLog(projectId, entry)
+ }
+ return new DeliveryQueue(
+ {
+ now,
+ deliver: (qreq) =>
+ runDelivery(
+ {
+ verb: qreq.verb as AgentMessageDeliverRequest['verb'],
+ sourceNodeId: qreq.sourceNodeId,
+ targetNodeId: qreq.targetNodeId,
+ body: qreq.body
+ },
+ deps
+ ),
+ // The trace leg: ring always, board log when the TARGET's owning project is resolvable.
+ trace: (input) =>
+ recordDelivery(input, {
+ appendBoardLog: (entry) => {
+ const projectId = deps.paneOwnerProject(input.targetNodeId)
+ return projectId ? deps.appendBoardLog(projectId, entry) : Promise.resolve(false)
+ },
+ now
+ }),
+ // The sender leg: a durable line where the sender's operator will see it.
+ onExpired: (req) => senderBoardLog(req, 'expired'),
+ onFlushed: (req, outcome) => senderBoardLog(req, outcome.kind),
+ // Injected so a test pins TTL expiry deterministically; production uses the default setTimeout.
+ ...(opts.schedule ? { schedule: opts.schedule } : {})
+ },
+ { capacity: opts.capacity, ttlMs: opts.ttlMs }
+ )
+}
+
/**
* 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
diff --git a/src/main/index.ts b/src/main/index.ts
index 74e31c9df..3f606bbf0 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -16,17 +16,14 @@ import {
} from './browser-guest-registry'
import { appendBoardLogVia, registerBoardLogHandlers, type BoardLogRoute } from '../core/board-log-handlers'
import {
+ createDeliveryQueue,
deliverFromControl,
isDeliverRequest,
messagingEnabledVia,
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'
@@ -946,30 +943,16 @@ app.whenReady().then(async () => {
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() })
- })
+ // Deliver-on-idle (PR 7): the process-lifetime bounded queue, built by the service factory so its
+ // trace + sender-facing legs are wired (and unit-tested) in one place. 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. A TTL expiry is board-logged to the
+ // sender's project AND held in the trace ring (never a silent drop). `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 wake is an explicitly-recorded residual (see the PR body).
+ messagingDeps.queue = createDeliveryQueue(messagingDeps)
setDeliveryQueue(messagingDeps.queue)
ipcMain.handle(IPC.agentMessageDeliver, async (_e, raw: unknown) => {
if (!isDeliverRequest(raw))