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

DesktopShellEnvironment.ts

755 lines25.2 KB

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