Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import { DESKTOP_UPDATE_IN_PROGRESS_TTL_MS } from "@t3tools/contracts";
3import * as Deferred from "effect/Deferred";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as Queue from "effect/Queue";
8import * as TestClock from "effect/testing/TestClock";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import * as Ref from "effect/Ref";
14import * as Sink from "effect/Sink";
15import * as Stream from "effect/Stream";
16import { HttpClient, HttpClientResponse } from "effect/http";
17import { ChildProcessSpawner } from "effect/process";
18
19import * as DesktopConfig from "../app/DesktopConfig.ts";
20import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
21import * as DesktopObservability from "../app/DesktopObservability.ts";
22import * as DesktopState from "../app/DesktopState.ts";
23import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
24import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
25import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
26import * as ElectronDialog from "../electron/ElectronDialog.ts";
27import * as ElectronApp from "../electron/ElectronApp.ts";
28import * as DesktopWindow from "../window/DesktopWindow.ts";
29import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
30import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
31import * as DesktopBackendPool from "./DesktopBackendPool.ts";
32import type { DesktopBackendStartConfig } from "./DesktopBackendManager.ts";
33
34// Models the spawner's release for a backend that ignores SIGTERM, without OS signals.
35const makeFakeBackendProcess = Effect.fn("test.makeFakeBackendProcess")(function* () {
36 const started = yield* Deferred.make<void>();
37 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
38 const signals = yield* Queue.unbounded<"SIGTERM" | "SIGKILL">();
39 let running = false;
40 const killWait = Duration.seconds(1);
41 const exit = Effect.sync(() => {
42 running = false;
43 }).pipe(Effect.andThen(Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0))), Effect.asVoid);
44 const layer = Layer.succeed(
45 ChildProcessSpawner.ChildProcessSpawner,
46 ChildProcessSpawner.make((command) =>
47 Effect.gen(function* () {
48 if (command._tag !== "StandardCommand") {
49 return yield* Effect.die("Expected a standard backend command");
50 }
51 const terminateGrace = Duration.fromInputUnsafe(command.options.forceKillAfter ?? 0);
52 running = true;
53 yield* Effect.addFinalizer(() =>
54 Effect.gen(function* () {
55 yield* Queue.offer(signals, "SIGTERM");
56 yield* Effect.sleep(terminateGrace);
57 yield* Queue.offer(signals, "SIGKILL");
58 yield* Effect.sleep(killWait);
59 yield* exit;
60 }),
61 );
62 yield* Deferred.succeed(started, undefined);
63 return ChildProcessSpawner.makeHandle({
64 pid: ChildProcessSpawner.ProcessId(123),
65 stdout: Stream.empty,
66 stderr: Stream.empty,
67 all: Stream.empty,
68 stdin: Sink.drain,
69 getInputFd: () => Sink.drain,
70 getOutputFd: () => Stream.empty,
71 exitCode: Deferred.await(exited),
72 exitStatus: Effect.map(Deferred.await(exited), (code) => ({
73 _tag: "Exited",
74 code,
75 })),
76 isRunning: Effect.sync(() => running),
77 kill: () => exit,
78 unref: Effect.succeed(Effect.void),
79 });
80 }),
81 ),
82 );
83 return {
84 layer,
85 started: Deferred.await(started),
86 signals,
87 isRunning: Effect.sync(() => running),
88 killWait,
89 };
90});
91
92const runningConfig = {
93 executablePath: "/electron",
94 args: [],
95 entryPath: "/server/bin.mjs",
96 cwd: "/server",
97 env: {},
98 bootstrap: {
99 mode: "desktop",
100 noBrowser: true,
101 port: 3774,
102 t3Home: "/tmp/t3",
103 host: "127.0.0.1",
104 desktopBootstrapToken: "token",
105 tailscaleServeEnabled: false,
106 tailscaleServePort: 443,
107 },
108 bootstrapDelivery: "fd3",
109 extendEnv: true,
110 httpBaseUrl: new URL("http://127.0.0.1:3774"),
111 captureOutput: false,
112 preflightFailure: Option.none(),
113} satisfies DesktopBackendStartConfig;
114
115function layerPool(
116 labelRef: Ref.Ref<string>,
117 options: {
118 readonly config?: DesktopBackendStartConfig;
119 readonly resolvePrimary?: Effect.Effect<DesktopBackendStartConfig>;
120 readonly onMainContentsCommand?: (
121 command: DesktopWindow.MainWindowContentsCommand,
122 ) => Effect.Effect<void>;
123 readonly fileSystem?: Partial<FileSystem.FileSystem>;
124 readonly spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
125 readonly httpClient?: HttpClient.HttpClient;
126 readonly onReady?: Effect.Effect<void>;
127 readonly backend?: Effect.Success<ReturnType<typeof makeFakeBackendProcess>>;
128 } = {},
129): Layer.Layer<DesktopBackendPool.DesktopBackendPool> {
130 return DesktopBackendPool.layer.pipe(
131 Layer.provideMerge(
132 Layer.mergeAll(
133 DesktopEnvironment.layer({
134 dirname: "/repo/apps/desktop/src",
135 homeDirectory: "/test-home",
136 platform: "linux",
137 processArch: "x64",
138 appVersion: "1.2.3",
139 appPath: "/repo",
140 isPackaged: true,
141 resourcesPath: "/missing/resources",
142 runningUnderArm64Translation: false,
143 }).pipe(
144 Layer.provide(
145 Layer.mergeAll(Path.layer, DesktopConfig.layerTest({ T3CODE_HOME: "/test-home" })),
146 ),
147 Layer.orDie,
148 ),
149 FileSystem.layerNoop(options.fileSystem ?? { exists: () => Effect.succeed(true) }),
150 Path.layer,
151 options.backend?.layer ??
152 Layer.succeed(
153 ChildProcessSpawner.ChildProcessSpawner,
154 options.spawner ??
155 ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")),
156 ),
157 Layer.succeed(
158 HttpClient.HttpClient,
159 options.httpClient ??
160 HttpClient.make((request) =>
161 options.backend === undefined
162 ? Effect.die("unexpected HTTP request")
163 : Effect.succeed(
164 HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })),
165 ),
166 ),
167 ),
168 Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
169 forInstance: () =>
170 Effect.succeed({
171 beginSession: () => Effect.void,
172 writeOutputChunk: () => Effect.void,
173 persistFailureSnapshot: () => Effect.void,
174 persistFailure: () => Effect.void,
175 discardSession: Effect.void,
176 } satisfies DesktopObservability.DesktopBackendOutputLogShape),
177 } satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
178 Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
179 latest: Effect.succeedNone,
180 changes: Stream.empty,
181 encoded: Stream.empty,
182 handleControlForSource: () => Effect.void,
183 removeControlSource: () => Effect.void,
184 publishUpdateReport: () => Effect.void,
185 updateRequests: Stream.empty,
186 updateCommits: Stream.empty,
187 updateCancellations: Stream.empty,
188 }),
189 DesktopBrowserHost.layer,
190 Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
191 resolvePrimary:
192 options.resolvePrimary ??
193 (options.config
194 ? Effect.succeed(options.config)
195 : Effect.die("unexpected primary config resolve")),
196 resolvePrimaryLabel: Ref.get(labelRef),
197 resolveWsl: () => Effect.die("unexpected WSL config resolve"),
198 currentBootstrapToken: Effect.die("unexpected bootstrap token read"),
199 } satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),
200 DesktopAppSettings.layerTest(),
201 DesktopState.layer,
202 DesktopWslEnvironment.layerTest(),
203 Layer.succeed(ElectronDialog.ElectronDialog, {
204 pickFolder: () => Effect.die("unexpected folder picker"),
205 pickFiles: () => Effect.die("unexpected file picker"),
206 showMessageBox: () => Effect.die("unexpected message box"),
207 showErrorBox: () => Effect.void,
208 } satisfies ElectronDialog.ElectronDialog["Service"]),
209 ElectronApp.layer,
210 Layer.succeed(DesktopWindow.DesktopWindow, {
211 createMain: Effect.die("unexpected window create"),
212 ensureMain: Effect.die("unexpected window ensure"),
213 revealOrCreateMain: Effect.die("unexpected window reveal"),
214 activate: Effect.die("unexpected window activate"),
215 createMainIfBackendReady: Effect.die("unexpected window create"),
216 showConnectingSplash: Effect.void,
217 handleBackendReady: () => options.onReady ?? Effect.void,
218 handleBackendNotReady: Effect.void,
219 flushMainWindowBounds: Effect.void,
220 prepareCaptureReveal: Effect.void,
221 dispatchMenuAction: () => Effect.die("unexpected menu action"),
222 dispatchSnapShotEvent: () => Effect.void,
223 zoomMain: () => Effect.die("unexpected zoom"),
224 runMainContentsCommand:
225 options.onMainContentsCommand ?? (() => Effect.die("unexpected main contents command")),
226 syncAppearance: Effect.void,
227 } satisfies DesktopWindow.DesktopWindow["Service"]),
228 ),
229 ),
230 );
231}
232
233const markerPath = "/test-home/runtime/desktop-update-in-progress";
234const runtimePath = "/test-home/userdata/server-runtime.json";
235
236const makeUpdateMarkerFixture = () =>
237 Effect.gen(function* () {
238 const allowReady = yield* Deferred.make<void>();
239 const runtimeChecked = yield* Deferred.make<void>();
240 const markerRemoved = yield* Deferred.make<void>();
241 const readyRuns = yield* Queue.unbounded<void>();
242 let nextPid = 123;
243 const files = new Map([[markerPath, JSON.stringify({ startedAt: 0, expiresAt: 60_000 })]]);
244 const removed: string[] = [];
245 const config: DesktopBackendStartConfig = {
246 executablePath: "/electron",
247 args: [],
248 entryPath: "/server/bin.mjs",
249 cwd: "/server",
250 env: {},
251 bootstrap: {
252 mode: "desktop",
253 noBrowser: true,
254 port: 3774,
255 t3Home: "/test-home",
256 host: "127.0.0.1",
257 desktopBootstrapToken: "token",
258 tailscaleServeEnabled: false,
259 tailscaleServePort: 443,
260 },
261 bootstrapDelivery: "fd3",
262 extendEnv: true,
263 httpBaseUrl: new URL("http://127.0.0.1:3774"),
264 captureOutput: false,
265 preflightFailure: Option.none(),
266 };
267 const layer = layerPool(Ref.makeUnsafe("Local"), {
268 config,
269 fileSystem: {
270 exists: (path) => Effect.succeed(files.has(path) || path === config.entryPath),
271 readFileString: (path) =>
272 (path === runtimePath ? Deferred.succeed(runtimeChecked, undefined) : Effect.void).pipe(
273 Effect.andThen(Effect.sync(() => files.get(path) ?? "")),
274 ),
275 remove: (path) =>
276 Effect.sync(() => {
277 removed.push(path);
278 files.delete(path);
279 }).pipe(
280 Effect.andThen(
281 path === markerPath ? Deferred.succeed(markerRemoved, undefined) : Effect.void,
282 ),
283 Effect.asVoid,
284 ),
285 },
286 spawner: ChildProcessSpawner.make(() =>
287 Effect.gen(function* () {
288 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
289 const exit = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe(
290 Effect.asVoid,
291 );
292 // Like the real spawner, closing the run's scope ends the process.
293 yield* Effect.addFinalizer(() => exit);
294 return ChildProcessSpawner.makeHandle({
295 pid: ChildProcessSpawner.ProcessId(nextPid++),
296 stdout: Stream.empty,
297 stderr: Stream.empty,
298 all: Stream.empty,
299 exitCode: Deferred.await(exited),
300 exitStatus: Effect.map(Deferred.await(exited), (code) => ({
301 _tag: "Exited",
302 code,
303 })),
304 isRunning: Effect.succeed(true),
305 kill: () => exit,
306 stdin: Sink.drain,
307 getInputFd: () => Sink.drain,
308 getOutputFd: () => Stream.empty,
309 unref: Effect.succeed(Effect.void),
310 });
311 }),
312 ),
313 httpClient: HttpClient.make((request) =>
314 Deferred.await(allowReady).pipe(
315 Effect.as(HttpClientResponse.fromWeb(request, new Response(null, { status: 200 }))),
316 ),
317 ),
318 onReady: Queue.offer(readyRuns, undefined).pipe(Effect.asVoid),
319 });
320 const publishRuntime = (pid: number) =>
321 files.set(
322 runtimePath,
323 JSON.stringify({
324 version: 1,
325 pid,
326 port: 3774,
327 origin: "http://127.0.0.1:3774",
328 startedAt: "2026-10-27T00:00:00.000Z",
329 }),
330 );
331 return {
332 layer,
333 files,
334 removed,
335 allowReady,
336 readyRuns,
337 runtimeChecked,
338 markerRemoved,
339 publishRuntime,
340 };
341 });
342
343describe("DesktopBackendPool", () => {
344 it.effect(
345 "keeps the update marker after HTTP readiness until the backend publishes its runtime",
346 () =>
347 Effect.gen(function* () {
348 const fixture = yield* makeUpdateMarkerFixture();
349 yield* Effect.gen(function* () {
350 const pool = yield* DesktopBackendPool.DesktopBackendPool;
351 const primary = yield* pool.primary;
352 yield* primary.start;
353 yield* Deferred.succeed(fixture.allowReady, undefined);
354 yield* Queue.take(fixture.readyRuns);
355 assert.isTrue(
356 fixture.files.has(markerPath),
357 "a launcher could neither wait nor adopt between readiness and publication",
358 );
359 yield* Deferred.await(fixture.runtimeChecked);
360 yield* TestClock.adjust(Duration.seconds(5));
361 assert.isTrue(fixture.files.has(markerPath));
362 fixture.publishRuntime(456);
363 yield* TestClock.adjust(Duration.seconds(1));
364 assert.isTrue(
365 fixture.files.has(markerPath),
366 "another process's runtime is not the replacement",
367 );
368 fixture.publishRuntime(123);
369 yield* TestClock.adjust(Duration.seconds(1));
370 yield* Deferred.await(fixture.markerRemoved);
371 assert.deepEqual(fixture.removed, [markerPath]);
372 }).pipe(Effect.provide(fixture.layer));
373 }),
374 );
375
376 it.effect("leaves a replacement update marker written while an earlier wait is pending", () =>
377 Effect.gen(function* () {
378 const fixture = yield* makeUpdateMarkerFixture();
379 yield* Effect.gen(function* () {
380 const pool = yield* DesktopBackendPool.DesktopBackendPool;
381 const primary = yield* pool.primary;
382 yield* primary.start;
383 yield* Deferred.succeed(fixture.allowReady, undefined);
384 yield* Queue.take(fixture.readyRuns);
385 yield* Deferred.await(fixture.runtimeChecked);
386 yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS - 1_000));
387 const replacement = JSON.stringify({ startedAt: 59_000, expiresAt: 119_000 });
388 fixture.files.set(markerPath, replacement);
389 yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS));
390 assert.equal(fixture.files.get(markerPath), replacement);
391 assert.deepEqual(fixture.removed, []);
392 }).pipe(Effect.provide(fixture.layer));
393 }),
394 );
395
396 it.effect("a later backend run's readiness supersedes the earlier run's marker wait", () =>
397 Effect.gen(function* () {
398 const fixture = yield* makeUpdateMarkerFixture();
399 yield* Effect.gen(function* () {
400 const pool = yield* DesktopBackendPool.DesktopBackendPool;
401 const primary = yield* pool.primary;
402 yield* primary.start;
403 yield* Deferred.succeed(fixture.allowReady, undefined);
404 yield* Queue.take(fixture.readyRuns);
405 yield* Deferred.await(fixture.runtimeChecked);
406 yield* TestClock.adjust(Duration.seconds(30));
407 yield* primary.stop();
408 yield* primary.start;
409 yield* Queue.take(fixture.readyRuns);
410 yield* TestClock.adjust(Duration.seconds(31));
411 assert.isTrue(
412 fixture.files.has(markerPath),
413 "the earlier run's wait must not end the later run's handoff",
414 );
415 assert.deepEqual(fixture.removed, []);
416 fixture.publishRuntime(124);
417 yield* TestClock.adjust(Duration.millis(100));
418 yield* Deferred.await(fixture.markerRemoved);
419 assert.deepEqual(fixture.removed, [markerPath]);
420 }).pipe(Effect.provide(fixture.layer));
421 }),
422 );
423
424 it.effect("unregister during pool quit does not interrupt sibling stops", () =>
425 Effect.gen(function* () {
426 const backend = yield* makeFakeBackendProcess();
427 yield* Effect.gen(function* () {
428 const pool = yield* DesktopBackendPool.DesktopBackendPool;
429 const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu");
430 const ready = yield* Deferred.make<void>();
431 const siblingStarted = yield* Deferred.make<void>();
432 const finishSibling = yield* Deferred.make<void>();
433 let siblingCompleted = false;
434 const instance = yield* pool.register({
435 id,
436 label: Effect.succeed("WSL (Ubuntu)"),
437 configResolve: Effect.succeed(runningConfig),
438 onReady: () => Deferred.succeed(ready, undefined).pipe(Effect.asVoid),
439 });
440 yield* instance.start;
441 yield* backend.started;
442 yield* Deferred.await(ready);
443 const quitFiber = yield* Effect.all(
444 [
445 instance.stop({ timeout: Duration.seconds(5) }),
446 Deferred.succeed(siblingStarted, undefined).pipe(
447 Effect.andThen(Deferred.await(finishSibling)),
448 Effect.andThen(
449 Effect.sync(() => {
450 siblingCompleted = true;
451 }),
452 ),
453 ),
454 ],
455 { concurrency: "unbounded" },
456 ).pipe(Effect.forkChild);
457 yield* Deferred.await(siblingStarted);
458 assert.equal(yield* Queue.take(backend.signals), "SIGTERM");
459 const unregisterFiber = yield* pool.unregister(id).pipe(Effect.forkChild);
460 yield* TestClock.adjust(Duration.seconds(5));
461 assert.equal(yield* Queue.take(backend.signals), "SIGKILL");
462 assert.isUndefined(quitFiber.pollUnsafe());
463 assert.isUndefined(unregisterFiber.pollUnsafe());
464 assert.isTrue(yield* backend.isRunning);
465 yield* TestClock.adjust(backend.killWait);
466 yield* Fiber.join(unregisterFiber);
467 yield* Deferred.succeed(finishSibling, undefined);
468 yield* Fiber.join(quitFiber);
469
470 assert.isTrue(siblingCompleted);
471 assert.isFalse(yield* backend.isRunning);
472 assert.isTrue(Option.isNone((yield* instance.snapshot).activePid));
473 assert.isTrue(Option.isNone(yield* pool.get(id)));
474 }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows"), { backend })));
475 }),
476 );
477
478 it.effect("unregister stops the registered instance", () =>
479 Effect.gen(function* () {
480 const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu");
481 const pool = yield* DesktopBackendPool.DesktopBackendPool;
482 const instance = yield* pool.register({
483 id,
484 label: Effect.succeed("WSL (Ubuntu)"),
485 configResolve: Effect.succeed({
486 ...runningConfig,
487 preflightFailure: Option.some({ reason: "WSL starting", fatal: false }),
488 }),
489 });
490 yield* instance.start;
491 assert.equal((yield* instance.snapshot).restartScheduled, true);
492
493 yield* pool.unregister(id);
494
495 const stopped = yield* instance.snapshot;
496 assert.equal(stopped.desiredRunning, false);
497 assert.equal(stopped.restartScheduled, false);
498 assert.equal(Option.isNone(yield* pool.get(id)), true);
499 }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows")))),
500 );
501
502 it.effect("reloads a main window that read the WSL endpoint before the Windows fallback", () =>
503 Effect.gen(function* () {
504 const events: string[] = [];
505 let resolves = 0;
506 const resolvePrimary = Effect.sync(() =>
507 resolves++ === 0
508 ? {
509 ...runningConfig,
510 preflightFailure: Option.some({
511 reason: "WSL still unavailable",
512 fatal: false,
513 retryLimit: 1,
514 }),
515 }
516 : runningConfig,
517 );
518 const ready = yield* Deferred.make<void>();
519 yield* Effect.gen(function* () {
520 const primary = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary;
521 yield* primary.start;
522 yield* TestClock.adjust(Duration.seconds(1));
523 yield* Deferred.await(ready);
524
525 assert.deepEqual(events, ["reload", "ready"]);
526 }).pipe(
527 Effect.provide(
528 layerPool(Ref.makeUnsafe("WSL"), {
529 resolvePrimary,
530 spawner: ChildProcessSpawner.make(() =>
531 Effect.gen(function* () {
532 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
533 const exit = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe(
534 Effect.asVoid,
535 );
536 yield* Effect.addFinalizer(() => exit);
537 return ChildProcessSpawner.makeHandle({
538 pid: ChildProcessSpawner.ProcessId(123),
539 stdout: Stream.empty,
540 stderr: Stream.empty,
541 all: Stream.empty,
542 exitCode: Deferred.await(exited),
543 exitStatus: Effect.map(Deferred.await(exited), (code) => ({
544 _tag: "Exited",
545 code,
546 })),
547 isRunning: Effect.succeed(true),
548 kill: () => exit,
549 stdin: Sink.drain,
550 getInputFd: () => Sink.drain,
551 getOutputFd: () => Stream.empty,
552 unref: Effect.succeed(Effect.void),
553 });
554 }),
555 ),
556 httpClient: HttpClient.make((request) =>
557 Effect.succeed(
558 HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })),
559 ),
560 ),
561 onMainContentsCommand: (command) => Effect.sync(() => void events.push(command)),
562 onReady: Effect.sync(() => void events.push("ready")).pipe(
563 Effect.andThen(Deferred.succeed(ready, undefined)),
564 Effect.asVoid,
565 ),
566 }),
567 ),
568 );
569 }),
570 );
571});