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 isRunning: Effect.sync(() => running),
73 kill: () => exit,
74 unref: Effect.succeed(Effect.void),
75 });
76 }),
77 ),
78 );
79 return {
80 layer,
81 started: Deferred.await(started),
82 signals,
83 isRunning: Effect.sync(() => running),
84 killWait,
85 };
86});
87
88const runningConfig = {
89 executablePath: "/electron",
90 args: [],
91 entryPath: "/server/bin.mjs",
92 cwd: "/server",
93 env: {},
94 bootstrap: {
95 mode: "desktop",
96 noBrowser: true,
97 port: 3774,
98 t3Home: "/tmp/t3",
99 host: "127.0.0.1",
100 desktopBootstrapToken: "token",
101 tailscaleServeEnabled: false,
102 tailscaleServePort: 443,
103 },
104 bootstrapDelivery: "fd3",
105 extendEnv: true,
106 httpBaseUrl: new URL("http://127.0.0.1:3774"),
107 captureOutput: false,
108 preflightFailure: Option.none(),
109} satisfies DesktopBackendStartConfig;
110
111function layerPool(
112 labelRef: Ref.Ref<string>,
113 options: {
114 readonly config?: DesktopBackendStartConfig;
115 readonly fileSystem?: Partial<FileSystem.FileSystem>;
116 readonly spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
117 readonly httpClient?: HttpClient.HttpClient;
118 readonly onReady?: Effect.Effect<void>;
119 readonly backend?: Effect.Success<ReturnType<typeof makeFakeBackendProcess>>;
120 } = {},
121): Layer.Layer<DesktopBackendPool.DesktopBackendPool> {
122 return DesktopBackendPool.layer.pipe(
123 Layer.provideMerge(
124 Layer.mergeAll(
125 DesktopEnvironment.layer({
126 dirname: "/repo/apps/desktop/src",
127 homeDirectory: "/test-home",
128 platform: "linux",
129 processArch: "x64",
130 appVersion: "1.2.3",
131 appPath: "/repo",
132 isPackaged: true,
133 resourcesPath: "/missing/resources",
134 runningUnderArm64Translation: false,
135 }).pipe(
136 Layer.provide(
137 Layer.mergeAll(Path.layer, DesktopConfig.layerTest({ T3CODE_HOME: "/test-home" })),
138 ),
139 Layer.orDie,
140 ),
141 FileSystem.layerNoop(options.fileSystem ?? { exists: () => Effect.succeed(true) }),
142 Path.layer,
143 options.backend?.layer ??
144 Layer.succeed(
145 ChildProcessSpawner.ChildProcessSpawner,
146 options.spawner ??
147 ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")),
148 ),
149 Layer.succeed(
150 HttpClient.HttpClient,
151 options.httpClient ??
152 HttpClient.make((request) =>
153 options.backend === undefined
154 ? Effect.die("unexpected HTTP request")
155 : Effect.succeed(
156 HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })),
157 ),
158 ),
159 ),
160 Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
161 forInstance: () =>
162 Effect.succeed({
163 beginSession: () => Effect.void,
164 writeOutputChunk: () => Effect.void,
165 persistFailureSnapshot: () => Effect.void,
166 persistFailure: () => Effect.void,
167 discardSession: Effect.void,
168 } satisfies DesktopObservability.DesktopBackendOutputLogShape),
169 } satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
170 Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
171 latest: Effect.succeedNone,
172 changes: Stream.empty,
173 encoded: Stream.empty,
174 handleControlForSource: () => Effect.void,
175 removeControlSource: () => Effect.void,
176 publishUpdateReport: () => Effect.void,
177 updateRequests: Stream.empty,
178 updateCommits: Stream.empty,
179 updateCancellations: Stream.empty,
180 }),
181 DesktopBrowserHost.layer,
182 Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
183 resolvePrimary: options.config
184 ? Effect.succeed(options.config)
185 : Effect.die("unexpected primary config resolve"),
186 resolvePrimaryLabel: Ref.get(labelRef),
187 resolveWsl: () => Effect.die("unexpected WSL config resolve"),
188 currentBootstrapToken: Effect.die("unexpected bootstrap token read"),
189 } satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),
190 DesktopAppSettings.layerTest(),
191 DesktopState.layer,
192 DesktopWslEnvironment.layerTest(),
193 ElectronDialog.layer,
194 ElectronApp.layer,
195 Layer.succeed(DesktopWindow.DesktopWindow, {
196 createMain: Effect.die("unexpected window create"),
197 ensureMain: Effect.die("unexpected window ensure"),
198 revealOrCreateMain: Effect.die("unexpected window reveal"),
199 activate: Effect.die("unexpected window activate"),
200 createMainIfBackendReady: Effect.die("unexpected window create"),
201 showConnectingSplash: Effect.void,
202 handleBackendReady: () => options.onReady ?? Effect.void,
203 handleBackendNotReady: Effect.void,
204 flushMainWindowBounds: Effect.void,
205 prepareCaptureReveal: Effect.void,
206 dispatchMenuAction: () => Effect.die("unexpected menu action"),
207 dispatchSnapShotEvent: () => Effect.void,
208 zoomMain: () => Effect.die("unexpected zoom"),
209 runMainContentsCommand: () => Effect.die("unexpected main contents command"),
210 syncAppearance: Effect.void,
211 } satisfies DesktopWindow.DesktopWindow["Service"]),
212 ),
213 ),
214 );
215}
216
217const markerPath = "/test-home/runtime/desktop-update-in-progress";
218const runtimePath = "/test-home/userdata/server-runtime.json";
219
220const makeUpdateMarkerFixture = () =>
221 Effect.gen(function* () {
222 const allowReady = yield* Deferred.make<void>();
223 const runtimeChecked = yield* Deferred.make<void>();
224 const markerRemoved = yield* Deferred.make<void>();
225 const readyRuns = yield* Queue.unbounded<void>();
226 let nextPid = 123;
227 const files = new Map([[markerPath, JSON.stringify({ startedAt: 0, expiresAt: 60_000 })]]);
228 const removed: string[] = [];
229 const config: DesktopBackendStartConfig = {
230 executablePath: "/electron",
231 args: [],
232 entryPath: "/server/bin.mjs",
233 cwd: "/server",
234 env: {},
235 bootstrap: {
236 mode: "desktop",
237 noBrowser: true,
238 port: 3774,
239 t3Home: "/test-home",
240 host: "127.0.0.1",
241 desktopBootstrapToken: "token",
242 tailscaleServeEnabled: false,
243 tailscaleServePort: 443,
244 },
245 bootstrapDelivery: "fd3",
246 extendEnv: true,
247 httpBaseUrl: new URL("http://127.0.0.1:3774"),
248 captureOutput: false,
249 preflightFailure: Option.none(),
250 };
251 const layer = layerPool(Ref.makeUnsafe("Local"), {
252 config,
253 fileSystem: {
254 exists: (path) => Effect.succeed(files.has(path) || path === config.entryPath),
255 readFileString: (path) =>
256 (path === runtimePath ? Deferred.succeed(runtimeChecked, undefined) : Effect.void).pipe(
257 Effect.andThen(Effect.sync(() => files.get(path) ?? "")),
258 ),
259 remove: (path) =>
260 Effect.sync(() => {
261 removed.push(path);
262 files.delete(path);
263 }).pipe(
264 Effect.andThen(
265 path === markerPath ? Deferred.succeed(markerRemoved, undefined) : Effect.void,
266 ),
267 Effect.asVoid,
268 ),
269 },
270 spawner: ChildProcessSpawner.make(() =>
271 Effect.gen(function* () {
272 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
273 const exit = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe(
274 Effect.asVoid,
275 );
276 // Like the real spawner, closing the run's scope ends the process.
277 yield* Effect.addFinalizer(() => exit);
278 return ChildProcessSpawner.makeHandle({
279 pid: ChildProcessSpawner.ProcessId(nextPid++),
280 stdout: Stream.empty,
281 stderr: Stream.empty,
282 all: Stream.empty,
283 exitCode: Deferred.await(exited),
284 isRunning: Effect.succeed(true),
285 kill: () => exit,
286 stdin: Sink.drain,
287 getInputFd: () => Sink.drain,
288 getOutputFd: () => Stream.empty,
289 unref: Effect.succeed(Effect.void),
290 });
291 }),
292 ),
293 httpClient: HttpClient.make((request) =>
294 Deferred.await(allowReady).pipe(
295 Effect.as(HttpClientResponse.fromWeb(request, new Response(null, { status: 200 }))),
296 ),
297 ),
298 onReady: Queue.offer(readyRuns, undefined).pipe(Effect.asVoid),
299 });
300 const publishRuntime = (pid: number) =>
301 files.set(
302 runtimePath,
303 JSON.stringify({
304 version: 1,
305 pid,
306 port: 3774,
307 origin: "http://127.0.0.1:3774",
308 startedAt: "2026-10-27T00:00:00.000Z",
309 }),
310 );
311 return {
312 layer,
313 files,
314 removed,
315 allowReady,
316 readyRuns,
317 runtimeChecked,
318 markerRemoved,
319 publishRuntime,
320 };
321 });
322
323describe("DesktopBackendPool", () => {
324 it.effect(
325 "keeps the update marker after HTTP readiness until the backend publishes its runtime",
326 () =>
327 Effect.scoped(
328 Effect.gen(function* () {
329 const fixture = yield* makeUpdateMarkerFixture();
330 yield* Effect.gen(function* () {
331 const pool = yield* DesktopBackendPool.DesktopBackendPool;
332 const primary = yield* pool.primary;
333 yield* primary.start;
334 yield* Deferred.succeed(fixture.allowReady, undefined);
335 yield* Queue.take(fixture.readyRuns);
336 assert.isTrue(
337 fixture.files.has(markerPath),
338 "a launcher could neither wait nor adopt between readiness and publication",
339 );
340 yield* Deferred.await(fixture.runtimeChecked);
341 yield* TestClock.adjust(Duration.seconds(5));
342 assert.isTrue(fixture.files.has(markerPath));
343 fixture.publishRuntime(456);
344 yield* TestClock.adjust(Duration.seconds(1));
345 assert.isTrue(
346 fixture.files.has(markerPath),
347 "another process's runtime is not the replacement",
348 );
349 fixture.publishRuntime(123);
350 yield* TestClock.adjust(Duration.seconds(1));
351 yield* Deferred.await(fixture.markerRemoved);
352 assert.deepEqual(fixture.removed, [markerPath]);
353 }).pipe(Effect.provide(fixture.layer));
354 }),
355 ),
356 );
357
358 it.effect("leaves a replacement update marker written while an earlier wait is pending", () =>
359 Effect.scoped(
360 Effect.gen(function* () {
361 const fixture = yield* makeUpdateMarkerFixture();
362 yield* Effect.gen(function* () {
363 const pool = yield* DesktopBackendPool.DesktopBackendPool;
364 const primary = yield* pool.primary;
365 yield* primary.start;
366 yield* Deferred.succeed(fixture.allowReady, undefined);
367 yield* Queue.take(fixture.readyRuns);
368 yield* Deferred.await(fixture.runtimeChecked);
369 yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS - 1_000));
370 const replacement = JSON.stringify({ startedAt: 59_000, expiresAt: 119_000 });
371 fixture.files.set(markerPath, replacement);
372 yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS));
373 assert.equal(fixture.files.get(markerPath), replacement);
374 assert.deepEqual(fixture.removed, []);
375 }).pipe(Effect.provide(fixture.layer));
376 }),
377 ),
378 );
379
380 it.effect("a later backend run's readiness supersedes the earlier run's marker wait", () =>
381 Effect.scoped(
382 Effect.gen(function* () {
383 const fixture = yield* makeUpdateMarkerFixture();
384 yield* Effect.gen(function* () {
385 const pool = yield* DesktopBackendPool.DesktopBackendPool;
386 const primary = yield* pool.primary;
387 yield* primary.start;
388 yield* Deferred.succeed(fixture.allowReady, undefined);
389 yield* Queue.take(fixture.readyRuns);
390 yield* Deferred.await(fixture.runtimeChecked);
391 yield* TestClock.adjust(Duration.seconds(30));
392 yield* primary.stop();
393 yield* primary.start;
394 yield* Queue.take(fixture.readyRuns);
395 yield* TestClock.adjust(Duration.seconds(31));
396 assert.isTrue(
397 fixture.files.has(markerPath),
398 "the earlier run's wait must not end the later run's handoff",
399 );
400 assert.deepEqual(fixture.removed, []);
401 fixture.publishRuntime(124);
402 yield* TestClock.adjust(Duration.millis(100));
403 yield* Deferred.await(fixture.markerRemoved);
404 assert.deepEqual(fixture.removed, [markerPath]);
405 }).pipe(Effect.provide(fixture.layer));
406 }),
407 ),
408 );
409
410 it.effect("unregister during pool quit does not interrupt sibling stops", () =>
411 Effect.scoped(
412 Effect.gen(function* () {
413 const backend = yield* makeFakeBackendProcess();
414 yield* Effect.gen(function* () {
415 const pool = yield* DesktopBackendPool.DesktopBackendPool;
416 const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu");
417 const ready = yield* Deferred.make<void>();
418 const siblingStarted = yield* Deferred.make<void>();
419 const finishSibling = yield* Deferred.make<void>();
420 let siblingCompleted = false;
421 const instance = yield* pool.register({
422 id,
423 label: Effect.succeed("WSL (Ubuntu)"),
424 configResolve: Effect.succeed(runningConfig),
425 onReady: () => Deferred.succeed(ready, undefined).pipe(Effect.asVoid),
426 });
427 yield* instance.start;
428 yield* backend.started;
429 yield* Deferred.await(ready);
430 const quitFiber = yield* Effect.all(
431 [
432 instance.stop({ timeout: Duration.seconds(5) }),
433 Deferred.succeed(siblingStarted, undefined).pipe(
434 Effect.andThen(Deferred.await(finishSibling)),
435 Effect.andThen(
436 Effect.sync(() => {
437 siblingCompleted = true;
438 }),
439 ),
440 ),
441 ],
442 { concurrency: "unbounded" },
443 ).pipe(Effect.forkChild);
444 yield* Deferred.await(siblingStarted);
445 assert.equal(yield* Queue.take(backend.signals), "SIGTERM");
446 const unregisterFiber = yield* pool.unregister(id).pipe(Effect.forkChild);
447 yield* TestClock.adjust(Duration.seconds(5));
448 assert.equal(yield* Queue.take(backend.signals), "SIGKILL");
449 assert.isUndefined(quitFiber.pollUnsafe());
450 assert.isUndefined(unregisterFiber.pollUnsafe());
451 assert.isTrue(yield* backend.isRunning);
452 yield* TestClock.adjust(backend.killWait);
453 yield* Fiber.join(unregisterFiber);
454 yield* Deferred.succeed(finishSibling, undefined);
455 yield* Fiber.join(quitFiber);
456
457 assert.isTrue(siblingCompleted);
458 assert.isFalse(yield* backend.isRunning);
459 assert.isTrue(Option.isNone((yield* instance.snapshot).activePid));
460 assert.isTrue(Option.isNone(yield* pool.get(id)));
461 }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows"), { backend })));
462 }),
463 ),
464 );
465
466 it.effect("unregister stops the registered instance", () =>
467 Effect.scoped(
468 Effect.gen(function* () {
469 const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu");
470 const pool = yield* DesktopBackendPool.DesktopBackendPool;
471 const instance = yield* pool.register({
472 id,
473 label: Effect.succeed("WSL (Ubuntu)"),
474 configResolve: Effect.succeed({
475 ...runningConfig,
476 preflightFailure: Option.some({ reason: "WSL starting", fatal: false }),
477 }),
478 });
479 yield* instance.start;
480 assert.equal((yield* instance.snapshot).restartScheduled, true);
481
482 yield* pool.unregister(id);
483
484 const stopped = yield* instance.snapshot;
485 assert.equal(stopped.desiredRunning, false);
486 assert.equal(stopped.restartScheduled, false);
487 assert.equal(Option.isNone(yield* pool.get(id)), true);
488 }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows")))),
489 ),
490 );
491});