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

DesktopWslEnvironment.test.ts

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