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