Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - the executed suite runs the generated install script through a real POSIX shell.
2import { describe, it } from "@effect/vitest";
3import { afterAll, expect } from "vite-plus/test";
4import * as NodeChildProcess from "node:child_process";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as Layer from "effect/Layer";
9import * as Sink from "effect/Sink";
10import * as Stream from "effect/Stream";
11import * as TestClock from "effect/testing/TestClock";
12import { ChildProcessSpawner } from "effect/process";
13
14import {
15 buildWslRuntimeInstallScript,
16 buildWslRuntimeInvalidateScript,
17 buildWslRuntimePruneScript,
18 buildWslRuntimeProbeScript,
19 DesktopWslDistroListError,
20 formatMissingToolsReason,
21 parseNodePath,
22 parseNodeVersion,
23 parseResolvedPath,
24 parseToolchainReport,
25 parseWslRuntimeRoot,
26 probeWslDistros,
27} from "./DesktopWslEnvironment.ts";
28
29const encoder = new TextEncoder();
30
31// The install script only fails the way this file cares about when a real shell
32// runs it, so find one that has the tools it needs: bash directly on Linux, and
33// the WSL distro on a Windows dev box, where Git Bash ships no flock. Anywhere
34// else the executed suite skips and the generated-text assertions stand alone.
35const REQUIRED_SHELL_TOOLS = ["flock", "sha256sum", "tar", "mktemp"] as const;
36
37const posixShellRunner = (() => {
38 const candidates = [
39 { file: "bash", args: [] as ReadonlyArray<string> },
40 { file: "wsl.exe", args: ["-e", "bash"] as ReadonlyArray<string> },
41 ];
42 const probe = [
43 "[ -d /proc/1 ] || exit 1",
44 ...REQUIRED_SHELL_TOOLS.map((tool) => `command -v ${tool} >/dev/null || exit 1`),
45 ].join("\n");
46 return (
47 candidates.find((candidate) => {
48 const result = NodeChildProcess.spawnSync(candidate.file, [...candidate.args, "-c", probe], {
49 encoding: "utf8",
50 });
51 return result.status === 0;
52 }) ?? null
53 );
54})();
55
56const runShell = (script: string) => {
57 if (posixShellRunner === null) throw new Error("no POSIX shell runner available");
58 // The install script arrives on stdin in production too, which is what lets
59 // its own /proc scan not match itself.
60 const result = NodeChildProcess.spawnSync(
61 posixShellRunner.file,
62 [...posixShellRunner.args, "-s"],
63 { input: script, encoding: "utf8" },
64 );
65 return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
66};
67
68const sh = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
69
70const awaitHolder = (condition: string) =>
71 `i=0; until ${condition}; do i=$((i + 1)); [ "$i" -lt 500 ] || exit 1; sleep 0.01; done`;
72
73// Holds a cache busy the way a running server does: the holder's argv[0] is the
74// runtime entry, which the prune and install scripts look for in /proc cmdline.
75// It reads a pipe the script keeps open on fd 7, so it exits with the script
76// instead of outliving it on a timer.
77const holdRuntimeBusy = (entry: string) =>
78 [
79 `exec 7> >(exec -a ${entry} cat >/dev/null 2>&1)`,
80 awaitHolder(`grep -qF -- ${entry} /proc/[0-9]*/cmdline 2>/dev/null`),
81 ].join("\n");
82
83const holdInstallLock = (lock: string) =>
84 [
85 `exec 6> >(exec 9> ${lock}; flock -x 9; cat >/dev/null 2>&1)`,
86 awaitHolder(`! flock -n ${lock} true`),
87 ].join("\n");
88
89const readField = (stdout: string, field: string) => {
90 const line = stdout.split("\n").find((candidate) => candidate.startsWith(`${field}:`));
91 if (line === undefined) throw new Error(`missing ${field} in fixture output: ${stdout}`);
92 return line.slice(field.length + 1).trim();
93};
94
95const SERVER_ENTRY_SOURCE = '#!/bin/sh\necho "t3code wsl runtime test server 0.0.0"\n';
96
97const makeDistroListSpawner = (result: { readonly stdout?: string; readonly exitCode?: number }) =>
98 ChildProcessSpawner.make(() =>
99 Effect.succeed(
100 ChildProcessSpawner.makeHandle({
101 pid: ChildProcessSpawner.ProcessId(1),
102 exitCode:
103 result.exitCode === undefined
104 ? Effect.never
105 : Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)),
106 isRunning: Effect.succeed(result.exitCode === undefined),
107 kill: () => Effect.void,
108 unref: Effect.succeed(Effect.void),
109 stdin: Sink.drain,
110 stdout: Stream.make(encoder.encode(result.stdout ?? "")),
111 stderr: Stream.empty,
112 all: Stream.empty,
113 getInputFd: () => Sink.drain,
114 getOutputFd: () => Stream.empty,
115 }),
116 ),
117 );
118
119describe("probeWslDistros", () => {
120 it.effect("preserves a successful empty distro list", () =>
121 Effect.gen(function* () {
122 const distros = yield* probeWslDistros;
123 expect(distros).toEqual([]);
124 }).pipe(
125 Effect.provideService(
126 ChildProcessSpawner.ChildProcessSpawner,
127 makeDistroListSpawner({ stdout: "", exitCode: 0 }),
128 ),
129 ),
130 );
131
132 it.effect("fails when the distro-list command exits unsuccessfully", () =>
133 Effect.gen(function* () {
134 const error = yield* probeWslDistros.pipe(Effect.flip);
135 expect(error).toBeInstanceOf(DesktopWslDistroListError);
136 expect(error.message).toContain("exited with code 1");
137 }).pipe(
138 Effect.provideService(
139 ChildProcessSpawner.ChildProcessSpawner,
140 makeDistroListSpawner({ exitCode: 1 }),
141 ),
142 ),
143 );
144
145 it.effect("fails when the distro-list command times out", () => {
146 const layer = Layer.merge(
147 TestClock.layer(),
148 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, makeDistroListSpawner({})),
149 );
150 return Effect.gen(function* () {
151 const fiber = yield* probeWslDistros.pipe(Effect.flip, Effect.forkScoped);
152 yield* Effect.yieldNow;
153 yield* TestClock.adjust(Duration.seconds(8));
154 const error = yield* Fiber.join(fiber);
155 expect(error).toBeInstanceOf(DesktopWslDistroListError);
156 expect(error.message).toContain("timed out");
157 }).pipe(Effect.provide(layer));
158 });
159});
160
161describe("WSL runtime cache", () => {
162 it.each([
163 [
164 "install",
165 (id: string) => buildWslRuntimeInstallScript("/runtime.tar.gz", id, "b".repeat(64)),
166 ],
167 ["prune", buildWslRuntimePruneScript],
168 ["invalidate", buildWslRuntimeInvalidateScript],
169 ] as const)("sanitizes cache ids in the %s script", (_, buildScript) => {
170 const runtimeId = "1.2.3/x64; touch /tmp/nope";
171 const script = buildScript(runtimeId);
172 expect(script).toContain("/1.2.3_x64__touch__tmp_nope");
173 expect(script).not.toContain(runtimeId);
174 });
175
176 it("installs through a temporary directory and only reuses valid completed caches", () => {
177 const script = buildWslRuntimeInstallScript(
178 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
179 "1.2.3-x64",
180 "b".repeat(64),
181 );
182
183 expect(script).toContain('runtime_parent="$HOME/.t3/wsl-runtime"');
184 expect(script).toContain(' [ -f "$ready_marker" ] &&');
185 expect(script).toContain(' runtime_entry_runs "$runtime_root" &&');
186 expect(script).toContain("if runtime_is_ready; then");
187 expect(script).not.toContain("bin.mjs");
188 expect(script).not.toContain("node-pty");
189 expect(script).toContain("trap 'exit 1' HUP INT TERM");
190 expect(script).toContain('exec 9> "$runtime_lock"');
191 expect(script).toContain("flock -x 9");
192 expect(script).not.toContain('rm -rf "$runtime_lock"');
193 expect(script).toContain('mv -T "$runtime_root" "$runtime_stale"');
194 expect(script).toContain('mktemp -d "$runtime_parent/.1.2.3-x64.tmp.XXXXXX"');
195 // The release archive wraps everything in one `t3-<version>-linux-x64/`
196 // directory; stripping it puts the executable at `$runtime_root/t3`.
197 expect(script).toContain(
198 "tar -xzf '/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz' -C \"$runtime_tmp\" --strip-components=1",
199 );
200 expect(script).toContain('if ! runtime_entry_runs "$runtime_tmp"; then');
201 expect(script).toContain('mv -T "$runtime_tmp" "$runtime_root"');
202 expect(script).not.toContain('rm -rf "$runtime_root"');
203
204 const lockAcquired = script.indexOf("flock -x 9");
205 const readinessAfterLock = script.indexOf("if runtime_is_ready; then", lockAcquired + 1);
206 const existingRuntimeMoved = script.indexOf('mv -T "$runtime_root" "$runtime_stale"');
207 expect(lockAcquired).toBeGreaterThan(-1);
208 expect(readinessAfterLock).toBeGreaterThan(lockAcquired);
209 expect(existingRuntimeMoved).toBeGreaterThan(readinessAfterLock);
210 });
211
212 it("verifies the archive digest before extracting, and only on a cache miss", () => {
213 const script = buildWslRuntimeInstallScript(
214 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
215 "1.2.3-x64",
216 "b".repeat(64),
217 );
218
219 const expected = "b".repeat(64);
220 expect(script).toContain(
221 "archive_sha=$(sha256sum '/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz' | cut -d ' ' -f 1)",
222 );
223 expect(script).toContain(`if [ "$archive_sha" != '${expected}' ]; then`);
224
225 const readyShortCircuit = script.indexOf("if runtime_is_ready; then");
226 const digestChecked = script.indexOf("archive_sha=$(sha256sum");
227 const existingRuntimeMoved = script.indexOf('mv -T "$runtime_root" "$runtime_stale"');
228 const extracted = script.indexOf("tar -xzf");
229 expect(digestChecked).toBeGreaterThan(readyShortCircuit);
230 expect(existingRuntimeMoved).toBeGreaterThan(digestChecked);
231 expect(extracted).toBeGreaterThan(digestChecked);
232 });
233
234 it("moves an in-use runtime aside instead of deleting it under a live backend", () => {
235 const script = buildWslRuntimeInstallScript(
236 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
237 "sha256-" + "c".repeat(64),
238 "b".repeat(64),
239 );
240
241 expect(script).toContain('grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null');
242 expect(script).toContain(" [ -d /proc/1 ] || return 0");
243 expect(script).toContain(' if runtime_in_use "$runtime_root"; then');
244
245 // A process's cmdline keeps the pre-rename path, so the question is only
246 // answerable before the move.
247 const inUseChecked = script.indexOf('if runtime_in_use "$runtime_root"; then');
248 const moved = script.indexOf('mv -T "$runtime_root" "$runtime_stale"');
249 expect(inUseChecked).toBeGreaterThan(-1);
250 expect(inUseChecked).toBeLessThan(moved);
251
252 const kept = script.indexOf('touch "$runtime_stale"');
253 const deleted = script.indexOf('rm -rf "$runtime_stale"');
254 expect(kept).toBeGreaterThan(moved);
255 expect(deleted).toBeGreaterThan(kept);
256 });
257
258 it("treats a runtime whose executable no longer runs as a cache miss", () => {
259 const script = buildWslRuntimeInstallScript(
260 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
261 "1.2.3-x64",
262 "b".repeat(64),
263 );
264
265 expect(script).toContain(' [ -x "$1/t3" ] && "$1/t3" --version >/dev/null 2>&1');
266
267 const entryCheckDefined = script.indexOf("runtime_entry_runs() {");
268 const readinessDefined = script.indexOf("runtime_is_ready() {");
269 const readyShortCircuit = script.indexOf("if runtime_is_ready; then");
270 expect(entryCheckDefined).toBeGreaterThan(-1);
271 expect(entryCheckDefined).toBeLessThan(readinessDefined);
272 expect(readinessDefined).toBeLessThan(readyShortCircuit);
273 });
274
275 it("re-hashes the executable against the digest the install recorded", () => {
276 const script = buildWslRuntimeInstallScript(
277 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
278 "1.2.3-x64",
279 "b".repeat(64),
280 );
281
282 expect(script).toContain(` sha256sum "$1/t3" 2>/dev/null | cut -d ' ' -f 1`);
283 expect(script).toContain(
284 ' [ "$recorded_entry_digest" = "$(runtime_server_entry_digest "$runtime_root")" ]',
285 );
286 expect(script).toContain(' [ -n "$recorded_entry_digest" ] &&');
287 expect(script).toContain(
288 `printf '%s\\n' "$installed_entry_digest" > "$runtime_tmp/.t3code-wsl-runtime-ready"`,
289 );
290
291 const extracted = script.indexOf("tar -xzf");
292 const digestRecorded = script.indexOf(
293 'installed_entry_digest=$(runtime_server_entry_digest "$runtime_tmp")',
294 );
295 const markerWritten = script.indexOf('> "$runtime_tmp/.t3code-wsl-runtime-ready"');
296 const promoted = script.indexOf('mv -T "$runtime_tmp" "$runtime_root"');
297 expect(digestRecorded).toBeGreaterThan(extracted);
298 expect(markerWritten).toBeGreaterThan(digestRecorded);
299 expect(promoted).toBeGreaterThan(markerWritten);
300 });
301
302 it("refuses to mark an archive whose executable does not run as ready", () => {
303 const script = buildWslRuntimeInstallScript(
304 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
305 "1.2.3-x64",
306 "b".repeat(64),
307 );
308
309 expect(script).toContain('if ! runtime_entry_runs "$runtime_tmp"; then');
310
311 const payloadValidated = script.indexOf('runtime_entry_runs "$runtime_tmp"');
312 const markerWritten = script.indexOf('> "$runtime_tmp/.t3code-wsl-runtime-ready"');
313 const promoted = script.indexOf('mv -T "$runtime_tmp" "$runtime_root"');
314 expect(payloadValidated).toBeGreaterThan(-1);
315 expect(markerWritten).toBeGreaterThan(payloadValidated);
316 expect(promoted).toBeGreaterThan(payloadValidated);
317 });
318
319 it("parses only absolute Linux runtime paths", () => {
320 expect(parseWslRuntimeRoot("runtimeRoot:/home/josh/.t3/wsl-runtime/1.2.3-x64\n")).toBe(
321 "/home/josh/.t3/wsl-runtime/1.2.3-x64",
322 );
323 expect(parseWslRuntimeRoot("runtimeRoot:relative/path\n")).toBeNull();
324 expect(parseWslRuntimeRoot("noise\n")).toBeNull();
325 });
326
327 it("prunes completed runtimes except the current and newest previous cache", () => {
328 const script = buildWslRuntimePruneScript("1.2.3/x64");
329
330 expect(script).toContain('current_runtime="$runtime_parent/1.2.3_x64"');
331 expect(script).toContain('[ "$candidate" -nt "$previous_runtime" ]');
332 expect(script).toContain('[ "$candidate" != "$current_runtime" ] || continue');
333 expect(script).toContain('[ "$candidate" != "$previous_runtime" ] || continue');
334 expect(script).toContain('[ -f "$candidate/.t3code-wsl-runtime-ready" ] || continue');
335 expect(script).toContain('rm -rf -- "$candidate"');
336 });
337
338 it("never deletes a runtime another backend is running from", () => {
339 const script = buildWslRuntimePruneScript("1.2.3/x64");
340
341 expect(script).toContain(' grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null');
342 expect(script).toContain(' ! runtime_in_use "$candidate" || continue');
343
344 expect(script).toContain("[ -d /proc/1 ] || exit 0");
345
346 const inUseChecked = script.indexOf('! runtime_in_use "$candidate"');
347 const removed = script.indexOf('rm -rf -- "$candidate"');
348 expect(inUseChecked).toBeGreaterThan(-1);
349 expect(removed).toBeGreaterThan(inUseChecked);
350 });
351
352 it("sweeps orphaned install scratch directories the ready-marker loops cannot see", () => {
353 const script = buildWslRuntimePruneScript("1.2.3/x64");
354
355 expect(script).toContain(
356 'for scratch in "$runtime_parent"/.*.tmp.* "$runtime_parent"/.*.stale.*; do',
357 );
358 expect(script).toContain('find "$scratch" -maxdepth 0 -mmin +120');
359 });
360
361 it("invalidates a cache by dropping its ready marker, not the tree", () => {
362 const script = buildWslRuntimeInvalidateScript("1.2.3/x64");
363
364 expect(script).toContain('rm -f "$HOME/.t3/wsl-runtime/1.2.3_x64/.t3code-wsl-runtime-ready"');
365 expect(script).not.toContain("rm -rf");
366 });
367});
368
369describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed)", () => {
370 const fixtures: Array<string> = [];
371
372 afterAll(() => {
373 for (const work of fixtures) runShell(`set -eu\nrm -rf ${sh(work)}`);
374 fixtures.length = 0;
375 });
376
377 const createFixture = () => {
378 const result = runShell(
379 [
380 "set -eu",
381 "work=$(mktemp -d)",
382 'stage="$work/stage/t3-0.0.0-linux-x64"',
383 'mkdir -p "$stage/node_modules/node-pty/build/Release" "$work/home"',
384 `printf '%s' ${sh(SERVER_ENTRY_SOURCE)} > "$stage/t3"`,
385 'chmod +x "$stage/t3"',
386 `printf '%s' 'pty-native-payload' > "$stage/node_modules/node-pty/build/Release/pty.node"`,
387 `tar -czf "$work/wsl-runtime.tar.gz" -C "$work/stage" t3-0.0.0-linux-x64`,
388 `printf 'work:%s\\n' "$work"`,
389 `printf 'archiveSha:%s\\n' "$(sha256sum "$work/wsl-runtime.tar.gz" | cut -d ' ' -f 1)"`,
390 ].join("\n"),
391 );
392 expect(result.status, result.stderr).toBe(0);
393
394 const work = readField(result.stdout, "work");
395 fixtures.push(work);
396 const archivePath = `${work}/wsl-runtime.tar.gz`;
397 const archiveSha = readField(result.stdout, "archiveSha");
398 const runtimeId = `sha256-${archiveSha}`;
399 // The script reads $HOME, and WSL does not inherit the parent process's
400 // environment, so the home override rides in the script itself.
401 const installScript = (archive = archivePath, sha = archiveSha) =>
402 [
403 `HOME=${sh(`${work}/home`)}`,
404 "export HOME",
405 buildWslRuntimeInstallScript(archive, runtimeId, sha),
406 ].join("\n");
407 return {
408 work,
409 archivePath,
410 archiveSha,
411 runtimeId,
412 runtimeParent: `${work}/home/.t3/wsl-runtime`,
413 runtimeRoot: `${work}/home/.t3/wsl-runtime/${runtimeId}`,
414 serverEntry: `${work}/home/.t3/wsl-runtime/${runtimeId}/t3`,
415 installScript,
416 install: (archive?: string, sha?: string) => runShell(installScript(archive, sha)),
417 };
418 };
419
420 const probeFixture = (fixture: ReturnType<typeof createFixture>) =>
421 runShell(
422 [
423 `export HOME=${sh(`${fixture.work}/home`)}`,
424 'export NVM_DIR="$HOME/.nvm" FNM_DIR="$HOME/.fnm" VOLTA_HOME="$HOME/.volta"',
425 "bash() { (",
426 " command() {",
427 ' case "$*" in',
428 ' "-v node"|"-v mise"|"-v fnm"|"-v nodenv") return 1 ;;',
429 ' *) builtin command "$@" ;;',
430 " esac",
431 " }",
432 ' eval "$2"',
433 "); }",
434 buildWslRuntimeProbeScript(fixture.runtimeRoot),
435 ].join("\n"),
436 );
437
438 it("discovers version-managed Node for providers with a standalone runtime", () => {
439 const fixture = createFixture();
440 expect(fixture.install().status).toBe(0);
441 const nodeBin = `${fixture.work}/home/.nvm/versions/node/v24.15.0/bin`;
442 const setup = runShell(
443 [
444 "set -eu",
445 `mkdir -p ${sh(nodeBin)}`,
446 `printf '%s' ${sh('#!/bin/sh\nprintf "linux-node-provider\\n"\n')} > ${sh(`${nodeBin}/node`)}`,
447 `chmod +x ${sh(`${nodeBin}/node`)}`,
448 ].join("\n"),
449 );
450 expect(setup.status, setup.stderr).toBe(0);
451
452 const probe = probeFixture(fixture);
453
454 expect(probe.status, probe.stderr).toBe(0);
455 const resolvedPath = parseResolvedPath(probe.stdout);
456 expect(resolvedPath?.split(":")).toContain(nodeBin);
457 const provider = runShell(`export PATH=${sh(resolvedPath ?? "")}\nnode provider.js`);
458 expect(provider.status, provider.stderr).toBe(0);
459 expect(provider.stdout).toBe("linux-node-provider\n");
460 });
461
462 it("keeps standalone runtime readiness independent of Node availability", () => {
463 const fixture = createFixture();
464 expect(fixture.install().status).toBe(0);
465
466 const probe = probeFixture(fixture);
467
468 expect(probe.status, probe.stderr).toBe(0);
469 expect(parseResolvedPath(probe.stdout)).not.toBeNull();
470 });
471
472 it("keeps the inherited PATH when bash is unavailable", () => {
473 const fixture = createFixture();
474 expect(fixture.install().status).toBe(0);
475 const probe = runShell(
476 [
477 "bash() { return 127; }",
478 'export PATH="/fixture/bin:/usr/bin:/bin"',
479 buildWslRuntimeProbeScript(fixture.runtimeRoot),
480 ].join("\n"),
481 );
482
483 expect(probe.status, probe.stderr).toBe(0);
484 expect(parseResolvedPath(probe.stdout)).toBe("/fixture/bin:/usr/bin:/bin");
485 });
486
487 it("reuses a warm cache without touching the archive", () => {
488 const fixture = createFixture();
489 expect(fixture.install().status).toBe(0);
490 expect(runShell(`set -eu\nrm ${sh(fixture.archivePath)}`).status).toBe(0);
491
492 const warm = fixture.install();
493
494 expect(warm.status, warm.stderr).toBe(0);
495 expect(parseWslRuntimeRoot(warm.stdout)).toBe(fixture.runtimeRoot);
496 });
497
498 it("reinstalls a cache whose executable was truncated", () => {
499 const fixture = createFixture();
500 expect(fixture.install().status).toBe(0);
501 expect(runShell(`set -eu\n: > ${sh(fixture.serverEntry)}`).status).toBe(0);
502
503 const repaired = fixture.install();
504
505 expect(repaired.status, repaired.stderr).toBe(0);
506 expect(parseWslRuntimeRoot(repaired.stdout)).toBe(fixture.runtimeRoot);
507 const restored = runShell(`set -eu\ncat ${sh(fixture.serverEntry)}`);
508 expect(restored.stdout).toBe(SERVER_ENTRY_SOURCE);
509 });
510
511 it("falls back instead of launching a corrupted cache it cannot reinstall", () => {
512 const fixture = createFixture();
513 expect(fixture.install().status).toBe(0);
514 expect(runShell(`set -eu\n: > ${sh(fixture.serverEntry)}`).status).toBe(0);
515 expect(runShell(`set -eu\nrm ${sh(fixture.archivePath)}`).status).toBe(0);
516
517 const broken = fixture.install();
518
519 expect(broken.status).not.toBe(0);
520 expect(parseWslRuntimeRoot(broken.stdout)).toBeNull();
521 });
522
523 it("extracts once when two installs race for the same cache", () => {
524 const fixture = createFixture();
525 const raced = runShell(
526 [
527 "set -eu",
528 `work=${sh(fixture.work)}`,
529 'mkdir -p "$work/bin"',
530 "real_tar=$(command -v tar)",
531 `printf '#!/bin/sh\\nprintf x >> "%s/tar-calls"\\nsleep 1\\nexec %s "$@"\\n' "$work" "$real_tar" > "$work/bin/tar"`,
532 'chmod +x "$work/bin/tar"',
533 ': > "$work/tar-calls"',
534 'PATH="$work/bin:$PATH"',
535 "export PATH",
536 `cat > "$work/install.sh" <<'T3CODE_INSTALL_SCRIPT'`,
537 fixture.installScript(),
538 "T3CODE_INSTALL_SCRIPT",
539 // Both racers run the same file, and neither file path contains the
540 // runtime root, so the script's own /proc scan cannot see them.
541 'sh "$work/install.sh" > "$work/first.out" 2>&1 &',
542 "first=$!",
543 'sh "$work/install.sh" > "$work/second.out" 2>&1 &',
544 "second=$!",
545 "if wait $first; then first_status=0; else first_status=$?; fi",
546 "if wait $second; then second_status=0; else second_status=$?; fi",
547 `printf 'firstStatus:%s\\n' "$first_status"`,
548 `printf 'secondStatus:%s\\n' "$second_status"`,
549 `printf 'extractions:%s\\n' "$(wc -c < "$work/tar-calls" | tr -d ' ')"`,
550 `printf 'firstRoot:%s\\n' "$(sed -n 's/^runtimeRoot://p' "$work/first.out")"`,
551 `printf 'secondRoot:%s\\n' "$(sed -n 's/^runtimeRoot://p' "$work/second.out")"`,
552 ].join("\n"),
553 );
554
555 expect(raced.status, raced.stderr).toBe(0);
556 expect(readField(raced.stdout, "firstStatus")).toBe("0");
557 expect(readField(raced.stdout, "secondStatus")).toBe("0");
558 expect(readField(raced.stdout, "extractions")).toBe("1");
559 expect(readField(raced.stdout, "firstRoot")).toBe(fixture.runtimeRoot);
560 expect(readField(raced.stdout, "secondRoot")).toBe(fixture.runtimeRoot);
561 });
562
563 it("leaves no half-built cache when extraction fails", () => {
564 const fixture = createFixture();
565 const truncated = runShell(
566 [
567 "set -eu",
568 `work=${sh(fixture.work)}`,
569 'size=$(wc -c < "$work/wsl-runtime.tar.gz")',
570 'head -c $((size / 2)) "$work/wsl-runtime.tar.gz" > "$work/truncated.tar.gz"',
571 `printf 'sha:%s\\n' "$(sha256sum "$work/truncated.tar.gz" | cut -d ' ' -f 1)"`,
572 ].join("\n"),
573 );
574 expect(truncated.status, truncated.stderr).toBe(0);
575
576 const failed = fixture.install(
577 `${fixture.work}/truncated.tar.gz`,
578 readField(truncated.stdout, "sha"),
579 );
580
581 expect(failed.status).not.toBe(0);
582 expect(parseWslRuntimeRoot(failed.stdout)).toBeNull();
583 const leftovers = runShell(
584 `set -eu\nfind ${sh(fixture.runtimeParent)} -mindepth 1 -maxdepth 1 -type d`,
585 );
586 expect(leftovers.stdout.trim()).toBe("");
587 });
588
589 it("refuses an archive whose bytes do not match the digest recorded for it", () => {
590 const fixture = createFixture();
591
592 const refused = fixture.install(fixture.archivePath, "e".repeat(64));
593
594 expect(refused.status).not.toBe(0);
595 expect(refused.stderr).toContain("does not match its recorded SHA-256");
596 expect(parseWslRuntimeRoot(refused.stdout)).toBeNull();
597 const leftovers = runShell(
598 `set -eu\nfind ${sh(fixture.runtimeParent)} -mindepth 1 -maxdepth 1 -type d`,
599 );
600 expect(leftovers.stdout.trim()).toBe("");
601 });
602
603 it("leases a warm cache across the prepare-to-spawn handoff", () => {
604 const fixture = createFixture();
605 expect(fixture.install().status).toBe(0);
606 const selected = runShell(
607 [
608 "set -eu",
609 `runtime_parent=${sh(fixture.runtimeParent)}`,
610 'mkdir -p "$runtime_parent/sha256-current" "$runtime_parent/sha256-previous"',
611 'printf ready > "$runtime_parent/sha256-current/.t3code-wsl-runtime-ready"',
612 'printf ready > "$runtime_parent/sha256-previous/.t3code-wsl-runtime-ready"',
613 `touch -d "10 minutes ago" ${sh(fixture.runtimeRoot)}`,
614 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"',
615 `cat > ${sh(`${fixture.work}/select.sh`)} <<'T3CODE_SELECT_SCRIPT'`,
616 fixture.installScript(),
617 "T3CODE_SELECT_SCRIPT",
618 `sh ${sh(`${fixture.work}/select.sh`)}`,
619 `HOME=${sh(`${fixture.work}/home`)}`,
620 "export HOME",
621 buildWslRuntimePruneScript("sha256-current"),
622 `test -d ${sh(fixture.runtimeRoot)}`,
623 ].join("\n"),
624 );
625
626 expect(selected.status, `${selected.stdout}\n${selected.stderr}`).toBe(0);
627 });
628
629 it("prunes a selected cache after its prepare-to-spawn grace period expires", () => {
630 const fixture = createFixture();
631 expect(fixture.install().status).toBe(0);
632 const result = runShell(
633 [
634 "set -eu",
635 `runtime_parent=${sh(fixture.runtimeParent)}`,
636 'mkdir -p "$runtime_parent/sha256-current" "$runtime_parent/sha256-previous"',
637 'printf ready > "$runtime_parent/sha256-current/.t3code-wsl-runtime-ready"',
638 'printf ready > "$runtime_parent/sha256-previous/.t3code-wsl-runtime-ready"',
639 `touch -d "10 minutes ago" ${sh(fixture.runtimeRoot)}`,
640 `touch -d "10 minutes ago" ${sh(`${fixture.runtimeRoot}/.t3code-wsl-runtime-selected`)}`,
641 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"',
642 `HOME=${sh(`${fixture.work}/home`)}`,
643 "export HOME",
644 buildWslRuntimePruneScript("sha256-current"),
645 `test ! -e ${sh(fixture.runtimeRoot)}`,
646 ].join("\n"),
647 );
648
649 expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
650 });
651
652 it("removes an aged stale tree after replacing an active unready cache", () => {
653 const fixture = createFixture();
654 expect(fixture.install().status).toBe(0);
655 const result = runShell(
656 [
657 "set -eu",
658 `runtime_root=${sh(fixture.runtimeRoot)}`,
659 `runtime_parent=${sh(fixture.runtimeParent)}`,
660 'rm "$runtime_root/.t3code-wsl-runtime-ready"',
661 holdRuntimeBusy('"$runtime_root/t3"'),
662 fixture.installScript(),
663 'stale=$(find "$runtime_parent" -maxdepth 1 -type d -name ".sha256-*.stale.*" -print -quit)',
664 'test -n "$stale"',
665 'touch -d "180 minutes ago" "$stale"',
666 `HOME=${sh(`${fixture.work}/home`)}`,
667 "export HOME",
668 buildWslRuntimePruneScript(fixture.runtimeId),
669 'test ! -e "$stale"',
670 ].join("\n"),
671 );
672
673 expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
674 });
675
676 it("prunes old and markerless caches without touching retained, active, locked, or unrelated roots", () => {
677 const result = runShell(
678 [
679 "set -eu",
680 "work=$(mktemp -d)",
681 'home="$work/home"',
682 'runtime_parent="$home/.t3/wsl-runtime"',
683 'mkdir -p "$runtime_parent"',
684 'make_ready() { mkdir -p "$runtime_parent/$1"; printf ready > "$runtime_parent/$1/.t3code-wsl-runtime-ready"; }',
685 "make_ready sha256-current",
686 "make_ready sha256-previous",
687 "make_ready sha256-active",
688 "make_ready sha256-old",
689 "make_ready sha256-locked",
690 'mkdir -p "$runtime_parent/sha256-markerless" "$runtime_parent/versions"',
691 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"',
692 'touch -d "4 minutes ago" "$runtime_parent/sha256-active"',
693 'touch -d "3 minutes ago" "$runtime_parent/sha256-old"',
694 'touch -d "2 minutes ago" "$runtime_parent/sha256-locked"',
695 holdRuntimeBusy('"$runtime_parent/sha256-active/t3"'),
696 holdInstallLock('"$runtime_parent/.sha256-locked.install.lock"'),
697 `HOME="$home"`,
698 "export HOME",
699 buildWslRuntimePruneScript("sha256-current"),
700 'test -d "$runtime_parent/sha256-current"',
701 'test -d "$runtime_parent/sha256-previous"',
702 'test -d "$runtime_parent/sha256-active"',
703 'test -d "$runtime_parent/sha256-locked"',
704 'test -d "$runtime_parent/versions"',
705 'test ! -e "$runtime_parent/sha256-old"',
706 'test ! -e "$runtime_parent/sha256-markerless"',
707 'rm -rf "$work"',
708 ].join("\n"),
709 );
710
711 expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
712 });
713});
714
715describe("parseToolchainReport", () => {
716 it("returns no missing tools and no node version on empty output", () => {
717 expect(parseToolchainReport("")).toEqual({ missingTools: [], nodeVersion: null });
718 });
719
720 it("collects all missing: lines", () => {
721 const stdout = ["missing:make", "missing:g++", "nodeVersion:24.10.0"].join("\n");
722 expect(parseToolchainReport(stdout)).toEqual({
723 missingTools: ["make", "g++"],
724 nodeVersion: "24.10.0",
725 });
726 });
727
728 it("ignores blank lines and trims whitespace", () => {
729 const stdout = [" missing:python3 ", "", " nodeVersion:v22.16.0 "].join("\n");
730 expect(parseToolchainReport(stdout)).toEqual({
731 missingTools: ["python3"],
732 nodeVersion: "v22.16.0",
733 });
734 });
735
736 it("returns null node version when value after prefix is empty", () => {
737 expect(parseToolchainReport("nodeVersion:")).toEqual({
738 missingTools: [],
739 nodeVersion: null,
740 });
741 });
742});
743
744describe("parseNodePath", () => {
745 it("extracts the absolute node path from a nodePath: line", () => {
746 const stdout = "nodePath:/home/josh/.nvm/versions/node/v22.16.0/bin/node";
747 expect(parseNodePath(stdout)).toBe("/home/josh/.nvm/versions/node/v22.16.0/bin/node");
748 });
749
750 it("returns null when node was not found (empty value after prefix)", () => {
751 expect(parseNodePath("nodePath:")).toBeNull();
752 });
753
754 it("returns null when there is no nodePath line at all", () => {
755 expect(parseNodePath("missing:node\nnodeVersion:")).toBeNull();
756 });
757
758 it("ignores surrounding noise and trims whitespace", () => {
759 const stdout = ["some preamble noise", " nodePath:/usr/bin/node ", "trailing"].join("\n");
760 expect(parseNodePath(stdout)).toBe("/usr/bin/node");
761 });
762});
763
764describe("parseNodeVersion", () => {
765 it("extracts the node version from a nodeVersion: line", () => {
766 expect(parseNodeVersion("nodeVersion:24.10.0")).toBe("24.10.0");
767 });
768
769 it("returns null when the version value is empty", () => {
770 expect(parseNodeVersion("nodeVersion:")).toBeNull();
771 });
772
773 it("returns null when there is no nodeVersion line at all", () => {
774 expect(parseNodeVersion("nodePath:/usr/bin/node\nresolvedPath:/usr/bin")).toBeNull();
775 });
776
777 it("ignores surrounding noise and trims whitespace", () => {
778 const stdout = [
779 "some preamble noise",
780 " nodeVersion:22.16.0 ",
781 "nodePath:/usr/bin/node",
782 ].join("\n");
783 expect(parseNodeVersion(stdout)).toBe("22.16.0");
784 });
785});
786
787describe("parseResolvedPath", () => {
788 it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {
789 const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
790 expect(parseResolvedPath(`nodePath:/usr/bin/node\nresolvedPath:${resolvedPath}\n`)).toBe(
791 resolvedPath,
792 );
793 });
794
795 it("accepts CRLF output without retaining the carriage return", () => {
796 expect(parseResolvedPath("resolvedPath:/usr/local/bin:/usr/bin\r\n")).toBe(
797 "/usr/local/bin:/usr/bin",
798 );
799 });
800
801 it("returns null when the resolved PATH is absent or empty", () => {
802 expect(parseResolvedPath("nodePath:/usr/bin/node\n")).toBeNull();
803 expect(parseResolvedPath("resolvedPath:\n")).toBeNull();
804 });
805});
806
807describe("formatMissingToolsReason", () => {
808 it("returns null when everything is present and node is in range", () => {
809 expect(
810 formatMissingToolsReason({ missingTools: [], nodeVersion: "24.10.0" }, "^24.10"),
811 ).toBeNull();
812 });
813
814 it("returns null when range is not specified and tools are present", () => {
815 expect(formatMissingToolsReason({ missingTools: [], nodeVersion: "18.0.0" }, null)).toBeNull();
816 });
817
818 it("flags missing node first", () => {
819 const reason = formatMissingToolsReason(
820 { missingTools: ["node", "make"], nodeVersion: null },
821 "^24.10",
822 );
823 expect(reason).toContain("node");
824 expect(reason).toContain("^24.10");
825 expect(reason).toContain("make");
826 expect(reason).toContain("nvm");
827 });
828
829 it("flags an out-of-range node version with the actual version surfaced", () => {
830 const reason = formatMissingToolsReason(
831 { missingTools: [], nodeVersion: "20.0.0" },
832 "^24.10 || ^22.16",
833 );
834 expect(reason).toContain("node 20.0.0");
835 expect(reason).toContain("requires ^24.10 || ^22.16");
836 });
837
838 it("flags missing build tools without node when node is fine", () => {
839 const reason = formatMissingToolsReason(
840 { missingTools: ["g++", "python3"], nodeVersion: "24.10.0" },
841 "^24.10",
842 );
843 expect(reason).toContain("g++");
844 expect(reason).toContain("python3");
845 expect(reason).toContain("build-essential");
846 expect(reason).not.toContain("nvm");
847 });
848});