The best way to control Claude Code, Codex and more from any computer or phone
perf(desktop): WSL preflight starts the staged runtime once instead of twice (#37052)
Julius Marminge committed
Nov 14, 2026 at 23:33 UTC
5d589547f0e2c45994a43e39203fd8c0c409553e
9 files changed
+186
-61
apps/desktop/src/app/DesktopApp.ts
-2
@@ -308,11 +308,9 @@ const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: bool
308
}
309
310
const primaryBackend = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary;
311
- // WSL-only fallback can change the primary endpoint before readiness.
311
const config = yield* primaryBackend.currentConfig;
312
if (
313
!environment.isDevelopment &&
315
- !settings.wslOnly &&
314
Option.isSome(config) &&
315
Option.isNone(config.value.preflightFailure)
316
) {
apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
+11
-11
@@ -385,7 +385,7 @@ describe("DesktopBackendConfiguration", () => {
385
runtimeId: string;
386
sha256: string;
387
}> = [];
388
- const observedProbeRoots: string[] = [];
388
+ let probeCount = 0;
389
let legacyCleanupCount = 0;
390
const linuxAppRoot = "/home/test/.t3/wsl-runtime/1.2.3-x64";
391
const resolvedPath = "/home/test/.local/bin:/usr/bin:/bin";
@@ -406,8 +406,8 @@ describe("DesktopBackendConfiguration", () => {
406
});
407
return { ok: true, linuxAppRoot };
408
},
409
- probeRuntime: (_distro, root) => {
410
- observedProbeRoots.push(root);
409
+ probeRuntime: () => {
410
+ probeCount += 1;
411
return { ok: true, resolvedPath };
412
},
413
ensureNodePty: () => {
@@ -428,7 +428,7 @@ describe("DesktopBackendConfiguration", () => {
428
sha256: archiveHash,
429
},
430
]);
431
- assert.deepEqual(observedProbeRoots, [linuxAppRoot]);
431
+ assert.equal(probeCount, 1);
432
assert.equal(
433
config.entryPath,
434
path.join(baseDir, "server.asar/apps/server/dist/bin.mjs"),
@@ -523,10 +523,10 @@ describe("DesktopBackendConfiguration", () => {
523
);
524
});
525
526
- it.effect("resolveWsl retires a staged runtime whose executable does not start", () => {
526
+ it.effect("resolveWsl retires a staged runtime whose launch probe fails", () => {
527
const archiveHash = "c".repeat(64);
528
const stagedAppRoot = `/home/test/.t3/wsl-runtime/sha256-${archiveHash}`;
529
- const observedProbeRoots: string[] = [];
529
+ let probeCount = 0;
530
const observedNodePtyRoots: string[] = [];
531
const invalidatedRuntimeIds: string[] = [];
532
return withPackagedWslHarness(
@@ -538,9 +538,9 @@ describe("DesktopBackendConfiguration", () => {
538
Effect.sync(() => {
539
invalidatedRuntimeIds.push(runtimeId);
540
}),
541
- probeRuntime: (_distro, root) => {
542
- observedProbeRoots.push(root);
543
- return { ok: false, reason: `${root}/t3 --version failed (exit 127)` };
541
+ probeRuntime: () => {
542
+ probeCount += 1;
543
+ return { ok: false, reason: "WSL login-shell PATH could not be resolved" };
544
},
545
ensureNodePty: (_distro, root) => {
546
observedNodePtyRoots.push(root);
@@ -553,7 +553,7 @@ describe("DesktopBackendConfiguration", () => {
553
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
554
const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
555
556
- assert.deepEqual(observedProbeRoots, [stagedAppRoot]);
556
+ assert.equal(probeCount, 1);
557
assert.deepEqual(observedNodePtyRoots, [mountedAppRoot]);
558
assert.include(config.args, "/usr/bin/node");
559
assert.include(config.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`);
@@ -578,7 +578,7 @@ describe("DesktopBackendConfiguration", () => {
578
Effect.sync(() => {
579
invalidatedRuntimeIds.push(runtimeId);
580
}),
581
- probeRuntime: () => ({ ok: false, reason: "t3 --version failed (exit 1)" }),
581
+ probeRuntime: () => ({ ok: false, reason: "WSL login-shell PATH could not be resolved" }),
582
ensureNodePty: () => ({
583
ok: false,
584
reason: "WSL backend preflight timed out while probing for Node.js.",
apps/desktop/src/backend/DesktopBackendConfiguration.ts
+2
-2
@@ -424,7 +424,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f
424
const runtime = yield* wslEnv.prepareRuntime(runningDistro, input.runtimeArchive);
425
if (runtime.ok) {
426
// Staged runtimes bundle Node and node-pty; provider PATH discovery must not require them.
427
- const stagedProbe = yield* wslEnv.probeRuntime(runningDistro, runtime.linuxAppRoot);
427
+ const stagedProbe = yield* wslEnv.probeRuntime(runningDistro);
428
if (stagedProbe.ok) {
429
yield* wslServerTree.cleanupLegacy;
430
return {
@@ -437,7 +437,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f
437
} as const;
438
}
439
yield* Effect.logWarning(
440
- "The staged WSL runtime did not start; retrying from the mounted server tree.",
440
+ "The staged WSL runtime probe failed; retrying from the mounted server tree.",
441
{ reason: stagedProbe.reason },
442
);
443
stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, reason: stagedProbe.reason };
apps/desktop/src/backend/DesktopBackendManager.test.ts
+38
@@ -11,6 +11,7 @@ import {
11
DATABASE_MIGRATIONS_STARTED_MESSAGE,
12
} from "@t3tools/shared/databaseMigrationLog";
13
import { assert, describe, it } from "@effect/vitest";
14
+import * as Clock from "effect/Clock";
15
import * as Deferred from "effect/Deferred";
16
import * as Duration from "effect/Duration";
17
import * as Effect from "effect/Effect";
@@ -239,6 +240,43 @@ describe("DesktopBackendManager", () => {
240
}),
241
);
242
243
+ it.effect("notices a WSL backend soon after it listens despite slow refused connects", () =>
244
+ Effect.gen(function* () {
245
+ const ready = yield* Deferred.make<void>();
246
+ const exit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
247
+ const instance = yield* makeTestInstance({
248
+ config: { ...baseConfig, httpBaseUrl: new URL("http://172.20.84.98:3773") },
249
+ onReady: Deferred.succeed(ready, undefined).pipe(Effect.asVoid),
250
+ spawnerLayer: Layer.succeed(
251
+ ChildProcessSpawner.ChildProcessSpawner,
252
+ ChildProcessSpawner.make(() =>
253
+ Effect.acquireRelease(
254
+ Effect.succeed(makeProcess({ exitCode: Deferred.await(exit) })),
255
+ () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)),
256
+ ),
257
+ ),
258
+ ),
259
+ // Before the server listens at 300 ms, each refused connect takes a second to fail.
260
+ httpClientLayer: layerHttpClient((request) =>
261
+ Clock.currentTimeMillis.pipe(
262
+ Effect.flatMap((now) =>
263
+ now < 300
264
+ ? Effect.sleep(Duration.seconds(1)).pipe(
265
+ Effect.as(responseForRequest(request, 503)),
266
+ )
267
+ : Effect.succeed(responseForRequest(request, 200)),
268
+ ),
269
+ ),
270
+ ),
271
+ });
272
+ yield* instance.start;
273
+ yield* TestClock.adjust(Duration.millis(600));
274
+
275
+ assert.isTrue(yield* Deferred.isDone(ready));
276
+ yield* instance.stop();
277
+ }),
278
+ );
279
+
280
it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () =>
281
Effect.gen(function* () {
282
let spawnedCommand: ChildProcess.Command | undefined;
apps/desktop/src/backend/DesktopBackendManager.ts
+18
@@ -344,8 +344,26 @@ const closeRun = (
344
);
345
};
346
347
+const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "localhost", "[::1]"]);
348
+// Windows takes about a second to fail a refused connection to a non-loopback address such as a
349
+// WSL distro IP, so one sequential poller notices readiness up to a second late.
350
+const STAGGERED_READINESS_POLLERS = 4;
351
+const READINESS_POLLER_STAGGER = Duration.millis(250);
352
+
353
const waitForHttpReady = (
354
options: BackendProcessContext & { readonly timeout: Duration.Duration },
355
+): Effect.Effect<void, BackendReadinessTimeoutError, HttpClient.HttpClient> => {
356
+ const poll = pollHttpReady(options);
357
+ if (LOOPBACK_HOSTNAMES.has(options.httpBaseUrl.hostname)) return poll;
358
+ return Effect.raceAll(
359
+ Array.from({ length: STAGGERED_READINESS_POLLERS }, (_, index) =>
360
+ Effect.sleep(Duration.times(READINESS_POLLER_STAGGER, index)).pipe(Effect.andThen(poll)),
361
+ ),
362
+ );
363
+};
364
+
365
+const pollHttpReady = (
366
+ options: BackendProcessContext & { readonly timeout: Duration.Duration },
367
): Effect.Effect<void, BackendReadinessTimeoutError, HttpClient.HttpClient> => {
368
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
369
return waitForHttpReadyShared({
apps/desktop/src/backend/DesktopBackendPool.test.ts
+83
-5
@@ -112,6 +112,10 @@ function layerPool(
112
labelRef: Ref.Ref<string>,
113
options: {
114
readonly config?: DesktopBackendStartConfig;
115
+ readonly resolvePrimary?: Effect.Effect<DesktopBackendStartConfig>;
116
+ readonly onMainContentsCommand?: (
117
+ command: DesktopWindow.MainWindowContentsCommand,
118
+ ) => Effect.Effect<void>;
119
readonly fileSystem?: Partial<FileSystem.FileSystem>;
120
readonly spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
121
readonly httpClient?: HttpClient.HttpClient;
@@ -180,9 +184,11 @@ function layerPool(
184
}),
185
DesktopBrowserHost.layer,
186
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
183
- resolvePrimary: options.config
184
- ? Effect.succeed(options.config)
185
- : Effect.die("unexpected primary config resolve"),
187
+ resolvePrimary:
188
+ options.resolvePrimary ??
189
+ (options.config
190
+ ? Effect.succeed(options.config)
191
+ : Effect.die("unexpected primary config resolve")),
192
resolvePrimaryLabel: Ref.get(labelRef),
193
resolveWsl: () => Effect.die("unexpected WSL config resolve"),
194
currentBootstrapToken: Effect.die("unexpected bootstrap token read"),
@@ -190,7 +196,12 @@ function layerPool(
196
DesktopAppSettings.layerTest(),
197
DesktopState.layer,
198
DesktopWslEnvironment.layerTest(),
193
- ElectronDialog.layer,
199
+ Layer.succeed(ElectronDialog.ElectronDialog, {
200
+ pickFolder: () => Effect.die("unexpected folder picker"),
201
+ pickFiles: () => Effect.die("unexpected file picker"),
202
+ showMessageBox: () => Effect.die("unexpected message box"),
203
+ showErrorBox: () => Effect.void,
204
+ } satisfies ElectronDialog.ElectronDialog["Service"]),
205
ElectronApp.layer,
206
Layer.succeed(DesktopWindow.DesktopWindow, {
207
createMain: Effect.die("unexpected window create"),
@@ -206,7 +217,8 @@ function layerPool(
217
dispatchMenuAction: () => Effect.die("unexpected menu action"),
218
dispatchSnapShotEvent: () => Effect.void,
219
zoomMain: () => Effect.die("unexpected zoom"),
209
- runMainContentsCommand: () => Effect.die("unexpected main contents command"),
220
+ runMainContentsCommand:
221
+ options.onMainContentsCommand ?? (() => Effect.die("unexpected main contents command")),
222
syncAppearance: Effect.void,
223
} satisfies DesktopWindow.DesktopWindow["Service"]),
224
),
@@ -478,4 +490,70 @@ describe("DesktopBackendPool", () => {
490
assert.equal(Option.isNone(yield* pool.get(id)), true);
491
}).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows")))),
492
);
493
+
494
+ it.effect("reloads a main window that read the WSL endpoint before the Windows fallback", () =>
495
+ Effect.gen(function* () {
496
+ const events: string[] = [];
497
+ let resolves = 0;
498
+ const resolvePrimary = Effect.sync(() =>
499
+ resolves++ === 0
500
+ ? {
501
+ ...runningConfig,
502
+ preflightFailure: Option.some({
503
+ reason: "WSL still unavailable",
504
+ fatal: false,
505
+ retryLimit: 1,
506
+ }),
507
+ }
508
+ : runningConfig,
509
+ );
510
+ const ready = yield* Deferred.make<void>();
511
+ yield* Effect.gen(function* () {
512
+ const primary = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary;
513
+ yield* primary.start;
514
+ yield* TestClock.adjust(Duration.seconds(1));
515
+ yield* Deferred.await(ready);
516
+
517
+ assert.deepEqual(events, ["reload", "ready"]);
518
+ }).pipe(
519
+ Effect.provide(
520
+ layerPool(Ref.makeUnsafe("WSL"), {
521
+ resolvePrimary,
522
+ spawner: ChildProcessSpawner.make(() =>
523
+ Effect.gen(function* () {
524
+ const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
525
+ const exit = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe(
526
+ Effect.asVoid,
527
+ );
528
+ yield* Effect.addFinalizer(() => exit);
529
+ return ChildProcessSpawner.makeHandle({
530
+ pid: ChildProcessSpawner.ProcessId(123),
531
+ stdout: Stream.empty,
532
+ stderr: Stream.empty,
533
+ all: Stream.empty,
534
+ exitCode: Deferred.await(exited),
535
+ isRunning: Effect.succeed(true),
536
+ kill: () => exit,
537
+ stdin: Sink.drain,
538
+ getInputFd: () => Sink.drain,
539
+ getOutputFd: () => Stream.empty,
540
+ unref: Effect.succeed(Effect.void),
541
+ });
542
+ }),
543
+ ),
544
+ httpClient: HttpClient.make((request) =>
545
+ Effect.succeed(
546
+ HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })),
547
+ ),
548
+ ),
549
+ onMainContentsCommand: (command) => Effect.sync(() => void events.push(command)),
550
+ onReady: Effect.sync(() => void events.push("ready")).pipe(
551
+ Effect.andThen(Deferred.succeed(ready, undefined)),
552
+ Effect.asVoid,
553
+ ),
554
+ }),
555
+ ),
556
+ );
557
+ }),
558
+ );
559
});
apps/desktop/src/backend/DesktopBackendPool.ts
+13
@@ -167,10 +167,22 @@ export const layer = Layer.effect(
167
// One wait at a time: each run's shutdown or readiness ends the previous run's wait.
168
const updateMarkerWait = yield* FiberHandle.make<void>();
169
170
+ // The main window loads during startup and reads the primary endpoint once; a Windows fallback
171
+ // before the first readiness replaces the WSL endpoint it read.
172
+ let primaryWasReady = false;
173
+ let reloadMainOnReady = false;
174
+ const reloadStaleMain = Effect.suspend(() => {
175
+ primaryWasReady = true;
176
+ if (!reloadMainOnReady) return Effect.void;
177
+ reloadMainOnReady = false;
178
+ return desktopWindow.runMainContentsCommand("reload");
179
+ });
180
+
181
// Persist fatal Windows fallbacks; transient transport failures must preserve the user's WSL preference.
182
const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
183
function* (failure: DesktopBackendManager.PreflightFailure) {
184
const { reason, fatal } = failure;
185
+ if (!primaryWasReady) reloadMainOnReady = true;
186
if (!fatal) {
187
yield* logBackendPoolWarning(
188
"primary WSL preflight retry window exhausted; using Windows for this launch",
@@ -215,6 +227,7 @@ export const layer = Layer.effect(
227
// Absorb window errors so readiness can reset restartAttempt.
228
onReady: (httpBaseUrl, pid) =>
229
FiberHandle.run(updateMarkerWait, releaseUpdateMarker(httpBaseUrl, pid)).pipe(
230
+ Effect.andThen(reloadStaleMain),
231
Effect.andThen(desktopWindow.handleBackendReady(httpBaseUrl)),
232
// Only once the main window exists, so the recovery window never closes into nothing.
233
Effect.andThen(SubscriptionRef.set(primaryBackendStartup, { _tag: "Ready" })),
apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
+2
-2
@@ -172,7 +172,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed
172
" }",
173
' eval "$2"',
174
"); }",
175
- buildWslRuntimeProbeScript(fixture.runtimeRoot),
175
+ buildWslRuntimeProbeScript(),
176
].join("\n"),
177
);
178
@@ -207,7 +207,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed
207
[
208
"bash() { return 127; }",
209
'export PATH="/fixture/bin:/usr/bin:/bin"',
210
- buildWslRuntimeProbeScript(fixture.runtimeRoot),
210
+ buildWslRuntimeProbeScript(),
211
].join("\n"),
212
);
213
apps/desktop/src/wsl/DesktopWslEnvironment.ts
+19
-39
@@ -110,10 +110,7 @@ export class DesktopWslEnvironment extends Context.Service<
110
) => Effect.Effect<PrepareWslRuntimeResult>;
111
readonly pruneRuntimes: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
112
readonly invalidateRuntime: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
113
- readonly probeRuntime: (
114
- distro: string | null,
115
- linuxAppRoot: string,
116
- ) => Effect.Effect<ProbeWslRuntimeResult>;
113
+ readonly probeRuntime: (distro: string | null) => Effect.Effect<ProbeWslRuntimeResult>;
114
readonly ensureNodePty: (
115
distro: string | null,
116
linuxAppRoot: string,
@@ -483,11 +480,9 @@ require("node-pty");
480
NODE`;
481
482
// Resolve version-managed Node for providers without making runtime readiness depend on it.
486
-export const buildWslRuntimeProbeScript = (linuxAppRoot: string) =>
487
- [
488
- `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`,
489
- `${shellQuote(`${linuxAppRoot}/t3`)} --version >/dev/null 2>&1`,
490
- ].join("\n");
483
+// The install script already ran the staged t3, so running it again here only adds a second startup.
484
+export const buildWslRuntimeProbeScript = () =>
485
+ `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`;
486
487
const TOOLCHAIN_CHECK_SCRIPT = [
488
"for tool in node make g++ python3; do",
@@ -601,30 +596,17 @@ const formatMissingToolsReason = (
596
597
const probeWslRuntimeImpl = Effect.fn("DesktopWslEnvironment.probeWslRuntimeImpl")(function* (
598
distro: string | null,
604
- linuxAppRoot: string,
599
): Effect.fn.Return<ProbeWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> {
606
- const probe = yield* runWslShell(
607
- distro,
608
- buildWslRuntimeProbeScript(linuxAppRoot),
609
- PROBE_TIMEOUT,
610
- {
611
- resolveNode: false,
612
- },
613
- );
600
+ const probe = yield* runWslShell(distro, buildWslRuntimeProbeScript(), PROBE_TIMEOUT, {
601
+ resolveNode: false,
602
+ });
603
const transportFailureReason = formatWslShellTransportFailureReason(
604
probe.transportFailure,
616
- "the staged runtime",
605
+ "the login-shell PATH",
606
);
607
if (transportFailureReason !== null) {
608
return { ok: false, reason: transportFailureReason } as const;
609
}
621
- if (probe.exitCode !== 0) {
622
- const trimmedTail = probe.stderr.trim().slice(-500);
623
- return {
624
- ok: false,
625
- reason: `${linuxAppRoot}/t3 --version failed (exit ${probe.exitCode})${trimmedTail ? `: ${trimmedTail}` : ""}`,
626
- } as const;
627
- }
610
const resolvedPath = parseResolvedPath(probe.stdout);
611
if (resolvedPath === null) {
612
return {
@@ -1175,7 +1157,7 @@ export interface DesktopWslEnvironmentTestStub {
1157
) => PrepareWslRuntimeResult;
1158
readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
1159
readonly invalidateRuntime?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
1178
- readonly probeRuntime?: (distro: string | null, linuxAppRoot: string) => ProbeWslRuntimeResult;
1160
+ readonly probeRuntime?: (distro: string | null) => ProbeWslRuntimeResult;
1161
readonly ensureNodePty?: (
1162
distro: string | null,
1163
linuxAppRoot: string,
@@ -1222,16 +1204,14 @@ export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
1204
return stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void;
1205
},
1206
),
1225
- probeRuntime: Effect.fn("DesktopWslEnvironment.probeRuntime")(
1226
- function (distro, linuxAppRoot) {
1227
- return Effect.succeed(
1228
- stub.probeRuntime?.(distro, linuxAppRoot) ?? {
1229
- ok: true,
1230
- resolvedPath: "/usr/bin:/bin",
1231
- },
1232
- );
1233
- },
1234
- ),
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
+ },
1213
+ );
1214
+ }),
1215
ensureNodePty: Effect.fn("DesktopWslEnvironment.ensureNodePty")(
1216
function (distro, linuxAppRoot, options) {
1217
return Effect.succeed(
@@ -1321,8 +1301,8 @@ export const layer = Layer.effect(
1301
invalidateRuntime: Effect.fn("desktop.wsl.invalidateRuntime")(function (distro, runtimeId) {
1302
return provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId));
1303
}),
1324
- probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro, linuxAppRoot) {
1325
- return provideSpawner(probeWslRuntimeImpl(distro, linuxAppRoot));
1304
+ probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro) {
1305
+ return provideSpawner(probeWslRuntimeImpl(distro));
1306
}),
1307
ensureNodePty: Effect.fn("desktop.wsl.ensureNodePty")(
1308
function (distro, linuxAppRoot, options) {