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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(control): send/reply — verified-only, with no override and no legacy path
enes99e0d3d93e86
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.tsindex d7ece2f6b..af3cfcb97 100644--- a/src/core/agent-status-mirror.ts+++ b/src/core/agent-status-mirror.ts@@ -1550,6 +1550,15 @@ export function nodeState(nodeId: string): AgentState | undefined {return state.get(nodeId)?.state}+/**+ * The full mirror entry for one node — agent messaging's gate 2 reads this (state, `stateVerified`,+ * `restored`, `idleInferred`, `clientRevision`) through `DeliveryDeps.mirrorEntry`. Read-only by+ * contract: the reference is live, and a caller that mutates it is corrupting the mirror.+ */+export function mirrorEntry(nodeId: string): MirrorEntry | undefined {+ return state.get(nodeId)+}+/*** The nodes the mirror currently believes are `working`, with the identity a synthetic event needs.* Read-only peek for the shells — the reconnect resync asks the host about exactly these, becausediff --git a/src/core/agents/agent-message.realtty.test.ts b/src/core/agents/agent-message.realtty.test.tsindex 2e36ced97..e29a2468d 100644--- a/src/core/agents/agent-message.realtty.test.ts+++ b/src/core/agents/agent-message.realtty.test.ts@@ -26,6 +26,7 @@ import path from 'path'import { deliverAgentMessage, type DeliveryDeps, type DeliveryRequest } from './agent-message'import { PANE_OWNER_FMT, foregroundArgvArgs, paneOwnerFrom, parsePaneOwner } from './pane-owner'import { bracketedInjection, PASTE_END, PASTE_START, sanitizePasteText } from '../paste-injection'+import { localFramedDelivery, runPasteDelivery } from '../tmux-naming'import { buildEnvelope } from './agent-message-envelope'import { MANAGED_SCRIPT_REVISION } from './hooks/managed-script'import type { MirrorEntry } from '../agent-status-mirror'@@ -148,11 +149,19 @@ function realPaneOwner(session: string): DeliveryDeps['paneOwner'] {}}-/** The REAL write: one `send-keys -l --`, exactly what `PtyManager.sendText`'s framed branch does. */+/**+ * The REAL write: the PRODUCTION plan (`localFramedDelivery` → `runPasteDelivery`), exactly what+ * `PtyManager.sendFramedPayload` runs — payload over `load-buffer -`'s stdin, `paste-buffer -r`+ * with no `-p` and no separate Enter. Until PR 5 this helper used `send-keys -l --`, which proved+ * the bytes but not the transport; now the same real reader judges the argv that ships.+ */function realSendFramed(session: string): DeliveryDeps['sendFramed'] {return async (_id, payload) => {- tmux('send-keys', '-t', session, '-l', '--', payload)- return true+ const plan = localFramedDelivery(socket, session, payload)+ if (!plan) return false+ return runPasteDelivery(plan, async (args, input) => {+ execFileSync(TMUX as string, args, { env, input, encoding: 'utf8' })+ })}}@@ -196,7 +205,7 @@ suite('REAL tmux pane, REAL bash: what the delivery actually does', () => {it('the whole multi-line envelope arrives as ONE block, frame intact',async () => {- const s = 'whole'+ const s = 'nt-whole' // an nt- name: the production plan asserts its target at the splicestartPane(s, 'claude')const out = await deliverAgentMessage(req({ body: 'line one\nline two' }),@@ -236,7 +245,7 @@ suite('REAL tmux pane, REAL bash: what the delivery actually does', () => {it('a body carrying the paste-END marker plus a command does NOT execute it',async () => {- const s = 'escape'+ const s = 'nt-escape' // nt- name, same reason as nt-wholeconst marker = path.join(work, 'PWNED-escape')startPane(s, 'claude')const out = await deliverAgentMessage(diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex 0023ce868..713b6e5a0 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -155,6 +155,32 @@ export interface HookEventMeta {verified: boolean}+/**+ * Control verbs that admit ONLY a `verified` caller — the agent-messaging verbs.+ *+ * A route that admits only `verified` is untouched by the foreign-kid escape: an invented kid is+ * FOREIGN, therefore `legacy` (invariant 3, required or cross-instance failover dies), therefore+ * never `verified` (node-identity-policy.ts, `verifyNodeToken`'s foreign-kid rule). The escape+ * defeats the latch and the window. It does not defeat this.+ *+ * Deliberately NOT routed through controlPolicy: `settings.hookIdentityStrict: false` releases the+ * latch and the dated cutoff, and it must never release these. There is no upgrade population to+ * protect — the routes are new — which is the one place in the whole control surface where+ * fail-closed from day one costs nobody anything.+ *+ * Consulted in the `/control/` route BEFORE `identityGate`'s decision is, so no future change to+ * the policy table can widen it; `messaging-verified-only.test.ts` drives the route on both sides+ * of every hatch and is the test that fails if either half of this comment stops being true.+ */+export const requiresVerified: ReadonlySet<string> = new Set(['send', 'reply'])++/**+ * The refusal for a messaging verb: one sentence, no diagnosis, no hint about tokens or restarts —+ * the same posture as STRICT_CONTROL_REFUSAL, for the same reason. Advice here is advice to an+ * attacker and a lie to nobody else.+ */+export const MESSAGING_CONTROL_REFUSAL = 'Agent messaging refused.'+class HookServer {private server: Server | null = nullprivate port = 0@@ -458,6 +484,19 @@ class HookServer {res.end()return}+ // VERIFIED-ONLY VERBS, decided on the VERDICT and never on the decision: the policy's+ // `decision` is what the escape hatch and the warning window can reach, and neither may+ // reach these. See `requiresVerified` for the whole argument.+ if (requiresVerified.has(verb) && verdict !== 'verified') {+ if (wantsText) {+ res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' })+ res.end(`${MESSAGING_CONTROL_REFUSAL}\n`)+ } else {+ res.writeHead(403, { 'content-type': 'application/json' })+ res.end(JSON.stringify({ ok: false, error: MESSAGING_CONTROL_REFUSAL }))+ }+ return+ }if (decision === 'refuse') {// The route's own refusal shape, so the sh shim (which prints any non-200 body to// stderr and exits 1) shows the sentence and nothing else.diff --git a/src/core/agents/messaging-verified-only.test.ts b/src/core/agents/messaging-verified-only.test.tsnew file mode 100644index 000000000..22b7d0ce0--- /dev/null+++ b/src/core/agents/messaging-verified-only.test.ts@@ -0,0 +1,143 @@+/**+ * The messaging verbs admit ONLY a `verified` caller — proven on the wire, against the real+ * hook server, on both sides of every escape hatch.+ *+ * The load-bearing claim: `settings.hookIdentityStrict: false` releases the latch and the dated+ * cutoff (node-identity-policy.ts, the `override === false` branch), and the foreign-kid escape+ * walks past both (an invented kid is FOREIGN, therefore `legacy`, therefore inside the branch the+ * hatch releases). Neither may release `send`/`reply`. That is why `requiresVerified` is a separate+ * check in hook-server.ts and NOT a controlPolicy row — and why this suite drives the HTTP route+ * rather than the policy table: a policy-table test cannot see the route consulting the policy+ * first.+ */+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { initPlatform, resetPlatformForTests } from '../platform'+import { fakePlatform } from '../platform-fake'+import { hookServer, MESSAGING_CONTROL_REFUSAL, requiresVerified } from './hook-server'+import { nodeAuthToken } from './node-auth-token'+import { TOLERANT_CONTROL_VERBS } from './node-identity-policy'+import { DESTRUCTIVE_VERBS } from '../../shared/control-verbs'++const SECRET = Buffer.alloc(32, 5)+/** Another instance's secret: a token minted with it is a FOREIGN kid — the invented-kid escape. */+const FOREIGN_SECRET = Buffer.alloc(32, 9)+let dir = ''+let handled: string[] = []++function post(verb: string, nodeId: string, token?: string, accept = 'application/json') {+ const headers: Record<string, string> = {+ 'X-Nodeterm-Hook-Token': hookServer.getToken(),+ 'content-type': 'application/x-www-form-urlencoded',+ accept+ }+ if (token) headers['X-Nodeterm-Node-Token'] = token+ return fetch(`http://127.0.0.1:${hookServer.getPort()}/control/${verb}`, {+ method: 'POST',+ headers,+ body: `nodeId=${encodeURIComponent(nodeId)}&arg.node=n-target&arg.text=hi`+ })+}++beforeAll(async () => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-msg-verified-'))+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: dir }))+ await hookServer.start()+ hookServer.setNodeAuthSecret(SECRET)+ // Records what REACHED the handler: the promise of a refusal is that nothing happened, so the+ // suite asserts absence here rather than inferring it from a status code.+ hookServer.setControlHandler(async ({ verb }) => {+ handled.push(verb)+ return { ok: true, message: 'handled' }+ })+})++afterAll(() => {+ hookServer.setIdentityStrictOverride(() => undefined)+ hookServer.clearNodeAuthSecretForTests()+ hookServer.stop()+ resetPlatformForTests()+ fs.rmSync(dir, { recursive: true, force: true })+})++beforeEach(() => {+ handled = []+})++describe('send/reply require `verified` — and controlPolicy is NOT the decider', () => {+ it('refuses legacy and foreign-kid callers under every hookIdentityStrict value', async () => {+ // A separate check runs FIRST and is not overridable. settings.hookIdentityStrict: false+ // releases the latch and the cutoff (the `override === false` branch of controlPolicy); it+ // must NOT release these routes.+ for (const strict of [true, false, undefined]) {+ hookServer.setIdentityStrictOverride(() => strict)+ for (const verb of requiresVerified) {+ const legacy = await post(verb, 'n-src')+ expect(legacy.status, `${verb} legacy strict=${String(strict)}`).toBe(403)+ expect(((await legacy.json()) as { error: string }).error).toBe(MESSAGING_CONTROL_REFUSAL)++ // The invented-kid escape: a token minted under ANOTHER secret is a foreign kid, which+ // invariant 3 requires to be `legacy` — it walks past the latch and the window. Not here.+ const foreign = await post(verb, 'n-src', nodeAuthToken(FOREIGN_SECRET, 'n-src'))+ expect(foreign.status, `${verb} foreign-kid strict=${String(strict)}`).toBe(403)++ const own = await post(verb, 'n-src', nodeAuthToken(SECRET, 'n-src'))+ expect(own.status, `${verb} verified strict=${String(strict)}`).not.toBe(403)+ }+ }+ // Only the verified calls reached the handler — one per verb per strict value.+ expect(handled).toEqual([true, false, undefined].flatMap(() => [...requiresVerified]))+ })++ it('tells a text/plain caller the same refusal, without token or restart advice', async () => {+ hookServer.setIdentityStrictOverride(() => undefined)+ const res = await post('send', 'n-src', undefined, 'text/plain')+ expect(res.status).toBe(403)+ const text = (await res.text()).trim()+ expect(text).toBe(MESSAGING_CONTROL_REFUSAL)+ // No diagnosis and no hint: advice here is advice to an attacker and a lie to nobody else.+ for (const hint of ['token', 'Restart', 'restart', 'identity']) {+ expect(text).not.toContain(hint)+ }+ expect(handled).toEqual([])+ })++ it('a caller with NO minted secret at all (identity unavailable) is still refused', async () => {+ // identityGate short-circuits to `legacy`/`allow` with no secret. The verbs are fail-closed+ // from day one — there is no upgrade population to protect.+ hookServer.clearNodeAuthSecretForTests()+ try {+ for (const verb of ['send', 'reply'] as const) {+ const res = await post(verb, 'n-src')+ expect(res.status, verb).toBe(403)+ }+ expect(handled).toEqual([])+ } finally {+ hookServer.setNodeAuthSecret(SECRET)+ }+ })+})++describe('where the verbs sit in the routing tables', () => {+ // `needsLiveCanvas('send'/'reply') === false` is pinned where the function lives —+ // `src/renderer/lib/controlRouting.test.ts` — because this core project cannot import the+ // renderer without breaking tsconfig.node's file list.++ it('send/reply are in neither DESTRUCTIVE_VERBS nor TOLERANT_CONTROL_VERBS', () => {+ for (const verb of ['send', 'reply']) {+ // Not confirm-gated (the per-project switch + verified-only + flow control are the gates),+ // and not tolerated for an unproven legacy caller (the opposite: verified-only).+ expect(DESTRUCTIVE_VERBS.has(verb as never), verb).toBe(false)+ expect(TOLERANT_CONTROL_VERBS.has(verb), verb).toBe(false)+ }+ })++ it('the verified-only set is exactly the messaging verbs', () => {+ // Pins that nothing ELSE ever drifts in: adding a SHIPPED verb here would strand its legacy+ // population with no hatch, which is the one thing this set must never be casually grown by.+ expect([...requiresVerified].sort()).toEqual(['reply', 'send'])+ })+})diff --git a/src/core/board-log-handlers.ts b/src/core/board-log-handlers.tsindex 6f9eef722..213d7a47c 100644--- a/src/core/board-log-handlers.ts+++ b/src/core/board-log-handlers.ts@@ -29,14 +29,30 @@ const POLL_MS = 5000/** Registers boardLogAppend / boardLogRead / boardLogSubscribe / boardLogUnsubscribe and drives the* per-project `boardLogChanged` push. Ref-counted per project: the first subscriber starts a watch* (local fs.watch) or a poll (desktop SSH), the last one stops it. */+/**+ * Append one entry through a router — the same routing the `boardLogAppend` IPC handler performs,+ * exported so an in-process writer (the agent-messaging delivery trace) appends through the+ * identical local/remote/unsupported decision instead of restating it. `false` covers both "no+ * reachable log" (a cwd-less inline project, a disconnected SSH project) and a failed write —+ * exactly the answer `recordDelivery` treats as "ring only".+ */+export function appendBoardLogVia(+ router: BoardLogRouter,+ projectId: string,+ entry: BoardLogEntry,+ localStore = new BoardLogStore({})+): Promise<boolean> {+ const r = router.route(projectId)+ if (r.kind === 'local') return localStore.append(r.cwd, entry)+ if (r.kind === 'remote') return new BoardLogStore({ remote: r.exec }).append(r.remoteCwd, entry)+ return Promise.resolve(false)+}+export function registerBoardLogHandlers(platform: CorePlatform, router: BoardLogRouter): void {const localStore = new BoardLogStore({})platform.handle(IPC.boardLogAppend, async (projectId: string, entry: BoardLogEntry): Promise<boolean> => {- const r = router.route(projectId)- if (r.kind === 'local') return localStore.append(r.cwd, entry)- if (r.kind === 'remote') return new BoardLogStore({ remote: r.exec }).append(r.remoteCwd, entry)- return false+ return appendBoardLogVia(router, projectId, entry, localStore)})platform.handle(diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 3da510954..a79f87dfc 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -27,6 +27,7 @@ import {localTmuxKillArgs,remoteTmuxPtyArgs,remotePasteDelivery,+ remoteFramedDelivery,remoteCapturePaneArgs,remotePaneCommandArgs,remotePaneOwnerArgs,@@ -51,6 +52,7 @@ import {sessionName,isSessionName,localPasteDelivery,+ localFramedDelivery,runPasteDelivery} from './tmux-naming'import { encodeSendKeysHex } from './tmux-control'@@ -2989,6 +2991,49 @@ export class PtyManager {* from "I cannot ask", which is exactly the confusion that shipped the bug.*/+ /**+ * Deliver one ALREADY-FRAMED payload — the agent-messaging envelope, composed by+ * `bracketedInjection` in `deliverAgentMessage` — into a node's pane, local or SSH.+ *+ * A two-line dispatcher over `localFramedDelivery` / `remoteFramedDelivery`, exactly as+ * `sendText` is over its plans and for the same reason: the composition (the no-sanitize rule,+ * the well-formed-frame assertion, the per-call buffer, the failure sweep) lives in the plan+ * builders, where `agent-message.realtty.test.ts` drives the local one against a real tmux and+ * a real bash. NOT `sendText`: that path sanitizes structurally, which would strip the ESC+ * bytes that ARE this payload's frame.+ */+ async sendFramedPayload(persistKey: string, payload: string): Promise<boolean> {+ const target = sessionName(persistKey)+ const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemote+ try {+ if (sshRemote) {+ const ssh = findSsh()+ if (!ssh) return false+ const plan = remoteFramedDelivery(sshRemote.conn, sshRemote.controlPath, target, payload)+ if (!plan) return false+ return await runPasteDelivery(plan, (args, input) => runWithStdin(ssh, args, input))+ }+ if (!this.tmuxPath) return false+ const tmuxPath = this.tmuxPath+ const plan = localFramedDelivery(TMUX_SOCKET, target, payload)+ if (!plan) return false+ return await runPasteDelivery(plan, (args, input) => runWithStdin(tmuxPath, args, input))+ } catch {+ // A builder throwing (unsafe target, an unframed payload) lands here; `runPasteDelivery`+ // itself answers false rather than throwing, so the buffer sweep is never skipped.+ return false+ }+ }++ /**+ * Does a live session exist for this node in THIS process right now? The messaging delivery's+ * `targetLive` fact — deliberately not derived from an unreadable pane (see `DeliveryRequest`):+ * only "no session is registered" may be reported as "the node is gone".+ */+ hasLiveSession(persistKey: string): boolean {+ return !!this.sessionByPersistKey(persistKey)+ }+/*** List the names of all live nodeterm tmux sessions (on our dedicated socket). Used by the* relay host's `projects.list` RPC so a paired phone can enumerate the host's sessions the samediff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.tsindex 82191e71a..38af19235 100644--- a/src/core/remote-ssh/control-master.test.ts+++ b/src/core/remote-ssh/control-master.test.ts@@ -6,6 +6,7 @@ import {childArgs,remoteTmuxHasSessionArgs,remoteTmuxPasteArgs,+ remoteFramedDelivery,remoteTmuxEnterArgs,probeSaysAbsent,remoteCapturePaneArgs,@@ -479,3 +480,49 @@ describe('killing a session by name (both sockets, exact target)', () => {for (const r of runs) expect(r.slice(0, childPrefix.length)).toEqual(childPrefix)})})++/**+ * The remote leg of the messaging envelope's delivery — the exact mirror of `localFramedDelivery`+ * (see tmux-naming.test.ts for the local twin and the full argument): payload byte-for-byte over+ * stdin, `paste-buffer -r` with NO `-p` (the bytes already carry their frame), no trailing Enter+ * (the composed `\r` rides inside the paste), and a refusal for anything that is not+ * `bracketedInjection` output — this is the one plan that does not sanitize, so it must not accept+ * what sanitize would have caught.+ */+describe('remoteFramedDelivery', () => {+ const TMUX = `tmux -L ${RMT_TMUX_SOCKET}`+ const PASTE_START = '\x1b[200~'+ const PASTE_END = '\x1b[201~'+ const framed = (inner: string): string => PASTE_START + inner + PASTE_END + '\r'++ it('moves the payload byte-for-byte and never re-frames (-r, no -p, no Enter)', () => {+ const payload = framed('line one\nline two')+ const plan = remoteFramedDelivery(conn, '/s.sock', 'nt-x', payload)!+ expect(plan.body).toBe(payload)+ const line = plan.args.slice(-1)[0]+ const buf = /-b (nt-paste-[0-9a-f]{12}) /.exec(line)?.[1]+ expect(buf).toBeTruthy()+ expect(plan.args).toEqual([+ ...childPrefix,+ '[email protected]',+ `${TMUX} load-buffer -b ${buf} - ';' ` ++ `if-shell -F -t nt-x '#{pane_in_mode}' 'send-keys -t nt-x -X cancel' ';' ` ++ `paste-buffer -d -r -b ${buf} -t nt-x`+ ])+ expect(line).not.toContain('-p -r')+ expect(line).not.toContain('Enter')+ expect(plan.cleanup?.slice(-1)[0]).toBe(`${TMUX} delete-buffer -b ${buf}`)+ })++ it('refuses a payload that is not a well-formed, pre-sanitized frame', () => {+ expect(() => remoteFramedDelivery(conn, '/s.sock', 'nt-x', 'naked\r')).toThrow(/framed/)+ expect(() => remoteFramedDelivery(conn, '/s.sock', 'nt-x', framed(`a${PASTE_END}b`))).toThrow(/framed/)+ expect(remoteFramedDelivery(conn, '/s.sock', 'nt-x', '')).toBeNull()+ })++ it('refuses an unsafe target like every sibling builder', () => {+ expect(() => remoteFramedDelivery(conn, '/s.sock', 'nt-x; kill-server', framed('x'))).toThrow(+ /unsafe tmux paste target/+ )+ })+})diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.tsindex d7699c181..c5db1f51f 100644--- a/src/core/remote-ssh/control-master.ts+++ b/src/core/remote-ssh/control-master.ts@@ -6,6 +6,7 @@ import { createHash } from 'crypto'import { posixQuote, quoteRemotePath, remoteTmuxCommand, type SshConnection } from '../../shared/ssh'import {TMUX_SOCKET,+ assertFramedPayload,assertPasteTarget,assertPasteBuffer,pasteBufferName,@@ -266,6 +267,50 @@ export function remoteTmuxPasteArgs(return childArgs(conn, controlPath, cmd)}+/**+ * The remote leg of the messaging envelope's delivery — `remoteFramedDelivery`'s argv. The exact+ * mirror of `localTmuxFramedPasteArgs` (tmux-naming.ts): NO `-p`, because the payload already+ * carries its frame and tmux re-framing it would render the inner markers as garbage; `-r` so the+ * bytes land verbatim; no trailing Enter, because the composed `\r` rides inside the paste.+ */+export function remoteTmuxFramedPasteArgs(+ conn: SshConnection,+ controlPath: string,+ sessionId: string,+ buffer: string+): string[] {+ assertPasteTarget(sessionId, buffer)+ const tmux = `tmux -L ${RMT_TMUX_SOCKET}`+ const cmd =+ `${tmux} load-buffer -b ${buffer} - ';' ` ++ `if-shell -F -t ${sessionId} '#{pane_in_mode}' 'send-keys -t ${sessionId} -X cancel' ';' ` ++ `paste-buffer -d -r -b ${buffer} -t ${sessionId}`+ return childArgs(conn, controlPath, cmd)+}++/**+ * The plan for delivering one composed frame remotely — same three decisions as+ * `localFramedDelivery`, taken by the SAME `assertFramedPayload` rather than restated: this is the+ * one plan pair that does not sanitize (the frame's ESC bytes must survive), so it refuses+ * anything that is not `bracketedInjection` output. No bare-Enter case: an envelope is never+ * empty, and a lone Enter into an agent's composer is an accidental submit.+ */+export function remoteFramedDelivery(+ conn: SshConnection,+ controlPath: string,+ sessionId: string,+ payload: string+): PasteDelivery | null {+ if (payload.length === 0) return null+ assertFramedPayload(payload)+ const buffer = pasteBufferName()+ return {+ args: remoteTmuxFramedPasteArgs(conn, controlPath, sessionId, buffer),+ body: payload,+ cleanup: remoteDeleteBufferArgs(conn, controlPath, buffer)+ }+}+/*** A bare Enter into the remote pane — the remote half of `sendText`'s empty-payload case.*diff --git a/src/core/tmux-naming.test.ts b/src/core/tmux-naming.test.tsindex 7cb428a54..a8e6723b3 100644--- a/src/core/tmux-naming.test.ts+++ b/src/core/tmux-naming.test.ts@@ -1,5 +1,6 @@import { describe, it, expect } from 'vitest'import {+ localFramedDelivery,localTmuxEnterArgs,localTmuxPasteArgs,pasteBufferName,@@ -86,3 +87,62 @@ describe('localTmuxPasteArgs', () => {expect(() => localTmuxPasteArgs('sock', sessionName('term-mabc-3'), pasteBufferName(), true)).not.toThrow()})})++/**+ * The messaging envelope's delivery (`deliverAgentMessage` → `PtyManager.sendFramedPayload`). The+ * payload arrives ALREADY FRAMED by `bracketedInjection` — markers, sanitized body, trailing `\r`+ * all composed in `src/core` — so this plan's one job is to move those bytes verbatim: stdin in,+ * `paste-buffer -r` out, and NO `-p` (tmux re-framing an already-framed payload would turn the+ * inner markers into visible garbage in the target's composer).+ */+describe('localFramedDelivery', () => {+ const PASTE_START = '\x1b[200~'+ const PASTE_END = '\x1b[201~'+ const framed = (inner: string): string => PASTE_START + inner + PASTE_END + '\r'++ it('moves the payload byte-for-byte — the frame markers survive to the pane', () => {+ const payload = framed('line one\nline two')+ const plan = localFramedDelivery('sock', 'nt-x', payload)+ // The mutation this catches: a "helpful" sanitizePasteText here strips the ESC bytes that ARE+ // the frame, and the multi-line body would land unframed — herdr :260, reintroduced by us.+ expect(plan?.body).toBe(payload)+ })++ it('is one invocation: stdin buffer, gated cancel, raw paste — no -p, no separate Enter', () => {+ const plan = localFramedDelivery('sock', 'nt-x', framed('hi'))!+ const buf = plan.args[plan.args.indexOf('-b') + 1]+ expect(buf).toMatch(/^nt-paste-[0-9a-f]{12}$/)+ expect(plan.args).toEqual([+ '-L', 'sock',+ 'load-buffer', '-b', buf, '-',+ ';', 'if-shell', '-F', '-t', 'nt-x', '#{pane_in_mode}', 'send-keys -t nt-x -X cancel',+ ';', 'paste-buffer', '-d', '-r', '-b', buf, '-t', 'nt-x'+ ])+ // No `-p`: the frame is already in the bytes. No trailing Enter: the `\r` rides INSIDE the+ // one paste, so text and submit cannot be re-chunked apart (herdr :48).+ expect(plan.args).not.toContain('-p')+ expect(plan.args).not.toContain('Enter')+ expect(plan.cleanup).toEqual(['-L', 'sock', 'delete-buffer', '-b', buf])+ })++ it('refuses a payload that is not a well-formed, pre-sanitized frame', () => {+ // This plan deliberately does NOT sanitize (the frame's own ESC bytes must survive), so it+ // must refuse anything that is not `bracketedInjection` output — otherwise it would be the+ // one path where unsanitized text reaches a pane. Same fail direction as assertPasteTarget.+ expect(() => localFramedDelivery('sock', 'nt-x', 'naked text\r')).toThrow(/framed/)+ expect(() => localFramedDelivery('sock', 'nt-x', PASTE_START + 'no close')).toThrow(/framed/)+ // An ESC inside the frame could close it early — bracketedInjection can never produce this.+ expect(() => localFramedDelivery('sock', 'nt-x', framed(`a${PASTE_END}b`))).toThrow(/framed/)+ expect(() => localFramedDelivery('sock', 'nt-x', framed('a\x1b[31mb'))).toThrow(/framed/)+ // Without the trailing \r is also legal composition (enter: false).+ expect(() => localFramedDelivery('sock', 'nt-x', PASTE_START + 'ok' + PASTE_END)).not.toThrow()+ })++ it('answers null for an empty frame — there is no bare-Enter case for an envelope', () => {+ expect(localFramedDelivery('sock', 'nt-x', '')).toBeNull()+ })++ it('refuses an unsafe target like every other builder', () => {+ expect(() => localFramedDelivery('sock', 'nt-x; kill-server', framed('x'))).toThrow(/paste target/)+ })+})diff --git a/src/core/tmux-naming.ts b/src/core/tmux-naming.tsindex 58ac892cf..9ba5b1472 100644--- a/src/core/tmux-naming.ts+++ b/src/core/tmux-naming.ts@@ -265,6 +265,89 @@ export function localPasteDelivery(}}+/**+ * Is `payload` the output of `bracketedInjection` — a complete frame whose interior went through+ * `sanitizePasteText`?+ *+ * `localFramedDelivery`/`remoteFramedDelivery` deliberately do NOT sanitize: the frame's own ESC+ * bytes ARE the framing, and stripping them (as every other plan in this file does, structurally)+ * would land the multi-line envelope unframed — herdr :260, reintroduced by the delivery built to+ * avoid it. Not sanitizing is only safe if nothing unframed or unsanitized can pass, so that is+ * asserted at the splice, same fail direction as `assertPasteTarget`: throw, never repair.+ * `tmux-naming.test.ts` ("refuses a payload that is not a well-formed, pre-sanitized frame") is+ * the test that fails if this stops being true.+ */+export function assertFramedPayload(payload: string): void {+ const START = '\x1b[200~'+ const END = '\x1b[201~'+ const ok =+ payload.startsWith(START) &&+ (payload.endsWith(END) || payload.endsWith(`${END}\r`)) &&+ payload.length >= START.length + END.length+ if (!ok) throw new Error('not a framed payload')+ const tail = payload.endsWith('\r') ? payload.length - END.length - 1 : payload.length - END.length+ const inner = payload.slice(START.length, tail)+ // No ESC (or 8-bit C1 CSI) byte may survive inside the frame — one could close it early and turn+ // the rest into key input. `bracketedInjection` can never produce one; refuse anything else.+ // eslint-disable-next-line no-control-regex+ if (/[\x1b]/.test(inner)) throw new Error('framed payload interior is not sanitized')+}++/**+ * The one tmux invocation that delivers an ALREADY-FRAMED payload (the messaging envelope):+ * stdin buffer, the same gated copy-mode cancel as `localTmuxPasteArgs`, then `paste-buffer -r`+ * with NO `-p` — tmux must not re-frame bytes that already carry their frame — and no trailing+ * Enter, because the composed `\r` rides INSIDE the paste, so text and submit are one write and+ * can never be re-chunked apart (herdr :48).+ */+export function localTmuxFramedPasteArgs(socket: string, target: string, buffer: string): string[] {+ assertPasteTarget(target, buffer)+ return [+ '-L',+ socket,+ 'load-buffer',+ '-b',+ buffer,+ '-',+ ';',+ 'if-shell',+ '-F',+ '-t',+ target,+ '#{pane_in_mode}',+ `send-keys -t ${target} -X cancel`,+ ';',+ 'paste-buffer',+ '-d',+ '-r',+ '-b',+ buffer,+ '-t',+ target+ ]+}++/**+ * The plan for delivering one composed frame locally, or null when there is nothing to deliver.+ * Unlike `localPasteDelivery` there is no bare-Enter case: an envelope is never empty, and a+ * lone Enter into an agent's composer is exactly the accidental submit this delivery exists to+ * make impossible.+ */+export function localFramedDelivery(+ socket: string,+ target: string,+ payload: string+): PasteDelivery | null {+ if (payload.length === 0) return null+ assertFramedPayload(payload)+ const buffer = pasteBufferName()+ return {+ args: localTmuxFramedPasteArgs(socket, target, buffer),+ body: payload,+ cleanup: localTmuxDeleteBufferArgs(socket, buffer)+ }+}+/*** Run a plan. The runner is injected so this is the same code in production and under a real tmux.*diff --git a/src/main/agent-messaging.test.ts b/src/main/agent-messaging.test.tsnew file mode 100644index 000000000..d4f779eb4Binary files /dev/null and b/src/main/agent-messaging.test.ts differdiff --git a/src/main/agent-messaging.ts b/src/main/agent-messaging.tsnew file mode 100644index 000000000..6212bcef8--- /dev/null+++ b/src/main/agent-messaging.ts@@ -0,0 +1,374 @@+/**+ * The desktop's agent-messaging service — the ONE caller of `deliverAgentMessage` (PR #207).+ *+ * Canvas.tsx's dispatch for `send`/`reply` is deliberately thin: it validates the arguments,+ * checks the SOURCE is a control-capable agent, and forwards `{verb, sourceNodeId, targetNodeId,+ * body}` here over IPC. Everything that decides whether and how the message lands runs in THIS+ * process, against main's own stores — the scope resolution, the per-project switch, flow control,+ * the pane probes, the envelope, the receipt, the trace — so nothing that ends up inside the+ * envelope or inside an authorization decision is renderer-supplied beyond the two node ids and+ * the body. `agent-messaging.test.ts` runs the whole service; `agent-message.test.ts` and+ * `agent-message.realtty.test.ts` pin the primitive underneath it.+ *+ * ── THREE SURFACES ──────────────────────────────────────────────────────────────────────────────+ * - **Desktop (Electron):** wired in `src/main/index.ts` — the only surface with the verbs.+ * - **Server Edition:** never wired; `/control/send` answers `control-unsupported-on-this-edition`+ * (`src/server/control-unsupported.ts`) for a verified caller and the messaging refusal for an+ * unverified one. Everything this file imports from `src/core` still ships on both shells.+ * - **Mobile (phone):** never a sender (it drives canvas control over relay→IPC, not `/control/*`);+ * a phone-spawned node is a valid TARGET and resolves like any other store node.+ */+import type { NormalizedAgentEvent } from '../shared/agents/normalize'+import { binariesFor, type PaneOwner } from '../shared/agents/pane-owner-predicate'+import type { BoardLogEntry } from '../shared/types'+import type {+ AgentMessageDeliverRequest,+ AgentMessageReply+} from '../shared/agents/agent-messaging'+import { AGENT_MESSAGE_VERBS } from '../shared/agents/agent-messaging'+import {+ deliverAgentMessage,+ type DeliveryDeps,+ type ReceiptEvent+} from '../core/agents/agent-message'+import {+ RETRYABLE,+ type AgentMessageOutcome,+ type NotPermittedReason+} from '../core/agents/agent-message-decide'+import { checkFlowLimits, noteNewTurn, noteSent } 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'+import { mirrorEntry as coreMirrorEntry, type MirrorEntry } from '../core/agent-status-mirror'++/** The little the service needs to know about a stored node. */+export interface MessagingStoredNode {+ id: string+ title?: string+ agentId?: string+}++/**+ * Every side effect and every store read, injected — same reasoning as `DeliveryDeps`: the suite+ * tests the SERVICE (scope→switch→flow→deps→reply) without a pty, a workspace file or a window.+ */+export interface AgentMessagingDeps {+ paneOwner(nodeId: string): Promise<PaneOwner | null>+ sendFramedPayload(nodeId: string, payload: string): Promise<boolean>+ hasLiveSession(nodeId: string): boolean+ mirrorEntry?(nodeId: string): MirrorEntry | undefined+ /** The main-process projects store (`workspaceStore.persistedCanvases()` on the desktop). */+ projects(): readonly { id: string; nodes: readonly MessagingStoredNode[] }[]+ isRemoteNode(nodeId: string): boolean+ /**+ * The per-project switch (Global Constraint 11): messaging is OFF unless the project opted in.+ * PR 6 gives `Project`/`ProjectFileV1` the `agentMessaging` field (validated `=== true` — the+ * file is hostile input) and wires this to it; until then the desktop wires `() => false`, so+ * the verbs ship fail-closed and every delivery answers `notPermitted (switch-off)`.+ */+ messagingEnabled(projectId: string): boolean+ customAgents(): readonly { id: string; launchCmd: string }[] | undefined+ appendBoardLog(projectId: string, entry: BoardLogEntry): Promise<boolean>+ /** Test seam: override the receipt subscription. Production uses the module bus below. */+ subscribeReceipts?(cb: (e: ReceiptEvent) => void): () => void+ now?(): number+}++// ── The receipt bus ───────────────────────────────────────────────────────────────────────────+// One tap on the normalized hook-event stream, fanned to per-delivery receipt watches. Fed by+// main/index.ts's `emitAgentStatus` — the same single stream the canvas store and the mobile+// mirror consume, so the receipt can never disagree with the badge about what the target did.+const receiptSubs = new Set<(e: ReceiptEvent) => void>()++function subscribeBus(cb: (e: ReceiptEvent) => void): () => void {+ receiptSubs.add(cb)+ return () => receiptSubs.delete(cb)+}++/**+ * 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+ * event is offered to the open receipt watches — which accept only `verified: true`+ * (`watchForReceipt`), so an unverifiable event resets a budget (fail-open, the flow module's+ * designed direction) but can never confirm a delivery (fail-closed, the receipt's).+ */+export function onMessagingAgentEvent(+ e: Pick<NormalizedAgentEvent, 'nodeId' | 'state' | 'newTurn' | 'verified'>+): void {+ if (!e?.nodeId) return+ if (e.newTurn === true) noteNewTurn(e.nodeId)+ const ev: ReceiptEvent = {+ nodeId: e.nodeId,+ newTurn: e.newTurn,+ state: e.state,+ verified: e.verified+ }+ for (const cb of [...receiptSubs]) cb(ev)+}++// ── The per-node delivery lock ────────────────────────────────────────────────────────────────+// Serialises deliveries against the SAME target inside this process. The renderer additionally+// wraps its IPC call in `guardConcurrentRestart(targetNodeId, …)`, which is what keeps a delivery+// out of a restart/wake's un-submitted resume line — the two locks guard different hazards in+// different processes, and neither replaces the other.+const nodeLocks = new Map<string, Promise<unknown>>()++function withNodeLock<T>(nodeId: string, fn: () => Promise<T>): Promise<T> {+ const prev = nodeLocks.get(nodeId) ?? Promise.resolve()+ const run = prev.then(fn, fn)+ nodeLocks.set(+ nodeId,+ run.then(+ () => undefined,+ () => undefined+ )+ )+ return run+}++/** The sentence for each `notPermitted` reason — exhaustive by the Record type, like RETRYABLE. */+const NOT_PERMITTED_TEXT: Record<NotPermittedReason, string> = {+ 'switch-off':+ 'agent messaging is switched off for this project (Settings → Agents enables it per project).',+ 'cross-project': 'the target node is not in the sending node\'s project.',+ 'self-send': 'a node cannot message itself.',+ 'unsupported-edition': 'agent messaging does not exist on this edition.',+ 'unaddressable-node-id': 'that node id cannot be addressed safely.'+}++/**+ * Render one typed outcome as the control reply the shim prints and a JSON client parses.+ *+ * The caller is a LANGUAGE MODEL, so whether to retry is stated IN WORDS and sourced from+ * `RETRYABLE` — the test asserts the words and the table can never disagree. `ok` is true only+ * for an outcome whose bytes reached the pane and were (or will be) consumed: `delivered`,+ * `stalled` (the text may already sit in the composer — a retry is a DOUBLE delivery, which is+ * exactly what `watchForReceipt`'s comment warns an ok:false would provoke) and `queued` (PR 7).+ */+export function renderMessageOutcome(o: AgentMessageOutcome): AgentMessageReply {+ const advice = RETRYABLE[o.kind]+ ? 'Retryable — wait, then try once more.'+ : 'Do not retry.'+ const trace = 'traceId' in o ? ` Trace ${o.traceId}${'traced' in o ? ` (${o.traced})` : ''}.` : ''+ switch (o.kind) {+ case 'delivered':+ return {+ ok: true,+ message: `delivered: the target started its turn (signal: ${o.signal}).${trace}`,+ result: o+ }+ case 'stalled':+ return {+ ok: true,+ message:+ `stalled: the message reached the pane but the target started no turn within ` ++ `${o.waitedMs}ms — it may sit unsubmitted in the composer. Do not retry: a second send ` ++ `would deliver the message twice.${trace}`,+ result: o+ }+ case 'queued':+ return {+ ok: true,+ message: `queued at position ${o.position}, expires in ${o.ttlMs}ms.${trace}`,+ result: o+ }+ case 'deliveredToReplacedTarget':+ return {+ ok: false,+ error:+ `deliveredToReplacedTarget: the pane changed hands during delivery ` ++ `(was: ${o.wasPane}, now: ${o.nowPane}); the bytes cannot be unsent and the event is ` ++ `recorded. ${advice}${trace}`,+ result: o+ }+ case 'expired':+ return {+ ok: false,+ error: `expired: the message waited ${o.queuedForMs}ms queued and was dropped. ${advice}${trace}`,+ result: o+ }+ case 'rateLimited':+ return {+ ok: false,+ error: `rateLimited: over the messaging budget — retry after ${o.retryAfterMs}ms.`,+ result: o+ }+ case 'queueFull':+ return {+ ok: false,+ error: `queueFull: the target's queue is at capacity (${o.capacity}). ${advice}`,+ result: o+ }+ case 'targetBusy':+ return {+ ok: false,+ error: `targetBusy: the target is mid-turn (${o.state}). ${advice}`,+ result: o+ }+ case 'targetNotIdleUnknown':+ return {+ ok: false,+ error: `targetNotIdleUnknown: ${o.reason}. ${advice}`,+ result: o+ }+ case 'targetStatusUnverified':+ return {+ ok: false,+ error: `targetStatusUnverified: ${o.note}. ${advice}`,+ result: o+ }+ case 'targetStatusStale':+ return {+ ok: false,+ error:+ 'targetStatusStale: the target has a node identity but has not posted a verified ' ++ `status yet. ${advice}`,+ result: o+ }+ case 'targetHookScriptStale':+ return {+ ok: false,+ error: `targetHookScriptStale: ${o.note}. ${advice}`,+ result: o+ }+ case 'targetNotAgentPane':+ return {+ ok: false,+ error:+ `targetNotAgentPane: the target's pane is not running its agent right now ` ++ `(observed: ${o.observed}). ${advice}`,+ result: o+ }+ case 'targetNotPasteAware':+ return {+ ok: false,+ error:+ 'targetNotPasteAware: the target pane did not request bracketed paste, and a ' ++ `multi-line message would submit line by line. ${advice}`,+ result: o+ }+ case 'targetGone':+ return {+ ok: false,+ error: `targetGone: no live session exists for the target node. ${advice}`,+ result: o+ }+ case 'notPermitted':+ return {+ ok: false,+ error: `notPermitted (${o.reason}): ${NOT_PERMITTED_TEXT[o.reason]} ${advice}`,+ result: o+ }+ }+}++/** Outcomes whose bytes reached the pane — the only ones that consume flow budget (`noteSent`'s+ * own contract: "called after the write, not before the gate"). */+const WROTE: ReadonlySet<AgentMessageOutcome['kind']> = new Set([+ 'delivered',+ 'stalled',+ 'deliveredToReplacedTarget'+])++/**+ * One control-verb delivery, end to end: scope → switch → flow → `deliverAgentMessage` → budget →+ * rendered reply.+ */+export async function deliverFromControl(+ req: AgentMessageDeliverRequest,+ deps: AgentMessagingDeps+): Promise<{ outcome: AgentMessageOutcome; reply: AgentMessageReply }> {+ 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+ // toward, by construction: see agent-message-scope.ts). This is also where `isSafeNodeId` runs,+ // which the pair limiter's key and the tmux session namespace both depend on.+ const scope = resolveDeliveryScope(projects, req.sourceNodeId, req.targetNodeId)+ let notPermitted = scopeRefusal(scope)+ const projectId = scope.kind === 'same-project' ? scope.projectId : undefined+ 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.+ let retryAfterMs: number | undefined+ if (!notPermitted) {+ const flow = checkFlowLimits(req.sourceNodeId, req.targetNodeId, now())+ if (!flow.ok) retryAfterMs = flow.outcome.retryAfterMs+ }++ const owner = projects.find((p) => p.id === projectId)+ const sourceNode = owner?.nodes.find((n) => n.id === req.sourceNodeId)+ const targetNode = owner?.nodes.find((n) => n.id === req.targetNodeId)+ // The spawn-time default (`options.agentId ?? 'claude'`), mirrored: a plain terminal node got+ // the claude hook env at spawn, so its pane is judged against claude's binaries — and a bare+ // shell in it still refuses as `targetNotAgentPane`.+ const targetAgentId = targetNode?.agentId ?? 'claude'++ const delivery: DeliveryDeps = {+ paneOwner: (id) => deps.paneOwner(id),+ // #210 retired the `#{bracket_paste_flag}` probe with a "do not reintroduce" note+ // (pty-manager.ts): pre-3.7 tmux cannot distinguish "the app did not ask" from "I cannot+ // ask". So the dep answers true and the gate never refuses on it. What keeps herdr :260+ // closed instead: gate 1 + gate 2 admit only a VERIFIED-idle supported agent CLI in the+ // pane's foreground, and `agent-message.realtty.test.ts` proves the framed transport lands+ // the envelope as one block against a real paste-aware reader.+ // TODO(pr7): a supported agent CLI idling WITHOUT bracketed paste on is asserted by no test —+ // if one exists, its deliveries splice line-by-line and only the receipt/trace make it+ // visible. Measure per CLI before relying on this any further.+ bracketPasteRequested: async () => true,+ sendFramed: (id, payload) => deps.sendFramedPayload(id, payload),+ mirrorEntry: (id) => (deps.mirrorEntry ?? coreMirrorEntry)(id),+ tokenFilePresent: (id) => nodeTokenFilePresent(id),+ lock: (id, fn) => withNodeLock(id, fn),+ now,+ trace: (input) =>+ recordDelivery(input, {+ appendBoardLog: (entry) =>+ projectId ? deps.appendBoardLog(projectId, entry) : Promise.resolve(false),+ now+ }),+ 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,+ 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)+}++/** 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+ return (+ !!r &&+ typeof r === 'object' &&+ AGENT_MESSAGE_VERBS.has(r.verb) &&+ typeof r.sourceNodeId === 'string' &&+ typeof r.targetNodeId === 'string' &&+ typeof r.body === 'string'+ )+}diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.tsindex 60f51e3eb..c91b48ca8 100644--- a/src/main/canvas-control-core.test.ts+++ b/src/main/canvas-control-core.test.ts@@ -236,22 +236,27 @@ describe('the strict identity bucket is pre-positioned, not live', () => {})/**- * The same pre-positioning, for messaging. `needsLiveCanvas` already declares `send`/`reply` as- * store-answered so that a delivery can never travel the camera — a routing decision made once,- * ahead of the dispatch that will consume it.- *- * This test is what stops "it ships inert" from becoming a false claim: it FAILS on the day the- * verbs land, which is exactly when the PR body has to stop saying nothing changes for anyone —- * and when Canvas's store-answered branch, which today only knows how to answer `list`, has to- * learn to deliver instead of replying with a node listing.+ * The messaging verbs are LIVE as of PR 5. The tripwire that used to sit here ("refused by the+ * parser, so nothing routes them today") did its one job — it failed on the day the verbs landed —+ * and is replaced by the positive claims: the verbs parse, a target is required, and they are+ * verified-only at the route (`messaging-verified-only.test.ts`) with the delivery itself behind+ * the per-project switch, off by default.*/-describe('the messaging verbs are declared but do not exist yet', () => {- it('send and reply are refused by the parser, so nothing routes them today', () => {+describe('the messaging verbs parse', () => {+ it('send and reply accept a target and require one', () => {expect(parseControlRequest('send', { node: 'n-1', text: 'hi' })).toEqual({- error: 'Unknown verb: send'+ verb: 'send',+ args: { node: 'n-1', text: 'hi' }})expect(parseControlRequest('reply', { node: 'n-1', text: 'hi' })).toEqual({- error: 'Unknown verb: reply'+ verb: 'reply',+ args: { node: 'n-1', text: 'hi' }+ })+ expect(parseControlRequest('send', { text: 'hi' })).toEqual({+ error: 'send requires --node <id>'+ })+ expect(parseControlRequest('reply', { text: 'hi' })).toEqual({+ error: 'reply requires --node <id>'})})})diff --git a/src/main/canvas-control-core.ts b/src/main/canvas-control-core.tsindex 1ac4b4375..ff5669b8e 100644--- a/src/main/canvas-control-core.ts+++ b/src/main/canvas-control-core.ts@@ -28,6 +28,8 @@ export type ControlVerb =| 'close'| 'board'| 'assign'+ | 'send'+ | 'reply'export interface ControlCommand {verb: ControlVerb@@ -58,7 +60,9 @@ const VERBS: ControlVerb[] = ['write','close','board',- 'assign'+ 'assign',+ 'send',+ 'reply']/**@@ -111,6 +115,7 @@ export function parseControlRequest(if (v === 'branch' && !args.node) return { error: 'branch requires --node <id>' }if (v === 'rename' && !args.node) return { error: 'rename requires --node <id>' }if (v === 'rename' && !args.title) return { error: 'rename requires --title' }+ if ((v === 'send' || v === 'reply') && !args.node) return { error: `${v} requires --node <id>` }return { verb: v, args }}diff --git a/src/main/index.ts b/src/main/index.tsindex 6c62f43d8..d775d1e79 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -14,7 +14,8 @@ import {type BrowserGuest,type BrowserSurfaceKind} from './browser-guest-registry'-import { registerBoardLogHandlers, type BoardLogRoute } from '../core/board-log-handlers'+import { appendBoardLogVia, registerBoardLogHandlers, type BoardLogRoute } from '../core/board-log-handlers'+import { deliverFromControl, isDeliverRequest, onMessagingAgentEvent } from './agent-messaging'import type { RemoteLogExec } from '../core/board-log'import { boardLogRemotePath } from '../core/board-log'import { PtyManager } from '../core/pty-manager'@@ -875,7 +876,9 @@ app.whenReady().then(async () => {// a desktop router that adds SSH routing on top of the local-cwd/unsupported the server also does.// A connected SSH project (refForProject → a ref with a remoteCwd) reads/writes/fingerprints over// its ControlMaster; anything else falls to the local folder cwd, then unsupported.- registerBoardLogHandlers(corePlatform, {+ // Extracted so the agent-messaging delivery trace can append THROUGH the same router the IPC+ // handler uses (appendBoardLogVia) instead of restating the local/remote/unsupported decision.+ const boardLogRouter = {route: (projectId: string): BoardLogRoute => {const ref = sshProjectManager?.refForProject(projectId)if (ref?.remoteCwd) {@@ -903,6 +906,31 @@ app.whenReady().then(async () => {if (cwd) return { kind: 'local', cwd }return { kind: 'unsupported' }}+ }+ registerBoardLogHandlers(corePlatform, boardLogRouter)++ // 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.+ 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 itself (Project/ProjectFileV1 `agentMessaging`, validated `=== true`+ // against a hostile project.json, plus the Settings row) is PR 6 — until it lands, nothing+ // can turn messaging on, and every delivery answers `notPermitted (switch-off)`. PR 6+ // replaces this closure with the validated read; it must not weaken the `=== true` rule.+ messagingEnabled: () => false,+ customAgents: () => settingsStore.get().customAgents,+ appendBoardLog: (projectId, entry) => appendBoardLogVia(boardLogRouter, projectId, entry)+ })+ return reply})ipcMain.handle(IPC.dialogSelectFolder, async () => {@@ -1581,6 +1609,9 @@ app.whenReady().then(async () => {sendToMain(IPC.agentStatus, enriched)// Feed the macOS Notch HUD its prompt (ev.task on newTurn) + subagent grouping (no-op off/non-darwin).notchHudOnAgentEvent(enriched)+ // Agent messaging taps the SAME stream: the sender's newTurn resets its fan-out budget, and+ // an open delivery receipt watch is satisfied by the target's verified advance.+ onMessagingAgentEvent(enriched)}hookServer.setListener(emitAgentStatus)// Deterministic hook-reply approvals (docs/hook-reply-approvals.md): the canvas Approve/Denydiff --git a/src/preload/index.ts b/src/preload/index.tsindex 941e8c83d..ffafcd04e 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -610,7 +610,10 @@ const api: NodeTerminalApi = {ipcRenderer.on(IPC.agentControl, handler)return () => ipcRenderer.removeListener(IPC.agentControl, handler)},- sendAgentControlResult: (payload) => ipcRenderer.send(IPC.agentControlResult, payload)+ sendAgentControlResult: (payload) => ipcRenderer.send(IPC.agentControlResult, payload),+ agentMessage: {+ deliver: (req) => ipcRenderer.invoke(IPC.agentMessageDeliver, req)+ }}contextBridge.exposeInMainWorld('nodeTerminal', api)diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.tsindex d93e26b5e..03f9716e4 100644--- a/src/renderer/bridge/relay-api.ts+++ b/src/renderer/bridge/relay-api.ts@@ -148,7 +148,10 @@ export function buildRelayApi(connectionId: string, transport?: FrameTransport):// Agent canvas-control (`agent:control`) is not wired over the relay (matches the Server// Edition); inert no-ops rather than a local subscription that never carries the host's events.onAgentControl: stub.onAgentControl,- sendAgentControlResult: stub.sendAgentControlResult+ sendAgentControlResult: stub.sendAgentControlResult,+ // Messaging rides the same decision: the browser client is never a sender (constraint 5 of+ // the messaging plan — the phone drives canvas control over relay→IPC, not /control/*).+ agentMessage: stub.agentMessage} satisfies NodeTerminalApireturn {diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 7ab8bb1af..e267d0db6 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -378,7 +378,16 @@ export function buildStubApi(): Omit<error: 'Raising the terminal limit must be done on the machine running the server.'}),onAgentControl: noopUnsub,- sendAgentControlResult: noop+ sendAgentControlResult: noop,+ // Messaging never runs in the browser: `onAgentControl` above is inert here, so no dispatch+ // can ever reach this. It answers the honest terminal refusal all the same, so a stray call+ // can never look like it delivered.+ agentMessage: {+ deliver: async () => ({+ ok: false as const,+ error: 'Agent messaging is only available in the desktop app. Do not retry.'+ })+ }} satisfies Omit<NodeTerminalApi,| 'pty'diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex dd11df5d3..40456646d 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -5999,6 +5999,68 @@ export function Canvas() {const reply = (r: { ok: boolean; message?: string; result?: unknown; error?: string }) =>api.sendAgentControlResult({ requestId, ...r })+ // ── Agent messaging (`send`/`reply`) — handled BEFORE the source-routing machinery ──────+ // These are STORE_ANSWERED_VERBS (lib/controlRouting): routing by source must never travel+ // to the sender's project (G5 — an off-canvas orchestrator would otherwise yank the human's+ // view on every message and clear an unread badge via `setActive` on the way), and the+ // delivery goes to a tmux PANE, not to a canvas, so no live canvas is needed at either end.+ // The renderer's whole job here: validate the arguments, check the SOURCE is a+ // control-capable agent, and forward to main — where the scope check, the per-project+ // switch, flow control and the pane probes all run against main's own stores+ // (src/main/agent-messaging.ts).+ if (verb === 'send' || verb === 'reply') {+ const targetId = (args.node ?? '').trim()+ if (!targetId) {+ reply({ ok: false, error: `${verb} requires --node` })+ return+ }+ if (!args.text) {+ reply({ ok: false, error: `${verb} requires --text` })+ return+ }+ const live = nodesRef.current.find((n) => n.id === sourceNodeId)+ const stored = useProjects+ .getState()+ .projects.flatMap((p) => p.nodes)+ .find((n) => n.id === sourceNodeId)+ if (!live && !stored) {+ reply({ ok: false, error: 'source node is not in any open project' })+ return+ }+ const srcAgent = (live?.data.agentId ?? stored?.agentId) as string | undefined+ if (!sourceIsControlCapable(srcAgent)) {+ reply({ ok: false, error: 'source node is not a control-capable agent' })+ return+ }+ // The SAME per-node lock every renderer-driven run that types into the target pane takes+ // (restart, hibernate-exit, wake-resume, the confirmed `write`). Main serialises+ // deliveries against each other; this lock serialises them against those runs — a+ // delivery must never land inside a wake's un-submitted resume line.+ let delivered: { ok: boolean; message?: string; result?: unknown; error?: string } | null =+ null+ const outcome = await guardConcurrentRestart(targetId, async () => {+ delivered = await api.agentMessage.deliver({+ verb,+ sourceNodeId,+ targetNodeId: targetId,+ body: args.text ?? ''+ })+ return 'done' as const+ })()+ if (outcome === 'not-eligible') {+ // The guard's own word for "that node is mid-restart/mid-wake": a retryable refusal in+ // the same dialect main renders, so the caller learns the same way in both cases.+ reply({+ ok: false,+ error:+ 'targetBusy: the target is mid-restart or mid-wake. Retryable — wait, then try once more.'+ })+ return+ }+ reply(delivered ?? { ok: false, error: 'delivery produced no reply' })+ return+ }+// Which canvas answers? React Flow holds only the ACTIVE project's nodes, but every OTHER// project's tmux sessions keep running and are re-adopted on the next app start — so after a// restart the agents of every project the app did NOT come up on were answered by a canvasdiff --git a/src/renderer/lib/controlRouting.ts b/src/renderer/lib/controlRouting.tsindex 08718de41..680279caf 100644--- a/src/renderer/lib/controlRouting.ts+++ b/src/renderer/lib/controlRouting.ts@@ -84,10 +84,10 @@ export function routeControlSource(* comes from `resolveDeliveryScope` (`src/core/agents/agent-message-scope.ts`) taking the* serialized store and having no live-node parameter at all, so there is nothing to travel toward.*- * INERT AS OF THIS COMMIT: neither verb is in `ControlVerb` yet, so `parseControlRequest` refuses- * both before any of this is reached (asserted by running it, in `canvas-control-core.test.ts`).- * The declaration lands first so the routing decision is made once, here, rather than inside the- * dispatch that Task 5.1 adds.+ * LIVE AS OF PR 5: Canvas.tsx's dispatch handles `send`/`reply` BEFORE its source-routing+ * machinery, so neither `routeControlSource` nor any travel runs for them — the declaration here+ * and that early-exit are the same decision stated once each, and `controlRouting.test.ts` pins+ * this half.*/const STORE_ANSWERED_VERBS: ReadonlySet<string> = new Set(['list', 'send', 'reply'])diff --git a/src/shared/agents/agent-messaging.ts b/src/shared/agents/agent-messaging.tsnew file mode 100644index 000000000..55d4c8d9d--- /dev/null+++ b/src/shared/agents/agent-messaging.ts@@ -0,0 +1,35 @@+/**+ * The agent-messaging verbs' wire shapes — shared because three projects touch them: the renderer+ * dispatch (Canvas.tsx forwards a control verb to main), the preload bridge, and the main-side+ * delivery service. Everything with behaviour stays in `src/core/agents/agent-message*`; this file+ * is deliberately types + one constant.+ */++export type AgentMessageVerb = 'send' | 'reply'++export const AGENT_MESSAGE_VERBS: ReadonlySet<string> = new Set([+ 'send',+ 'reply'+] satisfies AgentMessageVerb[])++/** What the renderer forwards to main for one delivery. Deliberately minimal: the source TITLE,+ * the target's agent id, remoteness, the scope verdict and the switch state are all resolved in+ * MAIN from its own stores, so nothing that ends up inside the envelope or inside an+ * authorization decision is renderer-supplied beyond the two node ids and the body. */+export interface AgentMessageDeliverRequest {+ verb: AgentMessageVerb+ sourceNodeId: string+ targetNodeId: string+ /** The sender's text. */+ body: string+}++/** The rendered control reply for one delivery — the exact shape every other control verb answers+ * with, so the hook server and the shim need no messaging-specific branch. */+export interface AgentMessageReply {+ ok: boolean+ message?: string+ error?: string+ /** The typed outcome (an `AgentMessageOutcome` from `src/core`), for JSON clients. */+ result?: unknown+}diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 98fa4cb10..2bdc80255 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -94,6 +94,7 @@ export const IPC = {hudDismiss: 'hud:dismiss',agentControl: 'agent:control',agentControlResult: 'agent:control-result',+ agentMessageDeliver: 'agent:message-deliver',/** Canvas sync: a client casts its local node mutations here; the core reflector* (src/core/canvas-sync.ts) stamps each with the total order (`seq`) and sends it back out on the* SAME channel to EVERY attached client — the sender included, whose copy is its ack (seediff --git a/src/shared/types.ts b/src/shared/types.tsindex c1ae09023..7ae632a53 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -3,6 +3,7 @@import type { CloneProgress } from './clone-url'import type { NormalizedAgentEvent } from './agents/normalize'import type { AgentId, AgentPermissionMode, PromptInjectionMode } from './agents/config'+import type { AgentMessageDeliverRequest, AgentMessageReply } from './agents/agent-messaging'import type { GroupWorktree } from './worktree'import type { ClientId, DinoSnapshot, PeerDiff, PeerIdentity, PeerState } from './presence'import type { WhisperModelInfo } from './speech'@@ -2304,4 +2305,10 @@ export interface NodeTerminalApi {result?: unknownerror?: string}): void+ /** Agent messaging (the `send`/`reply` control verbs): run one delivery in main, where the+ * scope check, the per-project switch, flow control and the pane probes all live. The reply is+ * already rendered as a control reply — Canvas forwards it verbatim. */+ agentMessage: {+ deliver(req: AgentMessageDeliverRequest): Promise<AgentMessageReply>+ }}