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