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

DesktopShellEnvironment.ts

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