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

DesktopWslEnvironment.ts

1,217 lines45.6 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​
516export const 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​
531export const 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​
541export const 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​
561export const 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 = (
603 distro: string | null,
604 linuxAppRoot: string,
605): Effect.Effect<ProbeWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> =>
606 Effect.gen(function* () {
607 const probe = yield* runWslShell(
608 distro,
609 buildWslRuntimeProbeScript(linuxAppRoot),
610 PROBE_TIMEOUT,
611 {
612 resolveNode: false,
613 },
614 );
615 const transportFailureReason = formatWslShellTransportFailureReason(
616 probe.transportFailure,
617 "the staged runtime",
618 );
619 if (transportFailureReason !== null) {
620 return { ok: false, reason: transportFailureReason } as const;
621 }
622 if (probe.exitCode !== 0) {
623 const trimmedTail = probe.stderr.trim().slice(-500);
624 return {
625 ok: false,
626 reason: `${linuxAppRoot}/t3 --version failed (exit ${probe.exitCode})${trimmedTail ? `: ${trimmedTail}` : ""}`,
627 } as const;
628 }
629 const resolvedPath = parseResolvedPath(probe.stdout);
630 if (resolvedPath === null) {
631 return {
632 ok: false,
633 reason: "WSL login-shell PATH could not be resolved during backend preflight.",
634 } as const;
635 }
636 return { ok: true, resolvedPath } as const;
637 });
638​
639const ensureNodePtyImpl = (
640 distro: string | null,
641 linuxRepoRoot: string,
642 options: EnsureWslNodePtyOptions = {},
643): Effect.Effect<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> =>
644 Effect.gen(function* () {
645 // node-pty lives in the apps/server workspace's node_modules; resolve from
646 // there rather than the monorepo root, where Bun's hoist layout omits it.
647 const linuxServerDir = `${linuxRepoRoot}/apps/server`;
648​
649 const probe = yield* runWslShell(
650 distro,
651 NODE_PTY_PROBE_SCRIPT(linuxServerDir),
652 PROBE_TIMEOUT,
653 options,
654 );
655 const nodePath = parseNodePath(probe.stdout);
656 const resolvedPath = parseResolvedPath(probe.stdout);
657​
658 const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
659 if (transportFailureReason !== null) {
660 return {
661 ok: false,
662 reason: transportFailureReason,
663 fatal: false,
664 } as const;
665 }
666​
667 if (nodePath === null) {
668 const toolchainCheck = yield* runWslShell(
669 distro,
670 TOOLCHAIN_CHECK_SCRIPT,
671 TOOLCHAIN_TIMEOUT,
672 options,
673 );
674 const toolchainTransportFailure = formatWslShellTransportFailureReason(
675 toolchainCheck.transportFailure,
676 );
677 if (toolchainTransportFailure !== null) {
678 return {
679 ok: false,
680 reason: toolchainTransportFailure,
681 fatal: false,
682 retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
683 } as const;
684 }
685 const report = parseToolchainReport(toolchainCheck.stdout);
686 const reason =
687 formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null) ??
688 "Node.js was not found in the WSL distro. Install it (e.g. via nvm) and restart the desktop app.";
689 return { ok: false, reason, fatal: true } as const;
690 }
691​
692 if (resolvedPath === null) {
693 return {
694 ok: false,
695 reason: "WSL login-shell PATH could not be resolved during backend preflight.",
696 fatal: true,
697 } as const;
698 }
699​
700 if (probe.exitCode === 3) {
701 return {
702 ok: false,
703 reason:
704 '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.',
705 fatal: true,
706 } as const;
707 }
708​
709 if (probe.exitCode === 0) {
710 const rawVersion = parseNodeVersion(probe.stdout);
711 if (
712 rawVersion !== null &&
713 options.nodeEngineRange &&
714 !satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())
715 ) {
716 const range = options.nodeEngineRange.trim();
717 return {
718 ok: false,
719 reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,
720 fatal: true,
721 } as const;
722 }
723 return { ok: true, nodePath, resolvedPath } as const;
724 }
725​
726 if (options.allowBuild !== true) {
727 const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
728 if (packagedProbeFailure !== null) {
729 return {
730 ok: false,
731 reason: packagedProbeFailure,
732 fatal: true,
733 } as const;
734 }
735 }
736​
737 const toolchainCheck = yield* runWslShell(
738 distro,
739 TOOLCHAIN_CHECK_SCRIPT,
740 TOOLCHAIN_TIMEOUT,
741 options,
742 );
743 const toolchainTransportFailure = formatWslShellTransportFailureReason(
744 toolchainCheck.transportFailure,
745 );
746 if (toolchainTransportFailure !== null) {
747 return {
748 ok: false,
749 reason: toolchainTransportFailure,
750 fatal: false,
751 retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
752 } as const;
753 }
754 const report = parseToolchainReport(toolchainCheck.stdout);
755​
756 if (options.allowBuild !== true) {
757 // Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp,
758 // or network is needed — and we must not nag the user to install build
759 // tools they don't need.
760 const nodeOnlyReason = formatMissingToolsReason(
761 {
762 missingTools: report.missingTools.filter((tool) => tool === "node"),
763 nodeVersion: report.nodeVersion,
764 },
765 options.nodeEngineRange?.trim() || null,
766 );
767 return {
768 ok: false,
769 reason:
770 nodeOnlyReason ??
771 "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`.",
772 fatal: true,
773 } as const;
774 }
775​
776 const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);
777 if (missingReason !== null) {
778 return { ok: false, reason: missingReason, fatal: true } as const;
779 }
780​
781 const build = yield* runWslShell(
782 distro,
783 NODE_PTY_BUILD_SCRIPT(linuxServerDir),
784 BUILD_TIMEOUT,
785 options,
786 );
787 const buildTransportFailure = formatWslShellTransportFailureReason(build.transportFailure);
788 if (buildTransportFailure !== null) {
789 return {
790 ok: false,
791 reason: buildTransportFailure,
792 fatal: false,
793 retryLimit: BUILD_TRANSPORT_RETRY_LIMIT,
794 } as const;
795 }
796 if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
797 const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500);
798 return {
799 ok: false,
800 reason: `node-pty Linux build failed (exit ${build.exitCode}): ${trimmedTail || "no stderr captured"}`,
801 fatal: true,
802 } as const;
803 });
804​
805const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(function* (
806 distro: string | null,
807 archive: WslRuntimeArchive,
808 windowsToWslPath: (
809 distro: string | null,
810 windowsPath: string,
811 ) => Effect.Effect<Option.Option<string>>,
812): Effect.fn.Return<PrepareWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> {
813 const linuxArchivePath = yield* windowsToWslPath(distro, archive.windowsPath);
814 if (Option.isNone(linuxArchivePath)) {
815 return {
816 ok: false,
817 reason: `wslpath conversion failed for ${archive.windowsPath}`,
818 } as const;
819 }
820​
821 const install = yield* runWslShell(
822 distro,
823 buildWslRuntimeInstallScript(linuxArchivePath.value, archive.runtimeId, archive.sha256),
824 RUNTIME_INSTALL_TIMEOUT,
825 { resolveNode: false },
826 );
827 if (install.transportFailure !== null) {
828 return {
829 ok: false,
830 reason:
831 install.transportFailure === "timeout"
832 ? "WSL runtime installation timed out. Check that the distro has free disk space, then retry."
833 : "WSL runtime installation lost communication with wsl.exe. Retry, or check that the distro is healthy.",
834 } as const;
835 }
836 if (install.exitCode !== 0) {
837 const trimmedTail = `${install.stdout}${install.stderr}`.trim().slice(-500);
838 return {
839 ok: false,
840 reason: `WSL runtime installation failed (exit ${install.exitCode}): ${trimmedTail || "no stderr captured"}`,
841 } as const;
842 }
843​
844 const linuxAppRoot = parseWslRuntimeRoot(install.stdout);
845 return linuxAppRoot === null
846 ? {
847 ok: false,
848 reason: "WSL runtime installation completed without reporting its cache path.",
849 }
850 : { ok: true, linuxAppRoot };
851});
852​
853const pruneWslRuntimesImpl = Effect.fn("desktop.wsl.pruneRuntimesImpl")(function* (
854 distro: string | null,
855 runtimeId: string,
856): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
857 const result = yield* runWslShell(
858 distro,
859 buildWslRuntimePruneScript(runtimeId),
860 RUNTIME_PRUNE_TIMEOUT,
861 { resolveNode: false },
862 );
863 if (result.transportFailure === null && result.exitCode === 0) return;
864​
865 const detail = `${result.stdout}${result.stderr}`.trim().slice(-500);
866 yield* Effect.logWarning("Could not prune old WSL runtime caches.", {
867 distro,
868 runtimeId,
869 detail: detail || `exit ${result.exitCode}`,
870 });
871});
872​
873const invalidateWslRuntimeImpl = Effect.fn("desktop.wsl.invalidateRuntimeImpl")(function* (
874 distro: string | null,
875 runtimeId: string,
876): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
877 const result = yield* runWslShell(
878 distro,
879 buildWslRuntimeInvalidateScript(runtimeId),
880 RUNTIME_INVALIDATE_TIMEOUT,
881 { resolveNode: false },
882 );
883 if (result.transportFailure === null && result.exitCode === 0) return;
884​
885 const detail = `${result.stdout}${result.stderr}`.trim().slice(-500);
886 yield* Effect.logWarning("Could not invalidate the staged WSL runtime cache.", {
887 distro,
888 runtimeId,
889 detail: detail || `exit ${result.exitCode}`,
890 });
891});
892​
893export const probeWslDistros: Effect.Effect<
894 readonly WslDistro[],
895 DesktopWslDistroListError,
896 ChildProcessSpawner.ChildProcessSpawner
897> = Effect.scoped(
898 Effect.gen(function* () {
899 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
900 const command = ChildProcess.make("wsl.exe", ["--list", "--verbose"], {
901 stdin: "ignore",
902 stdout: "pipe",
903 stderr: "ignore",
904 killSignal: "SIGTERM",
905 forceKillAfter: PROCESS_TERMINATE_GRACE,
906 });
907 const handle = yield* spawner.spawn(command);
908 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
909 const exitCode = yield* handle.exitCode;
910 if ((exitCode as unknown as number) !== 0) {
911 return yield* new DesktopWslDistroListError({
912 reason: `wsl.exe --list --verbose exited with code ${String(exitCode)}`,
913 });
914 }
915 return parseWslDistroList(Buffer.from(concatChunks(stdoutBytes)));
916 }),
917).pipe(
918 Effect.mapError((error) =>
919 isDesktopWslDistroListError(error)
920 ? error
921 : new DesktopWslDistroListError({
922 reason: `Failed to run wsl.exe --list --verbose: ${error.message}`,
923 }),
924 ),
925 Effect.timeoutOption(LIST_TIMEOUT),
926 Effect.flatMap(
927 Option.match({
928 onNone: () =>
929 new DesktopWslDistroListError({
930 reason: "wsl.exe --list --verbose timed out",
931 }),
932 onSome: Effect.succeed,
933 }),
934 ),
935);
936​
937const preWarmImpl = (
938 distro: string | null,
939): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> =>
940 Effect.scoped(
941 Effect.gen(function* () {
942 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
943 const command = ChildProcess.make("wsl.exe", [...buildDistroArgs(distro), "--", "true"], {
944 stdin: "ignore",
945 stdout: "ignore",
946 stderr: "ignore",
947 killSignal: "SIGTERM",
948 forceKillAfter: PROCESS_TERMINATE_GRACE,
949 });
950 const handle = yield* spawner.spawn(command);
951 yield* handle.exitCode;
952 }),
953 ).pipe(Effect.timeoutOption(PRE_WARM_TIMEOUT), Effect.ignore);
954​
955const windowsToWslPathImpl = (
956 distro: string | null,
957 windowsPath: string,
958): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> => {
959 // wsl.exe interprets backslashes as escape chars; normalize to forward slashes.
960 const normalized = windowsPath.replaceAll("\\", "/");
961 return Effect.scoped(
962 Effect.gen(function* () {
963 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
964 const command = ChildProcess.make(
965 "wsl.exe",
966 [...buildDistroArgs(distro), "--", "wslpath", "-u", normalized],
967 {
968 stdin: "ignore",
969 stdout: "pipe",
970 stderr: "ignore",
971 killSignal: "SIGTERM",
972 forceKillAfter: PROCESS_TERMINATE_GRACE,
973 },
974 );
975 const handle = yield* spawner.spawn(command);
976 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
977 const exitCode = yield* handle.exitCode;
978 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
979 const converted = decodeUtf8(concatChunks(stdoutBytes)).trim();
980 return converted.length > 0 ? Option.some(converted) : Option.none<string>();
981 }),
982 ).pipe(
983 Effect.timeoutOption(WSLPATH_TIMEOUT),
984 Effect.map(Option.flatten),
985 Effect.orElseSucceed(() => Option.none<string>()),
986 );
987};
988​
989const IPV4_PATTERN = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
990​
991const getDistroIpImpl = (
992 distro: string | null,
993): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
994 Effect.scoped(
995 Effect.gen(function* () {
996 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
997 // `hostname -I` prints a space-separated list of all non-loopback
998 // IPs the distro has bound. The first entry on the WSL2 default
999 // network is always the eth0 vEthernet address Windows can reach
1000 // directly (no wslhost forwarding required).
1001 const command = ChildProcess.make(
1002 "wsl.exe",
1003 [...buildDistroArgs(distro), "--", "sh", "-c", "hostname -I"],
1005 stdin: "ignore",
1006 stdout: "pipe",
1007 stderr: "ignore",
1008 killSignal: "SIGTERM",
1009 forceKillAfter: PROCESS_TERMINATE_GRACE,
1010 },
1011 );
1012 const handle = yield* spawner.spawn(command);
1013 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
1014 const exitCode = yield* handle.exitCode;
1015 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
1016 const raw = decodeUtf8(concatChunks(stdoutBytes)).trim();
1017 const candidate = raw.split(/\s+/).find((part) => IPV4_PATTERN.test(part));
1018 return candidate ? Option.some(candidate) : Option.none<string>();
1019 }),
1020 ).pipe(
1021 Effect.timeoutOption(USER_HOME_TIMEOUT),
1022 Effect.map(Option.flatten),
1023 Effect.orElseSucceed(() => Option.none<string>()),
1024 );
1025​
1026const getUserHomeImpl = (
1027 distro: string | null,
1028): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
1029 Effect.scoped(
1030 Effect.gen(function* () {
1031 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1032 const command = ChildProcess.make(
1033 "wsl.exe",
1035 ...buildDistroArgs(distro),
1036 "--",
1037 "sh",
1038 "-c",
1039 'printf "%s" "$(getent passwd "$(id -un)" | cut -d: -f6)"',
1040 ],
1042 stdin: "ignore",
1043 stdout: "pipe",
1044 stderr: "ignore",
1045 killSignal: "SIGTERM",
1046 forceKillAfter: PROCESS_TERMINATE_GRACE,
1047 },
1048 );
1049 const handle = yield* spawner.spawn(command);
1050 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
1051 const exitCode = yield* handle.exitCode;
1052 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
1053 const home = decodeUtf8(concatChunks(stdoutBytes)).trim();
1054 return home.startsWith("/") ? Option.some(home) : Option.none<string>();
1055 }),
1056 ).pipe(
1057 Effect.timeoutOption(USER_HOME_TIMEOUT),
1058 Effect.map(Option.flatten),
1059 Effect.orElseSucceed(() => Option.none<string>()),
1060 );
1061​
1062const makeIsAvailable = (
1063 platform: NodeJS.Platform,
1064 windir: string,
1065): Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path> =>
1066 Effect.gen(function* () {
1067 if (platform !== "win32") return false;
1068 const path = yield* Path.Path;
1069 const fileSystem = yield* FileSystem.FileSystem;
1070 const wslExePath = path.join(windir, "System32", "wsl.exe");
1071 return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));
1072 });
1073​
1074export interface DesktopWslEnvironmentTestStub {
1075 readonly isAvailable?: boolean;
1076 readonly distros?: ReadonlyArray<WslDistro>;
1077 readonly distroListError?: DesktopWslDistroListError;
1078 readonly windowsToWslPath?: (distro: string | null, windowsPath: string) => Option.Option<string>;
1079 readonly getUserHome?: (distro: string | null) => Option.Option<string>;
1080 readonly getDistroIp?: (distro: string | null) => Option.Option<string>;
1081 readonly prepareRuntime?: (
1082 distro: string | null,
1083 archive: WslRuntimeArchive,
1084 ) => PrepareWslRuntimeResult;
1085 readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
1086 readonly invalidateRuntime?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
1087 readonly probeRuntime?: (distro: string | null, linuxAppRoot: string) => ProbeWslRuntimeResult;
1088 readonly ensureNodePty?: (
1089 distro: string | null,
1090 linuxAppRoot: string,
1091 options?: EnsureWslNodePtyOptions,
1092 ) => EnsureWslNodePtyResult;
1094​
1095export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
1096 const probeDistros: Effect.Effect<readonly WslDistro[], DesktopWslDistroListError> =
1097 stub.distroListError ? Effect.fail(stub.distroListError) : Effect.succeed(stub.distros ?? []);
1098 return Layer.succeed(
1099 DesktopWslEnvironment,
1100 DesktopWslEnvironment.of({
1101 isAvailable: Effect.succeed(stub.isAvailable ?? false),
1102 listDistros: probeDistros.pipe(Effect.orElseSucceed(() => [])),
1103 probeDistros,
1104 preWarm: () => Effect.void,
1105 windowsToWslPath: (distro, windowsPath) =>
1106 Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none()),
1107 getUserHome: (distro) => Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>()),
1108 getDistroIp: (distro) => Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>()),
1109 prepareRuntime: (distro, archive) =>
1110 Effect.succeed(
1111 stub.prepareRuntime?.(distro, archive) ?? {
1112 ok: false,
1113 reason: "prepareRuntime stub not configured",
1114 },
1115 ),
1116 pruneRuntimes: (distro, runtimeId) => stub.pruneRuntimes?.(distro, runtimeId) ?? Effect.void,
1117 invalidateRuntime: (distro, runtimeId) =>
1118 stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void,
1119 probeRuntime: (distro, linuxAppRoot) =>
1120 Effect.succeed(
1121 stub.probeRuntime?.(distro, linuxAppRoot) ?? { ok: true, resolvedPath: "/usr/bin:/bin" },
1122 ),
1123 ensureNodePty: (distro, linuxAppRoot, options) =>
1124 Effect.succeed(
1125 stub.ensureNodePty?.(distro, linuxAppRoot, options) ?? {
1126 ok: false,
1127 reason: "ensureNodePty stub not configured",
1128 fatal: true,
1129 },
1130 ),
1131 }),
1132 );
1134​
1135export const layer = Layer.effect(
1136 DesktopWslEnvironment,
1137 Effect.gen(function* () {
1138 const environment = yield* DesktopEnvironment.DesktopEnvironment;
1139 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1140 const fileSystem = yield* FileSystem.FileSystem;
1141 const windir = process.env.WINDIR ?? "C:\\Windows";
1142​
1143 const provideSpawner = <A, E>(
1144 effect: Effect.Effect<A, E, ChildProcessSpawner.ChildProcessSpawner>,
1145 ): Effect.Effect<A, E> =>
1146 effect.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
1147​
1148 // Crucially this keeps `isAvailable` synchronously resolvable: it's read
1149 // inside the sync IPC handler getLocalEnvironmentBootstraps (via the
1150 // primary instance's lazy label -> resolvePrimaryLabel -> describePrimary).
1151 // The underlying probe does a filesystem `exists` check, so leaving it as a
1152 // live effect would make Effect.runSync throw there and break the
1153 // renderer's synchronous bootstrap path.
1154 const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe(
1155 Effect.provideService(FileSystem.FileSystem, fileSystem),
1156 Effect.provideService(Path.Path, environment.path),
1157 Effect.withSpan("desktop.wsl.isAvailable"),
1158 );
1159 const isAvailable = Effect.succeed(wslAvailable);
1160​
1161 const windowsToWslPath = (distro: string | null, windowsPath: string) =>
1162 provideSpawner(windowsToWslPathImpl(distro, windowsPath)).pipe(
1163 Effect.withSpan("desktop.wsl.windowsToWslPath"),
1164 );
1165​
1166 const userHomeCache = new Map<string, string>();
1167 const getUserHome = Effect.fn("desktop.wsl.getUserHome")(function* (distro: string | null) {
1168 const key = distro ?? "__default__";
1169 const cached = userHomeCache.get(key);
1170 if (cached !== undefined) return Option.some(cached);
1171 const resolved = yield* provideSpawner(getUserHomeImpl(distro));
1172 if (Option.isSome(resolved)) userHomeCache.set(key, resolved.value);
1173 return resolved;
1174 });
1175​
1176 const getDistroIp = (distro: string | null) =>
1177 provideSpawner(getDistroIpImpl(distro)).pipe(Effect.withSpan("desktop.wsl.getDistroIp"));
1178​
1179 const probeDistros = provideSpawner(probeWslDistros).pipe(
1180 Effect.withSpan("desktop.wsl.probeDistros"),
1181 );
1182​
1183 return DesktopWslEnvironment.of({
1184 isAvailable,
1185 listDistros: probeDistros.pipe(
1186 Effect.orElseSucceed(() => []),
1187 Effect.withSpan("desktop.wsl.listDistros"),
1188 ),
1189 probeDistros,
1190 preWarm: (distro) =>
1191 provideSpawner(preWarmImpl(distro)).pipe(Effect.withSpan("desktop.wsl.preWarm")),
1192 windowsToWslPath,
1193 getUserHome,
1194 getDistroIp,
1195 prepareRuntime: (distro, archive) =>
1196 provideSpawner(prepareWslRuntimeImpl(distro, archive, windowsToWslPath)).pipe(
1197 Effect.withSpan("desktop.wsl.prepareRuntime"),
1198 ),
1199 pruneRuntimes: (distro, runtimeId) =>
1200 provideSpawner(pruneWslRuntimesImpl(distro, runtimeId)).pipe(
1201 Effect.withSpan("desktop.wsl.pruneRuntimes"),
1202 ),
1203 invalidateRuntime: (distro, runtimeId) =>
1204 provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId)).pipe(
1205 Effect.withSpan("desktop.wsl.invalidateRuntime"),
1206 ),
1207 probeRuntime: (distro, linuxAppRoot) =>
1208 provideSpawner(probeWslRuntimeImpl(distro, linuxAppRoot)).pipe(
1209 Effect.withSpan("desktop.wsl.probeRuntime"),
1210 ),
1211 ensureNodePty: (distro, linuxAppRoot, options) =>
1212 provideSpawner(ensureNodePtyImpl(distro, linuxAppRoot, options)).pipe(
1213 Effect.withSpan("desktop.wsl.ensureNodePty"),
1214 ),
1215 });
1216 }),