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

DesktopShellEnvironment.ts

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