Open History to see the last commit
1// Per-instance backend factory. Replaces the legacy singleton
2// `DesktopBackendManager` Context.Service: each call to
3// `makeBackendInstance(spec)` constructs an isolated backend lifecycle —
4// its own state Ref, mutex, restart loop, and active child process. The
5// returned `DesktopBackendInstance` exposes start/stop/snapshot/wait
6// methods that operate on that single backend.
7//
8// The pool layer (`DesktopBackendPool.ts`) calls this factory once per
9// backend it wants to run. Today that's the Windows primary; follow-up
10// commits add a second call for the WSL instance.
11//
12// Singleton couplings that the legacy service held inline are now
13// parameterized via the spec:
14// - configResolve replaces the legacy `DesktopBackendConfiguration.resolve`
15// so each instance can resolve its own start config — the primary wires
16// `configuration.resolvePrimary`, the WSL orchestrator wires a
17// `configuration.resolveWsl({ port, distro })` closure.
18// - onReady / onShutdown drive UI side effects (window auto-open,
19// readiness latch) only for instances that want them — the primary's
20// spec passes the window's handleBackendReady/handleBackendNotReady,
21// other pool instances pass nothing.
22// - log writes go through a per-instance writer that the factory
23// pulls from `DesktopBackendOutputLogFactory.forInstance(spec.id)`,
24// so each instance lands in its own rotating file.
25
26import * as Brand from "effect/Brand";
27import * as Cause from "effect/Cause";
28import * as Duration from "effect/Duration";
29import * as Effect from "effect/Effect";
30import * as Exit from "effect/Exit";
31import * as Fiber from "effect/Fiber";
32import * as FileSystem from "effect/FileSystem";
33import * as Option from "effect/Option";
34import * as PlatformError from "effect/PlatformError";
35import * as Ref from "effect/Ref";
36import * as Schedule from "effect/Schedule";
37import * as Schema from "effect/Schema";
38import * as Semaphore from "effect/Semaphore";
39import * as Scope from "effect/Scope";
40import * as Stream from "effect/Stream";
41import { HttpClient } from "effect/unstable/http";
42import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
43
44import {
45 DesktopBackendBootstrap,
46 type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
47 PRIMARY_LOCAL_ENVIRONMENT_ID,
48 DesktopTelemetryControlMessage,
49 type DesktopTelemetryControlMessage as DesktopTelemetryControlMessageValue,
50} from "@t3tools/contracts";
51import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness";
52
53import * as DesktopObservability from "../app/DesktopObservability.ts";
54import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
55import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
56
57const INITIAL_RESTART_DELAY = Duration.millis(500);
58const MAX_RESTART_DELAY = Duration.seconds(10);
59// After this many consecutive fatal preflight failures, stop the silent
60// restart loop and surface the reason via onPreflightFailed. Transient
61// failures may instead provide their own larger retryLimit when they should
62// self-heal for a while but must not leave the app connecting forever.
63const MAX_PREFLIGHT_FAILURE_ATTEMPTS = 5;
64const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
65const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
66const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
67const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(2);
68const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.seconds(5);
69const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
70const { logWarning: logBackendProcessWarning } =
71 DesktopObservability.makeComponentLogger("desktop-backend-process");
72
73type BackendProcessLayerServices = ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient;
74
75type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
76
77export type BackendProcessOutputStream = "stdout" | "stderr";
78
79export interface BackendProcessContext {
80 readonly executablePath: string;
81 readonly entryPath: string;
82 readonly cwd: string;
83 readonly httpBaseUrl: URL;
84}
85
86export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
87
88export interface DesktopBackendStartConfig extends BackendProcessContext {
89 readonly args: ReadonlyArray<string>;
90 readonly env: Record<string, string | undefined>;
91 // When true the spawner merges the desktop process.env on top of `env`;
92 // when false `env` is passed verbatim. WSL mode opts out so a leaking
93 // T3CODE_HOME can't pin the WSL backend to /mnt/c/...\.t3.
94 readonly extendEnv: boolean;
95 readonly bootstrap: DesktopBackendBootstrapValue;
96 readonly bootstrapDelivery: DesktopBackendBootstrapDelivery;
97 readonly httpBaseUrl: URL;
98 readonly captureOutput: boolean;
99 readonly preflightFailure: Option.Option<PreflightFailure>;
100 // Present for a WSL run after the configured/default distro has been
101 // resolved to the concrete distro passed to wsl.exe.
102 readonly runningDistro?: string;
103 // Present only when this run launched from a staged WSL-local runtime.
104 // Once HTTP readiness succeeds, the manager uses it to retain this cache
105 // plus the newest previous cache and prune older versions.
106 readonly wslRuntimeId?: string;
107}
108
109// A preflight failure records whether it is fatal. Transient failures (WSL
110// cold-starting, wslpath while the VM boots) keep retrying so the backend can
111// self-heal; fatal ones (no node, wrong version, missing build tools) are
112// surfaced via onPreflightFailed and stop the restart loop after
113// MAX_PREFLIGHT_FAILURE_ATTEMPTS.
114export interface PreflightFailure {
115 readonly reason: string;
116 readonly fatal: boolean;
117 readonly retryLimit?: number;
118}
119
120interface BackendProcessExit {
121 readonly code: Option.Option<number>;
122 readonly reason: string;
123}
124
125const backendProcessContextSchema = {
126 executablePath: Schema.String,
127 entryPath: Schema.String,
128 cwd: Schema.String,
129 httpBaseUrl: Schema.URL,
130};
131
132export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
133 "BackendReadinessTimeoutError",
134 {
135 ...backendProcessContextSchema,
136 readinessUrl: Schema.URL,
137 timeoutMs: Schema.Number,
138 cause: Schema.Defect(),
139 },
140) {
141 override get message(): string {
142 return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
143 }
144}
145
146export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
147 "BackendProcessBootstrapEncodeError",
148 {
149 ...backendProcessContextSchema,
150 cause: Schema.Defect(),
151 },
152) {
153 override get message(): string {
154 return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
155 }
156}
157
158export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
159 "BackendProcessSpawnError",
160 {
161 ...backendProcessContextSchema,
162 cause: Schema.Defect(),
163 },
164) {
165 override get message(): string {
166 return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
167 }
168}
169
170export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()(
171 "BackendProcessOutputReadError",
172 {
173 ...backendProcessContextSchema,
174 pid: Schema.Number,
175 streamName: Schema.Literals(["stdout", "stderr"]),
176 cause: Schema.Defect(),
177 },
178) {
179 override get message(): string {
180 return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
181 }
182}
183
184export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
185 "BackendProcessOutputHandlingError",
186 {
187 ...backendProcessContextSchema,
188 pid: Schema.Number,
189 streamName: Schema.Literals(["stdout", "stderr"]),
190 chunkByteLength: Schema.Number,
191 cause: Schema.Defect(),
192 },
193) {
194 override get message(): string {
195 return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
196 }
197}
198
199export type BackendProcessOutputError =
200 | BackendProcessOutputReadError
201 | BackendProcessOutputHandlingError;
202
203export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
204 "BackendProcessExitStatusError",
205 {
206 ...backendProcessContextSchema,
207 pid: Schema.Number,
208 cause: Schema.Defect(),
209 },
210) {
211 override get message(): string {
212 return `Failed to read the exit status of desktop backend process ${this.pid}.`;
213 }
214}
215
216export const BackendProcessError = Schema.Union([
217 BackendProcessBootstrapEncodeError,
218 BackendProcessSpawnError,
219 BackendProcessExitStatusError,
220]);
221export type BackendProcessError = typeof BackendProcessError.Type;
222
223interface RunBackendProcessOptions extends DesktopBackendStartConfig {
224 readonly desktopTelemetryStream: Stream.Stream<Uint8Array>;
225 readonly onDesktopTelemetryControl?: (
226 message: DesktopTelemetryControlMessageValue,
227 ) => Effect.Effect<void>;
228 readonly readinessTimeout?: Duration.Duration;
229 readonly outputDrainTimeout?: Duration.Duration;
230 readonly onStarted?: (pid: number) => Effect.Effect<void>;
231 readonly onExitObserved?: () => Effect.Effect<void>;
232 readonly onReady?: () => Effect.Effect<void>;
233 readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
234 readonly onOutput?: (
235 streamName: BackendProcessOutputStream,
236 chunk: Uint8Array,
237 ) => Effect.Effect<void, Error>;
238 readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
239}
240
241export interface DesktopBackendSnapshot {
242 readonly desiredRunning: boolean;
243 readonly ready: boolean;
244 readonly activePid: Option.Option<number>;
245 readonly restartAttempt: number;
246 readonly restartScheduled: boolean;
247}
248
249// Opaque identifier for one backend process inside the pool. Today only
250// PRIMARY_INSTANCE_ID is registered. Follow-up commits add WSL distros
251// under ids derived from the distro name (e.g. "wsl:ubuntu"). Eventually
252// these map 1:1 with environment ids on the frontend; keeping them
253// desktop-local for now avoids leaking the contracts dependency.
254export type BackendInstanceId = string & Brand.Brand<"BackendInstanceId">;
255export const BackendInstanceId = Brand.nominal<BackendInstanceId>();
256
257export const PRIMARY_INSTANCE_ID: BackendInstanceId = BackendInstanceId(
258 PRIMARY_LOCAL_ENVIRONMENT_ID,
259);
260
261// One pooled backend instance. Same lifecycle surface as the legacy
262// `DesktopBackendManagerShape`; the id and label give the pool registry
263// + UI something to route on.
264export interface DesktopBackendInstance {
265 readonly id: BackendInstanceId;
266 readonly label: Effect.Effect<string>;
267 readonly start: Effect.Effect<void>;
268 readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
269 readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
270 readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
271 // Polls desiredRunning + the instance's own ready flag until the
272 // backend reports ready, or the timeout elapses. Returns true on
273 // ready, false on timeout. Used by the WSL backend swap to drive its
274 // rollback path.
275 readonly waitForReady: (timeout: Duration.Duration) => Effect.Effect<boolean>;
276}
277
278// Spec describing one backend instance to spawn. The configResolve
279// effect is awaited each time the instance is (re)started so live
280// settings changes are picked up on the next start cycle. onReady and
281// onShutdown let the primary instance trigger UI side effects (window
282// open, global readiness flag) without coupling the factory to those
283// concerns; other instances pass them as undefined.
284export interface BackendInstanceSpec {
285 readonly id: BackendInstanceId;
286 readonly label: Effect.Effect<string>;
287 // configResolve can now fail with PlatformError because the
288 // bootstrap-token closure inside DesktopBackendConfiguration uses
289 // crypto.randomBytes (Effect 4 beta.73 migration).
290 readonly configResolve: Effect.Effect<DesktopBackendStartConfig, PlatformError.PlatformError>;
291 // Receives the *resolved* httpBaseUrl of the run that just became
292 // ready. The window service uses this to decide what URL to load
293 // (the WSL backend reports its distro IP, the Windows backend reports
294 // 127.0.0.1). Splitting this off from configResolve avoids races
295 // between "fired onReady" and "currentConfig already advanced".
296 readonly onReady?: (httpBaseUrl: URL) => Effect.Effect<void>;
297 readonly onShutdown?: () => Effect.Effect<void>;
298 // Fired once when a fatal or bounded preflight failure has exhausted its
299 // retries. Returns true when the callback changed configuration and the
300 // manager should resolve once more; false stops the failed instance.
301 readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect<boolean>;
302}
303
304interface ActiveBackendRun {
305 readonly id: number;
306 readonly scope: Scope.Closeable;
307 readonly fiber: Option.Option<Fiber.Fiber<void, never>>;
308 readonly pid: Option.Option<number>;
309 readonly exitObserved: boolean;
310 readonly stopRequested: boolean;
311}
312
313interface BackendManagerState {
314 readonly desiredRunning: boolean;
315 readonly ready: boolean;
316 readonly config: Option.Option<DesktopBackendStartConfig>;
317 readonly active: Option.Option<ActiveBackendRun>;
318 readonly restartAttempt: number;
319 // Consecutive bounded/fatal preflight failures, reset on a clean or
320 // unbounded-transient preflight. restartAttempt counts all restarts.
321 readonly preflightFailureAttempt: number;
322 readonly restartFiber: Option.Option<Fiber.Fiber<void, never>>;
323 readonly nextRunId: number;
324}
325
326const initialState: BackendManagerState = {
327 desiredRunning: false,
328 ready: false,
329 config: Option.none(),
330 active: Option.none(),
331 restartAttempt: 0,
332 preflightFailureAttempt: 0,
333 restartFiber: Option.none(),
334 nextRunId: 1,
335};
336
337const activePid = (active: Option.Option<ActiveBackendRun>): Option.Option<number> =>
338 Option.flatMap(active, (run) => run.pid);
339
340const withActiveRun =
341 (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
342 (state: BackendManagerState): BackendManagerState => ({
343 ...state,
344 active: Option.map(state.active, (run) => (run.id === runId ? f(run) : run)),
345 });
346
347const calculateRestartDelay = (attempt: number): Duration.Duration =>
348 Duration.min(Duration.times(INITIAL_RESTART_DELAY, 2 ** attempt), MAX_RESTART_DELAY);
349
350const closeRun = (
351 run: ActiveBackendRun,
352 parentScope: Scope.Scope,
353 options?: { readonly timeout?: Duration.Duration },
354): Effect.Effect<boolean> => {
355 const waitForFiber = Option.match(run.fiber, {
356 onNone: () => Effect.void,
357 onSome: (fiber) => Fiber.await(fiber).pipe(Effect.asVoid),
358 });
359 const close = Scope.close(run.scope, Exit.void).pipe(Effect.andThen(waitForFiber));
360 const timeout = options?.timeout;
361
362 if (!timeout) {
363 return close.pipe(Effect.as(true));
364 }
365
366 return Effect.forkIn(close, parentScope).pipe(
367 Effect.flatMap((closeFiber) =>
368 Fiber.await(closeFiber).pipe(Effect.timeoutOption(timeout), Effect.map(Option.isSome)),
369 ),
370 );
371};
372
373export const waitForHttpReady = (
374 options: BackendProcessContext & { readonly timeout: Duration.Duration },
375): Effect.Effect<void, BackendReadinessTimeoutError, HttpClient.HttpClient> => {
376 const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
377 return waitForHttpReadyShared({
378 baseUrl: options.httpBaseUrl.href,
379 path: BACKEND_READINESS_PATH,
380 timeoutMs: Duration.toMillis(options.timeout),
381 intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
382 probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
383 makeError: ({ cause }) =>
384 new BackendReadinessTimeoutError({
385 executablePath: options.executablePath,
386 entryPath: options.entryPath,
387 cwd: options.cwd,
388 httpBaseUrl: options.httpBaseUrl,
389 readinessUrl,
390 timeoutMs: Duration.toMillis(options.timeout),
391 cause,
392 }),
393 });
394};
395
396function drainBackendOutput(
397 context: BackendProcessContext & { readonly pid: number },
398 streamName: BackendProcessOutputStream,
399 stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
400 onOutput: (
401 streamName: BackendProcessOutputStream,
402 chunk: Uint8Array,
403 ) => Effect.Effect<void, Error>,
404 onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
405): Effect.Effect<void> {
406 return stream.pipe(
407 Stream.mapError(
408 (cause) =>
409 new BackendProcessOutputReadError({
410 ...context,
411 streamName,
412 cause,
413 }),
414 ),
415 Stream.runForEach((chunk) =>
416 onOutput(streamName, chunk).pipe(
417 Effect.mapError(
418 (cause) =>
419 new BackendProcessOutputHandlingError({
420 ...context,
421 streamName,
422 chunkByteLength: chunk.byteLength,
423 cause,
424 }),
425 ),
426 Effect.catchTag("BackendProcessOutputHandlingError", onOutputFailure),
427 ),
428 ),
429 Effect.catchTags({
430 BackendProcessOutputReadError: onOutputFailure,
431 }),
432 );
433}
434
435const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
436const decodeDesktopTelemetryControlLine = Schema.decodeUnknownEffect(
437 Schema.fromJsonString(DesktopTelemetryControlMessage),
438);
439
440export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
441 options: RunBackendProcessOptions,
442): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
443 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
444 const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
445 Effect.mapError(
446 (cause) =>
447 new BackendProcessBootstrapEncodeError({
448 executablePath: options.executablePath,
449 entryPath: options.entryPath,
450 cwd: options.cwd,
451 httpBaseUrl: options.httpBaseUrl,
452 cause,
453 }),
454 ),
455 );
456 const onOutput = options.onOutput ?? (() => Effect.void);
457 const bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));
458 const additionalFds: Record<`fd${number}`, ChildProcess.AdditionalFdConfig> = {};
459 if (options.bootstrapDelivery === "fd3") {
460 additionalFds.fd3 = {
461 type: "input",
462 stream: bootstrapStream,
463 };
464 if (options.bootstrap.desktopTelemetryFd !== undefined) {
465 additionalFds[`fd${options.bootstrap.desktopTelemetryFd}`] = {
466 type: "input",
467 stream: options.desktopTelemetryStream,
468 };
469 }
470 if (options.bootstrap.desktopTelemetryControlFd !== undefined) {
471 additionalFds[`fd${options.bootstrap.desktopTelemetryControlFd}`] = {
472 type: "output",
473 };
474 }
475 }
476 const command = ChildProcess.make(options.executablePath, options.args, {
477 cwd: options.cwd,
478 env: options.env,
479 extendEnv: options.extendEnv,
480 // In Electron main, process.execPath points to the Electron binary.
481 // Run the child in Node mode so this backend process does not become a GUI app instance.
482 stdin: options.bootstrapDelivery === "stdin" ? bootstrapStream : "ignore",
483 stdout: options.captureOutput ? "pipe" : "inherit",
484 stderr: options.captureOutput ? "pipe" : "inherit",
485 killSignal: "SIGTERM",
486 forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
487 // wsl.exe drops additional file descriptors when forwarding to the Linux
488 // side, so the WSL spawn path delivers the bootstrap envelope via stdin
489 // (`--bootstrap-fd 0`) instead.
490 ...(options.bootstrapDelivery === "fd3" ? { additionalFds } : {}),
491 });
492
493 const handle = yield* spawner.spawn(command).pipe(
494 Effect.mapError(
495 (cause) =>
496 new BackendProcessSpawnError({
497 executablePath: options.executablePath,
498 entryPath: options.entryPath,
499 cwd: options.cwd,
500 httpBaseUrl: options.httpBaseUrl,
501 cause,
502 }),
503 ),
504 );
505 const outputFibers: Array<Fiber.Fiber<void, never>> = [];
506
507 yield* options.onStarted?.(handle.pid) ?? Effect.void;
508 if (
509 options.bootstrap.desktopTelemetryControlFd !== undefined &&
510 options.onDesktopTelemetryControl !== undefined
511 ) {
512 const controlFd = options.bootstrap.desktopTelemetryControlFd;
513 const handleControl = options.onDesktopTelemetryControl;
514 yield* handle.getOutputFd(controlFd).pipe(
515 Stream.decodeText(),
516 Stream.splitLines,
517 Stream.filter((line) => line.trim().length > 0),
518 Stream.runForEach((line) =>
519 decodeDesktopTelemetryControlLine(line).pipe(
520 Effect.flatMap(handleControl),
521 Effect.catchCause((cause) =>
522 logBackendProcessWarning("ignored invalid desktop telemetry control message", {
523 fd: controlFd,
524 cause: Cause.pretty(cause),
525 }),
526 ),
527 ),
528 ),
529 Effect.catchCause((cause) =>
530 logBackendProcessWarning("desktop telemetry control stream stopped", {
531 fd: controlFd,
532 cause: Cause.pretty(cause),
533 }),
534 ),
535 Effect.ensuring(
536 handleControl({
537 version: 1,
538 type: "setDiagnosticsDemand",
539 enabled: false,
540 }),
541 ),
542 Effect.forkScoped,
543 );
544 }
545 if (options.captureOutput) {
546 const outputContext = {
547 executablePath: options.executablePath,
548 entryPath: options.entryPath,
549 cwd: options.cwd,
550 httpBaseUrl: options.httpBaseUrl,
551 pid: Number(handle.pid),
552 };
553 const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
554 outputFibers.push(
555 yield* drainBackendOutput(
556 outputContext,
557 "stdout",
558 handle.stdout,
559 onOutput,
560 onOutputFailure,
561 ).pipe(Effect.forkScoped),
562 yield* drainBackendOutput(
563 outputContext,
564 "stderr",
565 handle.stderr,
566 onOutput,
567 onOutputFailure,
568 ).pipe(Effect.forkScoped),
569 );
570 }
571 // Probe readiness in a loop while the backend process is still alive
572 // instead of giving up after the first budget. A slow cold boot (the
573 // WSL bundle loading across /mnt/c, or a first launch right after an
574 // update) can exceed the initial readiness budget while the backend is
575 // about to come up moments later; a one-shot probe left the app stuck
576 // on "Connecting to WSL…" forever even though the backend kept running
577 // and became healthy. Each round gets a fresh budget, and the forked
578 // loop is torn down with the run scope once the child exits.
579 const probeReadiness = Effect.fn("desktop.backendProcess.probeReadiness")(() =>
580 waitForHttpReady({
581 executablePath: options.executablePath,
582 entryPath: options.entryPath,
583 cwd: options.cwd,
584 httpBaseUrl: options.httpBaseUrl,
585 timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
586 }).pipe(
587 Effect.flatMap(() => options.onReady?.() ?? Effect.void),
588 Effect.as(true),
589 Effect.catchTags({
590 BackendReadinessTimeoutError: (error) =>
591 (options.onReadinessFailure?.(error) ?? Effect.void).pipe(Effect.as(false)),
592 }),
593 ),
594 );
595
596 yield* probeReadiness().pipe(Effect.repeat({ while: (ready) => !ready }), Effect.forkScoped);
597
598 const exit = yield* handle.exitCode.pipe(
599 Effect.mapError(
600 (cause) =>
601 new BackendProcessExitStatusError({
602 executablePath: options.executablePath,
603 entryPath: options.entryPath,
604 cwd: options.cwd,
605 httpBaseUrl: options.httpBaseUrl,
606 pid: Number(handle.pid),
607 cause,
608 }),
609 ),
610 Effect.exit,
611 );
612 yield* options.onExitObserved?.() ?? Effect.void;
613 yield* Effect.forEach(outputFibers, Fiber.await, {
614 concurrency: "unbounded",
615 discard: true,
616 }).pipe(
617 Effect.timeout(options.outputDrainTimeout ?? DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT),
618 Effect.ignore,
619 );
620 if (Exit.isFailure(exit)) {
621 return yield* Effect.failCause(exit.cause);
622 }
623 const exitCode = exit.value;
624 return {
625 code: Option.some(exitCode),
626 reason: `code=${exitCode}`,
627 } satisfies BackendProcessExit;
628});
629
630// Factory for one pooled backend instance. The returned instance owns
631// its own state Ref, mutex, restart loop, and active child process;
632// nothing is shared between instances created from separate
633// makeBackendInstance calls. The instance shuts down automatically when
634// the calling scope closes (typically the application scope).
635export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
636 spec: BackendInstanceSpec,
637): Effect.fn.Return<
638 DesktopBackendInstance,
639 never,
640 | FileSystem.FileSystem
641 | ChildProcessSpawner.ChildProcessSpawner
642 | HttpClient.HttpClient
643 | DesktopObservability.DesktopBackendOutputLogFactory
644 | DesktopTelemetryPublisher.DesktopTelemetryPublisher
645 | DesktopWslEnvironment.DesktopWslEnvironment
646 | Scope.Scope
647> {
648 const parentScope = yield* Scope.Scope;
649 const fileSystem = yield* FileSystem.FileSystem;
650 const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
651 const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
652 const desktopTelemetryPublisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
653 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
654 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
655 const httpClient = yield* HttpClient.HttpClient;
656 const state = yield* Ref.make(initialState);
657 const mutex = yield* Semaphore.make(1);
658
659 const { logWarning: logInstanceWarning, logError: logInstanceError } =
660 DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`);
661
662 const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
663 Ref.update(state, withActiveRun(runId, f));
664
665 const snapshot = Ref.get(state).pipe(
666 Effect.map((current): DesktopBackendSnapshot => ({
667 desiredRunning: current.desiredRunning,
668 ready: current.ready,
669 activePid: activePid(current.active),
670 restartAttempt: current.restartAttempt,
671 restartScheduled: Option.isSome(current.restartFiber),
672 })),
673 );
674 const currentConfig = Ref.get(state).pipe(Effect.map((current) => current.config));
675
676 const cancelRestart = Effect.gen(function* () {
677 const restartFiber = yield* Ref.modify(state, (current) => [
678 current.restartFiber,
679 {
680 ...current,
681 restartFiber: Option.none(),
682 },
683 ]);
684
685 yield* Option.match(restartFiber, {
686 onNone: () => Effect.void,
687 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
688 });
689 });
690
691 const start: Effect.Effect<void> = Effect.suspend(() =>
692 mutex.withPermits(1)(
693 Effect.gen(function* () {
694 const current = yield* Ref.get(state);
695 if (Option.isSome(current.active)) {
696 if (!current.desiredRunning) {
697 yield* Ref.update(state, (latest) => ({
698 ...latest,
699 desiredRunning: true,
700 }));
701 }
702 return;
703 }
704
705 if (current.ready) {
706 yield* spec.onShutdown?.() ?? Effect.void;
707 yield* Ref.update(state, (latest) =>
708 latest.ready ? { ...latest, ready: false } : latest,
709 );
710 }
711 const config = yield* spec.configResolve.pipe(
712 Effect.tapError((error) =>
713 logInstanceError("failed to generate desktop backend configuration", {
714 cause: error.message,
715 }),
716 ),
717 Effect.option,
718 );
719 if (Option.isNone(config)) {
720 if (current.desiredRunning) {
721 yield* scheduleRestart("failed to generate desktop backend configuration");
722 }
723 return;
724 }
725 const entryExists = yield* fileSystem
726 .exists(config.value.entryPath)
727 .pipe(Effect.orElseSucceed(() => false));
728
729 const resetFatalPreflightCounter =
730 !current.desiredRunning && current.preflightFailureAttempt > 0;
731 yield* cancelRestart;
732 yield* Ref.update(state, (latest) => ({
733 ...latest,
734 desiredRunning: true,
735 ready: false,
736 config: Option.some(config.value),
737 preflightFailureAttempt: resetFatalPreflightCounter ? 0 : latest.preflightFailureAttempt,
738 }));
739
740 const preflightFailure = config.value.preflightFailure;
741 if (Option.isSome(preflightFailure)) {
742 const { reason, fatal, retryLimit } = preflightFailure.value;
743 if (!fatal && retryLimit === undefined) {
744 // Transient (WSL cold-starting, wslpath while the VM boots). Keep
745 // retrying so the backend self-heals once WSL is ready. Reset a
746 // prior bounded/fatal streak because this is a different failure.
747 yield* Ref.update(state, (latest) =>
748 latest.preflightFailureAttempt === 0
749 ? latest
750 : { ...latest, preflightFailureAttempt: 0 },
751 );
752 yield* scheduleRestart(reason);
753 return;
754 }
755 const attemptLimit = retryLimit ?? MAX_PREFLIGHT_FAILURE_ATTEMPTS;
756 const attempt = yield* Ref.modify(state, (latest) => {
757 const next = latest.preflightFailureAttempt + 1;
758 return [next, { ...latest, preflightFailureAttempt: next }] as const;
759 });
760 if (attempt > attemptLimit) {
761 // We already surfaced and asked for the Windows fallback, yet we're
762 // still resolving the WSL primary — the fallback didn't take (e.g.
763 // the settings write failed). Stop rather than loop forever.
764 yield* logInstanceError("backend preflight still failing after fallback; stopping", {
765 reason,
766 attempt,
767 });
768 yield* Ref.update(state, (latest) => ({
769 ...latest,
770 desiredRunning: false,
771 ready: false,
772 }));
773 return;
774 }
775 if (attempt === attemptLimit) {
776 // Fatal/bounded and out of retries. Surface the reason (onPreflightFailed,
777 // on the primary, shows a dialog and persists Windows mode), then
778 // schedule one more restart so the next resolve picks up the Windows
779 // primary and a window can open.
780 yield* logInstanceError(
781 "backend preflight failed repeatedly; surfacing and falling back",
782 { reason, attempt },
783 );
784 const shouldRestart = yield* (
785 spec.onPreflightFailed?.(preflightFailure.value) ?? Effect.succeed(false)
786 );
787 if (shouldRestart) {
788 yield* scheduleRestart(reason);
789 } else {
790 yield* Ref.update(state, (latest) => ({
791 ...latest,
792 desiredRunning: false,
793 ready: false,
794 }));
795 }
796 return;
797 }
798 yield* scheduleRestart(reason);
799 return;
800 }
801 // Clean preflight — reset the fatal counter so a later failure gets a
802 // fresh allowance.
803 yield* Ref.update(state, (latest) =>
804 latest.preflightFailureAttempt === 0 ? latest : { ...latest, preflightFailureAttempt: 0 },
805 );
806
807 if (!entryExists) {
808 yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
809 return;
810 }
811
812 const runScope = yield* Scope.make("sequential");
813 const runId = yield* Ref.modify(state, (latest) => [
814 latest.nextRunId,
815 {
816 ...latest,
817 active: Option.some({
818 id: latest.nextRunId,
819 scope: runScope,
820 fiber: Option.none(),
821 pid: Option.none(),
822 exitObserved: false,
823 stopRequested: false,
824 } satisfies ActiveBackendRun),
825 nextRunId: latest.nextRunId + 1,
826 },
827 ]);
828
829 const finalizeRun = Effect.fn("desktop.backendInstance.finalizeRun")(function* (
830 reason: string,
831 ) {
832 yield* mutex.withPermits(1)(
833 Effect.gen(function* () {
834 const { isCurrentRun, nextState, pid, exitObserved, stopRequested, wasReady } =
835 yield* Ref.modify(
836 state,
837 (
838 latest,
839 ): readonly [
840 {
841 readonly isCurrentRun: boolean;
842 readonly nextState: BackendManagerState;
843 readonly pid: Option.Option<number>;
844 readonly exitObserved: boolean;
845 readonly stopRequested: boolean;
846 readonly wasReady: boolean;
847 },
848 BackendManagerState,
849 ] => {
850 const currentRun = Option.getOrUndefined(latest.active);
851 if (currentRun?.id !== runId) {
852 return [
853 {
854 isCurrentRun: false,
855 nextState: latest,
856 pid: Option.none<number>(),
857 exitObserved: false,
858 stopRequested: false,
859 wasReady: false,
860 },
861 latest,
862 ] as const;
863 }
864
865 const next = {
866 ...latest,
867 active: Option.none<ActiveBackendRun>(),
868 ready: false,
869 };
870 return [
871 {
872 isCurrentRun: true,
873 nextState: next,
874 pid: currentRun.pid,
875 exitObserved: currentRun.exitObserved,
876 stopRequested: currentRun.stopRequested,
877 wasReady: latest.ready,
878 },
879 next,
880 ] as const;
881 },
882 );
883
884 if (isCurrentRun) {
885 yield* desktopTelemetryPublisher.removeControlSource(spec.id);
886 if (Option.isSome(pid)) {
887 if (exitObserved && !stopRequested) {
888 yield* backendOutputLog.persistFailure({
889 details: `pid=${pid.value} ${reason}`,
890 });
891 } else {
892 yield* backendOutputLog.discardSession;
893 }
894 }
895 if (wasReady) {
896 yield* spec.onShutdown?.() ?? Effect.void;
897 }
898 }
899
900 if (isCurrentRun && nextState.desiredRunning) {
901 yield* scheduleRestart(reason);
902 }
903 }),
904 );
905 });
906
907 const program = runBackendProcess({
908 ...config.value,
909 desktopTelemetryStream: desktopTelemetryPublisher.encoded,
910 onDesktopTelemetryControl: (message) =>
911 desktopTelemetryPublisher.handleControlForSource(spec.id, message),
912 onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
913 yield* updateActiveRun(runId, (run) => ({
914 ...run,
915 pid: Option.some(pid),
916 }));
917 yield* backendOutputLog.beginSession({
918 details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
919 });
920 }),
921 onExitObserved: () =>
922 updateActiveRun(runId, (run) => ({
923 ...run,
924 exitObserved: true,
925 })),
926 onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
927 const isCurrentRun = yield* Ref.modify(state, (latest) => {
928 const activeRun = Option.getOrUndefined(latest.active);
929 if (activeRun?.id !== runId) {
930 return [false, latest] as const;
931 }
932
933 return [
934 true,
935 {
936 ...latest,
937 restartAttempt: 0,
938 ready: true,
939 },
940 ] as const;
941 });
942 if (!isCurrentRun) {
943 return;
944 }
945
946 yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
947 if (
948 config.value.runningDistro !== undefined &&
949 config.value.wslRuntimeId !== undefined
950 ) {
951 yield* wslEnvironment.pruneRuntimes(
952 config.value.runningDistro,
953 config.value.wslRuntimeId,
954 );
955 }
956 }),
957 onReadinessFailure: Effect.fn("desktop.backendInstance.onReadinessFailure")(
958 function* (error) {
959 yield* logInstanceWarning("backend readiness check failed during bootstrap", {
960 error: error.message,
961 });
962 yield* backendOutputLog.persistFailureSnapshot({
963 details: error.message,
964 });
965 },
966 ),
967 onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
968 }).pipe(
969 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
970 Effect.provideService(HttpClient.HttpClient, httpClient),
971 Scope.provide(runScope),
972 Effect.matchEffect({
973 onFailure: (error) => finalizeRun(error.message),
974 onSuccess: (exit) => finalizeRun(exit.reason),
975 }),
976 Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
977 );
978
979 const fiber = yield* Effect.forkIn(program, parentScope);
980 yield* updateActiveRun(runId, (run) => ({
981 ...run,
982 fiber: Option.some(fiber),
983 }));
984 }),
985 ),
986 ).pipe(Effect.withSpan("desktop.backendInstance.start", { attributes: { id: spec.id } }));
987
988 const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* (
989 reason: string,
990 ) {
991 const scheduled = yield* Ref.modify(state, (latest) => {
992 if (!latest.desiredRunning || Option.isSome(latest.restartFiber)) {
993 return [Option.none<Duration.Duration>(), latest] as const;
994 }
995
996 const delay = calculateRestartDelay(latest.restartAttempt);
997 return [
998 Option.some(delay),
999 {
1000 ...latest,
1001 restartAttempt: latest.restartAttempt + 1,
1002 },
1003 ] as const;
1004 });
1005
1006 yield* Option.match(scheduled, {
1007 onNone: () => Effect.void,
1008 onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* (delay) {
1009 yield* logInstanceError("backend exited unexpectedly; restart scheduled", {
1010 reason,
1011 delayMs: Duration.toMillis(delay),
1012 });
1013 const restartFiber = yield* Effect.forkIn(
1014 Effect.sleep(delay).pipe(
1015 Effect.andThen(
1016 Ref.modify(state, (latest) => {
1017 const shouldRestart = latest.desiredRunning;
1018 return [
1019 shouldRestart,
1020 {
1021 ...latest,
1022 restartFiber: Option.none(),
1023 },
1024 ] as const;
1025 }),
1026 ),
1027 Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
1028 Effect.catchCause((cause) =>
1029 logInstanceError("desktop backend restart fiber failed", {
1030 cause: Cause.pretty(cause),
1031 }),
1032 ),
1033 ),
1034 parentScope,
1035 );
1036 yield* Ref.update(state, (latest) =>
1037 Option.isNone(latest.restartFiber)
1038 ? {
1039 ...latest,
1040 restartFiber: Option.some(restartFiber),
1041 }
1042 : latest,
1043 );
1044 }),
1045 });
1046 });
1047
1048 const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
1049 readonly timeout?: Duration.Duration;
1050 }) {
1051 const { active, restartFiber, notifyShutdown } = yield* mutex.withPermits(1)(
1052 Effect.gen(function* () {
1053 const result = yield* Ref.modify(state, (latest) => {
1054 const active = Option.map(latest.active, (run) =>
1055 run.exitObserved ? run : { ...run, stopRequested: true },
1056 );
1057 return [
1058 {
1059 active,
1060 restartFiber: latest.restartFiber,
1061 notifyShutdown: latest.ready,
1062 },
1063 {
1064 ...latest,
1065 desiredRunning: false,
1066 ready: false,
1067 active,
1068 restartFiber: Option.none<Fiber.Fiber<void, never>>(),
1069 },
1070 ] as const;
1071 });
1072 return result;
1073 }),
1074 );
1075
1076 if (notifyShutdown) {
1077 yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
1078 }
1079 yield* Option.match(restartFiber, {
1080 onNone: () => Effect.void,
1081 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
1082 });
1083 yield* Option.match(active, {
1084 onNone: () => Effect.void,
1085 onSome: (run) =>
1086 Effect.gen(function* () {
1087 const closed = yield* closeRun(run, parentScope, options);
1088 if (!closed) {
1089 return;
1090 }
1091 const cleanup = yield* mutex.withPermits(1)(
1092 Ref.modify(
1093 state,
1094 (
1095 latest,
1096 ): readonly [
1097 {
1098 readonly needsCleanup: boolean;
1099 readonly shouldStart: boolean;
1100 },
1101 BackendManagerState,
1102 ] => {
1103 const current = Option.getOrUndefined(latest.active);
1104 if (current?.id !== run.id) {
1105 return [
1106 {
1107 needsCleanup: false,
1108 shouldStart:
1109 latest.desiredRunning &&
1110 Option.isNone(latest.active) &&
1111 Option.isNone(latest.restartFiber),
1112 },
1113 latest,
1114 ];
1115 }
1116 return [
1117 {
1118 needsCleanup: true,
1119 shouldStart: latest.desiredRunning,
1120 },
1121 {
1122 ...latest,
1123 active: Option.none<ActiveBackendRun>(),
1124 },
1125 ];
1126 },
1127 ),
1128 );
1129 if (cleanup.needsCleanup) {
1130 yield* desktopTelemetryPublisher.removeControlSource(spec.id);
1131 yield* backendOutputLog.discardSession;
1132 }
1133 if (cleanup.shouldStart) {
1134 yield* start;
1135 }
1136 }),
1137 });
1138 });
1139
1140 const waitForReady = (timeout: Duration.Duration): Effect.Effect<boolean> =>
1141 Effect.gen(function* () {
1142 const current = yield* Ref.get(state);
1143 // Return false early if an external `stop()` flipped desiredRunning off
1144 // — no point polling for a backend that is being torn down.
1145 if (!current.desiredRunning) return { done: true, ready: false };
1146 return current.ready ? { done: true, ready: true } : { done: false, ready: false };
1147 }).pipe(
1148 Effect.repeat({
1149 until: (status) => status.done,
1150 schedule: Schedule.spaced(Duration.millis(100)),
1151 }),
1152 Effect.map((status) => status.ready),
1153 Effect.timeoutOption(timeout),
1154 Effect.map(Option.getOrElse(() => false)),
1155 );
1156
1157 yield* Effect.addFinalizer(() => stop());
1158
1159 return {
1160 id: spec.id,
1161 label: spec.label,
1162 start,
1163 stop,
1164 currentConfig,
1165 snapshot,
1166 waitForReady,
1167 } satisfies DesktopBackendInstance;
1168});