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

DesktopShellEnvironment.ts

860 lines29.2 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 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 probedPath = nonEmptyPath(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath));
531 const mergedPath = mergePaths(config.platform, [
532 probedPath,
533 readEnvPath(config.env),
534 Option.isNone(probedPath)
535 ? nonEmptyPath(listExistingPosixCliDirs(config.env, config.platform).join(":"))
536 : Option.none(),
537 ]);
538​
539 if (Option.isSome(mergedPath)) {
540 config.env.PATH = mergedPath.value;
541 }
542 if (!config.env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
543 config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
544 }
545​
546 const shellPreferredEnvNames = [
547 "DBUS_SESSION_BUS_ADDRESS",
548 "XDG_CURRENT_DESKTOP",
549 "XDG_SESSION_DESKTOP",
550 "XDG_SESSION_TYPE",
551 // Forward mise's PATH delta too, or mise x can rebuild PATH into a recursive same-named wrapper.
552 "__MISE_DIFF",
553 ] as const;
554 for (const name of shellPreferredEnvNames) {
555 if (shellEnvironment[name]) {
556 config.env[name] = shellEnvironment[name];
557 }
558 }
559​
560 for (const name of [
561 "DISPLAY",
562 "HOMEBREW_PREFIX",
563 "HOMEBREW_CELLAR",
564 "HOMEBREW_REPOSITORY",
565 "XDG_CONFIG_HOME",
566 "XDG_DATA_HOME",
567 "XDG_RUNTIME_DIR",
568 "WAYLAND_DISPLAY",
569 // Shell CA settings are required by Node/OpenSSL builds without bundled roots for registry TLS.
570 "SSL_CERT_FILE",
571 "SSL_CERT_DIR",
572 "NODE_EXTRA_CA_CERTS",
573 "JAVA_HOME",
574 "PNPM_HOME",
575 // Source-control CLIs read their login and defaults from these.
576 "AZURE_CONFIG_DIR",
577 "GH_CONFIG_DIR",
578 "GLAB_CONFIG_DIR",
579 "T3CODE_TELEMETRY_ENABLED",
580 "DO_NOT_TRACK",
581 "T3CODE_FEATURE_FLAGS",
582 "T3CODE_RELEASE_BASE_URL",
583 ] as const) {
584 if (!config.env[name] && shellEnvironment[name]) {
585 config.env[name] = shellEnvironment[name];
586 }
587 }
588​
589 // The device host picks the Android SDK from ANDROID_HOME before ANDROID_SDK_ROOT,
590 // so a profile-only ANDROID_HOME must not shadow an inherited ANDROID_SDK_ROOT.
591 if (ANDROID_SDK_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))) {
592 for (const name of ANDROID_SDK_ENV_NAMES) {
593 const value = trimNonEmpty(shellEnvironment[name]);
594 if (Option.isSome(value)) {
595 config.env[name] = value.value;
596 }
597 }
598 }
599​
600 // Hydrate locale variables together; inherited LC_ALL can override LANG or LC_CTYPE.
601 if (
602 config.platform === "darwin" &&
603 LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))
604 ) {
605 for (const name of LOCALE_ENV_NAMES) {
606 const value = trimNonEmpty(shellEnvironment[name]);
607 if (Option.isSome(value)) {
608 config.env[name] = value.value;
609 }
610 }
611​
612 // launchd lacks locale; UTF-8 LC_CTYPE fixes pbcopy's MacRoman decoding without changing C formatting or collation.
613 if (LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))) {
614 config.env.LC_CTYPE = FALLBACK_LC_CTYPE;
615 }
616 }
617​
618 if (
619 config.platform === "linux" &&
620 Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
621 ) {
622 for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
623 const dbusSessionBusPath = `${runtimeDir}/bus`;
624 const busExists = yield* fileSystem
625 .exists(dbusSessionBusPath)
626 .pipe(Effect.orElseSucceed(() => false));
627 if (busExists) {
628 config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
629 break;
630 }
631 }
632 }
633​
634 const prepared = Option.isSome(trimNonEmpty(shellEnvironment.PATH));
635 return {
636 prepared,
637 fromUserShell: prepared && answeredBy !== undefined && userShells.includes(answeredBy),
638 };
639 },
640);
641​
642/** `fromUserShell` is false when only a fallback shell answered, whose PATH can miss folders. */
643interface ShellDiscovery {
644 readonly prepared: boolean;
645 readonly fromUserShell: boolean;
647​
648const installShellEnvironment = (
649 config: ShellEnvironmentConfig,
650): Effect.Effect<
651 ShellDiscovery,
652 never,
653 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
654> => {
655 if (config.platform === "win32") {
656 return installWindowsEnvironment(config).pipe(
657 Effect.map((prepared) => ({ prepared, fromUserShell: prepared })),
658 );
659 }
660 if (config.platform === "darwin" || config.platform === "linux") {
661 return installPosixEnvironment(config);
662 }
663 return Effect.succeed({ prepared: false, fromUserShell: false });
664};
665​
666const ShellEnvironmentCache = Schema.fromJsonString(
667 Schema.Struct({
668 version: Schema.Literal(1),
669 key: Schema.String,
670 environment: ShellEnvironmentPatch,
671 }),
672);
673const encodeCacheKey = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
674const decodeCache = Schema.decodeUnknownEffect(ShellEnvironmentCache);
675const encodeCache = Schema.encodeEffect(ShellEnvironmentCache);
676const CACHED_ENV_NAMES = [
677 "PATH",
678 "__MISE_DIFF",
679 "HOMEBREW_PREFIX",
680 "HOMEBREW_CELLAR",
681 "HOMEBREW_REPOSITORY",
682 "JAVA_HOME",
683 "PNPM_HOME",
684 "SSL_CERT_FILE",
685 "SSL_CERT_DIR",
686 "NODE_EXTRA_CA_CERTS",
687 "T3CODE_TELEMETRY_ENABLED",
688 "DO_NOT_TRACK",
689 // The server reads its flags once at start, before discovery can finish.
690 "T3CODE_FEATURE_FLAGS",
691] as const;
692​
693/** @public */
694export const make = Effect.gen(function* () {
695 const environment = yield* DesktopEnvironment.DesktopEnvironment;
696 const fileSystem = yield* FileSystem.FileSystem;
697 const path = yield* Path.Path;
698 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
699 const scope = yield* Scope.Scope;
700 const env = process.env;
701 const isLinuxAppImage =
702 environment.platform === "linux" && (env.APPIMAGE !== undefined || env.APPDIR !== undefined);
703 const appDir = env.APPDIR?.replace(/\/+$/u, "");
704 const stripAppImagePaths = (target: NodeJS.ProcessEnv) => {
705 if (!isLinuxAppImage || target.PATH === undefined) return;
706 // Cached PATHs can outlive the AppImage mount that originally contributed them.
707 const kept = target.PATH.split(":").filter(
708 (entry) =>
709 !(appDir && (entry === appDir || entry.startsWith(`${appDir}/`))) &&
710 !/^\/tmp\/\.mount_T3-[^/]+(?:\/|$)/u.test(entry),
711 );
712 if (kept.length > 0) target.PATH = kept.join(":");
713 else delete target.PATH;
714 };
715 stripAppImagePaths(env);
716 const inherited = { ...env };
717 const key = encodeCacheKey([
718 environment.platform,
719 environment.homeDirectory,
720 inherited.SHELL ?? "",
721 inherited.ZDOTDIR ?? "",
722 ]);
723 const cachePath = path.join(environment.stateDir, "shell-environment-cache.json");
724 const changes = yield* PubSub.unbounded<DesktopShellEnvironmentSnapshot>();
725 const latest = yield* Ref.make<Option.Option<DesktopShellEnvironmentSnapshot>>(Option.none());
726 const discovered = yield* Deferred.make<ShellDiscovery>();
727 const settledDiscovery = yield* Deferred.make<void>();
728 const publish = Effect.fn("desktop.shellEnvironment.publish")(function* (
729 patch: ShellEnvironmentPatch,
730 discovered = false,
731 ) {
732 applyShellEnvironment(env, patch, environment.platform);
733 const message: DesktopShellEnvironmentSnapshot = {
734 version: 1,
735 type: "shellEnvironment",
736 discovered,
737 platform: environment.platform,
738 environment: patch,
739 };
740 yield* Ref.set(latest, Option.some(message));
741 yield* PubSub.publish(changes, message);
742 });
743 const probe = Effect.fn("desktop.shellEnvironment.refresh")(
744 function* (budget: ProbeBudget) {
745 // Refresh from the inherited baseline so removed cached paths and values do not survive.
746 const fresh = { ...inherited };
747 const discovery = yield* installShellEnvironment({
748 env: fresh,
749 platform: environment.platform,
750 budget,
751 });
752 const { prepared } = discovery;
753 stripAppImagePaths(fresh);
754 const patch = Object.fromEntries(
755 Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]),
756 );
757 if (prepared || Option.isNone(yield* Ref.get(latest))) yield* publish(patch, prepared);
758 if (prepared) {
759 const cached = Object.fromEntries(
760 CACHED_ENV_NAMES.flatMap((name) => (fresh[name] ? [[name, fresh[name]]] : [])),
761 );
762 const persist = Effect.gen(function* () {
763 const encoded = yield* encodeCache({ version: 1, key, environment: cached });
764 yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
765 yield* fileSystem.writeFileString(cachePath + ".tmp", encoded, { mode: 0o600 });
766 yield* fileSystem.rename(cachePath + ".tmp", cachePath);
767 });
768 yield* persist.pipe(
769 Effect.catch(() => Effect.logWarning("Could not cache shell environment")),
770 );
771 }
772 return discovery;
773 },
774 Effect.provideService(FileSystem.FileSystem, fileSystem),
775 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
776 );
777 // A fallback shell's PATH can miss folders the user's own shell adds, so keep asking that shell.
778 const awaitsUserShell = listUserShells(inherited).length > 0;
779 const settled = ({ prepared, fromUserShell }: ShellDiscovery) =>
780 fromUserShell || (prepared && !awaitsUserShell);
781 const refresh = probe(STARTUP_PROBE).pipe(
782 Effect.onExit((exit) => Deferred.done(discovered, exit)),
783 Effect.flatMap((discovery) =>
784 settled(discovery)
785 ? Effect.void
786 : Effect.sleep(DISCOVERY_RETRY_DELAY).pipe(
787 Effect.andThen(
788 probe(RETRY_PROBE).pipe(
789 Effect.repeat({
790 until: settled,
791 schedule: Schedule.spaced(DISCOVERY_RETRY_DELAY),
792 times: DISCOVERY_RETRIES - 1,
793 }),
794 ),
795 ),
796 ),
797 ),
798 Effect.onExit(() => Deferred.succeed(settledDiscovery, undefined)),
799 );
800 const installIntoProcess = yield* Effect.cached(
801 Effect.gen(function* () {
802 const cache = yield* fileSystem
803 .readFileString(cachePath)
804 .pipe(Effect.flatMap(decodeCache), Effect.option);
805 if (Option.isSome(cache) && cache.value.key === key) {
806 const cached = Object.fromEntries(
807 CACHED_ENV_NAMES.flatMap((name) => {
808 const value = cache.value.environment[name];
809 // mise's metadata must describe the cached PATH entries restored alongside it.
810 if (name !== "PATH" && name !== "__MISE_DIFF" && inherited[name] !== undefined)
811 return [];
812 return typeof value === "string" ? [[name, value]] : [];
813 }),
814 );
815 stripAppImagePaths(cached);
816 const baseline = { ...inherited };
817 const cachedPath = cached.PATH;
818 if (cachedPath) {
819 cached.PATH = Option.getOrElse(
820 mergePaths(environment.platform, [Option.some(cachedPath), readEnvPath(inherited)]),
821 () => cachedPath,
822 );
823 }
824 applyShellEnvironment(baseline, cached, environment.platform);
825 yield* publish(
826 Object.fromEntries(
827 Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, baseline[name] ?? null]),
828 ),
829 );
830 }
831 yield* Effect.forkIn(refresh, scope);
832 return true;
833 }).pipe(Effect.withSpan("desktop.shellEnvironment.installIntoProcess")),
834 );
835 const updates = Stream.unwrap(
836 Effect.gen(function* () {
837 const subscription = yield* PubSub.subscribe(changes);
838 const snapshot = yield* Ref.get(latest);
839 return Stream.concat(
840 Option.isSome(snapshot) ? Stream.make(snapshot.value) : Stream.empty,
841 Stream.fromSubscription(subscription),
842 );
843 }),
844 );
845 return DesktopShellEnvironment.of({
846 installIntoProcess,
847 awaitDiscovery: installIntoProcess.pipe(
848 Effect.andThen(Deferred.await(discovered)),
849 Effect.map(({ prepared }) => prepared),
850 ),
851 awaitUserShellDiscovery: installIntoProcess.pipe(
852 Effect.andThen(Deferred.await(discovered)),
853 Effect.map(({ fromUserShell }) => fromUserShell),
854 ),
855 discoveryFinished: Deferred.isDone(settledDiscovery),
856 updates,
857 });
858});
859​
860export const layer = Layer.effect(DesktopShellEnvironment, make);