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

DesktopShellEnvironment.ts

523 lines16.4 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 return [
246 `Write-Output '${startMarker(name)}'`,
247 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
248 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
249 `Write-Output '${endMarker(name)}'`,
250 ];
251 }),
252 ].join("; ");
253​
254const extractEnvironment = (output: string, names: ReadonlyArray<string>): EnvironmentPatch => {
255 const environment: EnvironmentPatch = {};
256​
257 for (const name of names) {
258 const start = output.indexOf(startMarker(name));
259 if (start === -1) continue;
260​
261 const valueStart = start + startMarker(name).length;
262 const end = output.indexOf(endMarker(name), valueStart);
263 if (end === -1) continue;
264​
265 const value = output
266 .slice(valueStart, end)
267 .replace(/^\r?\n/, "")
268 .replace(/\r?\n$/, "");
269 if (value.length > 0) {
270 environment[name] = value;
271 }
272 }
273​
274 return environment;
275};
276​
277const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(function* (input: {
278 readonly probe: DesktopShellEnvironmentProbe;
279 readonly command: string;
280 readonly args: ReadonlyArray<string>;
281 readonly timeout: Duration.Duration;
282 readonly shell?: boolean;
283}): Effect.fn.Return<string, never, ChildProcessSpawner.ChildProcessSpawner> {
284 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
285 const output = yield* spawner
286 .string(
287 ChildProcess.make(input.command, input.args, {
288 shell: input.shell ?? false,
289 stdin: "ignore",
290 stdout: "pipe",
291 stderr: "pipe",
292 killSignal: "SIGTERM",
293 forceKillAfter: PROCESS_TERMINATE_GRACE,
294 }),
295 )
296 .pipe(
297 Effect.mapError(
298 (cause) =>
299 new DesktopShellEnvironmentCommandError({
300 probe: input.probe,
301 executable: executableName(input.command),
302 argumentCount: input.args.length,
303 cause,
304 }),
305 ),
306 Effect.catchTags({
307 DesktopShellEnvironmentCommandError: (error) =>
308 logShellEnvironmentCommandError(error).pipe(Effect.as("")),
309 }),
310 Effect.timeoutOption(input.timeout),
311 );
312 if (Option.isSome(output)) {
313 return output.value;
314 }
315​
316 const error = new DesktopShellEnvironmentCommandTimeoutError({
317 probe: input.probe,
318 executable: executableName(input.command),
319 argumentCount: input.args.length,
320 timeoutMs: Duration.toMillis(input.timeout),
321 });
322 yield* logShellEnvironmentCommandError(error);
323 return "";
324});
325​
326const readLoginShellEnvironment = (
327 shell: string,
328 names: ReadonlyArray<string>,
329): Effect.Effect<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> =>
330 names.length === 0
331 ? Effect.succeed({})
332 : runCommandOutput({
333 probe: "login-shell",
334 command: shell,
335 args: ["-ilc", capturePosixEnvironmentCommand(names)],
336 timeout: LOGIN_SHELL_TIMEOUT,
337 }).pipe(Effect.map((output) => extractEnvironment(output, names)));
338​
339const readLaunchctlPath = runCommandOutput({
340 probe: "launchctl-path",
341 command: "/bin/launchctl",
342 args: ["getenv", "PATH"],
343 timeout: LAUNCHCTL_TIMEOUT,
344}).pipe(Effect.map(trimNonEmpty));
345​
346const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEnvironment")(
347 function* (
348 names: ReadonlyArray<string>,
349 options: WindowsProbeOptions,
350 ): Effect.fn.Return<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> {
351 if (names.length === 0) return {};
352​
353 const args = [
354 "-NoLogo",
355 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
356 "-NonInteractive",
357 "-Command",
358 captureWindowsEnvironmentCommand(names),
359 ];
360​
361 for (const command of WINDOWS_SHELL_CANDIDATES) {
362 const output = yield* runCommandOutput({
363 probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile",
364 command,
365 args,
366 timeout: LOGIN_SHELL_TIMEOUT,
367 });
368 const environment = extractEnvironment(output, names);
369 if (Object.keys(environment).length > 0) {
370 return environment;
371 }
372 }
373​
374 return {};
375 },
376);
377​
378const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWindowsEnvironment")(
379 function* (
380 config: ShellEnvironmentConfig,
381 ): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
382 // Concurrent, not sequential: these two probes are independent (only their
383 // results are combined below) and each spawns its own PowerShell. Run in
384 // series they sit at offset 0 of desktop.startup, before anything else, and
385 // launch traces measured them at 2718ms then 2066ms — the entire 4.8s
386 // startup span, of which desktop.bootstrap is ~30ms.
387 const [noProfile, profile] = yield* Effect.all(
388 [
389 readWindowsEnvironment(["PATH"], { loadProfile: false }),
390 readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }),
391 ],
392 { concurrency: 2 },
393 );
394 const mergedPath = mergePaths("win32", [
395 trimNonEmpty(profile.PATH),
396 trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
397 trimNonEmpty(noProfile.PATH),
398 readEnvPath(config.env),
399 ]);
400​
401 if (Option.isSome(mergedPath)) {
402 config.env.PATH = mergedPath.value;
403 }
404 if (!config.env.FNM_DIR && profile.FNM_DIR) {
405 config.env.FNM_DIR = profile.FNM_DIR;
406 }
407 if (!config.env.FNM_MULTISHELL_PATH && profile.FNM_MULTISHELL_PATH) {
408 config.env.FNM_MULTISHELL_PATH = profile.FNM_MULTISHELL_PATH;
409 }
410 },
411);
412​
413const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
414 function* (
415 config: ShellEnvironmentConfig,
416 ): Effect.fn.Return<
417 void,
418 never,
419 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
420 > {
421 const fileSystem = yield* FileSystem.FileSystem;
422 const shellEnvironment: EnvironmentPatch = {};
423​
424 for (const shell of listLoginShellCandidates(config)) {
425 Object.assign(
426 shellEnvironment,
427 yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES),
428 );
429 if (shellEnvironment.PATH) break;
430 }
431​
432 const launchctlPath =
433 config.platform === "darwin" && !shellEnvironment.PATH
434 ? yield* readLaunchctlPath
435 : Option.none<string>();
436 const mergedPath = mergePaths(config.platform, [
437 trimNonEmpty(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
438 readEnvPath(config.env),
439 ]);
440​
441 if (Option.isSome(mergedPath)) {
442 config.env.PATH = mergedPath.value;
443 }
444 if (!config.env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
445 config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
446 }
447​
448 const shellPreferredEnvNames = [
449 "DBUS_SESSION_BUS_ADDRESS",
450 "XDG_CURRENT_DESKTOP",
451 "XDG_SESSION_DESKTOP",
452 "XDG_SESSION_TYPE",
453 ] as const;
454 for (const name of shellPreferredEnvNames) {
455 if (shellEnvironment[name]) {
456 config.env[name] = shellEnvironment[name];
457 }
458 }
459​
460 for (const name of [
461 "DISPLAY",
462 "HOMEBREW_PREFIX",
463 "HOMEBREW_CELLAR",
464 "HOMEBREW_REPOSITORY",
465 "XDG_CONFIG_HOME",
466 "XDG_DATA_HOME",
467 "XDG_RUNTIME_DIR",
468 "WAYLAND_DISPLAY",
469 ] as const) {
470 if (!config.env[name] && shellEnvironment[name]) {
471 config.env[name] = shellEnvironment[name];
472 }
473 }
474​
475 if (
476 config.platform === "linux" &&
477 Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
478 ) {
479 for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
480 const dbusSessionBusPath = `${runtimeDir}/bus`;
481 const busExists = yield* fileSystem
482 .exists(dbusSessionBusPath)
483 .pipe(Effect.orElseSucceed(() => false));
484 if (busExists) {
485 config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
486 break;
487 }
488 }
489 }
490 },
491);
492​
493const installShellEnvironment = (
494 config: ShellEnvironmentConfig,
495): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem> => {
496 if (config.platform === "win32") {
497 return installWindowsEnvironment(config);
498 }
499 if (config.platform === "darwin" || config.platform === "linux") {
500 return installPosixEnvironment(config);
501 }
502 return Effect.void;
503};
504​
505export const make = Effect.gen(function* () {
506 const environment = yield* DesktopEnvironment.DesktopEnvironment;
507 const fileSystem = yield* FileSystem.FileSystem;
508 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
509 const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
510 installShellEnvironment({
511 env: process.env,
512 platform: environment.platform,
513 userShell: Option.none(),
514 }).pipe(
515 Effect.provideService(FileSystem.FileSystem, fileSystem),
516 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
517 Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
518 );
519​
520 return DesktopShellEnvironment.of({ installIntoProcess });
521});
522​
523export const layer = Layer.effect(DesktopShellEnvironment, make);