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
fix(relay): never promise an unbuildable launch, say which shell the pane speaks, keep keys off the local socket
review082a810c8822
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8bbf7db88..e7d4655ec 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -8619,11 +8619,17 @@ unix-socket forward over it. POSIX keeps OpenSSH untouched.field re-validated, cwd jailed to the fs roots, cwd/account folded into the SPAWN options of anunrecorded node (a recorded node keeps its records), and the line built for the pane's realparser — `assembleResumeCommand` on POSIX, the trusted Windows planner when its resolver is- wired, else only a dialect-neutral line. Reply `launched: true` = "type nothing". Without- `launch` the reply is byte-identical. `pty.scroll` writes the wheel only on a tmux /+ wired, else only a dialect-neutral line. Reply `launched: true` = "type nothing", and it is only+ promised after a preflight build succeeded (`relayLaunchPreflight` — an unset `${env:…}` or a+ non-neutral custom line on a Windows pane answers `launched:false`, never a launch that silently+ never comes). The reply also says `paneShell: 'posix' | 'windows'` — whether a typed POSIX line is+ safe in THAT pane, which is not `hostPlatform`: a Windows desktop's SSH-project node runs on a+ POSIX host (not host-launched; the phone types as before). Without `launch` the reply is+ byte-identical. `pty.scroll` writes the wheel only on a tmux /mouse-requesting pane (`PtyManager.scrollRoute`); a session-host / plain stream's reply says`scroll:'local'` and its snapshot is the full buffer. Keyed answers ride `agent.key` (closed key- set, host-side state + open-ask guard, hook reply first), read-acks `inbox.ack`+ set, host-side state + open-ask guard, hook reply first; an SSH-project node with no client held+ goes over its owner's ControlMaster or nowhere — never the local socket), read-acks `inbox.ack`(`applyPhoneReadAck`, the ack sweeper's body), plus `fs.browse` (home-jailed, dirs only) and`pty.capture`; `host.info` lists them. All additive — an old phone keeps its old path.diff --git a/docs/windows-session-host.md b/docs/windows-session-host.mdindex f3a000f7b..a9534a7a4 100644--- a/docs/windows-session-host.md+++ b/docs/windows-session-host.md@@ -690,7 +690,9 @@ you chose and why") rather than an oversight.bytes for tmux's copy-mode. Neither holds here: pwsh / cmd reject `2>/dev/null`, `env -u`,`VAR=x cmd`, and a wheel nobody asked for lands in the prompt as text. So the phone sends`pty.attach { launch }` and the HOST launches (`core/relay-launch.ts`: cwd/account ride the spawn- options, the line is built for the pane's real parser and typed once), the attach reply says+ options, the line is built for the pane's real parser and typed once; `launched:true` is promised+ only after a preflight build succeeded, and `paneShell` tells the phone whether a typed POSIX line+ is safe in that pane — an SSH-project node of a Windows desktop is `posix`), the attach reply says`scroll:'local'` with a full-buffer snapshot, and `pty.scroll` writes a wheel only when`paneModesV1` reports the app asked for the mouse. Keyed Inbox answers (`agent.key`), read-acks(`inbox.ack`), the folder browser (`fs.browse`) and plain capture (`pty.capture`) are relaydiff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 782463ff4..aefd2ee7d 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -221,7 +221,7 @@ import {import type { SessionHostPty } from './session-host-pty'import { NativeWindowsPane } from './native-windows-pane'import type { ProjectSpawnOverrides, ProjectSpawnOverridesReader } from './project-spawn-overrides'-import { buildRelayLaunch, relayLaunchAgentKnown, relayLaunchDialect, type RelayLaunchContext, type RelayLaunchRequest } from './relay-launch'+import { buildRelayLaunch, relayLaunchAgentKnown, relayLaunchDialect, relayLaunchPreflight, type RelayLaunchContext, type RelayLaunchRequest } from './relay-launch'import { RELAY_KEY_GAP_MS, rawKeyBytes, tmuxKeyArgs, type RelayKey } from './relay-keys'// How often we snapshot a live tmux session's scrollback to disk, so a machine reboot (which@@ -3457,7 +3457,8 @@ export class PtyManager {cols: size.cols,rows: size.rows}- const launch = plan.kind === 'local' ? this.relayLaunchFor(hint.launch, plan.projectId, options) : undefined+ let launch = plan.kind === 'local' ? this.relayLaunchFor(hint.launch, plan.projectId, options) : undefined+ if (launch && !(await this.relayLaunchViable(launch, nodeId))) launch = undefinedconst refused = this.spawnRefusal(options)if (refused) {return {@@ -3596,10 +3597,26 @@ export class PtyManager {// trusted as a path component.options.agentId = req.agentIdif (req.cwd) options.cwd = req.cwd- if (req.accountId && ctx.isKnownAccount(req.accountId)) options.accountId = req.accountId+ if (req.accountId && ctx.isKnownAccount(req.accountId, req.agentId)) options.accountId = req.accountIdreturn req}+ /** `relayLaunchPreflight` for this node's pane: a Windows pane unless a tmux (or a live non-Windows+ * backend) will hold it. A throwing context means no launch. */+ private async relayLaunchViable(req: RelayLaunchRequest, persistKey: string): Promise<boolean> {+ const ctxFn = this.relayLaunchContext+ if (!ctxFn) return false+ try {+ const live = this.liveSessionForPersistKey(persistKey)+ const windowsPane =+ this.runtimePlatform === 'win32' &&+ (live ? !!live.sessionHost || !!live.nativeWindowsPane || !live.tmuxBacked : !(this.tmuxPath && this.getSettings().tmuxEnabled))+ return await relayLaunchPreflight(req, ctxFn(), windowsPane)+ } catch {+ return false+ }+ }+/** How long a relay launch waits for a shell to own the fresh pane before giving up. */static readonly RELAY_LAUNCH_SHELL_WAIT_MS = 10_000@@ -3699,17 +3716,21 @@ export class PtyManager {const target = sessionName(persistKey)const live = this.liveSessionForPersistKey(persistKey)if (live?.nativeWindowsPane || this.isZellij(persistKey, live)) return false+ // An SSH-project node with no client of ours held right now lives on the HOST's tmux: its+ // owner's ControlMaster is the only way there. Never fall through to the LOCAL socket — a+ // same-named local `nt-<id>` (the pre-`requireRemote` orphan) would take the keystroke, and a+ // stray `1` / Enter into an unrelated pane is exactly what the closed key set exists to stop.+ const owner = live ? null : (this.remoteNodeOwner?.(persistKey) ?? null)+ if (owner && !owner.remote) return false+ const sshRemote = live?.sshRemote ?? owner?.remotefor (let i = 0; i < keys.length; i++) {if (i > 0) await new Promise((r) => setTimeout(r, RELAY_KEY_GAP_MS))const key = keys[i]try {- if (live?.sshRemote) {+ if (sshRemote) {const ssh = findSsh()if (!ssh) return false- await runAsync(- ssh,- remoteSendKeyArgs(live.sshRemote.conn, live.sshRemote.controlPath, target, tmuxKeyArgs(key))- )+ await runAsync(ssh, remoteSendKeyArgs(sshRemote.conn, sshRemote.controlPath, target, tmuxKeyArgs(key)))} else if (live?.sessionHost || !this.tmuxPath) {// No name-addressed raw write exists on the session host (its `sendKeys` is a paste),// so a key needs a client this process holds — the desktop node, or a relay stream.diff --git a/src/core/pty-relay-launch.test.ts b/src/core/pty-relay-launch.test.tsindex f8daef9b7..782a0463b 100644--- a/src/core/pty-relay-launch.test.ts+++ b/src/core/pty-relay-launch.test.ts@@ -55,18 +55,18 @@ function launchCtx(over: Partial<RelayLaunchContext> = {}): RelayLaunchContext {return {customAgents: [],claudeAutoSupported: true,- isKnownAccount: (id) => id === 'acct-1',+ isKnownAccount: (id, agentId) => id === 'acct-1' && agentId === 'claude',env: {},...over}}-async function manager(withLaunch = true) {+async function manager(withLaunch: boolean | Partial<RelayLaunchContext> = true, runtimePlatform?: NodeJS.Platform) {const { PtyManager } = await import('./pty-manager')- const m = new PtyManager()+ const m = new PtyManager(runtimePlatform ? { runtimePlatform } : {})m.init(() => ({ ...DEFAULT_SETTINGS, tmuxEnabled: false }))m.setRelayNodeResolver(resolver())- if (withLaunch) m.setRelayLaunchContext(() => launchCtx())+ if (withLaunch) m.setRelayLaunchContext(() => launchCtx(withLaunch === true ? {} : withLaunch))return m}@@ -101,6 +101,37 @@ describe('relay launch (pty.attach { launch })', () => {expect((spawn.mock.calls[0][0] as { accountId?: string }).accountId).toBeUndefined()})+ it("an account of the OTHER provider is dropped: a codex agent never runs under a claude account's home", async () => {+ const m = await manager()+ const spawn = vi.spyOn(m as unknown as { spawnSession: (...a: unknown[]) => string }, 'spawnSession')+ const prep = await m.prepareRelayAttach('fresh-x', { cols: 80, rows: 24 }, { launch: { agentId: 'codex', accountId: 'acct-1' } })+ if (prep.kind !== 'ready') throw new Error('not ready')+ await prep.attach(sinks)+ expect((spawn.mock.calls[0][0] as { accountId?: string }).accountId).toBeUndefined()+ })++ it('a launch no line can be built for is never PROMISED (the reply would say launched:true and nothing would come)', async () => {+ // A Windows pane with no trusted planner wired: a custom agent whose args were quoted is not+ // dialect-neutral, so buildRelayLaunch would answer null after the reply. Refused up front.+ const quoted = {+ customAgents: [{ id: 'mine', label: 'Mine', launchCmd: 'mine', args: "--flag 'a b'" } as never]+ }+ const win = await manager(quoted, 'win32')+ const w = await win.prepareRelayAttach('fresh-w', { cols: 80, rows: 24 }, { launch: { agentId: 'mine' } })+ expect(w.kind === 'ready' && w.launch).toBeFalsy()+ // The same agent on a POSIX host types the quoted line exactly as the phone used to.+ const posix = await manager(quoted, 'linux')+ const p = await posix.prepareRelayAttach('fresh-p', { cols: 80, rows: 24 }, { launch: { agentId: 'mine' } })+ expect(p.kind === 'ready' && p.launch).toBeTypeOf('function')+ // A plain builtin on the Windows pane is neutral and still offered.+ const plain = await win.prepareRelayAttach('fresh-b', { cols: 80, rows: 24 }, { launch: { agentId: 'claude', sessionId: SID } })+ expect(plain.kind === 'ready' && plain.launch).toBeTypeOf('function')+ // An ${env:…} that expands to nothing would type a mangled line on ANY host.+ const envd = await manager({ customAgents: [{ id: 'e', label: 'E', launchCmd: '${env:NOPE_UNSET}' } as never] }, 'linux')+ const e = await envd.prepareRelayAttach('fresh-e', { cols: 80, rows: 24 }, { launch: { agentId: 'e' } })+ expect(e.kind === 'ready' && e.launch).toBeFalsy()+ })+it('a RECORDED node keeps its records; a launch naming another agent is no launch', async () => {const m = await manager()const spawn = vi.spyOn(m as unknown as { spawnSession: (...a: unknown[]) => string }, 'spawnSession')@@ -196,6 +227,36 @@ describe('sendKeys into a session-host pane', () => {expect(await m.sendKeys('n1', [{ digit: '2' }, { name: 'Right' }, { name: 'Enter' }])).toBe(true)expect(writes).toEqual(['2', '\x1b[C', '\r'])})+ // A fake `tmux` that records its argv: proves which socket a key went to (POSIX sh script).+ it.skipIf(process.platform === 'win32')(+ "an SSH-project node with no client held never falls through to the LOCAL socket",+ async () => {+ const fs = await import('node:fs')+ const os = await import('node:os')+ const path = await import('node:path')+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-sendkeys-'))+ const log = path.join(dir, 'argv.log')+ const tmux = path.join(dir, 'tmux')+ fs.writeFileSync(tmux, `#!/bin/sh\necho "$@" >> '${log}'\n`, { mode: 0o755 })+ try {+ const m = await manager()+ ;(m as unknown as { tmuxPath: string | null }).tmuxPath = tmux+ // Owner known, ControlMaster down: nothing is sent anywhere — a same-named local orphan+ // `nt-<id>` must not take the keystroke.+ m.setRemoteNodeOwner((id) => (id === 'remote-n' ? { projectId: 'p', hostKey: 'u@h' } : null))+ expect(await m.sendKeys('remote-n', [{ digit: '1' }])).toBe(false)+ expect(fs.existsSync(log)).toBe(false)+ // A LOCAL node with no client held still goes to the local socket, as before.+ expect(await m.sendKeys('local-n', [{ digit: '1' }, { name: 'Enter' }])).toBe(true)+ expect(fs.readFileSync(log, 'utf8').trim().split('\n')).toEqual([+ '-L node-terminal send-keys -t nt-local-n -l 1',+ '-L node-terminal send-keys -t nt-local-n Enter'+ ])+ } finally {+ fs.rmSync(dir, { recursive: true, force: true })+ }+ }+ )it('no client this process holds ⇒ nothing delivered', async () => {const m = await manager();(m as unknown as { tmuxPath: string | null }).tmuxPath = nulldiff --git a/src/core/relay-launch.ts b/src/core/relay-launch.tsindex beb33eceb..ea02a959f 100644--- a/src/core/relay-launch.ts+++ b/src/core/relay-launch.ts@@ -65,8 +65,11 @@ export interface RelayLaunchContext {claudeAutoSupported: booleancodexApprovalValues?: readonly string[] | nullcodexNoDaemon?: boolean | null- /** Is `accountId` a usable LOCAL managed account (claude or codex) on this machine? */- isKnownAccount(accountId: string): boolean+ /** Is `accountId` a usable LOCAL managed account on this machine FOR THIS AGENT'S PROVIDER? A+ * claude agent takes only a claude account and a codex agent only a codex one: the two lists+ * share an id alphabet, and a cross-provider pair would scope the session to the wrong CLI's+ * home (or be refused at spawn). */+ isKnownAccount(accountId: string, agentId: AgentId): boolean/** `${env:…}` expansion for a custom agent's launchCmd/args (the host process env). */env: Record<string, string | undefined>/** The trusted Windows planner's executable resolver, once the host wires one. Absent ⇒ the@@ -137,6 +140,23 @@ export function isDialectNeutralCommand(command: string): boolean {return /^[A-Za-z0-9._:/=@+-]+( [A-Za-z0-9._:/=@+-]+)*$/.test(command) && !/^-/.test(command)}+/**+ * Can a launch line be built for this request BEFORE the pane exists? Run before the attach replies+ * `launched: true` (= "phone, type nothing"), so every DETERMINISTIC no-launch — an `${env:…}` that+ * expands to nothing, a custom agent whose line is not dialect-neutral on a Windows pane with no+ * trusted planner — answers `launched: false` and the phone keeps its own path, instead of a reply+ * that promises a launch nobody will ever deliver. `windowsPane` = the pane will be pwsh / Windows+ * PowerShell / cmd (all three take the same neutral-line rule, so one probe answers for them).+ */+export async function relayLaunchPreflight(+ req: RelayLaunchRequest,+ ctx: RelayLaunchContext,+ windowsPane: boolean+): Promise<boolean> {+ if (windowsPane && ctx.resolveExecutableKind) return relayLaunchAgentKnown(req.agentId, ctx)+ return (await buildRelayLaunch(req, windowsPane ? 'pwsh' : 'posix', ctx).catch(() => null)) !== null+}+/** The mode the launch carries: claude's own version gate, and nothing for an agent with no modes. */function effectiveMode(req: RelayLaunchRequest, ctx: RelayLaunchContext): AgentPermissionMode | undefined {const mode = req.permissionModediff --git a/src/main/index.ts b/src/main/index.tsindex 55d274cfe..0c25183a1 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -276,6 +276,7 @@ import { codexHome } from '../core/usage/codex-usage'import { isAsyncSubagentLaunch, grokRawFields, type NormalizedAgentEvent } from '../shared/agents/normalize'import { applyGrokHookSession } from '../core/grok-hook-session'import { agentAccountColor } from '../shared/agents/account-color'+import { capabilityAgentId } from '../shared/agents/config'import {setRemoteTranscriptReader,TITLE_TAIL_BYTES,@@ -2418,7 +2419,11 @@ app.whenReady().then(async () => {claudeAutoSupported: localClaudeCaps?.autoPermissionMode === true,codexApprovalValues: localCodexCaps?.approvalValues ?? null,codexNoDaemon: localCodexCaps?.noDaemon === true,- isKnownAccount: (id) => localClaude.has(id) || localCodex.has(id),+ // Provider-matched: a claude agent never runs under a codex home, or the reverse.+ isKnownAccount: (id, agentId) => {+ const cap = capabilityAgentId(agentId)+ return cap === 'claude' ? localClaude.has(id) : cap === 'codex' ? localCodex.has(id) : false+ },env: process.env}})diff --git a/src/main/remote/host-relay-parity.test.ts b/src/main/remote/host-relay-parity.test.tsindex 7001f56f5..51ddeea6a 100644--- a/src/main/remote/host-relay-parity.test.ts+++ b/src/main/remote/host-relay-parity.test.ts@@ -25,6 +25,7 @@ function setup(opts: {scroll?: 'host' | 'local'route?: 'tmux' | 'app-mouse' | 'local'withLaunch?: boolean+ remote?: booleanextras?: HostRelayExtraschat?: Partial<HostChatOps>roots?: string[]@@ -43,7 +44,7 @@ function setup(opts: {const pty = {prepareRelayAttach: vi.fn(async () => ({kind: 'ready' as const,- remote: false,+ remote: opts.remote ?? false,...(opts.scroll ? { scroll: opts.scroll } : {}),sessionExists: async () => opts.existed ?? true,snapshot: async () => '',@@ -105,7 +106,13 @@ describe('pty.attach { launch } — the host owns the launch', () => {})await flush()await flush()- expect(responses[0].body).toEqual({ streamId: 1, fresh: true, launched: true, hostPlatform: 'win32' })+ expect(responses[0].body).toEqual({+ streamId: 1,+ fresh: true,+ launched: true,+ hostPlatform: 'win32',+ paneShell: 'windows'+ })expect(pty.prepareRelayAttach.mock.calls[0][2]).toEqual({projectId: undefined,launch: { agentId: 'claude', sessionId: 'abc-1', cwd: 'c:\\Work\\app', permissionMode: 'plan' }@@ -118,7 +125,29 @@ describe('pty.attach { launch } — the host owns the launch', () => {handlers.onRpc({ id: '1', method: 'pty.attach', params: { nodeId: 'n1', launch: { agentId: 'claude' } } })await flush()await flush()- expect(responses[0].body).toEqual({ streamId: 1, fresh: false, launched: false, hostPlatform: 'linux' })+ expect(responses[0].body).toEqual({+ streamId: 1,+ fresh: false,+ launched: false,+ hostPlatform: 'linux',+ paneShell: 'posix'+ })+ expect(launch).not.toHaveBeenCalled()+ })+ it("a win32 host's SSH-project node: not host-launched, and the pane is POSIX (the phone types as before)", async () => {+ // A Windows desktop's SSH project runs on a POSIX host's tmux. `hostPlatform: 'win32'` alone+ // would tell an updated phone "never type shell syntax" and the remote agent would never start.+ const { handlers, responses, launch } = setup({ existed: false, remote: true, extras: { platform: 'win32' } })+ handlers.onRpc({ id: '1', method: 'pty.attach', params: { nodeId: 'n1', launch: { agentId: 'claude' } } })+ await flush()+ await flush()+ expect(responses[0].body).toEqual({+ streamId: 1,+ fresh: true,+ launched: false,+ hostPlatform: 'win32',+ paneShell: 'posix'+ })expect(launch).not.toHaveBeenCalled()})it('a cwd outside the shared roots is dropped; a forged launch reaches core as no launch', async () => {diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.tsindex dd94d1316..78bca9f0d 100644--- a/src/main/remote/host-service.ts+++ b/src/main/remote/host-service.ts@@ -508,7 +508,17 @@ export function createHostHandlers(// = no tmux in front of this pane (session host / plain shell), so `pty.scroll` will not// move history — scroll your own buffer. A tmux stream's reply is unchanged....(prep.scroll === 'local' ? { scroll: 'local' as const } : {}),- ...(launchAsked ? { launched: !!launch, hostPlatform } : {})+ // `paneShell` says whether a typed POSIX line is safe in THIS pane — not the same question+ // as `hostPlatform`: a Windows desktop's SSH-project node runs on a POSIX host's tmux (the+ // host does not own that launch, so `launched:false` + `paneShell:'posix'` = "type it as+ // before"), while a local pane on a win32 host is pwsh / cmd ("never type shell syntax").+ ...(launchAsked+ ? {+ launched: !!launch,+ hostPlatform,+ paneShell: prep.remote || hostPlatform !== 'win32' ? ('posix' as const) : ('windows' as const)+ }+ : {})})const snapshot = await prep.snapshot().catch(() => '')// The stream may have been killed/closed while the capture was in flight.