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

main
ts 831 lines 28.2 KB
Raw
1 import { DesktopShellEnvironmentSnapshot, ShellEnvironmentPatch } from "@t3tools/contracts";
2 import {
3 applyShellEnvironment,
4 buildEnvironmentCaptureCommand,
5 listLoginShellCandidates,
6 mergePathValues,
7 readUserLoginShell,
8 setWindowsPath,
9 windowsEnvironmentValueCommand,
10 } from "@t3tools/shared/shell";
11 import * as Context from "effect/Context";
12 import * as Duration from "effect/Duration";
13 import * as Effect from "effect/Effect";
14 import * as Fiber from "effect/Fiber";
15 import * as Deferred from "effect/Deferred";
16 import * as Path from "effect/Path";
17 import * as PubSub from "effect/PubSub";
18 import * as Ref from "effect/Ref";
19 import * as Schedule from "effect/Schedule";
20 import * as Scope from "effect/Scope";
21 import * as FileSystem from "effect/FileSystem";
22 import * as Layer from "effect/Layer";
23 import * as Option from "effect/Option";
24 import * as Schema from "effect/Schema";
25 import * as Stream from "effect/Stream";
26 import * as ChildProcess from "effect/process/ChildProcess";
27 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
28
29 import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
30
31 type EnvironmentPatch = Record<string, string>;
32
33 interface ProbeBudget {
34 readonly timeout: Duration.Duration;
35 // One longer wait for the first login shell that times out.
36 readonly slowTimeout?: Duration.Duration;
37 readonly terminateGrace: Duration.Duration;
38 }
39
40 interface ShellEnvironmentConfig {
41 readonly env: NodeJS.ProcessEnv;
42 readonly platform: NodeJS.Platform;
43 readonly budget: ProbeBudget;
44 }
45
46 interface WindowsProbeOptions {
47 readonly loadProfile: boolean;
48 }
49
50 const DesktopShellEnvironmentProbe = Schema.Literals([
51 "login-shell",
52 "launchctl-path",
53 "powershell-profile",
54 "powershell-no-profile",
55 ]);
56 type DesktopShellEnvironmentProbe = typeof DesktopShellEnvironmentProbe.Type;
57
58 const desktopShellEnvironmentCommandFields = {
59 probe: DesktopShellEnvironmentProbe,
60 executable: Schema.String,
61 argumentCount: Schema.Number,
62 };
63
64 export class DesktopShellEnvironmentCommandError extends Schema.TaggedError<DesktopShellEnvironmentCommandError>()(
65 "DesktopShellEnvironmentCommandError",
66 {
67 ...desktopShellEnvironmentCommandFields,
68 cause: Schema.Defect(),
69 },
70 ) {
71 override get message(): string {
72 return `Desktop shell environment ${this.probe} probe (${this.executable}) failed.`;
73 }
74 }
75
76 export class DesktopShellEnvironmentCommandTimeoutError extends Schema.TaggedError<DesktopShellEnvironmentCommandTimeoutError>()(
77 "DesktopShellEnvironmentCommandTimeoutError",
78 {
79 ...desktopShellEnvironmentCommandFields,
80 timeoutMs: Schema.Number,
81 },
82 ) {
83 override get message(): string {
84 return `Desktop shell environment ${this.probe} probe (${this.executable}) timed out after ${this.timeoutMs}ms.`;
85 }
86 }
87
88 export class DesktopShellEnvironment extends Context.Service<
89 DesktopShellEnvironment,
90 {
91 // Desktop owns discovery, including on cache misses; the backend receives updates over fd4.
92 readonly installIntoProcess: Effect.Effect<boolean>;
93 readonly awaitDiscovery: Effect.Effect<boolean>;
94 /** Whether the user's own login shell, not a fallback, gave the PATH a new terminal gets. */
95 readonly awaitUserShellDiscovery: Effect.Effect<boolean>;
96 /** Whether discovery has settled (the user's shell answered or retries ran out), without waiting. */
97 readonly discoveryFinished: Effect.Effect<boolean>;
98 readonly updates: Stream.Stream<DesktopShellEnvironmentSnapshot>;
99 }
100 >()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
101
102 const LOGIN_SHELL_ENV_NAMES = [
103 "PATH",
104 "ANDROID_HOME",
105 "ANDROID_SDK_ROOT",
106 "DBUS_SESSION_BUS_ADDRESS",
107 "DISPLAY",
108 "LANG",
109 "LC_ALL",
110 "LC_CTYPE",
111 "SSH_AUTH_SOCK",
112 "HOMEBREW_PREFIX",
113 "HOMEBREW_CELLAR",
114 "HOMEBREW_REPOSITORY",
115 "XDG_CONFIG_HOME",
116 "XDG_CURRENT_DESKTOP",
117 "XDG_DATA_HOME",
118 "XDG_RUNTIME_DIR",
119 "XDG_SESSION_DESKTOP",
120 "XDG_SESSION_TYPE",
121 "WAYLAND_DISPLAY",
122 "SSL_CERT_FILE",
123 "SSL_CERT_DIR",
124 "NODE_EXTRA_CA_CERTS",
125 "T3CODE_TELEMETRY_ENABLED",
126 "T3CODE_GITHUB_APP_CLIENT_ID",
127 "T3CODE_RELEASE_BASE_URL",
128 "__MISE_DIFF",
129 "JAVA_HOME",
130 "PNPM_HOME",
131 ] as const;
132 const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
133 const LOCALE_ENV_NAMES = ["LANG", "LC_ALL", "LC_CTYPE"] as const;
134 const ANDROID_SDK_ENV_NAMES = ["ANDROID_HOME", "ANDROID_SDK_ROOT"] as const;
135 const FALLBACK_LC_CTYPE = "en_US.UTF-8";
136 const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
137 const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
138 // A profile can be slow only while the machine boots; one longer wait covers it.
139 const SLOW_LOGIN_SHELL_TIMEOUT = Duration.seconds(20);
140 const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
141 const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
142 const STARTUP_PROBE: ProbeBudget = {
143 timeout: LOGIN_SHELL_TIMEOUT,
144 slowTimeout: SLOW_LOGIN_SHELL_TIMEOUT,
145 terminateGrace: PROCESS_TERMINATE_GRACE,
146 };
147 // Retries block nothing, so they outlast pyenv's 60 s wait on its rehash lock, and SIGTERM gets
148 // time to run the exit trap that releases it. A SIGKILL leaves the lock for two minutes.
149 const RETRY_PROBE: ProbeBudget = {
150 timeout: Duration.minutes(2),
151 terminateGrace: Duration.seconds(10),
152 };
153 // A Mac asleep at launch fails the first probe on wake, and nothing else would probe again.
154 const DISCOVERY_RETRY_DELAY = Duration.seconds(30);
155 const DISCOVERY_RETRIES = 10;
156
157 const trimNonEmpty = (value: string | null | undefined): Option.Option<string> =>
158 Option.fromNullishOr(value).pipe(
159 Option.map((entry) => entry.trim()),
160 Option.filter((entry) => entry.length > 0),
161 );
162
163 // POSIX directory names may begin or end with whitespace; mergePathValues trims only on Windows.
164 const nonEmptyPath = (value: string | null | undefined): Option.Option<string> =>
165 Option.fromNullishOr(value).pipe(Option.filter((entry) => entry.length > 0));
166
167 const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
168 nonEmptyPath(env.PATH ?? env.Path ?? env.path);
169
170 const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, "");
171
172 const linuxRuntimeDirCandidates = (
173 env: NodeJS.ProcessEnv,
174 uid: number | undefined,
175 ): ReadonlyArray<string> => {
176 const candidates: string[] = [];
177 const fromEnv = trimNonEmpty(env.XDG_RUNTIME_DIR);
178 if (Option.isSome(fromEnv)) {
179 candidates.push(normalizeRuntimeDir(fromEnv.value));
180 }
181 if (uid !== undefined) {
182 candidates.push(`/run/user/${uid}`);
183 }
184 return candidates.filter((candidate) => candidate.length > 0);
185 };
186
187 const mergePaths = (
188 platform: NodeJS.Platform,
189 values: ReadonlyArray<Option.Option<string>>,
190 ): Option.Option<string> =>
191 Option.fromNullishOr(
192 values.reduce<string | undefined>(
193 (merged, value) => mergePathValues(merged, Option.getOrUndefined(value), platform),
194 undefined,
195 ),
196 );
197
198 const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
199 ...trimNonEmpty(env.APPDATA).pipe(
200 Option.match({
201 onNone: () => [],
202 onSome: (value) => [`${value}\\npm`],
203 }),
204 ),
205 ...trimNonEmpty(env.LOCALAPPDATA).pipe(
206 Option.match({
207 onNone: () => [],
208 onSome: (value) => [`${value}\\Programs\\nodejs`, `${value}\\Volta\\bin`, `${value}\\pnpm`],
209 }),
210 ),
211 ...trimNonEmpty(env.USERPROFILE).pipe(
212 Option.match({
213 onNone: () => [],
214 onSome: (value) => [`${value}\\.local\\bin`, `${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
215 }),
216 ),
217 ];
218
219 const startMarker = (name: string) => `__T3CODE_ENV_${name}_START__`;
220 const endMarker = (name: string) => `__T3CODE_ENV_${name}_END__`;
221
222 const executableName = (command: string): string => command.split(/[\\/]/u).at(-1) ?? command;
223
224 const logShellEnvironmentCommandError = (
225 error: DesktopShellEnvironmentCommandError | DesktopShellEnvironmentCommandTimeoutError,
226 ) =>
227 Effect.logWarning(error).pipe(
228 Effect.annotateLogs({
229 component: "desktop-shell-environment",
230 error,
231 }),
232 );
233
234 const captureWindowsEnvironmentCommand = (names: ReadonlyArray<string>) =>
235 [
236 "$ErrorActionPreference = 'Stop'",
237 ...names.flatMap((name) => {
238 return [
239 `Write-Output '${startMarker(name)}'`,
240 windowsEnvironmentValueCommand(name),
241 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
242 `Write-Output '${endMarker(name)}'`,
243 ];
244 }),
245 ].join("; ");
246
247 const extractEnvironment = (output: string, names: ReadonlyArray<string>): EnvironmentPatch => {
248 const environment: EnvironmentPatch = {};
249
250 for (const name of names) {
251 const start = output.indexOf(startMarker(name));
252 if (start === -1) continue;
253
254 const valueStart = start + startMarker(name).length;
255 const end = output.indexOf(endMarker(name), valueStart);
256 if (end === -1) continue;
257
258 const value = output
259 .slice(valueStart, end)
260 .replace(/^\r?\n/, "")
261 .replace(/\r?\n$/, "");
262 if (value.length > 0) {
263 environment[name] = value;
264 }
265 }
266
267 return environment;
268 };
269
270 const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(function* (input: {
271 readonly probe: DesktopShellEnvironmentProbe;
272 readonly command: string;
273 readonly args: ReadonlyArray<string>;
274 readonly env: NodeJS.ProcessEnv;
275 readonly timeout: Duration.Duration;
276 readonly terminateGrace?: Duration.Duration;
277 readonly shell?: boolean;
278 }): Effect.fn.Return<
279 string,
280 DesktopShellEnvironmentCommandTimeoutError,
281 ChildProcessSpawner.ChildProcessSpawner
282 > {
283 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
284 const fiber = yield* Effect.scoped(
285 Effect.gen(function* () {
286 const child = yield* spawner.spawn(
287 ChildProcess.make(input.command, input.args, {
288 shell: input.shell ?? false,
289 env: input.env,
290 extendEnv: false,
291 stdin: "ignore",
292 stdout: "pipe",
293 stderr: "ignore",
294 killSignal: "SIGTERM",
295 forceKillAfter: input.terminateGrace ?? PROCESS_TERMINATE_GRACE,
296 }),
297 );
298 return yield* Effect.all([Stream.mkString(Stream.decodeText(child.stdout)), child.exitCode], {
299 concurrency: 2,
300 });
301 }),
302 ).pipe(
303 Effect.mapError(
304 (cause) =>
305 new DesktopShellEnvironmentCommandError({
306 probe: input.probe,
307 executable: executableName(input.command),
308 argumentCount: input.args.length,
309 cause,
310 }),
311 ),
312 Effect.filterOrFail(
313 ([, exitCode]) => exitCode === 0,
314 ([, exitCode]) =>
315 new DesktopShellEnvironmentCommandError({
316 probe: input.probe,
317 executable: executableName(input.command),
318 argumentCount: input.args.length,
319 cause: { exitCode },
320 }),
321 ),
322 Effect.map(([stdout]) => stdout),
323 Effect.catchTags({
324 DesktopShellEnvironmentCommandError: (error) =>
325 logShellEnvironmentCommandError(error).pipe(Effect.as("")),
326 }),
327 Effect.forkDetach,
328 );
329 const output = yield* Fiber.join(fiber).pipe(
330 Effect.timeoutOption(input.timeout),
331 // Interrupting awaits the child's exit, which a shell stuck in the kernel never reaches.
332 Effect.ensuring(Fiber.interrupt(fiber).pipe(Effect.forkDetach)),
333 );
334 if (Option.isSome(output)) {
335 return output.value;
336 }
337
338 return yield* new DesktopShellEnvironmentCommandTimeoutError({
339 probe: input.probe,
340 executable: executableName(input.command),
341 argumentCount: input.args.length,
342 timeoutMs: Duration.toMillis(input.timeout),
343 });
344 });
345
346 const orEmptyOnTimeout = <R>(
347 effect: Effect.Effect<string, DesktopShellEnvironmentCommandTimeoutError, R>,
348 ): Effect.Effect<string, never, R> =>
349 effect.pipe(
350 Effect.catchTags({
351 DesktopShellEnvironmentCommandTimeoutError: (error) =>
352 logShellEnvironmentCommandError(error).pipe(Effect.as("")),
353 }),
354 );
355
356 const readLoginShellEnvironment = (
357 shell: string,
358 names: ReadonlyArray<string>,
359 env: NodeJS.ProcessEnv,
360 timeout: Duration.Duration,
361 terminateGrace: Duration.Duration,
362 ): Effect.Effect<
363 EnvironmentPatch,
364 DesktopShellEnvironmentCommandTimeoutError,
365 ChildProcessSpawner.ChildProcessSpawner
366 > =>
367 names.length === 0
368 ? Effect.succeed({})
369 : runCommandOutput({
370 probe: "login-shell",
371 command: shell,
372 args: ["-ilc", buildEnvironmentCaptureCommand(shell, names)],
373 env,
374 timeout,
375 terminateGrace,
376 }).pipe(Effect.map((output) => extractEnvironment(output, names)));
377
378 const readLaunchctlPath = (env: NodeJS.ProcessEnv) =>
379 runCommandOutput({
380 env,
381 probe: "launchctl-path",
382 command: "/bin/launchctl",
383 args: ["getenv", "PATH"],
384 timeout: LAUNCHCTL_TIMEOUT,
385 }).pipe(orEmptyOnTimeout, Effect.map(trimNonEmpty));
386
387 const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEnvironment")(
388 function* (
389 names: ReadonlyArray<string>,
390 options: WindowsProbeOptions,
391 env: NodeJS.ProcessEnv,
392 budget: ProbeBudget,
393 ): Effect.fn.Return<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> {
394 if (names.length === 0) return {};
395
396 const args = [
397 "-NoLogo",
398 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
399 "-NonInteractive",
400 "-Command",
401 captureWindowsEnvironmentCommand(names),
402 ];
403
404 for (const command of WINDOWS_SHELL_CANDIDATES) {
405 const output = yield* runCommandOutput({
406 probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile",
407 command,
408 args,
409 env,
410 timeout: budget.timeout,
411 terminateGrace: budget.terminateGrace,
412 }).pipe(orEmptyOnTimeout);
413 const environment = extractEnvironment(output, names);
414 if (Object.keys(environment).length > 0) {
415 return environment;
416 }
417 }
418
419 return {};
420 },
421 );
422
423 const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWindowsEnvironment")(
424 function* (
425 config: ShellEnvironmentConfig,
426 ): Effect.fn.Return<boolean, never, ChildProcessSpawner.ChildProcessSpawner> {
427 const [noProfile, profile] = yield* Effect.all(
428 [
429 readWindowsEnvironment(["PATH"], { loadProfile: false }, config.env, config.budget),
430 readWindowsEnvironment(
431 WINDOWS_PROFILE_ENV_NAMES,
432 { loadProfile: true },
433 config.env,
434 config.budget,
435 ),
436 ],
437 { concurrency: 2 },
438 );
439 const mergedPath = mergePaths("win32", [
440 trimNonEmpty(profile.PATH),
441 trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
442 trimNonEmpty(noProfile.PATH),
443 readEnvPath(config.env),
444 ]);
445
446 if (Option.isSome(mergedPath)) {
447 setWindowsPath(config.env, mergedPath.value);
448 }
449 if (!config.env.FNM_DIR && profile.FNM_DIR) {
450 config.env.FNM_DIR = profile.FNM_DIR;
451 }
452 if (!config.env.FNM_MULTISHELL_PATH && profile.FNM_MULTISHELL_PATH) {
453 config.env.FNM_MULTISHELL_PATH = profile.FNM_MULTISHELL_PATH;
454 }
455 return Boolean(noProfile.PATH && profile.PATH);
456 },
457 );
458
459 const listUserShells = (env: NodeJS.ProcessEnv): ReadonlyArray<string> =>
460 [env.SHELL?.trim(), readUserLoginShell()].filter((shell): shell is string => Boolean(shell));
461
462 const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
463 function* (
464 config: ShellEnvironmentConfig,
465 ): Effect.fn.Return<
466 ShellDiscovery,
467 never,
468 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
469 > {
470 const fileSystem = yield* FileSystem.FileSystem;
471 const shellEnvironment: EnvironmentPatch = {};
472 const userShells = listUserShells(config.env);
473
474 let answeredBy: string | undefined;
475 let waitedForSlowShell = false;
476 for (const shell of listLoginShellCandidates(config.platform, config.env.SHELL)) {
477 const read = (timeout: Duration.Duration) =>
478 readLoginShellEnvironment(
479 shell,
480 LOGIN_SHELL_ENV_NAMES,
481 config.env,
482 timeout,
483 config.budget.terminateGrace,
484 );
485 Object.assign(
486 shellEnvironment,
487 yield* read(config.budget.timeout).pipe(
488 Effect.catchTags({
489 DesktopShellEnvironmentCommandTimeoutError: (error) => {
490 const slowTimeout = waitedForSlowShell ? undefined : config.budget.slowTimeout;
491 waitedForSlowShell = true;
492 return logShellEnvironmentCommandError(error).pipe(
493 Effect.andThen(slowTimeout ? read(slowTimeout) : Effect.succeed({})),
494 );
495 },
496 }),
497 Effect.catchTags({
498 DesktopShellEnvironmentCommandTimeoutError: (error) =>
499 logShellEnvironmentCommandError(error).pipe(Effect.as({})),
500 }),
501 ),
502 );
503 if (shellEnvironment.PATH) {
504 answeredBy = shell;
505 break;
506 }
507 }
508
509 const launchctlPath =
510 config.platform === "darwin" && !shellEnvironment.PATH
511 ? yield* readLaunchctlPath(config.env)
512 : Option.none<string>();
513 const mergedPath = mergePaths(config.platform, [
514 nonEmptyPath(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
515 readEnvPath(config.env),
516 ]);
517
518 if (Option.isSome(mergedPath)) {
519 config.env.PATH = mergedPath.value;
520 }
521 if (!config.env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
522 config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
523 }
524
525 const shellPreferredEnvNames = [
526 "DBUS_SESSION_BUS_ADDRESS",
527 "XDG_CURRENT_DESKTOP",
528 "XDG_SESSION_DESKTOP",
529 "XDG_SESSION_TYPE",
530 // Forward mise's PATH delta too, or mise x can rebuild PATH into a recursive same-named wrapper.
531 "__MISE_DIFF",
532 ] as const;
533 for (const name of shellPreferredEnvNames) {
534 if (shellEnvironment[name]) {
535 config.env[name] = shellEnvironment[name];
536 }
537 }
538
539 for (const name of [
540 "DISPLAY",
541 "HOMEBREW_PREFIX",
542 "HOMEBREW_CELLAR",
543 "HOMEBREW_REPOSITORY",
544 "XDG_CONFIG_HOME",
545 "XDG_DATA_HOME",
546 "XDG_RUNTIME_DIR",
547 "WAYLAND_DISPLAY",
548 // Shell CA settings are required by Node/OpenSSL builds without bundled roots for registry TLS.
549 "SSL_CERT_FILE",
550 "SSL_CERT_DIR",
551 "NODE_EXTRA_CA_CERTS",
552 "JAVA_HOME",
553 "PNPM_HOME",
554 "T3CODE_TELEMETRY_ENABLED",
555 "T3CODE_GITHUB_APP_CLIENT_ID",
556 "T3CODE_RELEASE_BASE_URL",
557 ] as const) {
558 if (!config.env[name] && shellEnvironment[name]) {
559 config.env[name] = shellEnvironment[name];
560 }
561 }
562
563 // The device host picks the Android SDK from ANDROID_HOME before ANDROID_SDK_ROOT,
564 // so a profile-only ANDROID_HOME must not shadow an inherited ANDROID_SDK_ROOT.
565 if (ANDROID_SDK_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))) {
566 for (const name of ANDROID_SDK_ENV_NAMES) {
567 const value = trimNonEmpty(shellEnvironment[name]);
568 if (Option.isSome(value)) {
569 config.env[name] = value.value;
570 }
571 }
572 }
573
574 // Hydrate locale variables together; inherited LC_ALL can override LANG or LC_CTYPE.
575 if (
576 config.platform === "darwin" &&
577 LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))
578 ) {
579 for (const name of LOCALE_ENV_NAMES) {
580 const value = trimNonEmpty(shellEnvironment[name]);
581 if (Option.isSome(value)) {
582 config.env[name] = value.value;
583 }
584 }
585
586 // launchd lacks locale; UTF-8 LC_CTYPE fixes pbcopy's MacRoman decoding without changing C formatting or collation.
587 if (LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))) {
588 config.env.LC_CTYPE = FALLBACK_LC_CTYPE;
589 }
590 }
591
592 if (
593 config.platform === "linux" &&
594 Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
595 ) {
596 for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
597 const dbusSessionBusPath = `${runtimeDir}/bus`;
598 const busExists = yield* fileSystem
599 .exists(dbusSessionBusPath)
600 .pipe(Effect.orElseSucceed(() => false));
601 if (busExists) {
602 config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
603 break;
604 }
605 }
606 }
607
608 const prepared = Option.isSome(trimNonEmpty(shellEnvironment.PATH));
609 return {
610 prepared,
611 fromUserShell: prepared && answeredBy !== undefined && userShells.includes(answeredBy),
612 };
613 },
614 );
615
616 /** `fromUserShell` is false when only a fallback shell answered, whose PATH can miss folders. */
617 interface ShellDiscovery {
618 readonly prepared: boolean;
619 readonly fromUserShell: boolean;
620 }
621
622 const installShellEnvironment = (
623 config: ShellEnvironmentConfig,
624 ): Effect.Effect<
625 ShellDiscovery,
626 never,
627 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
628 > => {
629 if (config.platform === "win32") {
630 return installWindowsEnvironment(config).pipe(
631 Effect.map((prepared) => ({ prepared, fromUserShell: prepared })),
632 );
633 }
634 if (config.platform === "darwin" || config.platform === "linux") {
635 return installPosixEnvironment(config);
636 }
637 return Effect.succeed({ prepared: false, fromUserShell: false });
638 };
639
640 const ShellEnvironmentCache = Schema.fromJsonString(
641 Schema.Struct({
642 version: Schema.Literal(1),
643 key: Schema.String,
644 environment: ShellEnvironmentPatch,
645 }),
646 );
647 const encodeCacheKey = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
648 const decodeCache = Schema.decodeUnknownEffect(ShellEnvironmentCache);
649 const encodeCache = Schema.encodeEffect(ShellEnvironmentCache);
650 const CACHED_ENV_NAMES = [
651 "PATH",
652 "__MISE_DIFF",
653 "HOMEBREW_PREFIX",
654 "HOMEBREW_CELLAR",
655 "HOMEBREW_REPOSITORY",
656 "JAVA_HOME",
657 "PNPM_HOME",
658 "SSL_CERT_FILE",
659 "SSL_CERT_DIR",
660 "NODE_EXTRA_CA_CERTS",
661 "T3CODE_TELEMETRY_ENABLED",
662 ] as const;
663
664 /** @public */
665 export const make = Effect.gen(function* () {
666 const environment = yield* DesktopEnvironment.DesktopEnvironment;
667 const fileSystem = yield* FileSystem.FileSystem;
668 const path = yield* Path.Path;
669 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
670 const scope = yield* Scope.Scope;
671 const env = process.env;
672 const isLinuxAppImage =
673 environment.platform === "linux" && (env.APPIMAGE !== undefined || env.APPDIR !== undefined);
674 const appDir = env.APPDIR?.replace(/\/+$/u, "");
675 const stripAppImagePaths = (target: NodeJS.ProcessEnv) => {
676 if (!isLinuxAppImage || target.PATH === undefined) return;
677 // Cached PATHs can outlive the AppImage mount that originally contributed them.
678 const kept = target.PATH.split(":").filter(
679 (entry) =>
680 !(appDir && (entry === appDir || entry.startsWith(`${appDir}/`))) &&
681 !/^\/tmp\/\.mount_T3-[^/]+(?:\/|$)/u.test(entry),
682 );
683 if (kept.length > 0) target.PATH = kept.join(":");
684 else delete target.PATH;
685 };
686 stripAppImagePaths(env);
687 const inherited = { ...env };
688 const key = encodeCacheKey([
689 environment.platform,
690 environment.homeDirectory,
691 inherited.SHELL ?? "",
692 inherited.ZDOTDIR ?? "",
693 ]);
694 const cachePath = path.join(environment.stateDir, "shell-environment-cache.json");
695 const changes = yield* PubSub.unbounded<DesktopShellEnvironmentSnapshot>();
696 const latest = yield* Ref.make<Option.Option<DesktopShellEnvironmentSnapshot>>(Option.none());
697 const discovered = yield* Deferred.make<ShellDiscovery>();
698 const settledDiscovery = yield* Deferred.make<void>();
699 const publish = Effect.fn("desktop.shellEnvironment.publish")(function* (
700 patch: ShellEnvironmentPatch,
701 discovered = false,
702 ) {
703 applyShellEnvironment(env, patch, environment.platform);
704 const message: DesktopShellEnvironmentSnapshot = {
705 version: 1,
706 type: "shellEnvironment",
707 discovered,
708 platform: environment.platform,
709 environment: patch,
710 };
711 yield* Ref.set(latest, Option.some(message));
712 yield* PubSub.publish(changes, message);
713 });
714 const probe = Effect.fn("desktop.shellEnvironment.refresh")(
715 function* (budget: ProbeBudget) {
716 // Refresh from the inherited baseline so removed cached paths and values do not survive.
717 const fresh = { ...inherited };
718 const discovery = yield* installShellEnvironment({
719 env: fresh,
720 platform: environment.platform,
721 budget,
722 });
723 const { prepared } = discovery;
724 stripAppImagePaths(fresh);
725 const patch = Object.fromEntries(
726 Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]),
727 );
728 if (prepared || Option.isNone(yield* Ref.get(latest))) yield* publish(patch, prepared);
729 if (prepared) {
730 const cached = Object.fromEntries(
731 CACHED_ENV_NAMES.flatMap((name) => (fresh[name] ? [[name, fresh[name]]] : [])),
732 );
733 const persist = Effect.gen(function* () {
734 const encoded = yield* encodeCache({ version: 1, key, environment: cached });
735 yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
736 yield* fileSystem.writeFileString(cachePath + ".tmp", encoded, { mode: 0o600 });
737 yield* fileSystem.rename(cachePath + ".tmp", cachePath);
738 });
739 yield* persist.pipe(
740 Effect.catch(() => Effect.logWarning("Could not cache shell environment")),
741 );
742 }
743 return discovery;
744 },
745 Effect.provideService(FileSystem.FileSystem, fileSystem),
746 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
747 );
748 // A fallback shell's PATH can miss folders the user's own shell adds, so keep asking that shell.
749 const awaitsUserShell = listUserShells(inherited).length > 0;
750 const settled = ({ prepared, fromUserShell }: ShellDiscovery) =>
751 fromUserShell || (prepared && !awaitsUserShell);
752 const refresh = probe(STARTUP_PROBE).pipe(
753 Effect.onExit((exit) => Deferred.done(discovered, exit)),
754 Effect.flatMap((discovery) =>
755 settled(discovery)
756 ? Effect.void
757 : Effect.sleep(DISCOVERY_RETRY_DELAY).pipe(
758 Effect.andThen(
759 probe(RETRY_PROBE).pipe(
760 Effect.repeat({
761 until: settled,
762 schedule: Schedule.spaced(DISCOVERY_RETRY_DELAY),
763 times: DISCOVERY_RETRIES - 1,
764 }),
765 ),
766 ),
767 ),
768 ),
769 Effect.onExit(() => Deferred.succeed(settledDiscovery, undefined)),
770 );
771 const installIntoProcess = yield* Effect.cached(
772 Effect.gen(function* () {
773 const cache = yield* fileSystem
774 .readFileString(cachePath)
775 .pipe(Effect.flatMap(decodeCache), Effect.option);
776 if (Option.isSome(cache) && cache.value.key === key) {
777 const cached = Object.fromEntries(
778 CACHED_ENV_NAMES.flatMap((name) => {
779 const value = cache.value.environment[name];
780 // mise's metadata must describe the cached PATH entries restored alongside it.
781 if (name !== "PATH" && name !== "__MISE_DIFF" && inherited[name] !== undefined)
782 return [];
783 return typeof value === "string" ? [[name, value]] : [];
784 }),
785 );
786 stripAppImagePaths(cached);
787 const baseline = { ...inherited };
788 const cachedPath = cached.PATH;
789 if (cachedPath) {
790 cached.PATH = Option.getOrElse(
791 mergePaths(environment.platform, [Option.some(cachedPath), readEnvPath(inherited)]),
792 () => cachedPath,
793 );
794 }
795 applyShellEnvironment(baseline, cached, environment.platform);
796 yield* publish(
797 Object.fromEntries(
798 Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, baseline[name] ?? null]),
799 ),
800 );
801 }
802 yield* Effect.forkIn(refresh, scope);
803 return true;
804 }).pipe(Effect.withSpan("desktop.shellEnvironment.installIntoProcess")),
805 );
806 const updates = Stream.unwrap(
807 Effect.gen(function* () {
808 const subscription = yield* PubSub.subscribe(changes);
809 const snapshot = yield* Ref.get(latest);
810 return Stream.concat(
811 Option.isSome(snapshot) ? Stream.make(snapshot.value) : Stream.empty,
812 Stream.fromSubscription(subscription),
813 );
814 }),
815 );
816 return DesktopShellEnvironment.of({
817 installIntoProcess,
818 awaitDiscovery: installIntoProcess.pipe(
819 Effect.andThen(Deferred.await(discovered)),
820 Effect.map(({ prepared }) => prepared),
821 ),
822 awaitUserShellDiscovery: installIntoProcess.pipe(
823 Effect.andThen(Deferred.await(discovered)),
824 Effect.map(({ fromUserShell }) => fromUserShell),
825 ),
826 discoveryFinished: Deferred.isDone(settledDiscovery),
827 updates,
828 });
829 });
830
831 export const layer = Layer.effect(DesktopShellEnvironment, make);