Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - these integration tests execute real POSIX shell tools against disposable directories.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeCrypto from "node:crypto";
4import * as NodeFS from "node:fs";
5import * as NodeOS from "node:os";
6import * as NodePath from "node:path";
7
8import { describe, it } from "@effect/vitest";
9import { expect } from "vite-plus/test";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as Fiber from "effect/Fiber";
13import * as Layer from "effect/Layer";
14import * as Sink from "effect/Sink";
15import * as Stream from "effect/Stream";
16import * as TestClock from "effect/testing/TestClock";
17import { ChildProcessSpawner } from "effect/unstable/process";
18
19import {
20 buildPackagedRuntimeStageScript,
21 buildWslNodeEnvPreamble,
22 DesktopWslDistroListError,
23 formatMissingToolsReason,
24 formatNodePtyProbeFailureReason,
25 formatPackagedRuntimeStageFailure,
26 formatWslShellTransportFailureReason,
27 parseNodePath,
28 parseNodeVersion,
29 parseResolvedPath,
30 parseToolchainReport,
31 probeWslDistros,
32 WSL_SCRIPT_SHELL_ARGS,
33} from "./DesktopWslEnvironment.ts";
34import { parseWslRuntimeArchiveHash } from "@t3tools/shared/wslRuntimeArchive";
35
36const encoder = new TextEncoder();
37
38const makeRuntimeArchiveFixture = () => {
39 const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-wsl-runtime-"));
40 const source = NodePath.join(root, "source");
41 const archive = NodePath.join(root, "wsl-runtime.tar.gz");
42 const tools = NodePath.join(root, "tools");
43 const cache = NodePath.join(root, "cache");
44 NodeFS.mkdirSync(NodePath.join(source, "apps/server/dist"), { recursive: true });
45 NodeFS.mkdirSync(NodePath.join(source, "node_modules/effect"), { recursive: true });
46 NodeFS.mkdirSync(tools);
47 NodeFS.writeFileSync(NodePath.join(source, "apps/server/dist/bin.mjs"), "version one\n");
48 NodeFS.writeFileSync(NodePath.join(source, "node_modules/effect/package.json"), "{}\n");
49 NodeFS.writeFileSync(NodePath.join(tools, "wslpath"), '#!/bin/sh\nprintf "%s\\n" "$2"\n', {
50 mode: 0o755,
51 });
52
53 const pack = (archivePath = archive) => {
54 const result = NodeChildProcess.spawnSync(
55 "tar",
56 ["-czf", archivePath, "-C", source, "apps", "node_modules"],
57 { encoding: "utf8" },
58 );
59 expect(result.status, result.stderr).toBe(0);
60 return NodeCrypto.createHash("sha256").update(NodeFS.readFileSync(archivePath)).digest("hex");
61 };
62 const env = {
63 ...process.env,
64 HOME: root,
65 PATH: `${tools}:${process.env.PATH ?? ""}`,
66 XDG_CACHE_HOME: cache,
67 };
68 const run = (archiveHash: string, archivePath = archive) =>
69 NodeChildProcess.spawnSync(
70 "bash",
71 ["-c", buildPackagedRuntimeStageScript(archivePath, archiveHash)],
72 { encoding: "utf8", env },
73 );
74 const runAsync = (archiveHash: string, archivePath = archive) =>
75 new Promise<{
76 readonly status: number | null;
77 readonly stdout: string;
78 readonly stderr: string;
79 }>((resolve) => {
80 const child = NodeChildProcess.spawn(
81 "bash",
82 ["-c", buildPackagedRuntimeStageScript(archivePath, archiveHash)],
83 { env },
84 );
85 let stdout = "";
86 let stderr = "";
87 child.stdout.setEncoding("utf8");
88 child.stdout.on("data", (chunk: string) => {
89 stdout += chunk;
90 });
91 child.stderr.setEncoding("utf8");
92 child.stderr.on("data", (chunk: string) => {
93 stderr += chunk;
94 });
95 child.on("close", (status) => resolve({ status, stdout, stderr }));
96 });
97 const runtimeBase = NodePath.join(cache, "t3code/desktop-wsl-runtime");
98 const runtimePath = (archiveHash: string) => NodePath.join(runtimeBase, `sha256-${archiveHash}`);
99
100 return { archive, pack, root, run, runAsync, runtimePath, source, tools };
101};
102
103const makeDistroListSpawner = (result: { readonly stdout?: string; readonly exitCode?: number }) =>
104 ChildProcessSpawner.make(() =>
105 Effect.succeed(
106 ChildProcessSpawner.makeHandle({
107 pid: ChildProcessSpawner.ProcessId(1),
108 exitCode:
109 result.exitCode === undefined
110 ? Effect.never
111 : Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)),
112 isRunning: Effect.succeed(result.exitCode === undefined),
113 kill: () => Effect.void,
114 unref: Effect.succeed(Effect.void),
115 stdin: Sink.drain,
116 stdout: Stream.make(encoder.encode(result.stdout ?? "")),
117 stderr: Stream.empty,
118 all: Stream.empty,
119 getInputFd: () => Sink.drain,
120 getOutputFd: () => Stream.empty,
121 }),
122 ),
123 );
124
125describe("probeWslDistros", () => {
126 it.effect("preserves a successful empty distro list", () =>
127 Effect.gen(function* () {
128 const distros = yield* probeWslDistros;
129 expect(distros).toEqual([]);
130 }).pipe(
131 Effect.provideService(
132 ChildProcessSpawner.ChildProcessSpawner,
133 makeDistroListSpawner({ stdout: "", exitCode: 0 }),
134 ),
135 ),
136 );
137
138 it.effect("fails when the distro-list command exits unsuccessfully", () =>
139 Effect.gen(function* () {
140 const error = yield* probeWslDistros.pipe(Effect.flip);
141 expect(error).toBeInstanceOf(DesktopWslDistroListError);
142 expect(error.message).toContain("exited with code 1");
143 }).pipe(
144 Effect.provideService(
145 ChildProcessSpawner.ChildProcessSpawner,
146 makeDistroListSpawner({ exitCode: 1 }),
147 ),
148 ),
149 );
150
151 it.effect("fails when the distro-list command times out", () => {
152 const layer = Layer.merge(
153 TestClock.layer(),
154 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, makeDistroListSpawner({})),
155 );
156 return Effect.gen(function* () {
157 const fiber = yield* probeWslDistros.pipe(Effect.flip, Effect.forkScoped);
158 yield* Effect.yieldNow;
159 yield* TestClock.adjust(Duration.seconds(8));
160 const error = yield* Fiber.join(fiber);
161 expect(error).toBeInstanceOf(DesktopWslDistroListError);
162 expect(error.message).toContain("timed out");
163 }).pipe(Effect.provide(layer));
164 });
165});
166
167describe("formatNodePtyProbeFailureReason", () => {
168 it("identifies a packaged build that omitted the Linux node-pty prebuild", () => {
169 const reason = formatNodePtyProbeFailureReason(4);
170
171 expect(reason).toContain("packaged Linux node-pty binary was not included");
172 expect(reason).toContain("--wsl-prebuild");
173 });
174
175 it("leaves other node-pty load failures to the compatibility diagnostic", () => {
176 expect(formatNodePtyProbeFailureReason(1)).toBeNull();
177 });
178});
179
180describe("formatWslShellTransportFailureReason", () => {
181 it("distinguishes timeouts and spawn failures from normal shell exit codes", () => {
182 expect(formatWslShellTransportFailureReason("timeout")).toContain("timed out");
183 expect(formatWslShellTransportFailureReason("spawn")).toContain("could not start wsl.exe");
184 expect(formatWslShellTransportFailureReason("process")).toContain("lost communication");
185 expect(formatWslShellTransportFailureReason(null)).toBeNull();
186 });
187});
188
189describe("WSL scripted shell transport", () => {
190 const runScript = (home: string, script: string) => {
191 const [, , ...bashArgs] = WSL_SCRIPT_SHELL_ARGS;
192 return NodeChildProcess.spawnSync("bash", bashArgs, {
193 input: script,
194 encoding: "utf8",
195 env: { ...process.env, HOME: home },
196 });
197 };
198
199 it("preserves exported login state without letting logout hooks rewrite success", () => {
200 const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-wsl-shell-"));
201 try {
202 NodeFS.writeFileSync(
203 NodePath.join(home, ".bash_profile"),
204 "export T3_PROFILE_VALUE=loaded\n",
205 );
206 NodeFS.writeFileSync(NodePath.join(home, ".bash_logout"), "false\n");
207
208 const result = runScript(home, 'set -eu\nprintf "%s\\n" "$T3_PROFILE_VALUE"\nexit 0\n');
209
210 expect(result.status).toBe(0);
211 expect(result.stdout).toBe("loaded\n");
212 } finally {
213 NodeFS.rmSync(home, { recursive: true, force: true });
214 }
215 });
216
217 it("preserves a scripted failure status", () => {
218 const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-wsl-shell-"));
219 try {
220 NodeFS.writeFileSync(NodePath.join(home, ".bash_logout"), "false\n");
221
222 const result = runScript(home, "set -eu\nexit 17\n");
223
224 expect(result.status).toBe(17);
225 } finally {
226 NodeFS.rmSync(home, { recursive: true, force: true });
227 }
228 });
229});
230
231describe("buildWslNodeEnvPreamble", () => {
232 it("passes the required Node engine range into the shared resolver", () => {
233 const preamble = buildWslNodeEnvPreamble("^22.16 || ^23.11 || >=24.10");
234
235 expect(preamble).toContain("T3_NODE_ENGINE_RANGE='^22.16 || ^23.11 || >=24.10'");
236 expect(preamble.indexOf("T3_NODE_ENGINE_RANGE=")).toBeLessThan(
237 preamble.lastIndexOf("ensure_remote_node_path || true"),
238 );
239 });
240
241 it("keeps the shared resolver permissive when no Node engine range is provided", () => {
242 expect(buildWslNodeEnvPreamble()).toContain("T3_NODE_ENGINE_RANGE=''");
243 });
244});
245
246describe("buildPackagedRuntimeStageScript", () => {
247 it("checks the Linux-native cache before converting or reading the mounted source", () => {
248 const script = buildPackagedRuntimeStageScript(
249 "C:\\Program Files\\T3 Code\\resources\\app.asar.unpacked",
250 "1.2.3-x64",
251 );
252 const cacheHit = script.indexOf('if [ "$(cat "$manifest_path"');
253 const sourceConversion = script.indexOf("wslpath -u");
254
255 expect(cacheHit).toBeGreaterThanOrEqual(0);
256 expect(sourceConversion).toBeGreaterThan(cacheHit);
257 expect(script.slice(cacheHit, sourceConversion)).toContain(
258 'runtimeRoot:%s\\n\' "$runtime_dir"',
259 );
260 expect(script.slice(cacheHit, sourceConversion)).toContain("exit 0");
261 });
262
263 it("derives an immutable runtime root from the validated archive hash", () => {
264 const archiveHash = "b".repeat(64);
265 const script = buildPackagedRuntimeStageScript(
266 "C:\\Program Files\\T3 Code\\resources\\wsl-runtime.tar.gz",
267 archiveHash,
268 );
269
270 expect(script).toContain('runtime_dir="$runtime_base/sha256-$archive_hash"');
271 expect(script).not.toContain('current_dir="$runtime_base/current"');
272 });
273
274 it("falls back from an XDG cache on a Windows-mounted filesystem", () => {
275 const script = buildPackagedRuntimeStageScript(
276 "C:\\Program Files\\T3 Code\\resources\\app.asar.unpacked",
277 "1.2.3-x64",
278 );
279 const xdgSelection = script.indexOf('cache_home="$XDG_CACHE_HOME"');
280 const filesystemProbe = script.indexOf('findmnt -T "$cache_home"');
281 const windowsMountFallback = script.indexOf("9p|drvfs|plan9|virtio-plan9|virtiofs");
282 const runtimeBase = script.indexOf('runtime_base="$cache_home/t3code/desktop-wsl-runtime"');
283
284 expect(filesystemProbe).toBeGreaterThan(xdgSelection);
285 expect(windowsMountFallback).toBeGreaterThan(filesystemProbe);
286 expect(runtimeBase).toBeGreaterThan(windowsMountFallback);
287 expect(script.slice(filesystemProbe, runtimeBase)).toContain(
288 'cache_home="${HOME:?WSL home directory is unavailable}/.cache"',
289 );
290 });
291
292 it("serializes cache misses and rechecks the cache before reading the mounted source", () => {
293 const script = buildPackagedRuntimeStageScript(
294 "C:\\Program Files\\T3 Code\\resources\\app.asar.unpacked",
295 "1.2.3-x64",
296 );
297 const firstCacheCheck = script.indexOf('if [ "$(cat "$manifest_path"');
298 const lock = script.indexOf("flock -x 9");
299 const secondCacheCheck = script.indexOf('if [ "$(cat "$manifest_path"', firstCacheCheck + 1);
300 const sourceConversion = script.indexOf("wslpath -u");
301
302 expect(lock).toBeGreaterThan(firstCacheCheck);
303 expect(secondCacheCheck).toBeGreaterThan(lock);
304 expect(sourceConversion).toBeGreaterThan(secondCacheCheck);
305 expect(script).toContain('if ! source_archive=$(wslpath -u "$windows_archive_path"); then');
306 expect(script.slice(sourceConversion)).toContain("exit 5");
307 });
308
309 it("extracts one packaged archive instead of copying the mounted file tree", () => {
310 const script = buildPackagedRuntimeStageScript(
311 "C:\\Program Files\\T3 Code\\resources\\wsl-runtime.tar.gz",
312 "b".repeat(64),
313 );
314
315 expect(script).toContain('sha256sum "$source_archive"');
316 expect(script).toContain('if [ "$actual_hash" != "$archive_hash" ]; then');
317 expect(script).toContain('tar -xzf "$source_archive" -C "$staging_dir"');
318 expect(script).not.toContain('cp -a "$source_root/." "$staging_dir/"');
319 });
320
321 it("extracts once, then starts from the native cache without reading the archive", () => {
322 const fixture = makeRuntimeArchiveFixture();
323 try {
324 const archiveHash = fixture.pack();
325 const runtimePath = fixture.runtimePath(archiveHash);
326
327 const cold = fixture.run(archiveHash);
328 expect(cold.status, cold.stderr).toBe(0);
329 expect(
330 NodeFS.readFileSync(NodePath.join(runtimePath, ".t3code-runtime-sha256"), "utf8"),
331 ).toBe(`${archiveHash}\n`);
332 expect(
333 NodeFS.readFileSync(NodePath.join(runtimePath, "apps/server/dist/bin.mjs"), "utf8"),
334 ).toBe("version one\n");
335
336 NodeFS.rmSync(fixture.archive);
337 const warm = fixture.run(archiveHash);
338 expect(warm.status, warm.stderr).toBe(0);
339 expect(warm.stdout).toContain(`runtimeRoot:${runtimePath}`);
340 } finally {
341 NodeFS.rmSync(fixture.root, { recursive: true, force: true });
342 }
343 });
344
345 it("keeps a returned runtime pinned when a later archive is staged", () => {
346 const fixture = makeRuntimeArchiveFixture();
347 try {
348 const firstHash = fixture.pack();
349 const first = fixture.run(firstHash);
350 expect(first.status, first.stderr).toBe(0);
351 const firstRuntime = fixture.runtimePath(firstHash);
352
353 NodeFS.writeFileSync(
354 NodePath.join(fixture.source, "apps/server/dist/bin.mjs"),
355 "version two\n",
356 );
357 const secondHash = fixture.pack();
358 const updated = fixture.run(secondHash);
359
360 expect(updated.status, updated.stderr).toBe(0);
361 expect(
362 NodeFS.readFileSync(NodePath.join(firstRuntime, "apps/server/dist/bin.mjs"), "utf8"),
363 ).toBe("version one\n");
364 const secondRuntime = fixture.runtimePath(secondHash);
365 expect(secondRuntime).not.toBe(firstRuntime);
366 expect(
367 NodeFS.readFileSync(NodePath.join(secondRuntime, "apps/server/dist/bin.mjs"), "utf8"),
368 ).toBe("version two\n");
369 expect(
370 NodeFS.readFileSync(NodePath.join(secondRuntime, ".t3code-runtime-sha256"), "utf8"),
371 ).toBe(`${secondHash}\n`);
372 } finally {
373 NodeFS.rmSync(fixture.root, { recursive: true, force: true });
374 }
375 });
376
377 it("keeps the last good cache when a replacement archive is broken", () => {
378 const fixture = makeRuntimeArchiveFixture();
379 try {
380 const goodHash = fixture.pack();
381 expect(fixture.run(goodHash).status).toBe(0);
382 const goodRuntime = fixture.runtimePath(goodHash);
383
384 NodeFS.writeFileSync(fixture.archive, "not a tar archive\n");
385 const brokenHash = NodeCrypto.createHash("sha256")
386 .update(NodeFS.readFileSync(fixture.archive))
387 .digest("hex");
388 const broken = fixture.run(brokenHash);
389
390 expect(broken.status).not.toBe(0);
391 expect(
392 NodeFS.readFileSync(NodePath.join(goodRuntime, "apps/server/dist/bin.mjs"), "utf8"),
393 ).toBe("version one\n");
394 expect(
395 NodeFS.readFileSync(NodePath.join(goodRuntime, ".t3code-runtime-sha256"), "utf8"),
396 ).toBe(`${goodHash}\n`);
397 } finally {
398 NodeFS.rmSync(fixture.root, { recursive: true, force: true });
399 }
400 });
401
402 it("serializes concurrent cache misses so the archive is extracted once", async () => {
403 const fixture = makeRuntimeArchiveFixture();
404 try {
405 const archiveHash = fixture.pack();
406 const extractionLog = NodePath.join(fixture.root, "tar-calls.log");
407 const realTar = NodeChildProcess.spawnSync("which", ["tar"], {
408 encoding: "utf8",
409 }).stdout.trim();
410 NodeFS.writeFileSync(
411 NodePath.join(fixture.tools, "tar"),
412 `#!/bin/sh\nprintf 'extract\\n' >> ${JSON.stringify(extractionLog)}\nexec ${JSON.stringify(realTar)} "$@"\n`,
413 { mode: 0o755 },
414 );
415
416 const results = await Promise.all([
417 fixture.runAsync(archiveHash),
418 fixture.runAsync(archiveHash),
419 ]);
420
421 for (const result of results) expect(result.status, result.stderr).toBe(0);
422 expect(NodeFS.readFileSync(extractionLog, "utf8")).toBe("extract\n");
423 } finally {
424 NodeFS.rmSync(fixture.root, { recursive: true, force: true });
425 }
426 });
427
428 it("keeps concurrent callers on their own archive contents", async () => {
429 const fixture = makeRuntimeArchiveFixture();
430 try {
431 const firstArchive = NodePath.join(fixture.root, "runtime-one.tar.gz");
432 const firstHash = fixture.pack(firstArchive);
433 NodeFS.writeFileSync(
434 NodePath.join(fixture.source, "apps/server/dist/bin.mjs"),
435 "version two\n",
436 );
437 const secondArchive = NodePath.join(fixture.root, "runtime-two.tar.gz");
438 const secondHash = fixture.pack(secondArchive);
439
440 const [first, second] = await Promise.all([
441 fixture.runAsync(firstHash, firstArchive),
442 fixture.runAsync(secondHash, secondArchive),
443 ]);
444
445 expect(first.status, first.stderr).toBe(0);
446 expect(second.status, second.stderr).toBe(0);
447 const firstRuntime = fixture.runtimePath(firstHash);
448 const secondRuntime = fixture.runtimePath(secondHash);
449 expect(first.stdout).toContain(`runtimeRoot:${firstRuntime}`);
450 expect(second.stdout).toContain(`runtimeRoot:${secondRuntime}`);
451 expect(
452 NodeFS.readFileSync(NodePath.join(firstRuntime, "apps/server/dist/bin.mjs"), "utf8"),
453 ).toBe("version one\n");
454 expect(
455 NodeFS.readFileSync(NodePath.join(secondRuntime, "apps/server/dist/bin.mjs"), "utf8"),
456 ).toBe("version two\n");
457 } finally {
458 NodeFS.rmSync(fixture.root, { recursive: true, force: true });
459 }
460 });
461});
462
463describe("formatPackagedRuntimeStageFailure", () => {
464 it("keeps the staging failure reason for fallback logging", () => {
465 expect(formatPackagedRuntimeStageFailure(5, "wslpath conversion failed")).toEqual({
466 ok: false,
467 reason: "Failed to prepare the packaged WSL runtime (exit 5): wslpath conversion failed",
468 });
469 });
470});
471
472describe("parseWslRuntimeArchiveHash", () => {
473 it("normalizes a valid SHA-256 sidecar", () => {
474 expect(parseWslRuntimeArchiveHash(`${"A".repeat(64)}\n`)).toBe("a".repeat(64));
475 });
476
477 it("rejects missing and malformed identities", () => {
478 expect(parseWslRuntimeArchiveHash("")).toBeNull();
479 expect(parseWslRuntimeArchiveHash("not-a-hash")).toBeNull();
480 expect(parseWslRuntimeArchiveHash("a".repeat(63))).toBeNull();
481 });
482});
483
484describe("parseToolchainReport", () => {
485 it("returns no missing tools and no node version on empty output", () => {
486 expect(parseToolchainReport("")).toEqual({ missingTools: [], nodeVersion: null });
487 });
488
489 it("collects all missing: lines", () => {
490 const stdout = ["missing:make", "missing:g++", "nodeVersion:24.10.0"].join("\n");
491 expect(parseToolchainReport(stdout)).toEqual({
492 missingTools: ["make", "g++"],
493 nodeVersion: "24.10.0",
494 });
495 });
496
497 it("ignores blank lines and trims whitespace", () => {
498 const stdout = [" missing:python3 ", "", " nodeVersion:v22.16.0 "].join("\n");
499 expect(parseToolchainReport(stdout)).toEqual({
500 missingTools: ["python3"],
501 nodeVersion: "v22.16.0",
502 });
503 });
504
505 it("returns null node version when value after prefix is empty", () => {
506 expect(parseToolchainReport("nodeVersion:")).toEqual({
507 missingTools: [],
508 nodeVersion: null,
509 });
510 });
511});
512
513describe("parseNodePath", () => {
514 it("extracts the absolute node path from a nodePath: line", () => {
515 const stdout = "nodePath:/home/josh/.nvm/versions/node/v22.16.0/bin/node";
516 expect(parseNodePath(stdout)).toBe("/home/josh/.nvm/versions/node/v22.16.0/bin/node");
517 });
518
519 it("returns null when node was not found (empty value after prefix)", () => {
520 expect(parseNodePath("nodePath:")).toBeNull();
521 });
522
523 it("returns null when there is no nodePath line at all", () => {
524 expect(parseNodePath("missing:node\nnodeVersion:")).toBeNull();
525 });
526
527 it("ignores surrounding noise and trims whitespace", () => {
528 const stdout = ["some preamble noise", " nodePath:/usr/bin/node ", "trailing"].join("\n");
529 expect(parseNodePath(stdout)).toBe("/usr/bin/node");
530 });
531});
532
533describe("parseNodeVersion", () => {
534 it("extracts the node version from a nodeVersion: line", () => {
535 expect(parseNodeVersion("nodeVersion:24.10.0")).toBe("24.10.0");
536 });
537
538 it("returns null when the version value is empty", () => {
539 expect(parseNodeVersion("nodeVersion:")).toBeNull();
540 });
541
542 it("returns null when there is no nodeVersion line at all", () => {
543 expect(parseNodeVersion("nodePath:/usr/bin/node\nresolvedPath:/usr/bin")).toBeNull();
544 });
545
546 it("ignores surrounding noise and trims whitespace", () => {
547 const stdout = [
548 "some preamble noise",
549 " nodeVersion:22.16.0 ",
550 "nodePath:/usr/bin/node",
551 ].join("\n");
552 expect(parseNodeVersion(stdout)).toBe("22.16.0");
553 });
554});
555
556describe("parseResolvedPath", () => {
557 it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {
558 const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
559 expect(parseResolvedPath(`nodePath:/usr/bin/node\nresolvedPath:${resolvedPath}\n`)).toBe(
560 resolvedPath,
561 );
562 });
563
564 it("accepts CRLF output without retaining the carriage return", () => {
565 expect(parseResolvedPath("resolvedPath:/usr/local/bin:/usr/bin\r\n")).toBe(
566 "/usr/local/bin:/usr/bin",
567 );
568 });
569
570 it("returns null when the resolved PATH is absent or empty", () => {
571 expect(parseResolvedPath("nodePath:/usr/bin/node\n")).toBeNull();
572 expect(parseResolvedPath("resolvedPath:\n")).toBeNull();
573 });
574});
575
576describe("formatMissingToolsReason", () => {
577 it("returns null when everything is present and node is in range", () => {
578 expect(
579 formatMissingToolsReason({ missingTools: [], nodeVersion: "24.10.0" }, "^24.10"),
580 ).toBeNull();
581 });
582
583 it("returns null when range is not specified and tools are present", () => {
584 expect(formatMissingToolsReason({ missingTools: [], nodeVersion: "18.0.0" }, null)).toBeNull();
585 });
586
587 it("flags missing node first", () => {
588 const reason = formatMissingToolsReason(
589 { missingTools: ["node", "make"], nodeVersion: null },
590 "^24.10",
591 );
592 expect(reason).toContain("node");
593 expect(reason).toContain("^24.10");
594 expect(reason).toContain("make");
595 expect(reason).toContain("nvm");
596 });
597
598 it("flags an out-of-range node version with the actual version surfaced", () => {
599 const reason = formatMissingToolsReason(
600 { missingTools: [], nodeVersion: "20.0.0" },
601 "^24.10 || ^22.16",
602 );
603 expect(reason).toContain("node 20.0.0");
604 expect(reason).toContain("requires ^24.10 || ^22.16");
605 });
606
607 it("flags missing build tools without node when node is fine", () => {
608 const reason = formatMissingToolsReason(
609 { missingTools: ["g++", "python3"], nodeVersion: "24.10.0" },
610 "^24.10",
611 );
612 expect(reason).toContain("g++");
613 expect(reason).toContain("python3");
614 expect(reason).toContain("build-essential");
615 expect(reason).not.toContain("nvm");
616 });
617});