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