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

DesktopShellEnvironment.ts

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