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 Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import * as ChildProcess from "effect/unstable/process/ChildProcess";
8import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
9
10import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
11
12type EnvironmentPatch = Record<string, string>;
13
14interface ShellEnvironmentConfig {
15 readonly env: NodeJS.ProcessEnv;
16 readonly platform: NodeJS.Platform;
17 readonly userShell: Option.Option<string>;
18}
19
20interface WindowsProbeOptions {
21 readonly loadProfile: boolean;
22}
23
24const DesktopShellEnvironmentProbe = Schema.Literals([
25 "login-shell",
26 "launchctl-path",
27 "powershell-profile",
28 "powershell-no-profile",
29]);
30type DesktopShellEnvironmentProbe = typeof DesktopShellEnvironmentProbe.Type;
31
32const desktopShellEnvironmentCommandFields = {
33 probe: DesktopShellEnvironmentProbe,
34 executable: Schema.String,
35 argumentCount: Schema.Number,
36};
37
38export class DesktopShellEnvironmentCommandError extends Schema.TaggedErrorClass<DesktopShellEnvironmentCommandError>()(
39 "DesktopShellEnvironmentCommandError",
40 {
41 ...desktopShellEnvironmentCommandFields,
42 cause: Schema.Defect(),
43 },
44) {
45 override get message(): string {
46 return `Desktop shell environment ${this.probe} probe (${this.executable}) failed.`;
47 }
48}
49
50export class DesktopShellEnvironmentCommandTimeoutError extends Schema.TaggedErrorClass<DesktopShellEnvironmentCommandTimeoutError>()(
51 "DesktopShellEnvironmentCommandTimeoutError",
52 {
53 ...desktopShellEnvironmentCommandFields,
54 timeoutMs: Schema.Number,
55 },
56) {
57 override get message(): string {
58 return `Desktop shell environment ${this.probe} probe (${this.executable}) timed out after ${this.timeoutMs}ms.`;
59 }
60}
61
62export class DesktopShellEnvironment extends Context.Service<
63 DesktopShellEnvironment,
64 {
65 readonly installIntoProcess: Effect.Effect<void>;
66 }
67>()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
68
69const LOGIN_SHELL_ENV_NAMES = [
70 "PATH",
71 "SSH_AUTH_SOCK",
72 "HOMEBREW_PREFIX",
73 "HOMEBREW_CELLAR",
74 "HOMEBREW_REPOSITORY",
75 "XDG_CONFIG_HOME",
76 "XDG_DATA_HOME",
77] as const;
78const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
79const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
80const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
81const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
82const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
83
84const trimNonEmpty = (value: string | null | undefined): Option.Option<string> =>
85 Option.fromNullishOr(value).pipe(
86 Option.map((entry) => entry.trim()),
87 Option.filter((entry) => entry.length > 0),
88 );
89
90const pathDelimiter = (platform: NodeJS.Platform) => (platform === "win32" ? ";" : ":");
91
92const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
93 trimNonEmpty(env.PATH ?? env.Path ?? env.path);
94
95const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => {
96 const normalized = entry.trim().replace(/^"+|"+$/g, "");
97 return platform === "win32" ? normalized.toLowerCase() : normalized;
98};
99
100const mergePaths = (
101 platform: NodeJS.Platform,
102 values: ReadonlyArray<Option.Option<string>>,
103): Option.Option<string> => {
104 const delimiter = pathDelimiter(platform);
105 const entries: string[] = [];
106 const seen = new Set<string>();
107
108 for (const value of values) {
109 if (Option.isNone(value)) continue;
110
111 for (const entry of value.value.split(delimiter)) {
112 const trimmed = entry.trim();
113 if (trimmed.length === 0) continue;
114
115 const key = pathComparisonKey(trimmed, platform);
116 if (key.length === 0 || seen.has(key)) continue;
117
118 seen.add(key);
119 entries.push(trimmed);
120 }
121 }
122
123 return entries.length > 0 ? Option.some(entries.join(delimiter)) : Option.none();
124};
125
126const listLoginShellCandidates = (config: ShellEnvironmentConfig): ReadonlyArray<string> => {
127 const fallback =
128 config.platform === "darwin" ? "/bin/zsh" : config.platform === "linux" ? "/bin/bash" : "";
129 const seen = new Set<string>();
130 const candidates: string[] = [];
131
132 for (const candidate of [
133 trimNonEmpty(config.env.SHELL),
134 config.userShell,
135 trimNonEmpty(fallback),
136 ]) {
137 if (Option.isNone(candidate) || seen.has(candidate.value)) continue;
138 seen.add(candidate.value);
139 candidates.push(candidate.value);
140 }
141
142 return candidates;
143};
144
145const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
146 ...trimNonEmpty(env.APPDATA).pipe(
147 Option.match({
148 onNone: () => [],
149 onSome: (value) => [`${value}\\npm`],
150 }),
151 ),
152 ...trimNonEmpty(env.LOCALAPPDATA).pipe(
153 Option.match({
154 onNone: () => [],
155 onSome: (value) => [`${value}\\Programs\\nodejs`, `${value}\\Volta\\bin`, `${value}\\pnpm`],
156 }),
157 ),
158 ...trimNonEmpty(env.USERPROFILE).pipe(
159 Option.match({
160 onNone: () => [],
161 onSome: (value) => [`${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
162 }),
163 ),
164];
165
166const startMarker = (name: string) => `__T3CODE_ENV_${name}_START__`;
167const endMarker = (name: string) => `__T3CODE_ENV_${name}_END__`;
168
169const executableName = (command: string): string => command.split(/[\\/]/u).at(-1) ?? command;
170
171const logShellEnvironmentCommandError = (
172 error: DesktopShellEnvironmentCommandError | DesktopShellEnvironmentCommandTimeoutError,
173) =>
174 Effect.logWarning(error).pipe(
175 Effect.annotateLogs({
176 component: "desktop-shell-environment",
177 error,
178 }),
179 );
180
181const capturePosixEnvironmentCommand = (names: ReadonlyArray<string>) =>
182 names
183 .map((name) => {
184 return [
185 `printf '%s\\n' '${startMarker(name)}'`,
186 `printenv ${name} || true`,
187 `printf '%s\\n' '${endMarker(name)}'`,
188 ].join("; ");
189 })
190 .join("; ");
191
192const captureWindowsEnvironmentCommand = (names: ReadonlyArray<string>) =>
193 [
194 "$ErrorActionPreference = 'Stop'",
195 ...names.flatMap((name) => {
196 return [
197 `Write-Output '${startMarker(name)}'`,
198 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
199 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
200 `Write-Output '${endMarker(name)}'`,
201 ];
202 }),
203 ].join("; ");
204
205const extractEnvironment = (output: string, names: ReadonlyArray<string>): EnvironmentPatch => {
206 const environment: EnvironmentPatch = {};
207
208 for (const name of names) {
209 const start = output.indexOf(startMarker(name));
210 if (start === -1) continue;
211
212 const valueStart = start + startMarker(name).length;
213 const end = output.indexOf(endMarker(name), valueStart);
214 if (end === -1) continue;
215
216 const value = output
217 .slice(valueStart, end)
218 .replace(/^\r?\n/, "")
219 .replace(/\r?\n$/, "");
220 if (value.length > 0) {
221 environment[name] = value;
222 }
223 }
224
225 return environment;
226};
227
228const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(function* (input: {
229 readonly probe: DesktopShellEnvironmentProbe;
230 readonly command: string;
231 readonly args: ReadonlyArray<string>;
232 readonly timeout: Duration.Duration;
233 readonly shell?: boolean;
234}): Effect.fn.Return<string, never, ChildProcessSpawner.ChildProcessSpawner> {
235 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
236 const output = yield* spawner
237 .string(
238 ChildProcess.make(input.command, input.args, {
239 shell: input.shell ?? false,
240 stdin: "ignore",
241 stdout: "pipe",
242 stderr: "pipe",
243 killSignal: "SIGTERM",
244 forceKillAfter: PROCESS_TERMINATE_GRACE,
245 }),
246 )
247 .pipe(
248 Effect.mapError(
249 (cause) =>
250 new DesktopShellEnvironmentCommandError({
251 probe: input.probe,
252 executable: executableName(input.command),
253 argumentCount: input.args.length,
254 cause,
255 }),
256 ),
257 Effect.catchTags({
258 DesktopShellEnvironmentCommandError: (error) =>
259 logShellEnvironmentCommandError(error).pipe(Effect.as("")),
260 }),
261 Effect.timeoutOption(input.timeout),
262 );
263 if (Option.isSome(output)) {
264 return output.value;
265 }
266
267 const error = new DesktopShellEnvironmentCommandTimeoutError({
268 probe: input.probe,
269 executable: executableName(input.command),
270 argumentCount: input.args.length,
271 timeoutMs: Duration.toMillis(input.timeout),
272 });
273 yield* logShellEnvironmentCommandError(error);
274 return "";
275});
276
277const readLoginShellEnvironment = (
278 shell: string,
279 names: ReadonlyArray<string>,
280): Effect.Effect<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> =>
281 names.length === 0
282 ? Effect.succeed({})
283 : runCommandOutput({
284 probe: "login-shell",
285 command: shell,
286 args: ["-ilc", capturePosixEnvironmentCommand(names)],
287 timeout: LOGIN_SHELL_TIMEOUT,
288 }).pipe(Effect.map((output) => extractEnvironment(output, names)));
289
290const readLaunchctlPath = runCommandOutput({
291 probe: "launchctl-path",
292 command: "/bin/launchctl",
293 args: ["getenv", "PATH"],
294 timeout: LAUNCHCTL_TIMEOUT,
295}).pipe(Effect.map(trimNonEmpty));
296
297const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEnvironment")(
298 function* (
299 names: ReadonlyArray<string>,
300 options: WindowsProbeOptions,
301 ): Effect.fn.Return<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> {
302 if (names.length === 0) return {};
303
304 const args = [
305 "-NoLogo",
306 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
307 "-NonInteractive",
308 "-Command",
309 captureWindowsEnvironmentCommand(names),
310 ];
311
312 for (const command of WINDOWS_SHELL_CANDIDATES) {
313 const output = yield* runCommandOutput({
314 probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile",
315 command,
316 args,
317 timeout: LOGIN_SHELL_TIMEOUT,
318 });
319 const environment = extractEnvironment(output, names);
320 if (Object.keys(environment).length > 0) {
321 return environment;
322 }
323 }
324
325 return {};
326 },
327);
328
329const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWindowsEnvironment")(
330 function* (
331 config: ShellEnvironmentConfig,
332 ): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
333 const noProfile = yield* readWindowsEnvironment(["PATH"], { loadProfile: false });
334 const profile = yield* readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, {
335 loadProfile: true,
336 });
337 const mergedPath = mergePaths("win32", [
338 trimNonEmpty(profile.PATH),
339 trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
340 trimNonEmpty(noProfile.PATH),
341 readEnvPath(config.env),
342 ]);
343
344 if (Option.isSome(mergedPath)) {
345 config.env.PATH = mergedPath.value;
346 }
347 if (!config.env.FNM_DIR && profile.FNM_DIR) {
348 config.env.FNM_DIR = profile.FNM_DIR;
349 }
350 if (!config.env.FNM_MULTISHELL_PATH && profile.FNM_MULTISHELL_PATH) {
351 config.env.FNM_MULTISHELL_PATH = profile.FNM_MULTISHELL_PATH;
352 }
353 },
354);
355
356const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
357 function* (
358 config: ShellEnvironmentConfig,
359 ): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
360 const shellEnvironment: EnvironmentPatch = {};
361
362 for (const shell of listLoginShellCandidates(config)) {
363 Object.assign(
364 shellEnvironment,
365 yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES),
366 );
367 if (shellEnvironment.PATH) break;
368 }
369
370 const launchctlPath =
371 config.platform === "darwin" && !shellEnvironment.PATH
372 ? yield* readLaunchctlPath
373 : Option.none<string>();
374 const mergedPath = mergePaths(config.platform, [
375 trimNonEmpty(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
376 readEnvPath(config.env),
377 ]);
378
379 if (Option.isSome(mergedPath)) {
380 config.env.PATH = mergedPath.value;
381 }
382 if (!config.env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
383 config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
384 }
385
386 for (const name of [
387 "HOMEBREW_PREFIX",
388 "HOMEBREW_CELLAR",
389 "HOMEBREW_REPOSITORY",
390 "XDG_CONFIG_HOME",
391 "XDG_DATA_HOME",
392 ] as const) {
393 if (!config.env[name] && shellEnvironment[name]) {
394 config.env[name] = shellEnvironment[name];
395 }
396 }
397 },
398);
399
400const installShellEnvironment = (
401 config: ShellEnvironmentConfig,
402): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
403 if (config.platform === "win32") {
404 return installWindowsEnvironment(config);
405 }
406 if (config.platform === "darwin" || config.platform === "linux") {
407 return installPosixEnvironment(config);
408 }
409 return Effect.void;
410};
411
412export const make = Effect.gen(function* () {
413 const environment = yield* DesktopEnvironment.DesktopEnvironment;
414 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
415 const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
416 installShellEnvironment({
417 env: process.env,
418 platform: environment.platform,
419 userShell: Option.none(),
420 }).pipe(
421 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
422 Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
423 );
424
425 return DesktopShellEnvironment.of({ installIntoProcess });
426});
427
428export const layer = Layer.effect(DesktopShellEnvironment, make);