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.

fix(relay): a phone attach never spawns an SSH project's node locally

review3402e438263d
diff --git a/CLAUDE.md b/CLAUDE.md
index 1cdeef29e..3f5cdf6c8 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -774,6 +774,49 @@ Lifecycle, by intent:
The refusal is **only** in `spawnNew` — a co-attach JOIN to a live session for that node id is
still correct. An offline node reports itself to `SshReconnector`, so the canvas heals itself;
`retryNow` (banner Reconnect / node Reconnect) skips the backoff and clears the refuse window.
+ **The phone's relay `pty.attach` is the other way in, and it is closed the same way**
+ (`PtyManager.prepareRelayAttach`, pure routing in `core/relay-attach-plan.ts`). It used to call
+ `attachDetached(nodeId)` → `tmux new-session -A` on the LOCAL socket for whatever id the phone
+ named, with no `sshRemote` and no `requireRemote` — so an SSH project's node opened on the phone
+ before the desktop mounted it became a local shell in this machine's `$HOME` (no context meter, ⌘M
+ fell back to Markdown, work ran on the wrong machine), and the desktop's later mount created a
+ SECOND `nt-<id>` on the host: one node id, two sessions, two machines. Rules a refactor must not
+ undo:
+ - **Where is decided from THIS machine's records, never the phone's words.** The desktop wires
+ `setRelayNodeResolver` (`workspaceStore.relayNodePlacements` — EVERY project holding the id, the
+ node as that project recorded it — plus `SshProjectManager.spawnRefFor` and the index's SSH
+ identity). A node is remote when it carries `sshRemoteTmux` + `ssh` (a host attachment routes
+ over its attachment scope, as `sshConnectionScope` does) or sits in an SSH project; a plain
+ `ssh` terminal (`ssh` without `sshRemoteTmux`) runs `ssh` locally, as the renderer does. The
+ phone's optional `projectId` may only CHOOSE among those placements, or REFUSE (an unknown id it
+ places in an SSH project) — it never routes a node anywhere on its own.
+ - **Remote = over the project's live master, with `requireRemote`, or refused** with a sentence
+ the phone shows (`{message, reason}`: `not-connected` / `no-ssh` / `still-connecting` /
+ `unregistered-remote`). Never a local fallback. A master whose connect setup has not finished
+ (`Conn.setupDone`, set exactly where `connected` is emitted) may only JOIN a session the host
+ positively lists — the renderer's `waitForSshRemote` rule: a session created before the setup
+ chain carries no hook/account env and no tmux.conf, for life.
+ - **The env is the desktop's, from the one builder.** The plan hands `spawnSession` the node's
+ recorded `agentId` / `agentModel` / `accountId` / `cwd` / `shell` / `ownerProjectId`, so
+ `buildPtyEnv` (agent id, canvas-control grant, permission wait), the account dir and project
+ overrides apply exactly as on a desktop create; no second env is written for the relay. The
+ shared pre-spawn refusals (`requireRemote`, the managed-Codex scope) are ONE helper,
+ `spawnRefusal`, used by `spawnNew` and the relay. Pane ownership is still NOT recorded for a
+ relay-created session (unchanged): the owner would be derived from project files, which is the
+ one source that ledger refuses to trust.
+ - **One id in a local AND an SSH project** (the same committed canvas opened in two folders) is
+ answered by whichever session exists: a live LOCAL one wins, otherwise the remote one.
+ - **Existing damage is reported, never killed.** A stray local `nt-<id>` the old path left for a
+ node that only lives remotely is never attached from the relay again (and the desktop's own
+ mounts already pass `requireRemote`), and a relay attach that finds one logs a `[relay] … left
+ untouched` warning. It is not killed automatically: it may hold work typed into it, and nothing
+ proves it idle. Do NOT point a user at the session-memory panel's × for it — a delete resolves
+ remoteness from the index (`planRemoteEnd`) and would end the REAL remote session too; the
+ manual cleanup is `tmux -L node-terminal kill-session -t =nt-<id>`.
+ - Server Edition: no phone relay host, no resolver wired — `prepareRelayAttach` there is the bare
+ local attach it always was. Tests: `relay-attach-plan.test.ts` (matrix),
+ `pty-relay-attach.test.ts` (real PtyManager, node-pty mocked), `remote-security.test.ts`
+ (host reply), `main/relay-attach-wiring.test.ts` (the desktop wire, at source level).
- **Codex's auto-started shared daemon: every nodeterm Codex TUI runs `--no-daemon`** (2026-09-30).
From codex-cli **0.157.0** the `daemon_auto_start` feature is `stable, true` (0.156.1:
`experimental, false`; 0.148.0: no such feature): a plain `codex` TUI no longer runs in-process
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 37a0c4b32..c4a7a09cf 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -491,6 +491,12 @@ anything else. Board-level fields survive every transform — `pullLinks` is one
the relay, so a key that works locks it onto a path that cannot work. CLAUDE.md, "Remote access",
has the details.
+- **A relay attach never decides where a session runs from what the phone sends.** The phone's
+ `pty.attach` goes through `PtyManager.prepareRelayAttach`, which routes an SSH project's node over
+ its project's master or refuses it, and gives a local node the env the desktop would. Never spawn
+ a session for a phone-named node id directly (`attachDetached` / `createDetached`): that is how an
+ SSH node became a local shell in this machine's `$HOME`. CLAUDE.md, "A remote node is NEVER
+ spawned locally".
- **Relay pins are per role, and a revoke is one call.** Pin a peer only through its role's store
in `src/main/remote/approved-devices.ts` (`phonePins` is the only one anything auto-admits from —
never write a desktop peer there), and revoke only through `src/main/remote/peer-revoke.ts`, which
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index e77664783..3391b7058 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -51,6 +51,13 @@ import {
type RemoteEndPlan,
type RemoteNodeOwnerResolver
} from './remote-end'
+import {
+ planRelayAttach,
+ placementIsRemote,
+ type RelayAttachRefusal,
+ type RelayNodePlacement,
+ type RelayRemoteRef
+} from './relay-attach-plan'
import { RemoteSessionIndex, type SessionVerdict } from './remote-ssh/remote-session-index'
import { isSshProgram, nativeExecFileAsync, nativeMux, useNativeSsh } from './remote-ssh/native/native-runtime'
import { NativeSshPty } from './remote-ssh/native/native-pty'
@@ -842,6 +849,34 @@ interface Session {
/** Sinks for a detached session whose output is served somewhere other than the renderer
* (the relay host). The PTY is otherwise identical to a normal session. */
+/** The machine-local records a relay attach is decided from (see `relay-attach-plan.ts`). */
+export interface RelayNodeResolver {
+ /** Every project holding this node id, as THIS machine recorded it. */
+ placements(nodeId: string): readonly RelayNodePlacement[]
+ /** The live ControlMaster (+ its connect-time setup facts) for a connection scope. */
+ refFor(scopeId: string): RelayRemoteRef | undefined
+ /** Is this project an SSH project, per the index (identity, not liveness)? */
+ projectIsRemote(projectId: string): boolean
+}
+
+export type RelayAttachPrep =
+ | {
+ kind: 'refused'
+ reason: RelayAttachRefusal | 'codex-account'
+ /** One sentence the phone can show as-is. */
+ message: string
+ }
+ | {
+ kind: 'ready'
+ 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. */
+ snapshot(): Promise<string>
+ /** Spawn the relay-served client; rejects when nothing could be started. */
+ attach(sinks: DetachedSinks): Promise<string>
+ }
+
export interface DetachedSinks {
onData(data: string): void
onExit(exitCode: number): void
@@ -1111,6 +1146,8 @@ export class PtyManager {
private overridesInFlight = new Map<string, Promise<ProjectSpawnOverrides | null>>()
/** "Which SSH host owns this node?", from the persisted index — see `setRemoteNodeOwner`. */
private remoteNodeOwner: RemoteNodeOwnerResolver | null = null
+ /** Machine-local records the relay host's attach is decided from — see `setRelayNodeResolver`. */
+ private relayNodes: RelayNodeResolver | null = null
/** 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
@@ -2473,21 +2510,26 @@ export class PtyManager {
)
}
- /** Spawn a brand-new session for this client (the non-co-attach path). */
- private async spawnNew(clientId: ClientId, options: PtyCreateOptions): Promise<PtyCreateResult> {
+ /**
+ * The refusals a NEW spawn owes before anything is spawned, shared by `spawnNew` and the relay
+ * host's attach (`prepareRelayAttach`) so the two can never disagree about when a remote node or
+ * an unscoped managed Codex account may start. `undefined` = may spawn.
+ */
+ private spawnRefusal(options: PtyCreateOptions): 'ssh' | 'codex-account' | undefined {
// This node runs on a remote host and we cannot reach it: spawn NOTHING. Everything below
// (and `spawnSession`'s program resolution) falls through to the LOCAL tmux/plain branches
// when `sshRemote` is absent or `ssh` is missing — a silent local shell wearing a remote
// node's identity, which is the one outcome a remote node must never have (see
// `PtyCreateOptions.requireRemote`). Refuse instead; the renderer waits for the master.
//
- // Deliberately here in `spawnNew` and not in `create`: a co-attach JOIN to a live session for
+ // Deliberately on the SPAWN path (`spawnNew`, and the relay host's `prepareRelayAttach`) and
+ // not in `create`: a co-attach JOIN to a live session for
// this node id is still correct (that session already runs wherever it runs), so only the
// branch that would have created a new local session is refused. `findSsh()` is checked for
// the same reason `spawnSession` checks it — without the executable the remote branch there
// is skipped and the local one runs.
if (options.requireRemote && !(options.sshRemote && options.persistKey && findSsh())) {
- return { sessionId: '', fresh: false, unavailable: 'ssh' }
+ return 'ssh'
}
// A managed remote Codex account needs a known id and a safe resolved home so the
// remote env builder can supply its private CODEX_HOME. Otherwise a fresh spawn would
@@ -2500,18 +2542,25 @@ export class PtyManager {
!this.isCodexAccount(options.accountId) ||
!isSafeRemoteHome(options.sshRemote.remoteHome))
) {
- return { sessionId: '', fresh: false, unavailable: 'codex-account' }
+ return 'codex-account'
}
if (!options.persistKey || !findSsh()) {
- return { sessionId: '', fresh: false, unavailable: 'ssh' }
+ return 'ssh'
}
} else {
const scope = resolveCodexSessionScope(platform().userDataDir, options.accountId)
if (isCodexScopeRefusal(scope)) {
- return { sessionId: '', fresh: false, unavailable: 'codex-account' }
+ return 'codex-account'
}
}
}
+ return undefined
+ }
+
+ /** Spawn a brand-new session for this client (the non-co-attach path). */
+ private async spawnNew(clientId: ClientId, options: PtyCreateOptions): Promise<PtyCreateResult> {
+ const refused = this.spawnRefusal(options)
+ if (refused) return { sessionId: '', fresh: false, unavailable: refused }
// A tmux-backed session is "fresh" (cold start) when no live session exists to reattach to
// — i.e. first open, or after a machine reboot killed the tmux server. Plain (non-tmux)
// sessions are always fresh: they have no cross-restart continuity. The renderer uses this
@@ -2625,22 +2674,13 @@ export class PtyManager {
if (options.agentId && hasSharedIdentity(options.agentId as AgentId) && !options.sshRemote) {
installCodexLauncher()
}
- // Resolved HERE rather than inside `spawnSession` because that function is synchronous and two
- // of its three callers (`createDetached`/`attachDetached`, the relay host's attach path) are
- // synchronous public API.
- //
- // Those two are NOT merely attaches — `attachDetached` goes through `tmux new-session -A`, which
- // CREATES when the host's session died (that is exactly what `sessionExists` is asked ahead of,
- // and what `fresh` reports). What makes them override-less is narrower and true either way: the
- // relay host passes only `{cols, rows}` (host-service.ts), so those spawns carry no
- // `ownerProjectId` — and no cwd, agent or account either. (They DO get the base hook env:
- // `persistKey` is set and `sshRemote` is not, so `buildPtyEnv(persistKey)` below runs — node id
- // and endpoint, but none of the agent-gated vars.) A mirrored client that lands on a re-created
- // session gets the same bare login shell it got before this feature.
+ // Resolved HERE rather than inside `spawnSession` because that function is synchronous. Its
+ // other callers resolve their own: the relay host's attach (`prepareRelayAttach`) awaits the
+ // same `projectSpawnOverrides` with the node's recorded owner, while `createDetached` /
+ // `attachDetached` pass none (no project owner ⇒ no overrides).
const projectOverrides = await this.projectSpawnOverrides(options)
- // Resolved HERE for the same synchronous-spawnSession reason as projectOverrides — and the
- // relay host's detached callers pass no `sshRemote` at all, so this is the one path that needs
- // it. Re-derive the login-agent pin for the endpoint (issue #427): same memoized `ssh -G`
+ // Resolved HERE for the same synchronous-spawnSession reason as projectOverrides (the relay
+ // host's remote attach runs the same probe in `spawnRelayRemote`). Re-derive the login-agent pin for the endpoint (issue #427): same memoized `ssh -G`
// probe the ControlMaster's connect uses, and it OVERWRITES any inbound value — `sshRemote` is
// renderer-built and its conn can descend from a shareable project file, so only the local
// probe may decide which agent socket the argv builders pin. The annotated conn is what the
@@ -3297,6 +3337,177 @@ export class PtyManager {
return this.spawnSession({ ...options, persistKey }, null, sinks)
}
+ /**
+ * Wire the machine-local records the relay host's attach is decided from — see
+ * `relay-attach-plan.ts`. The desktop wires the workspace index + the SSH-project manager; the
+ * Server Edition has no relay host and wires none, which leaves `prepareRelayAttach` on its
+ * pre-fix behaviour (a bare local attach).
+ */
+ setRelayNodeResolver(resolve: RelayNodeResolver | null): void {
+ this.relayNodes = resolve
+ }
+
+ /**
+ * Prepare a relay-served attach to the session for `nodeId` (the phone's `pty.attach`).
+ *
+ * Replaces the bare `attachDetached`, which ran `tmux new-session -A` on the LOCAL socket for
+ * whatever id the phone named — so a node of an SSH project, tapped on the phone before the
+ * desktop had mounted it, came up as a local shell in this machine's `$HOME` (the invariant
+ * `PtyCreateOptions.requireRemote` states, broken from the one path that never set it), and a
+ * local node the phone happened to create first was created with no agent / account / cwd env,
+ * which tmux then ignores on every later attach.
+ *
+ * WHERE and WITH WHAT come only from this machine's records (`planRelayAttach`); the phone's
+ * optional `projectId` may only choose among them, or refuse. A remote node runs over its
+ * project's live ControlMaster (`requireRemote`, so a master or `ssh` that disappears in between
+ * spawns nothing), or is REFUSED with a sentence the phone can show.
+ *
+ * Split in three because the host must answer `fresh` before it sends the snapshot, and the
+ * snapshot before any live output: `sessionExists` → reply → `snapshot` → `attach`.
+ */
+ async prepareRelayAttach(
+ nodeId: string,
+ size: { cols: number; rows: number },
+ hint: { projectId?: string } = {}
+ ): Promise<RelayAttachPrep> {
+ const resolver = this.relayNodes
+ const placements = resolver?.placements(nodeId) ?? []
+ const live = this.liveSessionForPersistKey(nodeId)
+ const liveRemote: RelayRemoteRef | undefined = live?.sshRemote
+ ? {
+ conn: live.sshRemote.conn,
+ controlPath: live.sshRemote.controlPath,
+ hookEndpointPath: live.sshRemote.hookEndpointPath,
+ tmuxConfPath: live.sshRemote.tmuxConfPath,
+ remoteHome: live.sshRemote.remoteHome
+ }
+ : undefined
+ // Asked only when the records disagree (one id in a local AND an SSH project): then whichever
+ // session already exists wins, and a LOCAL one must be really local — a live remote client
+ // held by this process says nothing about the local socket.
+ const mixed =
+ placements.some(placementIsRemote) && placements.some((p) => !placementIsRemote(p))
+ const localSessionExists =
+ mixed && !liveRemote ? await this.sessionExists(nodeId).catch(() => false) : undefined
+ const plan = planRelayAttach({
+ placements,
+ projectHint: hint.projectId,
+ hintIsRemoteProject: hint.projectId ? !!resolver?.projectIsRemote(hint.projectId) : false,
+ refFor: (scope) => resolver?.refFor(scope),
+ liveRemote,
+ sshAvailable: !!findSsh(),
+ localSessionExists
+ })
+ if (plan.kind === 'refuse') return { kind: 'refused', reason: plan.reason, message: plan.message }
+ const options: PtyCreateOptions = {
+ ...plan.options,
+ persistKey: nodeId,
+ cols: size.cols,
+ rows: size.rows
+ }
+ const refused = this.spawnRefusal(options)
+ if (refused) {
+ return {
+ kind: 'refused',
+ reason: refused === 'ssh' ? 'no-ssh' : 'codex-account',
+ message:
+ refused === 'ssh'
+ ? 'This session lives on a remote host this computer cannot reach right now. Nothing was started here.'
+ : "This session's Codex account is not available on this computer. Nothing was started here."
+ }
+ }
+ // A stray LOCAL `nt-<id>` for a node that only ever lived remotely is what the pre-fix relay
+ // attach left behind. It is never attached from here again, and never killed either (it may
+ // hold work someone typed into it): say so where an operator will find it.
+ if (plan.kind === 'remote' && !mixed && this.tmuxPath && !live) {
+ void this.strictTmuxVerdict(nodeId).then((v) => {
+ if (v === 'present')
+ console.warn(
+ `[relay] ${sessionName(nodeId)} exists on the LOCAL tmux socket but node ${nodeId} lives on ${plan.hostKey}; the phone was attached to the remote session and the local one was left untouched`
+ )
+ })
+ }
+ if (plan.kind === 'remote') {
+ const sshRemote = options.sshRemote as NonNullable<PtyCreateOptions['sshRemote']>
+ const name = sessionName(nodeId)
+ // A master whose connect is still setting up may JOIN a session the host positively lists
+ // (`new-session -A` on a live session only attaches), never CREATE one: a session created now
+ // would carry no hook/account env and no tmux.conf for life — the renderer's
+ // `waitForSshRemote` rule, applied here.
+ if (!plan.setupDone) {
+ const verdict = await this.remoteSessionVerdict(sshRemote, name).catch(() => 'unknown' as const)
+ if (verdict !== 'present') {
+ return {
+ kind: 'refused',
+ reason: 'still-connecting',
+ message: `This computer is still connecting to ${plan.hostKey}. Try again in a moment. Nothing was started here.`
+ }
+ }
+ }
+ return {
+ kind: 'ready',
+ remote: true,
+ sessionExists: async () =>
+ (await this.remoteSessionVerdict(sshRemote, name).catch(() => 'unknown' as const)) !== 'absent',
+ snapshot: async () => {
+ const ssh = findSsh()
+ if (!ssh) return ''
+ try {
+ const { stdout } = await runAsync(
+ ssh,
+ remoteCaptureVisibleArgs(sshRemote.conn, sshRemote.controlPath, name),
+ { encoding: 'utf-8', maxBuffer: 8 * 1024 * 1024 }
+ )
+ return parseVisibleCapture(stdout).screen
+ } catch {
+ return ''
+ }
+ },
+ attach: (sinks) => this.spawnRelayRemote(options, sinks)
+ }
+ }
+ return {
+ kind: 'ready',
+ remote: false,
+ sessionExists: () => this.sessionExists(nodeId),
+ snapshot: () => this.captureSnapshot(nodeId),
+ attach: async (sinks) => {
+ await resolveShellPath()
+ const overrides = await this.projectSpawnOverrides(options)
+ return this.spawnSession(options, null, sinks, undefined, overrides)
+ }
+ }
+ }
+
+ /** The remote half of `prepareRelayAttach`'s attach: the same pin / overrides / spawn-gate
+ * sequence `spawnNew` runs for a remote node, then a co-attach (`sinks` ⇒ no `-D`). */
+ private async spawnRelayRemote(options: PtyCreateOptions, sinks: DetachedSinks): Promise<string> {
+ // Re-asked at spawn time: `spawnSession` falls through to the LOCAL branch without `ssh`.
+ if (this.spawnRefusal(options)) throw new Error('remote host unreachable — nothing was started')
+ const remote = options.sshRemote as NonNullable<PtyCreateOptions['sshRemote']>
+ const pinned: PtyCreateOptions = {
+ ...options,
+ sshRemote: {
+ ...remote,
+ conn: {
+ ...remote.conn,
+ identityAgentSock: await probeAgentSockToPin(remote.conn).catch(() => undefined)
+ }
+ }
+ }
+ const overrides = await this.projectSpawnOverrides(pinned)
+ const slot = await remotePtySpawnGate.acquire(remote.controlPath, { background: false })
+ let sessionId: string
+ try {
+ sessionId = this.spawnSession(pinned, null, sinks, undefined, overrides)
+ } catch (err) {
+ slot()
+ throw err
+ }
+ releaseSpawnSlotOnOutput(this.sessions.get(sessionId), slot)
+ return sessionId
+ }
+
/**
* 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 --git a/src/core/pty-relay-attach.test.ts b/src/core/pty-relay-attach.test.ts
new file mode 100644
index 000000000..70bdd4149
--- /dev/null
+++ b/src/core/pty-relay-attach.test.ts
@@ -0,0 +1,152 @@
+/**
+ * The phone's relay `pty.attach` must never spawn an SSH project's node LOCALLY.
+ *
+ * The bug: the relay host attached with `attachDetached(nodeId)` → `tmux new-session -A` on the
+ * LOCAL socket, for whatever id the phone named. A node of an SSH project, opened on the phone
+ * before the desktop mounted it, therefore became a local shell in this machine's `$HOME` wearing
+ * the remote node's id — work typed there ran on the wrong machine, its hooks reported nothing the
+ * node could use, and the desktop's later mount created a SECOND session of the same name on the
+ * host. And a local node the phone created first got only the base hook env (no agent id, no
+ * canvas-control grant, no account dir, no cwd), which tmux ignores on every later attach.
+ *
+ * These drive the real `PtyManager.prepareRelayAttach` with node-pty mocked, so a spawn is
+ * observable and nothing real is started.
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { existsSync } from 'fs'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform } from './platform-fake'
+import { DEFAULT_SETTINGS } from '../shared/types'
+import { sessionName } from './tmux-naming'
+import type { RelayNodeResolver } from './pty-manager'
+
+const spawned: Array<{ file: string; args: string[]; opts: { cwd?: string; env?: Record<string, string> } }> = []
+
+vi.mock('./session-host-backend', async () =>
+ (await import('./__fixtures__/no-session-host')).noSessionHost()
+)
+vi.mock('node-pty', () => ({
+ spawn: (file: string, args: string[], opts: { cwd?: string; env?: Record<string, string> }) => {
+ spawned.push({ file, args, opts })
+ return {
+ 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 HAS_SSH = ['/usr/bin/ssh', '/usr/local/bin/ssh', '/opt/homebrew/bin/ssh'].some((p) =>
+ existsSync(p)
+)
+const SERVER = { host: 'box.test', user: 'deploy' }
+const SSH_NODE = 'node-ssh-1'
+const LOCAL_NODE = 'node-local-1'
+const sinks = { onData: () => {}, onExit: () => {} }
+
+function resolver(opts: { master?: boolean; setupDone?: boolean } = {}): RelayNodeResolver {
+ return {
+ placements: (nodeId) =>
+ nodeId === SSH_NODE
+ ? [
+ {
+ projectId: 'p-ssh',
+ projectServer: SERVER,
+ node: { kind: 'terminal', cwd: '/srv/app', agentId: 'claude', ssh: SERVER, sshRemoteTmux: true }
+ }
+ ]
+ : nodeId === LOCAL_NODE
+ ? [{ projectId: 'p-local', node: { kind: 'terminal', cwd: '/var/tmp', agentId: 'claude' } }]
+ : [],
+ refFor: (scope) =>
+ opts.master && scope === 'p-ssh'
+ ? { conn: SERVER, controlPath: '/var/tmp/nt-test-cm-p1', setupDone: opts.setupDone ?? true }
+ : undefined,
+ projectIsRemote: (id) => id === 'p-ssh'
+ }
+}
+
+describe('relay attach routes by this machine’s records, never to a local shell for a remote node', () => {
+ beforeEach(() => {
+ spawned.length = 0
+ initPlatform(fakePlatform())
+ })
+ afterEach(() => {
+ resetPlatformForTests()
+ vi.restoreAllMocks()
+ })
+
+ async function manager(r?: RelayNodeResolver) {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager()
+ m.init(() => DEFAULT_SETTINGS)
+ if (r) m.setRelayNodeResolver(r)
+ return m
+ }
+
+ it('an SSH-project node with no live master is refused and NOTHING is spawned', async () => {
+ const m = await manager(resolver())
+ const prep = await m.prepareRelayAttach(SSH_NODE, { cols: 80, rows: 24 })
+ expect(prep.kind).toBe('refused')
+ if (prep.kind !== 'refused') return
+ expect(prep.reason).toBe('not-connected')
+ expect(prep.message).toContain('[email protected]')
+ expect(spawned).toHaveLength(0) // ← the whole point: no local `nt-<id>` wearing a remote id
+ })
+
+ it('a master still setting up only JOINS a listed session — it never creates one', async () => {
+ // The fake control path answers nothing, so the host's listing is `unknown`: not `present`.
+ const m = await manager(resolver({ master: true, setupDone: false }))
+ const prep = await m.prepareRelayAttach(SSH_NODE, { cols: 80, rows: 24 })
+ expect(prep).toMatchObject({ kind: 'refused', reason: 'still-connecting' })
+ expect(spawned).toHaveLength(0)
+ })
+
+ it.skipIf(!HAS_SSH)('with a live master the session runs over it on the HOST', async () => {
+ const m = await manager(resolver({ master: true }))
+ const prep = await m.prepareRelayAttach(SSH_NODE, { cols: 80, rows: 24 })
+ expect(prep.kind).toBe('ready')
+ if (prep.kind !== 'ready') return
+ expect(prep.remote).toBe(true)
+ await prep.attach(sinks)
+ expect(spawned).toHaveLength(1)
+ const { file, args } = spawned[0]
+ expect(file).toMatch(/ssh$/) // an ssh client, never the local tmux
+ const line = args.join(' ')
+ expect(line).toContain('/var/tmp/nt-test-cm-p1')
+ expect(line).toContain(sessionName(SSH_NODE))
+ expect(line).toContain('nodeterm-rmt') // the REMOTE socket
+ }, 20_000)
+
+ it('a local node is created with the env the desktop gives it, via the one env builder', async () => {
+ const { hookServer } = await import('./agents/hook-server')
+ const build = vi.spyOn(hookServer, 'buildPtyEnv')
+ const m = await manager(resolver())
+ const prep = await m.prepareRelayAttach(LOCAL_NODE, { cols: 80, rows: 24 })
+ expect(prep).toMatchObject({ kind: 'ready', remote: false })
+ if (prep.kind !== 'ready') return
+ await prep.attach(sinks)
+ expect(spawned).toHaveLength(1)
+ // The agent id reaches the SAME builder the desktop's create uses (agent id, canvas-control
+ // grant and permission wait all hang off it) — not a second relay-only env.
+ expect(build).toHaveBeenCalledWith(LOCAL_NODE, 'claude', expect.any(Number))
+ const { args, opts } = spawned[0]
+ // The node's cwd: on tmux as the new session's `-c`, on a plain shell as the pty's cwd.
+ expect(args.includes('/var/tmp') || opts.cwd === '/var/tmp').toBe(true)
+ })
+
+ it('with no resolver wired (Server Edition) the attach is the bare local one it always was', async () => {
+ const m = await manager()
+ const prep = await m.prepareRelayAttach(SSH_NODE, { cols: 80, rows: 24 })
+ expect(prep).toMatchObject({ kind: 'ready', remote: false })
+ })
+})
diff --git a/src/core/relay-attach-plan.test.ts b/src/core/relay-attach-plan.test.ts
new file mode 100644
index 000000000..c8caf9b9e
--- /dev/null
+++ b/src/core/relay-attach-plan.test.ts
@@ -0,0 +1,196 @@
+import { describe, it, expect } from 'vitest'
+import { planRelayAttach, type RelayNodePlacement, type RelayRemoteRef } from './relay-attach-plan'
+
+/**
+ * The routing matrix of a phone's relay `pty.attach` — where the session runs and with what — from
+ * this machine's records alone. The bug it pins: an SSH project's node, attached from the phone
+ * before the desktop mounted it, came up as a LOCAL `nt-<id>` (a shell in this machine's `$HOME`
+ * wearing a remote node's identity), and a local node got none of its agent/account/cwd env.
+ */
+
+const SERVER = { host: 'box.test', user: 'deploy' }
+const MASTER: RelayRemoteRef = {
+ conn: SERVER,
+ controlPath: '/tmp/cm-p1',
+ hookEndpointPath: '/home/deploy/.nodeterm/hook-endpoint-p1.env',
+ tmuxConfPath: '/home/deploy/.nodeterm/tmux.conf',
+ remoteHome: '/home/deploy',
+ setupDone: true
+}
+
+const sshNode = (over: Partial<RelayNodePlacement['node']> = {}): RelayNodePlacement => ({
+ projectId: 'p-ssh',
+ projectServer: SERVER,
+ node: {
+ kind: 'terminal',
+ cwd: '/srv/app',
+ agentId: 'claude',
+ accountId: 'acct-1',
+ ssh: SERVER,
+ sshRemoteTmux: true,
+ ...over
+ }
+})
+const localNode = (over: Partial<RelayNodePlacement['node']> = {}): RelayNodePlacement => ({
+ projectId: 'p-local',
+ node: { kind: 'terminal', cwd: '/home/me/app', agentId: 'codex', agentModel: 'gpt-x', ...over }
+})
+
+const base = { refFor: () => undefined, sshAvailable: true }
+
+describe('planRelayAttach', () => {
+ it('an SSH-project node with no live master is REFUSED, never spawned locally', () => {
+ const plan = planRelayAttach({ ...base, placements: [sshNode()] })
+ expect(plan.kind).toBe('refuse')
+ if (plan.kind !== 'refuse') return
+ expect(plan.reason).toBe('not-connected')
+ expect(plan.message).toContain('[email protected]')
+ expect(plan.message).toContain('Nothing was started here')
+ })
+
+ it('…and with no ssh executable it is refused for that reason', () => {
+ const plan = planRelayAttach({
+ ...base,
+ sshAvailable: false,
+ refFor: () => MASTER,
+ placements: [sshNode()]
+ })
+ expect(plan).toMatchObject({ kind: 'refuse', reason: 'no-ssh' })
+ })
+
+ it('with a master it runs over that master, requireRemote, with the node’s own profile', () => {
+ const plan = planRelayAttach({
+ ...base,
+ refFor: (scope) => (scope === 'p-ssh' ? MASTER : undefined),
+ placements: [sshNode()]
+ })
+ expect(plan.kind).toBe('remote')
+ if (plan.kind !== 'remote') return
+ expect(plan.options).toMatchObject({
+ cwd: '/srv/app',
+ agentId: 'claude',
+ accountId: 'acct-1',
+ ownerProjectId: 'p-ssh',
+ requireRemote: true,
+ sshRemote: {
+ controlPath: '/tmp/cm-p1',
+ conn: SERVER,
+ remoteCwd: '/srv/app',
+ hookEndpointPath: MASTER.hookEndpointPath,
+ tmuxConfPath: MASTER.tmuxConfPath,
+ remoteHome: '/home/deploy'
+ }
+ })
+ expect(plan.setupDone).toBe(true)
+ })
+
+ it('a node in an SSH project with no flags is still remote (routing it local is the bug)', () => {
+ const plan = planRelayAttach({
+ ...base,
+ placements: [{ projectId: 'p-ssh', projectServer: SERVER, node: { kind: 'terminal' } }]
+ })
+ expect(plan).toMatchObject({ kind: 'refuse', reason: 'not-connected' })
+ })
+
+ it('a host attachment in a LOCAL project runs over the attachment scope, not the project', () => {
+ const other = { host: 'other.test', user: 'ops' }
+ const scopes: string[] = []
+ planRelayAttach({
+ ...base,
+ refFor: (scope) => {
+ scopes.push(scope)
+ return undefined
+ },
+ placements: [
+ { projectId: 'p-local', node: { kind: 'terminal', ssh: other, sshRemoteTmux: true } }
+ ]
+ })
+ expect(scopes).toHaveLength(1)
+ expect(scopes[0]).not.toBe('p-local')
+ })
+
+ it('a live remote handle held by this process wins over the index', () => {
+ const live: RelayRemoteRef = { conn: SERVER, controlPath: '/tmp/cm-live' }
+ const plan = planRelayAttach({ ...base, liveRemote: live, placements: [sshNode()] })
+ expect(plan.kind === 'remote' && plan.options.sshRemote?.controlPath).toBe('/tmp/cm-live')
+ })
+
+ it('a local node gets the profile the desktop would give it (agent, model, cwd, owner)', () => {
+ const plan = planRelayAttach({ ...base, placements: [localNode()] })
+ expect(plan).toEqual({
+ kind: 'local',
+ projectId: 'p-local',
+ options: {
+ cwd: '/home/me/app',
+ agentId: 'codex',
+ agentModel: 'gpt-x',
+ ownerProjectId: 'p-local'
+ }
+ })
+ })
+
+ it('a plain ssh terminal node runs `ssh` locally, as the renderer does', () => {
+ const plan = planRelayAttach({
+ ...base,
+ placements: [{ projectId: 'p-local', node: { kind: 'terminal', ssh: SERVER } }]
+ })
+ expect(plan.kind).toBe('local')
+ if (plan.kind !== 'local') return
+ expect(plan.options.shell).toBe('ssh')
+ expect(plan.options.shellArgs?.join(' ')).toContain('box.test')
+ })
+
+ it('an unknown node keeps the bare local attach (a phone-started local session)', () => {
+ expect(planRelayAttach({ ...base, placements: [] })).toEqual({ kind: 'local', options: {} })
+ })
+
+ it('an unknown node the phone says belongs to an SSH project is refused, not guessed', () => {
+ const plan = planRelayAttach({
+ ...base,
+ placements: [],
+ projectHint: 'p-ssh',
+ hintIsRemoteProject: true
+ })
+ expect(plan).toMatchObject({ kind: 'refuse', reason: 'unregistered-remote' })
+ })
+
+ it('a hint naming a project that does not hold the node cannot route it anywhere', () => {
+ const plan = planRelayAttach({
+ ...base,
+ placements: [sshNode()],
+ projectHint: 'p-local-elsewhere'
+ })
+ expect(plan).toMatchObject({ kind: 'refuse', reason: 'not-connected' })
+ })
+
+ describe('one id in a local AND an SSH project (the same canvas in two folders)', () => {
+ const both = [sshNode(), localNode()]
+ it('a hint picks among the real placements', () => {
+ expect(planRelayAttach({ ...base, placements: both, projectHint: 'p-local' }).kind).toBe(
+ 'local'
+ )
+ expect(
+ planRelayAttach({ ...base, placements: both, projectHint: 'p-ssh', refFor: () => MASTER })
+ .kind
+ ).toBe('remote')
+ })
+ it('without one, a live LOCAL session wins; otherwise the remote one', () => {
+ expect(
+ planRelayAttach({ ...base, placements: both, localSessionExists: true }).kind
+ ).toBe('local')
+ expect(
+ planRelayAttach({ ...base, placements: both, localSessionExists: false, refFor: () => MASTER })
+ .kind
+ ).toBe('remote')
+ })
+ })
+
+ it('a master whose setup is unfinished is reported as such (the caller only joins then)', () => {
+ const plan = planRelayAttach({
+ ...base,
+ refFor: () => ({ ...MASTER, setupDone: false }),
+ placements: [sshNode()]
+ })
+ expect(plan.kind === 'remote' && plan.setupDone).toBe(false)
+ })
+})
diff --git a/src/core/relay-attach-plan.ts b/src/core/relay-attach-plan.ts
new file mode 100644
index 000000000..f6aa92c70
--- /dev/null
+++ b/src/core/relay-attach-plan.ts
@@ -0,0 +1,209 @@
+import type { AgentId } from '../shared/agents/config'
+import { buildSshArgs, sshConnectionIdForProject, sshHostKey, type SshConnection } from '../shared/ssh'
+import type { PtyCreateOptions } from '../shared/types'
+
+/**
+ * WHERE a phone's relay `pty.attach` runs, and WITH WHAT, decided from this machine's own records.
+ *
+ * The phone sends a node id and nothing else we may trust. The relay host used to hand that id
+ * straight to `attachDetached` → `tmux new-session -A` on the LOCAL socket, so a phone tapping a
+ * node of an SSH project, before the desktop had mounted it, created a local `nt-<id>`: a shell in
+ * this machine's `$HOME` wearing a remote node's identity. Work typed there ran on the wrong
+ * machine; its hooks reported nothing the node could use (no context meter, ⌘M fell back to
+ * Markdown); and the desktop's later mount ran `new-session -A` on the HOST, so one node id ended
+ * up naming two different sessions on two machines. The invariant this restores is the one
+ * `PtyCreateOptions.requireRemote` states for the desktop: a remote node is never spawned locally.
+ *
+ * Even for a LOCAL node the relay spawn was bare — no agent id, no canvas-control grant, no
+ * permission wait, no account dir, no cwd — and tmux ignores the desktop's `-e` env on any later
+ * attach, so a session the phone happened to create first stayed hookless for life. The profile
+ * below is the one the desktop's own create passes (`TerminalNode.tsx`'s `transport.create`), read
+ * off the PERSISTED node; the env itself is still built by the one builder (`spawnSession` →
+ * `buildPtyEnv` / `remoteHookEnvArgs`), never a second copy here.
+ *
+ * Pure, so the routing matrix is provable without tmux, ssh or a workspace.
+ */
+
+/** One project that holds the node id, with the node as that project recorded it. */
+export interface RelayNodePlacement {
+ /** The machine-local project id (index entry id). */
+ projectId: string
+ /** The project's SSH server when the PROJECT is an SSH project; absent for local/inline. */
+ projectServer?: SshConnection
+ /** The persisted node. Local-ref cwds already resolved against the project root. */
+ node: {
+ kind?: string
+ cwd?: string
+ shell?: string
+ agentId?: AgentId
+ agentModel?: string
+ accountId?: string
+ ssh?: SshConnection
+ sshRemoteTmux?: boolean
+ }
+}
+
+/** A live ControlMaster plus the setup facts its connect produced (all read at CREATION only). */
+export interface RelayRemoteRef {
+ conn: SshConnection
+ controlPath: string
+ hookEndpointPath?: string
+ tmuxConfPath?: string
+ remoteHome?: string
+ /** The connect's setup chain has finished (hook endpoint, tmux.conf, home are final). A session
+ * CREATED before that would carry none of them for life, so `prepareRelayAttach` only joins an
+ * existing session over a master that is not set up yet. Absent = set up (a live session's own
+ * handle). */
+ setupDone?: boolean
+}
+
+/** Why a relay attach was refused. Never a local fallback — see the module comment. */
+export type RelayAttachRefusal = 'not-connected' | 'no-ssh' | 'unregistered-remote' | 'still-connecting'
+
+/** The create options a relay attach spawns with (size + persistKey are the caller's). */
+export type RelayAttachOptions = Omit<PtyCreateOptions, 'persistKey' | 'cols' | 'rows'>
+
+export type RelayAttachPlan =
+ | { kind: 'local'; options: RelayAttachOptions; projectId?: string }
+ | {
+ kind: 'remote'
+ options: RelayAttachOptions
+ projectId: string
+ hostKey: string
+ /** The master's setup chain has finished — see `RelayRemoteRef.setupDone`. */
+ setupDone: boolean
+ }
+ | { kind: 'refuse'; reason: RelayAttachRefusal; message: string; hostKey?: string }
+
+/** Does this placement put the node's session on a REMOTE host? */
+export function placementIsRemote(p: RelayNodePlacement): boolean {
+ // A plain `ssh` terminal (createSshTerminalNode) runs `ssh` as a LOCAL pty program — exactly the
+ // renderer's `localSsh` rule — wherever it sits.
+ if (p.node.ssh && p.node.sshRemoteTmux !== true) return false
+ if (p.node.sshRemoteTmux === true && p.node.ssh?.host) return true
+ // A node of an SSH project with no flags (hand-edited, or older than the flag) still belongs to
+ // that host. Routing it remote can only refuse; routing it local is the bug.
+ return !!p.projectServer
+}
+
+/** The connection scope (ControlMaster key) a remote placement runs over — the same choice the
+ * renderer's `sshConnectionScope` makes: the project's own master for its own host, the
+ * project×host attachment for a node bound to another endpoint. */
+export function placementScope(p: RelayNodePlacement): string {
+ return p.node.ssh ? sshConnectionIdForProject(p.projectId, p.node.ssh, p.projectServer) : p.projectId
+}
+
+function placementHostKey(p: RelayNodePlacement): string {
+ const conn = p.node.ssh ?? p.projectServer
+ return conn ? sshHostKey(conn) : ''
+}
+
+/** Only terminal nodes carry a spawn profile; anything else is treated as not recorded here. */
+function isTerminal(p: RelayNodePlacement): boolean {
+ return p.node.kind === undefined || p.node.kind === 'terminal'
+}
+
+/** Optional fields are only set when present, so a bare node yields the bare (pre-fix) options. */
+function profile(p: RelayNodePlacement): RelayAttachOptions {
+ const n = p.node
+ const out: RelayAttachOptions = {}
+ if (n.cwd) out.cwd = n.cwd
+ if (n.shell) out.shell = n.shell
+ if (n.agentId) out.agentId = n.agentId
+ if (n.agentModel) out.agentModel = n.agentModel
+ if (n.accountId) out.accountId = n.accountId
+ return out
+}
+
+export function planRelayAttach(args: {
+ /** Every project holding this node id, in index order. Empty = this machine has no record. */
+ placements: readonly RelayNodePlacement[]
+ /** The project the phone says it is looking at. Used ONLY to choose among `placements` — it can
+ * never add a placement, so it cannot route a node anywhere this machine would not. */
+ projectHint?: string
+ /** The live master (+ setup facts) for a connection scope, or undefined when not connected. */
+ refFor: (scopeId: string) => RelayRemoteRef | undefined
+ /** This process already holds the node's session over a master: the exact handle it runs on. */
+ liveRemote?: RelayRemoteRef
+ /** Is there an `ssh` executable? Without it the remote branch cannot run, and the spawn would
+ * fall through to the local one. */
+ sshAvailable: boolean
+ /** Is the hinted project an SSH project (per this machine's index)? Only consulted when this
+ * machine has no record of the node, and only ever to REFUSE. */
+ hintIsRemoteProject?: boolean
+ /** Only consulted when the placements disagree (one id in a local AND an SSH project — the same
+ * committed canvas opened in two folders): does a LOCAL session for the id exist right now? */
+ localSessionExists?: boolean
+}): RelayAttachPlan {
+ const terminals = args.placements.filter(isTerminal)
+ // The hint picks among real placements; one it does not name is ignored, not trusted.
+ const hinted = args.projectHint ? terminals.filter((p) => p.projectId === args.projectHint) : []
+ const pool = hinted.length > 0 ? hinted : terminals
+ // An SSH project the phone names, holding no record of this id (a session the phone is starting
+ // there before registering it): we cannot know its profile, and a local spawn is the one wrong
+ // answer. Refused rather than guessed.
+ if (pool.length === 0) {
+ // A node this machine records only as something other than a terminal still says where it
+ // lives: a remote record refuses exactly like a hinted SSH project.
+ if (args.hintIsRemoteProject || args.placements.some(placementIsRemote)) {
+ return {
+ kind: 'refuse',
+ reason: 'unregistered-remote',
+ message:
+ 'This session belongs to an SSH project, and this computer has no record of it yet, so it cannot be started from here. Nothing was started here.'
+ }
+ }
+ // No record at all (a session the phone is starting in a local project before registering
+ // it): the bare local spawn this path always made.
+ return { kind: 'local', options: {} }
+ }
+ const remote = pool.filter(placementIsRemote)
+ const local = pool.filter((p) => !placementIsRemote(p))
+ // Disagreeing records: whichever session already exists. A live local session is a real local
+ // node's (the same canvas checked out on this machine); otherwise the remote one.
+ const chooseLocal = remote.length === 0 || (local.length > 0 && args.localSessionExists === true)
+ if (chooseLocal) {
+ const p = local[0]
+ const options = profile(p)
+ if (p.node.ssh && p.node.sshRemoteTmux !== true) {
+ options.shell = 'ssh'
+ options.shellArgs = buildSshArgs(p.node.ssh)
+ }
+ options.ownerProjectId = p.projectId
+ return { kind: 'local', options, projectId: p.projectId }
+ }
+ const p = remote[0]
+ const hostKey = placementHostKey(p)
+ const scope = placementScope(p)
+ const where = hostKey || 'its remote host'
+ if (!args.sshAvailable) {
+ return {
+ kind: 'refuse',
+ reason: 'no-ssh',
+ hostKey,
+ message: `This session lives on ${where}, and this computer has no ssh to reach it. Nothing was started here.`
+ }
+ }
+ const ref = args.liveRemote ?? args.refFor(scope)
+ if (!ref) {
+ return {
+ kind: 'refuse',
+ reason: 'not-connected',
+ hostKey,
+ message: `This session lives on ${where}, which this computer is not connected to right now. Open the project on the desktop to reconnect. Nothing was started here.`
+ }
+ }
+ const options = profile(p)
+ options.ownerProjectId = scope
+ options.sshRemote = {
+ controlPath: ref.controlPath,
+ conn: ref.conn,
+ // The renderer's rule (`resolveSshRemote`): the node's own cwd, else the remote home.
+ remoteCwd: p.node.cwd || '~',
+ ...(ref.hookEndpointPath ? { hookEndpointPath: ref.hookEndpointPath } : {}),
+ ...(ref.tmuxConfPath ? { tmuxConfPath: ref.tmuxConfPath } : {}),
+ ...(ref.remoteHome ? { remoteHome: ref.remoteHome } : {})
+ }
+ options.requireRemote = true
+ return { kind: 'remote', options, projectId: p.projectId, hostKey, setupDone: ref.setupDone !== false }
+}
diff --git a/src/core/relay/scoped-guest-policy.test.ts b/src/core/relay/scoped-guest-policy.test.ts
index 85fdbf5ae..fecc005e0 100644
--- a/src/core/relay/scoped-guest-policy.test.ts
+++ b/src/core/relay/scoped-guest-policy.test.ts
@@ -95,6 +95,16 @@ describe('scoped guest — terminals', () => {
})
expect(d.allow && (d.args?.[0] as Record<string, unknown>).sshRemote).toBeUndefined()
})
+ it('forces requireRemote for an SSH project, whatever the guest sent (never a local shell)', () => {
+ const remote = { ...deps(), projectIsRemote: (p: string) => p === 'alpha' }
+ const d = decideScopedAccess('alpha', remote, IPC.ptyCreate, [
+ { persistKey: 'a1', cols: 1, rows: 1, requireRemote: false }
+ ])
+ expect(d.allow && (d.args?.[0] as Record<string, unknown>).requireRemote).toBe(true)
+ // A local shared project is left exactly as the guest asked.
+ const local = decide(IPC.ptyCreate, { persistKey: 'a1', cols: 1, rows: 1 })
+ expect(local.allow && (local.args?.[0] as Record<string, unknown>).requireRemote).toBeUndefined()
+ })
it('judges session-id and persistKey verbs by the node', () => {
expect(allowed(IPC.ptyWrite, 'sA', 'ls\r')).toBe(true)
expect(allowed(IPC.ptyWrite, 'sB', 'ls\r')).toBe(false)
diff --git a/src/core/relay/scoped-guest-policy.ts b/src/core/relay/scoped-guest-policy.ts
index 43f991d18..e58b620c3 100644
--- a/src/core/relay/scoped-guest-policy.ts
+++ b/src/core/relay/scoped-guest-policy.ts
@@ -48,6 +48,11 @@ export interface ScopedGuestDeps {
nodeOfSession(sessionId: string): string | undefined
/** The shared project's LOCAL folder, or undefined (a cwd-less or SSH project). */
projectCwd(projectId: string): string | undefined
+ /** Is the shared project an SSH project (per the index — identity, not liveness)? Its terminals
+ * run on the remote host, so a guest's create is forced `requireRemote`: joins a live session
+ * this process holds, never spawns a LOCAL `nt-<id>` wearing a remote node's id. Optional:
+ * absent = not an SSH project (the Server Edition has none). */
+ projectIsRemote?(projectId: string): boolean
/** This app's own data directory (keys, license, every project's scrollback): never reachable
* through a scoped guest's fs/git calls, even when the shared root contains it. */
hostDataDir: string
@@ -238,7 +243,9 @@ const worktreeAddOrRemove: Check = (a, s) => {
* of the shared project, in a working directory inside the project root. Rewritten, not just judged:
* - `sshRemote` is dropped. Its `conn.extraArgs` reach `ssh` on the host during the existence probe,
* and a guest never names an ssh route; a node that requires one (`requireRemote`) is then
- * refused by the core instead of spawning locally.
+ * refused by the core instead of spawning locally. For an SSH project `requireRemote` is SET here
+ * rather than trusted from the guest, so a guest that omits it still cannot start a local shell
+ * under a remote node's id (it can still join a live session this process holds).
* - a missing `cwd` becomes the project root (the core's default would be the host user's `$HOME`).
* - `ownerProjectId` may only name the shared project (it is recorded as the pane's owner, which
* agent messaging trusts).
@@ -250,6 +257,7 @@ const ptyCreate: Check = (a, s) => {
if (!nodeInScope(opts.persistKey, s)) return no(NODE_OUTSIDE)
if (opts.ownerProjectId !== undefined && opts.ownerProjectId !== s.projectId) return no(OUTSIDE)
delete opts.sshRemote
+ if (s.deps.projectIsRemote?.(s.projectId)) opts.requireRemote = true
const root = rootOf(s)
if (opts.cwd === undefined || opts.cwd === null || opts.cwd === '') {
if (root) opts.cwd = root
diff --git a/src/core/workspace-store.relay-placements.test.ts b/src/core/workspace-store.relay-placements.test.ts
new file mode 100644
index 000000000..936b990f3
--- /dev/null
+++ b/src/core/workspace-store.relay-placements.test.ts
@@ -0,0 +1,51 @@
+// `relayNodePlacements` is what the relay host's attach decides WHERE a phone-opened session runs
+// from (core/relay-attach-plan.ts). It must answer EVERY project holding the id — the same committed
+// canvas opened in two folders shares node ids — with the node as THAT project recorded it and a
+// local ref's portable cwd resolved, because the attach spawns in that cwd.
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import path from 'path'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform } from './platform-fake'
+import { testTmpDir } from './test-tmp'
+import { WorkspaceStore } from './workspace-store'
+import type { CanvasNodeState, Project, Workspace } from '../shared/types'
+
+const node = (id: string, extra: Partial<CanvasNodeState> = {}): CanvasNodeState =>
+ ({ id, kind: 'terminal', position: { x: 0, y: 0 }, size: { width: 1, height: 1 }, title: id, color: '#fff', group: null, ...extra }) as CanvasNodeState
+const project = (id: string, cwd: string | undefined, nodes: CanvasNodeState[]): Project => ({
+ id,
+ name: id,
+ color: '#7aa2f7',
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes,
+ ...(cwd ? { cwd } : {})
+})
+const ws = (projects: Project[]): Workspace => ({ version: 2, activeProjectId: projects[0]?.id ?? '', projects })
+
+beforeEach(() => {
+ initPlatform(fakePlatform({ userDataDir: testTmpDir('nt-rp-ws-') }))
+})
+afterEach(() => resetPlatformForTests())
+
+describe('WorkspaceStore.relayNodePlacements', () => {
+ it('answers every project holding the id, with that project’s record and a resolved cwd', async () => {
+ const [a, b] = [testTmpDir('nt-rp-a-'), testTmpDir('nt-rp-b-')]
+ const store = new WorkspaceStore()
+ await store.save(
+ ws([
+ project('pa', a, [node('shared', { cwd: path.join(a, 'sub'), agentId: 'claude' })]),
+ project('pb', b, [node('shared', { agentId: 'codex' }), node('only-b')]),
+ project('inline', undefined, [node('only-inline')])
+ ])
+ )
+ const shared = store.relayNodePlacements('shared')
+ expect(shared.map((p) => p.projectId)).toEqual(['pa', 'pb'])
+ // The shared file stores `./sub`; the attach must spawn in the absolute folder.
+ expect(shared[0].node.cwd).toBe(path.join(a, 'sub'))
+ expect(shared[0].node.agentId).toBe('claude')
+ expect(shared[1].node.agentId).toBe('codex')
+ expect(shared.every((p) => p.projectServer === undefined)).toBe(true)
+ expect(store.relayNodePlacements('only-inline').map((p) => p.projectId)).toEqual(['inline'])
+ expect(store.relayNodePlacements('nope')).toEqual([])
+ })
+})
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index dc6ed6998..9c8f2080f 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -1,3 +1,4 @@
+import type { SshConnection } from '../shared/ssh'
import { promises as fs } from 'fs'
import { createHash, randomUUID } from 'node:crypto'
import path from 'path'
@@ -2072,6 +2073,26 @@ export class WorkspaceStore {
return undefined
}
+ /**
+ * Every project that holds this node id, with the node as THAT project recorded it and the
+ * project's SSH server when it is an SSH project — the relay host's attach decides where a
+ * phone-opened session runs from this (core `relay-attach-plan.ts`), never from the phone's words.
+ * All of them, never the first: node ids travel in git-shared project files, so the same canvas
+ * opened in a local folder and over SSH holds the same ids. Local-ref cwds come back resolved.
+ */
+ relayNodePlacements(
+ nodeId: string
+ ): Array<{ projectId: string; projectServer?: SshConnection; node: CanvasNodeState }> {
+ const out: Array<{ projectId: string; projectServer?: SshConnection; node: CanvasNodeState }> = []
+ for (const c of this.persistedCanvases()) {
+ const node = c.nodes.find((n) => n.id === nodeId)
+ if (!node) continue
+ const server = this.index?.entries.find((e) => e.id === c.id)?.ssh?.server
+ out.push({ projectId: c.id, ...(server ? { projectServer: server } : {}), node })
+ }
+ return out
+ }
+
/**
* EVERY project that holds this node id, in index order ([] = none) — exactly what a
* `persistedCanvases` scan answers. All of them, never the first: node ids travel in git-shared
diff --git a/src/main/index.ts b/src/main/index.ts
index 80a9a477f..e121b3da2 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -634,6 +634,18 @@ ptyManager.setRemoteNodeOwner((nodeId) => {
remote: ref ? { conn: ref.conn, controlPath: ref.controlPath } : undefined
}
})
+// WHERE a phone's relay `pty.attach` runs, and with what env — decided in core
+// (`PtyManager.prepareRelayAttach` / `core/relay-attach-plan.ts`) from THIS machine's records, never
+// from the phone's words. Before this the relay attach ran `tmux new-session -A` on the LOCAL socket
+// for any node id, so an SSH project's node opened on the phone first came up as a local shell in
+// this machine's `$HOME`, and a local node created by the phone got no agent/account/cwd env.
+// Same late-binding reason as above for `sshProjectManager`: an attach before the manager exists
+// sees no master and is refused, never spawned locally.
+ptyManager.setRelayNodeResolver({
+ placements: (nodeId) => workspaceStore.relayNodePlacements(nodeId),
+ refFor: (scopeId) => sshProjectManager?.spawnRefFor(scopeId),
+ projectIsRemote: (projectId) => !!workspaceStore.projectTargetInfo(projectId)?.ssh
+})
const gitService = new GitService()
// Project setup/archive runner (SDD: 2026-08-19-project-settings-trust). The trust store is keyed
@@ -4641,6 +4653,7 @@ app.whenReady().then(async () => {
projectsOfNode: (nodeId) => workspaceStore.projectIdsForNode(nodeId),
nodeOfSession: (sessionId) => ptyManager.nodeOfSession(sessionId),
projectCwd: (projectId) => workspaceStore.localCwdForProject(projectId),
+ projectIsRemote: (projectId) => !!workspaceStore.projectTargetInfo(projectId)?.ssh,
hostDataDir: app.getPath('userData')
}
})
diff --git a/src/main/relay-attach-wiring.test.ts b/src/main/relay-attach-wiring.test.ts
new file mode 100644
index 000000000..883c52024
--- /dev/null
+++ b/src/main/relay-attach-wiring.test.ts
@@ -0,0 +1,31 @@
+// The relay host's attach decides where a phone-opened session runs from a resolver the desktop
+// shell wires (`ptyManager.setRelayNodeResolver`). It is optional in core — the Server Edition has
+// no relay host and wires none — so dropping the desktop's wire compiles, passes every unit test,
+// and silently restores the bare LOCAL attach that made an SSH project's node a local shell. Pinned
+// at source level, the remedy this repo uses for that class of hole (codex-chat-wiring.test.ts).
+import { describe, expect, it } from 'vitest'
+import fs from 'node:fs'
+import path from 'node:path'
+
+const read = (rel: string): string => fs.readFileSync(path.join(__dirname, '..', rel), 'utf8').replace(/\r\n/g, '\n')
+
+describe('relay attach routing is wired in the desktop shell', () => {
+ it('feeds core this machine’s placements, live masters and SSH-project identity', () => {
+ const src = read('main/index.ts')
+ expect(src).toMatch(/ptyManager\.setRelayNodeResolver\(\{\n\s*placements: \(nodeId\) => workspaceStore\.relayNodePlacements\(nodeId\),\n\s*refFor: \(scopeId\) => sshProjectManager\?\.spawnRefFor\(scopeId\),\n\s*projectIsRemote: \(projectId\) => !!workspaceStore\.projectTargetInfo\(projectId\)\?\.ssh\n\s*\}\)/)
+ })
+ 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 \}\)/)
+ expect(src).not.toMatch(/pty\.attachDetached\(/)
+ })
+ it('a Team Access guest’s create in an SSH project is forced requireRemote', () => {
+ expect(read('main/index.ts')).toMatch(
+ /projectCwd: \(projectId\) => workspaceStore\.localCwdForProject\(projectId\),\n\s*projectIsRemote: \(projectId\) => !!workspaceStore\.projectTargetInfo\(projectId\)\?\.ssh,/
+ )
+ })
+ it('a connection reports setup-done exactly where it reports connected', () => {
+ const src = read('main/remote-ssh/ssh-project.ts')
+ expect(src).toMatch(/entry\.setupDone = true\n\s*this\.emitStatus\(\{ projectId, status: 'connected' \}\)/)
+ })
+})
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 028cdbbea..942d144a5 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -386,6 +386,10 @@ interface Conn {
controlPath: string
master: ReturnType<Runners['spawnMaster']>
hookEndpointPath?: string
+ /** The connect's setup chain has finished on this master (the moment `connected` is emitted):
+ * the facts below are as final as they will get. A spawn that CREATES a session before this
+ * would create it without the hook/account env and tmux.conf, for life. */
+ setupDone?: boolean
/** The remote path of nodeterm's tmux.conf (`<remoteHome>/.nodeterm/tmux.conf`), written +
* source-filed at connect. Threaded to `remoteTmuxCommand`'s `-f` so cold-start remote sessions
* get mouse/clipboard/scrollback. Undefined if the write/source failed (fail-open). */
@@ -1069,6 +1073,7 @@ export class SshProjectManager {
entry.codexRelayScriptPath = codexRuntime?.relay
entry.codexRelayRuntimePath = codexRuntime?.runtime
entry.codexCliPath = codexRuntime?.codex
+ entry.setupDone = true
this.emitStatus({ projectId, status: 'connected' })
if (hookEndpointPath) this.hookTunnelHealth(projectId, true)
// The tunnel is live again on a master we just established (the reuse branch returned long
@@ -1562,6 +1567,34 @@ export class SshProjectManager {
return c ? { conn: c.conn, controlPath: c.controlPath, remoteCwd: c.remoteCwd } : undefined
}
+ /**
+ * Everything a remote SPAWN needs from this connection, for spawns the renderer did not build —
+ * today the relay host's `pty.attach` (core `prepareRelayAttach`). The same facts the renderer
+ * reads off the `connected` event (`resolveSshRemote`), read here from the entry itself.
+ * `undefined` = no master for this scope.
+ */
+ spawnRefFor(scopeId: string):
+ | {
+ conn: SshConnection
+ controlPath: string
+ hookEndpointPath?: string
+ tmuxConfPath?: string
+ remoteHome?: string
+ setupDone: boolean
+ }
+ | undefined {
+ const c = this.conns.get(scopeId)
+ if (!c) return undefined
+ return {
+ conn: c.conn,
+ controlPath: c.controlPath,
+ hookEndpointPath: c.hookEndpointPath,
+ tmuxConfPath: c.tmuxConfPath,
+ remoteHome: c.remoteHome,
+ setupDone: c.setupDone === true
+ }
+ }
+
/** Does this project already have a master, or an attempt in flight? The pre-warm's gate — it
* must never start a second attempt beside the user's own connect (see `prewarm`). */
isBusy(projectId: string): boolean {
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index 704b2a844..02c27b7b3 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -30,7 +30,7 @@ import { IPC } from '../../shared/ipc'
import { REF_MAX_LEN } from '../../shared/presence'
import type { CanvasMutation, CanvasState, DirEntry, KanbanColumn, KanbanLabel, PtyCreateOptions } from '../../shared/types'
import type { AgentId } from '../../shared/agents/config'
-import { PtyManager, type DetachedSinks } from '../../core/pty-manager'
+import { PtyManager, type DetachedSinks, type RelayAttachPrep } from '../../core/pty-manager'
import * as fsOps from '../../core/fs-ops'
import { TITLE_MAX, type RemoteNodeInput } from '../../core/project-node-append'
import { parseCardLabelEdit, type CardLabelEdit } from '../../core/project-kanban-write'
@@ -73,16 +73,15 @@ const FRESH_PROBE_BUDGET_MS = 750
// The slice of pty-manager the host needs. PtyManager satisfies this; tests pass a fake.
export interface HostPtyManager {
createDetached(options: PtyCreateOptions, sinks: DetachedSinks): string
- /** Attach a relay-served PTY to the EXISTING tmux session for a node id (create if absent). */
- attachDetached(
- persistKey: string,
- sinks: DetachedSinks,
- options?: Omit<PtyCreateOptions, 'persistKey'>
- ): string
- /** Current visible screen of a node's tmux session, for the attach snapshot. */
- captureSnapshot(persistKey: string): Promise<string>
- /** Does a tmux session for this node id exist RIGHT NOW? Asked before `attachDetached`, which
- * CREATES one when it doesn't — so the client can tell a warm join from a cold start. */
+ /** Decide where (and with what env) a relay attach for a node id runs, from this machine's own
+ * records — see `PtyManager.prepareRelayAttach`. Replaces the bare local `attachDetached`, which
+ * created a LOCAL session for a remote node. */
+ prepareRelayAttach(
+ nodeId: string,
+ size: { cols: number; rows: number },
+ hint?: { projectId?: string }
+ ): Promise<RelayAttachPrep>
+ /** 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
* attributed to it — null when this session has no peer, which just means it is not badged. */
@@ -388,10 +387,12 @@ export function createHostHandlers(
/**
* Attach a mirrored terminal to the host's tmux session for `nodeId`: respond with the streamId
* (and whether the session had to be CREATED — `fresh`), send a SNAPSHOT of the current screen
- * (so the client paints it before any live output), then start streaming live output via
- * `attachDetached`. Falls back to plain create semantics when no session exists yet
- * (attachDetached creates one; the snapshot is empty) — which is exactly what `fresh` reports,
- * so the client can run its cold restore instead of sitting in a bare login shell.
+ * (so the client paints it before any live output), then start streaming live output. Falls
+ * back to create semantics when no session exists yet (the attach creates one, with the env the
+ * desktop would give that node; the snapshot is empty) — which is exactly what `fresh` reports,
+ * so the client can run its cold restore instead of sitting in a bare login shell. A node whose
+ * session lives on a remote host with no live master is REFUSED (`{message, reason}`), never
+ * started locally.
*/
function handleAttach(req: RpcRequest): void {
const p = asRecord(req.params)
@@ -418,43 +419,67 @@ export function createHostHandlers(
/* viewer bookkeeping must never break the attach */
}
- // `fresh` — did this attach CREATE the session, or join a live one? It has to be asked BEFORE
- // `attachDetached`, whose `tmux new-session -A` creates when the session is gone; afterwards
- // it always exists and the answer is meaningless. Without it a mirrored client could not tell
- // "I joined your running agent" from "I just made you an empty login shell in $HOME", which is
- // what put a bare `~ %` prompt under a Claude node's title on the phone once the host's tmux
- // server had died. The agent transport has reported this all along; the relay did not.
- //
- // Bounded, and fail-safe toward "warm": a probe that is slow or unprobeable answers `false`,
- // so a client that cold-restores on `fresh` types nothing into a session that may be live.
- // The bound matters because this now precedes the RPC response and `has-session` can sit on
- // the 6 s probe timeout when tmux itself is wedged.
+ // WHERE this attach runs, and with what env, is decided by core from this machine's own
+ // records (`PtyManager.prepareRelayAttach`): a node of an SSH project runs over that project's
+ // ControlMaster or is REFUSED — never a local `nt-<id>` wearing a remote node's identity — and a
+ // 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)
void (async () => {
+ let prep: RelayAttachPrep
+ try {
+ prep = await pty.prepareRelayAttach(nodeId, { cols, rows }, { projectId: projectHint })
+ } catch {
+ prep = { kind: 'refused', reason: 'not-connected', message: 'Could not prepare this session.' }
+ }
+ if (prep.kind === 'refused') {
+ // Nothing was spawned and no streamId was ever handed out: release the reservation and
+ // answer with the reason, so the phone shows a sentence instead of a bare shell.
+ dropStream(streamId)
+ socket.respond(req.id, false, { message: prep.message, reason: prep.reason })
+ return
+ }
+ // `fresh` — did this attach CREATE the session, or join a live one? It has to be asked BEFORE
+ // `attach`, whose `tmux new-session -A` creates when the session is gone; afterwards it always
+ // exists and the answer is meaningless. Without it a mirrored client could not tell "I joined
+ // your running agent" from "I just made you an empty login shell", which is what put a bare
+ // `~ %` prompt under a Claude node's title on the phone once the host's tmux server had died.
+ //
+ // Bounded, and fail-safe toward "warm": a probe that is slow or unprobeable answers `false`,
+ // so a client that cold-restores on `fresh` types nothing into a session that may be live.
+ // The bound matters because this precedes the RPC response and a probe can sit on its
+ // timeout when tmux (or, for a remote node, the master) is wedged.
const existed = await Promise.race([
- pty.sessionExists(nodeId).catch(() => true),
+ prep.sessionExists().catch(() => true),
new Promise<boolean>((r) => setTimeout(() => r(true), FRESH_PROBE_BUDGET_MS))
])
socket.respond(req.id, true, { streamId, fresh: !existed })
- return pty.captureSnapshot(nodeId).catch(() => '')
- })()
- .then((snapshot) => {
- // The stream may have been killed/closed while the capture was in flight.
- if (!streams.has(streamId)) return
- // Snapshot first (current screen) — then live output begins on attach.
- sendSnapshot(streamId, stream, snapshot)
- try {
- stream.sessionId = pty.attachDetached(nodeId, sinks, { cols, rows })
- } catch {
- // Attach failed (e.g. tmux unavailable) — surface as an exit so the client tears down.
- socket.sendFrame(
- OP.Error,
- streamId,
- stream.seq++,
- textEncoder.encode(JSON.stringify({ exitCode: 1 }))
- )
- dropStream(streamId)
+ const snapshot = await prep.snapshot().catch(() => '')
+ // The stream may have been killed/closed while the capture was in flight.
+ if (!streams.has(streamId)) return
+ // Snapshot first (current screen) — then live output begins on attach.
+ sendSnapshot(streamId, stream, snapshot)
+ try {
+ const sessionId = await prep.attach(sinks)
+ if (!streams.has(streamId)) {
+ // Closed while the spawn was in flight (a remote spawn awaits the master's pacing gate):
+ // release the client we just made; the session itself keeps running.
+ pty.kill(null, sessionId)
+ return
}
- })
+ stream.sessionId = sessionId
+ } catch {
+ // Attach failed (e.g. tmux unavailable, master gone) — surface as an exit so the client
+ // tears down.
+ socket.sendFrame(
+ OP.Error,
+ streamId,
+ stream.seq++,
+ textEncoder.encode(JSON.stringify({ exitCode: 1 }))
+ )
+ dropStream(streamId)
+ }
+ })()
}
// Serve a `fs.*` RPC by calling the shared fs-ops on the host's real filesystem and responding
diff --git a/src/main/remote/remote-security.test.ts b/src/main/remote/remote-security.test.ts
index 9176f113f..623a1a0de 100644
--- a/src/main/remote/remote-security.test.ts
+++ b/src/main/remote/remote-security.test.ts
@@ -31,17 +31,30 @@ function makeHostFakes() {
readBinary: async () => '',
writeText: async () => true
}
- const pty = {
+ // The relay attach is decided in core (`prepareRelayAttach`); this fake composes it from the
+ // three steps it hands back, so the host-service tests below keep pinning the ORDER the host
+ // runs them in (probe → reply → snapshot → attach) without a real PtyManager.
+ const fake = {
createDetached: vi.fn(() => 'sess'),
- attachDetached: vi.fn(() => 'sess'),
- captureSnapshot: vi.fn(async () => ''),
+ attachDetached: vi.fn((..._args: unknown[]) => 'sess'),
+ captureSnapshot: vi.fn(async (_nodeId?: string) => ''),
// Asked before every attach so the client learns whether the session had to be created.
- sessionExists: vi.fn(async () => true),
+ sessionExists: vi.fn(async (_nodeId?: string) => true),
write: vi.fn(),
resize: vi.fn(),
setFlow: vi.fn(),
kill: vi.fn()
- } as unknown as HostPtyManager
+ }
+ const pty = {
+ ...fake,
+ prepareRelayAttach: vi.fn(async (nodeId: string, size: { cols: number; rows: number }) => ({
+ kind: 'ready' as const,
+ remote: false,
+ sessionExists: () => pty.sessionExists(nodeId),
+ snapshot: () => pty.captureSnapshot(nodeId),
+ attach: async (sinks: unknown) => pty.attachDetached(nodeId, sinks, size)
+ }))
+ } as unknown as HostPtyManager & typeof fake
return { socket, responses, fs, reads, pty }
}
@@ -266,6 +279,39 @@ describe('pty.attach reports whether it had to CREATE the session', () => {
})
})
+// A node that lives on a remote host the desktop cannot reach right now is REFUSED, with a sentence
+// the phone can show — never attached (the old bare `attachDetached` made it a LOCAL shell in this
+// machine's `$HOME` wearing the remote node's id). The refusal hands out no stream, so nothing may
+// be left reserved behind it.
+describe('pty.attach refused by core (remote node, no master)', () => {
+ it('answers ok:false with the reason, attaches nothing and releases the stream', async () => {
+ const { socket, responses, fs, pty } = makeHostFakes()
+ ;(pty.prepareRelayAttach as ReturnType<typeof vi.fn>).mockResolvedValue({
+ kind: 'refused',
+ reason: 'not-connected',
+ message: 'This session lives on [email protected], which this computer is not connected to right now.'
+ })
+ const events: string[] = []
+ const handlers = createHostHandlers(
+ pty, socket, fs, () => ['/work'], async () => '', () => null,
+ undefined, undefined, undefined,
+ { attached: (id: string) => events.push(`+${id}`), detached: (id: string) => events.push(`-${id}`) }
+ )
+ handlers.onRpc({ id: 'a', method: 'pty.attach', params: { nodeId: 'node-ssh', cols: 80, rows: 24, projectId: 'p-ssh' } })
+ await vi.waitFor(() => expect(responses.length).toBeGreaterThan(0))
+ expect(responses.at(-1)).toEqual({
+ id: 'a',
+ ok: false,
+ body: { reason: 'not-connected', message: expect.stringContaining('[email protected]') }
+ })
+ expect(pty.attachDetached).not.toHaveBeenCalled()
+ expect(pty.sessionExists).not.toHaveBeenCalled()
+ expect(events).toEqual(['+node-ssh', '-node-ssh'])
+ // The phone's project hint reaches core, which may only use it to choose or refuse.
+ expect(pty.prepareRelayAttach).toHaveBeenCalledWith('node-ssh', { cols: 80, rows: 24 }, { projectId: 'p-ssh' })
+ })
+})
+
// Issue #914: a session-host session follows its most recently active viewer, so the pty can run
// at a size the phone did not ask for. The relay tells it with `OP.Resized` (same payload as
// `OP.Resize`), and a phone that did not say it renders that frame is a ceiling for the session.
@@ -281,7 +327,7 @@ describe('pty.attach forwards the real pty size as OP.Resized', () => {
handlers.onRpc({ id: 'a', method: 'pty.attach', params: { nodeId: 'node-a', cols: 80, rows: 24, ...params } })
return { ...fakes, frames }
}
- const sinksOf = async (pty: HostPtyManager) => {
+ const sinksOf = async (pty: ReturnType<typeof makeHostFakes>['pty']) => {
await vi.waitFor(() => expect(pty.attachDetached).toHaveBeenCalled())
return (pty.attachDetached as ReturnType<typeof vi.fn>).mock.calls[0][1] as import('../../core/pty-manager').DetachedSinks
}
diff --git a/test/remote/host-handlers.test.ts b/test/remote/host-handlers.test.ts
index 9d502c8e1..363fa1d7a 100644
--- a/test/remote/host-handlers.test.ts
+++ b/test/remote/host-handlers.test.ts
@@ -16,7 +16,19 @@ function fakePty() {
let counter = 0
let snapshot = ''
let sessionLive = true
- const mgr: HostPtyManager = {
+ // The relay attach is decided in core (`prepareRelayAttach`); this fake composes it from its own
+ // probe/snapshot/attach so the sequence the host runs them in stays observable in `calls`.
+ const mgr: HostPtyManager & {
+ attachDetached(persistKey: string, sinks: DetachedSinks, options?: Omit<PtyCreateOptions, 'persistKey'>): string
+ captureSnapshot(persistKey: string): Promise<string>
+ } = {
+ prepareRelayAttach: async (nodeId, size) => ({
+ kind: 'ready',
+ remote: false,
+ sessionExists: () => mgr.sessionExists(nodeId),
+ snapshot: () => mgr.captureSnapshot(nodeId),
+ attach: async (sinks) => mgr.attachDetached(nodeId, sinks, size)
+ }),
createDetached(options, sinks) {
lastOptions = options
lastSinks = sinks