Open History to see the last commit
1import { listLoginShellCandidates, setWindowsPath } from "@t3tools/shared/shell";
2import * as Clock from "effect/Clock";
3import * as Context from "effect/Context";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Schema from "effect/Schema";
10import * as Stream from "effect/Stream";
11import * as ChildProcess from "effect/process/ChildProcess";
12import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13
14import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
15
16type EnvironmentPatch = Record<string, string>;
17
18interface ShellEnvironmentConfig {
19 readonly env: NodeJS.ProcessEnv;
20 readonly platform: NodeJS.Platform;
21}
22
23interface WindowsProbeOptions {
24 readonly loadProfile: boolean;
25}
26
27const DesktopShellEnvironmentProbe = Schema.Literals([
28 "login-shell",
29 "launchctl-path",
30 "powershell-profile",
31 "powershell-no-profile",
32]);
33type DesktopShellEnvironmentProbe = typeof DesktopShellEnvironmentProbe.Type;
34
35const desktopShellEnvironmentCommandFields = {
36 probe: DesktopShellEnvironmentProbe,
37 executable: Schema.String,
38 argumentCount: Schema.Number,
39};
40
41export class DesktopShellEnvironmentCommandError extends Schema.TaggedError<DesktopShellEnvironmentCommandError>()(
42 "DesktopShellEnvironmentCommandError",
43 {
44 ...desktopShellEnvironmentCommandFields,
45 cause: Schema.Defect(),
46 },
47) {
48 override get message(): string {
49 return `Desktop shell environment ${this.probe} probe (${this.executable}) failed.`;
50 }
51}
52
53export class DesktopShellEnvironmentCommandTimeoutError extends Schema.TaggedError<DesktopShellEnvironmentCommandTimeoutError>()(
54 "DesktopShellEnvironmentCommandTimeoutError",
55 {
56 ...desktopShellEnvironmentCommandFields,
57 timeoutMs: Schema.Number,
58 },
59) {
60 override get message(): string {
61 return `Desktop shell environment ${this.probe} probe (${this.executable}) timed out after ${this.timeoutMs}ms.`;
62 }
63}
64
65export class DesktopShellEnvironment extends Context.Service<
66 DesktopShellEnvironment,
67 {
68 // Reuses the installation result; false leaves server hydration enabled.
69 readonly installIntoProcess: Effect.Effect<boolean>;
70 }
71>()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
72
73const LOGIN_SHELL_ENV_NAMES = [
74 "PATH",
75 "DBUS_SESSION_BUS_ADDRESS",
76 "DISPLAY",
77 "LANG",
78 "LC_ALL",
79 "LC_CTYPE",
80 "SSH_AUTH_SOCK",
81 "HOMEBREW_PREFIX",
82 "HOMEBREW_CELLAR",
83 "HOMEBREW_REPOSITORY",
84 "XDG_CONFIG_HOME",
85 "XDG_CURRENT_DESKTOP",
86 "XDG_DATA_HOME",
87 "XDG_RUNTIME_DIR",
88 "XDG_SESSION_DESKTOP",
89 "XDG_SESSION_TYPE",
90 "WAYLAND_DISPLAY",
91 "SSL_CERT_FILE",
92 "SSL_CERT_DIR",
93 "NODE_EXTRA_CA_CERTS",
94 "T3CODE_TELEMETRY_ENABLED",
95 "__MISE_DIFF",
96] as const;
97const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
98const LOCALE_ENV_NAMES = ["LANG", "LC_ALL", "LC_CTYPE"] as const;
99const FALLBACK_LC_CTYPE = "en_US.UTF-8";
100const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
101const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
102const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
103const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
104
105const trimNonEmpty = (value: string | null | undefined): Option.Option<string> =>
106 Option.fromNullishOr(value).pipe(
107 Option.map((entry) => entry.trim()),
108 Option.filter((entry) => entry.length > 0),
109 );
110
111const pathDelimiter = (platform: NodeJS.Platform) => (platform === "win32" ? ";" : ":");
112
113const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
114 trimNonEmpty(env.PATH ?? env.Path ?? env.path);
115
116const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, "");
117
118const APPIMAGE_SEARCH_PATH_ENV_NAMES = ["PATH", "LD_LIBRARY_PATH", "XDG_DATA_DIRS"] as const;
119
120// The AppImage runtime mounts each launch at `$TMPDIR/.mount_<id>` and prepends
121// it to the search paths above. A launch started from a shell that inherited an
122// earlier launch's env carries that mount too, and once it is unmounted every
123// spawn that walks PATH (git first of all) fails with ENOTCONN.
124const APPIMAGE_MOUNT_ROOT = /^(.*?\/\.mount_[^/]+)(?:\/|$)/u;
125
126const stripStaleAppImageMounts = (env: NodeJS.ProcessEnv): void => {
127 if (env.APPIMAGE === undefined && env.APPDIR === undefined) return;
128 const appDir = env.APPDIR === undefined ? undefined : normalizeRuntimeDir(env.APPDIR);
129 for (const name of APPIMAGE_SEARCH_PATH_ENV_NAMES) {
130 const value = env[name];
131 if (value === undefined) continue;
132 // glibc's loader also splits LD_LIBRARY_PATH on `;`.
133 const segments = value.split(name === "LD_LIBRARY_PATH" ? /[:;]/u : ":");
134 const kept = segments.filter((segment) => {
135 const mountRoot = APPIMAGE_MOUNT_ROOT.exec(segment)?.[1];
136 return mountRoot === undefined || mountRoot === appDir;
137 });
138 if (kept.length === segments.length) continue;
139 if (kept.length === 0) {
140 delete env[name];
141 } else {
142 // An empty segment is the current dir to the loader and to PATH lookup,
143 // but a lone one joins to "", which reads as unset.
144 env[name] = kept.join(":") || ":";
145 }
146 }
147};
148
149const linuxRuntimeDirCandidates = (
150 env: NodeJS.ProcessEnv,
151 uid: number | undefined,
152): ReadonlyArray<string> => {
153 const candidates: string[] = [];
154 const fromEnv = trimNonEmpty(env.XDG_RUNTIME_DIR);
155 if (Option.isSome(fromEnv)) {
156 candidates.push(normalizeRuntimeDir(fromEnv.value));
157 }
158 if (uid !== undefined) {
159 candidates.push(`/run/user/${uid}`);
160 }
161 return candidates.filter((candidate) => candidate.length > 0);
162};
163
164const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => {
165 const normalized = entry.trim().replace(/^"+|"+$/g, "");
166 return platform === "win32" ? normalized.toLowerCase() : normalized;
167};
168
169const sanitizePathEntry = (entry: string, platform: NodeJS.Platform) =>
170 platform === "win32" ? entry.replaceAll('"', "") : entry;
171
172const mergePaths = (
173 platform: NodeJS.Platform,
174 values: ReadonlyArray<Option.Option<string>>,
175): Option.Option<string> => {
176 const delimiter = pathDelimiter(platform);
177 const entries: string[] = [];
178 const seen = new Set<string>();
179
180 for (const value of values) {
181 if (Option.isNone(value)) continue;
182
183 for (const entry of value.value.split(delimiter)) {
184 const sanitized = sanitizePathEntry(entry.trim(), platform);
185 if (sanitized.length === 0) continue;
186
187 const key = pathComparisonKey(sanitized, platform);
188 if (key.length === 0 || seen.has(key)) continue;
189
190 seen.add(key);
191 entries.push(sanitized);
192 }
193 }
194
195 return entries.length > 0 ? Option.some(entries.join(delimiter)) : Option.none();
196};
197
198const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
199 ...trimNonEmpty(env.APPDATA).pipe(
200 Option.match({
201 onNone: () => [],
202 onSome: (value) => [`${value}\\npm`],
203 }),
204 ),
205 ...trimNonEmpty(env.LOCALAPPDATA).pipe(
206 Option.match({
207 onNone: () => [],
208 onSome: (value) => [`${value}\\Programs\\nodejs`, `${value}\\Volta\\bin`, `${value}\\pnpm`],
209 }),
210 ),
211 ...trimNonEmpty(env.USERPROFILE).pipe(
212 Option.match({
213 onNone: () => [],
214 onSome: (value) => [`${value}\\.local\\bin`, `${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
215 }),
216 ),
217];
218
219const startMarker = (name: string) => `__T3CODE_ENV_${name}_START__`;
220const endMarker = (name: string) => `__T3CODE_ENV_${name}_END__`;
221
222const executableName = (command: string): string => command.split(/[\\/]/u).at(-1) ?? command;
223
224const logShellEnvironmentCommandError = (
225 error: DesktopShellEnvironmentCommandError | DesktopShellEnvironmentCommandTimeoutError,
226) =>
227 Effect.logWarning(error).pipe(
228 Effect.annotateLogs({
229 component: "desktop-shell-environment",
230 error,
231 }),
232 );
233
234const capturePosixEnvironmentCommand = (names: ReadonlyArray<string>) =>
235 names
236 .map((name) => {
237 return [
238 `printf '%s\\n' '${startMarker(name)}'`,
239 `printenv ${name} || true`,
240 `printf '%s\\n' '${endMarker(name)}'`,
241 ].join("; ");
242 })
243 .join("; ");
244
245const captureWindowsEnvironmentCommand = (names: ReadonlyArray<string>) =>
246 [
247 "$ErrorActionPreference = 'Stop'",
248 ...names.flatMap((name) => {
249 return [
250 `Write-Output '${startMarker(name)}'`,
251 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
252 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
253 `Write-Output '${endMarker(name)}'`,
254 ];
255 }),
256 ].join("; ");
257
258const extractEnvironment = (output: string, names: ReadonlyArray<string>): EnvironmentPatch => {
259 const environment: EnvironmentPatch = {};
260
261 for (const name of names) {
262 const start = output.indexOf(startMarker(name));
263 if (start === -1) continue;
264
265 const valueStart = start + startMarker(name).length;
266 const end = output.indexOf(endMarker(name), valueStart);
267 if (end === -1) continue;
268
269 const value = output
270 .slice(valueStart, end)
271 .replace(/^\r?\n/, "")
272 .replace(/\r?\n$/, "");
273 if (value.length > 0) {
274 environment[name] = value;
275 }
276 }
277
278 return environment;
279};
280
281const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(function* (input: {
282 readonly probe: DesktopShellEnvironmentProbe;
283 readonly command: string;
284 readonly args: ReadonlyArray<string>;
285 readonly timeout: Duration.Duration;
286 readonly shell?: boolean;
287}): Effect.fn.Return<string, never, ChildProcessSpawner.ChildProcessSpawner> {
288 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
289 const output = yield* Effect.scoped(
290 Effect.gen(function* () {
291 const child = yield* spawner.spawn(
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 return yield* Effect.all([Stream.mkString(Stream.decodeText(child.stdout)), child.exitCode], {
302 concurrency: 2,
303 });
304 }),
305 ).pipe(
306 Effect.mapError(
307 (cause) =>
308 new DesktopShellEnvironmentCommandError({
309 probe: input.probe,
310 executable: executableName(input.command),
311 argumentCount: input.args.length,
312 cause,
313 }),
314 ),
315 Effect.filterOrFail(
316 ([, exitCode]) => exitCode === 0,
317 ([, exitCode]) =>
318 new DesktopShellEnvironmentCommandError({
319 probe: input.probe,
320 executable: executableName(input.command),
321 argumentCount: input.args.length,
322 cause: { exitCode },
323 }),
324 ),
325 Effect.map(([stdout]) => stdout),
326 Effect.catchTags({
327 DesktopShellEnvironmentCommandError: (error) =>
328 logShellEnvironmentCommandError(error).pipe(Effect.as("")),
329 }),
330 Effect.timeoutOption(input.timeout),
331 );
332 if (Option.isSome(output)) {
333 return output.value;
334 }
335
336 const error = new DesktopShellEnvironmentCommandTimeoutError({
337 probe: input.probe,
338 executable: executableName(input.command),
339 argumentCount: input.args.length,
340 timeoutMs: Duration.toMillis(input.timeout),
341 });
342 yield* logShellEnvironmentCommandError(error);
343 return "";
344});
345
346const readLoginShellEnvironment = (
347 shell: string,
348 names: ReadonlyArray<string>,
349): Effect.Effect<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> =>
350 names.length === 0
351 ? Effect.succeed({})
352 : runCommandOutput({
353 probe: "login-shell",
354 command: shell,
355 args: ["-ilc", capturePosixEnvironmentCommand(names)],
356 timeout: LOGIN_SHELL_TIMEOUT,
357 }).pipe(Effect.map((output) => extractEnvironment(output, names)));
358
359const readLaunchctlPath = runCommandOutput({
360 probe: "launchctl-path",
361 command: "/bin/launchctl",
362 args: ["getenv", "PATH"],
363 timeout: LAUNCHCTL_TIMEOUT,
364}).pipe(Effect.map(trimNonEmpty));
365
366const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEnvironment")(
367 function* (
368 names: ReadonlyArray<string>,
369 options: WindowsProbeOptions,
370 ): Effect.fn.Return<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> {
371 if (names.length === 0) return {};
372
373 const args = [
374 "-NoLogo",
375 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
376 "-NonInteractive",
377 "-Command",
378 captureWindowsEnvironmentCommand(names),
379 ];
380
381 const deadline =
382 (yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(LOGIN_SHELL_TIMEOUT);
383 for (const command of WINDOWS_SHELL_CANDIDATES) {
384 const remainingNanos = deadline - (yield* Clock.monotonicTimeNanos);
385 if (remainingNanos <= 0n) break;
386 const output = yield* runCommandOutput({
387 probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile",
388 command,
389 args,
390 timeout: Duration.nanos(remainingNanos),
391 });
392 const environment = extractEnvironment(output, names);
393 if (Object.keys(environment).length > 0) {
394 return environment;
395 }
396 }
397
398 return {};
399 },
400);
401
402const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWindowsEnvironment")(
403 function* (
404 config: ShellEnvironmentConfig,
405 ): Effect.fn.Return<boolean, never, ChildProcessSpawner.ChildProcessSpawner> {
406 // Concurrent, not sequential: these two probes are independent (only their
407 // results are combined below) and each spawns its own PowerShell. Run in
408 // series they sit at offset 0 of desktop.startup, before anything else, and
409 // launch traces measured them at 2718ms then 2066ms — the entire 4.8s
410 // startup span, of which desktop.bootstrap is ~30ms.
411 const [noProfile, profile] = yield* Effect.all(
412 [
413 readWindowsEnvironment(["PATH"], { loadProfile: false }),
414 readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }),
415 ],
416 { concurrency: 2 },
417 );
418 const mergedPath = mergePaths("win32", [
419 trimNonEmpty(profile.PATH),
420 trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
421 trimNonEmpty(noProfile.PATH),
422 readEnvPath(config.env),
423 ]);
424
425 if (Option.isSome(mergedPath)) {
426 setWindowsPath(config.env, mergedPath.value);
427 }
428 if (!config.env.FNM_DIR && profile.FNM_DIR) {
429 config.env.FNM_DIR = profile.FNM_DIR;
430 }
431 if (!config.env.FNM_MULTISHELL_PATH && profile.FNM_MULTISHELL_PATH) {
432 config.env.FNM_MULTISHELL_PATH = profile.FNM_MULTISHELL_PATH;
433 }
434 return Boolean(noProfile.PATH && profile.PATH);
435 },
436);
437
438const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
439 function* (
440 config: ShellEnvironmentConfig,
441 ): Effect.fn.Return<
442 void,
443 never,
444 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
445 > {
446 const fileSystem = yield* FileSystem.FileSystem;
447 const shellEnvironment: EnvironmentPatch = {};
448
449 for (const shell of listLoginShellCandidates(config.platform, config.env.SHELL)) {
450 Object.assign(
451 shellEnvironment,
452 yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES),
453 );
454 if (shellEnvironment.PATH) break;
455 }
456
457 const launchctlPath =
458 config.platform === "darwin" && !shellEnvironment.PATH
459 ? yield* readLaunchctlPath
460 : Option.none<string>();
461 const mergedPath = mergePaths(config.platform, [
462 trimNonEmpty(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
463 readEnvPath(config.env),
464 ]);
465
466 if (Option.isSome(mergedPath)) {
467 config.env.PATH = mergedPath.value;
468 }
469 // The server, relaunch and updater all inherit process.env, so scrubbing
470 // here keeps earlier AppImage launches' mounts out of every one of them.
471 stripStaleAppImageMounts(config.env);
472 if (!config.env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
473 config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
474 }
475
476 const shellPreferredEnvNames = [
477 "DBUS_SESSION_BUS_ADDRESS",
478 "XDG_CURRENT_DESKTOP",
479 "XDG_SESSION_DESKTOP",
480 "XDG_SESSION_TYPE",
481 // mise's record of the PATH entries it added. It must travel with the
482 // shell's PATH, or `mise x` can rebuild PATH behind a same-named wrapper
483 // (`exec mise x claude -- claude`) that then re-runs itself forever.
484 "__MISE_DIFF",
485 ] as const;
486 for (const name of shellPreferredEnvNames) {
487 if (shellEnvironment[name]) {
488 config.env[name] = shellEnvironment[name];
489 }
490 }
491
492 for (const name of [
493 "DISPLAY",
494 "HOMEBREW_PREFIX",
495 "HOMEBREW_CELLAR",
496 "HOMEBREW_REPOSITORY",
497 "XDG_CONFIG_HOME",
498 "XDG_DATA_HOME",
499 "XDG_RUNTIME_DIR",
500 "WAYLAND_DISPLAY",
501 // CA trust set in the shell profile. Without it, a Node or OpenSSL build
502 // that has no bundled roots (a shared-OpenSSL node on PATH) cannot verify
503 // TLS, so provider updaters and agents fail to reach their registries.
504 "SSL_CERT_FILE",
505 "SSL_CERT_DIR",
506 "NODE_EXTRA_CA_CERTS",
507 "T3CODE_TELEMETRY_ENABLED",
508 ] as const) {
509 if (!config.env[name] && shellEnvironment[name]) {
510 config.env[name] = shellEnvironment[name];
511 }
512 }
513
514 // Locale variables form one precedence group: LC_ALL can override an inherited
515 // LANG or LC_CTYPE, so only hydrate the group when the process has none of them.
516 if (
517 config.platform === "darwin" &&
518 LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))
519 ) {
520 for (const name of LOCALE_ENV_NAMES) {
521 const value = trimNonEmpty(shellEnvironment[name]);
522 if (Option.isSome(value)) {
523 config.env[name] = value.value;
524 }
525 }
526
527 // GUI launches inherit no locale from launchd, so spawned agents land in the C
528 // locale and pbcopy decodes their UTF-8 output as MacRoman. Older supported
529 // macOS releases do not provide C.UTF-8, so set only LC_CTYPE to a UTF-8 locale
530 // available on those releases. Leaving LANG unset keeps C-stable collation and
531 // formatting, so output parsing is unaffected.
532 if (LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))) {
533 config.env.LC_CTYPE = FALLBACK_LC_CTYPE;
534 }
535 }
536
537 if (
538 config.platform === "linux" &&
539 Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
540 ) {
541 for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
542 const dbusSessionBusPath = `${runtimeDir}/bus`;
543 const busExists = yield* fileSystem
544 .exists(dbusSessionBusPath)
545 .pipe(Effect.orElseSucceed(() => false));
546 if (busExists) {
547 config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
548 break;
549 }
550 }
551 }
552 },
553);
554
555const installShellEnvironment = (
556 config: ShellEnvironmentConfig,
557): Effect.Effect<
558 boolean,
559 never,
560 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
561> => {
562 if (config.platform === "win32") {
563 return installWindowsEnvironment(config);
564 }
565 if (config.platform === "darwin" || config.platform === "linux") {
566 return installPosixEnvironment(config).pipe(Effect.as(true));
567 }
568 return Effect.succeed(false);
569};
570
571/** @public Service construction is part of the canonical Effect module API. */
572export const make = Effect.gen(function* () {
573 const environment = yield* DesktopEnvironment.DesktopEnvironment;
574 const fileSystem = yield* FileSystem.FileSystem;
575 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
576 const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
577 yield* Effect.cached(
578 installShellEnvironment({
579 env: process.env,
580 platform: environment.platform,
581 }).pipe(
582 Effect.provideService(FileSystem.FileSystem, fileSystem),
583 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
584 Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
585 ),
586 );
587
588 return DesktopShellEnvironment.of({ installIntoProcess });
589});
590
591export const layer = Layer.effect(DesktopShellEnvironment, make);