Open History to see the last commit
1import {
2 DesktopBackendBootstrap,
3 type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
4 DesktopTelemetryControlMessage,
5} from "@t3tools/contracts";
6import { assert, describe, it } from "@effect/vitest";
7import * as Deferred from "effect/Deferred";
8import * as Duration from "effect/Duration";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Fiber from "effect/Fiber";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as PlatformError from "effect/PlatformError";
15import * as Queue from "effect/Queue";
16import * as Ref from "effect/Ref";
17import * as Schema from "effect/Schema";
18import * as Sink from "effect/Sink";
19import * as Scope from "effect/Scope";
20import * as Stream from "effect/Stream";
21import * as TestClock from "effect/testing/TestClock";
22import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
23import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
24
25import * as DesktopBackendManager from "./DesktopBackendManager.ts";
26import * as DesktopObservability from "../app/DesktopObservability.ts";
27import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
28
29const decodeDesktopBackendBootstrap = Schema.decodeEffect(
30 Schema.fromJsonString(DesktopBackendBootstrap),
31);
32const isBackendProcessError = Schema.is(DesktopBackendManager.BackendProcessError);
33const encodeDesktopTelemetryControl = Schema.encodeSync(
34 Schema.fromJsonString(DesktopTelemetryControlMessage),
35);
36
37const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
38 executablePath: "/electron",
39 args: ["/server/bin.mjs", "--bootstrap-fd", "3"],
40 entryPath: "/server/bin.mjs",
41 cwd: "/server",
42 env: { ELECTRON_RUN_AS_NODE: "1" },
43 bootstrap: {
44 mode: "desktop",
45 noBrowser: true,
46 port: 3773,
47 t3Home: "/tmp/t3",
48 host: "127.0.0.1",
49 desktopBootstrapToken: "token",
50 tailscaleServeEnabled: false,
51 tailscaleServePort: 443,
52 desktopTelemetryFd: 4,
53 desktopTelemetryControlFd: 5,
54 },
55 bootstrapDelivery: "fd3",
56 extendEnv: true,
57 httpBaseUrl: new URL("http://127.0.0.1:3773"),
58 captureOutput: true,
59 preflightFailure: Option.none(),
60};
61
62const configWithObservability: DesktopBackendBootstrapValue = {
63 ...baseConfig.bootstrap,
64 tailscaleServeEnabled: true,
65 desktopTelemetryFd: 4,
66 otlpTracesUrl: "http://127.0.0.1:4318/v1/traces",
67};
68
69function makeProcess(options?: {
70 readonly stdout?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
71 readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
72 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
73 readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
74 readonly getOutputFd?: ChildProcessSpawner.ChildProcessHandle["getOutputFd"];
75}): ChildProcessSpawner.ChildProcessHandle {
76 return ChildProcessSpawner.makeHandle({
77 pid: ChildProcessSpawner.ProcessId(123),
78 stdout: options?.stdout ?? Stream.empty,
79 stderr: options?.stderr ?? Stream.empty,
80 all: Stream.merge(options?.stdout ?? Stream.empty, options?.stderr ?? Stream.empty),
81 exitCode: options?.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(0)),
82 isRunning: Effect.succeed(false),
83 kill: options?.kill ?? (() => Effect.void),
84 stdin: Sink.drain,
85 getInputFd: () => Sink.drain,
86 getOutputFd: options?.getOutputFd ?? (() => Stream.empty),
87 unref: Effect.succeed(Effect.void),
88 });
89}
90
91function responseForRequest(
92 request: HttpClientRequest.HttpClientRequest,
93 status: number,
94): HttpClientResponse.HttpClientResponse {
95 return HttpClientResponse.fromWeb(request, new Response(null, { status }));
96}
97
98function httpClientLayer(
99 handler: (
100 request: HttpClientRequest.HttpClientRequest,
101 ) => Effect.Effect<HttpClientResponse.HttpClientResponse>,
102) {
103 return Layer.succeed(
104 HttpClient.HttpClient,
105 HttpClient.make((request) => handler(request)),
106 );
107}
108
109const healthyHttpClientLayer = httpClientLayer((request) =>
110 Effect.succeed(responseForRequest(request, 200)),
111);
112
113function decodeBootstrap(raw: string) {
114 return decodeDesktopBackendBootstrap(raw);
115}
116
117interface MakeInstanceInput {
118 readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
119 readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
120 readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
121 readonly onReady?: Effect.Effect<void>;
122 readonly onShutdown?: Effect.Effect<void>;
123 readonly onPreflightFailed?: (
124 failure: DesktopBackendManager.PreflightFailure,
125 ) => Effect.Effect<boolean>;
126 readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
127 readonly configResolve?: Effect.Effect<
128 DesktopBackendManager.DesktopBackendStartConfig,
129 PlatformError.PlatformError
130 >;
131 readonly desktopTelemetryStream?: Stream.Stream<Uint8Array>;
132 readonly desktopTelemetryPublisher?: Partial<
133 DesktopTelemetryPublisher.DesktopTelemetryPublisher["Service"]
134 >;
135}
136
137// Helper that constructs a primary backend instance using the factory
138// directly. The factory's deps (FileSystem, ChildProcessSpawner,
139// HttpClient, DesktopBackendOutputLogFactory) are provided per-test via
140// a scoped layer; tests yield the returned Effect inside `Effect.scoped`
141// to drive the instance's lifecycle.
142function makeTestInstance(input: MakeInstanceInput) {
143 const stubLog: DesktopObservability.DesktopBackendOutputLogShape = {
144 beginSession: () => Effect.void,
145 writeOutputChunk: () => Effect.void,
146 persistFailureSnapshot: () => Effect.void,
147 persistFailure: () => Effect.void,
148 discardSession: Effect.void,
149 ...input.backendOutputLog,
150 };
151 const servicesLayer = Layer.mergeAll(
152 FileSystem.layerNoop({
153 exists: () => Effect.succeed(true),
154 }),
155 input.spawnerLayer,
156 input.httpClientLayer ?? healthyHttpClientLayer,
157 Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
158 forInstance: () => Effect.succeed(stubLog),
159 } satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
160 Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
161 latest: Effect.succeed(Option.none()),
162 changes: Stream.empty,
163 encoded: input.desktopTelemetryStream ?? Stream.empty,
164 handleControl: () => Effect.void,
165 handleControlForSource: (_sourceId, message) =>
166 (input.desktopTelemetryPublisher?.handleControl ?? (() => Effect.void))(message),
167 removeControlSource: () => Effect.void,
168 ...input.desktopTelemetryPublisher,
169 }),
170 );
171
172 const instance = DesktopBackendManager.makeBackendInstance({
173 id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
174 label: Effect.succeed("Windows"),
175 configResolve: input.configResolve ?? Effect.succeed(input.config ?? baseConfig),
176 ...(input.onReady ? { onReady: () => input.onReady! } : {}),
177 ...(input.onShutdown ? { onShutdown: () => input.onShutdown! } : {}),
178 ...(input.onPreflightFailed ? { onPreflightFailed: input.onPreflightFailed } : {}),
179 });
180
181 return instance.pipe(Effect.provide(servicesLayer));
182}
183
184describe("DesktopBackendManager", () => {
185 it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () =>
186 Effect.scoped(
187 Effect.gen(function* () {
188 let spawnedCommand: ChildProcess.Command | undefined;
189 let bootstrapJson = "";
190 let telemetryJson = "";
191 let readyCount = 0;
192 const ready = yield* Deferred.make<void>();
193 const exited = yield* Queue.unbounded<void>();
194
195 const spawnerLayer = Layer.succeed(
196 ChildProcessSpawner.ChildProcessSpawner,
197 ChildProcessSpawner.make((command) =>
198 Effect.gen(function* () {
199 spawnedCommand = command;
200 if (command._tag === "StandardCommand") {
201 const fd3 = command.options.additionalFds?.fd3;
202 if (fd3?.type === "input" && fd3.stream) {
203 bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
204 }
205 const fd4 = command.options.additionalFds?.fd4;
206 if (fd4?.type === "input" && fd4.stream) {
207 telemetryJson = yield* fd4.stream.pipe(Stream.decodeText(), Stream.mkString);
208 }
209 }
210
211 return makeProcess({
212 exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
213 });
214 }),
215 ),
216 );
217
218 const instance = yield* makeTestInstance({
219 config: {
220 ...baseConfig,
221 bootstrap: configWithObservability,
222 },
223 spawnerLayer,
224 desktopTelemetryStream: Stream.encodeText(
225 Stream.make('{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n'),
226 ),
227 onReady: Effect.sync(() => {
228 readyCount += 1;
229 }).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
230 backendOutputLog: {
231 persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
232 },
233 });
234
235 yield* instance.start;
236 yield* Queue.take(exited);
237
238 assert.equal(readyCount, 1);
239 assert.isDefined(spawnedCommand);
240 if (spawnedCommand._tag !== "StandardCommand") {
241 throw new Error("Expected backend to spawn a standard command.");
242 }
243
244 assert.equal(spawnedCommand.command, "/electron");
245 assert.deepEqual(spawnedCommand.args, ["/server/bin.mjs", "--bootstrap-fd", "3"]);
246 assert.equal(spawnedCommand.options.cwd, "/server");
247 assert.equal(spawnedCommand.options.extendEnv, true);
248 assert.equal(spawnedCommand.options.stdout, "pipe");
249 assert.equal(spawnedCommand.options.stderr, "pipe");
250 assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
251 assert.isDefined(spawnedCommand.options.forceKillAfter);
252 assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input");
253 assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
254 assert.equal(
255 Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
256 2_000,
257 );
258
259 assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
260 assert.equal(
261 telemetryJson,
262 '{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n',
263 );
264 }),
265 ),
266 );
267
268 it.effect("preserves the readiness timeout cause and process context", () =>
269 Effect.gen(function* () {
270 const requested = yield* Deferred.make<HttpClientRequest.HttpClientRequest>();
271 const layer = Layer.merge(
272 TestClock.layer(),
273 httpClientLayer((request) =>
274 Deferred.succeed(requested, request).pipe(Effect.andThen(Effect.never)),
275 ),
276 );
277
278 yield* Effect.gen(function* () {
279 const readiness = yield* DesktopBackendManager.waitForHttpReady({
280 executablePath: baseConfig.executablePath,
281 entryPath: baseConfig.entryPath,
282 cwd: baseConfig.cwd,
283 httpBaseUrl: baseConfig.httpBaseUrl,
284 timeout: Duration.millis(50),
285 }).pipe(Effect.flip, Effect.forkChild);
286
287 const request = yield* Deferred.await(requested);
288 assert.equal(request.url, "http://127.0.0.1:3773/.well-known/t3/environment");
289
290 yield* TestClock.adjust(Duration.millis(50));
291 const error = yield* Fiber.join(readiness);
292
293 assert.instanceOf(error, DesktopBackendManager.BackendReadinessTimeoutError);
294 assert.equal(error.executablePath, "/electron");
295 assert.equal(error.entryPath, "/server/bin.mjs");
296 assert.equal(error.cwd, "/server");
297 assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
298 assert.equal(error.readinessUrl.href, "http://127.0.0.1:3773/.well-known/t3/environment");
299 assert.equal(error.timeoutMs, 50);
300 assert.isDefined(error.cause);
301 assert.equal(
302 error.message,
303 "Timed out after 50ms waiting for desktop backend readiness at http://127.0.0.1:3773/.well-known/t3/environment.",
304 );
305 }).pipe(Effect.provide(layer));
306 }),
307 );
308
309 it.effect("reports bootstrap encoding failures with stable process context", () =>
310 Effect.gen(function* () {
311 const spawnerLayer = Layer.succeed(
312 ChildProcessSpawner.ChildProcessSpawner,
313 ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
314 );
315 const error = yield* DesktopBackendManager.runBackendProcess({
316 ...baseConfig,
317 desktopTelemetryStream: Stream.empty,
318 bootstrap: {
319 ...baseConfig.bootstrap,
320 port: 0,
321 },
322 }).pipe(
323 Effect.flip,
324 Effect.scoped,
325 Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
326 );
327
328 if (error._tag !== "BackendProcessBootstrapEncodeError") {
329 return assert.fail(`Expected bootstrap encode error, received ${error._tag}`);
330 }
331 assert.equal(error.executablePath, "/electron");
332 assert.equal(error.entryPath, "/server/bin.mjs");
333 assert.equal(error.cwd, "/server");
334 assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
335 assert.isDefined(error.cause);
336 assert.equal(
337 error.message,
338 "Failed to encode the desktop backend bootstrap payload for /server/bin.mjs.",
339 );
340 assert.isTrue(isBackendProcessError(error));
341 }),
342 );
343
344 it.effect("preserves spawn failures without deriving their message from the cause", () =>
345 Effect.gen(function* () {
346 const spawnCause = PlatformError.systemError({
347 _tag: "PermissionDenied",
348 module: "ChildProcessSpawner",
349 method: "spawn",
350 pathOrDescriptor: baseConfig.executablePath,
351 description: "low-level detail that must not become the public message",
352 });
353 const spawnerLayer = Layer.succeed(
354 ChildProcessSpawner.ChildProcessSpawner,
355 ChildProcessSpawner.make(() => Effect.fail(spawnCause)),
356 );
357 const error = yield* DesktopBackendManager.runBackendProcess({
358 ...baseConfig,
359 desktopTelemetryStream: Stream.empty,
360 }).pipe(
361 Effect.flip,
362 Effect.scoped,
363 Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
364 );
365
366 if (error._tag !== "BackendProcessSpawnError") {
367 return assert.fail(`Expected backend spawn error, received ${error._tag}`);
368 }
369 assert.equal(error.executablePath, "/electron");
370 assert.equal(error.entryPath, "/server/bin.mjs");
371 assert.equal(error.cwd, "/server");
372 assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
373 assert.strictEqual(error.cause, spawnCause);
374 assert.equal(
375 error.message,
376 "Failed to spawn desktop backend entry /server/bin.mjs with /electron.",
377 );
378 assert.notInclude(error.message, spawnCause.message);
379 assert.isTrue(isBackendProcessError(error));
380 }),
381 );
382
383 it.effect("preserves exit-status failures without copying their detail into the message", () =>
384 Effect.gen(function* () {
385 const exitCause = PlatformError.systemError({
386 _tag: "PermissionDenied",
387 module: "ChildProcess",
388 method: "exitCode",
389 description: "exit-status-secret-sentinel",
390 });
391 const spawnerLayer = Layer.succeed(
392 ChildProcessSpawner.ChildProcessSpawner,
393 ChildProcessSpawner.make(() =>
394 Effect.succeed(
395 makeProcess({
396 exitCode: Effect.fail(exitCause),
397 }),
398 ),
399 ),
400 );
401 const error = yield* DesktopBackendManager.runBackendProcess({
402 ...baseConfig,
403 desktopTelemetryStream: Stream.empty,
404 }).pipe(
405 Effect.flip,
406 Effect.scoped,
407 Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
408 );
409
410 if (error._tag !== "BackendProcessExitStatusError") {
411 return assert.fail(`Expected backend exit-status error, received ${error._tag}`);
412 }
413 assert.equal(error.pid, 123);
414 assert.equal(error.executablePath, "/electron");
415 assert.equal(error.entryPath, "/server/bin.mjs");
416 assert.equal(error.cwd, "/server");
417 assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
418 assert.strictEqual(error.cause, exitCause);
419 assert.equal(error.message, "Failed to read the exit status of desktop backend process 123.");
420 assert.notInclude(error.message, "exit-status-secret-sentinel");
421 assert.isTrue(isBackendProcessError(error));
422 }),
423 );
424
425 it.effect("reports output stream failures with process and stream context", () =>
426 Effect.gen(function* () {
427 const outputCause = PlatformError.systemError({
428 _tag: "BadResource",
429 module: "ChildProcess",
430 method: "stdout",
431 description: "output-stream-secret-sentinel",
432 });
433 const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
434 const spawnerLayer = Layer.succeed(
435 ChildProcessSpawner.ChildProcessSpawner,
436 ChildProcessSpawner.make(() =>
437 Effect.succeed(
438 makeProcess({
439 stdout: Stream.fail(outputCause),
440 exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
441 }),
442 ),
443 ),
444 );
445
446 const exit = yield* DesktopBackendManager.runBackendProcess({
447 ...baseConfig,
448 desktopTelemetryStream: Stream.empty,
449 onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
450 }).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
451 const error = yield* Deferred.await(reported);
452
453 assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
454 if (error._tag !== "BackendProcessOutputReadError") {
455 return assert.fail(`Expected output read error, received ${error._tag}`);
456 }
457 assert.equal(error.executablePath, "/electron");
458 assert.equal(error.entryPath, "/server/bin.mjs");
459 assert.equal(error.cwd, "/server");
460 assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
461 assert.equal(error.pid, 123);
462 assert.equal(error.streamName, "stdout");
463 assert.strictEqual(error.cause, outputCause);
464 assert.equal(error.message, "Failed to read stdout from desktop backend process 123.");
465 assert.notInclude(error.message, "output-stream-secret-sentinel");
466 }),
467 );
468
469 it.effect("reports output handler failures separately from stream read failures", () =>
470 Effect.gen(function* () {
471 const chunk = new TextEncoder().encode("backend output");
472 const nextChunk = new TextEncoder().encode("still draining");
473 const outputCause = new Error("output-handler-secret-sentinel");
474 const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
475 const drained = yield* Deferred.make<void>();
476 let outputCount = 0;
477 const spawnerLayer = Layer.succeed(
478 ChildProcessSpawner.ChildProcessSpawner,
479 ChildProcessSpawner.make(() =>
480 Effect.succeed(
481 makeProcess({
482 stdout: Stream.make(chunk, nextChunk),
483 exitCode: Deferred.await(drained).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
484 }),
485 ),
486 ),
487 );
488
489 const exit = yield* DesktopBackendManager.runBackendProcess({
490 ...baseConfig,
491 desktopTelemetryStream: Stream.empty,
492 onOutput: () => {
493 outputCount += 1;
494 return outputCount === 1
495 ? Effect.fail(outputCause)
496 : Deferred.succeed(drained, void 0).pipe(Effect.asVoid);
497 },
498 onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
499 }).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
500 const error = yield* Deferred.await(reported);
501
502 assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
503 if (error._tag !== "BackendProcessOutputHandlingError") {
504 return assert.fail(`Expected output handling error, received ${error._tag}`);
505 }
506 assert.equal(error.executablePath, "/electron");
507 assert.equal(error.entryPath, "/server/bin.mjs");
508 assert.equal(error.cwd, "/server");
509 assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
510 assert.equal(error.pid, 123);
511 assert.equal(error.streamName, "stdout");
512 assert.equal(error.chunkByteLength, chunk.byteLength);
513 assert.strictEqual(error.cause, outputCause);
514 assert.equal(
515 error.message,
516 `Failed to handle ${chunk.byteLength} bytes from stdout of desktop backend process 123.`,
517 );
518 assert.notInclude(error.message, "output-handler-secret-sentinel");
519 assert.equal(outputCount, 2);
520 }),
521 );
522
523 it.effect("reports child exit before waiting for trailing output to drain", () =>
524 Effect.scoped(
525 Effect.gen(function* () {
526 const exitObserved = yield* Deferred.make<void>();
527 const finishOutputDrain = yield* Deferred.make<void>();
528 const spawnerLayer = Layer.succeed(
529 ChildProcessSpawner.ChildProcessSpawner,
530 ChildProcessSpawner.make(() =>
531 Effect.succeed(
532 makeProcess({
533 stdout: Stream.fromEffect(
534 Deferred.await(finishOutputDrain).pipe(
535 Effect.as(new TextEncoder().encode("trailing output\n")),
536 ),
537 ),
538 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
539 }),
540 ),
541 ),
542 );
543
544 const runFiber = yield* DesktopBackendManager.runBackendProcess({
545 ...baseConfig,
546 desktopTelemetryStream: Stream.empty,
547 onExitObserved: () => Deferred.succeed(exitObserved, void 0).pipe(Effect.asVoid),
548 }).pipe(
549 Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
550 Effect.forkChild,
551 );
552
553 yield* Deferred.await(exitObserved);
554 assert.isUndefined(runFiber.pollUnsafe());
555
556 yield* Deferred.succeed(finishOutputDrain, void 0);
557 assert.equal((yield* Fiber.join(runFiber)).code.pipe(Option.getOrUndefined), 1);
558 }),
559 ),
560 );
561
562 it.effect("continues routing desktop telemetry control messages after an invalid line", () =>
563 Effect.scoped(
564 Effect.gen(function* () {
565 const handled = yield* Deferred.make<boolean>();
566 const controlMessage = encodeDesktopTelemetryControl({
567 version: 1,
568 type: "setDiagnosticsDemand",
569 enabled: true,
570 });
571 const spawnerLayer = Layer.succeed(
572 ChildProcessSpawner.ChildProcessSpawner,
573 ChildProcessSpawner.make(() =>
574 Effect.succeed(
575 makeProcess({
576 getOutputFd: (fd) =>
577 fd === 5
578 ? Stream.encodeText(Stream.make(`not-json\n${controlMessage}\n`))
579 : Stream.empty,
580 exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
581 }),
582 ),
583 ),
584 );
585 const instance = yield* makeTestInstance({
586 spawnerLayer,
587 desktopTelemetryPublisher: {
588 handleControl: (message) =>
589 message.type === "setDiagnosticsDemand"
590 ? Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid)
591 : Effect.void,
592 },
593 });
594
595 yield* instance.start;
596 assert.isTrue(yield* Deferred.await(handled));
597 }),
598 ),
599 );
600
601 it.effect("drains trailing child output before persisting an unexpected exit", () =>
602 Effect.scoped(
603 Effect.gen(function* () {
604 const persistedOutput = yield* Deferred.make<ReadonlyArray<string>>();
605 const outputDrainStarted = yield* Deferred.make<void>();
606 const outputChunks = yield* Ref.make<Array<string>>([]);
607 const spawnerLayer = Layer.succeed(
608 ChildProcessSpawner.ChildProcessSpawner,
609 ChildProcessSpawner.make(() =>
610 Effect.succeed(
611 makeProcess({
612 stdout: Stream.fromEffect(
613 Deferred.succeed(outputDrainStarted, void 0).pipe(
614 Effect.andThen(Effect.sleep(Duration.seconds(1))),
615 Effect.as(new TextEncoder().encode("trailing output\n")),
616 ),
617 ),
618 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
619 }),
620 ),
621 ),
622 );
623 const instance = yield* makeTestInstance({
624 spawnerLayer,
625 httpClientLayer: httpClientLayer(() => Effect.never),
626 backendOutputLog: {
627 writeOutputChunk: (_streamName, chunk) =>
628 Ref.update(outputChunks, (current) => [...current, new TextDecoder().decode(chunk)]),
629 persistFailure: () =>
630 Ref.get(outputChunks).pipe(
631 Effect.flatMap((chunks) => Deferred.succeed(persistedOutput, chunks)),
632 Effect.asVoid,
633 ),
634 },
635 });
636
637 yield* instance.start;
638 yield* Deferred.await(outputDrainStarted);
639 yield* TestClock.adjust(Duration.seconds(1));
640
641 assert.deepEqual(yield* Deferred.await(persistedOutput), ["trailing output\n"]);
642 }).pipe(Effect.provide(TestClock.layer())),
643 ),
644 );
645
646 it.effect("retries HTTP readiness before reporting the backend ready", () =>
647 Effect.scoped(
648 Effect.gen(function* () {
649 const requestUrls: Array<string> = [];
650 const statuses = [503, 200];
651 let readyCount = 0;
652 const firstRequest = yield* Deferred.make<void>();
653 const ready = yield* Deferred.make<void>();
654 const exited = yield* Queue.unbounded<void>();
655
656 const spawnerLayer = Layer.succeed(
657 ChildProcessSpawner.ChildProcessSpawner,
658 ChildProcessSpawner.make(() =>
659 Effect.succeed(
660 makeProcess({
661 exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
662 }),
663 ),
664 ),
665 );
666
667 const instance = yield* makeTestInstance({
668 spawnerLayer,
669 httpClientLayer: httpClientLayer((request) =>
670 Effect.gen(function* () {
671 const status = statuses.shift();
672 assert.isDefined(status);
673 requestUrls.push(request.url);
674 yield* Deferred.succeed(firstRequest, void 0);
675 return responseForRequest(request, status);
676 }),
677 ),
678 onReady: Effect.sync(() => {
679 readyCount += 1;
680 }).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
681 backendOutputLog: {
682 persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
683 },
684 });
685
686 yield* instance.start;
687 yield* Deferred.await(firstRequest);
688
689 assert.equal(readyCount, 0);
690 assert.deepEqual(requestUrls, ["http://127.0.0.1:3773/.well-known/t3/environment"]);
691
692 yield* TestClock.adjust(Duration.millis(100));
693 yield* Queue.take(exited);
694
695 assert.equal(readyCount, 1);
696 assert.deepEqual(requestUrls, [
697 "http://127.0.0.1:3773/.well-known/t3/environment",
698 "http://127.0.0.1:3773/.well-known/t3/environment",
699 ]);
700 }).pipe(Effect.provide(TestClock.layer())),
701 ),
702 );
703
704 it.effect(
705 "re-probes readiness after the first budget expires while the backend is still alive",
706 () =>
707 Effect.scoped(
708 Effect.gen(function* () {
709 const requestUrls: Array<string> = [];
710 let requestCount = 0;
711 let readyCount = 0;
712 let readinessTimeoutCount = 0;
713 const firstProbe = yield* Deferred.make<void>();
714 const childExit = yield* Deferred.make<void>();
715
716 const spawnerLayer = Layer.succeed(
717 ChildProcessSpawner.ChildProcessSpawner,
718 ChildProcessSpawner.make(() =>
719 Effect.succeed(
720 makeProcess({
721 exitCode: Deferred.await(childExit).pipe(
722 Effect.as(ChildProcessSpawner.ExitCode(0)),
723 ),
724 }),
725 ),
726 ),
727 );
728
729 // The backend stays 503 through the first *two* readiness budgets
730 // and only becomes healthy (200) for the third round, i.e. it comes
731 // up well after the initial 50ms budget has expired.
732 const httpLayer = httpClientLayer((request) =>
733 Effect.gen(function* () {
734 requestCount += 1;
735 requestUrls.push(request.url);
736 yield* Deferred.succeed(firstProbe, void 0);
737 return responseForRequest(request, requestCount <= 2 ? 503 : 200);
738 }),
739 );
740
741 const runFiber = yield* DesktopBackendManager.runBackendProcess({
742 ...baseConfig,
743 desktopTelemetryStream: Stream.empty,
744 readinessTimeout: Duration.millis(50),
745 onReady: () =>
746 Effect.sync(() => {
747 readyCount += 1;
748 }),
749 onReadinessFailure: () =>
750 Effect.sync(() => {
751 readinessTimeoutCount += 1;
752 }),
753 }).pipe(Effect.provide(Layer.merge(spawnerLayer, httpLayer)), Effect.forkChild);
754
755 yield* Deferred.await(firstProbe);
756 assert.equal(readyCount, 0);
757 assert.equal(readinessTimeoutCount, 0);
758
759 // The first 50ms readiness budget expires while the backend still
760 // answers 503. The child is alive and may yet become healthy, so the
761 // probe must start a fresh round instead of stopping permanently —
762 // the pre-fix behavior left the app stuck on "Connecting to WSL…"
763 // forever even though the backend kept running.
764 yield* TestClock.adjust(Duration.millis(50));
765 assert.equal(readinessTimeoutCount, 1);
766 assert.equal(readyCount, 0);
767
768 // The second budget also expires (backend still 503), then the third
769 // round connects. The point is the probe persisted across budgets
770 // while the process was alive instead of giving up after the first.
771 yield* TestClock.adjust(Duration.millis(100));
772 assert.equal(readinessTimeoutCount, 2);
773 assert.equal(readyCount, 1);
774 assert.equal(requestUrls.length, 3);
775
776 yield* Deferred.succeed(childExit, void 0);
777 assert.equal((yield* Fiber.join(runFiber)).code.pipe(Option.getOrUndefined), 0);
778 }).pipe(Effect.provide(TestClock.layer())),
779 ),
780 );
781
782 it.effect("starts the configured backend and closes the scoped process on stop", () =>
783 Effect.scoped(
784 Effect.gen(function* () {
785 let startCount = 0;
786 let closedCount = 0;
787 const closed = yield* Deferred.make<void>();
788 const teardownStarted = yield* Deferred.make<void>();
789 const finishTeardown = yield* Deferred.make<void>();
790 const startedPids = yield* Queue.unbounded<number>();
791 const ready = yield* Deferred.make<void>();
792 const backendReadyFlag = yield* Ref.make(false);
793 let shutdownCount = 0;
794 let persistedFailureCount = 0;
795 let discardedSessionCount = 0;
796 let removedTelemetrySources = 0;
797
798 const spawnerLayer = Layer.succeed(
799 ChildProcessSpawner.ChildProcessSpawner,
800 ChildProcessSpawner.make(() =>
801 Effect.gen(function* () {
802 const scope = yield* Scope.Scope;
803 startCount += 1;
804 yield* Queue.offer(startedPids, 123);
805 const close = Deferred.succeed(teardownStarted, undefined).pipe(
806 Effect.andThen(Deferred.await(finishTeardown)),
807 Effect.andThen(
808 Effect.sync(() => {
809 closedCount += 1;
810 }),
811 ),
812 Effect.andThen(Deferred.succeed(closed, void 0)),
813 Effect.asVoid,
814 );
815
816 yield* Scope.addFinalizer(scope, close);
817
818 return makeProcess({
819 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
820 kill: () => close,
821 });
822 }),
823 ),
824 );
825
826 const instance = yield* makeTestInstance({
827 spawnerLayer,
828 onReady: Ref.set(backendReadyFlag, true).pipe(
829 Effect.andThen(Deferred.succeed(ready, void 0)),
830 Effect.asVoid,
831 ),
832 onShutdown: Ref.set(backendReadyFlag, false).pipe(
833 Effect.andThen(
834 Effect.sync(() => {
835 shutdownCount += 1;
836 }),
837 ),
838 ),
839 backendOutputLog: {
840 persistFailure: () =>
841 Effect.sync(() => {
842 persistedFailureCount += 1;
843 }),
844 discardSession: Effect.sync(() => {
845 discardedSessionCount += 1;
846 }),
847 },
848 desktopTelemetryPublisher: {
849 removeControlSource: () =>
850 Effect.sync(() => {
851 removedTelemetrySources += 1;
852 }),
853 },
854 });
855 assert.isTrue(Option.isNone(yield* instance.currentConfig));
856
857 yield* instance.start;
858 assert.equal(yield* Queue.take(startedPids), 123);
859 yield* Deferred.await(ready);
860 assert.isTrue(yield* Ref.get(backendReadyFlag));
861 assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig));
862
863 const runningSnapshot = yield* instance.snapshot;
864 assert.equal(runningSnapshot.ready, true);
865 assert.deepEqual(runningSnapshot.activePid, Option.some(123));
866
867 const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
868 yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
869 assert.isFalse(yield* Ref.get(backendReadyFlag));
870 assert.equal(shutdownCount, 1);
871 yield* Deferred.succeed(finishTeardown, undefined);
872 yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
873 assert.equal(startCount, 1);
874 assert.equal(closedCount, 1);
875 assert.equal(persistedFailureCount, 0);
876 assert.equal(discardedSessionCount, 1);
877 assert.equal(removedTelemetrySources, 1);
878
879 const stoppedSnapshot = yield* instance.snapshot;
880 assert.isFalse(yield* Ref.get(backendReadyFlag));
881 assert.equal(shutdownCount, 1);
882 assert.equal(stoppedSnapshot.desiredRunning, false);
883 assert.equal(stoppedSnapshot.ready, false);
884 assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
885 }),
886 ),
887 );
888
889 it.effect("restarts when start is requested during stop teardown", () =>
890 Effect.scoped(
891 Effect.gen(function* () {
892 const starts = yield* Queue.unbounded<number>();
893 const teardownStarted = yield* Deferred.make<void>();
894 const finishTeardown = yield* Deferred.make<void>();
895 let startCount = 0;
896
897 const spawnerLayer = Layer.succeed(
898 ChildProcessSpawner.ChildProcessSpawner,
899 ChildProcessSpawner.make(() =>
900 Effect.gen(function* () {
901 const scope = yield* Scope.Scope;
902 const closed = yield* Deferred.make<void>();
903 startCount += 1;
904 yield* Queue.offer(starts, startCount);
905 if (startCount === 1) {
906 yield* Scope.addFinalizer(
907 scope,
908 Deferred.succeed(teardownStarted, undefined).pipe(
909 Effect.andThen(Deferred.await(finishTeardown)),
910 Effect.andThen(Deferred.succeed(closed, undefined)),
911 Effect.asVoid,
912 ),
913 );
914 } else {
915 yield* Scope.addFinalizer(
916 scope,
917 Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
918 );
919 }
920 return makeProcess({
921 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
922 });
923 }),
924 ),
925 );
926
927 const instance = yield* makeTestInstance({
928 spawnerLayer,
929 httpClientLayer: httpClientLayer(() => Effect.never),
930 });
931
932 yield* instance.start;
933 assert.equal(yield* Queue.take(starts), 1);
934
935 const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
936 yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
937 yield* instance.start;
938 assert.equal((yield* instance.snapshot).desiredRunning, true);
939
940 yield* Deferred.succeed(finishTeardown, undefined);
941 yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
942 yield* TestClock.adjust(Duration.millis(500));
943
944 assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
945 const restarted = yield* instance.snapshot;
946 assert.equal(restarted.desiredRunning, true);
947 assert.deepEqual(restarted.activePid, Option.some(123));
948 }).pipe(Effect.provide(TestClock.layer())),
949 ),
950 );
951
952 it.effect("retries config resolution after a start request during stop teardown", () =>
953 Effect.scoped(
954 Effect.gen(function* () {
955 const starts = yield* Queue.unbounded<number>();
956 const teardownStarted = yield* Deferred.make<void>();
957 const finishTeardown = yield* Deferred.make<void>();
958 const configAttempts = yield* Ref.make(0);
959 let startCount = 0;
960
961 const configFailure = PlatformError.systemError({
962 _tag: "Unknown",
963 module: "DesktopBackendManager",
964 method: "configResolve",
965 description: "transient configuration failure",
966 });
967 const spawnerLayer = Layer.succeed(
968 ChildProcessSpawner.ChildProcessSpawner,
969 ChildProcessSpawner.make(() =>
970 Effect.gen(function* () {
971 const scope = yield* Scope.Scope;
972 const closed = yield* Deferred.make<void>();
973 startCount += 1;
974 yield* Queue.offer(starts, startCount);
975 if (startCount === 1) {
976 yield* Scope.addFinalizer(
977 scope,
978 Deferred.succeed(teardownStarted, undefined).pipe(
979 Effect.andThen(Deferred.await(finishTeardown)),
980 Effect.andThen(Deferred.succeed(closed, undefined)),
981 Effect.asVoid,
982 ),
983 );
984 } else {
985 yield* Scope.addFinalizer(
986 scope,
987 Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
988 );
989 }
990 return makeProcess({
991 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
992 });
993 }),
994 ),
995 );
996 const configResolve = Ref.updateAndGet(configAttempts, (attempt) => attempt + 1).pipe(
997 Effect.flatMap((attempt) =>
998 attempt === 2 ? Effect.fail(configFailure) : Effect.succeed(baseConfig),
999 ),
1000 );
1001 const instance = yield* makeTestInstance({
1002 spawnerLayer,
1003 configResolve,
1004 httpClientLayer: httpClientLayer(() => Effect.never),
1005 });
1006
1007 yield* instance.start;
1008 assert.equal(yield* Queue.take(starts), 1);
1009
1010 const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
1011 yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
1012 yield* instance.start;
1013 yield* Deferred.succeed(finishTeardown, undefined);
1014 yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
1015
1016 const pendingRestart = yield* instance.snapshot;
1017 assert.equal(pendingRestart.desiredRunning, true);
1018 assert.equal(pendingRestart.restartScheduled, true);
1019
1020 yield* TestClock.adjust(Duration.seconds(2));
1021
1022 assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
1023 assert.equal(yield* Ref.get(configAttempts), 3);
1024 assert.equal((yield* instance.snapshot).desiredRunning, true);
1025 }).pipe(Effect.provide(TestClock.layer())),
1026 ),
1027 );
1028
1029 it.effect("keeps a timed-out run active until its process exits", () =>
1030 Effect.scoped(
1031 Effect.gen(function* () {
1032 const starts = yield* Queue.unbounded<number>();
1033 const teardownStarted = yield* Deferred.make<void>();
1034 const finishTeardown = yield* Deferred.make<void>();
1035 let startCount = 0;
1036
1037 const spawnerLayer = Layer.succeed(
1038 ChildProcessSpawner.ChildProcessSpawner,
1039 ChildProcessSpawner.make(() =>
1040 Effect.gen(function* () {
1041 const scope = yield* Scope.Scope;
1042 const closed = yield* Deferred.make<void>();
1043 startCount += 1;
1044 yield* Queue.offer(starts, startCount);
1045 if (startCount === 1) {
1046 yield* Scope.addFinalizer(
1047 scope,
1048 Deferred.succeed(teardownStarted, undefined).pipe(
1049 Effect.andThen(Deferred.await(finishTeardown)),
1050 Effect.andThen(Deferred.succeed(closed, undefined)),
1051 Effect.asVoid,
1052 ),
1053 );
1054 } else {
1055 yield* Scope.addFinalizer(
1056 scope,
1057 Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
1058 );
1059 }
1060 return makeProcess({
1061 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
1062 });
1063 }),
1064 ),
1065 );
1066
1067 const instance = yield* makeTestInstance({
1068 spawnerLayer,
1069 httpClientLayer: httpClientLayer(() => Effect.never),
1070 });
1071
1072 yield* instance.start;
1073 assert.equal(yield* Queue.take(starts), 1);
1074
1075 const stopFiber = yield* instance
1076 .stop({ timeout: Duration.millis(100) })
1077 .pipe(Effect.forkChild);
1078 yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
1079 yield* instance.start;
1080 yield* TestClock.adjust(Duration.millis(100));
1081 yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
1082
1083 assert.equal(startCount, 1);
1084 const timedOut = yield* instance.snapshot;
1085 assert.equal(timedOut.desiredRunning, true);
1086 assert.deepEqual(timedOut.activePid, Option.some(123));
1087
1088 yield* Deferred.succeed(finishTeardown, undefined);
1089 yield* TestClock.adjust(Duration.millis(500));
1090
1091 assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
1092 }).pipe(Effect.provide(TestClock.layer())),
1093 ),
1094 );
1095
1096 it.effect("does not notify shutdown before the first start has prior state", () =>
1097 Effect.scoped(
1098 Effect.gen(function* () {
1099 let shutdownCount = 0;
1100 const closed = yield* Deferred.make<void>();
1101 const startedPids = yield* Queue.unbounded<number>();
1102
1103 const spawnerLayer = Layer.succeed(
1104 ChildProcessSpawner.ChildProcessSpawner,
1105 ChildProcessSpawner.make(() =>
1106 Effect.gen(function* () {
1107 yield* Queue.offer(startedPids, 123);
1108 const close = Deferred.succeed(closed, void 0).pipe(Effect.asVoid);
1109 return makeProcess({
1110 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
1111 kill: () => close,
1112 });
1113 }),
1114 ),
1115 );
1116
1117 const instance = yield* makeTestInstance({
1118 spawnerLayer,
1119 httpClientLayer: httpClientLayer(() => Effect.never),
1120 onShutdown: Effect.sync(() => {
1121 shutdownCount += 1;
1122 }),
1123 });
1124
1125 yield* instance.start;
1126 assert.equal(yield* Queue.take(startedPids), 123);
1127 assert.equal(shutdownCount, 0);
1128 }),
1129 ),
1130 );
1131
1132 it.effect("restarts an unexpectedly exited backend with the Effect clock", () =>
1133 Effect.scoped(
1134 Effect.gen(function* () {
1135 const starts = yield* Queue.unbounded<number>();
1136 const failures = yield* Queue.unbounded<string>();
1137 let startCount = 0;
1138
1139 const spawnerLayer = Layer.succeed(
1140 ChildProcessSpawner.ChildProcessSpawner,
1141 ChildProcessSpawner.make(() =>
1142 Effect.sync(() => {
1143 startCount += 1;
1144 return makeProcess({
1145 exitCode: Queue.offer(starts, startCount).pipe(
1146 Effect.as(ChildProcessSpawner.ExitCode(1)),
1147 ),
1148 });
1149 }),
1150 ),
1151 );
1152
1153 const instance = yield* makeTestInstance({
1154 spawnerLayer,
1155 httpClientLayer: httpClientLayer(() => Effect.never),
1156 backendOutputLog: {
1157 persistFailure: ({ details }) => Queue.offer(failures, details).pipe(Effect.asVoid),
1158 },
1159 });
1160
1161 yield* instance.start;
1162
1163 assert.equal(yield* Queue.take(starts), 1);
1164 assert.equal(yield* Queue.take(failures), "pid=123 code=1");
1165
1166 yield* TestClock.adjust(Duration.millis(499));
1167 assert.equal(yield* Queue.size(starts), 0);
1168 yield* TestClock.adjust(Duration.millis(1));
1169 assert.equal(yield* Queue.take(starts), 2);
1170
1171 yield* TestClock.adjust(Duration.millis(999));
1172 assert.equal(yield* Queue.size(starts), 0);
1173 yield* TestClock.adjust(Duration.millis(1));
1174 assert.equal(yield* Queue.take(starts), 3);
1175 }).pipe(Effect.provide(TestClock.layer())),
1176 ),
1177 );
1178
1179 it.effect("does not notify shutdown when a scheduled restart starts from non-ready state", () =>
1180 Effect.scoped(
1181 Effect.gen(function* () {
1182 let shutdownCount = 0;
1183
1184 const spawnerLayer = Layer.succeed(
1185 ChildProcessSpawner.ChildProcessSpawner,
1186 ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
1187 );
1188
1189 const instance = yield* makeTestInstance({
1190 spawnerLayer,
1191 config: {
1192 ...baseConfig,
1193 preflightFailure: Option.some({ reason: "preflight failed", fatal: false }),
1194 },
1195 onShutdown: Effect.sync(() => {
1196 shutdownCount += 1;
1197 }),
1198 });
1199
1200 yield* instance.start;
1201 assert.equal(shutdownCount, 0);
1202
1203 yield* TestClock.adjust(Duration.millis(500));
1204 assert.equal(shutdownCount, 0);
1205 }).pipe(Effect.provide(TestClock.layer())),
1206 ),
1207 );
1208
1209 it.effect("surfaces a fatal preflight failure once and stops looping after the cap", () =>
1210 Effect.scoped(
1211 Effect.gen(function* () {
1212 const failures: string[] = [];
1213 const spawnerLayer = Layer.succeed(
1214 ChildProcessSpawner.ChildProcessSpawner,
1215 ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
1216 );
1217
1218 const instance = yield* makeTestInstance({
1219 spawnerLayer,
1220 config: {
1221 ...baseConfig,
1222 preflightFailure: Option.some({ reason: "Node.js not found", fatal: true }),
1223 },
1224 onPreflightFailed: (failure) =>
1225 Effect.sync(() => {
1226 failures.push(failure.reason);
1227 }).pipe(Effect.as(false)),
1228 });
1229
1230 yield* instance.start;
1231 assert.deepEqual(failures, []);
1232
1233 // Five fatal attempts with exponential backoff (500ms, 1s, 2s, 4s) reach
1234 // the cap, at which point the failure is surfaced exactly once.
1235 yield* TestClock.adjust(Duration.millis(500));
1236 yield* TestClock.adjust(Duration.seconds(1));
1237 yield* TestClock.adjust(Duration.seconds(2));
1238 yield* TestClock.adjust(Duration.seconds(4));
1239 assert.deepEqual(failures, ["Node.js not found"]);
1240
1241 // Past the cap the loop stops and nothing else is surfaced.
1242 yield* TestClock.adjust(Duration.seconds(8));
1243 yield* TestClock.adjust(Duration.seconds(30));
1244 assert.deepEqual(failures, ["Node.js not found"]);
1245 }).pipe(Effect.provide(TestClock.layer())),
1246 ),
1247 );
1248
1249 it.effect("can be started again after a fatal preflight cap once config recovers", () =>
1250 Effect.scoped(
1251 Effect.gen(function* () {
1252 const failing = yield* Ref.make(true);
1253 const starts = yield* Queue.unbounded<number>();
1254 const spawnerLayer = Layer.succeed(
1255 ChildProcessSpawner.ChildProcessSpawner,
1256 ChildProcessSpawner.make(() =>
1257 Queue.offer(starts, 123).pipe(
1258 Effect.as(
1259 makeProcess({
1260 exitCode: Effect.never,
1261 }),
1262 ),
1263 ),
1264 ),
1265 );
1266
1267 const instance = yield* makeTestInstance({
1268 spawnerLayer,
1269 configResolve: Ref.get(failing).pipe(
1270 Effect.map((isFailing) =>
1271 isFailing
1272 ? {
1273 ...baseConfig,
1274 preflightFailure: Option.some({
1275 reason: "Node.js not found",
1276 fatal: true,
1277 }),
1278 }
1279 : baseConfig,
1280 ),
1281 ),
1282 });
1283
1284 yield* instance.start;
1285 yield* TestClock.adjust(Duration.millis(500));
1286 yield* TestClock.adjust(Duration.seconds(1));
1287 yield* TestClock.adjust(Duration.seconds(2));
1288 yield* TestClock.adjust(Duration.seconds(4));
1289 yield* TestClock.adjust(Duration.seconds(8));
1290
1291 const parked = yield* instance.snapshot;
1292 assert.equal(parked.desiredRunning, false);
1293 assert.equal(parked.ready, false);
1294 assert.isTrue(Option.isNone(parked.activePid));
1295 assert.equal(parked.restartScheduled, false);
1296 assert.equal(yield* Queue.size(starts), 0);
1297
1298 yield* Ref.set(failing, false);
1299 yield* instance.start;
1300
1301 assert.equal(yield* Queue.take(starts), 123);
1302 const running = yield* instance.snapshot;
1303 assert.equal(running.desiredRunning, true);
1304 assert.deepEqual(running.activePid, Option.some(123));
1305 }).pipe(Effect.provide(TestClock.layer())),
1306 ),
1307 );
1308
1309 it.effect("keeps retrying a transient (non-fatal) preflight failure without surfacing", () =>
1310 Effect.scoped(
1311 Effect.gen(function* () {
1312 const failures: string[] = [];
1313 const spawnerLayer = Layer.succeed(
1314 ChildProcessSpawner.ChildProcessSpawner,
1315 ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
1316 );
1317
1318 const instance = yield* makeTestInstance({
1319 spawnerLayer,
1320 config: {
1321 ...baseConfig,
1322 preflightFailure: Option.some({ reason: "wslpath conversion failed", fatal: false }),
1323 },
1324 onPreflightFailed: (failure) =>
1325 Effect.sync(() => {
1326 failures.push(failure.reason);
1327 }).pipe(Effect.as(false)),
1328 });
1329
1330 yield* instance.start;
1331 // Well beyond the fatal cap's worth of time: a transient failure must
1332 // keep retrying (self-heal) and never surface.
1333 yield* TestClock.adjust(Duration.minutes(2));
1334 assert.deepEqual(failures, []);
1335 }).pipe(Effect.provide(TestClock.layer())),
1336 ),
1337 );
1338
1339 it.effect("surfaces a bounded transient preflight failure after its retry limit", () =>
1340 Effect.scoped(
1341 Effect.gen(function* () {
1342 const failures: string[] = [];
1343 const spawnerLayer = Layer.succeed(
1344 ChildProcessSpawner.ChildProcessSpawner,
1345 ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
1346 );
1347
1348 const instance = yield* makeTestInstance({
1349 spawnerLayer,
1350 config: {
1351 ...baseConfig,
1352 preflightFailure: Option.some({
1353 reason: "WSL toolchain probe timed out",
1354 fatal: false,
1355 retryLimit: 3,
1356 }),
1357 },
1358 onPreflightFailed: (failure) =>
1359 Effect.sync(() => {
1360 failures.push(failure.reason);
1361 }).pipe(Effect.as(false)),
1362 });
1363
1364 yield* instance.start;
1365 yield* TestClock.adjust(Duration.millis(500));
1366 assert.deepEqual(failures, []);
1367
1368 yield* TestClock.adjust(Duration.seconds(1));
1369 assert.deepEqual(failures, ["WSL toolchain probe timed out"]);
1370 }).pipe(Effect.provide(TestClock.layer())),
1371 ),
1372 );
1373
1374 it.effect("cancels a scheduled restart when start is requested manually", () =>
1375 Effect.scoped(
1376 Effect.gen(function* () {
1377 const starts = yield* Queue.unbounded<number>();
1378 const secondClosed = yield* Deferred.make<void>();
1379 let startCount = 0;
1380
1381 const spawnerLayer = Layer.succeed(
1382 ChildProcessSpawner.ChildProcessSpawner,
1383 ChildProcessSpawner.make(() =>
1384 Effect.gen(function* () {
1385 startCount += 1;
1386 yield* Queue.offer(starts, startCount);
1387
1388 if (startCount === 1) {
1389 return makeProcess({
1390 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
1391 });
1392 }
1393
1394 const scope = yield* Scope.Scope;
1395 const close = Deferred.succeed(secondClosed, void 0).pipe(Effect.asVoid);
1396 yield* Scope.addFinalizer(scope, close);
1397 return makeProcess({
1398 exitCode: Deferred.await(secondClosed).pipe(
1399 Effect.as(ChildProcessSpawner.ExitCode(0)),
1400 ),
1401 kill: () => close,
1402 });
1403 }),
1404 ),
1405 );
1406
1407 const instance = yield* makeTestInstance({
1408 spawnerLayer,
1409 httpClientLayer: httpClientLayer(() => Effect.never),
1410 });
1411
1412 yield* instance.start;
1413
1414 assert.equal(yield* Queue.take(starts), 1);
1415 let restartScheduled = false;
1416 while (!restartScheduled) {
1417 restartScheduled = (yield* instance.snapshot).restartScheduled;
1418 if (!restartScheduled) {
1419 yield* Effect.yieldNow;
1420 }
1421 }
1422
1423 yield* instance.start;
1424 assert.equal(yield* Queue.take(starts), 2);
1425
1426 yield* instance.stop();
1427 yield* TestClock.adjust(Duration.millis(500));
1428
1429 assert.equal(yield* Queue.size(starts), 0);
1430 }).pipe(Effect.provide(TestClock.layer())),
1431 ),
1432 );
1433
1434 it.effect("does not restart after stop cancels a scheduled restart", () =>
1435 Effect.scoped(
1436 Effect.gen(function* () {
1437 const starts = yield* Queue.unbounded<number>();
1438 let startCount = 0;
1439
1440 const spawnerLayer = Layer.succeed(
1441 ChildProcessSpawner.ChildProcessSpawner,
1442 ChildProcessSpawner.make(() =>
1443 Effect.sync(() => {
1444 startCount += 1;
1445 return makeProcess({
1446 exitCode: Queue.offer(starts, startCount).pipe(
1447 Effect.as(ChildProcessSpawner.ExitCode(1)),
1448 ),
1449 });
1450 }),
1451 ),
1452 );
1453
1454 const instance = yield* makeTestInstance({
1455 spawnerLayer,
1456 httpClientLayer: httpClientLayer(() => Effect.never),
1457 });
1458
1459 yield* instance.start;
1460 assert.equal(yield* Queue.take(starts), 1);
1461
1462 let restartScheduled = false;
1463 while (!restartScheduled) {
1464 restartScheduled = (yield* instance.snapshot).restartScheduled;
1465 if (!restartScheduled) {
1466 yield* Effect.yieldNow;
1467 }
1468 }
1469
1470 yield* instance.stop();
1471 yield* TestClock.adjust(Duration.millis(500));
1472
1473 assert.equal(yield* Queue.size(starts), 0);
1474 assert.equal((yield* instance.snapshot).desiredRunning, false);
1475 }).pipe(Effect.provide(TestClock.layer())),
1476 ),
1477 );
1478});