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