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

DesktopShellEnvironment.ts

531 lines16.7 KB

1import {
2 buildEnvironmentCaptureCommand,
3 listLoginShellCandidates,
4 setWindowsPath,
5} from "@t3tools/shared/shell";
6import * as Context from "effect/Context";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Schema from "effect/Schema";
13import * as Stream from "effect/Stream";
14import * as ChildProcess from "effect/process/ChildProcess";
15import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16​
17import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
18​
19type EnvironmentPatch = Record<string, string>;
20​
21interface ShellEnvironmentConfig {
22 readonly env: NodeJS.ProcessEnv;
23 readonly platform: NodeJS.Platform;
25​
26interface WindowsProbeOptions {
27 readonly loadProfile: boolean;
29​
30const DesktopShellEnvironmentProbe = Schema.Literals([
31 "login-shell",
32 "launchctl-path",
33 "powershell-profile",
34 "powershell-no-profile",
35]);
36type DesktopShellEnvironmentProbe = typeof DesktopShellEnvironmentProbe.Type;
37​
38const desktopShellEnvironmentCommandFields = {
39 probe: DesktopShellEnvironmentProbe,
40 executable: Schema.String,
41 argumentCount: Schema.Number,
42};
43​
44export class DesktopShellEnvironmentCommandError extends Schema.TaggedError<DesktopShellEnvironmentCommandError>()(
45 "DesktopShellEnvironmentCommandError",
46 {
47 ...desktopShellEnvironmentCommandFields,
48 cause: Schema.Defect(),
49 },
50) {
51 override get message(): string {
52 return `Desktop shell environment ${this.probe} probe (${this.executable}) failed.`;
53 }
55​
56export class DesktopShellEnvironmentCommandTimeoutError extends Schema.TaggedError<DesktopShellEnvironmentCommandTimeoutError>()(
57 "DesktopShellEnvironmentCommandTimeoutError",
58 {
59 ...desktopShellEnvironmentCommandFields,
60 timeoutMs: Schema.Number,
61 },
62) {
63 override get message(): string {
64 return `Desktop shell environment ${this.probe} probe (${this.executable}) timed out after ${this.timeoutMs}ms.`;
65 }
67​
68export class DesktopShellEnvironment extends Context.Service<
69 DesktopShellEnvironment,
70 {
71 // Reuses the installation result; false leaves server hydration enabled.
72 readonly installIntoProcess: Effect.Effect<boolean>;
73 }
74>()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
75​
76const LOGIN_SHELL_ENV_NAMES = [
77 "PATH",
78 "DBUS_SESSION_BUS_ADDRESS",
79 "DISPLAY",
80 "LANG",
81 "LC_ALL",
82 "LC_CTYPE",
83 "SSH_AUTH_SOCK",
84 "HOMEBREW_PREFIX",
85 "HOMEBREW_CELLAR",
86 "HOMEBREW_REPOSITORY",
87 "XDG_CONFIG_HOME",
88 "XDG_CURRENT_DESKTOP",
89 "XDG_DATA_HOME",
90 "XDG_RUNTIME_DIR",
91 "XDG_SESSION_DESKTOP",
92 "XDG_SESSION_TYPE",
93 "WAYLAND_DISPLAY",
94 "SSL_CERT_FILE",
95 "SSL_CERT_DIR",
96 "NODE_EXTRA_CA_CERTS",
97 "T3CODE_TELEMETRY_ENABLED",
98 "__MISE_DIFF",
99] as const;
100const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
101const LOCALE_ENV_NAMES = ["LANG", "LC_ALL", "LC_CTYPE"] as const;
102const FALLBACK_LC_CTYPE = "en_US.UTF-8";
103const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
104const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
105const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
106const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
107​
108const trimNonEmpty = (value: string | null | undefined): Option.Option<string> =>
109 Option.fromNullishOr(value).pipe(
110 Option.map((entry) => entry.trim()),
111 Option.filter((entry) => entry.length > 0),
112 );
113​
114const pathDelimiter = (platform: NodeJS.Platform) => (platform === "win32" ? ";" : ":");
115​
116const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
117 trimNonEmpty(env.PATH ?? env.Path ?? env.path);
118​
119const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, "");
120​
121const linuxRuntimeDirCandidates = (
122 env: NodeJS.ProcessEnv,
123 uid: number | undefined,
124): ReadonlyArray<string> => {
125 const candidates: string[] = [];
126 const fromEnv = trimNonEmpty(env.XDG_RUNTIME_DIR);
127 if (Option.isSome(fromEnv)) {
128 candidates.push(normalizeRuntimeDir(fromEnv.value));
129 }
130 if (uid !== undefined) {
131 candidates.push(`/run/user/${uid}`);
132 }
133 return candidates.filter((candidate) => candidate.length > 0);
134};
135​
136const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => {
137 const normalized = entry.trim().replace(/^"+|"+$/g, "");
138 return platform === "win32" ? normalized.toLowerCase() : normalized;
139};
140​
141const sanitizePathEntry = (entry: string, platform: NodeJS.Platform) =>
142 platform === "win32" ? entry.replaceAll('"', "") : entry;
143​
144const mergePaths = (
145 platform: NodeJS.Platform,
146 values: ReadonlyArray<Option.Option<string>>,
147): Option.Option<string> => {
148 const delimiter = pathDelimiter(platform);
149 const entries: string[] = [];
150 const seen = new Set<string>();
151​
152 for (const value of values) {
153 if (Option.isNone(value)) continue;
154​
155 for (const entry of value.value.split(delimiter)) {
156 const sanitized = sanitizePathEntry(entry.trim(), platform);
157 if (sanitized.length === 0) continue;
158​
159 const key = pathComparisonKey(sanitized, platform);
160 if (key.length === 0 || seen.has(key)) continue;
161​
162 seen.add(key);
163 entries.push(sanitized);
164 }
165 }
166​
167 return entries.length > 0 ? Option.some(entries.join(delimiter)) : Option.none();
168};
169​
170const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
171 ...trimNonEmpty(env.APPDATA).pipe(
172 Option.match({
173 onNone: () => [],
174 onSome: (value) => [`${value}\\npm`],
175 }),
176 ),
177 ...trimNonEmpty(env.LOCALAPPDATA).pipe(
178 Option.match({
179 onNone: () => [],
180 onSome: (value) => [`${value}\\Programs\\nodejs`, `${value}\\Volta\\bin`, `${value}\\pnpm`],
181 }),
182 ),
183 ...trimNonEmpty(env.USERPROFILE).pipe(
184 Option.match({
185 onNone: () => [],
186 onSome: (value) => [`${value}\\.local\\bin`, `${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
187 }),
188 ),
189];
190​
191const startMarker = (name: string) => `__T3CODE_ENV_${name}_START__`;
192const endMarker = (name: string) => `__T3CODE_ENV_${name}_END__`;
193​
194const executableName = (command: string): string => command.split(/[\\/]/u).at(-1) ?? command;
195​
196const logShellEnvironmentCommandError = (
197 error: DesktopShellEnvironmentCommandError | DesktopShellEnvironmentCommandTimeoutError,
198) =>
199 Effect.logWarning(error).pipe(
200 Effect.annotateLogs({
201 component: "desktop-shell-environment",
202 error,
203 }),
204 );
205​
206const captureWindowsEnvironmentCommand = (names: ReadonlyArray<string>) =>
207 [
208 "$ErrorActionPreference = 'Stop'",
209 ...names.flatMap((name) => {
210 return [
211 `Write-Output '${startMarker(name)}'`,
212 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
213 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
214 `Write-Output '${endMarker(name)}'`,
215 ];
216 }),
217 ].join("; ");
218​
219const extractEnvironment = (output: string, names: ReadonlyArray<string>): EnvironmentPatch => {
220 const environment: EnvironmentPatch = {};
221​
222 for (const name of names) {
223 const start = output.indexOf(startMarker(name));
224 if (start === -1) continue;
225​
226 const valueStart = start + startMarker(name).length;
227 const end = output.indexOf(endMarker(name), valueStart);
228 if (end === -1) continue;
229​
230 const value = output
231 .slice(valueStart, end)
232 .replace(/^\r?\n/, "")
233 .replace(/\r?\n$/, "");
234 if (value.length > 0) {
235 environment[name] = value;
236 }
237 }
238​
239 return environment;
240};
241​
242const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(function* (input: {
243 readonly probe: DesktopShellEnvironmentProbe;
244 readonly command: string;
245 readonly args: ReadonlyArray<string>;
246 readonly timeout: Duration.Duration;
247 readonly shell?: boolean;
248}): Effect.fn.Return<string, never, ChildProcessSpawner.ChildProcessSpawner> {
249 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
250 const output = yield* Effect.scoped(
251 Effect.gen(function* () {
252 const child = yield* spawner.spawn(
253 ChildProcess.make(input.command, input.args, {
254 shell: input.shell ?? false,
255 stdin: "ignore",
256 stdout: "pipe",
257 stderr: "pipe",
258 killSignal: "SIGTERM",
259 forceKillAfter: PROCESS_TERMINATE_GRACE,
260 }),
261 );
262 return yield* Effect.all([Stream.mkString(Stream.decodeText(child.stdout)), child.exitCode], {
263 concurrency: 2,
264 });
265 }),
266 ).pipe(
267 Effect.mapError(
268 (cause) =>
269 new DesktopShellEnvironmentCommandError({
270 probe: input.probe,
271 executable: executableName(input.command),
272 argumentCount: input.args.length,
273 cause,
274 }),
275 ),
276 Effect.filterOrFail(
277 ([, exitCode]) => exitCode === 0,
278 ([, exitCode]) =>
279 new DesktopShellEnvironmentCommandError({
280 probe: input.probe,
281 executable: executableName(input.command),
282 argumentCount: input.args.length,
283 cause: { exitCode },
284 }),
285 ),
286 Effect.map(([stdout]) => stdout),
287 Effect.catchTags({
288 DesktopShellEnvironmentCommandError: (error) =>
289 logShellEnvironmentCommandError(error).pipe(Effect.as("")),
290 }),
291 Effect.timeoutOption(input.timeout),
292 );
293 if (Option.isSome(output)) {
294 return output.value;
295 }
296​
297 const error = new DesktopShellEnvironmentCommandTimeoutError({
298 probe: input.probe,
299 executable: executableName(input.command),
300 argumentCount: input.args.length,
301 timeoutMs: Duration.toMillis(input.timeout),
302 });
303 yield* logShellEnvironmentCommandError(error);
304 return "";
305});
306​
307const readLoginShellEnvironment = (
308 shell: string,
309 names: ReadonlyArray<string>,
310): Effect.Effect<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> =>
311 names.length === 0
312 ? Effect.succeed({})
313 : runCommandOutput({
314 probe: "login-shell",
315 command: shell,
316 args: ["-ilc", buildEnvironmentCaptureCommand(shell, names)],
317 timeout: LOGIN_SHELL_TIMEOUT,
318 }).pipe(Effect.map((output) => extractEnvironment(output, names)));
319​
320const readLaunchctlPath = runCommandOutput({
321 probe: "launchctl-path",
322 command: "/bin/launchctl",
323 args: ["getenv", "PATH"],
324 timeout: LAUNCHCTL_TIMEOUT,
325}).pipe(Effect.map(trimNonEmpty));
326​
327const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEnvironment")(
328 function* (
329 names: ReadonlyArray<string>,
330 options: WindowsProbeOptions,
331 ): Effect.fn.Return<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> {
332 if (names.length === 0) return {};
333​
334 const args = [
335 "-NoLogo",
336 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
337 "-NonInteractive",
338 "-Command",
339 captureWindowsEnvironmentCommand(names),
340 ];
341​
342 for (const command of WINDOWS_SHELL_CANDIDATES) {
343 const output = yield* runCommandOutput({
344 probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile",
345 command,
346 args,
347 timeout: LOGIN_SHELL_TIMEOUT,
348 });
349 const environment = extractEnvironment(output, names);
350 if (Object.keys(environment).length > 0) {
351 return environment;
352 }
353 }
354​
355 return {};
356 },
357);
358​
359const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWindowsEnvironment")(
360 function* (
361 config: ShellEnvironmentConfig,
362 ): Effect.fn.Return<boolean, never, ChildProcessSpawner.ChildProcessSpawner> {
363 const [noProfile, profile] = yield* Effect.all(
364 [
365 readWindowsEnvironment(["PATH"], { loadProfile: false }),
366 readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }),
367 ],
368 { concurrency: 2 },
369 );
370 const mergedPath = mergePaths("win32", [
371 trimNonEmpty(profile.PATH),
372 trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
373 trimNonEmpty(noProfile.PATH),
374 readEnvPath(config.env),
375 ]);
376​
377 if (Option.isSome(mergedPath)) {
378 setWindowsPath(config.env, mergedPath.value);
379 }
380 if (!config.env.FNM_DIR && profile.FNM_DIR) {
381 config.env.FNM_DIR = profile.FNM_DIR;
382 }
383 if (!config.env.FNM_MULTISHELL_PATH && profile.FNM_MULTISHELL_PATH) {
384 config.env.FNM_MULTISHELL_PATH = profile.FNM_MULTISHELL_PATH;
385 }
386 return Boolean(noProfile.PATH && profile.PATH);
387 },
388);
389​
390const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
391 function* (
392 config: ShellEnvironmentConfig,
393 ): Effect.fn.Return<
394 void,
395 never,
396 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
397 > {
398 const fileSystem = yield* FileSystem.FileSystem;
399 const shellEnvironment: EnvironmentPatch = {};
400​
401 for (const shell of listLoginShellCandidates(config.platform, config.env.SHELL)) {
402 Object.assign(
403 shellEnvironment,
404 yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES),
405 );
406 if (shellEnvironment.PATH) break;
407 }
408​
409 const launchctlPath =
410 config.platform === "darwin" && !shellEnvironment.PATH
411 ? yield* readLaunchctlPath
412 : Option.none<string>();
413 const mergedPath = mergePaths(config.platform, [
414 trimNonEmpty(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
415 readEnvPath(config.env),
416 ]);
417​
418 if (Option.isSome(mergedPath)) {
419 config.env.PATH = mergedPath.value;
420 }
421 if (!config.env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
422 config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
423 }
424​
425 const shellPreferredEnvNames = [
426 "DBUS_SESSION_BUS_ADDRESS",
427 "XDG_CURRENT_DESKTOP",
428 "XDG_SESSION_DESKTOP",
429 "XDG_SESSION_TYPE",
430 // Forward mise's PATH delta too, or mise x can rebuild PATH into a recursive same-named wrapper.
431 "__MISE_DIFF",
432 ] as const;
433 for (const name of shellPreferredEnvNames) {
434 if (shellEnvironment[name]) {
435 config.env[name] = shellEnvironment[name];
436 }
437 }
438​
439 for (const name of [
440 "DISPLAY",
441 "HOMEBREW_PREFIX",
442 "HOMEBREW_CELLAR",
443 "HOMEBREW_REPOSITORY",
444 "XDG_CONFIG_HOME",
445 "XDG_DATA_HOME",
446 "XDG_RUNTIME_DIR",
447 "WAYLAND_DISPLAY",
448 // Shell CA settings are required by Node/OpenSSL builds without bundled roots for registry TLS.
449 "SSL_CERT_FILE",
450 "SSL_CERT_DIR",
451 "NODE_EXTRA_CA_CERTS",
452 "T3CODE_TELEMETRY_ENABLED",
453 ] as const) {
454 if (!config.env[name] && shellEnvironment[name]) {
455 config.env[name] = shellEnvironment[name];
456 }
457 }
458​
459 // Hydrate locale variables together; inherited LC_ALL can override LANG or LC_CTYPE.
460 if (
461 config.platform === "darwin" &&
462 LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))
463 ) {
464 for (const name of LOCALE_ENV_NAMES) {
465 const value = trimNonEmpty(shellEnvironment[name]);
466 if (Option.isSome(value)) {
467 config.env[name] = value.value;
468 }
469 }
470​
471 // launchd lacks locale; UTF-8 LC_CTYPE fixes pbcopy's MacRoman decoding without changing C formatting or collation.
472 if (LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))) {
473 config.env.LC_CTYPE = FALLBACK_LC_CTYPE;
474 }
475 }
476​
477 if (
478 config.platform === "linux" &&
479 Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
480 ) {
481 for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
482 const dbusSessionBusPath = `${runtimeDir}/bus`;
483 const busExists = yield* fileSystem
484 .exists(dbusSessionBusPath)
485 .pipe(Effect.orElseSucceed(() => false));
486 if (busExists) {
487 config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
488 break;
489 }
490 }
491 }
492 },
493);
494​
495const installShellEnvironment = (
496 config: ShellEnvironmentConfig,
497): Effect.Effect<
498 boolean,
499 never,
500 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
501> => {
502 if (config.platform === "win32") {
503 return installWindowsEnvironment(config);
504 }
505 if (config.platform === "darwin" || config.platform === "linux") {
506 return installPosixEnvironment(config).pipe(Effect.as(true));
507 }
508 return Effect.succeed(false);
509};
510​
511/** @public */
512export const make = Effect.gen(function* () {
513 const environment = yield* DesktopEnvironment.DesktopEnvironment;
514 const fileSystem = yield* FileSystem.FileSystem;
515 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
516 const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
517 yield* Effect.cached(
518 installShellEnvironment({
519 env: process.env,
520 platform: environment.platform,
521 }).pipe(
522 Effect.provideService(FileSystem.FileSystem, fileSystem),
523 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
524 Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
525 ),
526 );
527​
528 return DesktopShellEnvironment.of({ installIntoProcess });
529});
530​
531export const layer = Layer.effect(DesktopShellEnvironment, make);