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