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

DesktopWslEnvironment.ts

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