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