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