import { DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE, DESKTOP_UPDATE_IN_PROGRESS_TTL_MS, } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as FiberHandle from "effect/FiberHandle"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as SynchronizedRef from "effect/SynchronizedRef"; import * as FileSystem from "effect/FileSystem"; import { HttpClient } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts"; import * as DesktopBackendManager from "./DesktopBackendManager.ts"; import * as DesktopHomeOwner from "./DesktopHomeOwner.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopObservability from "../app/DesktopObservability.ts"; import * as DesktopState from "../app/DesktopState.ts"; import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts"; import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts"; import * as DesktopWindow from "../window/DesktopWindow.ts"; import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts"; import * as ElectronDialog from "../electron/ElectronDialog.ts"; import * as ElectronApp from "../electron/ElectronApp.ts"; const { logWarning: logBackendPoolWarning } = DesktopObservability.makeComponentLogger("desktop-backend-pool"); const decodeServerRuntime = Schema.decodeUnknownEffect( Schema.fromJsonString(Schema.Struct({ pid: Schema.Number, port: Schema.Number })), ); 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 type BackendInstanceSpec = DesktopBackendManager.BackendInstanceSpec; export class DesktopBackendPoolInstanceAlreadyRegisteredError extends Schema.TaggedError()( "DesktopBackendPoolInstanceAlreadyRegisteredError", { id: Schema.String, }, ) { override get message() { return `Backend instance "${this.id}" is already registered in the pool.`; } } export class DesktopBackendPoolCannotUnregisterPrimaryError extends Schema.TaggedError()( "DesktopBackendPoolCannotUnregisterPrimaryError", {}, ) { override get message() { return "Refusing to unregister the primary backend from the pool."; } } export class DesktopBackendPool extends Context.Service< DesktopBackendPool, { readonly get: (id: BackendInstanceId) => Effect.Effect>; readonly list: Effect.Effect; readonly primary: Effect.Effect; readonly register: ( spec: BackendInstanceSpec, ) => Effect.Effect; readonly unregister: ( id: BackendInstanceId, ) => Effect.Effect; } >()("@t3tools/desktop/backend/DesktopBackendPool") {} export type BackendInstanceFactoryRequirements = | FileSystem.FileSystem | ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient | DesktopObservability.DesktopBackendOutputLogFactory | DesktopTelemetryPublisher.DesktopTelemetryPublisher | DesktopBrowserHost.DesktopBrowserHost | DesktopWslEnvironment.DesktopWslEnvironment; interface ActiveRegisteredInstance { readonly _tag: "Active"; readonly instance: DesktopBackendInstance; readonly scope: Option.Option; } interface ClosingRegisteredInstance { readonly _tag: "Closing"; readonly done: Deferred.Deferred; } type RegisteredInstance = ActiveRegisteredInstance | ClosingRegisteredInstance; type RegisterAction = | { readonly _tag: "Registered"; readonly instance: DesktopBackendInstance } | { readonly _tag: "Wait"; readonly done: Deferred.Deferred }; type UnregisterAction = | { readonly _tag: "Absent" } | { readonly _tag: "Wait"; readonly done: Deferred.Deferred } | { readonly _tag: "Close"; readonly entry: ActiveRegisteredInstance }; export const layer = Layer.effect( DesktopBackendPool, Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const fileSystem = yield* FileSystem.FileSystem; const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; const desktopWindow = yield* DesktopWindow.DesktopWindow; const electronDialog = yield* ElectronDialog.ElectronDialog; const electronApp = yield* ElectronApp.ElectronApp; const appSettings = yield* DesktopAppSettings.DesktopAppSettings; const { primaryBackendStartup } = yield* DesktopState.DesktopState; // Parent instance scopes to the pool so shutdown runs stop finalizers before the OS kills backends. const layerScope = yield* Scope.Scope; const factoryContext = yield* Effect.context(); const homeOwnerContext = yield* Effect.context< FileSystem.FileSystem | Path.Path | DesktopEnvironment.DesktopEnvironment >(); const updateMarkerPath = environment.path.join( environment.baseDir, "runtime", DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE, ); const serverRuntimePath = environment.path.join(environment.stateDir, "server-runtime.json"); // The server publishes its runtime after HTTP readiness. Until then an SSH launcher // finds nothing to adopt, so dropping the marker earlier lets it start a competing server. const releaseUpdateMarker = Effect.fn("desktop.backendPool.releaseUpdateMarker")(function* ( httpBaseUrl: URL, pid: number, ) { const marker = yield* fileSystem.readFileString(updateMarkerPath).pipe(Effect.option); if (Option.isNone(marker)) { return; } yield* fileSystem.readFileString(serverRuntimePath).pipe( Effect.flatMap(decodeServerRuntime), Effect.map((runtime) => runtime.pid === pid && runtime.port === Number(httpBaseUrl.port)), Effect.orElseSucceed(() => false), Effect.repeat({ until: (published) => published, schedule: Schedule.spaced(Duration.millis(100)), }), Effect.timeoutOption(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS)), ); // A later update may have replaced the marker; that handoff is not ours to end. const current = yield* fileSystem.readFileString(updateMarkerPath).pipe(Effect.option); if (Option.isSome(current) && current.value === marker.value) { yield* fileSystem.remove(updateMarkerPath, { force: true }).pipe(Effect.ignore); } }); // One wait at a time: each run's shutdown or readiness ends the previous run's wait. const updateMarkerWait = yield* FiberHandle.make(); // In memory only: the saved WSL preference is retried on the next launch. const useWindowsForThisLaunch = Effect.fn("desktop.backendPool.useWindowsForThisLaunch")( function* (reason: string) { yield* electronDialog.showErrorBox( "WSL backend is still unavailable", `${reason}\n\nT3 Code will use the Windows backend for this launch and retry WSL the next time the app starts.`, ); yield* appSettings.applyWslWindowsFallbackInMemory; }, ); // Persist fatal Windows fallbacks; transient transport failures must preserve the user's WSL preference. const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")( function* (failure: DesktopBackendManager.PreflightFailure) { const { reason, fatal } = failure; if (!fatal) { yield* logBackendPoolWarning( "primary WSL preflight retry window exhausted; using Windows for this launch", { reason }, ); yield* useWindowsForThisLaunch(reason); return true; } yield* logBackendPoolWarning("primary WSL preflight failed; falling back to Windows", { reason, }); yield* electronDialog.showErrorBox( "WSL backend couldn't start", `${reason}\n\nFalling back to the Windows backend so T3 Code can open. Re-enable the WSL backend from Settings > Sharing & access once the WSL distro is fixed.`, ); // Clear wslOnly too so enabling WSL cannot restore a failed mode. // Keep the in-memory fallback if persistence fails. yield* appSettings.applyWslWindowsFallback.pipe( Effect.catch((error) => logBackendPoolWarning( "failed to persist Windows fallback after WSL preflight failure", { error: error.message, }, ).pipe(Effect.andThen(appSettings.applyWslWindowsFallbackInMemory)), ), ); return true; }, ); const handlePrimaryStartupFailure = Effect.fn("desktop.backendPool.primaryStartupFailed")( function* (failure: DesktopBackendManager.BackendStartupFailure) { const config = yield* primary.currentConfig; const runningOnWsl = Option.exists(config, (value) => value.runningDistro !== undefined); if (!runningOnWsl || !(yield* appSettings.get).wslOnly) { return yield* SubscriptionRef.set(primaryBackendStartup, { _tag: "Failing", ...failure }); } // A live server that missed readiness may still be booting: keep probing, and let // the recovery window offer Windows. Forked into the pool scope because stop closes this run. if (Option.isSome((yield* primary.snapshot).activePid)) { return yield* SubscriptionRef.set(primaryBackendStartup, { _tag: "Failing", ...failure, useWindows: appSettings.applyWslWindowsFallbackInMemory.pipe( Effect.andThen( Effect.forkIn(primary.stop().pipe(Effect.andThen(primary.start)), layerScope), ), Effect.asVoid, ), }); } yield* logBackendPoolWarning( "primary WSL backend failed to start; using Windows for this launch", { reason: failure.reason }, ); // The manager's scheduled restart resolves the primary again and comes up on Windows. yield* useWindowsForThisLaunch(failure.reason); }, ); const primary: DesktopBackendInstance = yield* DesktopBackendManager.makeBackendInstance({ id: DesktopBackendManager.PRIMARY_INSTANCE_ID, // Resolve lazily: startup loads persisted settings after pool initialization. label: configuration.resolvePrimaryLabel, configResolve: configuration.resolvePrimary, // Absorb window errors so readiness can reset restartAttempt. onReady: (httpBaseUrl, pid) => FiberHandle.run(updateMarkerWait, releaseUpdateMarker(httpBaseUrl, pid)).pipe( Effect.andThen(desktopWindow.handleBackendReady(httpBaseUrl)), // Only once the main window exists, so the recovery window never closes into nothing. Effect.andThen(SubscriptionRef.set(primaryBackendStartup, { _tag: "Ready" })), Effect.catch((error) => logBackendPoolWarning("failed to open main window after backend readiness", { error: error.message, }), ), ), onStartupFailure: handlePrimaryStartupFailure, onShutdown: () => FiberHandle.clear(updateMarkerWait).pipe( Effect.andThen(desktopWindow.handleBackendNotReady), ), onPreflightFailed: handlePrimaryPreflightFailure, onStateDirOwned: () => DesktopHomeOwner.readLiveHomeOwner().pipe( Effect.flatMap((owner) => electronDialog.showErrorBox( "This T3 home is unavailable", DesktopHomeOwner.homeOwnedMessage(owner), ), ), Effect.provideContext(homeOwnerContext), Effect.andThen(electronApp.quit), ), }); const instancesRef = yield* SynchronizedRef.make< ReadonlyMap >( new Map([ [ DesktopBackendManager.PRIMARY_INSTANCE_ID, { _tag: "Active", instance: primary, scope: Option.none() }, ], ]), ); const register: DesktopBackendPool["Service"]["register"] = (spec) => Effect.suspend(() => SynchronizedRef.modifyEffect( instancesRef, ( current, ): Effect.Effect< readonly [RegisterAction, ReadonlyMap], DesktopBackendPoolInstanceAlreadyRegisteredError > => { const existing = current.get(spec.id); if (existing?._tag === "Active") { return Effect.fail( new DesktopBackendPoolInstanceAlreadyRegisteredError({ id: spec.id }), ); } if (existing?._tag === "Closing") { return Effect.succeed([ { _tag: "Wait", done: existing.done } as const, current, ] as const); } return Effect.gen(function* () { // Provide the child Scope last so the captured pool Scope cannot shadow it and orphan stop/restart finalizers. const instanceScope = yield* Scope.fork(layerScope, "sequential"); const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe( Scope.provide(instanceScope), Effect.provide(factoryContext), ); const next = new Map(current); next.set(spec.id, { _tag: "Active", instance, scope: Option.some(instanceScope), }); return [ { _tag: "Registered", instance } as const, next as ReadonlyMap, ] as const; }); }, ).pipe( Effect.flatMap((result) => result._tag === "Registered" ? Effect.succeed(result.instance) : Deferred.await(result.done).pipe(Effect.andThen(register(spec))), ), ), ); const unregister: DesktopBackendPool["Service"]["unregister"] = Effect.fn( "DesktopBackendPool.unregister", )(function* (id) { if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) { return yield* new DesktopBackendPoolCannotUnregisterPrimaryError(); } const done = yield* Deferred.make(); const action = yield* SynchronizedRef.modifyEffect( instancesRef, ( current, ): Effect.Effect< readonly [UnregisterAction, ReadonlyMap] > => { const entry = current.get(id); if (entry === undefined) { return Effect.succeed([{ _tag: "Absent" } as const, current] as const); } if (entry._tag === "Closing") { return Effect.succeed([{ _tag: "Wait", done: entry.done } as const, current] as const); } const next = new Map(current); next.set(id, { _tag: "Closing", done }); return Effect.succeed([ { _tag: "Close", entry } as const, next as ReadonlyMap, ] as const); }, ); if (action._tag === "Absent") return; if (action._tag === "Wait") { yield* Deferred.await(action.done); return; } const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => { const closing = current.get(id); if (closing?._tag !== "Closing" || closing.done !== done) { return Effect.succeed([undefined, current] as const); } const next = new Map(current); next.delete(id); return Effect.succeed([ undefined, next as ReadonlyMap, ] as const); }).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid); yield* Option.match(action.entry.scope, { onNone: () => Effect.void, onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore), }).pipe(Effect.ensuring(finish)); }); return DesktopBackendPool.of({ get: Effect.fn("DesktopBackendPool.get")(function (id) { return SynchronizedRef.get(instancesRef).pipe( Effect.map((instances) => { const entry = instances.get(id); return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none(); }), ); }), list: SynchronizedRef.get(instancesRef).pipe( Effect.map((instances) => Array.from(instances.values()).flatMap((entry) => entry._tag === "Active" ? [entry.instance] : [], ), ), ), primary: Effect.succeed(primary), register, unregister, }); }), ); 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: Effect.fn("DesktopBackendPool.get")(function (id) { return Effect.succeed(Option.fromNullishOr(byId.get(id))); }), list: Effect.succeed(Array.from(byId.values())), primary: Effect.succeed(primary), register: Effect.fn("DesktopBackendPool.register")(function () { return Effect.die("DesktopBackendPool.layerTest does not support register"); }), unregister: Effect.fn("DesktopBackendPool.unregister")(function () { return Effect.die("DesktopBackendPool.layerTest does not support unregister"); }), }); }), );