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

DesktopShellEnvironment.ts

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