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

DesktopShellEnvironment.ts

577 lines18.7 KB

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