Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

shell.test.ts

1,051 lines36.3 KB

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 10+ can mark a directory case-sensitive, so the two spellings
459 // are not provably one directory and skipping the second could hide a
460 // command that is really there.
461 expect(probed).toHaveLength(8);
462 }),
463 );
464​
465 it.effect.each(["audit-command", "audit-command.CMD"])(
466 "resolves lowercase executable files for %s in a case-sensitive Windows PATH directory",
467 (command) =>
468 Effect.gen(function* () {
469 const fs = yield* FileSystem.FileSystem;
470 const path = yield* Path.Path;
471 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-case-sensitive-path-" });
472 const executable = path.join(cwd, "audit-command.cmd");
473 yield* fs.writeFileString(executable, "@echo off\n");
474​
475 const resolved = yield* resolveCommandPath(command, {
476 env: { PATH: cwd, PATHEXT: ".CMD" },
477 }).pipe(
478 Effect.provideService(HostProcess.Platform, "win32"),
479 Effect.provideService(CommandResolutionCache, new Map()),
480 Effect.provideService(FileSystem.FileSystem, {
481 ...fs,
482 stat: (filePath) =>
483 fs.stat(filePath === executable ? filePath : path.join(cwd, "missing")),
484 }),
485 );
486​
487 expect(resolved).toBe(executable);
488 }),
489 );
490​
491 it.effect("probes only listed PATH names and relists a directory that changes", () =>
492 Effect.gen(function* () {
493 const fs = yield* FileSystem.FileSystem;
494 const path = yield* Path.Path;
495 const first = yield* fs.makeTempDirectoryScoped();
496 const second = yield* fs.makeTempDirectoryScoped();
497 yield* fs.writeFileString(path.join(first, "cursor.CMD"), "");
498 yield* fs.writeFileString(path.join(second, "cursor.EXE"), "");
499 const env = { PATH: `${first};${second}`, PATHEXT: ".EXE;.CMD" };
500 const probed: Array<string> = [];
501 yield* Effect.gen(function* () {
502 expect(yield* resolveCommandPath("cursor", { env })).toBe(path.join(first, "cursor.CMD"));
503 expect(yield* isCommandAvailable("absent", { env })).toBe(false);
504 yield* fs.writeFileString(path.join(second, "late.EXE"), "");
505 yield* fs.utimes(second, 4_102_444_800, 4_102_444_800);
506 expect(yield* resolveCommandPath("late", { env })).toBe(path.join(second, "late.EXE"));
507 }).pipe(
508 withPathDirectoryListings,
509 Effect.provideService(FileSystem.FileSystem, {
510 ...fs,
511 stat: (file) => {
512 if (file !== first && file !== second) probed.push(file);
513 return fs.stat(file);
514 },
515 }),
516 );
517 expect(probed).toEqual([path.join(first, "cursor.CMD"), path.join(second, "late.EXE")]);
518 }).pipe(
519 Effect.provideService(HostProcess.Platform, "win32"),
520 Effect.provideService(CommandResolutionCache, new Map()),
521 ),
522 );
523});
524​
525describe("preferGitForWindowsBinary", () => {
526 const files =
527 (...paths: Array<string>) =>
528 (filePath: string) =>
529 paths.includes(filePath);
530​
531 it("runs the git.exe Git for Windows' launcher would start", () => {
532 expect(
533 preferGitForWindowsBinary(
534 "C:\\Program Files\\Git\\cmd\\git.EXE",
535 {},
536 files(
537 "C:\\Program Files\\Git\\ucrt64\\bin\\git.exe",
538 "C:\\Program Files\\Git\\mingw64\\bin\\git.exe",
539 ),
540 ),
541 ).toBe("C:\\Program Files\\Git\\ucrt64\\bin\\git.exe");
542 expect(
543 preferGitForWindowsBinary(
544 "D:\\PortableGit\\bin\\git.exe",
545 {},
546 files("D:\\PortableGit\\mingw64\\bin\\git.exe"),
547 ),
548 ).toBe("D:\\PortableGit\\mingw64\\bin\\git.exe");
549 expect(
550 preferGitForWindowsBinary(
551 "C:\\Program Files\\Git\\cmd\\git.exe",
552 {},
553 files("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe"),
554 ),
555 ).toBe("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe");
556 });
557​
558 it("keeps the launcher when MSYSTEM is set", () => {
559 // The real git.exe only adds its own folders to PATH when MSYSTEM is unset;
560 // without them a `#!/bin/sh` hook cannot start.
561 expect(
562 preferGitForWindowsBinary(
563 "C:\\Program Files\\Git\\cmd\\git.exe",
564 { MSYSTEM: "MINGW64" },
565 files("C:\\Program Files\\Git\\mingw64\\bin\\git.exe"),
566 ),
567 ).toBe("C:\\Program Files\\Git\\cmd\\git.exe");
568 });
569​
570 it("leaves other gits and other launchers alone", () => {
571 const everything = () => true;
572 expect(preferGitForWindowsBinary("C:\\Users\\me\\scoop\\shims\\git.exe", {}, everything)).toBe(
573 "C:\\Users\\me\\scoop\\shims\\git.exe",
574 );
575 expect(preferGitForWindowsBinary("C:\\Program Files\\Git\\cmd\\gitk.exe", {}, everything)).toBe(
576 "C:\\Program Files\\Git\\cmd\\gitk.exe",
577 );
578 });
579});
580​
581// Byte for byte what `npm install -g opencode-ai` writes as `opencode.cmd`.
582const NPM_OPENCODE_SHIM = [
583 "@ECHO off",
584 "GOTO start",
585 ":find_dp0",
586 "SET dp0=%~dp0",
587 "EXIT /b",
588 ":start",
589 "SETLOCAL",
590 "CALL :find_dp0",
591 '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',
592 "",
593].join("\r\n");
594​
595describe("npmShimExecutable", () => {
596 const shimPath = "C:\\Users\\me\\AppData\\Roaming\\npm\\opencode.cmd";
597 const executable =
598 "C:\\Users\\me\\AppData\\Roaming\\npm\\node_modules\\opencode-ai\\bin\\opencode.exe";
599 const exists = (filePath: string) => filePath === executable;
600​
601 it("finds the executable npm's shim runs", () => {
602 expect(npmShimExecutable(shimPath, () => NPM_OPENCODE_SHIM, exists)).toBe(executable);
603 expect(
604 npmShimExecutable(shimPath.replace(".cmd", ".CMD"), () => NPM_OPENCODE_SHIM, exists),
605 ).toBe(executable);
606 });
607​
608 it("keeps a shim that does more than run the executable", () => {
609 const withSetting = NPM_OPENCODE_SHIM.replace(
610 "SETLOCAL",
611 "SETLOCAL\r\nSET OPENCODE_CONFIG=C:\\x",
612 );
613 expect(npmShimExecutable(shimPath, () => withSetting, exists)).toBeUndefined();
614 const nodeScript = NPM_OPENCODE_SHIM.replace(
615 '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',
616 '"%_prog%" "%dp0%\\node_modules\\opencode-ai\\bin\\opencode.js" %*',
617 );
618 expect(
619 npmShimExecutable(
620 shimPath,
621 () => nodeScript,
622 () => true,
623 ),
624 ).toBeUndefined();
625 });
626​
627 it("keeps a shim CMD would read differently", () => {
628 // CMD keeps trailing characters in an unquoted `SET` value, so these point
629 // `dp0`, and with it the executable, somewhere else.
630 for (const suffix of ["\u00a0", "\t", " "]) {
631 const altered = NPM_OPENCODE_SHIM.replace("SET dp0=%~dp0", `SET dp0=%~dp0${suffix}`);
632 expect(
633 npmShimExecutable(
634 shimPath,
635 () => altered,
636 () => true,
637 ),
638 ).toBeUndefined();
639 }
640 const nonBreakingSeparator = NPM_OPENCODE_SHIM.replace(
641 'opencode.exe" %*',
642 'opencode.exe"\u00a0%*',
643 );
644 expect(
645 npmShimExecutable(
646 shimPath,
647 () => nonBreakingSeparator,
648 () => true,
649 ),
650 ).toBeUndefined();
651 const indented = NPM_OPENCODE_SHIM.replace("SETLOCAL", " SETLOCAL");
652 expect(
653 npmShimExecutable(
654 shimPath,
655 () => indented,
656 () => true,
657 ),
658 ).toBeUndefined();
659 });
660​
661 it("keeps the shim when its executable is missing or it is not a .cmd", () => {
662 expect(
663 npmShimExecutable(
664 shimPath,
665 () => NPM_OPENCODE_SHIM,
666 () => false,
667 ),
668 ).toBeUndefined();
669 expect(
670 npmShimExecutable(
671 shimPath,
672 () => undefined,
673 () => true,
674 ),
675 ).toBeUndefined();
676 expect(
677 npmShimExecutable(
678 shimPath.replace(".cmd", ".bat"),
679 () => NPM_OPENCODE_SHIM,
680 () => true,
681 ),
682 ).toBeUndefined();
683 });
684});
685​
686effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
687 it.effect("runs Windows executables directly without a shell", () =>
688 Effect.gen(function* () {
689 const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], {
690 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
691 }).pipe(
692 Effect.provideService(HostProcess.Platform, "win32"),
693 Effect.provideService(CommandResolutionCache, new Map()),
694 );
695​
696 expect(command).toEqual({
697 command: "node.exe",
698 args: ["script.js", "hello & goodbye"],
699 shell: false,
700 });
701 }),
702 );
703​
704 it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
705 "runs the executable behind an npm shim directly when asked",
706 () =>
707 Effect.scoped(
708 Effect.gen(function* () {
709 const fs = yield* FileSystem.FileSystem;
710 const path = yield* Path.Path;
711 const prefix = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-shim-" });
712 const shim = path.join(prefix, "opencode.cmd");
713 const executable = path.join(
714 prefix,
715 "node_modules",
716 "opencode-ai",
717 "bin",
718 "opencode.exe",
719 );
720 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
721 yield* fs.writeFileString(executable, "");
722 yield* fs.writeFileString(shim, NPM_OPENCODE_SHIM);
723 const resolve = (bypassNpmShim: boolean) =>
724 resolveSpawnCommand("opencode", ["serve", "--port=4096"], {
725 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
726 bypassNpmShim,
727 }).pipe(
728 Effect.provideService(HostProcess.Platform, "win32"),
729 Effect.provideService(CommandResolutionCache, new Map()),
730 Effect.provideService(SpawnExecutableResolution, () => shim),
731 );
732​
733 expect(yield* resolve(true)).toEqual({
734 command: executable,
735 args: ["serve", "--port=4096"],
736 shell: false,
737 });
738 expect((yield* resolve(false)).shell).toBe(true);
739 }),
740 ),
741 );
742​
743 it.effect("builds one escaped cmd.exe line for Windows command shims", () =>
744 Effect.gen(function* () {
745 const command = yield* resolveSpawnCommand(
746 "vp",
747 [
748 "run",
749 "value & calc",
750 "%PATH%",
751 'quote"value',
752 "C:\\dir with space\\",
753 'slash\\"quote',
754 "x|y<z>^",
755 ],
756 { env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" } },
757 ).pipe(
758 Effect.provideService(HostProcess.Platform, "win32"),
759 Effect.provideService(CommandResolutionCache, new Map()),
760 Effect.provideService(
761 SpawnExecutableResolution,
762 () => "C:\\Program Files\\npm & tools\\vp.cmd",
763 ),
764 );
765​
766 // No args alongside `shell: true`: Node prints DEP0190 for that pairing.
767 expect(command).toEqual({
768 command: [
769 String.raw`^"C:\Program^ Files\npm^ ^&^ tools\vp.cmd^"`,
770 String.raw`^"run^"`,
771 String.raw`^"value^ ^&^ calc^"`,
772 String.raw`^"^%PATH^%^"`,
773 String.raw`^"quote\^"value^"`,
774 String.raw`^"C:\dir^ with^ space\\^"`,
775 String.raw`^"slash\\\^"quote^"`,
776 String.raw`^"x^|y^<z^>^^^"`,
777 ].join(" "),
778 args: [],
779 shell: true,
780 });
781 }),
782 );
783​
784 it.effect("resolves against the effective environment when extending host env", () =>
785 Effect.gen(function* () {
786 let resolvedEnvironment: NodeJS.ProcessEnv | undefined;
787 yield* resolveSpawnCommand("codex", ["app-server"], {
788 env: { CODEX_HOME: "C:\\Users\\tester\\.codex" },
789 extendEnv: true,
790 }).pipe(
791 Effect.provideService(HostProcess.Platform, "win32"),
792 Effect.provideService(CommandResolutionCache, new Map()),
793 Effect.provideService(HostProcess.Environment, {
794 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
795 PATHEXT: ".COM;.EXE;.BAT;.CMD",
796 }),
797 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) => {
798 resolvedEnvironment = env;
799 return "C:\\Users\\tester\\AppData\\Roaming\\npm\\codex.cmd";
800 }),
801 );
802​
803 expect(resolvedEnvironment).toEqual({
804 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
805 PATHEXT: ".COM;.EXE;.BAT;.CMD",
806 CODEX_HOME: "C:\\Users\\tester\\.codex",
807 });
808 }),
809 );
810​
811 describe("macOS git", () => {
812 // Files that exist, the git first on PATH, and what `xcrun --find git` prints.
813 const setup = (options: {
814 readonly platform?: NodeJS.Platform;
815 readonly gitOnPath: string;
816 readonly xcrunGit: string | undefined;
817 }) => {
818 const files = new Set([options.gitOnPath, ...(options.xcrunGit ? [options.xcrunGit] : [])]);
819 const host = { xcrunGit: options.xcrunGit, xcrunCalls: 0 };
820 const resolve = resolveSpawnCommand("git", ["status"], { env: { PATH: "/fake/bin" } }).pipe(
821 Effect.map((resolved) => resolved.command),
822 Effect.provideService(HostProcess.Platform, options.platform ?? "darwin"),
823 Effect.provideService(SpawnExecutableResolution, (command) =>
824 command === "git" ? options.gitOnPath : files.has(command) ? command : undefined,
825 ),
826 Effect.provideService(XcodeGitLocation, () => {
827 host.xcrunCalls += 1;
828 return host.xcrunGit;
829 }),
830 );
831 return { files, host, resolve };
832 };
833​
834 const XCODE_GIT = "/Applications/Xcode.app/Contents/Developer/usr/bin/git";
835​
836 it.effect("runs the git behind the xcrun shim and looks it up once", () =>
837 Effect.gen(function* () {
838 const { host, resolve } = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
839 expect(yield* resolve).toBe(XCODE_GIT);
840 expect(yield* resolve).toBe(XCODE_GIT);
841 expect(host.xcrunCalls).toBe(1);
842 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
843 );
844​
845 it.effect("keeps git when PATH has another git or the host is not macOS", () =>
846 Effect.gen(function* () {
847 const homebrew = setup({ gitOnPath: "/opt/homebrew/bin/git", xcrunGit: XCODE_GIT });
848 expect(yield* homebrew.resolve).toBe("git");
849 expect(homebrew.host.xcrunCalls).toBe(0);
850​
851 const linux = setup({ platform: "linux", gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
852 expect(yield* linux.resolve).toBe("git");
853 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
854 );
855​
856 it.effect("keeps git when xcrun fails or names a missing file", () =>
857 Effect.gen(function* () {
858 const failed = setup({ gitOnPath: "/usr/bin/git", xcrunGit: undefined });
859 expect(yield* failed.resolve).toBe("git");
860​
861 const missing = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
862 missing.files.delete(XCODE_GIT);
863 expect(yield* missing.resolve).toBe("git");
864 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
865 );
866​
867 it.effect("looks again when the resolved git disappears", () =>
868 Effect.gen(function* () {
869 const betaGit = "/Applications/Xcode-beta.app/Contents/Developer/usr/bin/git";
870 const { files, host, resolve } = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
871 expect(yield* resolve).toBe(XCODE_GIT);
872​
873 files.delete(XCODE_GIT);
874 files.add(betaGit);
875 host.xcrunGit = betaGit;
876 expect(yield* resolve).toBe(betaGit);
877 expect(host.xcrunCalls).toBe(2);
878 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
879 );
880 });
881​
882 it.effect("does not fall back to a shell for unresolved Windows commands", () =>
883 Effect.gen(function* () {
884 const command = yield* resolveSpawnCommand("missing & calc", ["unsafe & value"], {
885 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
886 }).pipe(
887 Effect.provideService(HostProcess.Platform, "win32"),
888 Effect.provideService(CommandResolutionCache, new Map()),
889 );
890​
891 expect(command).toEqual({
892 command: "missing & calc",
893 args: ["unsafe & value"],
894 shell: false,
895 });
896 }),
897 );
898});
899​
900effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => {
901 it.effect("uses known CLI directories as a fallback without changing shell PATH priority", () =>
902 Effect.gen(function* () {
903 const readEnvironment = vi.fn(
904 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
905 options?.loadProfile
906 ? { PATH: "C:\\Profile\\Bin" }
907 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
908 );
909 const commandAvailable = vi.fn(() => Effect.succeed(true));
910​
911 expect(
912 yield* withWindowsEnvironmentMocks(
913 resolveWindowsEnvironment({
914 PATH: "C:\\Windows\\System32",
915 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
916 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
917 USERPROFILE: "C:\\Users\\testuser",
918 }),
919 readEnvironment,
920 commandAvailable,
921 ),
922 ).toEqual({
923 PATH: [
924 "C:\\Shell\\Bin",
925 "C:\\Windows\\System32",
926 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
927 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
928 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
929 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
930 "C:\\Users\\testuser\\.local\\bin",
931 "C:\\Users\\testuser\\.bun\\bin",
932 "C:\\Users\\testuser\\scoop\\shims",
933 ].join(";"),
934 });
935 expect(readEnvironment).toHaveBeenCalledTimes(1);
936 expect(readEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
937 expect(commandAvailable).toHaveBeenCalledWith(
938 "node",
939 expect.objectContaining({ env: expect.any(Object) }),
940 );
941 }),
942 );
943​
944 it.effect(
945 "probes node with one PATH key when inherited environment records have mixed casing",
946 () =>
947 Effect.gen(function* () {
948 const probedEnvironments: Array<NodeJS.ProcessEnv | undefined> = [];
949​
950 yield* withWindowsEnvironmentMocks(
951 resolveWindowsEnvironment({ Path: "C:\\Stale", PATH: "C:\\Windows\\System32" }),
952 () => ({ PATH: "C:\\Shell\\Bin" }),
953 (_command, options) =>
954 Effect.sync(() => {
955 probedEnvironments.push(options?.env);
956 return true;
957 }),
958 );
959​
960 const pathEntries = Object.entries(probedEnvironments[0] ?? {}).filter(
961 ([key]) => key.toUpperCase() === "PATH",
962 );
963 expect(pathEntries).toEqual([["PATH", "C:\\Shell\\Bin;C:\\Windows\\System32"]]);
964 }),
965 );
966​
967 it.effect("loads the PowerShell profile when baseline env cannot resolve node", () =>
968 Effect.gen(function* () {
969 const readEnvironment = vi.fn(
970 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
971 options?.loadProfile
972 ? {
973 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
974 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
975 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
976 }
977 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
978 );
979 const commandAvailable = vi.fn(() => Effect.succeed(false));
980​
981 expect(
982 yield* withWindowsEnvironmentMocks(
983 resolveWindowsEnvironment({
984 PATH: "C:\\Windows\\System32",
985 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
986 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
987 USERPROFILE: "C:\\Users\\testuser",
988 }),
989 readEnvironment,
990 commandAvailable,
991 ),
992 ).toEqual({
993 PATH: [
994 "C:\\Profile\\Node",
995 "C:\\Windows\\System32",
996 "C:\\Shell\\Bin",
997 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
998 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
999 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
1000 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
1001 "C:\\Users\\testuser\\.local\\bin",
1002 "C:\\Users\\testuser\\.bun\\bin",
1003 "C:\\Users\\testuser\\scoop\\shims",
1004 ].join(";"),
1005 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
1006 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
1007 });
1008 expect(readEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
1009 expect(readEnvironment).toHaveBeenNthCalledWith(
1010 2,
1011 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
1013 loadProfile: true,
1014 },
1015 );
1016 expect(commandAvailable).toHaveBeenCalledTimes(1);
1017 }),
1018 );
1019​
1020 it.effect("keeps the baseline env when profiled probe still does not resolve node", () =>
1021 Effect.gen(function* () {
1022 const readEnvironment = vi.fn(
1023 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
1024 options?.loadProfile ? { FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm" } : {},
1025 );
1026 const commandAvailable = vi.fn(() => Effect.succeed(false));
1027​
1028 expect(
1029 yield* withWindowsEnvironmentMocks(
1030 resolveWindowsEnvironment({
1031 PATH: "C:\\Windows\\System32",
1032 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
1033 USERPROFILE: "C:\\Users\\testuser",
1034 }),
1035 readEnvironment,
1036 commandAvailable,
1037 ),
1038 ).toEqual({
1039 PATH: [
1040 "C:\\Windows\\System32",
1041 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
1042 "C:\\Users\\testuser\\.local\\bin",
1043 "C:\\Users\\testuser\\.bun\\bin",
1044 "C:\\Users\\testuser\\scoop\\shims",
1045 ].join(";"),
1046 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
1047 });
1048 expect(commandAvailable).toHaveBeenCalledTimes(1);
1049 }),
1050 );
1051});