The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,312 lines 48.5 KB
Raw
1 import * as Context from "effect/Context";
2 import * as Duration from "effect/Duration";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5 import * as Layer from "effect/Layer";
6 import * as Option from "effect/Option";
7 import * as Path from "effect/Path";
8 import type * as PlatformError from "effect/PlatformError";
9 import * as Ref from "effect/Ref";
10 import * as Schema from "effect/Schema";
11 import * as Stream from "effect/Stream";
12 import { ChildProcess, ChildProcessSpawner } from "effect/process";
13
14 import * as HostProcess from "@t3tools/shared/HostProcess";
15 import { buildRemoteNodeEnvScript } from "@t3tools/ssh/tunnel";
16 import { satisfiesSemverRange } from "@t3tools/shared/semver";
17
18 import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
19 import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
20 import { parseWslDistroList, type WslDistro } from "./wslPathParsing.ts";
21
22 const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
23 const LIST_TIMEOUT = Duration.seconds(8);
24 // Booting a stopped distro needs more time than converting paths in a running one.
25 const PRE_WARM_TIMEOUT = Duration.seconds(30);
26 const WSLPATH_TIMEOUT = Duration.seconds(10);
27 const PROBE_TIMEOUT = Duration.seconds(10);
28 const TOOLCHAIN_TIMEOUT = Duration.seconds(10);
29 const BUILD_TIMEOUT = Duration.minutes(5);
30 const RUNTIME_INSTALL_TIMEOUT = Duration.minutes(2);
31 const RUNTIME_PRUNE_TIMEOUT = Duration.seconds(30);
32 const RUNTIME_INVALIDATE_TIMEOUT = Duration.seconds(15);
33 const USER_HOME_TIMEOUT = Duration.seconds(5);
34 const TOOLCHAIN_TRANSPORT_RETRY_LIMIT = 12;
35 const BUILD_TRANSPORT_RETRY_LIMIT = 2;
36
37 export interface EnsureWslNodePtyOptions {
38 readonly allowBuild?: boolean;
39 readonly nodeEngineRange?: string | null;
40 }
41
42 export interface WslRuntimeArchive {
43 readonly windowsPath: string;
44 readonly runtimeId: string;
45 readonly sha256: string;
46 }
47
48 export type PrepareWslRuntimeResult =
49 | {
50 readonly ok: true;
51 readonly linuxAppRoot: string;
52 }
53 | {
54 readonly ok: false;
55 readonly reason: string;
56 };
57
58 export type EnsureWslNodePtyResult =
59 | {
60 readonly ok: true;
61 readonly nodePath: string;
62 readonly resolvedPath: string;
63 readonly t3Home: string | null;
64 }
65 | {
66 readonly ok: false;
67 readonly reason: string;
68 readonly fatal: boolean;
69 readonly retryLimit?: number;
70 };
71
72 export type ProbeWslRuntimeResult =
73 | {
74 readonly ok: true;
75 readonly resolvedPath: string;
76 readonly t3Home: string | null;
77 }
78 | {
79 readonly ok: false;
80 readonly reason: string;
81 };
82
83 export class DesktopWslDistroListError extends Schema.TaggedError<DesktopWslDistroListError>()(
84 "DesktopWslDistroListError",
85 { reason: Schema.String },
86 ) {
87 override get message(): string {
88 return this.reason;
89 }
90 }
91
92 const isDesktopWslDistroListError = Schema.is(DesktopWslDistroListError);
93
94 export class DesktopWslEnvironment extends Context.Service<
95 DesktopWslEnvironment,
96 {
97 readonly isAvailable: Effect.Effect<boolean>;
98 // UX-only best effort; health checks need probeDistros to distinguish failures from an empty installation.
99 readonly listDistros: Effect.Effect<readonly WslDistro[]>;
100 readonly probeDistros: Effect.Effect<readonly WslDistro[], DesktopWslDistroListError>;
101 readonly preWarm: (distro: string | null) => Effect.Effect<void>;
102 readonly windowsToWslPath: (
103 distro: string | null,
104 windowsPath: string,
105 ) => Effect.Effect<Option.Option<string>>;
106 readonly getUserHome: (distro: string | null) => Effect.Effect<Option.Option<string>>;
107 // Use the distro IP to avoid unreliable wslhost localhost forwarding.
108 readonly getDistroIp: (distro: string | null) => Effect.Effect<Option.Option<string>>;
109 // A null t3Home means the distro's login shell has no absolute T3CODE_HOME, so ~/.t3 applies.
110 readonly prepareRuntime: (
111 distro: string | null,
112 archive: WslRuntimeArchive,
113 t3Home: string | null,
114 ) => Effect.Effect<PrepareWslRuntimeResult>;
115 readonly pruneRuntimes: (
116 distro: string | null,
117 runtimeId: string,
118 t3Home: string | null,
119 ) => Effect.Effect<void>;
120 readonly probeRuntime: (distro: string | null) => Effect.Effect<ProbeWslRuntimeResult>;
121 readonly ensureNodePty: (
122 distro: string | null,
123 linuxAppRoot: string,
124 options?: EnsureWslNodePtyOptions,
125 ) => Effect.Effect<EnsureWslNodePtyResult>;
126 }
127 >()("@t3tools/desktop/wsl/DesktopWslEnvironment") {}
128
129 const buildDistroArgs = (distro: string | null): ReadonlyArray<string> =>
130 distro ? ["-d", distro] : [];
131
132 const concatChunks = (arrays: ReadonlyArray<Uint8Array>): Uint8Array => {
133 let totalLength = 0;
134 for (const arr of arrays) totalLength += arr.byteLength;
135 const out = new Uint8Array(totalLength);
136 let offset = 0;
137 for (const arr of arrays) {
138 out.set(arr, offset);
139 offset += arr.byteLength;
140 }
141 return out;
142 };
143
144 const decodeUtf8 = (bytes: Uint8Array): string => new TextDecoder("utf-8").decode(bytes);
145
146 interface ShellResult {
147 readonly exitCode: number;
148 readonly stdout: string;
149 readonly stderr: string;
150 readonly transportFailure: "timeout" | "spawn" | "process" | null;
151 }
152
153 const TIMEOUT_RESULT: ShellResult = {
154 exitCode: 124,
155 stdout: "",
156 stderr: "\n[timeout]",
157 transportFailure: "timeout",
158 };
159
160 const formatWslShellTransportFailureReason = (
161 failure: ShellResult["transportFailure"],
162 subject = "Node.js",
163 ): string | null => {
164 switch (failure) {
165 case "timeout":
166 return `WSL backend preflight timed out while probing for ${subject}. WSL may be slow to start; retry, or check that the distro is healthy.`;
167 case "spawn":
168 return `WSL backend preflight could not start wsl.exe to probe for ${subject}. Check that WSL is installed and the distro is accessible.`;
169 case "process":
170 return `WSL backend preflight lost communication with wsl.exe while probing for ${subject}. Retry, or check that the distro is healthy.`;
171 case null:
172 return null;
173 }
174 };
175
176 const buildWslNodeEnvPreamble = (
177 nodeEngineRange?: string | null,
178 ): string => `${buildRemoteNodeEnvScript({ nodeEngineRange: nodeEngineRange ?? null })}
179 ensure_remote_node_path || true
180 `;
181
182 const runWslProcess = (
183 args: ReadonlyArray<string>,
184 stdin: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
185 timeout: Duration.Duration,
186 ): Effect.Effect<ShellResult, never, ChildProcessSpawner.ChildProcessSpawner> => {
187 const spawner = ChildProcessSpawner.ChildProcessSpawner;
188 const command = ChildProcess.make("wsl.exe", args, {
189 stdin,
190 stdout: "pipe",
191 stderr: "pipe",
192 killSignal: "SIGTERM",
193 forceKillAfter: PROCESS_TERMINATE_GRACE,
194 });
195
196 return Effect.scoped(
197 Effect.gen(function* () {
198 const spawnerService = yield* spawner;
199 const spawnResult = yield* spawnerService.spawn(command).pipe(
200 Effect.match({
201 onFailure: (error) => ({ _tag: "Failure", error }) as const,
202 onSuccess: (handle) => ({ _tag: "Success", handle }) as const,
203 }),
204 );
205 if (spawnResult._tag === "Failure") {
206 return {
207 exitCode: 127,
208 stdout: "",
209 stderr: `\n${spawnResult.error.message}`,
210 transportFailure: "spawn",
211 } satisfies ShellResult;
212 }
213 const handle = spawnResult.handle;
214 // Drain both pipes concurrently to prevent node-gyp output from blocking the child.
215 const [stdoutBytes, stderrBytes, exitCode] = yield* Effect.all(
216 [Stream.runCollect(handle.stdout), Stream.runCollect(handle.stderr), handle.exitCode],
217 { concurrency: "unbounded" },
218 );
219 return {
220 exitCode: exitCode as unknown as number,
221 stdout: decodeUtf8(concatChunks(stdoutBytes)),
222 stderr: decodeUtf8(concatChunks(stderrBytes)),
223 transportFailure: null,
224 } satisfies ShellResult;
225 }),
226 ).pipe(
227 Effect.timeoutOption(timeout),
228 Effect.map(Option.getOrElse((): ShellResult => TIMEOUT_RESULT)),
229 Effect.catch((error) =>
230 Effect.succeed<ShellResult>({
231 exitCode: 127,
232 stdout: "",
233 stderr: `\n${error.message}`,
234 transportFailure: "process",
235 }),
236 ),
237 );
238 };
239
240 // wsl.exe re-escaping mangles quotes inside bash -lc scripts.
241 const runWslShell = (
242 distro: string | null,
243 bashScript: string,
244 timeout: Duration.Duration,
245 options: {
246 readonly nodeEngineRange?: string | null;
247 readonly resolveNode?: boolean;
248 } = {},
249 ): Effect.Effect<ShellResult, never, ChildProcessSpawner.ChildProcessSpawner> => {
250 const resolveNode = options.resolveNode !== false;
251 return runWslProcess(
252 resolveNode
253 ? [...buildDistroArgs(distro), "--", "bash", "-l", "-s"]
254 : [...buildDistroArgs(distro), "--exec", "sh", "-s"],
255 Stream.encodeText(
256 Stream.make(
257 resolveNode
258 ? `${buildWslNodeEnvPreamble(options.nodeEngineRange)}${bashScript}`
259 : bashScript,
260 ),
261 ),
262 timeout,
263 );
264 };
265
266 const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
267
268 const WSL_RUNTIME_READY_MARKER = ".t3code-wsl-runtime-ready";
269 const WSL_RUNTIME_SELECTED_MARKER = ".t3code-wsl-runtime-selected";
270 const WSL_RUNTIME_SELECTION_GRACE_MINUTES = 5;
271
272 const sanitizeWslRuntimeId = (value: string): string => value.replace(/[^A-Za-z0-9._-]/g, "_");
273
274 const runtimeParentAssignment = (t3Home: string | null): string =>
275 t3Home === null
276 ? 'runtime_parent="$HOME/.t3/wsl-runtime"'
277 : `runtime_parent=${shellQuote(`${t3Home}/wsl-runtime`)}`;
278
279 // A null archive path asks for a staging directory to copy the archive into, unless the cache is ready.
280 export const buildWslRuntimeInstallScript = (
281 linuxArchivePath: string | null,
282 runtimeId: string,
283 archiveSha256: string,
284 t3Home: string | null,
285 ): string => {
286 const safeRuntimeId = sanitizeWslRuntimeId(runtimeId);
287 const readyCheck = [
288 "set -eu",
289 runtimeParentAssignment(t3Home),
290 `runtime_root="$runtime_parent/${safeRuntimeId}"`,
291 `ready_marker="$runtime_root/${WSL_RUNTIME_READY_MARKER}"`,
292 "runtime_entry_runs() {",
293 ' [ -x "$1/t3" ] && "$1/t3" --version >/dev/null',
294 "}",
295 // Hash the entry to detect a swapped or partially written executable, even if it still runs.
296 "runtime_server_entry_digest() {",
297 ` sha256sum "$1/t3" 2>/dev/null | cut -d ' ' -f 1`,
298 "}",
299 "runtime_is_ready() {",
300 ' [ -f "$ready_marker" ] &&',
301 ' runtime_entry_runs "$runtime_root" 2>/dev/null &&',
302 ` recorded_entry_digest=$(tr -d '[:space:]' < "$ready_marker" 2>/dev/null) &&`,
303 ' [ -n "$recorded_entry_digest" ] &&',
304 ' [ "$recorded_entry_digest" = "$(runtime_server_entry_digest "$runtime_root")" ]',
305 "}",
306 'mkdir -p "$runtime_parent"',
307 `runtime_lock="$runtime_parent/.${safeRuntimeId}.install.lock"`,
308 "trap 'exit 1' HUP INT TERM",
309 'exec 9> "$runtime_lock"',
310 "flock -x 9",
311 "if runtime_is_ready; then",
312 ` touch "$runtime_root/${WSL_RUNTIME_SELECTED_MARKER}"`,
313 ` printf 'runtimeRoot:%s\\n' "$runtime_root"`,
314 " exit 0",
315 "fi",
316 ];
317 if (linuxArchivePath === null) {
318 return [
319 ...readyCheck,
320 // The .tmp. name lets pruning collect a stage orphaned by a crash.
321 `archive_stage=$(mktemp -d "$runtime_parent/.${safeRuntimeId}.tmp.XXXXXX")`,
322 `printf 'archiveStage:%s\\n' "$archive_stage"`,
323 ].join("\n");
324 }
325 return [
326 ...readyCheck,
327 `archive_sha=$(sha256sum ${shellQuote(linuxArchivePath)} | cut -d ' ' -f 1)`,
328 `if [ "$archive_sha" != ${shellQuote(archiveSha256)} ]; then`,
329 ` printf 'WSL runtime archive does not match its recorded SHA-256 (expected %s, got %s)\\n' ${shellQuote(archiveSha256)} "$archive_sha" >&2`,
330 " exit 1",
331 "fi",
332 // Deletion can remove a live backend's lazy imports; check cmdline before rename preserves its old path.
333 "runtime_in_use() {",
334 // Without /proc, assume the runtime may still be in use.
335 " [ -d /proc/1 ] || return 0",
336 ' grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null',
337 "}",
338 'if [ -e "$runtime_root" ]; then',
339 ' if runtime_in_use "$runtime_root"; then',
340 " runtime_root_in_use=1",
341 " else",
342 " runtime_root_in_use=0",
343 " fi",
344 ` runtime_stale=$(mktemp -d "$runtime_parent/.${safeRuntimeId}.stale.XXXXXX")`,
345 ' rmdir "$runtime_stale"',
346 ' if mv -T "$runtime_root" "$runtime_stale" 2>/dev/null; then',
347 ' if [ "$runtime_root_in_use" = 1 ]; then',
348 // Renaming keeps the directory's old mtime, so restart the cleanup clock.
349 ' touch "$runtime_stale"',
350 " else",
351 ' rm -rf "$runtime_stale"',
352 " fi",
353 " fi",
354 "fi",
355 `runtime_tmp=$(mktemp -d "$runtime_parent/.${safeRuntimeId}.tmp.XXXXXX")`,
356 'cleanup_runtime_install() { rm -rf "$runtime_tmp"; }',
357 "trap cleanup_runtime_install EXIT",
358 `tar -xzf ${shellQuote(linuxArchivePath)} -C "$runtime_tmp" --strip-components=1`,
359 'if ! runtime_entry_runs "$runtime_tmp"; then',
360 " printf 'WSL runtime archive does not contain a working t3 executable\\n' >&2",
361 " exit 1",
362 "fi",
363 'installed_entry_digest=$(runtime_server_entry_digest "$runtime_tmp")',
364 'if [ -z "$installed_entry_digest" ]; then',
365 " printf 'Could not hash the WSL runtime server entry\\n' >&2",
366 " exit 1",
367 "fi",
368 `printf '%s\\n' "$installed_entry_digest" > "$runtime_tmp/${WSL_RUNTIME_READY_MARKER}"`,
369 'if mv -T "$runtime_tmp" "$runtime_root" 2>/dev/null; then',
370 " :",
371 "elif runtime_is_ready; then",
372 ' rm -rf "$runtime_tmp"',
373 "else",
374 ` printf 'Could not promote WSL runtime cache at %s\\n' "$runtime_root" >&2`,
375 " exit 1",
376 "fi",
377 `touch "$runtime_root/${WSL_RUNTIME_SELECTED_MARKER}"`,
378 `printf 'runtimeRoot:%s\\n' "$runtime_root"`,
379 ].join("\n");
380 };
381
382 // Two hours exceeds cold-install time while bounding orphan retention.
383 const ORPHANED_RUNTIME_SCRATCH_MAX_AGE_MINUTES = 120;
384
385 export const buildWslRuntimePruneScript = (runtimeId: string, t3Home: string | null): string => {
386 const safeRuntimeId = sanitizeWslRuntimeId(runtimeId);
387 return [
388 "set -eu",
389 runtimeParentAssignment(t3Home),
390 `current_runtime="$runtime_parent/${safeRuntimeId}"`,
391 '[ -d "$runtime_parent" ] || exit 0',
392 // Serialize pruning so backends cannot select and delete different previous caches.
393 'prune_lock="$runtime_parent/.prune.lock"',
394 'exec 8> "$prune_lock"',
395 "flock -x 8",
396 // Without /proc, retention cannot distinguish caches used by live backends.
397 "[ -d /proc/1 ] || exit 0",
398 "runtime_in_use() {",
399 ' grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null',
400 "}",
401 'previous_runtime=""',
402 'for candidate in "$runtime_parent"/sha256-*; do',
403 ' [ -d "$candidate" ] || continue',
404 ' [ "$candidate" != "$current_runtime" ] || continue',
405 ` [ -f "$candidate/${WSL_RUNTIME_READY_MARKER}" ] || continue`,
406 ' if [ -z "$previous_runtime" ] || [ "$candidate" -nt "$previous_runtime" ]; then',
407 ' previous_runtime="$candidate"',
408 " fi",
409 "done",
410 'for candidate in "$runtime_parent"/sha256-*; do',
411 ' [ -d "$candidate" ] || continue',
412 ' [ "$candidate" != "$current_runtime" ] || continue',
413 ' [ "$candidate" != "$previous_runtime" ] || continue',
414 ' ! runtime_in_use "$candidate" || continue',
415 " candidate_name=${candidate##*/}",
416 ' candidate_lock="$runtime_parent/.${candidate_name}.install.lock"',
417 ' exec 9> "$candidate_lock"',
418 " flock -n 9 || continue",
419 ` selected_marker="$candidate/${WSL_RUNTIME_SELECTED_MARKER}"`,
420 ` if [ -f "$selected_marker" ] && find "$selected_marker" -maxdepth 0 -mmin -${String(WSL_RUNTIME_SELECTION_GRACE_MINUTES)} -print -quit | grep -q .; then`,
421 " flock -u 9",
422 " continue",
423 " fi",
424 ' rm -rf -- "$candidate"',
425 " flock -u 9",
426 "done",
427 'for scratch in "$runtime_parent"/.*.tmp.* "$runtime_parent"/.*.stale.*; do',
428 ' [ -d "$scratch" ] || continue',
429 ` find "$scratch" -maxdepth 0 -mmin +${String(ORPHANED_RUNTIME_SCRATCH_MAX_AGE_MINUTES)} -print -quit | grep -q . || continue`,
430 ' rm -rf -- "$scratch"',
431 "done",
432 ].join("\n");
433 };
434
435 const parseAbsolutePathField = (stdout: string, field: string): string | null => {
436 const prefix = `${field}:`;
437 const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));
438 if (line === undefined) return null;
439 const value = line.slice(prefix.length).replace(/\r$/, "");
440 return value.startsWith("/") ? value : null;
441 };
442
443 export const parseWslRuntimeRoot = (stdout: string): string | null =>
444 parseAbsolutePathField(stdout, "runtimeRoot");
445
446 const NODE_PTY_BINARY_MISSING_EXIT_CODE = 4;
447
448 const formatNodePtyProbeFailureReason = (exitCode: number): string | null =>
449 exitCode === NODE_PTY_BINARY_MISSING_EXIT_CODE
450 ? "WSL support is missing from this T3 Code build: the packaged Linux node-pty binary was not included. Install a build that includes WSL support."
451 : null;
452
453 // Capture login-shell PATH because the server launches provider CLIs by name.
454 const RESOLVED_PATH_LINE = `printf 'resolvedPath:%s\\n' "$PATH"`;
455 // wsl.exe --exec skips the profile, so the server only sees a profile-exported T3CODE_HOME if passed on.
456 const T3_HOME_LINE = `printf 't3Home:%s\\n' "\${T3CODE_HOME:-}"`;
457
458 const NODE_PTY_PROBE_SCRIPT = (
459 linuxServerDir: string,
460 ) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"
461 printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)"
462 ${RESOLVED_PATH_LINE}
463 ${T3_HOME_LINE}
464 cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
465 // The WSL Node can't read inside app.asar, so confirm what the server needs is
466 // unpacked on the real filesystem before reporting the backend healthy. Exit 3
467 // marks this distinct from a node-pty binary problem so the caller can report
468 // it accurately instead of letting the server crash on ERR_MODULE_NOT_FOUND at
469 // launch (which, in wsl-only mode, would just fail to launch with no fallback).
470 //
471 // The sentinel must be a package the CLI bundle leaves external. The bundle
472 // inlines its JS dependencies, so only the native packages exist on disk.
473 // Resolving node-pty is what actually validates the unpacked tree.
474 try { require.resolve("node-pty/package.json"); } catch (_e) { process.exit(3); }
475 const fs = require("node:fs");
476 const path = require("node:path");
477 const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
478 // node-pty 1.x is N-API based, so a single Linux pty.node is ABI-stable across
479 // Node versions, so require() succeeding IS the real compatibility test. Look in
480 // the same places node-pty's own loader does.
481 const candidates = [
482 path.join(pkgDir, "build", "Release", "pty.node"),
483 path.join(pkgDir, "prebuilds", "linux-" + process.arch, "pty.node"),
484 ];
485 if (!candidates.some((candidate) => fs.existsSync(candidate))) process.exit(${NODE_PTY_BINARY_MISSING_EXIT_CODE});
486 require("node-pty");
487 NODE`;
488
489 // Resolve version-managed Node for providers without making runtime readiness depend on it.
490 // The install script already ran the staged t3, so running it again here only adds a second startup.
491 export const buildWslRuntimeProbeScript = () =>
492 `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}\n${T3_HOME_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`;
493
494 const TOOLCHAIN_CHECK_SCRIPT = [
495 "for tool in node make g++ python3; do",
496 ' command -v "$tool" >/dev/null 2>&1 || echo "missing:$tool"',
497 "done",
498 "if command -v node >/dev/null 2>&1; then",
499 ` ver="$(node -p 'process.versions.node' 2>/dev/null)"`,
500 ' if [ -n "$ver" ]; then printf "nodeVersion:%s\\n" "$ver"; fi',
501 "fi",
502 ].join("\n");
503
504 const NODE_PTY_BUILD_SCRIPT = (linuxServerDir: string) =>
505 [
506 "set -e",
507 `cd ${shellQuote(linuxServerDir)}`,
508 `pkg_dir=$(node -p "require('node:path').dirname(require.resolve('node-pty/package.json'))")`,
509 `cd "$pkg_dir"`,
510 "npx --yes node-gyp rebuild",
511 `node -e 'require("node-pty")'`,
512 ].join("\n");
513
514 export interface ToolchainReport {
515 readonly missingTools: ReadonlyArray<string>;
516 readonly nodeVersion: string | null;
517 }
518
519 const parseToolchainReport = (stdout: string): ToolchainReport => {
520 const lines = stdout
521 .split("\n")
522 .map((line) => line.trim())
523 .filter((line) => line.length > 0);
524 const missingTools = lines
525 .filter((line) => line.startsWith("missing:"))
526 .map((line) => line.slice("missing:".length));
527 const nodeVersionLine = lines.find((line) => line.startsWith("nodeVersion:"));
528 const nodeVersion = nodeVersionLine
529 ? nodeVersionLine.slice("nodeVersion:".length).trim() || null
530 : null;
531 return { missingTools, nodeVersion };
532 };
533
534 const parseNodePath = (stdout: string): string | null => {
535 const path = stdout
536 .split("\n")
537 .map((line) => line.trim())
538 .filter((line) => line.startsWith("nodePath:"))
539 .map((line) => line.slice("nodePath:".length).trim())
540 .find((value) => value.length > 0);
541 return path ?? null;
542 };
543
544 const parseNodeVersion = (stdout: string): string | null => {
545 const version = stdout
546 .split("\n")
547 .map((line) => line.trim())
548 .filter((line) => line.startsWith("nodeVersion:"))
549 .map((line) => line.slice("nodeVersion:".length).trim())
550 .find((value) => value.length > 0);
551 return version ?? null;
552 };
553
554 // Strip only Windows CR; spaces and apostrophes must survive as one env argument.
555 export const parseResolvedPath = (stdout: string): string | null => {
556 const prefix = "resolvedPath:";
557 const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));
558 if (line === undefined) return null;
559 const resolvedPath = line.slice(prefix.length).replace(/\r$/, "");
560 return resolvedPath.length > 0 ? resolvedPath : null;
561 };
562
563 // Relative values are ignored: the runtime scripts and the server would resolve them from different cwds.
564 export const parseT3Home = (stdout: string): string | null =>
565 parseAbsolutePathField(stdout, "t3Home");
566
567 const formatMissingToolsReason = (
568 report: ToolchainReport,
569 requiredRange: string | null,
570 ): string | null => {
571 const nodeMissing = report.missingTools.includes("node");
572 const nodeOutOfRange =
573 !nodeMissing &&
574 requiredRange !== null &&
575 report.nodeVersion !== null &&
576 !satisfiesSemverRange(report.nodeVersion, requiredRange);
577 const buildToolsMissing = report.missingTools.filter((tool) => tool !== "node");
578
579 if (!nodeMissing && !nodeOutOfRange && buildToolsMissing.length === 0) {
580 return null;
581 }
582
583 const issues: string[] = [];
584 const remediations: string[] = [];
585
586 if (nodeMissing) {
587 issues.push("node");
588 remediations.push(
589 `Node.js${requiredRange ? ` satisfying \`${requiredRange}\`` : " 18+"} (e.g. via nvm)`,
590 );
591 } else if (nodeOutOfRange) {
592 issues.push(`node ${report.nodeVersion} (requires ${requiredRange})`);
593 remediations.push(
594 `a newer Node.js satisfying \`${requiredRange}\` (e.g. \`nvm install 24 && nvm alias default 24\`)`,
595 );
596 }
597
598 if (buildToolsMissing.length > 0) {
599 issues.push(...buildToolsMissing);
600 remediations.push(
601 "the build toolchain (e.g. `sudo apt install -y build-essential python3` on Ubuntu/Debian)",
602 );
603 }
604
605 return `WSL distro is missing required tools: ${issues.join(", ")}. Install ${remediations.join(" and ")}, then retry.`;
606 };
607
608 const probeWslRuntimeImpl = Effect.fn("DesktopWslEnvironment.probeWslRuntimeImpl")(function* (
609 distro: string | null,
610 ): Effect.fn.Return<ProbeWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> {
611 const probe = yield* runWslShell(distro, buildWslRuntimeProbeScript(), PROBE_TIMEOUT, {
612 resolveNode: false,
613 });
614 const transportFailureReason = formatWslShellTransportFailureReason(
615 probe.transportFailure,
616 "the login-shell PATH",
617 );
618 if (transportFailureReason !== null) {
619 return { ok: false, reason: transportFailureReason } as const;
620 }
621 const resolvedPath = parseResolvedPath(probe.stdout);
622 if (resolvedPath === null) {
623 return {
624 ok: false,
625 reason: "WSL login-shell PATH could not be resolved during backend preflight.",
626 } as const;
627 }
628 return { ok: true, resolvedPath, t3Home: parseT3Home(probe.stdout) } as const;
629 });
630
631 const ensureNodePtyImpl = Effect.fn("DesktopWslEnvironment.ensureNodePtyImpl")(function* (
632 distro: string | null,
633 linuxRepoRoot: string,
634 options: EnsureWslNodePtyOptions = {},
635 ): Effect.fn.Return<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> {
636 // node-pty lives in the apps/server workspace's node_modules; resolve from
637 // there rather than the monorepo root, where Bun's hoist layout omits it.
638 const linuxServerDir = `${linuxRepoRoot}/apps/server`;
639
640 const probe = yield* runWslShell(
641 distro,
642 NODE_PTY_PROBE_SCRIPT(linuxServerDir),
643 PROBE_TIMEOUT,
644 options,
645 );
646 const nodePath = parseNodePath(probe.stdout);
647 const resolvedPath = parseResolvedPath(probe.stdout);
648 const t3Home = parseT3Home(probe.stdout);
649
650 const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
651 if (transportFailureReason !== null) {
652 return {
653 ok: false,
654 reason: transportFailureReason,
655 fatal: false,
656 } as const;
657 }
658
659 if (nodePath === null) {
660 const toolchainCheck = yield* runWslShell(
661 distro,
662 TOOLCHAIN_CHECK_SCRIPT,
663 TOOLCHAIN_TIMEOUT,
664 options,
665 );
666 const toolchainTransportFailure = formatWslShellTransportFailureReason(
667 toolchainCheck.transportFailure,
668 );
669 if (toolchainTransportFailure !== null) {
670 return {
671 ok: false,
672 reason: toolchainTransportFailure,
673 fatal: false,
674 retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
675 } as const;
676 }
677 const report = parseToolchainReport(toolchainCheck.stdout);
678 const reason =
679 formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null) ??
680 "Node.js was not found in the WSL distro. Install it (e.g. via nvm) and restart the desktop app.";
681 return { ok: false, reason, fatal: true } as const;
682 }
683
684 if (resolvedPath === null) {
685 return {
686 ok: false,
687 reason: "WSL login-shell PATH could not be resolved during backend preflight.",
688 fatal: true,
689 } as const;
690 }
691
692 if (probe.exitCode === 3) {
693 return {
694 ok: false,
695 reason:
696 '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.',
697 fatal: true,
698 } as const;
699 }
700
701 if (probe.exitCode === 0) {
702 const rawVersion = parseNodeVersion(probe.stdout);
703 if (
704 rawVersion !== null &&
705 options.nodeEngineRange &&
706 !satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())
707 ) {
708 const range = options.nodeEngineRange.trim();
709 return {
710 ok: false,
711 reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,
712 fatal: true,
713 } as const;
714 }
715 return { ok: true, nodePath, resolvedPath, t3Home } as const;
716 }
717
718 if (options.allowBuild !== true) {
719 const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
720 if (packagedProbeFailure !== null) {
721 return {
722 ok: false,
723 reason: packagedProbeFailure,
724 fatal: true,
725 } as const;
726 }
727 }
728
729 const toolchainCheck = yield* runWslShell(
730 distro,
731 TOOLCHAIN_CHECK_SCRIPT,
732 TOOLCHAIN_TIMEOUT,
733 options,
734 );
735 const toolchainTransportFailure = formatWslShellTransportFailureReason(
736 toolchainCheck.transportFailure,
737 );
738 if (toolchainTransportFailure !== null) {
739 return {
740 ok: false,
741 reason: toolchainTransportFailure,
742 fatal: false,
743 retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
744 } as const;
745 }
746 const report = parseToolchainReport(toolchainCheck.stdout);
747
748 if (options.allowBuild !== true) {
749 // Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp,
750 // or network is needed — and we must not nag the user to install build
751 // tools they don't need.
752 const nodeOnlyReason = formatMissingToolsReason(
753 {
754 missingTools: report.missingTools.filter((tool) => tool === "node"),
755 nodeVersion: report.nodeVersion,
756 },
757 options.nodeEngineRange?.trim() || null,
758 );
759 return {
760 ok: false,
761 reason:
762 nodeOnlyReason ??
763 "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`.",
764 fatal: true,
765 } as const;
766 }
767
768 const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);
769 if (missingReason !== null) {
770 return { ok: false, reason: missingReason, fatal: true } as const;
771 }
772
773 const build = yield* runWslShell(
774 distro,
775 NODE_PTY_BUILD_SCRIPT(linuxServerDir),
776 BUILD_TIMEOUT,
777 options,
778 );
779 const buildTransportFailure = formatWslShellTransportFailureReason(build.transportFailure);
780 if (buildTransportFailure !== null) {
781 return {
782 ok: false,
783 reason: buildTransportFailure,
784 fatal: false,
785 retryLimit: BUILD_TRANSPORT_RETRY_LIMIT,
786 } as const;
787 }
788 if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath, t3Home } as const;
789 const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500);
790 return {
791 ok: false,
792 reason: `node-pty Linux build failed (exit ${build.exitCode}): ${trimmedTail || "no stderr captured"}`,
793 fatal: true,
794 } as const;
795 });
796
797 type WslRuntimeInstallOutcome =
798 | { readonly ok: true; readonly stdout: string }
799 | { readonly ok: false; readonly reason: string };
800
801 const runWslRuntimeInstall = Effect.fn("desktop.wsl.runRuntimeInstall")(function* (
802 distro: string | null,
803 archive: WslRuntimeArchive,
804 t3Home: string | null,
805 linuxArchivePath: string | null,
806 ): Effect.fn.Return<WslRuntimeInstallOutcome, never, ChildProcessSpawner.ChildProcessSpawner> {
807 const install = yield* runWslShell(
808 distro,
809 buildWslRuntimeInstallScript(linuxArchivePath, archive.runtimeId, archive.sha256, t3Home),
810 RUNTIME_INSTALL_TIMEOUT,
811 { resolveNode: false },
812 );
813 if (install.transportFailure !== null) {
814 return {
815 ok: false,
816 reason:
817 install.transportFailure === "timeout"
818 ? "WSL runtime installation timed out. Check that the distro has free disk space, then retry."
819 : "WSL runtime installation lost communication with wsl.exe. Retry, or check that the distro is healthy.",
820 } as const;
821 }
822 if (install.exitCode !== 0) {
823 const trimmedTail = `${install.stdout}${install.stderr}`.trim().slice(-500);
824 return {
825 ok: false,
826 reason: `WSL runtime installation failed (exit ${install.exitCode}): ${trimmedTail || "no stderr captured"}`,
827 } as const;
828 }
829 return { ok: true, stdout: install.stdout } as const;
830 });
831
832 const toPrepareWslRuntimeResult = (outcome: WslRuntimeInstallOutcome): PrepareWslRuntimeResult => {
833 if (!outcome.ok) return outcome;
834 const linuxAppRoot = parseWslRuntimeRoot(outcome.stdout);
835 return linuxAppRoot === null
836 ? {
837 ok: false,
838 reason: "WSL runtime installation completed without reporting its cache path.",
839 }
840 : { ok: true, linuxAppRoot };
841 };
842
843 // Without drive mounts (`[automount] enabled=false`) wslpath cannot reach the archive, so copy it in over stdin.
844 const installWslRuntimeFromHostCopy = Effect.fn("desktop.wsl.installRuntimeFromHostCopy")(
845 function* (
846 distro: string | null,
847 archive: WslRuntimeArchive,
848 t3Home: string | null,
849 archiveBytes: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
850 ): Effect.fn.Return<PrepareWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> {
851 const staged = yield* runWslRuntimeInstall(distro, archive, t3Home, null);
852 if (!staged.ok || parseWslRuntimeRoot(staged.stdout) !== null) {
853 return toPrepareWslRuntimeResult(staged);
854 }
855 const stage = parseAbsolutePathField(staged.stdout, "archiveStage");
856 if (stage === null) {
857 return {
858 ok: false,
859 reason: `wslpath conversion failed for ${archive.windowsPath}, and the distro did not provide a directory to copy the runtime archive into.`,
860 } as const;
861 }
862 const linuxArchivePath = `${stage}/runtime.tar.gz`;
863
864 const copyAndInstall = Effect.gen(function* () {
865 const readError = yield* Ref.make(Option.none<PlatformError.PlatformError>());
866 // dd reads fd 0 itself; reopening /dev/stdin fails when WSL relays stdin as a socket.
867 const copy = yield* runWslProcess(
868 [...buildDistroArgs(distro), "--exec", "dd", `of=${linuxArchivePath}`, "bs=65536"],
869 archiveBytes.pipe(
870 // Ending stdin on a read error lets dd exit instead of waiting out the timeout.
871 Stream.catch((error) =>
872 Stream.drain(Stream.fromEffect(Ref.set(readError, Option.some(error)))),
873 ),
874 ),
875 RUNTIME_INSTALL_TIMEOUT,
876 );
877 const failedRead = yield* Ref.get(readError);
878 if (Option.isSome(failedRead)) {
879 return {
880 ok: false,
881 reason: `Could not read the WSL runtime archive at ${archive.windowsPath}: ${failedRead.value.message}`,
882 } as const;
883 }
884 if (copy.transportFailure !== null || copy.exitCode !== 0) {
885 const trimmedTail = copy.stderr.trim().slice(-500);
886 return {
887 ok: false,
888 reason: `Could not copy the WSL runtime archive into the distro (exit ${copy.exitCode})${trimmedTail ? `: ${trimmedTail}` : ""}`,
889 } as const;
890 }
891 return toPrepareWslRuntimeResult(
892 yield* runWslRuntimeInstall(distro, archive, t3Home, linuxArchivePath),
893 );
894 });
895
896 return yield* copyAndInstall.pipe(
897 Effect.ensuring(
898 runWslShell(distro, `rm -rf ${shellQuote(stage)}`, RUNTIME_INVALIDATE_TIMEOUT, {
899 resolveNode: false,
900 }),
901 ),
902 );
903 },
904 );
905
906 const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(function* (
907 distro: string | null,
908 archive: WslRuntimeArchive,
909 t3Home: string | null,
910 windowsToWslPath: (
911 distro: string | null,
912 windowsPath: string,
913 ) => Effect.Effect<Option.Option<string>>,
914 ): Effect.fn.Return<
915 PrepareWslRuntimeResult,
916 never,
917 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
918 > {
919 const linuxArchivePath = yield* windowsToWslPath(distro, archive.windowsPath);
920 if (Option.isNone(linuxArchivePath)) {
921 const fileSystem = yield* FileSystem.FileSystem;
922 return yield* installWslRuntimeFromHostCopy(
923 distro,
924 archive,
925 t3Home,
926 fileSystem.stream(archive.windowsPath),
927 );
928 }
929 return toPrepareWslRuntimeResult(
930 yield* runWslRuntimeInstall(distro, archive, t3Home, linuxArchivePath.value),
931 );
932 });
933
934 const pruneWslRuntimesImpl = Effect.fn("desktop.wsl.pruneRuntimesImpl")(function* (
935 distro: string | null,
936 runtimeId: string,
937 t3Home: string | null,
938 ): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
939 const result = yield* runWslShell(
940 distro,
941 buildWslRuntimePruneScript(runtimeId, t3Home),
942 RUNTIME_PRUNE_TIMEOUT,
943 { resolveNode: false },
944 );
945 if (result.transportFailure === null && result.exitCode === 0) return;
946
947 const detail = `${result.stdout}${result.stderr}`.trim().slice(-500);
948 yield* Effect.logWarning("Could not prune old WSL runtime caches.", {
949 distro,
950 runtimeId,
951 detail: detail || `exit ${result.exitCode}`,
952 });
953 });
954
955 const probeWslDistros: Effect.Effect<
956 readonly WslDistro[],
957 DesktopWslDistroListError,
958 ChildProcessSpawner.ChildProcessSpawner
959 > = Effect.scoped(
960 Effect.gen(function* () {
961 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
962 const command = ChildProcess.make("wsl.exe", ["--list", "--verbose"], {
963 stdin: "ignore",
964 stdout: "pipe",
965 stderr: "ignore",
966 killSignal: "SIGTERM",
967 forceKillAfter: PROCESS_TERMINATE_GRACE,
968 });
969 const handle = yield* spawner.spawn(command);
970 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
971 const exitCode = yield* handle.exitCode;
972 if ((exitCode as unknown as number) !== 0) {
973 return yield* new DesktopWslDistroListError({
974 reason: `wsl.exe --list --verbose exited with code ${String(exitCode)}`,
975 });
976 }
977 return parseWslDistroList(Buffer.from(concatChunks(stdoutBytes)));
978 }),
979 ).pipe(
980 Effect.mapError((error) =>
981 isDesktopWslDistroListError(error)
982 ? error
983 : new DesktopWslDistroListError({
984 reason: `Failed to run wsl.exe --list --verbose: ${error.message}`,
985 }),
986 ),
987 Effect.timeoutOption(LIST_TIMEOUT),
988 Effect.flatMap(
989 Option.match({
990 onNone: () =>
991 new DesktopWslDistroListError({
992 reason: "wsl.exe --list --verbose timed out",
993 }),
994 onSome: Effect.succeed,
995 }),
996 ),
997 );
998
999 const preWarmImpl = (
1000 distro: string | null,
1001 ): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> =>
1002 Effect.scoped(
1003 Effect.gen(function* () {
1004 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1005 const command = ChildProcess.make("wsl.exe", [...buildDistroArgs(distro), "--", "true"], {
1006 stdin: "ignore",
1007 stdout: "ignore",
1008 stderr: "ignore",
1009 killSignal: "SIGTERM",
1010 forceKillAfter: PROCESS_TERMINATE_GRACE,
1011 });
1012 const handle = yield* spawner.spawn(command);
1013 yield* handle.exitCode;
1014 }),
1015 ).pipe(Effect.timeoutOption(PRE_WARM_TIMEOUT), Effect.ignore);
1016
1017 export const windowsToWslPathImpl = (
1018 distro: string | null,
1019 windowsPath: string,
1020 ): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> => {
1021 // wsl.exe interprets backslashes as escape chars; normalize to forward slashes.
1022 const normalized = windowsPath.replaceAll("\\", "/");
1023 return Effect.scoped(
1024 Effect.gen(function* () {
1025 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1026 const command = ChildProcess.make(
1027 "wsl.exe",
1028 // --exec skips the distro shell, which would expand `$`, `&` or `;` in folder names.
1029 [...buildDistroArgs(distro), "--exec", "wslpath", "-u", normalized],
1030 {
1031 stdin: "ignore",
1032 stdout: "pipe",
1033 stderr: "ignore",
1034 killSignal: "SIGTERM",
1035 forceKillAfter: PROCESS_TERMINATE_GRACE,
1036 },
1037 );
1038 const handle = yield* spawner.spawn(command);
1039 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
1040 const exitCode = yield* handle.exitCode;
1041 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
1042 const converted = decodeUtf8(concatChunks(stdoutBytes)).trim();
1043 return converted.length > 0 ? Option.some(converted) : Option.none<string>();
1044 }),
1045 ).pipe(
1046 Effect.timeoutOption(WSLPATH_TIMEOUT),
1047 Effect.map(Option.flatten),
1048 Effect.orElseSucceed(() => Option.none<string>()),
1049 );
1050 };
1051
1052 const IPV4_PATTERN = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
1053
1054 const getDistroIpImpl = (
1055 distro: string | null,
1056 ): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
1057 Effect.scoped(
1058 Effect.gen(function* () {
1059 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1060 // WSL2's first hostname -I address is reachable directly from Windows without wslhost forwarding.
1061 const command = ChildProcess.make(
1062 "wsl.exe",
1063 [...buildDistroArgs(distro), "--", "sh", "-c", "hostname -I"],
1064 {
1065 stdin: "ignore",
1066 stdout: "pipe",
1067 stderr: "ignore",
1068 killSignal: "SIGTERM",
1069 forceKillAfter: PROCESS_TERMINATE_GRACE,
1070 },
1071 );
1072 const handle = yield* spawner.spawn(command);
1073 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
1074 const exitCode = yield* handle.exitCode;
1075 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
1076 const raw = decodeUtf8(concatChunks(stdoutBytes)).trim();
1077 const candidate = raw.split(/\s+/).find((part) => IPV4_PATTERN.test(part));
1078 return candidate ? Option.some(candidate) : Option.none<string>();
1079 }),
1080 ).pipe(
1081 Effect.timeoutOption(USER_HOME_TIMEOUT),
1082 Effect.map(Option.flatten),
1083 Effect.orElseSucceed(() => Option.none<string>()),
1084 );
1085
1086 const getUserHomeImpl = (
1087 distro: string | null,
1088 ): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
1089 Effect.scoped(
1090 Effect.gen(function* () {
1091 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1092 const command = ChildProcess.make(
1093 "wsl.exe",
1094 [
1095 ...buildDistroArgs(distro),
1096 "--",
1097 "sh",
1098 "-c",
1099 'printf "%s" "$(getent passwd "$(id -un)" | cut -d: -f6)"',
1100 ],
1101 {
1102 stdin: "ignore",
1103 stdout: "pipe",
1104 stderr: "ignore",
1105 killSignal: "SIGTERM",
1106 forceKillAfter: PROCESS_TERMINATE_GRACE,
1107 },
1108 );
1109 const handle = yield* spawner.spawn(command);
1110 const stdoutBytes = yield* Stream.runCollect(handle.stdout);
1111 const exitCode = yield* handle.exitCode;
1112 if ((exitCode as unknown as number) !== 0) return Option.none<string>();
1113 const home = decodeUtf8(concatChunks(stdoutBytes)).trim();
1114 return home.startsWith("/") ? Option.some(home) : Option.none<string>();
1115 }),
1116 ).pipe(
1117 Effect.timeoutOption(USER_HOME_TIMEOUT),
1118 Effect.map(Option.flatten),
1119 Effect.orElseSucceed(() => Option.none<string>()),
1120 );
1121
1122 export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable")(function* (
1123 platform: NodeJS.Platform,
1124 windir: string,
1125 ): Effect.fn.Return<
1126 boolean,
1127 never,
1128 FileSystem.FileSystem | Path.Path | DesktopManagedPolicy.DesktopManagedPolicy
1129 > {
1130 if (platform !== "win32") return false;
1131 const path = yield* Path.Path;
1132 const fileSystem = yield* FileSystem.FileSystem;
1133 const wslExePath = path.join(windir, "System32", "wsl.exe");
1134 if (!(yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false)))) {
1135 return false;
1136 }
1137 // A server in WSL reads Linux's policy, never this machine's, so a managed machine runs none.
1138 return yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe(
1139 Effect.map((found) => found === undefined),
1140 Effect.orElseSucceed(() => false),
1141 );
1142 });
1143
1144 export interface DesktopWslEnvironmentTestStub {
1145 readonly isAvailable?: boolean;
1146 readonly distros?: ReadonlyArray<WslDistro>;
1147 readonly distroListError?: DesktopWslDistroListError;
1148 readonly windowsToWslPath?: (distro: string | null, windowsPath: string) => Option.Option<string>;
1149 readonly getUserHome?: (distro: string | null) => Option.Option<string>;
1150 readonly getDistroIp?: (distro: string | null) => Option.Option<string>;
1151 readonly prepareRuntime?: (
1152 distro: string | null,
1153 archive: WslRuntimeArchive,
1154 t3Home: string | null,
1155 ) => PrepareWslRuntimeResult;
1156 readonly pruneRuntimes?: (
1157 distro: string | null,
1158 runtimeId: string,
1159 t3Home: string | null,
1160 ) => Effect.Effect<void>;
1161 readonly probeRuntime?: (distro: string | null) => ProbeWslRuntimeResult;
1162 readonly ensureNodePty?: (
1163 distro: string | null,
1164 linuxAppRoot: string,
1165 options?: EnsureWslNodePtyOptions,
1166 ) => EnsureWslNodePtyResult;
1167 }
1168
1169 export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
1170 const probeDistros: Effect.Effect<readonly WslDistro[], DesktopWslDistroListError> =
1171 stub.distroListError ? Effect.fail(stub.distroListError) : Effect.succeed(stub.distros ?? []);
1172 return Layer.succeed(
1173 DesktopWslEnvironment,
1174 DesktopWslEnvironment.of({
1175 isAvailable: Effect.succeed(stub.isAvailable ?? false),
1176 listDistros: probeDistros.pipe(Effect.orElseSucceed(() => [])),
1177 probeDistros,
1178 preWarm: Effect.fn("DesktopWslEnvironment.preWarm")(function () {
1179 return Effect.void;
1180 }),
1181 windowsToWslPath: Effect.fn("DesktopWslEnvironment.windowsToWslPath")(
1182 function (distro, windowsPath) {
1183 return Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none());
1184 },
1185 ),
1186 getUserHome: Effect.fn("DesktopWslEnvironment.getUserHome")(function (distro) {
1187 return Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>());
1188 }),
1189 getDistroIp: Effect.fn("DesktopWslEnvironment.getDistroIp")(function (distro) {
1190 return Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>());
1191 }),
1192 prepareRuntime: Effect.fn("DesktopWslEnvironment.prepareRuntime")(
1193 function (distro, archive, t3Home) {
1194 return Effect.succeed(
1195 stub.prepareRuntime?.(distro, archive, t3Home) ?? {
1196 ok: false,
1197 reason: "prepareRuntime stub not configured",
1198 },
1199 );
1200 },
1201 ),
1202 pruneRuntimes: Effect.fn("DesktopWslEnvironment.pruneRuntimes")(
1203 function (distro, runtimeId, t3Home) {
1204 return stub.pruneRuntimes?.(distro, runtimeId, t3Home) ?? Effect.void;
1205 },
1206 ),
1207 probeRuntime: Effect.fn("DesktopWslEnvironment.probeRuntime")(function (distro) {
1208 return Effect.succeed(
1209 stub.probeRuntime?.(distro) ?? {
1210 ok: true,
1211 resolvedPath: "/usr/bin:/bin",
1212 t3Home: null,
1213 },
1214 );
1215 }),
1216 ensureNodePty: Effect.fn("DesktopWslEnvironment.ensureNodePty")(
1217 function (distro, linuxAppRoot, options) {
1218 return Effect.succeed(
1219 stub.ensureNodePty?.(distro, linuxAppRoot, options) ?? {
1220 ok: false,
1221 reason: "ensureNodePty stub not configured",
1222 fatal: true,
1223 },
1224 );
1225 },
1226 ),
1227 }),
1228 );
1229 };
1230
1231 export const layer = Layer.effect(
1232 DesktopWslEnvironment,
1233 Effect.gen(function* () {
1234 const environment = yield* DesktopEnvironment.DesktopEnvironment;
1235 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1236 const fileSystem = yield* FileSystem.FileSystem;
1237 // Not Config: Windows variable names are case-insensitive only on the live process.env.
1238 const windir = (yield* HostProcess.Environment).WINDIR ?? "C:\\Windows";
1239
1240 const provideSpawner = <A, E>(
1241 effect: Effect.Effect<A, E, ChildProcessSpawner.ChildProcessSpawner>,
1242 ): Effect.Effect<A, E> =>
1243 effect.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
1244
1245 // Cache availability so synchronous IPC bootstrap can read it without yielding to filesystem I/O.
1246 const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe(
1247 Effect.provideService(FileSystem.FileSystem, fileSystem),
1248 Effect.provideService(Path.Path, environment.path),
1249 Effect.provideService(
1250 DesktopManagedPolicy.DesktopManagedPolicy,
1251 yield* DesktopManagedPolicy.DesktopManagedPolicy,
1252 ),
1253 Effect.withSpan("desktop.wsl.isAvailable"),
1254 );
1255 const isAvailable = Effect.succeed(wslAvailable);
1256
1257 const windowsToWslPath = (distro: string | null, windowsPath: string) =>
1258 provideSpawner(windowsToWslPathImpl(distro, windowsPath)).pipe(
1259 Effect.withSpan("desktop.wsl.windowsToWslPath"),
1260 );
1261
1262 const userHomeCache = new Map<string, string>();
1263 const getUserHome = Effect.fn("desktop.wsl.getUserHome")(function* (distro: string | null) {
1264 const key = distro ?? "__default__";
1265 const cached = userHomeCache.get(key);
1266 if (cached !== undefined) return Option.some(cached);
1267 const resolved = yield* provideSpawner(getUserHomeImpl(distro));
1268 if (Option.isSome(resolved)) userHomeCache.set(key, resolved.value);
1269 return resolved;
1270 });
1271
1272 const getDistroIp = (distro: string | null) =>
1273 provideSpawner(getDistroIpImpl(distro)).pipe(Effect.withSpan("desktop.wsl.getDistroIp"));
1274
1275 const probeDistros = provideSpawner(probeWslDistros).pipe(
1276 Effect.withSpan("desktop.wsl.probeDistros"),
1277 );
1278
1279 return DesktopWslEnvironment.of({
1280 isAvailable,
1281 listDistros: probeDistros.pipe(
1282 Effect.orElseSucceed(() => []),
1283 Effect.withSpan("desktop.wsl.listDistros"),
1284 ),
1285 probeDistros,
1286 preWarm: Effect.fn("desktop.wsl.preWarm")(function (distro) {
1287 return provideSpawner(preWarmImpl(distro));
1288 }),
1289 windowsToWslPath,
1290 getUserHome,
1291 getDistroIp,
1292 prepareRuntime: Effect.fn("desktop.wsl.prepareRuntime")(function (distro, archive, t3Home) {
1293 return provideSpawner(
1294 prepareWslRuntimeImpl(distro, archive, t3Home, windowsToWslPath).pipe(
1295 Effect.provideService(FileSystem.FileSystem, fileSystem),
1296 ),
1297 );
1298 }),
1299 pruneRuntimes: Effect.fn("desktop.wsl.pruneRuntimes")(function (distro, runtimeId, t3Home) {
1300 return provideSpawner(pruneWslRuntimesImpl(distro, runtimeId, t3Home));
1301 }),
1302 probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro) {
1303 return provideSpawner(probeWslRuntimeImpl(distro));
1304 }),
1305 ensureNodePty: Effect.fn("desktop.wsl.ensureNodePty")(
1306 function (distro, linuxAppRoot, options) {
1307 return provideSpawner(ensureNodePtyImpl(distro, linuxAppRoot, options));
1308 },
1309 ),
1310 });
1311 }),
1312 );