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

DesktopWslEnvironment.ts

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