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