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