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