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.

Merge branch 'feat/win-01-relay-phone' into feat/windows-parity

review488581d1da18
diff --cc docs/windows-session-host.md
index 550eb2917,a9534a7a4..08a8303f4
--- a/docs/windows-session-host.md
+++ b/docs/windows-session-host.md
@@@ -145,18 -143,11 +145,19 @@@ long-lived connection (no positional-FI
| `sendKeys` | `send-keys -l -- <text>` (+ `Enter`) | full — works with no attached client, exactly like tmux |
| `paneCommand` | `display-message -p '#{pane_current_command}'` | approximated — see `process-tree.ts` |
| `capture` | `capture-pane -p -e [-S -N]` | full, and strictly more (mode restoration — tmux's plain-text capture carries none) |
+ | `paneModesV1` | (none — tmux owns the mouse itself) | additive: the pane app's mouse-tracking protocol, for relay scroll routing; an older host answers `unknown command` = "no mouse" |
| `killSession` | `kill-session -t <name>` | full |
| `detach` | a client's own `tmux detach-client` | full |
-| `listSessions` | `list-sessions -F '#{session_name}'` | full |
+| `listSessions` | `list-sessions -F '#{session_name}'` — plus, with `sessionDetails`, `list-windows`/`list-panes` | full; see "Observability" below |
| `ping` | (liveness probe used during the startup race) | full |
+| `attachExisting {watch: true}` | `attach-session -E -f ignore-size,read-only` (a live link watcher's client) | feature `watch-attach`: subscribes with NO geometry claim and no pause ticket, refuses `write`/`resize` from that connection, never spawns; on an already-attached connection it withdraws the claim (its last voting subscriber left) |
+| `captureVisible` | `capture-pane -p -e` + `display-message '#{cursor_x} #{cursor_y}'` | feature `captureVisible`: visible rows of the ACTIVE buffer only (never history), viewport cursor, `altScreen` — a live link's keyframe |
+| `paneCwd` | `display-message -p '#{pane_current_path}'` | feature `paneCwd`: the cwd the pane last REPORTED (OSC 7 / 9;9 / 633, parsed by `cwd-report.ts`), null until one arrives — never the spawn cwd |
+
+The last three are **negotiated at hello** (`SESSION_HOST_FEATURES`) like `geometry`/`shutdown`: the
+client never sends one to a host that did not advertise it (an older, long-lived host keeps serving
+everything else and is never replaced for them). Without them: a live link viewer of a node this app
+does not hold is refused (`join-only`), there is no keyframe (R36), and `paneCwd` is null.
**Not implemented — deliberately out of scope for this pass:**
diff --cc src/core/__fixtures__/no-session-host.ts
index 3df9eadcd,428810ad7..83524a32f
--- a/src/core/__fixtures__/no-session-host.ts
+++ b/src/core/__fixtures__/no-session-host.ts
@@@ -49,18 -49,9 +49,22 @@@ export function noSessionHost(): Record
sessionHostListSessions: async () => [],
sessionHostPaneCommand: async () => null,
sessionHostSendKeys: async () => false,
+ sessionHostCaptureVisible: async () => null,
+ sessionHostPaneCwd: async () => null,
+ sessionHostSupportsWatch: async () => false,
+ sessionHostWatchKnown: () => undefined,
+ sessionHostListSessionsDetailed: async () => null,
+ sessionHostMessageOwner: async () => null,
+ sessionHostMessagePasteReady: async () => false,
+ sessionHostMessageEnvelope: async () => false,
+ sessionHostTerminateOwner: async () => 'unsupported',
+ sessionHostWriteDetached: async () => false,
+ // Error classes are read by `instanceof` checks on catch paths; a fresh class never matches.
+ SessionHostProtocolCompatibilityError: class extends Error {},
- SessionHostWatchUnsupportedError: class extends Error {}
++ SessionHostWatchUnsupportedError: class extends Error {},
+ sessionHostMouseTracking: async () => null,
+ sessionHostExecuteLaunch: async () => {
+ throw new Error('session-host launch in a suite that mocked the backend out')
+ }
}
}
diff --cc src/core/pty-manager.ts
index 591fdd760,aefd2ee7d..330ea5be2
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@@ -215,20 -214,15 +216,24 @@@ import
sessionHostMessageEnvelope,
sessionHostSendKeys,
sessionHostSupported,
+ sessionHostTerminateOwner,
+ sessionHostWriteDetached,
+ SessionHostProtocolCompatibilityError,
+ watchExistingSessionHostPty,
+ sessionHostSupportsWatch,
+ sessionHostWatchKnown,
+ sessionHostCaptureVisible,
- sessionHostPaneCwd
++ sessionHostPaneCwd,
+ sessionHostMouseTracking,
- sessionHostExecuteLaunch,
- SessionHostProtocolCompatibilityError
++ sessionHostExecuteLaunch
} from './session-host-backend'
import type { SessionHostPty } from './session-host-pty'
+import type { SessionHostReaperBackend, SessionInfo } from './session-budget'
import { NativeWindowsPane } from './native-windows-pane'
+import { terminatePaneOwner } from '../session-host/terminate-owner'
import type { ProjectSpawnOverrides, ProjectSpawnOverridesReader } from './project-spawn-overrides'
+ import { buildRelayLaunch, relayLaunchAgentKnown, relayLaunchDialect, relayLaunchPreflight, type RelayLaunchContext, type RelayLaunchRequest } from './relay-launch'
+ import { RELAY_KEY_GAP_MS, rawKeyBytes, tmuxKeyArgs, type RelayKey } from './relay-keys'
// How often we snapshot a live tmux session's scrollback to disk, so a machine reboot (which
// kills the tmux server) can still replay recent output on cold restart. A final snapshot also
@@@ -3685,6 -3567,187 +3719,196 @@@ 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, req.agentId)) options.accountId = req.accountId
+ return req
+ }
+
+ /** `relayLaunchPreflight` for this node's pane: a Windows pane unless a tmux (or a live non-Windows
+ * backend) will hold it. A throwing context means no launch. */
+ private async relayLaunchViable(req: RelayLaunchRequest, persistKey: string): Promise<boolean> {
+ const ctxFn = this.relayLaunchContext
+ if (!ctxFn) return false
+ try {
+ const live = this.liveSessionForPersistKey(persistKey)
+ const windowsPane =
+ this.runtimePlatform === 'win32' &&
+ (live ? !!live.sessionHost || !!live.nativeWindowsPane || !live.tmuxBacked : !(this.tmuxPath && this.getSettings().tmuxEnabled))
+ return await relayLaunchPreflight(req, ctxFn(), windowsPane)
+ } catch {
+ return false
+ }
+ }
+
+ /** How long a relay launch waits for a shell to own the fresh pane before giving up. */
+ static readonly RELAY_LAUNCH_SHELL_WAIT_MS = 10_000
+
+ /**
+ * 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` =
++ * has no tmux, takes the raw bytes through a client this process already holds (or, released, by name). `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
+ // An SSH-project node with no client of ours held right now lives on the HOST's tmux: its
+ // owner's ControlMaster is the only way there. Never fall through to the LOCAL socket — a
+ // same-named local `nt-<id>` (the pre-`requireRemote` orphan) would take the keystroke, and a
+ // stray `1` / Enter into an unrelated pane is exactly what the closed key set exists to stop.
+ const owner = live ? null : (this.remoteNodeOwner?.(persistKey) ?? null)
+ if (owner && !owner.remote) return false
+ const sshRemote = live?.sshRemote ?? owner?.remote
+ 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 (sshRemote) {
+ const ssh = findSsh()
+ if (!ssh) return false
+ await runAsync(ssh, remoteSendKeyArgs(sshRemote.conn, sshRemote.controlPath, target, tmuxKeyArgs(key)))
+ } else if (live?.sessionHost || !this.tmuxPath) {
- // No name-addressed raw write exists on the session host (its `sendKeys` is a paste),
- // so a key needs a client this process holds — the desktop node, or a relay stream.
++ // The session host's `sendKeys` is a paste, so a key needs a client this process holds
++ // (the desktop node, or a relay stream) — or, for a RELEASED session-host node, the
++ // name-addressed raw write (`writeDetachedV1`, same gate as `write()`'s released leg;
++ // an older host refuses it, which is a plain `false`, never a sendKeys fallback).
+ const current = this.liveSessionForPersistKey(persistKey)
- if (!current?.sessionHost) return false
- current.proc.write(rawKeyBytes(key))
++ if (current?.sessionHost) {
++ current.proc.write(rawKeyBytes(key))
++ } else {
++ const released = this.released.get(persistKey)
++ if (!released?.sessionHost || released.remote) return false
++ if (!this.getSettings().tmuxEnabled || !sessionHostSupported()) return false
++ if (!isSessionName(target)) return false
++ if (!(await sessionHostWriteDetached(target, rawKeyBytes(key)))) return false
++ }
+ } 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 before
diff --cc src/core/session-host-client.ts
index a072af405,281d560dc..ba9025c06
--- a/src/core/session-host-client.ts
+++ b/src/core/session-host-client.ts
@@@ -33,9 -32,7 +33,10 @@@ import
type HasSessionResult,
type PaneCommandResult,
type CaptureResult,
+ type CaptureVisibleResult,
+ type PaneCwdResult,
+ type SessionHostFeature,
+ type PaneModesResult,
type KillSessionResult,
type ExecuteLaunchResult,
type ListSessionsResult,
@@@ -1850,39 -1646,19 +1851,52 @@@ export class SessionHostClient
} catch { return false }
}
+ /** `terminateOwnerV1`. `'unsupported'` = the live host predates the verb (it answered `unknown
+ * command`) — distinct from `false`, so the UI can say "restart the app" instead of "busy". Any
+ * other failure, a lost reply included, is `false`: the caller then refuses to recycle. Never
+ * retried — a second kill aimed at a re-proven owner is the host's job, not a resend's. */
+ async terminateOwner(name: string, expected: PaneOwner): Promise<boolean | 'unsupported'> {
+ try {
+ const result = await this.request<{ terminated?: unknown } | undefined>(
+ { cmd: 'terminateOwnerV1', name, expected },
+ undefined,
+ undefined,
+ TERMINATE_OWNER_REQUEST_TIMEOUT_MS
+ )
+ return result?.terminated === true
+ } catch (error) {
+ return error instanceof SessionHostRequestRejectedError && error.message === 'unknown command'
+ ? 'unsupported'
+ : false
+ }
+ }
+
+ /** `writeDetachedV1`: raw bytes into a session this process holds no attachment on. True only on
+ * the host's acknowledgement. NEVER retried and never re-routed through `sendKeys`: a lost reply
+ * may still have been typed, and an older host's refusal never reached the pty at all — either
+ * way a second attempt risks typing the input twice or in a different shape. */
+ async writeDetached(name: string, data: string): Promise<boolean> {
+ try {
+ await this.request<unknown>({ cmd: 'writeDetachedV1', name, data })
+ return true
+ } catch {
+ return false
+ }
+ }
+
+ /** The pane app's mouse-tracking protocol, or null when unknown: no such session, or an older
+ * live host that predates `paneModesV1` (never replaced to learn it). Callers treat null as
+ * "the app did not ask for the mouse". */
+ async mouseTrackingMode(name: string): Promise<PaneModesResult['mouseTracking'] | null> {
+ try {
+ const r = await this.request<PaneModesResult | null>({ cmd: 'paneModesV1', name })
+ const m = r?.mouseTracking
+ return m === 'none' || m === 'x10' || m === 'vt200' || m === 'drag' || m === 'any' ? m : null
+ } catch {
+ return null
+ }
+ }
+
async capture(name: string, full: boolean): Promise<string> {
const result = await this.request<CaptureResult>({ cmd: 'capture', name, full })
return result.text
diff --cc src/session-host/host.ts
index e11b710e2,b3f59767e..a129b6e48
--- a/src/session-host/host.ts
+++ b/src/session-host/host.ts
@@@ -29,12 -29,9 +29,13 @@@ import
type HasSessionResult,
type PaneCommandResult,
type CaptureResult,
+ type TerminateOwnerResult,
+ type CaptureVisibleResult,
+ type PaneCwdResult,
+ type PaneModesResult,
type KillSessionResult,
type ListSessionsResult,
+ type SessionHostSessionDetail,
type ShutdownResult
} from './protocol'
import { HostSession } from './session'
@@@ -1019,21 -994,13 +1020,28 @@@ async function main(): Promise<void>
ok: true,
result: await hostMessagePane(() => sessions.get(req.name)).send(req.envelope, req.expected)
}
+ case 'terminateOwnerV1': {
+ const terminated = await terminatePaneOwner(() => sessions.get(req.name), req.expected, {
+ probe: readWindowsConsoleOwner,
+ terminate: (pid) => terminateWindowsProcessTree(pid)
+ })
+ return { ok: true, result: { terminated } satisfies TerminateOwnerResult }
+ }
+ case 'writeDetachedV1': {
+ // No subscriber check, exactly like sendKeys: the caller holds no attachment on purpose.
+ const s = sessions.get(req.name)
+ if (!s || s.exited) return { ok: false, error: 'no such session' }
+ if (typeof req.data !== 'string' || !req.data) return { ok: false, error: 'nothing to write' }
+ s.proc.write(req.data)
+ return { ok: true }
+ }
+ case 'paneModesV1': {
+ const s = sessions.get(req.name)
+ if (!s || s.exited) return { ok: true, result: null }
+ const mouseTracking = await s.mouseTrackingMode()
+ if (s.exited || sessions.get(req.name) !== s) return { ok: true, result: null }
+ return { ok: true, result: { mouseTracking } satisfies PaneModesResult }
+ }
case 'capture': {
const s = sessions.get(req.name)
if (!s || s.exited) return { ok: true, result: { text: '' } satisfies CaptureResult }
diff --cc src/session-host/protocol.ts
index ad241c322,a5ccb0289..014fa032f
--- a/src/session-host/protocol.ts
+++ b/src/session-host/protocol.ts
@@@ -103,21 -98,10 +103,24 @@@ export type SessionHostRequest
| { id: number; cmd: 'messageOwnerV1'; name: string }
| { id: number; cmd: 'messagePasteReadyV1'; name: string }
| { id: number; cmd: 'messageEnvelopeV1'; name: string; envelope: string; expected: PaneOwner }
+ /** End the proven agent process tree (`expected`, from `messageOwnerV1`) without touching the
+ * console root. Result: `TerminateOwnerResult`. Additive like the messaging extension: an older
+ * live host answers `unknown command`, which the client reports as unsupported. */
+ | { id: number; cmd: 'terminateOwnerV1'; name: string; expected: PaneOwner }
+ /** Raw, verbatim keystroke bytes into a session this connection need NOT be attached to — the
+ * `tmux send-keys -H` of a released node. No framing, no sanitizing, no Enter. An older host
+ * answers `unknown command`; the client then fails closed and never falls back to sendKeys. */
+ | { id: number; cmd: 'writeDetachedV1'; name: string; data: string }
| { id: number; cmd: 'capture'; name: string; full: boolean }
+ /** `captureVisible` feature only: the VISIBLE rows (no history) plus cursor + active buffer — a
+ * live link's keyframe. Never sent to a host that did not advertise it. */
+ | { id: number; cmd: 'captureVisible'; name: string }
+ /** `paneCwd` feature only: the last cwd the pane REPORTED (OSC 7 / 9;9 / 633), never the spawn
+ * cwd. */
+ | { id: number; cmd: 'paneCwd'; name: string }
+ /** Additive (the `messageOwnerV1` idiom): an older live host answers `unknown command`, which the
+ * client reads as "unknown", never as a reason to replace the host. Result: `PaneModesResult`. */
+ | { id: number; cmd: 'paneModesV1'; name: string }
| {
id: number
cmd: 'executeLaunch'
@@@ -270,9 -241,10 +273,13 @@@ export interface ExecuteLaunchResult
export interface PaneCommandResult {
command: string | null
}
+export interface TerminateOwnerResult {
+ terminated: boolean
+}
+ /** `result` of `paneModesV1`; `null` result = no such live session. */
+ export interface PaneModesResult {
+ mouseTracking: 'none' | 'x10' | 'vt200' | 'drag' | 'any'
+ }
export interface CaptureResult {
text: string
}