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

DesktopShellEnvironment.ts

856 lines28.9 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 end = output.indexOf(endMarker(name), valueStart);
268 if (end === -1) continue;
269​
270 const value = output
271 .slice(valueStart, end)
272 .replace(/^\r?\n/, "")
273 .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 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 Effect.filterOrFail(
325 ([, exitCode]) => exitCode === 0,
326 ([, exitCode]) =>
327 new DesktopShellEnvironmentCommandError({
328 probe: input.probe,
329 executable: executableName(input.command),
330 argumentCount: input.args.length,
331 cause: { exitCode },
332 }),
333 ),
334 Effect.map(([stdout]) => stdout),
335 Effect.catchTags({
336 DesktopShellEnvironmentCommandError: (error) =>
337 logShellEnvironmentCommandError(error).pipe(Effect.as("")),
338 }),
339 Effect.forkDetach,
340 );
341 const output = yield* Fiber.join(fiber).pipe(
342 Effect.timeoutOption(input.timeout),
343 // Interrupting awaits the child's exit, which a shell stuck in the kernel never reaches.
344 Effect.ensuring(Fiber.interrupt(fiber).pipe(Effect.forkDetach)),
345 );
346 if (Option.isSome(output)) {
347 return output.value;
348 }
349​
350 return yield* new DesktopShellEnvironmentCommandTimeoutError({
351 probe: input.probe,
352 executable: executableName(input.command),
353 argumentCount: input.args.length,
354 timeoutMs: Duration.toMillis(input.timeout),
355 });
356});
357​
358const orEmptyOnTimeout = <R>(
359 effect: Effect.Effect<string, DesktopShellEnvironmentCommandTimeoutError, R>,
360): Effect.Effect<string, never, R> =>
361 effect.pipe(
362 Effect.catchTags({
363 DesktopShellEnvironmentCommandTimeoutError: (error) =>
364 logShellEnvironmentCommandError(error).pipe(Effect.as("")),
365 }),
366 );
367​
368const readLoginShellEnvironment = (
369 shell: string,
370 names: ReadonlyArray<string>,
371 env: NodeJS.ProcessEnv,
372 timeout: Duration.Duration,
373 terminateGrace: Duration.Duration,
374): Effect.Effect<
375 EnvironmentPatch,
376 DesktopShellEnvironmentCommandTimeoutError,
377 ChildProcessSpawner.ChildProcessSpawner
378> =>
379 names.length === 0
380 ? Effect.succeed({})
381 : runCommandOutput({
382 probe: "login-shell",
383 command: shell,
384 args: ["-ilc", buildEnvironmentCaptureCommand(shell, names)],
385 env,
386 timeout,
387 terminateGrace,
388 }).pipe(Effect.map((output) => extractEnvironment(output, names)));
389​
390const readLaunchctlPath = (env: NodeJS.ProcessEnv) =>
391 runCommandOutput({
392 env,
393 probe: "launchctl-path",
394 command: "/bin/launchctl",
395 args: ["getenv", "PATH"],
396 timeout: LAUNCHCTL_TIMEOUT,
397 }).pipe(orEmptyOnTimeout, Effect.map(trimNonEmpty));
398​
399const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEnvironment")(
400 function* (
401 names: ReadonlyArray<string>,
402 options: WindowsProbeOptions,
403 env: NodeJS.ProcessEnv,
404 budget: ProbeBudget,
405 ): Effect.fn.Return<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> {
406 if (names.length === 0) return {};
407​
408 const args = [
409 "-NoLogo",
410 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
411 "-NonInteractive",
412 "-Command",
413 captureWindowsEnvironmentCommand(names),
414 ];
415​
416 for (const command of WINDOWS_SHELL_CANDIDATES) {
417 const output = yield* runCommandOutput({
418 probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile",
419 command,
420 args,
421 env,
422 timeout: budget.timeout,
423 terminateGrace: budget.terminateGrace,
424 }).pipe(orEmptyOnTimeout);
425 const environment = extractEnvironment(output, names);
426 if (Object.keys(environment).length > 0) {
427 return environment;
428 }
429 }
430​
431 return {};
432 },
433);
434​
435const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWindowsEnvironment")(
436 function* (
437 config: ShellEnvironmentConfig,
438 ): Effect.fn.Return<boolean, never, ChildProcessSpawner.ChildProcessSpawner> {
439 const [noProfile, profile] = yield* Effect.all(
440 [
441 readWindowsEnvironment(["PATH"], { loadProfile: false }, config.env, config.budget),
442 readWindowsEnvironment(
443 WINDOWS_PROFILE_ENV_NAMES,
444 { loadProfile: true },
445 config.env,
446 config.budget,
447 ),
448 ],
449 { concurrency: 2 },
450 );
451 const mergedPath = mergePaths("win32", [
452 trimNonEmpty(profile.PATH),
453 trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
454 trimNonEmpty(noProfile.PATH),
455 readEnvPath(config.env),
456 ]);
457​
458 if (Option.isSome(mergedPath)) {
459 setWindowsPath(config.env, mergedPath.value);
460 }
461 if (!config.env.FNM_DIR && profile.FNM_DIR) {
462 config.env.FNM_DIR = profile.FNM_DIR;
463 }
464 if (!config.env.FNM_MULTISHELL_PATH && profile.FNM_MULTISHELL_PATH) {
465 config.env.FNM_MULTISHELL_PATH = profile.FNM_MULTISHELL_PATH;
466 }
467 for (const name of ["T3CODE_TELEMETRY_ENABLED", "DO_NOT_TRACK"] as const) {
468 if (!config.env[name] && profile[name]) {
469 config.env[name] = profile[name];
470 }
471 }
472 return Boolean(noProfile.PATH && profile.PATH);
473 },
474);
475​
476const listUserShells = (env: NodeJS.ProcessEnv): ReadonlyArray<string> =>
477 [env.SHELL?.trim(), readUserLoginShell()].filter((shell): shell is string => Boolean(shell));
478​
479const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
480 function* (
481 config: ShellEnvironmentConfig,
482 ): Effect.fn.Return<
483 ShellDiscovery,
484 never,
485 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
486 > {
487 const fileSystem = yield* FileSystem.FileSystem;
488 const shellEnvironment: EnvironmentPatch = {};
489 const userShells = listUserShells(config.env);
490​
491 let answeredBy: string | undefined;
492 let waitedForSlowShell = false;
493 for (const shell of listLoginShellCandidates(config.platform, config.env.SHELL)) {
494 const read = (timeout: Duration.Duration) =>
495 readLoginShellEnvironment(
496 shell,
497 LOGIN_SHELL_ENV_NAMES,
498 config.env,
499 timeout,
500 config.budget.terminateGrace,
501 );
502 Object.assign(
503 shellEnvironment,
504 yield* read(config.budget.timeout).pipe(
505 Effect.catchTags({
506 DesktopShellEnvironmentCommandTimeoutError: (error) => {
507 const slowTimeout = waitedForSlowShell ? undefined : config.budget.slowTimeout;
508 waitedForSlowShell = true;
509 return logShellEnvironmentCommandError(error).pipe(
510 Effect.andThen(slowTimeout ? read(slowTimeout) : Effect.succeed({})),
511 );
512 },
513 }),
514 Effect.catchTags({
515 DesktopShellEnvironmentCommandTimeoutError: (error) =>
516 logShellEnvironmentCommandError(error).pipe(Effect.as({})),
517 }),
518 ),
519 );
520 if (shellEnvironment.PATH) {
521 answeredBy = shell;
522 break;
523 }
524 }
525​
526 const launchctlPath =
527 config.platform === "darwin" && !shellEnvironment.PATH
528 ? yield* readLaunchctlPath(config.env)
529 : Option.none<string>();
530 const mergedPath = mergePaths(config.platform, [
531 nonEmptyPath(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
532 readEnvPath(config.env),
533 ]);
534​
535 if (Option.isSome(mergedPath)) {
536 config.env.PATH = mergedPath.value;
537 }
538 if (!config.env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
539 config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
540 }
541​
542 const shellPreferredEnvNames = [
543 "DBUS_SESSION_BUS_ADDRESS",
544 "XDG_CURRENT_DESKTOP",
545 "XDG_SESSION_DESKTOP",
546 "XDG_SESSION_TYPE",
547 // Forward mise's PATH delta too, or mise x can rebuild PATH into a recursive same-named wrapper.
548 "__MISE_DIFF",
549 ] as const;
550 for (const name of shellPreferredEnvNames) {
551 if (shellEnvironment[name]) {
552 config.env[name] = shellEnvironment[name];
553 }
554 }
555​
556 for (const name of [
557 "DISPLAY",
558 "HOMEBREW_PREFIX",
559 "HOMEBREW_CELLAR",
560 "HOMEBREW_REPOSITORY",
561 "XDG_CONFIG_HOME",
562 "XDG_DATA_HOME",
563 "XDG_RUNTIME_DIR",
564 "WAYLAND_DISPLAY",
565 // Shell CA settings are required by Node/OpenSSL builds without bundled roots for registry TLS.
566 "SSL_CERT_FILE",
567 "SSL_CERT_DIR",
568 "NODE_EXTRA_CA_CERTS",
569 "JAVA_HOME",
570 "PNPM_HOME",
571 // Source-control CLIs read their login and defaults from these.
572 "AZURE_CONFIG_DIR",
573 "GH_CONFIG_DIR",
574 "GLAB_CONFIG_DIR",
575 "T3CODE_TELEMETRY_ENABLED",
576 "DO_NOT_TRACK",
577 "T3CODE_FEATURE_FLAGS",
578 "T3CODE_RELEASE_BASE_URL",
579 ] as const) {
580 if (!config.env[name] && shellEnvironment[name]) {
581 config.env[name] = shellEnvironment[name];
582 }
583 }
584​
585 // The device host picks the Android SDK from ANDROID_HOME before ANDROID_SDK_ROOT,
586 // so a profile-only ANDROID_HOME must not shadow an inherited ANDROID_SDK_ROOT.
587 if (ANDROID_SDK_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))) {
588 for (const name of ANDROID_SDK_ENV_NAMES) {
589 const value = trimNonEmpty(shellEnvironment[name]);
590 if (Option.isSome(value)) {
591 config.env[name] = value.value;
592 }
593 }
594 }
595​
596 // Hydrate locale variables together; inherited LC_ALL can override LANG or LC_CTYPE.
597 if (
598 config.platform === "darwin" &&
599 LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))
600 ) {
601 for (const name of LOCALE_ENV_NAMES) {
602 const value = trimNonEmpty(shellEnvironment[name]);
603 if (Option.isSome(value)) {
604 config.env[name] = value.value;
605 }
606 }
607​
608 // launchd lacks locale; UTF-8 LC_CTYPE fixes pbcopy's MacRoman decoding without changing C formatting or collation.
609 if (LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))) {
610 config.env.LC_CTYPE = FALLBACK_LC_CTYPE;
611 }
612 }
613​
614 if (
615 config.platform === "linux" &&
616 Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
617 ) {
618 for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
619 const dbusSessionBusPath = `${runtimeDir}/bus`;
620 const busExists = yield* fileSystem
621 .exists(dbusSessionBusPath)
622 .pipe(Effect.orElseSucceed(() => false));
623 if (busExists) {
624 config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
625 break;
626 }
627 }
628 }
629​
630 const prepared = Option.isSome(trimNonEmpty(shellEnvironment.PATH));
631 return {
632 prepared,
633 fromUserShell: prepared && answeredBy !== undefined && userShells.includes(answeredBy),
634 };
635 },
636);
637​
638/** `fromUserShell` is false when only a fallback shell answered, whose PATH can miss folders. */
639interface ShellDiscovery {
640 readonly prepared: boolean;
641 readonly fromUserShell: boolean;
643​
644const installShellEnvironment = (
645 config: ShellEnvironmentConfig,
646): Effect.Effect<
647 ShellDiscovery,
648 never,
649 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
650> => {
651 if (config.platform === "win32") {
652 return installWindowsEnvironment(config).pipe(
653 Effect.map((prepared) => ({ prepared, fromUserShell: prepared })),
654 );
655 }
656 if (config.platform === "darwin" || config.platform === "linux") {
657 return installPosixEnvironment(config);
658 }
659 return Effect.succeed({ prepared: false, fromUserShell: false });
660};
661​
662const ShellEnvironmentCache = Schema.fromJsonString(
663 Schema.Struct({
664 version: Schema.Literal(1),
665 key: Schema.String,
666 environment: ShellEnvironmentPatch,
667 }),
668);
669const encodeCacheKey = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
670const decodeCache = Schema.decodeUnknownEffect(ShellEnvironmentCache);
671const encodeCache = Schema.encodeEffect(ShellEnvironmentCache);
672const CACHED_ENV_NAMES = [
673 "PATH",
674 "__MISE_DIFF",
675 "HOMEBREW_PREFIX",
676 "HOMEBREW_CELLAR",
677 "HOMEBREW_REPOSITORY",
678 "JAVA_HOME",
679 "PNPM_HOME",
680 "SSL_CERT_FILE",
681 "SSL_CERT_DIR",
682 "NODE_EXTRA_CA_CERTS",
683 "T3CODE_TELEMETRY_ENABLED",
684 "DO_NOT_TRACK",
685 // The server reads its flags once at start, before discovery can finish.
686 "T3CODE_FEATURE_FLAGS",
687] as const;
688​
689/** @public */
690export const make = Effect.gen(function* () {
691 const environment = yield* DesktopEnvironment.DesktopEnvironment;
692 const fileSystem = yield* FileSystem.FileSystem;
693 const path = yield* Path.Path;
694 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
695 const scope = yield* Scope.Scope;
696 const env = process.env;
697 const isLinuxAppImage =
698 environment.platform === "linux" && (env.APPIMAGE !== undefined || env.APPDIR !== undefined);
699 const appDir = env.APPDIR?.replace(/\/+$/u, "");
700 const stripAppImagePaths = (target: NodeJS.ProcessEnv) => {
701 if (!isLinuxAppImage || target.PATH === undefined) return;
702 // Cached PATHs can outlive the AppImage mount that originally contributed them.
703 const kept = target.PATH.split(":").filter(
704 (entry) =>
705 !(appDir && (entry === appDir || entry.startsWith(`${appDir}/`))) &&
706 !/^\/tmp\/\.mount_T3-[^/]+(?:\/|$)/u.test(entry),
707 );
708 if (kept.length > 0) target.PATH = kept.join(":");
709 else delete target.PATH;
710 };
711 stripAppImagePaths(env);
712 const inherited = { ...env };
713 const key = encodeCacheKey([
714 environment.platform,
715 environment.homeDirectory,
716 inherited.SHELL ?? "",
717 inherited.ZDOTDIR ?? "",
718 ]);
719 const cachePath = path.join(environment.stateDir, "shell-environment-cache.json");
720 const changes = yield* PubSub.unbounded<DesktopShellEnvironmentSnapshot>();
721 const latest = yield* Ref.make<Option.Option<DesktopShellEnvironmentSnapshot>>(Option.none());
722 const discovered = yield* Deferred.make<ShellDiscovery>();
723 const settledDiscovery = yield* Deferred.make<void>();
724 const publish = Effect.fn("desktop.shellEnvironment.publish")(function* (
725 patch: ShellEnvironmentPatch,
726 discovered = false,
727 ) {
728 applyShellEnvironment(env, patch, environment.platform);
729 const message: DesktopShellEnvironmentSnapshot = {
730 version: 1,
731 type: "shellEnvironment",
732 discovered,
733 platform: environment.platform,
734 environment: patch,
735 };
736 yield* Ref.set(latest, Option.some(message));
737 yield* PubSub.publish(changes, message);
738 });
739 const probe = Effect.fn("desktop.shellEnvironment.refresh")(
740 function* (budget: ProbeBudget) {
741 // Refresh from the inherited baseline so removed cached paths and values do not survive.
742 const fresh = { ...inherited };
743 const discovery = yield* installShellEnvironment({
744 env: fresh,
745 platform: environment.platform,
746 budget,
747 });
748 const { prepared } = discovery;
749 stripAppImagePaths(fresh);
750 const patch = Object.fromEntries(
751 Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]),
752 );
753 if (prepared || Option.isNone(yield* Ref.get(latest))) yield* publish(patch, prepared);
754 if (prepared) {
755 const cached = Object.fromEntries(
756 CACHED_ENV_NAMES.flatMap((name) => (fresh[name] ? [[name, fresh[name]]] : [])),
757 );
758 const persist = Effect.gen(function* () {
759 const encoded = yield* encodeCache({ version: 1, key, environment: cached });
760 yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
761 yield* fileSystem.writeFileString(cachePath + ".tmp", encoded, { mode: 0o600 });
762 yield* fileSystem.rename(cachePath + ".tmp", cachePath);
763 });
764 yield* persist.pipe(
765 Effect.catch(() => Effect.logWarning("Could not cache shell environment")),
766 );
767 }
768 return discovery;
769 },
770 Effect.provideService(FileSystem.FileSystem, fileSystem),
771 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
772 );
773 // A fallback shell's PATH can miss folders the user's own shell adds, so keep asking that shell.
774 const awaitsUserShell = listUserShells(inherited).length > 0;
775 const settled = ({ prepared, fromUserShell }: ShellDiscovery) =>
776 fromUserShell || (prepared && !awaitsUserShell);
777 const refresh = probe(STARTUP_PROBE).pipe(
778 Effect.onExit((exit) => Deferred.done(discovered, exit)),
779 Effect.flatMap((discovery) =>
780 settled(discovery)
781 ? Effect.void
782 : Effect.sleep(DISCOVERY_RETRY_DELAY).pipe(
783 Effect.andThen(
784 probe(RETRY_PROBE).pipe(
785 Effect.repeat({
786 until: settled,
787 schedule: Schedule.spaced(DISCOVERY_RETRY_DELAY),
788 times: DISCOVERY_RETRIES - 1,
789 }),
790 ),
791 ),
792 ),
793 ),
794 Effect.onExit(() => Deferred.succeed(settledDiscovery, undefined)),
795 );
796 const installIntoProcess = yield* Effect.cached(
797 Effect.gen(function* () {
798 const cache = yield* fileSystem
799 .readFileString(cachePath)
800 .pipe(Effect.flatMap(decodeCache), Effect.option);
801 if (Option.isSome(cache) && cache.value.key === key) {
802 const cached = Object.fromEntries(
803 CACHED_ENV_NAMES.flatMap((name) => {
804 const value = cache.value.environment[name];
805 // mise's metadata must describe the cached PATH entries restored alongside it.
806 if (name !== "PATH" && name !== "__MISE_DIFF" && inherited[name] !== undefined)
807 return [];
808 return typeof value === "string" ? [[name, value]] : [];
809 }),
810 );
811 stripAppImagePaths(cached);
812 const baseline = { ...inherited };
813 const cachedPath = cached.PATH;
814 if (cachedPath) {
815 cached.PATH = Option.getOrElse(
816 mergePaths(environment.platform, [Option.some(cachedPath), readEnvPath(inherited)]),
817 () => cachedPath,
818 );
819 }
820 applyShellEnvironment(baseline, cached, environment.platform);
821 yield* publish(
822 Object.fromEntries(
823 Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, baseline[name] ?? null]),
824 ),
825 );
826 }
827 yield* Effect.forkIn(refresh, scope);
828 return true;
829 }).pipe(Effect.withSpan("desktop.shellEnvironment.installIntoProcess")),
830 );
831 const updates = Stream.unwrap(
832 Effect.gen(function* () {
833 const subscription = yield* PubSub.subscribe(changes);
834 const snapshot = yield* Ref.get(latest);
835 return Stream.concat(
836 Option.isSome(snapshot) ? Stream.make(snapshot.value) : Stream.empty,
837 Stream.fromSubscription(subscription),
838 );
839 }),
840 );
841 return DesktopShellEnvironment.of({
842 installIntoProcess,
843 awaitDiscovery: installIntoProcess.pipe(
844 Effect.andThen(Deferred.await(discovered)),
845 Effect.map(({ prepared }) => prepared),
846 ),
847 awaitUserShellDiscovery: installIntoProcess.pipe(
848 Effect.andThen(Deferred.await(discovered)),
849 Effect.map(({ fromUserShell }) => fromUserShell),
850 ),
851 discoveryFinished: Deferred.isDone(settledDiscovery),
852 updates,
853 });
854});
855​
856export const layer = Layer.effect(DesktopShellEnvironment, make);