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