Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- The synchronous shell probe runs real commands with isolated config files.
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { it as effectIt } from "@effect/vitest";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import { DesktopHostTelemetryMessage } from "@t3tools/contracts";
6import * as Schema from "effect/Schema";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as FileSystem from "effect/FileSystem";
10import * as Path from "effect/Path";
11import * as Option from "effect/Option";
12import * as TestClock from "effect/testing/TestClock";
13import * as NodeChildProcess from "node:child_process";
14import * as NodeFS from "node:fs";
15import * as NodeOS from "node:os";
16import * as NodePath from "node:path";
17import { describe, expect, it, vi } from "vite-plus/test";
18
19import {
20 applyShellEnvironment,
21 pathSetup,
22 pathSetupCommand,
23 CommandAvailability,
24 CommandResolutionCache,
25 type CommandAvailabilityChecker,
26 isCommandAvailable,
27 listLoginShellCandidates,
28 mergePathEntries,
29 mergePathValues,
30 npmShimExecutable,
31 preferGitForWindowsBinary,
32 readEnvironmentFromLoginShell,
33 readEnvironmentFromWindowsShell,
34 resolveCommandPath,
35 resolveSpawnCommand,
36 resolveWindowsEnvironment,
37 runsGitWithoutConsole,
38 windowsEnvironmentValueCommand,
39 SpawnExecutableResolution,
40 WindowsShellEnvironment,
41 withPathDirectoryListings,
42 type WindowsShellEnvironmentReader,
43 XcodeGitLocation,
44} from "./shell.ts";
45
46const decodeDesktopHostMessage = Schema.decodeUnknownSync(DesktopHostTelemetryMessage);
47
48const nativeProbe = vi.hoisted(() => ({
49 execFile: vi.fn<typeof import("node:child_process").execFile>(),
50 original: undefined as unknown as typeof import("node:child_process").execFile,
51}));
52
53vi.mock("node:child_process", async (importOriginal) => {
54 const original = await importOriginal<typeof import("node:child_process")>();
55 nativeProbe.original = original.execFile;
56 return { ...original, execFile: nativeProbe.execFile.mockImplementation(original.execFile) };
57});
58
59const withWindowsEnvironmentMocks = <A, E, R>(
60 effect: Effect.Effect<A, E, R>,
61 readEnvironment: (
62 ...args: Parameters<WindowsShellEnvironmentReader>
63 ) => Partial<Record<string, string>>,
64 commandAvailable: CommandAvailabilityChecker,
65) =>
66 effect.pipe(
67 Effect.provideService(WindowsShellEnvironment, (...args) =>
68 Effect.sync(() => readEnvironment(...args)),
69 ),
70 Effect.provideService(CommandAvailability, commandAvailable),
71 );
72
73describe("readEnvironmentFromLoginShell", () => {
74 // Opt in with an explicit binary, like the provider live probes; CI need not install Nu.
75 it.runIf(process.env.T3_TEST_NU_PATH !== undefined)(
76 "captures Nushell PATH and multiline values without external tools",
77 () => {
78 const shell = process.env.T3_TEST_NU_PATH!;
79 const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-nu-env-"));
80 try {
81 const toolPath = NodePath.join(home, "nu tools", "bin");
82 const extraToolPath = NodePath.join(home, "extra-tools", "bin");
83 NodeFS.mkdirSync(toolPath, { recursive: true });
84 NodeFS.mkdirSync(extraToolPath, { recursive: true });
85 const config = NodePath.join(home, "config.nu");
86 const envConfig = NodePath.join(home, "env.nu");
87 NodeFS.writeFileSync(envConfig, "");
88 NodeFS.writeFileSync(
89 config,
90 [
91 `$env.PATH = [${JSON.stringify(toolPath)}, "~/extra-tools/bin", "rel/dir", ""]`,
92 '$env.CUSTOM_VAR = " first\\nsecond "',
93 '$env.EMPTY_VAR = ""',
94 'print "startup noise"',
95 ].join("\n"),
96 );
97
98 expect(
99 readEnvironmentFromLoginShell(
100 shell,
101 ["MISSING_VAR", "PATH", "EMPTY_VAR", "CUSTOM_VAR"],
102 (file, args, options) =>
103 NodeChildProcess.execFileSync(
104 file,
105 ["--no-history", "--config", config, "--env-config", envConfig, ...args],
106 {
107 ...options,
108 env: { HOME: home, XDG_CONFIG_HOME: home, PATH: toolPath },
109 },
110 ),
111 ),
112 ).toEqual({
113 PATH: `${toolPath}:${extraToolPath}:rel/dir:`,
114 CUSTOM_VAR: " first\nsecond ",
115 });
116 } finally {
117 NodeFS.rmSync(home, { recursive: true, force: true });
118 }
119 },
120 );
121
122 it.runIf(NodeFS.existsSync("/bin/bash"))(
123 "captures values when the profile replaces PATH and a DEBUG trap echoes commands",
124 () => {
125 const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-bash-env-"));
126 try {
127 const tools = NodePath.join(home, "tools 'quoted $dir");
128 NodeFS.mkdirSync(tools);
129 const printenv = NodeChildProcess.execFileSync("/bin/bash", ["-c", "type -P printenv"], {
130 encoding: "utf8",
131 env: { PATH: process.env.PATH },
132 }).trim();
133 NodeFS.copyFileSync(printenv, NodePath.join(tools, "printenv"));
134 vi.stubEnv("PATH", tools);
135 const shellPath = NodePath.join(home, "bin");
136 const bashEnv = NodePath.join(home, "env.bash");
137 NodeFS.writeFileSync(
138 bashEnv,
139 [
140 `export PATH='${shellPath.replaceAll("'", "'\\''")}'`,
141 // Simulate a non-FHS host while retaining the real executable in its private prefix.
142 "function /usr/bin/printenv { return 127; }",
143 `trap 'echo -ne "\\033]0;\${BASH_COMMAND}\\007"' DEBUG`,
144 ].join("\n"),
145 );
146
147 expect(
148 readEnvironmentFromLoginShell(
149 "/bin/bash",
150 ["XDG_DATA_HOME", "PATH"],
151 // Non-interactive bash reads only BASH_ENV, not the host's /etc startup files that -il runs.
152 (file, [, command = ""], options) =>
153 NodeChildProcess.execFileSync(file, ["-c", command], {
154 ...options,
155 env: { HOME: home, PATH: tools, TERM: "dumb", BASH_ENV: bashEnv },
156 }),
157 ),
158 ).toEqual({ PATH: shellPath });
159 } finally {
160 vi.unstubAllEnvs();
161 NodeFS.rmSync(home, { recursive: true, force: true });
162 }
163 },
164 );
165
166 it("extracts multiple environment variables from a login shell command", () => {
167 const execFile = vi.fn<
168 (
169 file: string,
170 args: ReadonlyArray<string>,
171 options: { encoding: "utf8"; timeout: number },
172 ) => string
173 >(() =>
174 [
175 "__T3CODE_ENV_PATH_START__",
176 "/a:/b",
177 "__T3CODE_ENV_PATH_END__",
178 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
179 "/tmp/secretive.sock",
180 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
181 ].join("\n"),
182 );
183
184 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
185 PATH: "/a:/b",
186 SSH_AUTH_SOCK: "/tmp/secretive.sock",
187 });
188 expect(execFile).toHaveBeenCalledTimes(1);
189 expect(execFile).toHaveBeenCalledWith("/bin/zsh", expect.any(Array), {
190 encoding: "utf8",
191 timeout: 5000,
192 killSignal: "SIGKILL",
193 detached: true,
194 stdio: ["ignore", "pipe", "ignore"],
195 });
196 });
197
198 it("omits environment variables that are missing or empty", () => {
199 const execFile = vi.fn<
200 (
201 file: string,
202 args: ReadonlyArray<string>,
203 options: { encoding: "utf8"; timeout: number },
204 ) => string
205 >(() =>
206 [
207 "__T3CODE_ENV_PATH_START__",
208 "/a:/b",
209 "__T3CODE_ENV_PATH_END__",
210 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
211 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
212 ].join("\n"),
213 );
214
215 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
216 PATH: "/a:/b",
217 });
218 });
219
220 it("preserves multiline values and surrounding whitespace", () => {
221 const execFile = vi.fn<
222 (
223 file: string,
224 args: ReadonlyArray<string>,
225 options: { encoding: "utf8"; timeout: number },
226 ) => string
227 >(() =>
228 [
229 "__T3CODE_ENV_CUSTOM_VAR_START__",
230 " first\nsecond ",
231 "__T3CODE_ENV_CUSTOM_VAR_END__",
232 ].join("\n"),
233 );
234
235 expect(readEnvironmentFromLoginShell("/bin/zsh", ["CUSTOM_VAR"], execFile)).toEqual({
236 CUSTOM_VAR: " first\nsecond ",
237 });
238 });
239});
240
241describe("listLoginShellCandidates", () => {
242 it("returns env shell, user shell, then the platform fallback without duplicates", () => {
243 expect(listLoginShellCandidates("darwin", " /opt/homebrew/bin/nu ", "/bin/zsh")).toEqual([
244 "/opt/homebrew/bin/nu",
245 "/bin/zsh",
246 ]);
247 });
248});
249
250describe("mergePathEntries", () => {
251 it("prefers login-shell PATH entries and keeps inherited extras", () => {
252 expect(
253 mergePathEntries("/opt/homebrew/bin:/usr/bin", "/Users/test/.local/bin:/usr/bin", "darwin"),
254 ).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
255 expect(mergePathEntries("/opt/bin :/opt/bin", "/opt/bin :/usr/bin", "linux")).toBe(
256 "/opt/bin :/opt/bin:/usr/bin",
257 );
258 });
259});
260
261describe("windowsEnvironmentValueCommand", () => {
262 it("joins PATH as Process, then Machine, then User so prepends win and User installs still appear", () => {
263 const command = windowsEnvironmentValueCommand("PATH");
264 const processAt = command.indexOf("[Environment]::GetEnvironmentVariable('PATH','Process')");
265 const machineAt = command.indexOf("[Environment]::GetEnvironmentVariable('PATH','Machine')");
266 const userAt = command.indexOf("[Environment]::GetEnvironmentVariable('PATH','User')");
267 expect(processAt).toBeGreaterThan(-1);
268 expect(processAt).toBeLessThan(machineAt);
269 expect(machineAt).toBeLessThan(userAt);
270 });
271});
272
273describe("readEnvironmentFromWindowsShell", () => {
274 effectIt.effect("yields while the native shell probe is pending", () =>
275 Effect.gen(function* () {
276 let completed = false;
277 const [environment, completedBeforeProbeReturned] = yield* Effect.all(
278 [
279 readEnvironmentFromWindowsShell(["PATH"]).pipe(
280 Effect.tap(() =>
281 Effect.sync(() => {
282 completed = true;
283 }),
284 ),
285 ),
286 Effect.sync(() => completed),
287 ],
288 { concurrency: 2 },
289 );
290 expect(completedBeforeProbeReturned).toBe(false);
291 expect(environment).toBeTypeOf("object");
292 }),
293 );
294
295 effectIt.layer(NodeServices.layer)("synchronous spawn failures", (it) => {
296 it.effect("tries both shells and preserves baseline PATH repair", () =>
297 Effect.gen(function* () {
298 const execFile = nativeProbe.execFile;
299 execFile.mockImplementationOnce(() => {
300 throw new Error("spawn EPERM");
301 });
302 execFile.mockImplementationOnce(() => {
303 throw new Error("spawn EINVAL");
304 });
305 try {
306 const patch = yield* resolveWindowsEnvironment({
307 PATH: "C:\\Windows",
308 APPDATA: "C:\\Roaming",
309 }).pipe(Effect.provideService(CommandAvailability, () => Effect.succeed(true)));
310 expect(patch).toEqual({ PATH: "C:\\Windows;C:\\Roaming\\npm" });
311 expect(execFile.mock.calls.slice(-2).map(([file]) => file)).toEqual([
312 "pwsh.exe",
313 "powershell.exe",
314 ]);
315 } finally {
316 execFile.mockClear();
317 }
318 }),
319 );
320 });
321
322 effectIt.effect("returns an empty environment after both shell candidates fail", () =>
323 Effect.gen(function* () {
324 const execFile = vi.fn(() => Effect.succeed(Option.none<string>()));
325 expect(yield* readEnvironmentFromWindowsShell(["PATH"], {}, execFile)).toEqual({});
326 expect(execFile).toHaveBeenCalledTimes(2);
327 }),
328 );
329
330 effectIt.effect("does not launch a shell when no variables are requested", () =>
331 Effect.gen(function* () {
332 const execFile = vi.fn(() => Effect.succeed(Option.none<string>()));
333 expect(yield* readEnvironmentFromWindowsShell([], {}, execFile)).toEqual({});
334 expect(execFile).not.toHaveBeenCalled();
335 }),
336 );
337
338 effectIt.effect(
339 "kills the native probe child on interruption without trying the next shell",
340 () =>
341 Effect.gen(function* () {
342 const started = Promise.withResolvers<void>();
343 const kill = vi.fn(() => true);
344 const child = { kill, unref: vi.fn() } as unknown as ReturnType<
345 typeof import("node:child_process").execFile
346 >;
347 const execFile = nativeProbe.execFile;
348 execFile.mockClear();
349 execFile.mockImplementationOnce(() => {
350 started.resolve();
351 return child;
352 });
353 try {
354 const fiber = yield* readEnvironmentFromWindowsShell(["PATH"]).pipe(Effect.forkChild);
355 yield* Effect.promise(() => started.promise);
356 yield* Fiber.interrupt(fiber);
357 expect(kill).toHaveBeenCalledTimes(1);
358 expect(execFile).toHaveBeenCalledTimes(1);
359 expect(execFile.mock.calls[0]?.[0]).toBe("pwsh.exe");
360 } finally {
361 execFile.mockClear();
362 }
363 }),
364 );
365
366 effectIt.effect("gives up on a shell that survives the kill and holds stdout open", () =>
367 Effect.gen(function* () {
368 const stdout = { destroy: vi.fn() };
369 const unref = vi.fn();
370 const child = { kill: vi.fn(() => true), stdout, unref } as unknown as ReturnType<
371 typeof import("node:child_process").execFile
372 >;
373 const execFile = nativeProbe.execFile;
374 execFile.mockClear();
375 execFile.mockImplementation(() => child);
376 try {
377 const fiber = yield* readEnvironmentFromWindowsShell(["PATH"]).pipe(Effect.forkChild);
378 yield* Effect.yieldNow;
379 yield* TestClock.adjust("6 seconds");
380 expect(execFile.mock.calls.map(([file]) => file)).toEqual(["pwsh.exe", "powershell.exe"]);
381 yield* TestClock.adjust("6 seconds");
382 expect(yield* Fiber.join(fiber)).toEqual({});
383 expect(stdout.destroy).toHaveBeenCalledTimes(2);
384 expect(unref).toHaveBeenCalledTimes(2);
385 } finally {
386 execFile.mockReset();
387 execFile.mockImplementation(nativeProbe.original);
388 }
389 }),
390 );
391
392 effectIt.effect("extracts environment variables from a PowerShell command", () =>
393 Effect.gen(function* () {
394 const execFile = vi.fn<
395 (
396 file: string,
397 args: ReadonlyArray<string>,
398 options: { encoding: "utf8"; timeout: number },
399 ) => string
400 >(
401 () =>
402 "__T3CODE_ENV_PATH_START__\nC:\\Users\\testuser\\AppData\\Roaming\\npm\n__T3CODE_ENV_PATH_END__\n",
403 );
404
405 expect(
406 yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) =>
407 Effect.sync(() => Option.liftThrowable(execFile)(...args)),
408 ),
409 ).toEqual({
410 PATH: "C:\\Users\\testuser\\AppData\\Roaming\\npm",
411 });
412 expect(execFile).toHaveBeenCalledWith(
413 "pwsh.exe",
414 expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]),
415 { encoding: "utf8", timeout: 5000 },
416 );
417 }),
418 );
419
420 effectIt.effect("strips CRLF delimiters from captured PowerShell values", () =>
421 Effect.gen(function* () {
422 const execFile = vi.fn<
423 (
424 file: string,
425 args: ReadonlyArray<string>,
426 options: { encoding: "utf8"; timeout: number },
427 ) => string
428 >(
429 () =>
430 "__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
431 );
432
433 expect(
434 yield* readEnvironmentFromWindowsShell(["FNM_DIR"], {}, (...args) =>
435 Effect.sync(() => Option.liftThrowable(execFile)(...args)),
436 ),
437 ).toEqual({
438 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
439 });
440 }),
441 );
442
443 effectIt.effect("omits -NoProfile when loadProfile is enabled", () =>
444 Effect.gen(function* () {
445 const execFile = vi.fn<
446 (
447 file: string,
448 args: ReadonlyArray<string>,
449 options: { encoding: "utf8"; timeout: number },
450 ) => string
451 >(() => "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n");
452
453 expect(
454 yield* readEnvironmentFromWindowsShell(["PATH"], { loadProfile: true }, (...args) =>
455 Effect.sync(() => Option.liftThrowable(execFile)(...args)),
456 ),
457 ).toEqual({
458 PATH: "C:\\Tools",
459 });
460 expect(execFile).toHaveBeenCalledWith(
461 "pwsh.exe",
462 expect.arrayContaining(["-NoLogo", "-NonInteractive", "-Command"]),
463 { encoding: "utf8", timeout: 5000 },
464 );
465 expect(execFile.mock.calls[0]?.[1]).not.toContain("-NoProfile");
466 }),
467 );
468
469 effectIt.effect("falls back to Windows PowerShell when pwsh.exe is unavailable", () =>
470 Effect.gen(function* () {
471 const execFile = vi.fn<
472 (
473 file: string,
474 args: ReadonlyArray<string>,
475 options: { encoding: "utf8"; timeout: number },
476 ) => string
477 >((file) => {
478 if (file === "pwsh.exe") {
479 throw new Error("spawn pwsh.exe ENOENT");
480 }
481 return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
482 });
483
484 expect(
485 yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) =>
486 Effect.sync(() => Option.liftThrowable(execFile)(...args)),
487 ),
488 ).toEqual({
489 PATH: "C:\\Tools",
490 });
491 expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
492 encoding: "utf8",
493 timeout: 5000,
494 });
495 expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
496 encoding: "utf8",
497 timeout: 5000,
498 });
499 }),
500 );
501});
502
503describe("mergePathValues", () => {
504 it("sanitizes and dedupes Windows entries while preserving preferred order", () => {
505 expect(
506 mergePathValues(
507 'C:\\Users\\testuser\\AppData\\Roaming\\npm;"C:\\Program Files\\nodejs"',
508 "c:\\users\\testuser\\appdata\\roaming\\npm;C:\\Windows\\System32",
509 "win32",
510 ),
511 ).toBe(
512 "C:\\Users\\testuser\\AppData\\Roaming\\npm;C:\\Program Files\\nodejs;C:\\Windows\\System32",
513 );
514 });
515
516 it("removes stray quotes from Windows entries", () => {
517 expect(
518 mergePathValues(
519 'C:\\Windows\\System32;C:\\cloudflared.exe;C:";C:\\Program Files\\nodejs',
520 undefined,
521 "win32",
522 ),
523 ).toBe("C:\\Windows\\System32;C:\\cloudflared.exe;C:;C:\\Program Files\\nodejs");
524 });
525
526 it("dedupes case-sensitively on POSIX", () => {
527 expect(mergePathValues("/usr/local/bin:/usr/bin", "/usr/bin:/USR/BIN", "linux")).toBe(
528 "/usr/local/bin:/usr/bin:/USR/BIN",
529 );
530 expect(mergePathValues("/opt/bin :/opt/bin", "/opt/bin :/usr/bin", "linux")).toBe(
531 "/opt/bin :/opt/bin:/usr/bin",
532 );
533 expect(mergePathValues('/opt/bin"', "/opt/bin", "linux")).toBe('/opt/bin":/opt/bin');
534 });
535});
536
537effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => {
538 // Windows rejects `"` in file names.
539 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
540 "finds executables in a POSIX PATH directory ending in whitespace and quotes",
541 () =>
542 Effect.gen(function* () {
543 const fs = yield* FileSystem.FileSystem;
544 const path = yield* Path.Path;
545 const cwd = yield* fs.makeTempDirectoryScoped({ directory: ".", prefix: "t3-path-" });
546 const directory = `${cwd}/bin \u00a0"`;
547 yield* fs.makeDirectory(directory);
548 const executable = `${directory}/audit-command`;
549 yield* fs.writeFileString(executable, "#!/bin/sh\n");
550 yield* fs.chmod(executable, 0o755);
551 const env = { PATH: directory };
552
553 expect(
554 yield* resolveCommandPath("audit-command", { env }).pipe(
555 Effect.provideService(HostProcess.Platform, "linux"),
556 Effect.provideService(CommandResolutionCache, new Map()),
557 ),
558 ).toBe(path.join(directory, "audit-command"));
559 const resolveExecutable = yield* SpawnExecutableResolution;
560 expect(resolveExecutable("audit-command", "linux", env)).toBe(executable);
561 }),
562 );
563
564 const recordProbes = (env: NodeJS.ProcessEnv) =>
565 Effect.gen(function* () {
566 const probed: Array<string> = [];
567 const result = yield* resolveCommandPath("definitely-not-installed", { env }).pipe(
568 Effect.provideService(HostProcess.Platform, "win32"),
569 Effect.provideService(CommandResolutionCache, new Map()),
570 Effect.provide(
571 FileSystem.layerNoop({
572 stat: (filePath) =>
573 Effect.sync(() => {
574 probed.push(filePath);
575 return { type: "Directory" } as FileSystem.File.Info;
576 }),
577 }),
578 ),
579 );
580
581 expect(result).toBeNull();
582 return probed;
583 });
584
585 it.effect("still visits a PATH entry that differs only in case", () =>
586 Effect.gen(function* () {
587 const probed = yield* recordProbes({
588 PATH: "C:\\bin;C:\\BIN",
589 PATHEXT: ".COM;.EXE",
590 });
591
592 // Windows PATH directories can be case-sensitive; preserve both spellings.
593 expect(probed).toHaveLength(8);
594 }),
595 );
596
597 it.effect.each(["audit-command", "audit-command.CMD"])(
598 "resolves lowercase executable files for %s in a case-sensitive Windows PATH directory",
599 (command) =>
600 Effect.gen(function* () {
601 const fs = yield* FileSystem.FileSystem;
602 const path = yield* Path.Path;
603 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-case-sensitive-path-" });
604 const executable = path.join(cwd, "audit-command.cmd");
605 yield* fs.writeFileString(executable, "@echo off\n");
606
607 const decoy = path.join(cwd, "audit-command.exe");
608 yield* fs.writeFileString(decoy, "");
609 for (const key of ["PATHEXT", "PathExt", "pathext"]) {
610 const resolved = yield* resolveCommandPath(command, {
611 env: { PATH: cwd, [key]: ".CMD" },
612 }).pipe(
613 Effect.provideService(HostProcess.Platform, "win32"),
614 Effect.provideService(CommandResolutionCache, new Map()),
615 Effect.provideService(FileSystem.FileSystem, {
616 ...fs,
617 stat: (filePath) =>
618 fs.stat(
619 filePath === executable || filePath === decoy
620 ? filePath
621 : path.join(cwd, "missing"),
622 ),
623 }),
624 );
625 expect(resolved).toBe(executable);
626 }
627 }),
628 );
629
630 it.effect("probes only listed PATH names and relists a directory that changes", () =>
631 Effect.gen(function* () {
632 const fs = yield* FileSystem.FileSystem;
633 const path = yield* Path.Path;
634 const first = yield* fs.makeTempDirectoryScoped();
635 const second = yield* fs.makeTempDirectoryScoped();
636 yield* fs.writeFileString(path.join(first, "cursor.CMD"), "");
637 yield* fs.writeFileString(path.join(second, "cursor.EXE"), "");
638 const env = { PATH: `${first};${second}`, PATHEXT: ".EXE;.CMD" };
639 const probed: Array<string> = [];
640 yield* Effect.gen(function* () {
641 expect(yield* resolveCommandPath("cursor", { env })).toBe(path.join(first, "cursor.CMD"));
642 expect(yield* isCommandAvailable("absent", { env })).toBe(false);
643 yield* fs.writeFileString(path.join(second, "late.EXE"), "");
644 yield* fs.utimes(second, 4_102_444_800, 4_102_444_800);
645 expect(yield* resolveCommandPath("late", { env })).toBe(path.join(second, "late.EXE"));
646 }).pipe(
647 withPathDirectoryListings,
648 Effect.provideService(FileSystem.FileSystem, {
649 ...fs,
650 stat: (file) => {
651 if (file !== first && file !== second) probed.push(file);
652 return fs.stat(file);
653 },
654 }),
655 );
656 expect(probed).toEqual([path.join(first, "cursor.CMD"), path.join(second, "late.EXE")]);
657 }).pipe(
658 Effect.provideService(HostProcess.Platform, "win32"),
659 Effect.provideService(CommandResolutionCache, new Map()),
660 ),
661 );
662});
663
664describe("runsGitWithoutConsole", () => {
665 const git = "C:\\Program Files\\Git\\ucrt64\\bin\\git.exe";
666
667 it.each([
668 [["rev-parse", "--git-path", "index"], true],
669 [["--git-dir", "C:\\repo\\.git", "symbolic-ref", "refs/remotes/origin/HEAD"], true],
670 [["remote", "get-url", "--", "origin"], true],
671 [["config", "--get", "branch.main.pushRemote"], true],
672 [["symbolic-ref", "--quiet", "HEAD"], true],
673 [["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], true],
674 [["rev-parse", "HEAD"], false],
675 [["symbolic-ref", "HEAD", "refs/heads/x"], false],
676 [["symbolic-ref", "-qd", "refs/remotes/origin/HEAD"], false],
677 [["config", "--get", "--edit"], false],
678 [["-c", "core.pager=x", "config", "--get", "user.name"], false],
679 ])("Git for Windows %j without a console: %s", (args, expected) => {
680 expect(runsGitWithoutConsole("win32", git, args)).toBe(expected);
681 });
682
683 it.each([
684 ["win32", "C:\\Program Files\\Git\\cmd\\git.exe"],
685 ["win32", "C:\\Users\\x\\scoop\\shims\\git.exe"],
686 ["linux", git],
687 ] as const)("keeps the console on %s for %s", (platform, executable) => {
688 expect(runsGitWithoutConsole(platform, executable, ["rev-parse", "--show-toplevel"])).toBe(
689 false,
690 );
691 });
692});
693
694describe("preferGitForWindowsBinary", () => {
695 const files =
696 (...paths: Array<string>) =>
697 (filePath: string) =>
698 paths.includes(filePath);
699
700 it("runs the git.exe Git for Windows' launcher would start", () => {
701 expect(
702 preferGitForWindowsBinary(
703 "C:\\Program Files\\Git\\cmd\\git.EXE",
704 {},
705 files(
706 "C:\\Program Files\\Git\\ucrt64\\bin\\git.exe",
707 "C:\\Program Files\\Git\\mingw64\\bin\\git.exe",
708 ),
709 ),
710 ).toBe("C:\\Program Files\\Git\\ucrt64\\bin\\git.exe");
711 expect(
712 preferGitForWindowsBinary(
713 "D:\\PortableGit\\bin\\git.exe",
714 {},
715 files("D:\\PortableGit\\mingw64\\bin\\git.exe"),
716 ),
717 ).toBe("D:\\PortableGit\\mingw64\\bin\\git.exe");
718 expect(
719 preferGitForWindowsBinary(
720 "C:\\Program Files\\Git\\cmd\\git.exe",
721 {},
722 files("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe"),
723 ),
724 ).toBe("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe");
725 });
726
727 it("keeps the launcher when MSYSTEM is set", () => {
728 // git.exe adds hook dependencies to PATH only when MSYSTEM is unset.
729 expect(
730 preferGitForWindowsBinary(
731 "C:\\Program Files\\Git\\cmd\\git.exe",
732 { MSYSTEM: "MINGW64" },
733 files("C:\\Program Files\\Git\\mingw64\\bin\\git.exe"),
734 ),
735 ).toBe("C:\\Program Files\\Git\\cmd\\git.exe");
736 });
737
738 it("leaves other gits and other launchers alone", () => {
739 const everything = () => true;
740 expect(preferGitForWindowsBinary("C:\\Users\\me\\scoop\\shims\\git.exe", {}, everything)).toBe(
741 "C:\\Users\\me\\scoop\\shims\\git.exe",
742 );
743 expect(preferGitForWindowsBinary("C:\\Program Files\\Git\\cmd\\gitk.exe", {}, everything)).toBe(
744 "C:\\Program Files\\Git\\cmd\\gitk.exe",
745 );
746 });
747});
748
749// Byte for byte what `npm install -g opencode-ai` writes as `opencode.cmd`.
750const NPM_OPENCODE_SHIM = [
751 "@ECHO off",
752 "GOTO start",
753 ":find_dp0",
754 "SET dp0=%~dp0",
755 "EXIT /b",
756 ":start",
757 "SETLOCAL",
758 "CALL :find_dp0",
759 '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',
760 "",
761].join("\r\n");
762
763describe("npmShimExecutable", () => {
764 const shimPath = "C:\\Users\\me\\AppData\\Roaming\\npm\\opencode.cmd";
765 const executable =
766 "C:\\Users\\me\\AppData\\Roaming\\npm\\node_modules\\opencode-ai\\bin\\opencode.exe";
767 const exists = (filePath: string) => filePath === executable;
768
769 it("finds the executable npm's shim runs", () => {
770 expect(npmShimExecutable(shimPath, () => NPM_OPENCODE_SHIM, exists)).toBe(executable);
771 expect(
772 npmShimExecutable(shimPath.replace(".cmd", ".CMD"), () => NPM_OPENCODE_SHIM, exists),
773 ).toBe(executable);
774 });
775
776 it("keeps a shim that does more than run the executable", () => {
777 const withSetting = NPM_OPENCODE_SHIM.replace(
778 "SETLOCAL",
779 "SETLOCAL\r\nSET OPENCODE_CONFIG=C:\\x",
780 );
781 expect(npmShimExecutable(shimPath, () => withSetting, exists)).toBeUndefined();
782 const nodeScript = NPM_OPENCODE_SHIM.replace(
783 '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',
784 '"%_prog%" "%dp0%\\node_modules\\opencode-ai\\bin\\opencode.js" %*',
785 );
786 expect(
787 npmShimExecutable(
788 shimPath,
789 () => nodeScript,
790 () => true,
791 ),
792 ).toBeUndefined();
793 });
794
795 it("keeps a shim CMD would read differently", () => {
796 // CMD preserves trailing SET whitespace, changing the executable path.
797 for (const suffix of ["\u00a0", "\t", " "]) {
798 const altered = NPM_OPENCODE_SHIM.replace("SET dp0=%~dp0", `SET dp0=%~dp0${suffix}`);
799 expect(
800 npmShimExecutable(
801 shimPath,
802 () => altered,
803 () => true,
804 ),
805 ).toBeUndefined();
806 }
807 const nonBreakingSeparator = NPM_OPENCODE_SHIM.replace(
808 'opencode.exe" %*',
809 'opencode.exe"\u00a0%*',
810 );
811 expect(
812 npmShimExecutable(
813 shimPath,
814 () => nonBreakingSeparator,
815 () => true,
816 ),
817 ).toBeUndefined();
818 const indented = NPM_OPENCODE_SHIM.replace("SETLOCAL", " SETLOCAL");
819 expect(
820 npmShimExecutable(
821 shimPath,
822 () => indented,
823 () => true,
824 ),
825 ).toBeUndefined();
826 });
827
828 it("keeps the shim when its executable is missing or it is not a .cmd", () => {
829 expect(
830 npmShimExecutable(
831 shimPath,
832 () => NPM_OPENCODE_SHIM,
833 () => false,
834 ),
835 ).toBeUndefined();
836 expect(
837 npmShimExecutable(
838 shimPath,
839 () => undefined,
840 () => true,
841 ),
842 ).toBeUndefined();
843 expect(
844 npmShimExecutable(
845 shimPath.replace(".cmd", ".bat"),
846 () => NPM_OPENCODE_SHIM,
847 () => true,
848 ),
849 ).toBeUndefined();
850 });
851});
852
853effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
854 it.effect("runs Windows executables directly without a shell", () =>
855 Effect.gen(function* () {
856 const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], {
857 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
858 }).pipe(
859 Effect.provideService(HostProcess.Platform, "win32"),
860 Effect.provideService(CommandResolutionCache, new Map()),
861 );
862
863 expect(command).toEqual({
864 command: "node.exe",
865 args: ["script.js", "hello & goodbye"],
866 shell: false,
867 });
868 }),
869 );
870
871 it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
872 "runs the executable behind an npm shim directly when asked",
873 () =>
874 Effect.gen(function* () {
875 const fs = yield* FileSystem.FileSystem;
876 const path = yield* Path.Path;
877 const prefix = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-shim-" });
878 const shim = path.join(prefix, "opencode.cmd");
879 const executable = path.join(prefix, "node_modules", "opencode-ai", "bin", "opencode.exe");
880 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
881 yield* fs.writeFileString(executable, "");
882 yield* fs.writeFileString(shim, NPM_OPENCODE_SHIM);
883 const resolve = (bypassNpmShim: boolean) =>
884 resolveSpawnCommand("opencode", ["serve", "--port=4096"], {
885 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
886 bypassNpmShim,
887 }).pipe(
888 Effect.provideService(HostProcess.Platform, "win32"),
889 Effect.provideService(CommandResolutionCache, new Map()),
890 Effect.provideService(SpawnExecutableResolution, () => shim),
891 );
892
893 expect(yield* resolve(true)).toEqual({
894 command: executable,
895 args: ["serve", "--port=4096"],
896 shell: false,
897 });
898 expect((yield* resolve(false)).shell).toBe(true);
899 }),
900 );
901
902 it.effect("builds one escaped cmd.exe line for Windows command shims", () =>
903 Effect.gen(function* () {
904 const command = yield* resolveSpawnCommand(
905 "vp",
906 [
907 "run",
908 "value & calc",
909 "%PATH%",
910 'quote"value',
911 "C:\\dir with space\\",
912 'slash\\"quote',
913 "x|y<z>^",
914 ],
915 { env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" } },
916 ).pipe(
917 Effect.provideService(HostProcess.Platform, "win32"),
918 Effect.provideService(CommandResolutionCache, new Map()),
919 Effect.provideService(
920 SpawnExecutableResolution,
921 () => "C:\\Program Files\\npm & tools\\vp.cmd",
922 ),
923 );
924
925 // No args alongside `shell: true`: Node prints DEP0190 for that pairing.
926 expect(command).toEqual({
927 command: [
928 String.raw`^"C:\Program^ Files\npm^ ^&^ tools\vp.cmd^"`,
929 String.raw`^"run^"`,
930 String.raw`^"value^ ^&^ calc^"`,
931 String.raw`^"^%PATH^%^"`,
932 String.raw`^"quote\^"value^"`,
933 String.raw`^"C:\dir^ with^ space\\^"`,
934 String.raw`^"slash\\\^"quote^"`,
935 String.raw`^"x^|y^<z^>^^^"`,
936 ].join(" "),
937 args: [],
938 shell: true,
939 });
940 }),
941 );
942
943 it.effect("resolves against the effective environment when extending host env", () =>
944 Effect.gen(function* () {
945 let resolvedEnvironment: NodeJS.ProcessEnv | undefined;
946 yield* resolveSpawnCommand("codex", ["app-server"], {
947 env: { CODEX_HOME: "C:\\Users\\tester\\.codex" },
948 extendEnv: true,
949 }).pipe(
950 Effect.provideService(HostProcess.Platform, "win32"),
951 Effect.provideService(CommandResolutionCache, new Map()),
952 Effect.provideService(HostProcess.Environment, {
953 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
954 PATHEXT: ".COM;.EXE;.BAT;.CMD",
955 }),
956 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) => {
957 resolvedEnvironment = env;
958 return "C:\\Users\\tester\\AppData\\Roaming\\npm\\codex.cmd";
959 }),
960 );
961
962 expect(resolvedEnvironment).toEqual({
963 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
964 PATHEXT: ".COM;.EXE;.BAT;.CMD",
965 CODEX_HOME: "C:\\Users\\tester\\.codex",
966 });
967 }),
968 );
969
970 describe("macOS git", () => {
971 // Files that exist, the git first on PATH, and what `xcrun --find git` prints.
972 const setup = (options: {
973 readonly platform?: NodeJS.Platform;
974 readonly gitOnPath: string;
975 readonly xcrunGit: string | undefined;
976 }) => {
977 const files = new Set([options.gitOnPath, ...(options.xcrunGit ? [options.xcrunGit] : [])]);
978 const host = { xcrunGit: options.xcrunGit, xcrunCalls: 0 };
979 const resolve = resolveSpawnCommand("git", ["status"], { env: { PATH: "/fake/bin" } }).pipe(
980 Effect.map((resolved) => resolved.command),
981 Effect.provideService(HostProcess.Platform, options.platform ?? "darwin"),
982 Effect.provideService(SpawnExecutableResolution, (command) =>
983 command === "git" ? options.gitOnPath : files.has(command) ? command : undefined,
984 ),
985 Effect.provideService(XcodeGitLocation, () => {
986 host.xcrunCalls += 1;
987 return host.xcrunGit;
988 }),
989 );
990 return { files, host, resolve };
991 };
992
993 const XCODE_GIT = "/Applications/Xcode.app/Contents/Developer/usr/bin/git";
994
995 it.effect("runs the git behind the xcrun shim and looks it up once", () =>
996 Effect.gen(function* () {
997 const { host, resolve } = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
998 expect(yield* resolve).toBe(XCODE_GIT);
999 expect(yield* resolve).toBe(XCODE_GIT);
1000 expect(host.xcrunCalls).toBe(1);
1001 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
1002 );
1003
1004 it.effect("keeps git when PATH has another git or the host is not macOS", () =>
1005 Effect.gen(function* () {
1006 const homebrew = setup({ gitOnPath: "/opt/homebrew/bin/git", xcrunGit: XCODE_GIT });
1007 expect(yield* homebrew.resolve).toBe("git");
1008 expect(homebrew.host.xcrunCalls).toBe(0);
1009
1010 const linux = setup({ platform: "linux", gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
1011 expect(yield* linux.resolve).toBe("git");
1012 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
1013 );
1014
1015 it.effect("keeps git when xcrun fails or names a missing file", () =>
1016 Effect.gen(function* () {
1017 const failed = setup({ gitOnPath: "/usr/bin/git", xcrunGit: undefined });
1018 expect(yield* failed.resolve).toBe("git");
1019
1020 const missing = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
1021 missing.files.delete(XCODE_GIT);
1022 expect(yield* missing.resolve).toBe("git");
1023 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
1024 );
1025
1026 it.effect("looks again when the resolved git disappears", () =>
1027 Effect.gen(function* () {
1028 const betaGit = "/Applications/Xcode-beta.app/Contents/Developer/usr/bin/git";
1029 const { files, host, resolve } = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
1030 expect(yield* resolve).toBe(XCODE_GIT);
1031
1032 files.delete(XCODE_GIT);
1033 files.add(betaGit);
1034 host.xcrunGit = betaGit;
1035 expect(yield* resolve).toBe(betaGit);
1036 expect(host.xcrunCalls).toBe(2);
1037 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
1038 );
1039 });
1040
1041 it.effect("does not fall back to a shell for unresolved Windows commands", () =>
1042 Effect.gen(function* () {
1043 const command = yield* resolveSpawnCommand("missing & calc", ["unsafe & value"], {
1044 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
1045 }).pipe(
1046 Effect.provideService(HostProcess.Platform, "win32"),
1047 Effect.provideService(CommandResolutionCache, new Map()),
1048 );
1049
1050 expect(command).toEqual({
1051 command: "missing & calc",
1052 args: ["unsafe & value"],
1053 shell: false,
1054 });
1055 }),
1056 );
1057});
1058
1059effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => {
1060 it.effect("uses known CLI directories as a fallback without changing shell PATH priority", () =>
1061 Effect.gen(function* () {
1062 const readEnvironment = vi.fn(
1063 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
1064 options?.loadProfile
1065 ? { PATH: "C:\\Profile\\Bin" }
1066 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
1067 );
1068 const commandAvailable = vi.fn(() => Effect.succeed(true));
1069
1070 expect(
1071 yield* withWindowsEnvironmentMocks(
1072 resolveWindowsEnvironment({
1073 PATH: "C:\\Windows\\System32",
1074 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
1075 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
1076 USERPROFILE: "C:\\Users\\testuser",
1077 }),
1078 readEnvironment,
1079 commandAvailable,
1080 ),
1081 ).toEqual({
1082 PATH: [
1083 "C:\\Shell\\Bin",
1084 "C:\\Windows\\System32",
1085 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
1086 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
1087 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
1088 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
1089 "C:\\Users\\testuser\\.local\\bin",
1090 "C:\\Users\\testuser\\.bun\\bin",
1091 "C:\\Users\\testuser\\scoop\\shims",
1092 ].join(";"),
1093 });
1094 expect(readEnvironment).toHaveBeenCalledTimes(1);
1095 expect(readEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
1096 expect(commandAvailable).toHaveBeenCalledWith(
1097 "node",
1098 expect.objectContaining({ env: expect.any(Object) }),
1099 );
1100 }),
1101 );
1102
1103 it.effect(
1104 "probes node with one PATH key when inherited environment records have mixed casing",
1105 () =>
1106 Effect.gen(function* () {
1107 const probedEnvironments: Array<NodeJS.ProcessEnv | undefined> = [];
1108
1109 yield* withWindowsEnvironmentMocks(
1110 resolveWindowsEnvironment({ Path: "C:\\Stale", PATH: "C:\\Windows\\System32" }),
1111 () => ({ PATH: "C:\\Shell\\Bin" }),
1112 (_command, options) =>
1113 Effect.sync(() => {
1114 probedEnvironments.push(options?.env);
1115 return true;
1116 }),
1117 );
1118
1119 const pathEntries = Object.entries(probedEnvironments[0] ?? {}).filter(
1120 ([key]) => key.toUpperCase() === "PATH",
1121 );
1122 expect(pathEntries).toEqual([["PATH", "C:\\Shell\\Bin;C:\\Windows\\System32"]]);
1123 }),
1124 );
1125
1126 it.effect("loads the PowerShell profile when baseline env cannot resolve node", () =>
1127 Effect.gen(function* () {
1128 const readEnvironment = vi.fn(
1129 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
1130 options?.loadProfile
1131 ? {
1132 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
1133 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
1134 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
1135 }
1136 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
1137 );
1138 const commandAvailable = vi.fn(() => Effect.succeed(false));
1139
1140 expect(
1141 yield* withWindowsEnvironmentMocks(
1142 resolveWindowsEnvironment({
1143 PATH: "C:\\Windows\\System32",
1144 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
1145 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
1146 USERPROFILE: "C:\\Users\\testuser",
1147 }),
1148 readEnvironment,
1149 commandAvailable,
1150 ),
1151 ).toEqual({
1152 PATH: [
1153 "C:\\Profile\\Node",
1154 "C:\\Windows\\System32",
1155 "C:\\Shell\\Bin",
1156 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
1157 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
1158 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
1159 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
1160 "C:\\Users\\testuser\\.local\\bin",
1161 "C:\\Users\\testuser\\.bun\\bin",
1162 "C:\\Users\\testuser\\scoop\\shims",
1163 ].join(";"),
1164 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
1165 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
1166 });
1167 expect(readEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
1168 expect(readEnvironment).toHaveBeenNthCalledWith(
1169 2,
1170 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
1171 {
1172 loadProfile: true,
1173 },
1174 );
1175 expect(commandAvailable).toHaveBeenCalledTimes(1);
1176 }),
1177 );
1178
1179 it.effect("keeps the baseline env when profiled probe still does not resolve node", () =>
1180 Effect.gen(function* () {
1181 const readEnvironment = vi.fn(
1182 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
1183 options?.loadProfile ? { FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm" } : {},
1184 );
1185 const commandAvailable = vi.fn(() => Effect.succeed(false));
1186
1187 expect(
1188 yield* withWindowsEnvironmentMocks(
1189 resolveWindowsEnvironment({
1190 PATH: "C:\\Windows\\System32",
1191 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
1192 USERPROFILE: "C:\\Users\\testuser",
1193 }),
1194 readEnvironment,
1195 commandAvailable,
1196 ),
1197 ).toEqual({
1198 PATH: [
1199 "C:\\Windows\\System32",
1200 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
1201 "C:\\Users\\testuser\\.local\\bin",
1202 "C:\\Users\\testuser\\.bun\\bin",
1203 "C:\\Users\\testuser\\scoop\\shims",
1204 ].join(";"),
1205 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
1206 });
1207 expect(commandAvailable).toHaveBeenCalledTimes(1);
1208 }),
1209 );
1210});
1211
1212describe("desktop shell environment updates", () => {
1213 it.each(["win32", "linux", "darwin"] as const)(
1214 "applies shell updates with %s PATH semantics",
1215 (platform) => {
1216 const message = decodeDesktopHostMessage({
1217 version: 1,
1218 type: "shellEnvironment",
1219 discovered: true,
1220 platform,
1221 environment: {
1222 PATH: "C:\\fresh",
1223 FNM_DIR: null,
1224 __MISE_DIFF: null,
1225 SSH_AUTH_SOCK: "/current.sock",
1226 NODE_OPTIONS: "--bad",
1227 },
1228 });
1229 expect(message.type).toBe("shellEnvironment");
1230 if (message.type !== "shellEnvironment") throw new Error("Expected shell environment update");
1231 const env: NodeJS.ProcessEnv = {
1232 Path: "C:\\stale",
1233 FNM_DIR: "stale",
1234 __MISE_DIFF: "stale",
1235 UNRELATED: "keep",
1236 };
1237 applyShellEnvironment(env, message.environment, platform);
1238 expect(env).toEqual({
1239 PATH: "C:\\fresh",
1240 ...(platform === "win32" ? {} : { Path: "C:\\stale" }),
1241 SSH_AUTH_SOCK: "/current.sock",
1242 UNRELATED: "keep",
1243 });
1244 env.Path = "C:\\stale";
1245 env.path = "C:\\other";
1246 applyShellEnvironment(env, { PATH: null, SSH_AUTH_SOCK: null }, platform);
1247 expect(env).toEqual({
1248 ...(platform === "win32" ? {} : { Path: "C:\\stale", path: "C:\\other" }),
1249 UNRELATED: "keep",
1250 });
1251 },
1252 );
1253});
1254
1255describe("pathSetupCommand", () => {
1256 // Undefined where a pasted line could break things: Windows (it would flatten %VAR% entries in
1257 // the registry PATH), macOS bash (several startup files), other shells, and unsafe paths.
1258 it.each([
1259 [
1260 "/home/theo/.local/bin",
1261 "/bin/bash",
1262 "linux",
1263 `printf '\\n%s\\n' 'export PATH="$PATH:/home/theo/.local/bin"' >> ~/.bashrc`,
1264 ],
1265 [
1266 "/Users/theo/.local/bin",
1267 "/usr/bin/fish",
1268 "linux",
1269 `mkdir -p ~/.config/fish && printf '\\n%s\\n' 'fish_add_path --append --path $HOME/.local/bin' >> ~/.config/fish/config.fish`,
1270 ],
1271 [
1272 "/opt/t3/bin",
1273 "/bin/zsh",
1274 "linux",
1275 `printf '\\n%s\\n' 'export PATH="$PATH:/opt/t3/bin"' >> ~/.zshrc`,
1276 ],
1277 ["/Users/theo/.local/bin", "/bin/tcsh", "darwin", undefined],
1278 ["/Users/theo/.local/bin", "/bin/bash", "darwin", undefined],
1279 ["C:\\Users\\theo\\.local\\bin", "pwsh", "win32", undefined],
1280 ["/Users/theo/it's here", "/bin/zsh", "darwin", undefined],
1281 ["/opt/a$PWD/bin", "/bin/zsh", "linux", undefined],
1282 // Relative: PATH would follow the working directory into any checkout's `bin`.
1283 ["bin", "/bin/zsh", "linux", undefined],
1284 ] as const)("%s with %s on %s", (directory, shell, platform, expected) => {
1285 expect(pathSetupCommand({ directory, home: "/Users/theo", shell, platform })).toBe(expected);
1286 });
1287
1288 it("writes the startup file fish and zsh read, under XDG_CONFIG_HOME or ZDOTDIR", () => {
1289 const setup = { directory: "/opt/t3/bin", home: "/home/theo", shell: "/usr/bin/fish" } as const;
1290 expect(pathSetup({ ...setup, platform: "linux", configHome: "/home/theo/cfg" })?.file).toBe(
1291 "/home/theo/cfg/fish/config.fish",
1292 );
1293 expect(pathSetup({ ...setup, platform: "linux" })?.file).toBe("~/.config/fish/config.fish");
1294 // zsh reads .zshrc from ZDOTDIR when it is set.
1295 expect(
1296 pathSetup({ ...setup, shell: "/bin/zsh", platform: "darwin", zdotdir: "/Users/theo/.zsh" })
1297 ?.file,
1298 ).toBe("/Users/theo/.zsh/.zshrc");
1299 // A set folder that cannot be written safely means no setup, never the unread default.
1300 expect(
1301 pathSetup({ ...setup, shell: "/bin/zsh", platform: "darwin", zdotdir: "/Users/theo/my zsh" }),
1302 ).toBeUndefined();
1303 expect(
1304 pathSetup({ ...setup, platform: "linux", configHome: "/home/theo/my cfg" }),
1305 ).toBeUndefined();
1306 });
1307});