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

DesktopShellEnvironment.ts

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