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 * as HostProcess from "@t3tools/shared/HostProcess";
13import { buildRemoteNodeEnvScript } from "@t3tools/ssh/tunnel";
14import { satisfiesSemverRange } from "@t3tools/shared/semver";
15
16import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
17import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
18import { parseWslDistroList, type WslDistro } from "./wslPathParsing.ts";
19
20const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
21const LIST_TIMEOUT = Duration.seconds(8);
22// Booting a stopped distro needs more time than converting paths in a running one.
23const PRE_WARM_TIMEOUT = Duration.seconds(30);
24const WSLPATH_TIMEOUT = Duration.seconds(10);
25const PROBE_TIMEOUT = Duration.seconds(10);
26const TOOLCHAIN_TIMEOUT = Duration.seconds(10);
27const BUILD_TIMEOUT = Duration.minutes(5);
28const RUNTIME_INSTALL_TIMEOUT = Duration.minutes(2);
29const RUNTIME_PRUNE_TIMEOUT = Duration.seconds(30);
30const RUNTIME_INVALIDATE_TIMEOUT = Duration.seconds(15);
31const USER_HOME_TIMEOUT = Duration.seconds(5);
32const TOOLCHAIN_TRANSPORT_RETRY_LIMIT = 12;
33const BUILD_TRANSPORT_RETRY_LIMIT = 2;
34
35export interface EnsureWslNodePtyOptions {
36 readonly allowBuild?: boolean;
37 readonly nodeEngineRange?: string | null;
38}
39
40export interface WslRuntimeArchive {
41 readonly windowsPath: string;
42 readonly runtimeId: string;
43 readonly sha256: string;
44}
45
46export type PrepareWslRuntimeResult =
47 | {
48 readonly ok: true;
49 readonly linuxAppRoot: string;
50 }
51 | {
52 readonly ok: false;
53 readonly reason: string;
54 };
55
56export type EnsureWslNodePtyResult =
57 | {
58 readonly ok: true;
59 readonly nodePath: string;
60 readonly resolvedPath: string;
61 }
62 | {
63 readonly ok: false;
64 readonly reason: string;
65 readonly fatal: boolean;
66 readonly retryLimit?: number;
67 };
68
69export type ProbeWslRuntimeResult =
70 | {
71 readonly ok: true;
72 readonly resolvedPath: string;
73 }
74 | {
75 readonly ok: false;
76 readonly reason: string;
77 };
78
79export class DesktopWslDistroListError extends Schema.TaggedError<DesktopWslDistroListError>()(
80 "DesktopWslDistroListError",
81 { reason: Schema.String },
82) {
83 override get message(): string {
84 return this.reason;
85 }
86}
87
88const isDesktopWslDistroListError = Schema.is(DesktopWslDistroListError);
89
90export class DesktopWslEnvironment extends Context.Service<
91 DesktopWslEnvironment,
92 {
93 readonly isAvailable: Effect.Effect<boolean>;
94 // UX-only best effort; health checks need probeDistros to distinguish failures from an empty installation.
95 readonly listDistros: Effect.Effect<readonly WslDistro[]>;
96 readonly probeDistros: Effect.Effect<readonly WslDistro[], DesktopWslDistroListError>;
97 readonly preWarm: (distro: string | null) => Effect.Effect<void>;
98 readonly windowsToWslPath: (
99 distro: string | null,
100 windowsPath: string,
101 ) => Effect.Effect<Option.Option<string>>;
102 readonly getUserHome: (distro: string | null) => Effect.Effect<Option.Option<string>>;
103 // Use the distro IP to avoid unreliable wslhost localhost forwarding.
104 readonly getDistroIp: (distro: string | null) => Effect.Effect<Option.Option<string>>;
105 readonly prepareRuntime: (
106 distro: string | null,
107 archive: WslRuntimeArchive,
108 ) => Effect.Effect<PrepareWslRuntimeResult>;
109 readonly pruneRuntimes: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
110 readonly invalidateRuntime: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
111 readonly probeRuntime: (
112 distro: string | null,
113 linuxAppRoot: string,
114 ) => Effect.Effect<ProbeWslRuntimeResult>;
115 readonly ensureNodePty: (
116 distro: string | null,
117 linuxAppRoot: string,
118 options?: EnsureWslNodePtyOptions,
119 ) => Effect.Effect<EnsureWslNodePtyResult>;
120 }
121>()("@t3tools/desktop/wsl/DesktopWslEnvironment") {}
122
123const buildDistroArgs = (distro: string | null): ReadonlyArray<string> =>
124 distro ? ["-d", distro] : [];
125
126const concatChunks = (arrays: ReadonlyArray<Uint8Array>): Uint8Array => {
127 let totalLength = 0;
128 for (const arr of arrays) totalLength += arr.byteLength;
129 const out = new Uint8Array(totalLength);
130 let offset = 0;
131 for (const arr of arrays) {
132 out.set(arr, offset);
133 offset += arr.byteLength;
134 }
135 return out;
136};
137
138const decodeUtf8 = (bytes: Uint8Array): string => new TextDecoder("utf-8").decode(bytes);
139
140interface ShellResult {
141 readonly exitCode: number;
142 readonly stdout: string;
143 readonly stderr: string;
144 readonly transportFailure: "timeout" | "spawn" | "process" | null;
145}
146
147const TIMEOUT_RESULT: ShellResult = {
148 exitCode: 124,
149 stdout: "",
150 stderr: "\n[timeout]",
151 transportFailure: "timeout",
152};
153
154const formatWslShellTransportFailureReason = (
155 failure: ShellResult["transportFailure"],
156 subject = "Node.js",
157): string | null => {
158 switch (failure) {
159 case "timeout":
160 return `WSL backend preflight timed out while probing for ${subject}. WSL may be slow to start; retry, or check that the distro is healthy.`;
161 case "spawn":
162 return `WSL backend preflight could not start wsl.exe to probe for ${subject}. Check that WSL is installed and the distro is accessible.`;
163 case "process":
164 return `WSL backend preflight lost communication with wsl.exe while probing for ${subject}. Retry, or check that the distro is healthy.`;
165 case null:
166 return null;
167 }
168};
169
170const buildWslNodeEnvPreamble = (
171 nodeEngineRange?: string | null,
172): string => `${buildRemoteNodeEnvScript({ nodeEngineRange: nodeEngineRange ?? null })}
173ensure_remote_node_path || true
174`;
175
176// wsl.exe re-escaping mangles quotes inside bash -lc scripts.
177const runWslShell = (
178 distro: string | null,
179 bashScript: string,
180 timeout: Duration.Duration,
181 options: {
182 readonly nodeEngineRange?: string | null;
183 readonly resolveNode?: boolean;
184 } = {},
185): Effect.Effect<ShellResult, never, ChildProcessSpawner.ChildProcessSpawner> => {
186 const spawner = ChildProcessSpawner.ChildProcessSpawner;
187 const resolveNode = options.resolveNode !== false;
188 const command = ChildProcess.make(
189 "wsl.exe",
190 resolveNode
191 ? [...buildDistroArgs(distro), "--", "bash", "-l", "-s"]
192 : [...buildDistroArgs(distro), "--exec", "sh", "-s"],
193 {
194 stdin: Stream.encodeText(
195 Stream.make(
196 resolveNode
197 ? `${buildWslNodeEnvPreamble(options.nodeEngineRange)}${bashScript}`
198 : bashScript,
199 ),
200 ),
201 stdout: "pipe",
202 stderr: "pipe",
203 killSignal: "SIGTERM",
204 forceKillAfter: PROCESS_TERMINATE_GRACE,
205 },
206 );
207
208 return Effect.scoped(
209 Effect.gen(function* () {
210 const spawnerService = yield* spawner;
211 const spawnResult = yield* spawnerService.spawn(command).pipe(
212 Effect.match({
213 onFailure: (error) => ({ _tag: "Failure", error }) as const,
214 onSuccess: (handle) => ({ _tag: "Success", handle }) as const,
215 }),
216 );
217 if (spawnResult._tag === "Failure") {
218 return {
219 exitCode: 127,
220 stdout: "",
221 stderr: `\n${spawnResult.error.message}`,
222 transportFailure: "spawn",
223 } satisfies ShellResult;
224 }
225 const handle = spawnResult.handle;
226 // Drain both pipes concurrently to prevent node-gyp output from blocking the child.
227 const [stdoutBytes, stderrBytes, exitCode] = yield* Effect.all(
228 [Stream.runCollect(handle.stdout), Stream.runCollect(handle.stderr), handle.exitCode],
229 { concurrency: "unbounded" },
230 );
231 return {
232 exitCode: exitCode as unknown as number,
233 stdout: decodeUtf8(concatChunks(stdoutBytes)),
234 stderr: decodeUtf8(concatChunks(stderrBytes)),
235 transportFailure: null,
236 } satisfies ShellResult;
237 }),
238 ).pipe(
239 Effect.timeoutOption(timeout),
240 Effect.map(Option.getOrElse((): ShellResult => TIMEOUT_RESULT)),
241 Effect.catch((error) =>
242 Effect.succeed<ShellResult>({
243 exitCode: 127,
244 stdout: "",
245 stderr: `\n${error.message}`,
246 transportFailure: "process",
247 }),
248 ),
249 );
250};
251
252const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
253
254const WSL_RUNTIME_READY_MARKER = ".t3code-wsl-runtime-ready";
255const WSL_RUNTIME_SELECTED_MARKER = ".t3code-wsl-runtime-selected";
256const WSL_RUNTIME_SELECTION_GRACE_MINUTES = 5;
257
258const sanitizeWslRuntimeId = (value: string): string => value.replace(/[^A-Za-z0-9._-]/g, "_");
259
260export const buildWslRuntimeInstallScript = (
261 linuxArchivePath: string,
262 runtimeId: string,
263 archiveSha256: string,
264): string => {
265 const safeRuntimeId = sanitizeWslRuntimeId(runtimeId);
266 return [
267 "set -eu",
268 'runtime_parent="$HOME/.t3/wsl-runtime"',
269 `runtime_root="$runtime_parent/${safeRuntimeId}"`,
270 `ready_marker="$runtime_root/${WSL_RUNTIME_READY_MARKER}"`,
271 "runtime_entry_runs() {",
272 ' [ -x "$1/t3" ] && "$1/t3" --version >/dev/null',
273 "}",
274 // Hash the entry to detect a swapped or partially written executable, even if it still runs.
275 "runtime_server_entry_digest() {",
276 ` sha256sum "$1/t3" 2>/dev/null | cut -d ' ' -f 1`,
277 "}",
278 "runtime_is_ready() {",
279 ' [ -f "$ready_marker" ] &&',
280 ' runtime_entry_runs "$runtime_root" 2>/dev/null &&',
281 ` recorded_entry_digest=$(tr -d '[:space:]' < "$ready_marker" 2>/dev/null) &&`,
282 ' [ -n "$recorded_entry_digest" ] &&',
283 ' [ "$recorded_entry_digest" = "$(runtime_server_entry_digest "$runtime_root")" ]',
284 "}",
285 'mkdir -p "$runtime_parent"',
286 `runtime_lock="$runtime_parent/.${safeRuntimeId}.install.lock"`,
287 "trap 'exit 1' HUP INT TERM",
288 'exec 9> "$runtime_lock"',
289 "flock -x 9",
290 "if runtime_is_ready; then",
291 ` touch "$runtime_root/${WSL_RUNTIME_SELECTED_MARKER}"`,
292 ` printf 'runtimeRoot:%s\\n' "$runtime_root"`,
293 " exit 0",
294 "fi",
295 `archive_sha=$(sha256sum ${shellQuote(linuxArchivePath)} | cut -d ' ' -f 1)`,
296 `if [ "$archive_sha" != ${shellQuote(archiveSha256)} ]; then`,
297 ` printf 'WSL runtime archive does not match its recorded SHA-256 (expected %s, got %s)\\n' ${shellQuote(archiveSha256)} "$archive_sha" >&2`,
298 " exit 1",
299 "fi",
300 // Deletion can remove a live backend's lazy imports; check cmdline before rename preserves its old path.
301 "runtime_in_use() {",
302 // Without /proc, assume the runtime may still be in use.
303 " [ -d /proc/1 ] || return 0",
304 ' grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null',
305 "}",
306 'if [ -e "$runtime_root" ]; then',
307 ' if runtime_in_use "$runtime_root"; then',
308 " runtime_root_in_use=1",
309 " else",
310 " runtime_root_in_use=0",
311 " fi",
312 ` runtime_stale=$(mktemp -d "$runtime_parent/.${safeRuntimeId}.stale.XXXXXX")`,
313 ' rmdir "$runtime_stale"',
314 ' if mv -T "$runtime_root" "$runtime_stale" 2>/dev/null; then',
315 ' if [ "$runtime_root_in_use" = 1 ]; then',
316 // Renaming keeps the directory's old mtime, so restart the cleanup clock.
317 ' touch "$runtime_stale"',
318 " else",
319 ' rm -rf "$runtime_stale"',
320 " fi",
321 " fi",
322 "fi",
323 `runtime_tmp=$(mktemp -d "$runtime_parent/.${safeRuntimeId}.tmp.XXXXXX")`,
324 'cleanup_runtime_install() { rm -rf "$runtime_tmp"; }',
325 "trap cleanup_runtime_install EXIT",
326 `tar -xzf ${shellQuote(linuxArchivePath)} -C "$runtime_tmp" --strip-components=1`,
327 'if ! runtime_entry_runs "$runtime_tmp"; then',
328 " printf 'WSL runtime archive does not contain a working t3 executable\\n' >&2",
329 " exit 1",
330 "fi",
331 'installed_entry_digest=$(runtime_server_entry_digest "$runtime_tmp")',
332 'if [ -z "$installed_entry_digest" ]; then',
333 " printf 'Could not hash the WSL runtime server entry\\n' >&2",
334 " exit 1",
335 "fi",
336 `printf '%s\\n' "$installed_entry_digest" > "$runtime_tmp/${WSL_RUNTIME_READY_MARKER}"`,
337 'if mv -T "$runtime_tmp" "$runtime_root" 2>/dev/null; then',
338 " :",
339 "elif runtime_is_ready; then",
340 ' rm -rf "$runtime_tmp"',
341 "else",
342 ` printf 'Could not promote WSL runtime cache at %s\\n' "$runtime_root" >&2`,
343 " exit 1",
344 "fi",
345 `touch "$runtime_root/${WSL_RUNTIME_SELECTED_MARKER}"`,
346 `printf 'runtimeRoot:%s\\n' "$runtime_root"`,
347 ].join("\n");
348};
349
350// Two hours exceeds cold-install time while bounding orphan retention.
351const ORPHANED_RUNTIME_SCRATCH_MAX_AGE_MINUTES = 120;
352
353export const buildWslRuntimePruneScript = (runtimeId: string): string => {
354 const safeRuntimeId = sanitizeWslRuntimeId(runtimeId);
355 return [
356 "set -eu",
357 'runtime_parent="$HOME/.t3/wsl-runtime"',
358 `current_runtime="$runtime_parent/${safeRuntimeId}"`,
359 '[ -d "$runtime_parent" ] || exit 0',
360 // Serialize pruning so backends cannot select and delete different previous caches.
361 'prune_lock="$runtime_parent/.prune.lock"',
362 'exec 8> "$prune_lock"',
363 "flock -x 8",
364 // Without /proc, retention cannot distinguish caches used by live backends.
365 "[ -d /proc/1 ] || exit 0",
366 "runtime_in_use() {",
367 ' grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null',
368 "}",
369 'previous_runtime=""',
370 'for candidate in "$runtime_parent"/sha256-*; do',
371 ' [ -d "$candidate" ] || continue',
372 ' [ "$candidate" != "$current_runtime" ] || continue',
373 ` [ -f "$candidate/${WSL_RUNTIME_READY_MARKER}" ] || continue`,
374 ' if [ -z "$previous_runtime" ] || [ "$candidate" -nt "$previous_runtime" ]; then',
375 ' previous_runtime="$candidate"',
376 " fi",
377 "done",
378 'for candidate in "$runtime_parent"/sha256-*; do',
379 ' [ -d "$candidate" ] || continue',
380 ' [ "$candidate" != "$current_runtime" ] || continue',
381 ' [ "$candidate" != "$previous_runtime" ] || continue',
382 ' ! runtime_in_use "$candidate" || continue',
383 " candidate_name=${candidate##*/}",
384 ' candidate_lock="$runtime_parent/.${candidate_name}.install.lock"',
385 ' exec 9> "$candidate_lock"',
386 " flock -n 9 || continue",
387 ` selected_marker="$candidate/${WSL_RUNTIME_SELECTED_MARKER}"`,
388 ` if [ -f "$selected_marker" ] && find "$selected_marker" -maxdepth 0 -mmin -${String(WSL_RUNTIME_SELECTION_GRACE_MINUTES)} -print -quit | grep -q .; then`,
389 " flock -u 9",
390 " continue",
391 " fi",
392 ' rm -rf -- "$candidate"',
393 " flock -u 9",
394 "done",
395 'for scratch in "$runtime_parent"/.*.tmp.* "$runtime_parent"/.*.stale.*; do',
396 ' [ -d "$scratch" ] || continue',
397 ` find "$scratch" -maxdepth 0 -mmin +${String(ORPHANED_RUNTIME_SCRATCH_MAX_AGE_MINUTES)} -print -quit | grep -q . || continue`,
398 ' rm -rf -- "$scratch"',
399 "done",
400 ].join("\n");
401};
402
403// Invalidate trees that pass install checks but fail launch probes, or each launch reuses the broken cache.
404export const buildWslRuntimeInvalidateScript = (runtimeId: string): string => {
405 const safeRuntimeId = sanitizeWslRuntimeId(runtimeId);
406 return [
407 "set -eu",
408 `rm -f "$HOME/.t3/wsl-runtime/${safeRuntimeId}/${WSL_RUNTIME_READY_MARKER}"`,
409 ].join("\n");
410};
411
412export const parseWslRuntimeRoot = (stdout: string): string | null => {
413 const prefix = "runtimeRoot:";
414 const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));
415 if (line === undefined) return null;
416 const runtimeRoot = line.slice(prefix.length).replace(/\r$/, "");
417 return runtimeRoot.startsWith("/") ? runtimeRoot : null;
418};
419
420const NODE_PTY_BINARY_MISSING_EXIT_CODE = 4;
421
422const formatNodePtyProbeFailureReason = (exitCode: number): string | null =>
423 exitCode === NODE_PTY_BINARY_MISSING_EXIT_CODE
424 ? "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."
425 : null;
426
427// Capture login-shell PATH because the server launches provider CLIs by name.
428const RESOLVED_PATH_LINE = `printf 'resolvedPath:%s\\n' "$PATH"`;
429
430const NODE_PTY_PROBE_SCRIPT = (
431 linuxServerDir: string,
432) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"
433printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)"
434${RESOLVED_PATH_LINE}
435cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
436// The WSL Node can't read inside app.asar, so confirm what the server needs is
437// unpacked on the real filesystem before reporting the backend healthy. Exit 3
438// marks this distinct from a node-pty binary problem so the caller can report
439// it accurately instead of letting the server crash on ERR_MODULE_NOT_FOUND at
440// launch (which, in wsl-only mode, would just fail to launch with no fallback).
441//
442// The sentinel must be a package the CLI bundle leaves external. The bundle
443// inlines its JS dependencies, so only the native packages exist on disk.
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;
490}
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",
1004 [
1005 ...buildDistroArgs(distro),
1006 "--",
1007 "sh",
1008 "-c",
1009 'printf "%s" "$(getent passwd "$(id -un)" | cut -d: -f6)"',
1010 ],
1011 {
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
1032export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable")(function* (
1033 platform: NodeJS.Platform,
1034 windir: string,
1035): Effect.fn.Return<
1036 boolean,
1037 never,
1038 FileSystem.FileSystem | Path.Path | DesktopManagedPolicy.DesktopManagedPolicy
1039> {
1040 if (platform !== "win32") return false;
1041 const path = yield* Path.Path;
1042 const fileSystem = yield* FileSystem.FileSystem;
1043 const wslExePath = path.join(windir, "System32", "wsl.exe");
1044 if (!(yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false)))) {
1045 return false;
1046 }
1047 // A server in WSL reads Linux's policy, never this machine's, so a managed machine runs none.
1048 return yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe(
1049 Effect.map((found) => found === undefined),
1050 Effect.orElseSucceed(() => false),
1051 );
1052});
1053
1054export interface DesktopWslEnvironmentTestStub {
1055 readonly isAvailable?: boolean;
1056 readonly distros?: ReadonlyArray<WslDistro>;
1057 readonly distroListError?: DesktopWslDistroListError;
1058 readonly windowsToWslPath?: (distro: string | null, windowsPath: string) => Option.Option<string>;
1059 readonly getUserHome?: (distro: string | null) => Option.Option<string>;
1060 readonly getDistroIp?: (distro: string | null) => Option.Option<string>;
1061 readonly prepareRuntime?: (
1062 distro: string | null,
1063 archive: WslRuntimeArchive,
1064 ) => PrepareWslRuntimeResult;
1065 readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
1066 readonly invalidateRuntime?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
1067 readonly probeRuntime?: (distro: string | null, linuxAppRoot: string) => ProbeWslRuntimeResult;
1068 readonly ensureNodePty?: (
1069 distro: string | null,
1070 linuxAppRoot: string,
1071 options?: EnsureWslNodePtyOptions,
1072 ) => EnsureWslNodePtyResult;
1073}
1074
1075export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
1076 const probeDistros: Effect.Effect<readonly WslDistro[], DesktopWslDistroListError> =
1077 stub.distroListError ? Effect.fail(stub.distroListError) : Effect.succeed(stub.distros ?? []);
1078 return Layer.succeed(
1079 DesktopWslEnvironment,
1080 DesktopWslEnvironment.of({
1081 isAvailable: Effect.succeed(stub.isAvailable ?? false),
1082 listDistros: probeDistros.pipe(Effect.orElseSucceed(() => [])),
1083 probeDistros,
1084 preWarm: Effect.fn("DesktopWslEnvironment.preWarm")(function () {
1085 return Effect.void;
1086 }),
1087 windowsToWslPath: Effect.fn("DesktopWslEnvironment.windowsToWslPath")(
1088 function (distro, windowsPath) {
1089 return Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none());
1090 },
1091 ),
1092 getUserHome: Effect.fn("DesktopWslEnvironment.getUserHome")(function (distro) {
1093 return Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>());
1094 }),
1095 getDistroIp: Effect.fn("DesktopWslEnvironment.getDistroIp")(function (distro) {
1096 return Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>());
1097 }),
1098 prepareRuntime: Effect.fn("DesktopWslEnvironment.prepareRuntime")(function (distro, archive) {
1099 return Effect.succeed(
1100 stub.prepareRuntime?.(distro, archive) ?? {
1101 ok: false,
1102 reason: "prepareRuntime stub not configured",
1103 },
1104 );
1105 }),
1106 pruneRuntimes: Effect.fn("DesktopWslEnvironment.pruneRuntimes")(function (distro, runtimeId) {
1107 return stub.pruneRuntimes?.(distro, runtimeId) ?? Effect.void;
1108 }),
1109 invalidateRuntime: Effect.fn("DesktopWslEnvironment.invalidateRuntime")(
1110 function (distro, runtimeId) {
1111 return stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void;
1112 },
1113 ),
1114 probeRuntime: Effect.fn("DesktopWslEnvironment.probeRuntime")(
1115 function (distro, linuxAppRoot) {
1116 return Effect.succeed(
1117 stub.probeRuntime?.(distro, linuxAppRoot) ?? {
1118 ok: true,
1119 resolvedPath: "/usr/bin:/bin",
1120 },
1121 );
1122 },
1123 ),
1124 ensureNodePty: Effect.fn("DesktopWslEnvironment.ensureNodePty")(
1125 function (distro, linuxAppRoot, options) {
1126 return Effect.succeed(
1127 stub.ensureNodePty?.(distro, linuxAppRoot, options) ?? {
1128 ok: false,
1129 reason: "ensureNodePty stub not configured",
1130 fatal: true,
1131 },
1132 );
1133 },
1134 ),
1135 }),
1136 );
1137};
1138
1139export const layer = Layer.effect(
1140 DesktopWslEnvironment,
1141 Effect.gen(function* () {
1142 const environment = yield* DesktopEnvironment.DesktopEnvironment;
1143 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1144 const fileSystem = yield* FileSystem.FileSystem;
1145 // Not Config: Windows variable names are case-insensitive only on the live process.env.
1146 const windir = (yield* HostProcess.Environment).WINDIR ?? "C:\\Windows";
1147
1148 const provideSpawner = <A, E>(
1149 effect: Effect.Effect<A, E, ChildProcessSpawner.ChildProcessSpawner>,
1150 ): Effect.Effect<A, E> =>
1151 effect.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
1152
1153 // Cache availability so synchronous IPC bootstrap can read it without yielding to filesystem I/O.
1154 const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe(
1155 Effect.provideService(FileSystem.FileSystem, fileSystem),
1156 Effect.provideService(Path.Path, environment.path),
1157 Effect.provideService(
1158 DesktopManagedPolicy.DesktopManagedPolicy,
1159 yield* DesktopManagedPolicy.DesktopManagedPolicy,
1160 ),
1161 Effect.withSpan("desktop.wsl.isAvailable"),
1162 );
1163 const isAvailable = Effect.succeed(wslAvailable);
1164
1165 const windowsToWslPath = (distro: string | null, windowsPath: string) =>
1166 provideSpawner(windowsToWslPathImpl(distro, windowsPath)).pipe(
1167 Effect.withSpan("desktop.wsl.windowsToWslPath"),
1168 );
1169
1170 const userHomeCache = new Map<string, string>();
1171 const getUserHome = Effect.fn("desktop.wsl.getUserHome")(function* (distro: string | null) {
1172 const key = distro ?? "__default__";
1173 const cached = userHomeCache.get(key);
1174 if (cached !== undefined) return Option.some(cached);
1175 const resolved = yield* provideSpawner(getUserHomeImpl(distro));
1176 if (Option.isSome(resolved)) userHomeCache.set(key, resolved.value);
1177 return resolved;
1178 });
1179
1180 const getDistroIp = (distro: string | null) =>
1181 provideSpawner(getDistroIpImpl(distro)).pipe(Effect.withSpan("desktop.wsl.getDistroIp"));
1182
1183 const probeDistros = provideSpawner(probeWslDistros).pipe(
1184 Effect.withSpan("desktop.wsl.probeDistros"),
1185 );
1186
1187 return DesktopWslEnvironment.of({
1188 isAvailable,
1189 listDistros: probeDistros.pipe(
1190 Effect.orElseSucceed(() => []),
1191 Effect.withSpan("desktop.wsl.listDistros"),
1192 ),
1193 probeDistros,
1194 preWarm: Effect.fn("desktop.wsl.preWarm")(function (distro) {
1195 return provideSpawner(preWarmImpl(distro));
1196 }),
1197 windowsToWslPath,
1198 getUserHome,
1199 getDistroIp,
1200 prepareRuntime: Effect.fn("desktop.wsl.prepareRuntime")(function (distro, archive) {
1201 return provideSpawner(prepareWslRuntimeImpl(distro, archive, windowsToWslPath));
1202 }),
1203 pruneRuntimes: Effect.fn("desktop.wsl.pruneRuntimes")(function (distro, runtimeId) {
1204 return provideSpawner(pruneWslRuntimesImpl(distro, runtimeId));
1205 }),
1206 invalidateRuntime: Effect.fn("desktop.wsl.invalidateRuntime")(function (distro, runtimeId) {
1207 return provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId));
1208 }),
1209 probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro, linuxAppRoot) {
1210 return provideSpawner(probeWslRuntimeImpl(distro, linuxAppRoot));
1211 }),
1212 ensureNodePty: Effect.fn("desktop.wsl.ensureNodePty")(
1213 function (distro, linuxAppRoot, options) {
1214 return provideSpawner(ensureNodePtyImpl(distro, linuxAppRoot, options));
1215 },
1216 ),
1217 });
1218 }),
1219);