Open History to see the last commit
1// Pool registry for multiple backend processes. This file is the entry
2// point for the concurrent-Windows+WSL-backend feature; see the design
3// notes below before extending it.
4//
5// Current state:
6// - `DesktopBackendManager.ts` exposes a per-instance factory
7// (`makeBackendInstance(spec)`); the pool calls it once for the
8// Windows primary at startup, and `DesktopWslBackend.reconcile`
9// calls it through `pool.register` to bring up the WSL instance
10// when the user enables it.
11// - The primary spec wires `configResolve` to
12// `DesktopBackendConfiguration.resolvePrimary` and the
13// `onReady`/`onShutdown` callbacks to the window service. WSL
14// instances wire `configResolve: configuration.resolveWsl(...)`
15// and skip onReady/onShutdown — the window only follows the primary.
16// - The pool exposes `register(spec)` and `unregister(id)`. Each
17// registered instance gets its own child scope, so unregister can
18// stop it cleanly without tearing down the pool. The primary's id
19// refuses unregister.
20// - Settings: `wslBackendEnabled: boolean` + `wslDistro: string | null`.
21// The legacy `wslMode: "local" | "wsl"` swap setting is migrated on
22// load. IPC surface is `setWslBackendEnabled(boolean)` +
23// `setWslDistro(string | null)`; both persist and then call the
24// orchestrator's reconcile. No swap, no rollback, primary stays up.
25// - `getLocalEnvironmentBootstraps()` (plural) returns one entry per
26// pool instance currently registered with bootstrap info. The
27// primary keeps the "primary" id; WSL instances are "wsl:default"
28// or "wsl:<distro>".
29// - `pickFolder` accepts an optional `targetEnvironmentId`. Omitting
30// it gives the Windows picker — what every existing caller gets,
31// and what non-WSL users see. WSL targets route to the wsl helpers.
32// - Web settings UX: a plain toggle for "WSL backend" plus a distro
33// picker that shows up when the toggle is on. Default-off, so
34// users who never opted in see the same surface as before.
35//
36// Renderer-side wiring (apps/web/src/environments/local/):
37// - reconcileLocalSecondaryEnvironments() runs at app boot and after
38// WSL settings changes. It reads getLocalEnvironmentBootstraps(),
39// skips the primary (which the existing primary/ runtime owns),
40// and for every other entry POSTs the shared bootstrap token to
41// /api/auth/bootstrap/bearer on that backend's URL, fetches the
42// descriptor, builds a SavedEnvironmentRecord marked desktopLocal,
43// writes the bearer to the secret store, and opens a connection
44// through the same saved-env path remote envs use.
45// - The desktopLocal marker filters records out of saved-env
46// persistence, so toggling WSL off or switching distros doesn't
47// pollute the user's settings file. The sidebar, CommandPalette,
48// env switcher, and project-id routing all read the saved-env
49// registry, so the WSL backend shows up there without any
50// per-surface changes.
51//
52// Browser validation (2026-05-17, dev:desktop with wslBackendEnabled=true,
53// wslDistro="Ubuntu"):
54// - Two backends listening on distinct loopback ports
55// (server.log: 13773 primary, 13774 wsl).
56// - Per-instance log files: server-child.log + server-child-wsl_Ubuntu.log.
57// - Distinct environment ids reported by each backend's
58// /.well-known/t3/environment (Windows vs Linux platform).
59// - Renderer completes the bearer-token bootstrap against the WSL
60// backend (POST /api/auth/bootstrap/bearer 200), obtains a
61// ws-token (POST /api/auth/ws-token 200), and holds an
62// ESTABLISHED WebSocket connection to both ports (netstat).
63//
64// Migration history (commits):
65// 1. Reshape `DesktopBackendManager` into an instance factory and route
66// consumers through the pool. Pool held a single instance. (a8fc7845)
67// 2. Drop `DesktopState.backendReady`. The window owns its own
68// readiness latch via onReady / onShutdown callbacks. (425c7d0b)
69// 3. Per-instance log routing via DesktopBackendOutputLogFactory. (563820ed)
70// 4. Add register/unregister to the pool. (a0eaf560)
71// 5. Wire WSL through the pool: settings rename, BackendConfiguration
72// split, DesktopWslBackend orchestrator, new IPC, web compat.
73// (b1622191 + 31ce3add + 627c80cb)
74// 6. Widen getLocalEnvironmentBootstrap to *Bootstraps (plural). (bad66041)
75// 7. pickFolder takes optional targetEnvironmentId. (5d80468d)
76// 8. Settings UX: toggle + distro picker, no swap dialog. (eb5a03ea)
77// 9. Register WSL backend as desktop-local saved env via
78// reconcileLocalSecondaryEnvironments. (1c7e7873 + c17897bd)
79// 10. CommandPalette enables file-manager picker for desktop-local
80// envs, routes pickFolder by env id. (38e8477a)
81
82import * as Context from "effect/Context";
83import * as Deferred from "effect/Deferred";
84import * as Effect from "effect/Effect";
85import * as Exit from "effect/Exit";
86import * as Layer from "effect/Layer";
87import * as Option from "effect/Option";
88import * as Schema from "effect/Schema";
89import * as Scope from "effect/Scope";
90import * as SynchronizedRef from "effect/SynchronizedRef";
91
92import * as FileSystem from "effect/FileSystem";
93import { HttpClient } from "effect/unstable/http";
94import { ChildProcessSpawner } from "effect/unstable/process";
95
96import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
97import * as DesktopBackendManager from "./DesktopBackendManager.ts";
98import * as DesktopObservability from "../app/DesktopObservability.ts";
99import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
100import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
101import * as DesktopWindow from "../window/DesktopWindow.ts";
102import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
103import * as ElectronDialog from "../electron/ElectronDialog.ts";
104
105const { logWarning: logBackendPoolWarning } =
106 DesktopObservability.makeComponentLogger("desktop-backend-pool");
107
108export type BackendInstanceId = DesktopBackendManager.BackendInstanceId;
109export const BackendInstanceId = DesktopBackendManager.BackendInstanceId;
110export const PRIMARY_INSTANCE_ID = DesktopBackendManager.PRIMARY_INSTANCE_ID;
111export type DesktopBackendInstance = DesktopBackendManager.DesktopBackendInstance;
112export type BackendInstanceSpec = DesktopBackendManager.BackendInstanceSpec;
113
114// Caller tried to register an id that's already in the pool. The pool
115// refuses overwrites so two independent orchestrators racing on the
116// same id surface as a typed failure instead of one silently winning.
117export class DesktopBackendPoolInstanceAlreadyRegisteredError extends Schema.TaggedError<DesktopBackendPoolInstanceAlreadyRegisteredError>()(
118 "DesktopBackendPoolInstanceAlreadyRegisteredError",
119 {
120 id: Schema.String,
121 },
122) {
123 override get message() {
124 return `Backend instance "${this.id}" is already registered in the pool.`;
125 }
126}
127
128// Primary instance is registered for the pool's lifetime. Unregister is
129// a no-op for it today (no real callers), but if someone wires it up
130// later it's a clear bug rather than something to "handle".
131export class DesktopBackendPoolCannotUnregisterPrimaryError extends Schema.TaggedError<DesktopBackendPoolCannotUnregisterPrimaryError>()(
132 "DesktopBackendPoolCannotUnregisterPrimaryError",
133 {},
134) {
135 override get message() {
136 return "Refusing to unregister the primary backend from the pool.";
137 }
138}
139
140export class DesktopBackendPool extends Context.Service<
141 DesktopBackendPool,
142 {
143 // Look up a registered instance. None when no backend with that id is
144 // currently registered (e.g. WSL backend disabled).
145 readonly get: (id: BackendInstanceId) => Effect.Effect<Option.Option<DesktopBackendInstance>>;
146 // Snapshot of all currently-registered instances. Order is unspecified;
147 // callers that need a canonical "primary first" view should sort by id.
148 readonly list: Effect.Effect<readonly DesktopBackendInstance[]>;
149 // Convenience accessor for the always-registered primary instance.
150 // Currently equivalent to `get(PRIMARY_INSTANCE_ID)` unwrapped, but
151 // exposed as a typed effect so consumers don't have to handle the
152 // Option for the case that's guaranteed to be present.
153 readonly primary: Effect.Effect<DesktopBackendInstance>;
154 // Build a fresh DesktopBackendInstance from `spec` and add it to the
155 // registry. The pool owns the instance's scope: unregister(id) or pool
156 // teardown closes it and runs the instance's auto-stop finalizer. The
157 // returned instance has not been started — callers decide when to
158 // start it (and can call start more than once if a retry-after-failure
159 // story makes sense for them).
160 readonly register: (
161 spec: BackendInstanceSpec,
162 ) => Effect.Effect<DesktopBackendInstance, DesktopBackendPoolInstanceAlreadyRegisteredError>;
163 // Stop the named instance and remove it from the registry. Closing the
164 // instance's scope triggers its auto-stop finalizer; the registry is
165 // updated atomically with the scope close so subsequent get(id) calls
166 // observe the unregister before the underlying child process has fully
167 // exited.
168 readonly unregister: (
169 id: BackendInstanceId,
170 ) => Effect.Effect<void, DesktopBackendPoolCannotUnregisterPrimaryError>;
171 }
172>()("@t3tools/desktop/backend/DesktopBackendPool") {}
173
174// Services required by makeBackendInstance — exported so caller
175// orchestrators that build their own specs can confirm the layer graph
176// satisfies them at compile time.
177export type BackendInstanceFactoryRequirements =
178 | FileSystem.FileSystem
179 | ChildProcessSpawner.ChildProcessSpawner
180 | HttpClient.HttpClient
181 | DesktopObservability.DesktopBackendOutputLogFactory
182 | DesktopTelemetryPublisher.DesktopTelemetryPublisher
183 | DesktopWslEnvironment.DesktopWslEnvironment;
184
185interface ActiveRegisteredInstance {
186 readonly _tag: "Active";
187 readonly instance: DesktopBackendInstance;
188 // None for the primary (which lives in the pool's own layer scope and
189 // is never unregistered); Some for instances added via register, whose
190 // scope unregister closes to stop them.
191 readonly scope: Option.Option<Scope.Closeable>;
192}
193
194interface ClosingRegisteredInstance {
195 readonly _tag: "Closing";
196 readonly done: Deferred.Deferred<void>;
197}
198
199type RegisteredInstance = ActiveRegisteredInstance | ClosingRegisteredInstance;
200
201type RegisterAction =
202 | { readonly _tag: "Registered"; readonly instance: DesktopBackendInstance }
203 | { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> };
204
205type UnregisterAction =
206 | { readonly _tag: "Absent" }
207 | { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> }
208 | { readonly _tag: "Close"; readonly entry: ActiveRegisteredInstance };
209
210export const layer = Layer.effect(
211 DesktopBackendPool,
212 Effect.gen(function* () {
213 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
214 const desktopWindow = yield* DesktopWindow.DesktopWindow;
215 const electronDialog = yield* ElectronDialog.ElectronDialog;
216 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
217 // Anchor the pool's lifetime to its layer scope so registered
218 // instance scopes can be forked off it. Without this, instance
219 // scopes are orphaned: they only close via explicit unregister()
220 // calls, so on app shutdown the WSL backend child process gets
221 // hard-killed by the OS instead of receiving the graceful
222 // SIGTERM + grace period the instance's stop finalizer would
223 // otherwise run.
224 const layerScope = yield* Scope.Scope;
225 // Capture the services needed to build any future instance from the
226 // pool's layer scope. register() runs `makeBackendInstance` against
227 // a fresh child scope but reuses these services so the instance gets
228 // the same FileSystem, spawner, HTTP client and log factory the
229 // primary instance uses.
230 const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
231
232 // A WSL preflight failure on the primary only happens in wsl-only mode.
233 // Fatal configuration failures persist the Windows fallback. Bounded
234 // transport failures use an in-memory fallback for this launch so the app
235 // opens without overwriting the user's WSL preference.
236 const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
237 function* (failure: DesktopBackendManager.PreflightFailure) {
238 const { reason, fatal } = failure;
239 if (!fatal) {
240 yield* logBackendPoolWarning(
241 "primary WSL preflight retry window exhausted; using Windows for this launch",
242 { reason },
243 );
244 yield* electronDialog.showErrorBox(
245 "WSL backend is still unavailable",
246 `${reason}\n\nT3 Code will use the Windows backend for this launch and retry WSL the next time the app starts.`,
247 );
248 yield* appSettings.applyWslWindowsFallbackInMemory;
249 return true;
250 }
251
252 yield* logBackendPoolWarning("primary WSL preflight failed; falling back to Windows", {
253 reason,
254 });
255 yield* electronDialog.showErrorBox(
256 "WSL backend couldn't start",
257 `${reason}\n\nFalling back to the Windows backend so T3 Code can open. Re-enable the WSL backend from Settings > Connections once the WSL distro is fixed.`,
258 );
259 // Fully disable the WSL backend — both flags, matching the "Switch to
260 // Windows" recovery path — so the manager's next restart re-resolves the
261 // primary as Windows and reconcile won't register a secondary WSL backend
262 // against the same broken setup. Clearing wslBackendEnabled alone would
263 // leave a stale wslOnly:true that silently re-traps the user in wsl-only
264 // mode the next time they enable WSL. If the persisted write fails, keep
265 // this process recoverable by applying the fallback to in-memory settings.
266 yield* appSettings.applyWslWindowsFallback.pipe(
267 Effect.catch((error) =>
268 logBackendPoolWarning(
269 "failed to persist Windows fallback after WSL preflight failure",
270 {
271 error: error.message,
272 },
273 ).pipe(Effect.andThen(appSettings.applyWslWindowsFallbackInMemory)),
274 ),
275 );
276 return true;
277 },
278 );
279
280 const primary = yield* DesktopBackendManager.makeBackendInstance({
281 id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
282 // Keep this lazy. The pool layer is initialized before startup loads
283 // persisted desktop settings, so resolving the primary label here would
284 // permanently capture DEFAULT_DESKTOP_SETTINGS and mislabel WSL-only
285 // primaries as Windows.
286 label: configuration.resolvePrimaryLabel,
287 configResolve: configuration.resolvePrimary,
288 // Window creation errors propagating out of handleBackendReady must
289 // not block the readiness callback (that would prevent restartAttempt
290 // from being reset), so we absorb them here. The window service only
291 // logs on success, so log the failure here before swallowing it —
292 // otherwise a post-readiness window-open failure vanishes silently and
293 // is near-impossible to diagnose in production.
294 onReady: (httpBaseUrl) =>
295 desktopWindow.handleBackendReady(httpBaseUrl).pipe(
296 Effect.catch((error) =>
297 logBackendPoolWarning("failed to open main window after backend readiness", {
298 error: error.message,
299 }),
300 ),
301 ),
302 onShutdown: () => desktopWindow.handleBackendNotReady,
303 onPreflightFailed: handlePrimaryPreflightFailure,
304 onStateDirOwned: () =>
305 electronDialog.showErrorBox(
306 "Another server owns this T3 home",
307 "The desktop backend could not start because another T3 Code server is using the same data directory. Finish active agent work and stop the background service or server, then reopen the desktop. You can also use a separate T3CODE_HOME and pair with the running environment.",
308 ),
309 });
310
311 const instancesRef = yield* SynchronizedRef.make<
312 ReadonlyMap<BackendInstanceId, RegisteredInstance>
313 >(
314 new Map([
315 [
316 DesktopBackendManager.PRIMARY_INSTANCE_ID,
317 { _tag: "Active", instance: primary, scope: Option.none() },
318 ],
319 ]),
320 );
321
322 const register: DesktopBackendPool["Service"]["register"] = (spec) =>
323 Effect.suspend(() =>
324 SynchronizedRef.modifyEffect(
325 instancesRef,
326 (
327 current,
328 ): Effect.Effect<
329 readonly [RegisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>],
330 DesktopBackendPoolInstanceAlreadyRegisteredError
331 > => {
332 const existing = current.get(spec.id);
333 if (existing?._tag === "Active") {
334 return Effect.fail(
335 new DesktopBackendPoolInstanceAlreadyRegisteredError({ id: spec.id }),
336 );
337 }
338 if (existing?._tag === "Closing") {
339 return Effect.succeed([
340 { _tag: "Wait", done: existing.done } as const,
341 current,
342 ] as const);
343 }
344 return Effect.gen(function* () {
345 // Provide the captured factory services first, then the child scope
346 // last so instance finalizers are owned by the unregisterable scope.
347 const instanceScope = yield* Scope.fork(layerScope, "sequential");
348 const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe(
349 Effect.provide(factoryContext),
350 Scope.provide(instanceScope),
351 );
352 const next = new Map(current);
353 next.set(spec.id, {
354 _tag: "Active",
355 instance,
356 scope: Option.some(instanceScope),
357 });
358 return [
359 { _tag: "Registered", instance } as const,
360 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
361 ] as const;
362 });
363 },
364 ).pipe(
365 Effect.flatMap((result) =>
366 result._tag === "Registered"
367 ? Effect.succeed(result.instance)
368 : Deferred.await(result.done).pipe(Effect.andThen(register(spec))),
369 ),
370 ),
371 );
372
373 const unregister: DesktopBackendPool["Service"]["unregister"] = (id) =>
374 Effect.gen(function* () {
375 if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {
376 return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();
377 }
378 const done = yield* Deferred.make<void>();
379 const action = yield* SynchronizedRef.modifyEffect(
380 instancesRef,
381 (
382 current,
383 ): Effect.Effect<
384 readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]
385 > => {
386 const entry = current.get(id);
387 if (entry === undefined) {
388 return Effect.succeed([{ _tag: "Absent" } as const, current] as const);
389 }
390 if (entry._tag === "Closing") {
391 return Effect.succeed([
392 { _tag: "Wait", done: entry.done } as const,
393 current,
394 ] as const);
395 }
396 const next = new Map(current);
397 next.set(id, { _tag: "Closing", done });
398 return Effect.succeed([
399 { _tag: "Close", entry } as const,
400 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
401 ] as const);
402 },
403 );
404
405 if (action._tag === "Absent") return;
406 if (action._tag === "Wait") {
407 yield* Deferred.await(action.done);
408 return;
409 }
410
411 const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {
412 const closing = current.get(id);
413 if (closing?._tag !== "Closing" || closing.done !== done) {
414 return Effect.succeed([undefined, current] as const);
415 }
416 const next = new Map(current);
417 next.delete(id);
418 return Effect.succeed([
419 undefined,
420 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
421 ] as const);
422 }).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);
423 yield* Option.match(action.entry.scope, {
424 onNone: () => Effect.void,
425 onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),
426 }).pipe(Effect.ensuring(finish));
427 });
428
429 return DesktopBackendPool.of({
430 get: (id) =>
431 SynchronizedRef.get(instancesRef).pipe(
432 Effect.map((instances) => {
433 const entry = instances.get(id);
434 return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none();
435 }),
436 ),
437 list: SynchronizedRef.get(instancesRef).pipe(
438 Effect.map((instances) =>
439 Array.from(instances.values()).flatMap((entry) =>
440 entry._tag === "Active" ? [entry.instance] : [],
441 ),
442 ),
443 ),
444 primary: Effect.succeed(primary),
445 register,
446 unregister,
447 });
448 }),
449);
450
451// Test layer for unit tests that want to assert against a known pool
452// composition without standing up the full manager. Each provided
453// instance is registered under its own id; the first one is also
454// surfaced as `primary` so callers can stub a single-instance pool.
455// `register` and `unregister` are stubbed to die so tests that
456// accidentally exercise pool registration fail loudly instead of
457// silently noop'ing.
458export const layerTest = (
459 instances: readonly DesktopBackendInstance[],
460): Layer.Layer<DesktopBackendPool> =>
461 Layer.effect(
462 DesktopBackendPool,
463 Effect.gen(function* () {
464 if (instances.length === 0) {
465 return yield* Effect.die("DesktopBackendPool.layerTest requires at least one instance");
466 }
467 const byId = new Map<BackendInstanceId, DesktopBackendInstance>(
468 instances.map((instance) => [instance.id, instance] as const),
469 );
470 const primary = instances[0]!;
471 return DesktopBackendPool.of({
472 get: (id) => Effect.succeed(Option.fromNullishOr(byId.get(id))),
473 list: Effect.succeed(Array.from(byId.values())),
474 primary: Effect.succeed(primary),
475 register: () => Effect.die("DesktopBackendPool.layerTest does not support register"),
476 unregister: () => Effect.die("DesktopBackendPool.layerTest does not support unregister"),
477 });
478 }),
479 );