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

DesktopShellEnvironment.ts

677 lines22.3 KB

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