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