Open History to see the last commit
1// Orchestrator that keeps the WSL pool instance in sync with the user's
2// settings. `reconcile` is the single entry point — bootstrap calls it
3// once after the primary backend starts, and the wsl.ts IPC calls it
4// after persisting a `wslBackendEnabled` or `wslDistro` change. The
5// effect is idempotent and never fails: errors (WSL not available, port
6// allocation failed, register failed) get logged and reconcile returns
7// having left the pool in a consistent state (either the previous WSL
8// instance is still running, or none is).
9//
10// The instance id encodes the desired distro selection — `wsl:default`
11// when the user picked "track the WSL default" (settings.wslDistro is
12// null) and `wsl:<distro>` otherwise. Changing the distro setting
13// changes the id, so reconcile unregisters the old instance before
14// registering the new one. The label that the frontend env switcher
15// renders is derived from the same field.
16//
17// Port allocation: the concrete WSL distro is the source of truth. The
18// Windows host supplies only a preferred port (one above the primary); config
19// resolution tests/binds that number inside Linux and can fall back to a
20// kernel-selected ephemeral Linux port. Windows-side socket availability is
21// intentionally not consulted because it is the wrong namespace for a
22// Linux-owned listener.
23
24import * as Cause from "effect/Cause";
25import type { DesktopWslDiagnosticRecord } from "@t3tools/contracts";
26import * as Context from "effect/Context";
27import * as Effect from "effect/Effect";
28import * as Layer from "effect/Layer";
29import * as Option from "effect/Option";
30import * as Ref from "effect/Ref";
31import * as Semaphore from "effect/Semaphore";
32
33import * as DesktopObservability from "../app/DesktopObservability.ts";
34import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts";
35import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
36import type { DesktopBackendStartConfig } from "../backend/DesktopBackendManager.ts";
37import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
38import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
39import * as DesktopWslEnvironment from "./DesktopWslEnvironment.ts";
40import * as DesktopWslDiagnostics from "./DesktopWslDiagnostics.ts";
41
42// Exported so callers that parse pool ids (e.g. the pickFolder IPC
43// handler in ipc/methods/window.ts) reference the same prefix this
44// module produces. Keeping it inline in two places risks silent
45// divergence if one ever gets renamed.
46export const WSL_INSTANCE_ID_PREFIX = "wsl:";
47const WSL_DEFAULT_DISTRO_ID = `${WSL_INSTANCE_ID_PREFIX}default`;
48
49export class DesktopWslBackend extends Context.Service<
50 DesktopWslBackend,
51 {
52 // Bring the pool in line with the current persisted WSL settings.
53 // Idempotent. Never fails (errors are logged); callers can chain it
54 // after persisting settings without an error-handling dance.
55 readonly reconcile: Effect.Effect<void>;
56 // Reason the dual-mode WSL secondary last failed preflight (no node, wrong
57 // version, missing build tools), or None. Read by the getWslState IPC so
58 // Connections settings can show it inline. None in wsl-only mode (that path
59 // surfaces via a dialog + Windows fallback).
60 readonly lastPreflightError: Effect.Effect<Option.Option<string>>;
61 readonly lastDiagnostic: Effect.Effect<Option.Option<DesktopWslDiagnosticRecord>>;
62 readonly retry: Effect.Effect<void>;
63 }
64>()("@t3tools/desktop/wsl/DesktopWslBackend") {}
65
66const { logInfo: logWslBackendInfo, logWarning: logWslBackendWarning } =
67 DesktopObservability.makeComponentLogger("desktop-wsl-backend");
68
69const resolveTargetInstanceId = (distro: string | null): DesktopBackendPool.BackendInstanceId =>
70 DesktopBackendPool.BackendInstanceId(
71 distro === null ? WSL_DEFAULT_DISTRO_ID : `${WSL_INSTANCE_ID_PREFIX}${distro}`,
72 );
73
74const isWslInstanceId = (id: DesktopBackendPool.BackendInstanceId): boolean =>
75 id.startsWith(WSL_INSTANCE_ID_PREFIX);
76
77const buildLabel = (distro: string | null): string =>
78 distro === null ? "WSL (default distro)" : `WSL (${distro})`;
79
80export const layer = Layer.effect(
81 DesktopWslBackend,
82 Effect.gen(function* () {
83 const pool = yield* DesktopBackendPool.DesktopBackendPool;
84 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
85 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
86 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
87 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
88 const diagnostics = yield* DesktopWslDiagnostics.DesktopWslDiagnostics;
89 // Serialize reconcile so the bootstrap fork and the IPC handlers
90 // (setWslBackendEnabled, setWslDistro) can't interleave. Without
91 // this, two reconciles could both observe "no WSL instance
92 // registered" between their pool reads and both call startNew
93 // with different distros, leaving the loser stranded.
94 const reconcileMutex = yield* Semaphore.make(1);
95
96 // Last fatal preflight failure from the dual-mode WSL *secondary*, surfaced
97 // inline in Connections settings. The primary's failure is handled by the
98 // pool (dialog + Windows fallback) instead; here the app stays usable on
99 // Windows, so we record the reason rather than interrupting. Cleared on any
100 // reconcile state change so it reflects the current attempt.
101 const preflightErrorRef = yield* Ref.make(Option.none<string>());
102
103 const recordDiagnostic = Effect.fn("desktop.wslBackend.recordDiagnostic")(function* (input: {
104 readonly phase: "preflight" | "spawn" | "readiness" | "runtime-exit" | "configuration";
105 readonly message: string;
106 readonly distro: string | null;
107 readonly config?: DesktopBackendStartConfig;
108 readonly pid?: number | null;
109 readonly restartAttempt?: number | null;
110 }) {
111 const distros = yield* wslEnvironment.probeDistros.pipe(Effect.orElseSucceed(() => []));
112 const effectiveDistro = input.config?.runningDistro ?? input.distro;
113 const distroRecord = effectiveDistro
114 ? distros.find((candidate) => candidate.name.toLowerCase() === effectiveDistro.toLowerCase())
115 : distros.find((candidate) => candidate.isDefault);
116 yield* diagnostics.record({
117 phase: input.phase,
118 message: input.message,
119 distro: effectiveDistro ?? distroRecord?.name ?? null,
120 wslVersion: distroRecord?.version ?? null,
121 nodePath: input.config?.wslNodePath ?? null,
122 httpBaseUrl: input.config?.httpBaseUrl.href ?? null,
123 bindHost: input.config?.bootstrap.host ?? null,
124 port: input.config?.bootstrap.port ?? null,
125 restartAttempt: input.restartAttempt ?? null,
126 pid: input.pid ?? null,
127 });
128 });
129
130 const findExistingWslInstance = pool.list.pipe(
131 Effect.map((instances) => instances.find((instance) => isWslInstanceId(instance.id))),
132 Effect.map(Option.fromNullishOr),
133 );
134
135 const stopExisting = (id: DesktopBackendPool.BackendInstanceId) =>
136 pool.unregister(id).pipe(
137 Effect.catchTags({
138 DesktopBackendPoolCannotUnregisterPrimaryError: (cause) =>
139 // Should never happen — wsl: ids are not the primary id — but
140 // log loudly if the logic ever drifts.
141 logWslBackendWarning("refusing to unregister primary as wsl instance", {
142 id,
143 error: cause.message,
144 }),
145 }),
146 );
147
148 const startNew = Effect.fn("desktop.wslBackend.startNew")(function* (input: {
149 readonly distro: string | null;
150 }) {
151 const primaryConfig = yield* serverExposure.backendConfig;
152 // Keep the historical "primary + 1" as a stable preference, but the
153 // actual availability decision now happens inside the selected distro.
154 // If the preferred number is occupied in Linux, resolveWsl may choose an
155 // ephemeral Linux port instead. Clamp 65536 back into the valid range;
156 // the WSL-side allocator will fall back if 65535 is already occupied.
157 const preferredPort = Math.min(primaryConfig.port + 1, 65_535);
158
159 const targetId = resolveTargetInstanceId(input.distro);
160 yield* logWslBackendInfo("registering WSL backend with pool", {
161 id: targetId,
162 preferredPort,
163 distro: input.distro ?? null,
164 });
165
166 const instance = yield* pool
167 .register({
168 id: targetId,
169 label: Effect.succeed(buildLabel(input.distro)),
170 configResolve: configuration.resolveWsl({
171 port: preferredPort,
172 distro: input.distro,
173 portStrategy: "wsl-auto",
174 }),
175 // Dual-mode secondary: record a fatal preflight failure so Connections
176 // settings can show why the WSL backend never appeared. No dialog or
177 // fallback — Windows is the primary and keeps working.
178 onPreflightFailed: (failure) =>
179 Ref.set(preflightErrorRef, Option.some(failure.reason)).pipe(
180 Effect.andThen(
181 recordDiagnostic({
182 phase: "preflight",
183 message: failure.reason,
184 distro: input.distro,
185 }),
186 ),
187 Effect.as(false),
188 ),
189 onFailure: (failure) =>
190 recordDiagnostic({
191 phase: failure.phase,
192 message: failure.reason,
193 distro: input.distro,
194 config: failure.config,
195 pid: failure.pid,
196 restartAttempt: failure.restartAttempt,
197 }),
198 onReady: () =>
199 Ref.set(preflightErrorRef, Option.none()).pipe(Effect.andThen(diagnostics.clear)),
200 })
201 .pipe(
202 Effect.map((registered) => Option.some(registered)),
203 Effect.catch((error) =>
204 logWslBackendWarning("WSL backend already registered, skipping start", {
205 id: targetId,
206 error: error.message,
207 }).pipe(Effect.as(Option.none<DesktopBackendPool.DesktopBackendInstance>())),
208 ),
209 );
210
211 yield* Option.match(instance, {
212 onNone: () => Effect.void,
213 onSome: (registered) => registered.start,
214 });
215 });
216
217 const reconcileBody = Effect.gen(function* () {
218 const settings = yield* appSettings.get;
219 const available = yield* wslEnvironment.isAvailable;
220 const existing = yield* findExistingWslInstance;
221 const existingId = Option.map(existing, (instance) => instance.id);
222
223 // In wsl-only mode the pool's primary IS the WSL backend (see
224 // DesktopBackendConfiguration.resolvePrimary), so the
225 // orchestrator skips registering a parallel "wsl:<distro>"
226 // secondary. Without this skip we'd spin up two WSL processes
227 // on the same distro for users who explicitly asked for one.
228 const shouldRun = settings.wslBackendEnabled && available && !settings.wslOnly;
229 const targetId = shouldRun
230 ? Option.some(resolveTargetInstanceId(settings.wslDistro))
231 : Option.none<DesktopBackendPool.BackendInstanceId>();
232
233 // No-op if the desired state already matches what's registered.
234 if (Option.isNone(targetId) && Option.isNone(existingId)) {
235 return;
236 }
237 if (
238 Option.isSome(targetId) &&
239 Option.isSome(existing) &&
240 targetId.value === existing.value.id
241 ) {
242 const existingInstance = existing.value;
243 const snapshot = yield* existingInstance.snapshot;
244 const isIdle =
245 !snapshot.ready && Option.isNone(snapshot.activePid) && !snapshot.restartScheduled;
246 if (isIdle) {
247 yield* logWslBackendInfo("retrying idle WSL backend", { id: existingInstance.id });
248 yield* Ref.set(preflightErrorRef, Option.none());
249 yield* existingInstance.start;
250 }
251 return;
252 }
253
254 // A real state change is happening (start, stop, or distro swap). Clear
255 // any stale secondary preflight error so it reflects this fresh attempt;
256 // onPreflightFailed re-sets it only if the new secondary exhausts retries.
257 yield* Ref.set(preflightErrorRef, Option.none());
258 yield* diagnostics.clear;
259
260 if (Option.isSome(existingId)) {
261 yield* logWslBackendInfo("tearing down WSL backend", { id: existingId.value });
262 yield* stopExisting(existingId.value);
263 }
264
265 if (Option.isSome(targetId)) {
266 // Pre-warm the WSL VM before registering so the readiness probe
267 // doesn't race wsl.exe's first-spawn cold start. preWarm tolerates
268 // distro=null (uses the WSL default) and is bounded by its own
269 // timeout, so it's safe to await unconditionally here.
270 yield* wslEnvironment.preWarm(settings.wslDistro);
271 yield* startNew({ distro: settings.wslDistro });
272 }
273 });
274
275 // Top-level safety net. Every internal step today already catches
276 // its own failures (port allocation, register, preWarm), so the
277 // inferred error type is `never` and this catch is a no-op in
278 // steady state. It's here to enforce the file-header contract
279 // ("reconcile never fails; errors are logged") if a future change
280 // introduces an unhandled failure path — otherwise IPC callers
281 // like setWslBackendEnabled would surface it to the renderer as
282 // an opaque error.
283 const reconcile = reconcileMutex
284 .withPermits(1)(reconcileBody)
285 .pipe(
286 Effect.catchCause((cause) =>
287 logWslBackendWarning("reconcile failed", { cause: Cause.pretty(cause) }),
288 ),
289 Effect.withSpan("desktop.wslBackend.reconcile"),
290 );
291
292 const retry = reconcileMutex.withPermits(1)(
293 Effect.gen(function* () {
294 yield* Ref.set(preflightErrorRef, Option.none());
295 yield* diagnostics.clear;
296 const existing = yield* findExistingWslInstance;
297 if (Option.isSome(existing)) {
298 yield* stopExisting(existing.value.id);
299 }
300 yield* reconcileBody;
301 }),
302 ).pipe(
303 Effect.catchCause((cause) =>
304 logWslBackendWarning("explicit WSL retry failed", { cause: Cause.pretty(cause) }),
305 ),
306 );
307
308 return DesktopWslBackend.of({
309 reconcile,
310 retry,
311 lastPreflightError: Ref.get(preflightErrorRef),
312 lastDiagnostic: diagnostics.current,
313 });
314 }),
315);