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