diff --git a/apps/web/src/components/ServerUpdateAction.tsx b/apps/web/src/components/ServerUpdateAction.tsx index 14e0dd3c192cb..6cfe7a326a2ef 100644 --- a/apps/web/src/components/ServerUpdateAction.tsx +++ b/apps/web/src/components/ServerUpdateAction.tsx @@ -31,7 +31,7 @@ import { useServerConfigs } from "~/state/entities"; import { useManagedPolicy } from "~/state/managedPolicy"; import { environmentPresentations } from "~/state/presentation"; import { ManagedControl } from "./ManagedPolicy"; -import { manualServerUpdateCommand } from "~/versionSkew"; +import { isAppStartedSshServer, manualServerUpdateCommand, sshRestartVersion } from "~/versionSkew"; import { crossesReleaseTrack } from "@t3tools/shared/cliRelease"; import { Button } from "./ui/button"; import { toastManager } from "./ui/toast"; @@ -96,6 +96,8 @@ export interface ServerUpdateTarget { readonly targetDatabaseMigration?: number; /** The host already runs its track's newest build and only saves the track. */ readonly trackOnly?: boolean; + /** This desktop app started the server over SSH and updates it by restarting it. */ + readonly restartSshServer?: boolean; } type UpdateButtonProps = Pick, "variant" | "size" | "className"> & { @@ -134,6 +136,7 @@ export function useServerUpdate() { pendingUpdateEnvironmentIds.add(environmentId); const result = await updateServer({ environmentId, + ...(target.restartSshServer === true ? { restartSshServer: true } : {}), input: { targetVersion, ...(target.channel === undefined ? {} : { channel: target.channel }), @@ -184,7 +187,7 @@ export function ServerUpdatesAction({ const [isPending, setIsPending] = useState(false); const eligible = targets.filter( (target) => - target.selfUpdate !== null && + (target.selfUpdate !== null || target.restartSshServer === true) && (target.selfUpdate !== "desktop-managed" || target.desktopAppUpdate) && managedUpdatesDenial(serverConfigs.get(target.environmentId)?.managedPolicy) === undefined && !refusedCrossing(target, serverConfigs.get(target.environmentId)?.environment.serverVersion), @@ -206,6 +209,14 @@ export function ServerUpdatesAction({ )) ?? true; if (!confirmed) return; } + const sshTargets = available.filter((target) => target.restartSshServer === true); + if (sshTargets.length > 0) { + const confirmed = + (await requestConfirmDialog(sshRestartConfirmation(sshTargets), { + initialFocus: "confirm", + })) ?? true; + if (!confirmed) return; + } await Promise.all(available.map((target) => update(target))); }); pending.current = false; @@ -224,6 +235,10 @@ export function ServerUpdatesAction({ ); } +function sshRestartConfirmation(targets: ReadonlyArray>) { + return `Restart T3 Code on ${targets.map((target) => target.serverLabel).join(", ")} to update? Agent turns running there will stop.`; +} + export function canUpdateServer( result: AsyncResult.AsyncResult, ): boolean { @@ -271,6 +286,9 @@ export function ServerUpdateAction({ appearance = "button", }: ServerUpdateTarget & UpdateButtonProps) { const isDesktopAppUpdate = selfUpdate === "desktop-managed"; + const presentation = useAtomValue(environmentPresentations.presentationAtom(environmentId)); + const restartSshServer = + presentation !== null && sshRestartVersion(presentation) === targetVersion; const serverVersion = useServerConfigs().get(environmentId)?.environment.serverVersion; const sessionStateAtom = environmentSession.sessionStateAtom(environmentId); const canUpdate = useAtomValue(sessionStateAtom, canUpdateServer); @@ -305,6 +323,13 @@ export function ServerUpdateAction({ ) { return; } + if (restartSshServer) { + const confirmed = + (await requestConfirmDialog(sshRestartConfirmation([{ serverLabel }]), { + initialFocus: "confirm", + })) ?? true; + if (!confirmed) return; + } if (isDesktopAppUpdate) { const confirmed = (await requestConfirmDialog( @@ -322,6 +347,7 @@ export function ServerUpdateAction({ selfUpdate, desktopAppUpdate, targetVersion, + restartSshServer, }); }; @@ -350,7 +376,9 @@ export function ServerUpdateAction({ } const manualCommand = - selfUpdate === null ? manualServerUpdateCommand(targetVersion, installation) : null; + selfUpdate === null && !restartSshServer + ? manualServerUpdateCommand(targetVersion, installation) + : null; const actionLabel = manualCommand !== null ? installation?.kind === "npm-global" @@ -412,8 +440,17 @@ export function OutdatedServerUpdateAction({ readonly label?: string; }) { const update = useAtomCommand(updateOutdatedServer, { reportFailure: false }); + const presentation = useAtomValue(environmentPresentations.presentationAtom(environmentId)); + const restartsSshServer = presentation !== null && isAppStartedSshServer(presentation.entry); const handleUpdate = async () => { if (pendingUpdateEnvironmentIds.has(environmentId)) return; + if (restartsSshServer) { + const confirmed = + (await requestConfirmDialog(sshRestartConfirmation([{ serverLabel }]), { + initialFocus: "confirm", + })) ?? true; + if (!confirmed || pendingUpdateEnvironmentIds.has(environmentId)) return; + } pendingUpdateEnvironmentIds.add(environmentId); const result = await update({ environmentId, diff --git a/apps/web/src/components/chat/useAutoBalanceUpdateBanner.tsx b/apps/web/src/components/chat/useAutoBalanceUpdateBanner.tsx index 60f93aa54b965..64791d42181a1 100644 --- a/apps/web/src/components/chat/useAutoBalanceUpdateBanner.tsx +++ b/apps/web/src/components/chat/useAutoBalanceUpdateBanner.tsx @@ -13,6 +13,7 @@ import { isVersionMismatchDismissed, resolveServerConfigVersionMismatch, resolveServerSelfUpdateCapability, + sshRestartVersion, supportsDesktopAppUpdate, } from "~/versionSkew"; import { @@ -55,6 +56,8 @@ export function useAutoBalanceUpdateBanner( return []; const selfUpdate = resolveServerSelfUpdateCapability(environment.serverConfig); const desktopAppUpdate = supportsDesktopAppUpdate(environment.serverConfig); + const targetVersion = state.status === "idle" ? mismatch!.clientVersion : state.targetVersion; + const restartSshServer = sshRestartVersion(environment) === targetVersion; return [ { environmentId: environment.environmentId, @@ -62,9 +65,12 @@ export function useAutoBalanceUpdateBanner( selfUpdate, installation: environment.serverConfig?.environment.capabilities.serverInstallation, desktopAppUpdate, - targetVersion: state.status === "idle" ? mismatch!.clientVersion : state.targetVersion, + targetVersion, + restartSshServer, connected: environment.connection.phase === "connected", - remoteUpdate: selfUpdate !== null && (selfUpdate !== "desktop-managed" || desktopAppUpdate), + remoteUpdate: + restartSshServer || + (selfUpdate !== null && (selfUpdate !== "desktop-managed" || desktopAppUpdate)), state, dismissKey, }, diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index da46823292cad..30820a9d0f5f3 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -81,6 +81,7 @@ import { useUiStateStore } from "~/uiStateStore"; import { resolveServerConfigVersionMismatch, resolveServerSelfUpdateCapability, + sshRestartVersion, supportsDesktopAppUpdate, } from "~/versionSkew"; import { hasCloudPublicConfig } from "~/cloud/publicConfig"; @@ -281,13 +282,15 @@ function ConnectionsSettingsContent({ const mismatch = resolveServerConfigVersionMismatch(environment.serverConfig); const selfUpdate = resolveServerSelfUpdateCapability(environment.serverConfig); const desktopAppUpdate = supportsDesktopAppUpdate(environment.serverConfig); + const restartSshServer = + mismatch !== null && sshRestartVersion(environment) === mismatch.clientVersion; if ( !mismatch || updateStatus === "running" || !environment.entry.enabled || environment.connection.phase !== "connected" || isDesktopLocalConnectionTarget(environment.entry.target) || - selfUpdate === null || + (selfUpdate === null && !restartSshServer) || (selfUpdate === "desktop-managed" && !desktopAppUpdate) ) { return []; @@ -300,6 +303,7 @@ function ConnectionsSettingsContent({ installation: environment.serverConfig?.environment.capabilities.serverInstallation, desktopAppUpdate, targetVersion: mismatch.clientVersion, + restartSshServer, }, ]; }, diff --git a/apps/web/src/components/sidebar/updateEverything.logic.test.ts b/apps/web/src/components/sidebar/updateEverything.logic.test.ts index 58328dbc1eeeb..eaec781e8a155 100644 --- a/apps/web/src/components/sidebar/updateEverything.logic.test.ts +++ b/apps/web/src/components/sidebar/updateEverything.logic.test.ts @@ -67,13 +67,19 @@ describe("collectServerUpdateTargets", () => { machine("current", "0.0.50", "boot-service"), machine("current-offline", "0.0.50", "boot-service", { connected: false }), machine("manual", "0.0.40", undefined), + machine("ssh", "0.0.40", undefined, { sshRestartVersion: "0.0.50" }), + // This app has not restarted on 0.0.50 yet, so a restart would start 0.0.49. + machine("ssh-before-app", "0.0.40", undefined, { sshRestartVersion: "0.0.49" }), ], "0.0.50", ); - expect(targets.map((target) => [target.serverLabel, target.targetVersion])).toEqual([ - ["service", "0.0.50"], - ["other-desktop", "0.0.50"], + expect( + targets.map((target) => [target.serverLabel, target.targetVersion, target.restartSshServer]), + ).toEqual([ + ["service", "0.0.50", undefined], + ["other-desktop", "0.0.50", undefined], + ["ssh", "0.0.50", true], ]); expect(skipped.map((entry) => [entry.label, entry.reason])).toEqual([ ["nightly-service", "on the nightly channel"], @@ -82,6 +88,7 @@ describe("collectServerUpdateTargets", () => { ["no-scope", "no permission"], ["busy", "already updating"], ["manual", "needs a manual update"], + ["ssh-before-app", "updates after this app restarts"], ]); }); diff --git a/apps/web/src/components/sidebar/updateEverything.logic.ts b/apps/web/src/components/sidebar/updateEverything.logic.ts index cbbd3baa7c776..dd1367e1b2546 100644 --- a/apps/web/src/components/sidebar/updateEverything.logic.ts +++ b/apps/web/src/components/sidebar/updateEverything.logic.ts @@ -27,6 +27,8 @@ export interface UpdateEverythingMachine { } | null; readonly connected: boolean; readonly hostedByThisApp: boolean; + /** Set when this app started the server over SSH: the version restarting it starts. */ + readonly sshRestartVersion?: string | null; readonly canMaintain: boolean; readonly updateState: ServerUpdateState; } @@ -104,6 +106,22 @@ export function collectServerUpdateTargets( continue; } const desktopAppUpdate = supportsDesktopAppUpdate(config); + if (selfUpdate === null && machine.sshRestartVersion != null) { + // The restart starts this app's own version, so a pending app update comes first. + if (machine.sshRestartVersion !== targetVersion) { + skip("updates after this app restarts"); + continue; + } + targets.push({ + environmentId: machine.environmentId, + serverLabel: machine.label, + selfUpdate, + desktopAppUpdate, + targetVersion, + restartSshServer: true, + }); + continue; + } if (selfUpdate === null) { skip("needs a manual update"); continue; diff --git a/apps/web/src/components/sidebar/useUpdateEverything.ts b/apps/web/src/components/sidebar/useUpdateEverything.ts index 05127d9885768..414f49fd4d96f 100644 --- a/apps/web/src/components/sidebar/useUpdateEverything.ts +++ b/apps/web/src/components/sidebar/useUpdateEverything.ts @@ -8,6 +8,7 @@ import { useEnvironments } from "~/state/environments"; import { environmentIdsKey } from "~/state/environmentAtomList"; import { environmentUpdateStatesAtom } from "~/state/server"; import { environmentSessionStatesAtom } from "~/state/session"; +import { sshRestartVersion } from "~/versionSkew"; import { getProviderUpdateRunOutcome } from "../ProviderUpdateLaunchNotification.logic"; import { useProviderUpdates } from "../ProviderUpdatesAction"; import { canUpdateServer, type ServerUpdateOutcome, useServerUpdate } from "../ServerUpdateAction"; @@ -63,6 +64,7 @@ export function useUpdateEverything( serverConfig: environment.serverConfig, connected: environment.connection.phase === "connected", hostedByThisApp: isHostedByThisApp(environment), + sshRestartVersion: sshRestartVersion(environment), canMaintain: canUpdateServer(sessionStates[index]!), updateState: updateStates[index]!, })); diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts index dcd50342f1c91..97958bde7f749 100644 --- a/apps/web/src/connection/platform.ts +++ b/apps/web/src/connection/platform.ts @@ -248,7 +248,12 @@ export const provisionDesktopSshEnvironment = Effect.fn( } return new ConnectionBlockedError({ reason: "configuration", - detail: `${descriptor.label} runs T3 Code ${descriptor.serverVersion}, but this desktop is ${APP_VERSION}, and that server could not accept its pairing. Restart the T3 server on ${descriptor.label} so it runs ${APP_VERSION}, then retry.`, + detail: `${descriptor.label} runs T3 Code ${descriptor.serverVersion}, but this desktop is ${APP_VERSION}, and that server could not accept its pairing. ${ + bootstrap.remoteServerKind === "managed" + ? // Without a session the Update button is unavailable; switching off stops the server. + `Switch ${descriptor.label} off and on in Settings → Connections to restart it on ${APP_VERSION}.` + : `Restart the T3 server on ${descriptor.label} so it runs ${APP_VERSION}, then retry.` + }`, }); }, }); diff --git a/apps/web/src/versionSkew.ts b/apps/web/src/versionSkew.ts index 321e712f8a124..e0514c9d76204 100644 --- a/apps/web/src/versionSkew.ts +++ b/apps/web/src/versionSkew.ts @@ -4,11 +4,14 @@ import type { ServerInstallation, ServerSelfUpdateCapability, } from "@t3tools/contracts"; +import type { EnvironmentPresentation } from "@t3tools/client-runtime/connection"; import type { ServerUpdateState } from "@t3tools/client-runtime/state/server"; import { compareSemverVersions, parseSemver } from "@t3tools/shared/semver"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { APP_VERSION } from "./branding"; +import { isElectron } from "./env"; import { getLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorage"; export interface VersionMismatch { @@ -89,6 +92,25 @@ export function resolveServerSelfUpdateCapability( return serverConfig?.environment.capabilities.serverSelfUpdate ?? null; } +/** Whether this desktop app started the environment's server over SSH and can restart it. */ +export function isAppStartedSshServer(entry: Pick) { + const profile = Option.getOrNull(entry.profile); + return ( + isElectron && profile?._tag === "SshConnectionProfile" && profile.remoteServerKind === "managed" + ); +} + +/** The version a restart starts on a server this desktop app started over SSH, which reports no + * self-update of its own. Other servers keep their own update guidance. */ +export function sshRestartVersion( + environment: Pick, +): string | null { + return resolveServerSelfUpdateCapability(environment.serverConfig) === null && + isAppStartedSshServer(environment.entry) + ? APP_VERSION + : null; +} + export function supportsDesktopAppUpdate( serverConfig: Pick | null | undefined, ): boolean { diff --git a/docs/internals/remote.md b/docs/internals/remote.md index 4a348382ac47b..1c15c1c16e55b 100644 --- a/docs/internals/remote.md +++ b/docs/internals/remote.md @@ -168,10 +168,13 @@ every route. See [environment authentication](./environment-auth.md) and the SSH can launch a server as well as forward a port. Desktop main owns that lifecycle because it can spawn SSH and handle authentication prompts. The renderer uses the forwarded endpoint through the shared connection runtime. -[SSH cleanup](../../packages/ssh/src/tunnel.ts) stops a remote server only if the -launcher owns it; a server it discovered already running must survive a client -disconnect. Reconnection restores the forward before opening the application -transport. +[SSH cleanup](../../packages/ssh/src/tunnel.ts) stops a remote server only on an +explicit disconnect (removing or switching off the environment, or updating it) +and only if the launcher owns it; a server it discovered already running must +survive a client disconnect. Quitting the app or reconnecting with a newer +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. 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/docs/user/remote-access.md b/docs/user/remote-access.md index 9635a8af2a0a7..7dc464e7da01f 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -223,9 +223,12 @@ check with: ssh user@example.com 'sh -lc "command -v claude codex"' ``` -If SSH reconnecting fails after an app update, retry the launch once. Removing -the connection stops a server that T3 Code launched; a server that was already -running is left alone. +A server T3 Code launched keeps running when you quit the app, so agent work +continues, and reconnecting picks it up again. After an app update it stays on +its old version until you choose **Update**, which restarts it on the app's +version and stops any agent turns running there. Removing the connection or +switching the environment off stops a server that T3 Code launched; a server +that was already running is left alone. 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 → diff --git a/packages/client-runtime/src/connection/catalog.ts b/packages/client-runtime/src/connection/catalog.ts index 17065b8a4862c..4381165334ce3 100644 --- a/packages/client-runtime/src/connection/catalog.ts +++ b/packages/client-runtime/src/connection/catalog.ts @@ -37,6 +37,8 @@ export class SshConnectionProfile extends Schema.TaggedClass { }), ); + it.effect.each([ + { started: true, outcome: "restarts it on the app's version" }, + { started: false, outcome: "asks for a manual update" }, + ])("for an SSH server this app started=$started, $outcome", ({ started }) => + Effect.gen(function* () { + const sshTarget = new SshConnectionTarget({ + environmentId: TARGET.environmentId, + label: TARGET.label, + connectionId: "ssh-old", + }); + // An SSH-launched server reports no self-update; protocol 1 is refused. + const sshDescriptor = (protocol: number | undefined, serverVersion: string) => ({ + ...descriptor(protocol, serverVersion), + capabilities: { repositoryIdentity: true }, + }); + const calls: string[] = []; + const result = yield* Effect.result( + updateOutdatedHost(TARGET.environmentId, { targetVersion: "0.0.46" }, () => Effect.void), + ).pipe( + Effect.provide( + Layer.mergeAll( + Layer.succeed( + EnvironmentRegistry.EnvironmentRegistry, + EnvironmentRegistry.EnvironmentRegistry.of({ + entries: yield* SubscriptionRef.make< + ReadonlyMap + >( + new Map([ + [ + TARGET.environmentId, + { target: sshTarget, profile: Option.none(), enabled: false }, + ], + ]), + ), + restartSshServer: () => + started + ? Effect.sync(() => calls.push("restart")) + : Effect.fail( + new ConnectionBlockedError({ reason: "unsupported", detail: "external" }), + ), + setCompatibility: () => Effect.sync(() => calls.push("compatible")), + setEnabled: () => Effect.sync(() => calls.push("enabled")), + } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]), + ), + Layer.succeed( + ConnectionResolver.ConnectionResolver, + ConnectionResolver.ConnectionResolver.of({ + prepare: () => Effect.die(new Error("unused")), + prepareForUpdate: () => + Effect.sync(() => ({ + // The restarted server comes back on the app's version. + descriptor: calls.includes("restart") + ? sshDescriptor(ORCHESTRATION_PROTOCOL_VERSION, "0.0.46") + : sshDescriptor(undefined, "0.0.45"), + prepared: { + environmentId: TARGET.environmentId, + label: TARGET.label, + httpBaseUrl: "http://127.0.0.1:4010", + socketUrl: "ws://127.0.0.1:4010/ws", + httpAuthorization: null, + target: sshTarget, + }, + })), + }), + ), + Layer.succeed( + RelayEnvironmentDiscovery.RelayEnvironmentDiscovery, + RelayEnvironmentDiscovery.RelayEnvironmentDiscovery.of({ + state: yield* SubscriptionRef.make( + RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE, + ), + refresh: Effect.void, + }), + ), + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die(new Error("unused"))), + ), + Layer.succeed(Socket.WebSocketConstructor, () => { + throw new Error("An SSH restart opens no bare socket."); + }), + ), + ), + ); + if (started) { + expect(result).toMatchObject({ _tag: "Success", success: { targetVersion: "0.0.46" } }); + expect(calls).toEqual(["restart", "compatible", "enabled"]); + } else { + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + _tag: "OutdatedHostUpdateError", + message: expect.stringContaining("manually"), + }, + }); + expect(calls).toEqual([]); + } + }), + ); + it.effect("resumes an outdated host update after progress transport loss", () => Effect.gen(function* () { const blocked = orchestrationProtocolCompatibilityError(descriptor(undefined, "0.0.45")); diff --git a/packages/client-runtime/src/connection/outdatedHostUpdate.ts b/packages/client-runtime/src/connection/outdatedHostUpdate.ts index d702e1f6b057f..7b0ea1af1809a 100644 --- a/packages/client-runtime/src/connection/outdatedHostUpdate.ts +++ b/packages/client-runtime/src/connection/outdatedHostUpdate.ts @@ -101,6 +101,36 @@ export const updateOutdatedHost = Effect.fn("clientRuntime.connection.updateOutd } const capabilities = descriptor.capabilities; + // A server this desktop app started over SSH updates by restarting it on the + // app's version: stop it, then the next connect launches the new one. + if ( + capabilities.serverSelfUpdate === undefined && + entry.target._tag === "SshConnectionTarget" + ) { + yield* onStage("resuming"); + yield* registry.restartSshServer(environmentId).pipe( + Effect.mapError( + (error) => + new OutdatedHostUpdateError({ + environmentId, + message: + error._tag === "ConnectionBlockedError" && error.reason === "unsupported" + ? `Update T3 Code on ${descriptor.label} manually; this app did not start it.` + : error.message, + }), + ), + ); + const restarted = (yield* reachOutdatedHost(environmentId)).descriptor; + if (!isCompatibleDescriptor(restarted)) { + return yield* new OutdatedHostUpdateError({ + environmentId, + message: `${descriptor.label} restarted on T3 Code ${restarted.serverVersion}, which this app cannot use.`, + }); + } + yield* switchBackOn; + return { targetVersion: restarted.serverVersion }; + } + if ( capabilities.serverSelfUpdate === undefined || (capabilities.serverSelfUpdate === "desktop-managed" && diff --git a/packages/client-runtime/src/connection/registry.test.ts b/packages/client-runtime/src/connection/registry.test.ts index f6c305ab6bb90..175dd5187ab73 100644 --- a/packages/client-runtime/src/connection/registry.test.ts +++ b/packages/client-runtime/src/connection/registry.test.ts @@ -136,6 +136,23 @@ const SSH_PROFILE = new SshConnectionProfile({ target: SSH_TARGET, }); +const saveSshServerKind = ( + harness: { readonly storedProfiles: Ref.Ref> }, + remoteServerKind: "external" | "managed", +) => + Ref.update(harness.storedProfiles, (current) => + new Map(current).set( + SSH_CONNECTION.connectionId, + new SshConnectionProfile({ + connectionId: SSH_PROFILE.connectionId, + environmentId: SSH_PROFILE.environmentId, + label: SSH_PROFILE.label, + target: SSH_PROFILE.target, + remoteServerKind, + }), + ), + ); + const CACHED_SNAPSHOT: OrchestrationV2ShellSnapshot = { ...v2ShellSnapshot, snapshotSequence: 1, @@ -1217,6 +1234,71 @@ describe("EnvironmentRegistry", () => { }), ); + it.effect("restarts only an SSH server this app started and keeps the environment on", () => + Effect.gen(function* () { + const harness = yield* makeHarness([SSH_CONNECTION, RELAY_TARGET], [SSH_PROFILE]); + + yield* Effect.gen(function* () { + const registry = yield* EnvironmentRegistry.EnvironmentRegistry; + yield* registry.start; + yield* awaitConnectionState( + registry, + SSH_CONNECTION.environmentId, + (state) => state.phase === "connected", + ); + + // Each connect saves the kind of server it reached. + yield* saveSshServerKind(harness, "external"); + const external = yield* Effect.flip( + registry.restartSshServer(SSH_CONNECTION.environmentId), + ); + expect(external._tag).toBe("ConnectionBlockedError"); + expect(yield* Ref.get(harness.disconnectedSshTargets)).toEqual([]); + + yield* saveSshServerKind(harness, "managed"); + yield* registry.restartSshServer(SSH_CONNECTION.environmentId); + expect(yield* Ref.get(harness.disconnectedSshTargets)).toEqual([SSH_TARGET]); + const entry = (yield* SubscriptionRef.get(registry.entries)).get( + SSH_CONNECTION.environmentId, + ); + expect(entry?.enabled).toBe(true); + + const relay = yield* Effect.flip(registry.restartSshServer(RELAY_TARGET.environmentId)); + expect(relay._tag).toBe("ConnectionBlockedError"); + expect(yield* Ref.get(harness.disconnectedSshTargets)).toEqual([SSH_TARGET]); + }).pipe(Effect.provide(harness.layer)); + }), + ); + + it.effect("shows the SSH server kind a connect saved", () => + Effect.gen(function* () { + const harness = yield* makeHarness([SSH_CONNECTION], [SSH_PROFILE]); + + yield* Effect.gen(function* () { + const registry = yield* EnvironmentRegistry.EnvironmentRegistry; + yield* registry.start; + yield* awaitConnectionState( + registry, + SSH_CONNECTION.environmentId, + (state) => state.phase === "connected", + ); + yield* saveSshServerKind(harness, "managed"); + yield* registry.setEnabled(SSH_CONNECTION.environmentId, false); + yield* registry.setEnabled(SSH_CONNECTION.environmentId, true); + + const shown = yield* SubscriptionRef.changes(registry.entries).pipe( + Stream.map((entries) => { + const profile = Option.getOrNull(entries.get(SSH_CONNECTION.environmentId)!.profile); + return profile?._tag === "SshConnectionProfile" ? profile.remoteServerKind : undefined; + }), + Stream.filter((kind) => kind !== undefined), + Stream.runHead, + ); + expect(Option.getOrNull(shown)).toBe("managed"); + }).pipe(Effect.provide(harness.layer)); + }), + ); + it.effect("moves durable streams to a replacement supervisor", () => Effect.gen(function* () { const replacement = new RelayConnectionTarget({ diff --git a/packages/client-runtime/src/connection/registry.ts b/packages/client-runtime/src/connection/registry.ts index 12f8aa5ec505f..394a23f14e83e 100644 --- a/packages/client-runtime/src/connection/registry.ts +++ b/packages/client-runtime/src/connection/registry.ts @@ -158,6 +158,13 @@ export class EnvironmentRegistry extends Context.Service< | PlatformEnvironmentRemovalError >; readonly retryNow: (environmentId: EnvironmentId) => Effect.Effect; + /** + * Stops the server a desktop app started over SSH, then reconnects, which + * starts this client's version. Agent turns running there stop. + */ + readonly restartSshServer: ( + environmentId: EnvironmentId, + ) => Effect.Effect; readonly setEnabled: ( environmentId: EnvironmentId, enabled: boolean, @@ -381,11 +388,14 @@ export const make = Effect.gen(function* () { return next; }); yield* SubscriptionRef.changes(supervisor.state).pipe( - Stream.runForEach((state) => - state.phase === "blocked" && state.lastFailure?.reason === "unsupported" - ? setCompatibility(environmentId, state.lastFailure) - : Effect.void, - ), + Stream.runForEach((state) => { + if (state.phase === "blocked" && state.lastFailure?.reason === "unsupported") { + return setCompatibility(environmentId, state.lastFailure).pipe( + Effect.andThen(refreshSshProfile(environmentId)), + ); + } + return state.phase === "connected" ? refreshSshProfile(environmentId) : Effect.void; + }), Effect.forkIn(scope), ); return supervisor; @@ -393,6 +403,50 @@ export const make = Effect.gen(function* () { ), ); + const savedSshProfile = (entry: ConnectionCatalogEntry) => + entry.target._tag !== "SshConnectionTarget" + ? Effect.succeed(null) + : profiles.get(entry.target.connectionId).pipe( + Effect.map((saved) => { + const profile = Option.getOrNull(saved); + return profile !== null && isSshConnectionProfile(profile) ? profile : null; + }), + Effect.orElseSucceed(() => null), + ); + + /** + * Each SSH connect saves which kind of server it reached. Show it without + * replacing the supervisor, which `installEntryLocked` would tear down. + */ + const refreshSshProfile = (environmentId: EnvironmentId) => + withLeaseLock( + environmentId, + Effect.gen(function* () { + const entry = (yield* SubscriptionRef.get(entries)).get(environmentId); + if (entry === undefined) return; + const current = Option.getOrNull(entry.profile); + const saved = yield* savedSshProfile(entry); + if ( + saved === null || + current === null || + !isSshConnectionProfile(current) || + saved.remoteServerKind === current.remoteServerKind + ) { + return; + } + const next: ConnectionCatalogEntry = { ...entry, profile: Option.some(saved) }; + const lease = (yield* SubscriptionRef.get(serviceScopes)).get(environmentId); + if (lease !== undefined) { + yield* SubscriptionRef.update(serviceScopes, (scopes) => + new Map(scopes).set(environmentId, { ...lease, entry: next }), + ); + } + yield* SubscriptionRef.update(entries, (current) => + new Map(current).set(environmentId, next), + ); + }), + ).pipe(Effect.withSpan("EnvironmentRegistry.refreshSshProfile")); + const acquireSupervisor = Effect.fn("EnvironmentRegistry.acquireSupervisor")(function* ( environmentId: EnvironmentId, ) { @@ -1053,6 +1107,24 @@ export const make = Effect.gen(function* () { Effect.catchTags({ EnvironmentNotRegisteredError: () => Effect.void }), Effect.withSpan("EnvironmentRegistry.retryNow"), ); + const restartSshServer = Effect.fn("EnvironmentRegistry.restartSshServer")(function* ( + environmentId: EnvironmentId, + ) { + yield* withLeaseLock( + environmentId, + Effect.gen(function* () { + const profile = yield* savedSshProfile(yield* getEntry(environmentId)); + if (profile?.remoteServerKind !== "managed") { + return yield* new ConnectionBlockedError({ + reason: "unsupported", + detail: "This app did not start T3 Code on that machine, so it cannot restart it.", + }); + } + yield* ssh.disconnect(profile.target); + }), + ); + yield* retryNow(environmentId); + }); const setEnabled = Effect.fn("EnvironmentRegistry.setEnabled")(function* ( environmentId: EnvironmentId, enabled: boolean, @@ -1195,6 +1267,7 @@ export const make = Effect.gen(function* () { reorderRoutes, removeRelayEnvironments, retryNow, + restartSshServer, setEnabled, setCompatibility, state, diff --git a/packages/client-runtime/src/connection/resolver.test.ts b/packages/client-runtime/src/connection/resolver.test.ts index 62d43bbbe641a..d4eeeb06a827f 100644 --- a/packages/client-runtime/src/connection/resolver.test.ts +++ b/packages/client-runtime/src/connection/resolver.test.ts @@ -310,6 +310,7 @@ describe("ConnectionResolver", () => { httpBaseUrl: "http://127.0.0.1:4010", wsBaseUrl: "ws://127.0.0.1:4010", pairingToken: null, + remoteServerKind: "managed", }, bearerToken: "ssh-bearer", }), @@ -337,7 +338,11 @@ describe("ConnectionResolver", () => { expect(calls).toEqual(["revoke"]); } else { expect((yield* prepare).socketUrl).toContain("wsTicket=ssh"); - expect(savedProfile).toMatchObject({ target: preparedTarget }); + // The Update action restarts only servers this app started. + expect(savedProfile).toMatchObject({ + target: preparedTarget, + remoteServerKind: "managed", + }); expect(calls).toEqual( scenario === "unchanged" ? ["profile", "authorize"] diff --git a/packages/client-runtime/src/connection/resolver.ts b/packages/client-runtime/src/connection/resolver.ts index d3b22143d327a..eded482a94d9f 100644 --- a/packages/client-runtime/src/connection/resolver.ts +++ b/packages/client-runtime/src/connection/resolver.ts @@ -240,6 +240,9 @@ const makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(funct environmentId: profile.environmentId, label: profile.label, target: prepared.bootstrap.target, + ...(prepared.bootstrap.remoteServerKind === undefined + ? {} + : { remoteServerKind: prepared.bootstrap.remoteServerKind }), }); if ( pullRequestRoutingConnectionKey(entry) !== diff --git a/packages/client-runtime/src/state/server.test.ts b/packages/client-runtime/src/state/server.test.ts index f3c282d8bd312..06d26e1d7f7e4 100644 --- a/packages/client-runtime/src/state/server.test.ts +++ b/packages/client-runtime/src/state/server.test.ts @@ -384,6 +384,91 @@ describe("accepted server update recovery", () => { ); }); +describe("SSH server restart update", () => { + it.effect.each([ + { restartedVersion: "0.0.31", updated: true }, + // A server the desktop app did not start keeps running its own version. + { restartedVersion: "0.0.30", updated: false }, + ] as const)("restarts and reports $restartedVersion", ({ restartedVersion, updated }) => + Effect.gen(function* () { + const ready = (serverVersion: string) => + ({ + version: 1, + sequence: 1, + type: "ready", + payload: { at: "2026-09-01T00:00:00.000Z", environment: { serverVersion } }, + }) as Parameters[1]; + // Each session replays its server's ready snapshot, as the lifecycle stream does. + const sessionOn = (serverVersion: string) => + session({ + [WS_METHODS.subscribeServerConfig]: () => Stream.never, + [WS_METHODS.subscribeServerLifecycle]: () => + Stream.make(ready(serverVersion)).pipe(Stream.concat(Stream.never)), + } as unknown as WsRpcProtocolClient); + const restarts = yield* Ref.make(0); + const config = { + ...CONFIG, + environment: { ...CONFIG.environment, serverVersion: "0.0.30", capabilities: {} }, + } as ServerConfig; + const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ + target: TARGET, + state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE), + session: yield* SubscriptionRef.make(Option.some(sessionOn("0.0.30"))), + prepared: yield* SubscriptionRef.make(Option.none()), + connect: Effect.void, + disconnect: Effect.void, + retryNow: Effect.void, + }); + const runStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["runStream"] = ( + _id, + stream, + ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor); + const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({ + followStream: runStream, + stateChanges: () => Stream.never, + retryNow: () => Effect.void, + // The old server is gone once this returns; the reconnect reaches the restarted one. + restartSshServer: () => + Ref.update(restarts, (count) => count + 1).pipe( + Effect.andThen( + SubscriptionRef.set(supervisor.session, Option.some(sessionOn(restartedVersion))), + ), + ), + } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]); + const runtime = Atom.runtime( + Layer.mergeAll( + Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), + Layer.succeed(RpcPermissionGuard, { authorize: () => Effect.void }), + Layer.succeed(Persistence.EnvironmentCacheStore, { + loadServerConfig: () => Effect.succeedNone, + } as unknown as Persistence.EnvironmentCacheStore["Service"]), + ), + ); + const atoms = createServerEnvironmentAtoms(runtime, { + initialConfigValueAtom: () => Atom.make(config), + }); + const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (value) => + Effect.sync(() => value.dispose()), + ); + const result = yield* Effect.promise(() => + atoms.updateServer.run(registry, { + environmentId: TARGET.environmentId, + input: { targetVersion: "0.0.31" }, + restartSshServer: true, + }), + ); + + expect(yield* Ref.get(restarts)).toBe(1); + expect(AsyncResult.isSuccess(result)).toBe(updated); + expect(registry.get(serverUpdateStateAtom(TARGET.environmentId))).toMatchObject( + updated + ? { status: "idle" } + : { status: "failed", message: expect.stringContaining("still on t3@0.0.30") }, + ); + }).pipe(Effect.scoped), + ); +}); + const makeConfigPersistenceHarness = Effect.fn("test.makeConfigPersistenceHarness")(function* ( saveServerConfig: Persistence.EnvironmentCacheStore["Service"]["saveServerConfig"], ) { diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 6b757ba8d15cf..b198764c9efeb 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -83,6 +83,8 @@ export type ServerUpdateState = export interface ServerUpdateTarget { readonly environmentId: EnvironmentId; readonly input: EnvironmentRpcInput; + /** This desktop app started the server over SSH; a restart starts the app's own version. */ + readonly restartSshServer?: boolean; } const IDLE_SERVER_UPDATE_STATE: ServerUpdateState = { status: "idle" }; @@ -154,6 +156,23 @@ export function matchesServerUpdateResumeEvent( ); } +/** A server this app did not start survives the SSH restart on its old version. */ +function validateSshRestartReadyEvent( + targetVersion: string, + event: ServerLifecycleStreamReadyEvent, +): Effect.Effect { + const serverVersion = event.payload.environment.serverVersion; + return serverVersion === targetVersion + ? Effect.void + : Effect.fail( + new ServerUpdateTerminalError({ + targetVersion, + status: "failed", + reason: `The server is still on t3@${serverVersion} because this app did not start it. Update it on that machine.`, + }), + ); +} + export function validateServerUpdateReadyEvent( result: ServerSelfUpdateResult, event: ServerLifecycleStreamReadyEvent, @@ -886,6 +905,18 @@ export function createServerEnvironmentAtoms( targetVersion, }); + if (target.restartSshServer === true) { + currentStage = "resuming"; + atomRegistry.set(stateAtom, { + status: "running", + stage: currentStage, + fromVersion, + targetVersion, + }); + yield* environmentRegistry.restartSshServer(target.environmentId); + return { targetVersion, method: "respawn" } satisfies ServerSelfUpdateResult; + } + const supportsProgress = currentConfig?.environment.capabilities.serverSelfUpdateProgress === true; const updateResult: ServerSelfUpdateResult = supportsProgress @@ -1014,7 +1045,9 @@ export function createServerEnvironmentAtoms( .pipe( Stream.filter( (event): event is ServerLifecycleStreamReadyEvent => - event.type === "ready" && matchesServerUpdateResumeEvent(result, event), + event.type === "ready" && + // The stopped server sends nothing more, so the first ready names the restart's version. + (target.restartSshServer === true || matchesServerUpdateResumeEvent(result, event)), ), Stream.runHead, Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT), @@ -1051,7 +1084,9 @@ export function createServerEnvironmentAtoms( ), ) : yield* nextReady; - yield* validateServerUpdateReadyEvent(result, resumed); + yield* target.restartSshServer === true + ? validateSshRestartReadyEvent(targetVersion, resumed) + : validateServerUpdateReadyEvent(result, resumed); atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE); return result; diff --git a/packages/client-runtime/src/state/threads-atoms.test.ts b/packages/client-runtime/src/state/threads-atoms.test.ts index 460f7e593990a..e0bca00f044ad 100644 --- a/packages/client-runtime/src/state/threads-atoms.test.ts +++ b/packages/client-runtime/src/state/threads-atoms.test.ts @@ -139,6 +139,7 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options? reorderRoutes: () => Effect.die("Unexpected route reorder"), removeRelayEnvironments: () => Effect.die("Unexpected environment removal"), retryNow: () => Effect.void, + restartSshServer: () => Effect.die("Unexpected SSH restart"), setEnabled: () => Effect.die("Unexpected environment toggle"), setCompatibility: () => Effect.die("Unexpected compatibility update"), state: () => SubscriptionRef.get(supervisor.state), diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index e0458e7675fd3..c3438050346bc 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -133,6 +133,74 @@ const serve = (tries) => { serve(40); `; +// A release archive's `t3` installed in its runtime directory, named by its version. +const fakeT3Runtime = `#!/usr/bin/env node +const fs = require("node:fs"); +const http = require("node:http"); +const net = require("node:net"); +const path = require("node:path"); +const version = path.basename(__dirname); +const [command, ...args] = process.argv.slice(2); +const option = (name) => args[args.indexOf(name) + 1]; +if (command === "--version") { + console.log(version); +} else if (command === "auth") { + console.log(JSON.stringify({ credential: "paired-by-" + version })); +} else if (command === "__ssh-helper" && args[0] === "pick-port") { + const server = net.createServer().listen(0, "127.0.0.1", () => { + process.stdout.write(String(server.address().port)); + server.close(); + }); +} else if (command === "__ssh-helper" && args[0] === "wait-ready") { + const deadline = Date.now() + Number(args[2]); + const probe = () => + http + .get({ host: "127.0.0.1", port: Number(args[1]), path: "/" }, (response) => { + response.resume(); + process.exit(0); + }) + .on("error", () => (Date.now() < deadline ? setTimeout(probe, 50) : process.exit(1))); + probe(); +} else if (command === "__ssh-helper" && args[0] === "runtime-port") { + try { + const runtime = JSON.parse(fs.readFileSync(args[1], "utf8")); + process.kill(runtime.pid, 0); + process.stdout.write(runtime.pid + " " + runtime.port); + } catch { + process.exit(1); + } +} else if (command === "serve") { + const port = Number(option("--port")); + const userdata = path.join(option("--base-dir"), "userdata"); + fs.mkdirSync(userdata, { recursive: true }); + fs.appendFileSync(path.join(process.env.HOME, "servers"), process.pid + "\\n"); + setTimeout(() => process.exit(0), 60_000); + http.createServer((_, response) => response.end()).listen(port, "127.0.0.1", () => { + const runtime = { pid: process.pid, port, origin: "http://127.0.0.1:" + port, serverVersion: version }; + fs.writeFileSync(path.join(userdata, "server-runtime.json"), JSON.stringify(runtime)); + }); +} else { + process.exit(2); +} +`; + +const isAlive = (pid: number) => { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +}; + +const killAll = (pids: ReadonlyArray) => { + for (const pid of pids) { + try { + process.kill(pid, "SIGKILL"); + } catch {} + } +}; + // Runs the remote half of an SSH command (`sh -l -s -- `) as a local shell // whose HOME is the given directory. Every launch after the first starts once // a server is running (or after 10s), which lines up the race deterministically. @@ -164,20 +232,35 @@ const localRemoteShellLayer = (home: string) => }), ); +const managerOnRemoteShell = (home: string) => + SshTunnel.SshEnvironmentManager.layer().pipe( + Layer.provideMerge( + Layer.mergeAll( + localRemoteShellLayer(home), + Layer.succeed(HttpClient.HttpClient, testHttpClient), + Layer.succeed(NetService.NetService, testNetService), + SshAuth.SshPasswordPrompt.disabledLayer, + ), + ), + ); + describe("ssh tunnel scripts", () => { it.effect("connects and reuses a healthy tunnel when HTTP replies take 2.5 seconds", () => Effect.gen(function* () { let tunnels = 0; let kills = 0; + let remoteStops = 0; const spawner = ChildProcessSpawner.make((command) => Effect.sync(() => { - if (commandArgs(command).includes("-N")) { + const args = commandArgs(command); + if (args.includes("-N")) { tunnels += 1; return makeRunningProcess(() => { kills += 1; }); } - return makeSuccessfulProcess('{"remotePort":3773}\n'); + if (args.at(-1) === "-s") remoteStops += 1; + return makeSuccessfulProcess('{"remotePort":3773,"serverKind":"managed"}\n'); }), ); const requests = yield* Queue.unbounded(); @@ -211,6 +294,9 @@ describe("ssh tunnel scripts", () => { assert.equal(tunnels, 1); assert.equal(kills, 0); }).pipe(Effect.provide(layer), Effect.scoped); + // Quitting the app closes the manager: it drops the tunnel but leaves agent work running. + assert.equal(kills, 1); + assert.equal(remoteStops, 0); }), ); @@ -254,7 +340,7 @@ describe("ssh tunnel scripts", () => { ); NodeFS.writeFileSync( NodePath.join(bin, "curl"), - "#!/bin/sh\necho 'download attempt' >&2\nexit 22\n", + '#!/bin/sh\necho "download attempt $*" >&2\nexit 22\n', { mode: 0o755 }, ); const runner = NodePath.join(root, "run-t3.sh"); @@ -266,6 +352,9 @@ describe("ssh tunnel scripts", () => { assert.notEqual(result.status, 0); if (downloads) { assert.include(result.stderr, "download attempt"); + // Slow links get no total deadline; only a stalled transfer fails. + assert.include(result.stderr, "--speed-limit 1024 --speed-time 60"); + assert.notInclude(result.stderr, "--max-time"); } else { assert.notInclude(result.stderr, "download attempt"); assert.include(result.stderr, "has no t3 release archive."); @@ -276,7 +365,7 @@ describe("ssh tunnel scripts", () => { }, ); - it.effect("accepts launch JSON after remote shell startup noise", () => { + it.effect("accepts launch JSON after a slow archive launch and remote shell noise", () => { const target = { alias: "devbox", hostname: "devbox.example.com", @@ -287,7 +376,13 @@ describe("ssh tunnel scripts", () => { const spawner = ChildProcessSpawner.make((command) => Effect.sync(() => { spawnedCommands.push(commandArgs(command)); - return makeSuccessfulProcess('loaded nvm default\n{"remotePort":3774}\n'); + // A cold archive download on a slow link outlasts any fixed launch deadline. + return { + ...makeSuccessfulProcess('loaded nvm default\n{"remotePort":3774}\n'), + exitCode: Effect.sleep(Duration.minutes(20)).pipe( + Effect.as(ChildProcessSpawner.ExitCode(0)), + ), + }; }), ); const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner); @@ -297,7 +392,11 @@ describe("ssh tunnel scripts", () => { ); return Effect.gen(function* () { - const result = yield* SshTunnel.launchOrReuseRemoteServer(target, undefined, ARCHIVE); + const launch = yield* Effect.forkChild( + SshTunnel.launchOrReuseRemoteServer(target, undefined, ARCHIVE), + ); + yield* TestClock.adjust(Duration.minutes(20)); + const result = yield* Fiber.join(launch); assert.equal(result.remotePort, 3774); assert.deepEqual(spawnedCommands[0]?.slice(-5, -1), ["sh", "-l", "-s", "--"]); }).pipe(Effect.provide(layerProcess)); @@ -752,6 +851,172 @@ describe("ssh tunnel scripts", () => { }), ); + it.effect("disconnect cancels a launch still running for the same target", () => + Effect.gen(function* () { + const launchStarted = yield* Deferred.make(); + let stops = 0; + const spawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + const args = commandArgs(command); + if (args.includes("-G")) return makeSuccessfulProcess(""); + if (args.some((arg, index) => arg === "-s" && args[index + 1] === "--")) { + yield* Deferred.succeed(launchStarted, undefined); + // Stuck on the remote host, holding the target's lock. + return makeRunningProcess(() => undefined); + } + stops += 1; + return makeSuccessfulProcess('{"stopped":true}\n'); + }), + ); + const layer = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), + Layer.succeed(HttpClient.HttpClient, testHttpClient), + Layer.succeed(NetService.NetService, testNetService), + SshAuth.SshPasswordPrompt.disabledLayer, + SshTunnel.SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }), + ); + yield* Effect.gen(function* () { + const manager = yield* SshTunnel.SshEnvironmentManager; + const target = { alias: "devbox", hostname: "devbox", username: null, port: null }; + const connect = yield* Effect.forkChild(Effect.result(manager.ensureEnvironment(target))); + yield* Deferred.await(launchStarted); + yield* manager.disconnectEnvironment(target); + const result = yield* Fiber.join(connect); + assert.isTrue(Result.isFailure(result)); + if (Result.isFailure(result)) { + assert.include(result.failure.message, "disconnected"); + } + assert.equal(stops, 1); + }).pipe(Effect.provide(layer), Effect.scoped); + }), + ); + + it.live("an archive reconnect reuses the running server and its runner until disconnect", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ssh-update-" }); + const servers = () => + fs + .readFileString(path.join(home, "servers")) + .pipe(Effect.map((pids) => pids.trim().split("\n").filter(Boolean).map(Number))); + yield* Effect.addFinalizer(() => servers().pipe(Effect.map(killAll), Effect.ignore)); + const install = (version: string) => + Effect.gen(function* () { + const runtime = path.join(home, ".t3", "runtime", "versions", version); + yield* fs.makeDirectory(runtime, { recursive: true }); + yield* fs.writeFileString(path.join(runtime, "t3"), fakeT3Runtime, { mode: 0o755 }); + yield* fs.writeFileString(path.join(runtime, ".install-complete"), `${version}\n`); + }); + // Nothing answers here, so any download fails the launch. + const runner = (archiveVersion: string) => ({ + archiveVersion, + releaseBaseUrl: "http://127.0.0.1:9/releases", + }); + const devbox = { alias: "devbox", hostname: "devbox", username: null, port: null }; + const tailnet = { + alias: "devbox-tailnet", + hostname: "devbox-tailnet", + username: null, + port: null, + }; + + yield* Effect.gen(function* () { + yield* install("1.0.0"); + const first = yield* SshTunnel.launchOrReuseRemoteServer( + devbox, + undefined, + runner("1.0.0"), + ); + const [runningPid] = yield* servers(); + + // After an app update the runner names 1.0.1, which is not downloaded yet. + const reconnect = yield* SshTunnel.launchOrReuseRemoteServer( + devbox, + undefined, + runner("1.0.1"), + ); + assert.deepEqual(reconnect, first); + assert.deepEqual(yield* servers(), [runningPid]); + assert.isTrue(isAlive(runningPid!), "Reconnecting must not stop the running server."); + const paired = yield* SshTunnel.issueRemotePairingToken(devbox, undefined, runner("1.0.1")); + assert.equal(paired.credential, "paired-by-1.0.0"); + + // Another alias adopts the same server and still pairs with its version. + yield* install("1.0.1"); + const adopted = yield* SshTunnel.launchOrReuseRemoteServer( + tailnet, + undefined, + runner("1.0.1"), + ); + assert.equal(adopted.remotePort, first.remotePort); + assert.equal(adopted.remoteServerKind, "external"); + const adoptedPairing = yield* SshTunnel.issueRemotePairingToken( + tailnet, + undefined, + runner("1.0.1"), + ); + assert.equal(adoptedPairing.credential, "paired-by-1.0.0"); + + // Updating stops the server explicitly; the next connect starts the new runner. + const manager = yield* SshTunnel.SshEnvironmentManager; + yield* manager.disconnectEnvironment(devbox); + assert.isFalse(isAlive(runningPid!)); + const relaunched = yield* SshTunnel.launchOrReuseRemoteServer( + devbox, + undefined, + runner("1.0.1"), + ); + assert.equal(relaunched.remoteServerKind, "managed"); + const [, relaunchedPid] = yield* servers(); + assert.isTrue(isAlive(relaunchedPid!)); + assert.include( + yield* fs.readFileString( + path.join(home, ".t3", "ssh-launch", yield* remoteStateKey(devbox), "run-t3.sh"), + ), + "T3_ARCHIVE_VERSION='1.0.1'", + ); + }).pipe(Effect.provide(managerOnRemoteShell(home))); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.live("disconnect waits for a slow server to exit before it returns", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ssh-stop-" }); + // Like `t3 serve` finishing its shutdown work after SIGTERM. + const server = NodeChildProcess.spawn( + process.execPath, + [ + "-e", + "process.on('SIGTERM', () => setTimeout(() => process.exit(0), 2500)); setInterval(() => {}, 1000); console.log('ready');", + ], + { stdio: ["ignore", "pipe", "ignore"] }, + ); + const pid = server.pid!; + yield* Effect.addFinalizer(() => Effect.sync(() => killAll([pid]))); + yield* Effect.callback((resume) => { + server.stdout!.once("data", () => resume(Effect.void)); + }); + const devbox = { alias: "devbox", hostname: "devbox", username: null, port: null }; + const stateDir = path.join(home, ".t3", "ssh-launch", yield* remoteStateKey(devbox)); + yield* fs.makeDirectory(stateDir, { recursive: true }); + yield* fs.writeFileString(path.join(home, "servers"), `${pid}\n`); + yield* fs.writeFileString(path.join(stateDir, "pid"), `${pid}\n`); + yield* fs.writeFileString(path.join(stateDir, "managed"), "managed\n"); + + yield* Effect.gen(function* () { + const manager = yield* SshTunnel.SshEnvironmentManager; + yield* manager.disconnectEnvironment(devbox); + assert.isFalse(isAlive(pid), "The restart must not reconnect to an exiting server."); + assert.isFalse(yield* fs.exists(path.join(stateDir, "pid"))); + }).pipe(Effect.provide(managerOnRemoteShell(home))); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + it.live("concurrent launches on one remote home record the server that owns it", () => // The second row's server never publishes server-runtime.json. Effect.forEach([1_500, null], (publishDelayMs) => diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index c186c54b741dc..2409e88271968 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -10,6 +10,7 @@ import { extractJsonObject, fromLenientJson } from "@t3tools/shared/schemaJson"; 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 Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -60,13 +61,16 @@ 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; -// Cold archive launches download and extract ~70 MB and may wait on an install lock. -// Lock waits must outlast both downloads and extraction; SSH must outlast install or wait plus readiness. -// Leave slack for verification and extraction, which have no timeout. -const REMOTE_ARCHIVE_CHECKSUMS_SECONDS = 30; -const REMOTE_ARCHIVE_DOWNLOAD_SECONDS = 240; +// 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. +const REMOTE_ARCHIVE_STALL_BYTES_PER_SECOND = 1024; +const REMOTE_ARCHIVE_STALL_SECONDS = 60; const REMOTE_ARCHIVE_LOCK_WAIT_SECONDS = 360; -const REMOTE_ARCHIVE_LAUNCH_TIMEOUT_MS = 900_000; +const REMOTE_ARCHIVE_LAUNCH_TIMEOUT_MS = 2 * 60 * 60 * 1000; +const REMOTE_ARCHIVE_PAIRING_TIMEOUT_MS = 900_000; +// An update restart must not reconnect to a server that is still shutting down. +const REMOTE_STOP_WAIT_SECONDS = 60; const REMOTE_REUSE_READY_TIMEOUT_MS = 2_000; const REMOTE_PID_EXIT_WAIT_MS = 2_000; // The server answers HTTP before it writes server-runtime.json, which is how @@ -511,13 +515,13 @@ if ! t3_runtime_ready; then T3_STAGING="$(mktemp -d "$HOME/.t3/runtime/versions/.staging-XXXXXX")" trap 'rm -rf "$T3_STAGING" "$T3_LOCK"' EXIT t3_fetch() { - if command -v curl >/dev/null 2>&1; then curl -fsSL --connect-timeout 30 --max-time "$3" "$1" -o "$2" - elif command -v wget >/dev/null 2>&1; then wget -q --timeout=30 --tries=1 "$1" -O "$2" + if command -v curl >/dev/null 2>&1; then curl -fsSL --connect-timeout 30 --speed-limit @@T3_ARCHIVE_STALL_BYTES_PER_SECOND@@ --speed-time @@T3_ARCHIVE_STALL_SECONDS@@ "$1" -o "$2" + elif command -v wget >/dev/null 2>&1; then wget -q --timeout=@@T3_ARCHIVE_STALL_SECONDS@@ --tries=1 "$1" -O "$2" else printf 'Remote host needs curl or wget to download %s.\\n' "$T3_ARCHIVE" >&2; exit 1 fi } - t3_fetch "$T3_RELEASE_BASE_URL/v$T3_ARCHIVE_VERSION/SHA256SUMS" "$T3_STAGING/SHA256SUMS" @@T3_ARCHIVE_CHECKSUMS_SECONDS@@ - t3_fetch "$T3_RELEASE_BASE_URL/v$T3_ARCHIVE_VERSION/$T3_ARCHIVE" "$T3_STAGING/$T3_ARCHIVE" @@T3_ARCHIVE_DOWNLOAD_SECONDS@@ + t3_fetch "$T3_RELEASE_BASE_URL/v$T3_ARCHIVE_VERSION/SHA256SUMS" "$T3_STAGING/SHA256SUMS" + t3_fetch "$T3_RELEASE_BASE_URL/v$T3_ARCHIVE_VERSION/$T3_ARCHIVE" "$T3_STAGING/$T3_ARCHIVE" T3_EXPECTED="$(grep " \\*\\{0,1\\}$T3_ARCHIVE$" "$T3_STAGING/SHA256SUMS" | cut -d' ' -f1)" if command -v sha256sum >/dev/null 2>&1; then T3_ACTUAL="$(sha256sum "$T3_STAGING/$T3_ARCHIVE" | cut -d' ' -f1)" @@ -577,11 +581,20 @@ cat >"$RUNNER_NEXT" <<'SH' SH chmod 700 "$RUNNER_NEXT" T3_ARCHIVE_MODE=@@T3_ARCHIVE_MODE@@ +# Helpers run from RUNNER. RUNNER_FILE stays the runner of the server it +# started; this launch's runner replaces it only when it starts one. +RUNNER="$RUNNER_NEXT" if [ "$T3_ARCHIVE_MODE" = "1" ]; then # The archive ships the helpers below inside the executable; the remote - # needs no Node at all. Resolving the runner once here also downloads the - # archive before the port and readiness probes rely on it. - "$RUNNER_NEXT" --version >/dev/null + # needs no Node at all. Reusing this launcher's running server needs no + # download: its own runner has them. Otherwise resolving the new runner here + # downloads the archive before the port and readiness probes rely on it. + RECORDED_PID="$(cat "$PID_FILE" 2>/dev/null || true)" + 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 + 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 exit 1 @@ -628,14 +641,9 @@ while ! (set -C; printf '%s\\n' "$$" >"$LAUNCH_LOCK") 2>/dev/null; do sleep 1 LAUNCH_LOCK_WAITED=$((LAUNCH_LOCK_WAITED + 1)) done -RUNNER_CHANGED=0 -if [ ! -f "$RUNNER_FILE" ] || ! cmp -s "$RUNNER_NEXT" "$RUNNER_FILE"; then - RUNNER_CHANGED=1 -fi -mv "$RUNNER_NEXT" "$RUNNER_FILE" pick_port() { if [ "$T3_ARCHIVE_MODE" = "1" ]; then - "$RUNNER_FILE" __ssh-helper pick-port "$PORT_FILE" "@@T3_DEFAULT_REMOTE_PORT@@" "@@T3_REMOTE_PORT_SCAN_WINDOW@@" + "$RUNNER" __ssh-helper pick-port "$PORT_FILE" "@@T3_DEFAULT_REMOTE_PORT@@" "@@T3_REMOTE_PORT_SCAN_WINDOW@@" return fi node - "$PORT_FILE" "@@T3_DEFAULT_REMOTE_PORT@@" "@@T3_REMOTE_PORT_SCAN_WINDOW@@" <<'NODE' @@ -644,7 +652,7 @@ NODE } wait_ready() { if [ "$T3_ARCHIVE_MODE" = "1" ]; then - "$RUNNER_FILE" __ssh-helper wait-ready "$REMOTE_PORT" "$1" "@@T3_READY_PROBE_TIMEOUT_MS@@" + "$RUNNER" __ssh-helper wait-ready "$REMOTE_PORT" "$1" "@@T3_READY_PROBE_TIMEOUT_MS@@" return fi node - "$REMOTE_PORT" "$1" "@@T3_READY_PROBE_TIMEOUT_MS@@" <<'NODE' @@ -669,7 +677,7 @@ server_running() { } resolve_default_runtime_port() { if [ "$T3_ARCHIVE_MODE" = "1" ]; then - "$RUNNER_FILE" __ssh-helper runtime-port "$DEFAULT_RUNTIME_FILE" + "$RUNNER" __ssh-helper runtime-port "$DEFAULT_RUNTIME_FILE" return fi node - "$DEFAULT_RUNTIME_FILE" <<'NODE' @@ -749,14 +757,9 @@ if [ "$REMOTE_MANAGED" = "external" ]; then fi elif [ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && server_running "$REMOTE_PID"; then # Reconnect owns the local tunnel, not the lifetime of an already running - # server. A changed runner is the update path and still replaces it. - if [ "$RUNNER_CHANGED" -eq 1 ]; then - kill "$REMOTE_PID" 2>/dev/null || true - wait_for_pid_exit "$REMOTE_PID" - REMOTE_PID="" - REMOTE_PORT="" - REMOTE_MANAGED="" - elif ! wait_ready "@@T3_READY_TIMEOUT_MS@@"; then + # server, even an older version: agent turns may be running there. Updating + # stops it explicitly first. + if ! wait_ready "@@T3_READY_TIMEOUT_MS@@"; then printf 'Remote T3 server is still running but did not become ready. Retry the connection; the server was left running.\\n' >&2 exit 1 fi @@ -785,6 +788,11 @@ if [ -z "$REMOTE_PORT" ] && [ -z "$DEFAULT_RUNTIME_INFO" ]; then done 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 + RUNNER="$RUNNER_NEXT" + fi REMOTE_PORT="$(pick_port)" || true if [ -z "$REMOTE_PORT" ]; then if [ "$T3_ARCHIVE_MODE" = "1" ]; then @@ -794,6 +802,8 @@ if [ -z "$REMOTE_PORT" ]; then fi exit 1 fi + mv "$RUNNER_NEXT" "$RUNNER_FILE" + RUNNER="$RUNNER_FILE" nohup env T3CODE_NO_BROWSER=1 "$RUNNER_FILE" serve --host 127.0.0.1 --port "$REMOTE_PORT" --base-dir "$DEFAULT_SERVER_HOME" >>"$LOG_FILE" 2>&1 < /dev/null & REMOTE_PID="$!" printf '%s\\n' "$REMOTE_PID" >"$PID_FILE" @@ -826,14 +836,45 @@ printf '{"remotePort":%s,"serverKind":"%s"}\\n' "$REMOTE_PORT" "\${REMOTE_MANAGE const REMOTE_PAIRING_SCRIPT = `set -eu STATE_DIR="$HOME/.t3/ssh-launch/@@T3_STATE_KEY@@" DEFAULT_SERVER_HOME="$HOME/.t3" -RUNNER_FILE="$STATE_DIR/run-t3.sh" +RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json" mkdir -p "$STATE_DIR" -cat >"$RUNNER_FILE" <<'SH' +runtime_field() { + sed -n 's/.*"'"$1"'"[[:space:]]*:[[:space:]]*"\\{0,1\\}\\([^",}]*\\).*/\\1/p' "$RUNTIME_FILE" 2>/dev/null | head -n 1 +} +# A live server that owns this home issues the token with its own version: a +# newer binary would migrate the database under it. Find that server's runner +# through any alias's launch record, or its installed runtime. +PAIR_RUNNER="" +OWNER_PID="$(runtime_field pid)" +if [ -z "$OWNER_PID" ] || ! kill -0 "$OWNER_PID" 2>/dev/null; then + OWNER_PID="" + if [ "$(cat "$STATE_DIR/managed" 2>/dev/null || true)" = "managed" ]; then + OWNER_PID="$(cat "$STATE_DIR/pid" 2>/dev/null || true)" + fi +fi +if [ -n "$OWNER_PID" ] && kill -0 "$OWNER_PID" 2>/dev/null; then + for LAUNCH_DIR in "$STATE_DIR" "$DEFAULT_SERVER_HOME"/ssh-launch/*; do + if [ "$(cat "$LAUNCH_DIR/pid" 2>/dev/null || true)" = "$OWNER_PID" ] && [ -x "$LAUNCH_DIR/run-t3.sh" ]; then + PAIR_RUNNER="$LAUNCH_DIR/run-t3.sh" + break + fi + done + OWNER_VERSION="$(runtime_field serverVersion)" + case "$OWNER_VERSION" in */* | .*) OWNER_VERSION="" ;; esac + OWNER_RUNTIME="$DEFAULT_SERVER_HOME/runtime/versions/$OWNER_VERSION" + if [ -z "$PAIR_RUNNER" ] && [ -n "$OWNER_VERSION" ] && [ -x "$OWNER_RUNTIME/t3" ] && [ "$(cat "$OWNER_RUNTIME/.install-complete" 2>/dev/null || true)" = "$OWNER_VERSION" ]; then + PAIR_RUNNER="$OWNER_RUNTIME/t3" + fi +fi +if [ -z "$PAIR_RUNNER" ]; then + PAIR_RUNNER="$STATE_DIR/run-t3.pair.$$" + trap 'rm -f "$PAIR_RUNNER"' EXIT + cat >"$PAIR_RUNNER" <<'SH' @@T3_RUNNER_SCRIPT@@ SH -chmod 700 "$RUNNER_FILE" -PAIRING_BASE_DIR="$DEFAULT_SERVER_HOME" -"$RUNNER_FILE" auth pairing create --base-dir "$PAIRING_BASE_DIR" --json + chmod 700 "$PAIR_RUNNER" +fi +"$PAIR_RUNNER" auth pairing create --base-dir "$DEFAULT_SERVER_HOME" --json `; const REMOTE_STOP_SCRIPT = `set -eu @@ -846,12 +887,12 @@ REMOTE_PID="$(cat "$PID_FILE" 2>/dev/null || true)" if [ "$REMOTE_MANAGED" != "external" ] && [ -n "$REMOTE_PID" ] && kill -0 "$REMOTE_PID" 2>/dev/null; then kill "$REMOTE_PID" 2>/dev/null || true WAIT_COUNT=0 - while kill -0 "$REMOTE_PID" 2>/dev/null && [ "$WAIT_COUNT" -lt 20 ]; do + while kill -0 "$REMOTE_PID" 2>/dev/null && [ "$WAIT_COUNT" -lt @@T3_STOP_WAIT_TICKS@@ ]; do WAIT_COUNT=$((WAIT_COUNT + 1)) sleep 0.1 done if kill -0 "$REMOTE_PID" 2>/dev/null; then - printf 'Remote T3 server with PID %s did not stop within 2 seconds. Its ownership files were kept.\\n' "$REMOTE_PID" >&2 + printf 'Remote T3 server with PID %s did not stop within @@T3_STOP_WAIT_SECONDS@@ seconds. Its ownership files were kept.\\n' "$REMOTE_PID" >&2 exit 1 fi fi @@ -910,8 +951,8 @@ export function buildRemoteT3RunnerScript(input?: RemoteT3RunnerOptions): string T3_ARCHIVE_VERSION: shellSingleQuote(archiveVersion), T3_RELEASE_BASE_URL: shellSingleQuote(releaseBaseUrl), T3_ARCHIVE_LOCK_WAIT_SECONDS: String(REMOTE_ARCHIVE_LOCK_WAIT_SECONDS), - T3_ARCHIVE_DOWNLOAD_SECONDS: String(REMOTE_ARCHIVE_DOWNLOAD_SECONDS), - T3_ARCHIVE_CHECKSUMS_SECONDS: String(REMOTE_ARCHIVE_CHECKSUMS_SECONDS), + T3_ARCHIVE_STALL_BYTES_PER_SECOND: String(REMOTE_ARCHIVE_STALL_BYTES_PER_SECOND), + T3_ARCHIVE_STALL_SECONDS: String(REMOTE_ARCHIVE_STALL_SECONDS), T3_NODE_ENV_SCRIPT: buildRemoteNodeEnvScript(input), }), ); @@ -954,6 +995,8 @@ function buildRemotePairingScript(stateKey: string, input?: RemoteT3RunnerOption function buildRemoteStopScript(stateKey: string): string { return applyScriptPlaceholders(REMOTE_STOP_SCRIPT, { T3_STATE_KEY: stateKey, + T3_STOP_WAIT_TICKS: String(REMOTE_STOP_WAIT_SECONDS * 10), + T3_STOP_WAIT_SECONDS: String(REMOTE_STOP_WAIT_SECONDS), }); } @@ -1043,7 +1086,7 @@ export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingT const result = yield* runSshCommand(target, { remoteCommandArgs: ["sh", "-s"], stdin: buildRemotePairingScript(stateKey, runner), - ...(isNodeScriptRunner(runner) ? {} : { timeoutMs: REMOTE_ARCHIVE_LAUNCH_TIMEOUT_MS }), + ...(isNodeScriptRunner(runner) ? {} : { timeoutMs: REMOTE_ARCHIVE_PAIRING_TIMEOUT_MS }), ...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }), ...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }), ...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }), @@ -1095,6 +1138,7 @@ const stopRemoteServer = Effect.fn("ssh/tunnel.stopRemoteServer")(function* ( yield* runSshCommand(target, { remoteCommandArgs: ["sh", "-s"], stdin: buildRemoteStopScript(stateKey), + timeoutMs: (REMOTE_STOP_WAIT_SECONDS + 30) * 1000, ...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }), ...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }), ...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }), @@ -1480,6 +1524,17 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma const tunnels = new Map(); const targetLocks = yield* KeyedLock.make(); const authSecrets = new Map(); + // Disconnect cancels a connect queued or running for the same target, so a + // stuck launch cannot keep Switch off or Remove waiting behind it. + const connectCancellations = new Map>(); + const connectCancellation = (key: string) => { + let cancellation = connectCancellations.get(key); + if (cancellation === undefined) { + cancellation = Deferred.makeUnsafe(); + connectCancellations.set(key, cancellation); + } + return cancellation; + }; // Keep one lock per target so reconnect cannot reuse a server while stop is pending. const withTargetLock = Effect.fn("ssh/tunnel.withTargetLock")(function* ( @@ -1686,56 +1741,17 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma ), ); tunnels.set(input.key, tunnelEntry); - const spawnerService = yield* ChildProcessSpawner.ChildProcessSpawner; - const digestService = yield* Digest.Digest; - const fileSystemService = yield* FileSystem.FileSystem; - const pathService = yield* Path.Path; + // 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.gen(function* () { - const stopRemote = tunnels.get(tunnelEntry.key) === tunnelEntry; - if (stopRemote) { + Effect.suspend(() => { + if (tunnels.get(tunnelEntry.key) === tunnelEntry) { tunnels.delete(tunnelEntry.key); } - yield* tunnelEntry.process - .kill({ - killSignal: "SIGTERM", - forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS, - }) - .pipe(Effect.ignore); - if (!stopRemote) { - return; - } - yield* Effect.logDebug("ssh.environment.tunnel.finalizer.start", { - ...sshTargetLogFields(tunnelEntry.target), - key: tunnelEntry.key, - localPort: tunnelEntry.localPort, - remotePort: tunnelEntry.remotePort, - }); - const authSecret = authSecrets.get(tunnelEntry.key) ?? null; - yield* stopRemoteServer( - tunnelEntry.target, - authSecret === null - ? { - batchMode: "yes", - interactiveAuth: false, - } - : { - authSecret, - batchMode: "no", - interactiveAuth: true, - }, - ).pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawnerService), - Effect.provideService(Digest.Digest, digestService), - Effect.provideService(FileSystem.FileSystem, fileSystemService), - Effect.provideService(Path.Path, pathService), - ); - yield* Effect.logDebug("ssh.environment.tunnel.finalizer.succeeded", { - ...sshTargetLogFields(tunnelEntry.target), - key: tunnelEntry.key, - localPort: tunnelEntry.localPort, - remotePort: tunnelEntry.remotePort, + return tunnelEntry.process.kill({ + killSignal: "SIGTERM", + forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS, }); }).pipe(Effect.ignore), ); @@ -1785,7 +1801,6 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma remotePort: entry.remotePort, cause: readinessExit.cause, }); - // Closing a stale forward must not run the manager-owned remote stop. tunnels.delete(key); yield* closeTunnelEntry(entry); } @@ -1835,7 +1850,8 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma ...sshRunnerLogFields(runner), key, }); - return yield* withTargetLock( + const cancellation = connectCancellation(key); + const connect = withTargetLock( key, Effect.gen(function* () { const entry = yield* ensureTunnelEntry(key, resolvedTarget, runner); @@ -1868,6 +1884,19 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma }; }), ); + return yield* Effect.raceFirst( + connect, + Deferred.await(cancellation).pipe( + Effect.andThen( + Effect.fail( + new SshLaunchError({ + message: `Connecting to ${resolvedTarget.alias} stopped because it was disconnected.`, + stdout: "", + }), + ), + ), + ), + ); }); const disconnectEnvironment = Effect.fn("ssh/tunnel.disconnectEnvironment")(function* ( @@ -1881,6 +1910,11 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma ...(target.port !== null ? { port: target.port } : {}), }; const key = targetConnectionKey(resolvedTarget); + const pendingConnect = connectCancellations.get(key); + if (pendingConnect !== undefined) { + connectCancellations.delete(key); + yield* Deferred.succeed(pendingConnect, undefined); + } yield* withTargetLock( key, Effect.gen(function* () { @@ -1891,7 +1925,6 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma hasTunnel: entry !== null, }); if (entry !== null) { - // Explicit disconnect owns the remote stop so its failure reaches the caller. yield* Effect.gen(function* () { tunnels.delete(key); yield* closeTunnelEntry(entry);