Skip to content

Commit 28b6b6f

Browse files
committed
fix(desktop): recover failed shell environment capture
1 parent 357b8d5 commit 28b6b6f

5 files changed

Lines changed: 201 additions & 17 deletions

File tree

‎apps/desktop/src/app/DesktopApp.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as Cause from "effect/Cause";
22
import * as Effect from "effect/Effect";
33
import * as Option from "effect/Option";
44
import * as Ref from "effect/Ref";
5+
import * as Result from "effect/Result";
56
import * as Schema from "effect/Schema";
67

78
import * as NetService from "@t3tools/shared/Net";
@@ -26,6 +27,7 @@ import * as DesktopShutdown from "./DesktopShutdown.ts";
2627
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
2728
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
2829
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
30+
import { recoverShellEnvironment } from "../shell/DesktopShellEnvironmentRecovery.ts";
2931
import * as DesktopState from "./DesktopState.ts";
3032
import * as DesktopRemoteUpdates from "../updates/DesktopRemoteUpdates.ts";
3133
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
@@ -242,7 +244,7 @@ const startup = Effect.gen(function* () {
242244
const updates = yield* DesktopUpdates.DesktopUpdates;
243245
const environment = yield* DesktopEnvironment.DesktopEnvironment;
244246

245-
yield* shellEnvironment.installIntoProcess;
247+
const shellEnvironmentResult = yield* Effect.result(shellEnvironment.installIntoProcess);
246248
const hasCommandLinePasswordStore =
247249
preReadyElectronOptions.linuxPasswordStoreCommandLine !== null;
248250
const linuxElectronOptions =
@@ -287,6 +289,11 @@ const startup = Effect.gen(function* () {
287289
Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
288290
);
289291
yield* logStartupInfo("app ready");
292+
if (Result.isFailure(shellEnvironmentResult)) {
293+
yield* recoverShellEnvironment().pipe(
294+
Effect.catchCause((cause) => fatalStartupCause("shell environment recovery", cause)),
295+
);
296+
}
290297
if (environment.platform === "linux") {
291298
const selectedBackend = yield* safeStorage.selectedStorageBackend;
292299
yield* logStartupInfo("safe storage ready", {

‎apps/desktop/src/app/DesktopAppErrors.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
import { assert, describe, it } from "@effect/vitest";
2+
import * as Effect from "effect/Effect";
3+
import * as Layer from "effect/Layer";
4+
import { recoverShellEnvironment } from "../shell/DesktopShellEnvironmentRecovery.ts";
5+
import * as ElectronDialog from "../electron/ElectronDialog.ts";
6+
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
27

38
import {
49
DesktopBackendPortUnavailableError,
@@ -28,3 +33,44 @@ describe("DesktopApp errors", () => {
2833
assert.equal(error.message, "T3CODE_PORT is required in desktop development.");
2934
});
3035
});
36+
37+
describe("shell environment recovery", () => {
38+
it.effect.each([
39+
{ responses: [0], failures: 0, attempts: 1 },
40+
{ responses: [0, 0], failures: 1, attempts: 2 },
41+
{ responses: [1], failures: 0, attempts: 0 },
42+
{ responses: [0, 1], failures: 1, attempts: 1 },
43+
])("recovers or continues: %j", ({ responses, failures, attempts }) =>
44+
Effect.gen(function* () {
45+
let captures = 0;
46+
let dialogs = 0;
47+
yield* recoverShellEnvironment().pipe(
48+
Effect.provide(
49+
Layer.mergeAll(
50+
Layer.succeed(DesktopShellEnvironment.DesktopShellEnvironment, {
51+
installIntoProcess: Effect.suspend(() => {
52+
captures++;
53+
return captures <= failures
54+
? Effect.fail(new DesktopShellEnvironment.DesktopShellEnvironmentCaptureError())
55+
: Effect.void;
56+
}),
57+
}),
58+
Layer.succeed(ElectronDialog.ElectronDialog, {
59+
pickFolder: () => Effect.die("unused"),
60+
pickFiles: () => Effect.die("unused"),
61+
showErrorBox: () => Effect.die("unused"),
62+
showMessageBox: () =>
63+
Effect.sync(() => {
64+
const response = responses[dialogs++];
65+
assert.isDefined(response);
66+
return { response: response ?? 1, checkboxChecked: false };
67+
}),
68+
}),
69+
),
70+
),
71+
);
72+
assert.equal(captures, attempts);
73+
assert.equal(dialogs, responses.length);
74+
}),
75+
);
76+
});

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

Lines changed: 91 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
import * as NodeServices from "@effect/platform-node/NodeServices";
22
import { assert, describe, it } from "@effect/vitest";
33
import * as Effect from "effect/Effect";
4+
import * as Exit from "effect/Exit";
5+
import * as Fiber from "effect/Fiber";
6+
import * as TestClock from "effect/testing/TestClock";
47
import * as Layer from "effect/Layer";
58
import * as Logger from "effect/Logger";
9+
import * as Option from "effect/Option";
10+
import type * as Tracer from "effect/Tracer";
611
import * as PlatformError from "effect/PlatformError";
712
import * as Schema from "effect/Schema";
813
import * as Sink from "effect/Sink";
@@ -67,7 +72,7 @@ function withProcessEnv<A, E, R>(
6772
function runShellEnvironment(input: {
6873
readonly env: NodeJS.ProcessEnv;
6974
readonly platform: NodeJS.Platform;
70-
readonly handler: (command: ChildProcess.Command) => string;
75+
readonly handler: (command: ChildProcess.Command) => string | Effect.Effect<string>;
7176
readonly failure?: PlatformError.PlatformError;
7277
}) {
7378
const environmentLayer = Layer.succeed(
@@ -79,9 +84,13 @@ function runShellEnvironment(input: {
7984
const spawnerLayer = Layer.succeed(
8085
ChildProcessSpawner.ChildProcessSpawner,
8186
ChildProcessSpawner.make((command) =>
82-
input.failure === undefined
83-
? Effect.succeed(makeProcess(input.handler(command)))
84-
: Effect.fail(input.failure),
87+
Effect.suspend(() => {
88+
if (input.failure !== undefined) return Effect.fail(input.failure);
89+
const output = input.handler(command);
90+
return (Effect.isEffect(output) ? output : Effect.succeed(output)).pipe(
91+
Effect.map(makeProcess),
92+
);
93+
}),
8594
),
8695
);
8796

@@ -129,6 +138,75 @@ describe("DesktopShellEnvironment", () => {
129138
}),
130139
);
131140

141+
it.effect("retries a timed-out login shell before starting with an incomplete PATH", () =>
142+
Effect.gen(function* () {
143+
const env = { SHELL: "/bin/zsh", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" };
144+
let attempts = 0;
145+
const capture = yield* runShellEnvironment({
146+
env,
147+
platform: "darwin",
148+
handler: (command) => {
149+
if (command._tag !== "StandardCommand" || command.command === "/bin/launchctl") return "";
150+
attempts++;
151+
return attempts === 1 ? Effect.never : envOutput({ PATH: "/opt/homebrew/bin:/usr/bin" });
152+
},
153+
}).pipe(Effect.forkChild);
154+
155+
yield* TestClock.adjust("5 seconds");
156+
yield* Fiber.join(capture);
157+
assert.equal(attempts, 2);
158+
assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin");
159+
}),
160+
);
161+
162+
it.effect("fails capture when both login shell and launchctl provide no PATH", () =>
163+
Effect.gen(function* () {
164+
const env = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
165+
const spans = new Map<string, Tracer.Span>();
166+
const result = yield* runShellEnvironment({
167+
env,
168+
platform: "darwin",
169+
handler: () =>
170+
Effect.gen(function* () {
171+
let span: Tracer.AnySpan = yield* Effect.currentSpan.pipe(Effect.orDie);
172+
while (span._tag === "Span") {
173+
spans.set(span.name, span);
174+
if (Option.isNone(span.parent)) break;
175+
span = span.parent.value;
176+
}
177+
return "";
178+
}),
179+
}).pipe(Effect.exit);
180+
assert.isTrue(Exit.isFailure(result));
181+
for (const name of ["installPosixEnvironment", "installIntoProcess"]) {
182+
const status = spans.get(`desktop.shellEnvironment.${name}`)?.status;
183+
assert.equal(status?._tag, "Ended");
184+
if (status?._tag === "Ended") assert.isTrue(Exit.isFailure(status.exit));
185+
}
186+
assert.equal(env.PATH, "/usr/bin");
187+
}),
188+
);
189+
190+
it.effect("bounds repeated timeouts and still tries launchctl", () =>
191+
Effect.gen(function* () {
192+
const env = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
193+
const commands: string[] = [];
194+
const capture = yield* runShellEnvironment({
195+
env,
196+
platform: "darwin",
197+
handler: (command) => {
198+
if (command._tag !== "StandardCommand") return "";
199+
commands.push(command.command);
200+
return command.command === "/bin/launchctl" ? "" : Effect.never;
201+
},
202+
}).pipe(Effect.exit, Effect.forkChild);
203+
204+
yield* TestClock.adjust("10 seconds");
205+
assert.isTrue(Exit.isFailure(yield* Fiber.join(capture)));
206+
assert.deepEqual(commands, ["/bin/zsh", "/bin/zsh", "/bin/launchctl"]);
207+
}),
208+
);
209+
132210
it.effect("preserves inherited POSIX values when present", () =>
133211
Effect.gen(function* () {
134212
const env: NodeJS.ProcessEnv = {
@@ -294,7 +372,13 @@ describe("DesktopShellEnvironment", () => {
294372
},
295373
});
296374

297-
assert.deepEqual(commands, ["/opt/homebrew/bin/nu", "/bin/zsh", "/bin/launchctl"]);
375+
assert.deepEqual(commands, [
376+
"/opt/homebrew/bin/nu",
377+
"/opt/homebrew/bin/nu",
378+
"/bin/zsh",
379+
"/bin/zsh",
380+
"/bin/launchctl",
381+
]);
298382
assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin");
299383
}),
300384
);
@@ -429,12 +513,13 @@ describe("DesktopShellEnvironment", () => {
429513
handler: () => "",
430514
failure: cause,
431515
}).pipe(
516+
Effect.exit,
432517
Effect.andThen(
433518
Effect.sync(() => {
434519
const errors = messages
435520
.flatMap((message) => (Array.isArray(message) ? message : [message]))
436521
.filter(isDesktopShellEnvironmentCommandError);
437-
assert.lengthOf(errors, 1);
522+
assert.lengthOf(errors, 2);
438523
assert.equal(errors[0]?.probe, "login-shell");
439524
assert.equal(errors[0]?.executable, "bash");
440525
assert.equal(errors[0]?.argumentCount, 2);

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

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,19 @@ export class DesktopShellEnvironmentCommandTimeoutError extends Schema.TaggedErr
6060
}
6161
}
6262

63+
export class DesktopShellEnvironmentCaptureError extends Schema.TaggedErrorClass<DesktopShellEnvironmentCaptureError>()(
64+
"DesktopShellEnvironmentCaptureError",
65+
{},
66+
) {
67+
override get message(): string {
68+
return "The shell environment could not be captured.";
69+
}
70+
}
71+
6372
export class DesktopShellEnvironment extends Context.Service<
6473
DesktopShellEnvironment,
6574
{
66-
readonly installIntoProcess: Effect.Effect<void>;
75+
readonly installIntoProcess: Effect.Effect<void, DesktopShellEnvironmentCaptureError>;
6776
}
6877
>()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
6978

@@ -342,7 +351,10 @@ const readLoginShellEnvironment = (
342351
command: shell,
343352
args: ["-ilc", capturePosixEnvironmentCommand(names)],
344353
timeout: LOGIN_SHELL_TIMEOUT,
345-
}).pipe(Effect.map((output) => extractEnvironment(output, names)));
354+
}).pipe(
355+
Effect.map((output) => extractEnvironment(output, names)),
356+
Effect.repeat({ times: 1, while: (environment) => !environment.PATH?.trim() }),
357+
);
346358

347359
const readLaunchctlPath = runCommandOutput({
348360
probe: "launchctl-path",
@@ -423,7 +435,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
423435
config: ShellEnvironmentConfig,
424436
): Effect.fn.Return<
425437
void,
426-
never,
438+
DesktopShellEnvironmentCaptureError,
427439
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
428440
> {
429441
const fileSystem = yield* FileSystem.FileSystem;
@@ -434,17 +446,17 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
434446
shellEnvironment,
435447
yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES),
436448
);
437-
if (shellEnvironment.PATH) break;
449+
if (shellEnvironment.PATH?.trim()) break;
438450
}
439451

440452
const launchctlPath =
441-
config.platform === "darwin" && !shellEnvironment.PATH
453+
config.platform === "darwin" && !shellEnvironment.PATH?.trim()
442454
? yield* readLaunchctlPath
443455
: Option.none<string>();
444-
const mergedPath = mergePaths(config.platform, [
445-
trimNonEmpty(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
446-
readEnvPath(config.env),
447-
]);
456+
const capturedPath = trimNonEmpty(shellEnvironment.PATH).pipe(
457+
Option.orElse(() => launchctlPath),
458+
);
459+
const mergedPath = mergePaths(config.platform, [capturedPath, readEnvPath(config.env)]);
448460

449461
if (Option.isSome(mergedPath)) {
450462
config.env.PATH = mergedPath.value;
@@ -518,12 +530,19 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
518530
}
519531
}
520532
}
533+
if (Option.isNone(capturedPath)) {
534+
return yield* new DesktopShellEnvironmentCaptureError();
535+
}
521536
},
522537
);
523538

524539
const installShellEnvironment = (
525540
config: ShellEnvironmentConfig,
526-
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem> => {
541+
): Effect.Effect<
542+
void,
543+
DesktopShellEnvironmentCaptureError,
544+
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
545+
> => {
527546
if (config.platform === "win32") {
528547
return installWindowsEnvironment(config);
529548
}
@@ -546,6 +565,7 @@ export const make = Effect.gen(function* () {
546565
Effect.provideService(FileSystem.FileSystem, fileSystem),
547566
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
548567
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
568+
Effect.tapError(Effect.logWarning),
549569
);
550570

551571
return DesktopShellEnvironment.of({ installIntoProcess });
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import * as Effect from "effect/Effect";
2+
import * as Result from "effect/Result";
3+
import * as ElectronDialog from "../electron/ElectronDialog.ts";
4+
import * as DesktopShellEnvironment from "./DesktopShellEnvironment.ts";
5+
6+
export const recoverShellEnvironment = Effect.fn("desktop.startup.recoverShellEnvironment")(
7+
function* () {
8+
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
9+
const electronDialog = yield* ElectronDialog.ElectronDialog;
10+
while (true) {
11+
const { response } = yield* electronDialog.showMessageBox({
12+
type: "warning",
13+
title: "T3 Code",
14+
message: "The shell environment could not be captured.",
15+
detail:
16+
"Installed agent CLIs may appear missing because T3 Code could not read your shell's PATH. Retry after checking your shell configuration, or continue and set an absolute CLI path in provider settings.",
17+
buttons: ["Retry", "Continue"],
18+
defaultId: 0,
19+
cancelId: 1,
20+
});
21+
if (response !== 0) return;
22+
const result = yield* Effect.result(shellEnvironment.installIntoProcess);
23+
if (Result.isSuccess(result)) return;
24+
}
25+
},
26+
);

0 commit comments

Comments
 (0)