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

DesktopWslEnvironment.ts

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