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