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

DesktopShellEnvironment.ts

536 lines17.5 KB

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