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

DesktopShellEnvironment.ts

843 lines28.6 KB

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