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

DesktopWslEnvironment.ts

887 lines34.3 KB

1import * as Context from "effect/Context";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Path from "effect/Path";
8import * as Schema from "effect/Schema";
9import * as Stream from "effect/Stream";
10import { ChildProcess, ChildProcessSpawner } from "effect/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;
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 }
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;
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 server bundle externalizes its deps to node_modules, and the WSL Node
233// can't read inside app.asar, so confirm those deps are unpacked on the real
234// filesystem before reporting the backend healthy. "effect" is the framework
235// every server module imports; resolving it validates the whole node_modules
236// tree. Exit 3 marks this distinct from a node-pty problem so the caller can
237// report it accurately instead of letting the server crash on
238// ERR_MODULE_NOT_FOUND at launch (which, in wsl-only mode, would just fail to
239// launch with no fallback).
240try { require.resolve("effect"); } catch (_e) { process.exit(3); }
241const fs = require("node:fs");
242const path = require("node:path");
243const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
244// node-pty 1.x is N-API based, so a single Linux pty.node is ABI-stable across
245// Node versions — require() succeeding IS the real compatibility test. Compare
246// only arch and node-pty version (a stale binary from a different node-pty),
247// NOT process.versions.modules: that would reject a perfectly loadable prebuilt
248// whenever the user's WSL Node ABI differs from the build's, defeating the
249// whole point of shipping one prebuilt for all Node versions.
250const expected = {
251 arch: process.arch,
252 nodePtyVersion: require("node-pty/package.json").version,
253};
254const prebuildDir = path.join(pkgDir, "prebuilds", "linux-" + process.arch);
255const marker = path.join(prebuildDir, "t3code-wsl-node-pty.json");
256const binary = path.join(prebuildDir, "pty.node");
257if (!fs.existsSync(marker) || !fs.existsSync(binary)) process.exit(${NODE_PTY_PREBUILD_MISSING_EXIT_CODE});
258require("node-pty");
259const actual = JSON.parse(fs.readFileSync(marker, "utf8"));
260for (const key of Object.keys(expected)) {
261 if (actual[key] !== expected[key]) process.exit(2);
263NODE`;
264​
265const TOOLCHAIN_CHECK_SCRIPT = [
266 "for tool in node make g++ python3; do",
267 ' command -v "$tool" >/dev/null 2>&1 || echo "missing:$tool"',
268 "done",
269 "if command -v node >/dev/null 2>&1; then",
270 ` ver="$(node -p 'process.versions.node' 2>/dev/null)"`,
271 ' if [ -n "$ver" ]; then printf "nodeVersion:%s\\n" "$ver"; fi',
272 "fi",
273].join("\n");
274​
275const NODE_PTY_BUILD_SCRIPT = (linuxServerDir: string) =>
276 [
277 "set -e",
278 `cd ${shellQuote(linuxServerDir)}`,
279 `pkg_dir=$(node -p "require('node:path').dirname(require.resolve('node-pty/package.json'))")`,
280 `arch=$(node -p "process.arch")`,
281 `modules=$(node -p "process.versions.modules")`,
282 `node_pty_version=$(node -p "require('node-pty/package.json').version")`,
283 `cd "$pkg_dir"`,
284 "npx --yes node-gyp rebuild",
285 `prebuild_dir="prebuilds/linux-$arch"`,
286 `mkdir -p "$prebuild_dir"`,
287 `cp build/Release/pty.node "$prebuild_dir/pty.node"`,
288 `printf '{"arch":"%s","modules":"%s","nodePtyVersion":"%s"}\\n' "$arch" "$modules" "$node_pty_version" > "$prebuild_dir/t3code-wsl-node-pty.json"`,
289 `node -e 'require("node-pty")'`,
290 ].join("\n");
291​
292export interface ToolchainReport {
293 readonly missingTools: ReadonlyArray<string>;
294 readonly nodeVersion: string | null;
296​
297export const parseToolchainReport = (stdout: string): ToolchainReport => {
298 const lines = stdout
299 .split("\n")
300 .map((line) => line.trim())
301 .filter((line) => line.length > 0);
302 const missingTools = lines
303 .filter((line) => line.startsWith("missing:"))
304 .map((line) => line.slice("missing:".length));
305 const nodeVersionLine = lines.find((line) => line.startsWith("nodeVersion:"));
306 const nodeVersion = nodeVersionLine
307 ? nodeVersionLine.slice("nodeVersion:".length).trim() || null
308 : null;
309 return { missingTools, nodeVersion };
310};
311​
312// Pulls the absolute node path the WSL distro resolved after the shared remote
313// resolver repaired PATH. Returns null when no node was found, which the caller
314// turns into an actionable "install Node" message instead of a confusing
315// node-pty error.
316export const parseNodePath = (stdout: string): string | null => {
317 const path = stdout
318 .split("\n")
319 .map((line) => line.trim())
320 .filter((line) => line.startsWith("nodePath:"))
321 .map((line) => line.slice("nodePath:".length).trim())
322 .find((value) => value.length > 0);
323 return path ?? null;
324};
325​
326export const parseNodeVersion = (stdout: string): string | null => {
327 const version = stdout
328 .split("\n")
329 .map((line) => line.trim())
330 .filter((line) => line.startsWith("nodeVersion:"))
331 .map((line) => line.slice("nodeVersion:".length).trim())
332 .find((value) => value.length > 0);
333 return version ?? null;
334};
335​
336// Captures the login-shell PATH after the shared resolver has loaded version
337// managers. Preserve the value byte-for-byte apart from a Windows-style CR so
338// paths containing spaces or apostrophes can be forwarded as one env argv.
339export const parseResolvedPath = (stdout: string): string | null => {
340 const prefix = "resolvedPath:";
341 const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));
342 if (line === undefined) return null;
343 const resolvedPath = line.slice(prefix.length).replace(/\r$/, "");
344 return resolvedPath.length > 0 ? resolvedPath : null;
345};
346​
347export const formatMissingToolsReason = (
348 report: ToolchainReport,
349 requiredRange: string | null,
350): string | null => {
351 const nodeMissing = report.missingTools.includes("node");
352 const nodeOutOfRange =
353 !nodeMissing &&
354 requiredRange !== null &&
355 report.nodeVersion !== null &&
356 !satisfiesSemverRange(report.nodeVersion, requiredRange);
357 const buildToolsMissing = report.missingTools.filter((tool) => tool !== "node");
358​
359 if (!nodeMissing && !nodeOutOfRange && buildToolsMissing.length === 0) {
360 return null;
361 }
362​
363 const issues: string[] = [];
364 const remediations: string[] = [];
365​
366 if (nodeMissing) {
367 issues.push("node");
368 remediations.push(
369 `Node.js${requiredRange ? ` satisfying \`${requiredRange}\`` : " 18+"} (e.g. via nvm)`,
370 );
371 } else if (nodeOutOfRange) {
372 issues.push(`node ${report.nodeVersion} (requires ${requiredRange})`);
373 remediations.push(
374 `a newer Node.js satisfying \`${requiredRange}\` (e.g. \`nvm install 24 && nvm alias default 24\`)`,
375 );
376 }
377​
378 if (buildToolsMissing.length > 0) {
379 issues.push(...buildToolsMissing);
380 remediations.push(
381 "the build toolchain (e.g. `sudo apt install -y build-essential python3` on Ubuntu/Debian)",
382 );
383 }
384​
385 return `WSL distro is missing required tools: ${issues.join(", ")}. Install ${remediations.join(" and ")}, then retry.`;
386};
387​
388const ensureNodePtyImpl = (
389 distro: string | null,
390 windowsRepoRoot: string,
391 windowsToWslPath: (
392 distro: string | null,
393 windowsPath: string,
394 ) => Effect.Effect<Option.Option<string>>,
395 options: EnsureWslNodePtyOptions = {},
396): Effect.Effect<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> =>
397 Effect.gen(function* () {
398 const linuxRepoRootOption = yield* windowsToWslPath(distro, windowsRepoRoot);
399 if (Option.isNone(linuxRepoRootOption)) {
400 return {
401 ok: false,
402 reason: `wslpath conversion failed for ${windowsRepoRoot}`,
403 fatal: false,
404 } as const;
405 }
406 const linuxRepoRoot = linuxRepoRootOption.value;
407 // node-pty lives in the apps/server workspace's node_modules; resolve from
408 // there rather than the monorepo root, where Bun's hoist layout omits it.
409 const linuxServerDir = `${linuxRepoRoot}/apps/server`;
410​
411 const probe = yield* runWslShell(
412 distro,
413 NODE_PTY_PROBE_SCRIPT(linuxServerDir),
414 PROBE_TIMEOUT,
415 options,
416 );
417 const nodePath = parseNodePath(probe.stdout);
418 const resolvedPath = parseResolvedPath(probe.stdout);
419​
420 const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
421 if (transportFailureReason !== null) {
422 return {
423 ok: false,
424 reason: transportFailureReason,
425 fatal: false,
426 } as const;
427 }
428​
429 // No node at all, even after the shared resolver repaired PATH. Surface
430 // the specific, actionable toolchain message rather than a confusing
431 // node-pty error, and don't try to build.
432 if (nodePath === null) {
433 const toolchainCheck = yield* runWslShell(
434 distro,
435 TOOLCHAIN_CHECK_SCRIPT,
436 TOOLCHAIN_TIMEOUT,
437 options,
438 );
439 const toolchainTransportFailure = formatWslShellTransportFailureReason(
440 toolchainCheck.transportFailure,
441 );
442 if (toolchainTransportFailure !== null) {
443 return {
444 ok: false,
445 reason: toolchainTransportFailure,
446 fatal: false,
447 retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
448 } as const;
449 }
450 const report = parseToolchainReport(toolchainCheck.stdout);
451 const reason =
452 formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null) ??
453 "Node.js was not found in the WSL distro. Install it (e.g. via nvm) and restart the desktop app.";
454 return { ok: false, reason, fatal: true } as const;
455 }
456​
457 if (resolvedPath === null) {
458 return {
459 ok: false,
460 reason: "WSL login-shell PATH could not be resolved during backend preflight.",
461 fatal: true,
462 } as const;
463 }
464​
465 // Server dependencies (e.g. "effect") couldn't be resolved on the WSL
466 // filesystem — a packaging regression, since the server bundle needs its
467 // node_modules unpacked from the asar. Fatal so wsl-only mode falls back to
468 // Windows and dual mode surfaces the reason inline, instead of the server
469 // crash-looping on ERR_MODULE_NOT_FOUND once it actually launches.
470 if (probe.exitCode === 3) {
471 return {
472 ok: false,
473 reason:
474 "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.",
475 fatal: true,
476 } as const;
477 }
478​
479 if (probe.exitCode === 0) {
480 const rawVersion = parseNodeVersion(probe.stdout);
481 if (
482 rawVersion !== null &&
483 options.nodeEngineRange &&
484 !satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())
485 ) {
486 const range = options.nodeEngineRange.trim();
487 return {
488 ok: false,
489 reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,
490 fatal: true,
491 } as const;
492 }
493 return { ok: true, nodePath, resolvedPath } as const;
494 }
495​
496 if (options.allowBuild !== true) {
497 const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
498 if (packagedProbeFailure !== null) {
499 return {
500 ok: false,
501 reason: packagedProbeFailure,
502 fatal: true,
503 } as const;
504 }
505 }
506​
507 // node is present but node-pty's native module didn't load.
508 const toolchainCheck = yield* runWslShell(
509 distro,
510 TOOLCHAIN_CHECK_SCRIPT,
511 TOOLCHAIN_TIMEOUT,
512 options,
513 );
514 const toolchainTransportFailure = formatWslShellTransportFailureReason(
515 toolchainCheck.transportFailure,
516 );
517 if (toolchainTransportFailure !== null) {
518 return {
519 ok: false,
520 reason: toolchainTransportFailure,
521 fatal: false,
522 retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
523 } as const;
524 }
525 const report = parseToolchainReport(toolchainCheck.stdout);
526​
527 if (options.allowBuild !== true) {
528 // Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp,
529 // or network is needed — and we must not nag the user to install build
530 // tools they don't need. Still surface a missing/too-old Node (both the
531 // prebuilt and the server require a compatible Node); otherwise reaching
532 // here means the bundled binary itself couldn't load, which is almost
533 // always an unsupported CPU architecture or incompatible system libraries.
534 const nodeOnlyReason = formatMissingToolsReason(
535 {
536 missingTools: report.missingTools.filter((tool) => tool === "node"),
537 nodeVersion: report.nodeVersion,
538 },
539 options.nodeEngineRange?.trim() || null,
540 );
541 return {
542 ok: false,
543 reason:
544 nodeOnlyReason ??
545 "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`.",
546 fatal: true,
547 } as const;
548 }
549​
550 // Dev only: no prebuilt is bundled in a checkout, so compile node-pty from
551 // source. Run the toolchain check first so a missing compiler or out-of-range
552 // Node surfaces a specific, actionable message instead of an opaque node-gyp
553 // failure. Developers have the toolchain; end users never reach this path.
554 const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);
555 if (missingReason !== null) {
556 return { ok: false, reason: missingReason, fatal: true } as const;
557 }
558​
559 const build = yield* runWslShell(
560 distro,
561 NODE_PTY_BUILD_SCRIPT(linuxServerDir),
562 BUILD_TIMEOUT,
563 options,
564 );
565 const buildTransportFailure = formatWslShellTransportFailureReason(build.transportFailure);
566 if (buildTransportFailure !== null) {
567 return {
568 ok: false,
569 reason: buildTransportFailure,
570 fatal: false,
571 retryLimit: BUILD_TRANSPORT_RETRY_LIMIT,
572 } as const;
573 }
574 if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
575 const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500);
576 return {
577 ok: false,
578 reason: `node-pty Linux build failed (exit ${build.exitCode}): ${trimmedTail || "no stderr captured"}`,
579 fatal: true,
580 } as const;
581 });
582​
583export const probeWslDistros: Effect.Effect<
584 readonly WslDistro[],
585 DesktopWslDistroListError,
586 ChildProcessSpawner.ChildProcessSpawner
587> = Effect.scoped(
588 Effect.gen(function* () {
589 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
590 const command = ChildProcess.make("wsl.exe", ["--list", "--verbose"], {
591 stdin: "ignore",
592 stdout: "pipe",
593 stderr: "ignore",
594 killSignal: "SIGTERM",
595 forceKillAfter: PROCESS_TERMINATE_GRACE,
596 });
597 const handle = yield* spawner.spawn(command);
598 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
599 const exitCode = yield* handle.exitCode;
600 if ((exitCode as unknown as number) !== 0) {
601 return yield* new DesktopWslDistroListError({
602 reason: `wsl.exe --list --verbose exited with code ${String(exitCode)}`,
603 });
604 }
605 return parseWslDistroList(Buffer.from(concatChunks(stdoutBytes)));
606 }),
607).pipe(
608 Effect.mapError((error) =>
609 isDesktopWslDistroListError(error)
610 ? error
611 : new DesktopWslDistroListError({
612 reason: `Failed to run wsl.exe --list --verbose: ${error.message}`,
613 }),
614 ),
615 Effect.timeoutOption(LIST_TIMEOUT),
616 Effect.flatMap(
617 Option.match({
618 onNone: () =>
619 new DesktopWslDistroListError({
620 reason: "wsl.exe --list --verbose timed out",
621 }),
622 onSome: Effect.succeed,
623 }),
624 ),
625);
626​
627const preWarmImpl = (
628 distro: string | null,
629): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> =>
630 Effect.scoped(
631 Effect.gen(function* () {
632 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
633 const command = ChildProcess.make("wsl.exe", [...buildDistroArgs(distro), "--", "true"], {
634 stdin: "ignore",
635 stdout: "ignore",
636 stderr: "ignore",
637 killSignal: "SIGTERM",
638 forceKillAfter: PROCESS_TERMINATE_GRACE,
639 });
640 const handle = yield* spawner.spawn(command);
641 yield* handle.exitCode;
642 }),
643 ).pipe(
644 Effect.timeoutOption(PRE_WARM_TIMEOUT),
645 Effect.asVoid,
646 Effect.catch(() => Effect.void),
647 );
648​
649const windowsToWslPathImpl = (
650 distro: string | null,
651 windowsPath: string,
652): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> => {
653 // wsl.exe interprets backslashes as escape chars; normalize to forward slashes.
654 const normalized = windowsPath.replaceAll("\\", "/");
655 return Effect.scoped(
656 Effect.gen(function* () {
657 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
658 const command = ChildProcess.make(
659 "wsl.exe",
660 [...buildDistroArgs(distro), "--", "wslpath", "-u", normalized],
661 {
662 stdin: "ignore",
663 stdout: "pipe",
664 stderr: "ignore",
665 killSignal: "SIGTERM",
666 forceKillAfter: PROCESS_TERMINATE_GRACE,
667 },
668 );
669 const handle = yield* spawner.spawn(command);
670 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
671 const exitCode = yield* handle.exitCode;
672 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
673 const converted = decodeUtf8(concatChunks(stdoutBytes)).trim();
674 return converted.length > 0 ? Option.some(converted) : Option.none<string>();
675 }),
676 ).pipe(
677 Effect.timeoutOption(WSLPATH_TIMEOUT),
678 Effect.map(Option.flatten),
679 Effect.orElseSucceed(() => Option.none<string>()),
680 );
681};
682​
683const IPV4_PATTERN = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
684​
685const getDistroIpImpl = (
686 distro: string | null,
687): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
688 Effect.scoped(
689 Effect.gen(function* () {
690 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
691 // `hostname -I` prints a space-separated list of all non-loopback
692 // IPs the distro has bound. The first entry on the WSL2 default
693 // network is always the eth0 vEthernet address Windows can reach
694 // directly (no wslhost forwarding required).
695 const command = ChildProcess.make(
696 "wsl.exe",
697 [...buildDistroArgs(distro), "--", "sh", "-c", "hostname -I"],
698 {
699 stdin: "ignore",
700 stdout: "pipe",
701 stderr: "ignore",
702 killSignal: "SIGTERM",
703 forceKillAfter: PROCESS_TERMINATE_GRACE,
704 },
705 );
706 const handle = yield* spawner.spawn(command);
707 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
708 const exitCode = yield* handle.exitCode;
709 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
710 const raw = decodeUtf8(concatChunks(stdoutBytes)).trim();
711 const candidate = raw.split(/\s+/).find((part) => IPV4_PATTERN.test(part));
712 return candidate ? Option.some(candidate) : 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 getUserHomeImpl = (
721 distro: string | null,
722): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
723 Effect.scoped(
724 Effect.gen(function* () {
725 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
726 const command = ChildProcess.make(
727 "wsl.exe",
728 // printf so there's no trailing newline noise; getent so we get the
729 // real home from /etc/passwd even if $HOME is unset for some reason.
730 [
731 ...buildDistroArgs(distro),
732 "--",
733 "sh",
734 "-c",
735 'printf "%s" "$(getent passwd "$(id -un)" | cut -d: -f6)"',
736 ],
737 {
738 stdin: "ignore",
739 stdout: "pipe",
740 stderr: "ignore",
741 killSignal: "SIGTERM",
742 forceKillAfter: PROCESS_TERMINATE_GRACE,
743 },
744 );
745 const handle = yield* spawner.spawn(command);
746 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
747 const exitCode = yield* handle.exitCode;
748 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
749 const home = decodeUtf8(concatChunks(stdoutBytes)).trim();
750 return home.startsWith("/") ? Option.some(home) : Option.none<string>();
751 }),
752 ).pipe(
753 Effect.timeoutOption(USER_HOME_TIMEOUT),
754 Effect.map(Option.flatten),
755 Effect.orElseSucceed(() => Option.none<string>()),
756 );
757​
758const makeIsAvailable = (
759 platform: NodeJS.Platform,
760 windir: string,
761): Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path> =>
762 Effect.gen(function* () {
763 if (platform !== "win32") return false;
764 const path = yield* Path.Path;
765 const fileSystem = yield* FileSystem.FileSystem;
766 const wslExePath = path.join(windir, "System32", "wsl.exe");
767 return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));
768 });
769​
770export interface DesktopWslEnvironmentTestStub {
771 readonly isAvailable?: boolean;
772 readonly distros?: ReadonlyArray<WslDistro>;
773 readonly distroListError?: DesktopWslDistroListError;
774 readonly windowsToWslPath?: (distro: string | null, windowsPath: string) => Option.Option<string>;
775 readonly getUserHome?: (distro: string | null) => Option.Option<string>;
776 readonly getDistroIp?: (distro: string | null) => Option.Option<string>;
777 readonly ensureNodePty?: (
778 distro: string | null,
779 windowsRepoRoot: string,
780 options?: EnsureWslNodePtyOptions,
781 ) => EnsureWslNodePtyResult;
783​
784export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
785 const probeDistros = stub.distroListError
786 ? Effect.fail(stub.distroListError)
787 : Effect.succeed(stub.distros ?? []);
788 return Layer.succeed(
789 DesktopWslEnvironment,
790 DesktopWslEnvironment.of({
791 isAvailable: Effect.succeed(stub.isAvailable ?? false),
792 listDistros: probeDistros.pipe(Effect.orElseSucceed(() => [])),
793 probeDistros,
794 preWarm: () => Effect.void,
795 windowsToWslPath: (distro, windowsPath) =>
796 Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none()),
797 getUserHome: (distro) => Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>()),
798 getDistroIp: (distro) => Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>()),
799 ensureNodePty: (distro, windowsRepoRoot, options) =>
800 Effect.succeed(
801 stub.ensureNodePty?.(distro, windowsRepoRoot, options) ?? {
802 ok: false,
803 reason: "ensureNodePty stub not configured",
804 fatal: true,
805 },
806 ),
807 }),
808 );
809};
810​
811export const layer = Layer.effect(
812 DesktopWslEnvironment,
813 Effect.gen(function* () {
814 const environment = yield* DesktopEnvironment.DesktopEnvironment;
815 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
816 const fileSystem = yield* FileSystem.FileSystem;
817 const windir = process.env.WINDIR ?? "C:\\Windows";
818​
819 const provideSpawner = <A, E>(
820 effect: Effect.Effect<A, E, ChildProcessSpawner.ChildProcessSpawner>,
821 ): Effect.Effect<A, E> =>
822 effect.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
823​
824 // Probe wsl.exe once at layer init and cache the result, exposing
825 // `isAvailable` as a resolved value rather than a re-running effect.
826 // WSL availability is effectively static for the process lifetime — the
827 // Windows feature isn't added/removed mid-session, and backend mode
828 // changes already require an app restart — so the cached boolean stays
829 // accurate. Crucially this keeps `isAvailable` synchronously resolvable:
830 // it's read inside the sync IPC handler getLocalEnvironmentBootstraps
831 // (via the primary instance's lazy label -> resolvePrimaryLabel ->
832 // describePrimary). The underlying probe does a filesystem `exists`
833 // check, so leaving it as a live effect would make Effect.runSync throw
834 // there and break the renderer's synchronous bootstrap path.
835 const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe(
836 Effect.provideService(FileSystem.FileSystem, fileSystem),
837 Effect.provideService(Path.Path, environment.path),
838 Effect.withSpan("desktop.wsl.isAvailable"),
839 );
840 const isAvailable = Effect.succeed(wslAvailable);
841​
842 const windowsToWslPath = (distro: string | null, windowsPath: string) =>
843 provideSpawner(windowsToWslPathImpl(distro, windowsPath)).pipe(
844 Effect.withSpan("desktop.wsl.windowsToWslPath"),
845 );
846​
847 // Cache user-home results per distro key — folder picker can be opened
848 // many times in a session and the value is stable for the life of the
849 // distro. Negative results aren't cached so a transient wsl.exe failure
850 // doesn't permanently disable tilde expansion.
851 const userHomeCache = new Map<string, string>();
852 const getUserHome = (distro: string | null) =>
853 Effect.gen(function* () {
854 const key = distro ?? "__default__";
855 const cached = userHomeCache.get(key);
856 if (cached !== undefined) return Option.some(cached);
857 const resolved = yield* provideSpawner(getUserHomeImpl(distro));
858 if (Option.isSome(resolved)) userHomeCache.set(key, resolved.value);
859 return resolved;
860 }).pipe(Effect.withSpan("desktop.wsl.getUserHome"));
861​
862 const getDistroIp = (distro: string | null) =>
863 provideSpawner(getDistroIpImpl(distro)).pipe(Effect.withSpan("desktop.wsl.getDistroIp"));
864​
865 const probeDistros = provideSpawner(probeWslDistros).pipe(
866 Effect.withSpan("desktop.wsl.probeDistros"),
867 );
868​
869 return DesktopWslEnvironment.of({
870 isAvailable,
871 listDistros: probeDistros.pipe(
872 Effect.orElseSucceed(() => []),
873 Effect.withSpan("desktop.wsl.listDistros"),
874 ),
875 probeDistros,
876 preWarm: (distro) =>
877 provideSpawner(preWarmImpl(distro)).pipe(Effect.withSpan("desktop.wsl.preWarm")),
878 windowsToWslPath,
879 getUserHome,
880 getDistroIp,
881 ensureNodePty: (distro, windowsRepoRoot, options) =>
882 provideSpawner(ensureNodePtyImpl(distro, windowsRepoRoot, windowsToWslPath, options)).pipe(
883 Effect.withSpan("desktop.wsl.ensureNodePty"),
884 ),
885 });
886 }),
887);