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
perf(ssh): publish the ControlMaster before its setup chain, and pre-warm it at boot
enes7896fb8633de
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8e2e3feee..72981f227 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -855,6 +855,58 @@ session (you can't keep a live OS process across a reboot):reads no `CoState`, so a user who only ever opens the session from the board does not see thenotice; the honest fix is a shared node-notice surface rather than a second copy of the banner.+### SSH connect: the ControlMaster is published BEFORE its setup chain++`connectOnce` (`main/remote-ssh/ssh-project.ts`) used to publish a project's ControlMaster only with+`status: 'connected'` — i.e. after the reverse hook tunnel, ~23 serialized per-agent hook installs,+`printf $HOME`, the remote tmux.conf write + `source-file` and the Codex runtime staging had all+run. MEASURED against a real sshd through a 25 ms one-way delay proxy (50 ms RTT): that chain is+**3.54 s** on a fully-provisioned host, while **18 remote terminals attaching in parallel over a+warm master paint in a median of 0.16 s** and are all settled by 0.71 s. So the attach was never the+bottleneck — every terminal of a switched-to project simply sat in `resolveSshRemote`'s 20 s wait+printing `[connecting to user@host…]` into a blank pane, for a transport that was ready the whole+time.++Two additive changes, and the rules that keep them safe:++- **The early signal.** The moment `ssh -O check` answers, `connectOnce` emits+ `SshProjectStatusEvent.masterControlPath` on a `connecting` event. `connected` keeps its exact+ meaning (the whole chain finished) and everything hanging off it — git routing, the remote claude+ probe, the tunnel resync, the connection banner — is untouched. The renderer keeps it in its own+ map (`useSshConn.earlyByProject`), **never in `byProject`**, which a dozen readers treat as "this+ project is connected".+ - **Only a node whose remote tmux session ALREADY EXISTS may act on it**+ (`PtyApi.remoteSessionConfirmed` → `RemoteSessionIndex.verdict`, the strict `present`-only half+ of the coalesced `tmux list-sessions` read `create()` already makes, so a warm switch pays no+ extra round trip). `new-session -A` on a live session merely attaches, and the two things the+ setup chain provides — the remote tmux config (`-f`) and the hook/account environment (tmux+ `-e`) — are read at session CREATION only. A node whose session is ABSENT, **or whose host+ could not be read**, waits for `connected`: creating its session without the hook env costs it+ its agent-status badges silently, with no later event to repair it. That is why the index now+ exposes a TRI-STATE (`present | absent | unknown`) — `exists()` folds `unknown` into "exists"+ for its own caller, and this one needs the opposite fold. Decision logic is the pure+ `renderer/lib/sshRemoteWait.ts`; a cold node's wait is pinned by its own test.+ - **Never for an ADOPTED live-orphan master.** The tunnel-verification failure path may `-O exit`+ that master and rebuild it, which would kill a terminal that had attached over it meanwhile.+ The rebuild clears `reusedOrphan` and re-enters the loop, so a rebuilt master does publish.+- **The boot-time pre-warm** (`core/remote-ssh/ssh-prewarm.ts`, planner + runner pure and tested;+ wired in `main/index.ts`). The master for a project was dialed only when the user first switched+ to it, so the first visit of every app run paid the cold establish (**0.44 s** measured) plus the+ whole chain. `SshProjectManager.prewarm` now dials the masters of OPEN SSH projects shortly after+ boot, **one host at a time** (a burst of fresh masters is what trips a host's `MaxStartups`; the+ `SshChildGate` caps exec children per control path and does nothing about logins).+ - **A pre-warm is SILENT — no status event at all.** The user is by definition not looking (if+ they were, the active-project effect would have connected it loudly), so a failure must not+ raise the connection banner for a project they never opened. The mark is lifted the moment a+ real connect arrives for the same project, including one that coalesces onto the pre-warm's own+ in-flight attempt.+ - **It never prompts for a passphrase either** (`isQuietMasterPid` → main's prompt handler+ declines): a modal in front of a user who opened nothing is the loudest thing an SSH connect can+ do. That master fails auth quietly; the user's own connect spawns a new one and prompts normally.+ - **CLOSED projects are never dialed**, and neither is a project that already has a master or an+ attempt in flight. `closeProject` is non-destructive, so a closed tab is the user saying "not+ now".+### We have our own VT emulator — check it before asking tmuxxterm.js is not just a renderer. It parses the pane's output stream, so it **tracks DECSET modesdiff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex a131c67e5..af8498879 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -2355,6 +2355,36 @@ export class PtyManager {return this.remoteSessions.exists(sshRemote.controlPath, sessionId, sshRemote.conn)}+ /**+ * Was this node's remote tmux session POSITIVELY listed on the host? The strict half of the+ * probe above, for the renderer's early-attach gate.+ *+ * `exists()` folds an unreadable host into "exists" because its caller is about to decide+ * whether to type a resume command into a pane. This caller decides the opposite question —+ * may a terminal attach over a ControlMaster whose connect-time setup (remote tmux.conf, the+ * hook endpoint, the account env) has NOT finished yet — and there only a session that already+ * exists is safe: `new-session -A` on a live session merely attaches, so `-f` and the tmux `-e`+ * pairs (both creation-time only) are genuinely not needed. A session that is absent, or that we+ * simply could not read, must wait for the full `connected` instead, or the create would make a+ * session with no config and no hook env — which silently costs the node its agent-status badges.+ *+ * So: `true` ONLY for `present`; `absent` and `unknown` both answer false, and the caller waits.+ * Shares the one coalesced `tmux list-sessions` per host with `create()`, so a warm switch pays+ * no extra round trip (see remote-session-index.ts).+ */+ async remoteSessionConfirmed(+ persistKey: string,+ sshRemote: { controlPath: string; conn: SshConnection }+ ): Promise<boolean> {+ return (+ (await this.remoteSessions.verdict(+ sshRemote.controlPath,+ sessionName(persistKey),+ sshRemote.conn+ )) === 'present'+ )+ }+/** One coalesced remote `tmux list-sessions` per ControlMaster (see remote-session-index.ts).* `list` carries the SAME classification the per-node probe had: tmux's own exit 1 ("no server* running") is the only evidence of absence; ssh 255 / 127 / a timeout answer `unknown`, whichdiff --git a/src/core/remote-ssh/remote-session-index.test.ts b/src/core/remote-ssh/remote-session-index.test.tsindex a4762bf0f..3a6abc06a 100644--- a/src/core/remote-ssh/remote-session-index.test.ts+++ b/src/core/remote-ssh/remote-session-index.test.ts@@ -114,3 +114,39 @@ describe('RemoteSessionIndex', () => {expect(list).toHaveBeenCalledWith('/cm/p1', { host: 'nt-x' })})})++describe('RemoteSessionIndex.verdict (the strict tri-state behind exists)', () => {+ it('separates "absent" from "could not read" — the fold exists() cannot express', async () => {+ const present = new RemoteSessionIndex<null>({+ list: async (): Promise<SessionListOutcome> => ({ kind: 'names', names: ['nt-a'] })+ })+ const unreadable = new RemoteSessionIndex<null>({+ list: async (): Promise<SessionListOutcome> => ({ kind: 'unknown' })+ })++ expect(await present.verdict('/cm/p1', 'nt-a', null)).toBe('present')+ expect(await present.verdict('/cm/p1', 'nt-z', null)).toBe('absent')+ expect(await unreadable.verdict('/cm/p2', 'nt-a', null)).toBe('unknown')+ // …while exists() keeps folding an unreadable host into "exists" (never type into a live pane).+ expect(await unreadable.exists('/cm/p2', 'nt-a', null)).toBe(true)+ })++ it('a session this process just spawned reads present without a list read', async () => {+ const list = vi.fn(async (): Promise<SessionListOutcome> => ({ kind: 'names', names: [] }))+ const idx = new RemoteSessionIndex<null>({ list })+ idx.markPresent('/cm/p1', 'nt-a')+ expect(await idx.verdict('/cm/p1', 'nt-a', null)).toBe('present')+ expect(list).not.toHaveBeenCalled()+ })++ it('shares ONE list read between exists() and verdict() in a burst', async () => {+ const list = vi.fn(async (): Promise<SessionListOutcome> => ({ kind: 'names', names: ['nt-a'] }))+ const idx = new RemoteSessionIndex<null>({ list })+ const [a, b] = await Promise.all([+ idx.verdict('/cm/p1', 'nt-a', null),+ idx.exists('/cm/p1', 'nt-a', null)+ ])+ expect([a, b]).toEqual(['present', true])+ expect(list).toHaveBeenCalledTimes(1)+ })+})diff --git a/src/core/remote-ssh/remote-session-index.ts b/src/core/remote-ssh/remote-session-index.tsindex d6160bf93..658ad0f52 100644--- a/src/core/remote-ssh/remote-session-index.ts+++ b/src/core/remote-ssh/remote-session-index.ts@@ -35,6 +35,19 @@ export const REMOTE_SESSION_INDEX_TTL_MS = 1000/** What one `tmux list-sessions` read established. `unknown` is a failed READ, never absence. */export type SessionListOutcome = { kind: 'names'; names: string[] } | { kind: 'unknown' }+/**+ * What we know about ONE session, kept tri-state on purpose.+ *+ * `exists()` folds `unknown` into "exists" because its caller is about to type into a pane and a+ * failed read must never be mistaken for a cold session. A second caller — the early-attach gate+ * (`SshProjectManager` publishes the ControlMaster before its setup chain finishes) — needs the+ * OPPOSITE fold: it may only skip the wait when the host POSITIVELY listed the session, because+ * attaching early to a session that does not exist creates it without the tmux `-f` config and the+ * creation-time `-e` hook env. Both folds are honest; neither may be derived from the other's+ * boolean, so the verdict is exposed as it is actually known.+ */+export type SessionVerdict = 'present' | 'absent' | 'unknown'+export interface RemoteSessionIndexDeps<Ctx> {/** Run `tmux list-sessions` on the host behind `controlPath` and classify the result. `ctx` is* whatever the caller needs to BUILD that command (the project's `SshConnection`); the index@@ -67,8 +80,17 @@ export class RemoteSessionIndex<Ctx> {* nothing into the pane. Concurrent callers for the same host share ONE list read.*/async exists(controlPath: string, sessionId: string, ctx: Ctx): Promise<boolean> {+ // A failed read is never evidence of absence.+ return (await this.verdict(controlPath, sessionId, ctx)) !== 'absent'+ }++ /**+ * The tri-state answer behind `exists`. `unknown` is a failed READ (dead master, ssh missing, a+ * timeout) — callers that would ACT on absence must treat it as "do not know", not as absence.+ */+ async verdict(controlPath: string, sessionId: string, ctx: Ctx): Promise<SessionVerdict> {const entry = this.fresh(controlPath)- if (entry?.spawned.has(sessionId)) return true+ if (entry?.spawned.has(sessionId)) return 'present'if (entry?.outcome) return verdict(entry.outcome, sessionId)if (entry?.inflight) return verdict(await entry.inflight, sessionId)@@ -116,7 +138,7 @@ export class RemoteSessionIndex<Ctx> {}}-function verdict(outcome: SessionListOutcome, sessionId: string): boolean {- // A failed read is never evidence of absence.- return outcome.kind === 'unknown' ? true : outcome.names.includes(sessionId)+function verdict(outcome: SessionListOutcome, sessionId: string): SessionVerdict {+ if (outcome.kind === 'unknown') return 'unknown'+ return outcome.names.includes(sessionId) ? 'present' : 'absent'}diff --git a/src/core/remote-ssh/ssh-prewarm.test.ts b/src/core/remote-ssh/ssh-prewarm.test.tsnew file mode 100644index 000000000..320c758e8--- /dev/null+++ b/src/core/remote-ssh/ssh-prewarm.test.ts@@ -0,0 +1,148 @@+import { describe, it, expect, vi } from 'vitest'+import { planSshPrewarm, runSshPrewarm, type SshPrewarmCandidate } from './ssh-prewarm'+import type { SshConnection } from '../../shared/ssh'++const conn = (host: string): SshConnection => ({ host, user: 'u', label: host })+const sshProject = (id: string, host: string, over: Partial<SshPrewarmCandidate> = {}): SshPrewarmCandidate => ({+ id,+ ssh: { server: conn(host), remoteCwd: '/srv' },+ ...over+})++describe('planSshPrewarm', () => {+ it('plans the open SSH projects, in index order', () => {+ const plan = planSshPrewarm({+ projects: [sshProject('p1', 'a'), { id: 'local' }, sshProject('p2', 'b')],+ busy: () => false+ })+ expect(plan.map((t) => t.projectId)).toEqual(['p1', 'p2'])+ expect(plan[0]).toEqual({ projectId: 'p1', conn: conn('a'), remoteCwd: '/srv' })+ })++ it('never dials a CLOSED project — a closed tab is the user saying "not now"', () => {+ const plan = planSshPrewarm({+ projects: [sshProject('p1', 'a', { closed: true }), sshProject('p2', 'b')],+ busy: () => false+ })+ expect(plan.map((t) => t.projectId)).toEqual(['p2'])+ })++ it('skips a project that is already connected or already being connected', () => {+ const plan = planSshPrewarm({+ projects: [sshProject('p1', 'a'), sshProject('p2', 'b')],+ busy: (id) => id === 'p1'+ })+ expect(plan.map((t) => t.projectId)).toEqual(['p2'])+ })++ it('plans one master per project id even if the index repeats one', () => {+ const plan = planSshPrewarm({+ projects: [sshProject('p1', 'a'), sshProject('p1', 'a')],+ busy: () => false+ })+ expect(plan).toHaveLength(1)+ })+})++describe('runSshPrewarm', () => {+ it('dials ONE HOST AT A TIME, never a burst', async () => {+ const order: string[] = []+ let inFlight = 0+ let peak = 0+ const connect = vi.fn(async (t: { projectId: string }) => {+ inFlight+++ peak = Math.max(peak, inFlight)+ order.push(t.projectId)+ await Promise.resolve()+ inFlight--+ })+ const attempted = await runSshPrewarm(+ [+ { projectId: 'p1', conn: conn('a') },+ { projectId: 'p2', conn: conn('b') },+ { projectId: 'p3', conn: conn('c') }+ ],+ { connect, busy: () => false, delay: async () => {}, gapMs: 10 }+ )+ expect(attempted).toBe(3)+ expect(peak).toBe(1)+ expect(order).toEqual(['p1', 'p2', 'p3'])+ })++ it('re-asks at FIRE time: a project opened mid-queue is left to its own connect', async () => {+ const dialed: string[] = []+ const busy = new Set<string>()+ await runSshPrewarm(+ [+ { projectId: 'p1', conn: conn('a') },+ { projectId: 'p2', conn: conn('b') }+ ],+ {+ connect: async (t) => {+ dialed.push(t.projectId)+ busy.add('p2') // the user switched to p2 while p1 was dialing+ },+ busy: (id) => busy.has(id),+ delay: async () => {},+ gapMs: 0+ }+ )+ expect(dialed).toEqual(['p1'])+ })++ it('a failing dial is swallowed and the queue continues — a pre-warm never banners', async () => {+ const dialed: string[] = []+ const attempted = await runSshPrewarm(+ [+ { projectId: 'p1', conn: conn('a') },+ { projectId: 'p2', conn: conn('b') }+ ],+ {+ connect: async (t) => {+ dialed.push(t.projectId)+ if (t.projectId === 'p1') throw new Error('Could not establish the SSH connection.')+ },+ busy: () => false,+ delay: async () => {},+ gapMs: 0+ }+ )+ expect(dialed).toEqual(['p1', 'p2'])+ expect(attempted).toBe(2)+ })++ it('leaves a gap between hosts, but not a trailing one', async () => {+ const delay = vi.fn(async () => {})+ await runSshPrewarm(+ [+ { projectId: 'p1', conn: conn('a') },+ { projectId: 'p2', conn: conn('b') }+ ],+ { connect: async () => {}, busy: () => false, delay, gapMs: 750 }+ )+ expect(delay).toHaveBeenCalledTimes(1)+ expect(delay).toHaveBeenCalledWith(750)+ })++ it('stops when asked (quit)', async () => {+ const dialed: string[] = []+ let stop = false+ await runSshPrewarm(+ [+ { projectId: 'p1', conn: conn('a') },+ { projectId: 'p2', conn: conn('b') }+ ],+ {+ connect: async (t) => {+ dialed.push(t.projectId)+ stop = true+ },+ busy: () => false,+ delay: async () => {},+ gapMs: 0,+ stopped: () => stop+ }+ )+ expect(dialed).toEqual(['p1'])+ })+})diff --git a/src/core/remote-ssh/ssh-prewarm.ts b/src/core/remote-ssh/ssh-prewarm.tsnew file mode 100644index 000000000..b9cd32361--- /dev/null+++ b/src/core/remote-ssh/ssh-prewarm.ts@@ -0,0 +1,100 @@+// Dial the ControlMasters of OPEN SSH projects shortly after boot, so the first switch to one is+// already warm.+//+// WHY (measured, 2026-09-15, real sshd behind a 25 ms one-way delay proxy = 50 ms RTT). A project's+// master is established only when the user first switches to it, so the first visit of every app+// run pays the cold establish (TCP + KEX + auth until `-O check` answers: 0.44 s) and then the+// connect's remote setup chain (~23 serialized ssh exec children: 3.54 s) before a single terminal+// can attach. Both are wall-clock the user spends looking at blank panes. Neither depends on the+// user having switched — so do them while nobody is waiting.+//+// Three properties this planner exists to guarantee, all of them things that were easy to get+// wrong by hand:+// - CLOSED projects are never dialed. `closeProject` is non-destructive and deliberately leaves+// the host's sessions running; a closed tab is the user saying "not now", and waking an SSH+// login (and possibly a passphrase prompt) for it is worse than a slow first switch.+// - A project that is already connected, or already being connected, is never re-dialed. The+// pre-warm must never be the thing that competes with the user's own connect.+// - One host at a time. Bursting every master at once is the failure mode the `SshChildGate`+// exists for, one level up: the gate caps exec children PER control path, so N simultaneous+// fresh masters to N hosts are N independent budgets and nothing paces the logins themselves.++import type { SshConnection } from '../../shared/ssh'++/** One project to pre-warm: everything `SshProjectManager.prewarm` needs, and nothing else. */+export interface SshPrewarmTarget {+ projectId: string+ conn: SshConnection+ remoteCwd?: string+}++/** The shape this reads off the workspace index. Structural on purpose — `Project` carries far+ * more than a pre-warm may look at, and narrowing it here keeps the planner a pure unit. */+export interface SshPrewarmCandidate {+ id: string+ closed?: boolean+ ssh?: { server: SshConnection; remoteCwd: string }+}++export interface SshPrewarmPlanInput {+ projects: readonly SshPrewarmCandidate[]+ /** Is this project's master already up, or already being established? Re-asked at FIRE time too+ * (see `runSshPrewarm`), because a plan made at boot is stale the moment the user switches. */+ busy: (projectId: string) => boolean+}++/** The ordered list of projects worth pre-warming. Order is the index's own (the tab order). */+export function planSshPrewarm(input: SshPrewarmPlanInput): SshPrewarmTarget[] {+ const out: SshPrewarmTarget[] = []+ for (const p of input.projects) {+ if (!p.ssh || p.closed) continue+ if (input.busy(p.id)) continue+ // A project can appear twice in a malformed index; one master per id is all there is.+ if (out.some((t) => t.projectId === p.id)) continue+ out.push({ projectId: p.id, conn: p.ssh.server, remoteCwd: p.ssh.remoteCwd })+ }+ return out+}++export interface SshPrewarmRunDeps {+ /** Establish one master, silently. Must never reject (the manager's `prewarm` swallows). */+ connect: (target: SshPrewarmTarget) => Promise<void>+ /** Re-asked immediately before each dial: the user may have opened this project meanwhile. */+ busy: (projectId: string) => boolean+ /** Gap between hosts. Sequential dialing is the point; this only spaces them out further. */+ delay: (ms: number) => Promise<void>+ gapMs: number+ /** Abort the remaining queue (app quitting). */+ stopped?: () => boolean+}++/**+ * Dial the planned masters one at a time, re-checking each one at fire time.+ *+ * Sequential, never a `Promise.all`: each dial is a full TCP + KEX + auth login, and a burst of+ * them is exactly what trips a host's `MaxStartups` — the failure that reads to the user as a+ * dropped terminal and the reconnect backoff. Nothing here is awaited by any user-facing path.+ *+ * Returns how many dials were actually attempted, for tests and diagnostics.+ */+export async function runSshPrewarm(+ targets: readonly SshPrewarmTarget[],+ deps: SshPrewarmRunDeps+): Promise<number> {+ let attempted = 0+ for (let i = 0; i < targets.length; i++) {+ if (deps.stopped?.()) break+ const target = targets[i]+ // Fire-time re-ask: the plan was made seconds (and one user switch) ago.+ if (deps.busy(target.projectId)) continue+ attempted+++ try {+ await deps.connect(target)+ } catch {+ // A pre-warm failure is not a user-facing event. The project's own connect, on the switch+ // that actually opens it, reports its own error with its own ssh cause.+ }+ if (i < targets.length - 1 && deps.gapMs > 0) await deps.delay(deps.gapMs)+ }+ return attempted+}diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex 45628e80f..84c09a904 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -1308,6 +1308,21 @@ export class WorkspaceStore {return (this.index?.entries ?? []).filter((e) => e.ssh).map((e) => e.id)}+ /**+ * The OPEN ssh entries of the current index, with their endpoints — what the boot-time master+ * pre-warm dials (see core/remote-ssh/ssh-prewarm.ts).+ *+ * Deliberately NOT `sshProjectIds()` plus a lookup: a CLOSED project must never be dialed.+ * `closeProject` is non-destructive — it leaves the host's tmux sessions running and the project+ * on disk — so a closed tab is the user saying "not now", and waking an ssh login (possibly a+ * passphrase prompt) for one is worse than a slow first switch.+ */+ openSshProjects(): { id: string; ssh: NonNullable<Project['ssh']> }[] {+ return (this.index?.entries ?? [])+ .filter((e) => e.ssh && !e.closed)+ .map((e) => ({ id: e.id, ssh: e.ssh as NonNullable<Project['ssh']> }))+ }+/** The local folder cwd of a project by id (index lookup), or undefined for ssh/inline/unknown* projects. Sync (reads the in-memory index): the board-log router's local-vs-unsupported call. */localCwdForProject(projectId: string): string | undefined {diff --git a/src/main/index.ts b/src/main/index.tsindex 7f383e4ae..26b8a6cd3 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -220,6 +220,7 @@ import {remotePaneCommandArgs} from '../core/remote-ssh/control-master'import { planRemoteWorkspacePoll } from './remote-workspace-poll'+import { planSshPrewarm, runSshPrewarm } from '../core/remote-ssh/ssh-prewarm'import { sessionName } from '../core/tmux-naming'import { posixQuote, sshHostKey, type SshConnection } from '../shared/ssh'import { buildHandoff, type HandoffRemote } from './handoff'@@ -1443,6 +1444,15 @@ app.whenReady().then(async () => {ptyManager.captureSession(persistKey, full))+ // The early-attach gate (see PtyManager.remoteSessionConfirmed). Registered here rather than in+ // core's shared pty block because only the desktop shell has SSH projects at all; the browser+ // bridge answers a documented `false`.+ corePlatform.handle(+ IPC.ptyRemoteSessionConfirmed,+ (persistKey: string, sshRemote: { controlPath: string; conn: SshConnection }) =>+ ptyManager.remoteSessionConfirmed(persistKey, sshRemote)+ )+// Gemini's title read needs the transcript path its own context tail already tracks (nothing// scans for it). That tail is created ~600 lines below with the rest of the hook plumbing, while// this deps object is consumed by the ptyReadSessionName handler just under here and by the@@ -3950,6 +3960,48 @@ app.whenReady().then(async () => {// carries the value the user last saved. 0 (the default) keeps the conf byte-identical.() => settingsStore.get().tmuxLeadPaneWidth)+ // Pre-warm the ControlMasters of OPEN SSH projects, in the background, one host at a time.+ //+ // Without this the master for a project is dialed only when the user first switches to it, so the+ // first visit of every app run pays the cold establish (0.44 s at 50 ms RTT) and then the whole+ // connect-time setup chain (~3.5 s) before a terminal can attach. Both are wall-clock spent in+ // front of blank panes, and neither depends on the user having switched — so spend it while+ // nobody is waiting. Measured numbers and the planner's three rules: core/remote-ssh/ssh-prewarm.ts.+ //+ // Silent by construction: `prewarm` marks the attempt quiet, so no status event (and therefore no+ // connection banner) can come out of a project the user is not looking at — and any real connect+ // for the same project lifts that mark and takes over the attempt.+ {+ /** Let the window, the workspace load and the first canvas settle before dialing anything. */+ const PREWARM_START_MS = 4_000+ /** Gap between hosts. Sequential dialing already paces the logins; this widens it so a machine+ * with many saved servers does not look like a login burst to a shared bastion. */+ const PREWARM_GAP_MS = 750+ setTimeout(() => {+ void (async () => {+ const mgr = sshProjectManager+ if (!mgr) return+ // The index is normally already loaded by boot; load() is idempotent and cheap, and+ // without it a slow first load would make the pre-warm a no-op for the whole run.+ // sideline:false — a read-only caller must never rename a mid-merge project.json.+ await workspaceStore.load({ sideline: false }).catch(() => {})+ const targets = planSshPrewarm({+ projects: workspaceStore.openSshProjects(),+ busy: (projectId) => mgr.isBusy(projectId)+ })+ await runSshPrewarm(targets, {+ connect: (t) => mgr.prewarm(t.projectId, t.conn, t.remoteCwd),+ busy: (projectId) => mgr.isBusy(projectId),+ delay: (ms) => new Promise((res) => setTimeout(res, ms)),+ gapMs: PREWARM_GAP_MS+ // No `stopped` predicate: nothing here is awaited by a user-facing path, and a dial in+ // flight is abandoned with the process on quit.+ })+ })().catch(() => {+ // A pre-warm that cannot even be planned changes nothing about how projects connect.+ })+ }, PREWARM_START_MS)+ }// Wake-from-sleep: re-validate every SSH master NOW instead of letting ServerAlive discover the// dead TCP ~60s later — until it does, every remote terminal looks alive and is dead (no echo,// no scroll). The small delay lets the network interface come back up first; connect() isdiff --git a/src/main/remote-ssh/ssh-project.prewarm.test.ts b/src/main/remote-ssh/ssh-project.prewarm.test.tsnew file mode 100644index 000000000..52d93baac--- /dev/null+++ b/src/main/remote-ssh/ssh-project.prewarm.test.ts@@ -0,0 +1,250 @@+import { promises as fs } from 'fs'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { SshProjectManager } from './ssh-project'+import { controlPathFor } from '../../core/remote-ssh/control-master'+import type { SshProjectStatusEvent } from '@shared/types'+import type { SshConnection } from '@shared/ssh'++const conn: SshConnection = { host: 'h', user: 'u' }++/** `makeMgr` with the full status EVENTS retained (the shared harness keeps only `status`), and a+ * `run` that lets the remote hook setup verify so a connect reaches `connected`. */+function makeMgr(over: Partial<ConstructorParameters<typeof SshProjectManager>[0]> = {}) {+ const events: SshProjectStatusEvent[] = []+ const setupCalls: string[] = []+ const spawnMaster = vi.fn(() => ({ kill: vi.fn(), on: vi.fn(), pid: () => 4242 }))+ const run = vi.fn(async (args: string[]) => {+ const j = args.join(' ')+ // Anything that is NOT the `-O check` is part of the post-master setup chain.+ if (!j.includes('-O')) setupCalls.push(j)+ if (j.includes('$HOME')) return { code: 0, stdout: '/home/u' }+ if (j.includes('%{http_code}')) return { code: 0, stdout: '204' }+ return { code: 0, stdout: '' }+ })+ const mgr = new SshProjectManager({+ userDataDir: '/ud',+ spawnMaster,+ run,+ runScp: vi.fn(async () => ({ code: 0 })),+ getHook: () => ({ port: 1, token: 't', version: '1' }),+ onStatus: (e) => events.push({ ...e }),+ ...over+ } as ConstructorParameters<typeof SshProjectManager>[0])+ return { mgr, events, spawnMaster, run, setupCalls }+}++afterEach(() => {+ vi.restoreAllMocks()+})++describe('early ControlMaster publication (PR 1 part A)', () => {+ it('publishes the control path on `connecting`, BEFORE the setup chain runs', async () => {+ const seenSetupCallsAtPublish: number[] = []+ let setupCalls = 0+ const spawnMaster = vi.fn(() => ({ kill: vi.fn(), on: vi.fn(), pid: () => 1 }))+ const events: SshProjectStatusEvent[] = []+ const mgr = new SshProjectManager({+ userDataDir: '/ud',+ spawnMaster,+ run: vi.fn(async (args: string[]) => {+ const j = args.join(' ')+ if (!j.includes('-O')) setupCalls+++ if (j.includes('$HOME')) return { code: 0, stdout: '/home/u' }+ if (j.includes('%{http_code}')) return { code: 0, stdout: '204' }+ return { code: 0, stdout: '' }+ }),+ runScp: vi.fn(async () => ({ code: 0 })),+ getHook: () => ({ port: 1, token: 't', version: '1' }),+ onStatus: (e) => {+ events.push({ ...e })+ if (e.masterControlPath) seenSetupCallsAtPublish.push(setupCalls)+ }+ } as ConstructorParameters<typeof SshProjectManager>[0])++ await mgr.connect('p1', conn)++ const early = events.find((e) => e.masterControlPath)+ expect(early).toBeDefined()+ expect(early!.status).toBe('connecting') // additive: `connected` keeps its meaning+ expect(early!.masterControlPath).toBe(controlPathFor('p1'))+ // Nothing of the connect's remote setup chain had run yet — that is the whole point.+ expect(seenSetupCallsAtPublish).toEqual([0])+ // And the setup chain DID run afterwards, i.e. the early signal did not replace it.+ expect(setupCalls).toBeGreaterThan(0)+ expect(events.at(-1)?.status).toBe('connected')+ })++ it('does NOT publish early for an ADOPTED ORPHAN — that master can still be torn down', async () => {+ // A live leftover socket: connect adopts it instead of spawning. The tunnel-verification+ // failure path may `-O exit` and rebuild it, which would kill a terminal that attached early.+ vi.spyOn(fs, 'stat').mockResolvedValue({ isSocket: () => true } as never)+ const { mgr, events, spawnMaster } = makeMgr()++ await mgr.connect('p1', conn)++ expect(spawnMaster).not.toHaveBeenCalled() // adopted, not respawned+ expect(events.some((e) => e.masterControlPath)).toBe(false)+ expect(events.at(-1)?.status).toBe('connected') // the connect itself is unaffected+ })++ it('a REBUILT master (orphan whose tunnel failed) does publish early on its next pass', async () => {+ // The orphan is adopted, its hook tunnel fails to verify (curl never answers 204), so connect+ // drops it and spawns a fresh master — which is no longer an orphan and may publish.+ vi.spyOn(fs, 'stat').mockResolvedValue({ isSocket: () => true } as never)+ vi.spyOn(fs, 'rm').mockResolvedValue(undefined)+ let respawned = false+ const spawnMaster = vi.fn(() => {+ respawned = true+ return { kill: vi.fn(), on: vi.fn(), pid: () => 7 }+ })+ const events: SshProjectStatusEvent[] = []+ const mgr = new SshProjectManager({+ userDataDir: '/ud',+ spawnMaster,+ run: vi.fn(async (args: string[]) => {+ const j = args.join(' ')+ if (j.includes('$HOME')) return { code: 0, stdout: '/home/u' }+ // The tunnel verifies only once a FRESH master exists.+ if (j.includes('%{http_code}')) return { code: 0, stdout: respawned ? '204' : '000' }+ return { code: 0, stdout: '' }+ }),+ runScp: vi.fn(async () => ({ code: 0 })),+ getHook: () => ({ port: 1, token: 't', version: '1' }),+ onStatus: (e) => events.push({ ...e })+ } as ConstructorParameters<typeof SshProjectManager>[0])++ await mgr.connect('p1', conn)++ expect(spawnMaster).toHaveBeenCalledTimes(1)+ const early = events.filter((e) => e.masterControlPath)+ expect(early).toHaveLength(1)+ expect(early[0].masterControlPath).toBe(controlPathFor('p1'))+ })+})++describe('background pre-warm (PR 1 part B)', () => {+ it('connects silently — a pre-warm raises NO status event, and therefore no banner', async () => {+ const { mgr, events, spawnMaster } = makeMgr()++ await mgr.prewarm('p1', conn, '/srv')++ expect(spawnMaster).toHaveBeenCalledTimes(1)+ expect(mgr.refForProject('p1')).toBeDefined() // the master is up and reusable+ expect(events).toEqual([])+ })++ it('a FAILED pre-warm raises no error status either', async () => {+ const events: SshProjectStatusEvent[] = []+ const mgr = new SshProjectManager({+ userDataDir: '/ud',+ // Master exits at once and the socket never answers → connect fails.+ spawnMaster: vi.fn(() => ({+ kill: vi.fn(),+ on: vi.fn(),+ exited: () => true,+ stderr: () => 'Permission denied (publickey).',+ pid: () => 9+ })),+ run: vi.fn(async () => ({ code: 255, stdout: '' })),+ runScp: vi.fn(async () => ({ code: 0 })),+ getHook: () => ({ port: 1, token: 't', version: '1' }),+ onStatus: (e) => events.push({ ...e })+ } as ConstructorParameters<typeof SshProjectManager>[0])++ // Never rejects: a pre-warm is not a user action.+ await expect(mgr.prewarm('p1', conn)).resolves.toBeUndefined()+ expect(events).toEqual([])+ })++ it('the same connect FAILING loudly still reports its error (the mark is per attempt)', async () => {+ const events: SshProjectStatusEvent[] = []+ const mgr = new SshProjectManager({+ userDataDir: '/ud',+ spawnMaster: vi.fn(() => ({+ kill: vi.fn(),+ on: vi.fn(),+ exited: () => true,+ stderr: () => 'Permission denied (publickey).',+ pid: () => 9+ })),+ run: vi.fn(async () => ({ code: 255, stdout: '' })),+ runScp: vi.fn(async () => ({ code: 0 })),+ getHook: () => ({ port: 1, token: 't', version: '1' }),+ onStatus: (e) => events.push({ ...e })+ } as ConstructorParameters<typeof SshProjectManager>[0])++ await mgr.prewarm('p1', conn)+ events.length = 0+ await expect(mgr.connect('p1', conn)).rejects.toThrow(/SSH connection/)+ expect(events.map((e) => e.status)).toContain('error')+ })++ it('a LOUD connect that coalesces onto a pre-warm in flight lifts the silence', async () => {+ // The pre-warm's attempt is still waiting on `-O check` when the user opens the project.+ let answer = false+ const events: SshProjectStatusEvent[] = []+ const mgr = new SshProjectManager({+ userDataDir: '/ud',+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn(), pid: () => 3 })),+ run: vi.fn(async (args: string[]) => {+ const j = args.join(' ')+ if (j.includes('-O') && !answer) return { code: 1, stdout: '' }+ if (j.includes('$HOME')) return { code: 0, stdout: '/home/u' }+ if (j.includes('%{http_code}')) return { code: 0, stdout: '204' }+ return { code: 0, stdout: '' }+ }),+ runScp: vi.fn(async () => ({ code: 0 })),+ getHook: () => ({ port: 1, token: 't', version: '1' }),+ onStatus: (e) => events.push({ ...e })+ } as ConstructorParameters<typeof SshProjectManager>[0])++ const warm = mgr.prewarm('p1', conn)+ await Promise.resolve()+ const loud = mgr.connect('p1', conn) // joins the SAME attempt+ answer = true+ await Promise.all([warm, loud])++ // From the moment the user asked, this attempt speaks again — including the early signal.+ expect(events.some((e) => e.masterControlPath === controlPathFor('p1'))).toBe(true)+ expect(events.at(-1)?.status).toBe('connected')+ })++ it('never starts a second attempt beside a live connection or one in flight', async () => {+ const { mgr, spawnMaster } = makeMgr()+ await mgr.connect('p1', conn)+ await mgr.prewarm('p1', conn)+ expect(spawnMaster).toHaveBeenCalledTimes(1)+ expect(mgr.isBusy('p1')).toBe(true)+ expect(mgr.isBusy('p2')).toBe(false)+ })++ it('declines the passphrase prompt while an attempt is a silent pre-warm', async () => {+ let answer = false+ const mgr = new SshProjectManager({+ userDataDir: '/ud',+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn(), pid: () => 31337 })),+ run: vi.fn(async (args: string[]) => {+ const j = args.join(' ')+ if (j.includes('-O') && !answer) return { code: 1, stdout: '' }+ if (j.includes('$HOME')) return { code: 0, stdout: '/home/u' }+ if (j.includes('%{http_code}')) return { code: 0, stdout: '204' }+ return { code: 0, stdout: '' }+ }),+ runScp: vi.fn(async () => ({ code: 0 })),+ getHook: () => ({ port: 1, token: 't', version: '1' }),+ onStatus: () => {}+ } as ConstructorParameters<typeof SshProjectManager>[0])++ const warm = mgr.prewarm('p1', conn)+ // Wait until the master is REGISTERED (the connect does a few fs round trips first) but before+ // the socket answers — the window a real passphrase prompt would fire in.+ for (let i = 0; i < 50 && !mgr.isQuietMasterPid('31337'); i++) await new Promise((r) => setTimeout(r, 5))+ // The askpass helper's reported $PPID maps back to this project, which is a silent pre-warm.+ expect(mgr.isQuietMasterPid('31337')).toBe(true)+ expect(mgr.isQuietMasterPid('999')).toBe(false)+ answer = true+ await warm+ // Once the attempt settles the mark is gone: a later prompt for this project is the user's.+ expect(mgr.isQuietMasterPid('31337')).toBe(false)+ })+})diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.tsindex c0107ed6b..a5b60446e 100644--- a/src/main/remote-ssh/ssh-project.test.ts+++ b/src/main/remote-ssh/ssh-project.test.ts@@ -11,6 +11,20 @@ import type { SshConnection } from '@shared/ssh'const conn: SshConnection = { host: 'h', user: 'u' }+/**+ * The status PHASES a connect went through, with consecutive duplicates collapsed.+ *+ * A successful connect now emits `connecting` TWICE: once when the attempt starts, and once more+ * the moment `ssh -O check` answers, carrying `masterControlPath` — the additive early signal that+ * lets a terminal whose remote tmux session already exists attach without waiting out the remote+ * setup chain (see SshProjectStatusEvent.masterControlPath). The phase sequence is what these+ * assertions are about, so fold the repeat away rather than pinning an event count that says+ * nothing. The early signal has its own tests in ssh-project.prewarm.test.ts.+ */+function phases(statuses: readonly string[]): string[] {+ return statuses.filter((s, i) => s !== statuses[i - 1])+}+function makeMgr() {const statuses: string[] = []// spawnMaster: returns a fake child that "stays up"; run: resolves stdout for one-shot ssh.@@ -34,7 +48,7 @@ describe('SshProjectManager', () => {const { controlPath } = await mgr.connect('p1', conn)expect(controlPath).toBe(controlPathFor('p1'))// (A later `connected` event can carry the async claude-CLI probe's answer, see below.)- expect(statuses.slice(0, 2)).toEqual(['connecting', 'connected'])+ expect(phases(statuses).slice(0, 2)).toEqual(['connecting', 'connected'])})it('connect is idempotent, second call reuses the live master', async () => {@@ -557,7 +571,7 @@ describe('SshProjectManager', () => {onStatus: (e) => events.push(e.status)})const res = await mgr.connect('p1', conn) // resolves while the probe is still hanging- expect(events).toEqual(['connecting', 'connected'])+ expect(phases(events)).toEqual(['connecting', 'connected'])expect(res.claudeAutoPermissionMode).toBeUndefined() // unknown ⇒ bare command (fail-open)releaseProbe?.()})@@ -1093,7 +1107,7 @@ describe('SshProjectManager', () => {expect(rmSpy).toHaveBeenCalledWith(controlPathFor('p1'), { force: true })expect(spawnMaster).toHaveBeenCalledTimes(1)expect(controlPath).toBe(controlPathFor('p1'))- expect(statuses.slice(0, 2)).toEqual(['connecting', 'connected'])+ expect(phases(statuses).slice(0, 2)).toEqual(['connecting', 'connected'])})it('adopts a LIVE orphan master (whose hook tunnel verifies) instead of spawning a second one', async () => {@@ -1120,7 +1134,7 @@ describe('SshProjectManager', () => {await mgr.connect('p1', conn)expect(spawnMaster).not.toHaveBeenCalled() // reused, not respawnedexpect(rmSpy).not.toHaveBeenCalled() // a live socket is never unlinked- expect(statuses.slice(0, 2)).toEqual(['connecting', 'connected'])+ expect(phases(statuses).slice(0, 2)).toEqual(['connecting', 'connected'])})it('rebuilds a FRESH master when the adopted orphan cannot re-establish the hook tunnel', async () => {@@ -1168,7 +1182,7 @@ describe('SshProjectManager', () => {expect(seq).toEqual(['agent', 'spawn']) // agent up BEFORE the rebuilt master, on this site too// The retried setup over the fresh master verified → the remote endpoint file is advertised.expect(info.hookEndpointPath).toBe('/home/u/.nodeterm/hook-endpoint-p1.env')- expect(statuses.slice(0, 2)).toEqual(['connecting', 'connected'])+ expect(phases(statuses).slice(0, 2)).toEqual(['connecting', 'connected'])})it('the orphan-rebuild wait runs on connect-loop terms, not a fixed 5s inner loop', async () => {diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 0114e2ca5..08c0cbf14 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -528,7 +528,17 @@ export class SshProjectManager {* down under it. Waiting on a passphrase prompt widens that window to minutes, which turns the* race from unlikely into routine, so the coalescing has to live here rather than in callers.*/- connect(projectId: string, conn: SshConnection, remoteCwd?: string): Promise<ConnectResult> {+ connect(+ projectId: string,+ conn: SshConnection,+ remoteCwd?: string,+ /** INTERNAL (never reachable over IPC): `quiet` marks this attempt as the background pre-warm,+ * which emits no status events. Any loud connect — including one that coalesces onto a+ * pre-warm already in flight — lifts the mark for the rest of the attempt. See `quiet`. */+ opts?: { quiet?: boolean }+ ): Promise<ConnectResult> {+ if (opts?.quiet) this.quiet.add(projectId)+ else this.quiet.delete(projectId)const inFlight = this.inFlight.get(projectId)if (inFlight) {if (sameEndpoint(inFlight.conn, conn)) {@@ -595,6 +605,53 @@ export class SshProjectManager {})}+ /**+ * Projects whose CURRENT connect attempt was started by the background pre-warm, and which+ * therefore emit NO status events at all.+ *+ * A pre-warm is not a user action: it dials the masters of OPEN SSH projects shortly after boot+ * so the first switch to one is already warm. The user is by definition not looking at the+ * project (if they were, the active-project effect would have connected it loudly), so a failure+ * there must not raise the connection banner — an unreachable server the user never opened is+ * not an error they can act on. Silence is the whole contract: `connecting`, `connected`,+ * `disconnected` and `error` are all withheld, and the renderer learns everything it needs from+ * the reuse branch of the connect it issues when the project actually becomes active.+ *+ * The mark is LIFTED the moment a real (loud) `connect` arrives for the same project, including+ * one that coalesces onto the pre-warm's own in-flight attempt — from that point the user IS+ * looking, and the rest of that attempt's events surface normally.+ */+ private quiet = new Set<string>()++ /** Emit a status event unless this project's attempt is a silent pre-warm (see `quiet`). */+ private emitStatus(e: SshProjectStatusEvent): void {+ if (this.quiet.has(e.projectId)) return+ this.r.onStatus(e)+ }++ /**+ * Establish a project's ControlMaster in the BACKGROUND, silently.+ *+ * Without this the master for an SSH project is only dialed when the user first switches to it,+ * so the first visit of every app run pays the cold establish (measured 0.44 s at 50 ms RTT)+ * plus the whole connect-time setup chain before a single terminal can attach. Pre-warming turns+ * that first switch into the reuse branch, which returns in one `-O check`.+ *+ * Never starts a second attempt for a project that already has a master or an attempt in flight+ * — a pre-warm must never be the thing that competes with the user's own connect.+ */+ async prewarm(projectId: string, conn: SshConnection, remoteCwd?: string): Promise<void> {+ if (this.isBusy(projectId)) return+ try {+ await this.connect(projectId, conn, remoteCwd, { quiet: true })+ } catch {+ // Silent by design: this is a pre-warm, not a user action. The project's own connect (on the+ // switch that actually opens it) reports its own failure, with its own ssh error.+ } finally {+ this.quiet.delete(projectId)+ }+ }+private async connectOnce(projectId: string,conn: SshConnection,@@ -660,7 +717,7 @@ export class SshProjectManager {remoteClaudeVersion: existing.remoteClaudeVersion}}- this.r.onStatus({ projectId, status: 'reconnecting' })+ this.emitStatus({ projectId, status: 'reconnecting' })// `-O exit` first, kill() second: kill() is a no-op against a master that already daemonized// (ControlPersist), and the leftover-socket unlink below would otherwise pull the socket out// from under a still-live daemon that keeps its TCP session and remote reverse forward for@@ -678,7 +735,7 @@ export class SshProjectManager {} catch {// ignore, keeps the manager unit-testable}- this.r.onStatus({ projectId, status: 'connecting' })+ this.emitStatus({ projectId, status: 'connecting' })// A master socket FILE can outlive its process (app crash, `kill -9`, host sleep/resume, a// plain `kill()` on quit doesn't always let ssh unlink it). ssh's `ControlMaster=auto` REFUSES// to bind over an existing socket file ("ControlSocket … already exists, disabling@@ -754,6 +811,29 @@ export class SshProjectManager {for (;;) {const { code } = await this.r.run(checkMasterArgs(conn, controlPath))if (code === 0) {+ // THE TRANSPORT IS USABLE NOW — say so, before the setup chain below.+ //+ // Everything from here to `connected` is remote SETUP (the reverse hook tunnel and ~23+ // serialized per-agent hook installs, `printf $HOME`, the remote tmux.conf write ++ // source-file, the Codex runtime staging). Measured on a real sshd at 50 ms RTT that chain+ // is ~3.5 s, while 18 remote terminals attaching in parallel over a warm master paint in a+ // median of 0.16 s. Publishing the control path only at the END therefore left every+ // terminal of a switched-to project sitting in `resolveSshRemote`'s 20 s wait, printing+ // "[connecting to user@host…]" into a blank pane for seconds — for a transport that was+ // ready the whole time.+ //+ // Additive: `connected` still means the whole chain finished, and only a node whose remote+ // tmux session ALREADY EXISTS may act on this (see SshProjectStatusEvent.masterControlPath+ // and PtyApi.remoteSessionConfirmed). A cold node still waits, because its session is+ // CREATED by the attach and `-f` / the tmux `-e` hook+account env are creation-time only.+ //+ // Not for an ADOPTED ORPHAN: the tunnel-verification failure path a few lines below may+ // `-O exit` that master and rebuild it, which would kill any terminal that had attached+ // over it in the meantime. The rebuild clears `reusedOrphan` and re-enters this loop, so a+ // rebuilt master does publish here on its next pass.+ if (!reusedOrphan) {+ this.emitStatus({ projectId, status: 'connecting', masterControlPath: controlPath })+ }// Master is up. Best-effort remote hook setup (reverse tunnel + endpoint + install);// fail-open, a null result just means the remote agents run without hooks.const res = await this.remoteHooks.setup(projectId, conn, controlPath, this.r.getHook())@@ -876,7 +956,7 @@ export class SshProjectManager {entry.codexRelayScriptPath = codexRuntime?.relayentry.codexRelayRuntimePath = codexRuntime?.runtimeentry.codexCliPath = codexRuntime?.codex- this.r.onStatus({ projectId, status: 'connected' })+ this.emitStatus({ projectId, status: 'connected' })// The tunnel is live again on a master we just established (the reuse branch returned long// before this line), so this is exactly the moment the hook events lost while it was down// can be reconstructed from the host.@@ -982,7 +1062,7 @@ export class SshProjectManager {: detail? `Could not establish the SSH connection: ${detail}${agentOnlyHint}`: `Could not establish the SSH connection.${agentOnlyHint}`- this.r.onStatus({ projectId, status: 'error', error: message })+ this.emitStatus({ projectId, status: 'error', error: message })throw new Error(message)}@@ -1330,6 +1410,12 @@ export class SshProjectManager {return c ? { conn: c.conn, controlPath: c.controlPath, remoteCwd: c.remoteCwd } : undefined}+ /** 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 {+ return this.conns.has(projectId) || this.inFlight.has(projectId)+ }+/*** Resolve the `{ conn, controlPath }` ref for the connected project whose remote repo cwd matches* `cwd` (Phase 4). Backs the git-remote resolver registry so remote git ops route to the right@@ -1391,6 +1477,28 @@ export class SshProjectManager {return undefined}+ /**+ * Is this asking master a silent PRE-WARM's?+ *+ * The pre-warm dials projects the user is not looking at, so it must not raise the passphrase+ * dialog either — that is the loudest thing an SSH connect can do, and a modal for a project+ * nobody opened is worse than the slow first switch the pre-warm exists to remove. The caller+ * (main's prompt handler) declines instead: that master fails auth, the pre-warm swallows it,+ * and the user's own connect — which spawns a NEW master with a new pid — prompts normally.+ *+ * Asking by PID, not by project, because that is what the askpass helper reports (its `$PPID`,+ * verified against a real sshd) and it is exact: a master that is not in the map, or whose+ * project has since gone loud, answers false and prompts.+ */+ isQuietMasterPid(pid: string): boolean {+ if (!pid) return false+ for (const [projectId, c] of this.conns) {+ const p = c.master.pid?.()+ if (p !== undefined && String(p) === pid) return this.quiet.has(projectId)+ }+ return false+ }+/** The resolved remote `$HOME` for a connected project, if known. */remoteHomeFor(projectId: string): string | undefined {return this.conns.get(projectId)?.remoteHome@@ -2119,7 +2227,7 @@ export class SshProjectManager {const supported = supportsAutoPermissionMode(version)entry.claudeAutoPermissionMode = supportedentry.remoteClaudeVersion = version- this.r.onStatus({+ this.emitStatus({projectId,status: 'connected',claudeAutoPermissionMode: supported,@@ -2182,7 +2290,7 @@ export class SshProjectManager {// caller's opt-out: a teardown INSIDE a live attempt must not discard that attempt's own// coalescing entry (see connectOnce's endpoint-change branch).if (!opts?.keepInFlight) this.inFlight.delete(projectId)- this.r.onStatus({ projectId, status: 'disconnected' })+ this.emitStatus({ projectId, status: 'disconnected' })// Nothing left to keep an unlocked key alive for. Production schedules (not performs) the// agent shutdown: the connect dialog's throwaway browse master disconnects a few hundred ms// before the real project connects, and forgetting in that gap costs a second prompt.@@ -2213,7 +2321,7 @@ export class SshProjectManager {this.r.runSync?.(exitMasterArgs(c.conn, c.controlPath))c.master.kill()this.conns.delete(projectId)- this.r.onStatus({ projectId, status: 'disconnected' })+ this.emitStatus({ projectId, status: 'disconnected' })}// Drop every in-flight connect attempt (see disconnect: a stale attempt must not coalesce a// later connect onto a master that was just killed for a now-orphaned attempt).@@ -2485,7 +2593,12 @@ export function initSshProject(// Registered after `mgr` exists so the dialog can name the server: the askpass request carries// the asking master's pid, and only the manager can map it back to a connection.askpassServer.setPromptHandler((req) =>- promptForPassphrase({ ...req, target: mgr.targetForMasterPid(req.caller) })+ // A silent pre-warm never prompts: declining is what keeps a background dial from putting a+ // passphrase modal in front of a user who opened nothing. `null` is the same answer a decline+ // gives, so ssh abandons that key and the pre-warm's master simply fails, quietly.+ mgr.isQuietMasterPid(req.caller)+ ? Promise.resolve(null)+ : promptForPassphrase({ ...req, target: mgr.targetForMasterPid(req.caller) }))mgr.startWatchdog()ipcMain.handle(IPC.sshConnectProject, async (_e, projectId: string, conn: SshConnection, remoteCwd?: string) => {diff --git a/src/preload/index.ts b/src/preload/index.tsindex 3b36b47e1..a91d77d3e 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -90,6 +90,8 @@ const api: NodeTerminalApi = {generateGroupName: (memberKeys, cwd) =>ipcRenderer.invoke(IPC.ptyGenerateGroupName, memberKeys, cwd),capture: (persistKey, full) => ipcRenderer.invoke(IPC.ptyCapture, persistKey, full),+ remoteSessionConfirmed: (persistKey, sshRemote) =>+ ipcRenderer.invoke(IPC.ptyRemoteSessionConfirmed, persistKey, sshRemote),readScrollback: (persistKey) => ipcRenderer.invoke(IPC.ptyReadScrollback, persistKey),sendText: (persistKey, text, opts) =>ipcRenderer.invoke(IPC.ptySendText, persistKey, text, opts?.enter),diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 48135555d..9836fcea5 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -242,6 +242,11 @@ export function buildRealApi(generateGroupName: () => Promise.resolve(AI_NAMING_UNAVAILABLE),capture: (persistKey, full) =>client.request(IPC.ptyCapture, persistKey, full).catch(() => '') as Promise<string>,+ // Documented degrade, not a stub with a hole in it: SSH PROJECTS are desktop-only (the whole+ // `sshProject` surface is `U(...)`-stubbed here), so no browser session ever holds a remote+ // ControlMaster to attach early over. `false` = "never attach early" = the pre-feature wait,+ // which is exactly right for a shell that cannot produce the question.+ remoteSessionConfirmed: () => Promise.resolve(false),readScrollback: (persistKey) =>client.request(IPC.ptyReadScrollback, persistKey) as Promise<string>,sendText: (persistKey, text, opts) =>diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 1e3aab77f..29ff89e9c 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -13042,6 +13042,14 @@ export function Canvas() {// Feed the auto-reconnect coordinator: ANY successful connect (its own loop, the// active-project effect on a tab switch) respawns that project's dropped terminals.if (e.status === 'connected') sshReconnectorRef.current?.onConnected(e.projectId)+ // The ControlMaster answered `-O check`, published BEFORE the connect's remote setup chain+ // (see SshProjectStatusEvent.masterControlPath). A terminal whose remote tmux session already+ // exists may attach over it right away instead of waiting out the chain; a cold one still+ // waits for `connected`, which is what carries the creation-time tmux `-f`/`-e` facts. Kept+ // OUT of `byProject` on purpose — that map means "connected" to a dozen other readers.+ if (e.masterControlPath) {+ useSshConn.getState().setEarlyControlPath(e.projectId, e.masterControlPath)+ }// The remote claude probe runs AFTER connect (its login shell is slow) and pushes its answer// on a later `connected` event — record it so this project's next Claude launch can use// `--permission-mode auto`. Absent = nothing new to record (keep omitting the flag).@@ -13057,6 +13065,13 @@ export function Canvas() {if (e.status === 'disconnected' || e.status === 'reconnecting') {useSshConn.getState().invalidateAutoPermissionMode(e.projectId)}+ // The master is gone (or never came up): the early path must not outlive it, or the next+ // node to mount would attach over a socket nothing is listening on. `error` is included —+ // the early signal fires before the setup chain, which is exactly where a connect can still+ // fail. The full `byProject` entry is left alone; only `connect`'s own result writes that.+ if (e.status === 'disconnected' || e.status === 'reconnecting' || e.status === 'error') {+ useSshConn.getState().clearEarlyControlPath(e.projectId)+ }})}, [])diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsxindex b263424f5..5ffc557c9 100644--- a/src/renderer/components/kanban/ModalTerminal.tsx+++ b/src/renderer/components/kanban/ModalTerminal.tsx@@ -277,7 +277,7 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: Moda// 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)+ ? await resolveSshRemote(spawn.ssh, spawn.cwd, { nodeId, pty: api.pty }): undefinedif (dead) return// The host is unreachable: spawn NOTHING. A create with no `sshRemote` falls through todiff --git a/src/renderer/lib/sshRemoteWait.test.ts b/src/renderer/lib/sshRemoteWait.test.tsnew file mode 100644index 000000000..d733eb9f0--- /dev/null+++ b/src/renderer/lib/sshRemoteWait.test.ts@@ -0,0 +1,193 @@+import { describe, it, expect, vi } from 'vitest'+import { waitForSshRemote, type SshRemoteFacts, type SshRemoteWaitDeps } from './sshRemoteWait'++const FULL: SshRemoteFacts = {+ controlPath: '/cm/p1',+ hookEndpointPath: '/home/u/.nodeterm/hook-endpoint.env',+ tmuxConfPath: '/home/u/.nodeterm/tmux.conf',+ remoteHome: '/home/u'+}++/** A tiny stand-in for the sshConn store: two slots plus a subscriber list. */+function store() {+ let full: SshRemoteFacts | undefined+ let early: string | undefined+ const subs = new Set<() => void>()+ const notify = (): void => {+ for (const cb of [...subs]) cb()+ }+ return {+ setFull(v: SshRemoteFacts | undefined) {+ full = v+ notify()+ },+ setEarly(v: string | undefined) {+ early = v+ notify()+ },+ deps(over: Partial<SshRemoteWaitDeps> = {}): SshRemoteWaitDeps {+ return {+ getFull: () => full,+ getEarly: () => early,+ subscribe: (cb) => {+ subs.add(cb)+ return () => subs.delete(cb)+ },+ confirmSession: async () => false,+ waitMs: 20_000,+ ...over+ }+ },+ subscriberCount: () => subs.size+ }+}++describe('waitForSshRemote', () => {+ it('returns the full facts immediately when the connect already landed', async () => {+ const s = store()+ s.setFull(FULL)+ await expect(waitForSshRemote(s.deps())).resolves.toEqual({ kind: 'full', facts: FULL })+ })++ it('WARM node attaches on the early master, without waiting for the setup chain', async () => {+ const s = store()+ const confirmSession = vi.fn(async () => true)+ const p = waitForSshRemote(s.deps({ confirmSession }))+ s.setEarly('/cm/p1')+ await expect(p).resolves.toEqual({ kind: 'early', controlPath: '/cm/p1' })+ expect(confirmSession).toHaveBeenCalledWith('/cm/p1')+ })++ it('COLD node keeps waiting for `connected` — the tmux -f/-e facts are creation-time only', async () => {+ vi.useFakeTimers()+ try {+ const s = store()+ // The host answered and said this session does NOT exist.+ const p = waitForSshRemote(s.deps({ confirmSession: async () => false }))+ const seen = vi.fn()+ void p.then(seen)+ s.setEarly('/cm/p1')+ await vi.advanceTimersByTimeAsync(5_000)+ expect(seen).not.toHaveBeenCalled() // still waiting, not attached early+ s.setFull(FULL)+ await expect(p).resolves.toEqual({ kind: 'full', facts: FULL })+ } finally {+ vi.useRealTimers()+ }+ })++ it('an UNREADABLE host is not a licence to attach early (rejection ⇒ keep waiting)', async () => {+ vi.useFakeTimers()+ try {+ const s = store()+ const p = waitForSshRemote(s.deps({ confirmSession: () => Promise.reject(new Error('ssh 255')) }))+ const seen = vi.fn()+ void p.then(seen)+ s.setEarly('/cm/p1')+ await vi.advanceTimersByTimeAsync(1_000)+ expect(seen).not.toHaveBeenCalled()+ s.setFull(FULL)+ await expect(p).resolves.toEqual({ kind: 'full', facts: FULL })+ } finally {+ vi.useRealTimers()+ }+ })++ it('never attaches early without a node id to ask about (confirmSession null)', async () => {+ vi.useFakeTimers()+ try {+ const s = store()+ const p = waitForSshRemote(s.deps({ confirmSession: null }))+ const seen = vi.fn()+ void p.then(seen)+ s.setEarly('/cm/p1')+ await vi.advanceTimersByTimeAsync(1_000)+ expect(seen).not.toHaveBeenCalled()+ s.setFull(FULL)+ await expect(p).resolves.toEqual({ kind: 'full', facts: FULL })+ } finally {+ vi.useRealTimers()+ }+ })++ it('the FULL facts win a race with an in-flight early confirmation', async () => {+ const s = store()+ let release!: (v: boolean) => void+ const p = waitForSshRemote(+ s.deps({ confirmSession: () => new Promise<boolean>((r) => (release = r)) })+ )+ s.setEarly('/cm/p1')+ s.setFull(FULL) // lands while the confirm is still on the wire+ release(true)+ // The setup facts are strictly better than a bare control path — a cold node needs them.+ await expect(p).resolves.toEqual({ kind: 'full', facts: FULL })+ })++ it('does not attach early over a master that went away mid-confirmation', async () => {+ vi.useFakeTimers()+ try {+ const s = store()+ let release!: (v: boolean) => void+ const p = waitForSshRemote(+ s.deps({ confirmSession: () => new Promise<boolean>((r) => (release = r)) })+ )+ const seen = vi.fn()+ void p.then(seen)+ s.setEarly('/cm/p1')+ s.setEarly(undefined) // disconnected / error cleared it+ release(true)+ await vi.advanceTimersByTimeAsync(1_000)+ expect(seen).not.toHaveBeenCalled()+ } finally {+ vi.useRealTimers()+ }+ })++ it('confirms each early path ONCE — an unrelated store write is not another round trip', async () => {+ const s = store()+ let release!: (v: boolean) => void+ const confirmSession = vi.fn(() => new Promise<boolean>((r) => (release = r)))+ const p = waitForSshRemote(s.deps({ confirmSession }))+ s.setEarly('/cm/p1')+ s.setEarly('/cm/p1') // same path published again (a duplicate status event)+ s.setFull(undefined) // an unrelated write+ expect(confirmSession).toHaveBeenCalledTimes(1)+ release(true)+ await expect(p).resolves.toEqual({ kind: 'early', controlPath: '/cm/p1' })+ })++ it('gives up with `none` after the window, and unsubscribes', async () => {+ vi.useFakeTimers()+ try {+ const s = store()+ const p = waitForSshRemote(s.deps({ waitMs: 20_000 }))+ expect(s.subscriberCount()).toBe(1)+ await vi.advanceTimersByTimeAsync(20_000)+ await expect(p).resolves.toEqual({ kind: 'none' })+ expect(s.subscriberCount()).toBe(0)+ } finally {+ vi.useRealTimers()+ }+ })++ it('prefers a full entry that landed exactly at the deadline over giving up', async () => {+ vi.useFakeTimers()+ try {+ const s = store()+ const deps = s.deps({ waitMs: 20_000 })+ let landed = false+ const p = waitForSshRemote({+ ...deps,+ // No subscription fires for this one (a store that never notifies) — the timeout path+ // must still re-read rather than report `none` over a live connection.+ subscribe: () => () => {},+ getFull: () => (landed ? FULL : undefined)+ })+ landed = true+ await vi.advanceTimersByTimeAsync(20_000)+ await expect(p).resolves.toEqual({ kind: 'full', facts: FULL })+ } finally {+ vi.useRealTimers()+ }+ })+})diff --git a/src/renderer/lib/sshRemoteWait.ts b/src/renderer/lib/sshRemoteWait.tsnew file mode 100644index 000000000..06443bfd0--- /dev/null+++ b/src/renderer/lib/sshRemoteWait.ts@@ -0,0 +1,116 @@+/**+ * What a remote terminal waits for before it may spawn, and when it is allowed to stop waiting+ * early.+ *+ * WHY THIS EXISTS (measured, 2026-09-15, against a real sshd with a 25 ms one-way delay proxy =+ * 50 ms RTT). `SshProjectManager.connectOnce` used to publish a project's ControlMaster only with+ * `status: 'connected'` — i.e. after the reverse hook tunnel, ~23 serialized per-agent hook+ * installs, `printf $HOME`, the remote tmux.conf write + source-file and the Codex runtime staging+ * had all run. That chain is ~3.5 s. The attach itself is not the bottleneck at all: 18 remote+ * terminals attaching in parallel over a WARM master painted in a median of 0.16 s, everything+ * settled by 0.71 s. So every terminal of a switched-to project sat in the 20 s wait below,+ * printing "[connecting to user@host…]" into a blank pane, for a transport that was ready.+ *+ * The manager now publishes the control path the moment `ssh -O check` answers+ * (`SshProjectStatusEvent.masterControlPath`). This module decides who may act on that.+ *+ * THE RULE, and it is the load-bearing part: an early attach is safe ONLY for a node whose remote+ * tmux session ALREADY EXISTS. `tmux new-session -A` then merely attaches, and the two things the+ * setup chain provides — the remote tmux config (`-f`) and the hook/account environment (tmux+ * `-e`) — are read at session CREATION only, so a warm attach needs neither. A node whose session+ * is ABSENT, or whose host could not be read, must wait for the full `connected`: creating its+ * session without the hook env costs it agent-status badges silently, with no later event to+ * repair it. `confirmSession` is therefore the STRICT probe (`present` only — see+ * `PtyApi.remoteSessionConfirmed`), never the fail-safe `exists` boolean.+ */++/** The connection facts a spawn needs. The optional three are what the setup chain produces. */+export interface SshRemoteFacts {+ controlPath: string+ hookEndpointPath?: string+ tmuxConfPath?: string+ remoteHome?: string+}++export type SshRemoteWaitOutcome =+ /** The full connect landed: every setup fact is available, cold start included. */+ | { kind: 'full'; facts: SshRemoteFacts }+ /** The master answered and this node's session was confirmed present: attach now, no setup facts. */+ | { kind: 'early'; controlPath: string }+ /** No master within the window. The caller must spawn NOTHING (see `requireRemote`). */+ | { kind: 'none' }++export interface SshRemoteWaitDeps {+ /** The scope's full connection info, once `connect` resolved. */+ getFull: () => SshRemoteFacts | undefined+ /** The scope's early control path, once `-O check` answered. */+ getEarly: () => string | undefined+ /** Subscribe to changes of either of the two above; returns an unsubscribe. */+ subscribe: (cb: () => void) => () => void+ /**+ * Was this node's remote tmux session POSITIVELY listed on the host behind `controlPath`?+ * `null` = this caller may never attach early (no node id to ask about). A rejection is treated+ * as "not confirmed" — the node keeps waiting, which is the pre-feature behavior.+ */+ confirmSession: ((controlPath: string) => Promise<boolean>) | null+ /** How long to wait in total before giving up. */+ waitMs: number+}++/**+ * Resolve the connection a remote terminal should spawn over, or `none` if nothing appears in time.+ *+ * Ordering rules a refactor must not undo:+ * - The FULL info always wins, even if it lands while an early confirmation is still on the wire.+ * It is strictly better (it carries the setup facts) and a cold node depends on it.+ * - A failed or negative confirmation does NOT end the wait; it falls back to waiting for full.+ * - Each early control path is confirmed at most once. Without that, every unrelated store write+ * during the wait would fire another `tmux list-sessions` round trip at the host.+ */+export async function waitForSshRemote(deps: SshRemoteWaitDeps): Promise<SshRemoteWaitOutcome> {+ const full = deps.getFull()+ if (full) return { kind: 'full', facts: full }++ return new Promise<SshRemoteWaitOutcome>((resolve) => {+ let settled = false+ let confirming: string | undefined+ const finish = (outcome: SshRemoteWaitOutcome): void => {+ if (settled) return+ settled = true+ clearTimeout(timer)+ unsub()+ resolve(outcome)+ }+ const check = (): void => {+ if (settled) return+ const now = deps.getFull()+ if (now) {+ finish({ kind: 'full', facts: now })+ return+ }+ const early = deps.getEarly()+ if (!early || !deps.confirmSession || confirming === early) return+ confirming = early+ void deps.confirmSession(early).then(+ (confirmed) => {+ if (settled) return+ // Re-read both: the full info may have landed while this probe was on the wire, and the+ // early path may have been dropped (the master went away).+ const landed = deps.getFull()+ if (landed) finish({ kind: 'full', facts: landed })+ else if (confirmed && deps.getEarly() === early) finish({ kind: 'early', controlPath: early })+ },+ () => {+ // Unreadable host: not evidence the session is absent, but not a licence to attach+ // early either. Keep waiting for the full connect.+ }+ )+ }+ const unsub = deps.subscribe(check)+ const timer = setTimeout(() => {+ const last = deps.getFull()+ finish(last ? { kind: 'full', facts: last } : { kind: 'none' })+ }, deps.waitMs)+ check()+ })+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex d087e910a..74ddc7439 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -35,7 +35,7 @@ import {import { fileLinkDialect } from '../terminal/file-link-dialect'import { hostPlatformFor } from '../terminal/host-platform'import { sshFs } from '../terminal/ssh-fs'-import type { FsApi, PendingLaunch } from '@shared/types'+import type { FsApi, PendingLaunch, PtyApi } from '@shared/types'import {attachReplay,closedByLabel,@@ -220,6 +220,7 @@ import { nodeIconDialog } from '../components/NodeIconPicker'import { applyIconChoice } from '../lib/nodeIconChoice'import type { NodeIcon } from '@shared/node-icon'import { connectHostAttachment } from '../lib/sshAttachments'+import { waitForSshRemote } from '../lib/sshRemoteWait'/** Which physical modifier the registry's abstract `Cmd` resolves to for the find-bar chord. */const isMac = isMacPlatform()@@ -309,7 +310,19 @@ export function currentControlPath(conn?: SshConnection): string | undefined {*/export async function resolveSshRemote(conn: SshConnection,- cwd: string | undefined+ cwd: string | undefined,+ /**+ * Opt in to the EARLY attach path: spawn as soon as the ControlMaster answers `-O check`,+ * without waiting for the connect's remote setup chain — but ONLY once the host has positively+ * listed this node's remote tmux session (see `waitForSshRemote`). Absent ⇒ the pre-feature+ * behavior, wait for the full `connected`.+ *+ * `pty` is the CALLER'S SESSION-BOUND api, not the global: the confirmation has to be answered+ * by the same core that will run `create` a moment later, or the two would consult different+ * hosts — and the coalesced `tmux list-sessions` this shares with `create` would be two reads+ * instead of one.+ */+ early?: { nodeId: string; pty: Pick<PtyApi, 'remoteSessionConfirmed'> }): Promise<| {controlPath: string@@ -342,41 +355,29 @@ export async function resolveSshRemote((scopeId) => window.nodeTerminal.sshProject.disconnect(scopeId))}- let controlPath = useSshConn.getState().getControlPath(projectId)- if (!controlPath) {- controlPath = await new Promise<string | undefined>((resolve) => {- let settled = false- const finish = (v?: string) => {- if (settled) return- settled = true- clearTimeout(timer)- unsub()- resolve(v)- }- const unsub = useSshConn.subscribe((s) => {- const v = s.byProject[projectId]?.controlPath- if (v) finish(v)- })- const timer = setTimeout(- () => finish(useSshConn.getState().getControlPath(projectId)),- SSH_REMOTE_WAIT_MS- )- })+ // The three optional facts below (remote hook endpoint, remote tmux.conf path, remote $HOME) are+ // produced by the connect's SETUP chain and are read at session CREATION only — the tmux `-e`+ // hook/account env and the `-f` config. That is exactly why a node whose session already exists+ // may attach over the master before any of them exist; see `waitForSshRemote` for the full rule.+ const outcome = await waitForSshRemote({+ getFull: () => useSshConn.getState().byProject[projectId],+ getEarly: () => useSshConn.getState().getEarlyControlPath(projectId),+ subscribe: (cb) => useSshConn.subscribe(cb),+ confirmSession: early+ ? (controlPath) => early.pty.remoteSessionConfirmed(early.nodeId, { controlPath, conn })+ : null,+ waitMs: SSH_REMOTE_WAIT_MS+ })+ if (outcome.kind === 'none') return undefined+ const remoteCwd = cwd || '~'+ if (outcome.kind === 'early') {+ // Warm attach over a master whose setup chain is still running. No setup facts by+ // construction: `new-session -A` on a live session only attaches, so there is nothing for a+ // `-f` or an `-e` to apply to, and passing a half-built value would be a lie about what the+ // session carries.+ return { controlPath: outcome.controlPath, conn, remoteCwd }}- if (!controlPath) return undefined- // The remote hook endpoint (reverse tunnel + remote install) is set up alongside the master;- // pass it through so the remote tmux session carries the hook env. Optional (fail-open).- const hookEndpointPath = useSshConn.getState().getHookEndpointPath(projectId)- // The remote tmux config (mouse off, so a drag is the emulator's own selection; set-clipboard on- // so an app that emits OSC 52 itself still reaches the local clipboard; history-limit) is written- // + sourced alongside the master; pass its path so a fresh remote session launches with `-f`.- // Optional.- const tmuxConfPath = useSshConn.getState().getTmuxConfPath(projectId)- // The connection's resolved remote $HOME, used to build an ABSOLUTE remote CLAUDE_CONFIG_DIR for a- // managed remote account (Task 12). Optional (fail-open): absent → the remote account env is- // skipped and the session runs under the remote system default `~/.claude`.- const remoteHome = useSshConn.getState().getRemoteHome(projectId)- return { controlPath, conn, remoteCwd: cwd || '~', hookEndpointPath, tmuxConfPath, remoteHome }+ return { ...outcome.facts, conn, remoteCwd }}/**@@ -2975,7 +2976,7 @@ export function TerminalNode({}const sshRemote =sshRemoteTmux && ssh- ? await resolveSshRemote(ssh, data.cwd as string | undefined)+ ? await resolveSshRemote(ssh, data.cwd as string | undefined, { nodeId: id, pty: api.pty }): undefinedif (disposed) return// The host is unreachable (no master within the window). SPAWN NOTHING: a create with nodiff --git a/src/renderer/state/sshConn.test.ts b/src/renderer/state/sshConn.test.tsindex ce2d71d69..a7d0afd94 100644--- a/src/renderer/state/sshConn.test.ts+++ b/src/renderer/state/sshConn.test.ts@@ -4,6 +4,7 @@ import { useSshConn } from './sshConn'beforeEach(() => {useSshConn.setState({byProject: {},+ earlyByProject: {},attachments: {},autoPermByProject: {},remoteClaudeVersionByProject: {}@@ -220,3 +221,54 @@ describe('useSshConn — remote Codex runtime (getCodexRuntime)', () => {})})})++// The early (pre-setup) ControlMaster path lives in its OWN map. `byProject[id]` is read all over+// the app as "this project is connected"; an early entry there would make the usage pill, the RAM+// pill, Source Control and the accounts picker all claim a connection whose remote setup has not+// run. Its ONE consumer is resolveSshRemote's early-attach path.+describe('useSshConn — early ControlMaster path', () => {+ it('is kept out of byProject, so nothing else reads it as "connected"', () => {+ useSshConn.getState().setEarlyControlPath('p1', '/cm/p1')+ expect(useSshConn.getState().getEarlyControlPath('p1')).toBe('/cm/p1')+ expect(useSshConn.getState().byProject.p1).toBeUndefined()+ expect(useSshConn.getState().getControlPath('p1')).toBeUndefined()+ })++ it('is superseded (and dropped) by the full connection info', () => {+ useSshConn.getState().setEarlyControlPath('p1', '/cm/p1')+ useSshConn.getState().setConn('p1', { controlPath: '/cm/p1', remoteHome: '/home/u' })+ expect(useSshConn.getState().getEarlyControlPath('p1')).toBeUndefined()+ expect(useSshConn.getState().getControlPath('p1')).toBe('/cm/p1')+ })++ it('cannot walk a full entry back to an early one', () => {+ useSshConn.getState().setConn('p1', { controlPath: '/cm/p1', remoteHome: '/home/u' })+ useSshConn.getState().setEarlyControlPath('p1', '/cm/p1')+ expect(useSshConn.getState().getEarlyControlPath('p1')).toBeUndefined()+ })++ it('is cleared when the master goes away, without touching the rest of the entry', () => {+ useSshConn.getState().setEarlyControlPath('p1', '/cm/p1')+ useSshConn.getState().clearEarlyControlPath('p1')+ expect(useSshConn.getState().getEarlyControlPath('p1')).toBeUndefined()+ // Idempotent, and a no-op write keeps the SAME map object (no needless re-render).+ const before = useSshConn.getState().earlyByProject+ useSshConn.getState().clearEarlyControlPath('p1')+ expect(useSshConn.getState().earlyByProject).toBe(before)+ })++ it('goes with the scope on clear() and clearAttachment()', () => {+ useSshConn.getState().setEarlyControlPath('p1', '/cm/p1')+ useSshConn.getState().clear('p1')+ expect(useSshConn.getState().getEarlyControlPath('p1')).toBeUndefined()++ useSshConn.getState().registerAttachment('a1', {+ conn: { host: 'h', user: 'u' },+ hostKey: 'u@h',+ ownerProjectId: 'p9'+ })+ useSshConn.getState().setEarlyControlPath('a1', '/cm/a1')+ useSshConn.getState().clearAttachment('a1')+ expect(useSshConn.getState().getEarlyControlPath('a1')).toBeUndefined()+ })+})diff --git a/src/renderer/state/sshConn.ts b/src/renderer/state/sshConn.tsindex 4956aa825..5214c138e 100644--- a/src/renderer/state/sshConn.ts+++ b/src/renderer/state/sshConn.ts@@ -77,6 +77,18 @@ export type SshAutoPermAnswer = 'yes' | 'no' | 'unknown'*/interface SshConnState {byProject: Record<string, SshConnInfo>+ /**+ * Connection scope → the ControlMaster path published the moment `ssh -O check` answered, i.e.+ * BEFORE the connect's remote setup chain finished (`SshProjectStatusEvent.masterControlPath`).+ *+ * Kept in its OWN map, deliberately: `byProject[id]` is read all over the app as "this project is+ * connected" (the usage pill, the RAM pill, Source Control, the accounts picker), and an early+ * entry there would make every one of them claim a connection whose remote setup has not run.+ * The ONE consumer is `resolveSshRemote`'s early-attach path, which additionally requires the+ * node's remote tmux session to be confirmed present. Dropped the instant the full info lands+ * (it supersedes this) and on any status that means the master is gone.+ */+ earlyByProject: Record<string, string>/** Attachment scope id → how to reach it and whose canvas it serves. Written BEFORE the dial* (see `registerAttachment`), so it outlives a failed connect. */attachments: Record<string, SshAttachment>@@ -88,6 +100,13 @@ interface SshConnState {* beside `autoPermByProject` (same lifecycle) so the tab-menu hint can name the version. */remoteClaudeVersionByProject: Record<string, string | null>setConn(projectId: string, info: SshConnInfo): void+ /** Record the early (pre-setup) ControlMaster path for a scope. Ignored once the full info for+ * that scope has landed — the full entry is strictly better and must not be walked back. */+ setEarlyControlPath(projectId: string, controlPath: string): void+ /** The early ControlMaster path for a scope, if one was published and not yet superseded. */+ getEarlyControlPath(projectId: string): string | undefined+ /** Forget a scope's early path (the master is gone: disconnected / reconnecting / error). */+ clearEarlyControlPath(projectId: string): void/** Record the remote CLI probe's answer (pushed on a `connected` status event once it lands).* `version` rides the same event; undefined leaves the cached version untouched. */setClaudeAutoPermissionMode(projectId: string, supported: boolean, version?: string | null): void@@ -136,14 +155,27 @@ interface SshConnState {attachmentScopesOf(ownerProjectId: string): string[]}+/** Return `map` without `key` — a fresh object, or the SAME one when the key was never there (so a+ * no-op write cannot re-render every subscriber). */+function dropKey<T>(map: Record<string, T>, key: string): Record<string, T> {+ if (!(key in map)) return map+ const next = { ...map }+ delete next[key]+ return next+}+export const useSshConn = create<SshConnState>((set, get) => ({byProject: {},+ earlyByProject: {},attachments: {},autoPermByProject: {},remoteClaudeVersionByProject: {},setConn(projectId, info) {set((s) => ({byProject: { ...s.byProject, [projectId]: info },+ // The full info supersedes the early path — keeping both would leave a stale socket string+ // behind for the rest of the app run.+ earlyByProject: dropKey(s.earlyByProject, projectId),// A reused (already probed) connection returns the answer with the connect result.autoPermByProject:info.claudeAutoPermissionMode === undefined@@ -164,6 +196,21 @@ export const useSshConn = create<SshConnState>((set, get) => ({: { ...s.remoteClaudeVersionByProject, [projectId]: version }}))},+ setEarlyControlPath(projectId, controlPath) {+ set((s) =>+ s.byProject[projectId] || s.earlyByProject[projectId] === controlPath+ ? s+ : { earlyByProject: { ...s.earlyByProject, [projectId]: controlPath } }+ )+ },+ getEarlyControlPath(projectId) {+ return get().earlyByProject[projectId]+ },+ clearEarlyControlPath(projectId) {+ set((s) =>+ projectId in s.earlyByProject ? { earlyByProject: dropKey(s.earlyByProject, projectId) } : s+ )+ },getControlPath(projectId) {return get().byProject[projectId]?.controlPath},@@ -199,7 +246,7 @@ export const useSshConn = create<SshConnState>((set, get) => ({delete next[scopeId]const conns = { ...s.byProject }delete conns[scopeId]- return { attachments: next, byProject: conns }+ return { attachments: next, byProject: conns, earlyByProject: dropKey(s.earlyByProject, scopeId) }})},supportsAutoPermissionMode(projectId) {@@ -232,7 +279,12 @@ export const useSshConn = create<SshConnState>((set, get) => ({delete nextAuto[projectId]const nextVersion = { ...s.remoteClaudeVersionByProject }delete nextVersion[projectId]- return { byProject: next, autoPermByProject: nextAuto, remoteClaudeVersionByProject: nextVersion }+ return {+ byProject: next,+ earlyByProject: dropKey(s.earlyByProject, projectId),+ autoPermByProject: nextAuto,+ remoteClaudeVersionByProject: nextVersion+ }})},attachmentScopesOf(ownerProjectId) {diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 095c6d983..ed2428e51 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -17,6 +17,12 @@ export const IPC = {ptyGenerateName: 'pty:generate-name',ptyGenerateGroupName: 'pty:generate-group-name',ptyCapture: 'pty:capture',+ /** Renderer → core: has the host behind this ControlMaster POSITIVELY listed the node's remote+ * tmux session? The strict half of the coalesced `tmux list-sessions` read behind+ * `PtyManager.remoteSessionConfirmed` — an unreadable host answers false, not "assume warm".+ * Gates the early-attach path (attach as soon as the master answers `-O check`, before the+ * connect's remote setup chain finishes); desktop-only, like SSH projects themselves. */+ ptyRemoteSessionConfirmed: 'pty:remote-session-confirmed',ptyReadScrollback: 'pty:read-scrollback',ptySendText: 'pty:send-text',ptyTmuxStatus: 'pty:tmux-status',diff --git a/src/shared/types.ts b/src/shared/types.tsindex 6bd5e665e..45de04503 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -941,6 +941,22 @@ export interface PtyApi {generateGroupName(memberKeys: string[], cwd: string): Promise<GitResult>/** Capture a terminal session's output as text. `full` grabs the entire scrollback. */capture(persistKey: string, full?: boolean): Promise<string>+ /**+ * Has the host behind `sshRemote.controlPath` POSITIVELY listed this node's remote tmux session?+ *+ * The early-attach gate: a remote terminal may run over a ControlMaster whose connect-time setup+ * has not finished only when its session already exists (`new-session -A` then merely attaches,+ * and the remote tmux `-f` config and the `-e` hook/account env are read at session CREATION+ * only). Absent AND unreadable both answer `false` — the node then waits for the full connect,+ * because creating a session without that env silently costs it its agent-status badges.+ *+ * Desktop-only, like SSH projects; the Server Edition bridge answers `false` (never attach+ * early), which is the pre-feature behavior.+ */+ remoteSessionConfirmed(+ persistKey: string,+ sshRemote: { controlPath: string; conn: import('./ssh').SshConnection }+ ): Promise<boolean>/** Read the persisted scrollback snapshot for a node (for cold-restart replay). '' if none. */readScrollback(persistKey: string): Promise<string>/** Send literal text into a session, by default followed by Enter (e.g. a slash command).@@ -1922,6 +1938,25 @@ export interface SshProjectStatusEvent {projectId: stringstatus: SshProjectStatuserror?: string+ /**+ * The ControlMaster socket path, published the MOMENT `ssh -O check` answers — i.e. while the+ * status is still `connecting`, before the connect's remote setup chain (hook tunnel + per-agent+ * hook installs, `$HOME`, the remote tmux.conf write, the Codex runtime staging) has run.+ *+ * ADDITIVE, and deliberately not a new status value: `connected` keeps its exact meaning (the+ * whole chain finished), and everything hanging off it — git routing, the remote claude probe,+ * the tunnel resync, the connection banner — is untouched. This field only lets a terminal whose+ * remote tmux session ALREADY EXISTS stop waiting: `new-session -A` then merely attaches, and+ * the remote `-f` config and the tmux `-e` pairs are read at session CREATION only. A node whose+ * session does not exist (or could not be read) must still wait for `connected`, or it would+ * create a session with no hook env and lose its agent-status badges — see+ * `PtyApi.remoteSessionConfirmed`.+ *+ * Never emitted for an ADOPTED live-orphan master: that one can still be torn down and rebuilt+ * inside the same connect (the stale reverse-forward cure), which would kill a terminal that had+ * already attached over it.+ */+ masterControlPath?: stringclaudeAutoPermissionMode?: boolean/** The remote `claude --version` output the probe read, riding the same `connected` event as* `claudeAutoPermissionMode`. `null` = the probe ran but found no claude (distinguishable from