Skip to content

Commit 9d43f46

Browse files
committed
fix(desktop): retry failed shell preparation before SSH
Keep failed or degraded POSIX shell captures retryable and prepare the shell environment before SSH operations. Preserve indefinite caching for successful preferred-shell captures and existing Windows behavior. Verify recovery with temporary shell profiles, real OpenSSH host resolution, and ProxyCommand helpers without changing user settings. Implemented with GPT-6.1 Sol via Codex.
1 parent d36b7da commit 9d43f46

5 files changed

Lines changed: 260 additions & 26 deletions

File tree

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,9 @@ function runShellEnvironment(input: {
103103
const program = Effect.gen(function* () {
104104
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
105105
const prepared = yield* shellEnvironment.installIntoProcess;
106-
assert.equal(yield* shellEnvironment.installIntoProcess, prepared);
106+
if (prepared || input.platform === "win32") {
107+
assert.equal(yield* shellEnvironment.installIntoProcess, prepared);
108+
}
107109
return prepared;
108110
}).pipe(
109111
Effect.provide(

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

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
import * as Context from "effect/Context";
77
import * as Duration from "effect/Duration";
88
import * as Effect from "effect/Effect";
9+
import * as Exit from "effect/Exit";
910
import * as FileSystem from "effect/FileSystem";
1011
import * as Layer from "effect/Layer";
1112
import * as Option from "effect/Option";
@@ -68,7 +69,7 @@ export class DesktopShellEnvironmentCommandTimeoutError extends Schema.TaggedErr
6869
export class DesktopShellEnvironment extends Context.Service<
6970
DesktopShellEnvironment,
7071
{
71-
// Reuses the installation result; false leaves server hydration enabled.
72+
// False leaves server hydration enabled; failed POSIX captures can be retried.
7273
readonly installIntoProcess: Effect.Effect<boolean>;
7374
}
7475
>()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
@@ -396,29 +397,36 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
396397
function* (
397398
config: ShellEnvironmentConfig,
398399
): Effect.fn.Return<
399-
void,
400+
boolean,
400401
never,
401402
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
402403
> {
403404
const fileSystem = yield* FileSystem.FileSystem;
404405
const shellEnvironment: EnvironmentPatch = {};
405406

406-
for (const shell of listLoginShellCandidates(config.platform, config.env.SHELL)) {
407+
let preferredShellPrepared = false;
408+
for (const [index, shell] of listLoginShellCandidates(
409+
config.platform,
410+
config.env.SHELL,
411+
).entries()) {
407412
Object.assign(
408413
shellEnvironment,
409414
yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES),
410415
);
411-
if (shellEnvironment.PATH) break;
416+
if (Option.isSome(trimNonEmpty(shellEnvironment.PATH))) {
417+
preferredShellPrepared = index === 0;
418+
break;
419+
}
412420
}
413421

414422
const launchctlPath =
415423
config.platform === "darwin" && !shellEnvironment.PATH
416424
? yield* readLaunchctlPath
417425
: Option.none<string>();
418-
const mergedPath = mergePaths(config.platform, [
419-
trimNonEmpty(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
420-
readEnvPath(config.env),
421-
]);
426+
const capturedPath = trimNonEmpty(shellEnvironment.PATH).pipe(
427+
Option.orElse(() => launchctlPath),
428+
);
429+
const mergedPath = mergePaths(config.platform, [capturedPath, readEnvPath(config.env)]);
422430

423431
if (Option.isSome(mergedPath)) {
424432
config.env.PATH = mergedPath.value;
@@ -503,6 +511,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
503511
}
504512
}
505513
}
514+
return preferredShellPrepared;
506515
},
507516
);
508517

@@ -517,7 +526,7 @@ const installShellEnvironment = (
517526
return installWindowsEnvironment(config);
518527
}
519528
if (config.platform === "darwin" || config.platform === "linux") {
520-
return installPosixEnvironment(config).pipe(Effect.as(true));
529+
return installPosixEnvironment(config);
521530
}
522531
return Effect.succeed(false);
523532
};
@@ -528,7 +537,7 @@ export const make = Effect.gen(function* () {
528537
const fileSystem = yield* FileSystem.FileSystem;
529538
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
530539
const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
531-
yield* Effect.cached(
540+
yield* Effect.cachedWithTTL(
532541
installShellEnvironment({
533542
env: process.env,
534543
platform: environment.platform,
@@ -537,6 +546,10 @@ export const make = Effect.gen(function* () {
537546
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
538547
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
539548
),
549+
(exit) =>
550+
environment.platform === "win32" || (Exit.isSuccess(exit) && exit.value)
551+
? Duration.infinity
552+
: Duration.zero,
540553
);
541554

542555
return DesktopShellEnvironment.of({ installIntoProcess });
Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
// @effect-diagnostics nodeBuiltinImport:off -- Exercise real shells and OpenSSH with isolated fixtures.
2+
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
3+
import * as NodeServices from "@effect/platform-node/NodeServices";
4+
import { assert, describe, it } from "@effect/vitest";
5+
import * as HostProcess from "@t3tools/shared/HostProcess";
6+
import * as NetService from "@t3tools/shared/Net";
7+
import { SshCommandError } from "@t3tools/ssh/errors";
8+
import * as Effect from "effect/Effect";
9+
import * as FileSystem from "effect/FileSystem";
10+
import * as Layer from "effect/Layer";
11+
import * as Path from "effect/Path";
12+
import * as ChildProcess from "effect/process/ChildProcess";
13+
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14+
import * as NodeOS from "node:os";
15+
import { vi } from "vite-plus/test";
16+
17+
import * as DesktopConfig from "../app/DesktopConfig.ts";
18+
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
19+
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
20+
import * as DesktopSshEnvironment from "./DesktopSshEnvironment.ts";
21+
import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts";
22+
23+
vi.mock("node:os", { spy: true });
24+
25+
const target = {
26+
alias: "managed-workspace",
27+
hostname: "helper-missing.invalid",
28+
username: null,
29+
port: null,
30+
};
31+
32+
function runRecoveryScenario(
33+
operation: "resolve" | "connect" | "still-unavailable" | "fallback-shell" | "launchctl",
34+
) {
35+
return Effect.gen(function* () {
36+
const fs = yield* FileSystem.FileSystem;
37+
const path = yield* Path.Path;
38+
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ssh-path-" });
39+
const bin = path.join(home, "bin");
40+
const helpers = path.join(home, "workspace tools");
41+
const probes = path.join(home, "probes");
42+
const ready = path.join(home, "ready");
43+
const proxyReached = path.join(home, "proxy-reached");
44+
const config = path.join(home, "ssh_config");
45+
yield* fs.makeDirectory(bin);
46+
yield* fs.makeDirectory(helpers);
47+
const inheritedPath = `${bin}:/usr/bin:/bin:/usr/sbin:/sbin`;
48+
const shellPath = `${helpers}:${inheritedPath}`;
49+
const preferredShell = path.join(bin, "preferred-shell");
50+
yield* fs.writeFileString(
51+
preferredShell,
52+
'#!/bin/sh\nexport T3_TEST_PREFERRED=1\nexec /bin/zsh "$@"\n',
53+
);
54+
yield* fs.chmod(preferredShell, 0o700);
55+
yield* fs.writeFileString(
56+
path.join(home, ".zshenv"),
57+
[
58+
"[[ -o login && -o interactive ]] || return 0",
59+
`print probe >> '${probes}'`,
60+
`if [[ ! -f '${ready}' ]]; then`,
61+
' [[ "$T3_TEST_ALLOW_FALLBACK" = 1 && -z "$T3_TEST_PREFERRED" ]] || exit 1',
62+
"fi",
63+
"",
64+
].join("\n"),
65+
);
66+
yield* fs.writeFileString(
67+
path.join(home, ".zprofile"),
68+
`if [[ -f '${ready}' ]]; then\nexport PATH='${shellPath}'\nelse\nexport PATH='${inheritedPath}'\nfi\n`,
69+
);
70+
yield* fs.writeFileString(
71+
path.join(bin, "ssh"),
72+
`#!/bin/sh\nexec /usr/bin/ssh -F '${config}' "$@"\n`,
73+
);
74+
yield* fs.chmod(path.join(bin, "ssh"), 0o700);
75+
yield* fs.writeFileString(path.join(helpers, "workspace-check"), "#!/bin/sh\nexit 0\n");
76+
yield* fs.chmod(path.join(helpers, "workspace-check"), 0o700);
77+
yield* fs.writeFileString(
78+
path.join(helpers, "workspace-proxy"),
79+
`#!/bin/sh\nprintf 'proxy invoked\\n' > '${proxyReached}'\nexit 1\n`,
80+
);
81+
yield* fs.chmod(path.join(helpers, "workspace-proxy"), 0o700);
82+
yield* fs.writeFileString(
83+
config,
84+
[
85+
'Match originalhost managed-workspace exec "workspace-check"',
86+
" HostName helper-ready.invalid",
87+
"Host managed-workspace",
88+
" HostName helper-missing.invalid",
89+
" ProxyCommand workspace-proxy",
90+
" ControlMaster no",
91+
" ControlPath none",
92+
"",
93+
].join("\n"),
94+
);
95+
96+
const layerEnvironment = DesktopEnvironment.layer({
97+
dirname: home,
98+
homeDirectory: home,
99+
platform: "darwin",
100+
processArch: yield* HostProcess.Architecture,
101+
appVersion: "0.1.0",
102+
appPath: home,
103+
isPackaged: true,
104+
resourcesPath: home,
105+
runningUnderArm64Translation: false,
106+
}).pipe(Layer.provide(DesktopConfig.layerTest({ T3CODE_HOME: home })));
107+
const layerShell = DesktopShellEnvironment.layer.pipe(Layer.provide(layerEnvironment));
108+
const layerSsh = DesktopSshEnvironment.layer({
109+
resolveCliRunner: Effect.succeed({ archiveVersion: "0.1.0" }),
110+
}).pipe(
111+
Layer.provideMerge(layerShell),
112+
Layer.provide(
113+
Layer.succeed(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {
114+
request: () => Effect.die("Unexpected authentication prompt"),
115+
resolve: () => Effect.die("Unexpected authentication response"),
116+
}),
117+
),
118+
);
119+
const program = Effect.gen(function* () {
120+
const shell = yield* DesktopShellEnvironment.DesktopShellEnvironment;
121+
const ssh = yield* DesktopSshEnvironment.DesktopSshEnvironment;
122+
assert.equal(yield* shell.installIntoProcess, false);
123+
if (operation !== "still-unavailable") yield* fs.writeFileString(ready, "");
124+
if (operation === "resolve" || operation === "fallback-shell" || operation === "launchctl") {
125+
assert.equal((yield* ssh.resolveHost(target.alias)).hostname, "helper-ready.invalid");
126+
assert.equal((yield* ssh.resolveHost(target.alias)).hostname, "helper-ready.invalid");
127+
} else {
128+
const result = yield* Effect.result(ssh.ensureEnvironment(target));
129+
assert.equal(result._tag, "Failure");
130+
if (result._tag === "Failure") assert.instanceOf(result.failure, SshCommandError);
131+
if (operation === "connect") {
132+
assert.equal(yield* fs.readFileString(proxyReached), "proxy invoked\n");
133+
assert.equal((yield* ssh.resolveHost(target.alias)).hostname, "helper-ready.invalid");
134+
} else {
135+
assert.equal(yield* fs.exists(proxyReached), false);
136+
if (result._tag === "Failure") {
137+
assert.include(result.failure.message, "workspace-proxy");
138+
}
139+
}
140+
}
141+
assert.equal(
142+
yield* fs.readFileString(probes),
143+
operation === "fallback-shell" ? "probe\nprobe\nprobe\n" : "probe\nprobe\n",
144+
);
145+
assert.equal(process.env.PATH, operation === "still-unavailable" ? inheritedPath : shellPath);
146+
}).pipe(
147+
Effect.provide(
148+
layerSsh.pipe(
149+
Layer.provideMerge(Layer.mergeAll(NodeHttpClient.layerUndici, NetService.layer)),
150+
),
151+
),
152+
);
153+
154+
const nativeSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
155+
const spawner = ChildProcessSpawner.make((command) =>
156+
nativeSpawner.spawn(
157+
operation === "launchctl" &&
158+
ChildProcess.isStandardCommand(command) &&
159+
command.command === "/bin/launchctl"
160+
? ChildProcess.make("/bin/sh", ["-c", `printf '%s' '${inheritedPath}'`])
161+
: command,
162+
),
163+
);
164+
yield* Effect.acquireUseRelease(
165+
Effect.sync(() => {
166+
const previous = process.env;
167+
process.env = {
168+
...previous,
169+
HOME: home,
170+
ZDOTDIR: home,
171+
SHELL: operation === "fallback-shell" ? preferredShell : "/bin/zsh",
172+
T3_TEST_ALLOW_FALLBACK: operation === "fallback-shell" ? "1" : "0",
173+
PATH: inheritedPath,
174+
};
175+
const spy = vi.spyOn(NodeOS, "userInfo").mockReturnValue({
176+
...NodeOS.userInfo(),
177+
shell: "/bin/zsh",
178+
});
179+
return { previous, spy };
180+
}),
181+
() => program.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
182+
({ previous, spy }) =>
183+
Effect.sync(() => {
184+
spy.mockRestore();
185+
process.env = previous;
186+
}),
187+
);
188+
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
189+
}
190+
191+
describe("SSH shell PATH recovery with real OpenSSH", () => {
192+
it.effect.runIf(HostProcess.Platform.defaultValue() === "darwin")(
193+
"retries the preferred shell when a fallback shell supplied only a degraded PATH",
194+
() => runRecoveryScenario("fallback-shell"),
195+
);
196+
it.effect.runIf(HostProcess.Platform.defaultValue() === "darwin")(
197+
"retries the login shell when launchctl supplied only a degraded PATH",
198+
() => runRecoveryScenario("launchctl"),
199+
);
200+
it.effect.runIf(HostProcess.Platform.defaultValue() === "darwin")(
201+
"recovers a failed startup capture before resolving a host and caches the recovered PATH",
202+
() => runRecoveryScenario("resolve"),
203+
);
204+
it.effect.runIf(HostProcess.Platform.defaultValue() === "darwin")(
205+
"recovers a failed startup capture before invoking a saved host's ProxyCommand",
206+
() => runRecoveryScenario("connect"),
207+
);
208+
it.effect.runIf(HostProcess.Platform.defaultValue() === "darwin")(
209+
"preserves the SSH error when PATH capture is still unavailable",
210+
() => runRecoveryScenario("still-unavailable"),
211+
);
212+
});

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import * as FileSystem from "effect/FileSystem";
88
import * as Layer from "effect/Layer";
99
import * as Path from "effect/Path";
1010

11+
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
1112
import * as DesktopSshEnvironment from "./DesktopSshEnvironment.ts";
1213
import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts";
1314

@@ -115,6 +116,11 @@ describe("sshEnvironment", () => {
115116
}).pipe(
116117
Effect.provide(
117118
DesktopSshEnvironment.layer().pipe(
119+
Layer.provide(
120+
Layer.succeed(DesktopShellEnvironment.DesktopShellEnvironment, {
121+
installIntoProcess: Effect.succeed(true),
122+
}),
123+
),
118124
Layer.provideMerge(
119125
Layer.succeed(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {
120126
request: () => Effect.die("unexpected password prompt request"),

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

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import * as Path from "effect/Path";
2626
import * as HttpClient from "effect/http/HttpClient";
2727
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
2828

29+
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
2930
import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts";
3031

3132
export type DesktopSshEnvironmentRuntimeServices =
@@ -128,6 +129,7 @@ const makePasswordPrompt = (
128129
/** @public Service construction is part of the canonical Effect module API. */
129130
export const make = Effect.gen(function* () {
130131
const manager = yield* SshTunnel.SshEnvironmentManager;
132+
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
131133
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
132134
const runtimeContext = yield* Effect.context<DesktopSshEnvironmentRuntimeServices>();
133135
const passwordPrompt = SshAuth.SshPasswordPrompt.of(makePasswordPrompt(prompts));
@@ -139,26 +141,25 @@ export const make = Effect.gen(function* () {
139141
Effect.withSpan("desktop.ssh.discoverHosts"),
140142
),
141143
resolveHost: (alias) =>
142-
resolveSshTarget(alias.trim()).pipe(
144+
shellEnvironment.installIntoProcess.pipe(
145+
Effect.andThen(() => resolveSshTarget(alias.trim())),
143146
Effect.provide(runtimeContext),
144147
Effect.withSpan("desktop.ssh.resolveHost"),
145148
),
146149
ensureEnvironment: (target, ensureOptions) =>
147-
manager
148-
.ensureEnvironment(target, ensureOptions)
149-
.pipe(
150-
Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),
151-
Effect.provide(runtimeContext),
152-
Effect.withSpan("desktop.ssh.ensureEnvironment"),
153-
),
150+
shellEnvironment.installIntoProcess.pipe(
151+
Effect.andThen(() => manager.ensureEnvironment(target, ensureOptions)),
152+
Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),
153+
Effect.provide(runtimeContext),
154+
Effect.withSpan("desktop.ssh.ensureEnvironment"),
155+
),
154156
disconnectEnvironment: (target) =>
155-
manager
156-
.disconnectEnvironment(target)
157-
.pipe(
158-
Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),
159-
Effect.provide(runtimeContext),
160-
Effect.withSpan("desktop.ssh.disconnectEnvironment"),
161-
),
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+
),
162163
});
163164
});
164165

0 commit comments

Comments
 (0)