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

DesktopShellEnvironment.ts

586 lines19.6 KB

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