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

DesktopWslEnvironment.test.ts

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