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(windows): harden agent messaging backends
Fabricio Casalie5b2e1a641b9
diff --git a/docs/windows-session-host.md b/docs/windows-session-host.mdindex 3ebb82400..1f3fac764 100644--- a/docs/windows-session-host.md+++ b/docs/windows-session-host.md@@ -475,6 +475,63 @@ you chose and why") rather than an oversight.## Automated verification+### Direct ConPTY agent messages (separate from the persistent host)++The desktop can also hold a **non-persistent native PTY**, indexed by canvas node id but+without `Session.persistKey`. Checking only persisted sessions incorrectly returned `targetGone`+for such a running OpenCode. `hasLiveSession` now uses the common runtime lookup.++`core/native-windows-pane.ts` implements message delivery for those direct PTYs. It uses a+headless terminal for observed bracketed-paste mode and capture, and reads native executable+identity through console membership and an unambiguous shell-child chain. Process birth times+and a generation id detect replacement/PID reuse. It deliberately does not choose an arbitrary+deepest descendant, interpret prompt text as an executable, or accept a detached console.+This Windows ownership evidence is not POSIX foreground-group semantics; ambiguous console+trees and interpreter-only wrappers refuse. Existing project consent, verified idle hooks,+delivery locks, post-write verification and receipt tracking remain in force.++The persistent host has a separate, additive messaging extension (`messageOwnerV1`,+`messagePasteReadyV1`, `messageEnvelopeV1`). `session-host/message-pane.ts` observes the OS console+under the **host's** session generation and reads the host's existing emulator after its output+barrier. Before sending, it repeats the identity probe, checks paste mode again, and confirms+that the same session object is still registered after every await. The resulting write is one+sanitized multiline bracketed paste plus Enter. Main still owns the project/consent/hook/binary+and receipt gates. The direct adapter is never used for host-backed sessions.++The extension is independently versioned so the existing terminal protocol v1/v2 is unchanged.+Old live hosts reject the new command names, and the client returns null/false without falling+back to `write`, `sendKeys`, or a local tmux. **Installing a new app does not upgrade an already+running host.** It must retire after its existing sessions have ended, at a user-coordinated time;+the next host starts from the new bundle. Never terminate a user's live host as an upgrade step.+There is no hot migration of an existing ConPTY generation to another host.++`scripts/smoke-session-host-messaging.ts` exercises a separate real Windows host over its named+pipe, using a native fake reader (no model/API call): OS identity, probe latency within the 2 s+budget, exact multiline framing, stale-generation refusal, and retirement of the isolated fixture.+This proves the transport extension, not message/reply delivery between actual OpenCode agents.++Installed-device acceptance (2026-09-13, local build `0.3.5-windows-messaging.2`): after each+resumed OpenCode posted a fresh verified status, the coordinator's native messages reached both+architect and coder; their `NT2-ARQ-OK` / `NT2-CODER-OK` replies arrived as native message+envelopes in the coordinator transcript. Board-log traces confirmed delivery in both directions,+including queued replies delivered after the coordinator became idle. These resumed sessions+were **direct Windows PTYs** (their shell processes were children of the desktop main process);+the old persistent host was no longer running. This acceptance therefore proves the installed+message workflow on that backend, while the persistent extension remains covered by the separate+real-host fixture above, not by a claim that these OpenCodes ran inside it.++Desktop message dispatch also waits for pending canvas publication before asking main to authorize+the pair. Without it, a newly opened node can appear in `list` and context links but be absent+from main's persisted project snapshot, whose scope resolver labels it `cross-project`. A file+conflict blocks that publication; it is never silently answered as Keep mine. Server control+already persists its creations; mobile is not a sender of these agent messages.++`scripts/smoke-windows-agent-messaging.ts` tests a real isolated ConPTY with a native reader:+console identity, one multiline bracketed paste, and refusal after disposal. It makes no LLM+call. The installed-app message/reply check with actual OpenCode agents is a separate acceptance.+OpenCode transcript export on Windows now resolves the npm shim through PowerShell; session+identifiers are validated before entering the command, and export has a time/size bound.+The focused suites exercise behaviour rather than scan implementation source:- the Windows profile resolver covers detection precedence, standard Git Bash locations, customdiff --git a/scripts/smoke-session-host-messaging.ts b/scripts/smoke-session-host-messaging.tsnew file mode 100644index 000000000..1b08c90f9--- /dev/null+++ b/scripts/smoke-session-host-messaging.ts@@ -0,0 +1,70 @@+// Bundle to out/session-host-message-smoke.cjs, externalizing node-pty, and run with+// ELECTRON_RUN_AS_NODE=1 Electron. NODETERM_SMOKE_NODE_EXE points at node.exe.+// An isolated host + native fake CLI exercise the actual named-pipe protocol. No model call.+import fs from 'fs'+import os from 'os'+import path from 'path'+import assert from 'assert/strict'+import { SessionHostClient } from '../src/core/session-host-client'+import { isAgentPane } from '../src/shared/agents/pane-owner-predicate'++async function main(): Promise<void> {+ assert.equal(process.platform, 'win32')+ const nodeExe = process.env.NODETERM_SMOKE_NODE_EXE+ assert.ok(nodeExe && fs.existsSync(nodeExe))+ const tempRoot = path.join(os.tmpdir(), 'opencode')+ assert.ok(fs.existsSync(tempRoot), 'the approved temporary directory must exist')+ const dir = fs.mkdtempSync(path.join(tempRoot, 'nodeterm-host-message-'))+ const exe = path.join(dir, 'opencode.exe')+ fs.copyFileSync(nodeExe, exe)+ const quote = (s: string) => "'" + s.replace(/'/g, "''") + "'"+ const reader = "process.stdin.setRawMode(true);process.stdin.resume();process.stdout.write('\\x1b[?2004hREADY_HOST');let b='';process.stdin.on('data',d=>{b+=d;if(b.endsWith('\\r')){process.stdout.write('HOST_RECEIVED:'+Buffer.from(b).toString('base64')+';');b='';}})"+ const client = new SessionHostClient({ userDataDir: dir, repoRoot: process.cwd() })+ const env = Object.fromEntries(Object.entries(process.env).filter(([k, v]) =>+ v !== undefined && !k.startsWith('NODETERM_') && k !== 'ELECTRON_RUN_AS_NODE')) as Record<string, string>+ let output = ''+ const name = 'nt-isolated-message-smoke'+ const wait = async (predicate: () => boolean, timeout = 15_000) => {+ const until = Date.now() + timeout+ while (!predicate()) {+ if (Date.now() > until) throw new Error('isolated host fixture timed out')+ await new Promise((resolve) => setTimeout(resolve, 50))+ }+ }+ let probeMs = 0+ try {+ await client.attach(name, {+ shell: 'powershell.exe', args: ['-NoLogo', '-NoProfile', '-NoExit', '-Command', `& ${quote(exe)} -e ${quote(reader)}`],+ cwd: dir, env, cols: 120, rows: 30+ }, 200, { onData: (data) => { output += data }, onExit: () => {} })+ await wait(() => output.includes('READY_HOST'))+ const start = Date.now()+ const owner = await client.messageOwner(name)+ probeMs = Date.now() - start+ assert.equal(isAgentPane(owner, 'opencode'), 'agent')+ assert.ok(probeMs < 2000, `OS probe exceeds the delivery budget: ${probeMs}ms`)+ assert.equal(await client.messagePasteReady(name), true)+ const envelope = 'HOST_PING\nsecond line'+ assert.equal(await client.messageEnvelope(name, envelope, owner!), true)+ await wait(() => /HOST_RECEIVED:[A-Za-z0-9+/=]+;/.test(output))+ const received = output.match(/HOST_RECEIVED:([A-Za-z0-9+/=]+);/)![1]+ assert.equal(Buffer.from(received, 'base64').toString(), `\x1b[200~${envelope}\x1b[201~\r`)+ assert.equal(await client.messageEnvelope(name, 'must not arrive', { ...owner!, paneId: 'wrong-generation' }), false)+ } finally {+ await client.killSession(name)+ // Only the private fixture is retired. The real user's host is never contacted.+ await wait(() => !fs.existsSync(path.join(dir, 'session-host.json')), 40_000)+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })+ }+ console.log(JSON.stringify({ namedPipe: 'passed', consoleIdentity: 'passed', probeMs,+ multilinePaste: 'passed', staleGenerationRefusal: 'passed', cleanup: 'passed' }))+}++// The client intentionally unrefs its transport; Electron normally owns the event loop. Keep+// this standalone runner alive until assertions and the private host's retirement finish.+const keepAlive = setInterval(() => {}, 1000)+void main().then(() => { clearInterval(keepAlive); process.exit(0) }, (error) => {+ clearInterval(keepAlive)+ console.error(error)+ process.exit(1)+})diff --git a/scripts/smoke-windows-agent-messaging.ts b/scripts/smoke-windows-agent-messaging.tsnew file mode 100644index 000000000..827d78d8d--- /dev/null+++ b/scripts/smoke-windows-agent-messaging.ts@@ -0,0 +1,62 @@+// Run with Electron's Node ABI after bundling (node-pty is Electron-built):+// esbuild scripts/smoke-windows-agent-messaging.ts --bundle --platform=node --format=cjs+// --external:node-pty --outfile=out/native-messaging-smoke.cjs+// ELECTRON_RUN_AS_NODE=1 electron out/native-messaging-smoke.cjs+// NODETERM_SMOKE_NODE_EXE must name a real node.exe; no model/API call is made.+import fs from 'fs'+import os from 'os'+import path from 'path'+import assert from 'assert/strict'+import * as pty from 'node-pty'+import { NativeWindowsPane } from '../src/core/native-windows-pane'+import { isAgentPane } from '../src/shared/agents/pane-owner-predicate'++async function main(): Promise<void> {+ assert.equal(process.platform, 'win32', 'this smoke test needs a real Windows console')+ const nodeExe = process.env.NODETERM_SMOKE_NODE_EXE+ assert.ok(nodeExe && fs.existsSync(nodeExe), 'set NODETERM_SMOKE_NODE_EXE to node.exe')+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-native-message-'))+ // A native reader named opencode, like the fake CLI used by the real tmux tests. The+ // assertion is actual ConPTY input framing/identity, not a claim of an LLM response.+ const readerExe = path.join(dir, 'opencode.exe')+ fs.copyFileSync(nodeExe, readerExe)+ const reader = "process.stdin.setRawMode(true); process.stdin.resume(); process.stdout.write('\\x1b[?2004hREADY_NATIVE'); let b=''; process.stdin.on('data',d=>{b+=d.toString(); if(b.endsWith('\\r')) {process.stdout.write('RECEIVED_NATIVE:'+Buffer.from(b).toString('base64')+';'); b='';}});"+ const quote = (text: string) => "'" + text.replace(/'/g, "''") + "'"+ const proc = pty.spawn('powershell.exe', ['-NoLogo', '-NoProfile', '-NoExit', '-Command', `& ${quote(readerExe)} -e ${quote(reader)}`], {+ cwd: dir, env: process.env as Record<string, string>, cols: 120, rows: 30, name: 'xterm-256color'+ })+ const pane = new NativeWindowsPane(proc, { cols: 120, rows: 30, scrollback: 200 })+ const exited = new Promise<void>((resolve) => proc.onExit(() => resolve()))+ let output = ''+ proc.onData((data) => { output += data; pane.recordOutput(data) })+ const waitFor = async (test: () => boolean) => {+ const deadline = Date.now() + 15_000+ while (!test()) {+ if (Date.now() > deadline) throw new Error('native reader timed out')+ await new Promise((resolve) => setTimeout(resolve, 50))+ }+ }+ try {+ await waitFor(() => output.includes('READY_NATIVE'))+ const owner = await pane.owner()+ assert.equal(isAgentPane(owner, 'opencode'), 'agent')+ assert.equal(await pane.pasteAware(), true)+ const body = 'NT_PING_WINDOWS\nsecond line'+ assert.equal(await pane.sendEnvelope(body, owner!), true)+ await waitFor(() => /RECEIVED_NATIVE:[A-Za-z0-9+/=]+;/.test(output))+ const encoded = output.match(/RECEIVED_NATIVE:([A-Za-z0-9+/=]+);/)![1]+ assert.equal(Buffer.from(encoded, 'base64').toString(), `\x1b[200~${body}\x1b[201~\r`)+ pane.dispose()+ assert.equal(await pane.sendEnvelope('must not be sent', owner!), false)+ } finally {+ pane.dispose()+ // Let node-pty close its own ConPTY while the console still exists. Killing the root+ // first makes node-pty's asynchronous console-list cleanup fail on AttachConsole.+ proc.kill()+ await Promise.race([exited, new Promise<never>((_, reject) => setTimeout(() => reject(new Error('fixture did not exit')), 8000))])+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })+ }+ console.log(JSON.stringify({ consoleIdentity: 'passed', multilinePaste: 'passed', disposedRefusal: 'passed', cleanup: 'passed' }))+}++void main().then(() => process.exit(0), (error) => { console.error(error); process.exit(1) })diff --git a/src/core/agents/agent-message.ts b/src/core/agents/agent-message.tsindex c247cc700..b8c616962 100644--- a/src/core/agents/agent-message.ts+++ b/src/core/agents/agent-message.ts@@ -122,7 +122,7 @@ export interface DeliveryDeps {* 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>+ sendEnvelope(nodeId: string, envelope: string, expected?: PaneOwner): Promise<boolean>/** The target's status mirror entry — gate 2's whole input. */mirrorEntry(nodeId: string): MirrorEntry | undefined/** `nodeTokenFilePresent(nodeId)`. */@@ -182,6 +182,12 @@ function samePane(if (isAgentPane(after, agentId, binaries) !== 'agent') return falseconst wasPid = agentPidIn(before, agentId, binaries)const nowPid = agentPidIn(after, agentId, binaries)+ if (before.processBirths) {+ const beforeIndex = before.pids?.indexOf(wasPid ?? -1) ?? -1+ const afterIndex = after.pids?.indexOf(nowPid ?? -1) ?? -1+ if (!before.processBirths[beforeIndex] ||+ before.processBirths[beforeIndex] !== after.processBirths?.[afterIndex]) return false+ }return wasPid !== null && nowPid !== null && wasPid === nowPid}@@ -441,7 +447,7 @@ export async function deliverAgentMessage(// subscription opened after that probe would miss it and report `stalled` for a message that// demonstrably landed. See `watchForReceipt`: that miss is what makes an LLM send it twice.const watch = watchForReceipt(req.targetNodeId, deps.subscribeEvents)- const wrote = await deps.sendEnvelope(req.targetNodeId, payload)+ const wrote = await deps.sendEnvelope(req.targetNodeId, payload, owner)// The pane went away between the gate and the write. Not a failure of ours and not retryable:// the node is gone. It IS traced: a `sendEnvelope` that fails after a partial write has left// bytes in somebody's pane, and that must not be the one event with no record.diff --git a/src/core/agents/agent-messaging.ts b/src/core/agents/agent-messaging.tsindex 11b358330..41bd6325e 100644--- a/src/core/agents/agent-messaging.ts+++ b/src/core/agents/agent-messaging.ts@@ -68,7 +68,8 @@ export interface MessagingStoredNode {*/export interface AgentMessagingDeps {paneOwner(nodeId: string): Promise<PaneOwner | null>- sendEnvelope(nodeId: string, envelope: string): Promise<boolean>+ sendEnvelope(nodeId: string, envelope: string, expected?: PaneOwner): Promise<boolean>+ envelopePasteReady?(nodeId: string): Promise<boolean>hasLiveSession(nodeId: string): booleanmirrorEntry?(nodeId: string): MirrorEntry | undefined/** The main-process projects store (`workspaceStore.persistedCanvases()` on the desktop). */@@ -554,8 +555,8 @@ export async function runDelivery(// 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,- sendEnvelope: (id, envelope) => deps.sendEnvelope(id, envelope),+ bracketPasteRequested: (id) => deps.envelopePasteReady?.(id) ?? Promise.resolve(true),+ sendEnvelope: (id, envelope, expected) => deps.sendEnvelope(id, envelope, expected),mirrorEntry: (id) => (deps.mirrorEntry ?? coreMirrorEntry)(id),tokenFilePresent: (id) => nodeTokenFilePresent(id),lock: (id, fn) => withNodeLock(id, fn),diff --git a/src/core/native-windows-pane.test.ts b/src/core/native-windows-pane.test.tsnew file mode 100644index 000000000..eb639710a--- /dev/null+++ b/src/core/native-windows-pane.test.ts@@ -0,0 +1,81 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { NativeWindowsPane } from './native-windows-pane'+import type { PaneOwner } from '../shared/agents/pane-owner-predicate'++const expected: PaneOwner = { panePid: 10, paneId: 'win32:generation-a:birth-root', tty: 'win32-console:10', command: 'opencode', argv: ['opencode'], pids: [20], processBirths: ['birth-agent'] }+const panes: NativeWindowsPane[] = []+function fixture() {+ const write = vi.fn()+ const probe = vi.fn(async (): Promise<PaneOwner | null> => expected)+ const pane = new NativeWindowsPane({ pid: 10, write }, { cols: 80, rows: 24, scrollback: 100 }, probe)+ panes.push(pane)+ return { pane, write, probe }+}+afterEach(() => { for (const p of panes.splice(0)) p.dispose() })++describe('native Windows envelope delivery', () => {+ it('waits for split terminal-mode output and pastes one sanitized block before Enter', async () => {+ const { pane, write } = fixture()+ pane.recordOutput('\x1b[?20')+ pane.recordOutput('04h')+ expect(await pane.sendEnvelope('line 1\nline 2\x1b[201~', expected)).toBe(true)+ expect(write.mock.calls).toEqual([['\x1b[200~line 1\nline 2[201~\x1b[201~'], ['\r']])+ })+ it('refuses before paste mode is observed, after it is disabled, and without a checked owner', async () => {+ const { pane, write } = fixture()+ expect(await pane.sendEnvelope('hello', expected)).toBe(false)+ pane.recordOutput('\x1b[?2004h')+ expect(await pane.sendEnvelope('hello')).toBe(false)+ pane.recordOutput('\x1b[?2004l')+ expect(await pane.sendEnvelope('hello', expected)).toBe(false)+ expect(write).not.toHaveBeenCalled()+ })+ it.each([+ null,+ { ...expected, paneId: 'win32:replacement' },+ { ...expected, pids: [21] },+ { ...expected, processBirths: ['new-process-same-pid'] },+ { ...expected, argv: ['pwsh'] }+ ])('refuses unknown, replaced or returned-to-shell recipients', async (changed) => {+ const { pane, write, probe } = fixture()+ pane.recordOutput('\x1b[?2004h')+ probe.mockResolvedValue(changed)+ expect(await pane.sendEnvelope('hello', expected)).toBe(false)+ expect(write).not.toHaveBeenCalled()+ })+ it('refuses an exit while the identity probe is in flight', async () => {+ const { pane, write, probe } = fixture()+ pane.recordOutput('\x1b[?2004h')+ probe.mockImplementation(async () => { pane.dispose(); return expected })+ expect(await pane.sendEnvelope('hello', expected)).toBe(false)+ expect(write).not.toHaveBeenCalled()+ })+})++describe('native Windows sendText (the write verb and the app’s own writers)', () => {+ it('frames only when the app asked for bracketed paste, then Enter', async () => {+ const { pane, write, probe } = fixture()+ pane.recordOutput('\x1b[?2004h')+ expect(await pane.sendText('a\nb\x1b[201~', true)).toBe(true)+ expect(write.mock.calls).toEqual([['\x1b[200~a\nb[201~\x1b[201~'], ['\r']])+ // No process attestation: this path types into whatever owns the pane, like tmux send-keys.+ expect(probe).not.toHaveBeenCalled()+ })+ it('writes unframed (ESC still stripped) when paste mode was not requested', async () => {+ const { pane, write } = fixture()+ expect(await pane.sendText('ls\x1b', false)).toBe(true)+ expect(write.mock.calls).toEqual([['ls']])+ })+ it('sends a bare Enter for an empty payload, and nothing at all when neither is asked', async () => {+ const { pane, write } = fixture()+ expect(await pane.sendText('', true)).toBe(true)+ expect(await pane.sendText('', false)).toBe(true)+ expect(write.mock.calls).toEqual([['\r']])+ })+ it('refuses a disposed pane', async () => {+ const { pane, write } = fixture()+ pane.dispose()+ expect(await pane.sendText('hello', true)).toBe(false)+ expect(write).not.toHaveBeenCalled()+ })+})diff --git a/src/core/native-windows-pane.ts b/src/core/native-windows-pane.tsnew file mode 100644index 000000000..97ffe6b27--- /dev/null+++ b/src/core/native-windows-pane.ts@@ -0,0 +1,94 @@+import { randomUUID } from 'crypto'+import { TerminalEmulator } from '../session-host/terminal-emulator'+import { readWindowsConsoleOwner, sameNativeProcess } from '../session-host/windows-pane-owner'+import type { PaneOwner } from '../shared/agents/pane-owner-predicate'+import { sanitizePasteText } from './paste-injection'++export { sameNativeProcess } from '../session-host/windows-pane-owner'++/** Core-owned screen and generation for a direct Windows PTY. This is neither a persisted+ * agent label nor the "deepest descendant" restart heuristic. The caller still checks+ * project consent, verified idle status, agent binary and a receipt after delivery. */+export class NativeWindowsPane {+ private readonly generation = randomUUID()+ private readonly screen: TerminalEmulator+ private tail: Promise<void> = Promise.resolve()+ private alive = true++ constructor(+ private readonly proc: { pid: number; write(data: string): void },+ size: { cols: number; rows: number; scrollback: number },+ private readonly probe = readWindowsConsoleOwner+ ) {+ this.screen = new TerminalEmulator(size)+ }++ recordOutput(data: string): void {+ if (!this.alive) return+ this.tail = this.tail.then(() => this.screen.write(data)).catch(() => { this.alive = false })+ }++ resize(cols: number, rows: number): void {+ this.tail = this.tail.then(() => { if (this.alive) this.screen.resize(cols, rows) })+ }++ async capture(full: boolean): Promise<string> {+ await this.tail+ return this.alive ? this.screen.serialize(full ? undefined : 200) : ''+ }++ async owner(): Promise<PaneOwner | null> {+ if (!this.alive) return null+ const owner = await this.probe(this.proc.pid, this.generation)+ return this.alive ? owner : null+ }++ async pasteAware(): Promise<boolean> {+ await this.tail+ return this.alive && this.screen.bracketedPasteRequested()+ }++ async sendEnvelope(envelope: string, expected?: PaneOwner): Promise<boolean> {+ if (!envelope || !expected || !(await this.pasteAware())) return false+ // Re-check the exact process immediately before typing. A replacement with the same+ // PID but a different OS birth time, or a shell returned to the console, refuses.+ if (!sameNativeProcess(expected, await this.owner()) || !(await this.pasteAware())) return false+ try {+ const text = sanitizePasteText(envelope)+ if (!text) return false+ this.proc.write(`\x1b[200~${text}\x1b[201~`)+ this.proc.write('\r')+ return true+ } catch { return false }+ }++ /**+ * `PtyManager.sendText` for a direct Windows PTY — the `paste-buffer -p` contract: framed only+ * when the app in the pane asked for bracketed paste, then Enter when requested. Unlike+ * `sendEnvelope` there is no process attestation: this is the user-confirmed `write` verb and the+ * app's own writers (rename, note push, dictation), which have always typed into whatever owns+ * the pane. Without it those callers fell through to the session-host backend, which has no+ * session for a direct PTY, and failed every time.+ */+ async sendText(text: string, enter: boolean): Promise<boolean> {+ if (!this.alive) return false+ // ESC is stripped on BOTH deliveries, as `sanitizePasteText`'s contract requires.+ const clean = sanitizePasteText(text)+ try {+ if (clean) {+ const framed = await this.pasteAware()+ if (!this.alive) return false+ this.proc.write(framed ? `\x1b[200~${clean}\x1b[201~` : clean)+ }+ if (enter) this.proc.write('\r')+ return true+ } catch {+ return false+ }+ }++ dispose(): void {+ this.alive = false+ void this.tail.finally(() => this.screen.dispose())+ }+}diff --git a/src/core/pty-manager.pane-owner.test.ts b/src/core/pty-manager.pane-owner.test.tsindex a9c6361e4..d52ce1494 100644--- a/src/core/pty-manager.pane-owner.test.ts+++ b/src/core/pty-manager.pane-owner.test.ts@@ -55,6 +55,17 @@ vi.mock('node-pty', () => ({}))const NODE = 'node-1'+const hostMessaging = vi.hoisted(() => ({+ owner: vi.fn(async () => null as unknown),+ pasteReady: vi.fn(async () => false),+ send: vi.fn(async () => false)+}))+vi.mock('./session-host-backend', async (original) => ({+ ...(await original<typeof import('./session-host-backend')>()),+ sessionHostMessageOwner: hostMessaging.owner,+ sessionHostMessagePasteReady: hostMessaging.pasteReady,+ sessionHostMessageEnvelope: hostMessaging.send+}))const TARGET = sessionName(NODE)const TTY = '/dev/pts/7'const PS_OUT = [@@ -98,6 +109,56 @@ function healthy(file: string, args: string[]): { stdout: string } {}describe('PtyManager.paneOwner', () => {+ it('routes a persistent Windows generation exclusively through the host extension', async () => {+ const mgr = await manager() as unknown as {+ sessions: Map<string, unknown>+ byPersistKey: Map<string, string>+ paneOwner(id: string): Promise<unknown>+ envelopePasteReady(id: string): Promise<boolean>+ sendEnvelope(id: string, text: string, expected?: unknown): Promise<boolean>+ }+ mgr.sessions.set('host-session', { persistKey: NODE, indexKey: NODE, sessionHost: true })+ mgr.byPersistKey.set(NODE, 'host-session')+ const expected = { panePid: 10, tty: 'win32-console:10', paneId: 'host-generation', command: 'opencode', argv: ['opencode'] }+ hostMessaging.owner.mockResolvedValueOnce(expected)+ expect(await mgr.paneOwner(NODE)).toEqual(expected)+ expect(await mgr.envelopePasteReady(NODE)).toBe(false)+ expect(await mgr.sendEnvelope(NODE, 'message', expected)).toBe(false)+ expect(hostMessaging.owner).toHaveBeenCalledWith(TARGET)+ expect(hostMessaging.pasteReady).toHaveBeenCalledWith(TARGET)+ expect(hostMessaging.send).toHaveBeenCalledWith(TARGET, 'message', expected)+ expect(calls).toHaveLength(0) // No fallback to the POSIX tmux that is also installed.+ })++ it('finds a live non-persistent Windows node by its runtime index', async () => {+ const mgr = await manager({ tmux: null }) as unknown as {+ sessions: Map<string, unknown>+ byPersistKey: Map<string, string>+ hasLiveSession(id: string): boolean+ paneOwner(id: string): Promise<unknown>+ sendEnvelope(id: string, text: string, expected?: unknown): Promise<boolean>+ captureSession(id: string): Promise<string>+ }+ const nativeOwner = { panePid: 40, paneId: 'native-generation', tty: 'win32-console:40', command: 'opencode', argv: ['opencode'], pids: [41], processBirths: ['born'] }+ const sendEnvelope = vi.fn(async () => true)+ mgr.sessions.set('plain-session', {+ indexKey: 'plain-node',+ nativeWindowsPane: {+ owner: async () => nativeOwner,+ sendEnvelope,+ capture: async () => 'native terminal output'+ }+ })+ mgr.byPersistKey.set('plain-node', 'plain-session')+ expect(mgr.hasLiveSession('plain-node')).toBe(true)+ expect(await mgr.paneOwner('plain-node')).toEqual(nativeOwner)+ expect(await mgr.captureSession('plain-node')).toBe('native terminal output')+ expect(await mgr.sendEnvelope('plain-node', 'message', nativeOwner)).toBe(true)+ expect(sendEnvelope).toHaveBeenCalledWith('message', nativeOwner)+ mgr.sessions.delete('plain-session')+ expect(mgr.hasLiveSession('plain-node')).toBe(false)+ })+beforeEach(() => {calls.length = 0ssh.path = '/usr/bin/ssh'diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 97d927ef3..6329c5798 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -134,11 +134,15 @@ import {sessionHostKillSession,sessionHostListSessions,sessionHostPaneCommand,+ sessionHostMessageOwner,+ sessionHostMessagePasteReady,+ sessionHostMessageEnvelope,sessionHostSendKeys,sessionHostSupported,SessionHostProtocolCompatibilityError} from './session-host-backend'import type { SessionHostPty } from './session-host-pty'+import { NativeWindowsPane } from './native-windows-pane'import type { ProjectSpawnOverrides, ProjectSpawnOverridesReader } from './project-spawn-overrides'// How often we snapshot a live tmux session's scrollback to disk, so a machine reboot (which@@ -609,6 +613,7 @@ function releaseSpawnSlotOnOutput(session: Session | undefined, release: SpawnSlinterface Session {proc: pty.IPty+ nativeWindowsPane?: NativeWindowsPane/** Every VIEW watching this session, keyed by the composite `(ClientId, viewerId)` (`SubKey`).* Co-attach: ONE pty and ONE tmux client, N subscribers — a second client on the same persistKey* (or the SAME client's second view, e.g. the kanban card modal) joins this set instead of@@ -3323,6 +3328,9 @@ export class PtyManager {const spawnSub = clientId === null ? null : subKey(clientId, options.viewerId ?? PRIMARY_VIEWER)const session: Session = {proc,+ nativeWindowsPane: process.platform === 'win32' && !persisted+ ? new NativeWindowsPane(proc, { ...options, scrollback: settings.tmuxScrollback })+ : undefined,subscribers: spawnSub === null ? new Set<SubKey>() : new Set<SubKey>([spawnSub]),sizes:spawnSub === null@@ -3389,6 +3397,7 @@ export class PtyManager {// rollback removes this exact generation, late callbacks must not recreate its flush timer// or leak bytes into a replacement that happens to reuse the same node id.if (this.sessions.get(sessionId) !== session) return+ session.nativeWindowsPane?.recordOutput(data)this.queueData(sessionId, session, data)})@@ -3509,6 +3518,7 @@ export class PtyManager {/** Drop a dead/released session from both indexes. Keyed off `indexKey` (not `persistKey`,* which is only set for tmux-PERSISTED sessions) so a plain-shell node is un-indexed too. */private forget(sessionId: string, session: Session): void {+ session.nativeWindowsPane?.dispose()this.sessions.delete(sessionId)if (session.indexKey && this.byPersistKey.get(session.indexKey) === sessionId)this.byPersistKey.delete(session.indexKey)@@ -3578,6 +3588,7 @@ export class PtyManager {session.appliedSize = sizetry {session.proc.resize(size.cols, size.rows)+ session.nativeWindowsPane?.resize(size.cols, size.rows)} catch {// resize can throw if the proc already exited; ignore.}@@ -3937,6 +3948,7 @@ export class PtyManager {*/async captureSession(persistKey: string, full = false): Promise<string> {const live = this.liveSessionForPersistKey(persistKey)+ if (live?.nativeWindowsPane) return live.nativeWindowsPane.capture(full)// Remote (ssh-project) node: there is no local tmux session — capture from the REMOTE tmux// over the project's ControlMaster (mirrors snapshotScrollback / destroySession).const sshRemote = live?.sshRemote@@ -4139,6 +4151,9 @@ export class PtyManager {const enter = opts?.enter ?? trueconst target = sessionName(persistKey)const live = this.liveSessionForPersistKey(persistKey)+ // A direct (non-persistent) Windows PTY has no session-host entry and no tmux: it is typed+ // into through the pane itself. Routing it to the session host below failed every time.+ if (live?.nativeWindowsPane) return live.nativeWindowsPane.sendText(text, enter)const sshRemote = live?.sshRemotetry {if (sshRemote) {@@ -4376,6 +4391,7 @@ export class PtyManager {async paneOwner(persistKey: string): Promise<PaneOwner | null> {const target = sessionName(persistKey)const live = this.liveSessionForPersistKey(persistKey)+ if (live?.nativeWindowsPane) return live.nativeWindowsPane.owner()const sshRemote = live?.sshRemotetry {if (sshRemote) {@@ -4392,9 +4408,10 @@ export class PtyManager {)return parseCombinedPaneOwner(out.stdout)}- // The session host has no tty/tmux identity surface. Do not query an unrelated POSIX tmux- // merely because one is installed beside this native Windows generation.- if (live?.sessionHost || !this.tmuxPath) return null+ // Only the owning host may attest this generation. An older live host rejects the+ // extension; that refusal must never fall through to an unrelated POSIX tmux.+ if (live?.sessionHost) return sessionHostMessageOwner(target)+ if (!this.tmuxPath) return nullconst first = await runAsync(this.tmuxPath, ['-L',TMUX_SOCKET,@@ -4447,9 +4464,14 @@ export class PtyManager {* accidental submit a messaging delivery must never perform — an empty envelope refuses here.* (`buildEnvelope` can never return '', so this is a guard against a future caller, not a path.)*/- async sendEnvelope(persistKey: string, envelope: string): Promise<boolean> {+ async sendEnvelope(persistKey: string, envelope: string, expected?: PaneOwner): Promise<boolean> {if (envelope.length === 0) return false+ const live = this.liveSessionForPersistKey(persistKey)+ if (live?.nativeWindowsPane) return live.nativeWindowsPane.sendEnvelope(envelope, expected)const target = sessionName(persistKey)+ if (live?.sessionHost) {+ return expected ? sessionHostMessageEnvelope(target, envelope, expected) : false+ }const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemotetry {if (sshRemote) {@@ -4477,7 +4499,15 @@ export class PtyManager {* only "no session is registered" may be reported as "the node is gone".*/hasLiveSession(persistKey: string): boolean {- return !!this.sessionByPersistKey(persistKey)+ return !!this.liveSessionForPersistKey(persistKey)+ }++ async envelopePasteReady(persistKey: string): Promise<boolean> {+ const live = this.liveSessionForPersistKey(persistKey)+ if (live?.nativeWindowsPane) return live.nativeWindowsPane.pasteAware()+ if (live?.sessionHost) return sessionHostMessagePasteReady(sessionName(persistKey))+ // Existing tmux path frames in paste-buffer -p.+ return !!(live?.sshRemote || this.tmuxPath)}/**diff --git a/src/core/session-host-backend.ts b/src/core/session-host-backend.tsindex 744c7da2c..4bf48ceec 100644--- a/src/core/session-host-backend.ts+++ b/src/core/session-host-backend.ts@@ -12,6 +12,21 @@ import {import { SessionHostPty } from './session-host-pty'import type { ExecuteLaunchResult, SessionHostSpawnOptions } from '../session-host/protocol'import type { PreparedAgentLaunch } from './agent-launch'+import type { PaneOwner } from '../shared/agents/pane-owner-predicate'++export async function sessionHostMessageOwner(name: string): Promise<PaneOwner | null> {+ return getClient().messageOwner(name)+}++export async function sessionHostMessagePasteReady(name: string): Promise<boolean> {+ return getClient().messagePasteReady(name)+}++export async function sessionHostMessageEnvelope(+ name: string, envelope: string, expected: PaneOwner+): Promise<boolean> {+ return getClient().messageEnvelope(name, envelope, expected)+}let client: SessionHostClient | null = nulldiff --git a/src/core/session-host-client.test.ts b/src/core/session-host-client.test.tsindex a0da43bad..f308b9818 100644--- a/src/core/session-host-client.test.ts+++ b/src/core/session-host-client.test.ts@@ -196,6 +196,27 @@ afterEach(async () => {})describe('SessionHostClient handshake transition', () => {+ it('keeps an old live host usable when it refuses the additive messaging extension', async () => {+ const { userDataDir, paths } = createUserData('old-host-message-refusal')+ const commands: string[] = []+ await serve(paths.endpoint, (request, socket) => {+ commands.push(request.cmd)+ if (request.cmd === 'hello') socket.write(acceptedHello(request.id))+ else if (request.cmd === 'hasSession') {+ socket.write(encodeFrame({ id: request.id, ok: true, result: { exists: true, generation: 'kept-generation' } }))+ } else socket.write(encodeFrame({ id: request.id, ok: false, error: 'unknown command' }))+ })+ const client = new SessionHostClient({ userDataDir, repoRoot: userDataDir })+ expect(await within(client.messageOwner('nt-existing'))).toBeNull()+ expect(await within(client.messagePasteReady('nt-existing'))).toBe(false)+ expect(await within(client.messageEnvelope('nt-existing', 'message', {+ panePid: 42, tty: 'win32-console:42', command: 'opencode', argv: ['opencode']+ }))).toBe(false)+ expect(await within(client.hasSession('nt-existing'))).toBe(true)+ expect(commands).toEqual(['hello', 'messageOwnerV1', 'messagePasteReadyV1', 'messageEnvelopeV1', 'hasSession'])+ // No fallback to sendKeys/write/executeLaunch, no kill, no replacement/attach request.+ })+it('hands the socket to the production listener before the first attach response and data', async () => {const { userDataDir, paths, token } = createUserData('test-token-kept-off-argv')diff --git a/src/core/session-host-client.ts b/src/core/session-host-client.tsindex f2eb61706..fe5c6f956 100644--- a/src/core/session-host-client.ts+++ b/src/core/session-host-client.ts@@ -3,6 +3,7 @@// ordinary traffic through a replacement connection.import net from 'net'+import type { PaneOwner } from '../shared/agents/pane-owner-predicate'import { randomUUID } from 'crypto'// The REAL scheduler, immune to vi.useFakeTimers (which patches the global, not this module's// exports): requestOnSocket defers each frame's write by one genuine event-loop turn so queued@@ -1425,6 +1426,24 @@ export class SessionHostClient {}}+ async messageOwner(name: string): Promise<PaneOwner | null> {+ try {+ return await this.request<PaneOwner | null>({ cmd: 'messageOwnerV1', name })+ } catch { return null } // Older live hosts refuse; never replace them or use name-only input.+ }++ async messagePasteReady(name: string): Promise<boolean> {+ try {+ return await this.request<boolean>({ cmd: 'messagePasteReadyV1', name }) === true+ } catch { return false }+ }++ async messageEnvelope(name: string, envelope: string, expected: PaneOwner): Promise<boolean> {+ try {+ return await this.request<boolean>({ cmd: 'messageEnvelopeV1', name, envelope, expected }) === true+ } catch { return false }+ }+async capture(name: string, full: boolean): Promise<string> {const result = await this.request<CaptureResult>({ cmd: 'capture', name, full })return result.textdiff --git a/src/main/index.ts b/src/main/index.tsindex 05d422eed..71880654e 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1794,7 +1794,8 @@ app.whenReady().then(async () => {// src/core/agents/agent-messaging.ts for the whole map.const messagingDeps: AgentMessagingDeps = {paneOwner: (id) => ptyManager.paneOwner(id),- sendEnvelope: (id, envelope) => ptyManager.sendEnvelope(id, envelope),+ sendEnvelope: (id, envelope, expected) => ptyManager.sendEnvelope(id, envelope, expected),+ envelopePasteReady: (id) => ptyManager.envelopePasteReady(id),hasLiveSession: (id) => ptyManager.hasLiveSession(id),projects: () => workspaceStore.persistedCanvases(),isRemoteNode: (id) => !!ptyManager.sshRemoteForNode(id),diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 9cbed6b7a..93d5ed408 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -157,6 +157,7 @@ import {type SaveDelivery} from '../lib/savePersistence'import { SaveFailureBar } from '../components/SaveFailureBar'+import { syncMessageScope } from '../lib/messageScopeSync'import {adoptedNodesNotice,decideExternalChange,@@ -2756,22 +2757,23 @@ export function Canvas() {// backoff delay) and let the strip say so. Never clear `dirty` — nothing reached disk.console.warn('[canvas] workspace save failed', err)setSaveDelivery((prev) => nextSaveDelivery(prev, Date.now()))- return+ return false}setSaveDelivery(undefined)if (canClearDirty(gen, dirtyGenRef.current)) {setDirty(false)- return+ return true}// An edit raced the save: leave `dirty` set so nothing believes the canvas is on disk. But the// debounce effect only re-arms when one of its deps changes, and `dirty` never went false —// nudge it explicitly, or the racing edit would wait for an unrelated later edit to be saved.setResaveTick((v) => v + 1)+ return true}, [])const persist = useCallback(async () => {commitActiveToStore()- await writeDisk()+ return await writeDisk()}, [commitActiveToStore, writeDisk])// Global kanban reads ALL lanes from serialized `p.nodes`, but the active project's@@ -2815,6 +2817,8 @@ export function Canvas() {// Mirror `dirty` into a ref so the external-change listener (mounted once) reads the// live value without re-subscribing on every edit.const dirtyRef = useRef(false)+ const conflictRef = useRef(conflict)+ conflictRef.current = conflictuseEffect(() => {dirtyRef.current = dirty}, [dirty])@@ -9555,6 +9559,20 @@ export function Canvas() {let delivered: { ok: boolean; message?: string; result?: unknown; error?: string } | null =nullconst outcome = await guardConcurrentRestart(targetId, async () => {+ // Main authorizes against its persisted store, whereas open-agent/list can already see+ // unsaved live nodes. Publish before crossing that boundary, without travelling or+ // choosing "Keep mine" on an unresolved conflict. Main's security gates remain intact.+ const scopeSync = await syncMessageScope({+ needed: dirtyRef.current && nodesRef.current.some(+ (n) => n.id === sourceNodeId || n.id === targetId+ ),+ conflict: !!conflictRef.current,+ save: persist+ })+ if (!scopeSync.ok) {+ delivered = scopeSync+ return 'done' as const+ }delivered = await api.agentMessage.deliver({verb,sourceNodeId,diff --git a/src/renderer/lib/messageScopeSync.ts b/src/renderer/lib/messageScopeSync.tsnew file mode 100644index 000000000..01dbdc25a--- /dev/null+++ b/src/renderer/lib/messageScopeSync.ts@@ -0,0 +1,26 @@+/** Publishing pending canvas edits is not authorization: main still resolves the pair from its+ * own store and checks runtime ownership, consent and verified pane identity. Never publish over+ * an unresolved external-edit conflict merely because an agent asked to send a message. */+export async function syncMessageScope(options: {+ needed: boolean+ conflict: boolean+ save: () => Promise<boolean>+}): Promise<{ ok: true } | { ok: false; error: string }> {+ if (!options.needed) return { ok: true }+ if (options.conflict) {+ return {+ ok: false,+ error: 'Message not sent: resolve the canvas file conflict and save before trying again.'+ }+ }+ try {+ if (await options.save()) return { ok: true }+ } catch {+ // Serialization can fail before the workspace IPC. Neither failure may forward a message+ // against the old scope, and neither is evidence that the target belongs to another project.+ }+ return {+ ok: false,+ error: 'Message not sent: pending canvas changes could not be saved. Save successfully before trying again.'+ }+}diff --git a/src/session-host/host.ts b/src/session-host/host.tsindex db7bf7113..78cb7b16c 100644--- a/src/session-host/host.ts+++ b/src/session-host/host.ts@@ -14,6 +14,7 @@import fs from 'fs'import net from 'net'+import { hostMessagePane } from './message-pane'import path from 'path'import crypto from 'crypto'import { sessionHostPaths, currentProtocolVersion, type SessionHostState } from './paths'@@ -835,6 +836,15 @@ async function main(): Promise<void> {const command = await readPaneCommand(s.proc.pid)return { ok: true, result: { command } satisfies PaneCommandResult }}+ case 'messageOwnerV1':+ return { ok: true, result: await hostMessagePane(() => sessions.get(req.name)).owner() }+ case 'messagePasteReadyV1':+ return { ok: true, result: await hostMessagePane(() => sessions.get(req.name)).pasteReady() }+ case 'messageEnvelopeV1':+ return {+ ok: true,+ result: await hostMessagePane(() => sessions.get(req.name)).send(req.envelope, req.expected)+ }case 'capture': {const s = sessions.get(req.name)if (!s || s.exited) return { ok: true, result: { text: '' } satisfies CaptureResult }diff --git a/src/session-host/message-pane.test.ts b/src/session-host/message-pane.test.tsnew file mode 100644index 000000000..8595557a7--- /dev/null+++ b/src/session-host/message-pane.test.ts@@ -0,0 +1,90 @@+import { describe, expect, it, vi } from 'vitest'+import { hostMessagePane, type MessagePaneSession } from './message-pane'+import { windowsConsoleOwner } from './windows-pane-owner'++function fixture() {+ const session: MessagePaneSession = {+ generation: 'generation-a', exited: false,+ proc: { pid: 10, write: vi.fn() },+ messagePasteReady: vi.fn(async () => true)+ }+ const snapshot = {+ console: [10, 11],+ processes: [+ { pid: 10, parent: 1, executable: 'C:/pwsh.exe', born: '2026-09-13T01' },+ { pid: 11, parent: 10, executable: 'C:/opencode.exe', born: '2026-09-13T02' }+ ]+ }+ let live: MessagePaneSession | undefined = session+ const probe = vi.fn(async (pid: number, generation: string) => windowsConsoleOwner(pid, generation, snapshot))+ return { session, snapshot, probe, pane: hostMessagePane(() => live, probe), replace: () => {+ live = { ...session, generation: 'generation-b' }+ } }+}++describe('session-host messaging extension', () => {+ it('uses the host generation and OS process identity, then emits one sanitized bracketed paste', async () => {+ const { session, pane, probe } = fixture()+ const owner = await pane.owner()+ expect(owner?.paneId).toContain('generation-a')+ expect(await pane.send('line one\nline two\x1b[201~', owner!)).toBe(true)+ expect(probe).toHaveBeenCalledTimes(2)+ expect(session.proc.write).toHaveBeenCalledExactlyOnceWith('\x1b[200~line one\nline two[201~\x1b[201~\r')+ })++ it('refuses an expected owner from an older same-name generation', async () => {+ const f = fixture()+ const old = await f.pane.owner()+ f.replace()+ expect(await f.pane.send('message', old!)).toBe(false)+ expect(f.session.proc.write).not.toHaveBeenCalled()+ })++ it.each(['exit', 'replacement'] as const)('refuses %s during the OS probe', async (change) => {+ const f = fixture()+ const owner = await f.pane.owner()+ f.probe.mockImplementationOnce(async () => {+ if (change === 'exit') f.session.exited = true+ else f.replace()+ return owner+ })+ expect(await f.pane.send('message', owner!)).toBe(false)+ expect(f.session.proc.write).not.toHaveBeenCalled()+ })++ it('refuses a reused process PID and an ambiguous shell', async () => {+ const f = fixture()+ const owner = await f.pane.owner()+ f.snapshot.processes[1].born = '2026-09-13T03'+ expect(await f.pane.send('message', owner!)).toBe(false)+ f.snapshot.processes.push({ pid: 12, parent: 10, executable: 'C:/other.exe', born: '2026-09-13T04' })+ expect(await f.pane.owner()).toBeNull()+ expect(f.session.proc.write).not.toHaveBeenCalled()+ })++ it('rechecks paste mode after probing, never sends raw multiline input', async () => {+ const f = fixture()+ const owner = await f.pane.owner()+ vi.mocked(f.session.messagePasteReady).mockResolvedValueOnce(true).mockResolvedValueOnce(false)+ expect(await f.pane.send('a\nb', owner!)).toBe(false)+ expect(f.session.proc.write).not.toHaveBeenCalled()+ })++ it('refuses a replacement during the final emulator barrier', async () => {+ const f = fixture()+ const owner = await f.pane.owner()+ vi.mocked(f.session.messagePasteReady).mockResolvedValueOnce(true).mockImplementationOnce(async () => {+ f.replace()+ return true+ })+ expect(await f.pane.send('message', owner!)).toBe(false)+ expect(f.session.proc.write).not.toHaveBeenCalled()+ })++ it('never submits an empty envelope or an unobserved identity', async () => {+ const f = fixture()+ expect(await f.pane.send('', (await f.pane.owner())!)).toBe(false)+ expect(await f.pane.send('message', undefined)).toBe(false)+ expect(f.session.proc.write).not.toHaveBeenCalled()+ })+})diff --git a/src/session-host/message-pane.ts b/src/session-host/message-pane.tsnew file mode 100644index 000000000..89a03b7f9--- /dev/null+++ b/src/session-host/message-pane.ts@@ -0,0 +1,47 @@+import type { PaneOwner } from '../shared/agents/pane-owner-predicate'+import { sanitizePasteText } from '../core/paste-injection'+import { readWindowsConsoleOwner, sameNativeProcess } from './windows-pane-owner'++export interface MessagePaneSession {+ generation: string+ exited: boolean+ proc: { pid: number; write(data: string): void }+ messagePasteReady(): Promise<boolean>+}++/** The persistent host owns both the emulator and the generation. Never route this through the+ * main process's direct-PTY adapter: that object cannot observe a replacement inside this host.+ * Project grants, verified hooks, agent binary checks and receipts still belong to core. */+export function hostMessagePane(+ lookup: () => MessagePaneSession | undefined,+ probe = readWindowsConsoleOwner+) {+ const current = (s: MessagePaneSession): boolean => !s.exited && lookup() === s+ return {+ async owner(): Promise<PaneOwner | null> {+ const s = lookup()+ if (!s || !current(s)) return null+ const owner = await probe(s.proc.pid, s.generation)+ return current(s) ? owner : null+ },+ async pasteReady(): Promise<boolean> {+ const s = lookup()+ return !!s && current(s) && await s.messagePasteReady() && current(s)+ },+ async send(envelope: string, expected: PaneOwner | undefined): Promise<boolean> {+ const s = lookup()+ if (!s || !current(s) || !expected || typeof envelope !== 'string') return false+ const text = sanitizePasteText(envelope)+ if (!text || !(await s.messagePasteReady()) || !current(s)) return false+ const owner = await probe(s.proc.pid, s.generation)+ if (!current(s) || !sameNativeProcess(expected, owner)) return false+ // Cross the emulator barrier again after the OS probe: paste mode may have changed while+ // it was running. Check the registry again after EVERY await, then write synchronously.+ if (!(await s.messagePasteReady()) || !current(s)) return false+ try {+ s.proc.write(`\x1b[200~${text}\x1b[201~\r`)+ return true+ } catch { return false }+ }+ }+}diff --git a/src/session-host/protocol.ts b/src/session-host/protocol.tsindex 5bf518c68..22da49fce 100644--- a/src/session-host/protocol.ts+++ b/src/session-host/protocol.ts@@ -12,6 +12,11 @@* whose attach/flow contract predates its own. */export const SESSION_HOST_PROTOCOL_VERSION = 2+// Independently versioned, additive messaging extension. The v1/v2 terminal/attach contract is+// unchanged: an older live host rejects these unknown commands but is NEVER replaced to enable+// them. A future incompatible messaging shape gets new command names, not a forced host restart.+import type { PaneOwner } from '../shared/agents/pane-owner-predicate'+/** Concrete parser owned by the live terminal generation. Kept in the host so a new renderer/main* process can safely encode a delayed launch without re-guessing from a stale profile id. */export type SessionHostShellDialect = 'posix' | 'pwsh' | 'windows-powershell' | 'cmd'@@ -80,6 +85,9 @@ export type SessionHostRequest =| { id: number; cmd: 'resume'; name: string }| { id: number; cmd: 'sendKeys'; name: string; text: string; enter: boolean }| { id: number; cmd: 'paneCommand'; name: string }+ | { id: number; cmd: 'messageOwnerV1'; name: string }+ | { id: number; cmd: 'messagePasteReadyV1'; name: string }+ | { id: number; cmd: 'messageEnvelopeV1'; name: string; envelope: string; expected: PaneOwner }| { id: number; cmd: 'capture'; name: string; full: boolean }| {id: numberdiff --git a/src/session-host/session.ts b/src/session-host/session.tsindex dd98dd27a..0cbf81c37 100644--- a/src/session-host/session.ts+++ b/src/session-host/session.ts@@ -287,6 +287,13 @@ export class HostSession {return this.term.bracketedPasteRequested()}+ /** Agent messaging's stricter form of the same read: the pane must also still be alive and not+ * inside a private launch, because the envelope is only ever written as a framed paste. */+ async messagePasteReady(): Promise<boolean> {+ await this.outputTail+ return !this.exited && !this.suppressingPrivateLaunchOutput && this.term.bracketedPasteRequested()+ }+/** Stage an attach's explicit flow state and per-socket geometry before the warm screen barrier.* The returned commit is the only operation that activates live delivery. */async prepareAttachment(diff --git a/src/session-host/windows-pane-owner.test.ts b/src/session-host/windows-pane-owner.test.tsnew file mode 100644index 000000000..434a2e934--- /dev/null+++ b/src/session-host/windows-pane-owner.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest'+import { isAgentPane } from '../shared/agents/pane-owner-predicate'+import { windowsConsoleOwner, windowsConsoleProbeScript, type WindowsConsoleProcess } from './windows-pane-owner'++const root: WindowsConsoleProcess = { pid: 10, parent: 1, executable: 'C:\\Program Files\\PowerShell\\7\\pwsh.exe', born: '2026-09-12T10:00:00Z' }+const agent: WindowsConsoleProcess = { pid: 20, parent: 10, executable: 'C:\\Users\\A User\\bin\\opencode.exe', born: '2026-09-12T10:00:01Z' }+const owner = (processes = [root, agent], console = [10, 20]) => windowsConsoleOwner(10, 'generation-a', { processes, console })++describe('Windows console agent identity', () => {+ it('identifies a native executable with spaces in its path, keeping process birth and generation', () => {+ const result = owner()+ expect(isAgentPane(result, 'opencode')).toBe('agent')+ expect(result).toMatchObject({ panePid: 10, pids: [20], processBirths: [agent.born] })+ expect(result?.paneId).toContain('generation-a')+ })+ it('does not mistake a returned PowerShell prompt for an agent', () => {+ expect(isAgentPane(owner([root], [10]), 'opencode')).toBe('not-agent')+ })+ it('rejects a detached agent and an ambiguous shell with two children', () => {+ expect(owner([root, agent], [10])).toBeNull()+ expect(owner([root, agent, { ...agent, pid: 30 }], [10, 20, 30])).toBeNull()+ })+ it('does not choose an MCP descendant or match an executable by substring', () => {+ const worker = { ...agent, pid: 30, parent: 20, executable: 'C:\\bin\\python.exe' }+ expect(owner([root, agent, worker], [10, 20, 30])?.pids).toEqual([20])+ expect(isAgentPane(owner([root, { ...agent, executable: 'C:\\bin\\not-opencode.exe' }]), 'opencode')).toBe('not-agent')+ })+ it('rejects incomplete identity and a recycled parent PID', () => {+ expect(owner([{ ...root, born: '' }, agent])).toBeNull()+ expect(owner([root, { ...agent, born: '2025-01-01T00:00:00Z' }])).toBeNull()+ })+ it('never interpolates a non-integer process identifier into PowerShell', () => {+ expect(() => windowsConsoleProbeScript(NaN)).toThrow()+ expect(() => windowsConsoleProbeScript(-1)).toThrow()+ })+})diff --git a/src/session-host/windows-pane-owner.ts b/src/session-host/windows-pane-owner.tsnew file mode 100644index 000000000..e3ecf20c1--- /dev/null+++ b/src/session-host/windows-pane-owner.ts@@ -0,0 +1,113 @@+import { execFile } from 'child_process'+import type { PaneOwner } from '../shared/agents/pane-owner-predicate'++/** Exact Windows console/process generation, not merely a reused PID or executable name. */+export function sameNativeProcess(before: PaneOwner | undefined, after: PaneOwner | null): boolean {+ return !!before && !!after && !!before.paneId && before.paneId === after.paneId &&+ before.panePid === after.panePid && before.tty === after.tty &&+ before.pids?.length === 1 && after.pids?.length === 1 &&+ before.pids[0] === after.pids[0] && !!before.processBirths?.[0] &&+ before.processBirths[0] === after.processBirths?.[0] &&+ before.argv?.[0] === after.argv[0]+}++/** Windows has no POSIX foreground process group. Require the native executable to be on+ * the same console, reached through ONE unambiguous shell/bootstrap chain. Never search+ * arbitrary descendants (an MCP server or a detached background agent is not the reader).+ * Console membership comes from GetConsoleProcessList; paths and birth times from CIM.+ * Raw-input readiness and verified idle hooks remain separate delivery gates. */+export interface WindowsConsoleProcess {+ pid: number+ parent: number+ executable: string+ born: string+}++export interface WindowsConsoleSnapshot {+ console: number[]+ processes: WindowsConsoleProcess[]+}++const SHELLS = new Set(['pwsh', 'powershell', 'cmd'])+function executableName(executable: string): string {+ return (executable.replace(/\\/g, '/').split('/').pop() ?? '').toLowerCase().replace(/\.exe$/, '')+}++export function windowsConsoleOwner(+ rootPid: number,+ generation: string,+ snapshot: WindowsConsoleSnapshot+): PaneOwner | null {+ const attached = new Set(snapshot.console)+ const rows = new Map(snapshot.processes.map((row) => [row.pid, row]))+ const root = rows.get(rootPid)+ if (!root || !attached.has(rootPid) || !root.born || !generation) return null+ const seen = new Set<number>()+ let current = root+ for (let depth = 0; depth < 8; depth++) {+ if (seen.has(current.pid) || !attached.has(current.pid) || !current.executable || !current.born) return null+ seen.add(current.pid)+ const binary = executableName(current.executable)+ if (!binary) return null+ if (SHELLS.has(binary)) {+ // Count ALL children: ignoring a detached sibling would hide an ambiguous shell.+ const children = snapshot.processes.filter((row) => row.parent === current.pid)+ if (children.length > 1) return null+ if (children.length === 1) {+ const child = children[0]+ if (child.born < current.born) return null // recycled parent PID+ current = child+ continue+ }+ }+ return {+ panePid: rootPid,+ tty: `win32-console:${rootPid}`,+ paneId: `win32:${generation}:${root.born}`,+ command: binary,+ // Deliberately derived from the OS executable path, NOT arguments/prompt text.+ argv: [binary],+ pids: [current.pid],+ processBirths: [current.born]+ }+ }+ return null+}++/** Probe only. The helper joins the console to read its process list, writes nothing into+ * it, and detaches in finally. The target PID is a validated integer, never shell text.+ * Do not log stdout: the result is an internal identity read. */+export function windowsConsoleProbeScript(rootPid: number): string {+ if (!Number.isSafeInteger(rootPid) || rootPid <= 0) throw new Error('invalid console root PID')+ return `$ErrorActionPreference = 'Stop';+Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public static class NtConsoleProbe { [DllImport("kernel32.dll", SetLastError=true)] public static extern bool FreeConsole(); [DllImport("kernel32.dll", SetLastError=true)] public static extern bool AttachConsole(uint pid); [DllImport("kernel32.dll", SetLastError=true)] public static extern uint GetConsoleProcessList([Out] uint[] ids, uint length); }';+$self = $PID; $ids = @();+try {+ [void][NtConsoleProbe]::FreeConsole();+ if (-not [NtConsoleProbe]::AttachConsole(${rootPid})) { throw 'console unavailable' };+ $buffer = New-Object 'System.UInt32[]' 1024;+ $count = [NtConsoleProbe]::GetConsoleProcessList($buffer, $buffer.Length);+ if ($count -eq 0 -or $count -gt $buffer.Length) { throw 'console identity unavailable' };+ for ($i = 0; $i -lt $count; $i++) { if ($buffer[$i] -ne $self) { $ids += [int]$buffer[$i] } };+} finally { [void][NtConsoleProbe]::FreeConsole() };+$rows = @(Get-CimInstance Win32_Process | Where-Object { $_.ProcessId -ne $self } | ForEach-Object {+ @{ pid = [int]$_.ProcessId; parent = [int]$_.ParentProcessId; executable = [string]$_.ExecutablePath; born = $(if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { '' }) }+});+@{ console = @($ids); processes = $rows } | ConvertTo-Json -Depth 4 -Compress;`+}++export async function readWindowsConsoleOwner(rootPid: number, generation: string): Promise<PaneOwner | null> {+ if (process.platform !== 'win32') return null+ const script = windowsConsoleProbeScript(rootPid)+ return new Promise((resolve) => {+ execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script],+ { timeout: 4000, maxBuffer: 4 * 1024 * 1024, windowsHide: true }, (error, stdout) => {+ if (error) return resolve(null)+ try {+ const snapshot = JSON.parse(stdout) as WindowsConsoleSnapshot+ if (!Array.isArray(snapshot.console) || !Array.isArray(snapshot.processes)) return resolve(null)+ resolve(windowsConsoleOwner(rootPid, generation, snapshot))+ } catch { resolve(null) }+ })+ })+}diff --git a/src/shared/agents/pane-owner-predicate.ts b/src/shared/agents/pane-owner-predicate.tsindex d703dae2d..28aac9f70 100644--- a/src/shared/agents/pane-owner-predicate.ts+++ b/src/shared/agents/pane-owner-predicate.ts@@ -40,6 +40,9 @@ export interface PaneOwner {* makes the second case ordinary rather than exotic.*/pids?: readonly number[]+ /** Native Windows process birth times, paired with pids. Guards PID reuse when the+ * console root outlives a child. POSIX readers retain their existing contract. */+ processBirths?: readonly string[]}/**diff --git a/test/acceptance/message-scope-sync.test.ts b/test/acceptance/message-scope-sync.test.tsnew file mode 100644index 000000000..f0701229e--- /dev/null+++ b/test/acceptance/message-scope-sync.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it, vi } from 'vitest'+import { resolveDeliveryScope } from '../../src/core/agents/agent-message-scope'+import { syncMessageScope } from '../../src/renderer/lib/messageScopeSync'+import fs from 'fs'+import path from 'path'++describe('publishing the canvas before message scope resolution', () => {+ it('wires the barrier before delivery inside the renderer target lock', () => {+ const source = fs.readFileSync(path.resolve('src/renderer/canvas/Canvas.tsx'), 'utf8').replace(/\r\n/g, '\n')+ const start = source.indexOf("if (verb === 'send' || verb === 'reply' || verb === 'notify')")+ const end = source.indexOf('// ── `open-project`', start)+ const block = source.slice(start, end)+ expect(block.indexOf('guardConcurrentRestart(targetId')).toBeLessThan(block.indexOf('await syncMessageScope('))+ expect(block.indexOf('await syncMessageScope(')).toBeLessThan(block.indexOf('await api.agentMessage.deliver('))+ expect(block).toContain('conflict: !!conflictRef.current')+ expect(block).toContain('save: persist')+ expect(block).toContain('if (!scopeSync.ok)')+ })+ it('waits for the core store to see a newly opened node, independent of its cwd', async () => {+ const coordinator = { id: 'coordinator', cwd: 'C:/repo' }+ const architect = { id: 'architect', cwd: 'C:/repo/.opencode/launch/arquiteto' }+ const coder = { id: 'coder', cwd: 'C:/repo/.opencode/launch/coder' }+ const persisted = [{ id: 'project', nodes: [coordinator] }]+ expect(resolveDeliveryScope(persisted, coordinator.id, architect.id).kind).toBe('refused')+ let finish!: () => void+ const saving = syncMessageScope({+ needed: true,+ conflict: false,+ save: () => new Promise<boolean>((resolve) => {+ finish = () => {+ persisted[0].nodes = [coordinator, architect, coder]+ resolve(true)+ }+ })+ })+ let finished = false+ void saving.then(() => { finished = true })+ await Promise.resolve()+ expect(finished).toBe(false)+ finish()+ expect(await saving).toEqual({ ok: true })+ for (const target of [architect, coder]) {+ expect(resolveDeliveryScope(persisted, coordinator.id, target.id)).toEqual({+ kind: 'same-project', projectId: 'project'+ })+ }+ // Publishing a snapshot does not relax either boundary.+ expect(resolveDeliveryScope([...persisted, { id: 'other', nodes: [{ id: 'foreign', cwd: '' }] }],+ coordinator.id, 'foreign')).toMatchObject({ kind: 'refused', reason: 'cross-project' })+ expect(resolveDeliveryScope([...persisted, { id: 'clone', nodes: [architect] }],+ coordinator.id, architect.id)).toMatchObject({ kind: 'refused', reason: 'ambiguous-target-node-id' })+ })++ it('does not save an unrelated active canvas', async () => {+ const save = vi.fn()+ expect(await syncMessageScope({ needed: false, conflict: true, save })).toEqual({ ok: true })+ expect(save).not.toHaveBeenCalled()+ })++ it('does not overwrite an external conflict', async () => {+ const save = vi.fn()+ expect(await syncMessageScope({ needed: true, conflict: true, save })).toMatchObject({ ok: false })+ expect(save).not.toHaveBeenCalled()+ })++ it.each(['refused', 'rejected'] as const)('refuses forwarding after a %s save', async (failure) => {+ const save = failure === 'refused' ? async () => false : async () => { throw new Error('unavailable') }+ expect(await syncMessageScope({ needed: true, conflict: false, save })).toMatchObject({ ok: false })+ })+})