Open History to see the last commit
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>;
19}
20
21interface WindowsProbeOptions {
22 readonly loadProfile: boolean;
23}
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 }
49}
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 }
61}
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;
133}
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;
142}
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}\\.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 const noProfile = yield* readWindowsEnvironment(["PATH"], { loadProfile: false });
383 const profile = yield* readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, {
384 loadProfile: true,
385 });
386 const mergedPath = mergePaths("win32", [
387 trimNonEmpty(profile.PATH),
388 trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
389 trimNonEmpty(noProfile.PATH),
390 readEnvPath(config.env),
391 ]);
392
393 if (Option.isSome(mergedPath)) {
394 config.env.PATH = mergedPath.value;
395 }
396 if (!config.env.FNM_DIR && profile.FNM_DIR) {
397 config.env.FNM_DIR = profile.FNM_DIR;
398 }
399 if (!config.env.FNM_MULTISHELL_PATH && profile.FNM_MULTISHELL_PATH) {
400 config.env.FNM_MULTISHELL_PATH = profile.FNM_MULTISHELL_PATH;
401 }
402 },
403);
404
405const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
406 function* (
407 config: ShellEnvironmentConfig,
408 ): Effect.fn.Return<
409 void,
410 never,
411 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
412 > {
413 const fileSystem = yield* FileSystem.FileSystem;
414 const shellEnvironment: EnvironmentPatch = {};
415
416 for (const shell of listLoginShellCandidates(config)) {
417 Object.assign(
418 shellEnvironment,
419 yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES),
420 );
421 if (shellEnvironment.PATH) break;
422 }
423
424 const launchctlPath =
425 config.platform === "darwin" && !shellEnvironment.PATH
426 ? yield* readLaunchctlPath
427 : Option.none<string>();
428 const mergedPath = mergePaths(config.platform, [
429 trimNonEmpty(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
430 readEnvPath(config.env),
431 ]);
432
433 if (Option.isSome(mergedPath)) {
434 config.env.PATH = mergedPath.value;
435 }
436 if (!config.env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
437 config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
438 }
439
440 const shellPreferredEnvNames = [
441 "DBUS_SESSION_BUS_ADDRESS",
442 "XDG_CURRENT_DESKTOP",
443 "XDG_SESSION_DESKTOP",
444 "XDG_SESSION_TYPE",
445 ] as const;
446 for (const name of shellPreferredEnvNames) {
447 if (shellEnvironment[name]) {
448 config.env[name] = shellEnvironment[name];
449 }
450 }
451
452 for (const name of [
453 "DISPLAY",
454 "HOMEBREW_PREFIX",
455 "HOMEBREW_CELLAR",
456 "HOMEBREW_REPOSITORY",
457 "XDG_CONFIG_HOME",
458 "XDG_DATA_HOME",
459 "XDG_RUNTIME_DIR",
460 "WAYLAND_DISPLAY",
461 ] as const) {
462 if (!config.env[name] && shellEnvironment[name]) {
463 config.env[name] = shellEnvironment[name];
464 }
465 }
466
467 if (
468 config.platform === "linux" &&
469 Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
470 ) {
471 for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
472 const dbusSessionBusPath = `${runtimeDir}/bus`;
473 const busExists = yield* fileSystem
474 .exists(dbusSessionBusPath)
475 .pipe(Effect.orElseSucceed(() => false));
476 if (busExists) {
477 config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
478 break;
479 }
480 }
481 }
482 },
483);
484
485const installShellEnvironment = (
486 config: ShellEnvironmentConfig,
487): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem> => {
488 if (config.platform === "win32") {
489 return installWindowsEnvironment(config);
490 }
491 if (config.platform === "darwin" || config.platform === "linux") {
492 return installPosixEnvironment(config);
493 }
494 return Effect.void;
495};
496
497export const make = Effect.gen(function* () {
498 const environment = yield* DesktopEnvironment.DesktopEnvironment;
499 const fileSystem = yield* FileSystem.FileSystem;
500 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
501 const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
502 installShellEnvironment({
503 env: process.env,
504 platform: environment.platform,
505 userShell: Option.none(),
506 }).pipe(
507 Effect.provideService(FileSystem.FileSystem, fileSystem),
508 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
509 Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
510 );
511
512 return DesktopShellEnvironment.of({ installIntoProcess });
513});
514
515export const layer = Layer.effect(DesktopShellEnvironment, make);