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