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

DesktopShellEnvironment.test.ts

826 lines27.4 KB

1// @effect-diagnostics nodeBuiltinImport:off -- The process fixture runs real shell commands with isolated config files.
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Clock from "effect/Clock";
4import { assert, describe, it } from "@effect/vitest";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as Layer from "effect/Layer";
9import * as Logger from "effect/Logger";
10import * as PlatformError from "effect/PlatformError";
11import * as Schema from "effect/Schema";
12import * as Sink from "effect/Sink";
13import * as Stream from "effect/Stream";
14import * as ChildProcess from "effect/process/ChildProcess";
15import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16import * as NodeChildProcess from "node:child_process";
17import * as NodeFS from "node:fs";
18import * as TestClock from "effect/testing/TestClock";
19import * as NodeOS from "node:os";
20import * as NodePath from "node:path";
21import { vi } from "vite-plus/test";
22​
23import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
24import * as DesktopShellEnvironment from "./DesktopShellEnvironment.ts";
25​
26vi.mock("node:os", { spy: true });
27​
28const textEncoder = new TextEncoder();
29​
30const isDesktopShellEnvironmentCommandError = Schema.is(
31 DesktopShellEnvironment.DesktopShellEnvironmentCommandError,
32);
33​
34function envOutput(values: Readonly<Record<string, string>>): string {
35 return Object.entries(values)
36 .flatMap(([name, value]) => [
37 `__T3CODE_ENV_${name}_START__`,
38 value,
39 `__T3CODE_ENV_${name}_END__`,
40 ])
41 .join("\n");
43​
44function makeProcess(output: string, exitCode = 0): ChildProcessSpawner.ChildProcessHandle {
45 const stdout = output.length === 0 ? Stream.empty : Stream.make(textEncoder.encode(output));
46 return ChildProcessSpawner.makeHandle({
47 pid: ChildProcessSpawner.ProcessId(123),
48 stdout,
49 stderr: Stream.empty,
50 all: stdout,
51 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
52 isRunning: Effect.succeed(false),
53 kill: () => Effect.void,
54 stdin: Sink.drain,
55 getInputFd: () => Sink.drain,
56 getOutputFd: () => Stream.empty,
57 unref: Effect.succeed(Effect.void),
58 });
60​
61function withProcessEnv<A, E, R>(
62 env: NodeJS.ProcessEnv,
63 effect: Effect.Effect<A, E, R>,
64): Effect.Effect<A, E, R> {
65 return Effect.acquireUseRelease(
66 Effect.sync(() => {
67 const previous = process.env;
68 process.env = env;
69 return previous;
70 }),
71 () => effect,
72 (previous) =>
73 Effect.sync(() => {
74 process.env = previous;
75 }),
76 );
78​
79function runShellEnvironment(input: {
80 readonly env: NodeJS.ProcessEnv;
81 readonly platform: NodeJS.Platform;
82 readonly userShell?: string;
83 readonly handler: (
84 command: ChildProcess.Command,
85 ) =>
86 | string
87 | { output: string; exitCode: number }
88 | Effect.Effect<ChildProcessSpawner.ChildProcessHandle, PlatformError.PlatformError>;
89 readonly failure?: PlatformError.PlatformError;
90}) {
91 const layerEnvironment = Layer.succeed(
92 DesktopEnvironment.DesktopEnvironment,
93 DesktopEnvironment.DesktopEnvironment.of({
94 platform: input.platform,
95 } as DesktopEnvironment.DesktopEnvironment["Service"]),
96 );
97 const layerSpawner = Layer.succeed(
98 ChildProcessSpawner.ChildProcessSpawner,
99 ChildProcessSpawner.make((command) => {
100 if (input.failure !== undefined) return Effect.fail(input.failure);
101 const result = input.handler(command);
102 if (Effect.isEffect(result)) return result;
103 return Effect.succeed(
104 typeof result === "string"
105 ? makeProcess(result)
106 : makeProcess(result.output, result.exitCode),
107 );
108 }),
109 );
110​
111 const program = Effect.gen(function* () {
112 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
113 const prepared = yield* shellEnvironment.installIntoProcess;
114 assert.equal(yield* shellEnvironment.installIntoProcess, prepared);
115 return prepared;
116 }).pipe(
117 Effect.provide(
118 DesktopShellEnvironment.layer.pipe(
119 Layer.provide(Layer.mergeAll(layerEnvironment, NodeServices.layer, layerSpawner)),
120 ),
121 ),
122 );
123​
124 return Effect.acquireUseRelease(
125 Effect.sync(() =>
126 vi.spyOn(NodeOS, "userInfo").mockReturnValue({
127 ...NodeOS.userInfo(),
128 shell: input.userShell ?? null,
129 }),
130 ),
131 () => withProcessEnv(input.env, program),
132 (spy) => Effect.sync(() => spy.mockRestore()),
133 );
135​
136describe("DesktopShellEnvironment", () => {
137 // Explicit opt-in keeps real shell coverage independent of globally installed tools.
138 it.effect.runIf(process.env.T3_TEST_NU_PATH !== undefined)(
139 "hydrates the desktop through a renamed Nushell symlink with native export conversions",
140 () =>
141 Effect.gen(function* () {
142 const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-desktop-nu-"));
143 try {
144 const toolPath = NodePath.join(home, "nu tools", "bin");
145 const extraToolPath = NodePath.join(home, "extra-tools", "bin");
146 const convertedToolPath = NodePath.join(home, "converted-tools", "bin");
147 NodeFS.mkdirSync(toolPath, { recursive: true });
148 NodeFS.mkdirSync(extraToolPath, { recursive: true });
149 NodeFS.mkdirSync(convertedToolPath, { recursive: true });
150 const shell = NodePath.join(toolPath, "nushell");
151 NodeFS.symlinkSync(process.env.T3_TEST_NU_PATH!, shell);
152 const config = NodePath.join(home, "config.nu");
153 const envConfig = NodePath.join(home, "env.nu");
154 NodeFS.writeFileSync(envConfig, "");
155 NodeFS.writeFileSync(
156 config,
157 [
158 `$env.PATH = [${JSON.stringify(toolPath)}, ${JSON.stringify(extraToolPath)}]`,
159 '$env.SSH_AUTH_SOCK = "/tmp/nu-agent.sock"',
160 '$env.__MISE_DIFF = " first\\nsecond "',
161 '$env.HOMEBREW_PREFIX = ""',
162 "$env.ENV_CONVERSIONS = {",
163 " PATH: {",
164 " from_string: {|value| $value | split row (char esep) },",
165 ' to_string: {|value| $value | str join (char esep) | str replace "nu tools" "converted-tools" }',
166 " },",
167 " __MISE_DIFF: { from_string: {|value| $value }, to_string: { str upcase } }",
168 "}",
169 'print "startup noise"',
170 ].join("\n"),
171 );
172 const env: NodeJS.ProcessEnv = { SHELL: shell, PATH: `/inherited/bin:${extraToolPath}` };
173 yield* runShellEnvironment({
174 env,
175 platform: "linux",
176 handler: (command) => {
177 if (command._tag !== "StandardCommand" || command.command !== shell) return "";
178 const result = NodeChildProcess.spawnSync(
179 command.command,
180 ["--no-history", "--config", config, "--env-config", envConfig, ...command.args],
181 {
182 encoding: "utf8",
183 timeout: 5000,
184 env: { HOME: home, XDG_CONFIG_HOME: home, PATH: toolPath },
185 },
186 );
187 if (result.error) throw result.error;
188 return { output: result.stdout, exitCode: result.status ?? 1 };
189 },
190 });
191​
192 assert.deepEqual(
193 { PATH: env.PATH, __MISE_DIFF: env.__MISE_DIFF },
194 {
195 PATH: `${convertedToolPath}:${extraToolPath}:/inherited/bin`,
196 __MISE_DIFF: " FIRST\nSECOND ",
197 },
198 );
199 assert.equal(env.SSH_AUTH_SOCK, "/tmp/nu-agent.sock");
200 assert.isUndefined(env.DISPLAY);
201 assert.isUndefined(env.HOMEBREW_PREFIX);
202 } finally {
203 NodeFS.rmSync(home, { recursive: true, force: true });
204 }
205 }),
206 );
207​
208 it.effect("rejects PATH output from a failed shell and tries the next candidate", () =>
209 Effect.gen(function* () {
210 const env: NodeJS.ProcessEnv = { SHELL: "/bin/failing", PATH: "/usr/bin" };
211 const commands: string[] = [];
212​
213 yield* runShellEnvironment({
214 env,
215 platform: "linux",
216 userShell: "/usr/local/bin/fish",
217 handler: (command) => {
218 if (command._tag !== "StandardCommand") return "";
219 commands.push(command.command);
220 return command.command === "/bin/failing"
221 ? { output: envOutput({ PATH: "/failed/bin" }), exitCode: 7 }
222 : envOutput({ PATH: "/home/test/.local/bin:/usr/bin" });
223 },
224 }).pipe(Effect.provide(Logger.layer([])));
225​
226 assert.deepEqual(commands, ["/bin/failing", "/usr/local/bin/fish"]);
227 assert.equal(env.PATH, "/home/test/.local/bin:/usr/bin");
228 }),
229 );
230​
231 it.effect.each(["darwin", "linux"] as const)(
232 "uses the account shell when SHELL is missing on %s",
233 (platform) =>
234 Effect.gen(function* () {
235 const env: NodeJS.ProcessEnv = { PATH: "/usr/bin" };
236 const commands: string[] = [];
237​
238 yield* runShellEnvironment({
239 env,
240 platform,
241 userShell: "/usr/local/bin/fish",
242 handler: (command) => {
243 if (command._tag !== "StandardCommand") return "";
244 commands.push(command.command);
245 return envOutput({ PATH: "/home/test/.local/bin:/usr/bin" });
246 },
247 });
248​
249 assert.deepEqual(commands, ["/usr/local/bin/fish"]);
250 assert.equal(env.PATH, "/home/test/.local/bin:/usr/bin");
251 }),
252 );
253​
254 it.effect("tries the account shell before the platform fallback when SHELL has no PATH", () =>
255 Effect.gen(function* () {
256 const env: NodeJS.ProcessEnv = { SHELL: "/bin/missing", PATH: "/usr/bin" };
257 const commands: string[] = [];
258​
259 yield* runShellEnvironment({
260 env,
261 platform: "linux",
262 userShell: "/usr/local/bin/fish",
263 handler: (command) => {
264 if (command._tag !== "StandardCommand") return "";
265 commands.push(command.command);
266 return command.command === "/usr/local/bin/fish"
267 ? envOutput({ PATH: "/home/test/.local/bin:/usr/bin" })
268 : "";
269 },
270 });
271​
272 assert.deepEqual(commands, ["/bin/missing", "/usr/local/bin/fish"]);
273 assert.equal(env.PATH, "/home/test/.local/bin:/usr/bin");
274 }),
275 );
276​
277 it.effect("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () =>
278 Effect.gen(function* () {
279 const env: NodeJS.ProcessEnv = {
280 SHELL: "/bin/zsh",
281 PATH: "/Users/test/.local/bin:/usr/bin",
282 };
283 const commands: ChildProcess.Command[] = [];
284​
285 yield* runShellEnvironment({
286 env,
287 platform: "darwin",
288 handler: (command) => {
289 commands.push(command);
290 return envOutput({
291 PATH: "/opt/homebrew/bin:/usr/bin",
292 SSH_AUTH_SOCK: "/tmp/secretive.sock",
293 HOMEBREW_PREFIX: "/opt/homebrew",
294 });
295 },
296 });
297​
298 assert.equal(commands.length, 1);
299 assert.equal(commands[0]?._tag === "StandardCommand" ? commands[0].command : "", "/bin/zsh");
300 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
301 assert.equal(env.SSH_AUTH_SOCK, "/tmp/secretive.sock");
302 assert.equal(env.HOMEBREW_PREFIX, "/opt/homebrew");
303 }),
304 );
305​
306 it.effect("preserves inherited POSIX values when present", () =>
307 Effect.gen(function* () {
308 const env: NodeJS.ProcessEnv = {
309 SHELL: "/bin/zsh",
310 PATH: "/usr/bin",
311 SSH_AUTH_SOCK: "/tmp/inherited.sock",
312 };
313​
314 yield* runShellEnvironment({
315 env,
316 platform: "darwin",
317 handler: () =>
318 envOutput({
319 PATH: "/opt/homebrew/bin:/usr/bin",
320 SSH_AUTH_SOCK: "/tmp/login-shell.sock",
321 }),
322 });
323​
324 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin");
325 assert.equal(env.SSH_AUTH_SOCK, "/tmp/inherited.sock");
326 }),
327 );
328​
329 it.effect("hydrates the locale from the login shell on macOS", () =>
330 Effect.gen(function* () {
331 const env: NodeJS.ProcessEnv = {
332 SHELL: "/bin/zsh",
333 PATH: "/usr/bin",
334 };
335​
336 yield* runShellEnvironment({
337 env,
338 platform: "darwin",
339 handler: () =>
340 envOutput({
341 PATH: "/opt/homebrew/bin:/usr/bin",
342 LANG: "de_DE.UTF-8",
343 }),
344 });
345​
346 assert.equal(env.LANG, "de_DE.UTF-8");
347 }),
348 );
349​
350 it.effect("preserves an inherited locale over the login shell on macOS", () =>
351 Effect.gen(function* () {
352 const env: NodeJS.ProcessEnv = {
353 SHELL: "/bin/zsh",
354 PATH: "/usr/bin",
355 LANG: "en_US.UTF-8",
356 };
357​
358 yield* runShellEnvironment({
359 env,
360 platform: "darwin",
361 handler: () =>
362 envOutput({
363 PATH: "/opt/homebrew/bin:/usr/bin",
364 LANG: "de_DE.UTF-8",
365 }),
366 });
367​
368 assert.equal(env.LANG, "en_US.UTF-8");
369 }),
370 );
371​
372 it.effect("does not mix login-shell locale categories into an inherited locale", () =>
373 Effect.gen(function* () {
374 const env: NodeJS.ProcessEnv = {
375 SHELL: "/bin/zsh",
376 PATH: "/usr/bin",
377 LANG: "en_US.UTF-8",
378 };
379​
380 yield* runShellEnvironment({
381 env,
382 platform: "darwin",
383 handler: () =>
384 envOutput({
385 PATH: "/opt/homebrew/bin:/usr/bin",
386 LC_ALL: "de_DE.UTF-8",
387 }),
388 });
389​
390 assert.equal(env.LANG, "en_US.UTF-8");
391 assert.equal(env.LC_ALL, undefined);
392 }),
393 );
394​
395 it.effect("falls back to a UTF-8 LC_CTYPE when no locale is available on macOS", () =>
396 Effect.gen(function* () {
397 const env: NodeJS.ProcessEnv = {
398 SHELL: "/bin/zsh",
399 PATH: "/usr/bin",
400 };
401​
402 yield* runShellEnvironment({
403 env,
404 platform: "darwin",
405 handler: () => envOutput({ PATH: "/opt/homebrew/bin:/usr/bin" }),
406 });
407​
408 assert.equal(env.LANG, undefined);
409 assert.equal(env.LC_ALL, undefined);
410 assert.equal(env.LC_CTYPE, "en_US.UTF-8");
411 }),
412 );
413​
414 it.effect("does not apply the locale fallback on linux", () =>
415 Effect.gen(function* () {
416 const env: NodeJS.ProcessEnv = {
417 SHELL: "/bin/zsh",
418 PATH: "/usr/bin",
419 };
420​
421 yield* runShellEnvironment({
422 env,
423 platform: "linux",
424 handler: () => envOutput({ PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin" }),
425 });
426​
427 assert.equal(env.LANG, undefined);
428 }),
429 );
430​
431 it.effect("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () =>
432 Effect.gen(function* () {
433 const env: NodeJS.ProcessEnv = {
434 SHELL: "/bin/zsh",
435 PATH: "/usr/bin",
436 };
437​
438 yield* runShellEnvironment({
439 env,
440 platform: "linux",
441 handler: () =>
442 envOutput({
443 PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
444 SSH_AUTH_SOCK: "/tmp/secretive.sock",
445 T3CODE_TELEMETRY_ENABLED: "false",
446 }),
447 });
448​
449 assert.equal(env.PATH, "/home/linuxbrew/.linuxbrew/bin:/usr/bin");
450 assert.equal(env.SSH_AUTH_SOCK, "/tmp/secretive.sock");
451 assert.equal(env.T3CODE_TELEMETRY_ENABLED, "false");
452 }),
453 );
454​
455 it.effect("hydrates missing CA trust variables from the login shell", () =>
456 Effect.gen(function* () {
457 const env: NodeJS.ProcessEnv = {
458 SHELL: "/bin/zsh",
459 PATH: "/usr/bin",
460 SSL_CERT_DIR: "/etc/ssl/certs",
461 };
462​
463 yield* runShellEnvironment({
464 env,
465 platform: "darwin",
466 handler: () =>
467 envOutput({
468 PATH: "/opt/zerobrew/bin:/usr/bin",
469 SSL_CERT_FILE: "/opt/zerobrew/etc/ca-certificates/cacert.pem",
470 SSL_CERT_DIR: "/opt/zerobrew/etc/ca-certificates",
471 NODE_EXTRA_CA_CERTS: "/Users/me/corp-root.pem",
472 }),
473 });
474​
475 assert.equal(env.SSL_CERT_FILE, "/opt/zerobrew/etc/ca-certificates/cacert.pem");
476 assert.equal(env.SSL_CERT_DIR, "/etc/ssl/certs");
477 assert.equal(env.NODE_EXTRA_CA_CERTS, "/Users/me/corp-root.pem");
478 }),
479 );
480​
481 it.effect("keeps mise's PATH record with the login shell PATH", () =>
482 Effect.gen(function* () {
483 const env: NodeJS.ProcessEnv = {
484 SHELL: "/bin/bash",
485 PATH: "/usr/bin",
486 };
487​
488 yield* runShellEnvironment({
489 env,
490 platform: "linux",
491 handler: () =>
492 envOutput({
493 PATH: "/home/me/.local/bin:/mise/installs/claude/latest:/mise/shims",
494 __MISE_DIFF: "mise-diff",
495 }),
496 });
497​
498 assert.equal(env.__MISE_DIFF, "mise-diff");
499 }),
500 );
501​
502 it.effect("falls back to launchctl PATH on macOS when shell probing does not return one", () =>
503 Effect.gen(function* () {
504 const env: NodeJS.ProcessEnv = {
505 SHELL: "/opt/homebrew/bin/nu",
506 PATH: "/usr/bin",
507 };
508 const commands: string[] = [];
509​
510 yield* runShellEnvironment({
511 env,
512 platform: "darwin",
513 handler: (command) => {
514 if (command._tag !== "StandardCommand") return "";
515 commands.push(command.command);
516 return command.command === "/bin/launchctl" ? "/opt/homebrew/bin:/usr/bin" : "";
517 },
518 });
519​
520 assert.deepEqual(commands, ["/opt/homebrew/bin/nu", "/bin/zsh", "/bin/launchctl"]);
521 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin");
522 }),
523 );
524​
525 it.effect("loads PowerShell profile environment on Windows", () =>
526 Effect.gen(function* () {
527 const env: NodeJS.ProcessEnv = {
528 PATH: "C:\\Windows\\System32",
529 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
530 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
531 USERPROFILE: "C:\\Users\\testuser",
532 };
533​
534 const prepared = yield* runShellEnvironment({
535 env,
536 platform: "win32",
537 handler: (command) => {
538 if (command._tag !== "StandardCommand") return "";
539 const loadProfile = !command.args.includes("-NoProfile");
540 return loadProfile
541 ? envOutput({
542 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
543 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
544 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
545 })
546 : envOutput({ PATH: 'C:\\Custom\\Bin;C:";C:\\Windows\\System32' });
547 },
548 });
549​
550 assert.isTrue(prepared);
551 assert.equal(
552 env.PATH,
553 [
554 "C:\\Profile\\Node",
555 "C:\\Windows\\System32",
556 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
557 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
558 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
559 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
560 "C:\\Users\\testuser\\.local\\bin",
561 "C:\\Users\\testuser\\.bun\\bin",
562 "C:\\Users\\testuser\\scoop\\shims",
563 "C:\\Custom\\Bin",
564 "C:",
565 ].join(";"),
566 );
567 assert.equal(env.FNM_DIR, "C:\\Users\\testuser\\AppData\\Roaming\\fnm");
568 assert.equal(
569 env.FNM_MULTISHELL_PATH,
570 "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
571 );
572 }),
573 );
574​
575 it.effect("waits at most 5 seconds in total when the PowerShell profile hangs", () =>
576 Effect.gen(function* () {
577 const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows\\System32" };
578 const profileShells: string[] = [];
579 const started = yield* Deferred.make<void>();
580 const completed = yield* Deferred.make<void>();
581 const baseClock = yield* Clock.Clock;
582 let wallTime = 0;
583 const clockWithBackwardWallJump: Clock.Clock = {
584 ...baseClock,
585 currentTimeMillisUnsafe: () => wallTime,
586 currentTimeMillis: Effect.sync(() => wallTime),
587 };
588​
589 const install = yield* Effect.forkChild(
590 runShellEnvironment({
591 env,
592 platform: "win32",
593 handler: (command) => {
594 if (command._tag !== "StandardCommand") return "";
595 if (command.args.includes("-NoProfile")) {
596 return envOutput({ PATH: "C:\\NoProfile\\Bin;C:\\Windows\\System32" });
597 }
598 profileShells.push(command.command);
599 return Deferred.succeed(started, undefined).pipe(
600 Effect.as(
601 ChildProcessSpawner.makeHandle({
602 ...makeProcess(""),
603 stdout: Stream.never,
604 all: Stream.never,
605 exitCode: Effect.never,
606 isRunning: Effect.succeed(true),
607 }),
608 ),
609 );
610 },
611 }).pipe(
612 Effect.tap(() => Deferred.succeed(completed, undefined)),
613 Effect.provide(Logger.layer([])),
614 Effect.provideService(Clock.Clock, clockWithBackwardWallJump),
615 ),
616 );
617 yield* Deferred.await(started);
618 wallTime = -60_000;
619 yield* TestClock.adjust("5 seconds");
620 assert.isTrue(yield* Deferred.isDone(completed), "finishes within the shared budget");
621 assert.isFalse(yield* Fiber.join(install));
622 assert.deepEqual(profileShells, ["pwsh.exe"]);
623 assert.equal(env.PATH, "C:\\NoProfile\\Bin;C:\\Windows\\System32");
624 }),
625 );
626​
627 it.effect("falls back to Windows PowerShell when pwsh.exe is not installed", () =>
628 Effect.gen(function* () {
629 const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows\\System32" };
630 const missing = PlatformError.systemError({
631 _tag: "NotFound",
632 module: "ChildProcess",
633 method: "spawn",
634 pathOrDescriptor: "pwsh.exe",
635 });
636​
637 const prepared = yield* runShellEnvironment({
638 env,
639 platform: "win32",
640 handler: (command) => {
641 if (command._tag !== "StandardCommand") return "";
642 if (command.command === "pwsh.exe") return Effect.fail(missing);
643 return command.args.includes("-NoProfile")
644 ? envOutput({ PATH: "C:\\Windows\\System32" })
645 : envOutput({ PATH: "C:\\Profile\\Node;C:\\Windows\\System32" });
646 },
647 }).pipe(Effect.provide(Logger.layer([])));
648​
649 assert.isTrue(prepared);
650 assert.equal(env.PATH, "C:\\Profile\\Node;C:\\Windows\\System32");
651 }),
652 );
653​
654 it.effect.each([false, true])(
655 "leaves Windows preparation incomplete when loadProfile=%s fails",
656 (loadProfile) =>
657 Effect.gen(function* () {
658 const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows\\System32" };
659 let calls = 0;
660 const prepared = yield* runShellEnvironment({
661 env,
662 platform: "win32",
663 handler: (command) => {
664 calls++;
665 if (command._tag !== "StandardCommand") return "";
666 return !command.args.includes("-NoProfile") === loadProfile
667 ? { output: "", exitCode: 1 }
668 : envOutput({ PATH: "C:\\Working" });
669 },
670 }).pipe(Effect.provide(Logger.layer([])));
671 assert.isFalse(prepared);
672 assert.equal(calls, 3);
673 assert.include(env.PATH, "C:\\Working");
674 assert.include(env.PATH, "C:\\Windows\\System32");
675 }),
676 );
677​
678 it.effect("replaces a Path-spelled Windows PATH instead of adding a second key", () =>
679 Effect.gen(function* () {
680 const env: NodeJS.ProcessEnv = { Path: "C:\\Windows\\System32" };
681​
682 yield* runShellEnvironment({
683 env,
684 platform: "win32",
685 handler: (command) =>
686 command._tag === "StandardCommand" && command.args.includes("-NoProfile")
687 ? envOutput({ PATH: "C:\\Shell\\Bin" })
688 : "",
689 });
690​
691 assert.deepEqual(env, { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" });
692 }),
693 );
694​
695 it.effect("drops earlier AppImage launches' mount dirs from the search paths on linux", () =>
696 Effect.gen(function* () {
697 const current = "/var/tmp/.mount_cur";
698 const env: NodeJS.ProcessEnv = {
699 SHELL: "/bin/zsh",
700 APPIMAGE: "/home/me/T3-Code.AppImage",
701 APPDIR: `${current}/`,
702 PATH: `${current}/usr/bin:/tmp/.mount_old/usr/bin:/usr/bin`,
703 LD_LIBRARY_PATH: `/tmp/.mount_old/usr/lib:${current}/usr/lib::/opt/lib`,
704 XDG_DATA_DIRS: "/tmp/.mount_old/usr/share:/var/tmp/.mount_cur2/usr/share",
705 };
706​
707 yield* runShellEnvironment({
708 env,
709 platform: "linux",
710 handler: () => envOutput({ PATH: "/tmp/.mount_older/usr/bin:/home/me/.local/bin" }),
711 });
712​
713 assert.equal(env.PATH, `/home/me/.local/bin:${current}/usr/bin:/usr/bin`);
714 assert.equal(env.LD_LIBRARY_PATH, `${current}/usr/lib::/opt/lib`);
715 assert.equal(env.XDG_DATA_DIRS, undefined);
716 }),
717 );
718​
719 it.effect("keeps AppImage-looking search paths outside an AppImage launch", () =>
720 Effect.gen(function* () {
721 const env: NodeJS.ProcessEnv = {
722 SHELL: "/bin/zsh",
723 PATH: "/tmp/.mount_old/usr/bin:/usr/bin",
724 LD_LIBRARY_PATH: "/tmp/.mount_old/usr/lib",
725 };
726​
727 yield* runShellEnvironment({
728 env,
729 platform: "linux",
730 handler: () => envOutput({ PATH: "/usr/bin" }),
731 });
732​
733 assert.equal(env.PATH, "/usr/bin:/tmp/.mount_old/usr/bin");
734 assert.equal(env.LD_LIBRARY_PATH, "/tmp/.mount_old/usr/lib");
735 }),
736 );
737​
738 it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
739 Effect.gen(function* () {
740 const env: NodeJS.ProcessEnv = {
741 SHELL: "/bin/zsh",
742 PATH: "/usr/bin",
743 XDG_CURRENT_DESKTOP: "wrong-launcher",
744 XDG_SESSION_DESKTOP: "wrong-launcher",
745 };
746​
747 yield* runShellEnvironment({
748 env,
749 platform: "linux",
750 handler: () =>
751 envOutput({
752 PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
753 XDG_CURRENT_DESKTOP: "KDE",
754 XDG_SESSION_DESKTOP: "KDE",
755 XDG_SESSION_TYPE: "wayland",
756 }),
757 });
758​
759 assert.equal(env.XDG_CURRENT_DESKTOP, "KDE");
760 assert.equal(env.XDG_SESSION_DESKTOP, "KDE");
761 assert.equal(env.XDG_SESSION_TYPE, "wayland");
762 }),
763 );
764​
765 it.effect("overrides stale dbus session addresses from the login shell", () =>
766 Effect.gen(function* () {
767 const env: NodeJS.ProcessEnv = {
768 SHELL: "/bin/zsh",
769 PATH: "/usr/bin",
770 DBUS_SESSION_BUS_ADDRESS: "unix:path=/tmp/stale-bus",
771 };
772​
773 yield* runShellEnvironment({
774 env,
775 platform: "linux",
776 handler: () =>
777 envOutput({
778 PATH: "/usr/bin",
779 DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus",
780 }),
781 });
782​
783 assert.equal(env.DBUS_SESSION_BUS_ADDRESS, "unix:path=/run/user/1000/bus");
784 }),
785 );
786​
787 it.effect("logs command failures with safe probe context and the exact cause", () => {
788 const env: NodeJS.ProcessEnv = {
789 SHELL: "/bin/bash",
790 PATH: "/usr/bin",
791 };
792 const cause = PlatformError.systemError({
793 _tag: "PermissionDenied",
794 module: "ChildProcess",
795 method: "spawn",
796 pathOrDescriptor: "/bin/bash",
797 });
798 const messages: Array<unknown> = [];
799 const logger = Logger.make(({ message }) => {
800 messages.push(message);
801 });
802​
803 return runShellEnvironment({
804 env,
805 platform: "linux",
806 handler: () => "",
807 failure: cause,
808 }).pipe(
809 Effect.andThen(
810 Effect.sync(() => {
811 const errors = messages
812 .flatMap((message) => (Array.isArray(message) ? message : [message]))
813 .filter(isDesktopShellEnvironmentCommandError);
814 assert.lengthOf(errors, 1);
815 assert.equal(errors[0]?.probe, "login-shell");
816 assert.equal(errors[0]?.executable, "bash");
817 assert.equal(errors[0]?.argumentCount, 2);
818 assert.notProperty(errors[0] ?? {}, "args");
819 assert.equal(errors[0]?.cause, cause);
820 assert.notInclude(errors[0]?.message ?? "", cause.message);
821 }),
822 ),
823 Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
824 );
825 });
826});