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

DesktopWslEnvironment.test.ts

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