Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- The synchronous shell probe runs real commands with isolated config files.
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { it as effectIt } from "@effect/vitest";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Path from "effect/Path";
9import * as Option from "effect/Option";
10import * as NodeChildProcess from "node:child_process";
11import * as NodeFS from "node:fs";
12import * as NodeOS from "node:os";
13import * as NodePath from "node:path";
14import { describe, expect, it, vi } from "vite-plus/test";
15
16import {
17 CommandAvailability,
18 CommandResolutionCache,
19 type CommandAvailabilityChecker,
20 isCommandAvailable,
21 listLoginShellCandidates,
22 mergePathEntries,
23 mergePathValues,
24 npmShimExecutable,
25 preferGitForWindowsBinary,
26 readEnvironmentFromLoginShell,
27 readEnvironmentFromWindowsShell,
28 resolveCommandPath,
29 resolveSpawnCommand,
30 resolveWindowsEnvironment,
31 SpawnExecutableResolution,
32 WindowsShellEnvironment,
33 withPathDirectoryListings,
34 type WindowsShellEnvironmentReader,
35 XcodeGitLocation,
36} from "./shell.ts";
37
38const nativeProbe = vi.hoisted(() => ({
39 execFile: vi.fn<typeof import("node:child_process").execFile>(),
40}));
41
42vi.mock("node:child_process", async (importOriginal) => {
43 const original = await importOriginal<typeof import("node:child_process")>();
44 return { ...original, execFile: nativeProbe.execFile.mockImplementation(original.execFile) };
45});
46
47const withWindowsEnvironmentMocks = <A, E, R>(
48 effect: Effect.Effect<A, E, R>,
49 readEnvironment: (
50 ...args: Parameters<WindowsShellEnvironmentReader>
51 ) => Partial<Record<string, string>>,
52 commandAvailable: CommandAvailabilityChecker,
53) =>
54 effect.pipe(
55 Effect.provideService(WindowsShellEnvironment, (...args) =>
56 Effect.sync(() => readEnvironment(...args)),
57 ),
58 Effect.provideService(CommandAvailability, commandAvailable),
59 );
60
61describe("readEnvironmentFromLoginShell", () => {
62 // Opt in with an explicit binary, like the provider live probes; CI need not install Nu.
63 it.runIf(process.env.T3_TEST_NU_PATH !== undefined)(
64 "captures Nushell PATH and multiline values without external tools",
65 () => {
66 const shell = process.env.T3_TEST_NU_PATH!;
67 const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-nu-env-"));
68 try {
69 const toolPath = NodePath.join(home, "nu tools", "bin");
70 const extraToolPath = NodePath.join(home, "extra-tools", "bin");
71 NodeFS.mkdirSync(toolPath, { recursive: true });
72 NodeFS.mkdirSync(extraToolPath, { recursive: true });
73 const config = NodePath.join(home, "config.nu");
74 const envConfig = NodePath.join(home, "env.nu");
75 NodeFS.writeFileSync(envConfig, "");
76 NodeFS.writeFileSync(
77 config,
78 [
79 `$env.PATH = [${JSON.stringify(toolPath)}, "~/extra-tools/bin", "rel/dir", ""]`,
80 '$env.CUSTOM_VAR = " first\\nsecond "',
81 '$env.EMPTY_VAR = ""',
82 'print "startup noise"',
83 ].join("\n"),
84 );
85
86 expect(
87 readEnvironmentFromLoginShell(
88 shell,
89 ["MISSING_VAR", "PATH", "EMPTY_VAR", "CUSTOM_VAR"],
90 (file, args, options) =>
91 NodeChildProcess.execFileSync(
92 file,
93 ["--no-history", "--config", config, "--env-config", envConfig, ...args],
94 {
95 ...options,
96 env: { HOME: home, XDG_CONFIG_HOME: home, PATH: toolPath },
97 },
98 ),
99 ),
100 ).toEqual({
101 PATH: `${toolPath}:${extraToolPath}:rel/dir:`,
102 CUSTOM_VAR: " first\nsecond ",
103 });
104 } finally {
105 NodeFS.rmSync(home, { recursive: true, force: true });
106 }
107 },
108 );
109
110 it("extracts multiple environment variables from a login shell command", () => {
111 const execFile = vi.fn<
112 (
113 file: string,
114 args: ReadonlyArray<string>,
115 options: { encoding: "utf8"; timeout: number },
116 ) => string
117 >(() =>
118 [
119 "__T3CODE_ENV_PATH_START__",
120 "/a:/b",
121 "__T3CODE_ENV_PATH_END__",
122 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
123 "/tmp/secretive.sock",
124 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
125 ].join("\n"),
126 );
127
128 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
129 PATH: "/a:/b",
130 SSH_AUTH_SOCK: "/tmp/secretive.sock",
131 });
132 expect(execFile).toHaveBeenCalledTimes(1);
133 });
134
135 it("omits environment variables that are missing or empty", () => {
136 const execFile = vi.fn<
137 (
138 file: string,
139 args: ReadonlyArray<string>,
140 options: { encoding: "utf8"; timeout: number },
141 ) => string
142 >(() =>
143 [
144 "__T3CODE_ENV_PATH_START__",
145 "/a:/b",
146 "__T3CODE_ENV_PATH_END__",
147 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
148 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
149 ].join("\n"),
150 );
151
152 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
153 PATH: "/a:/b",
154 });
155 });
156
157 it("preserves multiline values and surrounding whitespace", () => {
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_CUSTOM_VAR_START__",
167 " first\nsecond ",
168 "__T3CODE_ENV_CUSTOM_VAR_END__",
169 ].join("\n"),
170 );
171
172 expect(readEnvironmentFromLoginShell("/bin/zsh", ["CUSTOM_VAR"], execFile)).toEqual({
173 CUSTOM_VAR: " first\nsecond ",
174 });
175 });
176});
177
178describe("listLoginShellCandidates", () => {
179 it("returns env shell, user shell, then the platform fallback without duplicates", () => {
180 expect(listLoginShellCandidates("darwin", " /opt/homebrew/bin/nu ", "/bin/zsh")).toEqual([
181 "/opt/homebrew/bin/nu",
182 "/bin/zsh",
183 ]);
184 });
185});
186
187describe("mergePathEntries", () => {
188 it("prefers login-shell PATH entries and keeps inherited extras", () => {
189 expect(
190 mergePathEntries("/opt/homebrew/bin:/usr/bin", "/Users/test/.local/bin:/usr/bin", "darwin"),
191 ).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
192 });
193});
194
195describe("readEnvironmentFromWindowsShell", () => {
196 effectIt.effect("yields while the native shell probe is pending", () =>
197 Effect.gen(function* () {
198 let completed = false;
199 const [environment, completedBeforeProbeReturned] = yield* Effect.all(
200 [
201 readEnvironmentFromWindowsShell(["PATH"]).pipe(
202 Effect.tap(() =>
203 Effect.sync(() => {
204 completed = true;
205 }),
206 ),
207 ),
208 Effect.sync(() => completed),
209 ],
210 { concurrency: 2 },
211 );
212 expect(completedBeforeProbeReturned).toBe(false);
213 expect(environment).toBeTypeOf("object");
214 }),
215 );
216
217 effectIt.layer(NodeServices.layer)("synchronous spawn failures", (it) => {
218 it.effect("tries both shells and preserves baseline PATH repair", () =>
219 Effect.gen(function* () {
220 const execFile = nativeProbe.execFile;
221 execFile.mockImplementationOnce(() => {
222 throw new Error("spawn EPERM");
223 });
224 execFile.mockImplementationOnce(() => {
225 throw new Error("spawn EINVAL");
226 });
227 try {
228 const patch = yield* resolveWindowsEnvironment({
229 PATH: "C:\\Windows",
230 APPDATA: "C:\\Roaming",
231 }).pipe(Effect.provideService(CommandAvailability, () => Effect.succeed(true)));
232 expect(patch).toEqual({ PATH: "C:\\Windows;C:\\Roaming\\npm" });
233 expect(execFile.mock.calls.slice(-2).map(([file]) => file)).toEqual([
234 "pwsh.exe",
235 "powershell.exe",
236 ]);
237 } finally {
238 execFile.mockClear();
239 }
240 }),
241 );
242 });
243
244 effectIt.effect("returns an empty environment after both shell candidates fail", () =>
245 Effect.gen(function* () {
246 const execFile = vi.fn(() => Effect.succeed(Option.none<string>()));
247 expect(yield* readEnvironmentFromWindowsShell(["PATH"], {}, execFile)).toEqual({});
248 expect(execFile).toHaveBeenCalledTimes(2);
249 }),
250 );
251
252 effectIt.effect("does not launch a shell when no variables are requested", () =>
253 Effect.gen(function* () {
254 const execFile = vi.fn(() => Effect.succeed(Option.none<string>()));
255 expect(yield* readEnvironmentFromWindowsShell([], {}, execFile)).toEqual({});
256 expect(execFile).not.toHaveBeenCalled();
257 }),
258 );
259
260 effectIt.effect(
261 "kills the native probe child on interruption without trying the next shell",
262 () =>
263 Effect.gen(function* () {
264 const started = Promise.withResolvers<void>();
265 const kill = vi.fn(() => true);
266 const child = { kill } as unknown as ReturnType<
267 typeof import("node:child_process").execFile
268 >;
269 const execFile = nativeProbe.execFile;
270 execFile.mockClear();
271 execFile.mockImplementationOnce(() => {
272 started.resolve();
273 return child;
274 });
275 try {
276 const fiber = yield* readEnvironmentFromWindowsShell(["PATH"]).pipe(Effect.forkChild);
277 yield* Effect.promise(() => started.promise);
278 yield* Fiber.interrupt(fiber);
279 expect(kill).toHaveBeenCalledTimes(1);
280 expect(execFile).toHaveBeenCalledTimes(1);
281 expect(execFile.mock.calls[0]?.[0]).toBe("pwsh.exe");
282 } finally {
283 execFile.mockClear();
284 }
285 }),
286 );
287
288 effectIt.effect("extracts environment variables from a PowerShell command", () =>
289 Effect.gen(function* () {
290 const execFile = vi.fn<
291 (
292 file: string,
293 args: ReadonlyArray<string>,
294 options: { encoding: "utf8"; timeout: number },
295 ) => string
296 >(
297 () =>
298 "__T3CODE_ENV_PATH_START__\nC:\\Users\\testuser\\AppData\\Roaming\\npm\n__T3CODE_ENV_PATH_END__\n",
299 );
300
301 expect(
302 yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) =>
303 Effect.try(() => execFile(...args)).pipe(Effect.option),
304 ),
305 ).toEqual({
306 PATH: "C:\\Users\\testuser\\AppData\\Roaming\\npm",
307 });
308 expect(execFile).toHaveBeenCalledWith(
309 "pwsh.exe",
310 expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]),
311 { encoding: "utf8", timeout: 5000 },
312 );
313 }),
314 );
315
316 effectIt.effect("strips CRLF delimiters from captured PowerShell values", () =>
317 Effect.gen(function* () {
318 const execFile = vi.fn<
319 (
320 file: string,
321 args: ReadonlyArray<string>,
322 options: { encoding: "utf8"; timeout: number },
323 ) => string
324 >(
325 () =>
326 "__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
327 );
328
329 expect(
330 yield* readEnvironmentFromWindowsShell(["FNM_DIR"], {}, (...args) =>
331 Effect.try(() => execFile(...args)).pipe(Effect.option),
332 ),
333 ).toEqual({
334 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
335 });
336 }),
337 );
338
339 effectIt.effect("omits -NoProfile when loadProfile is enabled", () =>
340 Effect.gen(function* () {
341 const execFile = vi.fn<
342 (
343 file: string,
344 args: ReadonlyArray<string>,
345 options: { encoding: "utf8"; timeout: number },
346 ) => string
347 >(() => "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n");
348
349 expect(
350 yield* readEnvironmentFromWindowsShell(["PATH"], { loadProfile: true }, (...args) =>
351 Effect.try(() => execFile(...args)).pipe(Effect.option),
352 ),
353 ).toEqual({
354 PATH: "C:\\Tools",
355 });
356 expect(execFile).toHaveBeenCalledWith(
357 "pwsh.exe",
358 expect.arrayContaining(["-NoLogo", "-NonInteractive", "-Command"]),
359 { encoding: "utf8", timeout: 5000 },
360 );
361 expect(execFile.mock.calls[0]?.[1]).not.toContain("-NoProfile");
362 }),
363 );
364
365 effectIt.effect("falls back to Windows PowerShell when pwsh.exe is unavailable", () =>
366 Effect.gen(function* () {
367 const execFile = vi.fn<
368 (
369 file: string,
370 args: ReadonlyArray<string>,
371 options: { encoding: "utf8"; timeout: number },
372 ) => string
373 >((file) => {
374 if (file === "pwsh.exe") {
375 throw new Error("spawn pwsh.exe ENOENT");
376 }
377 return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
378 });
379
380 expect(
381 yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) =>
382 Effect.try(() => execFile(...args)).pipe(Effect.option),
383 ),
384 ).toEqual({
385 PATH: "C:\\Tools",
386 });
387 expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
388 encoding: "utf8",
389 timeout: 5000,
390 });
391 expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
392 encoding: "utf8",
393 timeout: 5000,
394 });
395 }),
396 );
397});
398
399describe("mergePathValues", () => {
400 it("sanitizes and dedupes Windows entries while preserving preferred order", () => {
401 expect(
402 mergePathValues(
403 'C:\\Users\\testuser\\AppData\\Roaming\\npm;"C:\\Program Files\\nodejs"',
404 "c:\\users\\testuser\\appdata\\roaming\\npm;C:\\Windows\\System32",
405 "win32",
406 ),
407 ).toBe(
408 "C:\\Users\\testuser\\AppData\\Roaming\\npm;C:\\Program Files\\nodejs;C:\\Windows\\System32",
409 );
410 });
411
412 it("removes stray quotes from Windows entries", () => {
413 expect(
414 mergePathValues(
415 'C:\\Windows\\System32;C:\\cloudflared.exe;C:";C:\\Program Files\\nodejs',
416 undefined,
417 "win32",
418 ),
419 ).toBe("C:\\Windows\\System32;C:\\cloudflared.exe;C:;C:\\Program Files\\nodejs");
420 });
421
422 it("dedupes case-sensitively on POSIX", () => {
423 expect(mergePathValues("/usr/local/bin:/usr/bin", "/usr/bin:/USR/BIN", "linux")).toBe(
424 "/usr/local/bin:/usr/bin:/USR/BIN",
425 );
426 });
427});
428
429effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => {
430 const recordProbes = (env: NodeJS.ProcessEnv) =>
431 Effect.gen(function* () {
432 const probed: Array<string> = [];
433 const result = yield* resolveCommandPath("definitely-not-installed", { env }).pipe(
434 Effect.provideService(HostProcess.Platform, "win32"),
435 Effect.provideService(CommandResolutionCache, new Map()),
436 Effect.provide(
437 FileSystem.layerNoop({
438 stat: (filePath) =>
439 Effect.sync(() => {
440 probed.push(filePath);
441 return { type: "Directory" } as FileSystem.File.Info;
442 }),
443 }),
444 ),
445 );
446
447 expect(result).toBeNull();
448 return probed;
449 });
450
451 it.effect("still visits a PATH entry that differs only in case", () =>
452 Effect.gen(function* () {
453 const probed = yield* recordProbes({
454 PATH: "C:\\bin;C:\\BIN",
455 PATHEXT: ".COM;.EXE",
456 });
457
458 // Windows PATH directories can be case-sensitive; preserve both spellings.
459 expect(probed).toHaveLength(8);
460 }),
461 );
462
463 it.effect.each(["audit-command", "audit-command.CMD"])(
464 "resolves lowercase executable files for %s in a case-sensitive Windows PATH directory",
465 (command) =>
466 Effect.gen(function* () {
467 const fs = yield* FileSystem.FileSystem;
468 const path = yield* Path.Path;
469 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-case-sensitive-path-" });
470 const executable = path.join(cwd, "audit-command.cmd");
471 yield* fs.writeFileString(executable, "@echo off\n");
472
473 const resolved = yield* resolveCommandPath(command, {
474 env: { PATH: cwd, PATHEXT: ".CMD" },
475 }).pipe(
476 Effect.provideService(HostProcess.Platform, "win32"),
477 Effect.provideService(CommandResolutionCache, new Map()),
478 Effect.provideService(FileSystem.FileSystem, {
479 ...fs,
480 stat: (filePath) =>
481 fs.stat(filePath === executable ? filePath : path.join(cwd, "missing")),
482 }),
483 );
484
485 expect(resolved).toBe(executable);
486 }),
487 );
488
489 it.effect("probes only listed PATH names and relists a directory that changes", () =>
490 Effect.gen(function* () {
491 const fs = yield* FileSystem.FileSystem;
492 const path = yield* Path.Path;
493 const first = yield* fs.makeTempDirectoryScoped();
494 const second = yield* fs.makeTempDirectoryScoped();
495 yield* fs.writeFileString(path.join(first, "cursor.CMD"), "");
496 yield* fs.writeFileString(path.join(second, "cursor.EXE"), "");
497 const env = { PATH: `${first};${second}`, PATHEXT: ".EXE;.CMD" };
498 const probed: Array<string> = [];
499 yield* Effect.gen(function* () {
500 expect(yield* resolveCommandPath("cursor", { env })).toBe(path.join(first, "cursor.CMD"));
501 expect(yield* isCommandAvailable("absent", { env })).toBe(false);
502 yield* fs.writeFileString(path.join(second, "late.EXE"), "");
503 yield* fs.utimes(second, 4_102_444_800, 4_102_444_800);
504 expect(yield* resolveCommandPath("late", { env })).toBe(path.join(second, "late.EXE"));
505 }).pipe(
506 withPathDirectoryListings,
507 Effect.provideService(FileSystem.FileSystem, {
508 ...fs,
509 stat: (file) => {
510 if (file !== first && file !== second) probed.push(file);
511 return fs.stat(file);
512 },
513 }),
514 );
515 expect(probed).toEqual([path.join(first, "cursor.CMD"), path.join(second, "late.EXE")]);
516 }).pipe(
517 Effect.provideService(HostProcess.Platform, "win32"),
518 Effect.provideService(CommandResolutionCache, new Map()),
519 ),
520 );
521});
522
523describe("preferGitForWindowsBinary", () => {
524 const files =
525 (...paths: Array<string>) =>
526 (filePath: string) =>
527 paths.includes(filePath);
528
529 it("runs the git.exe Git for Windows' launcher would start", () => {
530 expect(
531 preferGitForWindowsBinary(
532 "C:\\Program Files\\Git\\cmd\\git.EXE",
533 {},
534 files(
535 "C:\\Program Files\\Git\\ucrt64\\bin\\git.exe",
536 "C:\\Program Files\\Git\\mingw64\\bin\\git.exe",
537 ),
538 ),
539 ).toBe("C:\\Program Files\\Git\\ucrt64\\bin\\git.exe");
540 expect(
541 preferGitForWindowsBinary(
542 "D:\\PortableGit\\bin\\git.exe",
543 {},
544 files("D:\\PortableGit\\mingw64\\bin\\git.exe"),
545 ),
546 ).toBe("D:\\PortableGit\\mingw64\\bin\\git.exe");
547 expect(
548 preferGitForWindowsBinary(
549 "C:\\Program Files\\Git\\cmd\\git.exe",
550 {},
551 files("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe"),
552 ),
553 ).toBe("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe");
554 });
555
556 it("keeps the launcher when MSYSTEM is set", () => {
557 // git.exe adds hook dependencies to PATH only when MSYSTEM is unset.
558 expect(
559 preferGitForWindowsBinary(
560 "C:\\Program Files\\Git\\cmd\\git.exe",
561 { MSYSTEM: "MINGW64" },
562 files("C:\\Program Files\\Git\\mingw64\\bin\\git.exe"),
563 ),
564 ).toBe("C:\\Program Files\\Git\\cmd\\git.exe");
565 });
566
567 it("leaves other gits and other launchers alone", () => {
568 const everything = () => true;
569 expect(preferGitForWindowsBinary("C:\\Users\\me\\scoop\\shims\\git.exe", {}, everything)).toBe(
570 "C:\\Users\\me\\scoop\\shims\\git.exe",
571 );
572 expect(preferGitForWindowsBinary("C:\\Program Files\\Git\\cmd\\gitk.exe", {}, everything)).toBe(
573 "C:\\Program Files\\Git\\cmd\\gitk.exe",
574 );
575 });
576});
577
578// Byte for byte what `npm install -g opencode-ai` writes as `opencode.cmd`.
579const NPM_OPENCODE_SHIM = [
580 "@ECHO off",
581 "GOTO start",
582 ":find_dp0",
583 "SET dp0=%~dp0",
584 "EXIT /b",
585 ":start",
586 "SETLOCAL",
587 "CALL :find_dp0",
588 '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',
589 "",
590].join("\r\n");
591
592describe("npmShimExecutable", () => {
593 const shimPath = "C:\\Users\\me\\AppData\\Roaming\\npm\\opencode.cmd";
594 const executable =
595 "C:\\Users\\me\\AppData\\Roaming\\npm\\node_modules\\opencode-ai\\bin\\opencode.exe";
596 const exists = (filePath: string) => filePath === executable;
597
598 it("finds the executable npm's shim runs", () => {
599 expect(npmShimExecutable(shimPath, () => NPM_OPENCODE_SHIM, exists)).toBe(executable);
600 expect(
601 npmShimExecutable(shimPath.replace(".cmd", ".CMD"), () => NPM_OPENCODE_SHIM, exists),
602 ).toBe(executable);
603 });
604
605 it("keeps a shim that does more than run the executable", () => {
606 const withSetting = NPM_OPENCODE_SHIM.replace(
607 "SETLOCAL",
608 "SETLOCAL\r\nSET OPENCODE_CONFIG=C:\\x",
609 );
610 expect(npmShimExecutable(shimPath, () => withSetting, exists)).toBeUndefined();
611 const nodeScript = NPM_OPENCODE_SHIM.replace(
612 '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',
613 '"%_prog%" "%dp0%\\node_modules\\opencode-ai\\bin\\opencode.js" %*',
614 );
615 expect(
616 npmShimExecutable(
617 shimPath,
618 () => nodeScript,
619 () => true,
620 ),
621 ).toBeUndefined();
622 });
623
624 it("keeps a shim CMD would read differently", () => {
625 // CMD preserves trailing SET whitespace, changing the executable path.
626 for (const suffix of ["\u00a0", "\t", " "]) {
627 const altered = NPM_OPENCODE_SHIM.replace("SET dp0=%~dp0", `SET dp0=%~dp0${suffix}`);
628 expect(
629 npmShimExecutable(
630 shimPath,
631 () => altered,
632 () => true,
633 ),
634 ).toBeUndefined();
635 }
636 const nonBreakingSeparator = NPM_OPENCODE_SHIM.replace(
637 'opencode.exe" %*',
638 'opencode.exe"\u00a0%*',
639 );
640 expect(
641 npmShimExecutable(
642 shimPath,
643 () => nonBreakingSeparator,
644 () => true,
645 ),
646 ).toBeUndefined();
647 const indented = NPM_OPENCODE_SHIM.replace("SETLOCAL", " SETLOCAL");
648 expect(
649 npmShimExecutable(
650 shimPath,
651 () => indented,
652 () => true,
653 ),
654 ).toBeUndefined();
655 });
656
657 it("keeps the shim when its executable is missing or it is not a .cmd", () => {
658 expect(
659 npmShimExecutable(
660 shimPath,
661 () => NPM_OPENCODE_SHIM,
662 () => false,
663 ),
664 ).toBeUndefined();
665 expect(
666 npmShimExecutable(
667 shimPath,
668 () => undefined,
669 () => true,
670 ),
671 ).toBeUndefined();
672 expect(
673 npmShimExecutable(
674 shimPath.replace(".cmd", ".bat"),
675 () => NPM_OPENCODE_SHIM,
676 () => true,
677 ),
678 ).toBeUndefined();
679 });
680});
681
682effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
683 it.effect("runs Windows executables directly without a shell", () =>
684 Effect.gen(function* () {
685 const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], {
686 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
687 }).pipe(
688 Effect.provideService(HostProcess.Platform, "win32"),
689 Effect.provideService(CommandResolutionCache, new Map()),
690 );
691
692 expect(command).toEqual({
693 command: "node.exe",
694 args: ["script.js", "hello & goodbye"],
695 shell: false,
696 });
697 }),
698 );
699
700 it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
701 "runs the executable behind an npm shim directly when asked",
702 () =>
703 Effect.scoped(
704 Effect.gen(function* () {
705 const fs = yield* FileSystem.FileSystem;
706 const path = yield* Path.Path;
707 const prefix = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-shim-" });
708 const shim = path.join(prefix, "opencode.cmd");
709 const executable = path.join(
710 prefix,
711 "node_modules",
712 "opencode-ai",
713 "bin",
714 "opencode.exe",
715 );
716 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
717 yield* fs.writeFileString(executable, "");
718 yield* fs.writeFileString(shim, NPM_OPENCODE_SHIM);
719 const resolve = (bypassNpmShim: boolean) =>
720 resolveSpawnCommand("opencode", ["serve", "--port=4096"], {
721 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
722 bypassNpmShim,
723 }).pipe(
724 Effect.provideService(HostProcess.Platform, "win32"),
725 Effect.provideService(CommandResolutionCache, new Map()),
726 Effect.provideService(SpawnExecutableResolution, () => shim),
727 );
728
729 expect(yield* resolve(true)).toEqual({
730 command: executable,
731 args: ["serve", "--port=4096"],
732 shell: false,
733 });
734 expect((yield* resolve(false)).shell).toBe(true);
735 }),
736 ),
737 );
738
739 it.effect("builds one escaped cmd.exe line for Windows command shims", () =>
740 Effect.gen(function* () {
741 const command = yield* resolveSpawnCommand(
742 "vp",
743 [
744 "run",
745 "value & calc",
746 "%PATH%",
747 'quote"value',
748 "C:\\dir with space\\",
749 'slash\\"quote',
750 "x|y<z>^",
751 ],
752 { env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" } },
753 ).pipe(
754 Effect.provideService(HostProcess.Platform, "win32"),
755 Effect.provideService(CommandResolutionCache, new Map()),
756 Effect.provideService(
757 SpawnExecutableResolution,
758 () => "C:\\Program Files\\npm & tools\\vp.cmd",
759 ),
760 );
761
762 // No args alongside `shell: true`: Node prints DEP0190 for that pairing.
763 expect(command).toEqual({
764 command: [
765 String.raw`^"C:\Program^ Files\npm^ ^&^ tools\vp.cmd^"`,
766 String.raw`^"run^"`,
767 String.raw`^"value^ ^&^ calc^"`,
768 String.raw`^"^%PATH^%^"`,
769 String.raw`^"quote\^"value^"`,
770 String.raw`^"C:\dir^ with^ space\\^"`,
771 String.raw`^"slash\\\^"quote^"`,
772 String.raw`^"x^|y^<z^>^^^"`,
773 ].join(" "),
774 args: [],
775 shell: true,
776 });
777 }),
778 );
779
780 it.effect("resolves against the effective environment when extending host env", () =>
781 Effect.gen(function* () {
782 let resolvedEnvironment: NodeJS.ProcessEnv | undefined;
783 yield* resolveSpawnCommand("codex", ["app-server"], {
784 env: { CODEX_HOME: "C:\\Users\\tester\\.codex" },
785 extendEnv: true,
786 }).pipe(
787 Effect.provideService(HostProcess.Platform, "win32"),
788 Effect.provideService(CommandResolutionCache, new Map()),
789 Effect.provideService(HostProcess.Environment, {
790 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
791 PATHEXT: ".COM;.EXE;.BAT;.CMD",
792 }),
793 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) => {
794 resolvedEnvironment = env;
795 return "C:\\Users\\tester\\AppData\\Roaming\\npm\\codex.cmd";
796 }),
797 );
798
799 expect(resolvedEnvironment).toEqual({
800 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
801 PATHEXT: ".COM;.EXE;.BAT;.CMD",
802 CODEX_HOME: "C:\\Users\\tester\\.codex",
803 });
804 }),
805 );
806
807 describe("macOS git", () => {
808 // Files that exist, the git first on PATH, and what `xcrun --find git` prints.
809 const setup = (options: {
810 readonly platform?: NodeJS.Platform;
811 readonly gitOnPath: string;
812 readonly xcrunGit: string | undefined;
813 }) => {
814 const files = new Set([options.gitOnPath, ...(options.xcrunGit ? [options.xcrunGit] : [])]);
815 const host = { xcrunGit: options.xcrunGit, xcrunCalls: 0 };
816 const resolve = resolveSpawnCommand("git", ["status"], { env: { PATH: "/fake/bin" } }).pipe(
817 Effect.map((resolved) => resolved.command),
818 Effect.provideService(HostProcess.Platform, options.platform ?? "darwin"),
819 Effect.provideService(SpawnExecutableResolution, (command) =>
820 command === "git" ? options.gitOnPath : files.has(command) ? command : undefined,
821 ),
822 Effect.provideService(XcodeGitLocation, () => {
823 host.xcrunCalls += 1;
824 return host.xcrunGit;
825 }),
826 );
827 return { files, host, resolve };
828 };
829
830 const XCODE_GIT = "/Applications/Xcode.app/Contents/Developer/usr/bin/git";
831
832 it.effect("runs the git behind the xcrun shim and looks it up once", () =>
833 Effect.gen(function* () {
834 const { host, resolve } = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
835 expect(yield* resolve).toBe(XCODE_GIT);
836 expect(yield* resolve).toBe(XCODE_GIT);
837 expect(host.xcrunCalls).toBe(1);
838 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
839 );
840
841 it.effect("keeps git when PATH has another git or the host is not macOS", () =>
842 Effect.gen(function* () {
843 const homebrew = setup({ gitOnPath: "/opt/homebrew/bin/git", xcrunGit: XCODE_GIT });
844 expect(yield* homebrew.resolve).toBe("git");
845 expect(homebrew.host.xcrunCalls).toBe(0);
846
847 const linux = setup({ platform: "linux", gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
848 expect(yield* linux.resolve).toBe("git");
849 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
850 );
851
852 it.effect("keeps git when xcrun fails or names a missing file", () =>
853 Effect.gen(function* () {
854 const failed = setup({ gitOnPath: "/usr/bin/git", xcrunGit: undefined });
855 expect(yield* failed.resolve).toBe("git");
856
857 const missing = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
858 missing.files.delete(XCODE_GIT);
859 expect(yield* missing.resolve).toBe("git");
860 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
861 );
862
863 it.effect("looks again when the resolved git disappears", () =>
864 Effect.gen(function* () {
865 const betaGit = "/Applications/Xcode-beta.app/Contents/Developer/usr/bin/git";
866 const { files, host, resolve } = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
867 expect(yield* resolve).toBe(XCODE_GIT);
868
869 files.delete(XCODE_GIT);
870 files.add(betaGit);
871 host.xcrunGit = betaGit;
872 expect(yield* resolve).toBe(betaGit);
873 expect(host.xcrunCalls).toBe(2);
874 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
875 );
876 });
877
878 it.effect("does not fall back to a shell for unresolved Windows commands", () =>
879 Effect.gen(function* () {
880 const command = yield* resolveSpawnCommand("missing & calc", ["unsafe & value"], {
881 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
882 }).pipe(
883 Effect.provideService(HostProcess.Platform, "win32"),
884 Effect.provideService(CommandResolutionCache, new Map()),
885 );
886
887 expect(command).toEqual({
888 command: "missing & calc",
889 args: ["unsafe & value"],
890 shell: false,
891 });
892 }),
893 );
894});
895
896effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => {
897 it.effect("uses known CLI directories as a fallback without changing shell PATH priority", () =>
898 Effect.gen(function* () {
899 const readEnvironment = vi.fn(
900 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
901 options?.loadProfile
902 ? { PATH: "C:\\Profile\\Bin" }
903 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
904 );
905 const commandAvailable = vi.fn(() => Effect.succeed(true));
906
907 expect(
908 yield* withWindowsEnvironmentMocks(
909 resolveWindowsEnvironment({
910 PATH: "C:\\Windows\\System32",
911 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
912 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
913 USERPROFILE: "C:\\Users\\testuser",
914 }),
915 readEnvironment,
916 commandAvailable,
917 ),
918 ).toEqual({
919 PATH: [
920 "C:\\Shell\\Bin",
921 "C:\\Windows\\System32",
922 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
923 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
924 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
925 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
926 "C:\\Users\\testuser\\.local\\bin",
927 "C:\\Users\\testuser\\.bun\\bin",
928 "C:\\Users\\testuser\\scoop\\shims",
929 ].join(";"),
930 });
931 expect(readEnvironment).toHaveBeenCalledTimes(1);
932 expect(readEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
933 expect(commandAvailable).toHaveBeenCalledWith(
934 "node",
935 expect.objectContaining({ env: expect.any(Object) }),
936 );
937 }),
938 );
939
940 it.effect(
941 "probes node with one PATH key when inherited environment records have mixed casing",
942 () =>
943 Effect.gen(function* () {
944 const probedEnvironments: Array<NodeJS.ProcessEnv | undefined> = [];
945
946 yield* withWindowsEnvironmentMocks(
947 resolveWindowsEnvironment({ Path: "C:\\Stale", PATH: "C:\\Windows\\System32" }),
948 () => ({ PATH: "C:\\Shell\\Bin" }),
949 (_command, options) =>
950 Effect.sync(() => {
951 probedEnvironments.push(options?.env);
952 return true;
953 }),
954 );
955
956 const pathEntries = Object.entries(probedEnvironments[0] ?? {}).filter(
957 ([key]) => key.toUpperCase() === "PATH",
958 );
959 expect(pathEntries).toEqual([["PATH", "C:\\Shell\\Bin;C:\\Windows\\System32"]]);
960 }),
961 );
962
963 it.effect("loads the PowerShell profile when baseline env cannot resolve node", () =>
964 Effect.gen(function* () {
965 const readEnvironment = vi.fn(
966 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
967 options?.loadProfile
968 ? {
969 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
970 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
971 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
972 }
973 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
974 );
975 const commandAvailable = vi.fn(() => Effect.succeed(false));
976
977 expect(
978 yield* withWindowsEnvironmentMocks(
979 resolveWindowsEnvironment({
980 PATH: "C:\\Windows\\System32",
981 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
982 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
983 USERPROFILE: "C:\\Users\\testuser",
984 }),
985 readEnvironment,
986 commandAvailable,
987 ),
988 ).toEqual({
989 PATH: [
990 "C:\\Profile\\Node",
991 "C:\\Windows\\System32",
992 "C:\\Shell\\Bin",
993 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
994 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
995 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
996 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
997 "C:\\Users\\testuser\\.local\\bin",
998 "C:\\Users\\testuser\\.bun\\bin",
999 "C:\\Users\\testuser\\scoop\\shims",
1000 ].join(";"),
1001 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
1002 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
1003 });
1004 expect(readEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
1005 expect(readEnvironment).toHaveBeenNthCalledWith(
1006 2,
1007 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
1008 {
1009 loadProfile: true,
1010 },
1011 );
1012 expect(commandAvailable).toHaveBeenCalledTimes(1);
1013 }),
1014 );
1015
1016 it.effect("keeps the baseline env when profiled probe still does not resolve node", () =>
1017 Effect.gen(function* () {
1018 const readEnvironment = vi.fn(
1019 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
1020 options?.loadProfile ? { FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm" } : {},
1021 );
1022 const commandAvailable = vi.fn(() => Effect.succeed(false));
1023
1024 expect(
1025 yield* withWindowsEnvironmentMocks(
1026 resolveWindowsEnvironment({
1027 PATH: "C:\\Windows\\System32",
1028 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
1029 USERPROFILE: "C:\\Users\\testuser",
1030 }),
1031 readEnvironment,
1032 commandAvailable,
1033 ),
1034 ).toEqual({
1035 PATH: [
1036 "C:\\Windows\\System32",
1037 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
1038 "C:\\Users\\testuser\\.local\\bin",
1039 "C:\\Users\\testuser\\.bun\\bin",
1040 "C:\\Users\\testuser\\scoop\\shims",
1041 ].join(";"),
1042 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
1043 });
1044 expect(commandAvailable).toHaveBeenCalledTimes(1);
1045 }),
1046 );
1047});