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

DesktopShellEnvironment.ts

735 lines24.6 KB

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