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

DesktopWslEnvironment.ts

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