Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopShellEnvironment.ts

584 lines19.6 KB

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