From 10718716533fd8af6b6d932604efce4796c3b2f1 Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Fri, 20 Nov 2026 10:29:23 +0100 Subject: [PATCH 1/5] perf(ssh): run each SSH environment's setup over one connection On a slow link every new ssh connection costs seconds of handshake round trips, and connecting an SSH environment opened one for the launch, one for the port forward, and one for pairing. Each tunnel now owns an OpenSSH control master with an app-owned socket under the desktop state directory. The launch, the forward (`-O forward`), pairing, and readiness diagnostics run over it, so a first connect opens one connection instead of three and a reconnect one instead of two. The master uses explicit options, so ssh config ControlMaster settings do not apply; each tunnel gets a fresh socket name, so a replacement for a slow tunnel never joins the master it may replace; closing the tunnel (including quitting the app) stops the master and removes its socket. Windows, a socket path over the macOS limit, and a master that cannot create its socket keep one connection per command, as before. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/main.ts | 1 + apps/desktop/src/ssh/DesktopSshEnvironment.ts | 12 +- docs/internals/remote.md | 8 + docs/user/remote-access.md | 5 + packages/ssh/src/command.ts | 15 +- packages/ssh/src/tunnel.test.ts | 161 +++++ packages/ssh/src/tunnel.ts | 550 ++++++++++++------ 7 files changed, 579 insertions(+), 173 deletions(-) diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index e3971d7c74ea5..d515c0bcfcf8b 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -124,6 +124,7 @@ const layerDesktopSshEnvironment = Layer.unwrap( const environment = yield* DesktopEnvironment.DesktopEnvironment; return DesktopSshEnvironment.layer({ resolveCliRunner: Effect.succeed(resolveDesktopSshCliRunner(environment)), + controlSocketDirectory: environment.path.join(environment.stateDir, "ssh-control"), }); }), ); diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.ts index 7b480b36fbd12..fb8b7bdad6c98 100644 --- a/apps/desktop/src/ssh/DesktopSshEnvironment.ts +++ b/apps/desktop/src/ssh/DesktopSshEnvironment.ts @@ -67,9 +67,7 @@ export class DesktopSshEnvironment extends Context.Service< } >()("@t3tools/desktop/ssh/DesktopSshEnvironment") {} -export interface DesktopSshEnvironmentLayerOptions { - readonly resolveCliRunner?: Effect.Effect; -} +export type DesktopSshEnvironmentLayerOptions = SshTunnel.SshEnvironmentManagerOptions; function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) { return discoverSshHosts(input ?? {}); @@ -161,11 +159,5 @@ export const make = Effect.gen(function* () { export const layer = (options: DesktopSshEnvironmentLayerOptions = {}) => Layer.effect(DesktopSshEnvironment, make).pipe( - Layer.provide( - SshTunnel.SshEnvironmentManager.layer( - options.resolveCliRunner === undefined - ? {} - : { resolveCliRunner: options.resolveCliRunner }, - ), - ), + Layer.provide(SshTunnel.SshEnvironmentManager.layer(options)), ); diff --git a/docs/internals/remote.md b/docs/internals/remote.md index 1c15c1c16e55b..b9bf013acdea8 100644 --- a/docs/internals/remote.md +++ b/docs/internals/remote.md @@ -176,6 +176,14 @@ runner never stops a server, since agent turns may be running there; an update stops it and the next connect starts the client's version. Reconnection restores the forward before opening the application transport. +Each new SSH connection costs several round trips, which is seconds on a slow +link, so each tunnel owns one control master and runs its launch, port forward, +and pairing over it. The master's socket gets a fresh name per tunnel, so a +replacement for a slow tunnel never joins the master it may be replacing. ssh +binds the socket at its path plus 17 characters, inside macOS's 104-byte limit, +so a path that cannot fit, Windows (whose OpenSSH has no multiplexing), and a +master that cannot create its socket all fall back to one connection per command. + Remote servers can outlive several client releases. Clients must use advertised capabilities and handle their absence, rather than assume their own version describes the server. Process replacement belongs to the launcher's diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index c9d56472503cd..3f715a3b3526a 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -237,6 +237,11 @@ neither answers, it keeps the first connection and tries again. When the old connection has clearly closed, for example after your computer sleeps, it is replaced right away. +T3 Code sets up the host and its port forward over a single SSH connection, so +a slow link pays for the SSH handshake once. It keeps its own shared connection +and does not use `ControlMaster` settings from your SSH config. On Windows each +step opens its own connection. + Each desktop app keeps one session on the host for its SSH connection and reuses it when it reconnects. Revoke sessions you no longer use in **Settings → Sharing & access** on the host, or on a headless host with `t3 auth session list` and diff --git a/packages/ssh/src/command.ts b/packages/ssh/src/command.ts index eafda87d4ff70..10ee9d4e25e58 100644 --- a/packages/ssh/src/command.ts +++ b/packages/ssh/src/command.ts @@ -34,7 +34,19 @@ export interface SshCommandResult { readonly stderr: string; } -export interface RunSshCommandOptions extends SshAuthOptions { +export interface SshConnectionOptions extends SshAuthOptions { + /** An app-owned control master to run over instead of opening a new connection. */ + readonly controlPath?: string | undefined; +} + +/** Joins a live control master; ssh connects on its own when the master is gone. */ +function controlClientSshArgs(controlPath: string | undefined): string[] { + return controlPath === undefined + ? [] + : ["-o", "ControlMaster=no", "-o", `ControlPath=${controlPath}`]; +} + +export interface RunSshCommandOptions extends SshConnectionOptions { readonly preHostArgs?: ReadonlyArray; readonly remoteCommandArgs?: ReadonlyArray; readonly stdin?: string; @@ -208,6 +220,7 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3", + ...controlClientSshArgs(input.controlPath), ...(input.preHostArgs ?? []), "--", hostSpec, diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index f948d77d28a7e..e0201de92038d 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -450,6 +450,167 @@ describe("ssh tunnel scripts", () => { }), ); + // Counts the ssh processes that open their own connection to the host. + const controlMasterHarness = Effect.fn("controlMasterHarness")(function* (input: { + readonly controlSocketDirectory: string | undefined; + readonly masterStderr?: string; + }) { + const spawned: Array> = []; + const masters: Array<{ controlPath: string; killed: boolean }> = []; + const spawner = ChildProcessSpawner.make((command) => + Effect.sync(() => { + const args = commandArgs(command); + spawned.push(args); + if (args.includes("ControlMaster=yes")) { + const controlPath = args.find((arg) => arg.startsWith("ControlPath="))!.slice(12); + if (input.masterStderr !== undefined) { + return { + ...makeSuccessfulProcess(""), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(255)), + stderr: Stream.make(new TextEncoder().encode(input.masterStderr)), + }; + } + const master = { controlPath, killed: false }; + masters.push(master); + NodeFS.writeFileSync(controlPath, ""); + return makeRunningProcess(() => { + master.killed = true; + }); + } + if (args.includes("-N")) return makeRunningProcess(() => {}); + if (args.at(-1) === "-s") return makeSuccessfulProcess('{"credential":"PAIRED"}\n'); + return makeSuccessfulProcess('{"remotePort":3773,"serverKind":"managed"}\n'); + }), + ); + const refused = new Set(); + const refusedProbes = yield* Queue.unbounded(); + let nextPort = 41_773; + const layer = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + refused.has(Number(new URL(request.url).port)) + ? Queue.offer(refusedProbes, undefined).pipe( + Effect.andThen( + Effect.fail( + new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ request }), + }), + ), + ), + ) + : Effect.succeed( + HttpClientResponse.fromWeb(request, new Response("", { status: 200 })), + ), + ), + ), + Layer.succeed( + NetService.NetService, + NetService.NetService.of({ + ...testNetService, + reserveLoopbackPort: () => Effect.sync(() => nextPort++), + hasListenerOnHost: (port) => Effect.sync(() => !refused.has(port)), + }), + ), + SshAuth.SshPasswordPrompt.disabledLayer, + SshTunnel.SshEnvironmentManager.layer({ + resolveCliRunner: Effect.succeed(ARCHIVE), + ...(input.controlSocketDirectory === undefined + ? {} + : { controlSocketDirectory: input.controlSocketDirectory }), + }), + ); + const connections = () => + spawned.filter( + (args) => + !args.includes("-G") && + (args.includes("ControlMaster=yes") || + !args.some((arg) => arg.startsWith("ControlPath=") && arg !== "ControlPath=none")), + ).length; + return { spawned, masters, refused, refusedProbes, layer, connections }; + }); + + it.effect.each([ + { mode: "plain connections", useControlMaster: false, connections: 3 }, + { mode: "one control master", useControlMaster: true, connections: 1 }, + ])("first connect opens $connections ssh connection(s) with $mode", (row) => + Effect.gen(function* () { + const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-ssh-cm-")); + try { + const harness = yield* controlMasterHarness({ + controlSocketDirectory: row.useControlMaster + ? NodePath.join(directory, "control") + : undefined, + }); + yield* Effect.gen(function* () { + const manager = yield* SshTunnel.SshEnvironmentManager; + const target = { alias: "devbox", hostname: "devbox", username: null, port: null }; + // Launch, tunnel forward, and pairing. + const result = yield* manager.ensureEnvironment(target, { issuePairingToken: true }); + assert.equal(result.pairingToken, "PAIRED"); + assert.equal(harness.connections(), row.connections); + if (!row.useControlMaster) return; + + const [master] = harness.masters; + assert.isDefined(master); + assert.isTrue(NodeFS.existsSync(master!.controlPath)); + assert.isTrue(harness.spawned.some((args) => args.includes("forward"))); + // A dead tunnel's replacement gets its own master. + harness.refused.add(41_773); + const replacing = yield* Effect.forkChild(manager.ensureEnvironment(target)); + yield* Queue.take(harness.refusedProbes); + yield* TestClock.adjust("10 seconds"); + yield* Fiber.join(replacing); + assert.equal(harness.connections(), 2); + assert.equal(harness.masters.length, 2); + assert.notEqual(harness.masters[1]!.controlPath, master!.controlPath); + assert.isTrue(master!.killed); + assert.isFalse(NodeFS.existsSync(master!.controlPath)); + }).pipe(Effect.provide(harness.layer), Effect.scoped); + // Quitting stops every master and removes its socket. + assert.isTrue(harness.masters.every((master) => master.killed)); + assert.deepEqual( + NodeFS.readdirSync(directory).flatMap((entry) => + NodeFS.readdirSync(NodePath.join(directory, entry)), + ), + [], + ); + } finally { + NodeFS.rmSync(directory, { recursive: true, force: true }); + } + }), + ); + + it.effect("falls back to plain connections when ssh cannot create the control socket", () => + Effect.gen(function* () { + const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-ssh-cm-")); + try { + const harness = yield* controlMasterHarness({ + controlSocketDirectory: directory, + masterStderr: `unix_listener: cannot bind to path ${directory}/x: Address already in use`, + }); + yield* Effect.gen(function* () { + const manager = yield* SshTunnel.SshEnvironmentManager; + const result = yield* manager.ensureEnvironment({ + alias: "devbox", + hostname: "devbox", + username: null, + port: null, + }); + assert.equal(result.httpBaseUrl, "http://127.0.0.1:41773/"); + assert.isTrue(harness.spawned.some((args) => args.includes("ControlMaster=yes"))); + const tunnel = harness.spawned.find((args) => args.includes("-L")); + assert.include(tunnel ?? [], "ControlPath=none"); + }).pipe(Effect.provide(harness.layer), Effect.scoped); + } finally { + NodeFS.rmSync(directory, { recursive: true, force: true }); + } + }), + ); + it("rejects archive versions that are not a single exact version segment", () => { for (const archiveVersion of [ "../other", diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index 1369551e14dd1..521a97befd46f 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -4,6 +4,7 @@ import type { } from "@t3tools/contracts"; import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness"; import { cliReleaseDownloadBaseUrl } from "@t3tools/shared/cliRelease"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import * as NetService from "@t3tools/shared/Net"; import { extractJsonObject, fromLenientJson } from "@t3tools/shared/schemaJson"; @@ -11,6 +12,7 @@ import { satisfiesSemverRange } from "@t3tools/shared/semver"; import * as Context from "effect/Context"; import * as Digest from "effect/crypto/Digest"; import * as Deferred from "effect/Deferred"; +import * as Hex from "effect/encoding/Hex"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -18,6 +20,7 @@ import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as Random from "effect/Random"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; @@ -29,6 +32,7 @@ import * as SshAuth from "./auth.ts"; import { baseSshArgs, buildSshHostSpecEffect, + type SshConnectionOptions, getLastNonEmptyOutputLine, remoteStateKey, resolveSshCommand, @@ -61,6 +65,11 @@ const REMOTE_LAUNCH_BASE_TIMEOUT_MS = 90_000; // Matches the node-script launch command's ssh run without the launch lock wait. const SSH_TUNNEL_CONNECT_TIMEOUT_MS = REMOTE_LAUNCH_BASE_TIMEOUT_MS; const SSH_TUNNEL_FORWARD_PROBE_INTERVAL_MS = 100; +// Control commands only talk to the local master. +const SSH_CONTROL_COMMAND_TIMEOUT_MS = 10_000; +// ssh binds the control socket at its path plus ".XXXXXXXXXXXXXXXX" before renaming it, +// and macOS allows 104 bytes for a socket path, including the terminating NUL. +const SSH_CONTROL_PATH_MAX_BYTES = 103 - 17; // Cold archive launches download ~70 MB, which can take an hour on a slow link. Downloads fail // only when they stall; the generous launch deadline only ends one stuck elsewhere, and ssh // keepalives end one whose connection dies. Another launch waits this long for a concurrent install. @@ -99,6 +108,11 @@ export interface RemoteT3RunnerOptions { export interface SshEnvironmentManagerOptions { readonly resolveCliRunner?: Effect.Effect; + /** + * Where the app keeps its SSH control sockets, so each tunnel's commands share + * one connection. Without it, every command opens its own connection. + */ + readonly controlSocketDirectory?: string; } interface SshTunnelEntry { @@ -109,6 +123,8 @@ interface SshTunnelEntry { readonly localPort: number; readonly httpBaseUrl: string; readonly wsBaseUrl: string; + /** The control master the tunnel's forward runs in, when there is one. */ + readonly controlPath: string | null; readonly process: ChildProcessSpawner.ChildProcessHandle; readonly scope: Scope.Closeable; } @@ -233,6 +249,16 @@ function normalizeSshErrorMessage(stderr: string, fallbackMessage: string): stri return cleaned.length > 0 ? cleaned : fallbackMessage; } +const isSshCommandError = Schema.is(SshCommandError); + +// ssh reports these when it cannot create or use the control socket itself. +function isControlSocketFailure(error: unknown): boolean { + return ( + isSshCommandError(error) && + /control ?socket|unix_listener|controlpath|mux_client|muxserver/iu.test(error.stderr) + ); +} + function stripTrailingNewlines(value: string): string { return value.replace(/\n+$/u, ""); } @@ -1009,7 +1035,7 @@ function buildRemoteLogTailScript(stateKey: string): string { export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemoteServer")( function* ( target: DesktopSshEnvironmentTarget, - input?: SshAuth.SshAuthOptions, + input?: SshConnectionOptions, runner?: RemoteT3RunnerOptions, ): Effect.fn.Return< { readonly remotePort: number; readonly remoteServerKind: "external" | "managed" | null }, @@ -1028,6 +1054,7 @@ export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemo timeoutMs: isNodeScriptRunner(runner) ? REMOTE_LAUNCH_TIMEOUT_MS : REMOTE_ARCHIVE_LAUNCH_TIMEOUT_MS, + controlPath: input?.controlPath, ...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }), ...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }), ...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }), @@ -1069,7 +1096,7 @@ export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemo export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingToken")(function* ( target: DesktopSshEnvironmentTarget, - input?: SshAuth.SshAuthOptions, + input?: SshConnectionOptions, runner?: RemoteT3RunnerOptions, ): Effect.fn.Return< { @@ -1087,6 +1114,7 @@ export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingT remoteCommandArgs: ["sh", "-s"], stdin: buildRemotePairingScript(stateKey, runner), ...(isNodeScriptRunner(runner) ? {} : { timeoutMs: REMOTE_ARCHIVE_PAIRING_TIMEOUT_MS }), + controlPath: input?.controlPath, ...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }), ...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }), ...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }), @@ -1151,7 +1179,7 @@ const stopRemoteServer = Effect.fn("ssh/tunnel.stopRemoteServer")(function* ( const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(function* ( target: DesktopSshEnvironmentTarget, - input?: SshAuth.SshAuthOptions, + input?: SshConnectionOptions, ): Effect.fn.Return< string, SshCommandError | SshInvalidTargetError, @@ -1161,6 +1189,7 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")( remoteCommandArgs: ["sh", "-s"], stdin: buildRemoteLogTailScript(yield* remoteStateKey(target)), timeoutMs: 10_000, + controlPath: input?.controlPath, ...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }), ...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }), ...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }), @@ -1270,27 +1299,32 @@ const waitForTunnelForward = Effect.fn("ssh/tunnel.waitForTunnelForward")(functi ); }); -const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: { - readonly key: string; - readonly resolvedTarget: DesktopSshEnvironmentTarget; - readonly remotePort: number; - readonly localPort: number; - readonly httpBaseUrl: string; - readonly wsBaseUrl: string; +interface WatchedSshProcess { + readonly child: ChildProcessSpawner.ChildProcessHandle; + readonly command: ReadonlyArray; + /** Fails with the exit code and stderr tail once the process exits. */ + readonly exitFailure: Effect.Effect; +} + +interface SshControlMaster extends WatchedSshProcess { + readonly controlPath: string; +} + +// Runs a long-lived ssh (a tunnel or a control master) in `scope`, draining its stderr. +const spawnWatchedSsh = Effect.fn("ssh/tunnel.spawnWatchedSsh")(function* (input: { + readonly role: "tunnel" | "controlMaster"; + readonly target: DesktopSshEnvironmentTarget; readonly authOptions: SshAuth.SshAuthOptions; - readonly remoteServerKind: "external" | "managed" | null; + readonly args: ReadonlyArray; readonly scope: Scope.Closeable; + readonly logFields: Record; }): Effect.fn.Return< - SshTunnelEntry, - SshCommandError | SshInvalidTargetError | SshReadinessError, - | ChildProcessSpawner.ChildProcessSpawner - | Digest.Digest - | FileSystem.FileSystem - | Path.Path - | HttpClient.HttpClient - | NetService.NetService + WatchedSshProcess, + SshCommandError | SshInvalidTargetError, + ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path > { - const hostSpec = yield* buildSshHostSpecEffect(input.resolvedTarget); + const label = input.role === "tunnel" ? "SSH tunnel" : "SSH connection"; + const hostSpec = yield* buildSshHostSpecEffect(input.target); const childEnvironment = yield* SshAuth.buildSshChildEnvironment({ ...(input.authOptions.authSecret === undefined ? {} @@ -1310,41 +1344,12 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: }), ), ); - const args = [ - ...baseSshArgs(input.resolvedTarget, { - batchMode: input.authOptions.batchMode ?? "no", - }), - "-o", - "ExitOnForwardFailure=yes", - "-o", - "ControlMaster=no", - "-o", - "ControlPath=none", - "-o", - "ControlPersist=no", - "-o", - "ServerAliveInterval=15", - "-o", - "ServerAliveCountMax=3", - "-n", - "-N", - "-L", - `${input.localPort}:127.0.0.1:${input.remotePort}`, - "--", - hostSpec, - ]; + const args = [...input.args, "--", hostSpec]; const sshCommand = yield* resolveSshCommand; - const tunnelCommand = [sshCommand, ...args]; + const command = [sshCommand, ...args]; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const { scope } = input; - yield* Effect.logDebug("ssh.tunnel.spawn.start", { - ...sshTargetLogFields(input.resolvedTarget), - command: tunnelCommand, - localPort: input.localPort, - remotePort: input.remotePort, - remoteServerKind: input.remoteServerKind, - httpBaseUrl: input.httpBaseUrl, - }); + const logFields = { ...sshTargetLogFields(input.target), command, ...input.logFields }; + yield* Effect.logDebug(`ssh.${input.role}.spawn.start`, logFields); const child = yield* spawner .spawn( ChildProcess.make(sshCommand, args, { @@ -1357,41 +1362,23 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: }), ) .pipe( - Effect.provideService(Scope.Scope, scope), + Effect.provideService(Scope.Scope, input.scope), Effect.mapError( (cause) => new SshCommandError({ - command: tunnelCommand, + command, exitCode: null, stderr: "", message: cause instanceof Error ? cause.message - : `Failed to spawn SSH tunnel for ${input.resolvedTarget.alias}.`, + : `Failed to spawn ${label} for ${input.target.alias}.`, cause, }), ), ); - yield* Effect.logDebug("ssh.tunnel.spawn.succeeded", { - ...sshTargetLogFields(input.resolvedTarget), - command: tunnelCommand, - pid: child.pid, - localPort: input.localPort, - remotePort: input.remotePort, - httpBaseUrl: input.httpBaseUrl, - }); - const tunnelEntry: SshTunnelEntry = { - key: input.key, - target: input.resolvedTarget, - remotePort: input.remotePort, - remoteServerKind: input.remoteServerKind, - localPort: input.localPort, - httpBaseUrl: input.httpBaseUrl, - wsBaseUrl: input.wsBaseUrl, - process: child, - scope, - }; - // Readiness cancels the exit waiter, but diagnostics must drain until the tunnel closes. + yield* Effect.logDebug(`ssh.${input.role}.spawn.succeeded`, { ...logFields, pid: child.pid }); + // Readiness cancels the exit waiter, but diagnostics must drain until the process closes. let stderrTail = ""; const stderrDrain = yield* child.stderr.pipe( Stream.decodeText(), @@ -1402,7 +1389,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: ), // Diagnostics are best-effort: a failed read must not hide the real exit. Effect.ignore, - Effect.forkIn(scope), + Effect.forkIn(input.scope), ); const exitFailure = Effect.all( [Fiber.join(stderrDrain), child.exitCode.pipe(Effect.map(Number))], @@ -1411,41 +1398,220 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: Effect.mapError( (cause) => new SshCommandError({ - command: tunnelCommand, + command, exitCode: null, stderr: "", message: cause instanceof Error ? cause.message - : `Failed to monitor SSH tunnel for ${input.resolvedTarget.alias}.`, + : `Failed to monitor ${label} for ${input.target.alias}.`, cause, }), ), Effect.flatMap(([, exitCode]) => { const stderr = stderrTail; const error = new SshCommandError({ - command: tunnelCommand, + command, exitCode, stderr, message: normalizeSshErrorMessage( stderr, - `SSH tunnel exited unexpectedly for ${input.resolvedTarget.alias} (exit ${exitCode}).`, + `${label} exited unexpectedly for ${input.target.alias} (exit ${exitCode}).`, ), }); - return Effect.logWarning("ssh.tunnel.process.exited", { - ...sshTargetLogFields(input.resolvedTarget), - command: tunnelCommand, + return Effect.logWarning(`ssh.${input.role}.process.exited`, { + ...logFields, pid: child.pid, - localPort: input.localPort, - remotePort: input.remotePort, - httpBaseUrl: input.httpBaseUrl, exitCode, stderr, }).pipe(Effect.andThen(Effect.fail(error))); }), ); + return { child, command, exitFailure }; +}); + +const killSshProcess = (child: ChildProcessSpawner.ChildProcessHandle) => + child + .kill({ killSignal: "SIGTERM", forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS }) + .pipe(Effect.ignore); + +// ssh creates the control socket once the connection is authenticated. +const waitForControlSocket = Effect.fn("ssh/tunnel.waitForControlSocket")(function* (input: { + readonly target: DesktopSshEnvironmentTarget; + readonly controlPath: string; +}) { + const fs = yield* FileSystem.FileSystem; + yield* fs.exists(input.controlPath).pipe( + Effect.orElseSucceed(() => false), + Effect.repeat({ + schedule: Schedule.spaced(Duration.millis(SSH_TUNNEL_FORWARD_PROBE_INTERVAL_MS)), + until: (exists) => exists, + }), + Effect.timeoutOrElse({ + duration: Duration.millis(SSH_TUNNEL_CONNECT_TIMEOUT_MS), + orElse: () => + Effect.fail( + new SshReadinessError({ + message: `SSH connection to ${input.target.alias} did not come up within ${SSH_TUNNEL_CONNECT_TIMEOUT_MS}ms.`, + }), + ), + }), + ); +}); + +// One authenticated connection per tunnel entry: the launch, the forward, and +// later commands run over it, which saves a handshake each on slow links. +const startControlMaster = Effect.fn("ssh/tunnel.startControlMaster")(function* (input: { + readonly target: DesktopSshEnvironmentTarget; + readonly controlPath: string; + readonly authOptions: SshAuth.SshAuthOptions; + readonly scope: Scope.Closeable; +}): Effect.fn.Return< + SshControlMaster, + SshCommandError | SshInvalidTargetError | SshReadinessError, + ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path +> { + const fs = yield* FileSystem.FileSystem; + const master = yield* spawnWatchedSsh({ + role: "controlMaster", + target: input.target, + authOptions: input.authOptions, + scope: input.scope, + logFields: { controlPath: input.controlPath }, + args: [ + ...baseSshArgs(input.target, { batchMode: input.authOptions.batchMode ?? "no" }), + // Explicit options override any ControlMaster settings in the user's ssh config. + "-o", + "ControlMaster=yes", + "-o", + `ControlPath=${input.controlPath}`, + "-o", + "ControlPersist=no", + "-o", + "ExitOnForwardFailure=yes", + "-o", + "ServerAliveInterval=15", + "-o", + "ServerAliveCountMax=3", + "-n", + "-N", + ], + }); + yield* Scope.addFinalizer( + input.scope, + killSshProcess(master.child).pipe( + // A force-killed master cannot remove its own socket. + Effect.andThen(fs.remove(input.controlPath, { force: true }).pipe(Effect.ignore)), + ), + ); yield* Effect.raceFirst( - waitForTunnelForward({ target: input.resolvedTarget, localPort: input.localPort }).pipe( + waitForControlSocket({ target: input.target, controlPath: input.controlPath }), + master.exitFailure, + ).pipe( + Effect.tap(() => + Effect.logInfo("ssh.controlMaster.ready", { + ...sshTargetLogFields(input.target), + pid: master.child.pid, + controlPath: input.controlPath, + }), + ), + Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : killSshProcess(master.child))), + ); + return { ...master, controlPath: input.controlPath }; +}); + +const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: { + readonly key: string; + readonly resolvedTarget: DesktopSshEnvironmentTarget; + readonly remotePort: number; + readonly localPort: number; + readonly httpBaseUrl: string; + readonly wsBaseUrl: string; + readonly authOptions: SshAuth.SshAuthOptions; + readonly remoteServerKind: "external" | "managed" | null; + readonly controlMaster: SshControlMaster | null; + readonly scope: Scope.Closeable; +}): Effect.fn.Return< + SshTunnelEntry, + SshCommandError | SshInvalidTargetError | SshReadinessError, + | ChildProcessSpawner.ChildProcessSpawner + | Digest.Digest + | FileSystem.FileSystem + | Path.Path + | HttpClient.HttpClient + | NetService.NetService +> { + const forward = `${input.localPort}:127.0.0.1:${input.remotePort}`; + const logFields = { + localPort: input.localPort, + remotePort: input.remotePort, + remoteServerKind: input.remoteServerKind, + httpBaseUrl: input.httpBaseUrl, + }; + const controlPath = input.controlMaster?.controlPath; + // The master owns the forward, so its exit is the tunnel's exit. + const tunnel = + input.controlMaster ?? + (yield* spawnWatchedSsh({ + role: "tunnel", + target: input.resolvedTarget, + authOptions: input.authOptions, + scope: input.scope, + logFields, + args: [ + ...baseSshArgs(input.resolvedTarget, { + batchMode: input.authOptions.batchMode ?? "no", + }), + "-o", + "ExitOnForwardFailure=yes", + "-o", + "ControlMaster=no", + "-o", + "ControlPath=none", + "-o", + "ControlPersist=no", + "-o", + "ServerAliveInterval=15", + "-o", + "ServerAliveCountMax=3", + "-n", + "-N", + "-L", + forward, + ], + })); + const { child } = tunnel; + const tunnelCommand = tunnel.command; + const forwardReady: Effect.Effect< + void, + SshCommandError | SshInvalidTargetError | SshReadinessError, + | ChildProcessSpawner.ChildProcessSpawner + | FileSystem.FileSystem + | Path.Path + | NetService.NetService + > = + controlPath === undefined + ? waitForTunnelForward({ target: input.resolvedTarget, localPort: input.localPort }) + : runSshCommand(input.resolvedTarget, { + preHostArgs: ["-O", "forward", "-L", forward], + controlPath, + batchMode: "yes", + timeoutMs: SSH_CONTROL_COMMAND_TIMEOUT_MS, + }).pipe(Effect.asVoid); + const tunnelEntry: SshTunnelEntry = { + key: input.key, + target: input.resolvedTarget, + remotePort: input.remotePort, + remoteServerKind: input.remoteServerKind, + localPort: input.localPort, + httpBaseUrl: input.httpBaseUrl, + wsBaseUrl: input.wsBaseUrl, + controlPath: controlPath ?? null, + process: child, + scope: input.scope, + }; + yield* Effect.raceFirst( + forwardReady.pipe( Effect.andThen( waitForHttpReady({ baseUrl: input.httpBaseUrl, @@ -1454,16 +1620,15 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: }), ), ), - exitFailure, + tunnel.exitFailure, ).pipe( Effect.tap(() => Effect.logInfo("ssh.tunnel.ready", { ...sshTargetLogFields(input.resolvedTarget), command: tunnelCommand, pid: child.pid, - localPort: input.localPort, - remotePort: input.remotePort, - httpBaseUrl: input.httpBaseUrl, + ...logFields, + controlPath: controlPath ?? null, }), ), Effect.tapError((cause) => @@ -1474,7 +1639,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: net.canListenOnHost(input.localPort, "127.0.0.1"), ); const remoteLogTailExit = yield* Effect.exit( - readRemoteServerLogTail(input.resolvedTarget, input.authOptions), + readRemoteServerLogTail(input.resolvedTarget, { ...input.authOptions, controlPath }), ); const processRunning = Exit.isSuccess(processRunningExit) ? processRunningExit.value : null; const localPortAvailable = Exit.isSuccess(localPortAvailableExit) @@ -1506,16 +1671,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: }); }), ), - Effect.onExit((exit) => - Exit.isSuccess(exit) - ? Effect.void - : child - .kill({ - killSignal: "SIGTERM", - forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS, - }) - .pipe(Effect.ignore), - ), + Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : killSshProcess(child))), ); return tunnelEntry; }); @@ -1690,6 +1846,39 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma }); }); + // Each entry gets a fresh socket name, so a replacement tunnel never joins the + // master of the tunnel it may replace. + const makeControlPath = Effect.fn("ssh/tunnel.makeControlPath")(function* (key: string) { + const directory = options.controlSocketDirectory; + if (directory === undefined || (yield* HostProcess.Platform) === "win32") return null; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const digestService = yield* Digest.Digest; + const digest = yield* digestService.digest(Digest.sha256, new TextEncoder().encode(key)); + const suffix = (yield* Random.nextIntBetween(0, 0xffff_ffff)).toString(16).padStart(8, "0"); + const controlPath = path.join(directory, `${Hex.encode(digest).slice(0, 8)}-${suffix}`); + // ssh splits option values at whitespace and expands % tokens. + if ( + new TextEncoder().encode(controlPath).length > SSH_CONTROL_PATH_MAX_BYTES || + /[\s%"]/u.test(controlPath) + ) { + yield* Effect.logInfo("ssh.controlMaster.unavailable", { controlPath, reason: "path" }); + return null; + } + const created = yield* Effect.exit( + fs.makeDirectory(directory, { recursive: true, mode: 0o700 }), + ); + if (Exit.isFailure(created)) { + yield* Effect.logWarning("ssh.controlMaster.unavailable", { + controlPath, + reason: "directory", + cause: created.cause, + }); + return null; + } + return controlPath; + }); + const createTunnelEntry = Effect.fn("ssh/tunnel.ensureTunnelEntry.create")(function* (input: { readonly key: string; readonly resolvedTarget: DesktopSshEnvironmentTarget; @@ -1700,70 +1889,103 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma ...sshRunnerLogFields(input.runner), key: input.key, }); - const remoteLaunch = yield* runWithSshAuth({ - key: input.key, - target: input.resolvedTarget, - operation: (authOptions) => - launchOrReuseRemoteServer(input.resolvedTarget, authOptions, input.runner), - }); - const remotePort = remoteLaunch.remotePort; - yield* Effect.logDebug("ssh.environment.remotePort.ready", { - ...sshTargetLogFields(input.resolvedTarget), - key: input.key, - remotePort, - remoteServerKind: remoteLaunch.remoteServerKind, - }); - const localPort = yield* reserveLocalTunnelPort(); - const httpBaseUrl = `http://127.0.0.1:${localPort}/`; - const wsBaseUrl = `ws://127.0.0.1:${localPort}/`; - yield* Effect.logDebug("ssh.environment.localPort.reserved", { - ...sshTargetLogFields(input.resolvedTarget), - key: input.key, - localPort, - remotePort, - }); const entryScope = yield* Scope.make("sequential"); - const tunnelEntry = yield* runWithSshAuth({ - key: input.key, - target: input.resolvedTarget, - operation: (authOptions) => - startSshTunnel({ - key: input.key, - resolvedTarget: input.resolvedTarget, - remotePort, - localPort, - httpBaseUrl, - wsBaseUrl, - authOptions, - remoteServerKind: remoteLaunch.remoteServerKind, - scope: entryScope, - }), + return yield* Effect.gen(function* () { + const controlPath = yield* makeControlPath(input.key); + const controlMaster = + controlPath === null + ? null + : yield* runWithSshAuth({ + key: input.key, + target: input.resolvedTarget, + operation: (authOptions) => + startControlMaster({ + target: input.resolvedTarget, + controlPath, + authOptions, + scope: entryScope, + }), + }).pipe( + Effect.catchIf(isControlSocketFailure, (cause) => + Effect.logWarning("ssh.controlMaster.unavailable", { + ...sshTargetLogFields(input.resolvedTarget), + controlPath, + reason: "socket", + cause, + }).pipe(Effect.as(null)), + ), + ); + const connection = { controlPath: controlMaster?.controlPath }; + const remoteLaunch = yield* runWithSshAuth({ + key: input.key, + target: input.resolvedTarget, + operation: (authOptions) => + launchOrReuseRemoteServer( + input.resolvedTarget, + { ...authOptions, ...connection }, + input.runner, + ), + }); + const remotePort = remoteLaunch.remotePort; + yield* Effect.logDebug("ssh.environment.remotePort.ready", { + ...sshTargetLogFields(input.resolvedTarget), + key: input.key, + remotePort, + remoteServerKind: remoteLaunch.remoteServerKind, + }); + const localPort = yield* reserveLocalTunnelPort(); + const httpBaseUrl = `http://127.0.0.1:${localPort}/`; + const wsBaseUrl = `ws://127.0.0.1:${localPort}/`; + yield* Effect.logDebug("ssh.environment.localPort.reserved", { + ...sshTargetLogFields(input.resolvedTarget), + key: input.key, + localPort, + remotePort, + }); + const tunnelEntry = yield* runWithSshAuth({ + key: input.key, + target: input.resolvedTarget, + operation: (authOptions) => + startSshTunnel({ + key: input.key, + resolvedTarget: input.resolvedTarget, + remotePort, + localPort, + httpBaseUrl, + wsBaseUrl, + authOptions, + remoteServerKind: remoteLaunch.remoteServerKind, + controlMaster, + scope: entryScope, + }), + }); + // Closing a tunnel, including when the app quits, leaves the remote server + // running: agent turns may be working there. Only disconnect stops it. + yield* Scope.addFinalizer( + entryScope, + Effect.suspend(() => { + if (tunnels.get(tunnelEntry.key) === tunnelEntry) { + tunnels.delete(tunnelEntry.key); + } + return tunnelEntry.process.kill({ + killSignal: "SIGTERM", + forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS, + }); + }).pipe(Effect.ignore), + ); + yield* Effect.logDebug("ssh.environment.tunnel.create.succeeded", { + ...sshTargetLogFields(input.resolvedTarget), + key: input.key, + localPort, + remotePort, + controlPath: tunnelEntry.controlPath, + }); + return tunnelEntry; }).pipe( Effect.onExit((exit) => Exit.isSuccess(exit) ? Effect.void : Scope.close(entryScope, Exit.void).pipe(Effect.ignore), ), ); - // Closing a tunnel, including when the app quits, leaves the remote server - // running: agent turns may be working there. Only disconnect stops it. - yield* Scope.addFinalizer( - entryScope, - Effect.suspend(() => { - if (tunnels.get(tunnelEntry.key) === tunnelEntry) { - tunnels.delete(tunnelEntry.key); - } - return tunnelEntry.process.kill({ - killSignal: "SIGTERM", - forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS, - }); - }).pipe(Effect.ignore), - ); - yield* Effect.logDebug("ssh.environment.tunnel.create.succeeded", { - ...sshTargetLogFields(input.resolvedTarget), - key: input.key, - localPort, - remotePort, - }); - return tunnelEntry; }); const tunnelStillForwarding = Effect.fn("ssh/tunnel.tunnelStillForwarding")(function* ( @@ -1959,7 +2181,11 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma key, target: entry.target, operation: (authOptions) => - issueRemotePairingToken(entry.target, authOptions, runner), + issueRemotePairingToken( + entry.target, + { ...authOptions, controlPath: entry.controlPath ?? undefined }, + runner, + ), }) : null; const pairingToken = pairingResult?.credential ?? null; From 0250200ccb0731ae3d554ee02d9130a0adc9b858 Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Fri, 20 Nov 2026 10:29:37 +0100 Subject: [PATCH 2/5] fix(client-runtime): do not abandon a slow SSH environment setup after 15 seconds The supervisor gave each connection attempt 15 seconds per route before the session synchronizes, and that budget included preparing an SSH route: the desktop launching or reusing the remote server, starting the tunnel, pairing, and authenticating over it. Over a slow link this takes longer, so attempts were cut off while still making progress and only a later attempt, adopting the earlier work, connected. The driver now reports which route it is preparing, and the supervisor stops the setup clock while an SSH route is being prepared. Desktop main already bounds every SSH step and HTTP request in that preparation and detects a dead link, so the extra deadline only aborted progress. Opening and synchronizing the session keep their usual budgets. Co-Authored-By: Claude Opus 5.5 --- docs/internals/remote.md | 3 + .../client-runtime/src/connection/driver.ts | 3 + .../src/connection/supervisor.test.ts | 52 ++++++++++++- .../src/connection/supervisor.ts | 77 ++++++++++++++----- 4 files changed, 112 insertions(+), 23 deletions(-) diff --git a/docs/internals/remote.md b/docs/internals/remote.md index b9bf013acdea8..ea7dff430ea80 100644 --- a/docs/internals/remote.md +++ b/docs/internals/remote.md @@ -183,6 +183,9 @@ replacement for a slow tunnel never joins the master it may be replacing. ssh binds the socket at its path plus 17 characters, inside macOS's 104-byte limit, so a path that cannot fit, Windows (whose OpenSSH has no multiplexing), and a master that cannot create its socket all fall back to one connection per command. +The supervisor's 15-second setup budget stops while an SSH route is being +prepared: desktop main bounds every SSH step and request in it, and a launch over +a slow link or a first install takes far longer than 15 seconds. Remote servers can outlive several client releases. Clients must use advertised capabilities and handle their absence, rather than assume their own version diff --git a/packages/client-runtime/src/connection/driver.ts b/packages/client-runtime/src/connection/driver.ts index 45f12d0b74509..695996acd365b 100644 --- a/packages/client-runtime/src/connection/driver.ts +++ b/packages/client-runtime/src/connection/driver.ts @@ -30,6 +30,8 @@ import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts"; export type ConnectionDriverProgress = | { readonly stage: "preparing"; + /** The route about to be prepared; absent before any route is chosen. */ + readonly route?: ConnectionRoute; } | { readonly stage: Exclude; @@ -199,6 +201,7 @@ export const make = Effect.gen(function* () { entry, (route) => checkRoute(entry, route), Effect.fnUntraced(function* (route) { + yield* reportProgress({ stage: "preparing", route }); const prepared = yield* resolver.prepare(routeEntry(entry, route)); yield* reportProgress({ stage: "opening", prepared }); const session = yield* sessions.connect(prepared); diff --git a/packages/client-runtime/src/connection/supervisor.test.ts b/packages/client-runtime/src/connection/supervisor.test.ts index f284c48e82772..9159098589bf3 100644 --- a/packages/client-runtime/src/connection/supervisor.test.ts +++ b/packages/client-runtime/src/connection/supervisor.test.ts @@ -32,6 +32,7 @@ import { ConnectionTransientError, PrimaryConnectionTarget, RelayConnectionTarget, + SshConnectionTarget, type ConnectionAttemptError, type ConnectionTarget, type NetworkStatus, @@ -68,6 +69,16 @@ const RELAY_ENTRY: ConnectionCatalogEntry = { enabled: true, }; +const SSH_ENTRY: ConnectionCatalogEntry = { + target: new SshConnectionTarget({ + environmentId: TARGET.environmentId, + label: TARGET.label, + connectionId: "ssh:devbox", + }), + profile: Option.none(), + enabled: true, +}; + const PREPARED_CONNECTION: PreparedConnection = { environmentId: TARGET.environmentId, label: TARGET.label, @@ -191,10 +202,11 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?: options?.checkRoute?.(route) ?? Effect.succeed("unchecked"); const connectRoute = Effect.fn("TestConnectionDriver.connectRoute")(function* ( - target: ConnectionTarget, + route: ConnectionRoute, reportProgress: (progress: ConnectionDriver.ConnectionDriverProgress) => Effect.Effect, ) { - const prepared = yield* prepare(target); + yield* reportProgress({ stage: "preparing", route }); + const prepared = yield* prepare(route.target); yield* reportProgress({ stage: "opening", prepared }); const attempt = yield* Ref.updateAndGet(sessionCount, (count) => count + 1); @@ -233,7 +245,7 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?: ) { yield* reportProgress({ stage: "preparing" }); return yield* ConnectionDriver.connectOverRoutes(entry, checkRoute, (route) => - connectRoute(route.target, reportProgress), + connectRoute(route, reportProgress), ); }); @@ -556,6 +568,40 @@ describe("EnvironmentSupervisor", () => { }).pipe(Effect.provide(TestClock.layer())), ); + it.effect("does not count preparing an SSH route against the setup timeout", () => + Effect.gen(function* () { + const prepareStarted = yield* Deferred.make(); + const tunnelReady = yield* Deferred.make(); + const harness = yield* makeHarness({ + prepare: (_attempt, target) => + Deferred.succeed(prepareStarted, undefined).pipe( + Effect.andThen(Deferred.await(tunnelReady)), + Effect.as(preparedFor(target)), + ), + ready: () => Effect.never, + }); + const supervisor = yield* EnvironmentSupervisor.make(SSH_ENTRY, { + initiallyDesired: true, + }).pipe(Effect.provide(harness.dependencies)); + + // A cold launch over a slow link outlasts the 15-second setup budget. + yield* Deferred.await(prepareStarted); + yield* TestClock.adjust("60 seconds"); + yield* Deferred.succeed(tunnelReady, undefined); + const settled = yield* awaitState( + supervisor.state, + (state) => state.phase === "backoff" || state.stage === "synchronizing", + ); + expect(settled).toMatchObject({ phase: "connecting", stage: "synchronizing", attempt: 1 }); + + // Once prepared, the session still has only its usual budget. + yield* TestClock.adjust("90 seconds"); + const timedOut = yield* awaitState(supervisor.state, (state) => state.phase === "backoff"); + expect(timedOut).toMatchObject({ attempt: 1, lastFailure: { reason: "timeout" } }); + expect(yield* Ref.get(harness.prepareCount)).toBe(1); + }).pipe(Effect.provide(TestClock.layer())), + ); + it.effect("treats an involuntary session close as transient and reconnects", () => Effect.gen(function* () { const harness = yield* makeHarness(); diff --git a/packages/client-runtime/src/connection/supervisor.ts b/packages/client-runtime/src/connection/supervisor.ts index 8f7536605810b..f21456c44ce5f 100644 --- a/packages/client-runtime/src/connection/supervisor.ts +++ b/packages/client-runtime/src/connection/supervisor.ts @@ -44,7 +44,9 @@ const RETRY_BASE_DELAY_MS = 1_000; const RETRY_MAX_DELAY_MS = 300_000; const SESSION_LOSS_RETRY_DELAY_MS = 250; // A cold server with a large database can take longer than 15 seconds to -// answer, and that is not a reason to drop a working connection. +// answer, and that is not a reason to drop a working connection. Preparing an +// SSH route does not count: the desktop bounds each SSH step and HTTP request +// itself, and a slow link or a cold remote install can take far longer. const CONNECTION_ESTABLISHMENT_TIMEOUT = "15 seconds"; const establishmentTimeout = Duration.fromInputUnsafe(CONNECTION_ESTABLISHMENT_TIMEOUT); const synchronizationTimeout = Duration.fromInputUnsafe("75 seconds"); @@ -73,6 +75,14 @@ const SILENT_ROUTE_BACKOFF_MAX_MS = 1_800_000; // tried again for this long, so a flaky LAN cannot bounce the connection. const BETTER_ROUTE_COOLDOWN_MS = 300_000; +/** What extends one attempt's setup deadline beyond its base budget. */ +interface EstablishmentBudget { + readonly synchronizedRoutes: number; + readonly exemptNanos: bigint; + /** When the SSH route now being prepared started, if one is. */ + readonly sshPreparingSince: bigint | null; +} + interface SupervisorIntent { readonly desired: boolean; readonly network: NetworkStatus; @@ -470,13 +480,31 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( attempt: number, generation: number, lastFailure: ConnectionAttemptError | null, - synchronizedRoutes: Ref.Ref, + budget: SubscriptionRef.SubscriptionRef, ) { return yield* driver.connect(yield* attemptEntry, (progress) => - (progress.stage === "synchronizing" - ? Ref.update(synchronizedRoutes, (count) => count + 1) - : Effect.void - ).pipe(Effect.andThen(reportProgress(attempt, generation, lastFailure, progress))), + Clock.monotonicTimeNanos.pipe( + Effect.flatMap((now) => + SubscriptionRef.update(budget, (current) => { + const resumed = + current.sshPreparingSince === null + ? current + : { + ...current, + exemptNanos: current.exemptNanos + (now - current.sshPreparingSince), + sshPreparingSince: null, + }; + if (progress.stage === "synchronizing") { + return { ...resumed, synchronizedRoutes: resumed.synchronizedRoutes + 1 }; + } + return progress.stage === "preparing" && + progress.route?.target._tag === "SshConnectionTarget" + ? { ...resumed, sshPreparingSince: now } + : resumed; + }), + ), + Effect.andThen(reportProgress(attempt, generation, lastFailure, progress)), + ), ); }); @@ -557,17 +585,17 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( generation: number, lastFailure: ConnectionAttemptError | null, pendingRetry: Option.Option, - synchronizedRoutes: Ref.Ref, + budget: SubscriptionRef.SubscriptionRef, ) { if (usesRelay) { return yield* traceRelayEstablishment( - establishConnection(attempt, generation, lastFailure, synchronizedRoutes), + establishConnection(attempt, generation, lastFailure, budget), attempt, generation, pendingRetry, ); } - return yield* establishConnection(attempt, generation, lastFailure, synchronizedRoutes).pipe( + return yield* establishConnection(attempt, generation, lastFailure, budget).pipe( Effect.map((lease) => ({ attemptSpan: Option.none(), lease, @@ -883,16 +911,14 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( ) { const switchingTo = yield* Ref.get(preferredRouteId); yield* SubscriptionRef.set(prepared, Option.none()); - const synchronizedRoutes = yield* Ref.make(0); + const budget = yield* SubscriptionRef.make({ + synchronizedRoutes: 0, + exemptNanos: 0n, + sshPreparingSince: null, + }); const establishment = yield* Effect.raceAllFirst([ exitUnlessInterrupted( - establishTracedConnection( - attempt, - generation, - lastFailure, - pendingRetry, - synchronizedRoutes, - ), + establishTracedConnection(attempt, generation, lastFailure, pendingRetry, budget), ).pipe( Effect.map((exit): EstablishmentEvent => ({ _tag: "Completed", @@ -907,15 +933,26 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( ), // Each route may use the full setup time before the next is tried, and // each route that reaches synchronizing adds its own snapshot budget, so - // a route that fails late does not eat the next route's time. + // a route that fails late does not eat the next route's time. The clock + // stops while an SSH route is being prepared. Effect.gen(function* () { const routeCount = connectionRoutes(yield* Ref.get(currentEntry)).length; const startedAt = yield* Clock.monotonicTimeNanos; const setup = Duration.toNanosUnsafe(Duration.times(establishmentTimeout, routeCount)); while (true) { - const synchronized = BigInt(yield* Ref.get(synchronizedRoutes)); + const current = yield* SubscriptionRef.get(budget); + if (current.sshPreparingSince !== null) { + yield* SubscriptionRef.changes(budget).pipe( + Stream.filter((next) => next.sshPreparingSince === null), + Stream.runHead, + ); + continue; + } const deadline = - startedAt + setup + synchronized * Duration.toNanosUnsafe(synchronizationTimeout); + startedAt + + setup + + current.exemptNanos + + BigInt(current.synchronizedRoutes) * Duration.toNanosUnsafe(synchronizationTimeout); const remaining = deadline - (yield* Clock.monotonicTimeNanos); if (remaining <= 0n) { return { _tag: "TimedOut" } as const satisfies EstablishmentEvent; From 3d415d761bf113147ccc9561e9fec3fee04a6bfc Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Fri, 20 Nov 2026 10:36:02 +0100 Subject: [PATCH 3/5] perf(ssh): open no SSH connection besides the tunnel's master Disconnecting stopped the remote server over a new connection after closing the tunnel, and a command whose master had died silently opened its own. Disconnect now stops the server over the live master before closing it. Commands over a master set ProxyCommand=false: ssh tries the master first, so they still work, but a dead master fails them instead of opening a second connection. Sockets a crashed app left behind get `ssh -O exit` before the first new one is created. The remote launch also prepares the release runtime without starting t3 (`--version` took about a second on a busy host), which leaves two t3 starts in a launch that reuses a running server. Co-Authored-By: Claude Opus 5.5 --- docs/internals/remote.md | 11 +++-- packages/ssh/src/command.ts | 7 ++- packages/ssh/src/tunnel.test.ts | 76 ++++++++++++++++++++----------- packages/ssh/src/tunnel.ts | 81 ++++++++++++++++++++++++++++----- 4 files changed, 132 insertions(+), 43 deletions(-) diff --git a/docs/internals/remote.md b/docs/internals/remote.md index ea7dff430ea80..4dad227d59c5b 100644 --- a/docs/internals/remote.md +++ b/docs/internals/remote.md @@ -177,9 +177,14 @@ stops it and the next connect starts the client's version. Reconnection restores the forward before opening the application transport. Each new SSH connection costs several round trips, which is seconds on a slow -link, so each tunnel owns one control master and runs its launch, port forward, -and pairing over it. The master's socket gets a fresh name per tunnel, so a -replacement for a slow tunnel never joins the master it may be replacing. ssh +link, so each tunnel is one supervised control master (`ssh -M -N`), and its +launch, port forward (`-O forward`), pairing, and disconnect run over it. Explicit +options override the user's `ControlMaster` and `ControlPersist`, which otherwise +hand the forward to another master and exit (upstream #3533), and the commands +over it set `ProxyCommand=false`, so a dead master fails them instead of letting +them connect on their own. The master's socket gets a fresh name per tunnel, so a +replacement for a slow tunnel never joins the master it may be replacing, and +sockets a crashed app left behind get `-O exit` before the first new one. ssh binds the socket at its path plus 17 characters, inside macOS's 104-byte limit, so a path that cannot fit, Windows (whose OpenSSH has no multiplexing), and a master that cannot create its socket all fall back to one connection per command. diff --git a/packages/ssh/src/command.ts b/packages/ssh/src/command.ts index 10ee9d4e25e58..50a919b752510 100644 --- a/packages/ssh/src/command.ts +++ b/packages/ssh/src/command.ts @@ -39,11 +39,14 @@ export interface SshConnectionOptions extends SshAuthOptions { readonly controlPath?: string | undefined; } -/** Joins a live control master; ssh connects on its own when the master is gone. */ +/** + * Runs over a live control master only. ssh tries the master before connecting, + * so a failing ProxyCommand stops it opening a second connection when the master is gone. + */ function controlClientSshArgs(controlPath: string | undefined): string[] { return controlPath === undefined ? [] - : ["-o", "ControlMaster=no", "-o", `ControlPath=${controlPath}`]; + : ["-o", "ControlMaster=no", "-o", `ControlPath=${controlPath}`, "-o", "ProxyCommand=false"]; } export interface RunSshCommandOptions extends SshConnectionOptions { diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index e0201de92038d..f6d2897173291 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -141,6 +141,7 @@ const net = require("node:net"); const path = require("node:path"); const version = path.basename(__dirname); const [command, ...args] = process.argv.slice(2); +fs.appendFileSync(path.join(process.env.HOME, "t3-starts"), command + "\\n"); const option = (name) => args[args.indexOf(name) + 1]; if (command === "--version") { console.log(version); @@ -523,61 +524,76 @@ describe("ssh tunnel scripts", () => { : { controlSocketDirectory: input.controlSocketDirectory }), }), ); + // Commands over a master cannot connect on their own (ProxyCommand=false). const connections = () => - spawned.filter( - (args) => - !args.includes("-G") && - (args.includes("ControlMaster=yes") || - !args.some((arg) => arg.startsWith("ControlPath=") && arg !== "ControlPath=none")), - ).length; + spawned.filter((args) => !args.includes("-G") && !args.includes("ProxyCommand=false")).length; return { spawned, masters, refused, refusedProbes, layer, connections }; }); it.effect.each([ - { mode: "plain connections", useControlMaster: false, connections: 3 }, + { mode: "plain connections", useControlMaster: false, connections: 4 }, { mode: "one control master", useControlMaster: true, connections: 1 }, - ])("first connect opens $connections ssh connection(s) with $mode", (row) => + ])("connect, pair, and disconnect open $connections ssh connection(s) with $mode", (row) => Effect.gen(function* () { const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-ssh-cm-")); + const controlDirectory = NodePath.join(directory, "control"); + // A socket left by a crashed app. + NodeFS.mkdirSync(controlDirectory); + const stale = NodePath.join(controlDirectory, "stale"); + NodeFS.writeFileSync(stale, ""); try { const harness = yield* controlMasterHarness({ - controlSocketDirectory: row.useControlMaster - ? NodePath.join(directory, "control") - : undefined, + controlSocketDirectory: row.useControlMaster ? controlDirectory : undefined, }); yield* Effect.gen(function* () { const manager = yield* SshTunnel.SshEnvironmentManager; const target = { alias: "devbox", hostname: "devbox", username: null, port: null }; - // Launch, tunnel forward, and pairing. + // Launch, tunnel forward, and pairing, then stopping the server. const result = yield* manager.ensureEnvironment(target, { issuePairingToken: true }); assert.equal(result.pairingToken, "PAIRED"); + const [master] = harness.masters; + if (row.useControlMaster) assert.isFalse(master!.killed); + yield* manager.disconnectEnvironment(target); assert.equal(harness.connections(), row.connections); if (!row.useControlMaster) return; - const [master] = harness.masters; - assert.isDefined(master); - assert.isTrue(NodeFS.existsSync(master!.controlPath)); + assert.isTrue(master!.killed); + assert.isFalse(NodeFS.existsSync(stale)); + assert.isTrue( + harness.spawned.some( + (args) => args.includes("exit") && args.includes(`ControlPath=${stale}`), + ), + ); + // Options from the user's ssh config (ControlMaster auto, ControlPersist) + // cannot hand the forward to another master or fork it into the background. + for (const args of harness.spawned.filter((entry) => !entry.includes("-G"))) { + const controlPath = args.find((arg) => arg.startsWith("ControlPath=")); + assert.isDefined(controlPath); + if (args.includes("-N")) { + assert.includeMembers([...args], ["ControlMaster=yes", "ControlPersist=no"]); + } else { + assert.includeMembers([...args], ["ControlMaster=no", "ProxyCommand=false"]); + } + } assert.isTrue(harness.spawned.some((args) => args.includes("forward"))); + // A dead tunnel's replacement gets its own master. - harness.refused.add(41_773); + yield* manager.ensureEnvironment(target); + const live = harness.masters[1]!; + harness.refused.add(41_774); const replacing = yield* Effect.forkChild(manager.ensureEnvironment(target)); yield* Queue.take(harness.refusedProbes); yield* TestClock.adjust("10 seconds"); yield* Fiber.join(replacing); - assert.equal(harness.connections(), 2); - assert.equal(harness.masters.length, 2); - assert.notEqual(harness.masters[1]!.controlPath, master!.controlPath); - assert.isTrue(master!.killed); - assert.isFalse(NodeFS.existsSync(master!.controlPath)); + assert.equal(harness.connections(), 3); + assert.equal(harness.masters.length, 3); + assert.notEqual(harness.masters[2]!.controlPath, live.controlPath); + assert.isTrue(live.killed); + assert.isFalse(NodeFS.existsSync(live.controlPath)); }).pipe(Effect.provide(harness.layer), Effect.scoped); // Quitting stops every master and removes its socket. assert.isTrue(harness.masters.every((master) => master.killed)); - assert.deepEqual( - NodeFS.readdirSync(directory).flatMap((entry) => - NodeFS.readdirSync(NodePath.join(directory, entry)), - ), - [], - ); + if (row.useControlMaster) assert.deepEqual(NodeFS.readdirSync(controlDirectory), []); } finally { NodeFS.rmSync(directory, { recursive: true, force: true }); } @@ -1257,6 +1273,7 @@ describe("ssh tunnel scripts", () => { // Another alias adopts the same server and still pairs with its version. yield* install("1.0.1"); + const startsBefore = (yield* fs.readFileString(path.join(home, "t3-starts"))).length; const adopted = yield* SshTunnel.launchOrReuseRemoteServer( tailnet, undefined, @@ -1264,6 +1281,11 @@ describe("ssh tunnel scripts", () => { ); assert.equal(adopted.remotePort, first.remotePort); assert.equal(adopted.remoteServerKind, "external"); + // Each t3 start costs about a second on a busy host; an installed runtime needs none to prepare. + assert.notInclude( + (yield* fs.readFileString(path.join(home, "t3-starts"))).slice(startsBefore), + "--version", + ); const adoptedPairing = yield* SshTunnel.issueRemotePairingToken( tailnet, undefined, diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index 521a97befd46f..e7729ebcc1a2a 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -67,6 +67,13 @@ const SSH_TUNNEL_CONNECT_TIMEOUT_MS = REMOTE_LAUNCH_BASE_TIMEOUT_MS; const SSH_TUNNEL_FORWARD_PROBE_INTERVAL_MS = 100; // Control commands only talk to the local master. const SSH_CONTROL_COMMAND_TIMEOUT_MS = 10_000; +// `ssh -O exit` needs a destination, though it only talks to the socket. +const STALE_CONTROL_TARGET: DesktopSshEnvironmentTarget = { + alias: "t3-stale-control", + hostname: "t3-stale-control", + username: null, + port: null, +}; // ssh binds the control socket at its path plus ".XXXXXXXXXXXXXXXX" before renaming it, // and macOS allows 104 bytes for a socket path, including the terminating NUL. const SSH_CONTROL_PATH_MAX_BYTES = 103 - 17; @@ -572,6 +579,10 @@ if [ -n "\${T3_LOCK:-}" ]; then rm -rf "$T3_LOCK" trap - EXIT fi +# A launch only needs the runtime installed; starting t3 takes a second on a busy host. +if [ "\${T3_RUNNER_PREPARE_ONLY:-}" = "1" ]; then + exit 0 +fi exec "$T3_RUNTIME_DIR/t3" "$@" `; @@ -619,7 +630,7 @@ if [ "$T3_ARCHIVE_MODE" = "1" ]; then if [ "$(cat "$MANAGED_FILE" 2>/dev/null || true)" = "managed" ] && [ -x "$RUNNER_FILE" ] && [ -n "$RECORDED_PID" ] && kill -0 "$RECORDED_PID" 2>/dev/null; then RUNNER="$RUNNER_FILE" else - "$RUNNER_NEXT" --version >/dev/null + T3_RUNNER_PREPARE_ONLY=1 "$RUNNER_NEXT" fi elif ! ensure_remote_node_path; then printf 'Remote host is missing node on PATH. Install Node or configure a supported version manager for non-interactive shells.\\n' >&2 @@ -816,7 +827,7 @@ fi if [ -z "$REMOTE_PORT" ]; then if [ "$RUNNER" != "$RUNNER_NEXT" ]; then # The server this launch meant to reuse is gone, so start the new runner. - "$RUNNER_NEXT" --version >/dev/null + T3_RUNNER_PREPARE_ONLY=1 "$RUNNER_NEXT" RUNNER="$RUNNER_NEXT" fi REMOTE_PORT="$(pick_port)" || true @@ -1152,7 +1163,7 @@ export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingT const stopRemoteServer = Effect.fn("ssh/tunnel.stopRemoteServer")(function* ( target: DesktopSshEnvironmentTarget, - input?: SshAuth.SshAuthOptions, + input?: SshConnectionOptions, ): Effect.fn.Return< void, SshCommandError | SshInvalidTargetError, @@ -1167,6 +1178,7 @@ const stopRemoteServer = Effect.fn("ssh/tunnel.stopRemoteServer")(function* ( remoteCommandArgs: ["sh", "-s"], stdin: buildRemoteStopScript(stateKey), timeoutMs: (REMOTE_STOP_WAIT_SECONDS + 30) * 1000, + controlPath: input?.controlPath, ...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }), ...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }), ...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }), @@ -1846,11 +1858,43 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma }); }); + // A master left by a crashed app would hold its connection open indefinitely. + // Runs once, before this manager creates a socket of its own. + const sweepStaleControlMasters = yield* Effect.cached( + Effect.gen(function* () { + const directory = options.controlSocketDirectory; + if (directory === undefined || (yield* HostProcess.Platform) === "win32") return; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const names = yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => [])); + yield* Effect.forEach( + names, + (name) => { + const controlPath = path.join(directory, name); + return runSshCommand(STALE_CONTROL_TARGET, { + preHostArgs: ["-F", "/dev/null", "-O", "exit"], + controlPath, + batchMode: "yes", + timeoutMs: SSH_CONTROL_COMMAND_TIMEOUT_MS, + }).pipe( + Effect.ignore, + Effect.andThen(fs.remove(controlPath, { force: true }).pipe(Effect.ignore)), + ); + }, + { concurrency: "unbounded", discard: true }, + ); + if (names.length > 0) { + yield* Effect.logInfo("ssh.controlMaster.staleSwept", { count: names.length }); + } + }).pipe(Effect.withSpan("ssh/tunnel.sweepStaleControlMasters")), + ); + // Each entry gets a fresh socket name, so a replacement tunnel never joins the // master of the tunnel it may replace. const makeControlPath = Effect.fn("ssh/tunnel.makeControlPath")(function* (key: string) { const directory = options.controlSocketDirectory; if (directory === undefined || (yield* HostProcess.Platform) === "win32") return null; + yield* sweepStaleControlMasters; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const digestService = yield* Digest.Digest; @@ -2248,17 +2292,32 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma key, hasTunnel: entry !== null, }); - if (entry !== null) { - yield* Effect.gen(function* () { - tunnels.delete(key); - yield* closeTunnelEntry(entry); - }).pipe(Effect.uninterruptible); - } - yield* runWithSshAuth({ + // Stop over the tunnel's live master rather than a new connection, then close it. + const controlPath = + entry !== null && + entry.controlPath !== null && + (yield* entry.process.isRunning.pipe(Effect.orElseSucceed(() => false))) + ? entry.controlPath + : undefined; + const stop = runWithSshAuth({ key, target: resolvedTarget, - operation: (authOptions) => stopRemoteServer(resolvedTarget, authOptions), + operation: (authOptions) => + stopRemoteServer(resolvedTarget, { ...authOptions, controlPath }), }); + const closeEntry = + entry === null + ? Effect.void + : Effect.gen(function* () { + tunnels.delete(key); + yield* closeTunnelEntry(entry); + }).pipe(Effect.uninterruptible); + if (controlPath === undefined) { + yield* closeEntry; + yield* stop; + } else { + yield* stop.pipe(Effect.ensuring(closeEntry)); + } yield* Effect.logInfo("ssh.environment.disconnect.succeeded", { ...sshTargetLogFields(resolvedTarget), key, From 8a0b7b482141d23e4e41d7374138d8b26c75d0e1 Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Fri, 20 Nov 2026 11:21:31 +0100 Subject: [PATCH 4/5] perf(ssh): skip the HTTP probe through a tunnel that runs in a live master The remote launch reports a port only once the server answered on the host, and a forward added to a live control master listens at once. Probing it through the forward again cost a channel open and a request, two round trips, before the renderer made its own first request. Plain tunnels, whose ssh may still be connecting, keep the probe. Co-Authored-By: Claude Opus 5.5 --- packages/ssh/src/tunnel.test.ts | 15 +++++++++++++-- packages/ssh/src/tunnel.ts | 14 +++++++++----- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index f6d2897173291..fcb855f9d1da5 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -485,6 +485,7 @@ describe("ssh tunnel scripts", () => { ); const refused = new Set(); const refusedProbes = yield* Queue.unbounded(); + let httpRequests = 0; let nextPort = 41_773; const layer = Layer.mergeAll( NodeServices.layer, @@ -493,7 +494,7 @@ describe("ssh tunnel scripts", () => { Layer.succeed( HttpClient.HttpClient, HttpClient.make((request) => - refused.has(Number(new URL(request.url).port)) + ++httpRequests > 0 && refused.has(Number(new URL(request.url).port)) ? Queue.offer(refusedProbes, undefined).pipe( Effect.andThen( Effect.fail( @@ -527,7 +528,15 @@ describe("ssh tunnel scripts", () => { // Commands over a master cannot connect on their own (ProxyCommand=false). const connections = () => spawned.filter((args) => !args.includes("-G") && !args.includes("ProxyCommand=false")).length; - return { spawned, masters, refused, refusedProbes, layer, connections }; + return { + spawned, + masters, + refused, + refusedProbes, + layer, + connections, + httpRequests: () => httpRequests, + }; }); it.effect.each([ @@ -551,6 +560,8 @@ describe("ssh tunnel scripts", () => { // Launch, tunnel forward, and pairing, then stopping the server. const result = yield* manager.ensureEnvironment(target, { issuePairingToken: true }); assert.equal(result.pairingToken, "PAIRED"); + // The launch already saw the server answer; only plain tunnels probe through the forward. + assert.equal(harness.httpRequests(), row.useControlMaster ? 0 : 1); const [master] = harness.masters; if (row.useControlMaster) assert.isFalse(master!.killed); yield* manager.disconnectEnvironment(target); diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index e7729ebcc1a2a..cda277597787d 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -1622,14 +1622,18 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: process: child, scope: input.scope, }; + // The launch only reports a server that answered on the host, and a forward added + // to a live master listens at once, so a probe through it would only cost round trips. yield* Effect.raceFirst( forwardReady.pipe( Effect.andThen( - waitForHttpReady({ - baseUrl: input.httpBaseUrl, - timeoutMs: SSH_READY_TIMEOUT_MS, - probeTimeoutMs: SSH_TUNNEL_READY_PROBE_TIMEOUT_MS, - }), + controlPath === undefined + ? waitForHttpReady({ + baseUrl: input.httpBaseUrl, + timeoutMs: SSH_READY_TIMEOUT_MS, + probeTimeoutMs: SSH_TUNNEL_READY_PROBE_TIMEOUT_MS, + }) + : Effect.void, ), ), tunnel.exitFailure, From aee6f5a99dedd6629be4cd13a7f868f1989c64ab Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Fri, 20 Nov 2026 11:21:48 +0100 Subject: [PATCH 5/5] perf(client-runtime): read an SSH environment's descriptor once per connect The desktop reads the descriptor through the SSH forward to check the host's identity before it sends the saved token, and then the renderer read it again before asking for a WebSocket ticket: a second channel open and request on a slow link. The SSH gateway now returns the descriptor the desktop read, and authorizing over SSH uses it when it names the expected environment. Other routes, including plain HTTP addresses, still read it. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/connection/platform.ts | 9 ++++- .../src/authorization/layer.test.ts | 37 +++++++++++++++++++ .../src/authorization/service.ts | 11 +++++- .../client-runtime/src/connection/resolver.ts | 1 + .../src/platform/capabilities.ts | 3 ++ 5 files changed, 58 insertions(+), 3 deletions(-) diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts index 97958bde7f749..1cf85eb58938a 100644 --- a/apps/web/src/connection/platform.ts +++ b/apps/web/src/connection/platform.ts @@ -262,6 +262,7 @@ export const provisionDesktopSshEnvironment = Effect.fn( label: descriptor.label, bootstrap, bearerToken: access.access_token, + descriptor, }; }); @@ -302,7 +303,7 @@ export const prepareDesktopSshEnvironment = Effect.fn("web.connectionPlatform.ss session.authenticated && AuthStandardClientScopes.every((scope) => granted.includes(scope)) ) { - return { bootstrap, bearerToken }; + return { bootstrap, bearerToken, descriptor }; } } const provisioned = yield* provisionDesktopSshEnvironment( @@ -310,7 +311,11 @@ export const prepareDesktopSshEnvironment = Effect.fn("web.connectionPlatform.ss input.target, input.expectedEnvironmentId, ); - return { bootstrap: provisioned.bootstrap, bearerToken: provisioned.bearerToken }; + return { + bootstrap: provisioned.bootstrap, + bearerToken: provisioned.bearerToken, + descriptor: provisioned.descriptor, + }; }, ); diff --git a/packages/client-runtime/src/authorization/layer.test.ts b/packages/client-runtime/src/authorization/layer.test.ts index 8c7cd57502b8b..73eccc5fb5ac9 100644 --- a/packages/client-runtime/src/authorization/layer.test.ts +++ b/packages/client-runtime/src/authorization/layer.test.ts @@ -378,6 +378,43 @@ describe("RemoteEnvironmentAuthorization", () => { }), ); + it.effect("authorizes over SSH without reading the descriptor the desktop just read", () => + Effect.gen(function* () { + const descriptor = { + ...DESCRIPTOR, + orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION, + } as ExecutionEnvironmentDescriptor; + const harness = yield* makeHarness({ + responses: [ + websocketTicket("forwarded"), + Response.json(descriptor), + websocketTicket("checked"), + ], + }); + yield* Effect.gen(function* () { + const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; + const authorize = (verifiedDescriptor: ExecutionEnvironmentDescriptor) => + remote.authorizeBearer({ + expectedEnvironmentId: ENVIRONMENT_ID, + httpBaseUrl: "http://127.0.0.1:41773", + wsBaseUrl: "ws://127.0.0.1:41773", + bearerToken: "bearer-token", + connectionMethod: "ssh", + verifiedDescriptor, + }); + yield* authorize(descriptor); + // One for another environment proves nothing, so it reads again. + yield* authorize({ ...descriptor, environmentId: "other" as never }); + }).pipe(Effect.provide(harness.layer)); + + expect(harness.fetch.calls.map(([url]) => new URL(String(url)).pathname)).toEqual([ + "/api/auth/websocket-ticket/rpc", + "/.well-known/t3/environment", + "/api/auth/websocket-ticket/rpc", + ]); + }), + ); + it.effect("blocks a warm direct bearer prepare when the environment changes identity", () => Effect.gen(function* () { const harness = yield* makeHarness({ diff --git a/packages/client-runtime/src/authorization/service.ts b/packages/client-runtime/src/authorization/service.ts index c197c3a9b38d1..018c54b3d7593 100644 --- a/packages/client-runtime/src/authorization/service.ts +++ b/packages/client-runtime/src/authorization/service.ts @@ -68,6 +68,11 @@ export class RemoteEnvironmentAuthorization extends Context.Service< readonly wsBaseUrl: string; readonly bearerToken: string; readonly connectionMethod: ClientConnectionMethod; + /** + * A descriptor this client read from the same endpoint moment ago over a route it + * controls, such as its own SSH forward, which saves reading it again. + */ + readonly verifiedDescriptor?: ExecutionEnvironmentDescriptor; }) => Effect.Effect; readonly authorizeDpop: (input: { readonly expectedEnvironmentId: EnvironmentId; @@ -189,8 +194,12 @@ export const make = Effect.gen(function* () { readonly wsBaseUrl: string; readonly bearerToken: string; readonly connectionMethod: ClientConnectionMethod; + readonly verifiedDescriptor?: ExecutionEnvironmentDescriptor; }) { - const descriptor = yield* verifyDirectEndpoint(input); + const descriptor = + input.verifiedDescriptor?.environmentId === input.expectedEnvironmentId + ? input.verifiedDescriptor + : yield* verifyDirectEndpoint(input); const socketUrl = yield* resolveRemoteWebSocketConnectionUrl({ wsBaseUrl: input.wsBaseUrl, httpBaseUrl: input.httpBaseUrl, diff --git a/packages/client-runtime/src/connection/resolver.ts b/packages/client-runtime/src/connection/resolver.ts index eded482a94d9f..350b24217be78 100644 --- a/packages/client-runtime/src/connection/resolver.ts +++ b/packages/client-runtime/src/connection/resolver.ts @@ -258,6 +258,7 @@ const makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(funct wsBaseUrl: prepared.bootstrap.wsBaseUrl, bearerToken: prepared.bearerToken, connectionMethod: "ssh", + ...(prepared.descriptor === undefined ? {} : { verifiedDescriptor: prepared.descriptor }), }); return { ...authorized, diff --git a/packages/client-runtime/src/platform/capabilities.ts b/packages/client-runtime/src/platform/capabilities.ts index f05c835dda290..f58e3e9fa1008 100644 --- a/packages/client-runtime/src/platform/capabilities.ts +++ b/packages/client-runtime/src/platform/capabilities.ts @@ -3,6 +3,7 @@ import { type DesktopSshEnvironmentBootstrap, type DesktopSshEnvironmentTarget, EnvironmentId, + type ExecutionEnvironmentDescriptor, } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -13,6 +14,8 @@ import type { ConnectionAttemptError } from "../connection/model.ts"; export interface PreparedSshEnvironment { readonly bootstrap: DesktopSshEnvironmentBootstrap; readonly bearerToken: string; + /** What the forwarded endpoint just answered, so authorizing need not ask again. */ + readonly descriptor?: ExecutionEnvironmentDescriptor; } export interface ProvisionedSshEnvironment extends PreparedSshEnvironment {