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