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

DesktopWslEnvironment.ts

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