Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import type { DesktopUpdateState } from "@t3tools/contracts";
4import * as Cause from "effect/Cause";
5import * as Deferred from "effect/Deferred";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as Layer from "effect/Layer";
10import * as Logger from "effect/Logger";
11import * as Option from "effect/Option";
12import * as References from "effect/References";
13import * as Ref from "effect/Ref";
14import * as TestClock from "effect/testing/TestClock";
15
16import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
17import * as DesktopConfig from "../app/DesktopConfig.ts";
18import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
19import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
20import * as ElectronWindow from "../electron/ElectronWindow.ts";
21import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
22import * as DesktopState from "../app/DesktopState.ts";
23import * as DesktopUpdates from "./DesktopUpdates.ts";
24
25interface UpdatesHarnessOptions {
26 readonly checkForUpdates?: Effect.Effect<
27 void,
28 ElectronUpdater.ElectronUpdaterCheckForUpdatesError
29 >;
30 readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
31 readonly setDisableDifferentialDownload?: Effect.Effect<void>;
32 readonly stopBackend?: Effect.Effect<void>;
33 readonly env?: Record<string, string | undefined>;
34}
35
36const flushCallbacks = Effect.yieldNow;
37
38function makeHarness(options: UpdatesHarnessOptions = {}) {
39 let checkCount = 0;
40 let allowDowngrade = false;
41 let fullChangelog = false;
42 const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
43 const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
44 const sentStates: DesktopUpdateState[] = [];
45
46 const addListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
47 const eventListeners = listeners.get(eventName) ?? new Set();
48 eventListeners.add(listener);
49 listeners.set(eventName, eventListeners);
50 };
51
52 const removeListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
53 const eventListeners = listeners.get(eventName);
54 if (!eventListeners) {
55 return;
56 }
57 eventListeners.delete(listener);
58 if (eventListeners.size === 0) {
59 listeners.delete(eventName);
60 }
61 };
62
63 const updaterLayer = Layer.succeed(ElectronUpdater.ElectronUpdater, {
64 setFeedURL: (options) =>
65 Effect.sync(() => {
66 feedUrls.push(options);
67 }),
68 setAutoDownload: () => Effect.void,
69 setAutoInstallOnAppQuit: () => Effect.void,
70 setChannel: () => Effect.void,
71 setAllowPrerelease: () => Effect.void,
72 allowDowngrade: Effect.sync(() => allowDowngrade),
73 setAllowDowngrade: (value) =>
74 Effect.sync(() => {
75 allowDowngrade = value;
76 }),
77 setFullChangelog: (value) =>
78 Effect.sync(() => {
79 fullChangelog = value;
80 }),
81 setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
82 checkForUpdates: Effect.sync(() => {
83 checkCount += 1;
84 }).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
85 downloadUpdate: Effect.void,
86 quitAndInstall: () => Effect.void,
87 on: (eventName, listener) =>
88 Effect.acquireRelease(
89 Effect.sync(() => {
90 addListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
91 }),
92 () =>
93 Effect.sync(() => {
94 removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
95 }),
96 ).pipe(Effect.asVoid),
97 } satisfies ElectronUpdater.ElectronUpdater["Service"]);
98
99 const windowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
100 create: () => Effect.die("unexpected BrowserWindow creation"),
101 main: Effect.succeed(Option.none()),
102 currentMainOrFirst: Effect.succeed(Option.none()),
103 focusedMainOrFirst: Effect.succeed(Option.none()),
104 setMain: () => Effect.void,
105 clearMain: () => Effect.void,
106 reveal: () => Effect.void,
107 sendAll: (_channel, state) =>
108 Effect.sync(() => {
109 sentStates.push(state as DesktopUpdateState);
110 }),
111 destroyAll: Effect.void,
112 syncAllAppearance: () => Effect.void,
113 } satisfies ElectronWindow.ElectronWindow["Service"]);
114
115 const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
116 id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
117 label: Effect.succeed("Windows"),
118 start: Effect.void,
119 stop: () => options.stopBackend ?? Effect.void,
120 currentConfig: Effect.succeed(Option.none()),
121 snapshot: Effect.succeed({
122 desiredRunning: false,
123 ready: false,
124 activePid: Option.none(),
125 restartAttempt: 0,
126 restartScheduled: false,
127 }),
128 waitForReady: () => Effect.succeed(true),
129 };
130 const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
131
132 const environmentLayer = DesktopEnvironment.layer({
133 dirname: "/repo/apps/desktop/src",
134 homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
135 platform: "darwin",
136 processArch: "x64",
137 appVersion: "1.2.3",
138 appPath: "/repo",
139 isPackaged: true,
140 resourcesPath: "/missing/resources",
141 runningUnderArm64Translation: false,
142 }).pipe(
143 Layer.provide(
144 Layer.mergeAll(
145 NodeServices.layer,
146 DesktopConfig.layerTest({
147 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
148 T3CODE_DESKTOP_MOCK_UPDATES: "true",
149 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
150 ...options.env,
151 }),
152 ),
153 ),
154 );
155
156 const setUpdateChannelError = options.setUpdateChannelError;
157 const settingsLayer = setUpdateChannelError
158 ? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
159 get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
160 load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
161 setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
162 setServerExposureMode: () => Effect.die("unexpected server exposure update"),
163 setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
164 setUpdateChannel: () => Effect.fail(setUpdateChannelError),
165 setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
166 setWslDistro: () => Effect.die("unexpected WSL distro change"),
167 setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
168 applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
169 applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
170 } satisfies DesktopAppSettings.DesktopAppSettings["Service"])
171 : DesktopAppSettings.layer;
172
173 const layer = DesktopUpdates.layer.pipe(
174 Layer.provideMerge(updaterLayer),
175 Layer.provideMerge(windowLayer),
176 Layer.provideMerge(backendLayer),
177 Layer.provideMerge(DesktopState.layer),
178 Layer.provideMerge(settingsLayer),
179 Layer.provideMerge(
180 DesktopConfig.layerTest({
181 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
182 T3CODE_DESKTOP_MOCK_UPDATES: "true",
183 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
184 ...options.env,
185 }),
186 ),
187 Layer.provideMerge(environmentLayer),
188 Layer.provideMerge(NodeServices.layer),
189 );
190
191 return {
192 layer,
193 checkCount: () => checkCount,
194 feedUrls: () => feedUrls,
195 fullChangelog: () => fullChangelog,
196 listenerCount: () =>
197 Array.from(listeners.values()).reduce(
198 (total, eventListeners) => total + eventListeners.size,
199 0,
200 ),
201 sentStates,
202 emit: (eventName: string, payload?: unknown) => {
203 for (const listener of listeners.get(eventName) ?? []) {
204 listener(payload);
205 }
206 },
207 };
208}
209
210describe("DesktopUpdates", () => {
211 it("preserves complete causes for update poller and event failures", () => {
212 const cause = Cause.combine(
213 Cause.fail(new Error("updater failed")),
214 Cause.die(new Error("updater defect")),
215 );
216 const pollerError = new DesktopUpdates.DesktopUpdatePollerError({
217 poller: "startup",
218 cause,
219 });
220 const eventError = new DesktopUpdates.DesktopUpdateEventHandlingError({
221 event: "download-progress",
222 cause,
223 });
224 const reportedError = new DesktopUpdates.DesktopUpdaterReportedError({
225 operation: "download",
226 cause,
227 });
228 const unexpectedActionError = new DesktopUpdates.DesktopUpdateUnexpectedActionError({
229 action: "install",
230 cause,
231 });
232
233 assert.strictEqual(pollerError.cause, cause);
234 assert.equal(pollerError.poller, "startup");
235 assert.equal(pollerError.message, "Desktop update startup poller failed.");
236 assert.strictEqual(eventError.cause, cause);
237 assert.equal(eventError.event, "download-progress");
238 assert.equal(eventError.message, "Failed to handle desktop update download-progress event.");
239 assert.strictEqual(reportedError.cause, cause);
240 assert.equal(reportedError.operation, "download");
241 assert.equal(reportedError.message, "Desktop updater download operation reported an error.");
242 assert.strictEqual(unexpectedActionError.cause, cause);
243 assert.equal(unexpectedActionError.action, "install");
244 assert.equal(
245 unexpectedActionError.message,
246 "Desktop update install action failed unexpectedly.",
247 );
248 });
249
250 it.effect("configures the updater and runs startup checks on the test clock", () => {
251 const harness = makeHarness();
252
253 return Effect.gen(function* () {
254 yield* Effect.scoped(
255 Effect.gen(function* () {
256 const updates = yield* DesktopUpdates.DesktopUpdates;
257 yield* updates.configure;
258
259 const state = yield* updates.getState;
260 assert.equal(state.enabled, true);
261 assert.equal(state.status, "idle");
262 assert.deepEqual(harness.feedUrls(), [
263 { provider: "generic", url: "http://localhost:4141" },
264 ]);
265 assert.equal(harness.listenerCount(), 6);
266 assert.equal(harness.checkCount(), 0);
267
268 yield* TestClock.adjust(Duration.millis(15_000));
269 assert.equal(harness.checkCount(), 1);
270 }),
271 );
272
273 assert.equal(harness.listenerCount(), 0);
274 }).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
275 });
276
277 it.effect("updates and broadcasts state from updater events", () => {
278 const harness = makeHarness();
279
280 return Effect.scoped(
281 Effect.gen(function* () {
282 const updates = yield* DesktopUpdates.DesktopUpdates;
283 yield* updates.configure;
284
285 harness.emit("update-available", { version: "1.2.4" });
286 yield* flushCallbacks;
287
288 const state = yield* updates.getState;
289 assert.equal(state.status, "available");
290 assert.equal(state.availableVersion, "1.2.4");
291 assert.isNotNull(state.checkedAt);
292 assert.equal(harness.sentStates.at(-1)?.status, "available");
293 }),
294 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
295 });
296
297 it.effect("enables nightly full changelog release notes and broadcasts summaries", () => {
298 const harness = makeHarness();
299
300 return Effect.scoped(
301 Effect.gen(function* () {
302 const updates = yield* DesktopUpdates.DesktopUpdates;
303 yield* updates.configure;
304
305 yield* updates.setChannel("nightly");
306 assert.equal(harness.fullChangelog(), true);
307
308 harness.emit("update-available", {
309 version: "1.2.4-nightly.20260709.766",
310 releaseNotes: [
311 {
312 version: "1.2.4-nightly.20260709.766",
313 note: `<h2>What's Changed</h2><ul><li>feat(client): persist offline environment data by <a>@juliusmarminge</a> in <a>#3795</a></li></ul><h2>Full Changelog</h2>`,
314 },
315 {
316 version: "1.2.4-nightly.20260709.765",
317 note: "- [codex] Upgrade Clerk stack by @juliusmarminge in #3821",
318 },
319 ],
320 });
321 yield* flushCallbacks;
322
323 const state = yield* updates.getState;
324 assert.equal(state.status, "available");
325 assert.deepEqual(state.releaseNotes, [
326 {
327 version: "1.2.4-nightly.20260709.766",
328 items: ["feat(client): persist offline environment data by @juliusmarminge in #3795"],
329 },
330 {
331 version: "1.2.4-nightly.20260709.765",
332 items: ["[codex] Upgrade Clerk stack by @juliusmarminge in #3821"],
333 },
334 ]);
335 assert.deepEqual(harness.sentStates.at(-1)?.releaseNotes, state.releaseNotes);
336 }),
337 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
338 });
339
340 it.effect("keeps raw updater event failures out of update state", () => {
341 const harness = makeHarness();
342 const cause = new Error(
343 "request failed for https://user:secret@example.com/update?token=secret",
344 );
345
346 return Effect.scoped(
347 Effect.gen(function* () {
348 const updates = yield* DesktopUpdates.DesktopUpdates;
349 yield* updates.configure;
350
351 harness.emit("error", cause);
352 yield* flushCallbacks;
353
354 const state = yield* updates.getState;
355 assert.equal(state.status, "error");
356 assert.equal(state.message, "Desktop updater background operation reported an error.");
357 assert.notInclude(state.message ?? "", "secret");
358 }),
359 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
360 });
361
362 it.effect("logs bounded updater failure context without exposing the cause", () => {
363 const cause = new Error(
364 "request failed for https://user:secret@example.com/update?token=secret",
365 );
366 const updaterError = new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({
367 channel: null,
368 cause,
369 });
370 const harness = makeHarness({ checkForUpdates: Effect.fail(updaterError) });
371 const loggedAnnotations: Array<Record<string, unknown>> = [];
372 const logger = Logger.make(({ fiber }) => {
373 const annotations = fiber.getRef(References.CurrentLogAnnotations);
374 if (annotations.errorTag === "ElectronUpdaterCheckForUpdatesError") {
375 loggedAnnotations.push(annotations);
376 }
377 });
378
379 return Effect.scoped(
380 Effect.gen(function* () {
381 const updates = yield* DesktopUpdates.DesktopUpdates;
382 yield* updates.configure;
383
384 yield* updates.check("manual");
385
386 const state = yield* updates.getState;
387 const loggedAnnotation = loggedAnnotations.at(-1);
388 assert.isDefined(loggedAnnotation);
389 assert.equal(loggedAnnotation.errorTag, "ElectronUpdaterCheckForUpdatesError");
390 assert.isNull(loggedAnnotation.channel);
391 assert.notProperty(loggedAnnotation, "error");
392 assert.notInclude(Object.values(loggedAnnotation).map(String).join(" "), "secret");
393 assert.equal(
394 state.message,
395 "Electron updater failed to check for updates on channel default.",
396 );
397 assert.notInclude(state.message ?? "", "secret");
398 }),
399 ).pipe(
400 Effect.provide(
401 Layer.mergeAll(
402 TestClock.layer(),
403 harness.layer,
404 Logger.layer([logger], { mergeWithExisting: false }),
405 ),
406 ),
407 );
408 });
409
410 it.effect("recovers download state after an unexpected setup failure", () => {
411 let disableDifferentialCalls = 0;
412 const harness = makeHarness({
413 setDisableDifferentialDownload: Effect.suspend(() => {
414 disableDifferentialCalls += 1;
415 return disableDifferentialCalls === 1
416 ? Effect.void
417 : Effect.die(new Error("download setup failed"));
418 }),
419 });
420
421 return Effect.scoped(
422 Effect.gen(function* () {
423 const updates = yield* DesktopUpdates.DesktopUpdates;
424 yield* updates.configure;
425 harness.emit("update-available", { version: "1.2.4" });
426 yield* flushCallbacks;
427
428 const result = yield* updates.download;
429 assert.isTrue(result.accepted);
430 assert.isFalse(result.completed);
431
432 const failedState = yield* updates.getState;
433 assert.equal(failedState.status, "available");
434 assert.equal(failedState.errorContext, "download");
435 assert.equal(failedState.message, "Desktop update download action failed unexpectedly.");
436
437 const changedState = yield* updates.setChannel("nightly");
438 assert.equal(changedState.channel, "nightly");
439 }),
440 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
441 });
442
443 it.effect("restores download state and permits retry after interruption", () =>
444 Effect.gen(function* () {
445 const actionStarted = yield* Deferred.make<void>();
446 let disableDifferentialCalls = 0;
447 const harness = makeHarness({
448 setDisableDifferentialDownload: Effect.suspend(() => {
449 disableDifferentialCalls += 1;
450 if (disableDifferentialCalls === 1) {
451 return Effect.void;
452 }
453 if (disableDifferentialCalls === 2) {
454 return Deferred.succeed(actionStarted, undefined).pipe(Effect.andThen(Effect.never));
455 }
456 return Effect.void;
457 }),
458 });
459
460 yield* Effect.scoped(
461 Effect.gen(function* () {
462 const updates = yield* DesktopUpdates.DesktopUpdates;
463 yield* updates.configure;
464 harness.emit("update-available", { version: "1.2.4" });
465 yield* flushCallbacks;
466
467 const downloadFiber = yield* updates.download.pipe(Effect.forkScoped);
468 yield* Deferred.await(actionStarted);
469 yield* Fiber.interrupt(downloadFiber);
470
471 const interruptedState = yield* updates.getState;
472 assert.equal(interruptedState.status, "available");
473 assert.isNull(interruptedState.message);
474
475 const retry = yield* updates.download;
476 assert.isTrue(retry.accepted);
477 assert.isTrue(retry.completed);
478 }),
479 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
480 }),
481 );
482
483 it.effect("clears quitting state after an unexpected install setup failure", () => {
484 const harness = makeHarness({
485 stopBackend: Effect.die(new Error("backend stop failed")),
486 });
487
488 return Effect.scoped(
489 Effect.gen(function* () {
490 const desktopState = yield* DesktopState.DesktopState;
491 const updates = yield* DesktopUpdates.DesktopUpdates;
492 yield* updates.configure;
493 harness.emit("update-downloaded", { version: "1.2.4" });
494 yield* flushCallbacks;
495
496 const result = yield* updates.install;
497 assert.isTrue(result.accepted);
498 assert.isFalse(result.completed);
499 assert.isFalse(yield* Ref.get(desktopState.quitting));
500
501 const failedState = yield* updates.getState;
502 assert.equal(failedState.status, "downloaded");
503 assert.equal(failedState.errorContext, "install");
504 assert.equal(failedState.message, "Desktop update install action failed unexpectedly.");
505
506 const changedState = yield* updates.setChannel("nightly");
507 assert.equal(changedState.channel, "nightly");
508 }),
509 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
510 });
511
512 it.effect("persists channel changes through the settings service", () => {
513 const harness = makeHarness();
514
515 return Effect.scoped(
516 Effect.gen(function* () {
517 const settings = yield* DesktopAppSettings.DesktopAppSettings;
518 const updates = yield* DesktopUpdates.DesktopUpdates;
519 yield* updates.configure;
520
521 const state = yield* updates.setChannel("nightly");
522 const persistedSettings = yield* settings.get;
523
524 assert.equal(state.channel, "nightly");
525 assert.equal(persistedSettings.updateChannel, "nightly");
526 assert.equal(persistedSettings.updateChannelConfiguredByUser, true);
527 }),
528 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
529 });
530
531 it.effect("does not persist an unchanged update channel as a user preference", () => {
532 const harness = makeHarness();
533
534 return Effect.scoped(
535 Effect.gen(function* () {
536 const settings = yield* DesktopAppSettings.DesktopAppSettings;
537 const updates = yield* DesktopUpdates.DesktopUpdates;
538 yield* updates.configure;
539
540 const state = yield* updates.setChannel("latest");
541 const persistedSettings = yield* settings.get;
542
543 assert.equal(state.channel, "latest");
544 assert.equal(persistedSettings.updateChannel, "latest");
545 assert.equal(persistedSettings.updateChannelConfiguredByUser, false);
546 }),
547 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
548 });
549
550 it.effect("fails channel changes with a typed error while a check is in progress", () =>
551 Effect.gen(function* () {
552 const checkStarted = yield* Deferred.make<void>();
553 const releaseCheck = yield* Deferred.make<void>();
554 const harness = makeHarness({
555 checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe(
556 Effect.andThen(Deferred.await(releaseCheck)),
557 ),
558 });
559
560 yield* Effect.scoped(
561 Effect.gen(function* () {
562 const updates = yield* DesktopUpdates.DesktopUpdates;
563 yield* updates.configure;
564
565 const checkFiber = yield* updates.check("manual").pipe(Effect.forkScoped);
566 yield* Deferred.await(checkStarted);
567
568 const exit = yield* Effect.exit(updates.setChannel("nightly"));
569 assert.equal(exit._tag, "Failure");
570 if (exit._tag === "Failure") {
571 const error = Cause.squash(exit.cause);
572 assert.instanceOf(error, DesktopUpdates.DesktopUpdateActionInProgressError);
573 assert.equal(error.action, "check");
574 assert.equal(error.requestedChannel, "nightly");
575 }
576
577 yield* Deferred.succeed(releaseCheck, undefined);
578 yield* Fiber.join(checkFiber);
579 }),
580 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
581 }),
582 );
583
584 it.effect("preserves settings failure context when an update channel cannot be persisted", () => {
585 const diskFailure = new Error("disk exploded");
586 const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
587 operation: "replace-settings-file",
588 path: "/tmp/settings.json",
589 cause: diskFailure,
590 });
591 const harness = makeHarness({ setUpdateChannelError: settingsFailure });
592
593 return Effect.scoped(
594 Effect.gen(function* () {
595 const updates = yield* DesktopUpdates.DesktopUpdates;
596 yield* updates.configure;
597
598 const error = yield* updates.setChannel("nightly").pipe(Effect.flip);
599
600 assert.instanceOf(error, DesktopUpdates.DesktopUpdateChannelPersistenceError);
601 assert.isTrue(DesktopUpdates.isDesktopUpdateSetChannelError(error));
602 assert.equal(error.channel, "nightly");
603 assert.strictEqual(error.cause, settingsFailure);
604 assert.strictEqual(error.cause.cause, diskFailure);
605 assert.equal(error.message, "Failed to persist the nightly desktop update channel.");
606 assert.notInclude(error.message, diskFailure.message);
607 }),
608 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
609 });
610});