From b20a9663d364934d272c6f9b40725113e3e87f28 Mon Sep 17 00:00:00 2001 From: Josh Gratton Date: Sat, 16 May 2026 16:47:15 -0400 Subject: [PATCH] feat(desktop): scaffold DesktopBackendPool for concurrent backends Phase-1 foundation for running Windows and WSL backends side by side. Introduces: * BackendInstanceId brand + PRIMARY_INSTANCE_ID constant * DesktopBackendInstance interface mirroring the legacy backend manager surface so consumers can migrate one call site at a time * DesktopBackendPool service with get/list/primary operations * Phase-1 layer that wraps the existing singleton DesktopBackendManager and exposes it under PRIMARY_INSTANCE_ID, no behavior change * layerTest helper for unit tests The pool is wired into the desktop application layer alongside the existing manager; current consumers (window/wsl IPC, lifecycle hooks, telemetry) still depend on DesktopBackendManager directly. The header docblock on DesktopBackendPool.ts captures the full migration sequence for follow-up commits: reshape the manager into an instance factory, move per-instance state off DesktopState/DesktopBackendOutputLog, wire WSL as a second pooled instance, widen the bootstrap IPC, and retire the swap-mode dialog. --- .../src/backend/DesktopBackendPool.test.ts | 65 +++++++ .../desktop/src/backend/DesktopBackendPool.ts | 171 ++++++++++++++++++ apps/desktop/src/main.ts | 10 +- 3 files changed, 245 insertions(+), 1 deletion(-) create mode 100644 apps/desktop/src/backend/DesktopBackendPool.test.ts create mode 100644 apps/desktop/src/backend/DesktopBackendPool.ts diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.ts new file mode 100644 index 0000000000..6fdf2d31f6 --- /dev/null +++ b/apps/desktop/src/backend/DesktopBackendPool.test.ts @@ -0,0 +1,65 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import * as DesktopBackendPool from "./DesktopBackendPool.ts"; +import type { DesktopBackendSnapshot, DesktopBackendStartConfig } from "./DesktopBackendManager.ts"; + +function makeStubInstance( + id: DesktopBackendPool.BackendInstanceId, + label: string, +): DesktopBackendPool.DesktopBackendInstance { + const snapshot: DesktopBackendSnapshot = { + desiredRunning: false, + ready: false, + activePid: Option.none(), + restartAttempt: 0, + restartScheduled: false, + }; + return { + id, + label, + start: Effect.void, + stop: () => Effect.void, + currentConfig: Effect.succeed(Option.none()), + snapshot: Effect.succeed(snapshot), + waitForReady: (_timeout: Duration.Duration) => Effect.succeed(false), + }; +} + +describe("DesktopBackendPool", () => { + it.effect("layerTest exposes registered instances by id", () => + Effect.gen(function* () { + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const fetchedPrimary = yield* pool.get(DesktopBackendPool.PRIMARY_INSTANCE_ID); + const fetchedWsl = yield* pool.get(DesktopBackendPool.BackendInstanceId("wsl:ubuntu")); + const fetchedMissing = yield* pool.get(DesktopBackendPool.BackendInstanceId("missing")); + const all = yield* pool.list; + const resolvedPrimary = yield* pool.primary; + + assert.equal(Option.getOrNull(fetchedPrimary)?.label, "Windows"); + assert.equal(Option.getOrNull(fetchedWsl)?.label, "WSL (Ubuntu)"); + assert.isTrue(Option.isNone(fetchedMissing)); + assert.lengthOf(all, 2); + // First instance becomes primary in layerTest so single-instance + // stubs don't have to wire an explicit primary. + assert.equal(resolvedPrimary.id, DesktopBackendPool.PRIMARY_INSTANCE_ID); + }).pipe( + Effect.provide( + DesktopBackendPool.layerTest([ + makeStubInstance(DesktopBackendPool.PRIMARY_INSTANCE_ID, "Windows"), + makeStubInstance(DesktopBackendPool.BackendInstanceId("wsl:ubuntu"), "WSL (Ubuntu)"), + ]), + ), + ), + ); + + it.effect("layerTest dies when no instances are supplied", () => + Effect.exit( + Effect.gen(function* () { + yield* DesktopBackendPool.DesktopBackendPool; + }).pipe(Effect.provide(DesktopBackendPool.layerTest([]))), + ).pipe(Effect.map((exit) => assert.equal(exit._tag, "Failure"))), + ); +}); diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.ts new file mode 100644 index 0000000000..5545b175f9 --- /dev/null +++ b/apps/desktop/src/backend/DesktopBackendPool.ts @@ -0,0 +1,171 @@ +// Pool registry for multiple backend processes. This file is the entry +// point for the concurrent-Windows+WSL-backend feature; see the design +// notes below before extending it. +// +// Current state (foundation commit): +// - The existing `DesktopBackendManager` still owns the singleton +// Windows backend lifecycle. All current consumers (window/wsl IPC, +// lifecycle hooks, telemetry) continue to depend on that service +// directly — nothing has migrated yet. +// - This pool exposes the running backend under PRIMARY_INSTANCE_ID by +// wrapping the existing manager methods. The wrapper introduces no +// behavior change; it exists so follow-up commits can migrate +// consumers off `DesktopBackendManager.DesktopBackendManager` onto +// `pool.get(id)` / `pool.primary` one at a time without breaking the +// intermediate states. +// +// Target state (concurrent Windows + WSL): +// - `DesktopBackendManager` is reshaped from a service into an instance +// factory parameterized by `DesktopBackendStartConfig` + an instance +// id, returning a `DesktopBackendInstance` directly. +// - The pool layer constructs N instances at startup — at minimum the +// Windows primary; the WSL instance is added when the user enables +// WSL backend mode (with the selected distro). +// - Singleton state currently held in `DesktopState.backendReady` and +// `DesktopBackendOutputLog` migrates onto each `DesktopBackendInstance` +// so per-backend readiness/logging is observable independently. +// - `getLocalEnvironmentBootstrap()` widens to +// `getLocalEnvironmentBootstraps()` returning one bootstrap per pool +// instance; the frontend env runtime registers each as a local +// environment. +// - The WSL "swap" IPC is replaced by `enableWslBackend()` + +// `setWslBackendDistro()` controlling which (if any) WSL instance the +// pool holds. No more swap-mode, no more rollback-on-restart. +// +// Migration sequence (each step is its own commit): +// 1. (this commit) Establish types + pool wrapper. No consumer changes. +// 2. Reshape `DesktopBackendManager` from a service singleton to an +// instance factory. Pool layer calls it once for the Windows primary. +// Move per-instance state (active run, restart fiber, ready, config) +// onto the returned instance. +// 3. Per-instance readiness: drop `DesktopState.backendReady`. UI +// subscribes to `pool.primary.snapshot.ready` (or the multi-instance +// readiness signal once it exists). +// 4. Per-instance log routing: split `DesktopBackendOutputLog` into a +// factory keyed by instance id. +// 5. Add `DesktopBackendInstance.create({ id, config })` to the pool so +// the WSL backend can be registered on demand. +// 6. Wire WSL distro startup through the pool; remove `setWslBackend` +// mode-swap IPC in favor of `enableWslBackend` / `setWslDistro`. +// 7. Widen `getLocalEnvironmentBootstrap` → `*Bootstraps`; frontend +// runtime registers each pool instance as a local environment. +// 8. Drop the swap dialog + the "mode" appSetting. Settings UI gets a +// "WSL backend enabled + distro" pair instead. + +import * as Brand from "effect/Brand"; +import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; + +import * as DesktopBackendManager from "./DesktopBackendManager.ts"; +import type { DesktopBackendSnapshot, DesktopBackendStartConfig } from "./DesktopBackendManager.ts"; + +// Opaque identifier for one backend process inside the pool. Today only +// `PRIMARY_INSTANCE_ID` is registered. Follow-up commits add WSL distros +// under ids derived from the distro name (e.g. "wsl:ubuntu"). Eventually +// these map 1:1 with environment ids on the frontend; keeping them +// desktop-local for now avoids leaking the contracts dependency into the +// pool while the migration is mid-flight. +export type BackendInstanceId = string & Brand.Brand<"BackendInstanceId">; +export const BackendInstanceId = Brand.nominal(); + +// Identifier for the always-on Windows backend. Stable across pool +// lifetimes so callers can route to it without consulting the registry. +export const PRIMARY_INSTANCE_ID: BackendInstanceId = BackendInstanceId("primary"); + +// One pooled backend instance — same surface as the legacy +// `DesktopBackendManagerShape` so consumers can swap with a one-line +// change. The id and label give the pool registry + UI something to +// route on; the rest mirrors per-process lifecycle controls. +export interface DesktopBackendInstance { + readonly id: BackendInstanceId; + readonly label: string; + readonly start: Effect.Effect; + readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect; + readonly currentConfig: Effect.Effect>; + readonly snapshot: Effect.Effect; + readonly waitForReady: (timeout: Duration.Duration) => Effect.Effect; +} + +export interface DesktopBackendPoolShape { + // Look up a registered instance. None when no backend with that id is + // currently registered (e.g. WSL backend disabled). + readonly get: (id: BackendInstanceId) => Effect.Effect>; + // Snapshot of all currently-registered instances. Order is unspecified; + // callers that need a canonical "primary first" view should sort by id. + readonly list: Effect.Effect; + // Convenience accessor for the always-registered primary instance. + // Currently equivalent to `get(PRIMARY_INSTANCE_ID)` unwrapped, but + // exposed as a typed effect so consumers don't have to handle the + // Option for the case that's guaranteed to be present. + readonly primary: Effect.Effect; +} + +export class DesktopBackendPool extends Context.Service< + DesktopBackendPool, + DesktopBackendPoolShape +>()("t3/desktop/BackendPool") {} + +// Phase-1 layer: depends on `DesktopBackendManager.layer` (the current +// singleton) and exposes its surface as a single-instance pool keyed by +// PRIMARY_INSTANCE_ID. No behavior change vs the legacy service — this +// is purely additive scaffolding so consumers can migrate one at a time. +// +// Phase 2 replaces this layer with one that constructs instances by +// calling a per-instance factory (the reshaped `DesktopBackendManager`) +// directly; the wrapper goes away once nothing references the legacy +// service. +export const layer = Layer.effect( + DesktopBackendPool, + Effect.gen(function* () { + const manager = yield* DesktopBackendManager.DesktopBackendManager; + const primaryInstance: DesktopBackendInstance = { + id: PRIMARY_INSTANCE_ID, + label: "Windows", + start: manager.start, + stop: manager.stop, + currentConfig: manager.currentConfig, + snapshot: manager.snapshot, + waitForReady: manager.waitForReady, + }; + const instancesRef = yield* Ref.make>( + new Map([[PRIMARY_INSTANCE_ID, primaryInstance]]), + ); + return DesktopBackendPool.of({ + get: (id) => + Ref.get(instancesRef).pipe( + Effect.map((instances) => Option.fromNullishOr(instances.get(id))), + ), + list: Ref.get(instancesRef).pipe(Effect.map((instances) => Array.from(instances.values()))), + primary: Effect.succeed(primaryInstance), + }); + }), +); + +// Test layer for unit tests that want to assert against a known pool +// composition without standing up the full manager. Each provided +// instance is registered under its own id; the first one is also +// surfaced as `primary` so callers can stub a single-instance pool. +export const layerTest = ( + instances: readonly DesktopBackendInstance[], +): Layer.Layer => + Layer.effect( + DesktopBackendPool, + Effect.gen(function* () { + if (instances.length === 0) { + return yield* Effect.die("DesktopBackendPool.layerTest requires at least one instance"); + } + const byId = new Map( + instances.map((instance) => [instance.id, instance] as const), + ); + const primary = instances[0]!; + return DesktopBackendPool.of({ + get: (id) => Effect.succeed(Option.fromNullishOr(byId.get(id))), + list: Effect.succeed(Array.from(byId.values())), + primary: Effect.succeed(primary), + }); + }), + ); diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index b2d0bee1ba..ed57713dfa 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -30,6 +30,7 @@ import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts"; import * as DesktopAssets from "./app/DesktopAssets.ts"; import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts"; import * as DesktopBackendManager from "./backend/DesktopBackendManager.ts"; +import * as DesktopBackendPool from "./backend/DesktopBackendPool.ts"; import * as DesktopEnvironment from "./app/DesktopEnvironment.ts"; import * as DesktopLifecycle from "./app/DesktopLifecycle.ts"; import * as DesktopObservability from "./app/DesktopObservability.ts"; @@ -128,7 +129,14 @@ const desktopServerExposureLayer = DesktopServerExposure.layer.pipe( const desktopWindowLayer = DesktopWindow.layer.pipe(Layer.provideMerge(desktopServerExposureLayer)); -const desktopBackendLayer = DesktopBackendManager.layer.pipe( +// Phase-1 of the parallel-backend refactor: pool wraps the existing +// singleton manager so consumers can migrate to instance-keyed access +// incrementally. See DesktopBackendPool.ts header for the rollout plan. +// provideMerge keeps the legacy DesktopBackendManager service exposed +// for current consumers (window/wsl IPC, lifecycle hooks) until they +// migrate to pool.primary. +const desktopBackendLayer = DesktopBackendPool.layer.pipe( + Layer.provideMerge(DesktopBackendManager.layer), Layer.provideMerge(DesktopAppIdentity.layer), Layer.provideMerge(DesktopBackendConfiguration.layer), Layer.provideMerge(DesktopWslEnvironment.layer),