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("starts the configured backend and closes the scoped process on stop", () =>
705 Effect.scoped(
706 Effect.gen(function* () {
707 let startCount = 0;
708 let closedCount = 0;
709 const closed = yield* Deferred.make<void>();
710 const teardownStarted = yield* Deferred.make<void>();
711 const finishTeardown = yield* Deferred.make<void>();
712 const startedPids = yield* Queue.unbounded<number>();
713 const ready = yield* Deferred.make<void>();
714 const backendReadyFlag = yield* Ref.make(false);
715 let shutdownCount = 0;
716 let persistedFailureCount = 0;
717 let discardedSessionCount = 0;
718 let removedTelemetrySources = 0;
719
720 const spawnerLayer = Layer.succeed(
721 ChildProcessSpawner.ChildProcessSpawner,
722 ChildProcessSpawner.make(() =>
723 Effect.gen(function* () {
724 const scope = yield* Scope.Scope;
725 startCount += 1;
726 yield* Queue.offer(startedPids, 123);
727 const close = Deferred.succeed(teardownStarted, undefined).pipe(
728 Effect.andThen(Deferred.await(finishTeardown)),
729 Effect.andThen(
730 Effect.sync(() => {
731 closedCount += 1;
732 }),
733 ),
734 Effect.andThen(Deferred.succeed(closed, void 0)),
735 Effect.asVoid,
736 );
737
738 yield* Scope.addFinalizer(scope, close);
739
740 return makeProcess({
741 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
742 kill: () => close,
743 });
744 }),
745 ),
746 );
747
748 const instance = yield* makeTestInstance({
749 spawnerLayer,
750 onReady: Ref.set(backendReadyFlag, true).pipe(
751 Effect.andThen(Deferred.succeed(ready, void 0)),
752 Effect.asVoid,
753 ),
754 onShutdown: Ref.set(backendReadyFlag, false).pipe(
755 Effect.andThen(
756 Effect.sync(() => {
757 shutdownCount += 1;
758 }),
759 ),
760 ),
761 backendOutputLog: {
762 persistFailure: () =>
763 Effect.sync(() => {
764 persistedFailureCount += 1;
765 }),
766 discardSession: Effect.sync(() => {
767 discardedSessionCount += 1;
768 }),
769 },
770 desktopTelemetryPublisher: {
771 removeControlSource: () =>
772 Effect.sync(() => {
773 removedTelemetrySources += 1;
774 }),
775 },
776 });
777 assert.isTrue(Option.isNone(yield* instance.currentConfig));
778
779 yield* instance.start;
780 assert.equal(yield* Queue.take(startedPids), 123);
781 yield* Deferred.await(ready);
782 assert.isTrue(yield* Ref.get(backendReadyFlag));
783 assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig));
784
785 const runningSnapshot = yield* instance.snapshot;
786 assert.equal(runningSnapshot.ready, true);
787 assert.deepEqual(runningSnapshot.activePid, Option.some(123));
788
789 const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
790 yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
791 assert.isFalse(yield* Ref.get(backendReadyFlag));
792 assert.equal(shutdownCount, 1);
793 yield* Deferred.succeed(finishTeardown, undefined);
794 yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
795 assert.equal(startCount, 1);
796 assert.equal(closedCount, 1);
797 assert.equal(persistedFailureCount, 0);
798 assert.equal(discardedSessionCount, 1);
799 assert.equal(removedTelemetrySources, 1);
800
801 const stoppedSnapshot = yield* instance.snapshot;
802 assert.isFalse(yield* Ref.get(backendReadyFlag));
803 assert.equal(shutdownCount, 1);
804 assert.equal(stoppedSnapshot.desiredRunning, false);
805 assert.equal(stoppedSnapshot.ready, false);
806 assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
807 }),
808 ),
809 );
810
811 it.effect("restarts when start is requested during stop teardown", () =>
812 Effect.scoped(
813 Effect.gen(function* () {
814 const starts = yield* Queue.unbounded<number>();
815 const teardownStarted = yield* Deferred.make<void>();
816 const finishTeardown = yield* Deferred.make<void>();
817 let startCount = 0;
818
819 const spawnerLayer = Layer.succeed(
820 ChildProcessSpawner.ChildProcessSpawner,
821 ChildProcessSpawner.make(() =>
822 Effect.gen(function* () {
823 const scope = yield* Scope.Scope;
824 const closed = yield* Deferred.make<void>();
825 startCount += 1;
826 yield* Queue.offer(starts, startCount);
827 if (startCount === 1) {
828 yield* Scope.addFinalizer(
829 scope,
830 Deferred.succeed(teardownStarted, undefined).pipe(
831 Effect.andThen(Deferred.await(finishTeardown)),
832 Effect.andThen(Deferred.succeed(closed, undefined)),
833 Effect.asVoid,
834 ),
835 );
836 } else {
837 yield* Scope.addFinalizer(
838 scope,
839 Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
840 );
841 }
842 return makeProcess({
843 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
844 });
845 }),
846 ),
847 );
848
849 const instance = yield* makeTestInstance({
850 spawnerLayer,
851 httpClientLayer: httpClientLayer(() => Effect.never),
852 });
853
854 yield* instance.start;
855 assert.equal(yield* Queue.take(starts), 1);
856
857 const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
858 yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
859 yield* instance.start;
860 assert.equal((yield* instance.snapshot).desiredRunning, true);
861
862 yield* Deferred.succeed(finishTeardown, undefined);
863 yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
864 yield* TestClock.adjust(Duration.millis(500));
865
866 assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
867 const restarted = yield* instance.snapshot;
868 assert.equal(restarted.desiredRunning, true);
869 assert.deepEqual(restarted.activePid, Option.some(123));
870 }).pipe(Effect.provide(TestClock.layer())),
871 ),
872 );
873
874 it.effect("retries config resolution after a start request during stop teardown", () =>
875 Effect.scoped(
876 Effect.gen(function* () {
877 const starts = yield* Queue.unbounded<number>();
878 const teardownStarted = yield* Deferred.make<void>();
879 const finishTeardown = yield* Deferred.make<void>();
880 const configAttempts = yield* Ref.make(0);
881 let startCount = 0;
882
883 const configFailure = PlatformError.systemError({
884 _tag: "Unknown",
885 module: "DesktopBackendManager",
886 method: "configResolve",
887 description: "transient configuration failure",
888 });
889 const spawnerLayer = Layer.succeed(
890 ChildProcessSpawner.ChildProcessSpawner,
891 ChildProcessSpawner.make(() =>
892 Effect.gen(function* () {
893 const scope = yield* Scope.Scope;
894 const closed = yield* Deferred.make<void>();
895 startCount += 1;
896 yield* Queue.offer(starts, startCount);
897 if (startCount === 1) {
898 yield* Scope.addFinalizer(
899 scope,
900 Deferred.succeed(teardownStarted, undefined).pipe(
901 Effect.andThen(Deferred.await(finishTeardown)),
902 Effect.andThen(Deferred.succeed(closed, undefined)),
903 Effect.asVoid,
904 ),
905 );
906 } else {
907 yield* Scope.addFinalizer(
908 scope,
909 Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
910 );
911 }
912 return makeProcess({
913 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
914 });
915 }),
916 ),
917 );
918 const configResolve = Ref.updateAndGet(configAttempts, (attempt) => attempt + 1).pipe(
919 Effect.flatMap((attempt) =>
920 attempt === 2 ? Effect.fail(configFailure) : Effect.succeed(baseConfig),
921 ),
922 );
923 const instance = yield* makeTestInstance({
924 spawnerLayer,
925 configResolve,
926 httpClientLayer: httpClientLayer(() => Effect.never),
927 });
928
929 yield* instance.start;
930 assert.equal(yield* Queue.take(starts), 1);
931
932 const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
933 yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
934 yield* instance.start;
935 yield* Deferred.succeed(finishTeardown, undefined);
936 yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
937
938 const pendingRestart = yield* instance.snapshot;
939 assert.equal(pendingRestart.desiredRunning, true);
940 assert.equal(pendingRestart.restartScheduled, true);
941
942 yield* TestClock.adjust(Duration.seconds(2));
943
944 assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
945 assert.equal(yield* Ref.get(configAttempts), 3);
946 assert.equal((yield* instance.snapshot).desiredRunning, true);
947 }).pipe(Effect.provide(TestClock.layer())),
948 ),
949 );
950
951 it.effect("keeps a timed-out run active until its process exits", () =>
952 Effect.scoped(
953 Effect.gen(function* () {
954 const starts = yield* Queue.unbounded<number>();
955 const teardownStarted = yield* Deferred.make<void>();
956 const finishTeardown = yield* Deferred.make<void>();
957 let startCount = 0;
958
959 const spawnerLayer = Layer.succeed(
960 ChildProcessSpawner.ChildProcessSpawner,
961 ChildProcessSpawner.make(() =>
962 Effect.gen(function* () {
963 const scope = yield* Scope.Scope;
964 const closed = yield* Deferred.make<void>();
965 startCount += 1;
966 yield* Queue.offer(starts, startCount);
967 if (startCount === 1) {
968 yield* Scope.addFinalizer(
969 scope,
970 Deferred.succeed(teardownStarted, undefined).pipe(
971 Effect.andThen(Deferred.await(finishTeardown)),
972 Effect.andThen(Deferred.succeed(closed, undefined)),
973 Effect.asVoid,
974 ),
975 );
976 } else {
977 yield* Scope.addFinalizer(
978 scope,
979 Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
980 );
981 }
982 return makeProcess({
983 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
984 });
985 }),
986 ),
987 );
988
989 const instance = yield* makeTestInstance({
990 spawnerLayer,
991 httpClientLayer: httpClientLayer(() => Effect.never),
992 });
993
994 yield* instance.start;
995 assert.equal(yield* Queue.take(starts), 1);
996
997 const stopFiber = yield* instance
998 .stop({ timeout: Duration.millis(100) })
999 .pipe(Effect.forkChild);
1000 yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
1001 yield* instance.start;
1002 yield* TestClock.adjust(Duration.millis(100));
1003 yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
1004
1005 assert.equal(startCount, 1);
1006 const timedOut = yield* instance.snapshot;
1007 assert.equal(timedOut.desiredRunning, true);
1008 assert.deepEqual(timedOut.activePid, Option.some(123));
1009
1010 yield* Deferred.succeed(finishTeardown, undefined);
1011 yield* TestClock.adjust(Duration.millis(500));
1012
1013 assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
1014 }).pipe(Effect.provide(TestClock.layer())),
1015 ),
1016 );
1017
1018 it.effect("does not notify shutdown before the first start has prior state", () =>
1019 Effect.scoped(
1020 Effect.gen(function* () {
1021 let shutdownCount = 0;
1022 const closed = yield* Deferred.make<void>();
1023 const startedPids = yield* Queue.unbounded<number>();
1024
1025 const spawnerLayer = Layer.succeed(
1026 ChildProcessSpawner.ChildProcessSpawner,
1027 ChildProcessSpawner.make(() =>
1028 Effect.gen(function* () {
1029 yield* Queue.offer(startedPids, 123);
1030 const close = Deferred.succeed(closed, void 0).pipe(Effect.asVoid);
1031 return makeProcess({
1032 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
1033 kill: () => close,
1034 });
1035 }),
1036 ),
1037 );
1038
1039 const instance = yield* makeTestInstance({
1040 spawnerLayer,
1041 httpClientLayer: httpClientLayer(() => Effect.never),
1042 onShutdown: Effect.sync(() => {
1043 shutdownCount += 1;
1044 }),
1045 });
1046
1047 yield* instance.start;
1048 assert.equal(yield* Queue.take(startedPids), 123);
1049 assert.equal(shutdownCount, 0);
1050 }),
1051 ),
1052 );
1053
1054 it.effect("restarts an unexpectedly exited backend with the Effect clock", () =>
1055 Effect.scoped(
1056 Effect.gen(function* () {
1057 const starts = yield* Queue.unbounded<number>();
1058 const failures = yield* Queue.unbounded<string>();
1059 let startCount = 0;
1060
1061 const spawnerLayer = Layer.succeed(
1062 ChildProcessSpawner.ChildProcessSpawner,
1063 ChildProcessSpawner.make(() =>
1064 Effect.sync(() => {
1065 startCount += 1;
1066 return makeProcess({
1067 exitCode: Queue.offer(starts, startCount).pipe(
1068 Effect.as(ChildProcessSpawner.ExitCode(1)),
1069 ),
1070 });
1071 }),
1072 ),
1073 );
1074
1075 const instance = yield* makeTestInstance({
1076 spawnerLayer,
1077 httpClientLayer: httpClientLayer(() => Effect.never),
1078 backendOutputLog: {
1079 persistFailure: ({ details }) => Queue.offer(failures, details).pipe(Effect.asVoid),
1080 },
1081 });
1082
1083 yield* instance.start;
1084
1085 assert.equal(yield* Queue.take(starts), 1);
1086 assert.equal(yield* Queue.take(failures), "pid=123 code=1");
1087
1088 yield* TestClock.adjust(Duration.millis(499));
1089 assert.equal(yield* Queue.size(starts), 0);
1090 yield* TestClock.adjust(Duration.millis(1));
1091 assert.equal(yield* Queue.take(starts), 2);
1092
1093 yield* TestClock.adjust(Duration.millis(999));
1094 assert.equal(yield* Queue.size(starts), 0);
1095 yield* TestClock.adjust(Duration.millis(1));
1096 assert.equal(yield* Queue.take(starts), 3);
1097 }).pipe(Effect.provide(TestClock.layer())),
1098 ),
1099 );
1100
1101 it.effect("does not notify shutdown when a scheduled restart starts from non-ready state", () =>
1102 Effect.scoped(
1103 Effect.gen(function* () {
1104 let shutdownCount = 0;
1105
1106 const spawnerLayer = Layer.succeed(
1107 ChildProcessSpawner.ChildProcessSpawner,
1108 ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
1109 );
1110
1111 const instance = yield* makeTestInstance({
1112 spawnerLayer,
1113 config: {
1114 ...baseConfig,
1115 preflightFailure: Option.some({ reason: "preflight failed", fatal: false }),
1116 },
1117 onShutdown: Effect.sync(() => {
1118 shutdownCount += 1;
1119 }),
1120 });
1121
1122 yield* instance.start;
1123 assert.equal(shutdownCount, 0);
1124
1125 yield* TestClock.adjust(Duration.millis(500));
1126 assert.equal(shutdownCount, 0);
1127 }).pipe(Effect.provide(TestClock.layer())),
1128 ),
1129 );
1130
1131 it.effect("surfaces a fatal preflight failure once and stops looping after the cap", () =>
1132 Effect.scoped(
1133 Effect.gen(function* () {
1134 const failures: string[] = [];
1135 const spawnerLayer = Layer.succeed(
1136 ChildProcessSpawner.ChildProcessSpawner,
1137 ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
1138 );
1139
1140 const instance = yield* makeTestInstance({
1141 spawnerLayer,
1142 config: {
1143 ...baseConfig,
1144 preflightFailure: Option.some({ reason: "Node.js not found", fatal: true }),
1145 },
1146 onPreflightFailed: (failure) =>
1147 Effect.sync(() => {
1148 failures.push(failure.reason);
1149 }).pipe(Effect.as(false)),
1150 });
1151
1152 yield* instance.start;
1153 assert.deepEqual(failures, []);
1154
1155 // Five fatal attempts with exponential backoff (500ms, 1s, 2s, 4s) reach
1156 // the cap, at which point the failure is surfaced exactly once.
1157 yield* TestClock.adjust(Duration.millis(500));
1158 yield* TestClock.adjust(Duration.seconds(1));
1159 yield* TestClock.adjust(Duration.seconds(2));
1160 yield* TestClock.adjust(Duration.seconds(4));
1161 assert.deepEqual(failures, ["Node.js not found"]);
1162
1163 // Past the cap the loop stops and nothing else is surfaced.
1164 yield* TestClock.adjust(Duration.seconds(8));
1165 yield* TestClock.adjust(Duration.seconds(30));
1166 assert.deepEqual(failures, ["Node.js not found"]);
1167 }).pipe(Effect.provide(TestClock.layer())),
1168 ),
1169 );
1170
1171 it.effect("can be started again after a fatal preflight cap once config recovers", () =>
1172 Effect.scoped(
1173 Effect.gen(function* () {
1174 const failing = yield* Ref.make(true);
1175 const starts = yield* Queue.unbounded<number>();
1176 const spawnerLayer = Layer.succeed(
1177 ChildProcessSpawner.ChildProcessSpawner,
1178 ChildProcessSpawner.make(() =>
1179 Queue.offer(starts, 123).pipe(
1180 Effect.as(
1181 makeProcess({
1182 exitCode: Effect.never,
1183 }),
1184 ),
1185 ),
1186 ),
1187 );
1188
1189 const instance = yield* makeTestInstance({
1190 spawnerLayer,
1191 configResolve: Ref.get(failing).pipe(
1192 Effect.map((isFailing) =>
1193 isFailing
1194 ? {
1195 ...baseConfig,
1196 preflightFailure: Option.some({
1197 reason: "Node.js not found",
1198 fatal: true,
1199 }),
1200 }
1201 : baseConfig,
1202 ),
1203 ),
1204 });
1205
1206 yield* instance.start;
1207 yield* TestClock.adjust(Duration.millis(500));
1208 yield* TestClock.adjust(Duration.seconds(1));
1209 yield* TestClock.adjust(Duration.seconds(2));
1210 yield* TestClock.adjust(Duration.seconds(4));
1211 yield* TestClock.adjust(Duration.seconds(8));
1212
1213 const parked = yield* instance.snapshot;
1214 assert.equal(parked.desiredRunning, false);
1215 assert.equal(parked.ready, false);
1216 assert.isTrue(Option.isNone(parked.activePid));
1217 assert.equal(parked.restartScheduled, false);
1218 assert.equal(yield* Queue.size(starts), 0);
1219
1220 yield* Ref.set(failing, false);
1221 yield* instance.start;
1222
1223 assert.equal(yield* Queue.take(starts), 123);
1224 const running = yield* instance.snapshot;
1225 assert.equal(running.desiredRunning, true);
1226 assert.deepEqual(running.activePid, Option.some(123));
1227 }).pipe(Effect.provide(TestClock.layer())),
1228 ),
1229 );
1230
1231 it.effect("keeps retrying a transient (non-fatal) preflight failure without surfacing", () =>
1232 Effect.scoped(
1233 Effect.gen(function* () {
1234 const failures: string[] = [];
1235 const spawnerLayer = Layer.succeed(
1236 ChildProcessSpawner.ChildProcessSpawner,
1237 ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
1238 );
1239
1240 const instance = yield* makeTestInstance({
1241 spawnerLayer,
1242 config: {
1243 ...baseConfig,
1244 preflightFailure: Option.some({ reason: "wslpath conversion failed", fatal: false }),
1245 },
1246 onPreflightFailed: (failure) =>
1247 Effect.sync(() => {
1248 failures.push(failure.reason);
1249 }).pipe(Effect.as(false)),
1250 });
1251
1252 yield* instance.start;
1253 // Well beyond the fatal cap's worth of time: a transient failure must
1254 // keep retrying (self-heal) and never surface.
1255 yield* TestClock.adjust(Duration.minutes(2));
1256 assert.deepEqual(failures, []);
1257 }).pipe(Effect.provide(TestClock.layer())),
1258 ),
1259 );
1260
1261 it.effect("surfaces a bounded transient preflight failure after its retry limit", () =>
1262 Effect.scoped(
1263 Effect.gen(function* () {
1264 const failures: string[] = [];
1265 const spawnerLayer = Layer.succeed(
1266 ChildProcessSpawner.ChildProcessSpawner,
1267 ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
1268 );
1269
1270 const instance = yield* makeTestInstance({
1271 spawnerLayer,
1272 config: {
1273 ...baseConfig,
1274 preflightFailure: Option.some({
1275 reason: "WSL toolchain probe timed out",
1276 fatal: false,
1277 retryLimit: 3,
1278 }),
1279 },
1280 onPreflightFailed: (failure) =>
1281 Effect.sync(() => {
1282 failures.push(failure.reason);
1283 }).pipe(Effect.as(false)),
1284 });
1285
1286 yield* instance.start;
1287 yield* TestClock.adjust(Duration.millis(500));
1288 assert.deepEqual(failures, []);
1289
1290 yield* TestClock.adjust(Duration.seconds(1));
1291 assert.deepEqual(failures, ["WSL toolchain probe timed out"]);
1292 }).pipe(Effect.provide(TestClock.layer())),
1293 ),
1294 );
1295
1296 it.effect("cancels a scheduled restart when start is requested manually", () =>
1297 Effect.scoped(
1298 Effect.gen(function* () {
1299 const starts = yield* Queue.unbounded<number>();
1300 const secondClosed = yield* Deferred.make<void>();
1301 let startCount = 0;
1302
1303 const spawnerLayer = Layer.succeed(
1304 ChildProcessSpawner.ChildProcessSpawner,
1305 ChildProcessSpawner.make(() =>
1306 Effect.gen(function* () {
1307 startCount += 1;
1308 yield* Queue.offer(starts, startCount);
1309
1310 if (startCount === 1) {
1311 return makeProcess({
1312 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
1313 });
1314 }
1315
1316 const scope = yield* Scope.Scope;
1317 const close = Deferred.succeed(secondClosed, void 0).pipe(Effect.asVoid);
1318 yield* Scope.addFinalizer(scope, close);
1319 return makeProcess({
1320 exitCode: Deferred.await(secondClosed).pipe(
1321 Effect.as(ChildProcessSpawner.ExitCode(0)),
1322 ),
1323 kill: () => close,
1324 });
1325 }),
1326 ),
1327 );
1328
1329 const instance = yield* makeTestInstance({
1330 spawnerLayer,
1331 httpClientLayer: httpClientLayer(() => Effect.never),
1332 });
1333
1334 yield* instance.start;
1335
1336 assert.equal(yield* Queue.take(starts), 1);
1337 let restartScheduled = false;
1338 while (!restartScheduled) {
1339 restartScheduled = (yield* instance.snapshot).restartScheduled;
1340 if (!restartScheduled) {
1341 yield* Effect.yieldNow;
1342 }
1343 }
1344
1345 yield* instance.start;
1346 assert.equal(yield* Queue.take(starts), 2);
1347
1348 yield* instance.stop();
1349 yield* TestClock.adjust(Duration.millis(500));
1350
1351 assert.equal(yield* Queue.size(starts), 0);
1352 }).pipe(Effect.provide(TestClock.layer())),
1353 ),
1354 );
1355
1356 it.effect("does not restart after stop cancels a scheduled restart", () =>
1357 Effect.scoped(
1358 Effect.gen(function* () {
1359 const starts = yield* Queue.unbounded<number>();
1360 let startCount = 0;
1361
1362 const spawnerLayer = Layer.succeed(
1363 ChildProcessSpawner.ChildProcessSpawner,
1364 ChildProcessSpawner.make(() =>
1365 Effect.sync(() => {
1366 startCount += 1;
1367 return makeProcess({
1368 exitCode: Queue.offer(starts, startCount).pipe(
1369 Effect.as(ChildProcessSpawner.ExitCode(1)),
1370 ),
1371 });
1372 }),
1373 ),
1374 );
1375
1376 const instance = yield* makeTestInstance({
1377 spawnerLayer,
1378 httpClientLayer: httpClientLayer(() => Effect.never),
1379 });
1380
1381 yield* instance.start;
1382 assert.equal(yield* Queue.take(starts), 1);
1383
1384 let restartScheduled = false;
1385 while (!restartScheduled) {
1386 restartScheduled = (yield* instance.snapshot).restartScheduled;
1387 if (!restartScheduled) {
1388 yield* Effect.yieldNow;
1389 }
1390 }
1391
1392 yield* instance.stop();
1393 yield* TestClock.adjust(Duration.millis(500));
1394
1395 assert.equal(yield* Queue.size(starts), 0);
1396 assert.equal((yield* instance.snapshot).desiredRunning, false);
1397 }).pipe(Effect.provide(TestClock.layer())),
1398 ),
1399 );
1400});