Skip to content

Commit 5617e27

Browse files
committed
fix(ssh): bound shell retries and preserve cleanup target
Share failed shell captures for five seconds. Keep disconnect free of shell probes and use its connected bootstrap target with an explicit hostname for remote stop. Cover retry expiry, real OpenSSH hostname pinning, tunnel closure after alias changes, and failed-stop retry. Implemented with GPT-6.1 Sol via Codex.
1 parent 9d43f46 commit 5617e27

5 files changed

Lines changed: 135 additions & 24 deletions

File tree

‎apps/desktop/src/shell/DesktopShellEnvironment.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ const FALLBACK_LC_CTYPE = "en_US.UTF-8";
104104
const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
105105
const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
106106
const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
107+
const FAILED_CAPTURE_RETRY_TTL = Duration.seconds(5);
107108
const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
108109

109110
const trimNonEmpty = (value: string | null | undefined): Option.Option<string> =>
@@ -549,7 +550,7 @@ export const make = Effect.gen(function* () {
549550
(exit) =>
550551
environment.platform === "win32" || (Exit.isSuccess(exit) && exit.value)
551552
? Duration.infinity
552-
: Duration.zero,
553+
: FAILED_CAPTURE_RETRY_TTL,
553554
);
554555

555556
return DesktopShellEnvironment.of({ installIntoProcess });

‎apps/desktop/src/ssh/DesktopSshEnvironment.integration.test.ts‎

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import * as Layer from "effect/Layer";
1111
import * as Path from "effect/Path";
1212
import * as ChildProcess from "effect/process/ChildProcess";
1313
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14+
import * as TestClock from "effect/testing/TestClock";
1415
import * as NodeOS from "node:os";
1516
import { vi } from "vite-plus/test";
1617

@@ -30,7 +31,13 @@ const target = {
3031
};
3132

3233
function runRecoveryScenario(
33-
operation: "resolve" | "connect" | "still-unavailable" | "fallback-shell" | "launchctl",
34+
operation:
35+
| "resolve"
36+
| "connect"
37+
| "disconnect"
38+
| "still-unavailable"
39+
| "fallback-shell"
40+
| "launchctl",
3441
) {
3542
return Effect.gen(function* () {
3643
const fs = yield* FileSystem.FileSystem;
@@ -76,7 +83,7 @@ function runRecoveryScenario(
7683
yield* fs.chmod(path.join(helpers, "workspace-check"), 0o700);
7784
yield* fs.writeFileString(
7885
path.join(helpers, "workspace-proxy"),
79-
`#!/bin/sh\nprintf 'proxy invoked\\n' > '${proxyReached}'\nexit 1\n`,
86+
`#!/bin/sh\nprintf 'proxy invoked %s\\n' "$1" > '${proxyReached}'\nexit 1\n`,
8087
);
8188
yield* fs.chmod(path.join(helpers, "workspace-proxy"), 0o700);
8289
yield* fs.writeFileString(
@@ -86,7 +93,7 @@ function runRecoveryScenario(
8693
" HostName helper-ready.invalid",
8794
"Host managed-workspace",
8895
" HostName helper-missing.invalid",
89-
" ProxyCommand workspace-proxy",
96+
" ProxyCommand workspace-proxy %h",
9097
" ControlMaster no",
9198
" ControlPath none",
9299
"",
@@ -121,28 +128,60 @@ function runRecoveryScenario(
121128
const ssh = yield* DesktopSshEnvironment.DesktopSshEnvironment;
122129
assert.equal(yield* shell.installIntoProcess, false);
123130
if (operation !== "still-unavailable") yield* fs.writeFileString(ready, "");
131+
const initialProbes = operation === "fallback-shell" ? "probe\nprobe\n" : "probe\n";
132+
assert.equal(yield* shell.installIntoProcess, false);
133+
assert.equal((yield* ssh.resolveHost(target.alias)).hostname, "helper-missing.invalid");
134+
assert.equal(yield* fs.readFileString(probes), initialProbes);
135+
yield* TestClock.adjust("4999 millis");
136+
assert.equal((yield* ssh.resolveHost(target.alias)).hostname, "helper-missing.invalid");
137+
assert.equal(yield* fs.readFileString(probes), initialProbes);
138+
yield* TestClock.adjust("1 millis");
124139
if (operation === "resolve" || operation === "fallback-shell" || operation === "launchctl") {
125140
assert.equal((yield* ssh.resolveHost(target.alias)).hostname, "helper-ready.invalid");
126141
assert.equal((yield* ssh.resolveHost(target.alias)).hostname, "helper-ready.invalid");
127142
} else {
128-
const result = yield* Effect.result(ssh.ensureEnvironment(target));
143+
if (operation === "disconnect") {
144+
assert.equal((yield* ssh.resolveHost(target.alias)).hostname, "helper-ready.invalid");
145+
}
146+
const result = yield* Effect.result(
147+
operation === "disconnect"
148+
? ssh.disconnectEnvironment(target)
149+
: ssh.ensureEnvironment(target),
150+
);
129151
assert.equal(result._tag, "Failure");
130152
if (result._tag === "Failure") assert.instanceOf(result.failure, SshCommandError);
131-
if (operation === "connect") {
132-
assert.equal(yield* fs.readFileString(proxyReached), "proxy invoked\n");
153+
if (operation === "connect" || operation === "disconnect") {
154+
assert.equal(
155+
yield* fs.readFileString(proxyReached),
156+
operation === "disconnect"
157+
? "proxy invoked helper-missing.invalid\n"
158+
: "proxy invoked helper-ready.invalid\n",
159+
);
133160
assert.equal((yield* ssh.resolveHost(target.alias)).hostname, "helper-ready.invalid");
134161
} else {
135162
assert.equal(yield* fs.exists(proxyReached), false);
136163
if (result._tag === "Failure") {
137164
assert.include(result.failure.message, "workspace-proxy");
138165
}
166+
assert.equal((yield* ssh.resolveHost(target.alias)).hostname, "helper-missing.invalid");
139167
}
140168
}
141169
assert.equal(
142170
yield* fs.readFileString(probes),
143171
operation === "fallback-shell" ? "probe\nprobe\nprobe\n" : "probe\nprobe\n",
144172
);
145173
assert.equal(process.env.PATH, operation === "still-unavailable" ? inheritedPath : shellPath);
174+
yield* TestClock.adjust("1 hour");
175+
assert.equal(
176+
(yield* ssh.resolveHost(target.alias)).hostname,
177+
operation === "still-unavailable" ? "helper-missing.invalid" : "helper-ready.invalid",
178+
);
179+
assert.equal(
180+
yield* fs.readFileString(probes),
181+
operation === "still-unavailable" || operation === "fallback-shell"
182+
? "probe\nprobe\nprobe\n"
183+
: "probe\nprobe\n",
184+
);
146185
}).pipe(
147186
Effect.provide(
148187
layerSsh.pipe(
@@ -189,6 +228,10 @@ function runRecoveryScenario(
189228
}
190229

191230
describe("SSH shell PATH recovery with real OpenSSH", () => {
231+
it.effect.runIf(HostProcess.Platform.defaultValue() === "darwin")(
232+
"pins remote cleanup to the supplied host after PATH recovery changes alias resolution",
233+
() => runRecoveryScenario("disconnect"),
234+
);
192235
it.effect.runIf(HostProcess.Platform.defaultValue() === "darwin")(
193236
"retries the preferred shell when a fallback shell supplied only a degraded PATH",
194237
() => runRecoveryScenario("fallback-shell"),

‎apps/desktop/src/ssh/DesktopSshEnvironment.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -154,12 +154,13 @@ export const make = Effect.gen(function* () {
154154
Effect.withSpan("desktop.ssh.ensureEnvironment"),
155155
),
156156
disconnectEnvironment: (target) =>
157-
shellEnvironment.installIntoProcess.pipe(
158-
Effect.andThen(() => manager.disconnectEnvironment(target)),
159-
Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),
160-
Effect.provide(runtimeContext),
161-
Effect.withSpan("desktop.ssh.disconnectEnvironment"),
162-
),
157+
manager
158+
.disconnectEnvironment(target)
159+
.pipe(
160+
Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),
161+
Effect.provide(runtimeContext),
162+
Effect.withSpan("desktop.ssh.disconnectEnvironment"),
163+
),
163164
});
164165
});
165166

‎packages/ssh/src/tunnel.test.ts‎

Lines changed: 74 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import { HttpClient, HttpClientResponse } from "effect/http";
2121
import { ChildProcess, ChildProcessSpawner } from "effect/process";
2222

2323
import * as SshAuth from "./auth.ts";
24+
import { resolveSshTarget } from "./command.ts";
2425
import { SshCommandError } from "./errors.ts";
2526
import * as SshTunnel from "./tunnel.ts";
2627

@@ -604,7 +605,7 @@ describe("ssh tunnel scripts", () => {
604605
assert.include(firstTunnelArgs, "ControlPersist=no");
605606
assert.deepEqual(firstTunnelArgs?.slice(-2), ["--", "julius@devbox"]);
606607

607-
const disconnected = yield* Effect.result(manager.disconnectEnvironment(target));
608+
const disconnected = yield* Effect.result(manager.disconnectEnvironment(first.target));
608609
if (mode === "failed stop") {
609610
assert.isTrue(Result.isFailure(disconnected));
610611
if (Result.isFailure(disconnected)) {
@@ -621,7 +622,7 @@ describe("ssh tunnel scripts", () => {
621622
assert.equal(stopCommandCount, 1);
622623

623624
if (mode === "failed stop") {
624-
yield* manager.disconnectEnvironment(target);
625+
yield* manager.disconnectEnvironment(first.target);
625626
assert.equal(tunnelKillCount, 1);
626627
assert.equal(stopCommandCount, 2);
627628
}
@@ -874,6 +875,76 @@ describe("ssh tunnel scripts", () => {
874875
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
875876
);
876877

878+
it.effect.each(["disconnect first", "resolve before disconnect", "failed stop"] as const)(
879+
"keeps cleanup bound to the connected host after alias routing changes: %s",
880+
(mode) => {
881+
let recovered = false;
882+
let resolutions = 0;
883+
let kills = 0;
884+
const stops: Array<ReadonlyArray<string>> = [];
885+
const spawner = ChildProcessSpawner.make((command) =>
886+
Effect.sync(() => {
887+
const args = commandArgs(command);
888+
if (args.includes("-G")) {
889+
resolutions += 1;
890+
return makeSuccessfulProcess(
891+
`hostname ${recovered ? "other.example.com" : "connected.example.com"}\nuser alice\nport 2222\n`,
892+
);
893+
}
894+
if (args.includes("-N"))
895+
return makeRunningProcess(() => {
896+
kills += 1;
897+
});
898+
if (args.some((arg, index) => arg === "-s" && args[index + 1] === "--")) {
899+
return makeSuccessfulProcess('{"remotePort":3773}\n');
900+
}
901+
stops.push(args);
902+
const stop = makeSuccessfulProcess('{"stopped":true}\n');
903+
return mode === "failed stop" && stops.length === 1
904+
? { ...stop, exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)) }
905+
: stop;
906+
}),
907+
);
908+
const layer = Layer.mergeAll(
909+
NodeServices.layer,
910+
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
911+
Layer.succeed(HttpClient.HttpClient, testHttpClient),
912+
Layer.succeed(NetService.NetService, testNetService),
913+
SshAuth.SshPasswordPrompt.disabledLayer,
914+
SshTunnel.SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }),
915+
);
916+
return Effect.gen(function* () {
917+
const manager = yield* SshTunnel.SshEnvironmentManager;
918+
const connected = yield* manager.ensureEnvironment({
919+
alias: "devbox",
920+
hostname: "devbox",
921+
username: null,
922+
port: null,
923+
});
924+
assert.equal(connected.target.hostname, "connected.example.com");
925+
recovered = true;
926+
if (mode === "resolve before disconnect") {
927+
assert.equal((yield* resolveSshTarget("devbox")).hostname, "other.example.com");
928+
}
929+
const result = yield* Effect.result(manager.disconnectEnvironment(connected.target));
930+
if (mode === "failed stop") {
931+
assert.isTrue(Result.isFailure(result));
932+
yield* manager.disconnectEnvironment(connected.target);
933+
} else {
934+
assert.isTrue(Result.isSuccess(result));
935+
}
936+
assert.equal(kills, 1);
937+
assert.equal(resolutions, mode === "resolve before disconnect" ? 2 : 1);
938+
assert.equal(stops.length, mode === "failed stop" ? 2 : 1);
939+
for (const args of stops) {
940+
assert.include(args, "HostName=connected.example.com");
941+
assert.include(args, "alice@devbox");
942+
assert.deepEqual(args.slice(args.indexOf("-p"), args.indexOf("-p") + 2), ["-p", "2222"]);
943+
}
944+
}).pipe(Effect.provide(layer), Effect.scoped);
945+
},
946+
);
947+
877948
it.effect.each(["local tunnel", "remote server"] as const)(
878949
"waits for %s shutdown before reconnecting the same target",
879950
(stalledStep) =>
@@ -895,7 +966,7 @@ describe("ssh tunnel scripts", () => {
895966
const args = commandArgs(command);
896967
const isTarget = args.includes(target.alias);
897968
if (args.includes("-G")) {
898-
if (isTarget && ++resolutions === 4) {
969+
if (isTarget && ++resolutions === 3) {
899970
yield* Deferred.succeed(reconnectsStarted, undefined);
900971
}
901972
return makeSuccessfulProcess("");

‎packages/ssh/src/tunnel.ts‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1005,6 +1005,7 @@ const stopRemoteServer = Effect.fn("ssh/tunnel.stopRemoteServer")(function* (
10051005
stateKey,
10061006
});
10071007
yield* runSshCommand(target, {
1008+
preHostArgs: ["-o", `HostName=${target.hostname}`],
10081009
remoteCommandArgs: ["sh", "-s"],
10091010
stdin: buildRemoteStopScript(stateKey),
10101011
...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }),
@@ -1751,15 +1752,9 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
17511752
});
17521753

17531754
const disconnectEnvironment = Effect.fn("ssh/tunnel.disconnectEnvironment")(function* (
1754-
target: DesktopSshEnvironmentTarget,
1755+
resolvedTarget: DesktopSshEnvironmentTarget,
17551756
): Effect.fn.Return<void, SshEnvironmentEffectError, SshEnvironmentEffectContext> {
1756-
yield* Effect.logInfo("ssh.environment.disconnect.start", sshTargetLogFields(target));
1757-
const baseResolved = yield* resolveSshTarget(target.alias || target.hostname);
1758-
const resolvedTarget: DesktopSshEnvironmentTarget = {
1759-
...baseResolved,
1760-
...(target.username !== null ? { username: target.username } : {}),
1761-
...(target.port !== null ? { port: target.port } : {}),
1762-
};
1757+
yield* Effect.logInfo("ssh.environment.disconnect.start", sshTargetLogFields(resolvedTarget));
17631758
const key = targetConnectionKey(resolvedTarget);
17641759
yield* withTargetLock(
17651760
key,

0 commit comments

Comments
 (0)