Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(ssh): a remote node is never spawned as a local shell
enesbb872c29a49b
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex d2ea10c89..1cd5548b9 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -873,6 +873,20 @@ 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> {+ // 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+ // 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' }+ }// 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@@ -2100,15 +2114,22 @@ export class PtyManager {// pre-move terminal into the new one.await deleteScrollback(persistKey)if (sshRemote) {- // Remote (ssh-project) node: there is no local tmux session — end the REMOTE one.+ // Remote (ssh-project) node: end the REMOTE session.const ssh = findSsh()- if (!ssh) return- try {- await runAsync(ssh, remoteTmuxKillArgs(sshRemote.conn, sshRemote.controlPath, sessionName(persistKey)))- } catch {- // remote session may not exist / master down; ignore+ if (ssh) {+ try {+ await runAsync(ssh, remoteTmuxKillArgs(sshRemote.conn, sshRemote.controlPath, sessionName(persistKey)))+ } catch {+ // remote session may not exist / master down; ignore+ }}- return+ // ...and then fall through to the LOCAL kill below rather than returning. A remote node+ // normally has no local session — but it may have one from before `requireRemote`, when a+ // create issued with the master down spawned a local shell under this exact name. That+ // orphan outlived everything (this branch used to return here, so the delete never reached+ // it) with whatever the node had launched still running in it. The node is being deleted:+ // anything wearing its name goes with it. Costs one `kill-session` that usually says "no+ // such session", which is already the ignored case below.}if (!this.tmuxPath) returntry {diff --git a/src/core/pty-require-remote.test.ts b/src/core/pty-require-remote.test.tsnew file mode 100644index 000000000..85428d439--- /dev/null+++ b/src/core/pty-require-remote.test.ts@@ -0,0 +1,87 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform, type FakePlatform } from './platform-fake'+import { IPC } from '../shared/ipc'+import type { PtyCreateOptions, PtyCreateResult } from '../shared/types'++/**+ * `requireRemote`: a node that belongs to a remote host is never spawned locally.+ *+ * The bug this pins: an SSH project's terminal, created while its ControlMaster was down (no+ * network, host unreachable), used to fall straight through to the LOCAL tmux/plain-shell branch —+ * a local shell in the local `$HOME` carrying the remote node's id, its `SSH user@host` header+ * chip, and (agent nodes) a cold-restore `--resume` typed on the wrong machine. Nothing in the+ * result said so, so it read as "the session reconnected".+ */+const spawned: Array<{ file: string; args: string[] }> = []++vi.mock('node-pty', () => ({+ spawn: (file: string, args: string[]) => {+ spawned.push({ file, args })+ return {+ onData: () => {},+ onExit: () => {},+ write: () => {},+ resize: () => {},+ pause: () => {},+ resume: () => {},+ kill: () => {},+ pid: 4321+ }+ }+}))++const ALICE = 1+const BOB = 2++describe('pty create: requireRemote never falls back to a local shell', () => {+ let fake: FakePlatform++ beforeEach(async () => {+ spawned.length = 0+ fake = fakePlatform()+ initPlatform(fake)+ const { PtyManager } = await import('./pty-manager')+ new PtyManager().registerIpc()+ })+ afterEach(() => {+ resetPlatformForTests()+ })++ const create = (clientId: number, options: Partial<PtyCreateOptions>) =>+ fake.handlers[IPC.ptyCreate](clientId, {+ cols: 80,+ rows: 24,+ persistKey: 'node-1',+ ...options+ }) as Promise<PtyCreateResult>++ it('refuses (spawning nothing) when the master is gone', async () => {+ const res = await create(ALICE, { requireRemote: true, cwd: '/srv/app' })++ expect(spawned).toHaveLength(0) // ← the whole point: no local shell wearing a remote node's id+ expect(res.unavailable).toBe('ssh')+ expect(res.sessionId).toBe('')+ expect(res.fresh).toBe(false) // nothing was created, so nothing is "cold"+ })++ it('without the flag the same options DO spawn locally (what used to happen silently)', async () => {+ const res = await create(ALICE, { cwd: '/srv/app' })++ expect(spawned).toHaveLength(1)+ expect(res.unavailable).toBeUndefined()+ expect(res.sessionId).not.toBe('')+ })++ it('still JOINS a live session for that node — only a fresh local spawn is refused', async () => {+ // The session is already running (it was created while the master was up). A second view —+ // the kanban card modal, another window — must attach to it: the session runs wherever it+ // runs, and refusing the join would break a perfectly healthy remote terminal.+ const first = await create(ALICE, {})+ const joined = await create(BOB, { requireRemote: true })++ expect(spawned).toHaveLength(1)+ expect(joined.unavailable).toBeUndefined()+ expect(joined.sessionId).toBe(first.sessionId)+ })+})diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 9365bfe1f..7337205a9 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -24,6 +24,7 @@ import {TerminalNode,setMoveIntoWorktreeHandler,setSshDropHandler,+ setSshRetryHandler,disposeTerminalOnUnmount,disposeParkedTerminal} from '../nodes/TerminalNode'@@ -6735,8 +6736,10 @@ export function Canvas() {})sshReconnectorRef.current = recsetSshDropHandler((projectId, nodeId) => rec.reportDrop(projectId, nodeId))+ setSshRetryHandler((projectId, nodeIds) => rec.retryNow(projectId, nodeIds))return () => {setSshDropHandler(null)+ setSshRetryHandler(null)rec.dispose()sshReconnectorRef.current = null}@@ -7376,7 +7379,22 @@ export function Canvas() {// reads as in-progress rather than hung.<span className="ui-spinner" aria-hidden />)}- {text}+ <span style={{ flex: 1 }}>{text}</span>+ {/* The banner used to be read-only: a failed connect left the user with a red strip+ and nowhere to click — the only ways back were switching tabs (which re-runs the+ active-project connect) or restarting the app. Reconnect runs the SAME attempt+ the auto-loop makes, jumping its backoff; on success the coordinator flushes the+ project's pending nodes, so terminals that refused to spawn locally come up+ remotely. Hidden while an attempt is already in flight (connecting/reconnecting)+ so it can't queue a second one on top. */}+ {isError && (+ <button+ className="ssh-banner__retry"+ onClick={() => sshReconnectorRef.current?.retryNow(activeProjectId)}+ >+ Reconnect+ </button>+ )}</div>)})()}diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsxindex 442dc26e0..f7764ed92 100644--- a/src/renderer/components/kanban/ModalTerminal.tsx+++ b/src/renderer/components/kanban/ModalTerminal.tsx@@ -24,7 +24,7 @@ import {CO_ATTACH_MOUSE_SEQ} from '../../terminal/terminal-config'import { useXtermVisualSettings } from '../../terminal/useXtermVisualSettings'-import { resolveSshRemote } from '../../nodes/TerminalNode'+import { resolveSshRemote, reportSshDrop } from '../../nodes/TerminalNode'import { buildSshArgs, type SshConnection } from '@shared/ssh'/** The subset of a node's `data` a SECOND client needs to attach to its session the same way the@@ -161,12 +161,26 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: Moda})void (async () => {+ // Read here, not at click time: a modal only ever opens over the ACTIVE project, and the+ // reconnect coordinator is keyed by project (same assumption as resolveSshRemote's).+ const projectId = useProjects.getState().activeProjectId// SSH-project node: resolve the live ControlMaster (may not be up yet on a cold load).const sshRemote =spawn.sshRemoteTmux && spawn.ssh? await resolveSshRemote(spawn.ssh, spawn.cwd): undefinedif (dead) return+ // The host is unreachable: spawn NOTHING. A create with no `sshRemote` falls through to+ // core's LOCAL tmux branch, and opening a card for a remote session would silently start a+ // local shell under that node's id — see PtyCreateOptions.requireRemote. The card says so+ // and the node is queued for the reconnect coordinator, exactly like the canvas node.+ if (spawn.sshRemoteTmux && !sshRemote) {+ term.write(+ `\r\n\x1b[90m[not connected — this session lives on ${spawn.ssh ? `${spawn.ssh.user}@${spawn.ssh.host}` : 'the remote host'}; nothing was started locally]\x1b[0m\r\n`+ )+ if (projectId) reportSshDrop(projectId, nodeId)+ return+ }// A local `ssh <host>` node runs ssh as its own pty program (shell:'ssh' + buildSshArgs); an// SSH-PROJECT node uses tmux on the remote host instead (sshRemote), so it is NOT localSsh.const localSsh = !!spawn.ssh && !spawn.sshRemoteTmux@@ -175,13 +189,19 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: Modarows: term.rows,shell: localSsh ? 'ssh' : spawn.shell,shellArgs: localSsh ? buildSshArgs(spawn.ssh!) : undefined,- // Don't spawn a LOCAL tmux in a non-existent remote cwd if the master never came up.- cwd: spawn.sshRemoteTmux && !sshRemote ? undefined : spawn.cwd,+ cwd: spawn.cwd,persistKey: nodeId,agentId: spawn.agentId,accountId: spawn.accountId,- sshRemote+ sshRemote,+ requireRemote: spawn.sshRemoteTmux})+ // Refused core-side (the master died inside our round-trip, or `ssh` is missing).+ if (res.unavailable) {+ term.write('\r\n\x1b[90m[not connected — nothing was started locally]\x1b[0m\r\n')+ if (projectId) reportSshDrop(projectId, nodeId)+ return+ }// Another client permanently deleted this node's session — never resurrect it (no live session// to join, and the tombstone refused a fresh spawn). Show the state and stop.if (res.closed) {diff --git a/src/renderer/lib/sshReconnect.test.ts b/src/renderer/lib/sshReconnect.test.tsindex 3a21480ae..956d1bcbe 100644--- a/src/renderer/lib/sshReconnect.test.ts+++ b/src/renderer/lib/sshReconnect.test.ts@@ -118,6 +118,51 @@ describe('SshReconnector', () => {expect(respawn).toHaveBeenCalledWith('p2', ['n2'])})+ // retryNow: the connection banner's Reconnect button, and an offline node's own. A person is+ // watching, so none of the automatic loop's patience applies to it.+ it('retryNow connects immediately, skipping the backoff delay', async () => {+ const { rec, connect, respawn } = make()+ rec.retryNow('p1', ['n1'])+ await vi.advanceTimersByTimeAsync(0) // no delay to wait out — just the connect's own promise+ expect(connect).toHaveBeenCalledTimes(1)+ expect(respawn).toHaveBeenCalledWith('p1', ['n1'])+ })++ it('retryNow revives an EXHAUSTED loop (giving up is for the automatic retries only)', async () => {+ let ok = false+ const { rec, connect, respawn } = make(async () => ok)+ rec.reportDrop('p1', 'n1')+ for (const d of RECONNECT_DELAYS_MS) await vi.advanceTimersByTimeAsync(d)+ expect(connect).toHaveBeenCalledTimes(RECONNECT_DELAYS_MS.length) // gave up++ ok = true // the user's network is back and they click Reconnect+ rec.retryNow('p1')+ await vi.advanceTimersByTimeAsync(0)+ expect(connect).toHaveBeenCalledTimes(RECONNECT_DELAYS_MS.length + 1)+ // The node queued by the original drop is still pending, so it comes back with this connect.+ expect(respawn).toHaveBeenCalledWith('p1', ['n1'])+ })++ it('retryNow clears the respawn-refuse window (a click is not a hot loop)', async () => {+ const { rec, respawn } = make()+ rec.reportDrop('p1', 'n1')+ await vi.advanceTimersByTimeAsync(RECONNECT_DELAYS_MS[0])+ expect(respawn).toHaveBeenCalledTimes(1)+ // Well inside the window that refuses an AUTOMATIC re-drop of this node.+ await vi.advanceTimersByTimeAsync(1000)+ rec.retryNow('p1', ['n1'])+ await vi.advanceTimersByTimeAsync(0)+ expect(respawn).toHaveBeenCalledTimes(2)+ })++ it('retryNow on a project with nothing pending still connects (banner with no dead nodes)', async () => {+ const { rec, connect, respawn } = make()+ rec.retryNow('p1')+ await vi.advanceTimersByTimeAsync(0)+ expect(connect).toHaveBeenCalledWith('p1')+ expect(respawn).not.toHaveBeenCalled()+ })+it('dispose cancels pending loops (no connects or respawns afterwards)', async () => {const { rec, connect, respawn } = make()rec.reportDrop('p1', 'n1')diff --git a/src/renderer/lib/sshReconnect.ts b/src/renderer/lib/sshReconnect.tsindex 232b81ad7..76683740a 100644--- a/src/renderer/lib/sshReconnect.ts+++ b/src/renderer/lib/sshReconnect.ts@@ -60,6 +60,34 @@ export class SshReconnector {if (loop.timer === null && loop.attempt < RECONNECT_DELAYS_MS.length) this.schedule(projectId, loop)}+ /**+ * The user asked for it (the connection banner's Reconnect, or an offline node's own button):+ * try NOW, whatever the backoff was doing.+ *+ * Three things separate this from `reportDrop`: it skips the first delay (a person is watching),+ * it resets an EXHAUSTED loop's attempt counter (giving up is for the automatic loop, not for+ * an explicit ask), and it clears the respawn-refuse window for the named nodes — that window+ * exists to stop a broken spawn from hot-looping by itself, and a click is not a hot loop.+ */+ retryNow(projectId: string, nodeIds: string[] = []): void {+ if (this.disposed) return+ let loop = this.loops.get(projectId)+ if (!loop) {+ loop = { pending: new Set(), timer: null, attempt: 0 }+ this.loops.set(projectId, loop)+ }+ for (const id of nodeIds) {+ loop.pending.add(id)+ this.lastRespawn.delete(id)+ }+ if (loop.timer !== null) {+ clearTimeout(loop.timer)+ loop.timer = null+ }+ loop.attempt = 0+ void this.tryConnect(projectId, loop)+ }+/** The project's master is (re)connected — by our loop or anyone else's. Flush pending nodes. */onConnected(projectId: string): void {if (this.disposed) returndiff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 50475e8d2..577747186 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -110,13 +110,27 @@ import { ColumnPill } from '../components/kanban/ColumnPill'import { BoardLogPanel } from '../components/kanban/BoardLogPanel'import { AgentMascot } from './AgentMascot'+/** How long a remote terminal waits for its project's ControlMaster before giving up and showing+ * the offline overlay. Sized for the SLOW-but-fine case (a cold app load whose connect is still+ * authenticating, a passphrase prompt, a distant host), not for the unreachable one — the+ * overlay it falls back to is cheap and self-healing, so waiting longer buys nothing. */+export const SSH_REMOTE_WAIT_MS = 20000++/** The active project's live ControlMaster path, if any. Lets the caller tell "we will resolve in+ * a microtask" from "we are about to sit in the wait below" without duplicating the lookup. */+export function currentControlPath(): string | undefined {+ return useSshConn.getState().getControlPath(useProjects.getState().activeProjectId)+}+/*** Resolve the `sshRemote` create option for an SSH-project terminal: the owning project's live* ControlMaster `controlPath` (set by Canvas's active-project effect on connect) plus the inline* connection and remote cwd. The controlPath may not be ready yet on a cold app load (child* effects run before the parent's connect resolves), so wait for it — briefly — before spawning.- * Returns undefined if no master appears within the window (connection failed); the caller then- * degrades gracefully instead of spawning a local tmux in a non-existent remote directory.+ *+ * Returns undefined if no master appears within the window (connection failed). The caller must+ * then spawn NOTHING — see `PtyCreateOptions.requireRemote`: a create without `sshRemote` does+ * not degrade to "no session", it degrades to a LOCAL one wearing the remote node's identity.*/export async function resolveSshRemote(conn: SshConnection,@@ -148,7 +162,10 @@ export async function resolveSshRemote(const v = s.byProject[projectId]?.controlPathif (v) finish(v)})- const timer = setTimeout(() => finish(useSshConn.getState().getControlPath(projectId)), 20000)+ const timer = setTimeout(+ () => finish(useSshConn.getState().getControlPath(projectId)),+ SSH_REMOTE_WAIT_MS+ )})}if (!controlPath) return undefined@@ -188,6 +205,28 @@ export function setSshDropHandler(fn: ((projectId: string, nodeId: string) => vosshDropHandler = fn}+/**+ * Report a remote terminal that has no session to the reconnect coordinator. Also used by the+ * kanban card modal, which spawns the same node through its own transport and hits the same+ * "no master" refusal — both surfaces queue the node so ONE reconnect flushes them together.+ */+export function reportSshDrop(projectId: string, nodeId: string): void {+ sshDropHandler?.(projectId, nodeId)+}++/**+ * Manual "Reconnect" bridge (same pattern as the drop bridge above). Canvas registers the+ * SshReconnector's `retryNow`; the offline overlay's button calls it with this node so the+ * user's explicit ask jumps the backoff — and clears the node's respawn-refuse window, which+ * exists to stop AUTOMATIC hot loops, not to make a person click twice.+ */+let sshRetryHandler: ((projectId: string, nodeIds: string[]) => void) | null = null+export function setSshRetryHandler(+ fn: ((projectId: string, nodeIds: string[]) => void) | null+): void {+ sshRetryHandler = fn+}+/*** Parked terminals: when a node unmounts (project switch), its xterm instance and live PTY* session are kept — the `.xterm` element is detached from the DOM and held here — so a remount@@ -449,8 +488,18 @@ interface CoState {* is recoverable and, unlike a silent stale-cwd respawn, honest. Cleared by that reopen.*/ended: boolean+ /**+ * This is an SSH-project terminal and its host is UNREACHABLE, so no session was spawned —+ * neither here nor, crucially, locally (see `PtyCreateOptions.requireRemote`).+ *+ * Unlike `closed`/`ended` this is not a respawn guard: it is the state the node sits in until+ * the project's ControlMaster comes back, and the reconnect coordinator (or the overlay's+ * Reconnect button) is expected to bump `respawnNonce` and try again. The node is reported to+ * that coordinator the moment it lands here, so an idle canvas heals itself.+ */+ offline: boolean}-const NO_CO: CoState = { letterbox: false, closed: null, ended: false }+const NO_CO: CoState = { letterbox: false, closed: null, ended: false, offline: false }const coStates = new Map<string, CoState>()const coSubs = new Map<string, (s: CoState) => void>()@@ -479,7 +528,12 @@ function setCo(key: string, patch: Partial<CoState>): void {const next = { ...prev, ...patch }// A no-op write must stay a no-op: applyFit clears the letterbox on every fit, and handing the// node a fresh object each time would re-render it for nothing (and, solo, on every resize tick).- if (next.letterbox === prev.letterbox && next.closed === prev.closed && next.ended === prev.ended)+ if (+ next.letterbox === prev.letterbox &&+ next.closed === prev.closed &&+ next.ended === prev.ended &&+ next.offline === prev.offline+ )returncoStates.set(key, next)coSubs.get(key)?.(next)@@ -797,6 +851,16 @@ export function TerminalNode({}))}+ // "Not connected" (CoState.offline): the host was unreachable, so this node has no session+ // anywhere. Ask the coordinator to re-establish the project's master NOW — it flushes the+ // pending nodes (this one included) on success, which is what respawns them. We do NOT bump+ // `respawnNonce` ourselves: a respawn before the master is back would just re-run the same+ // 20s wait and land right back here.+ const reconnectOffline = (): void => {+ const projectId = useProjects.getState().activeProjectId+ if (projectId) sshRetryHandler?.(projectId, [id])+ }+// Stable fallback reader: serialize the live xterm buffer when tmux capture is unavailable.const readBuffer = useCallback(() => {const t = termRef.current@@ -1676,11 +1740,36 @@ export function TerminalNode({// Canvas's active-project effect. On a cold app load child effects run before that parent// connect, so wait for it (briefly) before spawning. In Phase 1 a node only exists in the// active project's React Flow, so the active project is its owner.+ // Say so while we wait: the resolve below sits for up to SSH_REMOTE_WAIT_MS on a cold load+ // or an unreachable host, and a terminal that is silently blank for that long reads as+ // broken. Only when there is nothing to wait FOR is nothing printed (the common case: the+ // master is already up and this resolves in a microtask).+ if (sshRemoteTmux && ssh && !currentControlPath()) {+ // Drop the overlay for the duration of the attempt (this respawn IS the retry the user or+ // the coordinator asked for) so the line below is visible; it comes back if we fail.+ setCo(termKey, { offline: false })+ term.write(`\x1b[90m[connecting to ${ssh.user}@${ssh.host}…]\x1b[0m\r\n`)+ }const sshRemote =sshRemoteTmux && ssh? await resolveSshRemote(ssh, data.cwd as string | undefined): undefinedif (disposed) return+ // The host is unreachable (no master within the window). SPAWN NOTHING: a create with no+ // `sshRemote` lands in core's LOCAL tmux branch, and this node would come up as a local+ // shell in the local $HOME wearing its `SSH user@host` chip — replaying the REMOTE session's+ // scrollback snapshot, and (agent nodes) running the cold-restore `--resume` on the wrong+ // machine. `requireRemote` below refuses the same thing core-side; this is the near half,+ // which also saves the round-trip. Report the node so the reconnect coordinator retries.+ if (sshRemoteTmux && !sshRemote) {+ setCo(termKey, { offline: true })+ term.write(+ `\r\n\x1b[90m[not connected — this session lives on ${ssh ? `${ssh.user}@${ssh.host}` : 'the remote host'}; nothing was started locally]\x1b[0m\r\n`+ )+ if (sshProjectId) reportSshDrop(sshProjectId, id)+ return+ }+ setCo(termKey, { offline: false })sentCols = term.colssentRows = term.rowstransport@@ -1689,14 +1778,26 @@ export function TerminalNode({rows: term.rows,shell: localSsh ? 'ssh' : data.shell,shellArgs: localSsh ? buildSshArgs(ssh) : undefined,- // Don't spawn a LOCAL tmux in a non-existent remote cwd if the master never came up.- cwd: sshRemoteTmux && !sshRemote ? undefined : data.cwd,+ cwd: data.cwd,persistKey: id,agentId: data.agentId,accountId: data.accountId,- sshRemote+ sshRemote,+ // Belt AND braces: the guard above cannot see a `ssh` executable that has gone missing,+ // which is core's other route into the local branch.+ requireRemote: sshRemoteTmux})- .then(async ({ sessionId: sid, fresh, accountFallback: fellBack, closed, screen, coAttachMouse }) => {+ .then(async ({ sessionId: sid, fresh, accountFallback: fellBack, closed, screen, coAttachMouse, unavailable }) => {+ // REFUSED: `requireRemote` and core could not spawn remotely (the master died inside our+ // round-trip, or `ssh` is missing). Nothing was spawned — land in the same offline state+ // the near-side guard above produces, retry included.+ if (unavailable) {+ setCo(termKey, { offline: true })+ if (!disposed)+ term.write('\r\n\x1b[90m[not connected — nothing was started locally]\x1b[0m\r\n')+ if (sshProjectId) reportSshDrop(sshProjectId, id)+ return+ }// REFUSED: core's tombstone says another client deleted this node while we weren't// subscribed (our project was closed/inactive, so no `pty:closed` could reach us). Nothing// was spawned — land in the same "closed by <name>" state a subscribed co-viewer gets.@@ -3077,6 +3178,17 @@ export function TerminalNode({</button></div>)}+ {!co.closed && !co.ended && co.offline && (+ <div className="term-node__closed nodrag">+ <span>+ Not connected to {data.ssh ? `${(data.ssh as SshConnection).user}@${(data.ssh as SshConnection).host}` : 'the host'} — this session was not started+ locally.+ </span>+ <button className="term-node__reopen" onClick={reconnectOffline}>+ Reconnect+ </button>+ </div>+ )}{armed && !mdMode && (<divclassName="term-hover-guard"diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 77fb64640..482c41baf 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -1868,6 +1868,22 @@ body,background: rgba(var(--tint-rgb), 0.12);}+/* "Reconnect" in the SSH connection banner. The banner paints its own dark-red background, so this+ sits on a light translucent fill rather than the card tint the node buttons use. */+.ssh-banner__retry {+ padding: 3px 10px;+ border: 1px solid rgba(255, 255, 255, 0.35);+ border-radius: 6px;+ background: rgba(255, 255, 255, 0.12);+ color: inherit;+ font-size: 11px;+ cursor: pointer;+ white-space: nowrap;+}+.ssh-banner__retry:hover {+ background: rgba(255, 255, 255, 0.22);+}+/* Markdown view overlay (Cmd/Ctrl+M) */.term-md {position: absolute;diff --git a/src/shared/types.ts b/src/shared/types.tsindex 4d2f382ea..94b175afc 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -39,6 +39,20 @@ export interface PtyCreateOptions {* `remoteHome` is the connection's resolved `$HOME`, used to build an ABSOLUTE remote* `CLAUDE_CONFIG_DIR` for a managed remote account (tmux `-e` values are not shell-expanded). */sshRemote?: { controlPath: string; conn: import('./ssh').SshConnection; remoteCwd: string; hookEndpointPath?: string; tmuxConfPath?: string; remoteHome?: string }+ /**+ * This node BELONGS to a remote host: never spawn it locally.+ *+ * `sshRemote` says "here is the master to run over"; this says "and if there isn't one, spawn+ * NOTHING". Without it, a create with no `sshRemote` falls straight through to the local+ * tmux/plain-shell branches — which is how an SSH project's terminal, opened while the+ * ControlMaster was down (no network, laptop asleep, host unreachable), quietly became a LOCAL+ * shell in the local `$HOME`: same node id, same `SSH user@host` header chip, the remote+ * session's own scrollback snapshot replayed into it, and — for an agent node — a cold-restore+ * `claude --resume <remote session id>` running on the WRONG MACHINE, under the local account.+ * The refusal (`PtyCreateResult.unavailable`) is the honest answer: the node shows a+ * "not connected" overlay and re-spawns when the master is back.+ */+ requireRemote?: boolean}/**@@ -95,6 +109,17 @@ export interface PtyCreateResult {* must still restore the node), so the single-user delete→undo path is unchanged.*/closed?: { by: number | null }+ /**+ * REFUSED: `requireRemote` was set and no remote spawn was possible (no live ControlMaster, or+ * no `ssh` executable), so nothing was spawned (`sessionId` is empty) — see+ * `PtyCreateOptions.requireRemote` for what used to happen instead. The renderer shows the+ * "not connected" overlay and re-spawns the node once the project's master is back.+ *+ * Only ever set for a create that would have SPAWNED: a co-attach to a live session for this+ * node id still joins (the session is already running wherever it runs), so a second view of a+ * healthy remote terminal is unaffected.+ */+ unavailable?: 'ssh'}/** Payload of `pty:recycled` — see IPC.ptyRecycled and `recycleAction` in the renderer. */