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

DesktopShellEnvironment.ts

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