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