Open History to see the last commit
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";
5
6import {
7 buildWslRuntimeInstallScript,
8 buildWslRuntimeInvalidateScript,
9 buildWslRuntimePruneScript,
10 buildWslRuntimeProbeScript,
11 parseResolvedPath,
12 parseWslRuntimeRoot,
13} from "./DesktopWslEnvironment.ts";
14
15// The install script only fails the way this file cares about when a real shell
16// runs it, so find one that has the tools it needs: bash directly on Linux, and
17// the WSL distro on a Windows dev box, where Git Bash ships no flock. Anywhere
18// else the executed suite skips and the generated-text assertions stand alone.
19const REQUIRED_SHELL_TOOLS = ["flock", "sha256sum", "tar", "mktemp"] as const;
20
21const posixShellRunner = (() => {
22 const candidates = [
23 { file: "bash", args: [] as ReadonlyArray<string> },
24 { file: "wsl.exe", args: ["-e", "bash"] as ReadonlyArray<string> },
25 ];
26 const probe = [
27 "[ -d /proc/1 ] || exit 1",
28 ...REQUIRED_SHELL_TOOLS.map((tool) => `command -v ${tool} >/dev/null || exit 1`),
29 ].join("\n");
30 return (
31 candidates.find((candidate) => {
32 const result = NodeChildProcess.spawnSync(candidate.file, [...candidate.args, "-c", probe], {
33 encoding: "utf8",
34 });
35 return result.status === 0;
36 }) ?? null
37 );
38})();
39
40const runShell = (script: string) => {
41 if (posixShellRunner === null) throw new Error("no POSIX shell runner available");
42 // Pass the script on stdin, as production does, to avoid matching its own /proc scan.
43 const result = NodeChildProcess.spawnSync(
44 posixShellRunner.file,
45 [...posixShellRunner.args, "-s"],
46 { input: script, encoding: "utf8" },
47 );
48 return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
49};
50
51const sh = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
52
53const awaitHolder = (condition: string) =>
54 `i=0; until ${condition}; do i=$((i + 1)); [ "$i" -lt 500 ] || exit 1; sleep 0.01; done`;
55
56// Use runtime-entry argv[0] for /proc detection; an open pipe keeps it alive only while this script runs.
57const holdRuntimeBusy = (entry: string) =>
58 [
59 `exec 7> >(exec -a ${entry} cat >/dev/null 2>&1)`,
60 awaitHolder(`grep -qF -- ${entry} /proc/[0-9]*/cmdline 2>/dev/null`),
61 ].join("\n");
62
63const holdInstallLock = (lock: string) =>
64 [
65 `exec 6> >(exec 9> ${lock}; flock -x 9; cat >/dev/null 2>&1)`,
66 awaitHolder(`! flock -n ${lock} true`),
67 ].join("\n");
68
69const readField = (stdout: string, field: string) => {
70 const line = stdout.split("\n").find((candidate) => candidate.startsWith(`${field}:`));
71 if (line === undefined) throw new Error(`missing ${field} in fixture output: ${stdout}`);
72 return line.slice(field.length + 1).trim();
73};
74
75const SERVER_ENTRY_SOURCE = '#!/bin/sh\necho "t3code wsl runtime test server 0.0.0"\n';
76
77describe("WSL runtime cache", () => {
78 it.each([
79 [
80 "install",
81 (id: string) => buildWslRuntimeInstallScript("/runtime.tar.gz", id, "b".repeat(64)),
82 ],
83 ["prune", buildWslRuntimePruneScript],
84 ["invalidate", buildWslRuntimeInvalidateScript],
85 ] as const)("sanitizes cache ids in the %s script", (_, buildScript) => {
86 const runtimeId = "1.2.3/x64; touch /tmp/nope";
87 const script = buildScript(runtimeId);
88 expect(script).toContain("/1.2.3_x64__touch__tmp_nope");
89 expect(script).not.toContain(runtimeId);
90 });
91});
92
93describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed)", () => {
94 const fixtures: Array<string> = [];
95
96 afterAll(() => {
97 for (const work of fixtures) runShell(`set -eu\nrm -rf ${sh(work)}`);
98 fixtures.length = 0;
99 });
100
101 const createFixture = (serverEntry = SERVER_ENTRY_SOURCE) => {
102 const result = runShell(
103 [
104 "set -eu",
105 "work=$(mktemp -d)",
106 'stage="$work/stage/t3-0.0.0-linux-x64"',
107 'mkdir -p "$stage/node_modules/node-pty/build/Release" "$work/home"',
108 `printf '%s' ${sh(serverEntry)} > "$stage/t3"`,
109 'chmod +x "$stage/t3"',
110 `printf '%s' 'pty-native-payload' > "$stage/node_modules/node-pty/build/Release/pty.node"`,
111 `tar -czf "$work/wsl-runtime.tar.gz" -C "$work/stage" t3-0.0.0-linux-x64`,
112 `printf 'work:%s\\n' "$work"`,
113 `printf 'archiveSha:%s\\n' "$(sha256sum "$work/wsl-runtime.tar.gz" | cut -d ' ' -f 1)"`,
114 ].join("\n"),
115 );
116 expect(result.status, result.stderr).toBe(0);
117
118 const work = readField(result.stdout, "work");
119 fixtures.push(work);
120 const archivePath = `${work}/wsl-runtime.tar.gz`;
121 const archiveSha = readField(result.stdout, "archiveSha");
122 const runtimeId = `sha256-${archiveSha}`;
123 // WSL does not inherit HOME; embed the fixture's override in the script.
124 const installScript = (archive = archivePath, sha = archiveSha) =>
125 [
126 `HOME=${sh(`${work}/home`)}`,
127 "export HOME",
128 buildWslRuntimeInstallScript(archive, runtimeId, sha),
129 ].join("\n");
130 return {
131 work,
132 archivePath,
133 archiveSha,
134 runtimeId,
135 runtimeParent: `${work}/home/.t3/wsl-runtime`,
136 runtimeRoot: `${work}/home/.t3/wsl-runtime/${runtimeId}`,
137 serverEntry: `${work}/home/.t3/wsl-runtime/${runtimeId}/t3`,
138 installScript,
139 install: (archive?: string, sha?: string) => runShell(installScript(archive, sha)),
140 };
141 };
142
143 const probeFixture = (fixture: ReturnType<typeof createFixture>) =>
144 runShell(
145 [
146 `export HOME=${sh(`${fixture.work}/home`)}`,
147 'export NVM_DIR="$HOME/.nvm" FNM_DIR="$HOME/.fnm" VOLTA_HOME="$HOME/.volta"',
148 "bash() { (",
149 " command() {",
150 ' case "$*" in',
151 ' "-v node"|"-v mise"|"-v fnm"|"-v nodenv") return 1 ;;',
152 ' *) builtin command "$@" ;;',
153 " esac",
154 " }",
155 ' eval "$2"',
156 "); }",
157 buildWslRuntimeProbeScript(fixture.runtimeRoot),
158 ].join("\n"),
159 );
160
161 it("discovers version-managed Node for providers with a standalone runtime", () => {
162 const fixture = createFixture();
163 expect(fixture.install().status).toBe(0);
164 const nodeBin = `${fixture.work}/home/.nvm/versions/node/v24.15.0/bin`;
165 const setup = runShell(
166 [
167 "set -eu",
168 `mkdir -p ${sh(nodeBin)}`,
169 `printf '%s' ${sh('#!/bin/sh\nprintf "linux-node-provider\\n"\n')} > ${sh(`${nodeBin}/node`)}`,
170 `chmod +x ${sh(`${nodeBin}/node`)}`,
171 ].join("\n"),
172 );
173 expect(setup.status, setup.stderr).toBe(0);
174
175 const probe = probeFixture(fixture);
176
177 expect(probe.status, probe.stderr).toBe(0);
178 const resolvedPath = parseResolvedPath(probe.stdout);
179 expect(resolvedPath?.split(":")).toContain(nodeBin);
180 const provider = runShell(`export PATH=${sh(resolvedPath ?? "")}\nnode provider.js`);
181 expect(provider.status, provider.stderr).toBe(0);
182 expect(provider.stdout).toBe("linux-node-provider\n");
183 });
184
185 it("keeps the inherited PATH when bash is unavailable", () => {
186 const fixture = createFixture();
187 expect(fixture.install().status).toBe(0);
188 const probe = runShell(
189 [
190 "bash() { return 127; }",
191 'export PATH="/fixture/bin:/usr/bin:/bin"',
192 buildWslRuntimeProbeScript(fixture.runtimeRoot),
193 ].join("\n"),
194 );
195
196 expect(probe.status, probe.stderr).toBe(0);
197 expect(parseResolvedPath(probe.stdout)).toBe("/fixture/bin:/usr/bin:/bin");
198 });
199
200 it("reuses a warm cache without touching the archive", () => {
201 const fixture = createFixture();
202 expect(fixture.install().status).toBe(0);
203 expect(runShell(`set -eu\nrm ${sh(fixture.archivePath)}`).status).toBe(0);
204
205 const warm = fixture.install();
206
207 expect(warm.status, warm.stderr).toBe(0);
208 expect(parseWslRuntimeRoot(warm.stdout)).toBe(fixture.runtimeRoot);
209 });
210
211 it("retains the loader error when a bundled executable needs a missing system library", () => {
212 const fixture = createFixture(
213 '#!/bin/sh\nprintf "error while loading shared libraries: libatomic.so.1: cannot open shared object file\\n" >&2\nexit 127\n',
214 );
215
216 const result = fixture.install();
217
218 expect(result.status).not.toBe(0);
219 expect(result.stderr).toContain("libatomic.so.1");
220 expect(parseWslRuntimeRoot(result.stdout)).toBeNull();
221 });
222
223 it("reinstalls a cache whose executable was truncated", () => {
224 const fixture = createFixture();
225 expect(fixture.install().status).toBe(0);
226 expect(runShell(`set -eu\n: > ${sh(fixture.serverEntry)}`).status).toBe(0);
227
228 const repaired = fixture.install();
229
230 expect(repaired.status, repaired.stderr).toBe(0);
231 expect(parseWslRuntimeRoot(repaired.stdout)).toBe(fixture.runtimeRoot);
232 const restored = runShell(`set -eu\ncat ${sh(fixture.serverEntry)}`);
233 expect(restored.stdout).toBe(SERVER_ENTRY_SOURCE);
234 });
235
236 it("reinstalls an executable that fails --version despite a matching recorded digest", () => {
237 const fixture = createFixture();
238 expect(fixture.install().status).toBe(0);
239 const brokenEntry = "#!/bin/sh\nexit 42\n";
240 const corrupt = runShell(
241 [
242 "set -eu",
243 `printf '%s' ${sh(brokenEntry)} > ${sh(fixture.serverEntry)}`,
244 `chmod +x ${sh(fixture.serverEntry)}`,
245 `sha256sum ${sh(fixture.serverEntry)} | cut -d ' ' -f 1 > ${sh(`${fixture.runtimeRoot}/.t3code-wsl-runtime-ready`)}`,
246 ].join("\n"),
247 );
248 expect(corrupt.status, corrupt.stderr).toBe(0);
249 expect(runShell(`${sh(fixture.serverEntry)} --version`).status).toBe(42);
250
251 const repaired = fixture.install();
252 expect(repaired.status, repaired.stderr).toBe(0);
253 expect(parseWslRuntimeRoot(repaired.stdout)).toBe(fixture.runtimeRoot);
254 expect(runShell(`cat ${sh(fixture.serverEntry)}`).stdout).toBe(SERVER_ENTRY_SOURCE);
255 expect(runShell(`${sh(fixture.serverEntry)} --version`).status).toBe(0);
256 });
257
258 it("falls back instead of launching a corrupted cache it cannot reinstall", () => {
259 const fixture = createFixture();
260 expect(fixture.install().status).toBe(0);
261 expect(runShell(`set -eu\n: > ${sh(fixture.serverEntry)}`).status).toBe(0);
262 expect(runShell(`set -eu\nrm ${sh(fixture.archivePath)}`).status).toBe(0);
263
264 const broken = fixture.install();
265
266 expect(broken.status).not.toBe(0);
267 expect(parseWslRuntimeRoot(broken.stdout)).toBeNull();
268 });
269
270 it("extracts once when two installs race for the same cache", () => {
271 const fixture = createFixture();
272 const raced = runShell(
273 [
274 "set -eu",
275 `work=${sh(fixture.work)}`,
276 'mkdir -p "$work/bin"',
277 "real_tar=$(command -v tar)",
278 `printf '#!/bin/sh\\nprintf x >> "%s/tar-calls"\\nsleep 1\\nexec %s "$@"\\n' "$work" "$real_tar" > "$work/bin/tar"`,
279 'chmod +x "$work/bin/tar"',
280 ': > "$work/tar-calls"',
281 'PATH="$work/bin:$PATH"',
282 "export PATH",
283 `cat > "$work/install.sh" <<'T3CODE_INSTALL_SCRIPT'`,
284 fixture.installScript(),
285 "T3CODE_INSTALL_SCRIPT",
286 // Keep runtime roots out of both racers' argv so their /proc scans cannot match themselves.
287 'sh "$work/install.sh" > "$work/first.out" 2>&1 &',
288 "first=$!",
289 'sh "$work/install.sh" > "$work/second.out" 2>&1 &',
290 "second=$!",
291 "if wait $first; then first_status=0; else first_status=$?; fi",
292 "if wait $second; then second_status=0; else second_status=$?; fi",
293 `printf 'firstStatus:%s\\n' "$first_status"`,
294 `printf 'secondStatus:%s\\n' "$second_status"`,
295 `printf 'extractions:%s\\n' "$(wc -c < "$work/tar-calls" | tr -d ' ')"`,
296 `printf 'firstRoot:%s\\n' "$(sed -n 's/^runtimeRoot://p' "$work/first.out")"`,
297 `printf 'secondRoot:%s\\n' "$(sed -n 's/^runtimeRoot://p' "$work/second.out")"`,
298 ].join("\n"),
299 );
300
301 expect(raced.status, raced.stderr).toBe(0);
302 expect(readField(raced.stdout, "firstStatus")).toBe("0");
303 expect(readField(raced.stdout, "secondStatus")).toBe("0");
304 expect(readField(raced.stdout, "extractions")).toBe("1");
305 expect(readField(raced.stdout, "firstRoot")).toBe(fixture.runtimeRoot);
306 expect(readField(raced.stdout, "secondRoot")).toBe(fixture.runtimeRoot);
307 });
308
309 it("leaves no half-built cache when extraction fails", () => {
310 const fixture = createFixture();
311 const truncated = runShell(
312 [
313 "set -eu",
314 `work=${sh(fixture.work)}`,
315 'size=$(wc -c < "$work/wsl-runtime.tar.gz")',
316 'head -c $((size / 2)) "$work/wsl-runtime.tar.gz" > "$work/truncated.tar.gz"',
317 `printf 'sha:%s\\n' "$(sha256sum "$work/truncated.tar.gz" | cut -d ' ' -f 1)"`,
318 ].join("\n"),
319 );
320 expect(truncated.status, truncated.stderr).toBe(0);
321
322 const failed = fixture.install(
323 `${fixture.work}/truncated.tar.gz`,
324 readField(truncated.stdout, "sha"),
325 );
326
327 expect(failed.status).not.toBe(0);
328 expect(parseWslRuntimeRoot(failed.stdout)).toBeNull();
329 const leftovers = runShell(
330 `set -eu\nfind ${sh(fixture.runtimeParent)} -mindepth 1 -maxdepth 1 -type d`,
331 );
332 expect(leftovers.stdout.trim()).toBe("");
333 });
334
335 it("refuses an archive whose bytes do not match the digest recorded for it", () => {
336 const fixture = createFixture();
337
338 const refused = fixture.install(fixture.archivePath, "e".repeat(64));
339
340 expect(refused.status).not.toBe(0);
341 expect(refused.stderr).toContain("does not match its recorded SHA-256");
342 expect(parseWslRuntimeRoot(refused.stdout)).toBeNull();
343 const leftovers = runShell(
344 `set -eu\nfind ${sh(fixture.runtimeParent)} -mindepth 1 -maxdepth 1 -type d`,
345 );
346 expect(leftovers.stdout.trim()).toBe("");
347 });
348
349 it("leases a warm cache across the prepare-to-spawn handoff", () => {
350 const fixture = createFixture();
351 expect(fixture.install().status).toBe(0);
352 const selected = runShell(
353 [
354 "set -eu",
355 `runtime_parent=${sh(fixture.runtimeParent)}`,
356 'mkdir -p "$runtime_parent/sha256-current" "$runtime_parent/sha256-previous"',
357 'printf ready > "$runtime_parent/sha256-current/.t3code-wsl-runtime-ready"',
358 'printf ready > "$runtime_parent/sha256-previous/.t3code-wsl-runtime-ready"',
359 `touch -d "10 minutes ago" ${sh(fixture.runtimeRoot)}`,
360 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"',
361 `cat > ${sh(`${fixture.work}/select.sh`)} <<'T3CODE_SELECT_SCRIPT'`,
362 fixture.installScript(),
363 "T3CODE_SELECT_SCRIPT",
364 `sh ${sh(`${fixture.work}/select.sh`)}`,
365 `HOME=${sh(`${fixture.work}/home`)}`,
366 "export HOME",
367 buildWslRuntimePruneScript("sha256-current"),
368 `test -d ${sh(fixture.runtimeRoot)}`,
369 ].join("\n"),
370 );
371
372 expect(selected.status, `${selected.stdout}\n${selected.stderr}`).toBe(0);
373 });
374
375 it("prunes old and markerless caches without touching retained, active, locked, or unrelated roots", () => {
376 const result = runShell(
377 [
378 "set -eu",
379 "work=$(mktemp -d)",
380 'home="$work/home"',
381 'runtime_parent="$home/.t3/wsl-runtime"',
382 'mkdir -p "$runtime_parent"',
383 'make_ready() { mkdir -p "$runtime_parent/$1"; printf ready > "$runtime_parent/$1/.t3code-wsl-runtime-ready"; }',
384 "make_ready sha256-current",
385 "make_ready sha256-previous",
386 "make_ready sha256-active",
387 "make_ready sha256-old",
388 "make_ready sha256-locked",
389 'mkdir -p "$runtime_parent/sha256-markerless" "$runtime_parent/versions"',
390 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"',
391 'touch -d "4 minutes ago" "$runtime_parent/sha256-active"',
392 'touch -d "3 minutes ago" "$runtime_parent/sha256-old"',
393 'touch -d "2 minutes ago" "$runtime_parent/sha256-locked"',
394 holdRuntimeBusy('"$runtime_parent/sha256-active/t3"'),
395 holdInstallLock('"$runtime_parent/.sha256-locked.install.lock"'),
396 `HOME="$home"`,
397 "export HOME",
398 buildWslRuntimePruneScript("sha256-current"),
399 'test -d "$runtime_parent/sha256-current"',
400 'test -d "$runtime_parent/sha256-previous"',
401 'test -d "$runtime_parent/sha256-active"',
402 'test -d "$runtime_parent/sha256-locked"',
403 'test -d "$runtime_parent/versions"',
404 'test ! -e "$runtime_parent/sha256-old"',
405 'test ! -e "$runtime_parent/sha256-markerless"',
406 'rm -rf "$work"',
407 ].join("\n"),
408 );
409
410 expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
411 });
412});
413
414describe("parseResolvedPath", () => {
415 it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {
416 const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
417 expect(parseResolvedPath(`nodePath:/usr/bin/node\nresolvedPath:${resolvedPath}\n`)).toBe(
418 resolvedPath,
419 );
420 });
421
422 it("accepts CRLF output without retaining the carriage return", () => {
423 expect(parseResolvedPath("resolvedPath:/usr/local/bin:/usr/bin\r\n")).toBe(
424 "/usr/local/bin:/usr/bin",
425 );
426 });
427});