Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopShellEnvironment.ts

802 lines26.9 KB

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