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