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

DesktopShellEnvironment.ts

534 lines17.0 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.TaggedErrorClass<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.TaggedErrorClass<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 "SSH_AUTH_SOCK",
75 "HOMEBREW_PREFIX",
76 "HOMEBREW_CELLAR",
77 "HOMEBREW_REPOSITORY",
78 "XDG_CONFIG_HOME",
79 "XDG_CURRENT_DESKTOP",
80 "XDG_DATA_HOME",
81 "XDG_RUNTIME_DIR",
82 "XDG_SESSION_DESKTOP",
83 "XDG_SESSION_TYPE",
84 "WAYLAND_DISPLAY",
85] as const;
86const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
87const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
88const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
89const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
90const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
91​
92const trimNonEmpty = (value: string | null | undefined): Option.Option<string> =>
93 Option.fromNullishOr(value).pipe(
94 Option.map((entry) => entry.trim()),
95 Option.filter((entry) => entry.length > 0),
96 );
97​
98const pathDelimiter = (platform: NodeJS.Platform) => (platform === "win32" ? ";" : ":");
99​
100const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
101 trimNonEmpty(env.PATH ?? env.Path ?? env.path);
102​
103const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, "");
104​
105const linuxRuntimeDirCandidates = (
106 env: NodeJS.ProcessEnv,
107 uid: number | undefined,
108): ReadonlyArray<string> => {
109 const candidates: string[] = [];
110 const fromEnv = trimNonEmpty(env.XDG_RUNTIME_DIR);
111 if (Option.isSome(fromEnv)) {
112 candidates.push(normalizeRuntimeDir(fromEnv.value));
113 }
114 if (uid !== undefined) {
115 candidates.push(`/run/user/${uid}`);
116 }
117 return candidates.filter((candidate) => candidate.length > 0);
118};
119​
120function resolveDefaultLinuxDbusSessionBusPath(input: {
121 readonly env: NodeJS.ProcessEnv;
122 readonly uid: number | undefined;
123 readonly exists?: (path: string) => boolean;
124}): string | null {
125 for (const runtimeDir of linuxRuntimeDirCandidates(input.env, input.uid)) {
126 const busPath = `${runtimeDir}/bus`;
127 if (input.exists === undefined || input.exists(busPath)) {
128 return busPath;
129 }
130 }
131​
132 return null;
134​
135export function resolveDefaultLinuxDbusSessionBusAddress(input: {
136 readonly env: NodeJS.ProcessEnv;
137 readonly exists: (path: string) => boolean;
138 readonly uid: number | undefined;
139}): string | null {
140 const busPath = resolveDefaultLinuxDbusSessionBusPath(input);
141 return busPath !== null && input.exists(busPath) ? `unix:path=${busPath}` : null;
143​
144const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => {
145 const normalized = entry.trim().replace(/^"+|"+$/g, "");
146 return platform === "win32" ? normalized.toLowerCase() : normalized;
147};
148​
149const mergePaths = (
150 platform: NodeJS.Platform,
151 values: ReadonlyArray<Option.Option<string>>,
152): Option.Option<string> => {
153 const delimiter = pathDelimiter(platform);
154 const entries: string[] = [];
155 const seen = new Set<string>();
156​
157 for (const value of values) {
158 if (Option.isNone(value)) continue;
159​
160 for (const entry of value.value.split(delimiter)) {
161 const trimmed = entry.trim();
162 if (trimmed.length === 0) continue;
163​
164 const key = pathComparisonKey(trimmed, platform);
165 if (key.length === 0 || seen.has(key)) continue;
166​
167 seen.add(key);
168 entries.push(trimmed);
169 }
170 }
171​
172 return entries.length > 0 ? Option.some(entries.join(delimiter)) : Option.none();
173};
174​
175const listLoginShellCandidates = (config: ShellEnvironmentConfig): ReadonlyArray<string> => {
176 const fallback =
177 config.platform === "darwin" ? "/bin/zsh" : config.platform === "linux" ? "/bin/bash" : "";
178 const seen = new Set<string>();
179 const candidates: string[] = [];
180​
181 for (const candidate of [
182 trimNonEmpty(config.env.SHELL),
183 config.userShell,
184 trimNonEmpty(fallback),
185 ]) {
186 if (Option.isNone(candidate) || seen.has(candidate.value)) continue;
187 seen.add(candidate.value);
188 candidates.push(candidate.value);
189 }
190​
191 return candidates;
192};
193​
194const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
195 ...trimNonEmpty(env.APPDATA).pipe(
196 Option.match({
197 onNone: () => [],
198 onSome: (value) => [`${value}\\npm`],
199 }),
200 ),
201 ...trimNonEmpty(env.LOCALAPPDATA).pipe(
202 Option.match({
203 onNone: () => [],
204 onSome: (value) => [`${value}\\Programs\\nodejs`, `${value}\\Volta\\bin`, `${value}\\pnpm`],
205 }),
206 ),
207 ...trimNonEmpty(env.USERPROFILE).pipe(
208 Option.match({
209 onNone: () => [],
210 onSome: (value) => [`${value}\\.local\\bin`, `${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
211 }),
212 ),
213];
214​
215const startMarker = (name: string) => `__T3CODE_ENV_${name}_START__`;
216const endMarker = (name: string) => `__T3CODE_ENV_${name}_END__`;
217​
218const executableName = (command: string): string => command.split(/[\\/]/u).at(-1) ?? command;
219​
220const logShellEnvironmentCommandError = (
221 error: DesktopShellEnvironmentCommandError | DesktopShellEnvironmentCommandTimeoutError,
222) =>
223 Effect.logWarning(error).pipe(
224 Effect.annotateLogs({
225 component: "desktop-shell-environment",
226 error,
227 }),
228 );
229​
230const capturePosixEnvironmentCommand = (names: ReadonlyArray<string>) =>
231 names
232 .map((name) => {
233 return [
234 `printf '%s\\n' '${startMarker(name)}'`,
235 `printenv ${name} || true`,
236 `printf '%s\\n' '${endMarker(name)}'`,
237 ].join("; ");
238 })
239 .join("; ");
240​
241const captureWindowsEnvironmentCommand = (names: ReadonlyArray<string>) =>
242 [
243 "$ErrorActionPreference = 'Stop'",
244 ...names.flatMap((name) => {
245 if (name.toUpperCase() === "PATH") {
246 return [
247 `Write-Output '${startMarker(name)}'`,
248 `$machineValue = [Environment]::GetEnvironmentVariable('${name}', 'Machine')`,
249 `$userValue = [Environment]::GetEnvironmentVariable('${name}', 'User')`,
250 `$processValue = [Environment]::GetEnvironmentVariable('${name}')`,
251 `$merged = ($processValue, $machineValue, $userValue | Where-Object { $null -ne $_ -and $_.Length -gt 0 }) -join ';'`,
252 "if ($null -ne $merged -and $merged.Length -gt 0) { Write-Output $merged }",
253 `Write-Output '${endMarker(name)}'`,
254 ];
255 }
256 return [
257 `Write-Output '${startMarker(name)}'`,
258 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
259 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
260 `Write-Output '${endMarker(name)}'`,
261 ];
262 }),
263 ].join("; ");
264​
265const extractEnvironment = (output: string, names: ReadonlyArray<string>): EnvironmentPatch => {
266 const environment: EnvironmentPatch = {};
267​
268 for (const name of names) {
269 const start = output.indexOf(startMarker(name));
270 if (start === -1) continue;
271​
272 const valueStart = start + startMarker(name).length;
273 const end = output.indexOf(endMarker(name), valueStart);
274 if (end === -1) continue;
275​
276 const value = output
277 .slice(valueStart, end)
278 .replace(/^\r?\n/, "")
279 .replace(/\r?\n$/, "");
280 if (value.length > 0) {
281 environment[name] = value;
282 }
283 }
284​
285 return environment;
286};
287​
288const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(function* (input: {
289 readonly probe: DesktopShellEnvironmentProbe;
290 readonly command: string;
291 readonly args: ReadonlyArray<string>;
292 readonly timeout: Duration.Duration;
293 readonly shell?: boolean;
294}): Effect.fn.Return<string, never, ChildProcessSpawner.ChildProcessSpawner> {
295 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
296 const output = yield* spawner
297 .string(
298 ChildProcess.make(input.command, input.args, {
299 shell: input.shell ?? false,
300 stdin: "ignore",
301 stdout: "pipe",
302 stderr: "pipe",
303 killSignal: "SIGTERM",
304 forceKillAfter: PROCESS_TERMINATE_GRACE,
305 }),
306 )
307 .pipe(
308 Effect.mapError(
309 (cause) =>
310 new DesktopShellEnvironmentCommandError({
311 probe: input.probe,
312 executable: executableName(input.command),
313 argumentCount: input.args.length,
314 cause,
315 }),
316 ),
317 Effect.catchTags({
318 DesktopShellEnvironmentCommandError: (error) =>
319 logShellEnvironmentCommandError(error).pipe(Effect.as("")),
320 }),
321 Effect.timeoutOption(input.timeout),
322 );
323 if (Option.isSome(output)) {
324 return output.value;
325 }
326​
327 const error = new DesktopShellEnvironmentCommandTimeoutError({
328 probe: input.probe,
329 executable: executableName(input.command),
330 argumentCount: input.args.length,
331 timeoutMs: Duration.toMillis(input.timeout),
332 });
333 yield* logShellEnvironmentCommandError(error);
334 return "";
335});
336​
337const readLoginShellEnvironment = (
338 shell: string,
339 names: ReadonlyArray<string>,
340): Effect.Effect<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> =>
341 names.length === 0
342 ? Effect.succeed({})
343 : runCommandOutput({
344 probe: "login-shell",
345 command: shell,
346 args: ["-ilc", capturePosixEnvironmentCommand(names)],
347 timeout: LOGIN_SHELL_TIMEOUT,
348 }).pipe(Effect.map((output) => extractEnvironment(output, names)));
349​
350const readLaunchctlPath = runCommandOutput({
351 probe: "launchctl-path",
352 command: "/bin/launchctl",
353 args: ["getenv", "PATH"],
354 timeout: LAUNCHCTL_TIMEOUT,
355}).pipe(Effect.map(trimNonEmpty));
356​
357const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEnvironment")(
358 function* (
359 names: ReadonlyArray<string>,
360 options: WindowsProbeOptions,
361 ): Effect.fn.Return<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> {
362 if (names.length === 0) return {};
363​
364 const args = [
365 "-NoLogo",
366 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
367 "-NonInteractive",
368 "-Command",
369 captureWindowsEnvironmentCommand(names),
370 ];
371​
372 for (const command of WINDOWS_SHELL_CANDIDATES) {
373 const output = yield* runCommandOutput({
374 probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile",
375 command,
376 args,
377 timeout: LOGIN_SHELL_TIMEOUT,
378 });
379 const environment = extractEnvironment(output, names);
380 if (Object.keys(environment).length > 0) {
381 return environment;
382 }
383 }
384​
385 return {};
386 },
387);
388​
389const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWindowsEnvironment")(
390 function* (
391 config: ShellEnvironmentConfig,
392 ): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
393 // Concurrent, not sequential: these two probes are independent (only their
394 // results are combined below) and each spawns its own PowerShell. Run in
395 // series they sit at offset 0 of desktop.startup, before anything else, and
396 // launch traces measured them at 2718ms then 2066ms — the entire 4.8s
397 // startup span, of which desktop.bootstrap is ~30ms.
398 const [noProfile, profile] = yield* Effect.all(
399 [
400 readWindowsEnvironment(["PATH"], { loadProfile: false }),
401 readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }),
402 ],
403 { concurrency: 2 },
404 );
405 const mergedPath = mergePaths("win32", [
406 trimNonEmpty(profile.PATH),
407 trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
408 trimNonEmpty(noProfile.PATH),
409 readEnvPath(config.env),
410 ]);
411​
412 if (Option.isSome(mergedPath)) {
413 config.env.PATH = mergedPath.value;
414 }
415 if (!config.env.FNM_DIR && profile.FNM_DIR) {
416 config.env.FNM_DIR = profile.FNM_DIR;
417 }
418 if (!config.env.FNM_MULTISHELL_PATH && profile.FNM_MULTISHELL_PATH) {
419 config.env.FNM_MULTISHELL_PATH = profile.FNM_MULTISHELL_PATH;
420 }
421 },
422);
423​
424const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
425 function* (
426 config: ShellEnvironmentConfig,
427 ): Effect.fn.Return<
428 void,
429 never,
430 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
431 > {
432 const fileSystem = yield* FileSystem.FileSystem;
433 const shellEnvironment: EnvironmentPatch = {};
434​
435 for (const shell of listLoginShellCandidates(config)) {
436 Object.assign(
437 shellEnvironment,
438 yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES),
439 );
440 if (shellEnvironment.PATH) break;
441 }
442​
443 const launchctlPath =
444 config.platform === "darwin" && !shellEnvironment.PATH
445 ? yield* readLaunchctlPath
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 ] as const;
465 for (const name of shellPreferredEnvNames) {
466 if (shellEnvironment[name]) {
467 config.env[name] = shellEnvironment[name];
468 }
469 }
470​
471 for (const name of [
472 "DISPLAY",
473 "HOMEBREW_PREFIX",
474 "HOMEBREW_CELLAR",
475 "HOMEBREW_REPOSITORY",
476 "XDG_CONFIG_HOME",
477 "XDG_DATA_HOME",
478 "XDG_RUNTIME_DIR",
479 "WAYLAND_DISPLAY",
480 ] as const) {
481 if (!config.env[name] && shellEnvironment[name]) {
482 config.env[name] = shellEnvironment[name];
483 }
484 }
485​
486 if (
487 config.platform === "linux" &&
488 Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
489 ) {
490 for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
491 const dbusSessionBusPath = `${runtimeDir}/bus`;
492 const busExists = yield* fileSystem
493 .exists(dbusSessionBusPath)
494 .pipe(Effect.orElseSucceed(() => false));
495 if (busExists) {
496 config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
497 break;
498 }
499 }
500 }
501 },
502);
503​
504const installShellEnvironment = (
505 config: ShellEnvironmentConfig,
506): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem> => {
507 if (config.platform === "win32") {
508 return installWindowsEnvironment(config);
509 }
510 if (config.platform === "darwin" || config.platform === "linux") {
511 return installPosixEnvironment(config);
512 }
513 return Effect.void;
514};
515​
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 installShellEnvironment({
522 env: process.env,
523 platform: environment.platform,
524 userShell: Option.none(),
525 }).pipe(
526 Effect.provideService(FileSystem.FileSystem, fileSystem),
527 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
528 Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
529 );
530​
531 return DesktopShellEnvironment.of({ installIntoProcess });
532});
533​
534export const layer = Layer.effect(DesktopShellEnvironment, make);