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

DesktopWslEnvironment.test.ts

846 lines35.5 KB

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