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