diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index b981755296..f948adde13 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -12,7 +12,7 @@ import * as ElectronProtocol from "../electron/ElectronProtocol.ts"; import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts"; import * as DesktopAppIdentity from "./DesktopAppIdentity.ts"; import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts"; -import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts"; +import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; import * as DesktopLifecycle from "./DesktopLifecycle.ts"; import * as DesktopObservability from "./DesktopObservability.ts"; @@ -130,7 +130,8 @@ const fatalStartupCause = (stage: string, cause: Cause.Cause) => handleFatalStartupError(stage, Cause.pretty(cause)).pipe(Effect.andThen(Effect.failCause(cause))); const bootstrap = Effect.gen(function* () { - const backendManager = yield* DesktopBackendManager.DesktopBackendManager; + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const primaryBackend = yield* pool.primary; const state = yield* DesktopState.DesktopState; const environment = yield* DesktopEnvironment.DesktopEnvironment; const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings; @@ -178,7 +179,7 @@ const bootstrap = Effect.gen(function* () { yield* logBootstrapInfo("bootstrap ipc handlers registered"); if (!(yield* Ref.get(state.quitting))) { - yield* backendManager.start; + yield* primaryBackend.start; yield* logBootstrapInfo("bootstrap backend start requested"); } }).pipe(Effect.withSpan("desktop.bootstrap")); @@ -226,10 +227,11 @@ const scopedProgram = Effect.scoped( yield* Effect.annotateCurrentSpan({ scope: "desktop", runId }); const shutdown = yield* DesktopLifecycle.DesktopShutdown; - const backendManager = yield* DesktopBackendManager.DesktopBackendManager; + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const primaryBackend = yield* pool.primary; yield* Effect.addFinalizer(() => - backendManager.stop().pipe(Effect.ensuring(shutdown.markComplete)), + primaryBackend.stop().pipe(Effect.ensuring(shutdown.markComplete)), ); yield* startup; diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts index d6d04bcfc3..ae6fa16c4c 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.test.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts @@ -20,10 +20,7 @@ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstab import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import * as DesktopBackendManager from "./DesktopBackendManager.ts"; -import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts"; import * as DesktopObservability from "../app/DesktopObservability.ts"; -import * as DesktopState from "../app/DesktopState.ts"; -import * as DesktopWindow from "../window/DesktopWindow.ts"; const decodeDesktopBackendBootstrap = Schema.decodeEffect( Schema.fromJsonString(DesktopBackendBootstrap), @@ -105,97 +102,90 @@ function decodeBootstrap(raw: string) { return decodeDesktopBackendBootstrap(raw); } -function makeManagerLayer(input: { +interface MakeInstanceInput { readonly spawnerLayer: Layer.Layer; readonly httpClientLayer?: Layer.Layer; readonly backendOutputLog?: Partial; - readonly desktopState?: DesktopState.DesktopStateShape; - readonly desktopWindow?: Partial; + readonly onReady?: Effect.Effect; + readonly onShutdown?: Effect.Effect; readonly config?: DesktopBackendManager.DesktopBackendStartConfig; -}) { - return DesktopBackendManager.layer.pipe( - Layer.provide( - Layer.mergeAll( - FileSystem.layerNoop({ - exists: () => Effect.succeed(true), - }), - Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, { - resolve: Effect.succeed(input.config ?? baseConfig), - }), - input.spawnerLayer, - input.httpClientLayer ?? healthyHttpClientLayer, - input.desktopState - ? Layer.succeed(DesktopState.DesktopState, input.desktopState) - : DesktopState.layer, - Layer.succeed(DesktopObservability.DesktopBackendOutputLog, { - writeSessionBoundary: () => Effect.void, - writeOutputChunk: () => Effect.void, - ...input.backendOutputLog, - } satisfies DesktopObservability.DesktopBackendOutputLogShape), - Layer.succeed(DesktopWindow.DesktopWindow, { - createMain: Effect.die("unexpected createMain"), - ensureMain: Effect.die("unexpected ensureMain"), - revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"), - activate: Effect.void, - createMainIfBackendReady: Effect.void, - handleBackendReady: Effect.void, - dispatchMenuAction: () => Effect.void, - syncAppearance: Effect.void, - ...input.desktopWindow, - } satisfies DesktopWindow.DesktopWindowShape), - ), - ), +} + +// Helper that constructs a primary backend instance using the factory +// directly. The factory's deps (FileSystem, ChildProcessSpawner, +// HttpClient, DesktopBackendOutputLog) are provided per-test via a +// scoped layer; tests yield the returned Effect inside `Effect.scoped` +// to drive the instance's lifecycle. +function makeTestInstance(input: MakeInstanceInput) { + const servicesLayer = Layer.mergeAll( + FileSystem.layerNoop({ + exists: () => Effect.succeed(true), + }), + input.spawnerLayer, + input.httpClientLayer ?? healthyHttpClientLayer, + Layer.succeed(DesktopObservability.DesktopBackendOutputLog, { + writeSessionBoundary: () => Effect.void, + writeOutputChunk: () => Effect.void, + ...input.backendOutputLog, + } satisfies DesktopObservability.DesktopBackendOutputLogShape), ); + + const instance = DesktopBackendManager.makeBackendInstance({ + id: DesktopBackendManager.PRIMARY_INSTANCE_ID, + label: "Windows", + configResolve: Effect.succeed(input.config ?? baseConfig), + ...(input.onReady ? { onReady: () => input.onReady! } : {}), + ...(input.onShutdown ? { onShutdown: () => input.onShutdown! } : {}), + }); + + return instance.pipe(Effect.provide(servicesLayer)); } describe("DesktopBackendManager", () => { it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () => - Effect.gen(function* () { - let spawnedCommand: ChildProcess.Command | undefined; - let bootstrapJson = ""; - let readyCount = 0; - const ready = yield* Deferred.make(); - const exited = yield* Queue.unbounded(); + Effect.scoped( + Effect.gen(function* () { + let spawnedCommand: ChildProcess.Command | undefined; + let bootstrapJson = ""; + let readyCount = 0; + const ready = yield* Deferred.make(); + const exited = yield* Queue.unbounded(); - const spawnerLayer = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make((command) => - Effect.gen(function* () { - spawnedCommand = command; - if (command._tag === "StandardCommand") { - const fd3 = command.options.additionalFds?.fd3; - if (fd3?.type === "input" && fd3.stream) { - bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString); + const spawnerLayer = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => + Effect.gen(function* () { + spawnedCommand = command; + if (command._tag === "StandardCommand") { + const fd3 = command.options.additionalFds?.fd3; + if (fd3?.type === "input" && fd3.stream) { + bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString); + } } - } - return makeProcess({ - exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), - }); - }), - ), - ); + return makeProcess({ + exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), + }); + }), + ), + ); - const managerLayer = makeManagerLayer({ - config: { - ...baseConfig, - bootstrap: configWithObservability, - }, - spawnerLayer, - desktopWindow: { - handleBackendReady: Effect.sync(() => { + const instance = yield* makeTestInstance({ + config: { + ...baseConfig, + bootstrap: configWithObservability, + }, + spawnerLayer, + onReady: Effect.sync(() => { readyCount += 1; - }).pipe(Effect.andThen(Deferred.succeed(ready, void 0))), - }, - backendOutputLog: { - writeSessionBoundary: ({ phase }) => - phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void, - }, - }); + }).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid), + backendOutputLog: { + writeSessionBoundary: ({ phase }) => + phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void, + }, + }); - yield* Effect.gen(function* () { - const manager = yield* DesktopBackendManager.DesktopBackendManager; - yield* manager.start; + yield* instance.start; yield* Queue.take(exited); assert.equal(readyCount, 1); @@ -218,55 +208,52 @@ describe("DesktopBackendManager", () => { ); assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability); - }).pipe(Effect.provide(managerLayer)); - }), + }), + ), ); it.effect("retries HTTP readiness before reporting the backend ready", () => - Effect.gen(function* () { - const requestUrls: Array = []; - const statuses = [503, 200]; - let readyCount = 0; - const firstRequest = yield* Deferred.make(); - const ready = yield* Deferred.make(); - const exited = yield* Queue.unbounded(); + Effect.scoped( + Effect.gen(function* () { + const requestUrls: Array = []; + const statuses = [503, 200]; + let readyCount = 0; + const firstRequest = yield* Deferred.make(); + const ready = yield* Deferred.make(); + const exited = yield* Queue.unbounded(); - const spawnerLayer = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.succeed( - makeProcess({ - exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), + const spawnerLayer = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.succeed( + makeProcess({ + exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), + }), + ), + ), + ); + + const instance = yield* makeTestInstance({ + spawnerLayer, + httpClientLayer: httpClientLayer((request) => + Effect.gen(function* () { + const status = statuses.shift(); + assert.isDefined(status); + requestUrls.push(request.url); + yield* Deferred.succeed(firstRequest, void 0); + return responseForRequest(request, status); }), ), - ), - ); - - const managerLayer = makeManagerLayer({ - spawnerLayer, - httpClientLayer: httpClientLayer((request) => - Effect.gen(function* () { - const status = statuses.shift(); - assert.isDefined(status); - requestUrls.push(request.url); - yield* Deferred.succeed(firstRequest, void 0); - return responseForRequest(request, status); - }), - ), - desktopWindow: { - handleBackendReady: Effect.sync(() => { + onReady: Effect.sync(() => { readyCount += 1; - }).pipe(Effect.andThen(Deferred.succeed(ready, void 0))), - }, - backendOutputLog: { - writeSessionBoundary: ({ phase }) => - phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void, - }, - }); + }).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid), + backendOutputLog: { + writeSessionBoundary: ({ phase }) => + phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void, + }, + }); - yield* Effect.gen(function* () { - const manager = yield* DesktopBackendManager.DesktopBackendManager; - yield* manager.start; + yield* instance.start; yield* Deferred.await(firstRequest); assert.equal(readyCount, 0); @@ -280,106 +267,100 @@ describe("DesktopBackendManager", () => { "http://127.0.0.1:3773/.well-known/t3/environment", "http://127.0.0.1:3773/.well-known/t3/environment", ]); - }).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer))); - }), + }).pipe(Effect.provide(TestClock.layer())), + ), ); it.effect("starts the configured backend and closes the scoped process on stop", () => - Effect.gen(function* () { - let startCount = 0; - let closedCount = 0; - const closed = yield* Deferred.make(); - const startedPids = yield* Queue.unbounded(); - const ready = yield* Deferred.make(); - const backendReady = yield* Ref.make(false); - const quitting = yield* Ref.make(false); + Effect.scoped( + Effect.gen(function* () { + let startCount = 0; + let closedCount = 0; + const closed = yield* Deferred.make(); + const startedPids = yield* Queue.unbounded(); + const ready = yield* Deferred.make(); + const backendReadyFlag = yield* Ref.make(false); - const spawnerLayer = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.gen(function* () { - const scope = yield* Scope.Scope; - startCount += 1; - yield* Queue.offer(startedPids, 123); - const close = Effect.sync(() => { - closedCount += 1; - }).pipe(Effect.andThen(Deferred.succeed(closed, void 0)), Effect.asVoid); + const spawnerLayer = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.gen(function* () { + const scope = yield* Scope.Scope; + startCount += 1; + yield* Queue.offer(startedPids, 123); + const close = Effect.sync(() => { + closedCount += 1; + }).pipe(Effect.andThen(Deferred.succeed(closed, void 0)), Effect.asVoid); - yield* Scope.addFinalizer(scope, close); + yield* Scope.addFinalizer(scope, close); - return makeProcess({ - exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), - kill: () => close, - }); - }), - ), - ); + return makeProcess({ + exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), + kill: () => close, + }); + }), + ), + ); - const managerLayer = makeManagerLayer({ - spawnerLayer, - desktopState: { - backendReady, - quitting, - }, - desktopWindow: { - handleBackendReady: Deferred.succeed(ready, void 0).pipe(Effect.asVoid), - }, - }); + const instance = yield* makeTestInstance({ + spawnerLayer, + onReady: Ref.set(backendReadyFlag, true).pipe( + Effect.andThen(Deferred.succeed(ready, void 0)), + Effect.asVoid, + ), + onShutdown: Ref.set(backendReadyFlag, false), + }); + assert.isTrue(Option.isNone(yield* instance.currentConfig)); - yield* Effect.gen(function* () { - const manager = yield* DesktopBackendManager.DesktopBackendManager; - assert.isTrue(Option.isNone(yield* manager.currentConfig)); - - yield* manager.start; + yield* instance.start; assert.equal(yield* Queue.take(startedPids), 123); yield* Deferred.await(ready); - assert.isTrue(yield* Ref.get(backendReady)); - assert.deepEqual(yield* manager.currentConfig, Option.some(baseConfig)); + assert.isTrue(yield* Ref.get(backendReadyFlag)); + assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig)); - const runningSnapshot = yield* manager.snapshot; + const runningSnapshot = yield* instance.snapshot; assert.equal(runningSnapshot.ready, true); assert.deepEqual(runningSnapshot.activePid, Option.some(123)); - yield* manager.stop(); + yield* instance.stop(); assert.equal(startCount, 1); assert.equal(closedCount, 1); - const stoppedSnapshot = yield* manager.snapshot; - assert.isFalse(yield* Ref.get(backendReady)); + const stoppedSnapshot = yield* instance.snapshot; + assert.isFalse(yield* Ref.get(backendReadyFlag)); assert.equal(stoppedSnapshot.desiredRunning, false); assert.equal(stoppedSnapshot.ready, false); assert.equal(Option.isNone(stoppedSnapshot.activePid), true); - }).pipe(Effect.provide(managerLayer)); - }), + }), + ), ); it.effect("restarts an unexpectedly exited backend with the Effect clock", () => - Effect.gen(function* () { - const starts = yield* Queue.unbounded(); - let startCount = 0; + Effect.scoped( + Effect.gen(function* () { + const starts = yield* Queue.unbounded(); + let startCount = 0; - const spawnerLayer = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.sync(() => { - startCount += 1; - return makeProcess({ - exitCode: Queue.offer(starts, startCount).pipe( - Effect.as(ChildProcessSpawner.ExitCode(1)), - ), - }); - }), - ), - ); + const spawnerLayer = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.sync(() => { + startCount += 1; + return makeProcess({ + exitCode: Queue.offer(starts, startCount).pipe( + Effect.as(ChildProcessSpawner.ExitCode(1)), + ), + }); + }), + ), + ); - const managerLayer = makeManagerLayer({ - spawnerLayer, - httpClientLayer: httpClientLayer(() => Effect.never), - }); + const instance = yield* makeTestInstance({ + spawnerLayer, + httpClientLayer: httpClientLayer(() => Effect.never), + }); - yield* Effect.gen(function* () { - const manager = yield* DesktopBackendManager.DesktopBackendManager; - yield* manager.start; + yield* instance.start; assert.equal(yield* Queue.take(starts), 1); @@ -392,107 +373,105 @@ describe("DesktopBackendManager", () => { assert.equal(yield* Queue.size(starts), 0); yield* TestClock.adjust(Duration.millis(1)); assert.equal(yield* Queue.take(starts), 3); - }).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer))); - }), + }).pipe(Effect.provide(TestClock.layer())), + ), ); it.effect("cancels a scheduled restart when start is requested manually", () => - Effect.gen(function* () { - const starts = yield* Queue.unbounded(); - const secondClosed = yield* Deferred.make(); - let startCount = 0; + Effect.scoped( + Effect.gen(function* () { + const starts = yield* Queue.unbounded(); + const secondClosed = yield* Deferred.make(); + let startCount = 0; - const spawnerLayer = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.gen(function* () { - startCount += 1; - yield* Queue.offer(starts, startCount); + const spawnerLayer = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.gen(function* () { + startCount += 1; + yield* Queue.offer(starts, startCount); - if (startCount === 1) { + if (startCount === 1) { + return makeProcess({ + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), + }); + } + + const scope = yield* Scope.Scope; + const close = Deferred.succeed(secondClosed, void 0).pipe(Effect.asVoid); + yield* Scope.addFinalizer(scope, close); return makeProcess({ - exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), + exitCode: Deferred.await(secondClosed).pipe( + Effect.as(ChildProcessSpawner.ExitCode(0)), + ), + kill: () => close, }); - } + }), + ), + ); - const scope = yield* Scope.Scope; - const close = Deferred.succeed(secondClosed, void 0).pipe(Effect.asVoid); - yield* Scope.addFinalizer(scope, close); - return makeProcess({ - exitCode: Deferred.await(secondClosed).pipe( - Effect.as(ChildProcessSpawner.ExitCode(0)), - ), - kill: () => close, - }); - }), - ), - ); + const instance = yield* makeTestInstance({ + spawnerLayer, + httpClientLayer: httpClientLayer(() => Effect.never), + }); - const managerLayer = makeManagerLayer({ - spawnerLayer, - httpClientLayer: httpClientLayer(() => Effect.never), - }); - - yield* Effect.gen(function* () { - const manager = yield* DesktopBackendManager.DesktopBackendManager; - yield* manager.start; + yield* instance.start; assert.equal(yield* Queue.take(starts), 1); - yield* manager.start; + yield* instance.start; assert.equal(yield* Queue.take(starts), 2); - yield* manager.stop(); + yield* instance.stop(); yield* TestClock.adjust(Duration.millis(500)); assert.equal(yield* Queue.size(starts), 0); - }).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer))); - }), + }).pipe(Effect.provide(TestClock.layer())), + ), ); it.effect("does not restart after stop cancels a scheduled restart", () => - Effect.gen(function* () { - const starts = yield* Queue.unbounded(); - let startCount = 0; + Effect.scoped( + Effect.gen(function* () { + const starts = yield* Queue.unbounded(); + let startCount = 0; - const spawnerLayer = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.sync(() => { - startCount += 1; - return makeProcess({ - exitCode: Queue.offer(starts, startCount).pipe( - Effect.as(ChildProcessSpawner.ExitCode(1)), - ), - }); - }), - ), - ); + const spawnerLayer = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.sync(() => { + startCount += 1; + return makeProcess({ + exitCode: Queue.offer(starts, startCount).pipe( + Effect.as(ChildProcessSpawner.ExitCode(1)), + ), + }); + }), + ), + ); - const managerLayer = makeManagerLayer({ - spawnerLayer, - httpClientLayer: httpClientLayer(() => Effect.never), - }); + const instance = yield* makeTestInstance({ + spawnerLayer, + httpClientLayer: httpClientLayer(() => Effect.never), + }); - yield* Effect.gen(function* () { - const manager = yield* DesktopBackendManager.DesktopBackendManager; - yield* manager.start; + yield* instance.start; assert.equal(yield* Queue.take(starts), 1); let restartScheduled = false; while (!restartScheduled) { - restartScheduled = (yield* manager.snapshot).restartScheduled; + restartScheduled = (yield* instance.snapshot).restartScheduled; if (!restartScheduled) { yield* Effect.yieldNow; } } - yield* manager.stop(); + yield* instance.stop(); yield* TestClock.adjust(Duration.millis(500)); assert.equal(yield* Queue.size(starts), 0); - assert.equal((yield* manager.snapshot).desiredRunning, false); - }).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer))); - }), + assert.equal((yield* instance.snapshot).desiredRunning, false); + }).pipe(Effect.provide(TestClock.layer())), + ), ); }); diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts index bd992c1726..0d0195428c 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.ts @@ -1,12 +1,34 @@ +// Per-instance backend factory. Replaces the legacy singleton +// `DesktopBackendManager` Context.Service: each call to +// `makeBackendInstance(spec)` constructs an isolated backend lifecycle — +// its own state Ref, mutex, restart loop, and active child process. The +// returned `DesktopBackendInstance` exposes start/stop/snapshot/wait +// methods that operate on that single backend. +// +// The pool layer (`DesktopBackendPool.ts`) calls this factory once per +// backend it wants to run. Today that's the Windows primary; follow-up +// commits add a second call for the WSL instance. +// +// Singleton couplings that the legacy service held inline are now +// parameterized via the spec: +// - configResolve replaces `DesktopBackendConfiguration.resolve` so each +// instance can resolve its own start config (Windows-native, WSL via +// wsl.exe, etc.). +// - onReady / onShutdown replace direct writes to +// `DesktopState.backendReady` and `DesktopWindow.handleBackendReady` +// so only the primary's spec wires those side effects. +// - log writes still go through the shared `DesktopBackendOutputLog` +// service for now; step 3 of the migration will split that per +// instance. + +import * as Brand from "effect/Brand"; import * as Cause from "effect/Cause"; -import * as Context from "effect/Context"; import * as Data from "effect/Data"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; -import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as PlatformError from "effect/PlatformError"; import * as Ref from "effect/Ref"; @@ -24,10 +46,7 @@ import { type DesktopBackendBootstrap as DesktopBackendBootstrapValue, } from "@t3tools/contracts"; -import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts"; import * as DesktopObservability from "../app/DesktopObservability.ts"; -import * as DesktopState from "../app/DesktopState.ts"; -import * as DesktopWindow from "../window/DesktopWindow.ts"; const INITIAL_RESTART_DELAY = Duration.millis(500); const MAX_RESTART_DELAY = Duration.seconds(10); @@ -115,24 +134,46 @@ export interface DesktopBackendSnapshot { readonly restartScheduled: boolean; } -export interface DesktopBackendManagerShape { +// 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. +export type BackendInstanceId = string & Brand.Brand<"BackendInstanceId">; +export const BackendInstanceId = Brand.nominal(); + +export const PRIMARY_INSTANCE_ID: BackendInstanceId = BackendInstanceId("primary"); + +// One pooled backend instance. Same lifecycle surface as the legacy +// `DesktopBackendManagerShape`; the id and label give the pool registry +// + UI something to route on. +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; - // Polls desiredRunning + ready until the backend reports ready, or the - // timeout elapses. Returns true on ready, false on timeout. Used by the - // WSL backend swap to drive its rollback path. + // Polls desiredRunning + the instance's own ready flag until the + // backend reports ready, or the timeout elapses. Returns true on + // ready, false on timeout. Used by the WSL backend swap to drive its + // rollback path. readonly waitForReady: (timeout: Duration.Duration) => Effect.Effect; } -export class DesktopBackendManager extends Context.Service< - DesktopBackendManager, - DesktopBackendManagerShape ->()("t3/desktop/BackendManager") {} - -const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } = - DesktopObservability.makeComponentLogger("desktop-backend-manager"); +// Spec describing one backend instance to spawn. The configResolve +// effect is awaited each time the instance is (re)started so live +// settings changes are picked up on the next start cycle. onReady and +// onShutdown let the primary instance trigger UI side effects (window +// open, global readiness flag) without coupling the factory to those +// concerns; other instances pass them as undefined. +export interface BackendInstanceSpec { + readonly id: BackendInstanceId; + readonly label: string; + readonly configResolve: Effect.Effect; + readonly onReady?: () => Effect.Effect; + readonly onShutdown?: () => Effect.Effect; +} interface ActiveBackendRun { readonly id: number; @@ -287,18 +328,33 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* ( return describeProcessExit(yield* Effect.result(handle.exitCode)); }); -const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(function* () { +// Factory for one pooled backend instance. The returned instance owns +// its own state Ref, mutex, restart loop, and active child process; +// nothing is shared between instances created from separate +// makeBackendInstance calls. The instance shuts down automatically when +// the calling scope closes (typically the application scope). +export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( + spec: BackendInstanceSpec, +): Effect.fn.Return< + DesktopBackendInstance, + never, + | FileSystem.FileSystem + | ChildProcessSpawner.ChildProcessSpawner + | HttpClient.HttpClient + | DesktopObservability.DesktopBackendOutputLog + | Scope.Scope +> { const parentScope = yield* Scope.Scope; const fileSystem = yield* FileSystem.FileSystem; - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; const backendOutputLog = yield* DesktopObservability.DesktopBackendOutputLog; - const desktopState = yield* DesktopState.DesktopState; - const desktopWindow = yield* DesktopWindow.DesktopWindow; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const httpClient = yield* HttpClient.HttpClient; const state = yield* Ref.make(initialState); const mutex = yield* Semaphore.make(1); + const { logWarning: logInstanceWarning, logError: logInstanceError } = + DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`); + const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) => Ref.update(state, withActiveRun(runId, f)); @@ -338,8 +394,8 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio return; } - yield* Ref.set(desktopState.backendReady, false); - const config = yield* configuration.resolve; + yield* spec.onShutdown?.() ?? Effect.void; + const config = yield* spec.configResolve; const entryExists = yield* fileSystem .exists(config.entryPath) .pipe(Effect.orElseSucceed(() => false)); @@ -377,7 +433,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio }, ]); - const finalizeRun = Effect.fn("desktop.backendManager.finalizeRun")(function* ( + const finalizeRun = Effect.fn("desktop.backendInstance.finalizeRun")(function* ( reason: string, ) { yield* mutex.withPermits(1)( @@ -426,10 +482,10 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio if (Option.isSome(pid)) { yield* backendOutputLog.writeSessionBoundary({ phase: "END", - details: `pid=${pid.value} ${reason}`, + details: `instance=${spec.id} pid=${pid.value} ${reason}`, }); } - yield* Ref.set(desktopState.backendReady, false); + yield* spec.onShutdown?.() ?? Effect.void; } if (isCurrentRun && nextState.desiredRunning) { @@ -441,17 +497,17 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio const program = runBackendProcess({ ...config, - onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) { + onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) { yield* updateActiveRun(runId, (run) => ({ ...run, pid: Option.some(pid), })); yield* backendOutputLog.writeSessionBoundary({ phase: "START", - details: `pid=${pid} port=${config.bootstrap.port} cwd=${config.cwd}`, + details: `instance=${spec.id} pid=${pid} port=${config.bootstrap.port} cwd=${config.cwd}`, }); }), - onReady: Effect.fn("desktop.backendManager.onReady")(function* () { + onReady: Effect.fn("desktop.backendInstance.onReady")(function* () { const isCurrentRun = yield* Ref.modify(state, (latest) => { const activeRun = Option.getOrUndefined(latest.active); if (activeRun?.id !== runId) { @@ -471,17 +527,10 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio return; } - yield* Ref.set(desktopState.backendReady, true); - yield* desktopWindow.handleBackendReady.pipe( - Effect.catch((error) => - logBackendManagerError("failed to open main window after backend readiness", { - message: error.message, - }), - ), - ); + yield* spec.onReady?.() ?? Effect.void; }), onReadinessFailure: (error) => - logBackendManagerWarning("backend readiness check failed during bootstrap", { + logInstanceWarning("backend readiness check failed during bootstrap", { error: error.message, }), onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk), @@ -503,9 +552,9 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio })); }), ), - ).pipe(Effect.withSpan("desktop.backendManager.start")); + ).pipe(Effect.withSpan("desktop.backendInstance.start", { attributes: { id: spec.id } })); - const scheduleRestart = Effect.fn("desktop.backendManager.scheduleRestart")(function* ( + const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* ( reason: string, ) { const scheduled = yield* Ref.modify(state, (latest) => { @@ -525,8 +574,8 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio yield* Option.match(scheduled, { onNone: () => Effect.void, - onSome: Effect.fn("desktop.backendManager.scheduleRestartFiber")(function* (delay) { - yield* logBackendManagerError("backend exited unexpectedly; restart scheduled", { + onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* (delay) { + yield* logInstanceError("backend exited unexpectedly; restart scheduled", { reason, delayMs: Duration.toMillis(delay), }); @@ -546,7 +595,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio ), Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)), Effect.catchCause((cause) => - logBackendManagerError("desktop backend restart fiber failed", { + logInstanceError("desktop backend restart fiber failed", { cause: Cause.pretty(cause), }), ), @@ -565,7 +614,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio }); }); - const stop = Effect.fn("desktop.backendManager.stop")(function* (options?: { + const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: { readonly timeout?: Duration.Duration; }) { const { active, restartFiber } = yield* mutex.withPermits(1)( @@ -583,7 +632,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio restartFiber: Option.none>(), }, ]); - yield* Ref.set(desktopState.backendReady, false); + yield* spec.onShutdown?.() ?? Effect.void; return result; }), ); @@ -604,8 +653,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio // Return false early if an external `stop()` flipped desiredRunning off // — no point polling for a backend that is being torn down. if (!current.desiredRunning) return { done: true, ready: false }; - const ready = yield* Ref.get(desktopState.backendReady); - return ready ? { done: true, ready: true } : { done: false, ready: false }; + return current.ready ? { done: true, ready: true } : { done: false, ready: false }; }).pipe( Effect.repeat({ until: (status) => status.done, @@ -618,13 +666,13 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio yield* Effect.addFinalizer(() => stop()); - return DesktopBackendManager.of({ + return { + id: spec.id, + label: spec.label, start, stop, currentConfig, snapshot, waitForReady, - }); + } satisfies DesktopBackendInstance; }); - -export const layer = Layer.effect(DesktopBackendManager, makeDesktopBackendManager()); diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.ts index 5545b175f9..d3a80c0a3d 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.ts @@ -2,28 +2,26 @@ // 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. +// Current state (step 1): +// - `DesktopBackendManager.ts` no longer exposes a Context.Service. It +// is a per-instance factory (`makeBackendInstance(spec)`); the pool +// calls it once for the Windows primary at startup. +// - The primary spec wires `configResolve` to `DesktopBackendConfiguration` +// and the `onReady`/`onShutdown` callbacks to the legacy global side +// effects (`DesktopState.backendReady`, `DesktopWindow.handleBackendReady`). +// Those couplings move per-instance in steps 2-3. +// - Consumers (window/wsl IPC, lifecycle hooks, telemetry) read the +// primary instance off `pool.primary`. There is no longer a separate +// `DesktopBackendManager` service in the layer graph. // // 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. +// - The pool layer constructs N instances — at minimum the Windows +// primary; the WSL instance is added when the user enables the WSL +// backend (with the selected distro). +// - Per-instance state (readiness, restart fiber, active run) already +// lives on each `DesktopBackendInstance` after step 1. Step 2 moves +// the global `DesktopState.backendReady` flag onto the pool's primary +// readiness; step 3 splits backend log routing per instance. // - `getLocalEnvironmentBootstrap()` widens to // `getLocalEnvironmentBootstraps()` returning one bootstrap per pool // instance; the frontend env runtime registers each as a local @@ -33,62 +31,37 @@ // 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 +// 1. (this commit) Reshape `DesktopBackendManager` into an instance +// factory and route consumers through the pool. Pool still holds a +// single instance. +// 2. Drop `DesktopState.backendReady`. UI subscribes to +// `pool.primary.snapshot.ready` (or the multi-instance readiness +// signal once it exists). +// 3. 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` +// 4. Add register/unregister so WSL backend can be added on demand. +// 5. Wire WSL distro startup through the pool; remove `setWslBackend` // mode-swap IPC in favor of `enableWslBackend` / `setWslDistro`. -// 7. Widen `getLocalEnvironmentBootstrap` → `*Bootstraps`; frontend +// 6. 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 +// 7. 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 DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts"; import * as DesktopBackendManager from "./DesktopBackendManager.ts"; -import type { DesktopBackendSnapshot, DesktopBackendStartConfig } from "./DesktopBackendManager.ts"; +import * as DesktopState from "../app/DesktopState.ts"; +import * as DesktopWindow from "../window/DesktopWindow.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 type BackendInstanceId = DesktopBackendManager.BackendInstanceId; +export const BackendInstanceId = DesktopBackendManager.BackendInstanceId; +export const PRIMARY_INSTANCE_ID = DesktopBackendManager.PRIMARY_INSTANCE_ID; +export type DesktopBackendInstance = DesktopBackendManager.DesktopBackendInstance; export interface DesktopBackendPoolShape { // Look up a registered instance. None when no backend with that id is @@ -109,38 +82,32 @@ export class DesktopBackendPool extends Context.Service< 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, + const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; + const desktopState = yield* DesktopState.DesktopState; + const desktopWindow = yield* DesktopWindow.DesktopWindow; + + const primary = yield* DesktopBackendManager.makeBackendInstance({ + id: DesktopBackendManager.PRIMARY_INSTANCE_ID, label: "Windows", - start: manager.start, - stop: manager.stop, - currentConfig: manager.currentConfig, - snapshot: manager.snapshot, - waitForReady: manager.waitForReady, - }; + configResolve: configuration.resolve, + onReady: () => desktopWindow.handleBackendReady.pipe(Effect.catch(() => Effect.void)), + onShutdown: () => Ref.set(desktopState.backendReady, false), + }); + const instancesRef = yield* Ref.make>( - new Map([[PRIMARY_INSTANCE_ID, primaryInstance]]), + new Map([[DesktopBackendManager.PRIMARY_INSTANCE_ID, primary]]), ); + 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), + primary: Effect.succeed(primary), }); }), ); diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index b3121a22c2..ca10b1c9cd 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -9,7 +9,7 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts"; +import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts"; import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; @@ -51,8 +51,9 @@ export const getLocalEnvironmentBootstrap = makeSyncIpcMethod({ channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL, result: Schema.NullOr(DesktopEnvironmentBootstrapSchema), handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstrap")(function* () { - const backendManager = yield* DesktopBackendManager.DesktopBackendManager; - const config = yield* backendManager.currentConfig; + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const primaryBackend = yield* pool.primary; + const config = yield* primaryBackend.currentConfig; return Option.match(config, { onNone: () => null, onSome: ({ bootstrap, httpBaseUrl }) => ({ diff --git a/apps/desktop/src/ipc/methods/wsl.ts b/apps/desktop/src/ipc/methods/wsl.ts index 4bbd70248a..0e6bb0499c 100644 --- a/apps/desktop/src/ipc/methods/wsl.ts +++ b/apps/desktop/src/ipc/methods/wsl.ts @@ -8,7 +8,7 @@ import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; -import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts"; +import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts"; import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; import * as IpcChannels from "../channels.ts"; @@ -64,7 +64,8 @@ export const setWslBackend = makeIpcMethod({ result: DesktopWslStateSchema, handler: Effect.fn("desktop.ipc.wsl.setBackend")(function* (input) { const appSettings = yield* DesktopAppSettings.DesktopAppSettings; - const backendManager = yield* DesktopBackendManager.DesktopBackendManager; + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const primaryBackend = yield* pool.primary; const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment; // Pre-warm the WSL VM before swapping so the new backend boot doesn't @@ -81,23 +82,23 @@ export const setWslBackend = makeIpcMethod({ } // In-process swap: stop the running backend, then start it again. The - // backend manager re-resolves config on start, so the new wslMode picks + // backend instance re-resolves config on start, so the new wslMode picks // up automatically. - yield* backendManager.stop(); - yield* backendManager.start; + yield* primaryBackend.stop(); + yield* primaryBackend.start; // Bounded readiness wait — if the new backend doesn't come up in time // (bad distro, missing node-pty, preflight failure that scheduled // restarts forever) revert to the previous mode so the user isn't stuck. - const ready = yield* backendManager.waitForReady(SWAP_READINESS_TIMEOUT); + const ready = yield* primaryBackend.waitForReady(SWAP_READINESS_TIMEOUT); if (!ready) { yield* appSettings.setWslMode({ mode: previousSettings.wslMode, distro: previousSettings.wslDistro, }); - yield* backendManager.stop(); - yield* backendManager.start; - const rolledBack = yield* backendManager.waitForReady(SWAP_READINESS_TIMEOUT); + yield* primaryBackend.stop(); + yield* primaryBackend.start; + const rolledBack = yield* primaryBackend.waitForReady(SWAP_READINESS_TIMEOUT); const failedTarget = input.mode === "wsl" ? "WSL backend" : "local backend"; return yield* new WslBackendSwapError({ message: rolledBack diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index ed57713dfa..9cd0fe8888 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -29,7 +29,6 @@ import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts"; 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"; @@ -129,14 +128,12 @@ const desktopServerExposureLayer = DesktopServerExposure.layer.pipe( const desktopWindowLayer = DesktopWindow.layer.pipe(Layer.provideMerge(desktopServerExposureLayer)); -// 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. +// Pool layer instantiates the backend factory once for the Windows +// primary instance and exposes it via pool.primary. Consumers go through +// the pool now; the legacy DesktopBackendManager service is gone. The +// WSL second instance gets registered later in the migration. See +// DesktopBackendPool.ts header for the full rollout plan. const desktopBackendLayer = DesktopBackendPool.layer.pipe( - Layer.provideMerge(DesktopBackendManager.layer), Layer.provideMerge(DesktopAppIdentity.layer), Layer.provideMerge(DesktopBackendConfiguration.layer), Layer.provideMerge(DesktopWslEnvironment.layer), diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts index 384743ee91..d73235abf9 100644 --- a/apps/desktop/src/updates/DesktopUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopUpdates.test.ts @@ -10,7 +10,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as TestClock from "effect/testing/TestClock"; -import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts"; +import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts"; import * as DesktopConfig from "../app/DesktopConfig.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as ElectronUpdater from "../electron/ElectronUpdater.ts"; @@ -101,7 +101,9 @@ function makeHarness(options: UpdatesHarnessOptions = {}) { syncAllAppearance: () => Effect.void, } satisfies ElectronWindow.ElectronWindowShape); - const backendLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, { + const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = { + id: DesktopBackendPool.PRIMARY_INSTANCE_ID, + label: "Windows", start: Effect.void, stop: () => Effect.void, currentConfig: Effect.succeed(Option.none()), @@ -113,7 +115,8 @@ function makeHarness(options: UpdatesHarnessOptions = {}) { restartScheduled: false, }), waitForReady: () => Effect.succeed(true), - }); + }; + const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]); const environmentLayer = DesktopEnvironment.layer({ dirname: "/repo/apps/desktop/src", diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index 8c0acd2e8a..0b1e6ef915 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -18,7 +18,7 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; -import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts"; +import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts"; import * as DesktopConfig from "../app/DesktopConfig.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopObservability from "../app/DesktopObservability.ts"; @@ -187,7 +187,8 @@ function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean const make = Effect.gen(function* () { const config = yield* DesktopConfig.DesktopConfig; - const backendManager = yield* DesktopBackendManager.DesktopBackendManager; + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const primaryBackend = yield* pool.primary; const desktopState = yield* DesktopState.DesktopState; const electronUpdater = yield* ElectronUpdater.ElectronUpdater; const electronWindow = yield* ElectronWindow.ElectronWindow; @@ -368,7 +369,7 @@ const make = Effect.gen(function* () { yield* Ref.set(updateInstallInFlightRef, true); return yield* Effect.gen(function* () { - yield* backendManager.stop({ timeout: Duration.seconds(5) }); + yield* primaryBackend.stop({ timeout: Duration.seconds(5) }); yield* electronWindow.destroyAll; yield* electronUpdater.quitAndInstall({ isSilent: true,