Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopBackendPool.ts

485 lines22.5 KB

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/http";
94import { ChildProcessSpawner } from "effect/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 DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
102import * as DesktopWindow from "../window/DesktopWindow.ts";
103import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
104import * as ElectronDialog from "../electron/ElectronDialog.ts";
105import * as ElectronApp from "../electron/ElectronApp.ts";
106​
107const { logWarning: logBackendPoolWarning } =
108 DesktopObservability.makeComponentLogger("desktop-backend-pool");
109​
110export type BackendInstanceId = DesktopBackendManager.BackendInstanceId;
111export const BackendInstanceId = DesktopBackendManager.BackendInstanceId;
112export const PRIMARY_INSTANCE_ID = DesktopBackendManager.PRIMARY_INSTANCE_ID;
113export type DesktopBackendInstance = DesktopBackendManager.DesktopBackendInstance;
114export type BackendInstanceSpec = DesktopBackendManager.BackendInstanceSpec;
115​
116// Caller tried to register an id that's already in the pool. The pool
117// refuses overwrites so two independent orchestrators racing on the
118// same id surface as a typed failure instead of one silently winning.
119export class DesktopBackendPoolInstanceAlreadyRegisteredError extends Schema.TaggedError<DesktopBackendPoolInstanceAlreadyRegisteredError>()(
120 "DesktopBackendPoolInstanceAlreadyRegisteredError",
121 {
122 id: Schema.String,
123 },
124) {
125 override get message() {
126 return `Backend instance "${this.id}" is already registered in the pool.`;
127 }
129​
130// Primary instance is registered for the pool's lifetime. Unregister is
131// a no-op for it today (no real callers), but if someone wires it up
132// later it's a clear bug rather than something to "handle".
133export class DesktopBackendPoolCannotUnregisterPrimaryError extends Schema.TaggedError<DesktopBackendPoolCannotUnregisterPrimaryError>()(
134 "DesktopBackendPoolCannotUnregisterPrimaryError",
135 {},
136) {
137 override get message() {
138 return "Refusing to unregister the primary backend from the pool.";
139 }
141​
142export class DesktopBackendPool extends Context.Service<
143 DesktopBackendPool,
144 {
145 // Look up a registered instance. None when no backend with that id is
146 // currently registered (e.g. WSL backend disabled).
147 readonly get: (id: BackendInstanceId) => Effect.Effect<Option.Option<DesktopBackendInstance>>;
148 // Snapshot of all currently-registered instances. Order is unspecified;
149 // callers that need a canonical "primary first" view should sort by id.
150 readonly list: Effect.Effect<readonly DesktopBackendInstance[]>;
151 // Convenience accessor for the always-registered primary instance.
152 // Currently equivalent to `get(PRIMARY_INSTANCE_ID)` unwrapped, but
153 // exposed as a typed effect so consumers don't have to handle the
154 // Option for the case that's guaranteed to be present.
155 readonly primary: Effect.Effect<DesktopBackendInstance>;
156 // Build a fresh DesktopBackendInstance from `spec` and add it to the
157 // registry. The pool owns the instance's scope: unregister(id) or pool
158 // teardown closes it and runs the instance's auto-stop finalizer. The
159 // returned instance has not been started — callers decide when to
160 // start it (and can call start more than once if a retry-after-failure
161 // story makes sense for them).
162 readonly register: (
163 spec: BackendInstanceSpec,
164 ) => Effect.Effect<DesktopBackendInstance, DesktopBackendPoolInstanceAlreadyRegisteredError>;
165 // Stop the named instance and remove it from the registry. Closing the
166 // instance's scope triggers its auto-stop finalizer; the registry is
167 // updated atomically with the scope close so subsequent get(id) calls
168 // observe the unregister before the underlying child process has fully
169 // exited.
170 readonly unregister: (
171 id: BackendInstanceId,
172 ) => Effect.Effect<void, DesktopBackendPoolCannotUnregisterPrimaryError>;
173 }
174>()("@t3tools/desktop/backend/DesktopBackendPool") {}
175​
176// Services required by makeBackendInstance — exported so caller
177// orchestrators that build their own specs can confirm the layer graph
178// satisfies them at compile time.
179export type BackendInstanceFactoryRequirements =
180 | FileSystem.FileSystem
181 | ChildProcessSpawner.ChildProcessSpawner
182 | HttpClient.HttpClient
183 | DesktopObservability.DesktopBackendOutputLogFactory
184 | DesktopTelemetryPublisher.DesktopTelemetryPublisher
185 | DesktopBrowserHost.DesktopBrowserHost
186 | DesktopWslEnvironment.DesktopWslEnvironment;
187​
188interface ActiveRegisteredInstance {
189 readonly _tag: "Active";
190 readonly instance: DesktopBackendInstance;
191 // None for the primary (which lives in the pool's own layer scope and
192 // is never unregistered); Some for instances added via register, whose
193 // scope unregister closes to stop them.
194 readonly scope: Option.Option<Scope.Closeable>;
196​
197interface ClosingRegisteredInstance {
198 readonly _tag: "Closing";
199 readonly done: Deferred.Deferred<void>;
201​
202type RegisteredInstance = ActiveRegisteredInstance | ClosingRegisteredInstance;
203​
204type RegisterAction =
205 | { readonly _tag: "Registered"; readonly instance: DesktopBackendInstance }
206 | { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> };
207​
208type UnregisterAction =
209 | { readonly _tag: "Absent" }
210 | { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> }
211 | { readonly _tag: "Close"; readonly entry: ActiveRegisteredInstance };
212​
213export const layer = Layer.effect(
214 DesktopBackendPool,
215 Effect.gen(function* () {
216 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
217 const desktopWindow = yield* DesktopWindow.DesktopWindow;
218 const electronDialog = yield* ElectronDialog.ElectronDialog;
219 const electronApp = yield* ElectronApp.ElectronApp;
220 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
221 // Anchor the pool's lifetime to its layer scope so registered
222 // instance scopes can be forked off it. Without this, instance
223 // scopes are orphaned: they only close via explicit unregister()
224 // calls, so on app shutdown the WSL backend child process gets
225 // hard-killed by the OS instead of receiving the graceful
226 // SIGTERM + grace period the instance's stop finalizer would
227 // otherwise run.
228 const layerScope = yield* Scope.Scope;
229 // Capture the services needed to build any future instance from the
230 // pool's layer scope. register() runs `makeBackendInstance` against
231 // a fresh child scope but reuses these services so the instance gets
232 // the same FileSystem, spawner, HTTP client and log factory the
233 // primary instance uses.
234 const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
235​
236 // A WSL preflight failure on the primary only happens in wsl-only mode.
237 // Fatal configuration failures persist the Windows fallback. Bounded
238 // transport failures use an in-memory fallback for this launch so the app
239 // opens without overwriting the user's WSL preference.
240 const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
241 function* (failure: DesktopBackendManager.PreflightFailure) {
242 const { reason, fatal } = failure;
243 if (!fatal) {
244 yield* logBackendPoolWarning(
245 "primary WSL preflight retry window exhausted; using Windows for this launch",
246 { reason },
247 );
248 yield* electronDialog.showErrorBox(
249 "WSL backend is still unavailable",
250 `${reason}\n\nT3 Code will use the Windows backend for this launch and retry WSL the next time the app starts.`,
251 );
252 yield* appSettings.applyWslWindowsFallbackInMemory;
253 return true;
254 }
255​
256 yield* logBackendPoolWarning("primary WSL preflight failed; falling back to Windows", {
257 reason,
258 });
259 yield* electronDialog.showErrorBox(
260 "WSL backend couldn't start",
261 `${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.`,
262 );
263 // Fully disable the WSL backend — both flags, matching the "Switch to
264 // Windows" recovery path — so the manager's next restart re-resolves the
265 // primary as Windows and reconcile won't register a secondary WSL backend
266 // against the same broken setup. Clearing wslBackendEnabled alone would
267 // leave a stale wslOnly:true that silently re-traps the user in wsl-only
268 // mode the next time they enable WSL. If the persisted write fails, keep
269 // this process recoverable by applying the fallback to in-memory settings.
270 yield* appSettings.applyWslWindowsFallback.pipe(
271 Effect.catch((error) =>
272 logBackendPoolWarning(
273 "failed to persist Windows fallback after WSL preflight failure",
274 {
275 error: error.message,
276 },
277 ).pipe(Effect.andThen(appSettings.applyWslWindowsFallbackInMemory)),
278 ),
279 );
280 return true;
281 },
282 );
283​
284 const primary = yield* DesktopBackendManager.makeBackendInstance({
285 id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
286 // Keep this lazy. The pool layer is initialized before startup loads
287 // persisted desktop settings, so resolving the primary label here would
288 // permanently capture DEFAULT_DESKTOP_SETTINGS and mislabel WSL-only
289 // primaries as Windows.
290 label: configuration.resolvePrimaryLabel,
291 configResolve: configuration.resolvePrimary,
292 // Window creation errors propagating out of handleBackendReady must
293 // not block the readiness callback (that would prevent restartAttempt
294 // from being reset), so we absorb them here. The window service only
295 // logs on success, so log the failure here before swallowing it —
296 // otherwise a post-readiness window-open failure vanishes silently and
297 // is near-impossible to diagnose in production.
298 onReady: (httpBaseUrl) =>
299 desktopWindow.handleBackendReady(httpBaseUrl).pipe(
300 Effect.catch((error) =>
301 logBackendPoolWarning("failed to open main window after backend readiness", {
302 error: error.message,
303 }),
304 ),
305 ),
306 onShutdown: () => desktopWindow.handleBackendNotReady,
307 onPreflightFailed: handlePrimaryPreflightFailure,
308 onStateDirOwned: () =>
309 electronDialog
310 .showErrorBox(
311 "This T3 home is unavailable",
312 "Another T3 Code server, such as the background service, is using this data directory. Stop that server and reopen T3 Code, or set a separate T3CODE_HOME and pair with the running server.",
313 )
314 .pipe(Effect.andThen(electronApp.quit)),
315 });
316​
317 const instancesRef = yield* SynchronizedRef.make<
318 ReadonlyMap<BackendInstanceId, RegisteredInstance>
319 >(
320 new Map([
321 [
322 DesktopBackendManager.PRIMARY_INSTANCE_ID,
323 { _tag: "Active", instance: primary, scope: Option.none() },
324 ],
325 ]),
326 );
327​
328 const register: DesktopBackendPool["Service"]["register"] = (spec) =>
329 Effect.suspend(() =>
330 SynchronizedRef.modifyEffect(
331 instancesRef,
332 (
333 current,
334 ): Effect.Effect<
335 readonly [RegisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>],
336 DesktopBackendPoolInstanceAlreadyRegisteredError
337 > => {
338 const existing = current.get(spec.id);
339 if (existing?._tag === "Active") {
340 return Effect.fail(
341 new DesktopBackendPoolInstanceAlreadyRegisteredError({ id: spec.id }),
342 );
343 }
344 if (existing?._tag === "Closing") {
345 return Effect.succeed([
346 { _tag: "Wait", done: existing.done } as const,
347 current,
348 ] as const);
349 }
350 return Effect.gen(function* () {
351 // Provide the captured factory services first, then the child scope
352 // last so instance finalizers are owned by the unregisterable scope.
353 const instanceScope = yield* Scope.fork(layerScope, "sequential");
354 const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe(
355 Effect.provide(factoryContext),
356 Scope.provide(instanceScope),
357 );
358 const next = new Map(current);
359 next.set(spec.id, {
360 _tag: "Active",
361 instance,
362 scope: Option.some(instanceScope),
363 });
364 return [
365 { _tag: "Registered", instance } as const,
366 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
367 ] as const;
368 });
369 },
370 ).pipe(
371 Effect.flatMap((result) =>
372 result._tag === "Registered"
373 ? Effect.succeed(result.instance)
374 : Deferred.await(result.done).pipe(Effect.andThen(register(spec))),
375 ),
376 ),
377 );
378​
379 const unregister: DesktopBackendPool["Service"]["unregister"] = (id) =>
380 Effect.gen(function* () {
381 if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {
382 return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();
383 }
384 const done = yield* Deferred.make<void>();
385 const action = yield* SynchronizedRef.modifyEffect(
386 instancesRef,
387 (
388 current,
389 ): Effect.Effect<
390 readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]
391 > => {
392 const entry = current.get(id);
393 if (entry === undefined) {
394 return Effect.succeed([{ _tag: "Absent" } as const, current] as const);
395 }
396 if (entry._tag === "Closing") {
397 return Effect.succeed([
398 { _tag: "Wait", done: entry.done } as const,
399 current,
400 ] as const);
401 }
402 const next = new Map(current);
403 next.set(id, { _tag: "Closing", done });
404 return Effect.succeed([
405 { _tag: "Close", entry } as const,
406 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
407 ] as const);
408 },
409 );
410​
411 if (action._tag === "Absent") return;
412 if (action._tag === "Wait") {
413 yield* Deferred.await(action.done);
414 return;
415 }
416​
417 const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {
418 const closing = current.get(id);
419 if (closing?._tag !== "Closing" || closing.done !== done) {
420 return Effect.succeed([undefined, current] as const);
421 }
422 const next = new Map(current);
423 next.delete(id);
424 return Effect.succeed([
425 undefined,
426 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
427 ] as const);
428 }).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);
429 yield* Option.match(action.entry.scope, {
430 onNone: () => Effect.void,
431 onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),
432 }).pipe(Effect.ensuring(finish));
433 });
434​
435 return DesktopBackendPool.of({
436 get: (id) =>
437 SynchronizedRef.get(instancesRef).pipe(
438 Effect.map((instances) => {
439 const entry = instances.get(id);
440 return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none();
441 }),
442 ),
443 list: SynchronizedRef.get(instancesRef).pipe(
444 Effect.map((instances) =>
445 Array.from(instances.values()).flatMap((entry) =>
446 entry._tag === "Active" ? [entry.instance] : [],
447 ),
448 ),
449 ),
450 primary: Effect.succeed(primary),
451 register,
452 unregister,
453 });
454 }),
455);
456​
457// Test layer for unit tests that want to assert against a known pool
458// composition without standing up the full manager. Each provided
459// instance is registered under its own id; the first one is also
460// surfaced as `primary` so callers can stub a single-instance pool.
461// `register` and `unregister` are stubbed to die so tests that
462// accidentally exercise pool registration fail loudly instead of
463// silently noop'ing.
464export const layerTest = (
465 instances: readonly DesktopBackendInstance[],
466): Layer.Layer<DesktopBackendPool> =>
467 Layer.effect(
468 DesktopBackendPool,
469 Effect.gen(function* () {
470 if (instances.length === 0) {
471 return yield* Effect.die("DesktopBackendPool.layerTest requires at least one instance");
472 }
473 const byId = new Map<BackendInstanceId, DesktopBackendInstance>(
474 instances.map((instance) => [instance.id, instance] as const),
475 );
476 const primary = instances[0]!;
477 return DesktopBackendPool.of({
478 get: (id) => Effect.succeed(Option.fromNullishOr(byId.get(id))),
479 list: Effect.succeed(Array.from(byId.values())),
480 primary: Effect.succeed(primary),
481 register: () => Effect.die("DesktopBackendPool.layerTest does not support register"),
482 unregister: () => Effect.die("DesktopBackendPool.layerTest does not support unregister"),
483 });
484 }),
485 );