Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Logger from "effect/Logger";
6import * as PlatformError from "effect/PlatformError";
7import * as Schema from "effect/Schema";
8import * as Sink from "effect/Sink";
9import * as Stream from "effect/Stream";
10import * as ChildProcess from "effect/process/ChildProcess";
11import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12import * as NodeOS from "node:os";
13import { vi } from "vite-plus/test";
14
15import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
16import * as DesktopShellEnvironment from "./DesktopShellEnvironment.ts";
17
18vi.mock("node:os", { spy: true });
19
20const textEncoder = new TextEncoder();
21
22const isDesktopShellEnvironmentCommandError = Schema.is(
23 DesktopShellEnvironment.DesktopShellEnvironmentCommandError,
24);
25
26function envOutput(values: Readonly<Record<string, string>>): string {
27 return Object.entries(values)
28 .flatMap(([name, value]) => [
29 `__T3CODE_ENV_${name}_START__`,
30 value,
31 `__T3CODE_ENV_${name}_END__`,
32 ])
33 .join("\n");
34}
35
36function makeProcess(output: string, exitCode = 0): ChildProcessSpawner.ChildProcessHandle {
37 const stdout = output.length === 0 ? Stream.empty : Stream.make(textEncoder.encode(output));
38 return ChildProcessSpawner.makeHandle({
39 pid: ChildProcessSpawner.ProcessId(123),
40 stdout,
41 stderr: Stream.empty,
42 all: stdout,
43 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
44 isRunning: Effect.succeed(false),
45 kill: () => Effect.void,
46 stdin: Sink.drain,
47 getInputFd: () => Sink.drain,
48 getOutputFd: () => Stream.empty,
49 unref: Effect.succeed(Effect.void),
50 });
51}
52
53function withProcessEnv<A, E, R>(
54 env: NodeJS.ProcessEnv,
55 effect: Effect.Effect<A, E, R>,
56): Effect.Effect<A, E, R> {
57 return Effect.acquireUseRelease(
58 Effect.sync(() => {
59 const previous = process.env;
60 process.env = env;
61 return previous;
62 }),
63 () => effect,
64 (previous) =>
65 Effect.sync(() => {
66 process.env = previous;
67 }),
68 );
69}
70
71function runShellEnvironment(input: {
72 readonly env: NodeJS.ProcessEnv;
73 readonly platform: NodeJS.Platform;
74 readonly userShell?: string;
75 readonly handler: (
76 command: ChildProcess.Command,
77 ) => string | { output: string; exitCode: number };
78 readonly failure?: PlatformError.PlatformError;
79}) {
80 const layerEnvironment = Layer.succeed(
81 DesktopEnvironment.DesktopEnvironment,
82 DesktopEnvironment.DesktopEnvironment.of({
83 platform: input.platform,
84 } as DesktopEnvironment.DesktopEnvironment["Service"]),
85 );
86 const layerSpawner = Layer.succeed(
87 ChildProcessSpawner.ChildProcessSpawner,
88 ChildProcessSpawner.make((command) => {
89 if (input.failure !== undefined) return Effect.fail(input.failure);
90 const result = input.handler(command);
91 return Effect.succeed(
92 typeof result === "string"
93 ? makeProcess(result)
94 : makeProcess(result.output, result.exitCode),
95 );
96 }),
97 );
98
99 const program = Effect.gen(function* () {
100 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
101 const prepared = yield* shellEnvironment.installIntoProcess;
102 assert.equal(yield* shellEnvironment.installIntoProcess, prepared);
103 return prepared;
104 }).pipe(
105 Effect.provide(
106 DesktopShellEnvironment.layer.pipe(
107 Layer.provide(Layer.mergeAll(layerEnvironment, NodeServices.layer, layerSpawner)),
108 ),
109 ),
110 );
111
112 return Effect.acquireUseRelease(
113 Effect.sync(() =>
114 vi.spyOn(NodeOS, "userInfo").mockReturnValue({
115 ...NodeOS.userInfo(),
116 shell: input.userShell ?? null,
117 }),
118 ),
119 () => withProcessEnv(input.env, program),
120 (spy) => Effect.sync(() => spy.mockRestore()),
121 );
122}
123
124describe("DesktopShellEnvironment", () => {
125 it.effect("rejects PATH output from a failed shell and tries the next candidate", () =>
126 Effect.gen(function* () {
127 const env: NodeJS.ProcessEnv = { SHELL: "/bin/failing", PATH: "/usr/bin" };
128 const commands: string[] = [];
129
130 yield* runShellEnvironment({
131 env,
132 platform: "linux",
133 userShell: "/usr/local/bin/fish",
134 handler: (command) => {
135 if (command._tag !== "StandardCommand") return "";
136 commands.push(command.command);
137 return command.command === "/bin/failing"
138 ? { output: envOutput({ PATH: "/failed/bin" }), exitCode: 7 }
139 : envOutput({ PATH: "/home/test/.local/bin:/usr/bin" });
140 },
141 }).pipe(Effect.provide(Logger.layer([])));
142
143 assert.deepEqual(commands, ["/bin/failing", "/usr/local/bin/fish"]);
144 assert.equal(env.PATH, "/home/test/.local/bin:/usr/bin");
145 }),
146 );
147
148 it.effect.each(["darwin", "linux"] as const)(
149 "uses the account shell when SHELL is missing on %s",
150 (platform) =>
151 Effect.gen(function* () {
152 const env: NodeJS.ProcessEnv = { PATH: "/usr/bin" };
153 const commands: string[] = [];
154
155 yield* runShellEnvironment({
156 env,
157 platform,
158 userShell: "/usr/local/bin/fish",
159 handler: (command) => {
160 if (command._tag !== "StandardCommand") return "";
161 commands.push(command.command);
162 return envOutput({ PATH: "/home/test/.local/bin:/usr/bin" });
163 },
164 });
165
166 assert.deepEqual(commands, ["/usr/local/bin/fish"]);
167 assert.equal(env.PATH, "/home/test/.local/bin:/usr/bin");
168 }),
169 );
170
171 it.effect("tries the account shell before the platform fallback when SHELL has no PATH", () =>
172 Effect.gen(function* () {
173 const env: NodeJS.ProcessEnv = { SHELL: "/bin/missing", PATH: "/usr/bin" };
174 const commands: string[] = [];
175
176 yield* runShellEnvironment({
177 env,
178 platform: "linux",
179 userShell: "/usr/local/bin/fish",
180 handler: (command) => {
181 if (command._tag !== "StandardCommand") return "";
182 commands.push(command.command);
183 return command.command === "/usr/local/bin/fish"
184 ? envOutput({ PATH: "/home/test/.local/bin:/usr/bin" })
185 : "";
186 },
187 });
188
189 assert.deepEqual(commands, ["/bin/missing", "/usr/local/bin/fish"]);
190 assert.equal(env.PATH, "/home/test/.local/bin:/usr/bin");
191 }),
192 );
193
194 it.effect("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () =>
195 Effect.gen(function* () {
196 const env: NodeJS.ProcessEnv = {
197 SHELL: "/bin/zsh",
198 PATH: "/Users/test/.local/bin:/usr/bin",
199 };
200 const commands: ChildProcess.Command[] = [];
201
202 yield* runShellEnvironment({
203 env,
204 platform: "darwin",
205 handler: (command) => {
206 commands.push(command);
207 return envOutput({
208 PATH: "/opt/homebrew/bin:/usr/bin",
209 SSH_AUTH_SOCK: "/tmp/secretive.sock",
210 HOMEBREW_PREFIX: "/opt/homebrew",
211 });
212 },
213 });
214
215 assert.equal(commands.length, 1);
216 assert.equal(commands[0]?._tag === "StandardCommand" ? commands[0].command : "", "/bin/zsh");
217 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
218 assert.equal(env.SSH_AUTH_SOCK, "/tmp/secretive.sock");
219 assert.equal(env.HOMEBREW_PREFIX, "/opt/homebrew");
220 }),
221 );
222
223 it.effect("preserves inherited POSIX values when present", () =>
224 Effect.gen(function* () {
225 const env: NodeJS.ProcessEnv = {
226 SHELL: "/bin/zsh",
227 PATH: "/usr/bin",
228 SSH_AUTH_SOCK: "/tmp/inherited.sock",
229 };
230
231 yield* runShellEnvironment({
232 env,
233 platform: "darwin",
234 handler: () =>
235 envOutput({
236 PATH: "/opt/homebrew/bin:/usr/bin",
237 SSH_AUTH_SOCK: "/tmp/login-shell.sock",
238 }),
239 });
240
241 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin");
242 assert.equal(env.SSH_AUTH_SOCK, "/tmp/inherited.sock");
243 }),
244 );
245
246 it.effect("hydrates the locale from the login shell on macOS", () =>
247 Effect.gen(function* () {
248 const env: NodeJS.ProcessEnv = {
249 SHELL: "/bin/zsh",
250 PATH: "/usr/bin",
251 };
252
253 yield* runShellEnvironment({
254 env,
255 platform: "darwin",
256 handler: () =>
257 envOutput({
258 PATH: "/opt/homebrew/bin:/usr/bin",
259 LANG: "de_DE.UTF-8",
260 }),
261 });
262
263 assert.equal(env.LANG, "de_DE.UTF-8");
264 }),
265 );
266
267 it.effect("preserves an inherited locale over the login shell on macOS", () =>
268 Effect.gen(function* () {
269 const env: NodeJS.ProcessEnv = {
270 SHELL: "/bin/zsh",
271 PATH: "/usr/bin",
272 LANG: "en_US.UTF-8",
273 };
274
275 yield* runShellEnvironment({
276 env,
277 platform: "darwin",
278 handler: () =>
279 envOutput({
280 PATH: "/opt/homebrew/bin:/usr/bin",
281 LANG: "de_DE.UTF-8",
282 }),
283 });
284
285 assert.equal(env.LANG, "en_US.UTF-8");
286 }),
287 );
288
289 it.effect("does not mix login-shell locale categories into an inherited locale", () =>
290 Effect.gen(function* () {
291 const env: NodeJS.ProcessEnv = {
292 SHELL: "/bin/zsh",
293 PATH: "/usr/bin",
294 LANG: "en_US.UTF-8",
295 };
296
297 yield* runShellEnvironment({
298 env,
299 platform: "darwin",
300 handler: () =>
301 envOutput({
302 PATH: "/opt/homebrew/bin:/usr/bin",
303 LC_ALL: "de_DE.UTF-8",
304 }),
305 });
306
307 assert.equal(env.LANG, "en_US.UTF-8");
308 assert.equal(env.LC_ALL, undefined);
309 }),
310 );
311
312 it.effect("falls back to a UTF-8 LC_CTYPE when no locale is available on macOS", () =>
313 Effect.gen(function* () {
314 const env: NodeJS.ProcessEnv = {
315 SHELL: "/bin/zsh",
316 PATH: "/usr/bin",
317 };
318
319 yield* runShellEnvironment({
320 env,
321 platform: "darwin",
322 handler: () => envOutput({ PATH: "/opt/homebrew/bin:/usr/bin" }),
323 });
324
325 assert.equal(env.LANG, undefined);
326 assert.equal(env.LC_ALL, undefined);
327 assert.equal(env.LC_CTYPE, "en_US.UTF-8");
328 }),
329 );
330
331 it.effect("does not apply the locale fallback on linux", () =>
332 Effect.gen(function* () {
333 const env: NodeJS.ProcessEnv = {
334 SHELL: "/bin/zsh",
335 PATH: "/usr/bin",
336 };
337
338 yield* runShellEnvironment({
339 env,
340 platform: "linux",
341 handler: () => envOutput({ PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin" }),
342 });
343
344 assert.equal(env.LANG, undefined);
345 }),
346 );
347
348 it.effect("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () =>
349 Effect.gen(function* () {
350 const env: NodeJS.ProcessEnv = {
351 SHELL: "/bin/zsh",
352 PATH: "/usr/bin",
353 };
354
355 yield* runShellEnvironment({
356 env,
357 platform: "linux",
358 handler: () =>
359 envOutput({
360 PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
361 SSH_AUTH_SOCK: "/tmp/secretive.sock",
362 T3CODE_TELEMETRY_ENABLED: "false",
363 }),
364 });
365
366 assert.equal(env.PATH, "/home/linuxbrew/.linuxbrew/bin:/usr/bin");
367 assert.equal(env.SSH_AUTH_SOCK, "/tmp/secretive.sock");
368 assert.equal(env.T3CODE_TELEMETRY_ENABLED, "false");
369 }),
370 );
371
372 it.effect("hydrates missing CA trust variables from the login shell", () =>
373 Effect.gen(function* () {
374 const env: NodeJS.ProcessEnv = {
375 SHELL: "/bin/zsh",
376 PATH: "/usr/bin",
377 SSL_CERT_DIR: "/etc/ssl/certs",
378 };
379
380 yield* runShellEnvironment({
381 env,
382 platform: "darwin",
383 handler: () =>
384 envOutput({
385 PATH: "/opt/zerobrew/bin:/usr/bin",
386 SSL_CERT_FILE: "/opt/zerobrew/etc/ca-certificates/cacert.pem",
387 SSL_CERT_DIR: "/opt/zerobrew/etc/ca-certificates",
388 NODE_EXTRA_CA_CERTS: "/Users/me/corp-root.pem",
389 }),
390 });
391
392 assert.equal(env.SSL_CERT_FILE, "/opt/zerobrew/etc/ca-certificates/cacert.pem");
393 assert.equal(env.SSL_CERT_DIR, "/etc/ssl/certs");
394 assert.equal(env.NODE_EXTRA_CA_CERTS, "/Users/me/corp-root.pem");
395 }),
396 );
397
398 it.effect("keeps mise's PATH record with the login shell PATH", () =>
399 Effect.gen(function* () {
400 const env: NodeJS.ProcessEnv = {
401 SHELL: "/bin/bash",
402 PATH: "/usr/bin",
403 };
404
405 yield* runShellEnvironment({
406 env,
407 platform: "linux",
408 handler: () =>
409 envOutput({
410 PATH: "/home/me/.local/bin:/mise/installs/claude/latest:/mise/shims",
411 __MISE_DIFF: "mise-diff",
412 }),
413 });
414
415 assert.equal(env.__MISE_DIFF, "mise-diff");
416 }),
417 );
418
419 it.effect("falls back to launchctl PATH on macOS when shell probing does not return one", () =>
420 Effect.gen(function* () {
421 const env: NodeJS.ProcessEnv = {
422 SHELL: "/opt/homebrew/bin/nu",
423 PATH: "/usr/bin",
424 };
425 const commands: string[] = [];
426
427 yield* runShellEnvironment({
428 env,
429 platform: "darwin",
430 handler: (command) => {
431 if (command._tag !== "StandardCommand") return "";
432 commands.push(command.command);
433 return command.command === "/bin/launchctl" ? "/opt/homebrew/bin:/usr/bin" : "";
434 },
435 });
436
437 assert.deepEqual(commands, ["/opt/homebrew/bin/nu", "/bin/zsh", "/bin/launchctl"]);
438 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin");
439 }),
440 );
441
442 it.effect("loads PowerShell profile environment on Windows", () =>
443 Effect.gen(function* () {
444 const env: NodeJS.ProcessEnv = {
445 PATH: "C:\\Windows\\System32",
446 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
447 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
448 USERPROFILE: "C:\\Users\\testuser",
449 };
450
451 const prepared = yield* runShellEnvironment({
452 env,
453 platform: "win32",
454 handler: (command) => {
455 if (command._tag !== "StandardCommand") return "";
456 const loadProfile = !command.args.includes("-NoProfile");
457 return loadProfile
458 ? envOutput({
459 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
460 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
461 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
462 })
463 : envOutput({ PATH: 'C:\\Custom\\Bin;C:";C:\\Windows\\System32' });
464 },
465 });
466
467 assert.isTrue(prepared);
468 assert.equal(
469 env.PATH,
470 [
471 "C:\\Profile\\Node",
472 "C:\\Windows\\System32",
473 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
474 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
475 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
476 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
477 "C:\\Users\\testuser\\.local\\bin",
478 "C:\\Users\\testuser\\.bun\\bin",
479 "C:\\Users\\testuser\\scoop\\shims",
480 "C:\\Custom\\Bin",
481 "C:",
482 ].join(";"),
483 );
484 assert.equal(env.FNM_DIR, "C:\\Users\\testuser\\AppData\\Roaming\\fnm");
485 assert.equal(
486 env.FNM_MULTISHELL_PATH,
487 "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
488 );
489 }),
490 );
491
492 it.effect.each([false, true])(
493 "leaves Windows preparation incomplete when loadProfile=%s fails",
494 (loadProfile) =>
495 Effect.gen(function* () {
496 const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows\\System32" };
497 let calls = 0;
498 const prepared = yield* runShellEnvironment({
499 env,
500 platform: "win32",
501 handler: (command) => {
502 calls++;
503 if (command._tag !== "StandardCommand") return "";
504 return !command.args.includes("-NoProfile") === loadProfile
505 ? { output: "", exitCode: 1 }
506 : envOutput({ PATH: "C:\\Working" });
507 },
508 }).pipe(Effect.provide(Logger.layer([])));
509 assert.isFalse(prepared);
510 assert.equal(calls, 3);
511 assert.include(env.PATH, "C:\\Working");
512 assert.include(env.PATH, "C:\\Windows\\System32");
513 }),
514 );
515
516 it.effect("replaces a Path-spelled Windows PATH instead of adding a second key", () =>
517 Effect.gen(function* () {
518 const env: NodeJS.ProcessEnv = { Path: "C:\\Windows\\System32" };
519
520 yield* runShellEnvironment({
521 env,
522 platform: "win32",
523 handler: (command) =>
524 command._tag === "StandardCommand" && command.args.includes("-NoProfile")
525 ? envOutput({ PATH: "C:\\Shell\\Bin" })
526 : "",
527 });
528
529 assert.deepEqual(env, { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" });
530 }),
531 );
532
533 it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
534 Effect.gen(function* () {
535 const env: NodeJS.ProcessEnv = {
536 SHELL: "/bin/zsh",
537 PATH: "/usr/bin",
538 XDG_CURRENT_DESKTOP: "wrong-launcher",
539 XDG_SESSION_DESKTOP: "wrong-launcher",
540 };
541
542 yield* runShellEnvironment({
543 env,
544 platform: "linux",
545 handler: () =>
546 envOutput({
547 PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
548 XDG_CURRENT_DESKTOP: "KDE",
549 XDG_SESSION_DESKTOP: "KDE",
550 XDG_SESSION_TYPE: "wayland",
551 }),
552 });
553
554 assert.equal(env.XDG_CURRENT_DESKTOP, "KDE");
555 assert.equal(env.XDG_SESSION_DESKTOP, "KDE");
556 assert.equal(env.XDG_SESSION_TYPE, "wayland");
557 }),
558 );
559
560 it.effect("overrides stale dbus session addresses from the login shell", () =>
561 Effect.gen(function* () {
562 const env: NodeJS.ProcessEnv = {
563 SHELL: "/bin/zsh",
564 PATH: "/usr/bin",
565 DBUS_SESSION_BUS_ADDRESS: "unix:path=/tmp/stale-bus",
566 };
567
568 yield* runShellEnvironment({
569 env,
570 platform: "linux",
571 handler: () =>
572 envOutput({
573 PATH: "/usr/bin",
574 DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus",
575 }),
576 });
577
578 assert.equal(env.DBUS_SESSION_BUS_ADDRESS, "unix:path=/run/user/1000/bus");
579 }),
580 );
581
582 it.effect("logs command failures with safe probe context and the exact cause", () => {
583 const env: NodeJS.ProcessEnv = {
584 SHELL: "/bin/bash",
585 PATH: "/usr/bin",
586 };
587 const cause = PlatformError.systemError({
588 _tag: "PermissionDenied",
589 module: "ChildProcess",
590 method: "spawn",
591 pathOrDescriptor: "/bin/bash",
592 });
593 const messages: Array<unknown> = [];
594 const logger = Logger.make(({ message }) => {
595 messages.push(message);
596 });
597
598 return runShellEnvironment({
599 env,
600 platform: "linux",
601 handler: () => "",
602 failure: cause,
603 }).pipe(
604 Effect.andThen(
605 Effect.sync(() => {
606 const errors = messages
607 .flatMap((message) => (Array.isArray(message) ? message : [message]))
608 .filter(isDesktopShellEnvironmentCommandError);
609 assert.lengthOf(errors, 1);
610 assert.equal(errors[0]?.probe, "login-shell");
611 assert.equal(errors[0]?.executable, "bash");
612 assert.equal(errors[0]?.argumentCount, 2);
613 assert.notProperty(errors[0] ?? {}, "args");
614 assert.equal(errors[0]?.cause, cause);
615 assert.notInclude(errors[0]?.message ?? "", cause.message);
616 }),
617 ),
618 Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
619 );
620 });
621});