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 * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, describe, it } from "@effect/vitest";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as Redacted from "effect/Redacted";
10import * as Sink from "effect/Sink";
11import * as Stream from "effect/Stream";
12import { ChildProcess, ChildProcessSpawner } from "effect/process";
13import { afterAll, expect } from "vite-plus/test";
14import * as NodeChildProcess from "node:child_process";
15
16import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile";
17
18import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
19import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
20import {
21 DesktopWslEnvironment,
22 layer as layerDesktopWslEnvironment,
23 buildWslRuntimeInstallScript,
24 makeIsAvailable,
25 buildWslRuntimeInvalidateScript,
26 buildWslRuntimePruneScript,
27 buildWslRuntimeProbeScript,
28 parseResolvedPath,
29 parseWslRuntimeRoot,
30 windowsToWslPathImpl,
31} from "./DesktopWslEnvironment.ts";
32
33// The install script only fails the way this file cares about when a real shell
34// runs it, so find one that has the tools it needs: bash directly on Linux, and
35// the WSL distro on a Windows dev box, where Git Bash ships no flock. Anywhere
36// else the executed suite skips and the generated-text assertions stand alone.
37const REQUIRED_SHELL_TOOLS = ["flock", "sha256sum", "tar", "mktemp"] as const;
38
39const posixShellRunner = (() => {
40 const candidates = [
41 { file: "bash", args: [] as ReadonlyArray<string> },
42 { file: "wsl.exe", args: ["-e", "bash"] as ReadonlyArray<string> },
43 ];
44 const probe = [
45 "[ -d /proc/1 ] || exit 1",
46 ...REQUIRED_SHELL_TOOLS.map((tool) => `command -v ${tool} >/dev/null || exit 1`),
47 ].join("\n");
48 return (
49 candidates.find((candidate) => {
50 const result = NodeChildProcess.spawnSync(candidate.file, [...candidate.args, "-c", probe], {
51 encoding: "utf8",
52 });
53 return result.status === 0;
54 }) ?? null
55 );
56})();
57
58const runShell = (script: string) => {
59 if (posixShellRunner === null) throw new Error("no POSIX shell runner available");
60 // Pass the script on stdin, as production does, to avoid matching its own /proc scan.
61 const result = NodeChildProcess.spawnSync(
62 posixShellRunner.file,
63 [...posixShellRunner.args, "-s"],
64 { input: script, encoding: "utf8" },
65 );
66 return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
67};
68
69const sh = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
70
71const awaitHolder = (condition: string) =>
72 `i=0; until ${condition}; do i=$((i + 1)); [ "$i" -lt 500 ] || exit 1; sleep 0.01; done`;
73
74// Use runtime-entry argv[0] for /proc detection; an open pipe keeps it alive only while this script runs.
75const holdRuntimeBusy = (entry: string) =>
76 [
77 `exec 7> >(exec -a ${entry} cat >/dev/null 2>&1)`,
78 awaitHolder(`grep -qF -- ${entry} /proc/[0-9]*/cmdline 2>/dev/null`),
79 ].join("\n");
80
81const holdInstallLock = (lock: string) =>
82 [
83 `exec 6> >(exec 9> ${lock}; flock -x 9; cat >/dev/null 2>&1)`,
84 awaitHolder(`! flock -n ${lock} true`),
85 ].join("\n");
86
87const readField = (stdout: string, field: string) => {
88 const line = stdout.split("\n").find((candidate) => candidate.startsWith(`${field}:`));
89 if (line === undefined) throw new Error(`missing ${field} in fixture output: ${stdout}`);
90 return line.slice(field.length + 1).trim();
91};
92
93const SERVER_ENTRY_SOURCE = '#!/bin/sh\necho "t3code wsl runtime test server 0.0.0"\n';
94
95describe("WSL runtime cache", () => {
96 it.each([
97 [
98 "install",
99 (id: string) => buildWslRuntimeInstallScript("/runtime.tar.gz", id, "b".repeat(64)),
100 ],
101 ["prune", buildWslRuntimePruneScript],
102 ["invalidate", buildWslRuntimeInvalidateScript],
103 ] as const)("sanitizes cache ids in the %s script", (_, buildScript) => {
104 const runtimeId = "1.2.3/x64; touch /tmp/nope";
105 const script = buildScript(runtimeId);
106 expect(script).toContain("/1.2.3_x64__touch__tmp_nope");
107 expect(script).not.toContain(runtimeId);
108 });
109});
110
111describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed)", () => {
112 const fixtures: Array<string> = [];
113
114 afterAll(() => {
115 for (const work of fixtures) runShell(`set -eu\nrm -rf ${sh(work)}`);
116 fixtures.length = 0;
117 });
118
119 const createFixture = (serverEntry = SERVER_ENTRY_SOURCE) => {
120 const result = runShell(
121 [
122 "set -eu",
123 "work=$(mktemp -d)",
124 'stage="$work/stage/t3-0.0.0-linux-x64"',
125 'mkdir -p "$stage/node_modules/node-pty/build/Release" "$work/home"',
126 `printf '%s' ${sh(serverEntry)} > "$stage/t3"`,
127 'chmod +x "$stage/t3"',
128 `printf '%s' 'pty-native-payload' > "$stage/node_modules/node-pty/build/Release/pty.node"`,
129 `tar -czf "$work/wsl-runtime.tar.gz" -C "$work/stage" t3-0.0.0-linux-x64`,
130 `printf 'work:%s\\n' "$work"`,
131 `printf 'archiveSha:%s\\n' "$(sha256sum "$work/wsl-runtime.tar.gz" | cut -d ' ' -f 1)"`,
132 ].join("\n"),
133 );
134 expect(result.status, result.stderr).toBe(0);
135
136 const work = readField(result.stdout, "work");
137 fixtures.push(work);
138 const archivePath = `${work}/wsl-runtime.tar.gz`;
139 const archiveSha = readField(result.stdout, "archiveSha");
140 const runtimeId = `sha256-${archiveSha}`;
141 // WSL does not inherit HOME; embed the fixture's override in the script.
142 const installScript = (archive = archivePath, sha = archiveSha) =>
143 [
144 `HOME=${sh(`${work}/home`)}`,
145 "export HOME",
146 buildWslRuntimeInstallScript(archive, runtimeId, sha),
147 ].join("\n");
148 return {
149 work,
150 archivePath,
151 archiveSha,
152 runtimeId,
153 runtimeParent: `${work}/home/.t3/wsl-runtime`,
154 runtimeRoot: `${work}/home/.t3/wsl-runtime/${runtimeId}`,
155 serverEntry: `${work}/home/.t3/wsl-runtime/${runtimeId}/t3`,
156 installScript,
157 install: (archive?: string, sha?: string) => runShell(installScript(archive, sha)),
158 };
159 };
160
161 const probeFixture = (fixture: ReturnType<typeof createFixture>) =>
162 runShell(
163 [
164 `export HOME=${sh(`${fixture.work}/home`)}`,
165 'export NVM_DIR="$HOME/.nvm" FNM_DIR="$HOME/.fnm" VOLTA_HOME="$HOME/.volta"',
166 "bash() { (",
167 " command() {",
168 ' case "$*" in',
169 ' "-v node"|"-v mise"|"-v fnm"|"-v nodenv") return 1 ;;',
170 ' *) builtin command "$@" ;;',
171 " esac",
172 " }",
173 ' eval "$2"',
174 "); }",
175 buildWslRuntimeProbeScript(),
176 ].join("\n"),
177 );
178
179 it("discovers version-managed Node for providers with a standalone runtime", () => {
180 const fixture = createFixture();
181 expect(fixture.install().status).toBe(0);
182 const nodeBin = `${fixture.work}/home/.nvm/versions/node/v24.15.0/bin`;
183 const setup = runShell(
184 [
185 "set -eu",
186 `mkdir -p ${sh(nodeBin)}`,
187 `printf '%s' ${sh('#!/bin/sh\nprintf "linux-node-provider\\n"\n')} > ${sh(`${nodeBin}/node`)}`,
188 `chmod +x ${sh(`${nodeBin}/node`)}`,
189 ].join("\n"),
190 );
191 expect(setup.status, setup.stderr).toBe(0);
192
193 const probe = probeFixture(fixture);
194
195 expect(probe.status, probe.stderr).toBe(0);
196 const resolvedPath = parseResolvedPath(probe.stdout);
197 expect(resolvedPath?.split(":")).toContain(nodeBin);
198 const provider = runShell(`export PATH=${sh(resolvedPath ?? "")}\nnode provider.js`);
199 expect(provider.status, provider.stderr).toBe(0);
200 expect(provider.stdout).toBe("linux-node-provider\n");
201 });
202
203 it("keeps the inherited PATH when bash is unavailable", () => {
204 const fixture = createFixture();
205 expect(fixture.install().status).toBe(0);
206 const probe = runShell(
207 [
208 "bash() { return 127; }",
209 'export PATH="/fixture/bin:/usr/bin:/bin"',
210 buildWslRuntimeProbeScript(),
211 ].join("\n"),
212 );
213
214 expect(probe.status, probe.stderr).toBe(0);
215 expect(parseResolvedPath(probe.stdout)).toBe("/fixture/bin:/usr/bin:/bin");
216 });
217
218 it("reuses a warm cache without touching the archive", () => {
219 const fixture = createFixture();
220 expect(fixture.install().status).toBe(0);
221 expect(runShell(`set -eu\nrm ${sh(fixture.archivePath)}`).status).toBe(0);
222
223 const warm = fixture.install();
224
225 expect(warm.status, warm.stderr).toBe(0);
226 expect(parseWslRuntimeRoot(warm.stdout)).toBe(fixture.runtimeRoot);
227 });
228
229 it("retains the loader error when a bundled executable needs a missing system library", () => {
230 const fixture = createFixture(
231 '#!/bin/sh\nprintf "error while loading shared libraries: libatomic.so.1: cannot open shared object file\\n" >&2\nexit 127\n',
232 );
233
234 const result = fixture.install();
235
236 expect(result.status).not.toBe(0);
237 expect(result.stderr).toContain("libatomic.so.1");
238 expect(parseWslRuntimeRoot(result.stdout)).toBeNull();
239 });
240
241 it("reinstalls a cache whose executable was truncated", () => {
242 const fixture = createFixture();
243 expect(fixture.install().status).toBe(0);
244 expect(runShell(`set -eu\n: > ${sh(fixture.serverEntry)}`).status).toBe(0);
245
246 const repaired = fixture.install();
247
248 expect(repaired.status, repaired.stderr).toBe(0);
249 expect(parseWslRuntimeRoot(repaired.stdout)).toBe(fixture.runtimeRoot);
250 const restored = runShell(`set -eu\ncat ${sh(fixture.serverEntry)}`);
251 expect(restored.stdout).toBe(SERVER_ENTRY_SOURCE);
252 });
253
254 it("reinstalls an executable that fails --version despite a matching recorded digest", () => {
255 const fixture = createFixture();
256 expect(fixture.install().status).toBe(0);
257 const brokenEntry = "#!/bin/sh\nexit 42\n";
258 const corrupt = runShell(
259 [
260 "set -eu",
261 `printf '%s' ${sh(brokenEntry)} > ${sh(fixture.serverEntry)}`,
262 `chmod +x ${sh(fixture.serverEntry)}`,
263 `sha256sum ${sh(fixture.serverEntry)} | cut -d ' ' -f 1 > ${sh(`${fixture.runtimeRoot}/.t3code-wsl-runtime-ready`)}`,
264 ].join("\n"),
265 );
266 expect(corrupt.status, corrupt.stderr).toBe(0);
267 expect(runShell(`${sh(fixture.serverEntry)} --version`).status).toBe(42);
268
269 const repaired = fixture.install();
270 expect(repaired.status, repaired.stderr).toBe(0);
271 expect(parseWslRuntimeRoot(repaired.stdout)).toBe(fixture.runtimeRoot);
272 expect(runShell(`cat ${sh(fixture.serverEntry)}`).stdout).toBe(SERVER_ENTRY_SOURCE);
273 expect(runShell(`${sh(fixture.serverEntry)} --version`).status).toBe(0);
274 });
275
276 it("falls back instead of launching a corrupted cache it cannot reinstall", () => {
277 const fixture = createFixture();
278 expect(fixture.install().status).toBe(0);
279 expect(runShell(`set -eu\n: > ${sh(fixture.serverEntry)}`).status).toBe(0);
280 expect(runShell(`set -eu\nrm ${sh(fixture.archivePath)}`).status).toBe(0);
281
282 const broken = fixture.install();
283
284 expect(broken.status).not.toBe(0);
285 expect(parseWslRuntimeRoot(broken.stdout)).toBeNull();
286 });
287
288 it("extracts once when two installs race for the same cache", () => {
289 const fixture = createFixture();
290 const raced = runShell(
291 [
292 "set -eu",
293 `work=${sh(fixture.work)}`,
294 'mkdir -p "$work/bin"',
295 "real_tar=$(command -v tar)",
296 `printf '#!/bin/sh\\nprintf x >> "%s/tar-calls"\\nsleep 1\\nexec %s "$@"\\n' "$work" "$real_tar" > "$work/bin/tar"`,
297 'chmod +x "$work/bin/tar"',
298 ': > "$work/tar-calls"',
299 'PATH="$work/bin:$PATH"',
300 "export PATH",
301 `cat > "$work/install.sh" <<'T3CODE_INSTALL_SCRIPT'`,
302 fixture.installScript(),
303 "T3CODE_INSTALL_SCRIPT",
304 // Keep runtime roots out of both racers' argv so their /proc scans cannot match themselves.
305 'sh "$work/install.sh" > "$work/first.out" 2>&1 &',
306 "first=$!",
307 'sh "$work/install.sh" > "$work/second.out" 2>&1 &',
308 "second=$!",
309 "if wait $first; then first_status=0; else first_status=$?; fi",
310 "if wait $second; then second_status=0; else second_status=$?; fi",
311 `printf 'firstStatus:%s\\n' "$first_status"`,
312 `printf 'secondStatus:%s\\n' "$second_status"`,
313 `printf 'extractions:%s\\n' "$(wc -c < "$work/tar-calls" | tr -d ' ')"`,
314 `printf 'firstRoot:%s\\n' "$(sed -n 's/^runtimeRoot://p' "$work/first.out")"`,
315 `printf 'secondRoot:%s\\n' "$(sed -n 's/^runtimeRoot://p' "$work/second.out")"`,
316 ].join("\n"),
317 );
318
319 expect(raced.status, raced.stderr).toBe(0);
320 expect(readField(raced.stdout, "firstStatus")).toBe("0");
321 expect(readField(raced.stdout, "secondStatus")).toBe("0");
322 expect(readField(raced.stdout, "extractions")).toBe("1");
323 expect(readField(raced.stdout, "firstRoot")).toBe(fixture.runtimeRoot);
324 expect(readField(raced.stdout, "secondRoot")).toBe(fixture.runtimeRoot);
325 });
326
327 it("leaves no half-built cache when extraction fails", () => {
328 const fixture = createFixture();
329 const truncated = runShell(
330 [
331 "set -eu",
332 `work=${sh(fixture.work)}`,
333 'size=$(wc -c < "$work/wsl-runtime.tar.gz")',
334 'head -c $((size / 2)) "$work/wsl-runtime.tar.gz" > "$work/truncated.tar.gz"',
335 `printf 'sha:%s\\n' "$(sha256sum "$work/truncated.tar.gz" | cut -d ' ' -f 1)"`,
336 ].join("\n"),
337 );
338 expect(truncated.status, truncated.stderr).toBe(0);
339
340 const failed = fixture.install(
341 `${fixture.work}/truncated.tar.gz`,
342 readField(truncated.stdout, "sha"),
343 );
344
345 expect(failed.status).not.toBe(0);
346 expect(parseWslRuntimeRoot(failed.stdout)).toBeNull();
347 const leftovers = runShell(
348 `set -eu\nfind ${sh(fixture.runtimeParent)} -mindepth 1 -maxdepth 1 -type d`,
349 );
350 expect(leftovers.stdout.trim()).toBe("");
351 });
352
353 it("refuses an archive whose bytes do not match the digest recorded for it", () => {
354 const fixture = createFixture();
355
356 const refused = fixture.install(fixture.archivePath, "e".repeat(64));
357
358 expect(refused.status).not.toBe(0);
359 expect(refused.stderr).toContain("does not match its recorded SHA-256");
360 expect(parseWslRuntimeRoot(refused.stdout)).toBeNull();
361 const leftovers = runShell(
362 `set -eu\nfind ${sh(fixture.runtimeParent)} -mindepth 1 -maxdepth 1 -type d`,
363 );
364 expect(leftovers.stdout.trim()).toBe("");
365 });
366
367 it("leases a warm cache across the prepare-to-spawn handoff", () => {
368 const fixture = createFixture();
369 expect(fixture.install().status).toBe(0);
370 const selected = runShell(
371 [
372 "set -eu",
373 `runtime_parent=${sh(fixture.runtimeParent)}`,
374 'mkdir -p "$runtime_parent/sha256-current" "$runtime_parent/sha256-previous"',
375 'printf ready > "$runtime_parent/sha256-current/.t3code-wsl-runtime-ready"',
376 'printf ready > "$runtime_parent/sha256-previous/.t3code-wsl-runtime-ready"',
377 `touch -d "10 minutes ago" ${sh(fixture.runtimeRoot)}`,
378 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"',
379 `cat > ${sh(`${fixture.work}/select.sh`)} <<'T3CODE_SELECT_SCRIPT'`,
380 fixture.installScript(),
381 "T3CODE_SELECT_SCRIPT",
382 `sh ${sh(`${fixture.work}/select.sh`)}`,
383 `HOME=${sh(`${fixture.work}/home`)}`,
384 "export HOME",
385 buildWslRuntimePruneScript("sha256-current"),
386 `test -d ${sh(fixture.runtimeRoot)}`,
387 ].join("\n"),
388 );
389
390 expect(selected.status, `${selected.stdout}\n${selected.stderr}`).toBe(0);
391 });
392
393 // Runs the distro side on the local bash, so a Windows dev box using the wsl.exe runner skips it.
394 describe.skipIf(posixShellRunner?.file !== "bash")("prepareRuntime through wsl.exe", () => {
395 // Emulates `wsl.exe [-d <distro>] [--cd <dir>] [--|--exec] <argv>` in a distro with automount off.
396 const layerFakeWslExe = (home: string) =>
397 Layer.effect(
398 ChildProcessSpawner.ChildProcessSpawner,
399 Effect.map(ChildProcessSpawner.ChildProcessSpawner, (local) =>
400 ChildProcessSpawner.make((command) => {
401 if (!ChildProcess.isStandardCommand(command) || command.command !== "wsl.exe") {
402 return local.spawn(command);
403 }
404 const args = command.args.map((word) =>
405 Redacted.isRedacted(word) ? Redacted.value(word) : word,
406 );
407 while (args.length > 0) {
408 const flag = args[0];
409 if (flag === "-d" || flag === "--distribution" || flag === "--cd") {
410 args.splice(0, 2);
411 } else if (flag === "--" || flag === "--exec" || flag === "-e") {
412 args.shift();
413 break;
414 } else {
415 break;
416 }
417 }
418 const [file = "sh", ...rest] =
419 args[0] === "wslpath"
420 ? [
421 "sh",
422 "-c",
423 'printf "wslpath: %s\\n" "$1" >&2; exit 1',
424 "wslpath",
425 args.at(-1) ?? "",
426 ]
427 : args;
428 return local.spawn(
429 ChildProcess.make(file, rest, {
430 ...command.options,
431 env: { ...command.options.env, HOME: home },
432 extendEnv: true,
433 }),
434 );
435 }),
436 ),
437 );
438
439 const layerWslEnvironment = (home: string) =>
440 layerDesktopWslEnvironment.pipe(
441 Layer.provide(
442 Layer.mergeAll(
443 layerFakeWslExe(home),
444 DesktopManagedPolicy.layerTest(),
445 Layer.effect(
446 DesktopEnvironment.DesktopEnvironment,
447 Effect.map(
448 Path.Path,
449 (path) =>
450 ({ platform: "win32", path }) as DesktopEnvironment.DesktopEnvironment["Service"],
451 ),
452 ),
453 ),
454 ),
455 Layer.provide(NodeServices.layer),
456 );
457
458 it.live("installs the runtime when wslpath cannot translate the archive's Windows path", () => {
459 const fixture = createFixture();
460 return Effect.gen(function* () {
461 const wsl = yield* DesktopWslEnvironment;
462 // The archive's Windows path; with no drives mounted, wslpath cannot map it into the distro.
463 const translated = yield* wsl.windowsToWslPath("Ubuntu", fixture.archivePath);
464 expect(translated._tag).toBe("None");
465
466 const prepared = yield* wsl.prepareRuntime("Ubuntu", {
467 windowsPath: fixture.archivePath,
468 runtimeId: fixture.runtimeId,
469 sha256: fixture.archiveSha,
470 });
471
472 expect(prepared).toEqual({ ok: true, linuxAppRoot: fixture.runtimeRoot });
473 const version = runShell(`${sh(fixture.serverEntry)} --version`);
474 expect(version.status, version.stderr).toBe(0);
475 expect(version.stdout).toBe("t3code wsl runtime test server 0.0.0\n");
476 }).pipe(Effect.provide(layerWslEnvironment(`${fixture.work}/home`)));
477 });
478 });
479
480 it("prunes old and markerless caches without touching retained, active, locked, or unrelated roots", () => {
481 const result = runShell(
482 [
483 "set -eu",
484 "work=$(mktemp -d)",
485 'home="$work/home"',
486 'runtime_parent="$home/.t3/wsl-runtime"',
487 'mkdir -p "$runtime_parent"',
488 'make_ready() { mkdir -p "$runtime_parent/$1"; printf ready > "$runtime_parent/$1/.t3code-wsl-runtime-ready"; }',
489 "make_ready sha256-current",
490 "make_ready sha256-previous",
491 "make_ready sha256-active",
492 "make_ready sha256-old",
493 "make_ready sha256-locked",
494 'mkdir -p "$runtime_parent/sha256-markerless" "$runtime_parent/versions"',
495 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"',
496 'touch -d "4 minutes ago" "$runtime_parent/sha256-active"',
497 'touch -d "3 minutes ago" "$runtime_parent/sha256-old"',
498 'touch -d "2 minutes ago" "$runtime_parent/sha256-locked"',
499 holdRuntimeBusy('"$runtime_parent/sha256-active/t3"'),
500 holdInstallLock('"$runtime_parent/.sha256-locked.install.lock"'),
501 `HOME="$home"`,
502 "export HOME",
503 buildWslRuntimePruneScript("sha256-current"),
504 'test -d "$runtime_parent/sha256-current"',
505 'test -d "$runtime_parent/sha256-previous"',
506 'test -d "$runtime_parent/sha256-active"',
507 'test -d "$runtime_parent/sha256-locked"',
508 'test -d "$runtime_parent/versions"',
509 'test ! -e "$runtime_parent/sha256-old"',
510 'test ! -e "$runtime_parent/sha256-markerless"',
511 'rm -rf "$work"',
512 ].join("\n"),
513 );
514
515 expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
516 });
517});
518
519describe("parseResolvedPath", () => {
520 it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {
521 const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
522 expect(parseResolvedPath(`nodePath:/usr/bin/node\nresolvedPath:${resolvedPath}\n`)).toBe(
523 resolvedPath,
524 );
525 });
526
527 it("accepts CRLF output without retaining the carriage return", () => {
528 expect(parseResolvedPath("resolvedPath:/usr/local/bin:/usr/bin\r\n")).toBe(
529 "/usr/local/bin:/usr/bin",
530 );
531 });
532});
533
534// Path.layer joins with POSIX separators here, so the test windir is a POSIX path.
535const WSL_EXE = "/windows/System32/wsl.exe";
536
537const isAvailable = (policy?: Parameters<typeof DesktopManagedPolicy.layerTest>[0]) =>
538 makeIsAvailable("win32", "/windows").pipe(
539 Effect.provide(
540 Layer.mergeAll(
541 FileSystem.layerNoop({ exists: (path) => Effect.succeed(path === WSL_EXE) }),
542 Path.layer,
543 DesktopManagedPolicy.layerTest(policy),
544 ),
545 ),
546 );
547
548describe("makeIsAvailable", () => {
549 it.effect("turns WSL off on a machine with a managed policy, even an invalid one", () =>
550 Effect.gen(function* () {
551 assert.isTrue(yield* isAvailable());
552 assert.isFalse(yield* isAvailable({ schemaVersion: 1, organization: "Example Corp" }));
553 assert.isFalse(
554 yield* isAvailable(new ManagedPolicyFileError({ path: "/test", reason: "bad JSON" })),
555 );
556 }),
557 );
558});
559
560describe("windowsToWslPathImpl", () => {
561 it.effect("runs wslpath without a shell so folder names stay one literal argument", () =>
562 Effect.gen(function* () {
563 const spawned: Array<ChildProcess.Command> = [];
564 const stdout = Stream.make(new TextEncoder().encode("/mnt/c/a$b & c;(d)\n"));
565 const spawner = ChildProcessSpawner.make((command) => {
566 spawned.push(command);
567 return Effect.succeed(
568 ChildProcessSpawner.makeHandle({
569 pid: ChildProcessSpawner.ProcessId(1),
570 stdout,
571 stderr: Stream.empty,
572 all: stdout,
573 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
574 isRunning: Effect.succeed(false),
575 kill: () => Effect.void,
576 stdin: Sink.drain,
577 getInputFd: () => Sink.drain,
578 getOutputFd: () => Stream.empty,
579 unref: Effect.succeed(Effect.void),
580 }),
581 );
582 });
583
584 const converted = yield* windowsToWslPathImpl("Ubuntu", "C:\\a$b & c;(d)").pipe(
585 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
586 );
587
588 assert.deepStrictEqual(converted, Option.some("/mnt/c/a$b & c;(d)"));
589 assert.lengthOf(spawned, 1);
590 const [command] = spawned;
591 assert(command?._tag === "StandardCommand");
592 assert.strictEqual(command.command, "wsl.exe");
593 assert.deepStrictEqual(command.args, [
594 "-d",
595 "Ubuntu",
596 "--exec",
597 "wslpath",
598 "-u",
599 "C:/a$b & c;(d)",
600 ]);
601 }),
602 );
603});