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