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(server): harden canvas control sequencing

freshjuicez3695c50e186e
diff --git a/src/core/agents/agent-message.ts b/src/core/agents/agent-message.ts
index 6920b3563..c247cc700 100644
--- a/src/core/agents/agent-message.ts
+++ b/src/core/agents/agent-message.ts
@@ -115,11 +115,12 @@ export interface DeliveryDeps {
*/
bracketPasteRequested(nodeId: string): Promise<boolean>
/**
- * ONE tmux invocation: the envelope pasted (tmux frames it from the pane's real bracketed-paste
- * state — `paste-buffer -p`) and the submit as a `send-keys Enter` in the same command list.
- * Takes the PLAIN envelope text: the payload must carry no ESC byte of ours, because tmux ≥ 3.7
- * passes paste-buffer content through vis(3), which renders an embedded frame as literal `^[`
- * text (issue #453). Resolves false when the pane is gone.
+ * Deliver and submit the PLAIN envelope. Desktop uses one tmux command list; Server Edition
+ * separates paste from Enter until pane capture proves the fresh composer settled. The payload
+ * must carry no ESC byte of ours, because tmux ≥ 3.7 passes paste-buffer content through vis(3),
+ * which renders an embedded frame as literal `^[` text (issue #453). Resolves false only when
+ * the envelope did not reach the pane; a post-paste submit failure remains eligible for the
+ * receipt watch's honest `stalled` outcome.
*/
sendEnvelope(nodeId: string, envelope: string): Promise<boolean>
/** The target's status mirror entry — gate 2's whole input. */
@@ -413,17 +414,17 @@ export async function deliverAgentMessage(
if (!(await deps.bracketPasteRequested(req.targetNodeId)))
return refuse({ kind: 'targetNotPasteAware' })
- // The envelope goes out PLAIN — tmux applies the bracketed-paste frame itself and the Enter
- // rides the same tmux command list as a separate key event (`PtyManager.sendEnvelope` →
- // `localPasteDelivery`/`remotePasteDelivery`, enter=true). This replaced a JS-composed frame
+ // The envelope goes out PLAIN — tmux applies the bracketed-paste frame itself. Desktop's Enter
+ // rides the same tmux command list (`PtyManager.sendEnvelope`); Server Edition waits for pane
+ // settlement and submits separately. Both replaced a JS-composed frame
// (`bracketedInjection`, deleted): tmux ≥ 3.7 passes paste-buffer content through vis(3), so a
// payload-carried `ESC[200~` arrived as the literal text `^[[200~` and the `\r` riding inside
// the frameless burst never submitted (issue #453, measured on the bundled tmux 3.7b).
//
- // herdr :48 — the race that note feared (an Enter milliseconds behind an UNMARKED burst being
- // absorbed as pasted content) cannot occur here: the Enter arrives after tmux's own `ESC[201~`
- // close marker, a boundary a paste-aware composer cannot re-chunk across. Probe B in #453
- // measured exactly this delivery submitting cleanly against a live Claude Code pane.
+ // herdr :48 — the desktop Enter arrives after tmux's own `ESC[201~` close marker. Server's
+ // fresh-composer path additionally observes that the TUI rendered the paste before sending it;
+ // this closes the asynchronous boot-window case where the boundary was written but not yet
+ // consumed by Claude's composer.
//
// herdr :116 — framing an unaware app made OpenCode read `A != B` as shell mode; `-p` frames
// only when the pane's app really requested bracketed paste, so that failure mode is tmux's
diff --git a/src/core/tmux-paste.realtmux.test.ts b/src/core/tmux-paste.realtmux.test.ts
index ff0df7f18..6efc5b247 100644
--- a/src/core/tmux-paste.realtmux.test.ts
+++ b/src/core/tmux-paste.realtmux.test.ts
@@ -600,6 +600,10 @@ suite('REAL bash through REAL tmux: the payload cannot become key input', () =>
const m = path.join(work, 'pwn-ctl')
const buffer = pasteBufferName()
tmux(localTmuxPasteArgs(SOCKET, 'nt-sec-ctl', buffer, false), `hello${END}\rtouch ${m}\r`)
+ // tmux returning means the bytes reached the PTY, not that readline has consumed them. The
+ // drain starts with Ctrl-C, so firing it immediately can cancel the very attack this control
+ // is meant to witness and make the two sanitizer tests vacuous on a fast host.
+ waitFor(() => fs.existsSync(m), 'the unsanitized control attack to run')
bashDrain('nt-sec-ctl', 'nt-sec-ctl')
expect(fs.existsSync(m), 'the attack no longer works — these tests are vacuous').toBe(true)
})
diff --git a/src/server/canvas-control.test.ts b/src/server/canvas-control.test.ts
index 5c344f85a..2c885a71c 100644
--- a/src/server/canvas-control.test.ts
+++ b/src/server/canvas-control.test.ts
@@ -4,7 +4,17 @@ import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ _resetForTest as resetAgentStatusMirrorForTests,
+ recordAgentEvent
+} from '../core/agent-status-mirror'
import { resetMessageFlow } from '../core/agents/agent-message-flow'
+import { resetAgentMessageTraceForTests } from '../core/agents/agent-message-trace'
+import { MANAGED_SCRIPT_REVISION } from '../core/agents/hooks/managed-script'
+import {
+ resetNodeTokenFilesForTests,
+ writeNodeTokenFile
+} from '../core/agents/node-token-files'
import {
recordFreshSpawnOwner,
resetPaneOwnershipForTests
@@ -26,12 +36,17 @@ describe('initServerCanvasControl', () => {
initPlatform(fakePlatform({ userDataDir: dataDir }))
resetPaneOwnershipForTests()
resetMessageFlow()
+ resetAgentMessageTraceForTests()
+ resetAgentStatusMirrorForTests()
+ resetNodeTokenFilesForTests()
})
afterEach(() => {
runtime?.stop()
runtime = null
resetPaneOwnershipForTests()
+ resetAgentStatusMirrorForTests()
+ resetNodeTokenFilesForTests()
resetPlatformForTests()
fs.rmSync(dataDir, { recursive: true, force: true })
})
@@ -127,4 +142,113 @@ describe('initServerCanvasControl', () => {
expect(paneOwner).not.toHaveBeenCalled()
expect(sendEnvelope).not.toHaveBeenCalled()
})
+
+ it('wires permitted delivery through paste-settle-submit on the first fresh pane message', async () => {
+ const workspace: Workspace = {
+ version: 2,
+ activeProjectId: 'p1',
+ projects: [
+ {
+ id: 'p1',
+ name: 'Project',
+ color: '#0a84ff',
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [
+ {
+ id: 'source',
+ kind: 'terminal',
+ position: { x: 0, y: 0 },
+ size: { width: 640, height: 440 },
+ title: 'Source',
+ color: '#d97757',
+ group: null,
+ agentId: 'claude'
+ },
+ {
+ id: 'target',
+ kind: 'terminal',
+ position: { x: 700, y: 0 },
+ size: { width: 640, height: 440 },
+ title: 'Target',
+ color: '#d97757',
+ group: null,
+ agentId: 'claude'
+ }
+ ]
+ }
+ ]
+ }
+ const store = {
+ load: vi.fn(async () => workspace),
+ save: vi.fn(async () => undefined),
+ persistedCanvases: () => [{ id: 'p1', nodes: workspace.projects[0].nodes }],
+ capabilityProjectFor: () => ({
+ agentMessaging: true,
+ capabilityAck: { agentMessaging: 'kept' }
+ })
+ } as unknown as WorkspaceStore
+ const writes: Array<{ text: string; enter: boolean | undefined }> = []
+ let pasted = ''
+ const legacySendEnvelope = vi.fn(async () => true)
+ const pty = {
+ createHeadless: vi.fn(async () => ({ sessionId: 'unused', fresh: true })),
+ captureSession: vi.fn(async () =>
+ pasted ? `Claude composer\n${pasted.split('\n').at(-1)}` : 'Claude composer'),
+ sendText: vi.fn(async (_nodeId: string, text: string, opts?: { enter?: boolean }) => {
+ writes.push({ text, enter: opts?.enter })
+ if (text) pasted = text
+ else queueMicrotask(() => runtime?.onAgentEvent({
+ nodeId: 'target',
+ agentId: 'claude',
+ kind: 'state',
+ state: 'working',
+ newTurn: true,
+ verified: true,
+ clientRevision: MANAGED_SCRIPT_REVISION
+ } as never))
+ return true
+ }),
+ paneOwner: vi.fn(async () => ({
+ tty: '/dev/pts/9',
+ panePid: 100,
+ paneId: '%1',
+ command: 'claude',
+ argv: ['claude'],
+ pids: [200]
+ })),
+ sendEnvelope: legacySendEnvelope,
+ hasLiveSession: () => true
+ } as unknown as PtyManager
+
+ recordFreshSpawnOwner('target', 'p1')
+ expect(writeNodeTokenFile('target', 'token')).toBe(true)
+ recordAgentEvent({
+ nodeId: 'target',
+ agentId: 'claude',
+ kind: 'state',
+ state: 'done',
+ verified: true,
+ clientRevision: MANAGED_SCRIPT_REVISION
+ } as never)
+
+ runtime = await initServerCanvasControl({
+ workspaceStore: store,
+ ptyManager: pty,
+ settings: () => ({ ...DEFAULT_SETTINGS }),
+ boardLog: { append: async () => false },
+ installAgentIntegrations: false
+ })
+
+ const reply = await runtime.handler({
+ verb: 'send',
+ nodeId: 'source',
+ args: { node: 'target', text: 'hello' },
+ verified: true
+ })
+ expect(reply).toMatchObject({ ok: true, message: expect.stringContaining('delivered') })
+ expect(writes).toHaveLength(2)
+ expect(writes[0]).toMatchObject({ enter: false })
+ expect(writes[1]).toEqual({ text: '', enter: true })
+ expect(legacySendEnvelope).not.toHaveBeenCalled()
+ })
})
diff --git a/src/server/canvas-control.ts b/src/server/canvas-control.ts
index ab49f986b..f001a0663 100644
--- a/src/server/canvas-control.ts
+++ b/src/server/canvas-control.ts
@@ -34,6 +34,7 @@ import {
type ServerEditionControlActions
} from './control-unsupported'
import { HeadlessNodeFactory } from './headless-node-factory'
+import { sendSettledEnvelope } from './settled-envelope'
export interface ServerCanvasControlDeps {
workspaceStore: WorkspaceStore
@@ -145,7 +146,10 @@ export async function initServerCanvasControl(
const messaging: AgentMessagingDeps = {
paneOwner: (nodeId) => deps.ptyManager.paneOwner(nodeId),
- sendEnvelope: (nodeId, envelope) => deps.ptyManager.sendEnvelope(nodeId, envelope),
+ // Server delivery has no renderer/xterm echo stream. Capture the headless pane instead and
+ // separate paste from Enter so a fresh TUI cannot swallow the first submit keystroke.
+ sendEnvelope: (nodeId, envelope) =>
+ sendSettledEnvelope(deps.ptyManager, nodeId, envelope),
hasLiveSession: (nodeId) => deps.ptyManager.hasLiveSession(nodeId),
mirrorEntry,
projects: () => deps.workspaceStore.persistedCanvases(),
diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.ts
index a3e60d926..7b1f99956 100644
--- a/src/server/headless-node-factory.test.ts
+++ b/src/server/headless-node-factory.test.ts
@@ -202,6 +202,71 @@ describe('HeadlessNodeFactory', () => {
expect(workspace.projects[0].nodes.find((node) => node.id === id)?.pendingLaunch).toBeUndefined()
})
+ it('holds a fresh dependency through its boot done blip, then releases after working -> done', async () => {
+ const upstreamReply = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'produce result' },
+ true
+ )
+ const upstreamId = (upstreamReply.result as { id: string }).id
+ pty.sends.length = 0
+
+ const downstreamReply = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'consume result', after: upstreamId },
+ true
+ )
+ const downstreamId = (downstreamReply.result as { id: string }).id
+ let workspace = await store.load({ sideline: false })
+ expect(workspace.projects[0].nodes.find((node) => node.id === downstreamId)?.pendingLaunch)
+ .toMatchObject({ after: [upstreamId], awaitWorking: [upstreamId] })
+
+ // Fresh Claude briefly idles at its composer before its argv prompt begins. This done is not
+ // terminal evidence because no working turn has been observed since the downstream was armed.
+ states[upstreamId] = 'done'
+ factory.onAgentEvent({ nodeId: upstreamId, state: 'done' })
+ await factory.refreshArmed()
+ expect(pty.sends).toEqual([])
+
+ states[upstreamId] = 'working'
+ factory.onAgentEvent({ nodeId: upstreamId, state: 'working' })
+ await factory.refreshArmed()
+ expect(pty.sends).toEqual([])
+ workspace = await store.load({ sideline: false })
+ expect(workspace.projects[0].nodes.find((node) => node.id === downstreamId)?.pendingLaunch)
+ .not.toHaveProperty('awaitWorking')
+
+ states[upstreamId] = 'done'
+ factory.onAgentEvent({ nodeId: upstreamId, state: 'done' })
+ await factory.refreshArmed()
+ expect(pty.sends).toEqual([{ nodeId: downstreamId, text: "claude 'consume result'" }])
+ workspace = await store.load({ sideline: false })
+ expect(workspace.projects[0].nodes.find((node) => node.id === downstreamId)?.pendingLaunch)
+ .toBeUndefined()
+ })
+
+ it('launches immediately when a fresh dependency is already done at arm time', async () => {
+ const upstreamReply = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'produce result' },
+ true
+ )
+ const upstreamId = (upstreamReply.result as { id: string }).id
+ states[upstreamId] = 'done'
+ pty.sends.length = 0
+
+ const downstreamReply = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'consume result', after: upstreamId },
+ true
+ )
+ const downstreamId = (downstreamReply.result as { id: string }).id
+ expect(pty.sends).toEqual([{ nodeId: downstreamId, text: "claude 'consume result'" }])
+ const workspace = await store.load({ sideline: false })
+ expect(workspace.projects[0].nodes.find((node) => node.id === downstreamId)?.pendingLaunch)
+ .toBeUndefined()
+ })
+
it('creates and updates a persisted sticky with lineage and an accountable byline', async () => {
const createdReply = await factory.sticky('term-source', {
node: 'Round status',
diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.ts
index 51fb8ef54..48c06ee03 100644
--- a/src/server/headless-node-factory.ts
+++ b/src/server/headless-node-factory.ts
@@ -198,6 +198,8 @@ function ptyOptions(project: Project, node: CanvasNodeState): PtyCreateOptions {
export class HeadlessNodeFactory {
private serial: Promise<unknown> = Promise.resolve()
private attached = new Set<string>()
+ /** Fresh server-spawned agents that have not emitted their first real working turn yet. */
+ private awaitingFirstWorking = new Set<string>()
private retryCount = new Map<string, number>()
private retryTimers = new Map<string, ReturnType<typeof setTimeout>>()
private stopped = false
@@ -340,6 +342,19 @@ export class HeadlessNodeFactory {
const bridges = [...(target.bridges ?? [])]
const startIndex = target.nodes.length
const cwd = args.cwd || (target.id === source.project.id ? source.node.cwd : undefined) || target.cwd
+ // Snapshot dependency state at the arm boundary. A `working` state is already positive
+ // evidence that this fresh process made it through its boot composer; a later `done` may
+ // release it. An unknown/waiting fresh spawn needs a working event after this snapshot.
+ const afterStates = new Map(after.map((depId) => [depId, this.deps.stateOf(depId)]))
+ for (const [depId, state] of afterStates) {
+ if (state === 'working') this.awaitingFirstWorking.delete(depId)
+ }
+ const mustWait = after.some((depId) => afterStates.get(depId) !== 'done')
+ const awaitWorking = after.filter((depId) =>
+ afterStates.get(depId) !== 'done' &&
+ afterStates.get(depId) !== 'working' &&
+ this.awaitingFirstWorking.has(depId)
+ )
for (let i = 0; i < count; i++) {
let command = args.cmd
@@ -378,9 +393,13 @@ export class HeadlessNodeFactory {
const id = nextId('term')
// Match the desktop's `armAfter`: if every dependency is already done, launch now rather
// than persisting a wait that has no future edge left to wake it.
- const mustWait = after.some((depId) => this.deps.stateOf(depId) !== 'done')
const pendingLaunch = command && mustWait
- ? { after, command, executor: 'server' as const }
+ ? {
+ after,
+ command,
+ executor: 'server' as const,
+ ...(awaitWorking.length ? { awaitWorking: [...awaitWorking] } : {})
+ }
: undefined
const node: CanvasNodeState = {
id,
@@ -433,6 +452,7 @@ export class HeadlessNodeFactory {
failed.push(node.id)
continue
}
+ if (verb === 'open-agent' && result.fresh) this.awaitingFirstWorking.add(node.id)
const command = commands.get(node.id)
if (command && !(await this.deps.ptyManager.sendText(node.id, command))) failed.push(node.id)
} catch {
@@ -528,10 +548,12 @@ export class HeadlessNodeFactory {
}
onAgentEvent(event: Pick<NormalizedAgentEvent, 'nodeId' | 'state'>): void {
- if (!this.stopped && event?.nodeId && event.state === 'done') void this.refreshArmed()
+ if (this.stopped || !event?.nodeId) return
+ if (event.state === 'working') this.awaitingFirstWorking.delete(event.nodeId)
+ if (event.state === 'working' || event.state === 'done') void this.refreshArmed(event)
}
- refreshArmed(): Promise<void> {
+ refreshArmed(observed?: Pick<NormalizedAgentEvent, 'nodeId' | 'state'>): Promise<void> {
return this.runExclusive(async () => {
if (this.stopped) return
const workspace = await this.deps.workspaceStore.load({ sideline: false })
@@ -541,6 +563,22 @@ export class HeadlessNodeFactory {
for (const node of project.nodes) {
const pending = node.pendingLaunch
if (!pending || pending.executor !== 'server' || !pending.command) continue
+ const markChanged = (): void => {
+ const list = changedByProject.get(project) ?? []
+ if (!list.includes(node)) list.push(node)
+ changedByProject.set(project, list)
+ }
+ if (observed?.state === 'working' && pending.awaitWorking?.includes(observed.nodeId)) {
+ const remaining = pending.awaitWorking.filter((depId) => depId !== observed.nodeId)
+ pending.awaitWorking = remaining.length ? remaining : undefined
+ // Persist the evidence even if the dependent PTY is temporarily unavailable. Losing
+ // this mutation would strand the arm when the next event is the legitimate `done`.
+ markChanged()
+ }
+ for (const depId of pending.awaitWorking ?? []) {
+ if (!(observed?.state === 'working' && observed.nodeId === depId))
+ this.awaitingFirstWorking.add(depId)
+ }
try {
const result = await this.attach(project, node)
if (!result.sessionId) continue
@@ -551,7 +589,11 @@ export class HeadlessNodeFactory {
const ready = pending.after.every((depId) => {
const stillExists = project.nodes.some((candidate) => candidate.id === depId)
- return !stillExists || this.deps.stateOf(depId) === 'done'
+ if (!stillExists) return true
+ if (pending.awaitWorking?.includes(depId)) return false
+ return observed?.nodeId === depId
+ ? observed.state === 'done'
+ : this.deps.stateOf(depId) === 'done'
})
if (!ready) continue
if (!(await this.deps.ptyManager.sendText(node.id, pending.command))) {
@@ -563,12 +605,14 @@ export class HeadlessNodeFactory {
const timer = this.retryTimers.get(node.id)
if (timer) (this.deps.clearSchedule ?? clearTimeout)(timer)
this.retryTimers.delete(node.id)
- const list = changedByProject.get(project) ?? []
- list.push(node)
- changedByProject.set(project, list)
+ markChanged()
}
}
+ // A working event is definitive for every pending launch in this transaction. Keep the
+ // process-local fresh-spawn index aligned even when several arms named the same dependency.
+ if (observed?.state === 'working') this.awaitingFirstWorking.delete(observed.nodeId)
+
if (changedByProject.size) {
await this.deps.workspaceStore.save(workspace)
for (const [project, nodes] of changedByProject) this.publish(project, nodes)
diff --git a/src/server/settled-envelope.test.ts b/src/server/settled-envelope.test.ts
new file mode 100644
index 000000000..80cf917b3
--- /dev/null
+++ b/src/server/settled-envelope.test.ts
@@ -0,0 +1,114 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ deliverAgentMessage,
+ type DeliveryDeps,
+ type ReceiptEvent
+} from '../core/agents/agent-message'
+import type { MirrorEntry } from '../core/agent-status-mirror'
+import { MANAGED_SCRIPT_REVISION } from '../core/agents/hooks/managed-script'
+import type { PaneOwner } from '../shared/agents/pane-owner-predicate'
+import { sendSettledEnvelope, type SettledEnvelopePty } from './settled-envelope'
+
+const pane: PaneOwner = {
+ panePid: 4242,
+ tty: '/dev/pts/9',
+ command: 'node',
+ paneId: '%7',
+ argv: ['node /usr/local/bin/claude'],
+ pids: [5100]
+}
+
+const idle: MirrorEntry = {
+ state: 'done',
+ updatedAt: 1,
+ stateVerified: true,
+ clientRevision: MANAGED_SCRIPT_REVISION
+}
+
+function deliveryDeps(
+ pty: SettledEnvelopePty,
+ subscribeEvents: DeliveryDeps['subscribeEvents']
+): DeliveryDeps {
+ return {
+ paneOwner: async () => pane,
+ bracketPasteRequested: async () => true,
+ sendEnvelope: (nodeId, envelope) => sendSettledEnvelope(pty, nodeId, envelope),
+ mirrorEntry: () => idle,
+ tokenFilePresent: () => true,
+ lock: async (_nodeId, work) => work(),
+ now: () => 1,
+ nonce: () => 'NONCE0123456',
+ trace: async () => ({ traceId: 'trace-server', traced: 'memory' }),
+ subscribeEvents
+ }
+}
+
+const request = {
+ targetNodeId: 'target',
+ sourceNodeId: 'source',
+ sourceTitle: 'Director',
+ body: 'do the work',
+ targetAgentId: 'claude'
+}
+
+afterEach(() => vi.useRealTimers())
+
+describe('sendSettledEnvelope', () => {
+ it('submits the first fresh-pane delivery only after its envelope footer is visible', async () => {
+ const listeners = new Set<(event: ReceiptEvent) => void>()
+ const writes: Array<{ text: string; enter: boolean | undefined }> = []
+ let pasted = ''
+ const pty: SettledEnvelopePty = {
+ captureSession: async () =>
+ pasted ? `Claude composer\n${pasted.split('\n').at(-1)}` : 'Claude composer',
+ sendText: async (_nodeId, text, opts) => {
+ writes.push({ text, enter: opts?.enter })
+ if (text) pasted = text
+ else queueMicrotask(() => {
+ for (const listener of listeners) {
+ listener({ nodeId: 'target', state: 'working', newTurn: true, verified: true })
+ }
+ })
+ return true
+ }
+ }
+ const outcome = await deliverAgentMessage(
+ request,
+ deliveryDeps(pty, (listener) => {
+ listeners.add(listener)
+ return () => listeners.delete(listener)
+ })
+ )
+
+ expect(outcome.kind).toBe('delivered')
+ expect(writes).toHaveLength(2)
+ expect(writes[0]).toMatchObject({ enter: false })
+ expect(writes[0].text).toContain('--- END NODETERM MESSAGE NONCE0123456 ---')
+ expect(writes[1]).toEqual({ text: '', enter: true })
+ })
+
+ it('keeps a failed post-paste submit on the unchanged stalled outcome path', async () => {
+ vi.useFakeTimers()
+ const writes: Array<{ text: string; enter: boolean | undefined }> = []
+ let pasted = ''
+ const pty: SettledEnvelopePty = {
+ captureSession: async () =>
+ pasted ? `Claude composer\n${pasted.split('\n').at(-1)}` : 'Claude composer',
+ sendText: async (_nodeId, text, opts) => {
+ writes.push({ text, enter: opts?.enter })
+ if (text) {
+ pasted = text
+ return true
+ }
+ return false
+ }
+ }
+ const run = deliverAgentMessage(request, deliveryDeps(pty, () => () => {}))
+ await vi.runAllTimersAsync()
+ const outcome = await run
+
+ expect(outcome.kind).toBe('stalled')
+ expect(writes.at(-1)).toEqual({ text: '', enter: true })
+ })
+})
diff --git a/src/server/settled-envelope.ts b/src/server/settled-envelope.ts
new file mode 100644
index 000000000..69a3dd2c3
--- /dev/null
+++ b/src/server/settled-envelope.ts
@@ -0,0 +1,99 @@
+/**
+ * Server-only agent-message delivery sequencing.
+ *
+ * A fresh Claude composer can accept a bracketed paste asynchronously: tmux has written the close
+ * marker, but an Enter queued in the same command list is consumed before the TUI has installed the
+ * pasted block. The next key then submits both messages together. Paste first, observe the pane
+ * render the unique envelope footer (or become stably different from its baseline), then submit in
+ * a second write.
+ *
+ * The boolean deliberately means "the envelope reached the pane", not "Enter was observed". Once
+ * the paste succeeds, a capture or submit failure returns true so the unchanged receipt watcher can
+ * report `stalled`; returning false would misreport a partially delivered message as `targetGone`.
+ */
+
+export const ENVELOPE_SETTLE_POLL_MS = 40
+export const ENVELOPE_SETTLE_POLLS = 15
+
+export interface SettledEnvelopePty {
+ captureSession(nodeId: string): Promise<string>
+ sendText(nodeId: string, text: string, opts?: { enter?: boolean }): Promise<boolean>
+}
+
+export interface SettledEnvelopeOptions {
+ wait?: (ms: number) => Promise<void>
+ polls?: number
+}
+
+function delay(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
+function visibleSnapshot(value: string): string {
+ return value.replace(/\r/g, '').replace(/[ \t]+$/gm, '').trimEnd()
+}
+
+function compact(value: string): string {
+ return value.replace(/\s+/g, '')
+}
+
+async function capture(pty: SettledEnvelopePty, nodeId: string): Promise<string | null> {
+ try {
+ return visibleSnapshot(await pty.captureSession(nodeId))
+ } catch {
+ return null
+ }
+}
+
+/** Paste one complete envelope and submit only after the target pane has visibly settled. */
+export async function sendSettledEnvelope(
+ pty: SettledEnvelopePty,
+ nodeId: string,
+ envelope: string,
+ options: SettledEnvelopeOptions = {}
+): Promise<boolean> {
+ if (!envelope) return false
+ const before = await capture(pty, nodeId)
+ let pasted = false
+ try {
+ pasted = await pty.sendText(nodeId, envelope, { enter: false })
+ } catch {
+ return false
+ }
+ if (!pasted) return false
+
+ const footer = compact(envelope.split('\n').at(-1) ?? '')
+ const wait = options.wait ?? delay
+ const polls = Math.max(1, options.polls ?? ENVELOPE_SETTLE_POLLS)
+ let priorChanged: string | null = null
+ let settled = false
+
+ for (let i = 0; i < polls; i++) {
+ if (i > 0) await wait(ENVELOPE_SETTLE_POLL_MS)
+ const current = await capture(pty, nodeId)
+ if (current === null) continue
+ if (footer && compact(current).includes(footer)) {
+ settled = true
+ break
+ }
+ if (current && current !== before) {
+ if (current === priorChanged) {
+ settled = true
+ break
+ }
+ priorChanged = current
+ } else {
+ priorChanged = null
+ }
+ }
+
+ if (!settled) return true
+ try {
+ // False here is intentionally still a successful paste. No receipt follows, so shared
+ // agent-messaging reports the existing non-retryable `stalled` outcome after its deadline.
+ await pty.sendText(nodeId, '', { enter: true })
+ } catch {
+ // Same partial-delivery contract as a false return from the bare Enter.
+ }
+ return true
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 3afe2cbbf..b02a650d8 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -301,6 +301,14 @@ export interface PendingLaunch {
* dependency edges without racing the server to type the command into the same pane.
*/
executor?: 'server'
+ /**
+ * Server-owned dependencies whose first real turn has not been observed yet. A freshly spawned
+ * agent can briefly report `done` while its argv prompt is still booting; that idle blip must not
+ * release a downstream launch. The server removes an id only after a verified `working` event,
+ * then requires the ordinary later `done`. Persisted so a server restart cannot forget the gate.
+ * Desktop-owned launches leave this absent; renderer parity is a separate follow-up.
+ */
+ awaitWorking?: string[]
/**
* Also wait for this worktree GROUP's project setup script to finish (`waitForSetup`). Set when
* the node is opened into a frame whose checkout is still being prepared — running a command in a