Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Path from "effect/Path";
8import * as Schema from "effect/Schema";
9import * as Stream from "effect/Stream";
10import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
11
12import { buildRemoteNodeEnvScript } from "@t3tools/ssh/tunnel";
13import { satisfiesSemverRange } from "@t3tools/shared/semver";
14
15import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
16import { parseWslDistroList, type WslDistro } from "./wslPathParsing.ts";
17
18const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
19const LIST_TIMEOUT = Duration.seconds(8);
20const PRE_WARM_TIMEOUT = Duration.seconds(10);
21const WSLPATH_TIMEOUT = Duration.seconds(10);
22const PROBE_TIMEOUT = Duration.seconds(10);
23const TOOLCHAIN_TIMEOUT = Duration.seconds(10);
24const BUILD_TIMEOUT = Duration.minutes(5);
25const USER_HOME_TIMEOUT = Duration.seconds(5);
26const TCP_PORT_ALLOCATION_TIMEOUT = Duration.seconds(5);
27const TOOLCHAIN_TRANSPORT_RETRY_LIMIT = 12;
28const BUILD_TRANSPORT_RETRY_LIMIT = 2;
29
30export interface EnsureWslNodePtyOptions {
31 readonly allowBuild?: boolean;
32 readonly nodeEngineRange?: string | null;
33 // Packaged Windows builds provide an ABI-audited Linux Node executable. The
34 // preflight copies it from the Windows resource mount into a per-distro Linux
35 // cache and uses that exact runtime instead of requiring user-managed Node.
36 readonly bundledNodeWindowsPath?: string | null;
37}
38
39export type EnsureWslNodePtyResult =
40 | {
41 readonly ok: true;
42 readonly nodePath: string;
43 readonly resolvedPath: string;
44 }
45 | {
46 readonly ok: false;
47 readonly reason: string;
48 readonly fatal: boolean;
49 readonly retryLimit?: number;
50 };
51
52export type WslTcpPortAllocationResult =
53 | {
54 readonly ok: true;
55 readonly port: number;
56 readonly usedEphemeralFallback: boolean;
57 }
58 | {
59 readonly ok: false;
60 readonly reason: string;
61 };
62
63export class DesktopWslDistroListError extends Schema.TaggedErrorClass<DesktopWslDistroListError>()(
64 "DesktopWslDistroListError",
65 { reason: Schema.String },
66) {
67 override get message(): string {
68 return this.reason;
69 }
70}
71
72const isDesktopWslDistroListError = Schema.is(DesktopWslDistroListError);
73
74export class DesktopWslEnvironment extends Context.Service<
75 DesktopWslEnvironment,
76 {
77 readonly isAvailable: Effect.Effect<boolean>;
78 // Best-effort enumeration for renderer UX. Backend health checks must use
79 // probeDistros so a transient command failure is not mistaken for a
80 // successful empty installation.
81 readonly listDistros: Effect.Effect<readonly WslDistro[]>;
82 readonly probeDistros: Effect.Effect<readonly WslDistro[], DesktopWslDistroListError>;
83 readonly preWarm: (distro: string | null) => Effect.Effect<void>;
84 readonly windowsToWslPath: (
85 distro: string | null,
86 windowsPath: string,
87 ) => Effect.Effect<Option.Option<string>>;
88 // Resolves the user's Linux home dir inside the chosen distro (e.g.
89 // "/home/josh"). Used by the folder picker to expand `~` correctly.
90 readonly getUserHome: (distro: string | null) => Effect.Effect<Option.Option<string>>;
91 // Resolves the WSL distro's IPv4 address on the WSL vEthernet adapter
92 // (e.g. "172.x.x.x"). The orchestrator uses this for the WSL backend's
93 // httpBaseUrl so the renderer can reach it without relying on wslhost's
94 // localhost→WSL automatic forwarding, which is flaky in practice
95 // (the backend can be listening for 30+ seconds before wslhost starts
96 // forwarding 127.0.0.1:port to WSL-side localhost).
97 readonly getDistroIp: (distro: string | null) => Effect.Effect<Option.Option<string>>;
98 // Select/check the backend TCP port inside the concrete WSL distro — the
99 // Linux process that will own the real listener. `fallbackToEphemeral`
100 // keeps a preferred port when it is actually free in Linux, but lets the
101 // Linux kernel select a replacement when that preferred port is occupied.
102 // WSL-only mode disables the fallback because the desktop protocol still
103 // requires its configured primary port to remain stable.
104 readonly allocateTcpPort: (input: {
105 readonly distro: string;
106 readonly nodePath: string;
107 readonly host: string;
108 readonly preferredPort: number;
109 readonly fallbackToEphemeral: boolean;
110 }) => Effect.Effect<WslTcpPortAllocationResult>;
111 readonly ensureNodePty: (
112 distro: string | null,
113 windowsRepoRoot: 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
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.
177interface RunWslShellOptions {
178 readonly nodeEngineRange?: string | null;
179 readonly resolveUserNode?: boolean;
180}
181
182const runWslShell = (
183 distro: string | null,
184 bashScript: string,
185 timeout: Duration.Duration,
186 options: RunWslShellOptions = {},
187): Effect.Effect<ShellResult, never, ChildProcessSpawner.ChildProcessSpawner> => {
188 const spawner = ChildProcessSpawner.ChildProcessSpawner;
189 // -l picks up profile-managed PATH; the shared resolver covers supported
190 // version managers that non-interactive login shells can miss. -s so bash
191 // reads the script from stdin.
192 const command = ChildProcess.make(
193 "wsl.exe",
194 [...buildDistroArgs(distro), "--", "bash", "-l", "-s"],
195 {
196 stdin: Stream.encodeText(
197 Stream.make(
198 `${options.resolveUserNode === false ? "" : buildWslNodeEnvPreamble(options.nodeEngineRange)}${bashScript}`,
199 ),
200 ),
201 stdout: "pipe",
202 stderr: "pipe",
203 killSignal: "SIGTERM",
204 forceKillAfter: PROCESS_TERMINATE_GRACE,
205 },
206 );
207
208 return Effect.scoped(
209 Effect.gen(function* () {
210 const spawnerService = yield* spawner;
211 const spawnResult = yield* spawnerService.spawn(command).pipe(
212 Effect.match({
213 onFailure: (error) => ({ _tag: "Failure", error }) as const,
214 onSuccess: (handle) => ({ _tag: "Success", handle }) as const,
215 }),
216 );
217 if (spawnResult._tag === "Failure") {
218 return {
219 exitCode: 127,
220 stdout: "",
221 stderr: `\n${spawnResult.error.message}`,
222 transportFailure: "spawn",
223 } satisfies ShellResult;
224 }
225 const handle = spawnResult.handle;
226 // Drain stdout and stderr concurrently so neither pipe buffer can fill
227 // and stall the child (node-gyp rebuild emits large output on both).
228 const [stdoutBytes, stderrBytes, exitCode] = yield* Effect.all(
229 [Stream.runCollect(handle.stdout), Stream.runCollect(handle.stderr), handle.exitCode],
230 { concurrency: "unbounded" },
231 );
232 return {
233 exitCode: exitCode as unknown as number,
234 stdout: decodeUtf8(concatChunks(stdoutBytes)),
235 stderr: decodeUtf8(concatChunks(stderrBytes)),
236 transportFailure: null,
237 } satisfies ShellResult;
238 }),
239 ).pipe(
240 Effect.timeoutOption(timeout),
241 Effect.map(Option.getOrElse((): ShellResult => TIMEOUT_RESULT)),
242 Effect.catch((error) =>
243 Effect.succeed<ShellResult>({
244 exitCode: 127,
245 stdout: "",
246 stderr: `\n${error.message}`,
247 transportFailure: "process",
248 }),
249 ),
250 );
251};
252
253const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
254
255const WSL_TCP_PORT_RESULT_PREFIX = "t3code-wsl-port:";
256const WSL_TCP_PORT_ERROR_PREFIX = "t3code-wsl-port-error:";
257
258export const parseWslTcpPortAllocationOutput = (
259 stdout: string,
260): { readonly port: number; readonly usedEphemeralFallback: boolean } | null => {
261 for (const rawLine of stdout.split("\n")) {
262 const line = rawLine.trim();
263 if (!line.startsWith(WSL_TCP_PORT_RESULT_PREFIX)) continue;
264 const payload = line.slice(WSL_TCP_PORT_RESULT_PREFIX.length);
265 const match = /^(\d+):(0|1)$/.exec(payload);
266 if (match === null) return null;
267 const port = Number.parseInt(match[1] ?? "", 10);
268 if (!Number.isInteger(port) || port < 1 || port > 65_535) return null;
269 return { port, usedEphemeralFallback: match[2] === "1" };
270 }
271 return null;
272};
273
274const buildWslTcpPortAllocationScript = (input: {
275 readonly nodePath: string;
276 readonly host: string;
277 readonly preferredPort: number;
278 readonly fallbackToEphemeral: boolean;
279}): string => `${shellQuote(input.nodePath)} <<'T3CODE_WSL_PORT_NODE'
280const net = require("node:net");
281const host = ${JSON.stringify(input.host)};
282const preferredPort = ${input.preferredPort};
283const fallbackToEphemeral = ${input.fallbackToEphemeral ? "true" : "false"};
284const resultPrefix = ${JSON.stringify(WSL_TCP_PORT_RESULT_PREFIX)};
285const errorPrefix = ${JSON.stringify(WSL_TCP_PORT_ERROR_PREFIX)};
286
287function attempt(port, usedEphemeralFallback) {
288 const server = net.createServer();
289 server.once("error", (error) => {
290 if (error && error.code === "EADDRINUSE" && fallbackToEphemeral && port !== 0) {
291 attempt(0, true);
292 return;
293 }
294 const code = error && typeof error.code === "string" ? error.code : "UNKNOWN";
295 const message = error && typeof error.message === "string" ? error.message : String(error);
296 process.stderr.write(errorPrefix + code + ":" + message.replace(/[\r\n]+/g, " ") + "\n");
297 process.exitCode = 2;
298 });
299 server.listen({ host, port, exclusive: true }, () => {
300 const address = server.address();
301 if (!address || typeof address === "string") {
302 process.stderr.write(errorPrefix + "INVALID_ADDRESS:listener did not expose a TCP port\n");
303 process.exitCode = 3;
304 server.close();
305 return;
306 }
307 process.stdout.write(resultPrefix + String(address.port) + ":" + (usedEphemeralFallback ? "1" : "0") + "\n");
308 server.close();
309 });
310}
311
312attempt(preferredPort, false);
313T3CODE_WSL_PORT_NODE`;
314
315const allocateTcpPortImpl = (input: {
316 readonly distro: string;
317 readonly nodePath: string;
318 readonly host: string;
319 readonly preferredPort: number;
320 readonly fallbackToEphemeral: boolean;
321}): Effect.Effect<WslTcpPortAllocationResult, never, ChildProcessSpawner.ChildProcessSpawner> =>
322 Effect.gen(function* () {
323 if (
324 !Number.isInteger(input.preferredPort) ||
325 input.preferredPort < 1 ||
326 input.preferredPort > 65_535
327 ) {
328 return {
329 ok: false,
330 reason: `invalid preferred TCP port: ${input.preferredPort}`,
331 } as const;
332 }
333
334 const result = yield* runWslShell(
335 input.distro,
336 buildWslTcpPortAllocationScript(input),
337 TCP_PORT_ALLOCATION_TIMEOUT,
338 { resolveUserNode: false },
339 );
340 if (result.transportFailure !== null) {
341 return {
342 ok: false,
343 reason: `WSL TCP port allocation could not communicate with ${input.distro} (${result.transportFailure}).`,
344 } as const;
345 }
346 const parsed = parseWslTcpPortAllocationOutput(result.stdout);
347 if (result.exitCode === 0 && parsed !== null) {
348 return { ok: true, ...parsed } as const;
349 }
350 const detail = `${result.stdout}\n${result.stderr}`
351 .split("\n")
352 .map((line) => line.trim())
353 .find((line) => line.startsWith(WSL_TCP_PORT_ERROR_PREFIX));
354 return {
355 ok: false,
356 reason:
357 detail?.slice(WSL_TCP_PORT_ERROR_PREFIX.length) ||
358 `WSL TCP port allocation failed in ${input.distro} (exit ${result.exitCode}).`,
359 } as const;
360 });
361
362const BUNDLED_NODE_PATH_PREFIX = "bundledNodePath:";
363const BUNDLED_NODE_VERSION_PREFIX = "bundledNodeVersion:";
364const BUNDLED_NODE_ERROR_PREFIX = "bundledNodeError:";
365
366export interface BundledWslNodePreparation {
367 readonly nodePath: string;
368 readonly nodeVersion: string;
369}
370
371export const parseBundledWslNodePreparationOutput = (
372 stdout: string,
373): BundledWslNodePreparation | null => {
374 const lines = stdout.split("\n").map((line) => line.replace(/\r$/, ""));
375 const nodePath = lines
376 .find((line) => line.startsWith(BUNDLED_NODE_PATH_PREFIX))
377 ?.slice(BUNDLED_NODE_PATH_PREFIX.length);
378 const nodeVersion = lines
379 .find((line) => line.startsWith(BUNDLED_NODE_VERSION_PREFIX))
380 ?.slice(BUNDLED_NODE_VERSION_PREFIX.length);
381 if (!nodePath || !nodePath.startsWith("/") || nodePath.includes("\0")) return null;
382 if (!nodeVersion || !/^\d+(?:\.\d+){2}(?:[-+].+)?$/.test(nodeVersion)) return null;
383 return { nodePath, nodeVersion };
384};
385
386const BUNDLED_NODE_PREP_SCRIPT = (linuxSourcePath: string) => `set -u
387source_node=${shellQuote(linuxSourcePath)}
388if [ ! -r "$source_node" ]; then
389 printf '${BUNDLED_NODE_ERROR_PREFIX}%s\n' 'PACKAGED_RUNTIME_NOT_READABLE'
390 exit 40
391fi
392if ! command -v sha256sum >/dev/null 2>&1; then
393 printf '${BUNDLED_NODE_ERROR_PREFIX}%s\n' 'SHA256SUM_NOT_FOUND'
394 exit 41
395fi
396source_sha="$(sha256sum "$source_node" 2>/dev/null | awk '{print $1}')"
397case "$source_sha" in
398 ''|*[!0-9a-fA-F]*) printf '${BUNDLED_NODE_ERROR_PREFIX}%s\n' 'SOURCE_HASH_FAILED'; exit 42 ;;
399esac
400if [ "\${#source_sha}" -ne 64 ]; then
401 printf '${BUNDLED_NODE_ERROR_PREFIX}%s\n' 'SOURCE_HASH_INVALID'
402 exit 42
403fi
404if [ -n "\${HOME:-}" ]; then
405 runtime_dir="$HOME/.cache/t3code/wsl-runtime"
406else
407 runtime_dir="/tmp/t3code-\${UID:-0}/wsl-runtime"
408fi
409if ! mkdir -p "$runtime_dir" 2>/dev/null; then
410 runtime_dir="/tmp/t3code-\${UID:-0}/wsl-runtime"
411 mkdir -p "$runtime_dir" || { printf '${BUNDLED_NODE_ERROR_PREFIX}%s\n' 'CACHE_CREATE_FAILED'; exit 43; }
412fi
413target="$runtime_dir/node-$source_sha"
414needs_copy=1
415if [ -f "$target" ]; then
416 target_sha="$(sha256sum "$target" 2>/dev/null | awk '{print $1}')"
417 if [ "$target_sha" = "$source_sha" ]; then
418 needs_copy=0
419 fi
420fi
421if [ "$needs_copy" -ne 0 ]; then
422 tmp="$target.tmp.$$"
423 rm -f "$tmp"
424 cp "$source_node" "$tmp" || { rm -f "$tmp"; printf '${BUNDLED_NODE_ERROR_PREFIX}%s\n' 'COPY_FAILED'; exit 44; }
425 chmod 0755 "$tmp" || { rm -f "$tmp"; printf '${BUNDLED_NODE_ERROR_PREFIX}%s\n' 'CHMOD_FAILED'; exit 45; }
426 tmp_sha="$(sha256sum "$tmp" 2>/dev/null | awk '{print $1}')"
427 if [ "$tmp_sha" != "$source_sha" ]; then
428 rm -f "$tmp"
429 printf '${BUNDLED_NODE_ERROR_PREFIX}%s\n' 'CACHE_HASH_MISMATCH'
430 exit 46
431 fi
432 mv -f "$tmp" "$target" || { rm -f "$tmp"; printf '${BUNDLED_NODE_ERROR_PREFIX}%s\n' 'CACHE_COMMIT_FAILED'; exit 47; }
433fi
434chmod 0755 "$target" 2>/dev/null || { printf '${BUNDLED_NODE_ERROR_PREFIX}%s\n' 'CHMOD_FAILED'; exit 48; }
435final_sha="$(sha256sum "$target" 2>/dev/null | awk '{print $1}')"
436if [ "$final_sha" != "$source_sha" ]; then
437 printf '${BUNDLED_NODE_ERROR_PREFIX}%s\n' 'CACHE_HASH_MISMATCH'
438 exit 49
439fi
440node_version="$("$target" -p 'process.versions.node' 2>/dev/null)" || { printf '${BUNDLED_NODE_ERROR_PREFIX}%s\n' 'EXEC_FAILED'; exit 50; }
441printf '${BUNDLED_NODE_PATH_PREFIX}%s\n' "$target"
442printf '${BUNDLED_NODE_VERSION_PREFIX}%s\n' "$node_version"
443`;
444
445const NODE_PTY_PREBUILD_MISSING_EXIT_CODE = 4;
446export const MIN_WSL_GLIBC_VERSION = "2.35";
447
448const compareNumericVersion = (left: string, right: string): number => {
449 const leftParts = left.split(".").map((part) => Number.parseInt(part, 10));
450 const rightParts = right.split(".").map((part) => Number.parseInt(part, 10));
451 const count = Math.max(leftParts.length, rightParts.length);
452 for (let index = 0; index < count; index += 1) {
453 const leftPart = leftParts[index] ?? 0;
454 const rightPart = rightParts[index] ?? 0;
455 if (leftPart !== rightPart) return leftPart < rightPart ? -1 : 1;
456 }
457 return 0;
458};
459
460export const parseLibcFamily = (stdout: string): string | null => {
461 const family = stdout
462 .split("\n")
463 .map((line) => line.trim())
464 .filter((line) => line.startsWith("libcFamily:"))
465 .map((line) => line.slice("libcFamily:".length).trim().toLowerCase())
466 .find((value) => value.length > 0);
467 return family ?? null;
468};
469
470export const parseGlibcVersion = (stdout: string): string | null => {
471 const version = stdout
472 .split("\n")
473 .map((line) => line.trim())
474 .filter((line) => line.startsWith("glibcVersion:"))
475 .map((line) => line.slice("glibcVersion:".length).trim())
476 .find((value) => /^\d+(?:\.\d+)+$/.test(value));
477 return version ?? null;
478};
479
480export const formatWslLibcCompatibilityReason = (
481 distro: string | null,
482 family: string | null,
483 glibcVersion: string | null,
484): string | null => {
485 const distroLabel = distro ?? "selected WSL distro";
486 if (family === "musl") {
487 return `${distroLabel} uses musl libc, but T3 Code's packaged WSL native runtime targets GNU glibc ${MIN_WSL_GLIBC_VERSION} or newer. Use a glibc-based WSL2 distro (for example Ubuntu 22.04 or newer), then retry.`;
488 }
489 if (family === "glibc" && glibcVersion !== null) {
490 if (compareNumericVersion(glibcVersion, MIN_WSL_GLIBC_VERSION) < 0) {
491 return `${distroLabel} has GNU glibc ${glibcVersion}, but T3 Code's packaged WSL native runtime requires glibc ${MIN_WSL_GLIBC_VERSION} or newer. Upgrade this distro to a newer release or select another compatible WSL2 distro, then retry.`;
492 }
493 }
494 return null;
495};
496
497export const formatNodePtyProbeFailureReason = (exitCode: number): string | null =>
498 exitCode === NODE_PTY_PREBUILD_MISSING_EXIT_CODE
499 ? "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."
500 : null;
501
502const NODE_PTY_PROBE_SCRIPT = (
503 linuxServerDir: string,
504 exactNodePath: string | null,
505) => `libc_family=unknown
506glibc_version=
507glibc_report="$(getconf GNU_LIBC_VERSION 2>/dev/null || true)"
508case "$glibc_report" in
509 glibc\ *) libc_family=glibc; glibc_version="$(printf '%s\\n' "$glibc_report" | cut -d' ' -f2)" ;;
510 *)
511 ldd_banner="$(ldd --version 2>&1 | head -n 1 || true)"
512 case "$ldd_banner" in *musl*|*Musl*) libc_family=musl ;; esac
513 ;;
514esac
515printf 'libcFamily:%s\\n' "$libc_family"
516printf 'glibcVersion:%s\\n' "$glibc_version"
517node_path=${exactNodePath === null ? '"$(command -v node 2>/dev/null)"' : shellQuote(exactNodePath)}
518printf 'nodePath:%s\\n' "$node_path"
519printf 'resolvedPath:%s\\n' "$PATH"
520if [ -z "$node_path" ]; then
521 printf 'nodeVersion:\n'
522 exit 127
523fi
524printf 'nodeVersion:%s\\n' "$("$node_path" -p 'process.versions.node' 2>/dev/null)"
525cd ${shellQuote(linuxServerDir)} && "$node_path" <<'NODE' >/dev/null 2>&1
526// The server bundle externalizes its deps to node_modules, and the WSL Node
527// can't read inside app.asar, so confirm those deps are unpacked on the real
528// filesystem before reporting the backend healthy. "effect" is the framework
529// every server module imports; resolving it validates the whole node_modules
530// tree. Exit 3 marks this distinct from a node-pty problem so the caller can
531// report it accurately instead of letting the server crash on
532// ERR_MODULE_NOT_FOUND at launch (which, in wsl-only mode, would just fail to
533// launch with no fallback).
534try { require.resolve("effect"); } catch (_e) { process.exit(3); }
535const fs = require("node:fs");
536const path = require("node:path");
537const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
538// node-pty 1.x is N-API based, so a single Linux pty.node is ABI-stable across
539// Node versions. require() succeeding is the compatibility test.
540const expected = {
541 arch: process.arch,
542 nodePtyVersion: require("node-pty/package.json").version,
543};
544const prebuildDir = path.join(pkgDir, "prebuilds", "linux-" + process.arch);
545const marker = path.join(prebuildDir, "t3code-wsl-node-pty.json");
546const binary = path.join(prebuildDir, "pty.node");
547if (!fs.existsSync(marker) || !fs.existsSync(binary)) process.exit(${NODE_PTY_PREBUILD_MISSING_EXIT_CODE});
548require("node-pty");
549const actual = JSON.parse(fs.readFileSync(marker, "utf8"));
550for (const key of Object.keys(expected)) {
551 if (actual[key] !== expected[key]) process.exit(2);
552}
553NODE`;
554
555const TOOLCHAIN_CHECK_SCRIPT = [
556 "for tool in node make g++ python3; do",
557 ' command -v "$tool" >/dev/null 2>&1 || echo "missing:$tool"',
558 "done",
559 "if command -v node >/dev/null 2>&1; then",
560 ` ver="$(node -p 'process.versions.node' 2>/dev/null)"`,
561 ' if [ -n "$ver" ]; then printf "nodeVersion:%s\\n" "$ver"; fi',
562 "fi",
563].join("\n");
564
565const NODE_PTY_BUILD_SCRIPT = (linuxServerDir: string) =>
566 [
567 "set -e",
568 `cd ${shellQuote(linuxServerDir)}`,
569 `pkg_dir=$(node -p "require('node:path').dirname(require.resolve('node-pty/package.json'))")`,
570 `arch=$(node -p "process.arch")`,
571 `modules=$(node -p "process.versions.modules")`,
572 `node_pty_version=$(node -p "require('node-pty/package.json').version")`,
573 `cd "$pkg_dir"`,
574 "npx --yes node-gyp rebuild",
575 `prebuild_dir="prebuilds/linux-$arch"`,
576 `mkdir -p "$prebuild_dir"`,
577 `cp build/Release/pty.node "$prebuild_dir/pty.node"`,
578 `printf '{"arch":"%s","modules":"%s","nodePtyVersion":"%s"}\\n' "$arch" "$modules" "$node_pty_version" > "$prebuild_dir/t3code-wsl-node-pty.json"`,
579 `node -e 'require("node-pty")'`,
580 ].join("\n");
581
582export interface ToolchainReport {
583 readonly missingTools: ReadonlyArray<string>;
584 readonly nodeVersion: string | null;
585}
586
587export const parseToolchainReport = (stdout: string): ToolchainReport => {
588 const lines = stdout
589 .split("\n")
590 .map((line) => line.trim())
591 .filter((line) => line.length > 0);
592 const missingTools = lines
593 .filter((line) => line.startsWith("missing:"))
594 .map((line) => line.slice("missing:".length));
595 const nodeVersionLine = lines.find((line) => line.startsWith("nodeVersion:"));
596 const nodeVersion = nodeVersionLine
597 ? nodeVersionLine.slice("nodeVersion:".length).trim() || null
598 : null;
599 return { missingTools, nodeVersion };
600};
601
602// Pulls the absolute node path the WSL distro resolved after the shared remote
603// resolver repaired PATH. Returns null when no node was found, which the caller
604// turns into an actionable "install Node" message instead of a confusing
605// node-pty error.
606export const parseNodePath = (stdout: string): string | null => {
607 const path = stdout
608 .split("\n")
609 .map((line) => line.trim())
610 .filter((line) => line.startsWith("nodePath:"))
611 .map((line) => line.slice("nodePath:".length).trim())
612 .find((value) => value.length > 0);
613 return path ?? null;
614};
615
616export const parseNodeVersion = (stdout: string): string | null => {
617 const version = stdout
618 .split("\n")
619 .map((line) => line.trim())
620 .filter((line) => line.startsWith("nodeVersion:"))
621 .map((line) => line.slice("nodeVersion:".length).trim())
622 .find((value) => value.length > 0);
623 return version ?? null;
624};
625
626// Captures the login-shell PATH after the shared resolver has loaded version
627// managers. Preserve the value byte-for-byte apart from a Windows-style CR so
628// paths containing spaces or apostrophes can be forwarded as one env argv.
629export const parseResolvedPath = (stdout: string): string | null => {
630 const prefix = "resolvedPath:";
631 const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));
632 if (line === undefined) return null;
633 const resolvedPath = line.slice(prefix.length).replace(/\r$/, "");
634 return resolvedPath.length > 0 ? resolvedPath : null;
635};
636
637export const formatMissingToolsReason = (
638 report: ToolchainReport,
639 requiredRange: string | null,
640): string | null => {
641 const nodeMissing = report.missingTools.includes("node");
642 const nodeOutOfRange =
643 !nodeMissing &&
644 requiredRange !== null &&
645 report.nodeVersion !== null &&
646 !satisfiesSemverRange(report.nodeVersion, requiredRange);
647 const buildToolsMissing = report.missingTools.filter((tool) => tool !== "node");
648
649 if (!nodeMissing && !nodeOutOfRange && buildToolsMissing.length === 0) {
650 return null;
651 }
652
653 const issues: string[] = [];
654 const remediations: string[] = [];
655
656 if (nodeMissing) {
657 issues.push("node");
658 remediations.push(
659 `Node.js${requiredRange ? ` satisfying \`${requiredRange}\`` : " 18+"} (e.g. via nvm)`,
660 );
661 } else if (nodeOutOfRange) {
662 issues.push(`node ${report.nodeVersion} (requires ${requiredRange})`);
663 remediations.push(
664 `a newer Node.js satisfying \`${requiredRange}\` (e.g. \`nvm install 24 && nvm alias default 24\`)`,
665 );
666 }
667
668 if (buildToolsMissing.length > 0) {
669 issues.push(...buildToolsMissing);
670 remediations.push(
671 "the build toolchain (e.g. `sudo apt install -y build-essential python3` on Ubuntu/Debian)",
672 );
673 }
674
675 return `WSL distro is missing required tools: ${issues.join(", ")}. Install ${remediations.join(" and ")}, then retry.`;
676};
677
678const ensureNodePtyImpl = (
679 distro: string | null,
680 windowsRepoRoot: string,
681 windowsToWslPath: (
682 distro: string | null,
683 windowsPath: string,
684 ) => Effect.Effect<Option.Option<string>>,
685 options: EnsureWslNodePtyOptions = {},
686): Effect.Effect<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> =>
687 Effect.gen(function* () {
688 const linuxRepoRootOption = yield* windowsToWslPath(distro, windowsRepoRoot);
689 if (Option.isNone(linuxRepoRootOption)) {
690 return {
691 ok: false,
692 reason: `wslpath conversion failed for ${windowsRepoRoot}`,
693 fatal: false,
694 } as const;
695 }
696 const linuxRepoRoot = linuxRepoRootOption.value;
697 // node-pty lives in the apps/server workspace's node_modules; resolve from
698 // there rather than the monorepo root, where Bun's hoist layout omits it.
699 const linuxServerDir = `${linuxRepoRoot}/apps/server`;
700
701 let bundledNodePath: string | null = null;
702 if (options.bundledNodeWindowsPath) {
703 const bundledSource = yield* windowsToWslPath(distro, options.bundledNodeWindowsPath);
704 if (Option.isNone(bundledSource)) {
705 return {
706 ok: false,
707 reason: `wslpath conversion failed for bundled Node runtime ${options.bundledNodeWindowsPath}`,
708 fatal: false,
709 } as const;
710 }
711 const prepared = yield* runWslShell(
712 distro,
713 BUNDLED_NODE_PREP_SCRIPT(bundledSource.value),
714 PROBE_TIMEOUT,
715 { resolveUserNode: false },
716 );
717 const prepareTransportFailure = formatWslShellTransportFailureReason(prepared.transportFailure);
718 if (prepareTransportFailure !== null) {
719 return { ok: false, reason: prepareTransportFailure, fatal: false } as const;
720 }
721 const parsedPreparation = parseBundledWslNodePreparationOutput(prepared.stdout);
722 if (prepared.exitCode !== 0 || parsedPreparation === null) {
723 const detail = `${prepared.stdout}\n${prepared.stderr}`
724 .split("\n")
725 .map((line) => line.trim())
726 .find((line) => line.startsWith(BUNDLED_NODE_ERROR_PREFIX));
727 return {
728 ok: false,
729 reason: `The packaged WSL Node runtime could not be prepared inside ${distro ?? "the selected distro"}${detail ? ` (${detail.slice(BUNDLED_NODE_ERROR_PREFIX.length)})` : ""}. Reinstall T3 Code or check that the distro can read the Windows installation and write to its Linux cache directory.`,
730 fatal: true,
731 } as const;
732 }
733 bundledNodePath = parsedPreparation.nodePath;
734 if (
735 options.nodeEngineRange &&
736 !satisfiesSemverRange(parsedPreparation.nodeVersion, options.nodeEngineRange.trim())
737 ) {
738 return {
739 ok: false,
740 reason: `Packaged WSL Node.js ${parsedPreparation.nodeVersion} does not satisfy the server's required engine range (${options.nodeEngineRange.trim()}). This build is internally inconsistent; please report it.`,
741 fatal: true,
742 } as const;
743 }
744 }
745
746 const probe = yield* runWslShell(
747 distro,
748 NODE_PTY_PROBE_SCRIPT(linuxServerDir, bundledNodePath),
749 PROBE_TIMEOUT,
750 {
751 nodeEngineRange: options.nodeEngineRange,
752 resolveUserNode: bundledNodePath === null,
753 },
754 );
755 const nodePath = parseNodePath(probe.stdout);
756 const resolvedPath = parseResolvedPath(probe.stdout);
757 const libcFamily = parseLibcFamily(probe.stdout);
758 const glibcVersion = parseGlibcVersion(probe.stdout);
759
760 const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
761 if (transportFailureReason !== null) {
762 return {
763 ok: false,
764 reason: transportFailureReason,
765 fatal: false,
766 } as const;
767 }
768
769 const libcCompatibilityReason = formatWslLibcCompatibilityReason(
770 distro,
771 libcFamily,
772 glibcVersion,
773 );
774 if (libcCompatibilityReason !== null) {
775 return {
776 ok: false,
777 reason: libcCompatibilityReason,
778 fatal: true,
779 } as const;
780 }
781
782 // No node at all, even after the shared resolver repaired PATH. Surface
783 // the specific, actionable toolchain message rather than a confusing
784 // node-pty error, and don't try to build.
785 if (nodePath === null) {
786 const toolchainCheck = yield* runWslShell(
787 distro,
788 TOOLCHAIN_CHECK_SCRIPT,
789 TOOLCHAIN_TIMEOUT,
790 { nodeEngineRange: options.nodeEngineRange, resolveUserNode: true },
791 );
792 const toolchainTransportFailure = formatWslShellTransportFailureReason(
793 toolchainCheck.transportFailure,
794 );
795 if (toolchainTransportFailure !== null) {
796 return {
797 ok: false,
798 reason: toolchainTransportFailure,
799 fatal: false,
800 retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
801 } as const;
802 }
803 const report = parseToolchainReport(toolchainCheck.stdout);
804 const reason =
805 formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null) ??
806 "Node.js was not found in the WSL distro. Install it (e.g. via nvm) and restart the desktop app.";
807 return { ok: false, reason, fatal: true } as const;
808 }
809
810 if (resolvedPath === null) {
811 return {
812 ok: false,
813 reason: "WSL login-shell PATH could not be resolved during backend preflight.",
814 fatal: true,
815 } as const;
816 }
817
818 // Server dependencies (e.g. "effect") couldn't be resolved on the WSL
819 // filesystem — a packaging regression, since the server bundle needs its
820 // node_modules unpacked from the asar. Fatal so wsl-only mode falls back to
821 // Windows and dual mode surfaces the reason inline, instead of the server
822 // crash-looping on ERR_MODULE_NOT_FOUND once it actually launches.
823 if (probe.exitCode === 3) {
824 return {
825 ok: false,
826 reason:
827 "WSL server dependencies could not be loaded (for example \"effect\"). The server's bundled node_modules is not readable by the WSL distro's Node — this is a packaging problem with this build. Please report it.",
828 fatal: true,
829 } as const;
830 }
831
832 if (probe.exitCode === 0) {
833 const rawVersion = parseNodeVersion(probe.stdout);
834 if (
835 rawVersion !== null &&
836 options.nodeEngineRange &&
837 !satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())
838 ) {
839 const range = options.nodeEngineRange.trim();
840 return {
841 ok: false,
842 reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,
843 fatal: true,
844 } as const;
845 }
846 return { ok: true, nodePath, resolvedPath } as const;
847 }
848
849 if (options.allowBuild !== true) {
850 const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
851 if (packagedProbeFailure !== null) {
852 return {
853 ok: false,
854 reason: packagedProbeFailure,
855 fatal: true,
856 } as const;
857 }
858 }
859
860 // node is present but node-pty's native module didn't load.
861 const toolchainCheck = yield* runWslShell(
862 distro,
863 TOOLCHAIN_CHECK_SCRIPT,
864 TOOLCHAIN_TIMEOUT,
865 { nodeEngineRange: options.nodeEngineRange, resolveUserNode: true },
866 );
867 const toolchainTransportFailure = formatWslShellTransportFailureReason(
868 toolchainCheck.transportFailure,
869 );
870 if (toolchainTransportFailure !== null) {
871 return {
872 ok: false,
873 reason: toolchainTransportFailure,
874 fatal: false,
875 retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
876 } as const;
877 }
878 const report = parseToolchainReport(toolchainCheck.stdout);
879
880 if (options.allowBuild !== true) {
881 // Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp,
882 // or network is needed — and we must not nag the user to install build
883 // tools they don't need. Still surface a missing/too-old Node (both the
884 // prebuilt and the server require a compatible Node); otherwise reaching
885 // here means the bundled binary itself couldn't load, which is almost
886 // always an unsupported CPU architecture or incompatible system libraries.
887 const nodeOnlyReason =
888 bundledNodePath === null
889 ? formatMissingToolsReason(
890 {
891 missingTools: report.missingTools.filter((tool) => tool === "node"),
892 nodeVersion: report.nodeVersion,
893 },
894 options.nodeEngineRange?.trim() || null,
895 )
896 : null;
897 return {
898 ok: false,
899 reason:
900 nodeOnlyReason ??
901 "The bundled WSL backend native module (node-pty) could not be loaded with T3 Code's packaged Linux Node runtime. This usually means an unsupported CPU architecture or incompatible system libraries (glibc). Use a supported glibc-based WSL2 distro; if you already are, please report this with your distro and the output of `uname -m`.",
902 fatal: true,
903 } as const;
904 }
905
906 // Dev only: no prebuilt is bundled in a checkout, so compile node-pty from
907 // source. Run the toolchain check first so a missing compiler or out-of-range
908 // Node surfaces a specific, actionable message instead of an opaque node-gyp
909 // failure. Developers have the toolchain; end users never reach this path.
910 const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);
911 if (missingReason !== null) {
912 return { ok: false, reason: missingReason, fatal: true } as const;
913 }
914
915 const build = yield* runWslShell(
916 distro,
917 NODE_PTY_BUILD_SCRIPT(linuxServerDir),
918 BUILD_TIMEOUT,
919 { nodeEngineRange: options.nodeEngineRange, resolveUserNode: true },
920 );
921 const buildTransportFailure = formatWslShellTransportFailureReason(build.transportFailure);
922 if (buildTransportFailure !== null) {
923 return {
924 ok: false,
925 reason: buildTransportFailure,
926 fatal: false,
927 retryLimit: BUILD_TRANSPORT_RETRY_LIMIT,
928 } as const;
929 }
930 if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
931 const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500);
932 return {
933 ok: false,
934 reason: `node-pty Linux build failed (exit ${build.exitCode}): ${trimmedTail || "no stderr captured"}`,
935 fatal: true,
936 } as const;
937 });
938
939export const probeWslDistros: Effect.Effect<
940 readonly WslDistro[],
941 DesktopWslDistroListError,
942 ChildProcessSpawner.ChildProcessSpawner
943> = Effect.scoped(
944 Effect.gen(function* () {
945 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
946 const command = ChildProcess.make("wsl.exe", ["--list", "--verbose"], {
947 stdin: "ignore",
948 stdout: "pipe",
949 stderr: "ignore",
950 killSignal: "SIGTERM",
951 forceKillAfter: PROCESS_TERMINATE_GRACE,
952 });
953 const handle = yield* spawner.spawn(command);
954 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
955 const exitCode = yield* handle.exitCode;
956 if ((exitCode as unknown as number) !== 0) {
957 return yield* new DesktopWslDistroListError({
958 reason: `wsl.exe --list --verbose exited with code ${String(exitCode)}`,
959 });
960 }
961 return parseWslDistroList(Buffer.from(concatChunks(stdoutBytes)));
962 }),
963).pipe(
964 Effect.mapError((error) =>
965 isDesktopWslDistroListError(error)
966 ? error
967 : new DesktopWslDistroListError({
968 reason: `Failed to run wsl.exe --list --verbose: ${error.message}`,
969 }),
970 ),
971 Effect.timeoutOption(LIST_TIMEOUT),
972 Effect.flatMap(
973 Option.match({
974 onNone: () =>
975 new DesktopWslDistroListError({
976 reason: "wsl.exe --list --verbose timed out",
977 }),
978 onSome: Effect.succeed,
979 }),
980 ),
981);
982
983const preWarmImpl = (
984 distro: string | null,
985): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> =>
986 Effect.scoped(
987 Effect.gen(function* () {
988 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
989 const command = ChildProcess.make("wsl.exe", [...buildDistroArgs(distro), "--", "true"], {
990 stdin: "ignore",
991 stdout: "ignore",
992 stderr: "ignore",
993 killSignal: "SIGTERM",
994 forceKillAfter: PROCESS_TERMINATE_GRACE,
995 });
996 const handle = yield* spawner.spawn(command);
997 yield* handle.exitCode;
998 }),
999 ).pipe(
1000 Effect.timeoutOption(PRE_WARM_TIMEOUT),
1001 Effect.asVoid,
1002 Effect.catch(() => Effect.void),
1003 );
1004
1005const windowsToWslPathImpl = (
1006 distro: string | null,
1007 windowsPath: string,
1008): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> => {
1009 // wsl.exe interprets backslashes as escape chars; normalize to forward slashes.
1010 const normalized = windowsPath.replaceAll("\\", "/");
1011 return Effect.scoped(
1012 Effect.gen(function* () {
1013 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1014 const command = ChildProcess.make(
1015 "wsl.exe",
1016 [...buildDistroArgs(distro), "--", "wslpath", "-u", normalized],
1017 {
1018 stdin: "ignore",
1019 stdout: "pipe",
1020 stderr: "ignore",
1021 killSignal: "SIGTERM",
1022 forceKillAfter: PROCESS_TERMINATE_GRACE,
1023 },
1024 );
1025 const handle = yield* spawner.spawn(command);
1026 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
1027 const exitCode = yield* handle.exitCode;
1028 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
1029 const converted = decodeUtf8(concatChunks(stdoutBytes)).trim();
1030 return converted.length > 0 ? Option.some(converted) : Option.none<string>();
1031 }),
1032 ).pipe(
1033 Effect.timeoutOption(WSLPATH_TIMEOUT),
1034 Effect.map(Option.flatten),
1035 Effect.orElseSucceed(() => Option.none<string>()),
1036 );
1037};
1038
1039const IPV4_PATTERN = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
1040
1041const getDistroIpImpl = (
1042 distro: string | null,
1043): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
1044 Effect.scoped(
1045 Effect.gen(function* () {
1046 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1047 // `hostname -I` prints a space-separated list of all non-loopback
1048 // IPs the distro has bound. The first entry on the WSL2 default
1049 // network is always the eth0 vEthernet address Windows can reach
1050 // directly (no wslhost forwarding required).
1051 const command = ChildProcess.make(
1052 "wsl.exe",
1053 [...buildDistroArgs(distro), "--", "sh", "-c", "hostname -I"],
1054 {
1055 stdin: "ignore",
1056 stdout: "pipe",
1057 stderr: "ignore",
1058 killSignal: "SIGTERM",
1059 forceKillAfter: PROCESS_TERMINATE_GRACE,
1060 },
1061 );
1062 const handle = yield* spawner.spawn(command);
1063 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
1064 const exitCode = yield* handle.exitCode;
1065 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
1066 const raw = decodeUtf8(concatChunks(stdoutBytes)).trim();
1067 const candidate = raw.split(/\s+/).find((part) => IPV4_PATTERN.test(part));
1068 return candidate ? Option.some(candidate) : Option.none<string>();
1069 }),
1070 ).pipe(
1071 Effect.timeoutOption(USER_HOME_TIMEOUT),
1072 Effect.map(Option.flatten),
1073 Effect.orElseSucceed(() => Option.none<string>()),
1074 );
1075
1076const getUserHomeImpl = (
1077 distro: string | null,
1078): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
1079 Effect.scoped(
1080 Effect.gen(function* () {
1081 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1082 const command = ChildProcess.make(
1083 "wsl.exe",
1084 // printf so there's no trailing newline noise; getent so we get the
1085 // real home from /etc/passwd even if $HOME is unset for some reason.
1086 [
1087 ...buildDistroArgs(distro),
1088 "--",
1089 "sh",
1090 "-c",
1091 'printf "%s" "$(getent passwd "$(id -un)" | cut -d: -f6)"',
1092 ],
1093 {
1094 stdin: "ignore",
1095 stdout: "pipe",
1096 stderr: "ignore",
1097 killSignal: "SIGTERM",
1098 forceKillAfter: PROCESS_TERMINATE_GRACE,
1099 },
1100 );
1101 const handle = yield* spawner.spawn(command);
1102 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
1103 const exitCode = yield* handle.exitCode;
1104 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
1105 const home = decodeUtf8(concatChunks(stdoutBytes)).trim();
1106 return home.startsWith("/") ? Option.some(home) : Option.none<string>();
1107 }),
1108 ).pipe(
1109 Effect.timeoutOption(USER_HOME_TIMEOUT),
1110 Effect.map(Option.flatten),
1111 Effect.orElseSucceed(() => Option.none<string>()),
1112 );
1113
1114const makeIsAvailable = (
1115 platform: NodeJS.Platform,
1116 windir: string,
1117): Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path> =>
1118 Effect.gen(function* () {
1119 if (platform !== "win32") return false;
1120 const path = yield* Path.Path;
1121 const fileSystem = yield* FileSystem.FileSystem;
1122 const wslExePath = path.join(windir, "System32", "wsl.exe");
1123 return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));
1124 });
1125
1126export interface DesktopWslEnvironmentTestStub {
1127 readonly isAvailable?: boolean;
1128 readonly distros?: ReadonlyArray<WslDistro>;
1129 readonly distroListError?: DesktopWslDistroListError;
1130 readonly windowsToWslPath?: (distro: string | null, windowsPath: string) => Option.Option<string>;
1131 readonly getUserHome?: (distro: string | null) => Option.Option<string>;
1132 readonly getDistroIp?: (distro: string | null) => Option.Option<string>;
1133 readonly allocateTcpPort?: (input: {
1134 readonly distro: string;
1135 readonly nodePath: string;
1136 readonly host: string;
1137 readonly preferredPort: number;
1138 readonly fallbackToEphemeral: boolean;
1139 }) => WslTcpPortAllocationResult;
1140 readonly ensureNodePty?: (
1141 distro: string | null,
1142 windowsRepoRoot: string,
1143 options?: EnsureWslNodePtyOptions,
1144 ) => EnsureWslNodePtyResult;
1145}
1146
1147export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
1148 const probeDistros = stub.distroListError
1149 ? Effect.fail(stub.distroListError)
1150 : Effect.succeed(stub.distros ?? []);
1151 return Layer.succeed(
1152 DesktopWslEnvironment,
1153 DesktopWslEnvironment.of({
1154 isAvailable: Effect.succeed(stub.isAvailable ?? false),
1155 listDistros: probeDistros.pipe(Effect.orElseSucceed(() => [])),
1156 probeDistros,
1157 preWarm: () => Effect.void,
1158 windowsToWslPath: (distro, windowsPath) =>
1159 Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none()),
1160 getUserHome: (distro) => Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>()),
1161 getDistroIp: (distro) => Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>()),
1162 allocateTcpPort: (input) =>
1163 Effect.succeed(
1164 stub.allocateTcpPort?.(input) ?? {
1165 ok: true,
1166 port: input.preferredPort,
1167 usedEphemeralFallback: false,
1168 },
1169 ),
1170 ensureNodePty: (distro, windowsRepoRoot, options) =>
1171 Effect.succeed(
1172 stub.ensureNodePty?.(distro, windowsRepoRoot, options) ?? {
1173 ok: false,
1174 reason: "ensureNodePty stub not configured",
1175 fatal: true,
1176 },
1177 ),
1178 }),
1179 );
1180};
1181
1182export const layer = Layer.effect(
1183 DesktopWslEnvironment,
1184 Effect.gen(function* () {
1185 const environment = yield* DesktopEnvironment.DesktopEnvironment;
1186 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1187 const fileSystem = yield* FileSystem.FileSystem;
1188 const windir = process.env.WINDIR ?? "C:\\Windows";
1189
1190 const provideSpawner = <A, E>(
1191 effect: Effect.Effect<A, E, ChildProcessSpawner.ChildProcessSpawner>,
1192 ): Effect.Effect<A, E> =>
1193 effect.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
1194
1195 // Probe wsl.exe once at layer init and cache the result, exposing
1196 // `isAvailable` as a resolved value rather than a re-running effect.
1197 // WSL availability is effectively static for the process lifetime — the
1198 // Windows feature isn't added/removed mid-session, and backend mode
1199 // changes already require an app restart — so the cached boolean stays
1200 // accurate. Crucially this keeps `isAvailable` synchronously resolvable:
1201 // it's read inside the sync IPC handler getLocalEnvironmentBootstraps
1202 // (via the primary instance's lazy label -> resolvePrimaryLabel ->
1203 // describePrimary). The underlying probe does a filesystem `exists`
1204 // check, so leaving it as a live effect would make Effect.runSync throw
1205 // there and break the renderer's synchronous bootstrap path.
1206 const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe(
1207 Effect.provideService(FileSystem.FileSystem, fileSystem),
1208 Effect.provideService(Path.Path, environment.path),
1209 Effect.withSpan("desktop.wsl.isAvailable"),
1210 );
1211 const isAvailable = Effect.succeed(wslAvailable);
1212
1213 const windowsToWslPath = (distro: string | null, windowsPath: string) =>
1214 provideSpawner(windowsToWslPathImpl(distro, windowsPath)).pipe(
1215 Effect.withSpan("desktop.wsl.windowsToWslPath"),
1216 );
1217
1218 // Cache user-home results per distro key — folder picker can be opened
1219 // many times in a session and the value is stable for the life of the
1220 // distro. Negative results aren't cached so a transient wsl.exe failure
1221 // doesn't permanently disable tilde expansion.
1222 const userHomeCache = new Map<string, string>();
1223 const getUserHome = (distro: string | null) =>
1224 Effect.gen(function* () {
1225 const key = distro ?? "__default__";
1226 const cached = userHomeCache.get(key);
1227 if (cached !== undefined) return Option.some(cached);
1228 const resolved = yield* provideSpawner(getUserHomeImpl(distro));
1229 if (Option.isSome(resolved)) userHomeCache.set(key, resolved.value);
1230 return resolved;
1231 }).pipe(Effect.withSpan("desktop.wsl.getUserHome"));
1232
1233 const getDistroIp = (distro: string | null) =>
1234 provideSpawner(getDistroIpImpl(distro)).pipe(Effect.withSpan("desktop.wsl.getDistroIp"));
1235
1236 const allocateTcpPort: DesktopWslEnvironment["Service"]["allocateTcpPort"] = (input) =>
1237 provideSpawner(allocateTcpPortImpl(input)).pipe(
1238 Effect.withSpan("desktop.wsl.allocateTcpPort", {
1239 attributes: {
1240 distro: input.distro,
1241 host: input.host,
1242 preferredPort: input.preferredPort,
1243 fallbackToEphemeral: input.fallbackToEphemeral,
1244 },
1245 }),
1246 );
1247
1248 const probeDistros = provideSpawner(probeWslDistros).pipe(
1249 Effect.withSpan("desktop.wsl.probeDistros"),
1250 );
1251
1252 return DesktopWslEnvironment.of({
1253 isAvailable,
1254 listDistros: probeDistros.pipe(
1255 Effect.orElseSucceed(() => []),
1256 Effect.withSpan("desktop.wsl.listDistros"),
1257 ),
1258 probeDistros,
1259 preWarm: (distro) =>
1260 provideSpawner(preWarmImpl(distro)).pipe(Effect.withSpan("desktop.wsl.preWarm")),
1261 windowsToWslPath,
1262 getUserHome,
1263 getDistroIp,
1264 allocateTcpPort,
1265 ensureNodePty: (distro, windowsRepoRoot, options) =>
1266 provideSpawner(ensureNodePtyImpl(distro, windowsRepoRoot, windowsToWslPath, options)).pipe(
1267 Effect.withSpan("desktop.wsl.ensureNodePty"),
1268 ),
1269 });
1270 }),
1271);