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