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

DesktopWslEnvironment.ts

1,203 lines44.2 KB

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;
37​
38export interface WslRuntimeArchive {
39 readonly windowsPath: string;
40 readonly runtimeId: string;
41 readonly sha256: string;
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 }
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;
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. It used to be
441// "effect", back when the bundle externalized its runtime deps and the whole
442// node_modules tree was unpacked. The bundle now inlines its JS dependencies,
443// so "effect" no longer exists on disk and only the native packages do.
444// Resolving node-pty is what actually validates the unpacked tree.
445try { require.resolve("node-pty/package.json"); } catch (_e) { process.exit(3); }
446const fs = require("node:fs");
447const path = require("node:path");
448const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
449// node-pty 1.x is N-API based, so a single Linux pty.node is ABI-stable across
450// Node versions, so require() succeeding IS the real compatibility test. Look in
451// the same places node-pty's own loader does.
452const candidates = [
453 path.join(pkgDir, "build", "Release", "pty.node"),
454 path.join(pkgDir, "prebuilds", "linux-" + process.arch, "pty.node"),
455];
456if (!candidates.some((candidate) => fs.existsSync(candidate))) process.exit(${NODE_PTY_BINARY_MISSING_EXIT_CODE});
457require("node-pty");
458NODE`;
459​
460// Resolve version-managed Node for providers without making runtime readiness depend on it.
461export const buildWslRuntimeProbeScript = (linuxAppRoot: string) =>
462 [
463 `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`,
464 `${shellQuote(`${linuxAppRoot}/t3`)} --version >/dev/null 2>&1`,
465 ].join("\n");
466​
467const TOOLCHAIN_CHECK_SCRIPT = [
468 "for tool in node make g++ python3; do",
469 ' command -v "$tool" >/dev/null 2>&1 || echo "missing:$tool"',
470 "done",
471 "if command -v node >/dev/null 2>&1; then",
472 ` ver="$(node -p 'process.versions.node' 2>/dev/null)"`,
473 ' if [ -n "$ver" ]; then printf "nodeVersion:%s\\n" "$ver"; fi',
474 "fi",
475].join("\n");
476​
477const NODE_PTY_BUILD_SCRIPT = (linuxServerDir: string) =>
478 [
479 "set -e",
480 `cd ${shellQuote(linuxServerDir)}`,
481 `pkg_dir=$(node -p "require('node:path').dirname(require.resolve('node-pty/package.json'))")`,
482 `cd "$pkg_dir"`,
483 "npx --yes node-gyp rebuild",
484 `node -e 'require("node-pty")'`,
485 ].join("\n");
486​
487export interface ToolchainReport {
488 readonly missingTools: ReadonlyArray<string>;
489 readonly nodeVersion: string | null;
491​
492const parseToolchainReport = (stdout: string): ToolchainReport => {
493 const lines = stdout
494 .split("\n")
495 .map((line) => line.trim())
496 .filter((line) => line.length > 0);
497 const missingTools = lines
498 .filter((line) => line.startsWith("missing:"))
499 .map((line) => line.slice("missing:".length));
500 const nodeVersionLine = lines.find((line) => line.startsWith("nodeVersion:"));
501 const nodeVersion = nodeVersionLine
502 ? nodeVersionLine.slice("nodeVersion:".length).trim() || null
503 : null;
504 return { missingTools, nodeVersion };
505};
506​
507const parseNodePath = (stdout: string): string | null => {
508 const path = stdout
509 .split("\n")
510 .map((line) => line.trim())
511 .filter((line) => line.startsWith("nodePath:"))
512 .map((line) => line.slice("nodePath:".length).trim())
513 .find((value) => value.length > 0);
514 return path ?? null;
515};
516​
517const parseNodeVersion = (stdout: string): string | null => {
518 const version = stdout
519 .split("\n")
520 .map((line) => line.trim())
521 .filter((line) => line.startsWith("nodeVersion:"))
522 .map((line) => line.slice("nodeVersion:".length).trim())
523 .find((value) => value.length > 0);
524 return version ?? null;
525};
526​
527// Strip only Windows CR; spaces and apostrophes must survive as one env argument.
528export const parseResolvedPath = (stdout: string): string | null => {
529 const prefix = "resolvedPath:";
530 const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));
531 if (line === undefined) return null;
532 const resolvedPath = line.slice(prefix.length).replace(/\r$/, "");
533 return resolvedPath.length > 0 ? resolvedPath : null;
534};
535​
536const formatMissingToolsReason = (
537 report: ToolchainReport,
538 requiredRange: string | null,
539): string | null => {
540 const nodeMissing = report.missingTools.includes("node");
541 const nodeOutOfRange =
542 !nodeMissing &&
543 requiredRange !== null &&
544 report.nodeVersion !== null &&
545 !satisfiesSemverRange(report.nodeVersion, requiredRange);
546 const buildToolsMissing = report.missingTools.filter((tool) => tool !== "node");
547​
548 if (!nodeMissing && !nodeOutOfRange && buildToolsMissing.length === 0) {
549 return null;
550 }
551​
552 const issues: string[] = [];
553 const remediations: string[] = [];
554​
555 if (nodeMissing) {
556 issues.push("node");
557 remediations.push(
558 `Node.js${requiredRange ? ` satisfying \`${requiredRange}\`` : " 18+"} (e.g. via nvm)`,
559 );
560 } else if (nodeOutOfRange) {
561 issues.push(`node ${report.nodeVersion} (requires ${requiredRange})`);
562 remediations.push(
563 `a newer Node.js satisfying \`${requiredRange}\` (e.g. \`nvm install 24 && nvm alias default 24\`)`,
564 );
565 }
566​
567 if (buildToolsMissing.length > 0) {
568 issues.push(...buildToolsMissing);
569 remediations.push(
570 "the build toolchain (e.g. `sudo apt install -y build-essential python3` on Ubuntu/Debian)",
571 );
572 }
573​
574 return `WSL distro is missing required tools: ${issues.join(", ")}. Install ${remediations.join(" and ")}, then retry.`;
575};
576​
577const probeWslRuntimeImpl = Effect.fn("DesktopWslEnvironment.probeWslRuntimeImpl")(function* (
578 distro: string | null,
579 linuxAppRoot: string,
580): Effect.fn.Return<ProbeWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> {
581 const probe = yield* runWslShell(
582 distro,
583 buildWslRuntimeProbeScript(linuxAppRoot),
584 PROBE_TIMEOUT,
585 {
586 resolveNode: false,
587 },
588 );
589 const transportFailureReason = formatWslShellTransportFailureReason(
590 probe.transportFailure,
591 "the staged runtime",
592 );
593 if (transportFailureReason !== null) {
594 return { ok: false, reason: transportFailureReason } as const;
595 }
596 if (probe.exitCode !== 0) {
597 const trimmedTail = probe.stderr.trim().slice(-500);
598 return {
599 ok: false,
600 reason: `${linuxAppRoot}/t3 --version failed (exit ${probe.exitCode})${trimmedTail ? `: ${trimmedTail}` : ""}`,
601 } as const;
602 }
603 const resolvedPath = parseResolvedPath(probe.stdout);
604 if (resolvedPath === null) {
605 return {
606 ok: false,
607 reason: "WSL login-shell PATH could not be resolved during backend preflight.",
608 } as const;
609 }
610 return { ok: true, resolvedPath } as const;
611});
612​
613const ensureNodePtyImpl = Effect.fn("DesktopWslEnvironment.ensureNodePtyImpl")(function* (
614 distro: string | null,
615 linuxRepoRoot: string,
616 options: EnsureWslNodePtyOptions = {},
617): Effect.fn.Return<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> {
618 // node-pty lives in the apps/server workspace's node_modules; resolve from
619 // there rather than the monorepo root, where Bun's hoist layout omits it.
620 const linuxServerDir = `${linuxRepoRoot}/apps/server`;
621​
622 const probe = yield* runWslShell(
623 distro,
624 NODE_PTY_PROBE_SCRIPT(linuxServerDir),
625 PROBE_TIMEOUT,
626 options,
627 );
628 const nodePath = parseNodePath(probe.stdout);
629 const resolvedPath = parseResolvedPath(probe.stdout);
630​
631 const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
632 if (transportFailureReason !== null) {
633 return {
634 ok: false,
635 reason: transportFailureReason,
636 fatal: false,
637 } as const;
638 }
639​
640 if (nodePath === null) {
641 const toolchainCheck = yield* runWslShell(
642 distro,
643 TOOLCHAIN_CHECK_SCRIPT,
644 TOOLCHAIN_TIMEOUT,
645 options,
646 );
647 const toolchainTransportFailure = formatWslShellTransportFailureReason(
648 toolchainCheck.transportFailure,
649 );
650 if (toolchainTransportFailure !== null) {
651 return {
652 ok: false,
653 reason: toolchainTransportFailure,
654 fatal: false,
655 retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
656 } as const;
657 }
658 const report = parseToolchainReport(toolchainCheck.stdout);
659 const reason =
660 formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null) ??
661 "Node.js was not found in the WSL distro. Install it (e.g. via nvm) and restart the desktop app.";
662 return { ok: false, reason, fatal: true } as const;
663 }
664​
665 if (resolvedPath === null) {
666 return {
667 ok: false,
668 reason: "WSL login-shell PATH could not be resolved during backend preflight.",
669 fatal: true,
670 } as const;
671 }
672​
673 if (probe.exitCode === 3) {
674 return {
675 ok: false,
676 reason:
677 '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.',
678 fatal: true,
679 } as const;
680 }
681​
682 if (probe.exitCode === 0) {
683 const rawVersion = parseNodeVersion(probe.stdout);
684 if (
685 rawVersion !== null &&
686 options.nodeEngineRange &&
687 !satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())
688 ) {
689 const range = options.nodeEngineRange.trim();
690 return {
691 ok: false,
692 reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,
693 fatal: true,
694 } as const;
695 }
696 return { ok: true, nodePath, resolvedPath } as const;
697 }
698​
699 if (options.allowBuild !== true) {
700 const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
701 if (packagedProbeFailure !== null) {
702 return {
703 ok: false,
704 reason: packagedProbeFailure,
705 fatal: true,
706 } as const;
707 }
708 }
709​
710 const toolchainCheck = yield* runWslShell(
711 distro,
712 TOOLCHAIN_CHECK_SCRIPT,
713 TOOLCHAIN_TIMEOUT,
714 options,
715 );
716 const toolchainTransportFailure = formatWslShellTransportFailureReason(
717 toolchainCheck.transportFailure,
718 );
719 if (toolchainTransportFailure !== null) {
720 return {
721 ok: false,
722 reason: toolchainTransportFailure,
723 fatal: false,
724 retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
725 } as const;
726 }
727 const report = parseToolchainReport(toolchainCheck.stdout);
728​
729 if (options.allowBuild !== true) {
730 // Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp,
731 // or network is needed — and we must not nag the user to install build
732 // tools they don't need.
733 const nodeOnlyReason = formatMissingToolsReason(
734 {
735 missingTools: report.missingTools.filter((tool) => tool === "node"),
736 nodeVersion: report.nodeVersion,
737 },
738 options.nodeEngineRange?.trim() || null,
739 );
740 return {
741 ok: false,
742 reason:
743 nodeOnlyReason ??
744 "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`.",
745 fatal: true,
746 } as const;
747 }
748​
749 const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);
750 if (missingReason !== null) {
751 return { ok: false, reason: missingReason, fatal: true } as const;
752 }
753​
754 const build = yield* runWslShell(
755 distro,
756 NODE_PTY_BUILD_SCRIPT(linuxServerDir),
757 BUILD_TIMEOUT,
758 options,
759 );
760 const buildTransportFailure = formatWslShellTransportFailureReason(build.transportFailure);
761 if (buildTransportFailure !== null) {
762 return {
763 ok: false,
764 reason: buildTransportFailure,
765 fatal: false,
766 retryLimit: BUILD_TRANSPORT_RETRY_LIMIT,
767 } as const;
768 }
769 if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
770 const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500);
771 return {
772 ok: false,
773 reason: `node-pty Linux build failed (exit ${build.exitCode}): ${trimmedTail || "no stderr captured"}`,
774 fatal: true,
775 } as const;
776});
777​
778const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(function* (
779 distro: string | null,
780 archive: WslRuntimeArchive,
781 windowsToWslPath: (
782 distro: string | null,
783 windowsPath: string,
784 ) => Effect.Effect<Option.Option<string>>,
785): Effect.fn.Return<PrepareWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> {
786 const linuxArchivePath = yield* windowsToWslPath(distro, archive.windowsPath);
787 if (Option.isNone(linuxArchivePath)) {
788 return {
789 ok: false,
790 reason: `wslpath conversion failed for ${archive.windowsPath}`,
791 } as const;
792 }
793​
794 const install = yield* runWslShell(
795 distro,
796 buildWslRuntimeInstallScript(linuxArchivePath.value, archive.runtimeId, archive.sha256),
797 RUNTIME_INSTALL_TIMEOUT,
798 { resolveNode: false },
799 );
800 if (install.transportFailure !== null) {
801 return {
802 ok: false,
803 reason:
804 install.transportFailure === "timeout"
805 ? "WSL runtime installation timed out. Check that the distro has free disk space, then retry."
806 : "WSL runtime installation lost communication with wsl.exe. Retry, or check that the distro is healthy.",
807 } as const;
808 }
809 if (install.exitCode !== 0) {
810 const trimmedTail = `${install.stdout}${install.stderr}`.trim().slice(-500);
811 return {
812 ok: false,
813 reason: `WSL runtime installation failed (exit ${install.exitCode}): ${trimmedTail || "no stderr captured"}`,
814 } as const;
815 }
816​
817 const linuxAppRoot = parseWslRuntimeRoot(install.stdout);
818 return linuxAppRoot === null
819 ? {
820 ok: false,
821 reason: "WSL runtime installation completed without reporting its cache path.",
822 }
823 : { ok: true, linuxAppRoot };
824});
825​
826const pruneWslRuntimesImpl = Effect.fn("desktop.wsl.pruneRuntimesImpl")(function* (
827 distro: string | null,
828 runtimeId: string,
829): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
830 const result = yield* runWslShell(
831 distro,
832 buildWslRuntimePruneScript(runtimeId),
833 RUNTIME_PRUNE_TIMEOUT,
834 { resolveNode: false },
835 );
836 if (result.transportFailure === null && result.exitCode === 0) return;
837​
838 const detail = `${result.stdout}${result.stderr}`.trim().slice(-500);
839 yield* Effect.logWarning("Could not prune old WSL runtime caches.", {
840 distro,
841 runtimeId,
842 detail: detail || `exit ${result.exitCode}`,
843 });
844});
845​
846const invalidateWslRuntimeImpl = Effect.fn("desktop.wsl.invalidateRuntimeImpl")(function* (
847 distro: string | null,
848 runtimeId: string,
849): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
850 const result = yield* runWslShell(
851 distro,
852 buildWslRuntimeInvalidateScript(runtimeId),
853 RUNTIME_INVALIDATE_TIMEOUT,
854 { resolveNode: false },
855 );
856 if (result.transportFailure === null && result.exitCode === 0) return;
857​
858 const detail = `${result.stdout}${result.stderr}`.trim().slice(-500);
859 yield* Effect.logWarning("Could not invalidate the staged WSL runtime cache.", {
860 distro,
861 runtimeId,
862 detail: detail || `exit ${result.exitCode}`,
863 });
864});
865​
866const probeWslDistros: Effect.Effect<
867 readonly WslDistro[],
868 DesktopWslDistroListError,
869 ChildProcessSpawner.ChildProcessSpawner
870> = Effect.scoped(
871 Effect.gen(function* () {
872 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
873 const command = ChildProcess.make("wsl.exe", ["--list", "--verbose"], {
874 stdin: "ignore",
875 stdout: "pipe",
876 stderr: "ignore",
877 killSignal: "SIGTERM",
878 forceKillAfter: PROCESS_TERMINATE_GRACE,
879 });
880 const handle = yield* spawner.spawn(command);
881 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
882 const exitCode = yield* handle.exitCode;
883 if ((exitCode as unknown as number) !== 0) {
884 return yield* new DesktopWslDistroListError({
885 reason: `wsl.exe --list --verbose exited with code ${String(exitCode)}`,
886 });
887 }
888 return parseWslDistroList(Buffer.from(concatChunks(stdoutBytes)));
889 }),
890).pipe(
891 Effect.mapError((error) =>
892 isDesktopWslDistroListError(error)
893 ? error
894 : new DesktopWslDistroListError({
895 reason: `Failed to run wsl.exe --list --verbose: ${error.message}`,
896 }),
897 ),
898 Effect.timeoutOption(LIST_TIMEOUT),
899 Effect.flatMap(
900 Option.match({
901 onNone: () =>
902 new DesktopWslDistroListError({
903 reason: "wsl.exe --list --verbose timed out",
904 }),
905 onSome: Effect.succeed,
906 }),
907 ),
908);
909​
910const preWarmImpl = (
911 distro: string | null,
912): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> =>
913 Effect.scoped(
914 Effect.gen(function* () {
915 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
916 const command = ChildProcess.make("wsl.exe", [...buildDistroArgs(distro), "--", "true"], {
917 stdin: "ignore",
918 stdout: "ignore",
919 stderr: "ignore",
920 killSignal: "SIGTERM",
921 forceKillAfter: PROCESS_TERMINATE_GRACE,
922 });
923 const handle = yield* spawner.spawn(command);
924 yield* handle.exitCode;
925 }),
926 ).pipe(Effect.timeoutOption(PRE_WARM_TIMEOUT), Effect.ignore);
927​
928const windowsToWslPathImpl = (
929 distro: string | null,
930 windowsPath: string,
931): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> => {
932 // wsl.exe interprets backslashes as escape chars; normalize to forward slashes.
933 const normalized = windowsPath.replaceAll("\\", "/");
934 return Effect.scoped(
935 Effect.gen(function* () {
936 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
937 const command = ChildProcess.make(
938 "wsl.exe",
939 [...buildDistroArgs(distro), "--", "wslpath", "-u", normalized],
940 {
941 stdin: "ignore",
942 stdout: "pipe",
943 stderr: "ignore",
944 killSignal: "SIGTERM",
945 forceKillAfter: PROCESS_TERMINATE_GRACE,
946 },
947 );
948 const handle = yield* spawner.spawn(command);
949 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
950 const exitCode = yield* handle.exitCode;
951 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
952 const converted = decodeUtf8(concatChunks(stdoutBytes)).trim();
953 return converted.length > 0 ? Option.some(converted) : Option.none<string>();
954 }),
955 ).pipe(
956 Effect.timeoutOption(WSLPATH_TIMEOUT),
957 Effect.map(Option.flatten),
958 Effect.orElseSucceed(() => Option.none<string>()),
959 );
960};
961​
962const IPV4_PATTERN = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
963​
964const getDistroIpImpl = (
965 distro: string | null,
966): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
967 Effect.scoped(
968 Effect.gen(function* () {
969 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
970 // WSL2's first hostname -I address is reachable directly from Windows without wslhost forwarding.
971 const command = ChildProcess.make(
972 "wsl.exe",
973 [...buildDistroArgs(distro), "--", "sh", "-c", "hostname -I"],
974 {
975 stdin: "ignore",
976 stdout: "pipe",
977 stderr: "ignore",
978 killSignal: "SIGTERM",
979 forceKillAfter: PROCESS_TERMINATE_GRACE,
980 },
981 );
982 const handle = yield* spawner.spawn(command);
983 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
984 const exitCode = yield* handle.exitCode;
985 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
986 const raw = decodeUtf8(concatChunks(stdoutBytes)).trim();
987 const candidate = raw.split(/\s+/).find((part) => IPV4_PATTERN.test(part));
988 return candidate ? Option.some(candidate) : Option.none<string>();
989 }),
990 ).pipe(
991 Effect.timeoutOption(USER_HOME_TIMEOUT),
992 Effect.map(Option.flatten),
993 Effect.orElseSucceed(() => Option.none<string>()),
994 );
995​
996const getUserHomeImpl = (
997 distro: string | null,
998): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
999 Effect.scoped(
1000 Effect.gen(function* () {
1001 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1002 const command = ChildProcess.make(
1003 "wsl.exe",
1005 ...buildDistroArgs(distro),
1006 "--",
1007 "sh",
1008 "-c",
1009 'printf "%s" "$(getent passwd "$(id -un)" | cut -d: -f6)"',
1010 ],
1012 stdin: "ignore",
1013 stdout: "pipe",
1014 stderr: "ignore",
1015 killSignal: "SIGTERM",
1016 forceKillAfter: PROCESS_TERMINATE_GRACE,
1017 },
1018 );
1019 const handle = yield* spawner.spawn(command);
1020 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
1021 const exitCode = yield* handle.exitCode;
1022 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
1023 const home = decodeUtf8(concatChunks(stdoutBytes)).trim();
1024 return home.startsWith("/") ? Option.some(home) : Option.none<string>();
1025 }),
1026 ).pipe(
1027 Effect.timeoutOption(USER_HOME_TIMEOUT),
1028 Effect.map(Option.flatten),
1029 Effect.orElseSucceed(() => Option.none<string>()),
1030 );
1031​
1032const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable")(function* (
1033 platform: NodeJS.Platform,
1034 windir: string,
1035): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
1036 if (platform !== "win32") return false;
1037 const path = yield* Path.Path;
1038 const fileSystem = yield* FileSystem.FileSystem;
1039 const wslExePath = path.join(windir, "System32", "wsl.exe");
1040 return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));
1041});
1042​
1043export interface DesktopWslEnvironmentTestStub {
1044 readonly isAvailable?: boolean;
1045 readonly distros?: ReadonlyArray<WslDistro>;
1046 readonly distroListError?: DesktopWslDistroListError;
1047 readonly windowsToWslPath?: (distro: string | null, windowsPath: string) => Option.Option<string>;
1048 readonly getUserHome?: (distro: string | null) => Option.Option<string>;
1049 readonly getDistroIp?: (distro: string | null) => Option.Option<string>;
1050 readonly prepareRuntime?: (
1051 distro: string | null,
1052 archive: WslRuntimeArchive,
1053 ) => PrepareWslRuntimeResult;
1054 readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
1055 readonly invalidateRuntime?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
1056 readonly probeRuntime?: (distro: string | null, linuxAppRoot: string) => ProbeWslRuntimeResult;
1057 readonly ensureNodePty?: (
1058 distro: string | null,
1059 linuxAppRoot: string,
1060 options?: EnsureWslNodePtyOptions,
1061 ) => EnsureWslNodePtyResult;
1063​
1064export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
1065 const probeDistros: Effect.Effect<readonly WslDistro[], DesktopWslDistroListError> =
1066 stub.distroListError ? Effect.fail(stub.distroListError) : Effect.succeed(stub.distros ?? []);
1067 return Layer.succeed(
1068 DesktopWslEnvironment,
1069 DesktopWslEnvironment.of({
1070 isAvailable: Effect.succeed(stub.isAvailable ?? false),
1071 listDistros: probeDistros.pipe(Effect.orElseSucceed(() => [])),
1072 probeDistros,
1073 preWarm: Effect.fn("DesktopWslEnvironment.preWarm")(function () {
1074 return Effect.void;
1075 }),
1076 windowsToWslPath: Effect.fn("DesktopWslEnvironment.windowsToWslPath")(
1077 function (distro, windowsPath) {
1078 return Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none());
1079 },
1080 ),
1081 getUserHome: Effect.fn("DesktopWslEnvironment.getUserHome")(function (distro) {
1082 return Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>());
1083 }),
1084 getDistroIp: Effect.fn("DesktopWslEnvironment.getDistroIp")(function (distro) {
1085 return Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>());
1086 }),
1087 prepareRuntime: Effect.fn("DesktopWslEnvironment.prepareRuntime")(function (distro, archive) {
1088 return Effect.succeed(
1089 stub.prepareRuntime?.(distro, archive) ?? {
1090 ok: false,
1091 reason: "prepareRuntime stub not configured",
1092 },
1093 );
1094 }),
1095 pruneRuntimes: Effect.fn("DesktopWslEnvironment.pruneRuntimes")(function (distro, runtimeId) {
1096 return stub.pruneRuntimes?.(distro, runtimeId) ?? Effect.void;
1097 }),
1098 invalidateRuntime: Effect.fn("DesktopWslEnvironment.invalidateRuntime")(
1099 function (distro, runtimeId) {
1100 return stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void;
1101 },
1102 ),
1103 probeRuntime: Effect.fn("DesktopWslEnvironment.probeRuntime")(
1104 function (distro, linuxAppRoot) {
1105 return Effect.succeed(
1106 stub.probeRuntime?.(distro, linuxAppRoot) ?? {
1107 ok: true,
1108 resolvedPath: "/usr/bin:/bin",
1109 },
1110 );
1111 },
1112 ),
1113 ensureNodePty: Effect.fn("DesktopWslEnvironment.ensureNodePty")(
1114 function (distro, linuxAppRoot, options) {
1115 return Effect.succeed(
1116 stub.ensureNodePty?.(distro, linuxAppRoot, options) ?? {
1117 ok: false,
1118 reason: "ensureNodePty stub not configured",
1119 fatal: true,
1120 },
1121 );
1122 },
1123 ),
1124 }),
1125 );
1127​
1128export const layer = Layer.effect(
1129 DesktopWslEnvironment,
1130 Effect.gen(function* () {
1131 const environment = yield* DesktopEnvironment.DesktopEnvironment;
1132 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1133 const fileSystem = yield* FileSystem.FileSystem;
1134 const windir = process.env.WINDIR ?? "C:\\Windows";
1135​
1136 const provideSpawner = <A, E>(
1137 effect: Effect.Effect<A, E, ChildProcessSpawner.ChildProcessSpawner>,
1138 ): Effect.Effect<A, E> =>
1139 effect.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
1140​
1141 // Cache availability so synchronous IPC bootstrap can read it without yielding to filesystem I/O.
1142 const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe(
1143 Effect.provideService(FileSystem.FileSystem, fileSystem),
1144 Effect.provideService(Path.Path, environment.path),
1145 Effect.withSpan("desktop.wsl.isAvailable"),
1146 );
1147 const isAvailable = Effect.succeed(wslAvailable);
1148​
1149 const windowsToWslPath = (distro: string | null, windowsPath: string) =>
1150 provideSpawner(windowsToWslPathImpl(distro, windowsPath)).pipe(
1151 Effect.withSpan("desktop.wsl.windowsToWslPath"),
1152 );
1153​
1154 const userHomeCache = new Map<string, string>();
1155 const getUserHome = Effect.fn("desktop.wsl.getUserHome")(function* (distro: string | null) {
1156 const key = distro ?? "__default__";
1157 const cached = userHomeCache.get(key);
1158 if (cached !== undefined) return Option.some(cached);
1159 const resolved = yield* provideSpawner(getUserHomeImpl(distro));
1160 if (Option.isSome(resolved)) userHomeCache.set(key, resolved.value);
1161 return resolved;
1162 });
1163​
1164 const getDistroIp = (distro: string | null) =>
1165 provideSpawner(getDistroIpImpl(distro)).pipe(Effect.withSpan("desktop.wsl.getDistroIp"));
1166​
1167 const probeDistros = provideSpawner(probeWslDistros).pipe(
1168 Effect.withSpan("desktop.wsl.probeDistros"),
1169 );
1170​
1171 return DesktopWslEnvironment.of({
1172 isAvailable,
1173 listDistros: probeDistros.pipe(
1174 Effect.orElseSucceed(() => []),
1175 Effect.withSpan("desktop.wsl.listDistros"),
1176 ),
1177 probeDistros,
1178 preWarm: Effect.fn("desktop.wsl.preWarm")(function (distro) {
1179 return provideSpawner(preWarmImpl(distro));
1180 }),
1181 windowsToWslPath,
1182 getUserHome,
1183 getDistroIp,
1184 prepareRuntime: Effect.fn("desktop.wsl.prepareRuntime")(function (distro, archive) {
1185 return provideSpawner(prepareWslRuntimeImpl(distro, archive, windowsToWslPath));
1186 }),
1187 pruneRuntimes: Effect.fn("desktop.wsl.pruneRuntimes")(function (distro, runtimeId) {
1188 return provideSpawner(pruneWslRuntimesImpl(distro, runtimeId));
1189 }),
1190 invalidateRuntime: Effect.fn("desktop.wsl.invalidateRuntime")(function (distro, runtimeId) {
1191 return provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId));
1192 }),
1193 probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro, linuxAppRoot) {
1194 return provideSpawner(probeWslRuntimeImpl(distro, linuxAppRoot));
1195 }),
1196 ensureNodePty: Effect.fn("desktop.wsl.ensureNodePty")(
1197 function (distro, linuxAppRoot, options) {
1198 return provideSpawner(ensureNodePtyImpl(distro, linuxAppRoot, options));
1199 },
1200 ),
1201 });
1202 }),