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): phone relay parity for relay-only hosts
review2d724769ab1e
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 0e7282b15..782463ff4 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -40,6 +40,7 @@ import {remoteTmuxWatcherArgs,remoteWindowSizeArgs,remotePaneCommandArgs,+ remoteSendKeyArgs,remotePaneCwdArgs,remoteSessionAgeArgs,parseSessionAge,@@ -145,7 +146,7 @@ import { effectiveSize, type PtySize } from './pty-size'import { machOArch, archMismatch } from './macho-arch'import { writeScrollback, readScrollback, deleteScrollback } from './scrollback-store'import { snapshotDue } from './scrollback-cadence'-import { createHash } from 'node:crypto'+import { createHash, randomUUID } from 'node:crypto'import { claudeConfigDirFor } from './claude-config-dir'import { envPathKey, findExecutableSync, findInPathString, resolveShellPath, shellPathNow } from './exec-path'import {@@ -195,7 +196,7 @@ import {stageRemoteSessionEnv} from './remote-ssh/session-env'import { foregroundProcessGroup, parsePaneProcess } from './pane-process'-import { isShellCommand } from '../shared/agents/pane'+import { isLaunchShell, isShellCommand } from '../shared/agents/pane'// Third persistence backend, selected when no local tmux was found (primarily Windows, where// tmux does not exist at all) — see docs/windows-session-host.md. Deliberately a thin, separate// module rather than inline here: this is the one narrow seam this file needed to grow for a@@ -213,11 +214,15 @@ import {sessionHostMessageEnvelope,sessionHostSendKeys,sessionHostSupported,+ sessionHostMouseTracking,+ sessionHostExecuteLaunch,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'+import { buildRelayLaunch, relayLaunchAgentKnown, relayLaunchDialect, 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// kills the tmux server) can still replay recent output on cold restart. A final snapshot also@@ -896,10 +901,19 @@ export type RelayAttachPrep =remote: boolean/** Does the session exist RIGHT NOW (fail-safe toward "exists")? Ask before `attach`. */sessionExists(): Promise<boolean>- /** The current visible screen, '' when there is none. */+ /** The current visible screen, '' when there is none. For a `scroll: 'local'` stream this is+ * the emulator's FULL buffer instead, so the phone holds the history it will scroll itself. */snapshot(): Promise<string>/** Spawn the relay-served client; rejects when nothing could be started. */attach(sinks: DetachedSinks): Promise<string>+ /** Who scrolls this stream's history: `host` = a tmux behind the pty (the wheel drives its+ * copy-mode), `local` = no tmux in front (session host / plain shell) — the viewer's own+ * emulator holds the history. See `scrollRoute`. */+ scroll: 'host' | 'local'+ /** Present only when the attach was asked to launch an agent AND this machine may: run it+ * once, after `attach`, and only when `sessionExists` said the session was NOT there.+ * Resolves true when the launch line was delivered. See `relay-launch.ts`. */+ launch?: () => Promise<boolean>}export interface DetachedSinks {@@ -1173,6 +1187,13 @@ export class PtyManager {private remoteNodeOwner: RemoteNodeOwnerResolver | null = null/** Machine-local records the relay host's attach is decided from — see `setRelayNodeResolver`. */private relayNodes: RelayNodeResolver | null = null+ /** Host-authoritative launch facts for a phone's `pty.attach { launch }` (see relay-launch.ts).+ * Null — the Server Edition, which has no relay host, and every test that does not wire one —+ * means no relay launch is ever performed. */+ private relayLaunchContext: (() => RelayLaunchContext) | null = null+ /** Node ids a relay launch was delivered to recently: two phones attaching in the same instant+ * can both see "fresh", and only one of them may type. */+ private relayLaunched = new Set<string>()/** ONE shared snapshot interval for all persisted sessions — a per-session interval spawned* one tmux/ssh capture subprocess per session per tick, forever, even for idle terminals. */private snapshotTimer: ReturnType<typeof setInterval> | null = null@@ -3372,6 +3393,12 @@ export class PtyManager {this.relayNodes = resolve}+ /** Wire the host-authoritative facts a phone's relay launch is built from (main: settings, CLI+ * probes, account lists). Absent ⇒ `prepareRelayAttach` never offers a `launch`. */+ setRelayLaunchContext(provider: (() => RelayLaunchContext) | null): void {+ this.relayLaunchContext = provider+ }+/*** Prepare a relay-served attach to the session for `nodeId` (the phone's `pty.attach`).*@@ -3393,7 +3420,7 @@ export class PtyManager {async prepareRelayAttach(nodeId: string,size: { cols: number; rows: number },- hint: { projectId?: string } = {}+ hint: { projectId?: string; launch?: RelayLaunchRequest } = {}): Promise<RelayAttachPrep> {const resolver = this.relayNodesconst placements = resolver?.placements(nodeId) ?? []@@ -3430,6 +3457,7 @@ export class PtyManager {cols: size.cols,rows: size.rows}+ const launch = plan.kind === 'local' ? this.relayLaunchFor(hint.launch, plan.projectId, options) : undefinedconst refused = this.spawnRefusal(options)if (refused) {return {@@ -3472,6 +3500,8 @@ export class PtyManager {return {kind: 'ready',remote: true,+ // A remote node always runs inside the host's tmux, which owns its history.+ scroll: 'host',sessionExists: async () =>(await this.remoteSessionVerdict(sshRemote, name).catch(() => 'unknown' as const)) !== 'absent',snapshot: async () => {@@ -3491,11 +3521,14 @@ export class PtyManager {attach: (sinks) => this.spawnRelayRemote(options, sinks)}}+ const scroll = this.relayScrollOwner(nodeId)return {kind: 'ready',remote: false,+ scroll,sessionExists: () => this.sessionExists(nodeId),- snapshot: () => this.captureSnapshot(nodeId),+ snapshot: () => (scroll === 'local' ? this.relayLocalSnapshot(nodeId) : this.captureSnapshot(nodeId)),+ ...(launch ? { launch: () => this.deliverRelayLaunch(nodeId, launch) } : {}),attach: async (sinks) => {await resolveShellPath()const overrides = await this.projectSpawnOverrides(options)@@ -3533,6 +3566,167 @@ export class PtyManager {return sessionId}+ /**+ * Decide whether a phone's launch request may run for this LOCAL attach, and fold its cwd /+ * account / agent into the spawn options when the node is UNRECORDED (a session the phone is+ * starting before registering it) — so the one env builder applies them and nothing is typed.+ * A recorded node keeps its own records: the launch must name the agent the record names, and+ * the phone cannot move it or rebind its account. `undefined` = no launch.+ */+ private relayLaunchFor(+ req: RelayLaunchRequest | undefined,+ recordedProjectId: string | undefined,+ options: PtyCreateOptions+ ): RelayLaunchRequest | undefined {+ const ctxFn = this.relayLaunchContext+ if (!req || !ctxFn) return undefined+ let ctx: RelayLaunchContext+ try {+ ctx = ctxFn()+ } catch {+ return undefined+ }+ if (!relayLaunchAgentKnown(req.agentId, ctx)) return undefined+ if (recordedProjectId) {+ if (options.agentId !== req.agentId) return undefined+ return { agentId: req.agentId, sessionId: req.sessionId, permissionMode: req.permissionMode }+ }+ // Unrecorded: the phone's profile (already jailed for cwd by the relay host) becomes the+ // spawn profile. An account this machine does not know is dropped (system default), never+ // trusted as a path component.+ options.agentId = req.agentId+ if (req.cwd) options.cwd = req.cwd+ if (req.accountId && ctx.isKnownAccount(req.accountId)) options.accountId = req.accountId+ return req+ }++ /** 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++ /**+ * Deliver a relay launch into the session the attach just created: wait until a SHELL owns the+ * pane (a fresh tmux session is created by the attach's own client, asynchronously), read which+ * parser it is from that same answer, build the line for it, and deliver it exactly once.+ */+ private async deliverRelayLaunch(nodeId: string, req: RelayLaunchRequest): Promise<boolean> {+ const ctxFn = this.relayLaunchContext+ if (!ctxFn || this.relayLaunched.has(nodeId)) return false+ this.relayLaunched.add(nodeId)+ const forget = setTimeout(() => this.relayLaunched.delete(nodeId), 60_000)+ forget.unref?.()+ try {+ const deadline = Date.now() + PtyManager.RELAY_LAUNCH_SHELL_WAIT_MS+ let pane: string | null = null+ for (;;) {+ pane = await this.paneCommand(nodeId).catch(() => null)+ if (isLaunchShell(pane)) break+ if (Date.now() >= deadline) return false+ await new Promise((r) => setTimeout(r, 250))+ }+ const built = await buildRelayLaunch(req, relayLaunchDialect(pane), ctxFn())+ if (!built) return false+ if (built.kind === 'type') return (await this.sendText(nodeId, built.command)) === true+ // A trusted Windows plan goes through the session host's exactly-once launch ledger.+ const live = this.liveSessionForPersistKey(nodeId)+ if (!live?.sessionHost) return false+ const res = await this.serializePaneWrite(nodeId, () =>+ sessionHostExecuteLaunch(sessionName(nodeId), randomUUID(), built.plan)+ )+ return res.status === 'executed' || res.status === 'already-executed'+ } catch {+ return false+ }+ }++ /** Who owns a LOCAL node's history, before the attach exists: the live session's backend when+ * one is held, else the backend a spawn would pick (tmux, else session host / plain shell). */+ private relayScrollOwner(persistKey: string): 'host' | 'local' {+ const live = this.liveSessionForPersistKey(persistKey)+ if (live) return live.sessionHost || !live.tmuxBacked ? 'local' : 'host'+ if (this.isZellij(persistKey, undefined)) return 'host'+ return this.tmuxPath && this.getSettings().tmuxEnabled ? 'host' : 'local'+ }++ /** The relay snapshot for a `scroll: 'local'` stream: everything the session host's emulator+ * holds (bounded by `tmuxScrollback`, like a desktop warm attach's seed), not just the visible+ * screen — the relay attach never gets the host's attach repaint, so without this the phone has+ * no history at all. A plain shell has nothing to capture. */+ private async relayLocalSnapshot(persistKey: string): Promise<string> {+ const live = this.liveSessionForPersistKey(persistKey)+ const viaHost = live ? live.sessionHost : !this.tmuxPath && this.getSettings().tmuxEnabled && sessionHostSupported()+ if (!viaHost) return this.captureSnapshot(persistKey)+ try {+ return await sessionHostCapture(sessionName(persistKey), true)+ } catch {+ return ''+ }+ }++ /**+ * Where a relay `pty.scroll` wheel for this session goes:+ * - `tmux` — a tmux client (local, remote, or Zellij's own) is in front of the pane; it owns+ * the history and consumes the SGR wheel (the behaviour every POSIX host has always had);+ * - `app-mouse` — a session-host pane whose app has asked for mouse tracking (a full-screen+ * TUI): the wheel is the app's to handle;+ * - `local` — anything else (a session-host pane with no mouse app, a plain shell): there is+ * nothing to consume a wheel, and writing one types raw escape text into the prompt. The+ * viewer's own emulator holds the history (`RelayAttachPrep.scroll`).+ * Unknown (an older session host that cannot answer, a session already gone) is `local`.+ */+ async scrollRoute(sessionId: string): Promise<'tmux' | 'app-mouse' | 'local'> {+ const s = this.sessions.get(sessionId)+ if (!s) return 'local'+ if (s.sessionHost) {+ if (!s.persistKey) return 'local'+ const mode = await sessionHostMouseTracking(sessionName(s.persistKey)).catch(() => null)+ return mode && mode !== 'none' ? 'app-mouse' : 'local'+ }+ if (s.nativeWindowsPane) return 'local'+ return s.tmuxBacked || s.sshRemote ? 'tmux' : 'local'+ }++ /**+ * Type a closed set of KEYS into a node's pane — the phone's keyed Inbox answers over the relay+ * (`agent.key`). One key per write, `RELAY_KEY_GAP_MS` apart (an Ink picker reads one stdin+ * chunk as one string), all inside the pane's write chain so nothing interleaves. tmux names+ * the keys (`send-keys`, local or over the project's ControlMaster); a session-host pane, which+ * has no tmux, takes the raw bytes through a client this process already holds. `false` =+ * nothing (or not everything) was delivered.+ */+ async sendKeys(persistKey: string, keys: readonly RelayKey[]): Promise<boolean> {+ if (keys.length === 0) return false+ return this.serializePaneWrite(persistKey, async () => {+ const target = sessionName(persistKey)+ const live = this.liveSessionForPersistKey(persistKey)+ if (live?.nativeWindowsPane || this.isZellij(persistKey, live)) return false+ for (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) {+ const ssh = findSsh()+ if (!ssh) return false+ await runAsync(+ ssh,+ remoteSendKeyArgs(live.sshRemote.conn, live.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.+ const current = this.liveSessionForPersistKey(persistKey)+ if (!current?.sessionHost) return false+ current.proc.write(rawKeyBytes(key))+ } else {+ await runAsync(this.tmuxPath, ['-L', TMUX_SOCKET, 'send-keys', '-t', target, ...tmuxKeyArgs(key)])+ }+ } catch {+ return false+ }+ }+ return true+ })+ }+/*** Capture the CURRENT visible pane of a node's tmux session (with colors, via `-e`). Returns* the screen text so the relay host can send it as a snapshot the mirrored client paints beforediff --git a/src/core/pty-relay-launch.test.ts b/src/core/pty-relay-launch.test.tsnew file mode 100644index 000000000..f8daef9b7--- /dev/null+++ b/src/core/pty-relay-launch.test.ts@@ -0,0 +1,205 @@+/**+ * PtyManager's relay-only-host parity seams, driven with node-pty and the session-host backend+ * mocked:+ * - `prepareRelayAttach(…, {launch})` folds an UNRECORDED node's cwd / account / agent into the+ * SPAWN options (never typed), keeps a recorded node's own records, and offers a `launch` step+ * that types the line for the pane's real parser exactly once;+ * - `scrollRoute` sends a wheel only where something consumes it;+ * - `sendKeys` writes closed-set keys one at a time into a session-host pane.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'+import { DEFAULT_SETTINGS } from '../shared/types'+import type { RelayNodeResolver } from './pty-manager'+import type { RelayLaunchContext } from './relay-launch'++const mouse = { mode: null as null | 'none' | 'vt200' }++vi.mock('./session-host-backend', async () => ({+ ...(await import('./__fixtures__/no-session-host')).noSessionHost(),+ sessionHostMouseTracking: async () => mouse.mode+}))+vi.mock('node-pty', () => ({+ spawn: () => ({+ onData: () => {},+ onExit: () => {},+ write: () => {},+ resize: () => {},+ pause: () => {},+ resume: () => {},+ kill: () => {},+ pid: 4321+ })+}))+vi.mock('./pty-devices', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./pty-devices')>()),+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })+}))++const SID = '0f3c2a1e-5b7d-4c9a-8e21-3f4a5b6c7d8e'+const sinks = { onData: () => {}, onExit: () => {} }++function resolver(): RelayNodeResolver {+ return {+ placements: (nodeId) =>+ nodeId === 'recorded'+ ? [{ projectId: 'p1', node: { kind: 'terminal', cwd: '/var/tmp', agentId: 'claude' } }]+ : [],+ refFor: () => undefined,+ projectIsRemote: () => false+ }+}++function launchCtx(over: Partial<RelayLaunchContext> = {}): RelayLaunchContext {+ return {+ customAgents: [],+ claudeAutoSupported: true,+ isKnownAccount: (id) => id === 'acct-1',+ env: {},+ ...over+ }+}++async function manager(withLaunch = true) {+ const { PtyManager } = await import('./pty-manager')+ const m = new PtyManager()+ m.init(() => ({ ...DEFAULT_SETTINGS, tmuxEnabled: false }))+ m.setRelayNodeResolver(resolver())+ if (withLaunch) m.setRelayLaunchContext(() => launchCtx())+ return m+}++describe('relay launch (pty.attach { launch })', () => {+ beforeEach(() => initPlatform(fakePlatform()))+ afterEach(() => {+ resetPlatformForTests()+ vi.restoreAllMocks()+ })++ it('an UNRECORDED node: cwd, account and agent ride the spawn options, nothing is typed for them', async () => {+ const m = await manager()+ const spawn = vi.spyOn(m as unknown as { spawnSession: (...a: unknown[]) => string }, 'spawnSession')+ const prep = await m.prepareRelayAttach(+ 'fresh-node',+ { cols: 80, rows: 24 },+ { launch: { agentId: 'claude', cwd: '/var/tmp', accountId: 'acct-1', sessionId: SID } }+ )+ expect(prep.kind).toBe('ready')+ if (prep.kind !== 'ready') return+ expect(prep.launch).toBeTypeOf('function')+ await prep.attach(sinks)+ expect(spawn.mock.calls[0][0]).toMatchObject({ persistKey: 'fresh-node', cwd: '/var/tmp', accountId: 'acct-1', agentId: 'claude' })+ })++ it('an account this machine does not know is dropped (system default), never trusted', async () => {+ const m = await manager()+ const spawn = vi.spyOn(m as unknown as { spawnSession: (...a: unknown[]) => string }, 'spawnSession')+ const prep = await m.prepareRelayAttach('fresh-2', { cols: 80, rows: 24 }, { launch: { agentId: 'claude', accountId: 'stranger' } })+ 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 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')+ const other = await m.prepareRelayAttach('recorded', { cols: 80, rows: 24 }, { launch: { agentId: 'codex', cwd: '/elsewhere' } })+ expect(other.kind === 'ready' && other.launch).toBeFalsy()+ const same = await m.prepareRelayAttach('recorded', { cols: 80, rows: 24 }, { launch: { agentId: 'claude', cwd: '/elsewhere' } })+ if (same.kind !== 'ready') throw new Error('not ready')+ expect(same.launch).toBeTypeOf('function')+ await same.attach(sinks)+ expect((spawn.mock.calls[0][0] as { cwd?: string }).cwd).toBe('/var/tmp')+ })++ it('no launch context wired (Server Edition): never a launch, and the spawn is unchanged', async () => {+ const m = await manager(false)+ const prep = await m.prepareRelayAttach('fresh-3', { cols: 80, rows: 24 }, { launch: { agentId: 'claude' } })+ expect(prep.kind === 'ready' && prep.launch).toBeFalsy()+ })++ it('types the line for the pane’s parser exactly once — no POSIX syntax into pwsh', async () => {+ const m = await manager()+ vi.spyOn(m, 'paneCommand').mockResolvedValue('C:\\Program Files\\PowerShell\\7\\pwsh.exe')+ const send = vi.spyOn(m, 'sendText').mockResolvedValue(true)+ const prep = await m.prepareRelayAttach(+ 'fresh-4',+ { cols: 80, rows: 24 },+ { launch: { agentId: 'claude', sessionId: SID, permissionMode: 'auto', cwd: '/var/tmp', accountId: 'acct-1' } }+ )+ if (prep.kind !== 'ready' || !prep.launch) throw new Error('no launch')+ expect(await prep.launch()).toBe(true)+ expect(await prep.launch()).toBe(false) // exactly once+ expect(send).toHaveBeenCalledTimes(1)+ const [node, text] = send.mock.calls[0]+ expect(node).toBe('fresh-4')+ expect(text).toBe(`claude --resume ${SID} --permission-mode auto`)+ for (const posix of ['2>/dev/null', 'env -u', ';', 'cd ']) expect(text).not.toContain(posix)+ })++ it('waits for a shell to own the pane; none in time ⇒ nothing typed', async () => {+ const { PtyManager } = await import('./pty-manager')+ const m = await manager()+ vi.spyOn(PtyManager, 'RELAY_LAUNCH_SHELL_WAIT_MS', 'get').mockReturnValue(0 as never)+ vi.spyOn(m, 'paneCommand').mockResolvedValue('node')+ const send = vi.spyOn(m, 'sendText').mockResolvedValue(true)+ const prep = await m.prepareRelayAttach('fresh-5', { cols: 80, rows: 24 }, { launch: { agentId: 'claude' } })+ if (prep.kind !== 'ready' || !prep.launch) throw new Error('no launch')+ expect(await prep.launch()).toBe(false)+ expect(send).not.toHaveBeenCalled()+ })+})++describe('scrollRoute', () => {+ beforeEach(() => initPlatform(fakePlatform()))+ afterEach(() => resetPlatformForTests())++ async function withSession(fields: Record<string, unknown>) {+ const m = await manager()+ ;(m as unknown as { sessions: Map<string, unknown> }).sessions.set('s1', { persistKey: 'n1', ...fields })+ return m+ }++ it('a tmux client (local or remote) consumes the wheel', async () => {+ expect(await (await withSession({ tmuxBacked: true })).scrollRoute('s1')).toBe('tmux')+ expect(await (await withSession({ tmuxBacked: true, sshRemote: {} })).scrollRoute('s1')).toBe('tmux')+ })+ it('a session-host pane: app-mouse only when the app asked for the mouse', async () => {+ mouse.mode = 'vt200'+ expect(await (await withSession({ tmuxBacked: true, sessionHost: true })).scrollRoute('s1')).toBe('app-mouse')+ mouse.mode = 'none'+ expect(await (await withSession({ tmuxBacked: true, sessionHost: true })).scrollRoute('s1')).toBe('local')+ mouse.mode = null // an older host that cannot answer+ expect(await (await withSession({ tmuxBacked: true, sessionHost: true })).scrollRoute('s1')).toBe('local')+ })+ it('a plain shell, a native pane, an unknown session: local', async () => {+ expect(await (await withSession({ tmuxBacked: false })).scrollRoute('s1')).toBe('local')+ expect(await (await withSession({ tmuxBacked: false, nativeWindowsPane: {} })).scrollRoute('s1')).toBe('local')+ expect(await (await manager()).scrollRoute('nope')).toBe('local')+ })+})++describe('sendKeys into a session-host pane', () => {+ beforeEach(() => initPlatform(fakePlatform()))+ afterEach(() => resetPlatformForTests())++ it('writes each key as its own chunk, in order', async () => {+ const m = await manager()+ const writes: string[] = []+ ;(m as unknown as { sessions: Map<string, unknown> }).sessions.set('s1', {+ persistKey: 'n1',+ sessionHost: true,+ tmuxBacked: true,+ proc: { write: (d: string) => writes.push(d) }+ })+ expect(await m.sendKeys('n1', [{ digit: '2' }, { name: 'Right' }, { name: 'Enter' }])).toBe(true)+ expect(writes).toEqual(['2', '\x1b[C', '\r'])+ })+ it('no client this process holds ⇒ nothing delivered', async () => {+ const m = await manager()+ ;(m as unknown as { tmuxPath: string | null }).tmuxPath = null+ expect(await m.sendKeys('ghost', [{ name: 'Escape' }])).toBe(false)+ expect(await m.sendKeys('ghost', [])).toBe(false)+ })+})diff --git a/src/main/index.ts b/src/main/index.tsindex 3372a392a..55d274cfe 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -8,7 +8,7 @@ import { join, resolve, posix } from 'path'import { startSessionNameSweep, displayNodeTitle } from '../core/session-name-sweep'import { startTriggerService } from '../core/trigger-service'import { readAgentSessionName, type AgentSessionNameDeps } from '../core/agent-session-name'-import { readFile, realpath as fsRealpath, lstat as fsLstat, writeFile as fsWriteFile } from 'fs/promises'+import { readFile, readdir as fsReaddir, realpath as fsRealpath, lstat as fsLstat, writeFile as fsWriteFile } from 'fs/promises'import { existsSync, statSync, openSync, fstatSync, readFileSync, closeSync } from 'fs'import { homedir, hostname } from 'os'import { randomUUID } from 'crypto'@@ -238,14 +238,15 @@ import {nodeSessionName,workingNodes,mirrorEntry,- pendingTicketsFor+ pendingTicketsFor,+ openAskFor} from '../core/agent-status-mirror'import { mirrorCustomAgents } from '../core/mirror-custom-agents'import { paneOwnerProject } from '../core/agents/pane-ownership'import { createPushNotify, createLiveUpdatePush } from '../core/push-notify'import { createGrantsAccessor, type PushGrant } from '../core/push-grants'import { createRemoteGrantsCache } from '../core/remote-push-grants'-import { createAckSweeper } from '../core/ack-sweep'+import { applyPhoneReadAck, createAckSweeper, type AckSweepHandlers } from '../core/ack-sweep'import { createSessionReaper } from '../core/session-budget'import { initKeepAwake } from './keep-awake'import type { KeepAwakeTracker } from '../core/keep-awake'@@ -2401,7 +2402,24 @@ app.whenReady().then(async () => {.filter((a) => !a.host && !a.pending).map((a) => ({ id: a.id, dir: claudeConfigDirFor(a.id) })),// Derived binary names only — never the launch command/env (see core/mirror-custom-agents.ts).- customAgents: mirrorCustomAgents(s.customAgents)+ customAgents: mirrorCustomAgents(s.customAgents),+ // A phone must never type POSIX shell syntax into a win32 host's pane (core/relay-launch.ts).+ hostPlatform: process.platform+ }+ })+ // The host-authoritative facts a phone's relay launch (`pty.attach { launch }`) is built from:+ // the same probes and settings the mirror advertises. Read fresh per launch.+ ptyManager.setRelayLaunchContext(() => {+ const s = settingsStore.get()+ const localClaude = new Set((s.claudeAccounts ?? []).filter((a) => !a.host && !a.pending).map((a) => a.id))+ const localCodex = new Set((s.codexAccounts ?? []).filter((a) => !a.host && !a.pending).map((a) => a.id))+ return {+ customAgents: s.customAgents ?? [],+ claudeAutoSupported: localClaudeCaps?.autoPermissionMode === true,+ codexApprovalValues: localCodexCaps?.approvalValues ?? null,+ codexNoDaemon: localCodexCaps?.noDaemon === true,+ isKnownAccount: (id) => localClaude.has(id) || localCodex.has(id),+ env: process.env}})// Desktop → paired-phone APNs push (spec: apns-push). Feeds off the SAME actionable-event seam@@ -3388,9 +3406,13 @@ app.whenReady().then(async () => {onSshProjectStatus((e) => {if (e.status !== 'connected' && e.status !== 'connecting') devPorts.registry?.projectDisconnected(e.projectId)})- const ackSweeper = createAckSweeper({- handlers: { ackDone, onUnreadClear: (id) => sendToMain(IPC.agentUnreadClear, id) }- })+ // One handler pair for every phone read-ack arrival path: the local `.seen` sweep, the SSH hosts'+ // remote sweep below, and the relay's `inbox.ack` (relay-only hosts — see hostBridge.relayExtras).+ const phoneReadAckHandlers: AckSweepHandlers = {+ ackDone,+ onUnreadClear: (id) => sendToMain(IPC.agentUnreadClear, id)+ }+ const ackSweeper = createAckSweeper({ handlers: phoneReadAckHandlers })let remoteAckSweepBusy = falseconst ackSweepTimer = setInterval(() => {ackSweeper.sweep()@@ -3399,10 +3421,7 @@ app.whenReady().then(async () => {void sshProjectManager.sweepRemoteAcks().then((ids) => {- for (const id of ids) {- ackDone(id)- sendToMain(IPC.agentUnreadClear, id)- }+ for (const id of ids) applyPhoneReadAck(id, phoneReadAckHandlers)}).catch(() => {}).finally(() => {@@ -4592,6 +4611,11 @@ app.whenReady().then(async () => {}},hostSendRefusal: (nodeId) => mirrorChatSendRefusal(mirrorEntry(nodeId)),+ // The relay's keyed answers (`agent.key`): guarded on the host's own mirror, typed through+ // PtyManager's backend-neutral key writer.+ agentState: nodeState,+ openAsk: openAskFor,+ sendKeys: (nodeId, keys) => ptyManager.sendKeys(nodeId, keys),knownTickets: pendingTicketsFor,readTranscript: (q, rawPage) => readChatTranscript(q, rawPage, transcriptIpcDeps),catalog: (q) => readChatCatalog(q, chatCatalogDeps),@@ -4643,6 +4667,18 @@ app.whenReady().then(async () => {}})()}),+ // Relay-only-host parity verbs (Windows pairings have no SSH): a phone read-ack runs the+ // sweeper's own handler pair, and the new-project folder browser is jailed to this user's home.+ relayExtras: {+ inboxAck: (nodeId: string) => applyPhoneReadAck(nodeId, phoneReadAckHandlers),+ browse: {+ home: () => homedir(),+ fs: {+ readdir: (dir: string) => fsReaddir(dir, { withFileTypes: true }),+ exists: async (p: string) => existsSync(p)+ }+ }+ },// Jail roots beyond the active canvas: the phone browses EVERY project (projects.list), so// its fs/git access spans every local project root — not just the tab the desktop happens// to have focused (that gap read as "cwd is outside the shared project roots" on the phone).diff --git a/src/main/relay-attach-wiring.test.ts b/src/main/relay-attach-wiring.test.tsindex 883c52024..5f663724d 100644--- a/src/main/relay-attach-wiring.test.ts+++ b/src/main/relay-attach-wiring.test.ts@@ -16,7 +16,10 @@ describe('relay attach routing is wired in the desktop shell', () => {})it('the relay host attaches only through core’s decision, never the bare local attach', () => {const src = read('main/remote/host-service.ts')- expect(src).toMatch(/pty\.prepareRelayAttach\(nodeId, \{ cols, rows \}, \{ projectId: projectHint \}\)/)+ // The phone's project hint (and, when asked, its jailed launch request) is all that crosses.+ expect(src).toMatch(+ /pty\.prepareRelayAttach\(\n\s*nodeId,\n\s*\{ cols, rows \},\n\s*launchReq \? \{ projectId: projectHint, launch: launchReq \} : \{ projectId: projectHint \}\n\s*\)/+ )expect(src).not.toMatch(/pty\.attachDetached\(/)})it('a Team Access guest’s create in an SSH project is forced requireRemote', () => {diff --git a/src/main/relay-parity-wiring.test.ts b/src/main/relay-parity-wiring.test.tsnew file mode 100644index 000000000..16d4aae9f--- /dev/null+++ b/src/main/relay-parity-wiring.test.ts@@ -0,0 +1,29 @@+// Source pins for the relay-only-host parity wiring in the desktop shell: each seam is unit-tested+// where it lives (core / host-service / host-chat), and these pin that main actually connects them —+// a dependency left unwired answers "not served" forever and every unit test stays green.+import { describe, it, expect } from 'vitest'+import fs from 'fs'+import path from 'path'++const read = (rel: string): string => fs.readFileSync(path.join(__dirname, '..', rel), 'utf8').replace(/\r\n/g, '\n')++describe('relay-only-host parity is wired in the desktop shell', () => {+ const src = read('main/index.ts')+ it('the mirror tells the phone which platform it is talking to', () => {+ expect(src).toMatch(/hostPlatform: process\.platform\n/)+ })+ it('core gets the host-authoritative launch context', () => {+ expect(src).toMatch(/ptyManager\.setRelayLaunchContext\(\(\) => \{/)+ })+ it('agent.key is guarded on the mirror and typed through PtyManager', () => {+ expect(src).toMatch(/agentState: nodeState,\n\s*openAsk: openAskFor,\n\s*sendKeys: \(nodeId, keys\) => ptyManager\.sendKeys\(nodeId, keys\),/)+ })+ it('inbox.ack runs the ack sweeper’s own handler pair', () => {+ expect(src).toMatch(/inboxAck: \(nodeId: string\) => applyPhoneReadAck\(nodeId, phoneReadAckHandlers\)/)+ expect(src).toMatch(/createAckSweeper\(\{ handlers: phoneReadAckHandlers \}\)/)+ })+ it('both phone hosts forward the extras into their sessions', () => {+ expect(read('main/remote/host-service.ts')).toMatch(/relayExtras: bridge\.relayExtras,/)+ expect(read('main/remote/standing-host.ts')).toMatch(/relayExtras: bridge\.relayExtras,/)+ })+})diff --git a/src/main/remote/host-chat-key.test.ts b/src/main/remote/host-chat-key.test.tsnew file mode 100644index 000000000..17b9e3c9d--- /dev/null+++ b/src/main/remote/host-chat-key.test.ts@@ -0,0 +1,125 @@+// `HostChatOps.key` — the relay's keyed answers (`agent.key`) for a host the phone cannot SSH into.+// The guard matrix it pins is the phone's own (`InboxApproval.acceptStates` + `answerFitsAsk`),+// re-run HOST-side at delivery time: a stale card must never type a key into whatever ask+// replaced it — a question's digit typed into a permission prompt ANSWERS it ("2" = don't ask+// again).+import { describe, expect, it, vi } from 'vitest'+import { createHostChat, keyAcceptStates, keyFileDecision, keyFitsAsk, type HostChatDeps } from './host-chat'+import type { HeldPermissionIo } from '../../core/agents/permission-decision'+import type { RelayKey } from '../../core/relay-keys'++function deps(over: Partial<HostChatDeps> & { state?: string; ask?: { kind: 'approval' | 'question'; pendingId?: string } } = {}): HostChatDeps {+ const { state = 'blocked', ask, ...rest } = over+ return {+ lookupNode: vi.fn((id: string) => (id === 'n1' ? { agentId: 'claude' } : null)),+ readTranscript: vi.fn(),+ answerIo: vi.fn(() => ({ readPending: async () => null, write: async () => true }) as HeldPermissionIo),+ answerHeld: vi.fn(async () => ({ ok: true, decision: 'allow' as const })),+ onAnswered: vi.fn(),+ isStructuredTicket: vi.fn(() => false),+ renderer: { status: vi.fn(async () => null), send: vi.fn(), session: vi.fn() },+ hostSendRefusal: vi.fn(() => null),+ knownTickets: vi.fn(() => ['n1-1-1']),+ agentState: vi.fn(() => state),+ openAsk: vi.fn(() => ask),+ sendKeys: vi.fn(async () => true),+ timeoutMs: 20,+ ...rest+ } as HostChatDeps+}++const ONE: RelayKey[] = [{ digit: '1' }]+const TWO: RelayKey[] = [{ digit: '2' }]+const ESC: RelayKey[] = [{ name: 'Escape' }]++describe('keyed-answer guards (pure)', () => {+ it('an approval acts only on blocked; a question / submit also on waiting', () => {+ expect(keyAcceptStates('approval')).toEqual(['blocked'])+ expect(keyAcceptStates('question')).toEqual(['blocked', 'waiting'])+ expect(keyAcceptStates('submit')).toEqual(['blocked', 'waiting'])+ })+ it('the answer must fit the open ask; no open ask fails open', () => {+ expect(keyFitsAsk('approval', { kind: 'approval' })).toBe(true)+ expect(keyFitsAsk('question', { kind: 'approval' })).toBe(false)+ expect(keyFitsAsk('submit', { kind: 'approval' })).toBe(false)+ expect(keyFitsAsk('approval', { kind: 'question' })).toBe(false)+ expect(keyFitsAsk('question', undefined)).toBe(true)+ })+ it('only `1` and Escape map to a hook-reply decision', () => {+ expect(keyFileDecision(ONE)).toBe('allow')+ expect(keyFileDecision(ESC)).toBe('deny')+ expect(keyFileDecision(TWO)).toBeNull()+ expect(keyFileDecision([{ digit: '1' }, { name: 'Enter' }])).toBeNull()+ })+})++describe('host-chat key', () => {+ it('unknown node / unserved', async () => {+ expect(await createHostChat(deps()).key!('nope', { keys: ONE, ask: 'approval' })).toBe('unknown-node')+ const d = deps({ sendKeys: undefined })+ expect(await createHostChat(d).key!('n1', { keys: ONE, ask: 'approval' })).toEqual({+ result: 'refused',+ reason: 'unsupported'+ })+ })+ it.each([+ ['working', 'approval'],+ ['done', 'question'],+ ['waiting', 'approval'],+ [undefined, 'question']+ ] as const)('state %s does not accept a %s answer — nothing is typed', async (state, ask) => {+ const d = deps({ agentState: vi.fn(() => state) })+ expect(await createHostChat(d).key!('n1', { keys: ONE, ask })).toEqual({ result: 'alreadyHandled' })+ expect(d.sendKeys).not.toHaveBeenCalled()+ })+ it('the phone’s states can narrow, never widen', async () => {+ const d = deps({ state: 'waiting' })+ expect(await createHostChat(d).key!('n1', { keys: ONE, ask: 'question', states: ['blocked'] })).toEqual({+ result: 'alreadyHandled'+ })+ const w = deps({ state: 'working' })+ expect(await createHostChat(w).key!('n1', { keys: ONE, ask: 'question', states: ['working'] })).toEqual({+ result: 'alreadyHandled'+ })+ })+ it('a question’s digit is never typed into an open PERMISSION prompt', async () => {+ const d = deps({ state: 'blocked', ask: { kind: 'approval', pendingId: 'n1-1-1' } })+ expect(await createHostChat(d).key!('n1', { keys: TWO, ask: 'question' })).toEqual({ result: 'alreadyHandled' })+ expect(d.sendKeys).not.toHaveBeenCalled()+ })+ it('a fitting answer types the keys', async () => {+ const d = deps({ state: 'waiting', ask: { kind: 'question' } })+ expect(await createHostChat(d).key!('n1', { keys: TWO, ask: 'question' })).toEqual({ result: 'sent' })+ expect(d.sendKeys).toHaveBeenCalledWith('n1', TWO)+ })+ it('an approval with its ticket is answered through the hook reply, not a keypress', async () => {+ const d = deps({ ask: { kind: 'approval', pendingId: 'n1-1-1' } })+ expect(await createHostChat(d).key!('n1', { keys: ESC, ask: 'approval', pendingId: 'n1-1-1' })).toEqual({+ result: 'sent'+ })+ expect(d.answerHeld).toHaveBeenCalledWith('n1-1-1', { decision: 'deny' }, expect.anything())+ expect(d.onAnswered).toHaveBeenCalled()+ expect(d.sendKeys).not.toHaveBeenCalled()+ })+ it('a failed hook reply falls through to the keypress exactly once; a foreign ticket is never written', async () => {+ const failed = deps({ answerHeld: vi.fn(async () => ({ ok: false })) })+ expect(await createHostChat(failed).key!('n1', { keys: ONE, ask: 'approval', pendingId: 'n1-1-1' })).toEqual({+ result: 'sent'+ })+ expect(failed.sendKeys).toHaveBeenCalledTimes(1)+ const foreign = deps({ knownTickets: vi.fn(() => []) })+ await createHostChat(foreign).key!('n1', { keys: ONE, ask: 'approval', pendingId: 'n2-1-1' })+ expect(foreign.answerHeld).not.toHaveBeenCalled()+ expect(foreign.sendKeys).toHaveBeenCalledTimes(1)+ })+ it('one keyed answer at a time per node; a failed delivery is a refusal', async () => {+ let release: (v: boolean) => void = () => {}+ const d = deps({ sendKeys: vi.fn(() => new Promise<boolean>((r) => (release = r))) })+ const chat = createHostChat(d)+ const first = chat.key!('n1', { keys: ONE, ask: 'approval' })+ await new Promise((r) => setTimeout(r, 0))+ expect(await chat.key!('n1', { keys: ONE, ask: 'approval' })).toEqual({ result: 'refused', reason: 'busy' })+ release(false)+ expect(await first).toEqual({ result: 'refused', reason: 'unavailable' })+ })+})diff --git a/src/main/remote/host-chat-wiring.test.ts b/src/main/remote/host-chat-wiring.test.tsindex 8533dc114..875bb41d5 100644--- a/src/main/remote/host-chat-wiring.test.ts+++ b/src/main/remote/host-chat-wiring.test.ts@@ -20,7 +20,7 @@ describe('phone chat verbs are wired end to end', () => {it('both phone hosts forward bridge.chat into the session, and the session into the handlers', () => {expect(read('main/remote/host-service.ts')).toMatch(/chat: bridge\.chat,/)expect(read('main/remote/standing-host.ts')).toMatch(/chat: bridge\.chat,/)- expect(read('main/remote/host-service.ts')).toMatch(/opts\.kanban,\n\s*opts\.chat\n\s*\)/)+ expect(read('main/remote/host-service.ts')).toMatch(/opts\.kanban,\n\s*opts\.chat,\n\s*opts\.relayExtras \?\? \{\}\n\s*\)/)})it('the remote transcript leg resolves an UNMOUNTED SSH node by its project', () => {const src = read('main/index.ts')diff --git a/src/main/remote/host-chat.ts b/src/main/remote/host-chat.tsindex 6c15eeeaf..0834575fb 100644--- a/src/main/remote/host-chat.ts+++ b/src/main/remote/host-chat.ts@@ -24,6 +24,8 @@ import {type HeldPermissionIo} from '../../core/agents/permission-decision'import type { HostChatOps } from './host-service'+import type { RelayKey } from '../../core/relay-keys'+import { isValidPendingId } from '../../core/agents/pending-approvals'/** What the host knows about a node, from its own records. */export interface HostChatNode {@@ -67,6 +69,13 @@ export interface HostChatDeps {* an ssh round trip (and the child gate's queue) on a master that may be half dead; `chat.status`* must never wait on that. Default `HOST_CHAT_CATALOG_TIMEOUT_MS`. */catalogTimeoutMs?: number+ /** The node's agent state per the HOST's mirror (`nodeState`) — the keyed answer's guard. Absent+ * ⇒ `agent.key` is not served. */+ agentState?(nodeId: string): string | undefined+ /** The ask currently open on the node (`openAskFor`): its newest unresolved approval/question. */+ openAsk?(nodeId: string): { kind: 'approval' | 'question'; pendingId?: string } | undefined+ /** Deliver closed-set keys into the node's pane (`PtyManager.sendKeys`). Absent ⇒ not served. */+ sendKeys?(nodeId: string, keys: readonly RelayKey[]): Promise<boolean>/** The approval tickets the host's mirror holds for this node (`pendingTicketsFor`). */knownTickets(nodeId: string): string[]/** How long a status query may take, and how long a send has to START (the renderer refuses a@@ -91,6 +100,47 @@ export function mirrorChatSendRefusal(return entry.pendingQuestion || (entry.concurrentApprovalIds?.length ?? 0) > 0 ? 'dialog' : null}+/** What a keyed answer is answering — decides which states it may act on and which open ask it fits. */+export type KeyAnswerKind = 'approval' | 'question' | 'submit'++export interface KeyRequest {+ keys: readonly RelayKey[]+ ask: KeyAnswerKind+ /** The states the phone's card was built for; only NARROWS the host's own set (`keyAcceptStates`). */+ states?: readonly string[]+ /** The approval's hook-reply ticket, when the card carried one. */+ pendingId?: string+}++export type KeyOutcome =+ | { result: 'sent' }+ /** The node is no longer asking what the card answered — nothing was typed. */+ | { result: 'alreadyHandled' }+ | { result: 'refused'; reason: 'busy' | 'unavailable' | 'unsupported' }++/** The needs-you states an answer kind may act on — the phone's `InboxApproval.acceptStates`, held+ * host-side: an approval only on a still-`blocked` node (a stale Allow/Deny must not land in a+ * question that replaced it), a question option / multi-select Submit also on `waiting`. */+export function keyAcceptStates(ask: KeyAnswerKind): readonly string[] {+ return ask === 'approval' ? ['blocked'] : ['blocked', 'waiting']+}++/** Does the answer fit the ask that is open NOW? (The phone's `answerFitsAsk`.) No open ask fails+ * open, exactly as the phone does against a host too old to send an inbox. */+export function keyFitsAsk(ask: KeyAnswerKind, open: { kind: 'approval' | 'question' } | undefined): boolean {+ if (!open) return true+ return ask === 'approval' ? open.kind === 'approval' : open.kind === 'question'+}++/** The hook-reply decision a single approval key maps to (`1` = allow, Escape = deny); anything+ * else ("2" = always allow, a question digit) has no file decision and stays a keypress. */+export function keyFileDecision(keys: readonly RelayKey[]): 'allow' | 'deny' | null {+ if (keys.length !== 1) return null+ const k = keys[0]+ if ('digit' in k) return k.digit === '1' ? 'allow' : null+ return k.name === 'Escape' ? 'deny' : null+}+/** How long a node stays busy after an UNCONFIRMED send whose dispatch never settles (main drops an* unanswered query after 30 s, so its promise may never settle at all). */export const HOST_CHAT_BUSY_CAP_MS = 30_000@@ -244,6 +294,41 @@ export function createHostChat(deps: HostChatDeps): HostChatOps {}},+ async key(nodeId, req) {+ const node = deps.lookupNode(nodeId)+ if (!node) return 'unknown-node'+ if (!deps.sendKeys || !deps.agentState) return { result: 'refused', reason: 'unsupported' }+ // Re-checked HERE, on the host, at delivery time: a permission answered on another surface+ // must not have a stray key typed into whatever replaced it. The phone's states may narrow+ // the host's set, never widen it.+ const allowed = keyAcceptStates(req.ask).filter((st) => !req.states || req.states.includes(st))+ const state = deps.agentState(nodeId)+ if (!state || !allowed.includes(state)) return { result: 'alreadyHandled' }+ if (!keyFitsAsk(req.ask, deps.openAsk?.(nodeId))) return { result: 'alreadyHandled' }+ if (sending.has(nodeId)) return { result: 'refused', reason: 'busy' }+ sending.add(nodeId)+ try {+ // Hook-reply first (deterministic: the hook applies the decision before the prompt paints);+ // a failed answer falls through to the keypress exactly once, like the phone's SSH path.+ const decision = req.ask === 'approval' ? keyFileDecision(req.keys) : null+ if (decision && req.pendingId && isValidPendingId(req.pendingId)) {+ if (await ticketBelongsTo(nodeId, node.agentId, req.pendingId)) {+ const res = await answerHeld(req.pendingId, { decision }, deps.answerIo(nodeId, req.pendingId))+ if (res.ok) {+ if (res.decision) deps.onAnswered?.(nodeId, req.pendingId, res.decision)+ return { result: 'sent' }+ }+ }+ }+ const ok = await deps.sendKeys(nodeId, req.keys)+ return ok ? { result: 'sent' } : { result: 'refused', reason: 'unavailable' }+ } catch {+ return { result: 'refused', reason: 'unavailable' }+ } finally {+ sending.delete(nodeId)+ }+ },+async answer(nodeId, pendingId, answer) {const node = deps.lookupNode(nodeId)if (!node) return falsediff --git a/src/main/remote/host-relay-parity.test.ts b/src/main/remote/host-relay-parity.test.tsnew file mode 100644index 000000000..7001f56f5--- /dev/null+++ b/src/main/remote/host-relay-parity.test.ts@@ -0,0 +1,282 @@+// The relay verbs a relay-only host (every Windows pairing: no direct SSH) needs to give the phone+// what it used to do over SSH — host-owned launch, scroll routing, keyed answers, read-acks, the+// folder browser and plain capture. What these pin:+// - An attach with NO `launch` answers exactly `{streamId, fresh}` (an old phone sees no change),+// and a tmux stream's reply carries no `scroll` field.+// - A launch runs only for a session the attach CREATED, exactly once, after the attach, and the+// reply says so (`launched`) along with the host's platform; a cwd outside the jail is dropped.+// - `pty.scroll` writes the wheel only for a `tmux` / `app-mouse` route.+// - The new verbs validate their input and answer "not served" when not injected.+import { describe, expect, it, vi } from 'vitest'+import {+ RELAY_PARITY_VERBS,+ createHostHandlers,+ type HostChatOps,+ type HostFsOps,+ type HostPtyManager,+ type HostRelayExtras,+ type HostRelaySocket+} from './host-service'++const flush = (): Promise<void> => new Promise((r) => setTimeout(r, 0))++function setup(opts: {+ existed?: boolean+ scroll?: 'host' | 'local'+ route?: 'tmux' | 'app-mouse' | 'local'+ withLaunch?: boolean+ extras?: HostRelayExtras+ chat?: Partial<HostChatOps>+ roots?: string[]+} = {}) {+ const responses: Array<{ id: string; ok: boolean; body: unknown }> = []+ const socket: HostRelaySocket = {+ respond: (id, ok, body) => responses.push({ id, ok, body }),+ sendFrame: () => true+ }+ const fs: HostFsOps = { listDir: async () => [], readText: async () => '', readBinary: async () => '', writeText: async () => true }+ const order: string[] = []+ const launch = vi.fn(async () => {+ order.push('launch')+ return true+ })+ const pty = {+ prepareRelayAttach: vi.fn(async () => ({+ kind: 'ready' as const,+ remote: false,+ ...(opts.scroll ? { scroll: opts.scroll } : {}),+ sessionExists: async () => opts.existed ?? true,+ snapshot: async () => '',+ attach: async () => {+ order.push('attach')+ return 'sess-1'+ },+ ...(opts.withLaunch ? { launch } : {})+ })),+ sessionExists: vi.fn(async () => true),+ write: vi.fn(),+ resize: vi.fn(),+ setFlow: vi.fn(),+ kill: vi.fn(),+ createDetached: vi.fn(() => 'x'),+ scrollRoute: vi.fn(async () => opts.route ?? 'tmux'),+ captureSession: vi.fn(async () => '\x1b[31mred\x1b[0m line\n')+ } as unknown as HostPtyManager & { prepareRelayAttach: ReturnType<typeof vi.fn>; write: ReturnType<typeof vi.fn> }+ const handlers = createHostHandlers(+ pty,+ socket,+ fs,+ () => opts.roots ?? ['/work'],+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ opts.chat as HostChatOps | undefined,+ opts.extras ?? {}+ )+ return { handlers, responses, pty, launch, order }+}++describe('pty.attach { launch } — the host owns the launch', () => {+ it('no launch field: the reply is exactly {streamId, fresh}, and nothing is launched', async () => {+ const { handlers, responses, pty } = setup({ existed: false, withLaunch: true })+ handlers.onRpc({ id: '1', method: 'pty.attach', params: { nodeId: 'n1' } })+ await flush()+ await flush()+ expect(responses[0]).toEqual({ id: '1', ok: true, body: { streamId: 1, fresh: true } })+ expect(pty.prepareRelayAttach).toHaveBeenCalledWith('n1', { cols: 80, rows: 24 }, { projectId: undefined })+ })+ it('a fresh session: launched once, AFTER attach, and the reply says so with the platform', async () => {+ const { handlers, responses, pty, launch, order } = setup({+ existed: false,+ withLaunch: true,+ extras: { platform: 'win32' },+ roots: ['C:\\work']+ })+ handlers.onRpc({+ id: '1',+ method: 'pty.attach',+ // The jail speaks the HOST's dialect: a win32 host takes a drive path, case-insensitively.+ params: { nodeId: 'n1', launch: { agentId: 'claude', sessionId: 'abc-1', cwd: 'c:\\Work\\app', permissionMode: 'plan' } }+ })+ await flush()+ await flush()+ expect(responses[0].body).toEqual({ streamId: 1, fresh: true, launched: true, hostPlatform: 'win32' })+ expect(pty.prepareRelayAttach.mock.calls[0][2]).toEqual({+ projectId: undefined,+ launch: { agentId: 'claude', sessionId: 'abc-1', cwd: 'c:\\Work\\app', permissionMode: 'plan' }+ })+ expect(launch).toHaveBeenCalledTimes(1)+ expect(order).toEqual(['attach', 'launch'])+ })+ it('a warm session is never launched into', async () => {+ const { handlers, responses, launch } = setup({ existed: true, withLaunch: true, extras: { platform: 'linux' } })+ 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(launch).not.toHaveBeenCalled()+ })+ it('a cwd outside the shared roots is dropped; a forged launch reaches core as no launch', async () => {+ const a = setup({ existed: false, withLaunch: true })+ a.handlers.onRpc({ id: '1', method: 'pty.attach', params: { nodeId: 'n1', launch: { agentId: 'claude', cwd: '/etc' } } })+ await flush()+ expect(a.pty.prepareRelayAttach.mock.calls[0][2]).toEqual({ projectId: undefined, launch: { agentId: 'claude' } })+ const b = setup({ existed: false, withLaunch: true })+ b.handlers.onRpc({ id: '1', method: 'pty.attach', params: { nodeId: 'n1', launch: { agentId: 'claude', sessionId: '$(id)' } } })+ await flush()+ expect(b.pty.prepareRelayAttach.mock.calls[0][2]).toEqual({ projectId: undefined })+ })+ it('a session-host / plain stream says scroll:local; a tmux one says nothing new', async () => {+ const local = setup({ scroll: 'local' })+ local.handlers.onRpc({ id: '1', method: 'pty.attach', params: { nodeId: 'n1' } })+ await flush()+ expect(local.responses[0].body).toEqual({ streamId: 1, fresh: false, scroll: 'local' })+ const host = setup({ scroll: 'host' })+ host.handlers.onRpc({ id: '1', method: 'pty.attach', params: { nodeId: 'n1' } })+ await flush()+ expect(host.responses[0].body).toEqual({ streamId: 1, fresh: false })+ })+})++describe('pty.scroll routing', () => {+ async function scrollWith(route: 'tmux' | 'app-mouse' | 'local') {+ const s = setup({ route })+ s.handlers.onRpc({ id: '1', method: 'pty.attach', params: { nodeId: 'n1' } })+ await flush()+ await flush()+ s.handlers.onRpc({ id: '2', method: 'pty.scroll', params: { streamId: 1, dir: 'up', lines: 99 } })+ await flush()+ return s+ }+ it.each(['tmux', 'app-mouse'] as const)('%s: the SGR wheel, clamped to 20 notches', async (route) => {+ const s = await scrollWith(route)+ expect(s.pty.write).toHaveBeenCalledTimes(20)+ expect(s.pty.write).toHaveBeenCalledWith(null, 'sess-1', '\x1b[<64;1;1M')+ expect(s.responses.at(-1)).toEqual({ id: '2', ok: true, body: {} })+ })+ it('local: nothing is written (no tmux to consume it), still answered ok', async () => {+ const s = await scrollWith('local')+ expect(s.pty.write).not.toHaveBeenCalled()+ expect(s.responses.at(-1)).toEqual({ id: '2', ok: true, body: {} })+ })+})++describe('inbox.ack', () => {+ it('a valid ack runs the read-ack once and answers ok', () => {+ const inboxAck = vi.fn()+ const { handlers, responses } = setup({ extras: { inboxAck } })+ handlers.onRpc({ id: '1', method: 'inbox.ack', params: { nodeId: 'term-a-1', eventId: '1760000000000-12' } })+ expect(inboxAck).toHaveBeenCalledWith('term-a-1')+ expect(responses).toEqual([{ id: '1', ok: true, body: { ok: true } }])+ })+ it.each([+ [{ nodeId: 'term-a-1', eventId: '../x' }],+ [{ nodeId: 'term-a-1', eventId: 'constructor' }],+ [{ nodeId: 'term-a-1', eventId: '' }],+ [{ nodeId: '', eventId: '1-1' }],+ [{ nodeId: 'a\nb', eventId: '1-1' }],+ [{ eventId: '1-1' }]+ ])('refuses %j without calling the ack', (params) => {+ const inboxAck = vi.fn()+ const { handlers, responses } = setup({ extras: { inboxAck } })+ handlers.onRpc({ id: '1', method: 'inbox.ack', params })+ expect(inboxAck).not.toHaveBeenCalled()+ expect(responses[0].ok).toBe(false)+ })+ it('not injected: not served', () => {+ const { handlers, responses } = setup()+ handlers.onRpc({ id: '1', method: 'inbox.ack', params: { nodeId: 'n', eventId: '1-1' } })+ expect(responses).toEqual([{ id: '1', ok: false, body: { message: 'inbox.ack is not served on this host.' } }])+ })+})++describe('fs.browse / pty.capture / host.info', () => {+ it('fs.browse lists the home through the dialect-aware jail', async () => {+ const extras: HostRelayExtras = {+ platform: 'win32',+ browse: {+ home: () => 'C:\\Users\\me',+ fs: {+ readdir: async () => [{ name: 'repo', isDirectory: () => true }],+ exists: async () => false+ }+ }+ }+ const { handlers, responses } = setup({ extras })+ handlers.onRpc({ id: '1', method: 'fs.browse', params: {} })+ handlers.onRpc({ id: '2', method: 'fs.browse', params: { path: '\\\\server\\share' } })+ await flush()+ expect(responses.find((r) => r.id === '1')).toEqual({+ id: '1',+ ok: true,+ body: { path: 'C:\\Users\\me', parent: null, truncated: false, entries: [{ name: 'repo', dir: true, git: false }] }+ })+ expect(responses.find((r) => r.id === '2')?.ok).toBe(false)+ })+ it('pty.capture resolves the stream, never a client node id, and answers plain text', async () => {+ const s = setup()+ s.handlers.onRpc({ id: '1', method: 'pty.capture', params: { streamId: 9 } })+ s.handlers.onRpc({ id: '2', method: 'pty.attach', params: { nodeId: 'n1' } })+ await flush()+ await flush()+ s.handlers.onRpc({ id: '3', method: 'pty.capture', params: { streamId: 1, nodeId: 'other' } })+ await flush()+ expect(s.responses.find((r) => r.id === '1')?.body).toEqual({ text: '' })+ expect(s.responses.find((r) => r.id === '3')?.body).toEqual({ text: 'red line\n' })+ expect((s.pty as unknown as { captureSession: ReturnType<typeof vi.fn> }).captureSession).toHaveBeenCalledWith('n1', false)+ })+ it('host.info names the platform and the parity verbs', () => {+ const { handlers, responses } = setup({ extras: { platform: 'win32' } })+ handlers.onRpc({ id: '1', method: 'host.info', params: {} })+ expect(responses).toEqual([{ id: '1', ok: true, body: { platform: 'win32', verbs: [...RELAY_PARITY_VERBS] } }])+ })+})++describe('agent.key dispatch', () => {+ it('routes a valid single key with its expectation', async () => {+ const key = vi.fn(async () => ({ result: 'sent' as const }))+ const { handlers, responses } = setup({ chat: { key } })+ handlers.onRpc({+ id: '1',+ method: 'agent.key',+ params: { nodeId: 'n1', key: '1', expect: { ask: 'approval', states: ['blocked'] }, pendingId: 'n1-1-1' }+ })+ await flush()+ expect(key).toHaveBeenCalledWith('n1', {+ keys: [{ digit: '1' }],+ ask: 'approval',+ states: ['blocked'],+ pendingId: 'n1-1-1'+ })+ expect(responses).toEqual([{ id: '1', ok: true, body: { result: 'sent' } }])+ })+ it.each([+ [{ nodeId: 'n1', key: '0', expect: { ask: 'approval' } }],+ [{ nodeId: 'n1', key: 'rm -rf', expect: { ask: 'approval' } }],+ [{ nodeId: 'n1', key: '1' }],+ [{ nodeId: 'n1', key: '1', expect: { ask: 'whatever' } }],+ [{ nodeId: 'n1', digits: [1, 2], expect: { ask: 'question' } }],+ [{ nodeId: '', key: '1', expect: { ask: 'question' } }]+ ])('refuses %j before reaching the node', async (params) => {+ const key = vi.fn()+ const { handlers, responses } = setup({ chat: { key } })+ handlers.onRpc({ id: '1', method: 'agent.key', params })+ await flush()+ expect(key).not.toHaveBeenCalled()+ expect(responses[0].ok).toBe(false)+ })+ it('a chat service without keys answers not served; an unknown node is an error', async () => {+ const a = setup({ chat: {} })+ a.handlers.onRpc({ id: '1', method: 'agent.key', params: { nodeId: 'n1', key: '1', expect: { ask: 'approval' } } })+ expect(a.responses[0]).toEqual({ id: '1', ok: false, body: { message: 'agent.key is not served on this host.' } })+ const b = setup({ chat: { key: async () => 'unknown-node' as const } })+ b.handlers.onRpc({ id: '1', method: 'agent.key', params: { nodeId: 'n1', key: 'escape', expect: { ask: 'approval' } } })+ await flush()+ expect(b.responses[0]).toEqual({ id: '1', ok: false, body: { message: 'Unknown node.' } })+ })+})diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.tsindex 02c27b7b3..dd94d1316 100644--- a/src/main/remote/host-service.ts+++ b/src/main/remote/host-service.ts@@ -24,7 +24,6 @@// testable with fakes; `initRemoteHost` wires it to IPC, the license gate, and the API call.import { randomUUID } from 'crypto'-import path from 'path'import { app, ipcMain, type BrowserWindow } from 'electron'import { IPC } from '../../shared/ipc'import { REF_MAX_LEN } from '../../shared/presence'@@ -53,6 +52,11 @@ import { connectRelay, type RelaySocket, type RpcRequest } from './relay-socket'import { initHostCanvasHub, currentCanvas, subscribeCanvas } from './host-canvas-hub'import { createPhonePresence, type PhonePresence } from './phone-presence'import { registerPeerSessionKiller } from './peer-revoke'+import type { KeyOutcome, KeyRequest, KeyAnswerKind } from './host-chat'+import { parseRelayKeys } from '../../core/relay-keys'+import { parseRelayLaunch, type RelayLaunchRequest } from '../../core/relay-launch'+import { browseHostDirectory, isWithinRootsFor, type BrowseFs } from '../../core/remote/host-fs-rpc'+import { stripAnsi } from '../../core/transcript-reader'// Default relay endpoint; `NODETERM_RELAY_URL` overrides it (mirrors license.ts's API_BASE /// CHECKOUT_URL env-override pattern — used both as the dev gate and for local testing).@@ -79,8 +83,13 @@ export interface HostPtyManager {prepareRelayAttach(nodeId: string,size: { cols: number; rows: number },- hint?: { projectId?: string }+ hint?: { projectId?: string; launch?: RelayLaunchRequest }): Promise<RelayAttachPrep>+ /** Where a `pty.scroll` wheel for this stream goes (`PtyManager.scrollRoute`). Optional so a+ * pre-feature fake keeps today's tmux-only behaviour. */+ scrollRoute?(sessionId: string): Promise<'tmux' | 'app-mouse' | 'local'>+ /** The node's recent output as plain text (`PtyManager.captureSession`) — `pty.capture`. */+ captureSession?(persistKey: string, full?: boolean): Promise<string>/** Does a session for this node id exist RIGHT NOW? (The destroy path's outcome check.) */sessionExists(persistKey: string): Promise<boolean>/** `clientId` identifies WHO typed (the bridged phone's presence peer), so the keystroke can be@@ -211,6 +220,9 @@ export interface HostChatOps {/** Answer the node's held request (`answerHeldPermission`: validated against the pending* request file, structured-ticket gated). `false` = nothing was written. */answer(nodeId: string, pendingId: string, answer: unknown): Promise<boolean>+ /** Type a closed-set keyed answer (`agent.key`) after re-checking the node's state and open ask+ * on the host. Optional so a pre-feature host / test fake answers an honest "not served". */+ key?(nodeId: string, req: KeyRequest): Promise<KeyOutcome | 'unknown-node'>}interface Stream {@@ -248,15 +260,33 @@ function str(value: unknown): string | undefined {* or `~/.ssh` via `../../`. (Symlinks inside a shared root are not chased; the shared roots are* the user's own project directories.)*/-function isWithinRoots(target: string, roots: string[]): boolean {- if (!target) return false- const resolved = path.resolve(target)- for (const root of roots) {- if (!root) continue- const r = path.resolve(root)- if (resolved === r || resolved.startsWith(r + path.sep)) return true- }- return false+function isWithinRoots(target: string, roots: string[], platform: NodeJS.Platform = process.platform): boolean {+ // The dialect-aware jail lives in core (`host-fs-rpc.ts`): on a Windows host containment is+ // case-insensitive and UNC / drive-relative paths are refused; POSIX is the historical rule.+ return isWithinRootsFor(target, roots, platform)+}++/**+ * The relay verbs added for relay-only (Windows) hosts — one bag, so `createHostHandlers` stops+ * growing positionally. Every member is optional: absent ⇒ the verb answers an honest "not served".+ */+export interface HostRelayExtras {+ /** `process.platform` of this host (test seam). Rides `host.info` and the launch-aware attach. */+ platform?: NodeJS.Platform+ /** A phone read the node's finished turn (`inbox.ack`): resolve its done event(s) and clear the+ * desktop unread dot — `applyPhoneReadAck`, the same pair the ack sweeper runs. */+ inboxAck?: (nodeId: string) => void+ /** The folder browser's jail root (the host's home) and fs (`fs.browse`). */+ browse?: { home: () => string; fs: BrowseFs }+}++/** Methods this host serves beyond the pre-relay-parity set, for `host.info` feature detection. A+ * phone that gets `Unknown method: host.info` is talking to an older host and keeps its old path. */+export const RELAY_PARITY_VERBS = ['host.info', 'agent.key', 'inbox.ack', 'fs.browse', 'pty.capture'] as const++/** An inbox event id (`${ts}-${seq}`, agent-status-mirror) — the same closed shape as a pending id. */+function isInboxEventId(id: string): boolean {+ return /^[0-9]{1,16}-[0-9]{1,12}$/.test(id)}export function createHostHandlers(@@ -300,8 +330,11 @@ export function createHostHandlers(kanban?: HostKanbanOps,// The phone's Chat screen (`chat.page` / `chat.status` / `chat.send` / `agent.answer`).// Absent ⇒ the verbs answer an honest "not served".- chat?: HostChatOps+ chat?: HostChatOps,+ // Relay-only-host parity verbs (`inbox.ack`, `fs.browse`, `host.info`; see HostRelayExtras).+ extras: HostRelayExtras = {}): HostHandlers {+ const hostPlatform = extras.platform ?? process.platform// streamId -> Stream. PTY callbacks close over their own `streamId` directly, so no// reverse (sessionId -> streamId) index is needed.const streams = new Map<number, Stream>()@@ -425,10 +458,22 @@ export function createHostHandlers(// local node gets the env the desktop would give it. The phone's optional `projectId` can only// choose among those records or refuse; it never routes a node anywhere on its own.const projectHint = str(p.projectId)+ // `launch` (additive): the phone asks the HOST to start the agent in a session this attach+ // creates, instead of typing a POSIX shell line into it — which a Windows host's pwsh / cmd+ // cannot parse (core/relay-launch.ts). Shape-checked here; registry, account and agent checks+ // happen in core. A cwd outside the shared roots is dropped (the record / home stands), never+ // trusted: the jail is the same one `fs.*` lives in.+ const launchAsked = p.launch !== undefined+ const launchReq = launchAsked ? parseRelayLaunch(p.launch) : null+ if (launchReq?.cwd && !isWithinRoots(launchReq.cwd, getRoots(), hostPlatform)) delete launchReq.cwdvoid (async () => {let prep: RelayAttachPreptry {- prep = await pty.prepareRelayAttach(nodeId, { cols, rows }, { projectId: projectHint })+ prep = await pty.prepareRelayAttach(+ nodeId,+ { cols, rows },+ launchReq ? { projectId: projectHint, launch: launchReq } : { projectId: projectHint }+ )} catch {prep = { kind: 'refused', reason: 'not-connected', message: 'Could not prepare this session.' }}@@ -453,7 +498,18 @@ export function createHostHandlers(prep.sessionExists().catch(() => true),new Promise<boolean>((r) => setTimeout(() => r(true), FRESH_PROBE_BUDGET_MS))])- socket.respond(req.id, true, { streamId, fresh: !existed })+ // The host owns the launch only for a session this attach is CREATING, and only once (the+ // reply is the one place that says so: `launched: true` = "type nothing").+ const launch = !existed && prep.launch ? prep.launch : undefined+ socket.respond(req.id, true, {+ streamId,+ fresh: !existed,+ // Additive, and only when they say something an old phone could get wrong: `scroll:'local'`+ // = 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 } : {})+ })const snapshot = await prep.snapshot().catch(() => '')// The stream may have been killed/closed while the capture was in flight.if (!streams.has(streamId)) return@@ -468,6 +524,7 @@ export function createHostHandlers(return}stream.sessionId = sessionId+ if (launch) void launch().catch(() => false)} catch {// Attach failed (e.g. tmux unavailable, master gone) — surface as an exit so the client// tears down.@@ -492,7 +549,7 @@ export function createHostHandlers(// Confine remote filesystem access to the shared project roots. A path outside them (or any// `../` traversal) is denied — degrade to the same empty/false shape fs-ops returns on error,// so the remote Explorer/Editor just sees "nothing there" rather than a thrown RPC.- if (!isWithinRoots(filePath, getRoots())) {+ if (!isWithinRoots(filePath, getRoots(), hostPlatform)) {switch (req.method) {case 'fs.list':respond({ entries: [] })@@ -528,24 +585,47 @@ export function createHostHandlers(* Scroll a remote client's view of the session's tmux history.** Scrolling belongs to tmux (its mouse is on and the pane lives on the alternate screen, so the- * client's emulator has no scrollback of its own). This stream's pty IS a tmux client, so the+ * client's emulator has no scrollback of its own). When this stream's pty IS a tmux client, the* wheel is simply written into it as an SGR mouse event and tmux does the rest — no tmux command* channel, no copy-mode bookkeeping on our side. The phone drives this because it cannot deliver* the wheel itself: its own emulator would swallow the gesture.*+ * Not every stream has a tmux in front of it. A session-host pane (Windows) or a plain shell has+ * nothing to consume the wheel, so the bytes would land in the prompt as escape text. The route+ * (`PtyManager.scrollRoute`) therefore decides: `tmux` and `app-mouse` (a TUI that asked for the+ * mouse) get the wheel exactly as before; `local` gets nothing — the phone was told+ * `scroll:'local'` at attach and holds the full buffer. Still answered ok, so an old phone that+ * keeps sending scrolls sees no error.+ ** `lines` is untrusted (it arrives from a remote client) — clamp it, and address the wheel to* cell 1,1 so a hostile value cannot be interpolated anywhere interesting.*/function handleScroll(req: RpcRequest): void {const p = asRecord(req.params)const stream = streams.get(num(p.streamId, -1))- if (stream) {- const up = str(p.dir) !== 'down'- const notches = Math.min(20, Math.max(1, Math.floor(num(p.lines, 1))))- const seq = `\x1b[<${up ? 64 : 65};1;1M`+ if (!stream) {+ socket.respond(req.id, true, {})+ return+ }+ const up = str(p.dir) !== 'down'+ const notches = Math.min(20, Math.max(1, Math.floor(num(p.lines, 1))))+ const seq = `\x1b[<${up ? 64 : 65};1;1M`+ const write = (): void => {for (let i = 0; i < notches; i++) pty.write(getClientId(), stream.sessionId, seq)}- socket.respond(req.id, true, {})+ if (!pty.scrollRoute) {+ write()+ socket.respond(req.id, true, {})+ return+ }+ void pty+ .scrollRoute(stream.sessionId)+ .catch(() => 'local' as const)+ .then((route) => {+ // Re-checked: the stream may have closed while the route was asked.+ if (route !== 'local' && streams.get(num(p.streamId, -1)) === stream) write()+ socket.respond(req.id, true, {})+ })}// Serve a typed `git.*` verb against the injected GitService slice, jailed to the shared roots@@ -558,7 +638,7 @@ export function createHostHandlers(}const p = asRecord(req.params)const cwd = str(p.cwd) ?? ''- if (!isWithinRoots(cwd, getRoots())) {+ if (!isWithinRoots(cwd, getRoots(), hostPlatform)) {socket.respond(req.id, false, { message: 'cwd is outside the shared project roots.' })return}@@ -922,6 +1002,50 @@ export function createHostHandlers(.catch(() => socket.respond(req.id, true, { result: 'refused', reason: 'unavailable' }))return}+ case 'agent.key': {+ // `agent.key {nodeId, key | digits, expect: {ask, states?}, pendingId?}` — the keyed half of+ // the Inbox / push / Live Activity answers, for a host the phone cannot reach over SSH. A+ // CLOSED key set (relay-keys.ts): no free text crosses. The node's state and open ask are+ // re-checked against the host's own mirror inside `chat.key`.+ if (!chat.key) {+ fail('agent.key is not served on this host.')+ return+ }+ const keys = parseRelayKeys({ key: p.key, digits: p.digits })+ if (!keys) {+ fail('agent.key requires key (a digit 1-9, "escape" or "enter") or digits (1-9).')+ return+ }+ const expect = asRecord(p.expect)+ const ask = str(expect.ask)+ if (ask !== 'approval' && ask !== 'question' && ask !== 'submit') {+ fail('agent.key requires expect.ask: "approval", "question" or "submit".')+ return+ }+ // A multi-select batch is only ever a question's Submit.+ if (p.digits !== undefined && ask !== 'submit') {+ fail('agent.key digits are a multi-select submit (expect.ask "submit").')+ return+ }+ const states = Array.isArray(expect.states)+ ? expect.states.filter((x): x is string => typeof x === 'string')+ : undefined+ const pendingId = str(p.pendingId)+ void chat+ .key(nodeId, {+ keys,+ ask: ask as KeyAnswerKind,+ ...(states ? { states } : {}),+ ...(pendingId && isValidPendingId(pendingId) ? { pendingId } : {})+ })+ .then((out) =>+ out === 'unknown-node'+ ? fail('Unknown node.')+ : socket.respond(req.id, true, out satisfies KeyOutcome)+ )+ .catch(() => socket.respond(req.id, true, { result: 'refused', reason: 'unavailable' }))+ return+ }case 'agent.answer': {const pendingId = str(p.pendingId)if (!pendingId || !isValidPendingId(pendingId)) {@@ -937,9 +1061,98 @@ export function createHostHandlers(}}+ /** A node id a list-scoped verb may take from the client (the `handleNodeAction` envelope). */+ function validNodeId(v: unknown): string | null {+ const id = str(v)+ // eslint-disable-next-line no-control-regex -- refusing control chars is the point+ return id && id.length <= REF_MAX_LEN && !/[\x00-\x1f\x7f-\x9f]/.test(id) ? id : null+ }++ /**+ * `inbox.ack {nodeId, eventId}` — the phone READ a finished turn. Over SSH the phone drops+ * `~/.nodeterm/acks/<nodeId>.seen` for the ack sweeper; a relay-only host (Windows) has no SSH,+ * so the ack arrives here and runs the SAME pair the sweeper runs (`applyPhoneReadAck`: resolve+ * the node's done event(s) + clear the desktop unread dot without re-acking). Idempotent: the+ * mirror's `ackDone` is a no-op once nothing is unresolved.+ */+ function handleInboxAck(req: RpcRequest): void {+ if (!extras.inboxAck) {+ socket.respond(req.id, false, { message: 'inbox.ack is not served on this host.' })+ return+ }+ const p = asRecord(req.params)+ const nodeId = validNodeId(p.nodeId)+ const eventId = str(p.eventId)+ if (!nodeId || !eventId || !isInboxEventId(eventId)) {+ socket.respond(req.id, false, { message: 'inbox.ack requires a nodeId and an eventId.' })+ return+ }+ try {+ extras.inboxAck(nodeId)+ socket.respond(req.id, true, { ok: true })+ } catch {+ socket.respond(req.id, true, { ok: false })+ }+ }++ /**+ * `fs.browse {path?}` — the phone's new-project folder browser on a host it cannot SSH into.+ * Directories only, jailed to the host's home (in the host's own path dialect: case-insensitive,+ * no UNC, no other drive on Windows), capped. Unlike `fs.*`, which is jailed to project roots,+ * this is the one way to see a folder that is NOT a project yet — so it reveals names, never+ * contents. A refusal answers `ok:false` with a sentence.+ */+ function handleBrowse(req: RpcRequest): void {+ const browse = extras.browse+ if (!browse) {+ socket.respond(req.id, false, { message: 'fs.browse is not served on this host.' })+ return+ }+ const target = str(asRecord(req.params).path)+ void browseHostDirectory(target, { platform: hostPlatform, home: browse.home(), fs: browse.fs })+ .then((res) =>+ res+ ? socket.respond(req.id, true, res)+ : socket.respond(req.id, false, { message: 'This folder cannot be opened from here.' })+ )+ .catch(() => socket.respond(req.id, false, { message: 'This folder cannot be opened from here.' }))+ }++ /**+ * `pty.capture {streamId}` — the stream's recent output as PLAIN text (the phone's clean copy+ * reconciles against it). Resolved from the stream, never a client node id, and through+ * PtyManager's own capture (tmux capture-pane, the remote host's, or the session host's emulator)+ * — never a raw tmux command. A failure is `{text: ''}`: the phone then keeps its own buffer.+ */+ function handleCapture(req: RpcRequest): void {+ const stream = streams.get(num(asRecord(req.params).streamId, -1))+ if (!stream || !pty.captureSession) {+ socket.respond(req.id, true, { text: '' })+ return+ }+ void pty+ .captureSession(stream.persistKey, false)+ // The session host's capture is a serialized screen (SGR, modes); tmux's `-p` is plain.+ .then((text) => socket.respond(req.id, true, { text: stripAnsi(text ?? '') }))+ .catch(() => socket.respond(req.id, true, { text: '' }))+ }+return {onRpc(req) {switch (req.method) {+ case 'host.info':+ // Feature detection for the relay-only-host verbs (no client params, read-only).+ socket.respond(req.id, true, { platform: hostPlatform, verbs: [...RELAY_PARITY_VERBS] })+ break+ case 'inbox.ack':+ handleInboxAck(req)+ break+ case 'fs.browse':+ handleBrowse(req)+ break+ case 'pty.capture':+ handleCapture(req)+ breakcase 'pty.create':// Reject: remote clients only ever attach to the host's existing tmux sessions// (`pty.attach`). `pty.create` would let a client spawn an arbitrary shell with a@@ -986,6 +1199,7 @@ export function createHostHandlers(case 'chat.status':case 'chat.send':case 'agent.answer':+ case 'agent.key':handleChat(req)breakcase 'node.wake':@@ -1239,6 +1453,8 @@ export interface HostSessionOptions {kanban?: HostKanbanOps/** The phone's Chat screen verbs (`chat.*` / `agent.answer`). Optional: absent ⇒ "not served". */chat?: HostChatOps+ /** Relay-only-host parity verbs (`inbox.ack`, `fs.browse`). Optional: absent ⇒ "not served". */+ relayExtras?: HostRelayExtras/** Extra fs/git jail roots beyond the shared canvas's node cwds — production passes the* workspace's local project cwds: the phone browses EVERY project over `projects.list`, so a* canvas-only jail denied whichever project the desktop didn't happen to have focused. */@@ -1364,7 +1580,8 @@ export function connectHostSession(opts: HostSessionOptions): HostSession {opts.remoteViewer,opts.nodeActions,opts.kanban,- opts.chat+ opts.chat,+ opts.relayExtras ?? {})canvasSync = createHostCanvasSync(socket, opts.applyMutation)unsubCanvas = opts.subscribeCanvas(() => scheduleBroadcast())@@ -1397,6 +1614,8 @@ export interface HostBridgeDeps {kanban?: HostKanbanOps/** The phone's Chat screen verbs — see main/remote/host-chat.ts and main/index.ts's wiring. */chat?: HostChatOps+ /** Relay-only-host parity verbs (`inbox.ack`, `fs.browse`) — see main/index.ts's wiring. */+ relayExtras?: HostRelayExtras/** Workspace-level jail roots (local project cwds) merged with the canvas node cwds. */workspaceRoots?: () => string[]}@@ -1479,6 +1698,7 @@ export function initRemoteHost(nodeActions: bridge.nodeActions,kanban: bridge.kanban,chat: bridge.chat,+ relayExtras: bridge.relayExtras,extraRoots: bridge.workspaceRoots,// Typing attribution: this session's input frames are this phone's keystrokes.getClientId: () => phone.id(),diff --git a/src/main/remote/standing-host.ts b/src/main/remote/standing-host.tsindex fec11203a..a52153cbe 100644--- a/src/main/remote/standing-host.ts+++ b/src/main/remote/standing-host.ts@@ -460,6 +460,7 @@ export function initStandingHost(nodeActions: bridge.nodeActions,kanban: bridge.kanban,chat: bridge.chat,+ relayExtras: bridge.relayExtras,extraRoots: bridge.workspaceRoots,// Typing attribution: this pooled session's input frames are ITS phone's keystrokes.getClientId: () => pooled.presence.id(),