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

DesktopShellEnvironment.ts

555 lines17.8 KB

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