Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(windows): core building blocks for relay-only host parity

review3a8e008c385a
diff --git a/src/core/ack-sweep.test.ts b/src/core/ack-sweep.test.ts
index 358970a36..ec64dd8d9 100644
--- a/src/core/ack-sweep.test.ts
+++ b/src/core/ack-sweep.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { sweepAckDir, createAckSweeper, type AckSweepFsLike } from './ack-sweep'
+import { applyPhoneReadAck, sweepAckDir, createAckSweeper, type AckSweepFsLike } from './ack-sweep'
/**
* In-memory fs double for the sweeper. `dir` is a flat map of name → content; `mtime` advances on
@@ -154,3 +154,22 @@ describe('createAckSweeper — dir-mtime gate + no re-ack loop', () => {
expect(acked).toEqual([])
})
})
+
+// The relay's `inbox.ack` (relay-only hosts: no SSH to drop a `.seen` over) runs the same body.
+describe('applyPhoneReadAck — the one read-ack body every arrival path shares', () => {
+ it('acks then clears, once each, without re-acking', () => {
+ const calls: string[] = []
+ applyPhoneReadAck('n1', { ackDone: (id) => calls.push(`ack:${id}`), onUnreadClear: (id) => calls.push(`clear:${id}`) })
+ expect(calls).toEqual(['ack:n1', 'clear:n1'])
+ })
+ it('a throwing ackDone still clears the unread dot', () => {
+ const calls: string[] = []
+ applyPhoneReadAck('n1', {
+ ackDone: () => {
+ throw new Error('boom')
+ },
+ onUnreadClear: (id) => calls.push(`clear:${id}`)
+ })
+ expect(calls).toEqual(['clear:n1'])
+ })
+})
diff --git a/src/core/ack-sweep.ts b/src/core/ack-sweep.ts
index 54710689c..f5724f189 100644
--- a/src/core/ack-sweep.ts
+++ b/src/core/ack-sweep.ts
@@ -49,6 +49,26 @@ export interface AckSweepHandlers {
onUnreadClear(nodeId: string): void
}
+/**
+ * Apply ONE phone read-ack: resolve the node's done event(s) + fire the end seam, then clear the
+ * desktop unread dot without re-acking. The single body every arrival path runs — the local
+ * `.seen` sweep below, the SSH hosts' remote sweep, and the relay's `inbox.ack` (a relay-only host,
+ * every Windows pairing, has no SSH for the phone to drop a file over). Each half is best-effort
+ * and independent: a throwing `ackDone` must not leave the dot set.
+ */
+export function applyPhoneReadAck(nodeId: string, handlers: AckSweepHandlers): void {
+ try {
+ handlers.ackDone(nodeId)
+ } catch {
+ // ackDone is best-effort; the unread clear below still runs.
+ }
+ try {
+ handlers.onUnreadClear(nodeId)
+ } catch {
+ // ignore
+ }
+}
+
/**
* One pass over `dir`: for each `<nodeId>.seen` file, run `ackDone` + `onUnreadClear`, then delete
* the file. Returns the node ids it consumed. Tolerant at every step: a missing dir, an
@@ -80,16 +100,7 @@ export function sweepAckDir(dir: string, fsi: AckSweepFsLike, handlers: AckSweep
continue
}
// A handler must never break the sweep (or leave the file un-consumed): ack + clear, then delete.
- try {
- handlers.ackDone(nodeId)
- } catch {
- // ackDone is best-effort; keep going so the file is still deleted + unread still cleared.
- }
- try {
- handlers.onUnreadClear(nodeId)
- } catch {
- // ignore
- }
+ applyPhoneReadAck(nodeId, handlers)
try {
fsi.rmSync(full, { force: true })
} catch {
diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.ts
index 5382366e8..7640e693d 100644
--- a/src/core/agent-status-mirror.test.ts
+++ b/src/core/agent-status-mirror.test.ts
@@ -35,6 +35,7 @@ import {
workingNodes,
_resetForTest,
pendingTicketsFor,
+ openAskFor,
_snapshot,
_inboxSnapshot,
DONE_HOLDOFF_MS,
@@ -2610,3 +2611,18 @@ describe('pendingTicketsFor', () => {
expect(pendingTicketsFor('n1')).toEqual([])
})
})
+
+// The relay's `agent.key` (main/remote/host-chat.ts) compares the answer it is about to type with
+// the ask open NOW — the newest unresolved approval/question card, the phone's own pick.
+describe('openAskFor', () => {
+ beforeEach(() => _resetForTest())
+ it('names the open approval (with its ticket), and nothing once it is answered', () => {
+ expect(openAskFor('n1')).toBeUndefined()
+ recordAgentEvent(ev({ state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Approve write', pendingId: 'n1-1-1' }))
+ expect(openAskFor('n1')).toEqual({ kind: 'approval', pendingId: 'n1-1-1' })
+ expect(openAskFor('n2')).toBeUndefined()
+ recordAgentEvent(syntheticAnsweredEvent('n1', 'n1-1-1', 'allow')!)
+ expect(openAskFor('n1')).toBeUndefined()
+ })
+})
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index c606fc7ce..570ba3bb5 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -248,6 +248,13 @@ export interface MirrorSettings {
* custom node, exactly as before this field existed.
*/
customAgents?: MirrorCustomAgent[]
+ /**
+ * `process.platform` of the machine whose sessions this file describes (`darwin` / `linux` /
+ * `win32`). A phone must not type POSIX shell syntax into a `win32` host's fresh pane — pwsh and
+ * cmd reject `2>/dev/null`, `env -u`, `VAR=x cmd` — so it asks the host to launch instead
+ * (`pty.attach { launch }`). Absent on old files and on SSH slices (whose hosts are POSIX).
+ */
+ hostPlatform?: string
}
/** One custom agent as the mirror advertises it (see MirrorSettings.customAgents). */
@@ -1375,6 +1382,18 @@ export function pendingTicketsFor(nodeId: string): string[] {
return [...out]
}
+/**
+ * The ask that is CURRENTLY open on a node — its newest unresolved approval/question card, the same
+ * pick the phone renders its answer card from (`LiveActivityManager.needsYouContent`). The relay's
+ * `agent.key` compares it with the kind of answer it is about to type: a question's digit typed
+ * into a permission prompt ANSWERS it (`2` = "don't ask again"). Undefined = no open ask. Pure read.
+ */
+export function openAskFor(nodeId: string): { kind: 'approval' | 'question'; pendingId?: string } | undefined {
+ const e = newestUnresolved(inboxEvents, nodeId)
+ if (!e) return undefined
+ return { kind: e.kind as 'approval' | 'question', ...(e.pendingId ? { pendingId: e.pendingId } : {}) }
+}
+
export function isEventUnresolved(nodeId: string, eventId: string): boolean {
for (const e of inboxEvents) {
if (e.id === eventId && e.nodeId === nodeId) return !e.resolved
diff --git a/src/core/relay-keys.test.ts b/src/core/relay-keys.test.ts
new file mode 100644
index 000000000..a30577761
--- /dev/null
+++ b/src/core/relay-keys.test.ts
@@ -0,0 +1,57 @@
+import { describe, it, expect } from 'vitest'
+import { parseRelayKeys, rawKeyBytes, tmuxKeyArgs } from './relay-keys'
+import { remoteSendKeyArgs } from './remote-ssh/control-master'
+
+describe('parseRelayKeys — a closed set, nothing else crosses', () => {
+ it('one key', () => {
+ expect(parseRelayKeys({ key: '1' })).toEqual([{ digit: '1' }])
+ expect(parseRelayKeys({ key: '9' })).toEqual([{ digit: '9' }])
+ expect(parseRelayKeys({ key: 'escape' })).toEqual([{ name: 'Escape' }])
+ expect(parseRelayKeys({ key: 'enter' })).toEqual([{ name: 'Enter' }])
+ })
+ it.each([['0'], ['10'], ['a'], ['Escape'], ['1;rm'], [''], [1], [null]])('refuses key %j', (key) => {
+ expect(parseRelayKeys({ key })).toBeNull()
+ })
+ it('a multi-select batch: distinct digits ascending, then Right, then Enter (the phone’s SSH sequence)', () => {
+ expect(parseRelayKeys({ digits: [3, 1, 3] })).toEqual([
+ { digit: '1' },
+ { digit: '3' },
+ { name: 'Right' },
+ { name: 'Enter' }
+ ])
+ })
+ it.each([[[]], [[0]], [[10]], [[1.5]], [['1']], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 1]], ['12']])(
+ 'refuses digits %j',
+ (digits) => {
+ expect(parseRelayKeys({ digits })).toBeNull()
+ }
+ )
+ it('refuses key and digits together', () => {
+ expect(parseRelayKeys({ key: '1', digits: [1] })).toBeNull()
+ })
+})
+
+describe('key encodings', () => {
+ it('tmux: a literal digit, or the key NAME', () => {
+ expect(tmuxKeyArgs({ digit: '2' })).toEqual(['-l', '2'])
+ expect(tmuxKeyArgs({ name: 'Escape' })).toEqual(['Escape'])
+ expect(tmuxKeyArgs({ name: 'Right' })).toEqual(['Right'])
+ })
+ it('raw (session host): the bytes the key sends', () => {
+ expect(rawKeyBytes({ digit: '1' })).toBe('1')
+ expect(rawKeyBytes({ name: 'Escape' })).toBe('\x1b')
+ expect(rawKeyBytes({ name: 'Enter' })).toBe('\r')
+ expect(rawKeyBytes({ name: 'Right' })).toBe('\x1b[C')
+ })
+ it('re-validates at the interpolation site', () => {
+ expect(() => tmuxKeyArgs({ digit: '1; rm -rf ~' })).toThrow()
+ expect(() => rawKeyBytes({ name: 'Space' as never })).toThrow()
+ })
+ it('the remote send-keys line names only the closed set', () => {
+ const conn = { host: 'box.test', user: 'u' }
+ const args = remoteSendKeyArgs(conn, '/tmp/cm', 'nt-n1', ['-l', '1'])
+ expect(args[args.length - 1]).toContain('tmux -L nodeterm-rmt send-keys -t nt-n1 -l 1')
+ expect(() => remoteSendKeyArgs(conn, '/tmp/cm', 'nt-n1', ['-l', '1;id'])).toThrow()
+ expect(() => remoteSendKeyArgs(conn, '/tmp/cm', 'nt n1', ['Enter'])).toThrow()
+ })
+})
diff --git a/src/core/relay-keys.ts b/src/core/relay-keys.ts
new file mode 100644
index 000000000..0ae61d696
--- /dev/null
+++ b/src/core/relay-keys.ts
@@ -0,0 +1,74 @@
+// The closed key set behind the phone's relay `agent.key` — the keyed half of the Inbox / push /
+// Live Activity answers (a picker digit, Escape = deny, a multi-select batch), which a relay-only
+// host (every Windows pairing: no direct SSH) had no way to receive.
+//
+// The phone used to deliver these itself, over SSH, as `tmux send-keys` lines. Over the relay it
+// names the KEYS and nothing else: digits 1–9, Escape, Enter, Right. No free text crosses — a key
+// that is not in this set is refused, so a forged payload cannot become a typed command. The
+// backend (tmux send-keys, the remote host's tmux, or a raw write into a session-host pane) is
+// `PtyManager.sendKeys`'s choice; this module only owns the set, its parsing, and its encodings.
+
+export type RelayKeyName = 'Escape' | 'Enter' | 'Right'
+export type RelayKey = { digit: string } | { name: RelayKeyName }
+
+/** One key per write, this far apart. Claude's picker is an Ink TUI that reads ONE stdin chunk as
+ * ONE string: `234` arriving together matches no binding and is dropped. The phone's own SSH path
+ * learned the same lesson (`InboxApproval.multiSelectKeyDelay`, 0.15 s). */
+export const RELAY_KEY_GAP_MS = 150
+
+/** At most this many digits in a multi-select batch (a picker never has more than nine options). */
+export const RELAY_KEY_MAX_DIGITS = 9
+
+const DIGIT = /^[1-9]$/
+
+/**
+ * `key: 'escape' | 'enter' | '1'..'9'` (one key), or `digits: number[]` (a multi-select submit:
+ * each distinct digit 1–9 in ascending order, then Right to the Submit tab, then Enter — the exact
+ * sequence the phone's SSH path types). `null` = refused. An empty selection is refused too: a
+ * Submit never presses Enter on an empty picker.
+ */
+export function parseRelayKeys(params: { key?: unknown; digits?: unknown }): RelayKey[] | null {
+ if (params.digits !== undefined) {
+ if (params.key !== undefined || !Array.isArray(params.digits)) return null
+ if (params.digits.length === 0 || params.digits.length > RELAY_KEY_MAX_DIGITS) return null
+ const set = new Set<number>()
+ for (const d of params.digits) {
+ if (typeof d !== 'number' || !Number.isInteger(d) || d < 1 || d > 9) return null
+ set.add(d)
+ }
+ return [
+ ...[...set].sort((a, b) => a - b).map((d) => ({ digit: String(d) })),
+ { name: 'Right' as const },
+ { name: 'Enter' as const }
+ ]
+ }
+ const key = params.key
+ if (typeof key !== 'string') return null
+ if (DIGIT.test(key)) return [{ digit: key }]
+ if (key === 'escape') return [{ name: 'Escape' }]
+ if (key === 'enter') return [{ name: 'Enter' }]
+ return null
+}
+
+/** Re-validated at the interpolation site (the `SAFE_SESSION_ID` rule): the set is closed. */
+function assertKey(key: RelayKey): void {
+ if ('digit' in key) {
+ if (!DIGIT.test(key.digit)) throw new Error('unsafe relay key')
+ } else if (key.name !== 'Escape' && key.name !== 'Enter' && key.name !== 'Right') {
+ throw new Error('unsafe relay key')
+ }
+}
+
+/** `send-keys` arguments after the target: `-l <d>` for a literal digit (no key-name lookup), the
+ * key NAME for the rest (so tmux sends the key, honoring the pane's cursor-key mode). */
+export function tmuxKeyArgs(key: RelayKey): string[] {
+ assertKey(key)
+ return 'digit' in key ? ['-l', key.digit] : [key.name]
+}
+
+/** The bytes a key is on a raw pane write (a session-host pane has no tmux to name keys). */
+export function rawKeyBytes(key: RelayKey): string {
+ assertKey(key)
+ if ('digit' in key) return key.digit
+ return key.name === 'Escape' ? '\x1b' : key.name === 'Enter' ? '\r' : '\x1b[C'
+}
diff --git a/src/core/relay-launch.test.ts b/src/core/relay-launch.test.ts
new file mode 100644
index 000000000..ac13fa1f0
--- /dev/null
+++ b/src/core/relay-launch.test.ts
@@ -0,0 +1,142 @@
+import { describe, it, expect } from 'vitest'
+import {
+ buildRelayLaunch,
+ isDialectNeutralCommand,
+ parseRelayLaunch,
+ relayLaunchDialect,
+ type RelayLaunchContext
+} from './relay-launch'
+import { assembleResumeCommand } from '../shared/agents/launch'
+import type { CustomAgent } from '../shared/types'
+
+const SID = '0f3c2a1e-5b7d-4c9a-8e21-3f4a5b6c7d8e'
+
+function ctx(over: Partial<RelayLaunchContext> = {}): RelayLaunchContext {
+ return {
+ customAgents: [],
+ claudeAutoSupported: true,
+ isKnownAccount: (id) => id === 'acct-1',
+ env: {},
+ ...over
+ }
+}
+
+describe('parseRelayLaunch — everything the phone sends is re-validated', () => {
+ it('keeps a well-formed request', () => {
+ expect(
+ parseRelayLaunch({ agentId: 'claude', sessionId: SID, permissionMode: 'plan', cwd: '/w', accountId: 'acct-1' })
+ ).toEqual({ agentId: 'claude', sessionId: SID, permissionMode: 'plan', cwd: '/w', accountId: 'acct-1' })
+ })
+ it('a missing / non-string / control-bearing agent id is no launch', () => {
+ expect(parseRelayLaunch({})).toBeNull()
+ expect(parseRelayLaunch({ agentId: 7 })).toBeNull()
+ expect(parseRelayLaunch({ agentId: 'claude\n; rm -rf ~' })).toBeNull()
+ expect(parseRelayLaunch('claude')).toBeNull()
+ expect(parseRelayLaunch(null)).toBeNull()
+ })
+ it('a forged session id is no launch at all — never silently a fresh session', () => {
+ expect(parseRelayLaunch({ agentId: 'claude', sessionId: 'x; curl evil' })).toBeNull()
+ expect(parseRelayLaunch({ agentId: 'claude', sessionId: '-rf' })).toBeNull()
+ expect(parseRelayLaunch({ agentId: 'claude', sessionId: 42 })).toBeNull()
+ })
+ it('a forged mode is dropped (the bare, safe command); a forged account is dropped', () => {
+ expect(parseRelayLaunch({ agentId: 'claude', permissionMode: 'constructor' })).toEqual({ agentId: 'claude' })
+ expect(parseRelayLaunch({ agentId: 'claude', accountId: '../../etc' })).toEqual({ agentId: 'claude' })
+ })
+})
+
+describe('relayLaunchDialect — read from the pane’s own foreground program', () => {
+ it.each([
+ ['zsh', 'posix'],
+ ['-bash', 'posix'],
+ ['pwsh', 'pwsh'],
+ ['pwsh.exe', 'pwsh'],
+ ['C:\\Program Files\\PowerShell\\7\\pwsh.exe', 'pwsh'],
+ ['powershell.exe', 'windows-powershell'],
+ ['cmd.exe', 'cmd'],
+ [null, 'posix']
+ ] as const)('%s → %s', (cmd, dialect) => {
+ expect(relayLaunchDialect(cmd)).toBe(dialect)
+ })
+})
+
+describe('buildRelayLaunch', () => {
+ it('on a POSIX pane it is the renderer’s cold-restore line, byte for byte', async () => {
+ const plan = await buildRelayLaunch({ agentId: 'claude', sessionId: SID, permissionMode: 'auto' }, 'posix', ctx())
+ const expected = assembleResumeCommand({ agentId: 'claude', sessionId: SID, permissionMode: 'auto', approvalCaps: {} }, {})
+ expect(plan).toEqual({ kind: 'type', command: expected.command })
+ expect(plan).toEqual({ kind: 'type', command: `claude --resume ${SID} --permission-mode auto` })
+ })
+ it('claude’s version gate degrades auto to no flag; other agents are not gated by it', async () => {
+ expect(
+ await buildRelayLaunch({ agentId: 'claude', permissionMode: 'auto' }, 'posix', ctx({ claudeAutoSupported: false }))
+ ).toEqual({ kind: 'type', command: 'claude' })
+ const grok = await buildRelayLaunch({ agentId: 'grok', permissionMode: 'auto' }, 'posix', ctx({ claudeAutoSupported: false }))
+ expect(grok?.kind).toBe('type')
+ })
+ it('an agent this machine does not know is no launch', async () => {
+ expect(await buildRelayLaunch({ agentId: 'custom:nope' }, 'posix', ctx())).toBeNull()
+ })
+ it.each(['pwsh', 'windows-powershell', 'cmd'] as const)(
+ 'on a %s pane (no trusted resolver) a neutral line is typed, and it carries no POSIX syntax',
+ async (dialect) => {
+ const plan = await buildRelayLaunch(
+ { agentId: 'claude', sessionId: SID, permissionMode: 'acceptEdits', accountId: 'acct-1', cwd: 'C:\\w' },
+ dialect,
+ ctx()
+ )
+ expect(plan?.kind).toBe('type')
+ const text = plan && plan.kind === 'type' ? plan.command : ''
+ expect(text).toBe(`claude --resume ${SID} --permission-mode acceptEdits`)
+ // cwd and account ride the SPAWN options, never the typed line.
+ for (const posixOnly of ['2>/dev/null', 'env -u', ';', 'cd ', 'CLAUDE_CONFIG_DIR', "'"]) {
+ expect(text).not.toContain(posixOnly)
+ }
+ }
+ )
+ it('a Windows pane refuses a line that is not dialect-neutral (quoted custom args)', async () => {
+ const custom: CustomAgent = { id: 'custom:a', label: 'A', launchCmd: 'claude', baseAgent: 'claude', args: '--x "two words"' }
+ const posix = await buildRelayLaunch({ agentId: 'custom:a' }, 'posix', ctx({ customAgents: [custom] }))
+ expect(posix?.kind).toBe('type')
+ expect(await buildRelayLaunch({ agentId: 'custom:a' }, 'pwsh', ctx({ customAgents: [custom] }))).toBeNull()
+ })
+ it('an unset ${env:…} reference is no launch (never a mangled line)', async () => {
+ const custom: CustomAgent = { id: 'custom:b', label: 'B', launchCmd: '${env:NT_MISSING_BIN}' }
+ expect(await buildRelayLaunch({ agentId: 'custom:b' }, 'posix', ctx({ customAgents: [custom] }))).toBeNull()
+ })
+ it('with the trusted Windows resolver wired, a Windows pane gets the planner’s execute plan', async () => {
+ const plan = await buildRelayLaunch(
+ { agentId: 'claude', sessionId: SID, permissionMode: 'plan' },
+ 'pwsh',
+ ctx({ resolveExecutableKind: async () => ({ kind: 'native', executable: 'C:\\tools\\claude.exe' }) })
+ )
+ expect(plan?.kind).toBe('execute')
+ const cmd = plan && plan.kind === 'execute' ? plan.plan.command : ''
+ expect(cmd).toContain("Start-Process -FilePath 'C:\\tools\\claude.exe'")
+ expect(cmd).toContain(`--resume ${SID}`)
+ expect(cmd).not.toContain('2>/dev/null')
+ })
+ it('a resolver that cannot find the agent is no launch', async () => {
+ expect(
+ await buildRelayLaunch({ agentId: 'claude' }, 'cmd', ctx({ resolveExecutableKind: async () => null }))
+ ).toBeNull()
+ })
+})
+
+describe('isDialectNeutralCommand', () => {
+ it.each([
+ ['claude', true],
+ [`claude --resume ${SID} --permission-mode auto`, true],
+ ['codex resume abc --ask-for-approval on-request', true],
+ ["claude 'x'", false],
+ ['claude; rm', false],
+ ['claude && x', false],
+ ['claude $HOME', false],
+ ['claude %PATH%', false],
+ ['claude --x', false],
+ ['--version', false],
+ ['', false]
+ ])('%j → %s', (cmd, ok) => {
+ expect(isDialectNeutralCommand(cmd)).toBe(ok)
+ })
+})
diff --git a/src/core/relay-launch.ts b/src/core/relay-launch.ts
new file mode 100644
index 000000000..beb33eceb
--- /dev/null
+++ b/src/core/relay-launch.ts
@@ -0,0 +1,211 @@
+// The host-owned agent launch behind the phone's relay `pty.attach { launch }`.
+//
+// The phone used to cold-restore an agent session by TYPING a shell line into the fresh pane after
+// `pty.attach` answered `fresh: true` — `cd '<cwd>' 2>/dev/null; <cmd>`, and for a managed account
+// `env -u … CLAUDE_CONFIG_DIR=… claude --resume …`. That is POSIX syntax. On a Windows host the
+// fresh pane is pwsh / Windows PowerShell / cmd (the session host's shell resolution), where
+// `2>/dev/null`, `env -u` and `VAR=x cmd` are errors and cmd does not even understand `'` or `;`:
+// the agent failed to start, or started under the wrong account in the wrong folder.
+//
+// So the phone now sends WHAT it wants (agent, session id, mode, cwd, account) and the host decides
+// HOW. Three rules this module exists to hold:
+// - Everything the phone sends is re-validated here (agent id against this machine's registry,
+// session id against SAFE_SESSION_ID, mode against the permission-mode table, account against
+// this machine's account lists). A field that fails is dropped or refuses the whole launch;
+// nothing is ever interpolated unchecked.
+// - cwd and account are NOT typed: they ride the spawn options (`prepareRelayAttach`), where the
+// one env builder (`buildPtyEnv`) sets CLAUDE_CONFIG_DIR and strips AUTH_ENV_STRIP on every
+// backend — so no `cd` and no `env -u` is ever needed.
+// - The command is built by the builders the desktop already uses: on a POSIX pane exactly the
+// line the renderer's cold restore types (`assembleResumeCommand`), on a Windows pane the
+// trusted Windows planner (`prepareAgentLaunch`) when the host has wired its executable
+// resolver. Until then the POSIX-assembled line is used on Windows ONLY when it is
+// dialect-neutral (plain words, which pwsh, Windows PowerShell and cmd all parse identically);
+// anything else is no launch at all, never a guess.
+//
+// Pure: no tmux, no pty, no settings store. `PtyManager` supplies the pane facts and the context.
+
+import type { CustomAgent } from '../shared/types'
+import {
+ AGENT_CONFIG,
+ canResume,
+ capabilityAgentId,
+ gatePermissionMode,
+ hasPermissionMode,
+ isPermissionMode,
+ type AgentId,
+ type AgentPermissionMode
+} from '../shared/agents/config'
+import { assembleResumeCommand } from '../shared/agents/launch'
+import { SAFE_SESSION_ID } from '../shared/session-id'
+import { isSafeAccountId } from '../shared/codex-account'
+import {
+ prepareAgentLaunch,
+ type AgentLaunchDialect,
+ type AgentLaunchExecutableKindResolver,
+ type PreparedAgentLaunch
+} from './agent-launch'
+
+/** What a phone may ask the host to launch in a session the attach just CREATED. */
+export interface RelayLaunchRequest {
+ agentId: AgentId
+ /** Resume this provider session (SAFE_SESSION_ID); absent = a fresh launch with no prompt. */
+ sessionId?: string
+ /** Where an UNRECORDED node's session starts. Jailed by the caller (host-service's roots). */
+ cwd?: string
+ /** Managed account an UNRECORDED node runs under; dropped unless this machine knows it. */
+ accountId?: string
+ permissionMode?: AgentPermissionMode
+}
+
+/** Host-authoritative facts the launch is built from. Never populated from anything the phone sends. */
+export interface RelayLaunchContext {
+ customAgents: readonly CustomAgent[]
+ /** Can THIS host's claude take `--permission-mode auto`? (The claude-only version gate.) */
+ claudeAutoSupported: boolean
+ codexApprovalValues?: readonly string[] | null
+ codexNoDaemon?: boolean | null
+ /** Is `accountId` a usable LOCAL managed account (claude or codex) on this machine? */
+ isKnownAccount(accountId: string): 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
+ * dialect-neutral fallback below is the only Windows launch. */
+ resolveExecutableKind?: AgentLaunchExecutableKindResolver
+ windowsPowerShellPath?: string
+}
+
+/** Typed into the pane (`sendText`), or executed through the session host's exactly-once ledger. */
+export type RelayLaunchPlan =
+ | { kind: 'type'; command: string }
+ | { kind: 'execute'; plan: PreparedAgentLaunch }
+
+const MAX_FIELD = 4096
+// eslint-disable-next-line no-control-regex -- refusing control chars is the point
+const CONTROL = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/
+
+function cleanString(v: unknown, max = MAX_FIELD): string | undefined {
+ return typeof v === 'string' && v.length > 0 && v.length <= max && !CONTROL.test(v) ? v : undefined
+}
+
+/**
+ * Shape-check the wire's `launch` object. `null` = no launch: not an object, no usable agent id,
+ * or a session id that is present but malformed (a forged id must not silently become a FRESH
+ * session either — the phone asked to resume something specific). A malformed mode is dropped
+ * (= no flag, the bare safe command); a malformed cwd/account is dropped (= the record / system
+ * default). Registry membership is checked later, against the context.
+ */
+export function parseRelayLaunch(raw: unknown): RelayLaunchRequest | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
+ const r = raw as Record<string, unknown>
+ const agentId = cleanString(r.agentId, 128)
+ if (!agentId) return null
+ const out: RelayLaunchRequest = { agentId }
+ if (r.sessionId !== undefined && r.sessionId !== null && r.sessionId !== '') {
+ if (typeof r.sessionId !== 'string' || !SAFE_SESSION_ID.test(r.sessionId)) return null
+ out.sessionId = r.sessionId
+ }
+ const cwd = cleanString(r.cwd)
+ if (cwd) out.cwd = cwd
+ const accountId = cleanString(r.accountId, 128)
+ if (accountId && isSafeAccountId(accountId)) out.accountId = accountId
+ if (isPermissionMode(r.permissionMode)) out.permissionMode = r.permissionMode
+ return out
+}
+
+/** Is this agent id one THIS machine can launch (a builtin, or one of its own custom agents)? */
+export function relayLaunchAgentKnown(agentId: AgentId, ctx: Pick<RelayLaunchContext, 'customAgents'>): boolean {
+ return Object.hasOwn(AGENT_CONFIG, agentId) || ctx.customAgents.some((a) => a.id === agentId)
+}
+
+/** The parser the pane's foreground program speaks, from its command name (`paneCommand`). */
+export function relayLaunchDialect(paneCommand: string | null | undefined): AgentLaunchDialect {
+ const base = (paneCommand ?? '').split(/[\\/]/).pop()?.toLowerCase().replace(/\.exe$/, '')
+ if (base === 'pwsh') return 'pwsh'
+ if (base === 'powershell') return 'windows-powershell'
+ if (base === 'cmd') return 'cmd'
+ return 'posix'
+}
+
+/**
+ * A line every shell we spawn parses the SAME way: words of `[A-Za-z0-9._:/=@+-]`, single spaces.
+ * No quote, `;`, `&`, `|`, `<`, `>`, `$`, backtick, `%`, `^`, `!`, parenthesis or `~` — each of
+ * which means something different (or nothing) in POSIX sh, pwsh and cmd. `claude --resume <id>
+ * --permission-mode auto` qualifies; a custom agent whose args were single-quoted does not.
+ */
+export function isDialectNeutralCommand(command: string): boolean {
+ return /^[A-Za-z0-9._:/=@+-]+( [A-Za-z0-9._:/=@+-]+)*$/.test(command) && !/^-/.test(command)
+}
+
+/** 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.permissionMode
+ if (!mode || !hasPermissionMode(capabilityAgentId(req.agentId))) return undefined
+ // The gate is CLAUDE's alone (CLAUDE.md "Version gate"): it is fed by a `claude --version` probe.
+ return req.agentId === 'claude' ? gatePermissionMode(mode, ctx.claudeAutoSupported) : mode
+}
+
+/**
+ * Build the launch for a pane whose parser is `dialect`. `null` = no launch (unknown agent, an env
+ * reference that would type a mangled line, or a Windows pane with no trusted way to say it).
+ */
+export async function buildRelayLaunch(
+ req: RelayLaunchRequest,
+ dialect: AgentLaunchDialect,
+ ctx: RelayLaunchContext
+): Promise<RelayLaunchPlan | null> {
+ if (!relayLaunchAgentKnown(req.agentId, ctx)) return null
+ const customAgent = ctx.customAgents.find((a) => a.id === req.agentId)
+ const mode = effectiveMode(req, ctx)
+
+ if (dialect !== 'posix' && ctx.resolveExecutableKind) {
+ // Resume needs a builtin grammar in the trusted planner; a custom agent starts fresh.
+ const builtin = Object.hasOwn(AGENT_CONFIG, req.agentId)
+ const resume = !!req.sessionId && builtin && canResume(req.agentId)
+ try {
+ const plan = await prepareAgentLaunch(
+ resume
+ ? { kind: 'agent', action: 'resume', agentId: req.agentId, sessionId: req.sessionId as string, ...(mode ? { permissionMode: mode } : {}) }
+ : { kind: 'agent', action: 'start', agentId: req.agentId, ...(mode ? { permissionMode: mode } : {}) },
+ dialect,
+ {
+ expectedAgentId: req.agentId,
+ ...(customAgent
+ ? {
+ customAgent: {
+ id: customAgent.id,
+ launchCmd: customAgent.launchCmd,
+ promptInjectionMode: customAgent.promptInjectionMode ?? 'argv'
+ }
+ }
+ : {}),
+ sharedIdentityAvailable: false,
+ resolveExecutableKind: ctx.resolveExecutableKind,
+ windowsPowerShellPath: ctx.windowsPowerShellPath,
+ codexApprovalValues: ctx.codexApprovalValues,
+ codexNoDaemon: ctx.codexNoDaemon
+ }
+ )
+ return { kind: 'execute', plan }
+ } catch {
+ return null
+ }
+ }
+
+ // The renderer's cold-restore line, byte for byte (bare program: no shared-identity launcher and
+ // no launch-command override — the phone's own typed line never had either).
+ const { command, missingEnv } = assembleResumeCommand(
+ {
+ agentId: req.agentId,
+ customAgent,
+ sessionId: req.sessionId,
+ permissionMode: mode,
+ approvalCaps: { codexApprovalValues: ctx.codexApprovalValues, codexNoDaemon: ctx.codexNoDaemon }
+ },
+ ctx.env
+ )
+ // Never type a knowingly mangled line (an unset ${env:…} expanded to nothing).
+ if (missingEnv.length || !command.trim()) return null
+ if (dialect === 'posix') return { kind: 'type', command }
+ return isDialectNeutralCommand(command) ? { kind: 'type', command } : null
+}
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index 4f7182639..744782057 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -653,6 +653,26 @@ export function remotePaneCommandArgs(conn: SshConnection, controlPath: string,
)
}
+/**
+ * One closed-set key into a remote pane (`PtyManager.sendKeys`, the phone's relay `agent.key`).
+ * `keyArgs` comes from `relay-keys.tmuxKeyArgs` — a digit 1–9 after `-l`, or a fixed key name —
+ * and is re-checked here before it lands on a remote command line.
+ */
+export function remoteSendKeyArgs(
+ conn: SshConnection,
+ controlPath: string,
+ sessionId: string,
+ keyArgs: readonly string[]
+): string[] {
+ const safe = keyArgs.every((a) => /^(-l|[1-9]|Escape|Enter|Right)$/.test(a))
+ if (!safe || !/^[A-Za-z0-9._-]+$/.test(sessionId)) throw new Error('unsafe remote send-keys')
+ return childArgs(
+ conn,
+ controlPath,
+ tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} send-keys -t ${sessionId} ${keyArgs.join(' ')}`)
+ )
+}
+
/** The remote counterpart of `PtyManager.paneCwd`'s local `display-message` path. */
export function remotePaneCwdArgs(conn: SshConnection, controlPath: string, sessionId: string): string[] {
return childArgs(
diff --git a/src/core/remote/host-fs-rpc.test.ts b/src/core/remote/host-fs-rpc.test.ts
new file mode 100644
index 000000000..08b0071d7
--- /dev/null
+++ b/src/core/remote/host-fs-rpc.test.ts
@@ -0,0 +1,99 @@
+import { describe, it, expect } from 'vitest'
+import { browseHostDirectory, isWithinRootsFor, type BrowseFs } from './host-fs-rpc'
+
+describe('isWithinRootsFor — the relay fs jail, in the host’s own path dialect', () => {
+ it('POSIX keeps the historical rule', () => {
+ expect(isWithinRootsFor('/work/a/b', ['/work'], 'linux')).toBe(true)
+ expect(isWithinRootsFor('/work', ['/work'], 'linux')).toBe(true)
+ expect(isWithinRootsFor('/work/../etc/passwd', ['/work'], 'linux')).toBe(false)
+ expect(isWithinRootsFor('/workshop', ['/work'], 'linux')).toBe(false)
+ // Case-SENSITIVE on POSIX.
+ expect(isWithinRootsFor('/Work/a', ['/work'], 'darwin')).toBe(false)
+ expect(isWithinRootsFor('', ['/work'], 'linux')).toBe(false)
+ })
+ it('win32: case-insensitive, either separator', () => {
+ const roots = ['C:\\Users\\me\\repo']
+ expect(isWithinRootsFor('c:\\users\\ME\\repo\\src', roots, 'win32')).toBe(true)
+ expect(isWithinRootsFor('C:/Users/me/repo/src/x.ts', roots, 'win32')).toBe(true)
+ expect(isWithinRootsFor('C:\\Users\\me\\repo', roots, 'win32')).toBe(true)
+ })
+ it('win32: `..` traversal, another drive, a sibling prefix are outside', () => {
+ const roots = ['C:\\Users\\me\\repo']
+ expect(isWithinRootsFor('C:\\Users\\me\\repo\\..\\secrets', roots, 'win32')).toBe(false)
+ expect(isWithinRootsFor('D:\\Users\\me\\repo\\x', roots, 'win32')).toBe(false)
+ expect(isWithinRootsFor('C:\\Users\\me\\repository', roots, 'win32')).toBe(false)
+ })
+ it('win32: UNC, device and drive-relative paths are refused whole', () => {
+ const roots = ['C:\\Users\\me\\repo']
+ expect(isWithinRootsFor('\\\\server\\share\\repo', roots, 'win32')).toBe(false)
+ expect(isWithinRootsFor('//server/share', roots, 'win32')).toBe(false)
+ expect(isWithinRootsFor('\\\\?\\C:\\Users\\me\\repo\\x', roots, 'win32')).toBe(false)
+ expect(isWithinRootsFor('\\Users\\me\\repo\\x', roots, 'win32')).toBe(false)
+ expect(isWithinRootsFor('C:Users\\me\\repo', roots, 'win32')).toBe(false)
+ // …and a UNC ROOT never jails anything in.
+ expect(isWithinRootsFor('\\\\server\\share\\x', ['\\\\server\\share'], 'win32')).toBe(false)
+ })
+})
+
+function fakeFs(tree: Record<string, Array<{ name: string; dir: boolean }>>, gits: string[] = []): BrowseFs {
+ return {
+ readdir: async (d) => {
+ const list = tree[d]
+ if (!list) throw new Error('ENOENT')
+ return list.map((e) => ({ name: e.name, isDirectory: () => e.dir }))
+ },
+ exists: async (p) => gits.includes(p)
+ }
+}
+
+describe('browseHostDirectory — directories only, jailed to home', () => {
+ const home = 'C:\\Users\\me'
+ const fs = fakeFs(
+ {
+ 'C:\\Users\\me': [
+ { name: 'repo', dir: true },
+ { name: '.ssh', dir: true },
+ { name: 'notes.txt', dir: false },
+ { name: 'Apps', dir: true }
+ ],
+ 'C:\\Users\\me\\repo': []
+ },
+ ['C:\\Users\\me\\repo\\.git']
+ )
+
+ it('lists the home by default: directories only, hidden skipped, git marked, no parent past home', async () => {
+ const res = await browseHostDirectory(undefined, { platform: 'win32', home, fs })
+ expect(res).toEqual({
+ path: 'C:\\Users\\me',
+ parent: null,
+ truncated: false,
+ entries: [
+ { name: 'Apps', dir: true, git: false },
+ { name: 'repo', dir: true, git: true }
+ ]
+ })
+ })
+ it('a child reports its parent; separators normalize to win32', async () => {
+ const res = await browseHostDirectory('C:/Users/me/repo', { platform: 'win32', home, fs })
+ expect(res?.path).toBe('C:\\Users\\me\\repo')
+ expect(res?.parent).toBe('C:\\Users\\me')
+ })
+ it('the home jail is case-insensitive on win32 (NTFS)', async () => {
+ const res = await browseHostDirectory('c:\\users\\ME', { platform: 'win32', home, fs: fakeFs({ 'c:\\users\\ME': [] }) })
+ expect(res?.entries).toEqual([])
+ })
+ it('refuses outside home, another drive, UNC, traversal and relative paths', async () => {
+ for (const p of ['C:\\Windows', 'D:\\Users\\me', '\\\\srv\\share', 'C:\\Users\\me\\..\\other', 'repo']) {
+ expect(await browseHostDirectory(p, { platform: 'win32', home, fs })).toBeNull()
+ }
+ })
+ it('caps the listing', async () => {
+ const many = fakeFs({ '/home/u': Array.from({ length: 7 }, (_, i) => ({ name: `d${i}`, dir: true })) })
+ const res = await browseHostDirectory('/home/u', { platform: 'linux', home: '/home/u', fs: many, maxEntries: 3 })
+ expect(res?.entries.map((e) => e.name)).toEqual(['d0', 'd1', 'd2'])
+ expect(res?.truncated).toBe(true)
+ })
+ it('an unreadable directory is null, not an empty listing', async () => {
+ expect(await browseHostDirectory('/home/u/gone', { platform: 'linux', home: '/home/u', fs: fakeFs({}) })).toBeNull()
+ })
+})
diff --git a/src/core/remote/host-fs-rpc.ts b/src/core/remote/host-fs-rpc.ts
new file mode 100644
index 000000000..9611cfffe
--- /dev/null
+++ b/src/core/remote/host-fs-rpc.ts
@@ -0,0 +1,120 @@
+// The path jail behind the relay host's filesystem verbs (`fs.*`, `git.*`, `fs.browse`), and the
+// folder browser the phone's "new project" sheet walks when the host has no direct SSH (every
+// Windows pairing is relay-only).
+//
+// Pure over an injected platform + fs so the Windows rules are provable on any CI host:
+// - containment uses the FILESYSTEM-OWNING host's path dialect (`path.win32` on a Windows host,
+// `path.posix` elsewhere), never the dialect of whatever machine runs the test;
+// - on win32 the comparison is case-insensitive (NTFS is) and accepts both separators — a
+// case-sensitive `startsWith` would refuse `c:\Users\me\repo` against root `C:\Users\me`, and a
+// looser rule would not be a jail;
+// - a UNC / device path (`\\server\share`, `\\?\C:\…`) is refused whole on win32: it can name
+// another machine, and resolving it against a drive-letter root is not containment;
+// - `..` is normalized away by `resolve`, so `root/../../etc` is outside, as it always was.
+
+import path from 'path'
+
+export interface HostPathDialect {
+ platform: NodeJS.Platform
+}
+
+function pathFor(platform: NodeJS.Platform): typeof path.posix {
+ return platform === 'win32' ? path.win32 : path.posix
+}
+
+/** A Windows UNC or device-namespace path (`\\server\share`, `//server/share`, `\\?\…`, `\\.\…`). */
+export function isWindowsUncOrDevicePath(p: string): boolean {
+ return /^[\\/]{2}/.test(p)
+}
+
+/**
+ * Lexically resolve `target` and confirm it sits inside one of `roots` (or equals a root), in the
+ * host's own path dialect. Symlinks inside a shared root are not chased (the roots are the user's
+ * own project directories). On win32 only drive-absolute paths qualify.
+ */
+export function isWithinRootsFor(target: string, roots: readonly string[], platform: NodeJS.Platform): boolean {
+ if (!target) return false
+ const p = pathFor(platform)
+ if (platform === 'win32') {
+ if (isWindowsUncOrDevicePath(target)) return false
+ // Only a drive-absolute path: `\\foo` and `C:foo` resolve against the PROCESS's current drive
+ // / directory, which is not something a remote client may pick.
+ if (!/^[A-Za-z]:[\\/]/.test(target)) return false
+ }
+ const fold = (s: string): string => (platform === 'win32' ? s.toLowerCase() : s)
+ // POSIX keeps the historical rule byte for byte (`path.resolve`, root + separator prefix).
+ const resolved = fold(p.resolve(target))
+ for (const root of roots) {
+ if (!root) continue
+ if (platform === 'win32' && (isWindowsUncOrDevicePath(root) || !/^[A-Za-z]:[\\/]/.test(root))) continue
+ const r = fold(p.resolve(root))
+ if (resolved === r || resolved.startsWith(r + p.sep)) return true
+ }
+ return false
+}
+
+export interface BrowseEntry {
+ name: string
+ /** Always true — the browser lists directories only. Carried so the phone can share its row model. */
+ dir: true
+ /** The directory holds a `.git` (a likely project root). */
+ git: boolean
+}
+
+export interface BrowseFs {
+ /** Directory entries with their types (`fs.promises.readdir(p, {withFileTypes:true})`). */
+ readdir(dir: string): Promise<Array<{ name: string; isDirectory(): boolean }>>
+ /** Does this path exist? (For the `.git` marker.) */
+ exists(p: string): Promise<boolean>
+}
+
+/** At most this many directories per listing: a home directory can hold thousands. */
+export const BROWSE_MAX_ENTRIES = 500
+
+/**
+ * `fs.browse { path? }`: list the DIRECTORIES of `target` (default: the host's home), jailed to
+ * that home. `null` = refused (outside home, UNC/other drive on win32, relative) or unreadable — the
+ * phone shows "can't open this folder", never another machine's tree. Hidden (`.`-prefixed)
+ * directories are skipped; the listing is sorted and capped at `BROWSE_MAX_ENTRIES` (`truncated`).
+ */
+export async function browseHostDirectory(
+ target: string | undefined,
+ opts: { platform: NodeJS.Platform; home: string; fs: BrowseFs; maxEntries?: number }
+): Promise<{ path: string; parent: string | null; entries: BrowseEntry[]; truncated: boolean } | null> {
+ const p = pathFor(opts.platform)
+ const home = opts.home
+ if (!home || !p.isAbsolute(home)) return null
+ const want = target && target.length > 0 ? target : home
+ if (!p.isAbsolute(want)) return null
+ if (!isWithinRootsFor(want, [home], opts.platform)) return null
+ const dir = p.resolve(want)
+ let raw: Array<{ name: string; isDirectory(): boolean }>
+ try {
+ raw = await opts.fs.readdir(dir)
+ } catch {
+ return null
+ }
+ const max = opts.maxEntries ?? BROWSE_MAX_ENTRIES
+ const dirs = raw
+ .filter((e) => {
+ try {
+ return e.isDirectory() && !e.name.startsWith('.')
+ } catch {
+ return false
+ }
+ })
+ .map((e) => e.name)
+ .sort((a, b) => a.localeCompare(b))
+ const truncated = dirs.length > max
+ const kept = dirs.slice(0, max)
+ const entries = await Promise.all(
+ kept.map(async (name) => ({
+ name,
+ dir: true as const,
+ git: await opts.fs.exists(p.join(dir, name, '.git')).catch(() => false)
+ }))
+ )
+ const parentDir = p.dirname(dir)
+ const parent = parentDir !== dir && isWithinRootsFor(parentDir, [home], opts.platform) ? parentDir : null
+ return { path: dir, parent, entries, truncated }
+}