Open History to see the last commit
1import {
2 SERVER_EXIT_CODE_MANAGED_POLICY,
3 SERVER_EXIT_CODE_STATE_DIR_OWNED,
4 DesktopBackendBootstrap,
5 type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
6 DesktopTelemetryControlMessage,
7} from "@t3tools/contracts";
8import { assert, describe, it } from "@effect/vitest";
9import * as Deferred from "effect/Deferred";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Fiber from "effect/Fiber";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as PlatformError from "effect/PlatformError";
17import * as Queue from "effect/Queue";
18import * as Ref from "effect/Ref";
19import * as Schema from "effect/Schema";
20import * as Sink from "effect/Sink";
21import * as Scope from "effect/Scope";
22import * as Stream from "effect/Stream";
23import * as TestClock from "effect/testing/TestClock";
24import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
25import { ChildProcess, ChildProcessSpawner } from "effect/process";
26
27import * as DesktopBackendManager from "./DesktopBackendManager.ts";
28import * as DesktopObservability from "../app/DesktopObservability.ts";
29import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
30import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
31import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
32
33const decodeDesktopBackendBootstrap = Schema.decodeEffect(
34 Schema.fromJsonString(DesktopBackendBootstrap),
35);
36const encodeDesktopTelemetryControl = Schema.encodeSync(
37 Schema.fromJsonString(DesktopTelemetryControlMessage),
38);
39
40const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
41 executablePath: "/electron",
42 args: ["/server/bin.mjs", "--bootstrap-fd", "3"],
43 entryPath: "/server/bin.mjs",
44 cwd: "/server",
45 env: { ELECTRON_RUN_AS_NODE: "1" },
46 bootstrap: {
47 mode: "desktop",
48 noBrowser: true,
49 port: 3773,
50 t3Home: "/tmp/t3",
51 host: "127.0.0.1",
52 desktopBootstrapToken: "token",
53 tailscaleServeEnabled: false,
54 tailscaleServePort: 443,
55 desktopTelemetryFd: 4,
56 desktopTelemetryControlFd: 5,
57 },
58 bootstrapDelivery: "fd3",
59 extendEnv: true,
60 httpBaseUrl: new URL("http://127.0.0.1:3773"),
61 captureOutput: true,
62 preflightFailure: Option.none(),
63};
64
65const configWithObservability: DesktopBackendBootstrapValue = {
66 ...baseConfig.bootstrap,
67 tailscaleServeEnabled: true,
68 desktopTelemetryFd: 4,
69 otlpTracesUrl: "http://127.0.0.1:4318/v1/traces",
70};
71
72function makeProcess(options?: {
73 readonly stdout?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
74 readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
75 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
76 readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
77 readonly getOutputFd?: ChildProcessSpawner.ChildProcessHandle["getOutputFd"];
78}): ChildProcessSpawner.ChildProcessHandle {
79 return ChildProcessSpawner.makeHandle({
80 pid: ChildProcessSpawner.ProcessId(123),
81 stdout: options?.stdout ?? Stream.empty,
82 stderr: options?.stderr ?? Stream.empty,
83 all: Stream.merge(options?.stdout ?? Stream.empty, options?.stderr ?? Stream.empty),
84 exitCode: options?.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(0)),
85 isRunning: Effect.succeed(false),
86 kill: options?.kill ?? (() => Effect.void),
87 stdin: Sink.drain,
88 getInputFd: () => Sink.drain,
89 getOutputFd: options?.getOutputFd ?? (() => Stream.empty),
90 unref: Effect.succeed(Effect.void),
91 });
92}
93
94function responseForRequest(
95 request: HttpClientRequest.HttpClientRequest,
96 status: number,
97): HttpClientResponse.HttpClientResponse {
98 return HttpClientResponse.fromWeb(request, new Response(null, { status }));
99}
100
101function layerHttpClient(
102 handler: (
103 request: HttpClientRequest.HttpClientRequest,
104 ) => Effect.Effect<HttpClientResponse.HttpClientResponse>,
105) {
106 return Layer.succeed(
107 HttpClient.HttpClient,
108 HttpClient.make((request) => handler(request)),
109 );
110}
111
112const layerHealthyHttpClient = layerHttpClient((request) =>
113 Effect.succeed(responseForRequest(request, 200)),
114);
115
116function decodeBootstrap(raw: string) {
117 return decodeDesktopBackendBootstrap(raw);
118}
119
120interface MakeInstanceInput {
121 readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
122 readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
123 readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
124 readonly onReady?: Effect.Effect<void>;
125 readonly onShutdown?: Effect.Effect<void>;
126 readonly onStateDirOwned?: Effect.Effect<void>;
127 readonly onStartupFailure?: (
128 failure: DesktopBackendManager.BackendStartupFailure,
129 ) => Effect.Effect<void>;
130 readonly onPreflightFailed?: (
131 failure: DesktopBackendManager.PreflightFailure,
132 ) => Effect.Effect<boolean>;
133 readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
134 readonly configResolve?: Effect.Effect<
135 DesktopBackendManager.DesktopBackendStartConfig,
136 PlatformError.PlatformError
137 >;
138 readonly desktopTelemetryStream?: Stream.Stream<Uint8Array>;
139 readonly desktopTelemetryPublisher?: Partial<
140 DesktopTelemetryPublisher.DesktopTelemetryPublisher["Service"]
141 >;
142 readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
143}
144
145function makeTestInstance(input: MakeInstanceInput) {
146 const stubLog: DesktopObservability.DesktopBackendOutputLogShape = {
147 beginSession: () => Effect.void,
148 writeOutputChunk: () => Effect.void,
149 persistFailureSnapshot: () => Effect.void,
150 persistFailure: () => Effect.void,
151 discardSession: Effect.void,
152 ...input.backendOutputLog,
153 };
154 const layerServices = Layer.mergeAll(
155 FileSystem.layerNoop({
156 exists: () => Effect.succeed(true),
157 }),
158 input.spawnerLayer,
159 input.httpClientLayer ?? layerHealthyHttpClient,
160 Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
161 forInstance: () => Effect.succeed(stubLog),
162 } satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
163 Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
164 latest: Effect.succeedNone,
165 changes: Stream.empty,
166 encoded: input.desktopTelemetryStream ?? Stream.empty,
167 handleControlForSource: () => Effect.void,
168 removeControlSource: () => Effect.void,
169 publishUpdateReport: () => Effect.void,
170 updateRequests: Stream.empty,
171 updateCommits: Stream.empty,
172 updateCancellations: Stream.empty,
173 ...input.desktopTelemetryPublisher,
174 }),
175 DesktopBrowserHost.layer,
176 DesktopWslEnvironment.layerTest(
177 input.pruneRuntimes === undefined ? {} : { pruneRuntimes: input.pruneRuntimes },
178 ),
179 );
180
181 const instance = DesktopBackendManager.makeBackendInstance({
182 id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
183 label: Effect.succeed("Windows"),
184 configResolve: input.configResolve ?? Effect.succeed(input.config ?? baseConfig),
185 ...(input.onReady ? { onReady: () => input.onReady! } : {}),
186 ...(input.onShutdown ? { onShutdown: () => input.onShutdown! } : {}),
187 ...(input.onStateDirOwned ? { onStateDirOwned: () => input.onStateDirOwned! } : {}),
188 ...(input.onPreflightFailed ? { onPreflightFailed: input.onPreflightFailed } : {}),
189 ...(input.onStartupFailure ? { onStartupFailure: input.onStartupFailure } : {}),
190 });
191
192 return instance.pipe(Effect.provide(layerServices));
193}
194
195describe("DesktopBackendManager", () => {
196 it.effect("notifies readiness waiters on HTTP readiness and stop without clock advancement", () =>
197 Effect.scoped(
198 Effect.gen(function* () {
199 const probe = yield* Deferred.make<void>();
200 const ready = yield* Deferred.make<void>();
201 const exit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
202 const instance = yield* makeTestInstance({
203 spawnerLayer: Layer.succeed(
204 ChildProcessSpawner.ChildProcessSpawner,
205 ChildProcessSpawner.make(() =>
206 Effect.acquireRelease(
207 Effect.succeed(
208 makeProcess({
209 exitCode: Deferred.await(exit),
210 kill: () =>
211 Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid),
212 }),
213 ),
214 () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)),
215 ),
216 ),
217 ),
218 httpClientLayer: Layer.succeed(
219 HttpClient.HttpClient,
220 HttpClient.make((request) =>
221 Deferred.succeed(probe, undefined).pipe(
222 Effect.andThen(Deferred.await(ready)),
223 Effect.as(HttpClientResponse.fromWeb(request, new Response("{}"))),
224 ),
225 ),
226 ),
227 });
228 yield* instance.start;
229 yield* Deferred.await(probe);
230 const waiter = yield* instance.waitForReady(Duration.seconds(15)).pipe(Effect.forkChild);
231 yield* Deferred.succeed(ready, undefined);
232 assert.isTrue(yield* Fiber.join(waiter));
233 yield* instance.stop();
234 assert.isFalse(yield* instance.waitForReady(Duration.seconds(15)));
235 }),
236 ),
237 );
238
239 it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () =>
240 Effect.scoped(
241 Effect.gen(function* () {
242 let spawnedCommand: ChildProcess.Command | undefined;
243 let bootstrapJson = "";
244 let telemetryJson = "";
245 let readyCount = 0;
246 const ready = yield* Deferred.make<void>();
247 const exited = yield* Queue.unbounded<void>();
248
249 const layerSpawner = Layer.succeed(
250 ChildProcessSpawner.ChildProcessSpawner,
251 ChildProcessSpawner.make((command) =>
252 Effect.gen(function* () {
253 spawnedCommand = command;
254 if (command._tag === "StandardCommand") {
255 const fd3 = command.options.additionalFds?.fd3;
256 if (fd3?.type === "input" && fd3.stream) {
257 bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
258 }
259 const fd4 = command.options.additionalFds?.fd4;
260 if (fd4?.type === "input" && fd4.stream) {
261 telemetryJson = yield* fd4.stream.pipe(Stream.decodeText(), Stream.mkString);
262 }
263 }
264
265 return makeProcess({
266 exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
267 });
268 }),
269 ),
270 );
271
272 const instance = yield* makeTestInstance({
273 config: {
274 ...baseConfig,
275 bootstrap: configWithObservability,
276 },
277 spawnerLayer: layerSpawner,
278 desktopTelemetryStream: Stream.encodeText(
279 Stream.make('{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n'),
280 ),
281 onReady: Effect.sync(() => {
282 readyCount += 1;
283 }).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
284 backendOutputLog: {
285 persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
286 },
287 });
288
289 yield* instance.start;
290 yield* Queue.take(exited);
291
292 assert.equal(readyCount, 1);
293 assert.isDefined(spawnedCommand);
294 if (spawnedCommand._tag !== "StandardCommand") {
295 throw new Error("Expected backend to spawn a standard command.");
296 }
297
298 assert.equal(spawnedCommand.command, "/electron");
299 assert.deepEqual(spawnedCommand.args, ["/server/bin.mjs", "--bootstrap-fd", "3"]);
300 assert.equal(spawnedCommand.options.cwd, "/server");
301 assert.equal(spawnedCommand.options.extendEnv, true);
302 assert.equal(spawnedCommand.options.stdout, "pipe");
303 assert.equal(spawnedCommand.options.stderr, "pipe");
304 assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
305 assert.isDefined(spawnedCommand.options.forceKillAfter);
306 assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input");
307 assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
308 assert.equal(
309 Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
310 5_000,
311 );
312
313 assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
314 assert.equal(
315 telemetryJson,
316 '{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n',
317 );
318 }),
319 ),
320 );
321
322 it.effect("reports a SIGKILL exit without an exit code", () =>
323 Effect.gen(function* () {
324 const exitCause = PlatformError.systemError({
325 _tag: "Unknown",
326 module: "ChildProcess",
327 method: "exitCode",
328 cause: new Error("Process interrupted due to receipt of signal: 'SIGKILL'"),
329 });
330 const layerSpawner = Layer.succeed(
331 ChildProcessSpawner.ChildProcessSpawner,
332 ChildProcessSpawner.make(() =>
333 Effect.succeed(makeProcess({ exitCode: Effect.fail(exitCause) })),
334 ),
335 );
336
337 const exit = yield* DesktopBackendManager.runBackendProcess({
338 ...baseConfig,
339 desktopTelemetryStream: Stream.empty,
340 }).pipe(Effect.scoped, Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient)));
341
342 assert.deepEqual(exit, { code: Option.none(), reason: "killed by SIGKILL" });
343 }),
344 );
345
346 it.effect("reports child exit before waiting for trailing output to drain", () =>
347 Effect.scoped(
348 Effect.gen(function* () {
349 const exitObserved = yield* Deferred.make<void>();
350 const finishOutputDrain = yield* Deferred.make<void>();
351 const layerSpawner = Layer.succeed(
352 ChildProcessSpawner.ChildProcessSpawner,
353 ChildProcessSpawner.make(() =>
354 Effect.succeed(
355 makeProcess({
356 stdout: Stream.fromEffect(
357 Deferred.await(finishOutputDrain).pipe(
358 Effect.as(new TextEncoder().encode("trailing output\n")),
359 ),
360 ),
361 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
362 }),
363 ),
364 ),
365 );
366
367 const runFiber = yield* DesktopBackendManager.runBackendProcess({
368 ...baseConfig,
369 desktopTelemetryStream: Stream.empty,
370 onExitObserved: () => Deferred.succeed(exitObserved, void 0).pipe(Effect.asVoid),
371 }).pipe(
372 Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient)),
373 Effect.forkChild,
374 );
375
376 yield* Deferred.await(exitObserved);
377 assert.isUndefined(runFiber.pollUnsafe());
378
379 yield* Deferred.succeed(finishOutputDrain, void 0);
380 assert.equal((yield* Fiber.join(runFiber)).code.pipe(Option.getOrUndefined), 1);
381 }),
382 ),
383 );
384
385 it.effect("continues routing desktop telemetry control messages after an invalid line", () =>
386 Effect.scoped(
387 Effect.gen(function* () {
388 const handled = yield* Deferred.make<boolean>();
389 const controlMessage = encodeDesktopTelemetryControl({
390 version: 1,
391 type: "setDiagnosticsDemand",
392 enabled: true,
393 });
394 const layerSpawner = Layer.succeed(
395 ChildProcessSpawner.ChildProcessSpawner,
396 ChildProcessSpawner.make(() =>
397 Effect.succeed(
398 makeProcess({
399 getOutputFd: (fd) =>
400 fd === 5
401 ? Stream.encodeText(Stream.make(`not-json\n${controlMessage}\n`))
402 : Stream.empty,
403 exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
404 }),
405 ),
406 ),
407 );
408 const instance = yield* makeTestInstance({
409 spawnerLayer: layerSpawner,
410 desktopTelemetryPublisher: {
411 handleControlForSource: (_sourceId, message) =>
412 message.type === "setDiagnosticsDemand"
413 ? Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid)
414 : Effect.void,
415 },
416 });
417
418 yield* instance.start;
419 assert.isTrue(yield* Deferred.await(handled));
420 }),
421 ),
422 );
423
424 it.effect("starts the configured backend and closes the scoped process on stop", () =>
425 Effect.scoped(
426 Effect.gen(function* () {
427 let startCount = 0;
428 let closedCount = 0;
429 const closed = yield* Deferred.make<void>();
430 const teardownStarted = yield* Deferred.make<void>();
431 const finishTeardown = yield* Deferred.make<void>();
432 const startedPids = yield* Queue.unbounded<number>();
433 const ready = yield* Deferred.make<void>();
434 const backendReadyFlag = yield* Ref.make(false);
435 let shutdownCount = 0;
436 let persistedFailureCount = 0;
437 let discardedSessionCount = 0;
438 let removedTelemetrySources = 0;
439
440 const layerSpawner = Layer.succeed(
441 ChildProcessSpawner.ChildProcessSpawner,
442 ChildProcessSpawner.make(() =>
443 Effect.gen(function* () {
444 const scope = yield* Scope.Scope;
445 startCount += 1;
446 yield* Queue.offer(startedPids, 123);
447 const close = Deferred.succeed(teardownStarted, undefined).pipe(
448 Effect.andThen(Deferred.await(finishTeardown)),
449 Effect.andThen(
450 Effect.sync(() => {
451 closedCount += 1;
452 }),
453 ),
454 Effect.andThen(Deferred.succeed(closed, void 0)),
455 Effect.asVoid,
456 );
457
458 yield* Scope.addFinalizer(scope, close);
459
460 return makeProcess({
461 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
462 kill: () => close,
463 });
464 }),
465 ),
466 );
467
468 const instance = yield* makeTestInstance({
469 spawnerLayer: layerSpawner,
470 onReady: Ref.set(backendReadyFlag, true).pipe(
471 Effect.andThen(Deferred.succeed(ready, void 0)),
472 Effect.asVoid,
473 ),
474 onShutdown: Ref.set(backendReadyFlag, false).pipe(
475 Effect.andThen(
476 Effect.sync(() => {
477 shutdownCount += 1;
478 }),
479 ),
480 ),
481 backendOutputLog: {
482 persistFailure: () =>
483 Effect.sync(() => {
484 persistedFailureCount += 1;
485 }),
486 discardSession: Effect.sync(() => {
487 discardedSessionCount += 1;
488 }),
489 },
490 desktopTelemetryPublisher: {
491 removeControlSource: () =>
492 Effect.sync(() => {
493 removedTelemetrySources += 1;
494 }),
495 },
496 });
497 assert.isTrue(Option.isNone(yield* instance.currentConfig));
498
499 yield* instance.start;
500 assert.equal(yield* Queue.take(startedPids), 123);
501 yield* Deferred.await(ready);
502 assert.isTrue(yield* Ref.get(backendReadyFlag));
503 assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig));
504
505 const runningSnapshot = yield* instance.snapshot;
506 assert.equal(runningSnapshot.ready, true);
507 assert.deepEqual(runningSnapshot.activePid, Option.some(123));
508
509 const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
510 yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
511 assert.isFalse(yield* Ref.get(backendReadyFlag));
512 assert.equal(shutdownCount, 1);
513 yield* Deferred.succeed(finishTeardown, undefined);
514 yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
515 assert.equal(startCount, 1);
516 assert.equal(closedCount, 1);
517 assert.equal(persistedFailureCount, 0);
518 assert.equal(discardedSessionCount, 1);
519 assert.equal(removedTelemetrySources, 1);
520
521 const stoppedSnapshot = yield* instance.snapshot;
522 assert.isFalse(yield* Ref.get(backendReadyFlag));
523 assert.equal(shutdownCount, 1);
524 assert.equal(stoppedSnapshot.desiredRunning, false);
525 assert.equal(stoppedSnapshot.ready, false);
526 assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
527 }),
528 ),
529 );
530
531 it.effect("restarts when start is requested during stop teardown", () =>
532 Effect.scoped(
533 Effect.gen(function* () {
534 const starts = yield* Queue.unbounded<number>();
535 const teardownStarted = yield* Deferred.make<void>();
536 const finishTeardown = yield* Deferred.make<void>();
537 let startCount = 0;
538
539 const layerSpawner = Layer.succeed(
540 ChildProcessSpawner.ChildProcessSpawner,
541 ChildProcessSpawner.make(() =>
542 Effect.gen(function* () {
543 const scope = yield* Scope.Scope;
544 const closed = yield* Deferred.make<void>();
545 startCount += 1;
546 yield* Queue.offer(starts, startCount);
547 if (startCount === 1) {
548 yield* Scope.addFinalizer(
549 scope,
550 Deferred.succeed(teardownStarted, undefined).pipe(
551 Effect.andThen(Deferred.await(finishTeardown)),
552 Effect.andThen(Deferred.succeed(closed, undefined)),
553 Effect.asVoid,
554 ),
555 );
556 } else {
557 yield* Scope.addFinalizer(
558 scope,
559 Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
560 );
561 }
562 return makeProcess({
563 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
564 });
565 }),
566 ),
567 );
568
569 const instance = yield* makeTestInstance({
570 spawnerLayer: layerSpawner,
571 httpClientLayer: layerHttpClient(() => Effect.never),
572 });
573
574 yield* instance.start;
575 assert.equal(yield* Queue.take(starts), 1);
576
577 const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
578 yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
579 yield* instance.start;
580 assert.equal((yield* instance.snapshot).desiredRunning, true);
581
582 yield* Deferred.succeed(finishTeardown, undefined);
583 yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
584 yield* TestClock.adjust(Duration.millis(500));
585
586 assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
587 const restarted = yield* instance.snapshot;
588 assert.equal(restarted.desiredRunning, true);
589 assert.deepEqual(restarted.activePid, Option.some(123));
590 }).pipe(Effect.provide(TestClock.layer())),
591 ),
592 );
593
594 it.effect("reports state-directory ownership once without scheduling another backend", () =>
595 Effect.scoped(
596 Effect.gen(function* () {
597 let startCount = 0;
598 const refused = yield* Deferred.make<void>();
599 const instance = yield* makeTestInstance({
600 spawnerLayer: Layer.succeed(
601 ChildProcessSpawner.ChildProcessSpawner,
602 ChildProcessSpawner.make(() =>
603 Effect.sync(() => {
604 startCount += 1;
605 return makeProcess({
606 exitCode: Effect.succeed(
607 ChildProcessSpawner.ExitCode(SERVER_EXIT_CODE_STATE_DIR_OWNED),
608 ),
609 });
610 }),
611 ),
612 ),
613 httpClientLayer: layerHttpClient(() => Effect.never),
614 onStateDirOwned: Deferred.succeed(refused, undefined).pipe(Effect.asVoid),
615 });
616 yield* instance.start;
617 yield* Deferred.await(refused);
618 const snapshot = yield* instance.snapshot;
619 assert.isFalse(snapshot.desiredRunning);
620 assert.isFalse(snapshot.restartScheduled);
621 yield* TestClock.adjust(Duration.minutes(1));
622 assert.equal(startCount, 1);
623 }).pipe(Effect.provide(TestClock.layer())),
624 ),
625 );
626
627 // A policy refusal is reported on the first exit, since retrying cannot fix it.
628 it.effect.each([
629 { code: 1, exits: 3, managedPolicy: false },
630 { code: SERVER_EXIT_CODE_MANAGED_POLICY, exits: 1, managedPolicy: true },
631 ])(
632 "reports exit $code with the server output after $exits exits",
633 ({ code, exits, managedPolicy }) =>
634 Effect.scoped(
635 Effect.gen(function* () {
636 const message = "Error: Cannot find module 'zod/v4' in /Users/René";
637 let exitCount = 0;
638 const firstExit = yield* Deferred.make<void>();
639 const reports = yield* Queue.unbounded<{
640 readonly exitCount: number;
641 readonly failure: DesktopBackendManager.BackendStartupFailure;
642 }>();
643 const instance = yield* makeTestInstance({
644 spawnerLayer: Layer.succeed(
645 ChildProcessSpawner.ChildProcessSpawner,
646 ChildProcessSpawner.make(() =>
647 Effect.succeed(
648 makeProcess({
649 // "é" split across chunks must not decode as U+FFFD, and the 4,000-char cut
650 // lands inside the emoji's surrogate pair.
651 stderr: Stream.make(
652 new TextEncoder().encode(
653 `😀${"x".repeat(3_999 - message.length)}${message.slice(0, -1)}`,
654 ),
655 new Uint8Array([0xc3]),
656 new Uint8Array([0xa9]),
657 ),
658 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(code)),
659 }),
660 ),
661 ),
662 ),
663 httpClientLayer: layerHttpClient(() => Effect.never),
664 backendOutputLog: {
665 persistFailure: () => {
666 exitCount += 1;
667 return Deferred.succeed(firstExit, undefined).pipe(Effect.asVoid);
668 },
669 },
670 onStartupFailure: (failure) =>
671 Queue.offer(reports, { exitCount, failure }).pipe(Effect.asVoid),
672 });
673 yield* instance.start;
674 yield* Deferred.await(firstExit);
675 yield* TestClock.adjust(Duration.minutes(1));
676 const { exitCount: exitsWhenReported, failure } = yield* Queue.take(reports);
677 assert.equal(exitsWhenReported, exits);
678 assert.equal(failure.reason, `The server could not start (code=${code}).`);
679 assert.equal(failure.managedPolicy, managedPolicy);
680 assert.isTrue(failure.output.endsWith(message));
681 assert.isTrue(failure.output.isWellFormed());
682 }).pipe(Effect.provide(TestClock.layer())),
683 ),
684 );
685
686 it.effect("waits out a slow startup and reports one that never becomes ready", () =>
687 Effect.scoped(
688 Effect.gen(function* () {
689 const reports = yield* Queue.unbounded<DesktopBackendManager.BackendStartupFailure>();
690 const startInstance = (status: Ref.Ref<number>, onReady?: Effect.Effect<void>) =>
691 makeTestInstance({
692 spawnerLayer: Layer.succeed(
693 ChildProcessSpawner.ChildProcessSpawner,
694 ChildProcessSpawner.make(() =>
695 Effect.succeed(makeProcess({ exitCode: Effect.never })),
696 ),
697 ),
698 httpClientLayer: layerHttpClient((request) =>
699 Ref.get(status).pipe(Effect.map((code) => responseForRequest(request, code))),
700 ),
701 onStartupFailure: (failure) => Queue.offer(reports, failure).pipe(Effect.asVoid),
702 ...(onReady ? { onReady } : {}),
703 }).pipe(Effect.tap((instance) => instance.start));
704
705 const slowStatus = yield* Ref.make(503);
706 const ready = yield* Deferred.make<void>();
707 yield* startInstance(slowStatus, Deferred.succeed(ready, undefined).pipe(Effect.asVoid));
708 yield* TestClock.adjust(Duration.seconds(66));
709 yield* Ref.set(slowStatus, 200);
710 yield* TestClock.adjust(Duration.millis(100));
711 yield* Deferred.await(ready);
712 assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
713
714 yield* startInstance(yield* Ref.make(503));
715 yield* TestClock.adjust(Duration.seconds(179));
716 assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
717 yield* TestClock.adjust(Duration.seconds(1));
718 const failure = yield* Queue.take(reports);
719 assert.equal(failure.reason, "The server started but did not become ready in time.");
720 }).pipe(Effect.provide(TestClock.layer())),
721 ),
722 );
723
724 it.effect("the quit stop deadline waits for a backend that only exits at the force kill", () =>
725 Effect.scoped(
726 Effect.gen(function* () {
727 const spawned = yield* Deferred.make<void>();
728 const teardownStarted = yield* Deferred.make<void>();
729 const teardownFinished = yield* Deferred.make<void>();
730 // The real spawner sends SIGTERM, waits the grace, then SIGKILLs. A backend that
731 // ignores SIGTERM therefore finishes tearing down just after the grace.
732 const instance = yield* makeTestInstance({
733 spawnerLayer: Layer.succeed(
734 ChildProcessSpawner.ChildProcessSpawner,
735 ChildProcessSpawner.make(() =>
736 Effect.gen(function* () {
737 const scope = yield* Scope.Scope;
738 yield* Deferred.succeed(spawned, undefined);
739 yield* Scope.addFinalizer(
740 scope,
741 Deferred.succeed(teardownStarted, undefined).pipe(
742 Effect.andThen(Effect.sleep(Duration.seconds(6))),
743 Effect.andThen(Deferred.succeed(teardownFinished, undefined)),
744 Effect.asVoid,
745 ),
746 );
747 return makeProcess({
748 exitCode: Deferred.await(teardownFinished).pipe(
749 Effect.as(ChildProcessSpawner.ExitCode(0)),
750 ),
751 });
752 }),
753 ),
754 ),
755 httpClientLayer: layerHttpClient(() => Effect.never),
756 });
757 yield* instance.start;
758 yield* Deferred.await(spawned);
759
760 // App quit and the updater stop every backend with this deadline.
761 const quitDone = yield* Deferred.make<void>();
762 const quitFiber = yield* instance
763 .stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT })
764 .pipe(Effect.andThen(Deferred.succeed(quitDone, undefined)), Effect.forkChild);
765
766 yield* Deferred.await(teardownStarted);
767 // Past the SIGTERM grace but before the force kill lands: quit must still be waiting.
768 yield* TestClock.adjust(Duration.millis(5_500));
769 assert.isFalse(yield* Deferred.isDone(quitDone));
770
771 yield* TestClock.adjust(Duration.millis(500));
772 yield* Fiber.join(quitFiber);
773 assert.isTrue(yield* Deferred.isDone(teardownFinished));
774 }).pipe(Effect.provide(TestClock.layer())),
775 ),
776 );
777});