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 "T3CODE_FEATURE_FLAGS",
127 "T3CODE_RELEASE_BASE_URL",
128 "__MISE_DIFF",
129 "JAVA_HOME",
130 "PNPM_HOME",
131] as const;
132const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
133const LOCALE_ENV_NAMES = ["LANG", "LC_ALL", "LC_CTYPE"] as const;
134const ANDROID_SDK_ENV_NAMES = ["ANDROID_HOME", "ANDROID_SDK_ROOT"] as const;
135const FALLBACK_LC_CTYPE = "en_US.UTF-8";
136const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
137const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
138// A profile can be slow only while the machine boots; one longer wait covers it.
139const SLOW_LOGIN_SHELL_TIMEOUT = Duration.seconds(20);
140const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
141const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
142const STARTUP_PROBE: ProbeBudget = {
143 timeout: LOGIN_SHELL_TIMEOUT,
144 slowTimeout: SLOW_LOGIN_SHELL_TIMEOUT,
145 terminateGrace: PROCESS_TERMINATE_GRACE,
146};
147// Retries block nothing, so they outlast pyenv's 60 s wait on its rehash lock, and SIGTERM gets
148// time to run the exit trap that releases it. A SIGKILL leaves the lock for two minutes.
149const RETRY_PROBE: ProbeBudget = {
150 timeout: Duration.minutes(2),
151 terminateGrace: Duration.seconds(10),
152};
153// A Mac asleep at launch fails the first probe on wake, and nothing else would probe again.
154const DISCOVERY_RETRY_DELAY = Duration.seconds(30);
155const DISCOVERY_RETRIES = 10;
156
157const trimNonEmpty = (value: string | null | undefined): Option.Option<string> =>
158 Option.fromNullishOr(value).pipe(
159 Option.map((entry) => entry.trim()),
160 Option.filter((entry) => entry.length > 0),
161 );
162
163// POSIX directory names may begin or end with whitespace; mergePathValues trims only on Windows.
164const nonEmptyPath = (value: string | null | undefined): Option.Option<string> =>
165 Option.fromNullishOr(value).pipe(Option.filter((entry) => entry.length > 0));
166
167const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
168 nonEmptyPath(env.PATH ?? env.Path ?? env.path);
169
170const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, "");
171
172const linuxRuntimeDirCandidates = (
173 env: NodeJS.ProcessEnv,
174 uid: number | undefined,
175): ReadonlyArray<string> => {
176 const candidates: string[] = [];
177 const fromEnv = trimNonEmpty(env.XDG_RUNTIME_DIR);
178 if (Option.isSome(fromEnv)) {
179 candidates.push(normalizeRuntimeDir(fromEnv.value));
180 }
181 if (uid !== undefined) {
182 candidates.push(`/run/user/${uid}`);
183 }
184 return candidates.filter((candidate) => candidate.length > 0);
185};
186
187const mergePaths = (
188 platform: NodeJS.Platform,
189 values: ReadonlyArray<Option.Option<string>>,
190): Option.Option<string> =>
191 Option.fromNullishOr(
192 values.reduce<string | undefined>(
193 (merged, value) => mergePathValues(merged, Option.getOrUndefined(value), platform),
194 undefined,
195 ),
196 );
197
198const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
199 ...trimNonEmpty(env.APPDATA).pipe(
200 Option.match({
201 onNone: () => [],
202 onSome: (value) => [`${value}\\npm`],
203 }),
204 ),
205 ...trimNonEmpty(env.LOCALAPPDATA).pipe(
206 Option.match({
207 onNone: () => [],
208 onSome: (value) => [`${value}\\Programs\\nodejs`, `${value}\\Volta\\bin`, `${value}\\pnpm`],
209 }),
210 ),
211 ...trimNonEmpty(env.USERPROFILE).pipe(
212 Option.match({
213 onNone: () => [],
214 onSome: (value) => [`${value}\\.local\\bin`, `${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
215 }),
216 ),
217];
218
219const startMarker = (name: string) => `__T3CODE_ENV_${name}_START__`;
220const endMarker = (name: string) => `__T3CODE_ENV_${name}_END__`;
221
222const executableName = (command: string): string => command.split(/[\\/]/u).at(-1) ?? command;
223
224const logShellEnvironmentCommandError = (
225 error: DesktopShellEnvironmentCommandError | DesktopShellEnvironmentCommandTimeoutError,
226) =>
227 Effect.logWarning(error).pipe(
228 Effect.annotateLogs({
229 component: "desktop-shell-environment",
230 error,
231 }),
232 );
233
234const captureWindowsEnvironmentCommand = (names: ReadonlyArray<string>) =>
235 [
236 "$ErrorActionPreference = 'Stop'",
237 // Redirected PowerShell output uses the console code page, which mangles non-ASCII paths.
238 "try { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch {}",
239 ...names.flatMap((name) => {
240 return [
241 `Write-Output '${startMarker(name)}'`,
242 windowsEnvironmentValueCommand(name),
243 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
244 `Write-Output '${endMarker(name)}'`,
245 ];
246 }),
247 ].join("; ");
248
249const extractEnvironment = (output: string, names: ReadonlyArray<string>): EnvironmentPatch => {
250 const environment: EnvironmentPatch = {};
251
252 for (const name of names) {
253 const start = output.indexOf(startMarker(name));
254 if (start === -1) continue;
255
256 const valueStart = start + startMarker(name).length;
257 const end = output.indexOf(endMarker(name), valueStart);
258 if (end === -1) continue;
259
260 const value = output
261 .slice(valueStart, end)
262 .replace(/^\r?\n/, "")
263 .replace(/\r?\n$/, "");
264 if (value.length > 0) {
265 environment[name] = value;
266 }
267 }
268
269 return environment;
270};
271
272const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(function* (input: {
273 readonly probe: DesktopShellEnvironmentProbe;
274 readonly command: string;
275 readonly args: ReadonlyArray<string>;
276 readonly env: NodeJS.ProcessEnv;
277 readonly timeout: Duration.Duration;
278 readonly terminateGrace?: Duration.Duration;
279 readonly shell?: boolean;
280}): Effect.fn.Return<
281 string,
282 DesktopShellEnvironmentCommandTimeoutError,
283 ChildProcessSpawner.ChildProcessSpawner
284> {
285 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
286 const fiber = yield* Effect.scoped(
287 Effect.gen(function* () {
288 const child = yield* spawner.spawn(
289 ChildProcess.make(input.command, input.args, {
290 shell: input.shell ?? false,
291 env: input.env,
292 extendEnv: false,
293 stdin: "ignore",
294 stdout: "pipe",
295 stderr: "ignore",
296 killSignal: "SIGTERM",
297 forceKillAfter: input.terminateGrace ?? PROCESS_TERMINATE_GRACE,
298 }),
299 );
300 return yield* Effect.all([Stream.mkString(Stream.decodeText(child.stdout)), child.exitCode], {
301 concurrency: 2,
302 });
303 }),
304 ).pipe(
305 Effect.mapError(
306 (cause) =>
307 new DesktopShellEnvironmentCommandError({
308 probe: input.probe,
309 executable: executableName(input.command),
310 argumentCount: input.args.length,
311 cause,
312 }),
313 ),
314 Effect.filterOrFail(
315 ([, exitCode]) => exitCode === 0,
316 ([, exitCode]) =>
317 new DesktopShellEnvironmentCommandError({
318 probe: input.probe,
319 executable: executableName(input.command),
320 argumentCount: input.args.length,
321 cause: { exitCode },
322 }),
323 ),
324 Effect.map(([stdout]) => stdout),
325 Effect.catchTags({
326 DesktopShellEnvironmentCommandError: (error) =>
327 logShellEnvironmentCommandError(error).pipe(Effect.as("")),
328 }),
329 Effect.forkDetach,
330 );
331 const output = yield* Fiber.join(fiber).pipe(
332 Effect.timeoutOption(input.timeout),
333 // Interrupting awaits the child's exit, which a shell stuck in the kernel never reaches.
334 Effect.ensuring(Fiber.interrupt(fiber).pipe(Effect.forkDetach)),
335 );
336 if (Option.isSome(output)) {
337 return output.value;
338 }
339
340 return yield* new DesktopShellEnvironmentCommandTimeoutError({
341 probe: input.probe,
342 executable: executableName(input.command),
343 argumentCount: input.args.length,
344 timeoutMs: Duration.toMillis(input.timeout),
345 });
346});
347
348const orEmptyOnTimeout = <R>(
349 effect: Effect.Effect<string, DesktopShellEnvironmentCommandTimeoutError, R>,
350): Effect.Effect<string, never, R> =>
351 effect.pipe(
352 Effect.catchTags({
353 DesktopShellEnvironmentCommandTimeoutError: (error) =>
354 logShellEnvironmentCommandError(error).pipe(Effect.as("")),
355 }),
356 );
357
358const readLoginShellEnvironment = (
359 shell: string,
360 names: ReadonlyArray<string>,
361 env: NodeJS.ProcessEnv,
362 timeout: Duration.Duration,
363 terminateGrace: Duration.Duration,
364): Effect.Effect<
365 EnvironmentPatch,
366 DesktopShellEnvironmentCommandTimeoutError,
367 ChildProcessSpawner.ChildProcessSpawner
368> =>
369 names.length === 0
370 ? Effect.succeed({})
371 : runCommandOutput({
372 probe: "login-shell",
373 command: shell,
374 args: ["-ilc", buildEnvironmentCaptureCommand(shell, names)],
375 env,
376 timeout,
377 terminateGrace,
378 }).pipe(Effect.map((output) => extractEnvironment(output, names)));
379
380const readLaunchctlPath = (env: NodeJS.ProcessEnv) =>
381 runCommandOutput({
382 env,
383 probe: "launchctl-path",
384 command: "/bin/launchctl",
385 args: ["getenv", "PATH"],
386 timeout: LAUNCHCTL_TIMEOUT,
387 }).pipe(orEmptyOnTimeout, Effect.map(trimNonEmpty));
388
389const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEnvironment")(
390 function* (
391 names: ReadonlyArray<string>,
392 options: WindowsProbeOptions,
393 env: NodeJS.ProcessEnv,
394 budget: ProbeBudget,
395 ): Effect.fn.Return<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> {
396 if (names.length === 0) return {};
397
398 const args = [
399 "-NoLogo",
400 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
401 "-NonInteractive",
402 "-Command",
403 captureWindowsEnvironmentCommand(names),
404 ];
405
406 for (const command of WINDOWS_SHELL_CANDIDATES) {
407 const output = yield* runCommandOutput({
408 probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile",
409 command,
410 args,
411 env,
412 timeout: budget.timeout,
413 terminateGrace: budget.terminateGrace,
414 }).pipe(orEmptyOnTimeout);
415 const environment = extractEnvironment(output, names);
416 if (Object.keys(environment).length > 0) {
417 return environment;
418 }
419 }
420
421 return {};
422 },
423);
424
425const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWindowsEnvironment")(
426 function* (
427 config: ShellEnvironmentConfig,
428 ): Effect.fn.Return<boolean, never, ChildProcessSpawner.ChildProcessSpawner> {
429 const [noProfile, profile] = yield* Effect.all(
430 [
431 readWindowsEnvironment(["PATH"], { loadProfile: false }, config.env, config.budget),
432 readWindowsEnvironment(
433 WINDOWS_PROFILE_ENV_NAMES,
434 { loadProfile: true },
435 config.env,
436 config.budget,
437 ),
438 ],
439 { concurrency: 2 },
440 );
441 const mergedPath = mergePaths("win32", [
442 trimNonEmpty(profile.PATH),
443 trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
444 trimNonEmpty(noProfile.PATH),
445 readEnvPath(config.env),
446 ]);
447
448 if (Option.isSome(mergedPath)) {
449 setWindowsPath(config.env, mergedPath.value);
450 }
451 if (!config.env.FNM_DIR && profile.FNM_DIR) {
452 config.env.FNM_DIR = profile.FNM_DIR;
453 }
454 if (!config.env.FNM_MULTISHELL_PATH && profile.FNM_MULTISHELL_PATH) {
455 config.env.FNM_MULTISHELL_PATH = profile.FNM_MULTISHELL_PATH;
456 }
457 return Boolean(noProfile.PATH && profile.PATH);
458 },
459);
460
461const listUserShells = (env: NodeJS.ProcessEnv): ReadonlyArray<string> =>
462 [env.SHELL?.trim(), readUserLoginShell()].filter((shell): shell is string => Boolean(shell));
463
464const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
465 function* (
466 config: ShellEnvironmentConfig,
467 ): Effect.fn.Return<
468 ShellDiscovery,
469 never,
470 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
471 > {
472 const fileSystem = yield* FileSystem.FileSystem;
473 const shellEnvironment: EnvironmentPatch = {};
474 const userShells = listUserShells(config.env);
475
476 let answeredBy: string | undefined;
477 let waitedForSlowShell = false;
478 for (const shell of listLoginShellCandidates(config.platform, config.env.SHELL)) {
479 const read = (timeout: Duration.Duration) =>
480 readLoginShellEnvironment(
481 shell,
482 LOGIN_SHELL_ENV_NAMES,
483 config.env,
484 timeout,
485 config.budget.terminateGrace,
486 );
487 Object.assign(
488 shellEnvironment,
489 yield* read(config.budget.timeout).pipe(
490 Effect.catchTags({
491 DesktopShellEnvironmentCommandTimeoutError: (error) => {
492 const slowTimeout = waitedForSlowShell ? undefined : config.budget.slowTimeout;
493 waitedForSlowShell = true;
494 return logShellEnvironmentCommandError(error).pipe(
495 Effect.andThen(slowTimeout ? read(slowTimeout) : Effect.succeed({})),
496 );
497 },
498 }),
499 Effect.catchTags({
500 DesktopShellEnvironmentCommandTimeoutError: (error) =>
501 logShellEnvironmentCommandError(error).pipe(Effect.as({})),
502 }),
503 ),
504 );
505 if (shellEnvironment.PATH) {
506 answeredBy = shell;
507 break;
508 }
509 }
510
511 const launchctlPath =
512 config.platform === "darwin" && !shellEnvironment.PATH
513 ? yield* readLaunchctlPath(config.env)
514 : Option.none<string>();
515 const mergedPath = mergePaths(config.platform, [
516 nonEmptyPath(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
517 readEnvPath(config.env),
518 ]);
519
520 if (Option.isSome(mergedPath)) {
521 config.env.PATH = mergedPath.value;
522 }
523 if (!config.env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
524 config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
525 }
526
527 const shellPreferredEnvNames = [
528 "DBUS_SESSION_BUS_ADDRESS",
529 "XDG_CURRENT_DESKTOP",
530 "XDG_SESSION_DESKTOP",
531 "XDG_SESSION_TYPE",
532 // Forward mise's PATH delta too, or mise x can rebuild PATH into a recursive same-named wrapper.
533 "__MISE_DIFF",
534 ] as const;
535 for (const name of shellPreferredEnvNames) {
536 if (shellEnvironment[name]) {
537 config.env[name] = shellEnvironment[name];
538 }
539 }
540
541 for (const name of [
542 "DISPLAY",
543 "HOMEBREW_PREFIX",
544 "HOMEBREW_CELLAR",
545 "HOMEBREW_REPOSITORY",
546 "XDG_CONFIG_HOME",
547 "XDG_DATA_HOME",
548 "XDG_RUNTIME_DIR",
549 "WAYLAND_DISPLAY",
550 // Shell CA settings are required by Node/OpenSSL builds without bundled roots for registry TLS.
551 "SSL_CERT_FILE",
552 "SSL_CERT_DIR",
553 "NODE_EXTRA_CA_CERTS",
554 "JAVA_HOME",
555 "PNPM_HOME",
556 "T3CODE_TELEMETRY_ENABLED",
557 "T3CODE_FEATURE_FLAGS",
558 "T3CODE_RELEASE_BASE_URL",
559 ] as const) {
560 if (!config.env[name] && shellEnvironment[name]) {
561 config.env[name] = shellEnvironment[name];
562 }
563 }
564
565 // The device host picks the Android SDK from ANDROID_HOME before ANDROID_SDK_ROOT,
566 // so a profile-only ANDROID_HOME must not shadow an inherited ANDROID_SDK_ROOT.
567 if (ANDROID_SDK_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))) {
568 for (const name of ANDROID_SDK_ENV_NAMES) {
569 const value = trimNonEmpty(shellEnvironment[name]);
570 if (Option.isSome(value)) {
571 config.env[name] = value.value;
572 }
573 }
574 }
575
576 // Hydrate locale variables together; inherited LC_ALL can override LANG or LC_CTYPE.
577 if (
578 config.platform === "darwin" &&
579 LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))
580 ) {
581 for (const name of LOCALE_ENV_NAMES) {
582 const value = trimNonEmpty(shellEnvironment[name]);
583 if (Option.isSome(value)) {
584 config.env[name] = value.value;
585 }
586 }
587
588 // launchd lacks locale; UTF-8 LC_CTYPE fixes pbcopy's MacRoman decoding without changing C formatting or collation.
589 if (LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))) {
590 config.env.LC_CTYPE = FALLBACK_LC_CTYPE;
591 }
592 }
593
594 if (
595 config.platform === "linux" &&
596 Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
597 ) {
598 for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
599 const dbusSessionBusPath = `${runtimeDir}/bus`;
600 const busExists = yield* fileSystem
601 .exists(dbusSessionBusPath)
602 .pipe(Effect.orElseSucceed(() => false));
603 if (busExists) {
604 config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
605 break;
606 }
607 }
608 }
609
610 const prepared = Option.isSome(trimNonEmpty(shellEnvironment.PATH));
611 return {
612 prepared,
613 fromUserShell: prepared && answeredBy !== undefined && userShells.includes(answeredBy),
614 };
615 },
616);
617
618/** `fromUserShell` is false when only a fallback shell answered, whose PATH can miss folders. */
619interface ShellDiscovery {
620 readonly prepared: boolean;
621 readonly fromUserShell: boolean;
622}
623
624const installShellEnvironment = (
625 config: ShellEnvironmentConfig,
626): Effect.Effect<
627 ShellDiscovery,
628 never,
629 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
630> => {
631 if (config.platform === "win32") {
632 return installWindowsEnvironment(config).pipe(
633 Effect.map((prepared) => ({ prepared, fromUserShell: prepared })),
634 );
635 }
636 if (config.platform === "darwin" || config.platform === "linux") {
637 return installPosixEnvironment(config);
638 }
639 return Effect.succeed({ prepared: false, fromUserShell: false });
640};
641
642const ShellEnvironmentCache = Schema.fromJsonString(
643 Schema.Struct({
644 version: Schema.Literal(1),
645 key: Schema.String,
646 environment: ShellEnvironmentPatch,
647 }),
648);
649const encodeCacheKey = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
650const decodeCache = Schema.decodeUnknownEffect(ShellEnvironmentCache);
651const encodeCache = Schema.encodeEffect(ShellEnvironmentCache);
652const CACHED_ENV_NAMES = [
653 "PATH",
654 "__MISE_DIFF",
655 "HOMEBREW_PREFIX",
656 "HOMEBREW_CELLAR",
657 "HOMEBREW_REPOSITORY",
658 "JAVA_HOME",
659 "PNPM_HOME",
660 "SSL_CERT_FILE",
661 "SSL_CERT_DIR",
662 "NODE_EXTRA_CA_CERTS",
663 "T3CODE_TELEMETRY_ENABLED",
664 // The server reads its flags once at start, before discovery can finish.
665 "T3CODE_FEATURE_FLAGS",
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);