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