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

shell.test.ts

576 lines19.2 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { it as effectIt } from "@effect/vitest";
3import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
4import * as Effect from "effect/Effect";
5import { describe, expect, it, vi } from "vite-plus/test";
6​
7import {
8 extractPathFromShellOutput,
9 CommandAvailability,
10 type CommandAvailabilityChecker,
11 isCommandAvailable,
12 listLoginShellCandidates,
13 mergePathEntries,
14 mergePathValues,
15 readEnvironmentFromLoginShell,
16 readEnvironmentFromWindowsShell,
17 readPathFromLaunchctl,
18 readPathFromLoginShell,
19 resolveCommandPath,
20 resolveKnownWindowsCliDirs,
21 resolveSpawnCommand,
22 resolveWindowsEnvironment,
23 SpawnExecutableResolution,
24 WindowsShellEnvironment,
25 type WindowsShellEnvironmentReader,
26} from "./shell.ts";
27​
28const withWindowsEnvironmentMocks = <A, E, R>(
29 effect: Effect.Effect<A, E, R>,
30 readEnvironment: WindowsShellEnvironmentReader,
31 commandAvailable: CommandAvailabilityChecker,
32) =>
33 effect.pipe(
34 Effect.provideService(WindowsShellEnvironment, readEnvironment),
35 Effect.provideService(CommandAvailability, commandAvailable),
36 );
37​
38describe("extractPathFromShellOutput", () => {
39 it("extracts the path between capture markers", () => {
40 expect(
41 extractPathFromShellOutput(
42 "__T3CODE_PATH_START__\n/opt/homebrew/bin:/usr/bin\n__T3CODE_PATH_END__\n",
43 ),
44 ).toBe("/opt/homebrew/bin:/usr/bin");
45 });
46​
47 it("ignores shell startup noise around the capture markers", () => {
48 expect(
49 extractPathFromShellOutput(
50 "Welcome to fish\n__T3CODE_PATH_START__\n/opt/homebrew/bin:/usr/bin\n__T3CODE_PATH_END__\nBye\n",
51 ),
52 ).toBe("/opt/homebrew/bin:/usr/bin");
53 });
54​
55 it("returns null when the markers are missing", () => {
56 expect(extractPathFromShellOutput("/opt/homebrew/bin /usr/bin")).toBeNull();
57 });
58});
59​
60describe("readPathFromLoginShell", () => {
61 it("uses a shell-agnostic printenv PATH probe", () => {
62 const execFile = vi.fn<
63 (
64 file: string,
65 args: ReadonlyArray<string>,
66 options: { encoding: "utf8"; timeout: number },
67 ) => string
68 >(() => "__T3CODE_ENV_PATH_START__\n/a:/b\n__T3CODE_ENV_PATH_END__\n");
69​
70 expect(readPathFromLoginShell("/opt/homebrew/bin/fish", execFile)).toBe("/a:/b");
71 expect(execFile).toHaveBeenCalledTimes(1);
72​
73 const firstCall = execFile.mock.calls[0] as
74 | [string, ReadonlyArray<string>, { encoding: "utf8"; timeout: number }]
75 | undefined;
76 expect(firstCall).toBeDefined();
77 if (!firstCall) {
78 throw new Error("Expected execFile to be called");
79 }
80​
81 const [shell, args, options] = firstCall;
82 expect(shell).toBe("/opt/homebrew/bin/fish");
83 expect(args).toHaveLength(2);
84 expect(args?.[0]).toBe("-ilc");
85 expect(args?.[1]).toContain("printenv PATH || true");
86 expect(args?.[1]).toContain("__T3CODE_ENV_PATH_START__");
87 expect(args?.[1]).toContain("__T3CODE_ENV_PATH_END__");
88 expect(options).toEqual({ encoding: "utf8", timeout: 5000 });
89 });
90});
91​
92describe("readPathFromLaunchctl", () => {
93 it("returns a trimmed PATH value from launchctl", () => {
94 const execFile = vi.fn<
95 (
96 file: string,
97 args: ReadonlyArray<string>,
98 options: { encoding: "utf8"; timeout: number },
99 ) => string
100 >(() => " /opt/homebrew/bin:/usr/bin \n");
101​
102 expect(readPathFromLaunchctl(execFile)).toBe("/opt/homebrew/bin:/usr/bin");
103 expect(execFile).toHaveBeenCalledWith("/bin/launchctl", ["getenv", "PATH"], {
104 encoding: "utf8",
105 timeout: 2000,
106 });
107 });
108​
109 it("returns undefined when launchctl is unavailable", () => {
110 const execFile = vi.fn<
111 (
112 file: string,
113 args: ReadonlyArray<string>,
114 options: { encoding: "utf8"; timeout: number },
115 ) => string
116 >(() => {
117 throw new Error("spawn /bin/launchctl ENOENT");
118 });
119​
120 expect(readPathFromLaunchctl(execFile)).toBeUndefined();
121 });
122});
123​
124describe("readEnvironmentFromLoginShell", () => {
125 it("extracts multiple environment variables from a login shell command", () => {
126 const execFile = vi.fn<
127 (
128 file: string,
129 args: ReadonlyArray<string>,
130 options: { encoding: "utf8"; timeout: number },
131 ) => string
132 >(() =>
133 [
134 "__T3CODE_ENV_PATH_START__",
135 "/a:/b",
136 "__T3CODE_ENV_PATH_END__",
137 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
138 "/tmp/secretive.sock",
139 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
140 ].join("\n"),
141 );
142​
143 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
144 PATH: "/a:/b",
145 SSH_AUTH_SOCK: "/tmp/secretive.sock",
146 });
147 expect(execFile).toHaveBeenCalledTimes(1);
148 });
149​
150 it("omits environment variables that are missing or empty", () => {
151 const execFile = vi.fn<
152 (
153 file: string,
154 args: ReadonlyArray<string>,
155 options: { encoding: "utf8"; timeout: number },
156 ) => string
157 >(() =>
158 [
159 "__T3CODE_ENV_PATH_START__",
160 "/a:/b",
161 "__T3CODE_ENV_PATH_END__",
162 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
163 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
164 ].join("\n"),
165 );
166​
167 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
168 PATH: "/a:/b",
169 });
170 });
171​
172 it("preserves surrounding whitespace in captured values", () => {
173 const execFile = vi.fn<
174 (
175 file: string,
176 args: ReadonlyArray<string>,
177 options: { encoding: "utf8"; timeout: number },
178 ) => string
179 >(() =>
180 ["__T3CODE_ENV_CUSTOM_VAR_START__", " padded value ", "__T3CODE_ENV_CUSTOM_VAR_END__"].join(
181 "\n",
182 ),
183 );
184​
185 expect(readEnvironmentFromLoginShell("/bin/zsh", ["CUSTOM_VAR"], execFile)).toEqual({
186 CUSTOM_VAR: " padded value ",
187 });
188 });
189});
190​
191describe("listLoginShellCandidates", () => {
192 it("returns env shell, user shell, then the platform fallback without duplicates", () => {
193 expect(listLoginShellCandidates("darwin", " /opt/homebrew/bin/nu ", "/bin/zsh")).toEqual([
194 "/opt/homebrew/bin/nu",
195 "/bin/zsh",
196 ]);
197 });
198​
199 it("falls back to the platform default when no shells are available", () => {
200 expect(listLoginShellCandidates("linux", undefined, "")).toEqual(["/bin/bash"]);
201 });
202});
203​
204describe("mergePathEntries", () => {
205 it("prefers login-shell PATH entries and keeps inherited extras", () => {
206 expect(
207 mergePathEntries("/opt/homebrew/bin:/usr/bin", "/Users/test/.local/bin:/usr/bin", "darwin"),
208 ).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
209 });
210​
211 it("uses the platform-specific delimiter", () => {
212 expect(mergePathEntries("C:\\Tools;C:\\Windows", "C:\\Windows;C:\\Git", "win32")).toBe(
213 "C:\\Tools;C:\\Windows;C:\\Git",
214 );
215 });
216});
217​
218describe("readEnvironmentFromWindowsShell", () => {
219 it("extracts environment variables from a PowerShell command", () => {
220 const execFile = vi.fn<
221 (
222 file: string,
223 args: ReadonlyArray<string>,
224 options: { encoding: "utf8"; timeout: number },
225 ) => string
226 >(
227 () =>
228 "__T3CODE_ENV_PATH_START__\nC:\\Users\\testuser\\AppData\\Roaming\\npm\n__T3CODE_ENV_PATH_END__\n",
229 );
230​
231 expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
232 PATH: "C:\\Users\\testuser\\AppData\\Roaming\\npm",
233 });
234 expect(execFile).toHaveBeenCalledWith(
235 "pwsh.exe",
236 expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]),
237 { encoding: "utf8", timeout: 5000 },
238 );
239 });
240​
241 it("strips CRLF delimiters from captured PowerShell values", () => {
242 const execFile = vi.fn<
243 (
244 file: string,
245 args: ReadonlyArray<string>,
246 options: { encoding: "utf8"; timeout: number },
247 ) => string
248 >(
249 () =>
250 "__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
251 );
252​
253 expect(readEnvironmentFromWindowsShell(["FNM_DIR"], execFile)).toEqual({
254 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
255 });
256 });
257​
258 it("omits -NoProfile when loadProfile is enabled", () => {
259 const execFile = vi.fn<
260 (
261 file: string,
262 args: ReadonlyArray<string>,
263 options: { encoding: "utf8"; timeout: number },
264 ) => string
265 >(() => "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n");
266​
267 expect(readEnvironmentFromWindowsShell(["PATH"], { loadProfile: true }, execFile)).toEqual({
268 PATH: "C:\\Tools",
269 });
270 expect(execFile).toHaveBeenCalledWith(
271 "pwsh.exe",
272 expect.arrayContaining(["-NoLogo", "-NonInteractive", "-Command"]),
273 { encoding: "utf8", timeout: 5000 },
274 );
275 expect(execFile.mock.calls[0]?.[1]).not.toContain("-NoProfile");
276 });
277​
278 it("falls back to Windows PowerShell when pwsh.exe is unavailable", () => {
279 const execFile = vi.fn<
280 (
281 file: string,
282 args: ReadonlyArray<string>,
283 options: { encoding: "utf8"; timeout: number },
284 ) => string
285 >((file) => {
286 if (file === "pwsh.exe") {
287 throw new Error("spawn pwsh.exe ENOENT");
288 }
289 return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
290 });
291​
292 expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
293 PATH: "C:\\Tools",
294 });
295 expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
296 encoding: "utf8",
297 timeout: 5000,
298 });
299 expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
300 encoding: "utf8",
301 timeout: 5000,
302 });
303 });
304});
305​
306describe("mergePathValues", () => {
307 it("dedupes case-insensitively on Windows while preserving preferred order", () => {
308 expect(
309 mergePathValues(
310 'C:\\Users\\testuser\\AppData\\Roaming\\npm;"C:\\Program Files\\nodejs"',
311 "c:\\users\\testuser\\appdata\\roaming\\npm;C:\\Windows\\System32",
312 "win32",
313 ),
314 ).toBe(
315 'C:\\Users\\testuser\\AppData\\Roaming\\npm;"C:\\Program Files\\nodejs";C:\\Windows\\System32',
316 );
317 });
318​
319 it("dedupes case-sensitively on POSIX", () => {
320 expect(mergePathValues("/usr/local/bin:/usr/bin", "/usr/bin:/USR/BIN", "linux")).toBe(
321 "/usr/local/bin:/usr/bin:/USR/BIN",
322 );
323 });
324});
325​
326describe("resolveKnownWindowsCliDirs", () => {
327 it("returns known Windows CLI install directories in priority order", () => {
328 expect(
329 resolveKnownWindowsCliDirs({
330 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
331 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
332 USERPROFILE: "C:\\Users\\testuser",
333 }),
334 ).toEqual([
335 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
336 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
337 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
338 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
339 "C:\\Users\\testuser\\.bun\\bin",
340 "C:\\Users\\testuser\\scoop\\shims",
341 ]);
342 });
343});
344​
345effectIt.layer(NodeServices.layer)("isCommandAvailable", (it) => {
346 it.effect("returns false when PATH is empty", () =>
347 Effect.gen(function* () {
348 expect(
349 yield* isCommandAvailable("definitely-not-installed", {
350 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
351 }).pipe(Effect.provideService(HostProcessPlatform, "win32")),
352 ).toBe(false);
353 }),
354 );
355});
356​
357effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => {
358 it.effect("fails when PATH is empty", () =>
359 Effect.gen(function* () {
360 const result = yield* resolveCommandPath("definitely-not-installed", {
361 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
362 }).pipe(Effect.provideService(HostProcessPlatform, "win32"), Effect.result);
363​
364 expect(result._tag).toBe("Failure");
365 }),
366 );
367});
368​
369effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
370 it.effect("runs Windows executables directly without a shell", () =>
371 Effect.gen(function* () {
372 const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], {
373 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
374 }).pipe(Effect.provideService(HostProcessPlatform, "win32"));
375​
376 expect(command).toEqual({
377 command: "node.exe",
378 args: ["script.js", "hello & goodbye"],
379 shell: false,
380 });
381 }),
382 );
383​
384 it.effect("escapes the executable and arguments for Windows command shims", () =>
385 Effect.gen(function* () {
386 const command = yield* resolveSpawnCommand(
387 "vp",
388 ["run", "value & calc", "%PATH%", 'quote"value'],
389 { env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" } },
390 ).pipe(
391 Effect.provideService(HostProcessPlatform, "win32"),
392 Effect.provideService(
393 SpawnExecutableResolution,
394 () => "C:\\Program Files\\npm & tools\\vp.cmd",
395 ),
396 );
397​
398 expect(command.shell).toBe(true);
399 expect(command.command).not.toContain(" & ");
400 expect(command.command).toContain("^&");
401 expect(command.args).toEqual([
402 '^"run^"',
403 '^"value^ ^&^ calc^"',
404 '^"^%PATH^%^"',
405 '^"quote\\^"value^"',
406 ]);
407 }),
408 );
409​
410 it.effect("resolves against the effective environment when extending host env", () =>
411 Effect.gen(function* () {
412 let resolvedEnvironment: NodeJS.ProcessEnv | undefined;
413 yield* resolveSpawnCommand("codex", ["app-server"], {
414 env: { CODEX_HOME: "C:\\Users\\tester\\.codex" },
415 extendEnv: true,
416 }).pipe(
417 Effect.provideService(HostProcessPlatform, "win32"),
418 Effect.provideService(HostProcessEnvironment, {
419 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
420 PATHEXT: ".COM;.EXE;.BAT;.CMD",
421 }),
422 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) => {
423 resolvedEnvironment = env;
424 return "C:\\Users\\tester\\AppData\\Roaming\\npm\\codex.cmd";
425 }),
426 );
427​
428 expect(resolvedEnvironment).toEqual({
429 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
430 PATHEXT: ".COM;.EXE;.BAT;.CMD",
431 CODEX_HOME: "C:\\Users\\tester\\.codex",
432 });
433 }),
434 );
435​
436 it.effect("does not fall back to a shell for unresolved Windows commands", () =>
437 Effect.gen(function* () {
438 const command = yield* resolveSpawnCommand("missing & calc", ["unsafe & value"], {
439 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
440 }).pipe(Effect.provideService(HostProcessPlatform, "win32"));
441​
442 expect(command).toEqual({
443 command: "missing & calc",
444 args: ["unsafe & value"],
445 shell: false,
446 });
447 }),
448 );
449});
450​
451effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => {
452 it.effect("returns the baseline no-profile PATH patch when node is already available", () =>
453 Effect.gen(function* () {
454 const readEnvironment = vi.fn(
455 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
456 options?.loadProfile
457 ? { PATH: "C:\\Profile\\Bin" }
458 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
459 );
460 const commandAvailable = vi.fn(() => Effect.succeed(true));
461​
462 expect(
463 yield* withWindowsEnvironmentMocks(
464 resolveWindowsEnvironment({
465 PATH: "C:\\Windows\\System32",
466 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
467 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
468 USERPROFILE: "C:\\Users\\testuser",
469 }),
470 readEnvironment,
471 commandAvailable,
472 ),
473 ).toEqual({
474 PATH: [
475 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
476 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
477 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
478 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
479 "C:\\Users\\testuser\\.bun\\bin",
480 "C:\\Users\\testuser\\scoop\\shims",
481 "C:\\Shell\\Bin",
482 "C:\\Windows\\System32",
483 ].join(";"),
484 });
485 expect(readEnvironment).toHaveBeenCalledTimes(1);
486 expect(readEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
487 expect(commandAvailable).toHaveBeenCalledWith(
488 "node",
489 expect.objectContaining({ env: expect.any(Object) }),
490 );
491 }),
492 );
493​
494 it.effect("loads the PowerShell profile when baseline env cannot resolve node", () =>
495 Effect.gen(function* () {
496 const readEnvironment = vi.fn(
497 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
498 options?.loadProfile
499 ? {
500 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
501 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
502 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
503 }
504 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
505 );
506 const commandAvailable = vi.fn(() => Effect.succeed(false));
507​
508 expect(
509 yield* withWindowsEnvironmentMocks(
510 resolveWindowsEnvironment({
511 PATH: "C:\\Windows\\System32",
512 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
513 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
514 USERPROFILE: "C:\\Users\\testuser",
515 }),
516 readEnvironment,
517 commandAvailable,
518 ),
519 ).toEqual({
520 PATH: [
521 "C:\\Profile\\Node",
522 "C:\\Windows\\System32",
523 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
524 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
525 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
526 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
527 "C:\\Users\\testuser\\.bun\\bin",
528 "C:\\Users\\testuser\\scoop\\shims",
529 "C:\\Shell\\Bin",
530 ].join(";"),
531 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
532 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
533 });
534 expect(readEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
535 expect(readEnvironment).toHaveBeenNthCalledWith(
536 2,
537 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
538 {
539 loadProfile: true,
540 },
541 );
542 expect(commandAvailable).toHaveBeenCalledTimes(1);
543 }),
544 );
545​
546 it.effect("keeps the baseline env when profiled probe still does not resolve node", () =>
547 Effect.gen(function* () {
548 const readEnvironment = vi.fn(
549 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
550 options?.loadProfile ? { FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm" } : {},
551 );
552 const commandAvailable = vi.fn(() => Effect.succeed(false));
553​
554 expect(
555 yield* withWindowsEnvironmentMocks(
556 resolveWindowsEnvironment({
557 PATH: "C:\\Windows\\System32",
558 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
559 USERPROFILE: "C:\\Users\\testuser",
560 }),
561 readEnvironment,
562 commandAvailable,
563 ),
564 ).toEqual({
565 PATH: [
566 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
567 "C:\\Users\\testuser\\.bun\\bin",
568 "C:\\Users\\testuser\\scoop\\shims",
569 "C:\\Windows\\System32",
570 ].join(";"),
571 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
572 });
573 expect(commandAvailable).toHaveBeenCalledTimes(1);
574 }),
575 );
576});