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

DesktopShellEnvironment.ts

811 lines27.4 KB

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