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 "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;
138}
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;
147}
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 mergePaths = (
155 platform: NodeJS.Platform,
156 values: ReadonlyArray<Option.Option<string>>,
157): Option.Option<string> => {
158 const delimiter = pathDelimiter(platform);
159 const entries: string[] = [];
160 const seen = new Set<string>();
161
162 for (const value of values) {
163 if (Option.isNone(value)) continue;
164
165 for (const entry of value.value.split(delimiter)) {
166 const trimmed = entry.trim();
167 if (trimmed.length === 0) continue;
168
169 const key = pathComparisonKey(trimmed, platform);
170 if (key.length === 0 || seen.has(key)) continue;
171
172 seen.add(key);
173 entries.push(trimmed);
174 }
175 }
176
177 return entries.length > 0 ? Option.some(entries.join(delimiter)) : Option.none();
178};
179
180const listLoginShellCandidates = (config: ShellEnvironmentConfig): ReadonlyArray<string> => {
181 const fallback =
182 config.platform === "darwin" ? "/bin/zsh" : config.platform === "linux" ? "/bin/bash" : "";
183 const seen = new Set<string>();
184 const candidates: string[] = [];
185
186 for (const candidate of [
187 trimNonEmpty(config.env.SHELL),
188 config.userShell,
189 trimNonEmpty(fallback),
190 ]) {
191 if (Option.isNone(candidate) || seen.has(candidate.value)) continue;
192 seen.add(candidate.value);
193 candidates.push(candidate.value);
194 }
195
196 return candidates;
197};
198
199const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
200 ...trimNonEmpty(env.APPDATA).pipe(
201 Option.match({
202 onNone: () => [],
203 onSome: (value) => [`${value}\\npm`],
204 }),
205 ),
206 ...trimNonEmpty(env.LOCALAPPDATA).pipe(
207 Option.match({
208 onNone: () => [],
209 onSome: (value) => [`${value}\\Programs\\nodejs`, `${value}\\Volta\\bin`, `${value}\\pnpm`],
210 }),
211 ),
212 ...trimNonEmpty(env.USERPROFILE).pipe(
213 Option.match({
214 onNone: () => [],
215 onSome: (value) => [`${value}\\.local\\bin`, `${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
216 }),
217 ),
218];
219
220const startMarker = (name: string) => `__T3CODE_ENV_${name}_START__`;
221const endMarker = (name: string) => `__T3CODE_ENV_${name}_END__`;
222
223const executableName = (command: string): string => command.split(/[\\/]/u).at(-1) ?? command;
224
225const logShellEnvironmentCommandError = (
226 error: DesktopShellEnvironmentCommandError | DesktopShellEnvironmentCommandTimeoutError,
227) =>
228 Effect.logWarning(error).pipe(
229 Effect.annotateLogs({
230 component: "desktop-shell-environment",
231 error,
232 }),
233 );
234
235const capturePosixEnvironmentCommand = (names: ReadonlyArray<string>) =>
236 names
237 .map((name) => {
238 return [
239 `printf '%s\\n' '${startMarker(name)}'`,
240 `printenv ${name} || true`,
241 `printf '%s\\n' '${endMarker(name)}'`,
242 ].join("; ");
243 })
244 .join("; ");
245
246const captureWindowsEnvironmentCommand = (names: ReadonlyArray<string>) =>
247 [
248 "$ErrorActionPreference = 'Stop'",
249 ...names.flatMap((name) => {
250 return [
251 `Write-Output '${startMarker(name)}'`,
252 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
253 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
254 `Write-Output '${endMarker(name)}'`,
255 ];
256 }),
257 ].join("; ");
258
259const extractEnvironment = (output: string, names: ReadonlyArray<string>): EnvironmentPatch => {
260 const environment: EnvironmentPatch = {};
261
262 for (const name of names) {
263 const start = output.indexOf(startMarker(name));
264 if (start === -1) continue;
265
266 const valueStart = start + startMarker(name).length;
267 const end = output.indexOf(endMarker(name), valueStart);
268 if (end === -1) continue;
269
270 const value = output
271 .slice(valueStart, end)
272 .replace(/^\r?\n/, "")
273 .replace(/\r?\n$/, "");
274 if (value.length > 0) {
275 environment[name] = value;
276 }
277 }
278
279 return environment;
280};
281
282const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(function* (input: {
283 readonly probe: DesktopShellEnvironmentProbe;
284 readonly command: string;
285 readonly args: ReadonlyArray<string>;
286 readonly timeout: Duration.Duration;
287 readonly shell?: boolean;
288}): Effect.fn.Return<string, never, ChildProcessSpawner.ChildProcessSpawner> {
289 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
290 const output = yield* spawner
291 .string(
292 ChildProcess.make(input.command, input.args, {
293 shell: input.shell ?? false,
294 stdin: "ignore",
295 stdout: "pipe",
296 stderr: "pipe",
297 killSignal: "SIGTERM",
298 forceKillAfter: PROCESS_TERMINATE_GRACE,
299 }),
300 )
301 .pipe(
302 Effect.mapError(
303 (cause) =>
304 new DesktopShellEnvironmentCommandError({
305 probe: input.probe,
306 executable: executableName(input.command),
307 argumentCount: input.args.length,
308 cause,
309 }),
310 ),
311 Effect.catchTags({
312 DesktopShellEnvironmentCommandError: (error) =>
313 logShellEnvironmentCommandError(error).pipe(Effect.as("")),
314 }),
315 Effect.timeoutOption(input.timeout),
316 );
317 if (Option.isSome(output)) {
318 return output.value;
319 }
320
321 const error = new DesktopShellEnvironmentCommandTimeoutError({
322 probe: input.probe,
323 executable: executableName(input.command),
324 argumentCount: input.args.length,
325 timeoutMs: Duration.toMillis(input.timeout),
326 });
327 yield* logShellEnvironmentCommandError(error);
328 return "";
329});
330
331const readLoginShellEnvironment = (
332 shell: string,
333 names: ReadonlyArray<string>,
334): Effect.Effect<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> =>
335 names.length === 0
336 ? Effect.succeed({})
337 : runCommandOutput({
338 probe: "login-shell",
339 command: shell,
340 args: ["-ilc", capturePosixEnvironmentCommand(names)],
341 timeout: LOGIN_SHELL_TIMEOUT,
342 }).pipe(Effect.map((output) => extractEnvironment(output, names)));
343
344const readLaunchctlPath = runCommandOutput({
345 probe: "launchctl-path",
346 command: "/bin/launchctl",
347 args: ["getenv", "PATH"],
348 timeout: LAUNCHCTL_TIMEOUT,
349}).pipe(Effect.map(trimNonEmpty));
350
351const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEnvironment")(
352 function* (
353 names: ReadonlyArray<string>,
354 options: WindowsProbeOptions,
355 ): Effect.fn.Return<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> {
356 if (names.length === 0) return {};
357
358 const args = [
359 "-NoLogo",
360 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
361 "-NonInteractive",
362 "-Command",
363 captureWindowsEnvironmentCommand(names),
364 ];
365
366 for (const command of WINDOWS_SHELL_CANDIDATES) {
367 const output = yield* runCommandOutput({
368 probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile",
369 command,
370 args,
371 timeout: LOGIN_SHELL_TIMEOUT,
372 });
373 const environment = extractEnvironment(output, names);
374 if (Object.keys(environment).length > 0) {
375 return environment;
376 }
377 }
378
379 return {};
380 },
381);
382
383const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWindowsEnvironment")(
384 function* (
385 config: ShellEnvironmentConfig,
386 ): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
387 // Concurrent, not sequential: these two probes are independent (only their
388 // results are combined below) and each spawns its own PowerShell. Run in
389 // series they sit at offset 0 of desktop.startup, before anything else, and
390 // launch traces measured them at 2718ms then 2066ms — the entire 4.8s
391 // startup span, of which desktop.bootstrap is ~30ms.
392 const [noProfile, profile] = yield* Effect.all(
393 [
394 readWindowsEnvironment(["PATH"], { loadProfile: false }),
395 readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }),
396 ],
397 { concurrency: 2 },
398 );
399 const mergedPath = mergePaths("win32", [
400 trimNonEmpty(profile.PATH),
401 trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
402 trimNonEmpty(noProfile.PATH),
403 readEnvPath(config.env),
404 ]);
405
406 if (Option.isSome(mergedPath)) {
407 config.env.PATH = mergedPath.value;
408 }
409 if (!config.env.FNM_DIR && profile.FNM_DIR) {
410 config.env.FNM_DIR = profile.FNM_DIR;
411 }
412 if (!config.env.FNM_MULTISHELL_PATH && profile.FNM_MULTISHELL_PATH) {
413 config.env.FNM_MULTISHELL_PATH = profile.FNM_MULTISHELL_PATH;
414 }
415 },
416);
417
418const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
419 function* (
420 config: ShellEnvironmentConfig,
421 ): Effect.fn.Return<
422 void,
423 never,
424 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
425 > {
426 const fileSystem = yield* FileSystem.FileSystem;
427 const shellEnvironment: EnvironmentPatch = {};
428
429 for (const shell of listLoginShellCandidates(config)) {
430 Object.assign(
431 shellEnvironment,
432 yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES),
433 );
434 if (shellEnvironment.PATH) break;
435 }
436
437 const launchctlPath =
438 config.platform === "darwin" && !shellEnvironment.PATH
439 ? yield* readLaunchctlPath
440 : Option.none<string>();
441 const mergedPath = mergePaths(config.platform, [
442 trimNonEmpty(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
443 readEnvPath(config.env),
444 ]);
445
446 if (Option.isSome(mergedPath)) {
447 config.env.PATH = mergedPath.value;
448 }
449 if (!config.env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
450 config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
451 }
452
453 const shellPreferredEnvNames = [
454 "DBUS_SESSION_BUS_ADDRESS",
455 "XDG_CURRENT_DESKTOP",
456 "XDG_SESSION_DESKTOP",
457 "XDG_SESSION_TYPE",
458 ] as const;
459 for (const name of shellPreferredEnvNames) {
460 if (shellEnvironment[name]) {
461 config.env[name] = shellEnvironment[name];
462 }
463 }
464
465 for (const name of [
466 "DISPLAY",
467 "HOMEBREW_PREFIX",
468 "HOMEBREW_CELLAR",
469 "HOMEBREW_REPOSITORY",
470 "XDG_CONFIG_HOME",
471 "XDG_DATA_HOME",
472 "XDG_RUNTIME_DIR",
473 "WAYLAND_DISPLAY",
474 ] as const) {
475 if (!config.env[name] && shellEnvironment[name]) {
476 config.env[name] = shellEnvironment[name];
477 }
478 }
479
480 // Locale variables form one precedence group: LC_ALL can override an inherited
481 // LANG or LC_CTYPE, so only hydrate the group when the process has none of them.
482 if (
483 config.platform === "darwin" &&
484 LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))
485 ) {
486 for (const name of LOCALE_ENV_NAMES) {
487 const value = trimNonEmpty(shellEnvironment[name]);
488 if (Option.isSome(value)) {
489 config.env[name] = value.value;
490 }
491 }
492
493 // GUI launches inherit no locale from launchd, so spawned agents land in the C
494 // locale and pbcopy decodes their UTF-8 output as MacRoman. Older supported
495 // macOS releases do not provide C.UTF-8, so set only LC_CTYPE to a UTF-8 locale
496 // available on those releases. Leaving LANG unset keeps C-stable collation and
497 // formatting, so output parsing is unaffected.
498 if (LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))) {
499 config.env.LC_CTYPE = FALLBACK_LC_CTYPE;
500 }
501 }
502
503 if (
504 config.platform === "linux" &&
505 Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
506 ) {
507 for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
508 const dbusSessionBusPath = `${runtimeDir}/bus`;
509 const busExists = yield* fileSystem
510 .exists(dbusSessionBusPath)
511 .pipe(Effect.orElseSucceed(() => false));
512 if (busExists) {
513 config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
514 break;
515 }
516 }
517 }
518 },
519);
520
521const installShellEnvironment = (
522 config: ShellEnvironmentConfig,
523): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem> => {
524 if (config.platform === "win32") {
525 return installWindowsEnvironment(config);
526 }
527 if (config.platform === "darwin" || config.platform === "linux") {
528 return installPosixEnvironment(config);
529 }
530 return Effect.void;
531};
532
533export const make = Effect.gen(function* () {
534 const environment = yield* DesktopEnvironment.DesktopEnvironment;
535 const fileSystem = yield* FileSystem.FileSystem;
536 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
537 const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
538 installShellEnvironment({
539 env: process.env,
540 platform: environment.platform,
541 userShell: Option.none(),
542 }).pipe(
543 Effect.provideService(FileSystem.FileSystem, fileSystem),
544 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
545 Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
546 );
547
548 return DesktopShellEnvironment.of({ installIntoProcess });
549});
550
551export const layer = Layer.effect(DesktopShellEnvironment, make);