@devries-cameron20 / t3code-1 / commits / e5835c993a
Fork 0

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

fix(desktop): WSL backend starts in distros without automounted drives (#25734)

Julius Marminge committed Nov 13, 2026 at 19:21 UTC e5835c993a6af969088d1c8fe62278f711852b0a
2 files changed +258 -51
apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
+93
@@ -1,16 +1,22 @@
1 // @effect-diagnostics nodeBuiltinImport:off - the executed suite runs the generated install script through a real POSIX shell.
2 +import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { assert, describe, it } from "@effect/vitest";
4 import * as Effect from "effect/Effect";
5 import * as FileSystem from "effect/FileSystem";
6 import * as Layer from "effect/Layer";
7 import * as Path from "effect/Path";
8 +import * as Redacted from "effect/Redacted";
9 +import { ChildProcess, ChildProcessSpawner } from "effect/process";
10 import { afterAll, expect } from "vite-plus/test";
11 import * as NodeChildProcess from "node:child_process";
12
13 import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile";
14
15 +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
16 import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
17 import {
18 + DesktopWslEnvironment,
19 + layer as layerDesktopWslEnvironment,
20 buildWslRuntimeInstallScript,
21 makeIsAvailable,
22 buildWslRuntimeInvalidateScript,
@@ -380,6 +386,93 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed
386 expect(selected.status, `${selected.stdout}\n${selected.stderr}`).toBe(0);
387 });
388
389 + // Runs the distro side on the local bash, so a Windows dev box using the wsl.exe runner skips it.
390 + describe.skipIf(posixShellRunner?.file !== "bash")("prepareRuntime through wsl.exe", () => {
391 + // Emulates `wsl.exe [-d <distro>] [--cd <dir>] [--|--exec] <argv>` in a distro with automount off.
392 + const layerFakeWslExe = (home: string) =>
393 + Layer.effect(
394 + ChildProcessSpawner.ChildProcessSpawner,
395 + Effect.map(ChildProcessSpawner.ChildProcessSpawner, (local) =>
396 + ChildProcessSpawner.make((command) => {
397 + if (!ChildProcess.isStandardCommand(command) || command.command !== "wsl.exe") {
398 + return local.spawn(command);
399 + }
400 + const args = command.args.map((word) =>
401 + Redacted.isRedacted(word) ? Redacted.value(word) : word,
402 + );
403 + while (args.length > 0) {
404 + const flag = args[0];
405 + if (flag === "-d" || flag === "--distribution" || flag === "--cd") {
406 + args.splice(0, 2);
407 + } else if (flag === "--" || flag === "--exec" || flag === "-e") {
408 + args.shift();
409 + break;
410 + } else {
411 + break;
412 + }
413 + }
414 + const [file = "sh", ...rest] =
415 + args[0] === "wslpath"
416 + ? [
417 + "sh",
418 + "-c",
419 + 'printf "wslpath: %s\\n" "$1" >&2; exit 1',
420 + "wslpath",
421 + args.at(-1) ?? "",
422 + ]
423 + : args;
424 + return local.spawn(
425 + ChildProcess.make(file, rest, {
426 + ...command.options,
427 + env: { ...command.options.env, HOME: home },
428 + extendEnv: true,
429 + }),
430 + );
431 + }),
432 + ),
433 + );
434 +
435 + const layerWslEnvironment = (home: string) =>
436 + layerDesktopWslEnvironment.pipe(
437 + Layer.provide(
438 + Layer.mergeAll(
439 + layerFakeWslExe(home),
440 + DesktopManagedPolicy.layerTest(),
441 + Layer.effect(
442 + DesktopEnvironment.DesktopEnvironment,
443 + Effect.map(
444 + Path.Path,
445 + (path) =>
446 + ({ platform: "win32", path }) as DesktopEnvironment.DesktopEnvironment["Service"],
447 + ),
448 + ),
449 + ),
450 + ),
451 + Layer.provide(NodeServices.layer),
452 + );
453 +
454 + it.live("installs the runtime when wslpath cannot translate the archive's Windows path", () => {
455 + const fixture = createFixture();
456 + return Effect.gen(function* () {
457 + const wsl = yield* DesktopWslEnvironment;
458 + // The archive's Windows path; with no drives mounted, wslpath cannot map it into the distro.
459 + const translated = yield* wsl.windowsToWslPath("Ubuntu", fixture.archivePath);
460 + expect(translated._tag).toBe("None");
461 +
462 + const prepared = yield* wsl.prepareRuntime("Ubuntu", {
463 + windowsPath: fixture.archivePath,
464 + runtimeId: fixture.runtimeId,
465 + sha256: fixture.archiveSha,
466 + });
467 +
468 + expect(prepared).toEqual({ ok: true, linuxAppRoot: fixture.runtimeRoot });
469 + const version = runShell(`${sh(fixture.serverEntry)} --version`);
470 + expect(version.status, version.stderr).toBe(0);
471 + expect(version.stdout).toBe("t3code wsl runtime test server 0.0.0\n");
472 + }).pipe(Effect.provide(layerWslEnvironment(`${fixture.work}/home`)));
473 + });
474 + });
475 +
476 it("prunes old and markerless caches without touching retained, active, locked, or unrelated roots", () => {
477 const result = runShell(
478 [
apps/desktop/src/wsl/DesktopWslEnvironment.ts
+165 -51
@@ -5,6 +5,8 @@ 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";
@@ -173,37 +175,19 @@ const buildWslNodeEnvPreamble = (
175 ensure_remote_node_path || true
176 `;
177
176 -// wsl.exe re-escaping mangles quotes inside bash -lc scripts.
177 -const runWslShell = (
178 - distro: string | null,
179 - bashScript: string,
178 +const runWslProcess = (
179 + args: ReadonlyArray<string>,
180 + stdin: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
181 timeout: Duration.Duration,
181 - options: {
182 - readonly nodeEngineRange?: string | null;
183 - readonly resolveNode?: boolean;
184 - } = {},
182 ): Effect.Effect<ShellResult, never, ChildProcessSpawner.ChildProcessSpawner> => {
183 const spawner = ChildProcessSpawner.ChildProcessSpawner;
187 - const resolveNode = options.resolveNode !== false;
188 - const command = ChildProcess.make(
189 - "wsl.exe",
190 - resolveNode
191 - ? [...buildDistroArgs(distro), "--", "bash", "-l", "-s"]
192 - : [...buildDistroArgs(distro), "--exec", "sh", "-s"],
193 - {
194 - stdin: Stream.encodeText(
195 - Stream.make(
196 - resolveNode
197 - ? `${buildWslNodeEnvPreamble(options.nodeEngineRange)}${bashScript}`
198 - : bashScript,
199 - ),
200 - ),
201 - stdout: "pipe",
202 - stderr: "pipe",
203 - killSignal: "SIGTERM",
204 - forceKillAfter: PROCESS_TERMINATE_GRACE,
205 - },
206 - );
184 + const command = ChildProcess.make("wsl.exe", args, {
185 + stdin,
186 + stdout: "pipe",
187 + stderr: "pipe",
188 + killSignal: "SIGTERM",
189 + forceKillAfter: PROCESS_TERMINATE_GRACE,
190 + });
191
192 return Effect.scoped(
193 Effect.gen(function* () {
@@ -249,6 +233,32 @@ const runWslShell = (
233 );
234 };
235
236 +// wsl.exe re-escaping mangles quotes inside bash -lc scripts.
237 +const runWslShell = (
238 + distro: string | null,
239 + bashScript: string,
240 + timeout: Duration.Duration,
241 + options: {
242 + readonly nodeEngineRange?: string | null;
243 + readonly resolveNode?: boolean;
244 + } = {},
245 +): Effect.Effect<ShellResult, never, ChildProcessSpawner.ChildProcessSpawner> => {
246 + const resolveNode = options.resolveNode !== false;
247 + return runWslProcess(
248 + resolveNode
249 + ? [...buildDistroArgs(distro), "--", "bash", "-l", "-s"]
250 + : [...buildDistroArgs(distro), "--exec", "sh", "-s"],
251 + Stream.encodeText(
252 + Stream.make(
253 + resolveNode
254 + ? `${buildWslNodeEnvPreamble(options.nodeEngineRange)}${bashScript}`
255 + : bashScript,
256 + ),
257 + ),
258 + timeout,
259 + );
260 +};
261 +
262 const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
263
264 const WSL_RUNTIME_READY_MARKER = ".t3code-wsl-runtime-ready";
@@ -257,13 +267,14 @@ const WSL_RUNTIME_SELECTION_GRACE_MINUTES = 5;
267
268 const sanitizeWslRuntimeId = (value: string): string => value.replace(/[^A-Za-z0-9._-]/g, "_");
269
270 +// A null archive path asks for a staging directory to copy the archive into, unless the cache is ready.
271 export const buildWslRuntimeInstallScript = (
261 - linuxArchivePath: string,
272 + linuxArchivePath: string | null,
273 runtimeId: string,
274 archiveSha256: string,
275 ): string => {
276 const safeRuntimeId = sanitizeWslRuntimeId(runtimeId);
266 - return [
277 + const readyCheck = [
278 "set -eu",
279 'runtime_parent="$HOME/.t3/wsl-runtime"',
280 `runtime_root="$runtime_parent/${safeRuntimeId}"`,
@@ -292,6 +303,17 @@ export const buildWslRuntimeInstallScript = (
303 ` printf 'runtimeRoot:%s\\n' "$runtime_root"`,
304 " exit 0",
305 "fi",
306 + ];
307 + if (linuxArchivePath === null) {
308 + return [
309 + ...readyCheck,
310 + // The .tmp. name lets pruning collect a stage orphaned by a crash.
311 + `archive_stage=$(mktemp -d "$runtime_parent/.${safeRuntimeId}.tmp.XXXXXX")`,
312 + `printf 'archiveStage:%s\\n' "$archive_stage"`,
313 + ].join("\n");
314 + }
315 + return [
316 + ...readyCheck,
317 `archive_sha=$(sha256sum ${shellQuote(linuxArchivePath)} | cut -d ' ' -f 1)`,
318 `if [ "$archive_sha" != ${shellQuote(archiveSha256)} ]; then`,
319 ` printf 'WSL runtime archive does not match its recorded SHA-256 (expected %s, got %s)\\n' ${shellQuote(archiveSha256)} "$archive_sha" >&2`,
@@ -409,14 +431,17 @@ export const buildWslRuntimeInvalidateScript = (runtimeId: string): string => {
431 ].join("\n");
432 };
433
412 -export const parseWslRuntimeRoot = (stdout: string): string | null => {
413 - const prefix = "runtimeRoot:";
434 +const parseAbsolutePathField = (stdout: string, field: string): string | null => {
435 + const prefix = `${field}:`;
436 const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));
437 if (line === undefined) return null;
416 - const runtimeRoot = line.slice(prefix.length).replace(/\r$/, "");
417 - return runtimeRoot.startsWith("/") ? runtimeRoot : null;
438 + const value = line.slice(prefix.length).replace(/\r$/, "");
439 + return value.startsWith("/") ? value : null;
440 };
441
442 +export const parseWslRuntimeRoot = (stdout: string): string | null =>
443 + parseAbsolutePathField(stdout, "runtimeRoot");
444 +
445 const NODE_PTY_BINARY_MISSING_EXIT_CODE = 4;
446
447 const formatNodePtyProbeFailureReason = (exitCode: number): string | null =>
@@ -775,25 +800,18 @@ const ensureNodePtyImpl = Effect.fn("DesktopWslEnvironment.ensureNodePtyImpl")(f
800 } as const;
801 });
802
778 -const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(function* (
803 +type WslRuntimeInstallOutcome =
804 + | { readonly ok: true; readonly stdout: string }
805 + | { readonly ok: false; readonly reason: string };
806 +
807 +const runWslRuntimeInstall = Effect.fn("desktop.wsl.runRuntimeInstall")(function* (
808 distro: string | null,
809 archive: WslRuntimeArchive,
781 - windowsToWslPath: (
782 - distro: string | null,
783 - windowsPath: string,
784 - ) => Effect.Effect<Option.Option<string>>,
785 -): Effect.fn.Return<PrepareWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> {
786 - const linuxArchivePath = yield* windowsToWslPath(distro, archive.windowsPath);
787 - if (Option.isNone(linuxArchivePath)) {
788 - return {
789 - ok: false,
790 - reason: `wslpath conversion failed for ${archive.windowsPath}`,
791 - } as const;
792 - }
793 -
810 + linuxArchivePath: string | null,
811 +): Effect.fn.Return<WslRuntimeInstallOutcome, never, ChildProcessSpawner.ChildProcessSpawner> {
812 const install = yield* runWslShell(
813 distro,
796 - buildWslRuntimeInstallScript(linuxArchivePath.value, archive.runtimeId, archive.sha256),
814 + buildWslRuntimeInstallScript(linuxArchivePath, archive.runtimeId, archive.sha256),
815 RUNTIME_INSTALL_TIMEOUT,
816 { resolveNode: false },
817 );
@@ -813,14 +831,106 @@ const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(functi
831 reason: `WSL runtime installation failed (exit ${install.exitCode}): ${trimmedTail || "no stderr captured"}`,
832 } as const;
833 }
834 + return { ok: true, stdout: install.stdout } as const;
835 +});
836
817 - const linuxAppRoot = parseWslRuntimeRoot(install.stdout);
837 +const toPrepareWslRuntimeResult = (outcome: WslRuntimeInstallOutcome): PrepareWslRuntimeResult => {
838 + if (!outcome.ok) return outcome;
839 + const linuxAppRoot = parseWslRuntimeRoot(outcome.stdout);
840 return linuxAppRoot === null
841 ? {
842 ok: false,
843 reason: "WSL runtime installation completed without reporting its cache path.",
844 }
845 : { ok: true, linuxAppRoot };
846 +};
847 +
848 +// Without drive mounts (`[automount] enabled=false`) wslpath cannot reach the archive, so copy it in over stdin.
849 +const installWslRuntimeFromHostCopy = Effect.fn("desktop.wsl.installRuntimeFromHostCopy")(
850 + function* (
851 + distro: string | null,
852 + archive: WslRuntimeArchive,
853 + archiveBytes: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
854 + ): Effect.fn.Return<PrepareWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> {
855 + const staged = yield* runWslRuntimeInstall(distro, archive, null);
856 + if (!staged.ok || parseWslRuntimeRoot(staged.stdout) !== null) {
857 + return toPrepareWslRuntimeResult(staged);
858 + }
859 + const stage = parseAbsolutePathField(staged.stdout, "archiveStage");
860 + if (stage === null) {
861 + return {
862 + ok: false,
863 + reason: `wslpath conversion failed for ${archive.windowsPath}, and the distro did not provide a directory to copy the runtime archive into.`,
864 + } as const;
865 + }
866 + const linuxArchivePath = `${stage}/runtime.tar.gz`;
867 +
868 + const copyAndInstall = Effect.gen(function* () {
869 + const readError = yield* Ref.make(Option.none<PlatformError.PlatformError>());
870 + // dd reads fd 0 itself; reopening /dev/stdin fails when WSL relays stdin as a socket.
871 + const copy = yield* runWslProcess(
872 + [...buildDistroArgs(distro), "--exec", "dd", `of=${linuxArchivePath}`, "bs=65536"],
873 + archiveBytes.pipe(
874 + // Ending stdin on a read error lets dd exit instead of waiting out the timeout.
875 + Stream.catch((error) =>
876 + Stream.drain(Stream.fromEffect(Ref.set(readError, Option.some(error)))),
877 + ),
878 + ),
879 + RUNTIME_INSTALL_TIMEOUT,
880 + );
881 + const failedRead = yield* Ref.get(readError);
882 + if (Option.isSome(failedRead)) {
883 + return {
884 + ok: false,
885 + reason: `Could not read the WSL runtime archive at ${archive.windowsPath}: ${failedRead.value.message}`,
886 + } as const;
887 + }
888 + if (copy.transportFailure !== null || copy.exitCode !== 0) {
889 + const trimmedTail = copy.stderr.trim().slice(-500);
890 + return {
891 + ok: false,
892 + reason: `Could not copy the WSL runtime archive into the distro (exit ${copy.exitCode})${trimmedTail ? `: ${trimmedTail}` : ""}`,
893 + } as const;
894 + }
895 + return toPrepareWslRuntimeResult(
896 + yield* runWslRuntimeInstall(distro, archive, linuxArchivePath),
897 + );
898 + });
899 +
900 + return yield* copyAndInstall.pipe(
901 + Effect.ensuring(
902 + runWslShell(distro, `rm -rf ${shellQuote(stage)}`, RUNTIME_INVALIDATE_TIMEOUT, {
903 + resolveNode: false,
904 + }),
905 + ),
906 + );
907 + },
908 +);
909 +
910 +const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(function* (
911 + distro: string | null,
912 + archive: WslRuntimeArchive,
913 + windowsToWslPath: (
914 + distro: string | null,
915 + windowsPath: string,
916 + ) => Effect.Effect<Option.Option<string>>,
917 +): Effect.fn.Return<
918 + PrepareWslRuntimeResult,
919 + never,
920 + ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
921 +> {
922 + const linuxArchivePath = yield* windowsToWslPath(distro, archive.windowsPath);
923 + if (Option.isNone(linuxArchivePath)) {
924 + const fileSystem = yield* FileSystem.FileSystem;
925 + return yield* installWslRuntimeFromHostCopy(
926 + distro,
927 + archive,
928 + fileSystem.stream(archive.windowsPath),
929 + );
930 + }
931 + return toPrepareWslRuntimeResult(
932 + yield* runWslRuntimeInstall(distro, archive, linuxArchivePath.value),
933 + );
934 });
935
936 const pruneWslRuntimesImpl = Effect.fn("desktop.wsl.pruneRuntimesImpl")(function* (
@@ -1198,7 +1308,11 @@ export const layer = Layer.effect(
1308 getUserHome,
1309 getDistroIp,
1310 prepareRuntime: Effect.fn("desktop.wsl.prepareRuntime")(function (distro, archive) {
1201 - return provideSpawner(prepareWslRuntimeImpl(distro, archive, windowsToWslPath));
1311 + return provideSpawner(
1312 + prepareWslRuntimeImpl(distro, archive, windowsToWslPath).pipe(
1313 + Effect.provideService(FileSystem.FileSystem, fileSystem),
1314 + ),
1315 + );
1316 }),
1317 pruneRuntimes: Effect.fn("desktop.wsl.pruneRuntimes")(function (distro, runtimeId) {
1318 return provideSpawner(pruneWslRuntimesImpl(distro, runtimeId));