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

DesktopWslEnvironment.test.ts

964 lines37.7 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 Deferred from "effect/Deferred";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import * as Sink from "effect/Sink";
14import * as Stream from "effect/Stream";
15import * as TestClock from "effect/testing/TestClock";
16import { ChildProcessSpawner } from "effect/process";
17​
18import * as DesktopConfig from "../app/DesktopConfig.ts";
19import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
20import {
21 buildWslRuntimeInstallScript,
22 buildWslRuntimeInvalidateScript,
23 buildWslRuntimePruneScript,
24 buildWslRuntimeProbeScript,
25 DesktopWslDistroListError,
26 DesktopWslEnvironment,
27 formatMissingToolsReason,
28 layer as wslEnvironmentLayer,
29 parseNodePath,
30 parseNodeVersion,
31 parseResolvedPath,
32 parseToolchainReport,
33 parseWslRuntimeRoot,
34 probeWslDistros,
35} from "./DesktopWslEnvironment.ts";
36​
37const encoder = new TextEncoder();
38​
39// The install script only fails the way this file cares about when a real shell
40// runs it, so find one that has the tools it needs: bash directly on Linux, and
41// the WSL distro on a Windows dev box, where Git Bash ships no flock. Anywhere
42// else the executed suite skips and the generated-text assertions stand alone.
43const REQUIRED_SHELL_TOOLS = ["flock", "sha256sum", "tar", "mktemp"] as const;
44​
45const posixShellRunner = (() => {
46 const candidates = [
47 { file: "bash", args: [] as ReadonlyArray<string> },
48 { file: "wsl.exe", args: ["-e", "bash"] as ReadonlyArray<string> },
49 ];
50 const probe = [
51 "[ -d /proc/1 ] || exit 1",
52 ...REQUIRED_SHELL_TOOLS.map((tool) => `command -v ${tool} >/dev/null || exit 1`),
53 ].join("\n");
54 return (
55 candidates.find((candidate) => {
56 const result = NodeChildProcess.spawnSync(candidate.file, [...candidate.args, "-c", probe], {
57 encoding: "utf8",
58 });
59 return result.status === 0;
60 }) ?? null
61 );
62})();
63​
64const runShell = (script: string) => {
65 if (posixShellRunner === null) throw new Error("no POSIX shell runner available");
66 // The install script arrives on stdin in production too, which is what lets
67 // its own /proc scan not match itself.
68 const result = NodeChildProcess.spawnSync(
69 posixShellRunner.file,
70 [...posixShellRunner.args, "-s"],
71 { input: script, encoding: "utf8" },
72 );
73 return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
74};
75​
76const sh = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
77​
78const awaitHolder = (condition: string) =>
79 `i=0; until ${condition}; do i=$((i + 1)); [ "$i" -lt 500 ] || exit 1; sleep 0.01; done`;
80​
81// Holds a cache busy the way a running server does: the holder's argv[0] is the
82// runtime entry, which the prune and install scripts look for in /proc cmdline.
83// It reads a pipe the script keeps open on fd 7, so it exits with the script
84// instead of outliving it on a timer.
85const holdRuntimeBusy = (entry: string) =>
86 [
87 `exec 7> >(exec -a ${entry} cat >/dev/null 2>&1)`,
88 awaitHolder(`grep -qF -- ${entry} /proc/[0-9]*/cmdline 2>/dev/null`),
89 ].join("\n");
90​
91const holdInstallLock = (lock: string) =>
92 [
93 `exec 6> >(exec 9> ${lock}; flock -x 9; cat >/dev/null 2>&1)`,
94 awaitHolder(`! flock -n ${lock} true`),
95 ].join("\n");
96​
97const readField = (stdout: string, field: string) => {
98 const line = stdout.split("\n").find((candidate) => candidate.startsWith(`${field}:`));
99 if (line === undefined) throw new Error(`missing ${field} in fixture output: ${stdout}`);
100 return line.slice(field.length + 1).trim();
101};
102​
103const SERVER_ENTRY_SOURCE = '#!/bin/sh\necho "t3code wsl runtime test server 0.0.0"\n';
104​
105const makeDistroListSpawner = (result: { readonly stdout?: string; readonly exitCode?: number }) =>
106 ChildProcessSpawner.make(() =>
107 Effect.succeed(
108 ChildProcessSpawner.makeHandle({
109 pid: ChildProcessSpawner.ProcessId(1),
110 exitCode:
111 result.exitCode === undefined
112 ? Effect.never
113 : Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)),
114 isRunning: Effect.succeed(result.exitCode === undefined),
115 kill: () => Effect.void,
116 unref: Effect.succeed(Effect.void),
117 stdin: Sink.drain,
118 stdout: Stream.make(encoder.encode(result.stdout ?? "")),
119 stderr: Stream.empty,
120 all: Stream.empty,
121 getInputFd: () => Sink.drain,
122 getOutputFd: () => Stream.empty,
123 }),
124 ),
125 );
126​
127describe("probeWslDistros", () => {
128 it.effect("preserves a successful empty distro list", () =>
129 Effect.gen(function* () {
130 const distros = yield* probeWslDistros;
131 expect(distros).toEqual([]);
132 }).pipe(
133 Effect.provideService(
134 ChildProcessSpawner.ChildProcessSpawner,
135 makeDistroListSpawner({ stdout: "", exitCode: 0 }),
136 ),
137 ),
138 );
139​
140 it.effect("fails when the distro-list command exits unsuccessfully", () =>
141 Effect.gen(function* () {
142 const error = yield* probeWslDistros.pipe(Effect.flip);
143 expect(error).toBeInstanceOf(DesktopWslDistroListError);
144 expect(error.message).toContain("exited with code 1");
145 }).pipe(
146 Effect.provideService(
147 ChildProcessSpawner.ChildProcessSpawner,
148 makeDistroListSpawner({ exitCode: 1 }),
149 ),
150 ),
151 );
152​
153 it.effect("fails when the distro-list command times out", () => {
154 const layer = Layer.merge(
155 TestClock.layer(),
156 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, makeDistroListSpawner({})),
157 );
158 return Effect.gen(function* () {
159 const fiber = yield* probeWslDistros.pipe(Effect.flip, Effect.forkScoped);
160 yield* Effect.yieldNow;
161 yield* TestClock.adjust(Duration.seconds(8));
162 const error = yield* Fiber.join(fiber);
163 expect(error).toBeInstanceOf(DesktopWslDistroListError);
164 expect(error.message).toContain("timed out");
165 }).pipe(Effect.provide(layer));
166 });
167});
168​
169describe("WSL command deadlines", () => {
170 const makeControlledEnvironment = Effect.gen(function* () {
171 const started = yield* Deferred.make<void>();
172 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
173 const released = yield* Deferred.make<void>();
174 const spawner = ChildProcessSpawner.make(() =>
175 Effect.acquireRelease(
176 Deferred.succeed(started, undefined).pipe(
177 Effect.as(
178 ChildProcessSpawner.makeHandle({
179 pid: ChildProcessSpawner.ProcessId(1),
180 exitCode: Deferred.await(exited),
181 isRunning: Deferred.isDone(exited).pipe(Effect.map((done) => !done)),
182 kill: () => Effect.void,
183 unref: Effect.succeed(Effect.void),
184 stdin: Sink.drain,
185 stdout: Stream.empty,
186 stderr: Stream.empty,
187 all: Stream.empty,
188 getInputFd: () => Sink.drain,
189 getOutputFd: () => Stream.empty,
190 }),
191 ),
192 ),
193 () => Deferred.succeed(released, undefined),
194 ),
195 );
196 const environment = yield* DesktopWslEnvironment.pipe(
197 Effect.provide(
198 wslEnvironmentLayer.pipe(
199 Layer.provide([
200 DesktopEnvironment.layer({
201 dirname: "/repo/apps/desktop",
202 homeDirectory: "/home/test",
203 platform: "win32",
204 processArch: "x64",
205 appVersion: "1.2.3",
206 appPath: "/repo",
207 isPackaged: true,
208 resourcesPath: "/repo/resources",
209 runningUnderArm64Translation: false,
210 }).pipe(Layer.provide([Path.layer, DesktopConfig.layerTest({})])),
211 FileSystem.layerNoop({ exists: () => Effect.succeed(true) }),
212 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
213 ]),
214 ),
215 ),
216 );
217 return { environment, started, exited, released };
218 });
219​
220 it.effect("waits for a cold distro to finish starting after 15 seconds", () =>
221 Effect.gen(function* () {
222 const { environment, started, exited, released } = yield* makeControlledEnvironment;
223 const fiber = yield* environment.preWarm("Ubuntu").pipe(Effect.forkScoped);
224 yield* Deferred.await(started);
225 yield* TestClock.adjust(Duration.seconds(15));
226 expect(yield* Deferred.isDone(released)).toBe(false);
227​
228 yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0));
229 yield* Fiber.join(fiber);
230 expect(yield* Deferred.isDone(released)).toBe(true);
231 }),
232 );
233​
234 it.effect("releases a stalled warmup process at the 30-second deadline", () =>
235 Effect.gen(function* () {
236 const { environment, started, released } = yield* makeControlledEnvironment;
237 const fiber = yield* environment.preWarm("Ubuntu").pipe(Effect.forkScoped);
238 yield* Deferred.await(started);
239 yield* TestClock.adjust(Duration.seconds(29));
240 expect(yield* Deferred.isDone(released)).toBe(false);
241​
242 yield* TestClock.adjust(Duration.seconds(1));
243 yield* Fiber.join(fiber);
244 expect(yield* Deferred.isDone(released)).toBe(true);
245 }),
246 );
247​
248 it.effect("still gives path conversion only 10 seconds and releases its process", () =>
249 Effect.gen(function* () {
250 const { environment, started, released } = yield* makeControlledEnvironment;
251 const fiber = yield* environment
252 .windowsToWslPath("Ubuntu", "C:\\project")
253 .pipe(Effect.forkScoped);
254 yield* Deferred.await(started);
255 yield* TestClock.adjust(Duration.seconds(9));
256 expect(yield* Deferred.isDone(released)).toBe(false);
257​
258 yield* TestClock.adjust(Duration.seconds(1));
259 expect(yield* Fiber.join(fiber)).toEqual(Option.none());
260 expect(yield* Deferred.isDone(released)).toBe(true);
261 }),
262 );
263});
264​
265describe("WSL runtime cache", () => {
266 it.each([
267 [
268 "install",
269 (id: string) => buildWslRuntimeInstallScript("/runtime.tar.gz", id, "b".repeat(64)),
270 ],
271 ["prune", buildWslRuntimePruneScript],
272 ["invalidate", buildWslRuntimeInvalidateScript],
273 ] as const)("sanitizes cache ids in the %s script", (_, buildScript) => {
274 const runtimeId = "1.2.3/x64; touch /tmp/nope";
275 const script = buildScript(runtimeId);
276 expect(script).toContain("/1.2.3_x64__touch__tmp_nope");
277 expect(script).not.toContain(runtimeId);
278 });
279​
280 it("installs through a temporary directory and only reuses valid completed caches", () => {
281 const script = buildWslRuntimeInstallScript(
282 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
283 "1.2.3-x64",
284 "b".repeat(64),
285 );
286​
287 expect(script).toContain('runtime_parent="$HOME/.t3/wsl-runtime"');
288 expect(script).toContain(' [ -f "$ready_marker" ] &&');
289 expect(script).toContain(' runtime_entry_runs "$runtime_root" 2>/dev/null &&');
290 expect(script).toContain("if runtime_is_ready; then");
291 expect(script).not.toContain("bin.mjs");
292 expect(script).not.toContain("node-pty");
293 expect(script).toContain("trap 'exit 1' HUP INT TERM");
294 expect(script).toContain('exec 9> "$runtime_lock"');
295 expect(script).toContain("flock -x 9");
296 expect(script).not.toContain('rm -rf "$runtime_lock"');
297 expect(script).toContain('mv -T "$runtime_root" "$runtime_stale"');
298 expect(script).toContain('mktemp -d "$runtime_parent/.1.2.3-x64.tmp.XXXXXX"');
299 // The release archive wraps everything in one `t3-<version>-linux-x64/`
300 // directory; stripping it puts the executable at `$runtime_root/t3`.
301 expect(script).toContain(
302 "tar -xzf '/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz' -C \"$runtime_tmp\" --strip-components=1",
303 );
304 expect(script).toContain('if ! runtime_entry_runs "$runtime_tmp"; then');
305 expect(script).toContain('mv -T "$runtime_tmp" "$runtime_root"');
306 expect(script).not.toContain('rm -rf "$runtime_root"');
307​
308 const lockAcquired = script.indexOf("flock -x 9");
309 const readinessAfterLock = script.indexOf("if runtime_is_ready; then", lockAcquired + 1);
310 const existingRuntimeMoved = script.indexOf('mv -T "$runtime_root" "$runtime_stale"');
311 expect(lockAcquired).toBeGreaterThan(-1);
312 expect(readinessAfterLock).toBeGreaterThan(lockAcquired);
313 expect(existingRuntimeMoved).toBeGreaterThan(readinessAfterLock);
314 });
315​
316 it("verifies the archive digest before extracting, and only on a cache miss", () => {
317 const script = buildWslRuntimeInstallScript(
318 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
319 "1.2.3-x64",
320 "b".repeat(64),
321 );
322​
323 const expected = "b".repeat(64);
324 expect(script).toContain(
325 "archive_sha=$(sha256sum '/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz' | cut -d ' ' -f 1)",
326 );
327 expect(script).toContain(`if [ "$archive_sha" != '${expected}' ]; then`);
328​
329 const readyShortCircuit = script.indexOf("if runtime_is_ready; then");
330 const digestChecked = script.indexOf("archive_sha=$(sha256sum");
331 const existingRuntimeMoved = script.indexOf('mv -T "$runtime_root" "$runtime_stale"');
332 const extracted = script.indexOf("tar -xzf");
333 expect(digestChecked).toBeGreaterThan(readyShortCircuit);
334 expect(existingRuntimeMoved).toBeGreaterThan(digestChecked);
335 expect(extracted).toBeGreaterThan(digestChecked);
336 });
337​
338 it("moves an in-use runtime aside instead of deleting it under a live backend", () => {
339 const script = buildWslRuntimeInstallScript(
340 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
341 "sha256-" + "c".repeat(64),
342 "b".repeat(64),
343 );
344​
345 expect(script).toContain('grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null');
346 expect(script).toContain(" [ -d /proc/1 ] || return 0");
347 expect(script).toContain(' if runtime_in_use "$runtime_root"; then');
348​
349 // A process's cmdline keeps the pre-rename path, so the question is only
350 // answerable before the move.
351 const inUseChecked = script.indexOf('if runtime_in_use "$runtime_root"; then');
352 const moved = script.indexOf('mv -T "$runtime_root" "$runtime_stale"');
353 expect(inUseChecked).toBeGreaterThan(-1);
354 expect(inUseChecked).toBeLessThan(moved);
355​
356 const kept = script.indexOf('touch "$runtime_stale"');
357 const deleted = script.indexOf('rm -rf "$runtime_stale"');
358 expect(kept).toBeGreaterThan(moved);
359 expect(deleted).toBeGreaterThan(kept);
360 });
361​
362 it("treats a runtime whose executable no longer runs as a cache miss", () => {
363 const script = buildWslRuntimeInstallScript(
364 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
365 "1.2.3-x64",
366 "b".repeat(64),
367 );
368​
369 expect(script).toContain(' [ -x "$1/t3" ] && "$1/t3" --version >/dev/null');
370​
371 const entryCheckDefined = script.indexOf("runtime_entry_runs() {");
372 const readinessDefined = script.indexOf("runtime_is_ready() {");
373 const readyShortCircuit = script.indexOf("if runtime_is_ready; then");
374 expect(entryCheckDefined).toBeGreaterThan(-1);
375 expect(entryCheckDefined).toBeLessThan(readinessDefined);
376 expect(readinessDefined).toBeLessThan(readyShortCircuit);
377 });
378​
379 it("re-hashes the executable against the digest the install recorded", () => {
380 const script = buildWslRuntimeInstallScript(
381 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
382 "1.2.3-x64",
383 "b".repeat(64),
384 );
385​
386 expect(script).toContain(` sha256sum "$1/t3" 2>/dev/null | cut -d ' ' -f 1`);
387 expect(script).toContain(
388 ' [ "$recorded_entry_digest" = "$(runtime_server_entry_digest "$runtime_root")" ]',
389 );
390 expect(script).toContain(' [ -n "$recorded_entry_digest" ] &&');
391 expect(script).toContain(
392 `printf '%s\\n' "$installed_entry_digest" > "$runtime_tmp/.t3code-wsl-runtime-ready"`,
393 );
394​
395 const extracted = script.indexOf("tar -xzf");
396 const digestRecorded = script.indexOf(
397 'installed_entry_digest=$(runtime_server_entry_digest "$runtime_tmp")',
398 );
399 const markerWritten = script.indexOf('> "$runtime_tmp/.t3code-wsl-runtime-ready"');
400 const promoted = script.indexOf('mv -T "$runtime_tmp" "$runtime_root"');
401 expect(digestRecorded).toBeGreaterThan(extracted);
402 expect(markerWritten).toBeGreaterThan(digestRecorded);
403 expect(promoted).toBeGreaterThan(markerWritten);
404 });
405​
406 it("refuses to mark an archive whose executable does not run as ready", () => {
407 const script = buildWslRuntimeInstallScript(
408 "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",
409 "1.2.3-x64",
410 "b".repeat(64),
411 );
412​
413 expect(script).toContain('if ! runtime_entry_runs "$runtime_tmp"; then');
414​
415 const payloadValidated = script.indexOf('runtime_entry_runs "$runtime_tmp"');
416 const markerWritten = script.indexOf('> "$runtime_tmp/.t3code-wsl-runtime-ready"');
417 const promoted = script.indexOf('mv -T "$runtime_tmp" "$runtime_root"');
418 expect(payloadValidated).toBeGreaterThan(-1);
419 expect(markerWritten).toBeGreaterThan(payloadValidated);
420 expect(promoted).toBeGreaterThan(payloadValidated);
421 });
422​
423 it("parses only absolute Linux runtime paths", () => {
424 expect(parseWslRuntimeRoot("runtimeRoot:/home/josh/.t3/wsl-runtime/1.2.3-x64\n")).toBe(
425 "/home/josh/.t3/wsl-runtime/1.2.3-x64",
426 );
427 expect(parseWslRuntimeRoot("runtimeRoot:relative/path\n")).toBeNull();
428 expect(parseWslRuntimeRoot("noise\n")).toBeNull();
429 });
430​
431 it("prunes completed runtimes except the current and newest previous cache", () => {
432 const script = buildWslRuntimePruneScript("1.2.3/x64");
433​
434 expect(script).toContain('current_runtime="$runtime_parent/1.2.3_x64"');
435 expect(script).toContain('[ "$candidate" -nt "$previous_runtime" ]');
436 expect(script).toContain('[ "$candidate" != "$current_runtime" ] || continue');
437 expect(script).toContain('[ "$candidate" != "$previous_runtime" ] || continue');
438 expect(script).toContain('[ -f "$candidate/.t3code-wsl-runtime-ready" ] || continue');
439 expect(script).toContain('rm -rf -- "$candidate"');
440 });
441​
442 it("never deletes a runtime another backend is running from", () => {
443 const script = buildWslRuntimePruneScript("1.2.3/x64");
444​
445 expect(script).toContain(' grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null');
446 expect(script).toContain(' ! runtime_in_use "$candidate" || continue');
447​
448 expect(script).toContain("[ -d /proc/1 ] || exit 0");
449​
450 const inUseChecked = script.indexOf('! runtime_in_use "$candidate"');
451 const removed = script.indexOf('rm -rf -- "$candidate"');
452 expect(inUseChecked).toBeGreaterThan(-1);
453 expect(removed).toBeGreaterThan(inUseChecked);
454 });
455​
456 it("sweeps orphaned install scratch directories the ready-marker loops cannot see", () => {
457 const script = buildWslRuntimePruneScript("1.2.3/x64");
458​
459 expect(script).toContain(
460 'for scratch in "$runtime_parent"/.*.tmp.* "$runtime_parent"/.*.stale.*; do',
461 );
462 expect(script).toContain('find "$scratch" -maxdepth 0 -mmin +120');
463 });
464​
465 it("invalidates a cache by dropping its ready marker, not the tree", () => {
466 const script = buildWslRuntimeInvalidateScript("1.2.3/x64");
467​
468 expect(script).toContain('rm -f "$HOME/.t3/wsl-runtime/1.2.3_x64/.t3code-wsl-runtime-ready"');
469 expect(script).not.toContain("rm -rf");
470 });
471});
472​
473describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed)", () => {
474 const fixtures: Array<string> = [];
475​
476 afterAll(() => {
477 for (const work of fixtures) runShell(`set -eu\nrm -rf ${sh(work)}`);
478 fixtures.length = 0;
479 });
480​
481 const createFixture = (serverEntry = SERVER_ENTRY_SOURCE) => {
482 const result = runShell(
483 [
484 "set -eu",
485 "work=$(mktemp -d)",
486 'stage="$work/stage/t3-0.0.0-linux-x64"',
487 'mkdir -p "$stage/node_modules/node-pty/build/Release" "$work/home"',
488 `printf '%s' ${sh(serverEntry)} > "$stage/t3"`,
489 'chmod +x "$stage/t3"',
490 `printf '%s' 'pty-native-payload' > "$stage/node_modules/node-pty/build/Release/pty.node"`,
491 `tar -czf "$work/wsl-runtime.tar.gz" -C "$work/stage" t3-0.0.0-linux-x64`,
492 `printf 'work:%s\\n' "$work"`,
493 `printf 'archiveSha:%s\\n' "$(sha256sum "$work/wsl-runtime.tar.gz" | cut -d ' ' -f 1)"`,
494 ].join("\n"),
495 );
496 expect(result.status, result.stderr).toBe(0);
497​
498 const work = readField(result.stdout, "work");
499 fixtures.push(work);
500 const archivePath = `${work}/wsl-runtime.tar.gz`;
501 const archiveSha = readField(result.stdout, "archiveSha");
502 const runtimeId = `sha256-${archiveSha}`;
503 // The script reads $HOME, and WSL does not inherit the parent process's
504 // environment, so the home override rides in the script itself.
505 const installScript = (archive = archivePath, sha = archiveSha) =>
506 [
507 `HOME=${sh(`${work}/home`)}`,
508 "export HOME",
509 buildWslRuntimeInstallScript(archive, runtimeId, sha),
510 ].join("\n");
511 return {
512 work,
513 archivePath,
514 archiveSha,
515 runtimeId,
516 runtimeParent: `${work}/home/.t3/wsl-runtime`,
517 runtimeRoot: `${work}/home/.t3/wsl-runtime/${runtimeId}`,
518 serverEntry: `${work}/home/.t3/wsl-runtime/${runtimeId}/t3`,
519 installScript,
520 install: (archive?: string, sha?: string) => runShell(installScript(archive, sha)),
521 };
522 };
523​
524 const probeFixture = (fixture: ReturnType<typeof createFixture>) =>
525 runShell(
526 [
527 `export HOME=${sh(`${fixture.work}/home`)}`,
528 'export NVM_DIR="$HOME/.nvm" FNM_DIR="$HOME/.fnm" VOLTA_HOME="$HOME/.volta"',
529 "bash() { (",
530 " command() {",
531 ' case "$*" in',
532 ' "-v node"|"-v mise"|"-v fnm"|"-v nodenv") return 1 ;;',
533 ' *) builtin command "$@" ;;',
534 " esac",
535 " }",
536 ' eval "$2"',
537 "); }",
538 buildWslRuntimeProbeScript(fixture.runtimeRoot),
539 ].join("\n"),
540 );
541​
542 it("discovers version-managed Node for providers with a standalone runtime", () => {
543 const fixture = createFixture();
544 expect(fixture.install().status).toBe(0);
545 const nodeBin = `${fixture.work}/home/.nvm/versions/node/v24.15.0/bin`;
546 const setup = runShell(
547 [
548 "set -eu",
549 `mkdir -p ${sh(nodeBin)}`,
550 `printf '%s' ${sh('#!/bin/sh\nprintf "linux-node-provider\\n"\n')} > ${sh(`${nodeBin}/node`)}`,
551 `chmod +x ${sh(`${nodeBin}/node`)}`,
552 ].join("\n"),
553 );
554 expect(setup.status, setup.stderr).toBe(0);
555​
556 const probe = probeFixture(fixture);
557​
558 expect(probe.status, probe.stderr).toBe(0);
559 const resolvedPath = parseResolvedPath(probe.stdout);
560 expect(resolvedPath?.split(":")).toContain(nodeBin);
561 const provider = runShell(`export PATH=${sh(resolvedPath ?? "")}\nnode provider.js`);
562 expect(provider.status, provider.stderr).toBe(0);
563 expect(provider.stdout).toBe("linux-node-provider\n");
564 });
565​
566 it("keeps standalone runtime readiness independent of Node availability", () => {
567 const fixture = createFixture();
568 expect(fixture.install().status).toBe(0);
569​
570 const probe = probeFixture(fixture);
571​
572 expect(probe.status, probe.stderr).toBe(0);
573 expect(parseResolvedPath(probe.stdout)).not.toBeNull();
574 });
575​
576 it("keeps the inherited PATH when bash is unavailable", () => {
577 const fixture = createFixture();
578 expect(fixture.install().status).toBe(0);
579 const probe = runShell(
580 [
581 "bash() { return 127; }",
582 'export PATH="/fixture/bin:/usr/bin:/bin"',
583 buildWslRuntimeProbeScript(fixture.runtimeRoot),
584 ].join("\n"),
585 );
586​
587 expect(probe.status, probe.stderr).toBe(0);
588 expect(parseResolvedPath(probe.stdout)).toBe("/fixture/bin:/usr/bin:/bin");
589 });
590​
591 it("reuses a warm cache without touching the archive", () => {
592 const fixture = createFixture();
593 expect(fixture.install().status).toBe(0);
594 expect(runShell(`set -eu\nrm ${sh(fixture.archivePath)}`).status).toBe(0);
595​
596 const warm = fixture.install();
597​
598 expect(warm.status, warm.stderr).toBe(0);
599 expect(parseWslRuntimeRoot(warm.stdout)).toBe(fixture.runtimeRoot);
600 });
601​
602 it("retains the loader error when a bundled executable needs a missing system library", () => {
603 const fixture = createFixture(
604 '#!/bin/sh\nprintf "error while loading shared libraries: libatomic.so.1: cannot open shared object file\\n" >&2\nexit 127\n',
605 );
606​
607 const result = fixture.install();
608​
609 expect(result.status).not.toBe(0);
610 expect(result.stderr).toContain("libatomic.so.1");
611 expect(parseWslRuntimeRoot(result.stdout)).toBeNull();
612 });
613​
614 it("reinstalls a cache whose executable was truncated", () => {
615 const fixture = createFixture();
616 expect(fixture.install().status).toBe(0);
617 expect(runShell(`set -eu\n: > ${sh(fixture.serverEntry)}`).status).toBe(0);
618​
619 const repaired = fixture.install();
620​
621 expect(repaired.status, repaired.stderr).toBe(0);
622 expect(parseWslRuntimeRoot(repaired.stdout)).toBe(fixture.runtimeRoot);
623 const restored = runShell(`set -eu\ncat ${sh(fixture.serverEntry)}`);
624 expect(restored.stdout).toBe(SERVER_ENTRY_SOURCE);
625 });
626​
627 it("falls back instead of launching a corrupted cache it cannot reinstall", () => {
628 const fixture = createFixture();
629 expect(fixture.install().status).toBe(0);
630 expect(runShell(`set -eu\n: > ${sh(fixture.serverEntry)}`).status).toBe(0);
631 expect(runShell(`set -eu\nrm ${sh(fixture.archivePath)}`).status).toBe(0);
632​
633 const broken = fixture.install();
634​
635 expect(broken.status).not.toBe(0);
636 expect(parseWslRuntimeRoot(broken.stdout)).toBeNull();
637 });
638​
639 it("extracts once when two installs race for the same cache", () => {
640 const fixture = createFixture();
641 const raced = runShell(
642 [
643 "set -eu",
644 `work=${sh(fixture.work)}`,
645 'mkdir -p "$work/bin"',
646 "real_tar=$(command -v tar)",
647 `printf '#!/bin/sh\\nprintf x >> "%s/tar-calls"\\nsleep 1\\nexec %s "$@"\\n' "$work" "$real_tar" > "$work/bin/tar"`,
648 'chmod +x "$work/bin/tar"',
649 ': > "$work/tar-calls"',
650 'PATH="$work/bin:$PATH"',
651 "export PATH",
652 `cat > "$work/install.sh" <<'T3CODE_INSTALL_SCRIPT'`,
653 fixture.installScript(),
654 "T3CODE_INSTALL_SCRIPT",
655 // Both racers run the same file, and neither file path contains the
656 // runtime root, so the script's own /proc scan cannot see them.
657 'sh "$work/install.sh" > "$work/first.out" 2>&1 &',
658 "first=$!",
659 'sh "$work/install.sh" > "$work/second.out" 2>&1 &',
660 "second=$!",
661 "if wait $first; then first_status=0; else first_status=$?; fi",
662 "if wait $second; then second_status=0; else second_status=$?; fi",
663 `printf 'firstStatus:%s\\n' "$first_status"`,
664 `printf 'secondStatus:%s\\n' "$second_status"`,
665 `printf 'extractions:%s\\n' "$(wc -c < "$work/tar-calls" | tr -d ' ')"`,
666 `printf 'firstRoot:%s\\n' "$(sed -n 's/^runtimeRoot://p' "$work/first.out")"`,
667 `printf 'secondRoot:%s\\n' "$(sed -n 's/^runtimeRoot://p' "$work/second.out")"`,
668 ].join("\n"),
669 );
670​
671 expect(raced.status, raced.stderr).toBe(0);
672 expect(readField(raced.stdout, "firstStatus")).toBe("0");
673 expect(readField(raced.stdout, "secondStatus")).toBe("0");
674 expect(readField(raced.stdout, "extractions")).toBe("1");
675 expect(readField(raced.stdout, "firstRoot")).toBe(fixture.runtimeRoot);
676 expect(readField(raced.stdout, "secondRoot")).toBe(fixture.runtimeRoot);
677 });
678​
679 it("leaves no half-built cache when extraction fails", () => {
680 const fixture = createFixture();
681 const truncated = runShell(
682 [
683 "set -eu",
684 `work=${sh(fixture.work)}`,
685 'size=$(wc -c < "$work/wsl-runtime.tar.gz")',
686 'head -c $((size / 2)) "$work/wsl-runtime.tar.gz" > "$work/truncated.tar.gz"',
687 `printf 'sha:%s\\n' "$(sha256sum "$work/truncated.tar.gz" | cut -d ' ' -f 1)"`,
688 ].join("\n"),
689 );
690 expect(truncated.status, truncated.stderr).toBe(0);
691​
692 const failed = fixture.install(
693 `${fixture.work}/truncated.tar.gz`,
694 readField(truncated.stdout, "sha"),
695 );
696​
697 expect(failed.status).not.toBe(0);
698 expect(parseWslRuntimeRoot(failed.stdout)).toBeNull();
699 const leftovers = runShell(
700 `set -eu\nfind ${sh(fixture.runtimeParent)} -mindepth 1 -maxdepth 1 -type d`,
701 );
702 expect(leftovers.stdout.trim()).toBe("");
703 });
704​
705 it("refuses an archive whose bytes do not match the digest recorded for it", () => {
706 const fixture = createFixture();
707​
708 const refused = fixture.install(fixture.archivePath, "e".repeat(64));
709​
710 expect(refused.status).not.toBe(0);
711 expect(refused.stderr).toContain("does not match its recorded SHA-256");
712 expect(parseWslRuntimeRoot(refused.stdout)).toBeNull();
713 const leftovers = runShell(
714 `set -eu\nfind ${sh(fixture.runtimeParent)} -mindepth 1 -maxdepth 1 -type d`,
715 );
716 expect(leftovers.stdout.trim()).toBe("");
717 });
718​
719 it("leases a warm cache across the prepare-to-spawn handoff", () => {
720 const fixture = createFixture();
721 expect(fixture.install().status).toBe(0);
722 const selected = runShell(
723 [
724 "set -eu",
725 `runtime_parent=${sh(fixture.runtimeParent)}`,
726 'mkdir -p "$runtime_parent/sha256-current" "$runtime_parent/sha256-previous"',
727 'printf ready > "$runtime_parent/sha256-current/.t3code-wsl-runtime-ready"',
728 'printf ready > "$runtime_parent/sha256-previous/.t3code-wsl-runtime-ready"',
729 `touch -d "10 minutes ago" ${sh(fixture.runtimeRoot)}`,
730 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"',
731 `cat > ${sh(`${fixture.work}/select.sh`)} <<'T3CODE_SELECT_SCRIPT'`,
732 fixture.installScript(),
733 "T3CODE_SELECT_SCRIPT",
734 `sh ${sh(`${fixture.work}/select.sh`)}`,
735 `HOME=${sh(`${fixture.work}/home`)}`,
736 "export HOME",
737 buildWslRuntimePruneScript("sha256-current"),
738 `test -d ${sh(fixture.runtimeRoot)}`,
739 ].join("\n"),
740 );
741​
742 expect(selected.status, `${selected.stdout}\n${selected.stderr}`).toBe(0);
743 });
744​
745 it("prunes a selected cache after its prepare-to-spawn grace period expires", () => {
746 const fixture = createFixture();
747 expect(fixture.install().status).toBe(0);
748 const result = runShell(
749 [
750 "set -eu",
751 `runtime_parent=${sh(fixture.runtimeParent)}`,
752 'mkdir -p "$runtime_parent/sha256-current" "$runtime_parent/sha256-previous"',
753 'printf ready > "$runtime_parent/sha256-current/.t3code-wsl-runtime-ready"',
754 'printf ready > "$runtime_parent/sha256-previous/.t3code-wsl-runtime-ready"',
755 `touch -d "10 minutes ago" ${sh(fixture.runtimeRoot)}`,
756 `touch -d "10 minutes ago" ${sh(`${fixture.runtimeRoot}/.t3code-wsl-runtime-selected`)}`,
757 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"',
758 `HOME=${sh(`${fixture.work}/home`)}`,
759 "export HOME",
760 buildWslRuntimePruneScript("sha256-current"),
761 `test ! -e ${sh(fixture.runtimeRoot)}`,
762 ].join("\n"),
763 );
764​
765 expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
766 });
767​
768 it("removes an aged stale tree after replacing an active unready cache", () => {
769 const fixture = createFixture();
770 expect(fixture.install().status).toBe(0);
771 const result = runShell(
772 [
773 "set -eu",
774 `runtime_root=${sh(fixture.runtimeRoot)}`,
775 `runtime_parent=${sh(fixture.runtimeParent)}`,
776 'rm "$runtime_root/.t3code-wsl-runtime-ready"',
777 holdRuntimeBusy('"$runtime_root/t3"'),
778 fixture.installScript(),
779 'stale=$(find "$runtime_parent" -maxdepth 1 -type d -name ".sha256-*.stale.*" -print -quit)',
780 'test -n "$stale"',
781 'touch -d "180 minutes ago" "$stale"',
782 `HOME=${sh(`${fixture.work}/home`)}`,
783 "export HOME",
784 buildWslRuntimePruneScript(fixture.runtimeId),
785 'test ! -e "$stale"',
786 ].join("\n"),
787 );
788​
789 expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
790 });
791​
792 it("prunes old and markerless caches without touching retained, active, locked, or unrelated roots", () => {
793 const result = runShell(
794 [
795 "set -eu",
796 "work=$(mktemp -d)",
797 'home="$work/home"',
798 'runtime_parent="$home/.t3/wsl-runtime"',
799 'mkdir -p "$runtime_parent"',
800 'make_ready() { mkdir -p "$runtime_parent/$1"; printf ready > "$runtime_parent/$1/.t3code-wsl-runtime-ready"; }',
801 "make_ready sha256-current",
802 "make_ready sha256-previous",
803 "make_ready sha256-active",
804 "make_ready sha256-old",
805 "make_ready sha256-locked",
806 'mkdir -p "$runtime_parent/sha256-markerless" "$runtime_parent/versions"',
807 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"',
808 'touch -d "4 minutes ago" "$runtime_parent/sha256-active"',
809 'touch -d "3 minutes ago" "$runtime_parent/sha256-old"',
810 'touch -d "2 minutes ago" "$runtime_parent/sha256-locked"',
811 holdRuntimeBusy('"$runtime_parent/sha256-active/t3"'),
812 holdInstallLock('"$runtime_parent/.sha256-locked.install.lock"'),
813 `HOME="$home"`,
814 "export HOME",
815 buildWslRuntimePruneScript("sha256-current"),
816 'test -d "$runtime_parent/sha256-current"',
817 'test -d "$runtime_parent/sha256-previous"',
818 'test -d "$runtime_parent/sha256-active"',
819 'test -d "$runtime_parent/sha256-locked"',
820 'test -d "$runtime_parent/versions"',
821 'test ! -e "$runtime_parent/sha256-old"',
822 'test ! -e "$runtime_parent/sha256-markerless"',
823 'rm -rf "$work"',
824 ].join("\n"),
825 );
826​
827 expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
828 });
829});
830​
831describe("parseToolchainReport", () => {
832 it("returns no missing tools and no node version on empty output", () => {
833 expect(parseToolchainReport("")).toEqual({ missingTools: [], nodeVersion: null });
834 });
835​
836 it("collects all missing: lines", () => {
837 const stdout = ["missing:make", "missing:g++", "nodeVersion:24.10.0"].join("\n");
838 expect(parseToolchainReport(stdout)).toEqual({
839 missingTools: ["make", "g++"],
840 nodeVersion: "24.10.0",
841 });
842 });
843​
844 it("ignores blank lines and trims whitespace", () => {
845 const stdout = [" missing:python3 ", "", " nodeVersion:v22.16.0 "].join("\n");
846 expect(parseToolchainReport(stdout)).toEqual({
847 missingTools: ["python3"],
848 nodeVersion: "v22.16.0",
849 });
850 });
851​
852 it("returns null node version when value after prefix is empty", () => {
853 expect(parseToolchainReport("nodeVersion:")).toEqual({
854 missingTools: [],
855 nodeVersion: null,
856 });
857 });
858});
859​
860describe("parseNodePath", () => {
861 it("extracts the absolute node path from a nodePath: line", () => {
862 const stdout = "nodePath:/home/josh/.nvm/versions/node/v22.16.0/bin/node";
863 expect(parseNodePath(stdout)).toBe("/home/josh/.nvm/versions/node/v22.16.0/bin/node");
864 });
865​
866 it("returns null when node was not found (empty value after prefix)", () => {
867 expect(parseNodePath("nodePath:")).toBeNull();
868 });
869​
870 it("returns null when there is no nodePath line at all", () => {
871 expect(parseNodePath("missing:node\nnodeVersion:")).toBeNull();
872 });
873​
874 it("ignores surrounding noise and trims whitespace", () => {
875 const stdout = ["some preamble noise", " nodePath:/usr/bin/node ", "trailing"].join("\n");
876 expect(parseNodePath(stdout)).toBe("/usr/bin/node");
877 });
878});
879​
880describe("parseNodeVersion", () => {
881 it("extracts the node version from a nodeVersion: line", () => {
882 expect(parseNodeVersion("nodeVersion:24.10.0")).toBe("24.10.0");
883 });
884​
885 it("returns null when the version value is empty", () => {
886 expect(parseNodeVersion("nodeVersion:")).toBeNull();
887 });
888​
889 it("returns null when there is no nodeVersion line at all", () => {
890 expect(parseNodeVersion("nodePath:/usr/bin/node\nresolvedPath:/usr/bin")).toBeNull();
891 });
892​
893 it("ignores surrounding noise and trims whitespace", () => {
894 const stdout = [
895 "some preamble noise",
896 " nodeVersion:22.16.0 ",
897 "nodePath:/usr/bin/node",
898 ].join("\n");
899 expect(parseNodeVersion(stdout)).toBe("22.16.0");
900 });
901});
902​
903describe("parseResolvedPath", () => {
904 it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {
905 const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
906 expect(parseResolvedPath(`nodePath:/usr/bin/node\nresolvedPath:${resolvedPath}\n`)).toBe(
907 resolvedPath,
908 );
909 });
910​
911 it("accepts CRLF output without retaining the carriage return", () => {
912 expect(parseResolvedPath("resolvedPath:/usr/local/bin:/usr/bin\r\n")).toBe(
913 "/usr/local/bin:/usr/bin",
914 );
915 });
916​
917 it("returns null when the resolved PATH is absent or empty", () => {
918 expect(parseResolvedPath("nodePath:/usr/bin/node\n")).toBeNull();
919 expect(parseResolvedPath("resolvedPath:\n")).toBeNull();
920 });
921});
922​
923describe("formatMissingToolsReason", () => {
924 it("returns null when everything is present and node is in range", () => {
925 expect(
926 formatMissingToolsReason({ missingTools: [], nodeVersion: "24.10.0" }, "^24.10"),
927 ).toBeNull();
928 });
929​
930 it("returns null when range is not specified and tools are present", () => {
931 expect(formatMissingToolsReason({ missingTools: [], nodeVersion: "18.0.0" }, null)).toBeNull();
932 });
933​
934 it("flags missing node first", () => {
935 const reason = formatMissingToolsReason(
936 { missingTools: ["node", "make"], nodeVersion: null },
937 "^24.10",
938 );
939 expect(reason).toContain("node");
940 expect(reason).toContain("^24.10");
941 expect(reason).toContain("make");
942 expect(reason).toContain("nvm");
943 });
944​
945 it("flags an out-of-range node version with the actual version surfaced", () => {
946 const reason = formatMissingToolsReason(
947 { missingTools: [], nodeVersion: "20.0.0" },
948 "^24.10 || ^22.16",
949 );
950 expect(reason).toContain("node 20.0.0");
951 expect(reason).toContain("requires ^24.10 || ^22.16");
952 });
953​
954 it("flags missing build tools without node when node is fine", () => {
955 const reason = formatMissingToolsReason(
956 { missingTools: ["g++", "python3"], nodeVersion: "24.10.0" },
957 "^24.10",
958 );
959 expect(reason).toContain("g++");
960 expect(reason).toContain("python3");
961 expect(reason).toContain("build-essential");
962 expect(reason).not.toContain("nvm");
963 });
964});