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 RUNTIME_INSTALL_TIMEOUT = Duration.minutes(2);
26const RUNTIME_PRUNE_TIMEOUT = Duration.seconds(30);
27const RUNTIME_INVALIDATE_TIMEOUT = Duration.seconds(15);
28const USER_HOME_TIMEOUT = Duration.seconds(5);
29const TOOLCHAIN_TRANSPORT_RETRY_LIMIT = 12;
30const BUILD_TRANSPORT_RETRY_LIMIT = 2;
31
32export interface EnsureWslNodePtyOptions {
33 readonly allowBuild?: boolean;
34 readonly nodeEngineRange?: string | null;
35}
36
37// The packaged WSL runtime archive plus the SHA-256 identity the build recorded
38// for it. The cache key derives from the same digest, and installation verifies
39// the bytes before promoting the extracted tree.
40export interface WslRuntimeArchive {
41 readonly windowsPath: string;
42 readonly runtimeId: string;
43 readonly sha256: string;
44}
45
46export type PrepareWslRuntimeResult =
47 | {
48 readonly ok: true;
49 readonly linuxAppRoot: string;
50 }
51 | {
52 readonly ok: false;
53 readonly reason: string;
54 };
55
56export type EnsureWslNodePtyResult =
57 | {
58 readonly ok: true;
59 readonly nodePath: string;
60 readonly resolvedPath: string;
61 }
62 | {
63 readonly ok: false;
64 readonly reason: string;
65 readonly fatal: boolean;
66 readonly retryLimit?: number;
67 };
68
69export class DesktopWslDistroListError extends Schema.TaggedError<DesktopWslDistroListError>()(
70 "DesktopWslDistroListError",
71 { reason: Schema.String },
72) {
73 override get message(): string {
74 return this.reason;
75 }
76}
77
78const isDesktopWslDistroListError = Schema.is(DesktopWslDistroListError);
79
80export class DesktopWslEnvironment extends Context.Service<
81 DesktopWslEnvironment,
82 {
83 readonly isAvailable: Effect.Effect<boolean>;
84 // Best-effort enumeration for renderer UX. Backend health checks must use
85 // probeDistros so a transient command failure is not mistaken for a
86 // successful empty installation.
87 readonly listDistros: Effect.Effect<readonly WslDistro[]>;
88 readonly probeDistros: Effect.Effect<readonly WslDistro[], DesktopWslDistroListError>;
89 readonly preWarm: (distro: string | null) => Effect.Effect<void>;
90 readonly windowsToWslPath: (
91 distro: string | null,
92 windowsPath: string,
93 ) => Effect.Effect<Option.Option<string>>;
94 // Resolves the user's Linux home dir inside the chosen distro (e.g.
95 // "/home/josh"). Used by the folder picker to expand `~` correctly.
96 readonly getUserHome: (distro: string | null) => Effect.Effect<Option.Option<string>>;
97 // Resolves the WSL distro's IPv4 address on the WSL vEthernet adapter
98 // (e.g. "172.x.x.x"). The orchestrator uses this for the WSL backend's
99 // httpBaseUrl so the renderer can reach it without relying on wslhost's
100 // localhost→WSL automatic forwarding, which is flaky in practice
101 // (the backend can be listening for 30+ seconds before wslhost starts
102 // forwarding 127.0.0.1:port to WSL-side localhost).
103 readonly getDistroIp: (distro: string | null) => Effect.Effect<Option.Option<string>>;
104 readonly prepareRuntime: (
105 distro: string | null,
106 archive: WslRuntimeArchive,
107 ) => Effect.Effect<PrepareWslRuntimeResult>;
108 readonly pruneRuntimes: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
109 // Marks a staged runtime as unusable so the next launch reinstalls it.
110 readonly invalidateRuntime: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
111 readonly ensureNodePty: (
112 distro: string | null,
113 linuxAppRoot: string,
114 options?: EnsureWslNodePtyOptions,
115 ) => Effect.Effect<EnsureWslNodePtyResult>;
116 }
117>()("@t3tools/desktop/wsl/DesktopWslEnvironment") {}
118
119const buildDistroArgs = (distro: string | null): ReadonlyArray<string> =>
120 distro ? ["-d", distro] : [];
121
122const concatChunks = (arrays: ReadonlyArray<Uint8Array>): Uint8Array => {
123 let totalLength = 0;
124 for (const arr of arrays) totalLength += arr.byteLength;
125 const out = new Uint8Array(totalLength);
126 let offset = 0;
127 for (const arr of arrays) {
128 out.set(arr, offset);
129 offset += arr.byteLength;
130 }
131 return out;
132};
133
134const decodeUtf8 = (bytes: Uint8Array): string => new TextDecoder("utf-8").decode(bytes);
135
136interface ShellResult {
137 readonly exitCode: number;
138 readonly stdout: string;
139 readonly stderr: string;
140 readonly transportFailure: "timeout" | "spawn" | "process" | null;
141}
142
143const TIMEOUT_RESULT: ShellResult = {
144 exitCode: 124,
145 stdout: "",
146 stderr: "\n[timeout]",
147 transportFailure: "timeout",
148};
149
150const formatWslShellTransportFailureReason = (
151 failure: ShellResult["transportFailure"],
152): string | null => {
153 switch (failure) {
154 case "timeout":
155 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.";
156 case "spawn":
157 return "WSL backend preflight could not start wsl.exe to probe for Node.js. Check that WSL is installed and the distro is accessible.";
158 case "process":
159 return "WSL backend preflight lost communication with wsl.exe while probing for Node.js. Retry, or check that the distro is healthy.";
160 case null:
161 return null;
162 }
163};
164
165// Reuse the SSH remote resolver so WSL and SSH discover version-managed Node
166// the same way. Passing the engine range lets the resolver fall through to
167// version managers like nvm when a system node exists but is too old.
168const buildWslNodeEnvPreamble = (
169 nodeEngineRange?: string | null,
170): string => `${buildRemoteNodeEnvScript({ nodeEngineRange: nodeEngineRange ?? null })}
171ensure_remote_node_path || true
172`;
173
174// wsl.exe re-escapes args before forwarding them to the Linux side, which
175// mangles quotes inside `bash -lc "<script>"`. Pipe the script via stdin to
176// avoid passing it on the command line at all.
177const runWslShell = (
178 distro: string | null,
179 bashScript: string,
180 timeout: Duration.Duration,
181 options: {
182 readonly nodeEngineRange?: string | null;
183 readonly resolveNode?: boolean;
184 } = {},
185): Effect.Effect<ShellResult, never, ChildProcessSpawner.ChildProcessSpawner> => {
186 const spawner = ChildProcessSpawner.ChildProcessSpawner;
187 // Node probes use a login bash so profile-managed PATH entries and supported
188 // version managers are available. Runtime installation needs only POSIX tools,
189 // so it skips profile loading and runs sh directly.
190 const resolveNode = options.resolveNode !== false;
191 const command = ChildProcess.make(
192 "wsl.exe",
193 resolveNode
194 ? [...buildDistroArgs(distro), "--", "bash", "-l", "-s"]
195 : [...buildDistroArgs(distro), "--exec", "sh", "-s"],
196 {
197 stdin: Stream.encodeText(
198 Stream.make(
199 resolveNode
200 ? `${buildWslNodeEnvPreamble(options.nodeEngineRange)}${bashScript}`
201 : bashScript,
202 ),
203 ),
204 stdout: "pipe",
205 stderr: "pipe",
206 killSignal: "SIGTERM",
207 forceKillAfter: PROCESS_TERMINATE_GRACE,
208 },
209 );
210
211 return Effect.scoped(
212 Effect.gen(function* () {
213 const spawnerService = yield* spawner;
214 const spawnResult = yield* spawnerService.spawn(command).pipe(
215 Effect.match({
216 onFailure: (error) => ({ _tag: "Failure", error }) as const,
217 onSuccess: (handle) => ({ _tag: "Success", handle }) as const,
218 }),
219 );
220 if (spawnResult._tag === "Failure") {
221 return {
222 exitCode: 127,
223 stdout: "",
224 stderr: `\n${spawnResult.error.message}`,
225 transportFailure: "spawn",
226 } satisfies ShellResult;
227 }
228 const handle = spawnResult.handle;
229 // Drain stdout and stderr concurrently so neither pipe buffer can fill
230 // and stall the child (node-gyp rebuild emits large output on both).
231 const [stdoutBytes, stderrBytes, exitCode] = yield* Effect.all(
232 [Stream.runCollect(handle.stdout), Stream.runCollect(handle.stderr), handle.exitCode],
233 { concurrency: "unbounded" },
234 );
235 return {
236 exitCode: exitCode as unknown as number,
237 stdout: decodeUtf8(concatChunks(stdoutBytes)),
238 stderr: decodeUtf8(concatChunks(stderrBytes)),
239 transportFailure: null,
240 } satisfies ShellResult;
241 }),
242 ).pipe(
243 Effect.timeoutOption(timeout),
244 Effect.map(Option.getOrElse((): ShellResult => TIMEOUT_RESULT)),
245 Effect.catch((error) =>
246 Effect.succeed<ShellResult>({
247 exitCode: 127,
248 stdout: "",
249 stderr: `\n${error.message}`,
250 transportFailure: "process",
251 }),
252 ),
253 );
254};
255
256const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
257
258// Holds the sha256 of the runtime's server entry, written when the install
259// promotes a verified tree. Presence alone only says an install once finished
260// here; the digest is what lets a later launch prove the entry still is what
261// that install wrote.
262const WSL_RUNTIME_READY_MARKER = ".t3code-wsl-runtime-ready";
263const WSL_RUNTIME_SELECTED_MARKER = ".t3code-wsl-runtime-selected";
264const WSL_RUNTIME_SELECTION_GRACE_MINUTES = 5;
265
266const sanitizeWslRuntimeId = (value: string): string => value.replace(/[^A-Za-z0-9._-]/g, "_");
267
268// `archiveSha256` is the digest the build recorded alongside the archive. The
269// install verifies the bytes before extracting, so an archive can never be
270// promoted under an identity that does not describe it.
271export const buildWslRuntimeInstallScript = (
272 linuxArchivePath: string,
273 runtimeId: string,
274 archiveSha256: string,
275): string => {
276 const safeRuntimeId = sanitizeWslRuntimeId(runtimeId);
277 return [
278 "set -eu",
279 'runtime_parent="$HOME/.t3/wsl-runtime"',
280 `runtime_root="$runtime_parent/${safeRuntimeId}"`,
281 `ready_marker="$runtime_root/${WSL_RUNTIME_READY_MARKER}"`,
282 // The native payload is the part of the tree the WSL backend actually
283 // dlopens, and the only part a user can plausibly break by hand. Checking
284 // node-pty's package.json alone let a runtime whose pty.node had gone
285 // missing stay cache-ready forever: every launch reused it and then failed
286 // the native probe, with no reinstall and no fallback. Match on the glob
287 // rather than a mapped `uname -m` so this stays a presence check; the probe
288 // is what decides whether the binary is the right arch and loadable.
289 "node_pty_payload_present() {",
290 ' for candidate in "$1"/node_modules/node-pty/prebuilds/linux-*/pty.node; do',
291 ' [ -f "$candidate" ] || continue',
292 ' [ -f "${candidate%/*}/t3code-wsl-node-pty.json" ] || continue',
293 " return 0",
294 " done",
295 " return 1",
296 "}",
297 // Hashing the server entry is the only check that can tell a working cache
298 // from one whose bin.mjs was truncated or half-written: the file is still
299 // there, the native probe still passes, and launch then picks a server that
300 // exits before it can become ready, on every restart. Hashing the ~7MB
301 // entry measures in single-digit milliseconds inside the distro, once per
302 // launch, against a cold reinstall of a few hundred megabytes.
303 "runtime_server_entry_digest() {",
304 ` sha256sum "$1/apps/server/dist/bin.mjs" 2>/dev/null | cut -d ' ' -f 1`,
305 "}",
306 "runtime_is_ready() {",
307 ' [ -f "$ready_marker" ] &&',
308 ' [ -f "$runtime_root/apps/server/dist/bin.mjs" ] &&',
309 ' [ -f "$runtime_root/node_modules/node-pty/package.json" ] &&',
310 ' node_pty_payload_present "$runtime_root" &&',
311 // An empty or unreadable marker is a miss, not a pass: that is what a
312 // runtime installed before the marker carried a digest looks like, and one
313 // reinstall is the cheapest way to make it verifiable from then on.
314 ` recorded_entry_digest=$(tr -d '[:space:]' < "$ready_marker" 2>/dev/null) &&`,
315 ' [ -n "$recorded_entry_digest" ] &&',
316 ' [ "$recorded_entry_digest" = "$(runtime_server_entry_digest "$runtime_root")" ]',
317 "}",
318 'mkdir -p "$runtime_parent"',
319 `runtime_lock="$runtime_parent/.${safeRuntimeId}.install.lock"`,
320 "trap 'exit 1' HUP INT TERM",
321 'exec 9> "$runtime_lock"',
322 "flock -x 9",
323 "if runtime_is_ready; then",
324 ` touch "$runtime_root/${WSL_RUNTIME_SELECTED_MARKER}"`,
325 ` printf 'runtimeRoot:%s\\n' "$runtime_root"`,
326 " exit 0",
327 "fi",
328 // Hash only on a cache miss: a warm launch already exited above, and a cold
329 // install is about to read the whole archive through tar anyway. `set -eu`
330 // turns a distro without sha256sum into an install failure, which falls back
331 // to the mounted server tree rather than trusting unverified bytes.
332 `archive_sha=$(sha256sum ${shellQuote(linuxArchivePath)} | cut -d ' ' -f 1)`,
333 `if [ "$archive_sha" != ${shellQuote(archiveSha256)} ]; then`,
334 ` printf 'WSL runtime archive does not match its recorded SHA-256 (expected %s, got %s)\\n' ${shellQuote(archiveSha256)} "$archive_sha" >&2`,
335 " exit 1",
336 "fi",
337 // A backend can still be running out of an unready tree: the probe revokes
338 // the ready marker without stopping the process it just failed for, and
339 // invalidation deliberately leaves the tree in place for exactly that
340 // reason. Deleting it here unlinks node_modules from under a live backend,
341 // which then breaks the moment it lazily loads anything it had not already
342 // read. Move it aside either way, but only delete it now when nothing is
343 // running from it; otherwise hand it to the pruner's scratch sweep, which
344 // is what that delay is for. A process's cmdline keeps the pre-rename path,
345 // so this has to be asked before the move, not after. This script arrives
346 // on stdin, so it cannot match itself.
347 "runtime_in_use() {",
348 // No /proc means no way to tell, and guessing wrong costs a live backend
349 // its runtime. Keeping the tree only costs disk until the sweep runs.
350 " [ -d /proc/1 ] || return 0",
351 ' grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null',
352 "}",
353 'if [ -e "$runtime_root" ]; then',
354 ' if runtime_in_use "$runtime_root"; then',
355 " runtime_root_in_use=1",
356 " else",
357 " runtime_root_in_use=0",
358 " fi",
359 ` runtime_stale=$(mktemp -d "$runtime_parent/.${safeRuntimeId}.stale.XXXXXX")`,
360 ' rmdir "$runtime_stale"',
361 ' if mv -T "$runtime_root" "$runtime_stale" 2>/dev/null; then',
362 ' if [ "$runtime_root_in_use" = 1 ]; then',
363 // Renaming keeps the directory's old mtime, so restart the cleanup clock.
364 ' touch "$runtime_stale"',
365 " else",
366 ' rm -rf "$runtime_stale"',
367 " fi",
368 " fi",
369 "fi",
370 `runtime_tmp=$(mktemp -d "$runtime_parent/.${safeRuntimeId}.tmp.XXXXXX")`,
371 'cleanup_runtime_install() { rm -rf "$runtime_tmp"; }',
372 "trap cleanup_runtime_install EXIT",
373 `tar -xzf ${shellQuote(linuxArchivePath)} -C "$runtime_tmp"`,
374 'test -f "$runtime_tmp/apps/server/dist/bin.mjs"',
375 'test -f "$runtime_tmp/node_modules/node-pty/package.json"',
376
377 // Never write the ready marker over a tree that is missing the native
378 // payload. Failing here drops out to the mounted-tree fallback, which is
379 // recoverable; promoting it would mark the defect ready and cache it.
380 'if ! node_pty_payload_present "$runtime_tmp"; then',
381 " printf 'WSL runtime archive is missing its Linux node-pty binary\\n' >&2",
382 " exit 1",
383 "fi",
384 // The archive's bytes were verified against archiveSha256 above, so the
385 // digest recorded here describes content this install proved. Every later
386 // warm reuse checks the entry against it.
387 'installed_entry_digest=$(runtime_server_entry_digest "$runtime_tmp")',
388 'if [ -z "$installed_entry_digest" ]; then',
389 " printf 'Could not hash the WSL runtime server entry\\n' >&2",
390 " exit 1",
391 "fi",
392 `printf '%s\\n' "$installed_entry_digest" > "$runtime_tmp/${WSL_RUNTIME_READY_MARKER}"`,
393 'if mv -T "$runtime_tmp" "$runtime_root" 2>/dev/null; then',
394 " :",
395 "elif runtime_is_ready; then",
396 ' rm -rf "$runtime_tmp"',
397 "else",
398 ` printf 'Could not promote WSL runtime cache at %s\\n' "$runtime_root" >&2`,
399 " exit 1",
400 "fi",
401 `touch "$runtime_root/${WSL_RUNTIME_SELECTED_MARKER}"`,
402 `printf 'runtimeRoot:%s\\n' "$runtime_root"`,
403 ].join("\n");
404};
405
406// An interrupted install leaves a dot-prefixed scratch directory behind. A cold
407// install extracts a few hundred MB inside the distro, so two hours is far past
408// any live install while still bounding how long an orphan survives.
409const ORPHANED_RUNTIME_SCRATCH_MAX_AGE_MINUTES = 120;
410
411export const buildWslRuntimePruneScript = (runtimeId: string): string => {
412 const safeRuntimeId = sanitizeWslRuntimeId(runtimeId);
413 return [
414 "set -eu",
415 'runtime_parent="$HOME/.t3/wsl-runtime"',
416 `current_runtime="$runtime_parent/${safeRuntimeId}"`,
417 '[ -d "$runtime_parent" ] || exit 0',
418 // Serialize the whole retention decision so two backends cannot select
419 // different "previous" caches and delete around one another.
420 'prune_lock="$runtime_parent/.prune.lock"',
421 'exec 8> "$prune_lock"',
422 "flock -x 8",
423 // Without a way to see the distro's processes we cannot tell which caches
424 // are load-bearing, and the retention rules below are not safe on their own.
425 "[ -d /proc/1 ] || exit 0",
426 "runtime_in_use() {",
427 ' grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null',
428 "}",
429 'previous_runtime=""',
430 'for candidate in "$runtime_parent"/sha256-*; do',
431 ' [ -d "$candidate" ] || continue',
432 ' [ "$candidate" != "$current_runtime" ] || continue',
433 ` [ -f "$candidate/${WSL_RUNTIME_READY_MARKER}" ] || continue`,
434 ' if [ -z "$previous_runtime" ] || [ "$candidate" -nt "$previous_runtime" ]; then',
435 ' previous_runtime="$candidate"',
436 " fi",
437 "done",
438 // Only this desktop-owned prefix is eligible. Markerless roots are broken
439 // caches left by invalidation and must not become permanent disk leaks.
440 'for candidate in "$runtime_parent"/sha256-*; do',
441 ' [ -d "$candidate" ] || continue',
442 ' [ "$candidate" != "$current_runtime" ] || continue',
443 ' [ "$candidate" != "$previous_runtime" ] || continue',
444 ' ! runtime_in_use "$candidate" || continue',
445 " candidate_name=${candidate##*/}",
446 ' candidate_lock="$runtime_parent/.${candidate_name}.install.lock"',
447 ' exec 9> "$candidate_lock"',
448 // A held lock means another launch is installing or repairing this cache.
449 // Skip instead of waiting or deleting underneath it.
450 " flock -n 9 || continue",
451 ` selected_marker="$candidate/${WSL_RUNTIME_SELECTED_MARKER}"`,
452 ` if [ -f "$selected_marker" ] && find "$selected_marker" -maxdepth 0 -mmin -${String(WSL_RUNTIME_SELECTION_GRACE_MINUTES)} -print -quit | grep -q .; then`,
453 " flock -u 9",
454 " continue",
455 " fi",
456 ' rm -rf -- "$candidate"',
457 " flock -u 9",
458 "done",
459 // Interrupted installs use dot-prefixed names under this dedicated parent.
460 'for scratch in "$runtime_parent"/.*.tmp.* "$runtime_parent"/.*.stale.*; do',
461 ' [ -d "$scratch" ] || continue',
462 ` find "$scratch" -maxdepth 0 -mmin +${String(ORPHANED_RUNTIME_SCRATCH_MAX_AGE_MINUTES)} -print -quit | grep -q . || continue`,
463 ' rm -rf -- "$scratch"',
464 "done",
465 ].join("\n");
466};
467
468// Drops the ready marker so the next launch reinstalls the runtime from the
469// archive. Readiness is a presence check by design, so a cached tree whose
470// native payload is present but unloadable (truncated pty.node, a distro whose
471// glibc the binary needs and the tree was copied from another machine) stays
472// ready forever and fails the probe on every launch. Only the probe can see
473// that, so the probe is what revokes the marker. The tree itself is left in
474// place: the install script moves an unready root aside before extracting.
475export const buildWslRuntimeInvalidateScript = (runtimeId: string): string => {
476 const safeRuntimeId = sanitizeWslRuntimeId(runtimeId);
477 return [
478 "set -eu",
479 `rm -f "$HOME/.t3/wsl-runtime/${safeRuntimeId}/${WSL_RUNTIME_READY_MARKER}"`,
480 ].join("\n");
481};
482
483export const parseWslRuntimeRoot = (stdout: string): string | null => {
484 const prefix = "runtimeRoot:";
485 const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));
486 if (line === undefined) return null;
487 const runtimeRoot = line.slice(prefix.length).replace(/\r$/, "");
488 return runtimeRoot.startsWith("/") ? runtimeRoot : null;
489};
490
491const NODE_PTY_PREBUILD_MISSING_EXIT_CODE = 4;
492
493const formatNodePtyProbeFailureReason = (exitCode: number): string | null =>
494 exitCode === NODE_PTY_PREBUILD_MISSING_EXIT_CODE
495 ? "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."
496 : null;
497
498const NODE_PTY_PROBE_SCRIPT = (
499 linuxServerDir: string,
500) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"
501printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)"
502printf 'resolvedPath:%s\\n' "$PATH"
503cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
504// The WSL Node can't read inside app.asar, so confirm what the server needs is
505// unpacked on the real filesystem before reporting the backend healthy. Exit 3
506// marks this distinct from a node-pty prebuild problem so the caller can report
507// it accurately instead of letting the server crash on ERR_MODULE_NOT_FOUND at
508// launch (which, in wsl-only mode, would just fail to launch with no fallback).
509//
510// The sentinel must be a package the CLI bundle leaves external. It used to be
511// "effect", back when the bundle externalized its runtime deps and the whole
512// node_modules tree was unpacked. The bundle now inlines its JS dependencies,
513// so "effect" no longer exists on disk and only the native packages do —
514// resolving node-pty is what actually validates the unpacked tree.
515try { require.resolve("node-pty/package.json"); } catch (_e) { process.exit(3); }
516const fs = require("node:fs");
517const path = require("node:path");
518const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
519// node-pty 1.x is N-API based, so a single Linux pty.node is ABI-stable across
520// Node versions — require() succeeding IS the real compatibility test. Compare
521// only arch and node-pty version (a stale binary from a different node-pty),
522// NOT process.versions.modules: that would reject a perfectly loadable prebuilt
523// whenever the user's WSL Node ABI differs from the build's, defeating the
524// whole point of shipping one prebuilt for all Node versions.
525const expected = {
526 arch: process.arch,
527 nodePtyVersion: require("node-pty/package.json").version,
528};
529const prebuildDir = path.join(pkgDir, "prebuilds", "linux-" + process.arch);
530const marker = path.join(prebuildDir, "t3code-wsl-node-pty.json");
531const binary = path.join(prebuildDir, "pty.node");
532if (!fs.existsSync(marker) || !fs.existsSync(binary)) process.exit(${NODE_PTY_PREBUILD_MISSING_EXIT_CODE});
533require("node-pty");
534const actual = JSON.parse(fs.readFileSync(marker, "utf8"));
535for (const key of Object.keys(expected)) {
536 if (actual[key] !== expected[key]) process.exit(2);
537}
538NODE`;
539
540const TOOLCHAIN_CHECK_SCRIPT = [
541 "for tool in node make g++ python3; do",
542 ' command -v "$tool" >/dev/null 2>&1 || echo "missing:$tool"',
543 "done",
544 "if command -v node >/dev/null 2>&1; then",
545 ` ver="$(node -p 'process.versions.node' 2>/dev/null)"`,
546 ' if [ -n "$ver" ]; then printf "nodeVersion:%s\\n" "$ver"; fi',
547 "fi",
548].join("\n");
549
550const NODE_PTY_BUILD_SCRIPT = (linuxServerDir: string) =>
551 [
552 "set -e",
553 `cd ${shellQuote(linuxServerDir)}`,
554 `pkg_dir=$(node -p "require('node:path').dirname(require.resolve('node-pty/package.json'))")`,
555 `arch=$(node -p "process.arch")`,
556 `modules=$(node -p "process.versions.modules")`,
557 `node_pty_version=$(node -p "require('node-pty/package.json').version")`,
558 `cd "$pkg_dir"`,
559 "npx --yes node-gyp rebuild",
560 `prebuild_dir="prebuilds/linux-$arch"`,
561 `mkdir -p "$prebuild_dir"`,
562 `cp build/Release/pty.node "$prebuild_dir/pty.node"`,
563 `printf '{"arch":"%s","modules":"%s","nodePtyVersion":"%s"}\\n' "$arch" "$modules" "$node_pty_version" > "$prebuild_dir/t3code-wsl-node-pty.json"`,
564 `node -e 'require("node-pty")'`,
565 ].join("\n");
566
567export interface ToolchainReport {
568 readonly missingTools: ReadonlyArray<string>;
569 readonly nodeVersion: string | null;
570}
571
572export const parseToolchainReport = (stdout: string): ToolchainReport => {
573 const lines = stdout
574 .split("\n")
575 .map((line) => line.trim())
576 .filter((line) => line.length > 0);
577 const missingTools = lines
578 .filter((line) => line.startsWith("missing:"))
579 .map((line) => line.slice("missing:".length));
580 const nodeVersionLine = lines.find((line) => line.startsWith("nodeVersion:"));
581 const nodeVersion = nodeVersionLine
582 ? nodeVersionLine.slice("nodeVersion:".length).trim() || null
583 : null;
584 return { missingTools, nodeVersion };
585};
586
587// Pulls the absolute node path the WSL distro resolved after the shared remote
588// resolver repaired PATH. Returns null when no node was found, which the caller
589// turns into an actionable "install Node" message instead of a confusing
590// node-pty error.
591export const parseNodePath = (stdout: string): string | null => {
592 const path = stdout
593 .split("\n")
594 .map((line) => line.trim())
595 .filter((line) => line.startsWith("nodePath:"))
596 .map((line) => line.slice("nodePath:".length).trim())
597 .find((value) => value.length > 0);
598 return path ?? null;
599};
600
601export const parseNodeVersion = (stdout: string): string | null => {
602 const version = stdout
603 .split("\n")
604 .map((line) => line.trim())
605 .filter((line) => line.startsWith("nodeVersion:"))
606 .map((line) => line.slice("nodeVersion:".length).trim())
607 .find((value) => value.length > 0);
608 return version ?? null;
609};
610
611// Captures the login-shell PATH after the shared resolver has loaded version
612// managers. Preserve the value byte-for-byte apart from a Windows-style CR so
613// paths containing spaces or apostrophes can be forwarded as one env argv.
614export const parseResolvedPath = (stdout: string): string | null => {
615 const prefix = "resolvedPath:";
616 const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));
617 if (line === undefined) return null;
618 const resolvedPath = line.slice(prefix.length).replace(/\r$/, "");
619 return resolvedPath.length > 0 ? resolvedPath : null;
620};
621
622export const formatMissingToolsReason = (
623 report: ToolchainReport,
624 requiredRange: string | null,
625): string | null => {
626 const nodeMissing = report.missingTools.includes("node");
627 const nodeOutOfRange =
628 !nodeMissing &&
629 requiredRange !== null &&
630 report.nodeVersion !== null &&
631 !satisfiesSemverRange(report.nodeVersion, requiredRange);
632 const buildToolsMissing = report.missingTools.filter((tool) => tool !== "node");
633
634 if (!nodeMissing && !nodeOutOfRange && buildToolsMissing.length === 0) {
635 return null;
636 }
637
638 const issues: string[] = [];
639 const remediations: string[] = [];
640
641 if (nodeMissing) {
642 issues.push("node");
643 remediations.push(
644 `Node.js${requiredRange ? ` satisfying \`${requiredRange}\`` : " 18+"} (e.g. via nvm)`,
645 );
646 } else if (nodeOutOfRange) {
647 issues.push(`node ${report.nodeVersion} (requires ${requiredRange})`);
648 remediations.push(
649 `a newer Node.js satisfying \`${requiredRange}\` (e.g. \`nvm install 24 && nvm alias default 24\`)`,
650 );
651 }
652
653 if (buildToolsMissing.length > 0) {
654 issues.push(...buildToolsMissing);
655 remediations.push(
656 "the build toolchain (e.g. `sudo apt install -y build-essential python3` on Ubuntu/Debian)",
657 );
658 }
659
660 return `WSL distro is missing required tools: ${issues.join(", ")}. Install ${remediations.join(" and ")}, then retry.`;
661};
662
663const ensureNodePtyImpl = (
664 distro: string | null,
665 linuxRepoRoot: string,
666 options: EnsureWslNodePtyOptions = {},
667): Effect.Effect<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> =>
668 Effect.gen(function* () {
669 // node-pty lives in the apps/server workspace's node_modules; resolve from
670 // there rather than the monorepo root, where Bun's hoist layout omits it.
671 const linuxServerDir = `${linuxRepoRoot}/apps/server`;
672
673 const probe = yield* runWslShell(
674 distro,
675 NODE_PTY_PROBE_SCRIPT(linuxServerDir),
676 PROBE_TIMEOUT,
677 options,
678 );
679 const nodePath = parseNodePath(probe.stdout);
680 const resolvedPath = parseResolvedPath(probe.stdout);
681
682 const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
683 if (transportFailureReason !== null) {
684 return {
685 ok: false,
686 reason: transportFailureReason,
687 fatal: false,
688 } as const;
689 }
690
691 // No node at all, even after the shared resolver repaired PATH. Surface
692 // the specific, actionable toolchain message rather than a confusing
693 // node-pty error, and don't try to build.
694 if (nodePath === null) {
695 const toolchainCheck = yield* runWslShell(
696 distro,
697 TOOLCHAIN_CHECK_SCRIPT,
698 TOOLCHAIN_TIMEOUT,
699 options,
700 );
701 const toolchainTransportFailure = formatWslShellTransportFailureReason(
702 toolchainCheck.transportFailure,
703 );
704 if (toolchainTransportFailure !== null) {
705 return {
706 ok: false,
707 reason: toolchainTransportFailure,
708 fatal: false,
709 retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
710 } as const;
711 }
712 const report = parseToolchainReport(toolchainCheck.stdout);
713 const reason =
714 formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null) ??
715 "Node.js was not found in the WSL distro. Install it (e.g. via nvm) and restart the desktop app.";
716 return { ok: false, reason, fatal: true } as const;
717 }
718
719 if (resolvedPath === null) {
720 return {
721 ok: false,
722 reason: "WSL login-shell PATH could not be resolved during backend preflight.",
723 fatal: true,
724 } as const;
725 }
726
727 // The packages the server bundle leaves external (node-pty and the other
728 // native addons) couldn't be resolved on the WSL filesystem — a packaging
729 // regression, since those must be unpacked from the asar. Fatal so wsl-only
730 // mode falls back to Windows and dual mode surfaces the reason inline,
731 // instead of the server crash-looping on ERR_MODULE_NOT_FOUND once it
732 // actually launches.
733 if (probe.exitCode === 3) {
734 return {
735 ok: false,
736 reason:
737 '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.',
738 fatal: true,
739 } as const;
740 }
741
742 if (probe.exitCode === 0) {
743 const rawVersion = parseNodeVersion(probe.stdout);
744 if (
745 rawVersion !== null &&
746 options.nodeEngineRange &&
747 !satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())
748 ) {
749 const range = options.nodeEngineRange.trim();
750 return {
751 ok: false,
752 reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,
753 fatal: true,
754 } as const;
755 }
756 return { ok: true, nodePath, resolvedPath } as const;
757 }
758
759 if (options.allowBuild !== true) {
760 const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
761 if (packagedProbeFailure !== null) {
762 return {
763 ok: false,
764 reason: packagedProbeFailure,
765 fatal: true,
766 } as const;
767 }
768 }
769
770 // node is present but node-pty's native module didn't load.
771 const toolchainCheck = yield* runWslShell(
772 distro,
773 TOOLCHAIN_CHECK_SCRIPT,
774 TOOLCHAIN_TIMEOUT,
775 options,
776 );
777 const toolchainTransportFailure = formatWslShellTransportFailureReason(
778 toolchainCheck.transportFailure,
779 );
780 if (toolchainTransportFailure !== null) {
781 return {
782 ok: false,
783 reason: toolchainTransportFailure,
784 fatal: false,
785 retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
786 } as const;
787 }
788 const report = parseToolchainReport(toolchainCheck.stdout);
789
790 if (options.allowBuild !== true) {
791 // Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp,
792 // or network is needed — and we must not nag the user to install build
793 // tools they don't need. Still surface a missing/too-old Node (both the
794 // prebuilt and the server require a compatible Node); otherwise reaching
795 // here means the bundled binary itself couldn't load, which is almost
796 // always an unsupported CPU architecture or incompatible system libraries.
797 const nodeOnlyReason = formatMissingToolsReason(
798 {
799 missingTools: report.missingTools.filter((tool) => tool === "node"),
800 nodeVersion: report.nodeVersion,
801 },
802 options.nodeEngineRange?.trim() || null,
803 );
804 return {
805 ok: false,
806 reason:
807 nodeOnlyReason ??
808 "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`.",
809 fatal: true,
810 } as const;
811 }
812
813 // Dev only: no prebuilt is bundled in a checkout, so compile node-pty from
814 // source. Run the toolchain check first so a missing compiler or out-of-range
815 // Node surfaces a specific, actionable message instead of an opaque node-gyp
816 // failure. Developers have the toolchain; end users never reach this path.
817 const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);
818 if (missingReason !== null) {
819 return { ok: false, reason: missingReason, fatal: true } as const;
820 }
821
822 const build = yield* runWslShell(
823 distro,
824 NODE_PTY_BUILD_SCRIPT(linuxServerDir),
825 BUILD_TIMEOUT,
826 options,
827 );
828 const buildTransportFailure = formatWslShellTransportFailureReason(build.transportFailure);
829 if (buildTransportFailure !== null) {
830 return {
831 ok: false,
832 reason: buildTransportFailure,
833 fatal: false,
834 retryLimit: BUILD_TRANSPORT_RETRY_LIMIT,
835 } as const;
836 }
837 if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
838 const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500);
839 return {
840 ok: false,
841 reason: `node-pty Linux build failed (exit ${build.exitCode}): ${trimmedTail || "no stderr captured"}`,
842 fatal: true,
843 } as const;
844 });
845
846const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(function* (
847 distro: string | null,
848 archive: WslRuntimeArchive,
849 windowsToWslPath: (
850 distro: string | null,
851 windowsPath: string,
852 ) => Effect.Effect<Option.Option<string>>,
853): Effect.fn.Return<PrepareWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> {
854 const linuxArchivePath = yield* windowsToWslPath(distro, archive.windowsPath);
855 if (Option.isNone(linuxArchivePath)) {
856 return {
857 ok: false,
858 reason: `wslpath conversion failed for ${archive.windowsPath}`,
859 } as const;
860 }
861
862 const install = yield* runWslShell(
863 distro,
864 buildWslRuntimeInstallScript(linuxArchivePath.value, archive.runtimeId, archive.sha256),
865 RUNTIME_INSTALL_TIMEOUT,
866 { resolveNode: false },
867 );
868 if (install.transportFailure !== null) {
869 return {
870 ok: false,
871 reason:
872 install.transportFailure === "timeout"
873 ? "WSL runtime installation timed out. Check that the distro has free disk space, then retry."
874 : "WSL runtime installation lost communication with wsl.exe. Retry, or check that the distro is healthy.",
875 } as const;
876 }
877 if (install.exitCode !== 0) {
878 const trimmedTail = `${install.stdout}${install.stderr}`.trim().slice(-500);
879 return {
880 ok: false,
881 reason: `WSL runtime installation failed (exit ${install.exitCode}): ${trimmedTail || "no stderr captured"}`,
882 } as const;
883 }
884
885 const linuxAppRoot = parseWslRuntimeRoot(install.stdout);
886 return linuxAppRoot === null
887 ? {
888 ok: false,
889 reason: "WSL runtime installation completed without reporting its cache path.",
890 }
891 : { ok: true, linuxAppRoot };
892});
893
894const pruneWslRuntimesImpl = Effect.fn("desktop.wsl.pruneRuntimesImpl")(function* (
895 distro: string | null,
896 runtimeId: string,
897): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
898 const result = yield* runWslShell(
899 distro,
900 buildWslRuntimePruneScript(runtimeId),
901 RUNTIME_PRUNE_TIMEOUT,
902 { resolveNode: false },
903 );
904 if (result.transportFailure === null && result.exitCode === 0) return;
905
906 const detail = `${result.stdout}${result.stderr}`.trim().slice(-500);
907 yield* Effect.logWarning("Could not prune old WSL runtime caches.", {
908 distro,
909 runtimeId,
910 detail: detail || `exit ${result.exitCode}`,
911 });
912});
913
914const invalidateWslRuntimeImpl = Effect.fn("desktop.wsl.invalidateRuntimeImpl")(function* (
915 distro: string | null,
916 runtimeId: string,
917): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
918 const result = yield* runWslShell(
919 distro,
920 buildWslRuntimeInvalidateScript(runtimeId),
921 RUNTIME_INVALIDATE_TIMEOUT,
922 { resolveNode: false },
923 );
924 if (result.transportFailure === null && result.exitCode === 0) return;
925
926 const detail = `${result.stdout}${result.stderr}`.trim().slice(-500);
927 // Best effort: the caller has already fallen back to the mounted tree, so a
928 // failure here only costs the reinstall that would have repaired the cache.
929 yield* Effect.logWarning("Could not invalidate the staged WSL runtime cache.", {
930 distro,
931 runtimeId,
932 detail: detail || `exit ${result.exitCode}`,
933 });
934});
935
936export const probeWslDistros: Effect.Effect<
937 readonly WslDistro[],
938 DesktopWslDistroListError,
939 ChildProcessSpawner.ChildProcessSpawner
940> = Effect.scoped(
941 Effect.gen(function* () {
942 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
943 const command = ChildProcess.make("wsl.exe", ["--list", "--verbose"], {
944 stdin: "ignore",
945 stdout: "pipe",
946 stderr: "ignore",
947 killSignal: "SIGTERM",
948 forceKillAfter: PROCESS_TERMINATE_GRACE,
949 });
950 const handle = yield* spawner.spawn(command);
951 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
952 const exitCode = yield* handle.exitCode;
953 if ((exitCode as unknown as number) !== 0) {
954 return yield* new DesktopWslDistroListError({
955 reason: `wsl.exe --list --verbose exited with code ${String(exitCode)}`,
956 });
957 }
958 return parseWslDistroList(Buffer.from(concatChunks(stdoutBytes)));
959 }),
960).pipe(
961 Effect.mapError((error) =>
962 isDesktopWslDistroListError(error)
963 ? error
964 : new DesktopWslDistroListError({
965 reason: `Failed to run wsl.exe --list --verbose: ${error.message}`,
966 }),
967 ),
968 Effect.timeoutOption(LIST_TIMEOUT),
969 Effect.flatMap(
970 Option.match({
971 onNone: () =>
972 new DesktopWslDistroListError({
973 reason: "wsl.exe --list --verbose timed out",
974 }),
975 onSome: Effect.succeed,
976 }),
977 ),
978);
979
980const preWarmImpl = (
981 distro: string | null,
982): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> =>
983 Effect.scoped(
984 Effect.gen(function* () {
985 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
986 const command = ChildProcess.make("wsl.exe", [...buildDistroArgs(distro), "--", "true"], {
987 stdin: "ignore",
988 stdout: "ignore",
989 stderr: "ignore",
990 killSignal: "SIGTERM",
991 forceKillAfter: PROCESS_TERMINATE_GRACE,
992 });
993 const handle = yield* spawner.spawn(command);
994 yield* handle.exitCode;
995 }),
996 ).pipe(
997 Effect.timeoutOption(PRE_WARM_TIMEOUT),
998 Effect.asVoid,
999 Effect.catch(() => Effect.void),
1000 );
1001
1002const windowsToWslPathImpl = (
1003 distro: string | null,
1004 windowsPath: string,
1005): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> => {
1006 // wsl.exe interprets backslashes as escape chars; normalize to forward slashes.
1007 const normalized = windowsPath.replaceAll("\\", "/");
1008 return Effect.scoped(
1009 Effect.gen(function* () {
1010 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1011 const command = ChildProcess.make(
1012 "wsl.exe",
1013 [...buildDistroArgs(distro), "--", "wslpath", "-u", normalized],
1014 {
1015 stdin: "ignore",
1016 stdout: "pipe",
1017 stderr: "ignore",
1018 killSignal: "SIGTERM",
1019 forceKillAfter: PROCESS_TERMINATE_GRACE,
1020 },
1021 );
1022 const handle = yield* spawner.spawn(command);
1023 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
1024 const exitCode = yield* handle.exitCode;
1025 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
1026 const converted = decodeUtf8(concatChunks(stdoutBytes)).trim();
1027 return converted.length > 0 ? Option.some(converted) : Option.none<string>();
1028 }),
1029 ).pipe(
1030 Effect.timeoutOption(WSLPATH_TIMEOUT),
1031 Effect.map(Option.flatten),
1032 Effect.orElseSucceed(() => Option.none<string>()),
1033 );
1034};
1035
1036const IPV4_PATTERN = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
1037
1038const getDistroIpImpl = (
1039 distro: string | null,
1040): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
1041 Effect.scoped(
1042 Effect.gen(function* () {
1043 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1044 // `hostname -I` prints a space-separated list of all non-loopback
1045 // IPs the distro has bound. The first entry on the WSL2 default
1046 // network is always the eth0 vEthernet address Windows can reach
1047 // directly (no wslhost forwarding required).
1048 const command = ChildProcess.make(
1049 "wsl.exe",
1050 [...buildDistroArgs(distro), "--", "sh", "-c", "hostname -I"],
1051 {
1052 stdin: "ignore",
1053 stdout: "pipe",
1054 stderr: "ignore",
1055 killSignal: "SIGTERM",
1056 forceKillAfter: PROCESS_TERMINATE_GRACE,
1057 },
1058 );
1059 const handle = yield* spawner.spawn(command);
1060 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
1061 const exitCode = yield* handle.exitCode;
1062 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
1063 const raw = decodeUtf8(concatChunks(stdoutBytes)).trim();
1064 const candidate = raw.split(/\s+/).find((part) => IPV4_PATTERN.test(part));
1065 return candidate ? Option.some(candidate) : Option.none<string>();
1066 }),
1067 ).pipe(
1068 Effect.timeoutOption(USER_HOME_TIMEOUT),
1069 Effect.map(Option.flatten),
1070 Effect.orElseSucceed(() => Option.none<string>()),
1071 );
1072
1073const getUserHomeImpl = (
1074 distro: string | null,
1075): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
1076 Effect.scoped(
1077 Effect.gen(function* () {
1078 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1079 const command = ChildProcess.make(
1080 "wsl.exe",
1081 // printf so there's no trailing newline noise; getent so we get the
1082 // real home from /etc/passwd even if $HOME is unset for some reason.
1083 [
1084 ...buildDistroArgs(distro),
1085 "--",
1086 "sh",
1087 "-c",
1088 'printf "%s" "$(getent passwd "$(id -un)" | cut -d: -f6)"',
1089 ],
1090 {
1091 stdin: "ignore",
1092 stdout: "pipe",
1093 stderr: "ignore",
1094 killSignal: "SIGTERM",
1095 forceKillAfter: PROCESS_TERMINATE_GRACE,
1096 },
1097 );
1098 const handle = yield* spawner.spawn(command);
1099 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
1100 const exitCode = yield* handle.exitCode;
1101 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
1102 const home = decodeUtf8(concatChunks(stdoutBytes)).trim();
1103 return home.startsWith("/") ? Option.some(home) : Option.none<string>();
1104 }),
1105 ).pipe(
1106 Effect.timeoutOption(USER_HOME_TIMEOUT),
1107 Effect.map(Option.flatten),
1108 Effect.orElseSucceed(() => Option.none<string>()),
1109 );
1110
1111const makeIsAvailable = (
1112 platform: NodeJS.Platform,
1113 windir: string,
1114): Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path> =>
1115 Effect.gen(function* () {
1116 if (platform !== "win32") return false;
1117 const path = yield* Path.Path;
1118 const fileSystem = yield* FileSystem.FileSystem;
1119 const wslExePath = path.join(windir, "System32", "wsl.exe");
1120 return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));
1121 });
1122
1123export interface DesktopWslEnvironmentTestStub {
1124 readonly isAvailable?: boolean;
1125 readonly distros?: ReadonlyArray<WslDistro>;
1126 readonly distroListError?: DesktopWslDistroListError;
1127 readonly windowsToWslPath?: (distro: string | null, windowsPath: string) => Option.Option<string>;
1128 readonly getUserHome?: (distro: string | null) => Option.Option<string>;
1129 readonly getDistroIp?: (distro: string | null) => Option.Option<string>;
1130 readonly prepareRuntime?: (
1131 distro: string | null,
1132 archive: WslRuntimeArchive,
1133 ) => PrepareWslRuntimeResult;
1134 readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
1135 readonly invalidateRuntime?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
1136 readonly ensureNodePty?: (
1137 distro: string | null,
1138 linuxAppRoot: string,
1139 options?: EnsureWslNodePtyOptions,
1140 ) => EnsureWslNodePtyResult;
1141}
1142
1143export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
1144 const probeDistros = stub.distroListError
1145 ? Effect.fail(stub.distroListError)
1146 : Effect.succeed(stub.distros ?? []);
1147 return Layer.succeed(
1148 DesktopWslEnvironment,
1149 DesktopWslEnvironment.of({
1150 isAvailable: Effect.succeed(stub.isAvailable ?? false),
1151 listDistros: probeDistros.pipe(Effect.orElseSucceed(() => [])),
1152 probeDistros,
1153 preWarm: () => Effect.void,
1154 windowsToWslPath: (distro, windowsPath) =>
1155 Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none()),
1156 getUserHome: (distro) => Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>()),
1157 getDistroIp: (distro) => Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>()),
1158 prepareRuntime: (distro, archive) =>
1159 Effect.succeed(
1160 stub.prepareRuntime?.(distro, archive) ?? {
1161 ok: false,
1162 reason: "prepareRuntime stub not configured",
1163 },
1164 ),
1165 pruneRuntimes: (distro, runtimeId) => stub.pruneRuntimes?.(distro, runtimeId) ?? Effect.void,
1166 invalidateRuntime: (distro, runtimeId) =>
1167 stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void,
1168 ensureNodePty: (distro, linuxAppRoot, options) =>
1169 Effect.succeed(
1170 stub.ensureNodePty?.(distro, linuxAppRoot, options) ?? {
1171 ok: false,
1172 reason: "ensureNodePty stub not configured",
1173 fatal: true,
1174 },
1175 ),
1176 }),
1177 );
1178};
1179
1180export const layer = Layer.effect(
1181 DesktopWslEnvironment,
1182 Effect.gen(function* () {
1183 const environment = yield* DesktopEnvironment.DesktopEnvironment;
1184 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1185 const fileSystem = yield* FileSystem.FileSystem;
1186 const windir = process.env.WINDIR ?? "C:\\Windows";
1187
1188 const provideSpawner = <A, E>(
1189 effect: Effect.Effect<A, E, ChildProcessSpawner.ChildProcessSpawner>,
1190 ): Effect.Effect<A, E> =>
1191 effect.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
1192
1193 // Probe wsl.exe once at layer init and cache the result, exposing
1194 // `isAvailable` as a resolved value rather than a re-running effect.
1195 // WSL availability is effectively static for the process lifetime — the
1196 // Windows feature isn't added/removed mid-session, and backend mode
1197 // changes already require an app restart — so the cached boolean stays
1198 // accurate. Crucially this keeps `isAvailable` synchronously resolvable:
1199 // it's read inside the sync IPC handler getLocalEnvironmentBootstraps
1200 // (via the primary instance's lazy label -> resolvePrimaryLabel ->
1201 // describePrimary). The underlying probe does a filesystem `exists`
1202 // check, so leaving it as a live effect would make Effect.runSync throw
1203 // there and break the renderer's synchronous bootstrap path.
1204 const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe(
1205 Effect.provideService(FileSystem.FileSystem, fileSystem),
1206 Effect.provideService(Path.Path, environment.path),
1207 Effect.withSpan("desktop.wsl.isAvailable"),
1208 );
1209 const isAvailable = Effect.succeed(wslAvailable);
1210
1211 const windowsToWslPath = (distro: string | null, windowsPath: string) =>
1212 provideSpawner(windowsToWslPathImpl(distro, windowsPath)).pipe(
1213 Effect.withSpan("desktop.wsl.windowsToWslPath"),
1214 );
1215
1216 // Cache user-home results per distro key — folder picker can be opened
1217 // many times in a session and the value is stable for the life of the
1218 // distro. Negative results aren't cached so a transient wsl.exe failure
1219 // doesn't permanently disable tilde expansion.
1220 const userHomeCache = new Map<string, string>();
1221 const getUserHome = (distro: string | null) =>
1222 Effect.gen(function* () {
1223 const key = distro ?? "__default__";
1224 const cached = userHomeCache.get(key);
1225 if (cached !== undefined) return Option.some(cached);
1226 const resolved = yield* provideSpawner(getUserHomeImpl(distro));
1227 if (Option.isSome(resolved)) userHomeCache.set(key, resolved.value);
1228 return resolved;
1229 }).pipe(Effect.withSpan("desktop.wsl.getUserHome"));
1230
1231 const getDistroIp = (distro: string | null) =>
1232 provideSpawner(getDistroIpImpl(distro)).pipe(Effect.withSpan("desktop.wsl.getDistroIp"));
1233
1234 const probeDistros = provideSpawner(probeWslDistros).pipe(
1235 Effect.withSpan("desktop.wsl.probeDistros"),
1236 );
1237
1238 return DesktopWslEnvironment.of({
1239 isAvailable,
1240 listDistros: probeDistros.pipe(
1241 Effect.orElseSucceed(() => []),
1242 Effect.withSpan("desktop.wsl.listDistros"),
1243 ),
1244 probeDistros,
1245 preWarm: (distro) =>
1246 provideSpawner(preWarmImpl(distro)).pipe(Effect.withSpan("desktop.wsl.preWarm")),
1247 windowsToWslPath,
1248 getUserHome,
1249 getDistroIp,
1250 prepareRuntime: (distro, archive) =>
1251 provideSpawner(prepareWslRuntimeImpl(distro, archive, windowsToWslPath)).pipe(
1252 Effect.withSpan("desktop.wsl.prepareRuntime"),
1253 ),
1254 pruneRuntimes: (distro, runtimeId) =>
1255 provideSpawner(pruneWslRuntimesImpl(distro, runtimeId)).pipe(
1256 Effect.withSpan("desktop.wsl.pruneRuntimes"),
1257 ),
1258 invalidateRuntime: (distro, runtimeId) =>
1259 provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId)).pipe(
1260 Effect.withSpan("desktop.wsl.invalidateRuntime"),
1261 ),
1262 ensureNodePty: (distro, linuxAppRoot, options) =>
1263 provideSpawner(ensureNodePtyImpl(distro, linuxAppRoot, options)).pipe(
1264 Effect.withSpan("desktop.wsl.ensureNodePty"),
1265 ),
1266 });
1267 }),
1268);