Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopBackendManager.ts

819 lines31.0 KB

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 Result from "effect/Result";
37import * as Schedule from "effect/Schedule";
38import * as Schema from "effect/Schema";
39import * as Semaphore from "effect/Semaphore";
40import * as Scope from "effect/Scope";
41import * as Stream from "effect/Stream";
42import { HttpClient } from "effect/unstable/http";
43import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
44​
45import {
46 DesktopBackendBootstrap,
47 type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
48 PRIMARY_LOCAL_ENVIRONMENT_ID,
49} from "@v12/contracts";
50import { waitForHttpReady as waitForHttpReadyShared } from "@v12/shared/httpReadiness";
51​
52import * as DesktopObservability from "../app/DesktopObservability.ts";
53​
54const INITIAL_RESTART_DELAY = Duration.millis(500);
55const MAX_RESTART_DELAY = Duration.seconds(10);
56// After this many consecutive fatal preflight failures, stop the silent
57// restart loop and surface the reason via onPreflightFailed. Transient
58// failures may instead provide their own larger retryLimit when they should
59// self-heal for a while but must not leave the app connecting forever.
60const MAX_PREFLIGHT_FAILURE_ATTEMPTS = 5;
61const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
62const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
63const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
64const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(2);
65const BACKEND_READINESS_PATH = "/.well-known/v12/environment";
66​
67type BackendProcessLayerServices = ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient;
68​
69type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
70​
71export type BackendProcessOutputStream = "stdout" | "stderr";
72​
73export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
74​
75export interface DesktopBackendStartConfig {
76 readonly executablePath: string;
77 readonly args: ReadonlyArray<string>;
78 readonly entryPath: string;
79 readonly cwd: string;
80 readonly env: Record<string, string | undefined>;
81 // When true the spawner merges the desktop process.env on top of `env`;
82 // when false `env` is passed verbatim. WSL mode opts out so a leaking
83 // V12_HOME can't pin the WSL backend to /mnt/c/...\.v12.
84 readonly extendEnv: boolean;
85 readonly bootstrap: DesktopBackendBootstrapValue;
86 readonly bootstrapDelivery: DesktopBackendBootstrapDelivery;
87 readonly httpBaseUrl: URL;
88 readonly captureOutput: boolean;
89 readonly preflightFailure: Option.Option<PreflightFailure>;
90 // Present for a WSL run after the configured/default distro has been
91 // resolved to the concrete distro passed to wsl.exe.
92 readonly runningDistro?: string;
94​
95// A preflight failure records whether it is fatal. Transient failures (WSL
96// cold-starting, wslpath while the VM boots) keep retrying so the backend can
97// self-heal; fatal ones (no node, wrong version, missing build tools) are
98// surfaced via onPreflightFailed and stop the restart loop after
99// MAX_PREFLIGHT_FAILURE_ATTEMPTS.
100export interface PreflightFailure {
101 readonly reason: string;
102 readonly fatal: boolean;
103 readonly retryLimit?: number;
105​
106interface BackendProcessExit {
107 readonly code: Option.Option<number>;
108 readonly reason: string;
109 readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
111​
112export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
113 "BackendTimeoutError",
114 {
115 url: Schema.instanceOf(URL),
116 },
117) {
118 override get message() {
119 return `Timed out waiting for backend readiness at ${this.url.href}.`;
120 }
122​
123class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
124 "BackendProcessBootstrapEncodeError",
125 {
126 entryPath: Schema.String,
127 cause: Schema.Defect(),
128 },
129) {
130 override get message() {
131 return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
132 }
134​
135class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
136 "BackendProcessSpawnError",
137 {
138 executablePath: Schema.String,
139 cause: Schema.Defect(),
140 },
141) {
142 override get message() {
143 return `Failed to spawn the desktop backend process at ${this.executablePath}.`;
144 }
146​
147type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
148​
149interface RunBackendProcessOptions extends DesktopBackendStartConfig {
150 readonly readinessTimeout?: Duration.Duration;
151 readonly onStarted?: (pid: number) => Effect.Effect<void>;
152 readonly onReady?: () => Effect.Effect<void>;
153 readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
154 readonly onOutput?: (
155 streamName: BackendProcessOutputStream,
156 chunk: Uint8Array,
157 ) => Effect.Effect<void>;
159​
160export interface DesktopBackendSnapshot {
161 readonly desiredRunning: boolean;
162 readonly ready: boolean;
163 readonly activePid: Option.Option<number>;
164 readonly restartAttempt: number;
165 readonly restartScheduled: boolean;
167​
168// Opaque identifier for one backend process inside the pool. Today only
169// PRIMARY_INSTANCE_ID is registered. Follow-up commits add WSL distros
170// under ids derived from the distro name (e.g. "wsl:ubuntu"). Eventually
171// these map 1:1 with environment ids on the frontend; keeping them
172// desktop-local for now avoids leaking the contracts dependency.
173export type BackendInstanceId = string & Brand.Brand<"BackendInstanceId">;
174export const BackendInstanceId = Brand.nominal<BackendInstanceId>();
175​
176export const PRIMARY_INSTANCE_ID: BackendInstanceId = BackendInstanceId(
177 PRIMARY_LOCAL_ENVIRONMENT_ID,
178);
179​
180// One pooled backend instance. Same lifecycle surface as the legacy
181// `DesktopBackendManagerShape`; the id and label give the pool registry
182// + UI something to route on.
183export interface DesktopBackendInstance {
184 readonly id: BackendInstanceId;
185 readonly label: Effect.Effect<string>;
186 readonly start: Effect.Effect<void>;
187 readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
188 readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
189 readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
190 // Polls desiredRunning + the instance's own ready flag until the
191 // backend reports ready, or the timeout elapses. Returns true on
192 // ready, false on timeout. Used by the WSL backend swap to drive its
193 // rollback path.
194 readonly waitForReady: (timeout: Duration.Duration) => Effect.Effect<boolean>;
196​
197// Spec describing one backend instance to spawn. The configResolve
198// effect is awaited each time the instance is (re)started so live
199// settings changes are picked up on the next start cycle. onReady and
200// onShutdown let the primary instance trigger UI side effects (window
201// open, global readiness flag) without coupling the factory to those
202// concerns; other instances pass them as undefined.
203export interface BackendInstanceSpec {
204 readonly id: BackendInstanceId;
205 readonly label: Effect.Effect<string>;
206 // configResolve can now fail with PlatformError because the
207 // bootstrap-token closure inside DesktopBackendConfiguration uses
208 // crypto.randomBytes (Effect 4 beta.73 migration).
209 readonly configResolve: Effect.Effect<DesktopBackendStartConfig, PlatformError.PlatformError>;
210 // Receives the *resolved* httpBaseUrl of the run that just became
211 // ready. The window service uses this to decide what URL to load
212 // (the WSL backend reports its distro IP, the Windows backend reports
213 // 127.0.0.1). Splitting this off from configResolve avoids races
214 // between "fired onReady" and "currentConfig already advanced".
215 readonly onReady?: (httpBaseUrl: URL) => Effect.Effect<void>;
216 readonly onShutdown?: () => Effect.Effect<void>;
217 // Fired once when a fatal or bounded preflight failure has exhausted its
218 // retries. Returns true when the callback changed configuration and the
219 // manager should resolve once more; false stops the failed instance.
220 readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect<boolean>;
222​
223interface ActiveBackendRun {
224 readonly id: number;
225 readonly scope: Scope.Closeable;
226 readonly fiber: Option.Option<Fiber.Fiber<void, never>>;
227 readonly pid: Option.Option<number>;
229​
230interface BackendManagerState {
231 readonly desiredRunning: boolean;
232 readonly ready: boolean;
233 readonly config: Option.Option<DesktopBackendStartConfig>;
234 readonly active: Option.Option<ActiveBackendRun>;
235 readonly restartAttempt: number;
236 // Consecutive bounded/fatal preflight failures, reset on a clean or
237 // unbounded-transient preflight. restartAttempt counts all restarts.
238 readonly preflightFailureAttempt: number;
239 readonly restartFiber: Option.Option<Fiber.Fiber<void, never>>;
240 readonly nextRunId: number;
242​
243const initialState: BackendManagerState = {
244 desiredRunning: false,
245 ready: false,
246 config: Option.none(),
247 active: Option.none(),
248 restartAttempt: 0,
249 preflightFailureAttempt: 0,
250 restartFiber: Option.none(),
251 nextRunId: 1,
252};
253​
254const activePid = (active: Option.Option<ActiveBackendRun>): Option.Option<number> =>
255 Option.flatMap(active, (run) => run.pid);
256​
257const withActiveRun =
258 (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
259 (state: BackendManagerState): BackendManagerState => ({
260 ...state,
261 active: Option.map(state.active, (run) => (run.id === runId ? f(run) : run)),
262 });
263​
264const calculateRestartDelay = (attempt: number): Duration.Duration =>
265 Duration.min(Duration.times(INITIAL_RESTART_DELAY, 2 ** attempt), MAX_RESTART_DELAY);
266​
267const closeRun = (
268 run: ActiveBackendRun,
269 options?: { readonly timeout?: Duration.Duration },
270): Effect.Effect<void> => {
271 const waitForFiber = Option.match(run.fiber, {
272 onNone: () => Effect.void,
273 onSome: (fiber) => Fiber.await(fiber).pipe(Effect.asVoid),
274 });
275 const close = Scope.close(run.scope, Exit.void).pipe(Effect.andThen(waitForFiber));
276​
277 return (
278 options?.timeout ? close.pipe(Effect.timeoutOption(options.timeout), Effect.asVoid) : close
279 ).pipe(Effect.ignore);
280};
281​
282const waitForHttpReady = (
283 baseUrl: URL,
284 timeout: Duration.Duration,
285): Effect.Effect<void, BackendTimeoutError, HttpClient.HttpClient> => {
286 const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
287 return waitForHttpReadyShared({
288 baseUrl: baseUrl.href,
289 path: BACKEND_READINESS_PATH,
290 timeoutMs: Duration.toMillis(timeout),
291 intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
292 probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
293 makeError: () => new BackendTimeoutError({ url: readinessUrl }),
294 });
295};
296​
297function describeProcessExit(
298 result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
299): BackendProcessExit {
300 if (Result.isSuccess(result)) {
301 return {
302 code: Option.some(result.success),
303 reason: `code=${result.success}`,
304 result,
305 };
306 }
307​
308 return {
309 code: Option.none(),
310 reason: result.failure.message,
311 result,
312 };
314​
315function drainBackendOutput(
316 streamName: BackendProcessOutputStream,
317 stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
318 onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
319): Effect.Effect<void> {
320 return stream.pipe(
321 Stream.runForEach((chunk) => onOutput(streamName, chunk)),
322 Effect.ignore,
323 );
325​
326const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
327​
328const runBackendProcess = Effect.fn("runBackendProcess")(function* (
329 options: RunBackendProcessOptions,
330): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
331 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
332 const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
333 Effect.mapError(
334 (cause) => new BackendProcessBootstrapEncodeError({ entryPath: options.entryPath, cause }),
335 ),
336 );
337 const onOutput = options.onOutput ?? (() => Effect.void);
338 const bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));
339 const command = ChildProcess.make(options.executablePath, options.args, {
340 cwd: options.cwd,
341 env: options.env,
342 extendEnv: options.extendEnv,
343 // In Electron main, process.execPath points to the Electron binary.
344 // Run the child in Node mode so this backend process does not become a GUI app instance.
345 stdin: options.bootstrapDelivery === "stdin" ? bootstrapStream : "ignore",
346 stdout: options.captureOutput ? "pipe" : "inherit",
347 stderr: options.captureOutput ? "pipe" : "inherit",
348 killSignal: "SIGTERM",
349 forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
350 // wsl.exe drops additional file descriptors when forwarding to the Linux
351 // side, so the WSL spawn path delivers the bootstrap envelope via stdin
352 // (`--bootstrap-fd 0`) instead.
353 ...(options.bootstrapDelivery === "fd3"
354 ? { additionalFds: { fd3: { type: "input" as const, stream: bootstrapStream } } }
355 : {}),
356 });
357​
358 const handle = yield* spawner
359 .spawn(command)
360 .pipe(
361 Effect.mapError(
362 (cause) => new BackendProcessSpawnError({ executablePath: options.executablePath, cause }),
363 ),
364 );
365​
366 yield* options.onStarted?.(handle.pid) ?? Effect.void;
367 if (options.captureOutput) {
368 yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
369 yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
370 }
371 yield* waitForHttpReady(
372 options.httpBaseUrl,
373 options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
374 ).pipe(
375 Effect.tap(() => options.onReady?.() ?? Effect.void),
376 Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
377 Effect.forkScoped,
378 );
379​
380 return describeProcessExit(yield* Effect.result(handle.exitCode));
381});
382​
383// Factory for one pooled backend instance. The returned instance owns
384// its own state Ref, mutex, restart loop, and active child process;
385// nothing is shared between instances created from separate
386// makeBackendInstance calls. The instance shuts down automatically when
387// the calling scope closes (typically the application scope).
388export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
389 spec: BackendInstanceSpec,
390): Effect.fn.Return<
391 DesktopBackendInstance,
392 never,
393 | FileSystem.FileSystem
394 | ChildProcessSpawner.ChildProcessSpawner
395 | HttpClient.HttpClient
396 | DesktopObservability.DesktopBackendOutputLogFactory
397 | Scope.Scope
398> {
399 const parentScope = yield* Scope.Scope;
400 const fileSystem = yield* FileSystem.FileSystem;
401 const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
402 const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
403 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
404 const httpClient = yield* HttpClient.HttpClient;
405 const state = yield* Ref.make(initialState);
406 const mutex = yield* Semaphore.make(1);
407​
408 const { logWarning: logInstanceWarning, logError: logInstanceError } =
409 DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`);
410​
411 const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
412 Ref.update(state, withActiveRun(runId, f));
413​
414 const snapshot = Ref.get(state).pipe(
415 Effect.map(
416 (current): DesktopBackendSnapshot => ({
417 desiredRunning: current.desiredRunning,
418 ready: current.ready,
419 activePid: activePid(current.active),
420 restartAttempt: current.restartAttempt,
421 restartScheduled: Option.isSome(current.restartFiber),
422 }),
423 ),
424 );
425 const currentConfig = Ref.get(state).pipe(Effect.map((current) => current.config));
426​
427 const cancelRestart = Effect.gen(function* () {
428 const restartFiber = yield* Ref.modify(state, (current) => [
429 current.restartFiber,
430 {
431 ...current,
432 restartFiber: Option.none(),
433 },
434 ]);
435​
436 yield* Option.match(restartFiber, {
437 onNone: () => Effect.void,
438 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
439 });
440 });
441​
442 const start: Effect.Effect<void> = Effect.suspend(() =>
443 mutex.withPermits(1)(
444 Effect.gen(function* () {
445 const current = yield* Ref.get(state);
446 if (Option.isSome(current.active)) {
447 return;
448 }
449​
450 if (current.ready) {
451 yield* spec.onShutdown?.() ?? Effect.void;
452 yield* Ref.update(state, (latest) =>
453 latest.ready ? { ...latest, ready: false } : latest,
454 );
455 }
456 const config = yield* spec.configResolve.pipe(
457 Effect.tapError((error) =>
458 logInstanceError("failed to generate desktop backend configuration", {
459 cause: error.message,
460 }),
461 ),
462 Effect.option,
463 );
464 if (Option.isNone(config)) {
465 return;
466 }
467 const entryExists = yield* fileSystem
468 .exists(config.value.entryPath)
469 .pipe(Effect.orElseSucceed(() => false));
470​
471 const resetFatalPreflightCounter =
472 !current.desiredRunning && current.preflightFailureAttempt > 0;
473 yield* cancelRestart;
474 yield* Ref.update(state, (latest) => ({
475 ...latest,
476 desiredRunning: true,
477 ready: false,
478 config: Option.some(config.value),
479 preflightFailureAttempt: resetFatalPreflightCounter ? 0 : latest.preflightFailureAttempt,
480 }));
481​
482 const preflightFailure = config.value.preflightFailure;
483 if (Option.isSome(preflightFailure)) {
484 const { reason, fatal, retryLimit } = preflightFailure.value;
485 if (!fatal && retryLimit === undefined) {
486 // Transient (WSL cold-starting, wslpath while the VM boots). Keep
487 // retrying so the backend self-heals once WSL is ready. Reset a
488 // prior bounded/fatal streak because this is a different failure.
489 yield* Ref.update(state, (latest) =>
490 latest.preflightFailureAttempt === 0
491 ? latest
492 : { ...latest, preflightFailureAttempt: 0 },
493 );
494 yield* scheduleRestart(reason);
495 return;
496 }
497 const attemptLimit = retryLimit ?? MAX_PREFLIGHT_FAILURE_ATTEMPTS;
498 const attempt = yield* Ref.modify(state, (latest) => {
499 const next = latest.preflightFailureAttempt + 1;
500 return [next, { ...latest, preflightFailureAttempt: next }] as const;
501 });
502 if (attempt > attemptLimit) {
503 // We already surfaced and asked for the Windows fallback, yet we're
504 // still resolving the WSL primary — the fallback didn't take (e.g.
505 // the settings write failed). Stop rather than loop forever.
506 yield* logInstanceError("backend preflight still failing after fallback; stopping", {
507 reason,
508 attempt,
509 });
510 yield* Ref.update(state, (latest) => ({
511 ...latest,
512 desiredRunning: false,
513 ready: false,
514 }));
515 return;
516 }
517 if (attempt === attemptLimit) {
518 // Fatal/bounded and out of retries. Surface the reason (onPreflightFailed,
519 // on the primary, shows a dialog and persists Windows mode), then
520 // schedule one more restart so the next resolve picks up the Windows
521 // primary and a window can open.
522 yield* logInstanceError(
523 "backend preflight failed repeatedly; surfacing and falling back",
524 { reason, attempt },
525 );
526 const shouldRestart = yield* (
527 spec.onPreflightFailed?.(preflightFailure.value) ?? Effect.succeed(false)
528 );
529 if (shouldRestart) {
530 yield* scheduleRestart(reason);
531 } else {
532 yield* Ref.update(state, (latest) => ({
533 ...latest,
534 desiredRunning: false,
535 ready: false,
536 }));
537 }
538 return;
539 }
540 yield* scheduleRestart(reason);
541 return;
542 }
543 // Clean preflight — reset the fatal counter so a later failure gets a
544 // fresh allowance.
545 yield* Ref.update(state, (latest) =>
546 latest.preflightFailureAttempt === 0 ? latest : { ...latest, preflightFailureAttempt: 0 },
547 );
548​
549 if (!entryExists) {
550 yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
551 return;
552 }
553​
554 const runScope = yield* Scope.make("sequential");
555 const runId = yield* Ref.modify(state, (latest) => [
556 latest.nextRunId,
557 {
558 ...latest,
559 active: Option.some({
560 id: latest.nextRunId,
561 scope: runScope,
562 fiber: Option.none(),
563 pid: Option.none(),
564 } satisfies ActiveBackendRun),
565 nextRunId: latest.nextRunId + 1,
566 },
567 ]);
568​
569 const finalizeRun = Effect.fn("desktop.backendInstance.finalizeRun")(function* (
570 reason: string,
571 ) {
572 yield* mutex.withPermits(1)(
573 Effect.gen(function* () {
574 const { isCurrentRun, nextState, pid } = yield* Ref.modify(
575 state,
576 (
577 latest,
578 ): readonly [
579 {
580 readonly isCurrentRun: boolean;
581 readonly nextState: BackendManagerState;
582 readonly pid: Option.Option<number>;
583 },
584 BackendManagerState,
585 ] => {
586 const currentRun = Option.getOrUndefined(latest.active);
587 if (currentRun?.id !== runId) {
588 return [
589 {
590 isCurrentRun: false,
591 nextState: latest,
592 pid: Option.none<number>(),
593 },
594 latest,
595 ] as const;
596 }
597​
598 const next = {
599 ...latest,
600 active: Option.none<ActiveBackendRun>(),
601 ready: false,
602 };
603 return [
604 {
605 isCurrentRun: true,
606 nextState: next,
607 pid: currentRun.pid,
608 },
609 next,
610 ] as const;
611 },
612 );
613​
614 if (isCurrentRun) {
615 if (Option.isSome(pid)) {
616 yield* backendOutputLog.writeSessionBoundary({
617 phase: "END",
618 details: `pid=${pid.value} ${reason}`,
619 });
620 }
621 yield* spec.onShutdown?.() ?? Effect.void;
622 }
623​
624 if (isCurrentRun && nextState.desiredRunning) {
625 yield* scheduleRestart(reason);
626 }
627 }),
628 );
629 });
630​
631 const program = runBackendProcess({
632 ...config.value,
633 onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
634 yield* updateActiveRun(runId, (run) => ({
635 ...run,
636 pid: Option.some(pid),
637 }));
638 yield* backendOutputLog.writeSessionBoundary({
639 phase: "START",
640 details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
641 });
642 }),
643 onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
644 const isCurrentRun = yield* Ref.modify(state, (latest) => {
645 const activeRun = Option.getOrUndefined(latest.active);
646 if (activeRun?.id !== runId) {
647 return [false, latest] as const;
648 }
649​
650 return [
651 true,
652 {
653 ...latest,
654 restartAttempt: 0,
655 ready: true,
656 },
657 ] as const;
658 });
659 if (!isCurrentRun) {
660 return;
661 }
662​
663 yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
664 }),
665 onReadinessFailure: (error) =>
666 logInstanceWarning("backend readiness check failed during bootstrap", {
667 error: error.message,
668 }),
669 onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
670 }).pipe(
671 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
672 Effect.provideService(HttpClient.HttpClient, httpClient),
673 Scope.provide(runScope),
674 Effect.matchEffect({
675 onFailure: (error) => finalizeRun(error.message),
676 onSuccess: (exit) => finalizeRun(exit.reason),
677 }),
678 Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
679 );
680​
681 const fiber = yield* Effect.forkIn(program, parentScope);
682 yield* updateActiveRun(runId, (run) => ({
683 ...run,
684 fiber: Option.some(fiber),
685 }));
686 }),
687 ),
688 ).pipe(Effect.withSpan("desktop.backendInstance.start", { attributes: { id: spec.id } }));
689​
690 const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* (
691 reason: string,
692 ) {
693 const scheduled = yield* Ref.modify(state, (latest) => {
694 if (!latest.desiredRunning || Option.isSome(latest.restartFiber)) {
695 return [Option.none<Duration.Duration>(), latest] as const;
696 }
697​
698 const delay = calculateRestartDelay(latest.restartAttempt);
699 return [
700 Option.some(delay),
701 {
702 ...latest,
703 restartAttempt: latest.restartAttempt + 1,
704 },
705 ] as const;
706 });
707​
708 yield* Option.match(scheduled, {
709 onNone: () => Effect.void,
710 onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* (delay) {
711 yield* logInstanceError("backend exited unexpectedly; restart scheduled", {
712 reason,
713 delayMs: Duration.toMillis(delay),
714 });
715 const restartFiber = yield* Effect.forkIn(
716 Effect.sleep(delay).pipe(
717 Effect.andThen(
718 Ref.modify(state, (latest) => {
719 const shouldRestart = latest.desiredRunning;
720 return [
721 shouldRestart,
722 {
723 ...latest,
724 restartFiber: Option.none(),
725 },
726 ] as const;
727 }),
728 ),
729 Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
730 Effect.catchCause((cause) =>
731 logInstanceError("desktop backend restart fiber failed", {
732 cause: Cause.pretty(cause),
733 }),
734 ),
735 ),
736 parentScope,
737 );
738 yield* Ref.update(state, (latest) =>
739 Option.isNone(latest.restartFiber)
740 ? {
741 ...latest,
742 restartFiber: Option.some(restartFiber),
743 }
744 : latest,
745 );
746 }),
747 });
748 });
749​
750 const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
751 readonly timeout?: Duration.Duration;
752 }) {
753 const { active, restartFiber } = yield* mutex.withPermits(1)(
754 Effect.gen(function* () {
755 const result = yield* Ref.modify(state, (latest) => [
756 {
757 active: latest.active,
758 restartFiber: latest.restartFiber,
759 },
760 {
761 ...latest,
762 desiredRunning: false,
763 ready: false,
764 active: Option.none<ActiveBackendRun>(),
765 restartFiber: Option.none<Fiber.Fiber<void, never>>(),
766 },
767 ]);
768 // Ignore failures from spec.onShutdown so a downstream throw
769 // can't abort the rest of stop(). Ref.modify above already
770 // flipped state to "no active run / no restart fiber", and the
771 // physical cleanup (Fiber.interrupt + closeRun) runs after the
772 // mutex releases. If onShutdown were allowed to propagate, both
773 // would be skipped and the child process + restart fiber would
774 // be orphaned while state claimed nothing was running — the
775 // next start() would then spawn a second backend on top.
776 yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
777 return result;
778 }),
779 );
780​
781 yield* Option.match(restartFiber, {
782 onNone: () => Effect.void,
783 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
784 });
785 yield* Option.match(active, {
786 onNone: () => Effect.void,
787 onSome: (run) => closeRun(run, options),
788 });
789 });
790​
791 const waitForReady = (timeout: Duration.Duration): Effect.Effect<boolean> =>
792 Effect.gen(function* () {
793 const current = yield* Ref.get(state);
794 // Return false early if an external `stop()` flipped desiredRunning off
795 // — no point polling for a backend that is being torn down.
796 if (!current.desiredRunning) return { done: true, ready: false };
797 return current.ready ? { done: true, ready: true } : { done: false, ready: false };
798 }).pipe(
799 Effect.repeat({
800 until: (status) => status.done,
801 schedule: Schedule.spaced(Duration.millis(100)),
802 }),
803 Effect.map((status) => status.ready),
804 Effect.timeoutOption(timeout),
805 Effect.map(Option.getOrElse(() => false)),
806 );
807​
808 yield* Effect.addFinalizer(() => stop());
809​
810 return {
811 id: spec.id,
812 label: spec.label,
813 start,
814 stop,
815 currentConfig,
816 snapshot,
817 waitForReady,
818 } satisfies DesktopBackendInstance;
819});