Open History to see the last commit
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/unstable/process";
11
12import { buildRemoteNodeEnvScript } from "@t3tools/ssh/tunnel";
13import { satisfiesSemverRange } from "@t3tools/shared/semver";
14
15import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
16import { parseWslDistroList, type WslDistro } from "./wslPathParsing.ts";
17
18const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
19const LIST_TIMEOUT = Duration.seconds(8);
20const PRE_WARM_TIMEOUT = Duration.seconds(10);
21const WSLPATH_TIMEOUT = Duration.seconds(10);
22const PROBE_TIMEOUT = Duration.seconds(10);
23const TOOLCHAIN_TIMEOUT = Duration.seconds(10);
24const BUILD_TIMEOUT = Duration.minutes(5);
25const USER_HOME_TIMEOUT = Duration.seconds(5);
26const TOOLCHAIN_TRANSPORT_RETRY_LIMIT = 12;
27const BUILD_TRANSPORT_RETRY_LIMIT = 2;
28
29export interface EnsureWslNodePtyOptions {
30 readonly allowBuild?: boolean;
31 readonly nodeEngineRange?: string | null;
32}
33
34export type EnsureWslNodePtyResult =
35 | { readonly ok: true; readonly nodePath: string; readonly resolvedPath: string }
36 | {
37 readonly ok: false;
38 readonly reason: string;
39 readonly fatal: boolean;
40 readonly retryLimit?: number;
41 };
42
43export class DesktopWslDistroListError extends Schema.TaggedErrorClass<DesktopWslDistroListError>()(
44 "DesktopWslDistroListError",
45 { reason: Schema.String },
46) {
47 override get message(): string {
48 return this.reason;
49 }
50}
51
52const isDesktopWslDistroListError = Schema.is(DesktopWslDistroListError);
53
54export class DesktopWslEnvironment extends Context.Service<
55 DesktopWslEnvironment,
56 {
57 readonly isAvailable: Effect.Effect<boolean>;
58 // Best-effort enumeration for renderer UX. Backend health checks must use
59 // probeDistros so a transient command failure is not mistaken for a
60 // successful empty installation.
61 readonly listDistros: Effect.Effect<readonly WslDistro[]>;
62 readonly probeDistros: Effect.Effect<readonly WslDistro[], DesktopWslDistroListError>;
63 readonly preWarm: (distro: string | null) => Effect.Effect<void>;
64 readonly windowsToWslPath: (
65 distro: string | null,
66 windowsPath: string,
67 ) => Effect.Effect<Option.Option<string>>;
68 // Resolves the user's Linux home dir inside the chosen distro (e.g.
69 // "/home/josh"). Used by the folder picker to expand `~` correctly.
70 readonly getUserHome: (distro: string | null) => Effect.Effect<Option.Option<string>>;
71 // Resolves the WSL distro's IPv4 address on the WSL vEthernet adapter
72 // (e.g. "172.x.x.x"). The orchestrator uses this for the WSL backend's
73 // httpBaseUrl so the renderer can reach it without relying on wslhost's
74 // localhost→WSL automatic forwarding, which is flaky in practice
75 // (the backend can be listening for 30+ seconds before wslhost starts
76 // forwarding 127.0.0.1:port to WSL-side localhost).
77 readonly getDistroIp: (distro: string | null) => Effect.Effect<Option.Option<string>>;
78 readonly ensureNodePty: (
79 distro: string | null,
80 windowsRepoRoot: string,
81 options?: EnsureWslNodePtyOptions,
82 ) => Effect.Effect<EnsureWslNodePtyResult>;
83 }
84>()("@t3tools/desktop/wsl/DesktopWslEnvironment") {}
85
86const buildDistroArgs = (distro: string | null): ReadonlyArray<string> =>
87 distro ? ["-d", distro] : [];
88
89const concatChunks = (arrays: ReadonlyArray<Uint8Array>): Uint8Array => {
90 let totalLength = 0;
91 for (const arr of arrays) totalLength += arr.byteLength;
92 const out = new Uint8Array(totalLength);
93 let offset = 0;
94 for (const arr of arrays) {
95 out.set(arr, offset);
96 offset += arr.byteLength;
97 }
98 return out;
99};
100
101const decodeUtf8 = (bytes: Uint8Array): string => new TextDecoder("utf-8").decode(bytes);
102
103interface ShellResult {
104 readonly exitCode: number;
105 readonly stdout: string;
106 readonly stderr: string;
107 readonly transportFailure: "timeout" | "spawn" | "process" | null;
108}
109
110const TIMEOUT_RESULT: ShellResult = {
111 exitCode: 124,
112 stdout: "",
113 stderr: "\n[timeout]",
114 transportFailure: "timeout",
115};
116
117export const formatWslShellTransportFailureReason = (
118 failure: ShellResult["transportFailure"],
119): string | null => {
120 switch (failure) {
121 case "timeout":
122 return "WSL backend preflight timed out while probing for Node.js. WSL may be slow to start; retry, or check that the distro is healthy.";
123 case "spawn":
124 return "WSL backend preflight could not start wsl.exe to probe for Node.js. Check that WSL is installed and the distro is accessible.";
125 case "process":
126 return "WSL backend preflight lost communication with wsl.exe while probing for Node.js. Retry, or check that the distro is healthy.";
127 case null:
128 return null;
129 }
130};
131
132// Reuse the SSH remote resolver so WSL and SSH discover version-managed Node
133// the same way. Passing the engine range lets the resolver fall through to
134// version managers like nvm when a system node exists but is too old.
135export const buildWslNodeEnvPreamble = (
136 nodeEngineRange?: string | null,
137): string => `${buildRemoteNodeEnvScript({ nodeEngineRange: nodeEngineRange ?? null })}
138ensure_remote_node_path || true
139`;
140
141// wsl.exe re-escapes args before forwarding them to the Linux side, which
142// mangles quotes inside `bash -lc "<script>"`. Pipe the script via stdin to
143// avoid passing it on the command line at all.
144const runWslShell = (
145 distro: string | null,
146 bashScript: string,
147 timeout: Duration.Duration,
148 options: EnsureWslNodePtyOptions = {},
149): Effect.Effect<ShellResult, never, ChildProcessSpawner.ChildProcessSpawner> => {
150 const spawner = ChildProcessSpawner.ChildProcessSpawner;
151 // -l picks up profile-managed PATH; the shared resolver covers supported
152 // version managers that non-interactive login shells can miss. -s so bash
153 // reads the script from stdin.
154 const command = ChildProcess.make(
155 "wsl.exe",
156 [...buildDistroArgs(distro), "--", "bash", "-l", "-s"],
157 {
158 stdin: Stream.encodeText(
159 Stream.make(`${buildWslNodeEnvPreamble(options.nodeEngineRange)}${bashScript}`),
160 ),
161 stdout: "pipe",
162 stderr: "pipe",
163 killSignal: "SIGTERM",
164 forceKillAfter: PROCESS_TERMINATE_GRACE,
165 },
166 );
167
168 return Effect.scoped(
169 Effect.gen(function* () {
170 const spawnerService = yield* spawner;
171 const spawnResult = yield* spawnerService.spawn(command).pipe(
172 Effect.match({
173 onFailure: (error) => ({ _tag: "Failure", error }) as const,
174 onSuccess: (handle) => ({ _tag: "Success", handle }) as const,
175 }),
176 );
177 if (spawnResult._tag === "Failure") {
178 return {
179 exitCode: 127,
180 stdout: "",
181 stderr: `\n${spawnResult.error.message}`,
182 transportFailure: "spawn",
183 } satisfies ShellResult;
184 }
185 const handle = spawnResult.handle;
186 // Drain stdout and stderr concurrently so neither pipe buffer can fill
187 // and stall the child (node-gyp rebuild emits large output on both).
188 const [stdoutBytes, stderrBytes, exitCode] = yield* Effect.all(
189 [Stream.runCollect(handle.stdout), Stream.runCollect(handle.stderr), handle.exitCode],
190 { concurrency: "unbounded" },
191 );
192 return {
193 exitCode: exitCode as unknown as number,
194 stdout: decodeUtf8(concatChunks(stdoutBytes)),
195 stderr: decodeUtf8(concatChunks(stderrBytes)),
196 transportFailure: null,
197 } satisfies ShellResult;
198 }),
199 ).pipe(
200 Effect.timeoutOption(timeout),
201 Effect.map(Option.getOrElse((): ShellResult => TIMEOUT_RESULT)),
202 Effect.catch((error) =>
203 Effect.succeed<ShellResult>({
204 exitCode: 127,
205 stdout: "",
206 stderr: `\n${error.message}`,
207 transportFailure: "process",
208 }),
209 ),
210 );
211};
212
213const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
214
215const NODE_PTY_PREBUILD_MISSING_EXIT_CODE = 4;
216
217export const formatNodePtyProbeFailureReason = (exitCode: number): string | null =>
218 exitCode === NODE_PTY_PREBUILD_MISSING_EXIT_CODE
219 ? "WSL support is missing from this T3 Code build: the packaged Linux node-pty binary was not included. Rebuild the Windows artifact with `--wsl-prebuild <path-to-linux-pty.node>` or install a build that includes WSL support."
220 : null;
221
222const NODE_PTY_PROBE_SCRIPT = (
223 linuxServerDir: string,
224) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"
225printf 'resolvedPath:%s\\n' "$PATH"
226cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
227// The server bundle externalizes its deps to node_modules, and the WSL Node
228// can't read inside app.asar, so confirm those deps are unpacked on the real
229// filesystem before reporting the backend healthy. "effect" is the framework
230// every server module imports; resolving it validates the whole node_modules
231// tree. Exit 3 marks this distinct from a node-pty problem so the caller can
232// report it accurately instead of letting the server crash on
233// ERR_MODULE_NOT_FOUND at launch (which, in wsl-only mode, would just fail to
234// launch with no fallback).
235try { require.resolve("effect"); } catch (_e) { process.exit(3); }
236const fs = require("node:fs");
237const path = require("node:path");
238const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
239// node-pty 1.x is N-API based, so a single Linux pty.node is ABI-stable across
240// Node versions — require() succeeding IS the real compatibility test. Compare
241// only arch and node-pty version (a stale binary from a different node-pty),
242// NOT process.versions.modules: that would reject a perfectly loadable prebuilt
243// whenever the user's WSL Node ABI differs from the build's, defeating the
244// whole point of shipping one prebuilt for all Node versions.
245const expected = {
246 arch: process.arch,
247 nodePtyVersion: require("node-pty/package.json").version,
248};
249const prebuildDir = path.join(pkgDir, "prebuilds", "linux-" + process.arch);
250const marker = path.join(prebuildDir, "t3code-wsl-node-pty.json");
251const binary = path.join(prebuildDir, "pty.node");
252if (!fs.existsSync(marker) || !fs.existsSync(binary)) process.exit(${NODE_PTY_PREBUILD_MISSING_EXIT_CODE});
253require("node-pty");
254const actual = JSON.parse(fs.readFileSync(marker, "utf8"));
255for (const key of Object.keys(expected)) {
256 if (actual[key] !== expected[key]) process.exit(2);
257}
258NODE`;
259
260const TOOLCHAIN_CHECK_SCRIPT = [
261 "for tool in node make g++ python3; do",
262 ' command -v "$tool" >/dev/null 2>&1 || echo "missing:$tool"',
263 "done",
264 "if command -v node >/dev/null 2>&1; then",
265 ` ver="$(node -p 'process.versions.node' 2>/dev/null)"`,
266 ' if [ -n "$ver" ]; then printf "nodeVersion:%s\\n" "$ver"; fi',
267 "fi",
268].join("\n");
269
270const NODE_PTY_BUILD_SCRIPT = (linuxServerDir: string) =>
271 [
272 "set -e",
273 `cd ${shellQuote(linuxServerDir)}`,
274 `pkg_dir=$(node -p "require('node:path').dirname(require.resolve('node-pty/package.json'))")`,
275 `arch=$(node -p "process.arch")`,
276 `modules=$(node -p "process.versions.modules")`,
277 `node_pty_version=$(node -p "require('node-pty/package.json').version")`,
278 `cd "$pkg_dir"`,
279 "npx --yes node-gyp rebuild",
280 `prebuild_dir="prebuilds/linux-$arch"`,
281 `mkdir -p "$prebuild_dir"`,
282 `cp build/Release/pty.node "$prebuild_dir/pty.node"`,
283 `printf '{"arch":"%s","modules":"%s","nodePtyVersion":"%s"}\\n' "$arch" "$modules" "$node_pty_version" > "$prebuild_dir/t3code-wsl-node-pty.json"`,
284 `node -e 'require("node-pty")'`,
285 ].join("\n");
286
287export interface ToolchainReport {
288 readonly missingTools: ReadonlyArray<string>;
289 readonly nodeVersion: string | null;
290}
291
292export const parseToolchainReport = (stdout: string): ToolchainReport => {
293 const lines = stdout
294 .split("\n")
295 .map((line) => line.trim())
296 .filter((line) => line.length > 0);
297 const missingTools = lines
298 .filter((line) => line.startsWith("missing:"))
299 .map((line) => line.slice("missing:".length));
300 const nodeVersionLine = lines.find((line) => line.startsWith("nodeVersion:"));
301 const nodeVersion = nodeVersionLine
302 ? nodeVersionLine.slice("nodeVersion:".length).trim() || null
303 : null;
304 return { missingTools, nodeVersion };
305};
306
307// Pulls the absolute node path the WSL distro resolved after the shared remote
308// resolver repaired PATH. Returns null when no node was found, which the caller
309// turns into an actionable "install Node" message instead of a confusing
310// node-pty error.
311export const parseNodePath = (stdout: string): string | null => {
312 const path = stdout
313 .split("\n")
314 .map((line) => line.trim())
315 .filter((line) => line.startsWith("nodePath:"))
316 .map((line) => line.slice("nodePath:".length).trim())
317 .find((value) => value.length > 0);
318 return path ?? null;
319};
320
321// Captures the login-shell PATH after the shared resolver has loaded version
322// managers. Preserve the value byte-for-byte apart from a Windows-style CR so
323// paths containing spaces or apostrophes can be forwarded as one env argv.
324export const parseResolvedPath = (stdout: string): string | null => {
325 const prefix = "resolvedPath:";
326 const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));
327 if (line === undefined) return null;
328 const resolvedPath = line.slice(prefix.length).replace(/\r$/, "");
329 return resolvedPath.length > 0 ? resolvedPath : null;
330};
331
332export const formatMissingToolsReason = (
333 report: ToolchainReport,
334 requiredRange: string | null,
335): string | null => {
336 const nodeMissing = report.missingTools.includes("node");
337 const nodeOutOfRange =
338 !nodeMissing &&
339 requiredRange !== null &&
340 report.nodeVersion !== null &&
341 !satisfiesSemverRange(report.nodeVersion, requiredRange);
342 const buildToolsMissing = report.missingTools.filter((tool) => tool !== "node");
343
344 if (!nodeMissing && !nodeOutOfRange && buildToolsMissing.length === 0) {
345 return null;
346 }
347
348 const issues: string[] = [];
349 const remediations: string[] = [];
350
351 if (nodeMissing) {
352 issues.push("node");
353 remediations.push(
354 `Node.js${requiredRange ? ` satisfying \`${requiredRange}\`` : " 18+"} (e.g. via nvm)`,
355 );
356 } else if (nodeOutOfRange) {
357 issues.push(`node ${report.nodeVersion} (requires ${requiredRange})`);
358 remediations.push(
359 `a newer Node.js satisfying \`${requiredRange}\` (e.g. \`nvm install 24 && nvm alias default 24\`)`,
360 );
361 }
362
363 if (buildToolsMissing.length > 0) {
364 issues.push(...buildToolsMissing);
365 remediations.push(
366 "the build toolchain (e.g. `sudo apt install -y build-essential python3` on Ubuntu/Debian)",
367 );
368 }
369
370 return `WSL distro is missing required tools: ${issues.join(", ")}. Install ${remediations.join(" and ")}, then retry.`;
371};
372
373const ensureNodePtyImpl = (
374 distro: string | null,
375 windowsRepoRoot: string,
376 windowsToWslPath: (
377 distro: string | null,
378 windowsPath: string,
379 ) => Effect.Effect<Option.Option<string>>,
380 options: EnsureWslNodePtyOptions = {},
381): Effect.Effect<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> =>
382 Effect.gen(function* () {
383 const linuxRepoRootOption = yield* windowsToWslPath(distro, windowsRepoRoot);
384 if (Option.isNone(linuxRepoRootOption)) {
385 return {
386 ok: false,
387 reason: `wslpath conversion failed for ${windowsRepoRoot}`,
388 fatal: false,
389 } as const;
390 }
391 const linuxRepoRoot = linuxRepoRootOption.value;
392 // node-pty lives in the apps/server workspace's node_modules; resolve from
393 // there rather than the monorepo root, where Bun's hoist layout omits it.
394 const linuxServerDir = `${linuxRepoRoot}/apps/server`;
395
396 const probe = yield* runWslShell(
397 distro,
398 NODE_PTY_PROBE_SCRIPT(linuxServerDir),
399 PROBE_TIMEOUT,
400 options,
401 );
402 const nodePath = parseNodePath(probe.stdout);
403 const resolvedPath = parseResolvedPath(probe.stdout);
404
405 const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
406 if (transportFailureReason !== null) {
407 return { ok: false, reason: transportFailureReason, fatal: false } as const;
408 }
409
410 // No node at all, even after the shared resolver repaired PATH. Surface
411 // the specific, actionable toolchain message rather than a confusing
412 // node-pty error, and don't try to build.
413 if (nodePath === null) {
414 const toolchainCheck = yield* runWslShell(
415 distro,
416 TOOLCHAIN_CHECK_SCRIPT,
417 TOOLCHAIN_TIMEOUT,
418 options,
419 );
420 const toolchainTransportFailure = formatWslShellTransportFailureReason(
421 toolchainCheck.transportFailure,
422 );
423 if (toolchainTransportFailure !== null) {
424 return {
425 ok: false,
426 reason: toolchainTransportFailure,
427 fatal: false,
428 retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
429 } as const;
430 }
431 const report = parseToolchainReport(toolchainCheck.stdout);
432 const reason =
433 formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null) ??
434 "Node.js was not found in the WSL distro. Install it (e.g. via nvm) and restart the desktop app.";
435 return { ok: false, reason, fatal: true } as const;
436 }
437
438 if (resolvedPath === null) {
439 return {
440 ok: false,
441 reason: "WSL login-shell PATH could not be resolved during backend preflight.",
442 fatal: true,
443 } as const;
444 }
445
446 // Server dependencies (e.g. "effect") couldn't be resolved on the WSL
447 // filesystem — a packaging regression, since the server bundle needs its
448 // node_modules unpacked from the asar. Fatal so wsl-only mode falls back to
449 // Windows and dual mode surfaces the reason inline, instead of the server
450 // crash-looping on ERR_MODULE_NOT_FOUND once it actually launches.
451 if (probe.exitCode === 3) {
452 return {
453 ok: false,
454 reason:
455 "WSL server dependencies could not be loaded (for example \"effect\"). The server's bundled node_modules is not readable by the WSL distro's Node — this is a packaging problem with this build. Please report it.",
456 fatal: true,
457 } as const;
458 }
459
460 if (probe.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
461
462 if (options.allowBuild !== true) {
463 const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
464 if (packagedProbeFailure !== null) {
465 return { ok: false, reason: packagedProbeFailure, fatal: true } as const;
466 }
467 }
468
469 // node is present but node-pty's native module didn't load.
470 const toolchainCheck = yield* runWslShell(
471 distro,
472 TOOLCHAIN_CHECK_SCRIPT,
473 TOOLCHAIN_TIMEOUT,
474 options,
475 );
476 const toolchainTransportFailure = formatWslShellTransportFailureReason(
477 toolchainCheck.transportFailure,
478 );
479 if (toolchainTransportFailure !== null) {
480 return {
481 ok: false,
482 reason: toolchainTransportFailure,
483 fatal: false,
484 retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
485 } as const;
486 }
487 const report = parseToolchainReport(toolchainCheck.stdout);
488
489 if (options.allowBuild !== true) {
490 // Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp,
491 // or network is needed — and we must not nag the user to install build
492 // tools they don't need. Still surface a missing/too-old Node (both the
493 // prebuilt and the server require a compatible Node); otherwise reaching
494 // here means the bundled binary itself couldn't load, which is almost
495 // always an unsupported CPU architecture or incompatible system libraries.
496 const nodeOnlyReason = formatMissingToolsReason(
497 {
498 missingTools: report.missingTools.filter((tool) => tool === "node"),
499 nodeVersion: report.nodeVersion,
500 },
501 options.nodeEngineRange?.trim() || null,
502 );
503 return {
504 ok: false,
505 reason:
506 nodeOnlyReason ??
507 "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`.",
508 fatal: true,
509 } as const;
510 }
511
512 // Dev only: no prebuilt is bundled in a checkout, so compile node-pty from
513 // source. Run the toolchain check first so a missing compiler or out-of-range
514 // Node surfaces a specific, actionable message instead of an opaque node-gyp
515 // failure. Developers have the toolchain; end users never reach this path.
516 const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);
517 if (missingReason !== null) {
518 return { ok: false, reason: missingReason, fatal: true } as const;
519 }
520
521 const build = yield* runWslShell(
522 distro,
523 NODE_PTY_BUILD_SCRIPT(linuxServerDir),
524 BUILD_TIMEOUT,
525 options,
526 );
527 const buildTransportFailure = formatWslShellTransportFailureReason(build.transportFailure);
528 if (buildTransportFailure !== null) {
529 return {
530 ok: false,
531 reason: buildTransportFailure,
532 fatal: false,
533 retryLimit: BUILD_TRANSPORT_RETRY_LIMIT,
534 } as const;
535 }
536 if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
537 const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500);
538 return {
539 ok: false,
540 reason: `node-pty Linux build failed (exit ${build.exitCode}): ${trimmedTail || "no stderr captured"}`,
541 fatal: true,
542 } as const;
543 });
544
545export const probeWslDistros: Effect.Effect<
546 readonly WslDistro[],
547 DesktopWslDistroListError,
548 ChildProcessSpawner.ChildProcessSpawner
549> = Effect.scoped(
550 Effect.gen(function* () {
551 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
552 const command = ChildProcess.make("wsl.exe", ["--list", "--verbose"], {
553 stdin: "ignore",
554 stdout: "pipe",
555 stderr: "ignore",
556 killSignal: "SIGTERM",
557 forceKillAfter: PROCESS_TERMINATE_GRACE,
558 });
559 const handle = yield* spawner.spawn(command);
560 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
561 const exitCode = yield* handle.exitCode;
562 if ((exitCode as unknown as number) !== 0) {
563 return yield* new DesktopWslDistroListError({
564 reason: `wsl.exe --list --verbose exited with code ${String(exitCode)}`,
565 });
566 }
567 return parseWslDistroList(Buffer.from(concatChunks(stdoutBytes)));
568 }),
569).pipe(
570 Effect.mapError((error) =>
571 isDesktopWslDistroListError(error)
572 ? error
573 : new DesktopWslDistroListError({
574 reason: `Failed to run wsl.exe --list --verbose: ${error.message}`,
575 }),
576 ),
577 Effect.timeoutOption(LIST_TIMEOUT),
578 Effect.flatMap(
579 Option.match({
580 onNone: () =>
581 new DesktopWslDistroListError({
582 reason: "wsl.exe --list --verbose timed out",
583 }),
584 onSome: Effect.succeed,
585 }),
586 ),
587);
588
589const preWarmImpl = (
590 distro: string | null,
591): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> =>
592 Effect.scoped(
593 Effect.gen(function* () {
594 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
595 const command = ChildProcess.make("wsl.exe", [...buildDistroArgs(distro), "--", "true"], {
596 stdin: "ignore",
597 stdout: "ignore",
598 stderr: "ignore",
599 killSignal: "SIGTERM",
600 forceKillAfter: PROCESS_TERMINATE_GRACE,
601 });
602 const handle = yield* spawner.spawn(command);
603 yield* handle.exitCode;
604 }),
605 ).pipe(
606 Effect.timeoutOption(PRE_WARM_TIMEOUT),
607 Effect.asVoid,
608 Effect.catch(() => Effect.void),
609 );
610
611const windowsToWslPathImpl = (
612 distro: string | null,
613 windowsPath: string,
614): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> => {
615 // wsl.exe interprets backslashes as escape chars; normalize to forward slashes.
616 const normalized = windowsPath.replaceAll("\\", "/");
617 return Effect.scoped(
618 Effect.gen(function* () {
619 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
620 const command = ChildProcess.make(
621 "wsl.exe",
622 [...buildDistroArgs(distro), "--", "wslpath", "-u", normalized],
623 {
624 stdin: "ignore",
625 stdout: "pipe",
626 stderr: "ignore",
627 killSignal: "SIGTERM",
628 forceKillAfter: PROCESS_TERMINATE_GRACE,
629 },
630 );
631 const handle = yield* spawner.spawn(command);
632 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
633 const exitCode = yield* handle.exitCode;
634 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
635 const converted = decodeUtf8(concatChunks(stdoutBytes)).trim();
636 return converted.length > 0 ? Option.some(converted) : Option.none<string>();
637 }),
638 ).pipe(
639 Effect.timeoutOption(WSLPATH_TIMEOUT),
640 Effect.map(Option.flatten),
641 Effect.orElseSucceed(() => Option.none<string>()),
642 );
643};
644
645const IPV4_PATTERN = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
646
647const getDistroIpImpl = (
648 distro: string | null,
649): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
650 Effect.scoped(
651 Effect.gen(function* () {
652 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
653 // `hostname -I` prints a space-separated list of all non-loopback
654 // IPs the distro has bound. The first entry on the WSL2 default
655 // network is always the eth0 vEthernet address Windows can reach
656 // directly (no wslhost forwarding required).
657 const command = ChildProcess.make(
658 "wsl.exe",
659 [...buildDistroArgs(distro), "--", "sh", "-c", "hostname -I"],
660 {
661 stdin: "ignore",
662 stdout: "pipe",
663 stderr: "ignore",
664 killSignal: "SIGTERM",
665 forceKillAfter: PROCESS_TERMINATE_GRACE,
666 },
667 );
668 const handle = yield* spawner.spawn(command);
669 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
670 const exitCode = yield* handle.exitCode;
671 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
672 const raw = decodeUtf8(concatChunks(stdoutBytes)).trim();
673 const candidate = raw.split(/\s+/).find((part) => IPV4_PATTERN.test(part));
674 return candidate ? Option.some(candidate) : Option.none<string>();
675 }),
676 ).pipe(
677 Effect.timeoutOption(USER_HOME_TIMEOUT),
678 Effect.map(Option.flatten),
679 Effect.orElseSucceed(() => Option.none<string>()),
680 );
681
682const getUserHomeImpl = (
683 distro: string | null,
684): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
685 Effect.scoped(
686 Effect.gen(function* () {
687 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
688 const command = ChildProcess.make(
689 "wsl.exe",
690 // printf so there's no trailing newline noise; getent so we get the
691 // real home from /etc/passwd even if $HOME is unset for some reason.
692 [
693 ...buildDistroArgs(distro),
694 "--",
695 "sh",
696 "-c",
697 'printf "%s" "$(getent passwd "$(id -un)" | cut -d: -f6)"',
698 ],
699 {
700 stdin: "ignore",
701 stdout: "pipe",
702 stderr: "ignore",
703 killSignal: "SIGTERM",
704 forceKillAfter: PROCESS_TERMINATE_GRACE,
705 },
706 );
707 const handle = yield* spawner.spawn(command);
708 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
709 const exitCode = yield* handle.exitCode;
710 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
711 const home = decodeUtf8(concatChunks(stdoutBytes)).trim();
712 return home.startsWith("/") ? Option.some(home) : Option.none<string>();
713 }),
714 ).pipe(
715 Effect.timeoutOption(USER_HOME_TIMEOUT),
716 Effect.map(Option.flatten),
717 Effect.orElseSucceed(() => Option.none<string>()),
718 );
719
720const makeIsAvailable = (
721 platform: NodeJS.Platform,
722 windir: string,
723): Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path> =>
724 Effect.gen(function* () {
725 if (platform !== "win32") return false;
726 const path = yield* Path.Path;
727 const fileSystem = yield* FileSystem.FileSystem;
728 const wslExePath = path.join(windir, "System32", "wsl.exe");
729 return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));
730 });
731
732export interface DesktopWslEnvironmentTestStub {
733 readonly isAvailable?: boolean;
734 readonly distros?: ReadonlyArray<WslDistro>;
735 readonly distroListError?: DesktopWslDistroListError;
736 readonly windowsToWslPath?: (distro: string | null, windowsPath: string) => Option.Option<string>;
737 readonly getUserHome?: (distro: string | null) => Option.Option<string>;
738 readonly getDistroIp?: (distro: string | null) => Option.Option<string>;
739 readonly ensureNodePty?: (
740 distro: string | null,
741 windowsRepoRoot: string,
742 options?: EnsureWslNodePtyOptions,
743 ) => EnsureWslNodePtyResult;
744}
745
746export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
747 const probeDistros = stub.distroListError
748 ? Effect.fail(stub.distroListError)
749 : Effect.succeed(stub.distros ?? []);
750 return Layer.succeed(
751 DesktopWslEnvironment,
752 DesktopWslEnvironment.of({
753 isAvailable: Effect.succeed(stub.isAvailable ?? false),
754 listDistros: probeDistros.pipe(Effect.orElseSucceed(() => [])),
755 probeDistros,
756 preWarm: () => Effect.void,
757 windowsToWslPath: (distro, windowsPath) =>
758 Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none()),
759 getUserHome: (distro) => Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>()),
760 getDistroIp: (distro) => Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>()),
761 ensureNodePty: (distro, windowsRepoRoot, options) =>
762 Effect.succeed(
763 stub.ensureNodePty?.(distro, windowsRepoRoot, options) ?? {
764 ok: false,
765 reason: "ensureNodePty stub not configured",
766 fatal: true,
767 },
768 ),
769 }),
770 );
771};
772
773export const layer = Layer.effect(
774 DesktopWslEnvironment,
775 Effect.gen(function* () {
776 const environment = yield* DesktopEnvironment.DesktopEnvironment;
777 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
778 const fileSystem = yield* FileSystem.FileSystem;
779 const windir = process.env.WINDIR ?? "C:\\Windows";
780
781 const provideSpawner = <A, E>(
782 effect: Effect.Effect<A, E, ChildProcessSpawner.ChildProcessSpawner>,
783 ): Effect.Effect<A, E> =>
784 effect.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
785
786 // Probe wsl.exe once at layer init and cache the result, exposing
787 // `isAvailable` as a resolved value rather than a re-running effect.
788 // WSL availability is effectively static for the process lifetime — the
789 // Windows feature isn't added/removed mid-session, and backend mode
790 // changes already require an app restart — so the cached boolean stays
791 // accurate. Crucially this keeps `isAvailable` synchronously resolvable:
792 // it's read inside the sync IPC handler getLocalEnvironmentBootstraps
793 // (via the primary instance's lazy label -> resolvePrimaryLabel ->
794 // describePrimary). The underlying probe does a filesystem `exists`
795 // check, so leaving it as a live effect would make Effect.runSync throw
796 // there and break the renderer's synchronous bootstrap path.
797 const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe(
798 Effect.provideService(FileSystem.FileSystem, fileSystem),
799 Effect.provideService(Path.Path, environment.path),
800 Effect.withSpan("desktop.wsl.isAvailable"),
801 );
802 const isAvailable = Effect.succeed(wslAvailable);
803
804 const windowsToWslPath = (distro: string | null, windowsPath: string) =>
805 provideSpawner(windowsToWslPathImpl(distro, windowsPath)).pipe(
806 Effect.withSpan("desktop.wsl.windowsToWslPath"),
807 );
808
809 // Cache user-home results per distro key — folder picker can be opened
810 // many times in a session and the value is stable for the life of the
811 // distro. Negative results aren't cached so a transient wsl.exe failure
812 // doesn't permanently disable tilde expansion.
813 const userHomeCache = new Map<string, string>();
814 const getUserHome = (distro: string | null) =>
815 Effect.gen(function* () {
816 const key = distro ?? "__default__";
817 const cached = userHomeCache.get(key);
818 if (cached !== undefined) return Option.some(cached);
819 const resolved = yield* provideSpawner(getUserHomeImpl(distro));
820 if (Option.isSome(resolved)) userHomeCache.set(key, resolved.value);
821 return resolved;
822 }).pipe(Effect.withSpan("desktop.wsl.getUserHome"));
823
824 const getDistroIp = (distro: string | null) =>
825 provideSpawner(getDistroIpImpl(distro)).pipe(Effect.withSpan("desktop.wsl.getDistroIp"));
826
827 const probeDistros = provideSpawner(probeWslDistros).pipe(
828 Effect.withSpan("desktop.wsl.probeDistros"),
829 );
830
831 return DesktopWslEnvironment.of({
832 isAvailable,
833 listDistros: probeDistros.pipe(
834 Effect.orElseSucceed(() => []),
835 Effect.withSpan("desktop.wsl.listDistros"),
836 ),
837 probeDistros,
838 preWarm: (distro) =>
839 provideSpawner(preWarmImpl(distro)).pipe(Effect.withSpan("desktop.wsl.preWarm")),
840 windowsToWslPath,
841 getUserHome,
842 getDistroIp,
843 ensureNodePty: (distro, windowsRepoRoot, options) =>
844 provideSpawner(ensureNodePtyImpl(distro, windowsRepoRoot, windowsToWslPath, options)).pipe(
845 Effect.withSpan("desktop.wsl.ensureNodePty"),
846 ),
847 });
848 }),
849);