Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { it as effectIt } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as FileSystem from "effect/FileSystem";
7import * as Path from "effect/Path";
8import * as Result from "effect/Result";
9import * as TestClock from "effect/testing/TestClock";
10import * as Tracer from "effect/Tracer";
11import { describe, expect, it, vi } from "vite-plus/test";
12
13import {
14 CommandAvailability,
15 CommandResolutionCache,
16 type CommandAvailabilityChecker,
17 isCommandAvailable,
18 listLoginShellCandidates,
19 mergePathEntries,
20 mergePathValues,
21 preferGitForWindowsBinary,
22 readEnvironmentFromLoginShell,
23 readEnvironmentFromWindowsShell,
24 readPathFromLaunchctl,
25 readPathFromLoginShell,
26 resolveCommandPath,
27 resolveKnownWindowsCliDirs,
28 resolveSpawnCommand,
29 resolveWindowsEnvironment,
30 SpawnExecutableResolution,
31 type SpawnExecutableResolver,
32 WindowsShellEnvironment,
33 withPathDirectoryListings,
34 type WindowsShellEnvironmentReader,
35} from "./shell.ts";
36
37const withWindowsEnvironmentMocks = <A, E, R>(
38 effect: Effect.Effect<A, E, R>,
39 readEnvironment: WindowsShellEnvironmentReader,
40 commandAvailable: CommandAvailabilityChecker,
41) =>
42 effect.pipe(
43 Effect.provideService(WindowsShellEnvironment, readEnvironment),
44 Effect.provideService(CommandAvailability, commandAvailable),
45 );
46
47const recordCommandTrace = Effect.fnUntraced(function* <A, E, R>(effect: Effect.Effect<A, E, R>) {
48 const spans: Array<Tracer.NativeSpan> = [];
49 const tracer = Tracer.make({
50 span: (options) => {
51 const span = new Tracer.NativeSpan(options);
52 spans.push(span);
53 return span;
54 },
55 });
56 const result = yield* effect.pipe(Effect.withTracer(tracer), Effect.result);
57 return { result, spans };
58});
59
60describe("readPathFromLoginShell", () => {
61 it("uses a shell-agnostic printenv PATH probe", () => {
62 const execFile = vi.fn<
63 (
64 file: string,
65 args: ReadonlyArray<string>,
66 options: { encoding: "utf8"; timeout: number },
67 ) => string
68 >(() => "__T3CODE_ENV_PATH_START__\n/a:/b\n__T3CODE_ENV_PATH_END__\n");
69
70 expect(readPathFromLoginShell("/opt/homebrew/bin/fish", execFile)).toBe("/a:/b");
71 expect(execFile).toHaveBeenCalledTimes(1);
72
73 const firstCall = execFile.mock.calls[0] as
74 | [string, ReadonlyArray<string>, { encoding: "utf8"; timeout: number }]
75 | undefined;
76 expect(firstCall).toBeDefined();
77 if (!firstCall) {
78 throw new Error("Expected execFile to be called");
79 }
80
81 const [shell, args, options] = firstCall;
82 expect(shell).toBe("/opt/homebrew/bin/fish");
83 expect(args).toHaveLength(2);
84 expect(args?.[0]).toBe("-ilc");
85 expect(args?.[1]).toContain("printenv PATH || true");
86 expect(args?.[1]).toContain("__T3CODE_ENV_PATH_START__");
87 expect(args?.[1]).toContain("__T3CODE_ENV_PATH_END__");
88 expect(options).toEqual({ encoding: "utf8", timeout: 5000 });
89 });
90});
91
92describe("readPathFromLaunchctl", () => {
93 it("returns a trimmed PATH value from launchctl", () => {
94 const execFile = vi.fn<
95 (
96 file: string,
97 args: ReadonlyArray<string>,
98 options: { encoding: "utf8"; timeout: number },
99 ) => string
100 >(() => " /opt/homebrew/bin:/usr/bin \n");
101
102 expect(readPathFromLaunchctl(execFile)).toBe("/opt/homebrew/bin:/usr/bin");
103 expect(execFile).toHaveBeenCalledWith("/bin/launchctl", ["getenv", "PATH"], {
104 encoding: "utf8",
105 timeout: 2000,
106 });
107 });
108
109 it("returns undefined when launchctl is unavailable", () => {
110 const execFile = vi.fn<
111 (
112 file: string,
113 args: ReadonlyArray<string>,
114 options: { encoding: "utf8"; timeout: number },
115 ) => string
116 >(() => {
117 throw new Error("spawn /bin/launchctl ENOENT");
118 });
119
120 expect(readPathFromLaunchctl(execFile)).toBeUndefined();
121 });
122});
123
124describe("readEnvironmentFromLoginShell", () => {
125 it("extracts multiple environment variables from a login shell command", () => {
126 const execFile = vi.fn<
127 (
128 file: string,
129 args: ReadonlyArray<string>,
130 options: { encoding: "utf8"; timeout: number },
131 ) => string
132 >(() =>
133 [
134 "__T3CODE_ENV_PATH_START__",
135 "/a:/b",
136 "__T3CODE_ENV_PATH_END__",
137 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
138 "/tmp/secretive.sock",
139 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
140 ].join("\n"),
141 );
142
143 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
144 PATH: "/a:/b",
145 SSH_AUTH_SOCK: "/tmp/secretive.sock",
146 });
147 expect(execFile).toHaveBeenCalledTimes(1);
148 });
149
150 it("omits environment variables that are missing or empty", () => {
151 const execFile = vi.fn<
152 (
153 file: string,
154 args: ReadonlyArray<string>,
155 options: { encoding: "utf8"; timeout: number },
156 ) => string
157 >(() =>
158 [
159 "__T3CODE_ENV_PATH_START__",
160 "/a:/b",
161 "__T3CODE_ENV_PATH_END__",
162 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
163 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
164 ].join("\n"),
165 );
166
167 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
168 PATH: "/a:/b",
169 });
170 });
171
172 it("preserves surrounding whitespace in captured values", () => {
173 const execFile = vi.fn<
174 (
175 file: string,
176 args: ReadonlyArray<string>,
177 options: { encoding: "utf8"; timeout: number },
178 ) => string
179 >(() =>
180 ["__T3CODE_ENV_CUSTOM_VAR_START__", " padded value ", "__T3CODE_ENV_CUSTOM_VAR_END__"].join(
181 "\n",
182 ),
183 );
184
185 expect(readEnvironmentFromLoginShell("/bin/zsh", ["CUSTOM_VAR"], execFile)).toEqual({
186 CUSTOM_VAR: " padded value ",
187 });
188 });
189});
190
191describe("listLoginShellCandidates", () => {
192 it("returns env shell, user shell, then the platform fallback without duplicates", () => {
193 expect(listLoginShellCandidates("darwin", " /opt/homebrew/bin/nu ", "/bin/zsh")).toEqual([
194 "/opt/homebrew/bin/nu",
195 "/bin/zsh",
196 ]);
197 });
198
199 it("falls back to the platform default when no shells are available", () => {
200 expect(listLoginShellCandidates("linux", undefined, "")).toEqual(["/bin/bash"]);
201 });
202});
203
204describe("mergePathEntries", () => {
205 it("prefers login-shell PATH entries and keeps inherited extras", () => {
206 expect(
207 mergePathEntries("/opt/homebrew/bin:/usr/bin", "/Users/test/.local/bin:/usr/bin", "darwin"),
208 ).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
209 });
210
211 it("uses the platform-specific delimiter", () => {
212 expect(mergePathEntries("C:\\Tools;C:\\Windows", "C:\\Windows;C:\\Git", "win32")).toBe(
213 "C:\\Tools;C:\\Windows;C:\\Git",
214 );
215 });
216});
217
218describe("readEnvironmentFromWindowsShell", () => {
219 it("extracts environment variables from a PowerShell command", () => {
220 const execFile = vi.fn<
221 (
222 file: string,
223 args: ReadonlyArray<string>,
224 options: { encoding: "utf8"; timeout: number },
225 ) => string
226 >(
227 () =>
228 "__T3CODE_ENV_PATH_START__\nC:\\Users\\testuser\\AppData\\Roaming\\npm\n__T3CODE_ENV_PATH_END__\n",
229 );
230
231 expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
232 PATH: "C:\\Users\\testuser\\AppData\\Roaming\\npm",
233 });
234 expect(execFile).toHaveBeenCalledWith(
235 "pwsh.exe",
236 expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]),
237 { encoding: "utf8", timeout: 5000 },
238 );
239 });
240
241 it("strips CRLF delimiters from captured PowerShell values", () => {
242 const execFile = vi.fn<
243 (
244 file: string,
245 args: ReadonlyArray<string>,
246 options: { encoding: "utf8"; timeout: number },
247 ) => string
248 >(
249 () =>
250 "__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
251 );
252
253 expect(readEnvironmentFromWindowsShell(["FNM_DIR"], execFile)).toEqual({
254 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
255 });
256 });
257
258 it("omits -NoProfile when loadProfile is enabled", () => {
259 const execFile = vi.fn<
260 (
261 file: string,
262 args: ReadonlyArray<string>,
263 options: { encoding: "utf8"; timeout: number },
264 ) => string
265 >(() => "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n");
266
267 expect(readEnvironmentFromWindowsShell(["PATH"], { loadProfile: true }, execFile)).toEqual({
268 PATH: "C:\\Tools",
269 });
270 expect(execFile).toHaveBeenCalledWith(
271 "pwsh.exe",
272 expect.arrayContaining(["-NoLogo", "-NonInteractive", "-Command"]),
273 { encoding: "utf8", timeout: 5000 },
274 );
275 expect(execFile.mock.calls[0]?.[1]).not.toContain("-NoProfile");
276 });
277
278 it("falls back to Windows PowerShell when pwsh.exe is unavailable", () => {
279 const execFile = vi.fn<
280 (
281 file: string,
282 args: ReadonlyArray<string>,
283 options: { encoding: "utf8"; timeout: number },
284 ) => string
285 >((file) => {
286 if (file === "pwsh.exe") {
287 throw new Error("spawn pwsh.exe ENOENT");
288 }
289 return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
290 });
291
292 expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
293 PATH: "C:\\Tools",
294 });
295 expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
296 encoding: "utf8",
297 timeout: 5000,
298 });
299 expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
300 encoding: "utf8",
301 timeout: 5000,
302 });
303 });
304});
305
306describe("mergePathValues", () => {
307 it("sanitizes and dedupes Windows entries while preserving preferred order", () => {
308 expect(
309 mergePathValues(
310 'C:\\Users\\testuser\\AppData\\Roaming\\npm;"C:\\Program Files\\nodejs"',
311 "c:\\users\\testuser\\appdata\\roaming\\npm;C:\\Windows\\System32",
312 "win32",
313 ),
314 ).toBe(
315 "C:\\Users\\testuser\\AppData\\Roaming\\npm;C:\\Program Files\\nodejs;C:\\Windows\\System32",
316 );
317 });
318
319 it("removes stray quotes from Windows entries", () => {
320 expect(
321 mergePathValues(
322 'C:\\Windows\\System32;C:\\cloudflared.exe;C:";C:\\Program Files\\nodejs',
323 undefined,
324 "win32",
325 ),
326 ).toBe("C:\\Windows\\System32;C:\\cloudflared.exe;C:;C:\\Program Files\\nodejs");
327 });
328
329 it("dedupes case-sensitively on POSIX", () => {
330 expect(mergePathValues("/usr/local/bin:/usr/bin", "/usr/bin:/USR/BIN", "linux")).toBe(
331 "/usr/local/bin:/usr/bin:/USR/BIN",
332 );
333 });
334});
335
336describe("resolveKnownWindowsCliDirs", () => {
337 it("returns known Windows CLI install directories in priority order", () => {
338 expect(
339 resolveKnownWindowsCliDirs({
340 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
341 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
342 USERPROFILE: "C:\\Users\\testuser",
343 }),
344 ).toEqual([
345 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
346 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
347 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
348 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
349 "C:\\Users\\testuser\\.local\\bin",
350 "C:\\Users\\testuser\\.bun\\bin",
351 "C:\\Users\\testuser\\scoop\\shims",
352 ]);
353 });
354});
355
356effectIt.layer(NodeServices.layer)("isCommandAvailable", (it) => {
357 it.effect.each(["win32", "linux"] as const)(
358 "records missing optional commands as successful lookups on %s",
359 (platform) =>
360 Effect.gen(function* () {
361 const fs = yield* FileSystem.FileSystem;
362 const path = yield* Path.Path;
363 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-command-trace-" });
364 const env = { PATH: cwd, PATHEXT: ".CMD" };
365 const checks = [
366 isCommandAvailable("missing", { env }),
367 isCommandAvailable("missing", { env }),
368 isCommandAvailable("missing", { env: { ...env, PATH: "" } }),
369 isCommandAvailable(path.join(cwd, "missing.cmd"), { env }),
370 ];
371 for (const check of checks) {
372 const { result, spans } = yield* recordCommandTrace(check);
373 expect(Result.getOrThrow(result)).toBe(false);
374 expect(spans.length).toBeGreaterThan(0);
375 for (const span of spans) {
376 expect(span.status._tag).toBe("Ended");
377 if (span.status._tag === "Ended") {
378 expect(Exit.isSuccess(span.status.exit), span.name).toBe(true);
379 }
380 }
381 }
382 }).pipe(
383 Effect.provideService(HostProcess.Platform, platform),
384 Effect.provideService(CommandResolutionCache, new Map()),
385 ),
386 );
387
388 it.effect.each(["win32", "linux"] as const)(
389 "records available commands as successful lookups on %s",
390 (platform) =>
391 Effect.gen(function* () {
392 const fs = yield* FileSystem.FileSystem;
393 const path = yield* Path.Path;
394 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-command-trace-" });
395 const executable = path.join(cwd, platform === "win32" ? "available.cmd" : "available");
396 yield* fs.writeFileString(executable, "");
397 yield* fs.chmod(executable, 0o700);
398 const env = { PATH: cwd, PATHEXT: ".CMD" };
399 for (const command of ["available", executable]) {
400 const { result, spans } = yield* recordCommandTrace(isCommandAvailable(command, { env }));
401 expect(Result.getOrThrow(result)).toBe(true);
402 expect(spans.length).toBeGreaterThan(0);
403 for (const span of spans) {
404 expect(span.status._tag).toBe("Ended");
405 if (span.status._tag === "Ended") {
406 expect(Exit.isSuccess(span.status.exit), span.name).toBe(true);
407 }
408 }
409 }
410 }).pipe(
411 Effect.provideService(HostProcess.Platform, platform),
412 Effect.provideService(CommandResolutionCache, new Map()),
413 ),
414 );
415
416 it.effect("returns false when PATH is empty", () =>
417 Effect.gen(function* () {
418 expect(
419 yield* isCommandAvailable("definitely-not-installed", {
420 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
421 }).pipe(Effect.provideService(HostProcess.Platform, "win32")),
422 ).toBe(false);
423 }),
424 );
425});
426
427effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => {
428 it.effect("records a successful lookup when a command is missing", () =>
429 Effect.gen(function* () {
430 const { result, spans } = yield* recordCommandTrace(
431 resolveCommandPath("missing", { env: { PATH: "" } }),
432 );
433 expect(Result.getOrThrow(result)).toBeNull();
434 expect(spans.length).toBeGreaterThan(0);
435 for (const span of spans) {
436 expect(span.status._tag).toBe("Ended");
437 if (span.status._tag === "Ended") {
438 expect(Exit.isSuccess(span.status.exit), span.name).toBe(true);
439 }
440 }
441 }),
442 );
443
444 it.effect("returns null when PATH is empty", () =>
445 Effect.gen(function* () {
446 const result = yield* resolveCommandPath("definitely-not-installed", {
447 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
448 }).pipe(Effect.provideService(HostProcess.Platform, "win32"));
449
450 expect(result).toBeNull();
451 }),
452 );
453
454 // Records every path the scan stats, without ever reporting a match, so the
455 // walk runs to exhaustion and the probe set can be inspected. Assertions
456 // below count probes rather than naming paths: `Path` is the host's, so the
457 // separator differs between a Windows and a Linux CI runner.
458 const recordProbes = (env: NodeJS.ProcessEnv) =>
459 Effect.gen(function* () {
460 const probed: Array<string> = [];
461 const result = yield* resolveCommandPath("definitely-not-installed", { env }).pipe(
462 Effect.provideService(HostProcess.Platform, "win32"),
463 Effect.provideService(CommandResolutionCache, new Map()),
464 Effect.provide(
465 FileSystem.layerNoop({
466 stat: (filePath) =>
467 Effect.sync(() => {
468 probed.push(filePath);
469 return { type: "Directory" } as FileSystem.File.Info;
470 }),
471 }),
472 ),
473 );
474
475 expect(result).toBeNull();
476 return probed;
477 });
478
479 it.effect("visits a repeated PATH directory only once", () =>
480 Effect.gen(function* () {
481 const probed = yield* recordProbes({
482 PATH: "C:\\bin;C:\\other;C:\\bin;C:\\other",
483 PATHEXT: ".COM;.EXE",
484 });
485
486 // Two directories, two extensions, upper and lowercase spellings.
487 expect(probed).toHaveLength(8);
488 expect(new Set(probed).size).toBe(probed.length);
489 }),
490 );
491
492 it.effect("still visits a PATH entry that differs only in case", () =>
493 Effect.gen(function* () {
494 const probed = yield* recordProbes({
495 PATH: "C:\\bin;C:\\BIN",
496 PATHEXT: ".COM;.EXE",
497 });
498
499 // Deliberately not folded together. Windows 10+ can mark a directory
500 // case-sensitive, so the two spellings are not provably one directory and
501 // skipping the second could hide a command that is really there.
502 expect(probed).toHaveLength(8);
503 }),
504 );
505
506 it.effect.each(["audit-command", "audit-command.CMD"])(
507 "resolves lowercase executable files for %s in a case-sensitive Windows PATH directory",
508 (command) =>
509 Effect.gen(function* () {
510 const fs = yield* FileSystem.FileSystem;
511 const path = yield* Path.Path;
512 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-case-sensitive-path-" });
513 const executable = path.join(cwd, "audit-command.cmd");
514 yield* fs.writeFileString(executable, "@echo off\n");
515
516 const resolved = yield* resolveCommandPath(command, {
517 env: { PATH: cwd, PATHEXT: ".CMD" },
518 }).pipe(
519 Effect.provideService(HostProcess.Platform, "win32"),
520 Effect.provideService(CommandResolutionCache, new Map()),
521 Effect.provideService(FileSystem.FileSystem, {
522 ...fs,
523 // Keep this case-sensitive fixture portable to case-insensitive hosts.
524 stat: (filePath) =>
525 fs.stat(filePath === executable ? filePath : path.join(cwd, "missing")),
526 }),
527 );
528
529 expect(resolved).toBe(executable);
530 }),
531 );
532
533 it.effect("keeps cached misses until expiry while allowing explicit paths", () =>
534 Effect.gen(function* () {
535 const fs = yield* FileSystem.FileSystem;
536 const path = yield* Path.Path;
537 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-path-cache-" });
538 const executable = path.join(cwd, "appeared.CMD");
539 const options = { env: { PATH: `${cwd};${cwd}`, PATHEXT: ".CMD" } };
540
541 expect(yield* resolveCommandPath("appeared", options)).toBeNull();
542 yield* fs.writeFileString(executable, "@echo off\n");
543 expect(yield* resolveCommandPath("appeared", options)).toBeNull();
544 expect(yield* resolveCommandPath(executable, options)).toBe(executable);
545 yield* TestClock.adjust("30 seconds");
546 expect(yield* resolveCommandPath("appeared", options)).toBe(executable);
547 }).pipe(
548 Effect.provideService(HostProcess.Platform, "win32"),
549 Effect.provideService(CommandResolutionCache, new Map()),
550 ),
551 );
552
553 it.effect("keeps upper and lowercase PATHEXT candidates", () =>
554 Effect.gen(function* () {
555 const probed = yield* recordProbes({
556 PATH: "C:\\bin",
557 PATHEXT: ".COM;.EXE;.BAT;.CMD",
558 });
559
560 expect(probed).toHaveLength(8);
561 expect(probed.filter((filePath) => /\.(COM|EXE|BAT|CMD)$/.test(filePath))).toHaveLength(4);
562 expect(probed.filter((filePath) => /\.(com|exe|bat|cmd)$/.test(filePath))).toHaveLength(4);
563 }),
564 );
565
566 it.effect("probes only listed PATH names and relists a directory that changes", () =>
567 Effect.gen(function* () {
568 const fs = yield* FileSystem.FileSystem;
569 const path = yield* Path.Path;
570 const first = yield* fs.makeTempDirectoryScoped();
571 const second = yield* fs.makeTempDirectoryScoped();
572 yield* fs.writeFileString(path.join(first, "cursor.CMD"), "");
573 yield* fs.writeFileString(path.join(second, "cursor.EXE"), "");
574 const env = { PATH: `${first};${second}`, PATHEXT: ".EXE;.CMD" };
575 const probed: Array<string> = [];
576 yield* Effect.gen(function* () {
577 expect(yield* resolveCommandPath("cursor", { env })).toBe(path.join(first, "cursor.CMD"));
578 expect(yield* isCommandAvailable("absent", { env })).toBe(false);
579 yield* fs.writeFileString(path.join(second, "late.EXE"), "");
580 yield* fs.utimes(second, 4_102_444_800, 4_102_444_800); // seconds: 2100-01-01
581 expect(yield* resolveCommandPath("late", { env })).toBe(path.join(second, "late.EXE"));
582 }).pipe(
583 withPathDirectoryListings,
584 Effect.provideService(FileSystem.FileSystem, {
585 ...fs,
586 stat: (file) => {
587 // Record candidate probes, not the per-lookup directory mtime checks.
588 if (file !== first && file !== second) probed.push(file);
589 return fs.stat(file);
590 },
591 }),
592 );
593 expect(probed).toEqual([path.join(first, "cursor.CMD"), path.join(second, "late.EXE")]);
594 }).pipe(
595 Effect.provideService(HostProcess.Platform, "win32"),
596 Effect.provideService(CommandResolutionCache, new Map()),
597 ),
598 );
599});
600
601describe("preferGitForWindowsBinary", () => {
602 const files =
603 (...paths: Array<string>) =>
604 (filePath: string) =>
605 paths.includes(filePath);
606
607 it("runs the git.exe Git for Windows' launcher would start", () => {
608 // 2.56+ on x64. The PATHEXT scan returns the extension in PATHEXT's case.
609 expect(
610 preferGitForWindowsBinary(
611 "C:\\Program Files\\Git\\cmd\\git.EXE",
612 {},
613 files(
614 "C:\\Program Files\\Git\\ucrt64\\bin\\git.exe",
615 "C:\\Program Files\\Git\\mingw64\\bin\\git.exe",
616 ),
617 ),
618 ).toBe("C:\\Program Files\\Git\\ucrt64\\bin\\git.exe");
619 // Before 2.56, and the portable build's bin launcher.
620 expect(
621 preferGitForWindowsBinary(
622 "D:\\PortableGit\\bin\\git.exe",
623 {},
624 files("D:\\PortableGit\\mingw64\\bin\\git.exe"),
625 ),
626 ).toBe("D:\\PortableGit\\mingw64\\bin\\git.exe");
627 expect(
628 preferGitForWindowsBinary(
629 "C:\\Program Files\\Git\\cmd\\git.exe",
630 {},
631 files("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe"),
632 ),
633 ).toBe("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe");
634 });
635
636 it("keeps the launcher when MSYSTEM is set", () => {
637 // The real git.exe only adds its own folders to PATH when MSYSTEM is unset;
638 // without them a `#!/bin/sh` hook cannot start.
639 expect(
640 preferGitForWindowsBinary(
641 "C:\\Program Files\\Git\\cmd\\git.exe",
642 { MSYSTEM: "MINGW64" },
643 files("C:\\Program Files\\Git\\mingw64\\bin\\git.exe"),
644 ),
645 ).toBe("C:\\Program Files\\Git\\cmd\\git.exe");
646 });
647
648 it("keeps the launcher when no git.exe sits beside it", () => {
649 expect(preferGitForWindowsBinary("C:\\Program Files\\Git\\cmd\\git.exe", {}, () => false)).toBe(
650 "C:\\Program Files\\Git\\cmd\\git.exe",
651 );
652 });
653
654 it("leaves other gits and other launchers alone", () => {
655 const everything = () => true;
656 expect(preferGitForWindowsBinary("C:\\Users\\me\\scoop\\shims\\git.exe", {}, everything)).toBe(
657 "C:\\Users\\me\\scoop\\shims\\git.exe",
658 );
659 expect(preferGitForWindowsBinary("C:\\Program Files\\Git\\cmd\\gitk.exe", {}, everything)).toBe(
660 "C:\\Program Files\\Git\\cmd\\gitk.exe",
661 );
662 });
663});
664
665effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
666 it.effect("runs Windows executables directly without a shell", () =>
667 Effect.gen(function* () {
668 const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], {
669 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
670 }).pipe(
671 Effect.provideService(HostProcess.Platform, "win32"),
672 Effect.provideService(CommandResolutionCache, new Map()),
673 );
674
675 expect(command).toEqual({
676 command: "node.exe",
677 args: ["script.js", "hello & goodbye"],
678 shell: false,
679 });
680 }),
681 );
682
683 it.effect("escapes the executable and arguments for Windows command shims", () =>
684 Effect.gen(function* () {
685 const command = yield* resolveSpawnCommand(
686 "vp",
687 ["run", "value & calc", "%PATH%", 'quote"value'],
688 { env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" } },
689 ).pipe(
690 Effect.provideService(HostProcess.Platform, "win32"),
691 Effect.provideService(CommandResolutionCache, new Map()),
692 Effect.provideService(
693 SpawnExecutableResolution,
694 () => "C:\\Program Files\\npm & tools\\vp.cmd",
695 ),
696 );
697
698 expect(command.shell).toBe(true);
699 expect(command.command).not.toContain(" & ");
700 expect(command.command).toContain("^&");
701 expect(command.args).toEqual([
702 '^"run^"',
703 '^"value^ ^&^ calc^"',
704 '^"^%PATH^%^"',
705 '^"quote\\^"value^"',
706 ]);
707 }),
708 );
709
710 it.effect("resolves against the effective environment when extending host env", () =>
711 Effect.gen(function* () {
712 let resolvedEnvironment: NodeJS.ProcessEnv | undefined;
713 yield* resolveSpawnCommand("codex", ["app-server"], {
714 env: { CODEX_HOME: "C:\\Users\\tester\\.codex" },
715 extendEnv: true,
716 }).pipe(
717 Effect.provideService(HostProcess.Platform, "win32"),
718 Effect.provideService(CommandResolutionCache, new Map()),
719 Effect.provideService(HostProcess.Environment, {
720 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
721 PATHEXT: ".COM;.EXE;.BAT;.CMD",
722 }),
723 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) => {
724 resolvedEnvironment = env;
725 return "C:\\Users\\tester\\AppData\\Roaming\\npm\\codex.cmd";
726 }),
727 );
728
729 expect(resolvedEnvironment).toEqual({
730 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
731 PATHEXT: ".COM;.EXE;.BAT;.CMD",
732 CODEX_HOME: "C:\\Users\\tester\\.codex",
733 });
734 }),
735 );
736
737 it.effect("scans PATH once per command until the search environment changes", () =>
738 Effect.gen(function* () {
739 const scans: Array<string> = [];
740 const scan: SpawnExecutableResolver = (name, _platform, env) => {
741 scans.push(`${name}@${env.PATH}`);
742 return name === "missing" ? undefined : `${env.PATH}\\${name}.exe`;
743 };
744 const resolve = (command: string, path: string, resolver = scan) =>
745 resolveSpawnCommand(command, [], { env: { PATH: path, PATHEXT: ".EXE" } }).pipe(
746 Effect.provideService(HostProcess.Platform, "win32"),
747 Effect.provideService(SpawnExecutableResolution, resolver),
748 );
749
750 expect((yield* resolve("git", "C:\\one")).command).toBe("C:\\one\\git.exe");
751 expect((yield* resolve("git", "C:\\one")).command).toBe("C:\\one\\git.exe");
752 // A failed spawn is how a provider reports "not installed", so a miss
753 // must clear the moment the binary appears.
754 yield* resolve("missing", "C:\\one");
755 yield* resolve("missing", "C:\\one");
756 expect((yield* resolve("git", "C:\\two")).command).toBe("C:\\two\\git.exe");
757 // Callers probe explicit paths they may have just written.
758 yield* resolve("C:\\tools\\git.exe", "C:\\one");
759 yield* resolve("C:\\tools\\git.exe", "C:\\one");
760 expect(scans).toEqual([
761 "git@C:\\one",
762 "missing@C:\\one",
763 "missing@C:\\one",
764 "git@C:\\two",
765 "C:\\tools\\git.exe@C:\\one",
766 "C:\\tools\\git.exe@C:\\one",
767 ]);
768
769 yield* TestClock.adjust("31 seconds");
770 yield* resolve("git", "C:\\one");
771 expect(scans).toHaveLength(7);
772
773 // Another resolver sharing the cache gets its own answer, not the cached one.
774 const elsewhere = yield* resolve("git", "C:\\one", () => "D:\\elsewhere\\git.exe");
775 expect(elsewhere.command).toBe("D:\\elsewhere\\git.exe");
776 expect((yield* resolve("git", "C:\\one")).command).toBe("C:\\one\\git.exe");
777 expect(scans).toHaveLength(7);
778 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
779 );
780
781 it.effect("keeps launcher swaps apart for environments with and without MSYSTEM", () =>
782 Effect.gen(function* () {
783 let scans = 0;
784 const scan: SpawnExecutableResolver = () => {
785 scans++;
786 return "C:\\Git\\cmd\\git.exe";
787 };
788 const resolve = (env: NodeJS.ProcessEnv) =>
789 resolveSpawnCommand("git", [], {
790 env: { PATH: "C:\\Git\\cmd", PATHEXT: ".EXE", ...env },
791 }).pipe(
792 Effect.provideService(HostProcess.Platform, "win32"),
793 Effect.provideService(SpawnExecutableResolution, scan),
794 );
795
796 yield* resolve({});
797 yield* resolve({});
798 expect(scans).toBe(1);
799 // A swap made without MSYSTEM must not reach a child that has it set.
800 yield* resolve({ MSYSTEM: "MINGW64" });
801 expect(scans).toBe(2);
802 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
803 );
804
805 it.effect("does not fall back to a shell for unresolved Windows commands", () =>
806 Effect.gen(function* () {
807 const command = yield* resolveSpawnCommand("missing & calc", ["unsafe & value"], {
808 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
809 }).pipe(
810 Effect.provideService(HostProcess.Platform, "win32"),
811 Effect.provideService(CommandResolutionCache, new Map()),
812 );
813
814 expect(command).toEqual({
815 command: "missing & calc",
816 args: ["unsafe & value"],
817 shell: false,
818 });
819 }),
820 );
821});
822
823effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => {
824 it.effect("uses known CLI directories as a fallback without changing shell PATH priority", () =>
825 Effect.gen(function* () {
826 const readEnvironment = vi.fn(
827 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
828 options?.loadProfile
829 ? { PATH: "C:\\Profile\\Bin" }
830 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
831 );
832 const commandAvailable = vi.fn(() => Effect.succeed(true));
833
834 expect(
835 yield* withWindowsEnvironmentMocks(
836 resolveWindowsEnvironment({
837 PATH: "C:\\Windows\\System32",
838 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
839 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
840 USERPROFILE: "C:\\Users\\testuser",
841 }),
842 readEnvironment,
843 commandAvailable,
844 ),
845 ).toEqual({
846 PATH: [
847 "C:\\Shell\\Bin",
848 "C:\\Windows\\System32",
849 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
850 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
851 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
852 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
853 "C:\\Users\\testuser\\.local\\bin",
854 "C:\\Users\\testuser\\.bun\\bin",
855 "C:\\Users\\testuser\\scoop\\shims",
856 ].join(";"),
857 });
858 expect(readEnvironment).toHaveBeenCalledTimes(1);
859 expect(readEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
860 expect(commandAvailable).toHaveBeenCalledWith(
861 "node",
862 expect.objectContaining({ env: expect.any(Object) }),
863 );
864 }),
865 );
866
867 it.effect("loads the PowerShell profile when baseline env cannot resolve node", () =>
868 Effect.gen(function* () {
869 const readEnvironment = vi.fn(
870 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
871 options?.loadProfile
872 ? {
873 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
874 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
875 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
876 }
877 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
878 );
879 const commandAvailable = vi.fn(() => Effect.succeed(false));
880
881 expect(
882 yield* withWindowsEnvironmentMocks(
883 resolveWindowsEnvironment({
884 PATH: "C:\\Windows\\System32",
885 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
886 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
887 USERPROFILE: "C:\\Users\\testuser",
888 }),
889 readEnvironment,
890 commandAvailable,
891 ),
892 ).toEqual({
893 PATH: [
894 "C:\\Profile\\Node",
895 "C:\\Windows\\System32",
896 "C:\\Shell\\Bin",
897 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
898 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
899 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
900 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
901 "C:\\Users\\testuser\\.local\\bin",
902 "C:\\Users\\testuser\\.bun\\bin",
903 "C:\\Users\\testuser\\scoop\\shims",
904 ].join(";"),
905 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
906 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
907 });
908 expect(readEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
909 expect(readEnvironment).toHaveBeenNthCalledWith(
910 2,
911 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
912 {
913 loadProfile: true,
914 },
915 );
916 expect(commandAvailable).toHaveBeenCalledTimes(1);
917 }),
918 );
919
920 it.effect("keeps the baseline env when profiled probe still does not resolve node", () =>
921 Effect.gen(function* () {
922 const readEnvironment = vi.fn(
923 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
924 options?.loadProfile ? { FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm" } : {},
925 );
926 const commandAvailable = vi.fn(() => Effect.succeed(false));
927
928 expect(
929 yield* withWindowsEnvironmentMocks(
930 resolveWindowsEnvironment({
931 PATH: "C:\\Windows\\System32",
932 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
933 USERPROFILE: "C:\\Users\\testuser",
934 }),
935 readEnvironment,
936 commandAvailable,
937 ),
938 ).toEqual({
939 PATH: [
940 "C:\\Windows\\System32",
941 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
942 "C:\\Users\\testuser\\.local\\bin",
943 "C:\\Users\\testuser\\.bun\\bin",
944 "C:\\Users\\testuser\\scoop\\shims",
945 ].join(";"),
946 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
947 });
948 expect(commandAvailable).toHaveBeenCalledTimes(1);
949 }),
950 );
951});