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

DesktopWslEnvironment.ts

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