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

shell.test.ts

1,303 lines46.5 KB

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