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

DesktopShellEnvironment.ts

955 lines33.7 KB

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