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