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