@devries-cameron20 / t3code Mirror · read-only / commits / abc0fde5e0
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 13:30 UTC

fix(desktop): providers are found after a failed shell probe without relaunching (#30667)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>

tatsuaki watanabe committed Nov 15, 2026 at 08:59 UTC abc0fde5e063d77ffa324a7ec491976661e441d2
2 files changed +241 -37
apps/desktop/src/shell/DesktopShellEnvironment.test.ts
+137
@@ -2,6 +2,7 @@
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { assert, describe, it } from "@effect/vitest";
4 import * as HostProcess from "@t3tools/shared/HostProcess";
5 +import * as Duration from "effect/Duration";
6 import * as Effect from "effect/Effect";
7 import * as Fiber from "effect/Fiber";
8 import * as Deferred from "effect/Deferred";
@@ -62,6 +63,26 @@ function makeProcess(output: string, exitCode = 0): ChildProcessSpawner.ChildPro
63 });
64 }
65
66 +function makeSlowProcess(
67 + output: string,
68 + delay: Duration.Input,
69 +): ChildProcessSpawner.ChildProcessHandle {
70 + const stdout = Stream.fromEffect(Effect.as(Effect.sleep(delay), textEncoder.encode(output)));
71 + return ChildProcessSpawner.makeHandle({
72 + pid: ChildProcessSpawner.ProcessId(125),
73 + stdout,
74 + stderr: Stream.empty,
75 + all: stdout,
76 + exitCode: Effect.as(Effect.sleep(delay), ChildProcessSpawner.ExitCode(0)),
77 + isRunning: Effect.succeed(true),
78 + kill: () => Effect.void,
79 + stdin: Sink.drain,
80 + getInputFd: () => Sink.drain,
81 + getOutputFd: () => Stream.empty,
82 + unref: Effect.succeed(Effect.void),
83 + });
84 +}
85 +
86 function makeHungProcess(): ChildProcessSpawner.ChildProcessHandle {
87 return ChildProcessSpawner.makeHandle({
88 pid: ChildProcessSpawner.ProcessId(124),
@@ -670,6 +691,122 @@ describe("DesktopShellEnvironment", () => {
691 }),
692 );
693
694 + it.effect("retries the user's shell when only the fallback shell answered", () =>
695 + Effect.gen(function* () {
696 + const env: NodeJS.ProcessEnv = { SHELL: "/usr/bin/fish", PATH: "/usr/bin" };
697 + const commands: string[] = [];
698 + let fishReady = false;
699 + yield* runShellEnvironment({
700 + env,
701 + platform: "linux",
702 + handler: (command) => {
703 + if (command._tag !== "StandardCommand") return "";
704 + commands.push(command.command);
705 + if (command.command !== "/usr/bin/fish") return envOutput({ PATH: "/usr/bin" });
706 + return fishReady
707 + ? envOutput({ PATH: "/fish/bin:/usr/bin" })
708 + : { output: "", exitCode: 7 };
709 + },
710 + use: (service) =>
711 + Effect.gen(function* () {
712 + assert.isTrue(yield* service.awaitDiscovery);
713 + assert.equal(env.PATH, "/usr/bin");
714 +
715 + fishReady = true;
716 + yield* TestClock.adjust("30 seconds");
717 + assert.equal(env.PATH, "/fish/bin:/usr/bin");
718 + return true;
719 + }),
720 + }).pipe(Effect.provide(Logger.layer([])));
721 + assert.deepEqual(commands, ["/usr/bin/fish", "/bin/bash", "/usr/bin/fish"]);
722 +
723 + // With no user shell to wait for, the fallback's answer is final.
724 + commands.length = 0;
725 + yield* runShellEnvironment({
726 + env: { PATH: "/usr/bin" },
727 + platform: "linux",
728 + handler: (command) => {
729 + if (command._tag === "StandardCommand") commands.push(command.command);
730 + return envOutput({ PATH: "/usr/bin" });
731 + },
732 + use: (service) =>
733 + Effect.gen(function* () {
734 + assert.isTrue(yield* service.awaitDiscovery);
735 + yield* TestClock.adjust("5 minutes");
736 + return true;
737 + }),
738 + }).pipe(Effect.provide(Logger.layer([])));
739 + assert.deepEqual(commands, ["/bin/bash"]);
740 + }),
741 + );
742 +
743 + it.effect("gives background retries time for a locked or slow shell, then publishes", () =>
744 + Effect.gen(function* () {
745 + const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
746 + // Startup fails fast, the first retry meets a shell blocked on a lock, the second a slow one.
747 + const spawned = yield* Effect.forEach([0, 1, 2], () => Deferred.make<void>());
748 + const stopped = yield* Deferred.make<ChildProcess.KillOptions>();
749 + let attempts = 0;
750 + yield* runShellEnvironment({
751 + env,
752 + platform: "darwin",
753 + handler: () => "",
754 + processSpawner: ChildProcessSpawner.make((command) => {
755 + if (command._tag !== "StandardCommand" || command.command !== "/bin/zsh") {
756 + return Effect.succeed(makeProcess(""));
757 + }
758 + const attempt = attempts++;
759 + const spawn = Deferred.succeed(spawned[attempt]!, undefined);
760 + if (attempt === 0) return spawn.pipe(Effect.as(makeProcess("")));
761 + if (attempt === 1) {
762 + return spawn.pipe(
763 + Effect.andThen(
764 + Effect.acquireRelease(Effect.succeed(makeHungProcess()), () =>
765 + Deferred.succeed(stopped, command.options),
766 + ),
767 + ),
768 + );
769 + }
770 + return spawn.pipe(
771 + Effect.as(makeSlowProcess(envOutput({ PATH: "/fresh/bin" }), "20 seconds")),
772 + );
773 + }),
774 + use: (service) =>
775 + Effect.gen(function* () {
776 + assert.isFalse(yield* service.awaitDiscovery);
777 + const published = yield* service.updates.pipe(
778 + Stream.drop(1),
779 + Stream.runHead,
780 + Effect.forkChild({ startImmediately: true }),
781 + );
782 +
783 + yield* TestClock.adjust("30 seconds");
784 + yield* Deferred.await(spawned[1]!);
785 + // pyenv waits up to 60 s on its rehash lock before the shell continues.
786 + yield* TestClock.adjust("1 minute");
787 + assert.isFalse(yield* Deferred.isDone(stopped));
788 + yield* TestClock.adjust("1 minute");
789 + const stop = yield* Deferred.await(stopped);
790 + // pyenv releases that lock in an EXIT trap, which SIGTERM runs and SIGKILL skips.
791 + assert.equal(stop.killSignal, "SIGTERM");
792 + assert.isAtLeast(Duration.toMillis(stop.forceKillAfter ?? 0), 5_000);
793 +
794 + yield* TestClock.adjust("30 seconds");
795 + yield* Deferred.await(spawned[2]!);
796 + yield* TestClock.adjust("20 seconds");
797 + const snapshot = yield* Fiber.join(published);
798 + assert.equal(env.PATH, "/fresh/bin:/usr/bin");
799 + assert.isTrue(Option.isSome(snapshot) && snapshot.value.discovered);
800 + assert.equal(
801 + Option.isSome(snapshot) ? snapshot.value.environment.PATH : undefined,
802 + "/fresh/bin:/usr/bin",
803 + );
804 + return true;
805 + }),
806 + });
807 + }),
808 + );
809 +
810 it.effect("recovers the login-shell PATH when the first probe outlasts the timeout", () =>
811 Effect.gen(function* () {
812 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" };
apps/desktop/src/shell/DesktopShellEnvironment.ts
+104 -37
@@ -15,6 +15,7 @@ import * as Deferred from "effect/Deferred";
15 import * as Path from "effect/Path";
16 import * as PubSub from "effect/PubSub";
17 import * as Ref from "effect/Ref";
18 +import * as Schedule from "effect/Schedule";
19 import * as Scope from "effect/Scope";
20 import * as FileSystem from "effect/FileSystem";
21 import * as Layer from "effect/Layer";
@@ -28,9 +29,17 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
29
30 type EnvironmentPatch = Record<string, string>;
31
32 +interface ProbeBudget {
33 + readonly timeout: Duration.Duration;
34 + // One longer wait for the first login shell that times out.
35 + readonly slowTimeout?: Duration.Duration;
36 + readonly terminateGrace: Duration.Duration;
37 +}
38 +
39 interface ShellEnvironmentConfig {
40 readonly env: NodeJS.ProcessEnv;
41 readonly platform: NodeJS.Platform;
42 + readonly budget: ProbeBudget;
43 }
44
45 interface WindowsProbeOptions {
@@ -125,6 +134,20 @@ const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
134 const SLOW_LOGIN_SHELL_TIMEOUT = Duration.seconds(20);
135 const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
136 const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
137 +const STARTUP_PROBE: ProbeBudget = {
138 + timeout: LOGIN_SHELL_TIMEOUT,
139 + slowTimeout: SLOW_LOGIN_SHELL_TIMEOUT,
140 + terminateGrace: PROCESS_TERMINATE_GRACE,
141 +};
142 +// Retries block nothing, so they outlast pyenv's 60 s wait on its rehash lock, and SIGTERM gets
143 +// time to run the exit trap that releases it. A SIGKILL leaves the lock for two minutes.
144 +const RETRY_PROBE: ProbeBudget = {
145 + timeout: Duration.minutes(2),
146 + terminateGrace: Duration.seconds(10),
147 +};
148 +// A Mac asleep at launch fails the first probe on wake, and nothing else would probe again.
149 +const DISCOVERY_RETRY_DELAY = Duration.seconds(30);
150 +const DISCOVERY_RETRIES = 10;
151
152 const trimNonEmpty = (value: string | null | undefined): Option.Option<string> =>
153 Option.fromNullishOr(value).pipe(
@@ -245,6 +268,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
268 readonly args: ReadonlyArray<string>;
269 readonly env: NodeJS.ProcessEnv;
270 readonly timeout: Duration.Duration;
271 + readonly terminateGrace?: Duration.Duration;
272 readonly shell?: boolean;
273 }): Effect.fn.Return<
274 string,
@@ -263,7 +287,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
287 stdout: "pipe",
288 stderr: "ignore",
289 killSignal: "SIGTERM",
266 - forceKillAfter: PROCESS_TERMINATE_GRACE,
290 + forceKillAfter: input.terminateGrace ?? PROCESS_TERMINATE_GRACE,
291 }),
292 );
293 return yield* Effect.all([Stream.mkString(Stream.decodeText(child.stdout)), child.exitCode], {
@@ -329,6 +353,7 @@ const readLoginShellEnvironment = (
353 names: ReadonlyArray<string>,
354 env: NodeJS.ProcessEnv,
355 timeout: Duration.Duration,
356 + terminateGrace: Duration.Duration,
357 ): Effect.Effect<
358 EnvironmentPatch,
359 DesktopShellEnvironmentCommandTimeoutError,
@@ -342,6 +367,7 @@ const readLoginShellEnvironment = (
367 args: ["-ilc", buildEnvironmentCaptureCommand(shell, names)],
368 env,
369 timeout,
370 + terminateGrace,
371 }).pipe(Effect.map((output) => extractEnvironment(output, names)));
372
373 const readLaunchctlPath = (env: NodeJS.ProcessEnv) =>
@@ -358,6 +384,7 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn
384 names: ReadonlyArray<string>,
385 options: WindowsProbeOptions,
386 env: NodeJS.ProcessEnv,
387 + budget: ProbeBudget,
388 ): Effect.fn.Return<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> {
389 if (names.length === 0) return {};
390
@@ -375,7 +402,8 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn
402 command,
403 args,
404 env,
378 - timeout: LOGIN_SHELL_TIMEOUT,
405 + timeout: budget.timeout,
406 + terminateGrace: budget.terminateGrace,
407 }).pipe(orEmptyOnTimeout);
408 const environment = extractEnvironment(output, names);
409 if (Object.keys(environment).length > 0) {
@@ -393,8 +421,13 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
421 ): Effect.fn.Return<boolean, never, ChildProcessSpawner.ChildProcessSpawner> {
422 const [noProfile, profile] = yield* Effect.all(
423 [
396 - readWindowsEnvironment(["PATH"], { loadProfile: false }, config.env),
397 - readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }, config.env),
424 + readWindowsEnvironment(["PATH"], { loadProfile: false }, config.env, config.budget),
425 + readWindowsEnvironment(
426 + WINDOWS_PROFILE_ENV_NAMES,
427 + { loadProfile: true },
428 + config.env,
429 + config.budget,
430 + ),
431 ],
432 { concurrency: 2 },
433 );
@@ -418,6 +451,9 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
451 },
452 );
453
454 +const listUserShells = (env: NodeJS.ProcessEnv): ReadonlyArray<string> =>
455 + [env.SHELL?.trim(), readUserLoginShell()].filter((shell): shell is string => Boolean(shell));
456 +
457 const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
458 function* (
459 config: ShellEnvironmentConfig,
@@ -428,22 +464,28 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
464 > {
465 const fileSystem = yield* FileSystem.FileSystem;
466 const shellEnvironment: EnvironmentPatch = {};
431 - const userShells = [config.env.SHELL?.trim(), readUserLoginShell()];
467 + const userShells = listUserShells(config.env);
468
469 let answeredBy: string | undefined;
470 let waitedForSlowShell = false;
471 for (const shell of listLoginShellCandidates(config.platform, config.env.SHELL)) {
472 const read = (timeout: Duration.Duration) =>
437 - readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES, config.env, timeout);
473 + readLoginShellEnvironment(
474 + shell,
475 + LOGIN_SHELL_ENV_NAMES,
476 + config.env,
477 + timeout,
478 + config.budget.terminateGrace,
479 + );
480 Object.assign(
481 shellEnvironment,
440 - yield* read(LOGIN_SHELL_TIMEOUT).pipe(
482 + yield* read(config.budget.timeout).pipe(
483 Effect.catchTags({
484 DesktopShellEnvironmentCommandTimeoutError: (error) => {
443 - const retry = !waitedForSlowShell;
485 + const slowTimeout = waitedForSlowShell ? undefined : config.budget.slowTimeout;
486 waitedForSlowShell = true;
487 return logShellEnvironmentCommandError(error).pipe(
446 - Effect.andThen(retry ? read(SLOW_LOGIN_SHELL_TIMEOUT) : Effect.succeed({})),
488 + Effect.andThen(slowTimeout ? read(slowTimeout) : Effect.succeed({})),
489 );
490 },
491 }),
@@ -557,7 +599,10 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
599 }
600
601 const prepared = Option.isSome(trimNonEmpty(shellEnvironment.PATH));
560 - return { prepared, fromUserShell: prepared && userShells.includes(answeredBy) };
602 + return {
603 + prepared,
604 + fromUserShell: prepared && answeredBy !== undefined && userShells.includes(answeredBy),
605 + };
606 },
607 );
608
@@ -641,38 +686,60 @@ export const make = Effect.gen(function* () {
686 yield* Ref.set(latest, Option.some(message));
687 yield* PubSub.publish(changes, message);
688 });
644 - const refresh = Effect.gen(function* () {
645 - // Refresh from the inherited baseline so removed cached paths and values do not survive.
646 - const fresh = { ...inherited };
647 - const discovery = yield* installShellEnvironment({
648 - env: fresh,
649 - platform: environment.platform,
650 - });
651 - const { prepared } = discovery;
652 - const patch = Object.fromEntries(
653 - Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]),
654 - );
655 - if (prepared || Option.isNone(yield* Ref.get(latest))) yield* publish(patch, prepared);
656 - if (prepared) {
657 - const cached = Object.fromEntries(
658 - CACHED_ENV_NAMES.flatMap((name) => (fresh[name] ? [[name, fresh[name]]] : [])),
659 - );
660 - const persist = Effect.gen(function* () {
661 - const encoded = yield* encodeCache({ version: 1, key, environment: cached });
662 - yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
663 - yield* fileSystem.writeFileString(cachePath + ".tmp", encoded, { mode: 0o600 });
664 - yield* fileSystem.rename(cachePath + ".tmp", cachePath);
689 + const probe = Effect.fn("desktop.shellEnvironment.refresh")(
690 + function* (budget: ProbeBudget) {
691 + // Refresh from the inherited baseline so removed cached paths and values do not survive.
692 + const fresh = { ...inherited };
693 + const discovery = yield* installShellEnvironment({
694 + env: fresh,
695 + platform: environment.platform,
696 + budget,
697 });
666 - yield* persist.pipe(
667 - Effect.catch(() => Effect.logWarning("Could not cache shell environment")),
698 + const { prepared } = discovery;
699 + const patch = Object.fromEntries(
700 + Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]),
701 );
669 - }
670 - return discovery;
671 - }).pipe(
702 + if (prepared || Option.isNone(yield* Ref.get(latest))) yield* publish(patch, prepared);
703 + if (prepared) {
704 + const cached = Object.fromEntries(
705 + CACHED_ENV_NAMES.flatMap((name) => (fresh[name] ? [[name, fresh[name]]] : [])),
706 + );
707 + const persist = Effect.gen(function* () {
708 + const encoded = yield* encodeCache({ version: 1, key, environment: cached });
709 + yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
710 + yield* fileSystem.writeFileString(cachePath + ".tmp", encoded, { mode: 0o600 });
711 + yield* fileSystem.rename(cachePath + ".tmp", cachePath);
712 + });
713 + yield* persist.pipe(
714 + Effect.catch(() => Effect.logWarning("Could not cache shell environment")),
715 + );
716 + }
717 + return discovery;
718 + },
719 Effect.provideService(FileSystem.FileSystem, fileSystem),
720 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
674 - Effect.withSpan("desktop.shellEnvironment.refresh"),
721 + );
722 + // A fallback shell's PATH can miss folders the user's own shell adds, so keep asking that shell.
723 + const awaitsUserShell = listUserShells(inherited).length > 0;
724 + const settled = ({ prepared, fromUserShell }: ShellDiscovery) =>
725 + fromUserShell || (prepared && !awaitsUserShell);
726 + const refresh = probe(STARTUP_PROBE).pipe(
727 Effect.onExit((exit) => Deferred.done(discovered, exit)),
728 + Effect.flatMap((discovery) =>
729 + settled(discovery)
730 + ? Effect.void
731 + : Effect.sleep(DISCOVERY_RETRY_DELAY).pipe(
732 + Effect.andThen(
733 + probe(RETRY_PROBE).pipe(
734 + Effect.repeat({
735 + until: settled,
736 + schedule: Schedule.spaced(DISCOVERY_RETRY_DELAY),
737 + times: DISCOVERY_RETRIES - 1,
738 + }),
739 + ),
740 + ),
741 + ),
742 + ),
743 );
744 const installIntoProcess = yield* Effect.cached(
745 Effect.gen(function* () {