Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Path from "effect/Path";
8import * as Schema from "effect/Schema";
9import * as Stream from "effect/Stream";
10import { ChildProcess, ChildProcessSpawner } from "effect/process";
11
12import { buildRemoteNodeEnvScript } from "@t3tools/ssh/tunnel";
13import { satisfiesSemverRange } from "@t3tools/shared/semver";
14
15import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
16import { parseWslDistroList, type WslDistro } from "./wslPathParsing.ts";
17
18const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
19const LIST_TIMEOUT = Duration.seconds(8);
20// Booting a stopped distro needs more time than converting paths in a running one.
21const PRE_WARM_TIMEOUT = Duration.seconds(30);
22const WSLPATH_TIMEOUT = Duration.seconds(10);
23const PROBE_TIMEOUT = Duration.seconds(10);
24const TOOLCHAIN_TIMEOUT = Duration.seconds(10);
25const BUILD_TIMEOUT = Duration.minutes(5);
26const RUNTIME_INSTALL_TIMEOUT = Duration.minutes(2);
27const RUNTIME_PRUNE_TIMEOUT = Duration.seconds(30);
28const RUNTIME_INVALIDATE_TIMEOUT = Duration.seconds(15);
29const USER_HOME_TIMEOUT = Duration.seconds(5);
30const TOOLCHAIN_TRANSPORT_RETRY_LIMIT = 12;
31const BUILD_TRANSPORT_RETRY_LIMIT = 2;
32
33export interface EnsureWslNodePtyOptions {
34 readonly allowBuild?: boolean;
35 readonly nodeEngineRange?: string | null;
36}
37
38export interface WslRuntimeArchive {
39 readonly windowsPath: string;
40 readonly runtimeId: string;
41 readonly sha256: string;
42}
43
44export type PrepareWslRuntimeResult =
45 | {
46 readonly ok: true;
47 readonly linuxAppRoot: string;
48 }
49 | {
50 readonly ok: false;
51 readonly reason: string;
52 };
53
54export type EnsureWslNodePtyResult =
55 | {
56 readonly ok: true;
57 readonly nodePath: string;
58 readonly resolvedPath: string;
59 }
60 | {
61 readonly ok: false;
62 readonly reason: string;
63 readonly fatal: boolean;
64 readonly retryLimit?: number;
65 };
66
67export type ProbeWslRuntimeResult =
68 | {
69 readonly ok: true;
70 readonly resolvedPath: string;
71 }
72 | {
73 readonly ok: false;
74 readonly reason: string;
75 };
76
77export class DesktopWslDistroListError extends Schema.TaggedError<DesktopWslDistroListError>()(
78 "DesktopWslDistroListError",
79 { reason: Schema.String },
80) {
81 override get message(): string {
82 return this.reason;
83 }
84}
85
86const isDesktopWslDistroListError = Schema.is(DesktopWslDistroListError);
87
88export class DesktopWslEnvironment extends Context.Service<
89 DesktopWslEnvironment,
90 {
91 readonly isAvailable: Effect.Effect<boolean>;
92 // UX-only best effort; health checks need probeDistros to distinguish failures from an empty installation.
93 readonly listDistros: Effect.Effect<readonly WslDistro[]>;
94 readonly probeDistros: Effect.Effect<readonly WslDistro[], DesktopWslDistroListError>;
95 readonly preWarm: (distro: string | null) => Effect.Effect<void>;
96 readonly windowsToWslPath: (
97 distro: string | null,
98 windowsPath: string,
99 ) => Effect.Effect<Option.Option<string>>;
100 readonly getUserHome: (distro: string | null) => Effect.Effect<Option.Option<string>>;
101 // Use the distro IP to avoid unreliable wslhost localhost forwarding.
102 readonly getDistroIp: (distro: string | null) => Effect.Effect<Option.Option<string>>;
103 readonly prepareRuntime: (
104 distro: string | null,
105 archive: WslRuntimeArchive,
106 ) => Effect.Effect<PrepareWslRuntimeResult>;
107 readonly pruneRuntimes: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
108 readonly invalidateRuntime: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
109 readonly probeRuntime: (
110 distro: string | null,
111 linuxAppRoot: string,
112 ) => Effect.Effect<ProbeWslRuntimeResult>;
113 readonly ensureNodePty: (
114 distro: string | null,
115 linuxAppRoot: string,
116 options?: EnsureWslNodePtyOptions,
117 ) => Effect.Effect<EnsureWslNodePtyResult>;
118 }
119>()("@t3tools/desktop/wsl/DesktopWslEnvironment") {}
120
121const buildDistroArgs = (distro: string | null): ReadonlyArray<string> =>
122 distro ? ["-d", distro] : [];
123
124const concatChunks = (arrays: ReadonlyArray<Uint8Array>): Uint8Array => {
125 let totalLength = 0;
126 for (const arr of arrays) totalLength += arr.byteLength;
127 const out = new Uint8Array(totalLength);
128 let offset = 0;
129 for (const arr of arrays) {
130 out.set(arr, offset);
131 offset += arr.byteLength;
132 }
133 return out;
134};
135
136const decodeUtf8 = (bytes: Uint8Array): string => new TextDecoder("utf-8").decode(bytes);
137
138interface ShellResult {
139 readonly exitCode: number;
140 readonly stdout: string;
141 readonly stderr: string;
142 readonly transportFailure: "timeout" | "spawn" | "process" | null;
143}
144
145const TIMEOUT_RESULT: ShellResult = {
146 exitCode: 124,
147 stdout: "",
148 stderr: "\n[timeout]",
149 transportFailure: "timeout",
150};
151
152const formatWslShellTransportFailureReason = (
153 failure: ShellResult["transportFailure"],
154 subject = "Node.js",
155): string | null => {
156 switch (failure) {
157 case "timeout":
158 return `WSL backend preflight timed out while probing for ${subject}. WSL may be slow to start; retry, or check that the distro is healthy.`;
159 case "spawn":
160 return `WSL backend preflight could not start wsl.exe to probe for ${subject}. Check that WSL is installed and the distro is accessible.`;
161 case "process":
162 return `WSL backend preflight lost communication with wsl.exe while probing for ${subject}. Retry, or check that the distro is healthy.`;
163 case null:
164 return null;
165 }
166};
167
168const buildWslNodeEnvPreamble = (
169 nodeEngineRange?: string | null,
170): string => `${buildRemoteNodeEnvScript({ nodeEngineRange: nodeEngineRange ?? null })}
171ensure_remote_node_path || true
172`;
173
174// wsl.exe re-escaping mangles quotes inside bash -lc scripts.
175const runWslShell = (
176 distro: string | null,
177 bashScript: string,
178 timeout: Duration.Duration,
179 options: {
180 readonly nodeEngineRange?: string | null;
181 readonly resolveNode?: boolean;
182 } = {},
183): Effect.Effect<ShellResult, never, ChildProcessSpawner.ChildProcessSpawner> => {
184 const spawner = ChildProcessSpawner.ChildProcessSpawner;
185 const resolveNode = options.resolveNode !== false;
186 const command = ChildProcess.make(
187 "wsl.exe",
188 resolveNode
189 ? [...buildDistroArgs(distro), "--", "bash", "-l", "-s"]
190 : [...buildDistroArgs(distro), "--exec", "sh", "-s"],
191 {
192 stdin: Stream.encodeText(
193 Stream.make(
194 resolveNode
195 ? `${buildWslNodeEnvPreamble(options.nodeEngineRange)}${bashScript}`
196 : bashScript,
197 ),
198 ),
199 stdout: "pipe",
200 stderr: "pipe",
201 killSignal: "SIGTERM",
202 forceKillAfter: PROCESS_TERMINATE_GRACE,
203 },
204 );
205
206 return Effect.scoped(
207 Effect.gen(function* () {
208 const spawnerService = yield* spawner;
209 const spawnResult = yield* spawnerService.spawn(command).pipe(
210 Effect.match({
211 onFailure: (error) => ({ _tag: "Failure", error }) as const,
212 onSuccess: (handle) => ({ _tag: "Success", handle }) as const,
213 }),
214 );
215 if (spawnResult._tag === "Failure") {
216 return {
217 exitCode: 127,
218 stdout: "",
219 stderr: `\n${spawnResult.error.message}`,
220 transportFailure: "spawn",
221 } satisfies ShellResult;
222 }
223 const handle = spawnResult.handle;
224 // Drain both pipes concurrently to prevent node-gyp output from blocking the child.
225 const [stdoutBytes, stderrBytes, exitCode] = yield* Effect.all(
226 [Stream.runCollect(handle.stdout), Stream.runCollect(handle.stderr), handle.exitCode],
227 { concurrency: "unbounded" },
228 );
229 return {
230 exitCode: exitCode as unknown as number,
231 stdout: decodeUtf8(concatChunks(stdoutBytes)),
232 stderr: decodeUtf8(concatChunks(stderrBytes)),
233 transportFailure: null,
234 } satisfies ShellResult;
235 }),
236 ).pipe(
237 Effect.timeoutOption(timeout),
238 Effect.map(Option.getOrElse((): ShellResult => TIMEOUT_RESULT)),
239 Effect.catch((error) =>
240 Effect.succeed<ShellResult>({
241 exitCode: 127,
242 stdout: "",
243 stderr: `\n${error.message}`,
244 transportFailure: "process",
245 }),
246 ),
247 );
248};
249
250const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
251
252const WSL_RUNTIME_READY_MARKER = ".t3code-wsl-runtime-ready";
253const WSL_RUNTIME_SELECTED_MARKER = ".t3code-wsl-runtime-selected";
254const WSL_RUNTIME_SELECTION_GRACE_MINUTES = 5;
255
256const sanitizeWslRuntimeId = (value: string): string => value.replace(/[^A-Za-z0-9._-]/g, "_");
257
258export const buildWslRuntimeInstallScript = (
259 linuxArchivePath: string,
260 runtimeId: string,
261 archiveSha256: string,
262): string => {
263 const safeRuntimeId = sanitizeWslRuntimeId(runtimeId);
264 return [
265 "set -eu",
266 'runtime_parent="$HOME/.t3/wsl-runtime"',
267 `runtime_root="$runtime_parent/${safeRuntimeId}"`,
268 `ready_marker="$runtime_root/${WSL_RUNTIME_READY_MARKER}"`,
269 "runtime_entry_runs() {",
270 ' [ -x "$1/t3" ] && "$1/t3" --version >/dev/null',
271 "}",
272 // Hash the entry to detect a swapped or partially written executable, even if it still runs.
273 "runtime_server_entry_digest() {",
274 ` sha256sum "$1/t3" 2>/dev/null | cut -d ' ' -f 1`,
275 "}",
276 "runtime_is_ready() {",
277 ' [ -f "$ready_marker" ] &&',
278 ' runtime_entry_runs "$runtime_root" 2>/dev/null &&',
279 ` recorded_entry_digest=$(tr -d '[:space:]' < "$ready_marker" 2>/dev/null) &&`,
280 ' [ -n "$recorded_entry_digest" ] &&',
281 ' [ "$recorded_entry_digest" = "$(runtime_server_entry_digest "$runtime_root")" ]',
282 "}",
283 'mkdir -p "$runtime_parent"',
284 `runtime_lock="$runtime_parent/.${safeRuntimeId}.install.lock"`,
285 "trap 'exit 1' HUP INT TERM",
286 'exec 9> "$runtime_lock"',
287 "flock -x 9",
288 "if runtime_is_ready; then",
289 ` touch "$runtime_root/${WSL_RUNTIME_SELECTED_MARKER}"`,
290 ` printf 'runtimeRoot:%s\\n' "$runtime_root"`,
291 " exit 0",
292 "fi",
293 `archive_sha=$(sha256sum ${shellQuote(linuxArchivePath)} | cut -d ' ' -f 1)`,
294 `if [ "$archive_sha" != ${shellQuote(archiveSha256)} ]; then`,
295 ` printf 'WSL runtime archive does not match its recorded SHA-256 (expected %s, got %s)\\n' ${shellQuote(archiveSha256)} "$archive_sha" >&2`,
296 " exit 1",
297 "fi",
298 // Deletion can remove a live backend's lazy imports; check cmdline before rename preserves its old path.
299 "runtime_in_use() {",
300 // Without /proc, assume the runtime may still be in use.
301 " [ -d /proc/1 ] || return 0",
302 ' grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null',
303 "}",
304 'if [ -e "$runtime_root" ]; then',
305 ' if runtime_in_use "$runtime_root"; then',
306 " runtime_root_in_use=1",
307 " else",
308 " runtime_root_in_use=0",
309 " fi",
310 ` runtime_stale=$(mktemp -d "$runtime_parent/.${safeRuntimeId}.stale.XXXXXX")`,
311 ' rmdir "$runtime_stale"',
312 ' if mv -T "$runtime_root" "$runtime_stale" 2>/dev/null; then',
313 ' if [ "$runtime_root_in_use" = 1 ]; then',
314 // Renaming keeps the directory's old mtime, so restart the cleanup clock.
315 ' touch "$runtime_stale"',
316 " else",
317 ' rm -rf "$runtime_stale"',
318 " fi",
319 " fi",
320 "fi",
321 `runtime_tmp=$(mktemp -d "$runtime_parent/.${safeRuntimeId}.tmp.XXXXXX")`,
322 'cleanup_runtime_install() { rm -rf "$runtime_tmp"; }',
323 "trap cleanup_runtime_install EXIT",
324 `tar -xzf ${shellQuote(linuxArchivePath)} -C "$runtime_tmp" --strip-components=1`,
325 'if ! runtime_entry_runs "$runtime_tmp"; then',
326 " printf 'WSL runtime archive does not contain a working t3 executable\\n' >&2",
327 " exit 1",
328 "fi",
329 'installed_entry_digest=$(runtime_server_entry_digest "$runtime_tmp")',
330 'if [ -z "$installed_entry_digest" ]; then',
331 " printf 'Could not hash the WSL runtime server entry\\n' >&2",
332 " exit 1",
333 "fi",
334 `printf '%s\\n' "$installed_entry_digest" > "$runtime_tmp/${WSL_RUNTIME_READY_MARKER}"`,
335 'if mv -T "$runtime_tmp" "$runtime_root" 2>/dev/null; then',
336 " :",
337 "elif runtime_is_ready; then",
338 ' rm -rf "$runtime_tmp"',
339 "else",
340 ` printf 'Could not promote WSL runtime cache at %s\\n' "$runtime_root" >&2`,
341 " exit 1",
342 "fi",
343 `touch "$runtime_root/${WSL_RUNTIME_SELECTED_MARKER}"`,
344 `printf 'runtimeRoot:%s\\n' "$runtime_root"`,
345 ].join("\n");
346};
347
348// Two hours exceeds cold-install time while bounding orphan retention.
349const ORPHANED_RUNTIME_SCRATCH_MAX_AGE_MINUTES = 120;
350
351export const buildWslRuntimePruneScript = (runtimeId: string): string => {
352 const safeRuntimeId = sanitizeWslRuntimeId(runtimeId);
353 return [
354 "set -eu",
355 'runtime_parent="$HOME/.t3/wsl-runtime"',
356 `current_runtime="$runtime_parent/${safeRuntimeId}"`,
357 '[ -d "$runtime_parent" ] || exit 0',
358 // Serialize pruning so backends cannot select and delete different previous caches.
359 'prune_lock="$runtime_parent/.prune.lock"',
360 'exec 8> "$prune_lock"',
361 "flock -x 8",
362 // Without /proc, retention cannot distinguish caches used by live backends.
363 "[ -d /proc/1 ] || exit 0",
364 "runtime_in_use() {",
365 ' grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null',
366 "}",
367 'previous_runtime=""',
368 'for candidate in "$runtime_parent"/sha256-*; do',
369 ' [ -d "$candidate" ] || continue',
370 ' [ "$candidate" != "$current_runtime" ] || continue',
371 ` [ -f "$candidate/${WSL_RUNTIME_READY_MARKER}" ] || continue`,
372 ' if [ -z "$previous_runtime" ] || [ "$candidate" -nt "$previous_runtime" ]; then',
373 ' previous_runtime="$candidate"',
374 " fi",
375 "done",
376 'for candidate in "$runtime_parent"/sha256-*; do',
377 ' [ -d "$candidate" ] || continue',
378 ' [ "$candidate" != "$current_runtime" ] || continue',
379 ' [ "$candidate" != "$previous_runtime" ] || continue',
380 ' ! runtime_in_use "$candidate" || continue',
381 " candidate_name=${candidate##*/}",
382 ' candidate_lock="$runtime_parent/.${candidate_name}.install.lock"',
383 ' exec 9> "$candidate_lock"',
384 " flock -n 9 || continue",
385 ` selected_marker="$candidate/${WSL_RUNTIME_SELECTED_MARKER}"`,
386 ` if [ -f "$selected_marker" ] && find "$selected_marker" -maxdepth 0 -mmin -${String(WSL_RUNTIME_SELECTION_GRACE_MINUTES)} -print -quit | grep -q .; then`,
387 " flock -u 9",
388 " continue",
389 " fi",
390 ' rm -rf -- "$candidate"',
391 " flock -u 9",
392 "done",
393 'for scratch in "$runtime_parent"/.*.tmp.* "$runtime_parent"/.*.stale.*; do',
394 ' [ -d "$scratch" ] || continue',
395 ` find "$scratch" -maxdepth 0 -mmin +${String(ORPHANED_RUNTIME_SCRATCH_MAX_AGE_MINUTES)} -print -quit | grep -q . || continue`,
396 ' rm -rf -- "$scratch"',
397 "done",
398 ].join("\n");
399};
400
401// Invalidate trees that pass install checks but fail launch probes, or each launch reuses the broken cache.
402export const buildWslRuntimeInvalidateScript = (runtimeId: string): string => {
403 const safeRuntimeId = sanitizeWslRuntimeId(runtimeId);
404 return [
405 "set -eu",
406 `rm -f "$HOME/.t3/wsl-runtime/${safeRuntimeId}/${WSL_RUNTIME_READY_MARKER}"`,
407 ].join("\n");
408};
409
410export const parseWslRuntimeRoot = (stdout: string): string | null => {
411 const prefix = "runtimeRoot:";
412 const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));
413 if (line === undefined) return null;
414 const runtimeRoot = line.slice(prefix.length).replace(/\r$/, "");
415 return runtimeRoot.startsWith("/") ? runtimeRoot : null;
416};
417
418const NODE_PTY_BINARY_MISSING_EXIT_CODE = 4;
419
420const formatNodePtyProbeFailureReason = (exitCode: number): string | null =>
421 exitCode === NODE_PTY_BINARY_MISSING_EXIT_CODE
422 ? "WSL support is missing from this T3 Code build: the packaged Linux node-pty binary was not included. Install a build that includes WSL support."
423 : null;
424
425// Capture login-shell PATH because the server launches provider CLIs by name.
426const RESOLVED_PATH_LINE = `printf 'resolvedPath:%s\\n' "$PATH"`;
427
428const NODE_PTY_PROBE_SCRIPT = (
429 linuxServerDir: string,
430) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"
431printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)"
432${RESOLVED_PATH_LINE}
433cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
434// The WSL Node can't read inside app.asar, so confirm what the server needs is
435// unpacked on the real filesystem before reporting the backend healthy. Exit 3
436// marks this distinct from a node-pty binary problem so the caller can report
437// it accurately instead of letting the server crash on ERR_MODULE_NOT_FOUND at
438// launch (which, in wsl-only mode, would just fail to launch with no fallback).
439//
440// The sentinel must be a package the CLI bundle leaves external. The bundle
441// inlines its JS dependencies, so only the native packages exist on disk.
442// Resolving node-pty is what actually validates the unpacked tree.
443try { require.resolve("node-pty/package.json"); } catch (_e) { process.exit(3); }
444const fs = require("node:fs");
445const path = require("node:path");
446const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
447// node-pty 1.x is N-API based, so a single Linux pty.node is ABI-stable across
448// Node versions, so require() succeeding IS the real compatibility test. Look in
449// the same places node-pty's own loader does.
450const candidates = [
451 path.join(pkgDir, "build", "Release", "pty.node"),
452 path.join(pkgDir, "prebuilds", "linux-" + process.arch, "pty.node"),
453];
454if (!candidates.some((candidate) => fs.existsSync(candidate))) process.exit(${NODE_PTY_BINARY_MISSING_EXIT_CODE});
455require("node-pty");
456NODE`;
457
458// Resolve version-managed Node for providers without making runtime readiness depend on it.
459export const buildWslRuntimeProbeScript = (linuxAppRoot: string) =>
460 [
461 `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`,
462 `${shellQuote(`${linuxAppRoot}/t3`)} --version >/dev/null 2>&1`,
463 ].join("\n");
464
465const TOOLCHAIN_CHECK_SCRIPT = [
466 "for tool in node make g++ python3; do",
467 ' command -v "$tool" >/dev/null 2>&1 || echo "missing:$tool"',
468 "done",
469 "if command -v node >/dev/null 2>&1; then",
470 ` ver="$(node -p 'process.versions.node' 2>/dev/null)"`,
471 ' if [ -n "$ver" ]; then printf "nodeVersion:%s\\n" "$ver"; fi',
472 "fi",
473].join("\n");
474
475const NODE_PTY_BUILD_SCRIPT = (linuxServerDir: string) =>
476 [
477 "set -e",
478 `cd ${shellQuote(linuxServerDir)}`,
479 `pkg_dir=$(node -p "require('node:path').dirname(require.resolve('node-pty/package.json'))")`,
480 `cd "$pkg_dir"`,
481 "npx --yes node-gyp rebuild",
482 `node -e 'require("node-pty")'`,
483 ].join("\n");
484
485export interface ToolchainReport {
486 readonly missingTools: ReadonlyArray<string>;
487 readonly nodeVersion: string | null;
488}
489
490const parseToolchainReport = (stdout: string): ToolchainReport => {
491 const lines = stdout
492 .split("\n")
493 .map((line) => line.trim())
494 .filter((line) => line.length > 0);
495 const missingTools = lines
496 .filter((line) => line.startsWith("missing:"))
497 .map((line) => line.slice("missing:".length));
498 const nodeVersionLine = lines.find((line) => line.startsWith("nodeVersion:"));
499 const nodeVersion = nodeVersionLine
500 ? nodeVersionLine.slice("nodeVersion:".length).trim() || null
501 : null;
502 return { missingTools, nodeVersion };
503};
504
505const parseNodePath = (stdout: string): string | null => {
506 const path = stdout
507 .split("\n")
508 .map((line) => line.trim())
509 .filter((line) => line.startsWith("nodePath:"))
510 .map((line) => line.slice("nodePath:".length).trim())
511 .find((value) => value.length > 0);
512 return path ?? null;
513};
514
515const parseNodeVersion = (stdout: string): string | null => {
516 const version = stdout
517 .split("\n")
518 .map((line) => line.trim())
519 .filter((line) => line.startsWith("nodeVersion:"))
520 .map((line) => line.slice("nodeVersion:".length).trim())
521 .find((value) => value.length > 0);
522 return version ?? null;
523};
524
525// Strip only Windows CR; spaces and apostrophes must survive as one env argument.
526export const parseResolvedPath = (stdout: string): string | null => {
527 const prefix = "resolvedPath:";
528 const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));
529 if (line === undefined) return null;
530 const resolvedPath = line.slice(prefix.length).replace(/\r$/, "");
531 return resolvedPath.length > 0 ? resolvedPath : null;
532};
533
534const formatMissingToolsReason = (
535 report: ToolchainReport,
536 requiredRange: string | null,
537): string | null => {
538 const nodeMissing = report.missingTools.includes("node");
539 const nodeOutOfRange =
540 !nodeMissing &&
541 requiredRange !== null &&
542 report.nodeVersion !== null &&
543 !satisfiesSemverRange(report.nodeVersion, requiredRange);
544 const buildToolsMissing = report.missingTools.filter((tool) => tool !== "node");
545
546 if (!nodeMissing && !nodeOutOfRange && buildToolsMissing.length === 0) {
547 return null;
548 }
549
550 const issues: string[] = [];
551 const remediations: string[] = [];
552
553 if (nodeMissing) {
554 issues.push("node");
555 remediations.push(
556 `Node.js${requiredRange ? ` satisfying \`${requiredRange}\`` : " 18+"} (e.g. via nvm)`,
557 );
558 } else if (nodeOutOfRange) {
559 issues.push(`node ${report.nodeVersion} (requires ${requiredRange})`);
560 remediations.push(
561 `a newer Node.js satisfying \`${requiredRange}\` (e.g. \`nvm install 24 && nvm alias default 24\`)`,
562 );
563 }
564
565 if (buildToolsMissing.length > 0) {
566 issues.push(...buildToolsMissing);
567 remediations.push(
568 "the build toolchain (e.g. `sudo apt install -y build-essential python3` on Ubuntu/Debian)",
569 );
570 }
571
572 return `WSL distro is missing required tools: ${issues.join(", ")}. Install ${remediations.join(" and ")}, then retry.`;
573};
574
575const probeWslRuntimeImpl = Effect.fn("DesktopWslEnvironment.probeWslRuntimeImpl")(function* (
576 distro: string | null,
577 linuxAppRoot: string,
578): Effect.fn.Return<ProbeWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> {
579 const probe = yield* runWslShell(
580 distro,
581 buildWslRuntimeProbeScript(linuxAppRoot),
582 PROBE_TIMEOUT,
583 {
584 resolveNode: false,
585 },
586 );
587 const transportFailureReason = formatWslShellTransportFailureReason(
588 probe.transportFailure,
589 "the staged runtime",
590 );
591 if (transportFailureReason !== null) {
592 return { ok: false, reason: transportFailureReason } as const;
593 }
594 if (probe.exitCode !== 0) {
595 const trimmedTail = probe.stderr.trim().slice(-500);
596 return {
597 ok: false,
598 reason: `${linuxAppRoot}/t3 --version failed (exit ${probe.exitCode})${trimmedTail ? `: ${trimmedTail}` : ""}`,
599 } as const;
600 }
601 const resolvedPath = parseResolvedPath(probe.stdout);
602 if (resolvedPath === null) {
603 return {
604 ok: false,
605 reason: "WSL login-shell PATH could not be resolved during backend preflight.",
606 } as const;
607 }
608 return { ok: true, resolvedPath } as const;
609});
610
611const ensureNodePtyImpl = Effect.fn("DesktopWslEnvironment.ensureNodePtyImpl")(function* (
612 distro: string | null,
613 linuxRepoRoot: string,
614 options: EnsureWslNodePtyOptions = {},
615): Effect.fn.Return<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> {
616 // node-pty lives in the apps/server workspace's node_modules; resolve from
617 // there rather than the monorepo root, where Bun's hoist layout omits it.
618 const linuxServerDir = `${linuxRepoRoot}/apps/server`;
619
620 const probe = yield* runWslShell(
621 distro,
622 NODE_PTY_PROBE_SCRIPT(linuxServerDir),
623 PROBE_TIMEOUT,
624 options,
625 );
626 const nodePath = parseNodePath(probe.stdout);
627 const resolvedPath = parseResolvedPath(probe.stdout);
628
629 const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
630 if (transportFailureReason !== null) {
631 return {
632 ok: false,
633 reason: transportFailureReason,
634 fatal: false,
635 } as const;
636 }
637
638 if (nodePath === null) {
639 const toolchainCheck = yield* runWslShell(
640 distro,
641 TOOLCHAIN_CHECK_SCRIPT,
642 TOOLCHAIN_TIMEOUT,
643 options,
644 );
645 const toolchainTransportFailure = formatWslShellTransportFailureReason(
646 toolchainCheck.transportFailure,
647 );
648 if (toolchainTransportFailure !== null) {
649 return {
650 ok: false,
651 reason: toolchainTransportFailure,
652 fatal: false,
653 retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
654 } as const;
655 }
656 const report = parseToolchainReport(toolchainCheck.stdout);
657 const reason =
658 formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null) ??
659 "Node.js was not found in the WSL distro. Install it (e.g. via nvm) and restart the desktop app.";
660 return { ok: false, reason, fatal: true } as const;
661 }
662
663 if (resolvedPath === null) {
664 return {
665 ok: false,
666 reason: "WSL login-shell PATH could not be resolved during backend preflight.",
667 fatal: true,
668 } as const;
669 }
670
671 if (probe.exitCode === 3) {
672 return {
673 ok: false,
674 reason:
675 'WSL server dependencies could not be loaded (for example "node-pty"). The native packages the server needs are not unpacked where the WSL distro\'s Node can read them. This is a packaging problem with this build. Please report it.',
676 fatal: true,
677 } as const;
678 }
679
680 if (probe.exitCode === 0) {
681 const rawVersion = parseNodeVersion(probe.stdout);
682 if (
683 rawVersion !== null &&
684 options.nodeEngineRange &&
685 !satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())
686 ) {
687 const range = options.nodeEngineRange.trim();
688 return {
689 ok: false,
690 reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,
691 fatal: true,
692 } as const;
693 }
694 return { ok: true, nodePath, resolvedPath } as const;
695 }
696
697 if (options.allowBuild !== true) {
698 const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
699 if (packagedProbeFailure !== null) {
700 return {
701 ok: false,
702 reason: packagedProbeFailure,
703 fatal: true,
704 } as const;
705 }
706 }
707
708 const toolchainCheck = yield* runWslShell(
709 distro,
710 TOOLCHAIN_CHECK_SCRIPT,
711 TOOLCHAIN_TIMEOUT,
712 options,
713 );
714 const toolchainTransportFailure = formatWslShellTransportFailureReason(
715 toolchainCheck.transportFailure,
716 );
717 if (toolchainTransportFailure !== null) {
718 return {
719 ok: false,
720 reason: toolchainTransportFailure,
721 fatal: false,
722 retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
723 } as const;
724 }
725 const report = parseToolchainReport(toolchainCheck.stdout);
726
727 if (options.allowBuild !== true) {
728 // Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp,
729 // or network is needed — and we must not nag the user to install build
730 // tools they don't need.
731 const nodeOnlyReason = formatMissingToolsReason(
732 {
733 missingTools: report.missingTools.filter((tool) => tool === "node"),
734 nodeVersion: report.nodeVersion,
735 },
736 options.nodeEngineRange?.trim() || null,
737 );
738 return {
739 ok: false,
740 reason:
741 nodeOnlyReason ??
742 "The bundled WSL backend binary (node-pty) could not be loaded in this distro. This usually means an unsupported CPU architecture or incompatible system libraries (glibc). Use a glibc-based x64/arm64 WSL distro such as Ubuntu; if you already are, please report this with your distro and the output of `uname -m`.",
743 fatal: true,
744 } as const;
745 }
746
747 const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);
748 if (missingReason !== null) {
749 return { ok: false, reason: missingReason, fatal: true } as const;
750 }
751
752 const build = yield* runWslShell(
753 distro,
754 NODE_PTY_BUILD_SCRIPT(linuxServerDir),
755 BUILD_TIMEOUT,
756 options,
757 );
758 const buildTransportFailure = formatWslShellTransportFailureReason(build.transportFailure);
759 if (buildTransportFailure !== null) {
760 return {
761 ok: false,
762 reason: buildTransportFailure,
763 fatal: false,
764 retryLimit: BUILD_TRANSPORT_RETRY_LIMIT,
765 } as const;
766 }
767 if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
768 const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500);
769 return {
770 ok: false,
771 reason: `node-pty Linux build failed (exit ${build.exitCode}): ${trimmedTail || "no stderr captured"}`,
772 fatal: true,
773 } as const;
774});
775
776const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(function* (
777 distro: string | null,
778 archive: WslRuntimeArchive,
779 windowsToWslPath: (
780 distro: string | null,
781 windowsPath: string,
782 ) => Effect.Effect<Option.Option<string>>,
783): Effect.fn.Return<PrepareWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> {
784 const linuxArchivePath = yield* windowsToWslPath(distro, archive.windowsPath);
785 if (Option.isNone(linuxArchivePath)) {
786 return {
787 ok: false,
788 reason: `wslpath conversion failed for ${archive.windowsPath}`,
789 } as const;
790 }
791
792 const install = yield* runWslShell(
793 distro,
794 buildWslRuntimeInstallScript(linuxArchivePath.value, archive.runtimeId, archive.sha256),
795 RUNTIME_INSTALL_TIMEOUT,
796 { resolveNode: false },
797 );
798 if (install.transportFailure !== null) {
799 return {
800 ok: false,
801 reason:
802 install.transportFailure === "timeout"
803 ? "WSL runtime installation timed out. Check that the distro has free disk space, then retry."
804 : "WSL runtime installation lost communication with wsl.exe. Retry, or check that the distro is healthy.",
805 } as const;
806 }
807 if (install.exitCode !== 0) {
808 const trimmedTail = `${install.stdout}${install.stderr}`.trim().slice(-500);
809 return {
810 ok: false,
811 reason: `WSL runtime installation failed (exit ${install.exitCode}): ${trimmedTail || "no stderr captured"}`,
812 } as const;
813 }
814
815 const linuxAppRoot = parseWslRuntimeRoot(install.stdout);
816 return linuxAppRoot === null
817 ? {
818 ok: false,
819 reason: "WSL runtime installation completed without reporting its cache path.",
820 }
821 : { ok: true, linuxAppRoot };
822});
823
824const pruneWslRuntimesImpl = Effect.fn("desktop.wsl.pruneRuntimesImpl")(function* (
825 distro: string | null,
826 runtimeId: string,
827): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
828 const result = yield* runWslShell(
829 distro,
830 buildWslRuntimePruneScript(runtimeId),
831 RUNTIME_PRUNE_TIMEOUT,
832 { resolveNode: false },
833 );
834 if (result.transportFailure === null && result.exitCode === 0) return;
835
836 const detail = `${result.stdout}${result.stderr}`.trim().slice(-500);
837 yield* Effect.logWarning("Could not prune old WSL runtime caches.", {
838 distro,
839 runtimeId,
840 detail: detail || `exit ${result.exitCode}`,
841 });
842});
843
844const invalidateWslRuntimeImpl = Effect.fn("desktop.wsl.invalidateRuntimeImpl")(function* (
845 distro: string | null,
846 runtimeId: string,
847): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
848 const result = yield* runWslShell(
849 distro,
850 buildWslRuntimeInvalidateScript(runtimeId),
851 RUNTIME_INVALIDATE_TIMEOUT,
852 { resolveNode: false },
853 );
854 if (result.transportFailure === null && result.exitCode === 0) return;
855
856 const detail = `${result.stdout}${result.stderr}`.trim().slice(-500);
857 yield* Effect.logWarning("Could not invalidate the staged WSL runtime cache.", {
858 distro,
859 runtimeId,
860 detail: detail || `exit ${result.exitCode}`,
861 });
862});
863
864const probeWslDistros: Effect.Effect<
865 readonly WslDistro[],
866 DesktopWslDistroListError,
867 ChildProcessSpawner.ChildProcessSpawner
868> = Effect.scoped(
869 Effect.gen(function* () {
870 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
871 const command = ChildProcess.make("wsl.exe", ["--list", "--verbose"], {
872 stdin: "ignore",
873 stdout: "pipe",
874 stderr: "ignore",
875 killSignal: "SIGTERM",
876 forceKillAfter: PROCESS_TERMINATE_GRACE,
877 });
878 const handle = yield* spawner.spawn(command);
879 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
880 const exitCode = yield* handle.exitCode;
881 if ((exitCode as unknown as number) !== 0) {
882 return yield* new DesktopWslDistroListError({
883 reason: `wsl.exe --list --verbose exited with code ${String(exitCode)}`,
884 });
885 }
886 return parseWslDistroList(Buffer.from(concatChunks(stdoutBytes)));
887 }),
888).pipe(
889 Effect.mapError((error) =>
890 isDesktopWslDistroListError(error)
891 ? error
892 : new DesktopWslDistroListError({
893 reason: `Failed to run wsl.exe --list --verbose: ${error.message}`,
894 }),
895 ),
896 Effect.timeoutOption(LIST_TIMEOUT),
897 Effect.flatMap(
898 Option.match({
899 onNone: () =>
900 new DesktopWslDistroListError({
901 reason: "wsl.exe --list --verbose timed out",
902 }),
903 onSome: Effect.succeed,
904 }),
905 ),
906);
907
908const preWarmImpl = (
909 distro: string | null,
910): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> =>
911 Effect.scoped(
912 Effect.gen(function* () {
913 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
914 const command = ChildProcess.make("wsl.exe", [...buildDistroArgs(distro), "--", "true"], {
915 stdin: "ignore",
916 stdout: "ignore",
917 stderr: "ignore",
918 killSignal: "SIGTERM",
919 forceKillAfter: PROCESS_TERMINATE_GRACE,
920 });
921 const handle = yield* spawner.spawn(command);
922 yield* handle.exitCode;
923 }),
924 ).pipe(Effect.timeoutOption(PRE_WARM_TIMEOUT), Effect.ignore);
925
926const windowsToWslPathImpl = (
927 distro: string | null,
928 windowsPath: string,
929): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> => {
930 // wsl.exe interprets backslashes as escape chars; normalize to forward slashes.
931 const normalized = windowsPath.replaceAll("\\", "/");
932 return Effect.scoped(
933 Effect.gen(function* () {
934 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
935 const command = ChildProcess.make(
936 "wsl.exe",
937 [...buildDistroArgs(distro), "--", "wslpath", "-u", normalized],
938 {
939 stdin: "ignore",
940 stdout: "pipe",
941 stderr: "ignore",
942 killSignal: "SIGTERM",
943 forceKillAfter: PROCESS_TERMINATE_GRACE,
944 },
945 );
946 const handle = yield* spawner.spawn(command);
947 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
948 const exitCode = yield* handle.exitCode;
949 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
950 const converted = decodeUtf8(concatChunks(stdoutBytes)).trim();
951 return converted.length > 0 ? Option.some(converted) : Option.none<string>();
952 }),
953 ).pipe(
954 Effect.timeoutOption(WSLPATH_TIMEOUT),
955 Effect.map(Option.flatten),
956 Effect.orElseSucceed(() => Option.none<string>()),
957 );
958};
959
960const IPV4_PATTERN = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
961
962const getDistroIpImpl = (
963 distro: string | null,
964): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
965 Effect.scoped(
966 Effect.gen(function* () {
967 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
968 // WSL2's first hostname -I address is reachable directly from Windows without wslhost forwarding.
969 const command = ChildProcess.make(
970 "wsl.exe",
971 [...buildDistroArgs(distro), "--", "sh", "-c", "hostname -I"],
972 {
973 stdin: "ignore",
974 stdout: "pipe",
975 stderr: "ignore",
976 killSignal: "SIGTERM",
977 forceKillAfter: PROCESS_TERMINATE_GRACE,
978 },
979 );
980 const handle = yield* spawner.spawn(command);
981 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
982 const exitCode = yield* handle.exitCode;
983 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
984 const raw = decodeUtf8(concatChunks(stdoutBytes)).trim();
985 const candidate = raw.split(/\s+/).find((part) => IPV4_PATTERN.test(part));
986 return candidate ? Option.some(candidate) : Option.none<string>();
987 }),
988 ).pipe(
989 Effect.timeoutOption(USER_HOME_TIMEOUT),
990 Effect.map(Option.flatten),
991 Effect.orElseSucceed(() => Option.none<string>()),
992 );
993
994const getUserHomeImpl = (
995 distro: string | null,
996): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
997 Effect.scoped(
998 Effect.gen(function* () {
999 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1000 const command = ChildProcess.make(
1001 "wsl.exe",
1002 [
1003 ...buildDistroArgs(distro),
1004 "--",
1005 "sh",
1006 "-c",
1007 'printf "%s" "$(getent passwd "$(id -un)" | cut -d: -f6)"',
1008 ],
1009 {
1010 stdin: "ignore",
1011 stdout: "pipe",
1012 stderr: "ignore",
1013 killSignal: "SIGTERM",
1014 forceKillAfter: PROCESS_TERMINATE_GRACE,
1015 },
1016 );
1017 const handle = yield* spawner.spawn(command);
1018 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
1019 const exitCode = yield* handle.exitCode;
1020 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
1021 const home = decodeUtf8(concatChunks(stdoutBytes)).trim();
1022 return home.startsWith("/") ? Option.some(home) : Option.none<string>();
1023 }),
1024 ).pipe(
1025 Effect.timeoutOption(USER_HOME_TIMEOUT),
1026 Effect.map(Option.flatten),
1027 Effect.orElseSucceed(() => Option.none<string>()),
1028 );
1029
1030const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable")(function* (
1031 platform: NodeJS.Platform,
1032 windir: string,
1033): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
1034 if (platform !== "win32") return false;
1035 const path = yield* Path.Path;
1036 const fileSystem = yield* FileSystem.FileSystem;
1037 const wslExePath = path.join(windir, "System32", "wsl.exe");
1038 return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));
1039});
1040
1041export interface DesktopWslEnvironmentTestStub {
1042 readonly isAvailable?: boolean;
1043 readonly distros?: ReadonlyArray<WslDistro>;
1044 readonly distroListError?: DesktopWslDistroListError;
1045 readonly windowsToWslPath?: (distro: string | null, windowsPath: string) => Option.Option<string>;
1046 readonly getUserHome?: (distro: string | null) => Option.Option<string>;
1047 readonly getDistroIp?: (distro: string | null) => Option.Option<string>;
1048 readonly prepareRuntime?: (
1049 distro: string | null,
1050 archive: WslRuntimeArchive,
1051 ) => PrepareWslRuntimeResult;
1052 readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
1053 readonly invalidateRuntime?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
1054 readonly probeRuntime?: (distro: string | null, linuxAppRoot: string) => ProbeWslRuntimeResult;
1055 readonly ensureNodePty?: (
1056 distro: string | null,
1057 linuxAppRoot: string,
1058 options?: EnsureWslNodePtyOptions,
1059 ) => EnsureWslNodePtyResult;
1060}
1061
1062export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
1063 const probeDistros: Effect.Effect<readonly WslDistro[], DesktopWslDistroListError> =
1064 stub.distroListError ? Effect.fail(stub.distroListError) : Effect.succeed(stub.distros ?? []);
1065 return Layer.succeed(
1066 DesktopWslEnvironment,
1067 DesktopWslEnvironment.of({
1068 isAvailable: Effect.succeed(stub.isAvailable ?? false),
1069 listDistros: probeDistros.pipe(Effect.orElseSucceed(() => [])),
1070 probeDistros,
1071 preWarm: Effect.fn("DesktopWslEnvironment.preWarm")(function () {
1072 return Effect.void;
1073 }),
1074 windowsToWslPath: Effect.fn("DesktopWslEnvironment.windowsToWslPath")(
1075 function (distro, windowsPath) {
1076 return Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none());
1077 },
1078 ),
1079 getUserHome: Effect.fn("DesktopWslEnvironment.getUserHome")(function (distro) {
1080 return Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>());
1081 }),
1082 getDistroIp: Effect.fn("DesktopWslEnvironment.getDistroIp")(function (distro) {
1083 return Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>());
1084 }),
1085 prepareRuntime: Effect.fn("DesktopWslEnvironment.prepareRuntime")(function (distro, archive) {
1086 return Effect.succeed(
1087 stub.prepareRuntime?.(distro, archive) ?? {
1088 ok: false,
1089 reason: "prepareRuntime stub not configured",
1090 },
1091 );
1092 }),
1093 pruneRuntimes: Effect.fn("DesktopWslEnvironment.pruneRuntimes")(function (distro, runtimeId) {
1094 return stub.pruneRuntimes?.(distro, runtimeId) ?? Effect.void;
1095 }),
1096 invalidateRuntime: Effect.fn("DesktopWslEnvironment.invalidateRuntime")(
1097 function (distro, runtimeId) {
1098 return stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void;
1099 },
1100 ),
1101 probeRuntime: Effect.fn("DesktopWslEnvironment.probeRuntime")(
1102 function (distro, linuxAppRoot) {
1103 return Effect.succeed(
1104 stub.probeRuntime?.(distro, linuxAppRoot) ?? {
1105 ok: true,
1106 resolvedPath: "/usr/bin:/bin",
1107 },
1108 );
1109 },
1110 ),
1111 ensureNodePty: Effect.fn("DesktopWslEnvironment.ensureNodePty")(
1112 function (distro, linuxAppRoot, options) {
1113 return Effect.succeed(
1114 stub.ensureNodePty?.(distro, linuxAppRoot, options) ?? {
1115 ok: false,
1116 reason: "ensureNodePty stub not configured",
1117 fatal: true,
1118 },
1119 );
1120 },
1121 ),
1122 }),
1123 );
1124};
1125
1126export const layer = Layer.effect(
1127 DesktopWslEnvironment,
1128 Effect.gen(function* () {
1129 const environment = yield* DesktopEnvironment.DesktopEnvironment;
1130 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1131 const fileSystem = yield* FileSystem.FileSystem;
1132 const windir = process.env.WINDIR ?? "C:\\Windows";
1133
1134 const provideSpawner = <A, E>(
1135 effect: Effect.Effect<A, E, ChildProcessSpawner.ChildProcessSpawner>,
1136 ): Effect.Effect<A, E> =>
1137 effect.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
1138
1139 // Cache availability so synchronous IPC bootstrap can read it without yielding to filesystem I/O.
1140 const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe(
1141 Effect.provideService(FileSystem.FileSystem, fileSystem),
1142 Effect.provideService(Path.Path, environment.path),
1143 Effect.withSpan("desktop.wsl.isAvailable"),
1144 );
1145 const isAvailable = Effect.succeed(wslAvailable);
1146
1147 const windowsToWslPath = (distro: string | null, windowsPath: string) =>
1148 provideSpawner(windowsToWslPathImpl(distro, windowsPath)).pipe(
1149 Effect.withSpan("desktop.wsl.windowsToWslPath"),
1150 );
1151
1152 const userHomeCache = new Map<string, string>();
1153 const getUserHome = Effect.fn("desktop.wsl.getUserHome")(function* (distro: string | null) {
1154 const key = distro ?? "__default__";
1155 const cached = userHomeCache.get(key);
1156 if (cached !== undefined) return Option.some(cached);
1157 const resolved = yield* provideSpawner(getUserHomeImpl(distro));
1158 if (Option.isSome(resolved)) userHomeCache.set(key, resolved.value);
1159 return resolved;
1160 });
1161
1162 const getDistroIp = (distro: string | null) =>
1163 provideSpawner(getDistroIpImpl(distro)).pipe(Effect.withSpan("desktop.wsl.getDistroIp"));
1164
1165 const probeDistros = provideSpawner(probeWslDistros).pipe(
1166 Effect.withSpan("desktop.wsl.probeDistros"),
1167 );
1168
1169 return DesktopWslEnvironment.of({
1170 isAvailable,
1171 listDistros: probeDistros.pipe(
1172 Effect.orElseSucceed(() => []),
1173 Effect.withSpan("desktop.wsl.listDistros"),
1174 ),
1175 probeDistros,
1176 preWarm: Effect.fn("desktop.wsl.preWarm")(function (distro) {
1177 return provideSpawner(preWarmImpl(distro));
1178 }),
1179 windowsToWslPath,
1180 getUserHome,
1181 getDistroIp,
1182 prepareRuntime: Effect.fn("desktop.wsl.prepareRuntime")(function (distro, archive) {
1183 return provideSpawner(prepareWslRuntimeImpl(distro, archive, windowsToWslPath));
1184 }),
1185 pruneRuntimes: Effect.fn("desktop.wsl.pruneRuntimes")(function (distro, runtimeId) {
1186 return provideSpawner(pruneWslRuntimesImpl(distro, runtimeId));
1187 }),
1188 invalidateRuntime: Effect.fn("desktop.wsl.invalidateRuntime")(function (distro, runtimeId) {
1189 return provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId));
1190 }),
1191 probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro, linuxAppRoot) {
1192 return provideSpawner(probeWslRuntimeImpl(distro, linuxAppRoot));
1193 }),
1194 ensureNodePty: Effect.fn("desktop.wsl.ensureNodePty")(
1195 function (distro, linuxAppRoot, options) {
1196 return provideSpawner(ensureNodePtyImpl(distro, linuxAppRoot, options));
1197 },
1198 ),
1199 });
1200 }),
1201);