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