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/unstable/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 // Candidates rather than a platform switch: wsl.exe simply fails to spawn
39 // where it does not exist, which is the same answer as a shell missing flock.
40 const candidates = [
41 { file: "bash", args: [] as ReadonlyArray<string> },
42 { file: "wsl.exe", args: ["-e", "bash"] as ReadonlyArray<string> },
43 ];
44 const probe = [
45 "[ -d /proc/1 ] || exit 1",
46 ...REQUIRED_SHELL_TOOLS.map((tool) => `command -v ${tool} >/dev/null || exit 1`),
47 ].join("\n");
48 return (
49 candidates.find((candidate) => {
50 const result = NodeChildProcess.spawnSync(candidate.file, [...candidate.args, "-c", probe], {
51 encoding: "utf8",
52 });
53 return result.status === 0;
54 }) ?? null
55 );
56})();
57
58const runShell = (script: string) => {
59 if (posixShellRunner === null) throw new Error("no POSIX shell runner available");
60 // The install script arrives on stdin in production too, which is what lets
61 // its own /proc scan not match itself.
62 const result = NodeChildProcess.spawnSync(
63 posixShellRunner.file,
64 [...posixShellRunner.args, "-s"],
65 { input: script, encoding: "utf8" },
66 );
67 return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
68};
69
70const sh = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
71
72const readField = (stdout: string, field: string) => {
73 const line = stdout.split("\n").find((candidate) => candidate.startsWith(`${field}:`));
74 if (line === undefined) throw new Error(`missing ${field} in fixture output: ${stdout}`);
75 return line.slice(field.length + 1).trim();
76};
77
78// Stands in for the release's self-contained `t3` executable: the install
79// script only asks it for `--version`.
80const SERVER_ENTRY_SOURCE = '#!/bin/sh\necho "t3code wsl runtime test server 0.0.0"\n';
81
82const makeDistroListSpawner = (result: { readonly stdout?: string; readonly exitCode?: number }) =>
83 ChildProcessSpawner.make(() =>
84 Effect.succeed(
85 ChildProcessSpawner.makeHandle({
86 pid: ChildProcessSpawner.ProcessId(1),
87 exitCode:
88 result.exitCode === undefined
89 ? Effect.never
90 : Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)),
91 isRunning: Effect.succeed(result.exitCode === undefined),
92 kill: () => Effect.void,
93 unref: Effect.succeed(Effect.void),
94 stdin: Sink.drain,
95 stdout: Stream.make(encoder.encode(result.stdout ?? "")),
96 stderr: Stream.empty,
97 all: Stream.empty,
98 getInputFd: () => Sink.drain,
99 getOutputFd: () => Stream.empty,
100 }),
101 ),
102 );
103
104describe("probeWslDistros", () => {
105 it.effect("preserves a successful empty distro list", () =>
106 Effect.gen(function* () {
107 const distros = yield* probeWslDistros;
108 expect(distros).toEqual([]);
109 }).pipe(
110 Effect.provideService(
111 ChildProcessSpawner.ChildProcessSpawner,
112 makeDistroListSpawner({ stdout: "", exitCode: 0 }),
113 ),
114 ),
115 );
116
117 it.effect("fails when the distro-list command exits unsuccessfully", () =>
118 Effect.gen(function* () {
119 const error = yield* probeWslDistros.pipe(Effect.flip);
120 expect(error).toBeInstanceOf(DesktopWslDistroListError);
121 expect(error.message).toContain("exited with code 1");
122 }).pipe(
123 Effect.provideService(
124 ChildProcessSpawner.ChildProcessSpawner,
125 makeDistroListSpawner({ exitCode: 1 }),
126 ),
127 ),
128 );
129
130 it.effect("fails when the distro-list command times out", () => {
131 const layer = Layer.merge(
132 TestClock.layer(),
133 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, makeDistroListSpawner({})),
134 );
135 return Effect.gen(function* () {
136 const fiber = yield* probeWslDistros.pipe(Effect.flip, Effect.forkScoped);
137 yield* Effect.yieldNow;
138 yield* TestClock.adjust(Duration.seconds(8));
139 const error = yield* Fiber.join(fiber);
140 expect(error).toBeInstanceOf(DesktopWslDistroListError);
141 expect(error.message).toContain("timed out");
142 }).pipe(Effect.provide(layer));
143 });
144});
145
146describe("WSL runtime cache", () => {
147 it.each([
148 [
149 "install",
150 (id: string) => buildWslRuntimeInstallScript("/runtime.tar.gz", id, "b".repeat(64)),
151 ],
152 ["prune", buildWslRuntimePruneScript],
153 ["invalidate", buildWslRuntimeInvalidateScript],
154 ] as const)("sanitizes cache ids in the %s script", (_, buildScript) => {
155 const runtimeId = "1.2.3/x64; touch /tmp/nope";
156 const script = buildScript(runtimeId);
157 expect(script).toContain("/1.2.3_x64__touch__tmp_nope");
158 expect(script).not.toContain(runtimeId);
159 });
160
161 it("installs through a temporary directory and only reuses valid completed caches", () => {
162 const script = buildWslRuntimeInstallScript(
163 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
164 "1.2.3-x64",
165 "b".repeat(64),
166 );
167
168 expect(script).toContain('runtime_parent="$HOME/.t3/wsl-runtime"');
169 expect(script).toContain(' [ -f "$ready_marker" ] &&');
170 expect(script).toContain(' runtime_entry_runs "$runtime_root" &&');
171 expect(script).toContain("if runtime_is_ready; then");
172 expect(script).not.toContain("bin.mjs");
173 expect(script).not.toContain("node-pty");
174 expect(script).toContain("trap 'exit 1' HUP INT TERM");
175 expect(script).toContain('exec 9> "$runtime_lock"');
176 expect(script).toContain("flock -x 9");
177 expect(script).not.toContain('rm -rf "$runtime_lock"');
178 expect(script).toContain('mv -T "$runtime_root" "$runtime_stale"');
179 expect(script).toContain('mktemp -d "$runtime_parent/.1.2.3-x64.tmp.XXXXXX"');
180 // The release archive wraps everything in one `t3-<version>-linux-x64/`
181 // directory; stripping it puts the executable at `$runtime_root/t3`.
182 expect(script).toContain(
183 "tar -xzf '/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz' -C \"$runtime_tmp\" --strip-components=1",
184 );
185 expect(script).toContain('if ! runtime_entry_runs "$runtime_tmp"; then');
186 expect(script).toContain('mv -T "$runtime_tmp" "$runtime_root"');
187 expect(script).not.toContain('rm -rf "$runtime_root"');
188
189 const lockAcquired = script.indexOf("flock -x 9");
190 const readinessAfterLock = script.indexOf("if runtime_is_ready; then", lockAcquired + 1);
191 const existingRuntimeMoved = script.indexOf('mv -T "$runtime_root" "$runtime_stale"');
192 expect(lockAcquired).toBeGreaterThan(-1);
193 expect(readinessAfterLock).toBeGreaterThan(lockAcquired);
194 expect(existingRuntimeMoved).toBeGreaterThan(readinessAfterLock);
195 });
196
197 it("verifies the archive digest before extracting, and only on a cache miss", () => {
198 const script = buildWslRuntimeInstallScript(
199 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
200 "1.2.3-x64",
201 "b".repeat(64),
202 );
203
204 const expected = "b".repeat(64);
205 expect(script).toContain(
206 "archive_sha=$(sha256sum '/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz' | cut -d ' ' -f 1)",
207 );
208 expect(script).toContain(`if [ "$archive_sha" != '${expected}' ]; then`);
209
210 // A warm cache exits before the hash, so reuse never pays for it, and the
211 // mismatch check runs before anything mutates the cache.
212 const readyShortCircuit = script.indexOf("if runtime_is_ready; then");
213 const digestChecked = script.indexOf("archive_sha=$(sha256sum");
214 const existingRuntimeMoved = script.indexOf('mv -T "$runtime_root" "$runtime_stale"');
215 const extracted = script.indexOf("tar -xzf");
216 expect(digestChecked).toBeGreaterThan(readyShortCircuit);
217 expect(existingRuntimeMoved).toBeGreaterThan(digestChecked);
218 expect(extracted).toBeGreaterThan(digestChecked);
219 });
220
221 // Invalidation revokes the ready marker without stopping the backend that
222 // failed the probe, so the next install can find an unready tree that a live
223 // process is still running out of. Deleting it there unlinks node_modules
224 // under that process; the pruner already refuses to touch in-use caches, and
225 // the install path has to refuse too.
226 it("moves an in-use runtime aside instead of deleting it under a live backend", () => {
227 const script = buildWslRuntimeInstallScript(
228 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
229 "sha256-" + "c".repeat(64),
230 "b".repeat(64),
231 );
232
233 expect(script).toContain('grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null');
234 // No /proc means no way to tell, and guessing wrong costs a backend its
235 // runtime, so an unknowable answer has to count as in use.
236 expect(script).toContain(" [ -d /proc/1 ] || return 0");
237 expect(script).toContain(' if runtime_in_use "$runtime_root"; then');
238
239 // A process's cmdline keeps the pre-rename path, so the question is only
240 // answerable before the move.
241 const inUseChecked = script.indexOf('if runtime_in_use "$runtime_root"; then');
242 const moved = script.indexOf('mv -T "$runtime_root" "$runtime_stale"');
243 expect(inUseChecked).toBeGreaterThan(-1);
244 expect(inUseChecked).toBeLessThan(moved);
245
246 // In use: keep the tree and restart the sweep's clock, because renaming
247 // preserves the directory's mtime and a long-installed tree would otherwise
248 // already be past the age gate. Idle: delete it now, as before.
249 const kept = script.indexOf('touch "$runtime_stale"');
250 const deleted = script.indexOf('rm -rf "$runtime_stale"');
251 expect(kept).toBeGreaterThan(moved);
252 expect(deleted).toBeGreaterThan(kept);
253 });
254
255 it("treats a runtime whose executable no longer runs as a cache miss", () => {
256 const script = buildWslRuntimeInstallScript(
257 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
258 "1.2.3-x64",
259 "b".repeat(64),
260 );
261
262 // The same proof the SSH runner and CLI installers use: executable, and
263 // `--version` exits 0. That is what decides arch and loadability, so no
264 // separate native probe is needed.
265 expect(script).toContain(' [ -x "$1/t3" ] && "$1/t3" --version >/dev/null 2>&1');
266
267 // Readiness gates the short-circuit, so a cache whose executable broke
268 // reinstalls from the archive instead of being reused forever.
269 const entryCheckDefined = script.indexOf("runtime_entry_runs() {");
270 const readinessDefined = script.indexOf("runtime_is_ready() {");
271 const readyShortCircuit = script.indexOf("if runtime_is_ready; then");
272 expect(entryCheckDefined).toBeGreaterThan(-1);
273 expect(entryCheckDefined).toBeLessThan(readinessDefined);
274 expect(readinessDefined).toBeLessThan(readyShortCircuit);
275 });
276
277 // A swapped or half-written `t3` can still exist and even still answer
278 // `--version`, and launch then runs something this install never verified.
279 // The digest the install records is what turns that into a miss.
280 it("re-hashes the executable against the digest the install recorded", () => {
281 const script = buildWslRuntimeInstallScript(
282 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
283 "1.2.3-x64",
284 "b".repeat(64),
285 );
286
287 expect(script).toContain(` sha256sum "$1/t3" 2>/dev/null | cut -d ' ' -f 1`);
288 expect(script).toContain(
289 ' [ "$recorded_entry_digest" = "$(runtime_server_entry_digest "$runtime_root")" ]',
290 );
291 // A runtime installed before the marker carried a digest reads as empty,
292 // which has to be a miss rather than a pass.
293 expect(script).toContain(' [ -n "$recorded_entry_digest" ] &&');
294 expect(script).toContain(
295 `printf '%s\\n' "$installed_entry_digest" > "$runtime_tmp/.t3code-wsl-runtime-ready"`,
296 );
297
298 // The digest is recorded after extraction and before promotion.
299 const extracted = script.indexOf("tar -xzf");
300 const digestRecorded = script.indexOf(
301 'installed_entry_digest=$(runtime_server_entry_digest "$runtime_tmp")',
302 );
303 const markerWritten = script.indexOf('> "$runtime_tmp/.t3code-wsl-runtime-ready"');
304 const promoted = script.indexOf('mv -T "$runtime_tmp" "$runtime_root"');
305 expect(digestRecorded).toBeGreaterThan(extracted);
306 expect(markerWritten).toBeGreaterThan(digestRecorded);
307 expect(promoted).toBeGreaterThan(markerWritten);
308 });
309
310 it("refuses to mark an archive whose executable does not run as ready", () => {
311 const script = buildWslRuntimeInstallScript(
312 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
313 "1.2.3-x64",
314 "b".repeat(64),
315 );
316
317 expect(script).toContain('if ! runtime_entry_runs "$runtime_tmp"; then');
318
319 // The extracted tree is rejected before the ready marker is written, so a
320 // defective archive falls back to the mounted tree instead of caching.
321 const payloadValidated = script.indexOf('runtime_entry_runs "$runtime_tmp"');
322 const markerWritten = script.indexOf('> "$runtime_tmp/.t3code-wsl-runtime-ready"');
323 const promoted = script.indexOf('mv -T "$runtime_tmp" "$runtime_root"');
324 expect(payloadValidated).toBeGreaterThan(-1);
325 expect(markerWritten).toBeGreaterThan(payloadValidated);
326 expect(promoted).toBeGreaterThan(payloadValidated);
327 });
328
329 it("parses only absolute Linux runtime paths", () => {
330 expect(parseWslRuntimeRoot("runtimeRoot:/home/josh/.t3/wsl-runtime/1.2.3-x64\n")).toBe(
331 "/home/josh/.t3/wsl-runtime/1.2.3-x64",
332 );
333 expect(parseWslRuntimeRoot("runtimeRoot:relative/path\n")).toBeNull();
334 expect(parseWslRuntimeRoot("noise\n")).toBeNull();
335 });
336
337 it("prunes completed runtimes except the current and newest previous cache", () => {
338 const script = buildWslRuntimePruneScript("1.2.3/x64");
339
340 expect(script).toContain('current_runtime="$runtime_parent/1.2.3_x64"');
341 expect(script).toContain('[ "$candidate" -nt "$previous_runtime" ]');
342 expect(script).toContain('[ "$candidate" != "$current_runtime" ] || continue');
343 expect(script).toContain('[ "$candidate" != "$previous_runtime" ] || continue');
344 expect(script).toContain('[ -f "$candidate/.t3code-wsl-runtime-ready" ] || continue');
345 expect(script).toContain('rm -rf -- "$candidate"');
346 });
347
348 it("never deletes a runtime another backend is running from", () => {
349 const script = buildWslRuntimePruneScript("1.2.3/x64");
350
351 // The running backend's argv holds `<runtime>/t3`, so
352 // the process itself is the lease and exiting releases it. Nothing has to be
353 // registered up front, which is what makes this cover backends already
354 // running from an older version that knows nothing about pruning.
355 expect(script).toContain(' grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null');
356 expect(script).toContain(' ! runtime_in_use "$candidate" || continue');
357
358 // Without visible processes the retention rules cannot tell a live cache
359 // from an abandoned one, so the sweep is skipped rather than guessed at.
360 expect(script).toContain("[ -d /proc/1 ] || exit 0");
361
362 // The guard has to gate the delete, not just exist.
363 const inUseChecked = script.indexOf('! runtime_in_use "$candidate"');
364 const removed = script.indexOf('rm -rf -- "$candidate"');
365 expect(inUseChecked).toBeGreaterThan(-1);
366 expect(removed).toBeGreaterThan(inUseChecked);
367 });
368
369 it("sweeps orphaned install scratch directories the ready-marker loops cannot see", () => {
370 const script = buildWslRuntimePruneScript("1.2.3/x64");
371
372 // Dot-prefixed, so `"$runtime_parent"/*` never matches them, and they carry
373 // no ready marker either; without this pass a killed install leaks forever.
374 expect(script).toContain(
375 'for scratch in "$runtime_parent"/.*.tmp.* "$runtime_parent"/.*.stale.*; do',
376 );
377 // Age guard: a scratch directory younger than this belongs to a live install.
378 expect(script).toContain('find "$scratch" -maxdepth 0 -mmin +120');
379 });
380
381 it("invalidates a cache by dropping its ready marker, not the tree", () => {
382 const script = buildWslRuntimeInvalidateScript("1.2.3/x64");
383
384 // Readiness is a presence check, so a tree whose pty.node is present but
385 // unloadable stays ready forever unless the probe can revoke the marker.
386 expect(script).toContain('rm -f "$HOME/.t3/wsl-runtime/1.2.3_x64/.t3code-wsl-runtime-ready"');
387 // Deleting the tree here would pull it out from under any backend still
388 // running from it; the next install moves an unready root aside instead.
389 expect(script).not.toContain("rm -rf");
390 });
391});
392
393// Reading the generated script proves what it says, not what it does. A cache
394// whose entry was truncated satisfied every assertion above and still got
395// reused, so these run the real script against a real archive in a throwaway
396// HOME and check the outcome.
397describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed)", () => {
398 const fixtures: Array<string> = [];
399
400 afterAll(() => {
401 for (const work of fixtures) runShell(`set -eu\nrm -rf ${sh(work)}`);
402 fixtures.length = 0;
403 });
404
405 const createFixture = () => {
406 const result = runShell(
407 [
408 "set -eu",
409 "work=$(mktemp -d)",
410 // Mirrors the release archive: one top-level versioned directory that
411 // holds the executable and its native addons.
412 'stage="$work/stage/t3-0.0.0-linux-x64"',
413 'mkdir -p "$stage/node_modules/node-pty/build/Release" "$work/home"',
414 `printf '%s' ${sh(SERVER_ENTRY_SOURCE)} > "$stage/t3"`,
415 'chmod +x "$stage/t3"',
416 `printf '%s' 'pty-native-payload' > "$stage/node_modules/node-pty/build/Release/pty.node"`,
417 `tar -czf "$work/wsl-runtime.tar.gz" -C "$work/stage" t3-0.0.0-linux-x64`,
418 `printf 'work:%s\\n' "$work"`,
419 `printf 'archiveSha:%s\\n' "$(sha256sum "$work/wsl-runtime.tar.gz" | cut -d ' ' -f 1)"`,
420 ].join("\n"),
421 );
422 expect(result.status, result.stderr).toBe(0);
423
424 const work = readField(result.stdout, "work");
425 fixtures.push(work);
426 const archivePath = `${work}/wsl-runtime.tar.gz`;
427 const archiveSha = readField(result.stdout, "archiveSha");
428 const runtimeId = `sha256-${archiveSha}`;
429 // The script reads $HOME, and WSL does not inherit the parent process's
430 // environment, so the home override rides in the script itself.
431 const installScript = (archive = archivePath, sha = archiveSha) =>
432 [
433 `HOME=${sh(`${work}/home`)}`,
434 "export HOME",
435 buildWslRuntimeInstallScript(archive, runtimeId, sha),
436 ].join("\n");
437 return {
438 work,
439 archivePath,
440 archiveSha,
441 runtimeId,
442 runtimeParent: `${work}/home/.t3/wsl-runtime`,
443 runtimeRoot: `${work}/home/.t3/wsl-runtime/${runtimeId}`,
444 serverEntry: `${work}/home/.t3/wsl-runtime/${runtimeId}/t3`,
445 installScript,
446 install: (archive?: string, sha?: string) => runShell(installScript(archive, sha)),
447 };
448 };
449
450 const probeFixture = (fixture: ReturnType<typeof createFixture>) =>
451 runShell(
452 [
453 `export HOME=${sh(`${fixture.work}/home`)}`,
454 'export NVM_DIR="$HOME/.nvm" FNM_DIR="$HOME/.fnm" VOLTA_HOME="$HOME/.volta"',
455 // Isolate login profiles and hide the host's Node/version managers.
456 // The resolver must discover the fixture's installation itself.
457 "bash() { (",
458 " command() {",
459 ' case "$*" in',
460 ' "-v node"|"-v mise"|"-v fnm"|"-v nodenv") return 1 ;;',
461 ' *) builtin command "$@" ;;',
462 " esac",
463 " }",
464 ' eval "$2"',
465 "); }",
466 buildWslRuntimeProbeScript(fixture.runtimeRoot),
467 ].join("\n"),
468 );
469
470 it("discovers version-managed Node for providers with a standalone runtime", () => {
471 const fixture = createFixture();
472 expect(fixture.install().status).toBe(0);
473 const nodeBin = `${fixture.work}/home/.nvm/versions/node/v24.15.0/bin`;
474 const setup = runShell(
475 [
476 "set -eu",
477 `mkdir -p ${sh(nodeBin)}`,
478 `printf '%s' ${sh('#!/bin/sh\nprintf "linux-node-provider\\n"\n')} > ${sh(`${nodeBin}/node`)}`,
479 `chmod +x ${sh(`${nodeBin}/node`)}`,
480 ].join("\n"),
481 );
482 expect(setup.status, setup.stderr).toBe(0);
483
484 const probe = probeFixture(fixture);
485
486 expect(probe.status, probe.stderr).toBe(0);
487 const resolvedPath = parseResolvedPath(probe.stdout);
488 expect(resolvedPath?.split(":")).toContain(nodeBin);
489 const provider = runShell(`export PATH=${sh(resolvedPath ?? "")}\nnode provider.js`);
490 expect(provider.status, provider.stderr).toBe(0);
491 expect(provider.stdout).toBe("linux-node-provider\n");
492 });
493
494 it("keeps standalone runtime readiness independent of Node availability", () => {
495 const fixture = createFixture();
496 expect(fixture.install().status).toBe(0);
497
498 const probe = probeFixture(fixture);
499
500 expect(probe.status, probe.stderr).toBe(0);
501 expect(parseResolvedPath(probe.stdout)).not.toBeNull();
502 });
503
504 it("keeps the inherited PATH when bash is unavailable", () => {
505 const fixture = createFixture();
506 expect(fixture.install().status).toBe(0);
507 const probe = runShell(
508 [
509 "bash() { return 127; }",
510 'export PATH="/fixture/bin:/usr/bin:/bin"',
511 buildWslRuntimeProbeScript(fixture.runtimeRoot),
512 ].join("\n"),
513 );
514
515 expect(probe.status, probe.stderr).toBe(0);
516 expect(parseResolvedPath(probe.stdout)).toBe("/fixture/bin:/usr/bin:/bin");
517 });
518
519 it("reuses a warm cache without touching the archive", () => {
520 const fixture = createFixture();
521 expect(fixture.install().status).toBe(0);
522 // Deleting the archive is how the test tells reuse apart from a silent
523 // reinstall: only the warm path can succeed without it.
524 expect(runShell(`set -eu\nrm ${sh(fixture.archivePath)}`).status).toBe(0);
525
526 const warm = fixture.install();
527
528 expect(warm.status, warm.stderr).toBe(0);
529 expect(parseWslRuntimeRoot(warm.stdout)).toBe(fixture.runtimeRoot);
530 });
531
532 it("reinstalls a cache whose executable was truncated", () => {
533 const fixture = createFixture();
534 expect(fixture.install().status).toBe(0);
535 expect(runShell(`set -eu\n: > ${sh(fixture.serverEntry)}`).status).toBe(0);
536
537 const repaired = fixture.install();
538
539 expect(repaired.status, repaired.stderr).toBe(0);
540 expect(parseWslRuntimeRoot(repaired.stdout)).toBe(fixture.runtimeRoot);
541 const restored = runShell(`set -eu\ncat ${sh(fixture.serverEntry)}`);
542 expect(restored.stdout).toBe(SERVER_ENTRY_SOURCE);
543 });
544
545 it("falls back instead of launching a corrupted cache it cannot reinstall", () => {
546 const fixture = createFixture();
547 expect(fixture.install().status).toBe(0);
548 expect(runShell(`set -eu\n: > ${sh(fixture.serverEntry)}`).status).toBe(0);
549 expect(runShell(`set -eu\nrm ${sh(fixture.archivePath)}`).status).toBe(0);
550
551 const broken = fixture.install();
552
553 // Non-zero with no runtimeRoot is what sends the backend to the mounted
554 // server tree. Exiting 0 here is the bug: launch would pick the zero-byte
555 // server, fail to become ready, and do it again on every restart.
556 expect(broken.status).not.toBe(0);
557 expect(parseWslRuntimeRoot(broken.stdout)).toBeNull();
558 });
559
560 it("extracts once when two installs race for the same cache", () => {
561 const fixture = createFixture();
562 // A tar shim counts extractions and holds the critical section open long
563 // enough that the second install is certain to arrive while the first is
564 // still inside it. One extraction is the answer either way the runs
565 // interleave: whoever waits for the lock re-checks readiness before
566 // spending an extract, so a broken lock shows up as two.
567 const raced = runShell(
568 [
569 "set -eu",
570 `work=${sh(fixture.work)}`,
571 'mkdir -p "$work/bin"',
572 "real_tar=$(command -v tar)",
573 `printf '#!/bin/sh\\nprintf x >> "%s/tar-calls"\\nsleep 1\\nexec %s "$@"\\n' "$work" "$real_tar" > "$work/bin/tar"`,
574 'chmod +x "$work/bin/tar"',
575 ': > "$work/tar-calls"',
576 'PATH="$work/bin:$PATH"',
577 "export PATH",
578 `cat > "$work/install.sh" <<'T3CODE_INSTALL_SCRIPT'`,
579 fixture.installScript(),
580 "T3CODE_INSTALL_SCRIPT",
581 // Both racers run the same file, and neither file path contains the
582 // runtime root, so the script's own /proc scan cannot see them.
583 'sh "$work/install.sh" > "$work/first.out" 2>&1 &',
584 "first=$!",
585 'sh "$work/install.sh" > "$work/second.out" 2>&1 &',
586 "second=$!",
587 "if wait $first; then first_status=0; else first_status=$?; fi",
588 "if wait $second; then second_status=0; else second_status=$?; fi",
589 `printf 'firstStatus:%s\\n' "$first_status"`,
590 `printf 'secondStatus:%s\\n' "$second_status"`,
591 `printf 'extractions:%s\\n' "$(wc -c < "$work/tar-calls" | tr -d ' ')"`,
592 `printf 'firstRoot:%s\\n' "$(sed -n 's/^runtimeRoot://p' "$work/first.out")"`,
593 `printf 'secondRoot:%s\\n' "$(sed -n 's/^runtimeRoot://p' "$work/second.out")"`,
594 ].join("\n"),
595 );
596
597 expect(raced.status, raced.stderr).toBe(0);
598 expect(readField(raced.stdout, "firstStatus")).toBe("0");
599 expect(readField(raced.stdout, "secondStatus")).toBe("0");
600 expect(readField(raced.stdout, "extractions")).toBe("1");
601 expect(readField(raced.stdout, "firstRoot")).toBe(fixture.runtimeRoot);
602 expect(readField(raced.stdout, "secondRoot")).toBe(fixture.runtimeRoot);
603 });
604
605 it("leaves no half-built cache when extraction fails", () => {
606 const fixture = createFixture();
607 // Truncating the archive and re-recording its digest gets the install past
608 // the digest gate and into a tar that dies mid-stream, which is what a full
609 // disk or an interrupted write looks like from inside the distro.
610 const truncated = runShell(
611 [
612 "set -eu",
613 `work=${sh(fixture.work)}`,
614 'size=$(wc -c < "$work/wsl-runtime.tar.gz")',
615 'head -c $((size / 2)) "$work/wsl-runtime.tar.gz" > "$work/truncated.tar.gz"',
616 `printf 'sha:%s\\n' "$(sha256sum "$work/truncated.tar.gz" | cut -d ' ' -f 1)"`,
617 ].join("\n"),
618 );
619 expect(truncated.status, truncated.stderr).toBe(0);
620
621 const failed = fixture.install(
622 `${fixture.work}/truncated.tar.gz`,
623 readField(truncated.stdout, "sha"),
624 );
625
626 expect(failed.status).not.toBe(0);
627 expect(parseWslRuntimeRoot(failed.stdout)).toBeNull();
628 // A partial extract that survived under the cache name would be promoted by
629 // the next launch's readiness check; scratch that survived would sit there
630 // until the pruner's age sweep. Neither is left behind. Only directories
631 // are counted: the empty flock file stays on purpose, which is what keeps
632 // the lock from carrying stale state across a killed install.
633 const leftovers = runShell(
634 `set -eu\nfind ${sh(fixture.runtimeParent)} -mindepth 1 -maxdepth 1 -type d`,
635 );
636 expect(leftovers.stdout.trim()).toBe("");
637 });
638
639 // The archive and the identity recorded beside it can diverge — a partial
640 // download, or a rebuilt archive dropped next to an older sidecar. Either
641 // gate firing means the bytes never reach the cache under a name that claims
642 // to describe something else.
643 it("refuses an archive whose bytes do not match the digest recorded for it", () => {
644 const fixture = createFixture();
645
646 const refused = fixture.install(fixture.archivePath, "e".repeat(64));
647
648 expect(refused.status).not.toBe(0);
649 expect(refused.stderr).toContain("does not match its recorded SHA-256");
650 expect(parseWslRuntimeRoot(refused.stdout)).toBeNull();
651 const leftovers = runShell(
652 `set -eu\nfind ${sh(fixture.runtimeParent)} -mindepth 1 -maxdepth 1 -type d`,
653 );
654 expect(leftovers.stdout.trim()).toBe("");
655 });
656
657 it("leases a warm cache across the prepare-to-spawn handoff", () => {
658 const fixture = createFixture();
659 expect(fixture.install().status).toBe(0);
660 const selected = runShell(
661 [
662 "set -eu",
663 `runtime_parent=${sh(fixture.runtimeParent)}`,
664 'mkdir -p "$runtime_parent/sha256-current" "$runtime_parent/sha256-previous"',
665 'printf ready > "$runtime_parent/sha256-current/.t3code-wsl-runtime-ready"',
666 'printf ready > "$runtime_parent/sha256-previous/.t3code-wsl-runtime-ready"',
667 `touch -d "10 minutes ago" ${sh(fixture.runtimeRoot)}`,
668 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"',
669 `cat > ${sh(`${fixture.work}/select.sh`)} <<'T3CODE_SELECT_SCRIPT'`,
670 fixture.installScript(),
671 "T3CODE_SELECT_SCRIPT",
672 `sh ${sh(`${fixture.work}/select.sh`)}`,
673 `HOME=${sh(`${fixture.work}/home`)}`,
674 "export HOME",
675 buildWslRuntimePruneScript("sha256-current"),
676 `test -d ${sh(fixture.runtimeRoot)}`,
677 ].join("\n"),
678 );
679
680 expect(selected.status, `${selected.stdout}\n${selected.stderr}`).toBe(0);
681 });
682
683 it("prunes a selected cache after its prepare-to-spawn grace period expires", () => {
684 const fixture = createFixture();
685 expect(fixture.install().status).toBe(0);
686 const result = runShell(
687 [
688 "set -eu",
689 `runtime_parent=${sh(fixture.runtimeParent)}`,
690 'mkdir -p "$runtime_parent/sha256-current" "$runtime_parent/sha256-previous"',
691 'printf ready > "$runtime_parent/sha256-current/.t3code-wsl-runtime-ready"',
692 'printf ready > "$runtime_parent/sha256-previous/.t3code-wsl-runtime-ready"',
693 `touch -d "10 minutes ago" ${sh(fixture.runtimeRoot)}`,
694 `touch -d "10 minutes ago" ${sh(`${fixture.runtimeRoot}/.t3code-wsl-runtime-selected`)}`,
695 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"',
696 `HOME=${sh(`${fixture.work}/home`)}`,
697 "export HOME",
698 buildWslRuntimePruneScript("sha256-current"),
699 `test ! -e ${sh(fixture.runtimeRoot)}`,
700 ].join("\n"),
701 );
702
703 expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
704 });
705
706 it("removes an aged stale tree after replacing an active unready cache", () => {
707 const fixture = createFixture();
708 expect(fixture.install().status).toBe(0);
709 const result = runShell(
710 [
711 "set -eu",
712 `runtime_root=${sh(fixture.runtimeRoot)}`,
713 `runtime_parent=${sh(fixture.runtimeParent)}`,
714 'rm "$runtime_root/.t3code-wsl-runtime-ready"',
715 'sh -c "sleep 30" "$runtime_root/t3" >/dev/null 2>&1 &',
716 "active_pid=$!",
717 "sleep 0.1",
718 fixture.installScript(),
719 'stale=$(find "$runtime_parent" -maxdepth 1 -type d -name ".sha256-*.stale.*" -print -quit)',
720 'test -n "$stale"',
721 'touch -d "180 minutes ago" "$stale"',
722 `HOME=${sh(`${fixture.work}/home`)}`,
723 "export HOME",
724 buildWslRuntimePruneScript(fixture.runtimeId),
725 'test ! -e "$stale"',
726 "kill $active_pid",
727 "wait $active_pid 2>/dev/null || true",
728 ].join("\n"),
729 );
730
731 expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
732 });
733
734 it("prunes old and markerless caches without touching retained, active, locked, or unrelated roots", () => {
735 const result = runShell(
736 [
737 "set -eu",
738 "work=$(mktemp -d)",
739 'home="$work/home"',
740 'runtime_parent="$home/.t3/wsl-runtime"',
741 'mkdir -p "$runtime_parent"',
742 'make_ready() { mkdir -p "$runtime_parent/$1"; printf ready > "$runtime_parent/$1/.t3code-wsl-runtime-ready"; }',
743 "make_ready sha256-current",
744 "make_ready sha256-previous",
745 "make_ready sha256-active",
746 "make_ready sha256-old",
747 "make_ready sha256-locked",
748 'mkdir -p "$runtime_parent/sha256-markerless" "$runtime_parent/versions"',
749 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"',
750 'touch -d "4 minutes ago" "$runtime_parent/sha256-active"',
751 'touch -d "3 minutes ago" "$runtime_parent/sha256-old"',
752 'touch -d "2 minutes ago" "$runtime_parent/sha256-locked"',
753 'sh -c "sleep 30" "$runtime_parent/sha256-active/t3" >/dev/null 2>&1 &',
754 "active_pid=$!",
755 "(",
756 ' exec 9> "$runtime_parent/.sha256-locked.install.lock"',
757 " flock -x 9",
758 " sleep 30",
759 ") >/dev/null 2>&1 &",
760 "lock_pid=$!",
761 "sleep 0.1",
762 `HOME="$home"`,
763 "export HOME",
764 buildWslRuntimePruneScript("sha256-current"),
765 'test -d "$runtime_parent/sha256-current"',
766 'test -d "$runtime_parent/sha256-previous"',
767 'test -d "$runtime_parent/sha256-active"',
768 'test -d "$runtime_parent/sha256-locked"',
769 'test -d "$runtime_parent/versions"',
770 'test ! -e "$runtime_parent/sha256-old"',
771 'test ! -e "$runtime_parent/sha256-markerless"',
772 "kill $active_pid $lock_pid",
773 "wait $active_pid 2>/dev/null || true",
774 "wait $lock_pid 2>/dev/null || true",
775 'rm -rf "$work"',
776 ].join("\n"),
777 );
778
779 expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
780 });
781});
782
783describe("parseToolchainReport", () => {
784 it("returns no missing tools and no node version on empty output", () => {
785 expect(parseToolchainReport("")).toEqual({ missingTools: [], nodeVersion: null });
786 });
787
788 it("collects all missing: lines", () => {
789 const stdout = ["missing:make", "missing:g++", "nodeVersion:24.10.0"].join("\n");
790 expect(parseToolchainReport(stdout)).toEqual({
791 missingTools: ["make", "g++"],
792 nodeVersion: "24.10.0",
793 });
794 });
795
796 it("ignores blank lines and trims whitespace", () => {
797 const stdout = [" missing:python3 ", "", " nodeVersion:v22.16.0 "].join("\n");
798 expect(parseToolchainReport(stdout)).toEqual({
799 missingTools: ["python3"],
800 nodeVersion: "v22.16.0",
801 });
802 });
803
804 it("returns null node version when value after prefix is empty", () => {
805 expect(parseToolchainReport("nodeVersion:")).toEqual({
806 missingTools: [],
807 nodeVersion: null,
808 });
809 });
810});
811
812describe("parseNodePath", () => {
813 it("extracts the absolute node path from a nodePath: line", () => {
814 const stdout = "nodePath:/home/josh/.nvm/versions/node/v22.16.0/bin/node";
815 expect(parseNodePath(stdout)).toBe("/home/josh/.nvm/versions/node/v22.16.0/bin/node");
816 });
817
818 it("returns null when node was not found (empty value after prefix)", () => {
819 expect(parseNodePath("nodePath:")).toBeNull();
820 });
821
822 it("returns null when there is no nodePath line at all", () => {
823 expect(parseNodePath("missing:node\nnodeVersion:")).toBeNull();
824 });
825
826 it("ignores surrounding noise and trims whitespace", () => {
827 const stdout = ["some preamble noise", " nodePath:/usr/bin/node ", "trailing"].join("\n");
828 expect(parseNodePath(stdout)).toBe("/usr/bin/node");
829 });
830});
831
832describe("parseNodeVersion", () => {
833 it("extracts the node version from a nodeVersion: line", () => {
834 expect(parseNodeVersion("nodeVersion:24.10.0")).toBe("24.10.0");
835 });
836
837 it("returns null when the version value is empty", () => {
838 expect(parseNodeVersion("nodeVersion:")).toBeNull();
839 });
840
841 it("returns null when there is no nodeVersion line at all", () => {
842 expect(parseNodeVersion("nodePath:/usr/bin/node\nresolvedPath:/usr/bin")).toBeNull();
843 });
844
845 it("ignores surrounding noise and trims whitespace", () => {
846 const stdout = [
847 "some preamble noise",
848 " nodeVersion:22.16.0 ",
849 "nodePath:/usr/bin/node",
850 ].join("\n");
851 expect(parseNodeVersion(stdout)).toBe("22.16.0");
852 });
853});
854
855describe("parseResolvedPath", () => {
856 it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {
857 const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
858 expect(parseResolvedPath(`nodePath:/usr/bin/node\nresolvedPath:${resolvedPath}\n`)).toBe(
859 resolvedPath,
860 );
861 });
862
863 it("accepts CRLF output without retaining the carriage return", () => {
864 expect(parseResolvedPath("resolvedPath:/usr/local/bin:/usr/bin\r\n")).toBe(
865 "/usr/local/bin:/usr/bin",
866 );
867 });
868
869 it("returns null when the resolved PATH is absent or empty", () => {
870 expect(parseResolvedPath("nodePath:/usr/bin/node\n")).toBeNull();
871 expect(parseResolvedPath("resolvedPath:\n")).toBeNull();
872 });
873});
874
875describe("formatMissingToolsReason", () => {
876 it("returns null when everything is present and node is in range", () => {
877 expect(
878 formatMissingToolsReason({ missingTools: [], nodeVersion: "24.10.0" }, "^24.10"),
879 ).toBeNull();
880 });
881
882 it("returns null when range is not specified and tools are present", () => {
883 expect(formatMissingToolsReason({ missingTools: [], nodeVersion: "18.0.0" }, null)).toBeNull();
884 });
885
886 it("flags missing node first", () => {
887 const reason = formatMissingToolsReason(
888 { missingTools: ["node", "make"], nodeVersion: null },
889 "^24.10",
890 );
891 expect(reason).toContain("node");
892 expect(reason).toContain("^24.10");
893 expect(reason).toContain("make");
894 expect(reason).toContain("nvm");
895 });
896
897 it("flags an out-of-range node version with the actual version surfaced", () => {
898 const reason = formatMissingToolsReason(
899 { missingTools: [], nodeVersion: "20.0.0" },
900 "^24.10 || ^22.16",
901 );
902 expect(reason).toContain("node 20.0.0");
903 expect(reason).toContain("requires ^24.10 || ^22.16");
904 });
905
906 it("flags missing build tools without node when node is fine", () => {
907 const reason = formatMissingToolsReason(
908 { missingTools: ["g++", "python3"], nodeVersion: "24.10.0" },
909 "^24.10",
910 );
911 expect(reason).toContain("g++");
912 expect(reason).toContain("python3");
913 expect(reason).toContain("build-essential");
914 expect(reason).not.toContain("nvm");
915 });
916});