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