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 setServerExposureMode: () => Effect.die("unexpected server exposure update"),
162 setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
163 setUpdateChannel: () => Effect.fail(setUpdateChannelError),
164 setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
165 setWslDistro: () => Effect.die("unexpected WSL distro change"),
166 setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
167 applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
168 applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
169 } satisfies DesktopAppSettings.DesktopAppSettings["Service"])
170 : DesktopAppSettings.layer;
171
172 const layer = DesktopUpdates.layer.pipe(
173 Layer.provideMerge(updaterLayer),
174 Layer.provideMerge(windowLayer),
175 Layer.provideMerge(backendLayer),
176 Layer.provideMerge(DesktopState.layer),
177 Layer.provideMerge(settingsLayer),
178 Layer.provideMerge(
179 DesktopConfig.layerTest({
180 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
181 T3CODE_DESKTOP_MOCK_UPDATES: "true",
182 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
183 ...options.env,
184 }),
185 ),
186 Layer.provideMerge(environmentLayer),
187 Layer.provideMerge(NodeServices.layer),
188 );
189
190 return {
191 layer,
192 checkCount: () => checkCount,
193 feedUrls: () => feedUrls,
194 fullChangelog: () => fullChangelog,
195 listenerCount: () =>
196 Array.from(listeners.values()).reduce(
197 (total, eventListeners) => total + eventListeners.size,
198 0,
199 ),
200 sentStates,
201 emit: (eventName: string, payload?: unknown) => {
202 for (const listener of listeners.get(eventName) ?? []) {
203 listener(payload);
204 }
205 },
206 };
207}
208
209describe("DesktopUpdates", () => {
210 it("preserves complete causes for update poller and event failures", () => {
211 const cause = Cause.combine(
212 Cause.fail(new Error("updater failed")),
213 Cause.die(new Error("updater defect")),
214 );
215 const pollerError = new DesktopUpdates.DesktopUpdatePollerError({
216 poller: "startup",
217 cause,
218 });
219 const eventError = new DesktopUpdates.DesktopUpdateEventHandlingError({
220 event: "download-progress",
221 cause,
222 });
223 const reportedError = new DesktopUpdates.DesktopUpdaterReportedError({
224 operation: "download",
225 cause,
226 });
227 const unexpectedActionError = new DesktopUpdates.DesktopUpdateUnexpectedActionError({
228 action: "install",
229 cause,
230 });
231
232 assert.strictEqual(pollerError.cause, cause);
233 assert.equal(pollerError.poller, "startup");
234 assert.equal(pollerError.message, "Desktop update startup poller failed.");
235 assert.strictEqual(eventError.cause, cause);
236 assert.equal(eventError.event, "download-progress");
237 assert.equal(eventError.message, "Failed to handle desktop update download-progress event.");
238 assert.strictEqual(reportedError.cause, cause);
239 assert.equal(reportedError.operation, "download");
240 assert.equal(reportedError.message, "Desktop updater download operation reported an error.");
241 assert.strictEqual(unexpectedActionError.cause, cause);
242 assert.equal(unexpectedActionError.action, "install");
243 assert.equal(
244 unexpectedActionError.message,
245 "Desktop update install action failed unexpectedly.",
246 );
247 });
248
249 it.effect("configures the updater and runs startup checks on the test clock", () => {
250 const harness = makeHarness();
251
252 return Effect.gen(function* () {
253 yield* Effect.scoped(
254 Effect.gen(function* () {
255 const updates = yield* DesktopUpdates.DesktopUpdates;
256 yield* updates.configure;
257
258 const state = yield* updates.getState;
259 assert.equal(state.enabled, true);
260 assert.equal(state.status, "idle");
261 assert.deepEqual(harness.feedUrls(), [
262 { provider: "generic", url: "http://localhost:4141" },
263 ]);
264 assert.equal(harness.listenerCount(), 6);
265 assert.equal(harness.checkCount(), 0);
266
267 yield* TestClock.adjust(Duration.millis(15_000));
268 assert.equal(harness.checkCount(), 1);
269 }),
270 );
271
272 assert.equal(harness.listenerCount(), 0);
273 }).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
274 });
275
276 it.effect("updates and broadcasts state from updater events", () => {
277 const harness = makeHarness();
278
279 return Effect.scoped(
280 Effect.gen(function* () {
281 const updates = yield* DesktopUpdates.DesktopUpdates;
282 yield* updates.configure;
283
284 harness.emit("update-available", { version: "1.2.4" });
285 yield* flushCallbacks;
286
287 const state = yield* updates.getState;
288 assert.equal(state.status, "available");
289 assert.equal(state.availableVersion, "1.2.4");
290 assert.isNotNull(state.checkedAt);
291 assert.equal(harness.sentStates.at(-1)?.status, "available");
292 }),
293 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
294 });
295
296 it.effect("enables nightly full changelog release notes and broadcasts summaries", () => {
297 const harness = makeHarness();
298
299 return Effect.scoped(
300 Effect.gen(function* () {
301 const updates = yield* DesktopUpdates.DesktopUpdates;
302 yield* updates.configure;
303
304 yield* updates.setChannel("nightly");
305 assert.equal(harness.fullChangelog(), true);
306
307 harness.emit("update-available", {
308 version: "1.2.4-nightly.20260709.766",
309 releaseNotes: [
310 {
311 version: "1.2.4-nightly.20260709.766",
312 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>`,
313 },
314 {
315 version: "1.2.4-nightly.20260709.765",
316 note: "- [codex] Upgrade Clerk stack by @juliusmarminge in #3821",
317 },
318 ],
319 });
320 yield* flushCallbacks;
321
322 const state = yield* updates.getState;
323 assert.equal(state.status, "available");
324 assert.deepEqual(state.releaseNotes, [
325 {
326 version: "1.2.4-nightly.20260709.766",
327 items: ["feat(client): persist offline environment data by @juliusmarminge in #3795"],
328 },
329 {
330 version: "1.2.4-nightly.20260709.765",
331 items: ["[codex] Upgrade Clerk stack by @juliusmarminge in #3821"],
332 },
333 ]);
334 assert.deepEqual(harness.sentStates.at(-1)?.releaseNotes, state.releaseNotes);
335 }),
336 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
337 });
338
339 it.effect("keeps raw updater event failures out of update state", () => {
340 const harness = makeHarness();
341 const cause = new Error(
342 "request failed for https://user:secret@example.com/update?token=secret",
343 );
344
345 return Effect.scoped(
346 Effect.gen(function* () {
347 const updates = yield* DesktopUpdates.DesktopUpdates;
348 yield* updates.configure;
349
350 harness.emit("error", cause);
351 yield* flushCallbacks;
352
353 const state = yield* updates.getState;
354 assert.equal(state.status, "error");
355 assert.equal(state.message, "Desktop updater background operation reported an error.");
356 assert.notInclude(state.message ?? "", "secret");
357 }),
358 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
359 });
360
361 it.effect("logs bounded updater failure context without exposing the cause", () => {
362 const cause = new Error(
363 "request failed for https://user:secret@example.com/update?token=secret",
364 );
365 const updaterError = new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({
366 channel: null,
367 cause,
368 });
369 const harness = makeHarness({ checkForUpdates: Effect.fail(updaterError) });
370 const loggedAnnotations: Array<Record<string, unknown>> = [];
371 const logger = Logger.make(({ fiber }) => {
372 const annotations = fiber.getRef(References.CurrentLogAnnotations);
373 if (annotations.errorTag === "ElectronUpdaterCheckForUpdatesError") {
374 loggedAnnotations.push(annotations);
375 }
376 });
377
378 return Effect.scoped(
379 Effect.gen(function* () {
380 const updates = yield* DesktopUpdates.DesktopUpdates;
381 yield* updates.configure;
382
383 yield* updates.check("manual");
384
385 const state = yield* updates.getState;
386 const loggedAnnotation = loggedAnnotations.at(-1);
387 assert.isDefined(loggedAnnotation);
388 assert.equal(loggedAnnotation.errorTag, "ElectronUpdaterCheckForUpdatesError");
389 assert.isNull(loggedAnnotation.channel);
390 assert.notProperty(loggedAnnotation, "error");
391 assert.notInclude(Object.values(loggedAnnotation).map(String).join(" "), "secret");
392 assert.equal(
393 state.message,
394 "Electron updater failed to check for updates on channel default.",
395 );
396 assert.notInclude(state.message ?? "", "secret");
397 }),
398 ).pipe(
399 Effect.provide(
400 Layer.mergeAll(
401 TestClock.layer(),
402 harness.layer,
403 Logger.layer([logger], { mergeWithExisting: false }),
404 ),
405 ),
406 );
407 });
408
409 it.effect("recovers download state after an unexpected setup failure", () => {
410 let disableDifferentialCalls = 0;
411 const harness = makeHarness({
412 setDisableDifferentialDownload: Effect.suspend(() => {
413 disableDifferentialCalls += 1;
414 return disableDifferentialCalls === 1
415 ? Effect.void
416 : Effect.die(new Error("download setup failed"));
417 }),
418 });
419
420 return Effect.scoped(
421 Effect.gen(function* () {
422 const updates = yield* DesktopUpdates.DesktopUpdates;
423 yield* updates.configure;
424 harness.emit("update-available", { version: "1.2.4" });
425 yield* flushCallbacks;
426
427 const result = yield* updates.download;
428 assert.isTrue(result.accepted);
429 assert.isFalse(result.completed);
430
431 const failedState = yield* updates.getState;
432 assert.equal(failedState.status, "available");
433 assert.equal(failedState.errorContext, "download");
434 assert.equal(failedState.message, "Desktop update download action failed unexpectedly.");
435
436 const changedState = yield* updates.setChannel("nightly");
437 assert.equal(changedState.channel, "nightly");
438 }),
439 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
440 });
441
442 it.effect("restores download state and permits retry after interruption", () =>
443 Effect.gen(function* () {
444 const actionStarted = yield* Deferred.make<void>();
445 let disableDifferentialCalls = 0;
446 const harness = makeHarness({
447 setDisableDifferentialDownload: Effect.suspend(() => {
448 disableDifferentialCalls += 1;
449 if (disableDifferentialCalls === 1) {
450 return Effect.void;
451 }
452 if (disableDifferentialCalls === 2) {
453 return Deferred.succeed(actionStarted, undefined).pipe(Effect.andThen(Effect.never));
454 }
455 return Effect.void;
456 }),
457 });
458
459 yield* Effect.scoped(
460 Effect.gen(function* () {
461 const updates = yield* DesktopUpdates.DesktopUpdates;
462 yield* updates.configure;
463 harness.emit("update-available", { version: "1.2.4" });
464 yield* flushCallbacks;
465
466 const downloadFiber = yield* updates.download.pipe(Effect.forkScoped);
467 yield* Deferred.await(actionStarted);
468 yield* Fiber.interrupt(downloadFiber);
469
470 const interruptedState = yield* updates.getState;
471 assert.equal(interruptedState.status, "available");
472 assert.isNull(interruptedState.message);
473
474 const retry = yield* updates.download;
475 assert.isTrue(retry.accepted);
476 assert.isTrue(retry.completed);
477 }),
478 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
479 }),
480 );
481
482 it.effect("clears quitting state after an unexpected install setup failure", () => {
483 const harness = makeHarness({
484 stopBackend: Effect.die(new Error("backend stop failed")),
485 });
486
487 return Effect.scoped(
488 Effect.gen(function* () {
489 const desktopState = yield* DesktopState.DesktopState;
490 const updates = yield* DesktopUpdates.DesktopUpdates;
491 yield* updates.configure;
492 harness.emit("update-downloaded", { version: "1.2.4" });
493 yield* flushCallbacks;
494
495 const result = yield* updates.install;
496 assert.isTrue(result.accepted);
497 assert.isFalse(result.completed);
498 assert.isFalse(yield* Ref.get(desktopState.quitting));
499
500 const failedState = yield* updates.getState;
501 assert.equal(failedState.status, "downloaded");
502 assert.equal(failedState.errorContext, "install");
503 assert.equal(failedState.message, "Desktop update install action failed unexpectedly.");
504
505 const changedState = yield* updates.setChannel("nightly");
506 assert.equal(changedState.channel, "nightly");
507 }),
508 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
509 });
510
511 it.effect("persists channel changes through the settings service", () => {
512 const harness = makeHarness();
513
514 return Effect.scoped(
515 Effect.gen(function* () {
516 const settings = yield* DesktopAppSettings.DesktopAppSettings;
517 const updates = yield* DesktopUpdates.DesktopUpdates;
518 yield* updates.configure;
519
520 const state = yield* updates.setChannel("nightly");
521 const persistedSettings = yield* settings.get;
522
523 assert.equal(state.channel, "nightly");
524 assert.equal(persistedSettings.updateChannel, "nightly");
525 assert.equal(persistedSettings.updateChannelConfiguredByUser, true);
526 }),
527 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
528 });
529
530 it.effect("does not persist an unchanged update channel as a user preference", () => {
531 const harness = makeHarness();
532
533 return Effect.scoped(
534 Effect.gen(function* () {
535 const settings = yield* DesktopAppSettings.DesktopAppSettings;
536 const updates = yield* DesktopUpdates.DesktopUpdates;
537 yield* updates.configure;
538
539 const state = yield* updates.setChannel("latest");
540 const persistedSettings = yield* settings.get;
541
542 assert.equal(state.channel, "latest");
543 assert.equal(persistedSettings.updateChannel, "latest");
544 assert.equal(persistedSettings.updateChannelConfiguredByUser, false);
545 }),
546 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
547 });
548
549 it.effect("fails channel changes with a typed error while a check is in progress", () =>
550 Effect.gen(function* () {
551 const checkStarted = yield* Deferred.make<void>();
552 const releaseCheck = yield* Deferred.make<void>();
553 const harness = makeHarness({
554 checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe(
555 Effect.andThen(Deferred.await(releaseCheck)),
556 ),
557 });
558
559 yield* Effect.scoped(
560 Effect.gen(function* () {
561 const updates = yield* DesktopUpdates.DesktopUpdates;
562 yield* updates.configure;
563
564 const checkFiber = yield* updates.check("manual").pipe(Effect.forkScoped);
565 yield* Deferred.await(checkStarted);
566
567 const exit = yield* Effect.exit(updates.setChannel("nightly"));
568 assert.equal(exit._tag, "Failure");
569 if (exit._tag === "Failure") {
570 const error = Cause.squash(exit.cause);
571 assert.instanceOf(error, DesktopUpdates.DesktopUpdateActionInProgressError);
572 assert.equal(error.action, "check");
573 assert.equal(error.requestedChannel, "nightly");
574 }
575
576 yield* Deferred.succeed(releaseCheck, undefined);
577 yield* Fiber.join(checkFiber);
578 }),
579 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
580 }),
581 );
582
583 it.effect("preserves settings failure context when an update channel cannot be persisted", () => {
584 const diskFailure = new Error("disk exploded");
585 const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
586 operation: "replace-settings-file",
587 path: "/tmp/settings.json",
588 cause: diskFailure,
589 });
590 const harness = makeHarness({ setUpdateChannelError: settingsFailure });
591
592 return Effect.scoped(
593 Effect.gen(function* () {
594 const updates = yield* DesktopUpdates.DesktopUpdates;
595 yield* updates.configure;
596
597 const error = yield* updates.setChannel("nightly").pipe(Effect.flip);
598
599 assert.instanceOf(error, DesktopUpdates.DesktopUpdateChannelPersistenceError);
600 assert.isTrue(DesktopUpdates.isDesktopUpdateSetChannelError(error));
601 assert.equal(error.channel, "nightly");
602 assert.strictEqual(error.cause, settingsFailure);
603 assert.strictEqual(error.cause.cause, diskFailure);
604 assert.equal(error.message, "Failed to persist the nightly desktop update channel.");
605 assert.notInclude(error.message, diskFailure.message);
606 }),
607 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
608 });
609});