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

DesktopBackendManager.ts

1,311 lines47.5 KB

1import * as Brand from "effect/Brand";
2import * as Cause from "effect/Cause";
3import * as Deferred from "effect/Deferred";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as Fiber from "effect/Fiber";
8import * as FileSystem from "effect/FileSystem";
9import * as Option from "effect/Option";
10import * as PlatformError from "effect/PlatformError";
11import * as Ref from "effect/Ref";
12import * as SubscriptionRef from "effect/SubscriptionRef";
13import * as Schema from "effect/Schema";
14import * as Semaphore from "effect/Semaphore";
15import * as Scope from "effect/Scope";
16import * as Stream from "effect/Stream";
17import { HttpClient } from "effect/http";
18import { ChildProcess, ChildProcessSpawner } from "effect/process";
19​
20import {
21 SERVER_EXIT_CODE_MANAGED_POLICY,
22 SERVER_EXIT_CODE_STATE_DIR_OWNED,
23 DesktopBackendBootstrap,
24 type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
25 PRIMARY_LOCAL_ENVIRONMENT_ID,
26 DesktopTelemetryControlMessage,
27 type DesktopTelemetryControlMessage as DesktopTelemetryControlMessageValue,
28 type DatabaseMigrationProgress,
29} from "@t3tools/contracts";
30import {
31 databaseMigrationProgress,
32 isRunningDatabaseMigrations,
33} from "@t3tools/shared/databaseMigrationLog";
34import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness";
35​
36import * as DesktopObservability from "../app/DesktopObservability.ts";
37import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
38import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
39import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
40​
41const INITIAL_RESTART_DELAY = Duration.millis(500);
42const MAX_RESTART_DELAY = Duration.seconds(10);
43const MAX_PREFLIGHT_FAILURE_ATTEMPTS = 5;
44// Large state databases can take over a minute to become ready.
45const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(3);
46const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
47const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
48// Match the service launcher's grace period so backends can stop provider sessions.
49const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(5);
50// Allow SIGKILL and the spawner exit wait after the SIGTERM grace so quit cannot
51// orphan a backend whose shutdown hangs.
52export const BACKEND_QUIT_STOP_TIMEOUT = Duration.sum(
53 DEFAULT_BACKEND_TERMINATE_GRACE,
54 Duration.seconds(2),
55);
56const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.seconds(5);
57const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
58// Three restarts without readiness is about 2 s of backoff: past a blip, early enough to help.
59const STARTUP_FAILURE_RESTART_ATTEMPTS = 3;
60const STARTUP_FAILURE_OUTPUT_CHARS = 4_000;
61const { logWarning: logBackendProcessWarning } =
62 DesktopObservability.makeComponentLogger("desktop-backend-process");
63​
64type BackendProcessLayerServices = ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient;
65​
66type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
67​
68export type BackendProcessOutputStream = "stdout" | "stderr";
69​
70export interface BackendProcessContext {
71 readonly executablePath: string;
72 readonly entryPath: string;
73 readonly cwd: string;
74 readonly httpBaseUrl: URL;
76​
77export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
78​
79/** One readiness request and the test its answer must pass to count as this launch's backend. */
80export interface BackendReadinessProbe {
81 readonly path: string;
82 readonly accept: (body: string) => Effect.Effect<boolean>;
84​
85export interface DesktopBackendStartConfig extends BackendProcessContext {
86 readonly args: ReadonlyArray<string>;
87 readonly env: Record<string, string | undefined>;
88 /** False passes env verbatim, preventing the Windows T3CODE_HOME from leaking into WSL. */
89 readonly extendEnv: boolean;
90 readonly bootstrap: DesktopBackendBootstrapValue;
91 readonly bootstrapDelivery: DesktopBackendBootstrapDelivery;
92 readonly httpBaseUrl: URL;
93 readonly captureOutput: boolean;
94 readonly preflightFailure: Option.Option<PreflightFailure>;
95 /** Set for a backend without a control channel; each evaluation yields a fresh probe. */
96 readonly readinessProbe?: Effect.Effect<BackendReadinessProbe>;
97 readonly runningDistro?: string;
98 readonly wslRuntimeId?: string;
99 readonly wslT3Home?: string | null;
101​
102export interface PreflightFailure {
103 readonly reason: string;
104 readonly fatal: boolean;
105 readonly retryLimit?: number;
107​
108interface BackendProcessExit {
109 readonly code: Option.Option<number>;
110 readonly reason: string;
112​
113const backendProcessContextSchema = {
114 executablePath: Schema.String,
115 entryPath: Schema.String,
116 cwd: Schema.String,
117 httpBaseUrl: Schema.URL,
118};
119​
120export class BackendReadinessTimeoutError extends Schema.TaggedError<BackendReadinessTimeoutError>()(
121 "BackendReadinessTimeoutError",
122 {
123 ...backendProcessContextSchema,
124 readinessUrl: Schema.URL,
125 timeoutMs: Schema.Number,
126 cause: Schema.Defect(),
127 },
128) {
129 override get message(): string {
130 return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
131 }
133​
134export class BackendProcessBootstrapEncodeError extends Schema.TaggedError<BackendProcessBootstrapEncodeError>()(
135 "BackendProcessBootstrapEncodeError",
136 {
137 ...backendProcessContextSchema,
138 cause: Schema.Defect(),
139 },
140) {
141 override get message(): string {
142 return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
143 }
145​
146export class BackendProcessSpawnError extends Schema.TaggedError<BackendProcessSpawnError>()(
147 "BackendProcessSpawnError",
148 {
149 ...backendProcessContextSchema,
150 cause: Schema.Defect(),
151 },
152) {
153 override get message(): string {
154 return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
155 }
157​
158export class BackendProcessOutputReadError extends Schema.TaggedError<BackendProcessOutputReadError>()(
159 "BackendProcessOutputReadError",
160 {
161 ...backendProcessContextSchema,
162 pid: Schema.Number,
163 streamName: Schema.Literals(["stdout", "stderr"]),
164 cause: Schema.Defect(),
165 },
166) {
167 override get message(): string {
168 return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
169 }
171​
172export class BackendProcessOutputHandlingError extends Schema.TaggedError<BackendProcessOutputHandlingError>()(
173 "BackendProcessOutputHandlingError",
174 {
175 ...backendProcessContextSchema,
176 pid: Schema.Number,
177 streamName: Schema.Literals(["stdout", "stderr"]),
178 chunkByteLength: Schema.Number,
179 cause: Schema.Defect(),
180 },
181) {
182 override get message(): string {
183 return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
184 }
186​
187export type BackendProcessOutputError =
188 | BackendProcessOutputReadError
189 | BackendProcessOutputHandlingError;
190​
191export class BackendProcessExitStatusError extends Schema.TaggedError<BackendProcessExitStatusError>()(
192 "BackendProcessExitStatusError",
193 {
194 ...backendProcessContextSchema,
195 pid: Schema.Number,
196 cause: Schema.Defect(),
197 },
198) {
199 override get message(): string {
200 return `Failed to read the exit status of desktop backend process ${this.pid}.`;
201 }
203​
204export const BackendProcessError = Schema.Union([
205 BackendProcessBootstrapEncodeError,
206 BackendProcessSpawnError,
207 BackendProcessExitStatusError,
208]);
209export type BackendProcessError = typeof BackendProcessError.Type;
210​
211type TrackBackendProcess = (pid: number) => Effect.Effect<Effect.Effect<void>>;
212​
213interface RunBackendProcessOptions extends DesktopBackendStartConfig {
214 readonly desktopTelemetryStream: Stream.Stream<Uint8Array>;
215 readonly desktopBrowserStream?: Stream.Stream<Uint8Array>;
216 readonly onDesktopBrowserCommand?: (line: string) => Effect.Effect<void>;
217 readonly onDesktopTelemetryControl?: (
218 message: DesktopTelemetryControlMessageValue,
219 ) => Effect.Effect<void>;
220 readonly readinessTimeout?: Duration.Duration;
221 readonly outputDrainTimeout?: Duration.Duration;
222 readonly trackProcess?: TrackBackendProcess;
223 readonly onStarted?: (pid: number) => Effect.Effect<void>;
224 readonly onExitObserved?: () => Effect.Effect<void>;
225 readonly onReady?: (pid: number) => Effect.Effect<void>;
226 readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
227 readonly onOutput?: (
228 streamName: BackendProcessOutputStream,
229 chunk: Uint8Array,
230 ) => Effect.Effect<void, Error>;
231 readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
233​
234export interface DesktopBackendSnapshot {
235 readonly desiredRunning: boolean;
236 readonly ready: boolean;
237 readonly activePid: Option.Option<number>;
238 readonly restartAttempt: number;
239 readonly restartScheduled: boolean;
241​
242export type BackendInstanceId = string & Brand.Brand<"BackendInstanceId">;
243export const BackendInstanceId = Brand.nominal<BackendInstanceId>();
244​
245export const PRIMARY_INSTANCE_ID: BackendInstanceId = BackendInstanceId(
246 PRIMARY_LOCAL_ENVIRONMENT_ID,
247);
248​
249export interface BackendStartupFailure {
250 readonly reason: string;
251 /** The server refused to start under this machine's managed policy. */
252 readonly managedPolicy: boolean;
253 /** Tail of the last run's stdout and stderr. */
254 readonly output: string;
256​
257export interface DesktopBackendInstance {
258 readonly id: BackendInstanceId;
259 readonly label: Effect.Effect<string>;
260 readonly start: Effect.Effect<void>;
261 /** Timeout controls the warning; stop still waits for process teardown and exit. */
262 readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
263 readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
264 readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
265 readonly waitForReady: (timeout: Duration.Duration) => Effect.Effect<boolean>;
267​
268export interface BackendInstanceSpec {
269 readonly id: BackendInstanceId;
270 readonly label: Effect.Effect<string>;
271 readonly configResolve: Effect.Effect<DesktopBackendStartConfig, PlatformError.PlatformError>;
272 readonly trackProcess?: TrackBackendProcess;
273 /** Receives the ready run's URL and pid; reading current config could race a subsequent restart. */
274 readonly onReady?: (httpBaseUrl: URL, pid: number) => Effect.Effect<void>;
275 readonly onShutdown?: () => Effect.Effect<void>;
276 readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect<boolean>;
277 readonly onStateDirOwned?: () => Effect.Effect<void>;
278 /** Fires on each repeated crash or readiness timeout until the backend becomes ready. */
279 readonly onStartupFailure?: (failure: BackendStartupFailure) => Effect.Effect<void>;
280 readonly onMigrationProgress?: (
281 progress: DatabaseMigrationProgress | null,
282 ) => Effect.Effect<void>;
284​
285interface ActiveBackendRun {
286 readonly id: number;
287 readonly scope: Scope.Closeable;
288 readonly fiber: Option.Option<Fiber.Fiber<void, never>>;
289 readonly pid: Option.Option<number>;
290 readonly exitObserved: boolean;
291 readonly stopRequested: boolean;
293​
294interface BackendManagerState {
295 readonly desiredRunning: boolean;
296 readonly ready: boolean;
297 readonly config: Option.Option<DesktopBackendStartConfig>;
298 readonly active: Option.Option<ActiveBackendRun>;
299 readonly restartAttempt: number;
300 readonly preflightFailureAttempt: number;
301 readonly restartFiber: Option.Option<Fiber.Fiber<void, never>>;
302 readonly nextRunId: number;
304​
305const initialState: BackendManagerState = {
306 desiredRunning: false,
307 ready: false,
308 config: Option.none(),
309 active: Option.none(),
310 restartAttempt: 0,
311 preflightFailureAttempt: 0,
312 restartFiber: Option.none(),
313 nextRunId: 1,
314};
315​
316const activePid = (active: Option.Option<ActiveBackendRun>): Option.Option<number> =>
317 Option.flatMap(active, (run) => run.pid);
318​
319const withActiveRun =
320 (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
321 (state: BackendManagerState): BackendManagerState => ({
322 ...state,
323 active: Option.map(state.active, (run) => (run.id === runId ? f(run) : run)),
324 });
325​
326const calculateRestartDelay = (attempt: number): Duration.Duration =>
327 Duration.min(Duration.times(INITIAL_RESTART_DELAY, 2 ** attempt), MAX_RESTART_DELAY);
328​
329const closeRun = (
330 run: ActiveBackendRun,
331 parentScope: Scope.Scope,
332 options?: { readonly timeout?: Duration.Duration },
333) => {
334 const waitForFiber = Option.match(run.fiber, {
335 onNone: () => Effect.void,
336 onSome: (fiber) => Fiber.await(fiber).pipe(Effect.asVoid),
337 });
338 const close = Scope.close(run.scope, Exit.void).pipe(
339 Effect.withSpan("desktop.backendInstance.closeScope"),
340 Effect.andThen(waitForFiber.pipe(Effect.withSpan("desktop.backendInstance.awaitRun"))),
341 );
342 const timeout = options?.timeout;
343​
344 if (!timeout) {
345 return close;
346 }
347​
348 return Effect.forkIn(close, parentScope, { startImmediately: true }).pipe(
349 Effect.flatMap((closeFiber) =>
350 Fiber.await(closeFiber).pipe(
351 Effect.timeoutOption(timeout),
352 Effect.tap((completed) =>
353 Option.isNone(completed)
354 ? logBackendProcessWarning("backend shutdown exceeded timeout; waiting for exit", {
355 timeoutMs: Duration.toMillis(timeout),
356 })
357 : Effect.void,
358 ),
359 // Parent-scope interruption still finishes release; do not cancel sibling stops.
360 Effect.andThen(Fiber.await(closeFiber)),
361 Effect.asVoid,
362 ),
363 ),
364 );
365};
366​
367const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "localhost", "[::1]"]);
368// Windows takes about a second to fail a refused connection to a non-loopback address such as a
369// WSL distro IP, so one sequential poller notices readiness up to a second late.
370const STAGGERED_READINESS_POLLERS = 4;
371const READINESS_POLLER_STAGGER = Duration.millis(250);
372​
373interface HttpReadinessOptions extends BackendProcessContext {
374 readonly timeout: Duration.Duration;
375 readonly readinessProbe?: Effect.Effect<BackendReadinessProbe>;
377​
378const waitForHttpReady = (
379 options: HttpReadinessOptions,
380): Effect.Effect<void, BackendReadinessTimeoutError, HttpClient.HttpClient> => {
381 const poll = pollHttpReady(options);
382 if (LOOPBACK_HOSTNAMES.has(options.httpBaseUrl.hostname)) return poll;
383 return Effect.raceAll(
384 Array.from({ length: STAGGERED_READINESS_POLLERS }, (_, index) =>
385 Effect.sleep(Duration.times(READINESS_POLLER_STAGGER, index)).pipe(Effect.andThen(poll)),
386 ),
387 );
388};
389​
390const pollHttpReady = Effect.fnUntraced(function* (
391 options: HttpReadinessOptions,
392): Effect.fn.Return<void, BackendReadinessTimeoutError, HttpClient.HttpClient> {
393 const probe = options.readinessProbe === undefined ? undefined : yield* options.readinessProbe;
394 const path = probe?.path ?? BACKEND_READINESS_PATH;
395 const readinessUrl = new URL(path, options.httpBaseUrl);
396 return yield* waitForHttpReadyShared({
397 baseUrl: options.httpBaseUrl.href,
398 path,
399 ...(probe === undefined ? {} : { accept: probe.accept }),
400 timeoutMs: Duration.toMillis(options.timeout),
401 intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
402 probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
403 makeError: ({ cause }) =>
404 new BackendReadinessTimeoutError({
405 executablePath: options.executablePath,
406 entryPath: options.entryPath,
407 cwd: options.cwd,
408 httpBaseUrl: options.httpBaseUrl,
409 readinessUrl,
410 timeoutMs: Duration.toMillis(options.timeout),
411 cause,
412 }),
413 });
414});
415​
416function drainBackendOutput(
417 context: BackendProcessContext & { readonly pid: number },
418 streamName: BackendProcessOutputStream,
419 stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
420 onOutput: (
421 streamName: BackendProcessOutputStream,
422 chunk: Uint8Array,
423 ) => Effect.Effect<void, Error>,
424 onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
425): Effect.Effect<void> {
426 return stream.pipe(
427 Stream.mapError(
428 (cause) =>
429 new BackendProcessOutputReadError({
430 ...context,
431 streamName,
432 cause,
433 }),
434 ),
435 Stream.runForEach((chunk) =>
436 onOutput(streamName, chunk).pipe(
437 Effect.mapError(
438 (cause) =>
439 new BackendProcessOutputHandlingError({
440 ...context,
441 streamName,
442 chunkByteLength: chunk.byteLength,
443 cause,
444 }),
445 ),
446 Effect.catchTags({ BackendProcessOutputHandlingError: onOutputFailure }),
447 ),
448 ),
449 Effect.catchTags({
450 BackendProcessOutputReadError: onOutputFailure,
451 }),
452 );
454​
455const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
456const decodeDesktopTelemetryControlLine = Schema.decodeUnknownEffect(
457 Schema.fromJsonString(DesktopTelemetryControlMessage),
458);
459​
460export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
461 options: RunBackendProcessOptions,
462): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
463 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
464 const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
465 Effect.mapError(
466 (cause) =>
467 new BackendProcessBootstrapEncodeError({
468 executablePath: options.executablePath,
469 entryPath: options.entryPath,
470 cwd: options.cwd,
471 httpBaseUrl: options.httpBaseUrl,
472 cause,
473 }),
474 ),
475 );
476 const onOutput = options.onOutput ?? (() => Effect.void);
477 const bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));
478 const additionalFds: Record<`fd${number}`, ChildProcess.AdditionalFdConfig> = {};
479 if (options.bootstrapDelivery === "fd3") {
480 additionalFds.fd3 = {
481 type: "input",
482 stream: bootstrapStream,
483 };
484 if (options.bootstrap.desktopTelemetryFd !== undefined) {
485 additionalFds[`fd${options.bootstrap.desktopTelemetryFd}`] = {
486 type: "input",
487 stream: options.desktopTelemetryStream,
488 };
489 }
490 if (options.bootstrap.desktopTelemetryControlFd !== undefined) {
491 additionalFds[`fd${options.bootstrap.desktopTelemetryControlFd}`] = {
492 type: "output",
493 };
494 }
495 if (
496 options.bootstrap.desktopBrowserFd !== undefined &&
497 options.desktopBrowserStream !== undefined
498 ) {
499 additionalFds[`fd${options.bootstrap.desktopBrowserFd}`] = {
500 type: "input",
501 stream: options.desktopBrowserStream,
502 };
503 }
504 if (options.bootstrap.desktopBrowserControlFd !== undefined) {
505 additionalFds[`fd${options.bootstrap.desktopBrowserControlFd}`] = { type: "output" };
506 }
507 }
508 const command = ChildProcess.make(options.executablePath, options.args, {
509 cwd: options.cwd,
510 env: options.env,
511 extendEnv: options.extendEnv,
512 stdin: options.bootstrapDelivery === "stdin" ? bootstrapStream : "ignore",
513 stdout: options.captureOutput ? "pipe" : "inherit",
514 stderr: options.captureOutput ? "pipe" : "inherit",
515 killSignal: "SIGTERM",
516 forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
517 // wsl.exe drops extra file descriptors; deliver its bootstrap via stdin.
518 ...(options.bootstrapDelivery === "fd3" ? { additionalFds } : {}),
519 });
520​
521 const handle = yield* spawner.spawn(command).pipe(
522 Effect.mapError(
523 (cause) =>
524 new BackendProcessSpawnError({
525 executablePath: options.executablePath,
526 entryPath: options.entryPath,
527 cwd: options.cwd,
528 httpBaseUrl: options.httpBaseUrl,
529 cause,
530 }),
531 ),
532 );
533 // The child has a deadline for reading fd 3. Keep recovery bookkeeping off its startup path.
534 const tracking = options.trackProcess
535 ? yield* options.trackProcess(handle.pid).pipe(Effect.forkScoped)
536 : undefined;
537 const outputFibers: Array<Fiber.Fiber<void, never>> = [];
538 const serverReady = yield* Deferred.make<void>();
539​
540 yield* options.onStarted?.(handle.pid) ?? Effect.void;
541 if (options.bootstrap.desktopTelemetryControlFd !== undefined) {
542 const controlFd = options.bootstrap.desktopTelemetryControlFd;
543 const handleControl = options.onDesktopTelemetryControl ?? (() => Effect.void);
544 yield* handle.getOutputFd(controlFd).pipe(
545 Stream.decodeText(),
546 Stream.splitLines,
547 Stream.filter((line) => line.trim().length > 0),
548 Stream.runForEach((line) =>
549 decodeDesktopTelemetryControlLine(line).pipe(
550 Effect.flatMap((message) =>
551 message.type === "serverReady"
552 ? Deferred.succeed(serverReady, undefined)
553 : handleControl(message),
554 ),
555 Effect.catchCause((cause) =>
556 logBackendProcessWarning("ignored invalid desktop telemetry control message", {
557 fd: controlFd,
558 cause: Cause.pretty(cause),
559 }),
560 ),
561 ),
562 ),
563 Effect.catchCause((cause) =>
564 logBackendProcessWarning("desktop telemetry control stream stopped", {
565 fd: controlFd,
566 cause: Cause.pretty(cause),
567 }),
568 ),
569 Effect.ensuring(
570 handleControl({
571 version: 1,
572 type: "setDiagnosticsDemand",
573 enabled: false,
574 }),
575 ),
576 Effect.forkScoped,
577 );
578 }
579 if (
580 options.bootstrap.desktopBrowserControlFd !== undefined &&
581 options.onDesktopBrowserCommand !== undefined
582 ) {
583 const browserFd = options.bootstrap.desktopBrowserControlFd;
584 const handleCommand = options.onDesktopBrowserCommand;
585 yield* handle.getOutputFd(browserFd).pipe(
586 Stream.decodeText(),
587 Stream.splitLines,
588 Stream.filter((line) => line.length > 0),
589 Stream.runForEach(handleCommand),
590 Effect.catchCause((cause) =>
591 logBackendProcessWarning("desktop browser command stream stopped", {
592 fd: browserFd,
593 cause: Cause.pretty(cause),
594 }),
595 ),
596 Effect.forkScoped,
597 );
598 }
599 if (options.captureOutput) {
600 const outputContext = {
601 executablePath: options.executablePath,
602 entryPath: options.entryPath,
603 cwd: options.cwd,
604 httpBaseUrl: options.httpBaseUrl,
605 pid: Number(handle.pid),
606 };
607 const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
608 outputFibers.push(
609 yield* drainBackendOutput(
610 outputContext,
611 "stdout",
612 handle.stdout,
613 onOutput,
614 onOutputFailure,
615 ).pipe(Effect.forkScoped),
616 yield* drainBackendOutput(
617 outputContext,
618 "stderr",
619 handle.stderr,
620 onOutput,
621 onOutputFailure,
622 ).pipe(Effect.forkScoped),
623 );
624 }
625 const readinessContext = {
626 executablePath: options.executablePath,
627 entryPath: options.entryPath,
628 cwd: options.cwd,
629 httpBaseUrl: options.httpBaseUrl,
630 };
631 const readinessTimeout = options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT;
632 // A backend with a control fd reports readiness there itself, after its HTTP server is up.
633 // Backends without the fd, such as WSL, are polled over HTTP and must pass their readiness probe.
634 const awaitReady =
635 options.bootstrap.desktopTelemetryControlFd === undefined
636 ? waitForHttpReady({
637 ...readinessContext,
638 timeout: readinessTimeout,
639 ...(options.readinessProbe === undefined
640 ? {}
641 : { readinessProbe: options.readinessProbe }),
642 })
643 : Deferred.await(serverReady).pipe(
644 Effect.timeoutOrElse({
645 duration: readinessTimeout,
646 orElse: () =>
647 Effect.fail(
648 new BackendReadinessTimeoutError({
649 ...readinessContext,
650 readinessUrl: new URL(BACKEND_READINESS_PATH, options.httpBaseUrl),
651 timeoutMs: Duration.toMillis(readinessTimeout),
652 cause: "The backend did not signal readiness on its control channel.",
653 }),
654 ),
655 }),
656 );
657 // Cold WSL boots across /mnt/c can exceed one probe budget; retry while the backend is alive.
658 const probeReadiness = Effect.fn("desktop.backendProcess.probeReadiness")(() =>
659 awaitReady.pipe(
660 Effect.flatMap(() => options.onReady?.(handle.pid) ?? Effect.void),
661 Effect.as(true),
662 Effect.catchTags({
663 BackendReadinessTimeoutError: (error) =>
664 (options.onReadinessFailure?.(error) ?? Effect.void).pipe(Effect.as(false)),
665 }),
666 ),
667 );
668​
669 yield* probeReadiness().pipe(Effect.repeat({ while: (ready) => !ready }), Effect.forkScoped);
670​
671 const exit = yield* handle.exitCode.pipe(
672 Effect.withSpan("desktop.backendProcess.awaitExit"),
673 Effect.map((exitCode) => ({
674 code: Option.some(exitCode),
675 reason: `code=${exitCode}`,
676 })),
677 Effect.catch((cause) => {
678 // Effect's Node spawner exposes signal exits only through this cause message.
679 const signal =
680 cause.cause instanceof Error
681 ? /^Process interrupted due to receipt of signal: '(SIG[A-Z0-9]+)'$/.exec(
682 cause.cause.message,
683 )?.[1]
684 : undefined;
685 if (signal !== undefined) {
686 return Effect.succeed({ code: Option.none(), reason: `killed by ${signal}` });
687 }
688 return Effect.fail(
689 new BackendProcessExitStatusError({
690 executablePath: options.executablePath,
691 entryPath: options.entryPath,
692 cwd: options.cwd,
693 httpBaseUrl: options.httpBaseUrl,
694 pid: Number(handle.pid),
695 cause,
696 }),
697 );
698 }),
699 Effect.exit,
700 );
701 yield* options.onExitObserved?.() ?? Effect.void;
702 // A cancelled run may leave a survivor. Only forget after observing a real exit.
703 if (tracking && Exit.isSuccess(exit)) {
704 const forgetProcess = yield* Fiber.join(tracking);
705 yield* forgetProcess;
706 }
707 yield* Effect.forEach(outputFibers, Fiber.await, {
708 concurrency: "unbounded",
709 discard: true,
710 }).pipe(
711 Effect.timeout(options.outputDrainTimeout ?? DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT),
712 Effect.ignore,
713 Effect.withSpan("desktop.backendProcess.drainOutput"),
714 );
715 if (Exit.isFailure(exit)) {
716 return yield* Effect.failCause(exit.cause);
717 }
718 return exit.value;
719});
720​
721export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
722 spec: BackendInstanceSpec,
723): Effect.fn.Return<
724 DesktopBackendInstance,
725 never,
726 | FileSystem.FileSystem
727 | ChildProcessSpawner.ChildProcessSpawner
728 | HttpClient.HttpClient
729 | DesktopObservability.DesktopBackendOutputLogFactory
730 | DesktopTelemetryPublisher.DesktopTelemetryPublisher
731 | DesktopBrowserHost.DesktopBrowserHost
732 | DesktopWslEnvironment.DesktopWslEnvironment
733 | Scope.Scope
734> {
735 const parentScope = yield* Scope.Scope;
736 const fileSystem = yield* FileSystem.FileSystem;
737 const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
738 const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
739 const desktopTelemetryPublisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
740 const desktopBrowserHost = yield* DesktopBrowserHost.DesktopBrowserHost;
741 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
742 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
743 const httpClient = yield* HttpClient.HttpClient;
744 const state = yield* SubscriptionRef.make(initialState);
745 const mutex = yield* Semaphore.make(1);
746 const outputTail = yield* Ref.make("");
747 const migrationProgress = yield* Ref.make<DatabaseMigrationProgress | null>(null);
748 // One streaming decoder per stream keeps UTF-8 characters split across chunks intact.
749 const makeOutputDecoders = () => ({ stdout: new TextDecoder(), stderr: new TextDecoder() });
750 let outputDecoders = makeOutputDecoders();
751 const reportStartupFailure = (reason: string, managedPolicy = false) =>
752 Ref.get(outputTail).pipe(
753 Effect.flatMap(
754 (output) => spec.onStartupFailure?.({ reason, managedPolicy, output }) ?? Effect.void,
755 ),
756 );
757​
758 const { logWarning: logInstanceWarning, logError: logInstanceError } =
759 DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`);
760​
761 const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
762 SubscriptionRef.update(state, withActiveRun(runId, f));
763​
764 const snapshot = SubscriptionRef.get(state).pipe(
765 Effect.map((current): DesktopBackendSnapshot => ({
766 desiredRunning: current.desiredRunning,
767 ready: current.ready,
768 activePid: activePid(current.active),
769 restartAttempt: current.restartAttempt,
770 restartScheduled: Option.isSome(current.restartFiber),
771 })),
772 );
773 const currentConfig = SubscriptionRef.get(state).pipe(Effect.map((current) => current.config));
774​
775 const cancelRestart = Effect.gen(function* () {
776 const restartFiber = yield* SubscriptionRef.modify(state, (current) => [
777 current.restartFiber,
778 {
779 ...current,
780 restartFiber: Option.none(),
781 },
782 ]);
783​
784 yield* Option.match(restartFiber, {
785 onNone: () => Effect.void,
786 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
787 });
788 });
789​
790 const start: Effect.Effect<void> = Effect.suspend(() =>
791 mutex.withPermits(1)(
792 Effect.gen(function* () {
793 const current = yield* SubscriptionRef.get(state);
794 if (Option.isSome(current.active)) {
795 if (!current.desiredRunning) {
796 yield* SubscriptionRef.update(state, (latest) => ({
797 ...latest,
798 desiredRunning: true,
799 }));
800 }
801 return;
802 }
803​
804 if (current.ready) {
805 yield* spec.onShutdown?.() ?? Effect.void;
806 yield* SubscriptionRef.update(state, (latest) =>
807 latest.ready ? { ...latest, ready: false } : latest,
808 );
809 }
810 const config = yield* spec.configResolve.pipe(
811 Effect.tapError((error) =>
812 logInstanceError("failed to generate desktop backend configuration", {
813 cause: error.message,
814 }),
815 ),
816 Effect.option,
817 );
818 if (Option.isNone(config)) {
819 if (current.desiredRunning) {
820 yield* scheduleRestart("failed to generate desktop backend configuration");
821 }
822 return;
823 }
824 const entryExists = yield* fileSystem
825 .exists(config.value.entryPath)
826 .pipe(Effect.orElseSucceed(() => false));
827​
828 const resetFatalPreflightCounter =
829 !current.desiredRunning && current.preflightFailureAttempt > 0;
830 yield* cancelRestart;
831 yield* SubscriptionRef.update(state, (latest) => ({
832 ...latest,
833 desiredRunning: true,
834 ready: false,
835 config: Option.some(config.value),
836 preflightFailureAttempt: resetFatalPreflightCounter ? 0 : latest.preflightFailureAttempt,
837 }));
838​
839 const preflightFailure = config.value.preflightFailure;
840 if (Option.isSome(preflightFailure)) {
841 const { reason, fatal, retryLimit } = preflightFailure.value;
842 if (!fatal && retryLimit === undefined) {
843 yield* SubscriptionRef.update(state, (latest) =>
844 latest.preflightFailureAttempt === 0
845 ? latest
846 : { ...latest, preflightFailureAttempt: 0 },
847 );
848 yield* scheduleRestart(reason);
849 return;
850 }
851 const attemptLimit = retryLimit ?? MAX_PREFLIGHT_FAILURE_ATTEMPTS;
852 const attempt = yield* SubscriptionRef.modify(state, (latest) => {
853 const next = latest.preflightFailureAttempt + 1;
854 return [next, { ...latest, preflightFailureAttempt: next }] as const;
855 });
856 if (attempt > attemptLimit) {
857 yield* logInstanceError("backend preflight still failing after fallback; stopping", {
858 reason,
859 attempt,
860 });
861 yield* SubscriptionRef.update(state, (latest) => ({
862 ...latest,
863 desiredRunning: false,
864 ready: false,
865 }));
866 return;
867 }
868 if (attempt === attemptLimit) {
869 yield* logInstanceError(
870 "backend preflight failed repeatedly; surfacing and falling back",
871 { reason, attempt },
872 );
873 const shouldRestart = yield* (
874 spec.onPreflightFailed?.(preflightFailure.value) ?? Effect.succeed(false)
875 );
876 if (shouldRestart) {
877 yield* scheduleRestart(reason);
878 } else {
879 yield* SubscriptionRef.update(state, (latest) => ({
880 ...latest,
881 desiredRunning: false,
882 ready: false,
883 }));
884 }
885 return;
886 }
887 yield* scheduleRestart(reason);
888 return;
889 }
890 yield* SubscriptionRef.update(state, (latest) =>
891 latest.preflightFailureAttempt === 0 ? latest : { ...latest, preflightFailureAttempt: 0 },
892 );
893​
894 if (!entryExists) {
895 yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
896 return;
897 }
898​
899 const runScope = yield* Scope.make("sequential");
900 const runId = yield* SubscriptionRef.modify(state, (latest) => [
901 latest.nextRunId,
902 {
903 ...latest,
904 active: Option.some({
905 id: latest.nextRunId,
906 scope: runScope,
907 fiber: Option.none(),
908 pid: Option.none(),
909 exitObserved: false,
910 stopRequested: false,
911 } satisfies ActiveBackendRun),
912 nextRunId: latest.nextRunId + 1,
913 },
914 ]);
915​
916 const finalizeRun = Effect.fn("desktop.backendInstance.finalizeRun")(function* (
917 reason: string,
918 exitCode?: number,
919 ) {
920 const stateDirOwned = exitCode === SERVER_EXIT_CODE_STATE_DIR_OWNED;
921 yield* mutex.withPermits(1)(
922 Effect.gen(function* () {
923 const { isCurrentRun, nextState, pid, exitObserved, stopRequested, wasReady } =
924 yield* SubscriptionRef.modify(
925 state,
926 (
927 latest,
928 ): readonly [
929 {
930 readonly isCurrentRun: boolean;
931 readonly nextState: BackendManagerState;
932 readonly pid: Option.Option<number>;
933 readonly exitObserved: boolean;
934 readonly stopRequested: boolean;
935 readonly wasReady: boolean;
936 },
937 BackendManagerState,
938 ] => {
939 const currentRun = Option.getOrUndefined(latest.active);
940 if (currentRun?.id !== runId) {
941 return [
942 {
943 isCurrentRun: false,
944 nextState: latest,
945 pid: Option.none<number>(),
946 exitObserved: false,
947 stopRequested: false,
948 wasReady: false,
949 },
950 latest,
951 ] as const;
952 }
953​
954 const next = {
955 ...latest,
956 active: Option.none<ActiveBackendRun>(),
957 ready: false,
958 };
959 return [
960 {
961 isCurrentRun: true,
962 nextState: next,
963 pid: currentRun.pid,
964 exitObserved: currentRun.exitObserved,
965 stopRequested: currentRun.stopRequested,
966 wasReady: latest.ready,
967 },
968 next,
969 ] as const;
970 },
971 );
972​
973 if (isCurrentRun) {
974 yield* Ref.set(migrationProgress, null);
975 yield* spec.onMigrationProgress?.(null) ?? Effect.void;
976 yield* desktopTelemetryPublisher.removeControlSource(spec.id);
977 if (Option.isSome(pid)) {
978 if (exitObserved && !stopRequested) {
979 yield* backendOutputLog.persistFailure({
980 details: `pid=${pid.value} ${reason}`,
981 });
982 } else {
983 yield* backendOutputLog.discardSession;
984 }
985 }
986 if (wasReady) {
987 yield* spec.onShutdown?.() ?? Effect.void;
988 }
989 }
990​
991 if (isCurrentRun && nextState.desiredRunning) {
992 if (stateDirOwned && !stopRequested) {
993 yield* SubscriptionRef.update(state, (latest) => ({
994 ...latest,
995 desiredRunning: false,
996 }));
997 yield* (spec.onStateDirOwned?.() ?? Effect.void).pipe(Effect.ignore);
998 return;
999 }
1000 yield* scheduleRestart(reason, exitCode);
1002 }),
1003 );
1004 });
1005​
1006 const program = runBackendProcess({
1007 ...config.value,
1008 ...(spec.trackProcess === undefined ? {} : { trackProcess: spec.trackProcess }),
1009 desktopTelemetryStream: desktopTelemetryPublisher.encoded,
1010 desktopBrowserStream: desktopBrowserHost.events,
1011 onDesktopBrowserCommand: desktopBrowserHost.handleCommandLine,
1012 onDesktopTelemetryControl: (message) =>
1013 desktopTelemetryPublisher.handleControlForSource(spec.id, message),
1014 onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
1015 yield* updateActiveRun(runId, (run) => ({
1016 ...run,
1017 pid: Option.some(pid),
1018 }));
1019 yield* Ref.set(outputTail, "");
1020 yield* Ref.set(migrationProgress, null);
1021 yield* spec.onMigrationProgress?.(null) ?? Effect.void;
1022 outputDecoders = makeOutputDecoders();
1023 yield* backendOutputLog.beginSession({
1024 details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
1025 });
1026 }),
1027 onExitObserved: () =>
1028 updateActiveRun(runId, (run) => ({
1029 ...run,
1030 exitObserved: true,
1031 })),
1032 onReady: Effect.fn("desktop.backendInstance.onReady")(function* (pid) {
1033 const isCurrentRun = yield* SubscriptionRef.modify(state, (latest) => {
1034 const activeRun = Option.getOrUndefined(latest.active);
1035 if (activeRun?.id !== runId) {
1036 return [false, latest] as const;
1038​
1039 return [
1040 true,
1042 ...latest,
1043 restartAttempt: 0,
1044 ready: true,
1045 },
1046 ] as const;
1047 });
1048 if (!isCurrentRun) {
1049 return;
1051​
1052 yield* Ref.set(migrationProgress, null);
1053 yield* spec.onMigrationProgress?.(null) ?? Effect.void;
1054 yield* spec.onReady?.(config.value.httpBaseUrl, pid) ?? Effect.void;
1055 if (
1056 config.value.runningDistro !== undefined &&
1057 config.value.wslRuntimeId !== undefined
1058 ) {
1059 yield* wslEnvironment.pruneRuntimes(
1060 config.value.runningDistro,
1061 config.value.wslRuntimeId,
1062 config.value.wslT3Home ?? null,
1063 );
1065 }),
1066 onReadinessFailure: Effect.fn("desktop.backendInstance.onReadinessFailure")(
1067 function* (error) {
1068 if (
1069 (yield* Ref.get(migrationProgress)) !== null ||
1070 isRunningDatabaseMigrations(yield* Ref.get(outputTail))
1071 ) {
1072 yield* logInstanceWarning("backend is still migrating its database; waiting", {
1073 error: error.message,
1074 });
1075 return;
1077 yield* logInstanceWarning("backend readiness check failed during bootstrap", {
1078 error: error.message,
1079 });
1080 yield* backendOutputLog.persistFailureSnapshot({
1081 details: error.message,
1082 });
1083 yield* reportStartupFailure("The server started but did not become ready in time.");
1084 },
1085 ),
1086 onOutput: (streamName, chunk) =>
1087 Ref.modify(outputTail, (tail) => {
1088 const output = tail + outputDecoders[streamName].decode(chunk, { stream: true });
1089 return [
1090 output,
1091 // A cut through a surrogate pair would make encodeURIComponent throw when rendering.
1092 output.slice(-STARTUP_FAILURE_OUTPUT_CHARS).toWellFormed(),
1093 ];
1094 }).pipe(
1095 Effect.flatMap((output) =>
1096 Effect.gen(function* () {
1097 const latest = yield* SubscriptionRef.get(state);
1098 if (
1099 !latest.ready &&
1100 Option.isSome(latest.active) &&
1101 latest.active.value.id === runId
1102 ) {
1103 const progress = yield* Ref.updateAndGet(migrationProgress, (previous) =>
1104 databaseMigrationProgress(output, previous),
1105 );
1106 yield* spec.onMigrationProgress?.(progress) ?? Effect.void;
1108 }),
1109 ),
1110 Effect.andThen(backendOutputLog.writeOutputChunk(streamName, chunk)),
1111 ),
1112 }).pipe(
1113 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1114 Effect.provideService(HttpClient.HttpClient, httpClient),
1115 Scope.provide(runScope),
1116 Effect.matchEffect({
1117 onFailure: (error) => finalizeRun(error.message),
1118 onSuccess: (exit) => finalizeRun(exit.reason, Option.getOrUndefined(exit.code)),
1119 }),
1120 Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
1121 );
1122​
1123 const fiber = yield* Effect.forkIn(program, parentScope);
1124 yield* updateActiveRun(runId, (run) => ({
1125 ...run,
1126 fiber: Option.some(fiber),
1127 }));
1128 }),
1129 ),
1130 ).pipe(Effect.withSpan("desktop.backendInstance.start", { attributes: { id: spec.id } }));
1131​
1132 const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* (
1133 reason: string,
1134 exitCode?: number,
1135 ) {
1136 const scheduled = yield* SubscriptionRef.modify(state, (latest) => {
1137 if (!latest.desiredRunning || Option.isSome(latest.restartFiber)) {
1138 return [Option.none<{ delay: Duration.Duration; attempt: number }>(), latest] as const;
1140​
1141 const attempt = latest.restartAttempt + 1;
1142 return [
1143 Option.some({ delay: calculateRestartDelay(latest.restartAttempt), attempt }),
1144 { ...latest, restartAttempt: attempt },
1145 ] as const;
1146 });
1147​
1148 yield* Option.match(scheduled, {
1149 onNone: () => Effect.void,
1150 onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* ({
1151 delay,
1152 attempt,
1153 }) {
1154 yield* logInstanceError("backend exited unexpectedly; restart scheduled", {
1155 reason,
1156 delayMs: Duration.toMillis(delay),
1157 });
1158 // Retrying cannot fix a policy refusal, so say so at once; retries still pick up a fix.
1159 const managedPolicy = exitCode === SERVER_EXIT_CODE_MANAGED_POLICY;
1160 if (managedPolicy || attempt >= STARTUP_FAILURE_RESTART_ATTEMPTS) {
1161 yield* reportStartupFailure(`The server could not start (${reason}).`, managedPolicy);
1163 const restartFiber = yield* Effect.forkIn(
1164 Effect.sleep(delay).pipe(
1165 Effect.andThen(
1166 SubscriptionRef.modify(state, (latest) => {
1167 const shouldRestart = latest.desiredRunning;
1168 return [
1169 shouldRestart,
1171 ...latest,
1172 restartFiber: Option.none(),
1173 },
1174 ] as const;
1175 }),
1176 ),
1177 Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
1178 Effect.catchCause((cause) =>
1179 logInstanceError("desktop backend restart fiber failed", {
1180 cause: Cause.pretty(cause),
1181 }),
1182 ),
1183 ),
1184 parentScope,
1185 );
1186 yield* SubscriptionRef.update(state, (latest) =>
1187 Option.isNone(latest.restartFiber)
1188 ? {
1189 ...latest,
1190 restartFiber: Option.some(restartFiber),
1192 : latest,
1193 );
1194 }),
1195 });
1196 });
1197​
1198 const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
1199 readonly timeout?: Duration.Duration;
1200 }) {
1201 const { active, restartFiber, notifyShutdown } = yield* mutex.withPermits(1)(
1202 Effect.gen(function* () {
1203 const result = yield* SubscriptionRef.modify(state, (latest) => {
1204 const active = Option.map(latest.active, (run) =>
1205 run.exitObserved ? run : { ...run, stopRequested: true },
1206 );
1207 return [
1209 active,
1210 restartFiber: latest.restartFiber,
1211 notifyShutdown: latest.ready,
1212 },
1214 ...latest,
1215 desiredRunning: false,
1216 ready: false,
1217 active,
1218 restartFiber: Option.none<Fiber.Fiber<void, never>>(),
1219 },
1220 ] as const;
1221 });
1222 return result;
1223 }),
1224 );
1225​
1226 if (notifyShutdown) {
1227 yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
1229 yield* Option.match(restartFiber, {
1230 onNone: () => Effect.void,
1231 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
1232 });
1233 yield* Option.match(active, {
1234 onNone: () => Effect.void,
1235 // The enclosing operation owns the span for this inline handler.
1236 onSome: Effect.fnUntraced(function* (run) {
1237 yield* closeRun(run, parentScope, options);
1238 const cleanup = yield* mutex.withPermits(1)(
1239 SubscriptionRef.modify(
1240 state,
1242 latest,
1243 ): readonly [
1245 readonly needsCleanup: boolean;
1246 readonly shouldStart: boolean;
1247 },
1248 BackendManagerState,
1249 ] => {
1250 const current = Option.getOrUndefined(latest.active);
1251 if (current?.id !== run.id) {
1252 return [
1254 needsCleanup: false,
1255 shouldStart:
1256 latest.desiredRunning &&
1257 Option.isNone(latest.active) &&
1258 Option.isNone(latest.restartFiber),
1259 },
1260 latest,
1261 ];
1263 return [
1265 needsCleanup: true,
1266 shouldStart: latest.desiredRunning,
1267 },
1269 ...latest,
1270 active: Option.none<ActiveBackendRun>(),
1271 },
1272 ];
1273 },
1274 ),
1275 );
1276 if (cleanup.needsCleanup) {
1277 yield* desktopTelemetryPublisher.removeControlSource(spec.id);
1278 yield* backendOutputLog.discardSession;
1280 if (cleanup.shouldStart) {
1281 yield* start;
1283 }),
1284 });
1285 });
1286​
1287 const waitForReady = Effect.fn("DesktopBackendManager.waitForReady")(
1288 (timeout: Duration.Duration) =>
1289 SubscriptionRef.changes(state).pipe(
1290 Stream.filter((current) => current.ready || !current.desiredRunning),
1291 Stream.map((current) => current.ready),
1292 Stream.runHead,
1293 Effect.timeoutOption(timeout),
1294 Effect.map(
1295 (result) => Option.isSome(result) && Option.getOrElse(result.value, () => false),
1296 ),
1297 ),
1298 );
1299​
1300 yield* Effect.addFinalizer(() => stop());
1301​
1302 return {
1303 id: spec.id,
1304 label: spec.label,
1305 start,
1306 stop,
1307 currentConfig,
1308 snapshot,
1309 waitForReady,
1310 } satisfies DesktopBackendInstance;
1311});