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

DesktopShellEnvironment.ts

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