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