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

shell.test.ts

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