The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // @effect-diagnostics nodeBuiltinImport:off -- The synchronous shell probe runs real commands with isolated config files. |
| 2 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 3 | import { it as effectIt } from "@effect/vitest"; |
| 4 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 5 | import { DesktopHostTelemetryMessage } from "@t3tools/contracts"; |
| 6 | import * as Schema from "effect/Schema"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Fiber from "effect/Fiber"; |
| 9 | import * as FileSystem from "effect/FileSystem"; |
| 10 | import * as Path from "effect/Path"; |
| 11 | import * as Option from "effect/Option"; |
| 12 | import * as TestClock from "effect/testing/TestClock"; |
| 13 | import * as NodeChildProcess from "node:child_process"; |
| 14 | import * as NodeFS from "node:fs"; |
| 15 | import * as NodeOS from "node:os"; |
| 16 | import * as NodePath from "node:path"; |
| 17 | import { describe, expect, it, vi } from "vite-plus/test"; |
| 18 | |
| 19 | import { |
| 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 | |
| 46 | const decodeDesktopHostMessage = Schema.decodeUnknownSync(DesktopHostTelemetryMessage); |
| 47 | |
| 48 | const 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 | |
| 53 | vi.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 | |
| 59 | const 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 | |
| 73 | describe("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 | |
| 241 | describe("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 | |
| 250 | describe("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 | |
| 261 | describe("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 | |
| 273 | describe("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 | |
| 503 | describe("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 | expect(mergePathValues('/opt/bin"', "/opt/bin", "linux")).toBe('/opt/bin":/opt/bin'); |
| 534 | }); |
| 535 | }); |
| 536 | |
| 537 | effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { |
| 538 | // Windows rejects `"` in file names. |
| 539 | it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( |
| 540 | "finds executables in a POSIX PATH directory ending in whitespace and quotes", |
| 541 | () => |
| 542 | Effect.gen(function* () { |
| 543 | const fs = yield* FileSystem.FileSystem; |
| 544 | const path = yield* Path.Path; |
| 545 | const cwd = yield* fs.makeTempDirectoryScoped({ directory: ".", prefix: "t3-path-" }); |
| 546 | const directory = `${cwd}/bin \u00a0"`; |
| 547 | yield* fs.makeDirectory(directory); |
| 548 | const executable = `${directory}/audit-command`; |
| 549 | yield* fs.writeFileString(executable, "#!/bin/sh\n"); |
| 550 | yield* fs.chmod(executable, 0o755); |
| 551 | const env = { PATH: directory }; |
| 552 | |
| 553 | expect( |
| 554 | yield* resolveCommandPath("audit-command", { env }).pipe( |
| 555 | Effect.provideService(HostProcess.Platform, "linux"), |
| 556 | Effect.provideService(CommandResolutionCache, new Map()), |
| 557 | ), |
| 558 | ).toBe(path.join(directory, "audit-command")); |
| 559 | const resolveExecutable = yield* SpawnExecutableResolution; |
| 560 | expect(resolveExecutable("audit-command", "linux", env)).toBe(executable); |
| 561 | }), |
| 562 | ); |
| 563 | |
| 564 | const recordProbes = (env: NodeJS.ProcessEnv) => |
| 565 | Effect.gen(function* () { |
| 566 | const probed: Array<string> = []; |
| 567 | const result = yield* resolveCommandPath("definitely-not-installed", { env }).pipe( |
| 568 | Effect.provideService(HostProcess.Platform, "win32"), |
| 569 | Effect.provideService(CommandResolutionCache, new Map()), |
| 570 | Effect.provide( |
| 571 | FileSystem.layerNoop({ |
| 572 | stat: (filePath) => |
| 573 | Effect.sync(() => { |
| 574 | probed.push(filePath); |
| 575 | return { type: "Directory" } as FileSystem.File.Info; |
| 576 | }), |
| 577 | }), |
| 578 | ), |
| 579 | ); |
| 580 | |
| 581 | expect(result).toBeNull(); |
| 582 | return probed; |
| 583 | }); |
| 584 | |
| 585 | it.effect("still visits a PATH entry that differs only in case", () => |
| 586 | Effect.gen(function* () { |
| 587 | const probed = yield* recordProbes({ |
| 588 | PATH: "C:\\bin;C:\\BIN", |
| 589 | PATHEXT: ".COM;.EXE", |
| 590 | }); |
| 591 | |
| 592 | // Windows PATH directories can be case-sensitive; preserve both spellings. |
| 593 | expect(probed).toHaveLength(8); |
| 594 | }), |
| 595 | ); |
| 596 | |
| 597 | it.effect.each(["audit-command", "audit-command.CMD"])( |
| 598 | "resolves lowercase executable files for %s in a case-sensitive Windows PATH directory", |
| 599 | (command) => |
| 600 | Effect.gen(function* () { |
| 601 | const fs = yield* FileSystem.FileSystem; |
| 602 | const path = yield* Path.Path; |
| 603 | const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-case-sensitive-path-" }); |
| 604 | const executable = path.join(cwd, "audit-command.cmd"); |
| 605 | yield* fs.writeFileString(executable, "@echo off\n"); |
| 606 | |
| 607 | const decoy = path.join(cwd, "audit-command.exe"); |
| 608 | yield* fs.writeFileString(decoy, ""); |
| 609 | for (const key of ["PATHEXT", "PathExt", "pathext"]) { |
| 610 | const resolved = yield* resolveCommandPath(command, { |
| 611 | env: { PATH: cwd, [key]: ".CMD" }, |
| 612 | }).pipe( |
| 613 | Effect.provideService(HostProcess.Platform, "win32"), |
| 614 | Effect.provideService(CommandResolutionCache, new Map()), |
| 615 | Effect.provideService(FileSystem.FileSystem, { |
| 616 | ...fs, |
| 617 | stat: (filePath) => |
| 618 | fs.stat( |
| 619 | filePath === executable || filePath === decoy |
| 620 | ? filePath |
| 621 | : path.join(cwd, "missing"), |
| 622 | ), |
| 623 | }), |
| 624 | ); |
| 625 | expect(resolved).toBe(executable); |
| 626 | } |
| 627 | }), |
| 628 | ); |
| 629 | |
| 630 | it.effect("probes only listed PATH names and relists a directory that changes", () => |
| 631 | Effect.gen(function* () { |
| 632 | const fs = yield* FileSystem.FileSystem; |
| 633 | const path = yield* Path.Path; |
| 634 | const first = yield* fs.makeTempDirectoryScoped(); |
| 635 | const second = yield* fs.makeTempDirectoryScoped(); |
| 636 | yield* fs.writeFileString(path.join(first, "cursor.CMD"), ""); |
| 637 | yield* fs.writeFileString(path.join(second, "cursor.EXE"), ""); |
| 638 | const env = { PATH: `${first};${second}`, PATHEXT: ".EXE;.CMD" }; |
| 639 | const probed: Array<string> = []; |
| 640 | yield* Effect.gen(function* () { |
| 641 | expect(yield* resolveCommandPath("cursor", { env })).toBe(path.join(first, "cursor.CMD")); |
| 642 | expect(yield* isCommandAvailable("absent", { env })).toBe(false); |
| 643 | yield* fs.writeFileString(path.join(second, "late.EXE"), ""); |
| 644 | yield* fs.utimes(second, 4_102_444_800, 4_102_444_800); |
| 645 | expect(yield* resolveCommandPath("late", { env })).toBe(path.join(second, "late.EXE")); |
| 646 | }).pipe( |
| 647 | withPathDirectoryListings, |
| 648 | Effect.provideService(FileSystem.FileSystem, { |
| 649 | ...fs, |
| 650 | stat: (file) => { |
| 651 | if (file !== first && file !== second) probed.push(file); |
| 652 | return fs.stat(file); |
| 653 | }, |
| 654 | }), |
| 655 | ); |
| 656 | expect(probed).toEqual([path.join(first, "cursor.CMD"), path.join(second, "late.EXE")]); |
| 657 | }).pipe( |
| 658 | Effect.provideService(HostProcess.Platform, "win32"), |
| 659 | Effect.provideService(CommandResolutionCache, new Map()), |
| 660 | ), |
| 661 | ); |
| 662 | }); |
| 663 | |
| 664 | describe("runsGitWithoutConsole", () => { |
| 665 | const git = "C:\\Program Files\\Git\\ucrt64\\bin\\git.exe"; |
| 666 | |
| 667 | it.each([ |
| 668 | [["rev-parse", "--git-path", "index"], true], |
| 669 | [ |
| 670 | [ |
| 671 | "rev-parse", |
| 672 | "--path-format=absolute", |
| 673 | "--git-path", |
| 674 | "index", |
| 675 | "--git-common-dir", |
| 676 | "--show-toplevel", |
| 677 | ], |
| 678 | true, |
| 679 | ], |
| 680 | [["--git-dir", "C:\\repo\\.git", "symbolic-ref", "refs/remotes/origin/HEAD"], true], |
| 681 | [["remote", "get-url", "--", "origin"], true], |
| 682 | [["config", "--get", "branch.main.pushRemote"], true], |
| 683 | [["symbolic-ref", "--quiet", "HEAD"], true], |
| 684 | [["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], true], |
| 685 | [["rev-parse", "HEAD"], false], |
| 686 | [["symbolic-ref", "HEAD", "refs/heads/x"], false], |
| 687 | [["symbolic-ref", "-qd", "refs/remotes/origin/HEAD"], false], |
| 688 | [["config", "--get", "--edit"], false], |
| 689 | [["-c", "core.pager=x", "config", "--get", "user.name"], false], |
| 690 | ])("Git for Windows %j without a console: %s", (args, expected) => { |
| 691 | expect(runsGitWithoutConsole("win32", git, args)).toBe(expected); |
| 692 | }); |
| 693 | |
| 694 | it.each([ |
| 695 | ["win32", "C:\\Program Files\\Git\\cmd\\git.exe"], |
| 696 | ["win32", "C:\\Users\\x\\scoop\\shims\\git.exe"], |
| 697 | ["linux", git], |
| 698 | ] as const)("keeps the console on %s for %s", (platform, executable) => { |
| 699 | expect(runsGitWithoutConsole(platform, executable, ["rev-parse", "--show-toplevel"])).toBe( |
| 700 | false, |
| 701 | ); |
| 702 | }); |
| 703 | }); |
| 704 | |
| 705 | describe("preferGitForWindowsBinary", () => { |
| 706 | const files = |
| 707 | (...paths: Array<string>) => |
| 708 | (filePath: string) => |
| 709 | paths.includes(filePath); |
| 710 | |
| 711 | it("runs the git.exe Git for Windows' launcher would start", () => { |
| 712 | expect( |
| 713 | preferGitForWindowsBinary( |
| 714 | "C:\\Program Files\\Git\\cmd\\git.EXE", |
| 715 | {}, |
| 716 | files( |
| 717 | "C:\\Program Files\\Git\\ucrt64\\bin\\git.exe", |
| 718 | "C:\\Program Files\\Git\\mingw64\\bin\\git.exe", |
| 719 | ), |
| 720 | ), |
| 721 | ).toBe("C:\\Program Files\\Git\\ucrt64\\bin\\git.exe"); |
| 722 | expect( |
| 723 | preferGitForWindowsBinary( |
| 724 | "D:\\PortableGit\\bin\\git.exe", |
| 725 | {}, |
| 726 | files("D:\\PortableGit\\mingw64\\bin\\git.exe"), |
| 727 | ), |
| 728 | ).toBe("D:\\PortableGit\\mingw64\\bin\\git.exe"); |
| 729 | expect( |
| 730 | preferGitForWindowsBinary( |
| 731 | "C:\\Program Files\\Git\\cmd\\git.exe", |
| 732 | {}, |
| 733 | files("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe"), |
| 734 | ), |
| 735 | ).toBe("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe"); |
| 736 | }); |
| 737 | |
| 738 | it("keeps the launcher when MSYSTEM is set", () => { |
| 739 | // git.exe adds hook dependencies to PATH only when MSYSTEM is unset. |
| 740 | expect( |
| 741 | preferGitForWindowsBinary( |
| 742 | "C:\\Program Files\\Git\\cmd\\git.exe", |
| 743 | { MSYSTEM: "MINGW64" }, |
| 744 | files("C:\\Program Files\\Git\\mingw64\\bin\\git.exe"), |
| 745 | ), |
| 746 | ).toBe("C:\\Program Files\\Git\\cmd\\git.exe"); |
| 747 | }); |
| 748 | |
| 749 | it("leaves other gits and other launchers alone", () => { |
| 750 | const everything = () => true; |
| 751 | expect(preferGitForWindowsBinary("C:\\Users\\me\\scoop\\shims\\git.exe", {}, everything)).toBe( |
| 752 | "C:\\Users\\me\\scoop\\shims\\git.exe", |
| 753 | ); |
| 754 | expect(preferGitForWindowsBinary("C:\\Program Files\\Git\\cmd\\gitk.exe", {}, everything)).toBe( |
| 755 | "C:\\Program Files\\Git\\cmd\\gitk.exe", |
| 756 | ); |
| 757 | }); |
| 758 | }); |
| 759 | |
| 760 | // Byte for byte what `npm install -g opencode-ai` writes as `opencode.cmd`. |
| 761 | const NPM_OPENCODE_SHIM = [ |
| 762 | "@ECHO off", |
| 763 | "GOTO start", |
| 764 | ":find_dp0", |
| 765 | "SET dp0=%~dp0", |
| 766 | "EXIT /b", |
| 767 | ":start", |
| 768 | "SETLOCAL", |
| 769 | "CALL :find_dp0", |
| 770 | '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*', |
| 771 | "", |
| 772 | ].join("\r\n"); |
| 773 | |
| 774 | describe("npmShimExecutable", () => { |
| 775 | const shimPath = "C:\\Users\\me\\AppData\\Roaming\\npm\\opencode.cmd"; |
| 776 | const executable = |
| 777 | "C:\\Users\\me\\AppData\\Roaming\\npm\\node_modules\\opencode-ai\\bin\\opencode.exe"; |
| 778 | const exists = (filePath: string) => filePath === executable; |
| 779 | |
| 780 | it("finds the executable npm's shim runs", () => { |
| 781 | expect(npmShimExecutable(shimPath, () => NPM_OPENCODE_SHIM, exists)).toBe(executable); |
| 782 | expect( |
| 783 | npmShimExecutable(shimPath.replace(".cmd", ".CMD"), () => NPM_OPENCODE_SHIM, exists), |
| 784 | ).toBe(executable); |
| 785 | }); |
| 786 | |
| 787 | it("keeps a shim that does more than run the executable", () => { |
| 788 | const withSetting = NPM_OPENCODE_SHIM.replace( |
| 789 | "SETLOCAL", |
| 790 | "SETLOCAL\r\nSET OPENCODE_CONFIG=C:\\x", |
| 791 | ); |
| 792 | expect(npmShimExecutable(shimPath, () => withSetting, exists)).toBeUndefined(); |
| 793 | const nodeScript = NPM_OPENCODE_SHIM.replace( |
| 794 | '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*', |
| 795 | '"%_prog%" "%dp0%\\node_modules\\opencode-ai\\bin\\opencode.js" %*', |
| 796 | ); |
| 797 | expect( |
| 798 | npmShimExecutable( |
| 799 | shimPath, |
| 800 | () => nodeScript, |
| 801 | () => true, |
| 802 | ), |
| 803 | ).toBeUndefined(); |
| 804 | }); |
| 805 | |
| 806 | it("keeps a shim CMD would read differently", () => { |
| 807 | // CMD preserves trailing SET whitespace, changing the executable path. |
| 808 | for (const suffix of ["\u00a0", "\t", " "]) { |
| 809 | const altered = NPM_OPENCODE_SHIM.replace("SET dp0=%~dp0", `SET dp0=%~dp0${suffix}`); |
| 810 | expect( |
| 811 | npmShimExecutable( |
| 812 | shimPath, |
| 813 | () => altered, |
| 814 | () => true, |
| 815 | ), |
| 816 | ).toBeUndefined(); |
| 817 | } |
| 818 | const nonBreakingSeparator = NPM_OPENCODE_SHIM.replace( |
| 819 | 'opencode.exe" %*', |
| 820 | 'opencode.exe"\u00a0%*', |
| 821 | ); |
| 822 | expect( |
| 823 | npmShimExecutable( |
| 824 | shimPath, |
| 825 | () => nonBreakingSeparator, |
| 826 | () => true, |
| 827 | ), |
| 828 | ).toBeUndefined(); |
| 829 | const indented = NPM_OPENCODE_SHIM.replace("SETLOCAL", " SETLOCAL"); |
| 830 | expect( |
| 831 | npmShimExecutable( |
| 832 | shimPath, |
| 833 | () => indented, |
| 834 | () => true, |
| 835 | ), |
| 836 | ).toBeUndefined(); |
| 837 | }); |
| 838 | |
| 839 | it("keeps the shim when its executable is missing or it is not a .cmd", () => { |
| 840 | expect( |
| 841 | npmShimExecutable( |
| 842 | shimPath, |
| 843 | () => NPM_OPENCODE_SHIM, |
| 844 | () => false, |
| 845 | ), |
| 846 | ).toBeUndefined(); |
| 847 | expect( |
| 848 | npmShimExecutable( |
| 849 | shimPath, |
| 850 | () => undefined, |
| 851 | () => true, |
| 852 | ), |
| 853 | ).toBeUndefined(); |
| 854 | expect( |
| 855 | npmShimExecutable( |
| 856 | shimPath.replace(".cmd", ".bat"), |
| 857 | () => NPM_OPENCODE_SHIM, |
| 858 | () => true, |
| 859 | ), |
| 860 | ).toBeUndefined(); |
| 861 | }); |
| 862 | }); |
| 863 | |
| 864 | effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { |
| 865 | it.effect("runs Windows executables directly without a shell", () => |
| 866 | Effect.gen(function* () { |
| 867 | const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], { |
| 868 | env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" }, |
| 869 | }).pipe( |
| 870 | Effect.provideService(HostProcess.Platform, "win32"), |
| 871 | Effect.provideService(CommandResolutionCache, new Map()), |
| 872 | ); |
| 873 | |
| 874 | expect(command).toEqual({ |
| 875 | command: "node.exe", |
| 876 | args: ["script.js", "hello & goodbye"], |
| 877 | shell: false, |
| 878 | }); |
| 879 | }), |
| 880 | ); |
| 881 | |
| 882 | it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")( |
| 883 | "runs the executable behind an npm shim directly when asked", |
| 884 | () => |
| 885 | Effect.gen(function* () { |
| 886 | const fs = yield* FileSystem.FileSystem; |
| 887 | const path = yield* Path.Path; |
| 888 | const prefix = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-shim-" }); |
| 889 | const shim = path.join(prefix, "opencode.cmd"); |
| 890 | const executable = path.join(prefix, "node_modules", "opencode-ai", "bin", "opencode.exe"); |
| 891 | yield* fs.makeDirectory(path.dirname(executable), { recursive: true }); |
| 892 | yield* fs.writeFileString(executable, ""); |
| 893 | yield* fs.writeFileString(shim, NPM_OPENCODE_SHIM); |
| 894 | const resolve = (bypassNpmShim: boolean) => |
| 895 | resolveSpawnCommand("opencode", ["serve", "--port=4096"], { |
| 896 | env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" }, |
| 897 | bypassNpmShim, |
| 898 | }).pipe( |
| 899 | Effect.provideService(HostProcess.Platform, "win32"), |
| 900 | Effect.provideService(CommandResolutionCache, new Map()), |
| 901 | Effect.provideService(SpawnExecutableResolution, () => shim), |
| 902 | ); |
| 903 | |
| 904 | expect(yield* resolve(true)).toEqual({ |
| 905 | command: executable, |
| 906 | args: ["serve", "--port=4096"], |
| 907 | shell: false, |
| 908 | }); |
| 909 | expect((yield* resolve(false)).shell).toBe(true); |
| 910 | }), |
| 911 | ); |
| 912 | |
| 913 | it.effect("builds one escaped cmd.exe line for Windows command shims", () => |
| 914 | Effect.gen(function* () { |
| 915 | const command = yield* resolveSpawnCommand( |
| 916 | "vp", |
| 917 | [ |
| 918 | "run", |
| 919 | "value & calc", |
| 920 | "%PATH%", |
| 921 | 'quote"value', |
| 922 | "C:\\dir with space\\", |
| 923 | 'slash\\"quote', |
| 924 | "x|y<z>^", |
| 925 | ], |
| 926 | { env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" } }, |
| 927 | ).pipe( |
| 928 | Effect.provideService(HostProcess.Platform, "win32"), |
| 929 | Effect.provideService(CommandResolutionCache, new Map()), |
| 930 | Effect.provideService( |
| 931 | SpawnExecutableResolution, |
| 932 | () => "C:\\Program Files\\npm & tools\\vp.cmd", |
| 933 | ), |
| 934 | ); |
| 935 | |
| 936 | // No args alongside `shell: true`: Node prints DEP0190 for that pairing. |
| 937 | expect(command).toEqual({ |
| 938 | command: [ |
| 939 | String.raw`^"C:\Program^ Files\npm^ ^&^ tools\vp.cmd^"`, |
| 940 | String.raw`^"run^"`, |
| 941 | String.raw`^"value^ ^&^ calc^"`, |
| 942 | String.raw`^"^%PATH^%^"`, |
| 943 | String.raw`^"quote\^"value^"`, |
| 944 | String.raw`^"C:\dir^ with^ space\\^"`, |
| 945 | String.raw`^"slash\\\^"quote^"`, |
| 946 | String.raw`^"x^|y^<z^>^^^"`, |
| 947 | ].join(" "), |
| 948 | args: [], |
| 949 | shell: true, |
| 950 | }); |
| 951 | }), |
| 952 | ); |
| 953 | |
| 954 | it.effect("resolves against the effective environment when extending host env", () => |
| 955 | Effect.gen(function* () { |
| 956 | let resolvedEnvironment: NodeJS.ProcessEnv | undefined; |
| 957 | yield* resolveSpawnCommand("codex", ["app-server"], { |
| 958 | env: { CODEX_HOME: "C:\\Users\\tester\\.codex" }, |
| 959 | extendEnv: true, |
| 960 | }).pipe( |
| 961 | Effect.provideService(HostProcess.Platform, "win32"), |
| 962 | Effect.provideService(CommandResolutionCache, new Map()), |
| 963 | Effect.provideService(HostProcess.Environment, { |
| 964 | PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm", |
| 965 | PATHEXT: ".COM;.EXE;.BAT;.CMD", |
| 966 | }), |
| 967 | Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) => { |
| 968 | resolvedEnvironment = env; |
| 969 | return "C:\\Users\\tester\\AppData\\Roaming\\npm\\codex.cmd"; |
| 970 | }), |
| 971 | ); |
| 972 | |
| 973 | expect(resolvedEnvironment).toEqual({ |
| 974 | PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm", |
| 975 | PATHEXT: ".COM;.EXE;.BAT;.CMD", |
| 976 | CODEX_HOME: "C:\\Users\\tester\\.codex", |
| 977 | }); |
| 978 | }), |
| 979 | ); |
| 980 | |
| 981 | describe("macOS git", () => { |
| 982 | // Files that exist, the git first on PATH, and what `xcrun --find git` prints. |
| 983 | const setup = (options: { |
| 984 | readonly platform?: NodeJS.Platform; |
| 985 | readonly gitOnPath: string; |
| 986 | readonly xcrunGit: string | undefined; |
| 987 | }) => { |
| 988 | const files = new Set([options.gitOnPath, ...(options.xcrunGit ? [options.xcrunGit] : [])]); |
| 989 | const host = { xcrunGit: options.xcrunGit, xcrunCalls: 0 }; |
| 990 | const resolve = resolveSpawnCommand("git", ["status"], { env: { PATH: "/fake/bin" } }).pipe( |
| 991 | Effect.map((resolved) => resolved.command), |
| 992 | Effect.provideService(HostProcess.Platform, options.platform ?? "darwin"), |
| 993 | Effect.provideService(SpawnExecutableResolution, (command) => |
| 994 | command === "git" ? options.gitOnPath : files.has(command) ? command : undefined, |
| 995 | ), |
| 996 | Effect.provideService(XcodeGitLocation, () => { |
| 997 | host.xcrunCalls += 1; |
| 998 | return host.xcrunGit; |
| 999 | }), |
| 1000 | ); |
| 1001 | return { files, host, resolve }; |
| 1002 | }; |
| 1003 | |
| 1004 | const XCODE_GIT = "/Applications/Xcode.app/Contents/Developer/usr/bin/git"; |
| 1005 | |
| 1006 | it.effect("runs the git behind the xcrun shim and looks it up once", () => |
| 1007 | Effect.gen(function* () { |
| 1008 | const { host, resolve } = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT }); |
| 1009 | expect(yield* resolve).toBe(XCODE_GIT); |
| 1010 | expect(yield* resolve).toBe(XCODE_GIT); |
| 1011 | expect(host.xcrunCalls).toBe(1); |
| 1012 | }).pipe(Effect.provideService(CommandResolutionCache, new Map())), |
| 1013 | ); |
| 1014 | |
| 1015 | it.effect("keeps git when PATH has another git or the host is not macOS", () => |
| 1016 | Effect.gen(function* () { |
| 1017 | const homebrew = setup({ gitOnPath: "/opt/homebrew/bin/git", xcrunGit: XCODE_GIT }); |
| 1018 | expect(yield* homebrew.resolve).toBe("git"); |
| 1019 | expect(homebrew.host.xcrunCalls).toBe(0); |
| 1020 | |
| 1021 | const linux = setup({ platform: "linux", gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT }); |
| 1022 | expect(yield* linux.resolve).toBe("git"); |
| 1023 | }).pipe(Effect.provideService(CommandResolutionCache, new Map())), |
| 1024 | ); |
| 1025 | |
| 1026 | it.effect("keeps git when xcrun fails or names a missing file", () => |
| 1027 | Effect.gen(function* () { |
| 1028 | const failed = setup({ gitOnPath: "/usr/bin/git", xcrunGit: undefined }); |
| 1029 | expect(yield* failed.resolve).toBe("git"); |
| 1030 | |
| 1031 | const missing = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT }); |
| 1032 | missing.files.delete(XCODE_GIT); |
| 1033 | expect(yield* missing.resolve).toBe("git"); |
| 1034 | }).pipe(Effect.provideService(CommandResolutionCache, new Map())), |
| 1035 | ); |
| 1036 | |
| 1037 | it.effect("looks again when the resolved git disappears", () => |
| 1038 | Effect.gen(function* () { |
| 1039 | const betaGit = "/Applications/Xcode-beta.app/Contents/Developer/usr/bin/git"; |
| 1040 | const { files, host, resolve } = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT }); |
| 1041 | expect(yield* resolve).toBe(XCODE_GIT); |
| 1042 | |
| 1043 | files.delete(XCODE_GIT); |
| 1044 | files.add(betaGit); |
| 1045 | host.xcrunGit = betaGit; |
| 1046 | expect(yield* resolve).toBe(betaGit); |
| 1047 | expect(host.xcrunCalls).toBe(2); |
| 1048 | }).pipe(Effect.provideService(CommandResolutionCache, new Map())), |
| 1049 | ); |
| 1050 | }); |
| 1051 | |
| 1052 | it.effect("does not fall back to a shell for unresolved Windows commands", () => |
| 1053 | Effect.gen(function* () { |
| 1054 | const command = yield* resolveSpawnCommand("missing & calc", ["unsafe & value"], { |
| 1055 | env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" }, |
| 1056 | }).pipe( |
| 1057 | Effect.provideService(HostProcess.Platform, "win32"), |
| 1058 | Effect.provideService(CommandResolutionCache, new Map()), |
| 1059 | ); |
| 1060 | |
| 1061 | expect(command).toEqual({ |
| 1062 | command: "missing & calc", |
| 1063 | args: ["unsafe & value"], |
| 1064 | shell: false, |
| 1065 | }); |
| 1066 | }), |
| 1067 | ); |
| 1068 | }); |
| 1069 | |
| 1070 | effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => { |
| 1071 | it.effect("uses known CLI directories as a fallback without changing shell PATH priority", () => |
| 1072 | Effect.gen(function* () { |
| 1073 | const readEnvironment = vi.fn( |
| 1074 | (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) => |
| 1075 | options?.loadProfile |
| 1076 | ? { PATH: "C:\\Profile\\Bin" } |
| 1077 | : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" }, |
| 1078 | ); |
| 1079 | const commandAvailable = vi.fn(() => Effect.succeed(true)); |
| 1080 | |
| 1081 | expect( |
| 1082 | yield* withWindowsEnvironmentMocks( |
| 1083 | resolveWindowsEnvironment({ |
| 1084 | PATH: "C:\\Windows\\System32", |
| 1085 | APPDATA: "C:\\Users\\testuser\\AppData\\Roaming", |
| 1086 | LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local", |
| 1087 | USERPROFILE: "C:\\Users\\testuser", |
| 1088 | }), |
| 1089 | readEnvironment, |
| 1090 | commandAvailable, |
| 1091 | ), |
| 1092 | ).toEqual({ |
| 1093 | PATH: [ |
| 1094 | "C:\\Shell\\Bin", |
| 1095 | "C:\\Windows\\System32", |
| 1096 | "C:\\Users\\testuser\\AppData\\Roaming\\npm", |
| 1097 | "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs", |
| 1098 | "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin", |
| 1099 | "C:\\Users\\testuser\\AppData\\Local\\pnpm", |
| 1100 | "C:\\Users\\testuser\\.local\\bin", |
| 1101 | "C:\\Users\\testuser\\.bun\\bin", |
| 1102 | "C:\\Users\\testuser\\scoop\\shims", |
| 1103 | ].join(";"), |
| 1104 | }); |
| 1105 | expect(readEnvironment).toHaveBeenCalledTimes(1); |
| 1106 | expect(readEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false }); |
| 1107 | expect(commandAvailable).toHaveBeenCalledWith( |
| 1108 | "node", |
| 1109 | expect.objectContaining({ env: expect.any(Object) }), |
| 1110 | ); |
| 1111 | }), |
| 1112 | ); |
| 1113 | |
| 1114 | it.effect( |
| 1115 | "probes node with one PATH key when inherited environment records have mixed casing", |
| 1116 | () => |
| 1117 | Effect.gen(function* () { |
| 1118 | const probedEnvironments: Array<NodeJS.ProcessEnv | undefined> = []; |
| 1119 | |
| 1120 | yield* withWindowsEnvironmentMocks( |
| 1121 | resolveWindowsEnvironment({ Path: "C:\\Stale", PATH: "C:\\Windows\\System32" }), |
| 1122 | () => ({ PATH: "C:\\Shell\\Bin" }), |
| 1123 | (_command, options) => |
| 1124 | Effect.sync(() => { |
| 1125 | probedEnvironments.push(options?.env); |
| 1126 | return true; |
| 1127 | }), |
| 1128 | ); |
| 1129 | |
| 1130 | const pathEntries = Object.entries(probedEnvironments[0] ?? {}).filter( |
| 1131 | ([key]) => key.toUpperCase() === "PATH", |
| 1132 | ); |
| 1133 | expect(pathEntries).toEqual([["PATH", "C:\\Shell\\Bin;C:\\Windows\\System32"]]); |
| 1134 | }), |
| 1135 | ); |
| 1136 | |
| 1137 | it.effect("loads the PowerShell profile when baseline env cannot resolve node", () => |
| 1138 | Effect.gen(function* () { |
| 1139 | const readEnvironment = vi.fn( |
| 1140 | (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) => |
| 1141 | options?.loadProfile |
| 1142 | ? { |
| 1143 | PATH: "C:\\Profile\\Node;C:\\Windows\\System32", |
| 1144 | FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm", |
| 1145 | FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123", |
| 1146 | } |
| 1147 | : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" }, |
| 1148 | ); |
| 1149 | const commandAvailable = vi.fn(() => Effect.succeed(false)); |
| 1150 | |
| 1151 | expect( |
| 1152 | yield* withWindowsEnvironmentMocks( |
| 1153 | resolveWindowsEnvironment({ |
| 1154 | PATH: "C:\\Windows\\System32", |
| 1155 | APPDATA: "C:\\Users\\testuser\\AppData\\Roaming", |
| 1156 | LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local", |
| 1157 | USERPROFILE: "C:\\Users\\testuser", |
| 1158 | }), |
| 1159 | readEnvironment, |
| 1160 | commandAvailable, |
| 1161 | ), |
| 1162 | ).toEqual({ |
| 1163 | PATH: [ |
| 1164 | "C:\\Profile\\Node", |
| 1165 | "C:\\Windows\\System32", |
| 1166 | "C:\\Shell\\Bin", |
| 1167 | "C:\\Users\\testuser\\AppData\\Roaming\\npm", |
| 1168 | "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs", |
| 1169 | "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin", |
| 1170 | "C:\\Users\\testuser\\AppData\\Local\\pnpm", |
| 1171 | "C:\\Users\\testuser\\.local\\bin", |
| 1172 | "C:\\Users\\testuser\\.bun\\bin", |
| 1173 | "C:\\Users\\testuser\\scoop\\shims", |
| 1174 | ].join(";"), |
| 1175 | FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm", |
| 1176 | FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123", |
| 1177 | }); |
| 1178 | expect(readEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false }); |
| 1179 | expect(readEnvironment).toHaveBeenNthCalledWith( |
| 1180 | 2, |
| 1181 | ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"], |
| 1182 | { |
| 1183 | loadProfile: true, |
| 1184 | }, |
| 1185 | ); |
| 1186 | expect(commandAvailable).toHaveBeenCalledTimes(1); |
| 1187 | }), |
| 1188 | ); |
| 1189 | |
| 1190 | it.effect("keeps the baseline env when profiled probe still does not resolve node", () => |
| 1191 | Effect.gen(function* () { |
| 1192 | const readEnvironment = vi.fn( |
| 1193 | (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) => |
| 1194 | options?.loadProfile ? { FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm" } : {}, |
| 1195 | ); |
| 1196 | const commandAvailable = vi.fn(() => Effect.succeed(false)); |
| 1197 | |
| 1198 | expect( |
| 1199 | yield* withWindowsEnvironmentMocks( |
| 1200 | resolveWindowsEnvironment({ |
| 1201 | PATH: "C:\\Windows\\System32", |
| 1202 | APPDATA: "C:\\Users\\testuser\\AppData\\Roaming", |
| 1203 | USERPROFILE: "C:\\Users\\testuser", |
| 1204 | }), |
| 1205 | readEnvironment, |
| 1206 | commandAvailable, |
| 1207 | ), |
| 1208 | ).toEqual({ |
| 1209 | PATH: [ |
| 1210 | "C:\\Windows\\System32", |
| 1211 | "C:\\Users\\testuser\\AppData\\Roaming\\npm", |
| 1212 | "C:\\Users\\testuser\\.local\\bin", |
| 1213 | "C:\\Users\\testuser\\.bun\\bin", |
| 1214 | "C:\\Users\\testuser\\scoop\\shims", |
| 1215 | ].join(";"), |
| 1216 | FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm", |
| 1217 | }); |
| 1218 | expect(commandAvailable).toHaveBeenCalledTimes(1); |
| 1219 | }), |
| 1220 | ); |
| 1221 | }); |
| 1222 | |
| 1223 | describe("desktop shell environment updates", () => { |
| 1224 | it.each(["win32", "linux", "darwin"] as const)( |
| 1225 | "applies shell updates with %s PATH semantics", |
| 1226 | (platform) => { |
| 1227 | const message = decodeDesktopHostMessage({ |
| 1228 | version: 1, |
| 1229 | type: "shellEnvironment", |
| 1230 | discovered: true, |
| 1231 | platform, |
| 1232 | environment: { |
| 1233 | PATH: "C:\\fresh", |
| 1234 | FNM_DIR: null, |
| 1235 | __MISE_DIFF: null, |
| 1236 | SSH_AUTH_SOCK: "/current.sock", |
| 1237 | NODE_OPTIONS: "--bad", |
| 1238 | }, |
| 1239 | }); |
| 1240 | expect(message.type).toBe("shellEnvironment"); |
| 1241 | if (message.type !== "shellEnvironment") throw new Error("Expected shell environment update"); |
| 1242 | const env: NodeJS.ProcessEnv = { |
| 1243 | Path: "C:\\stale", |
| 1244 | FNM_DIR: "stale", |
| 1245 | __MISE_DIFF: "stale", |
| 1246 | UNRELATED: "keep", |
| 1247 | }; |
| 1248 | applyShellEnvironment(env, message.environment, platform); |
| 1249 | expect(env).toEqual({ |
| 1250 | PATH: "C:\\fresh", |
| 1251 | ...(platform === "win32" ? {} : { Path: "C:\\stale" }), |
| 1252 | SSH_AUTH_SOCK: "/current.sock", |
| 1253 | UNRELATED: "keep", |
| 1254 | }); |
| 1255 | env.Path = "C:\\stale"; |
| 1256 | env.path = "C:\\other"; |
| 1257 | applyShellEnvironment(env, { PATH: null, SSH_AUTH_SOCK: null }, platform); |
| 1258 | expect(env).toEqual({ |
| 1259 | ...(platform === "win32" ? {} : { Path: "C:\\stale", path: "C:\\other" }), |
| 1260 | UNRELATED: "keep", |
| 1261 | }); |
| 1262 | }, |
| 1263 | ); |
| 1264 | }); |
| 1265 | |
| 1266 | describe("pathSetupCommand", () => { |
| 1267 | // Undefined where a pasted line could break things: Windows (it would flatten %VAR% entries in |
| 1268 | // the registry PATH), macOS bash (several startup files), other shells, and unsafe paths. |
| 1269 | it.each([ |
| 1270 | [ |
| 1271 | "/home/theo/.local/bin", |
| 1272 | "/bin/bash", |
| 1273 | "linux", |
| 1274 | `printf '\\n%s\\n' 'export PATH="$PATH:/home/theo/.local/bin"' >> ~/.bashrc`, |
| 1275 | ], |
| 1276 | [ |
| 1277 | "/Users/theo/.local/bin", |
| 1278 | "/usr/bin/fish", |
| 1279 | "linux", |
| 1280 | `mkdir -p ~/.config/fish && printf '\\n%s\\n' 'fish_add_path --append --path $HOME/.local/bin' >> ~/.config/fish/config.fish`, |
| 1281 | ], |
| 1282 | [ |
| 1283 | "/opt/t3/bin", |
| 1284 | "/bin/zsh", |
| 1285 | "linux", |
| 1286 | `printf '\\n%s\\n' 'export PATH="$PATH:/opt/t3/bin"' >> ~/.zshrc`, |
| 1287 | ], |
| 1288 | ["/Users/theo/.local/bin", "/bin/tcsh", "darwin", undefined], |
| 1289 | ["/Users/theo/.local/bin", "/bin/bash", "darwin", undefined], |
| 1290 | ["C:\\Users\\theo\\.local\\bin", "pwsh", "win32", undefined], |
| 1291 | ["/Users/theo/it's here", "/bin/zsh", "darwin", undefined], |
| 1292 | ["/opt/a$PWD/bin", "/bin/zsh", "linux", undefined], |
| 1293 | // Relative: PATH would follow the working directory into any checkout's `bin`. |
| 1294 | ["bin", "/bin/zsh", "linux", undefined], |
| 1295 | ] as const)("%s with %s on %s", (directory, shell, platform, expected) => { |
| 1296 | expect(pathSetupCommand({ directory, home: "/Users/theo", shell, platform })).toBe(expected); |
| 1297 | }); |
| 1298 | |
| 1299 | it("writes the startup file fish and zsh read, under XDG_CONFIG_HOME or ZDOTDIR", () => { |
| 1300 | const setup = { directory: "/opt/t3/bin", home: "/home/theo", shell: "/usr/bin/fish" } as const; |
| 1301 | expect(pathSetup({ ...setup, platform: "linux", configHome: "/home/theo/cfg" })?.file).toBe( |
| 1302 | "/home/theo/cfg/fish/config.fish", |
| 1303 | ); |
| 1304 | expect(pathSetup({ ...setup, platform: "linux" })?.file).toBe("~/.config/fish/config.fish"); |
| 1305 | // zsh reads .zshrc from ZDOTDIR when it is set. |
| 1306 | expect( |
| 1307 | pathSetup({ ...setup, shell: "/bin/zsh", platform: "darwin", zdotdir: "/Users/theo/.zsh" }) |
| 1308 | ?.file, |
| 1309 | ).toBe("/Users/theo/.zsh/.zshrc"); |
| 1310 | // A set folder that cannot be written safely means no setup, never the unread default. |
| 1311 | expect( |
| 1312 | pathSetup({ ...setup, shell: "/bin/zsh", platform: "darwin", zdotdir: "/Users/theo/my zsh" }), |
| 1313 | ).toBeUndefined(); |
| 1314 | expect( |
| 1315 | pathSetup({ ...setup, platform: "linux", configHome: "/home/theo/my cfg" }), |
| 1316 | ).toBeUndefined(); |
| 1317 | }); |
| 1318 | }); |