Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopUpdates.test.ts

862 lines32.3 KB

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 beforeSetUpdateChannel?: Effect.Effect<void>;
31 readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
32 readonly setDisableDifferentialDownload?: Effect.Effect<void>;
33 readonly stopBackend?: Effect.Effect<void>;
34 readonly env?: Record<string, string | undefined>;
36​
37const flushCallbacks = Effect.yieldNow;
38​
39function makeHarness(options: UpdatesHarnessOptions = {}) {
40 let checkCount = 0;
41 let allowDowngrade = false;
42 let fullChangelog = false;
43 const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
44 const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
45 const sentStates: DesktopUpdateState[] = [];
46​
47 const addListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
48 const eventListeners = listeners.get(eventName) ?? new Set();
49 eventListeners.add(listener);
50 listeners.set(eventName, eventListeners);
51 };
52​
53 const removeListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
54 const eventListeners = listeners.get(eventName);
55 if (!eventListeners) {
56 return;
57 }
58 eventListeners.delete(listener);
59 if (eventListeners.size === 0) {
60 listeners.delete(eventName);
61 }
62 };
63​
64 const updaterLayer = Layer.succeed(ElectronUpdater.ElectronUpdater, {
65 setFeedURL: (options) =>
66 Effect.sync(() => {
67 feedUrls.push(options);
68 }),
69 setAutoDownload: () => Effect.void,
70 setAutoInstallOnAppQuit: () => Effect.void,
71 setChannel: () => Effect.void,
72 setAllowPrerelease: () => Effect.void,
73 allowDowngrade: Effect.sync(() => allowDowngrade),
74 setAllowDowngrade: (value) =>
75 Effect.sync(() => {
76 allowDowngrade = value;
77 }),
78 setFullChangelog: (value) =>
79 Effect.sync(() => {
80 fullChangelog = value;
81 }),
82 setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
83 checkForUpdates: Effect.sync(() => {
84 checkCount += 1;
85 }).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
86 downloadUpdate: Effect.void,
87 quitAndInstall: () => Effect.void,
88 on: (eventName, listener) =>
89 Effect.acquireRelease(
90 Effect.sync(() => {
91 addListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
92 }),
93 () =>
94 Effect.sync(() => {
95 removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
96 }),
97 ).pipe(Effect.asVoid),
98 } satisfies ElectronUpdater.ElectronUpdater["Service"]);
99​
100 const windowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
101 create: () => Effect.die("unexpected BrowserWindow creation"),
102 main: Effect.succeed(Option.none()),
103 currentMainOrFirst: Effect.succeed(Option.none()),
104 focusedMainOrFirst: Effect.succeed(Option.none()),
105 setMain: () => Effect.void,
106 clearMain: () => Effect.void,
107 reveal: () => Effect.void,
108 sendAll: (_channel, state) =>
109 Effect.sync(() => {
110 sentStates.push(state as DesktopUpdateState);
111 }),
112 destroyAll: Effect.void,
113 syncAllAppearance: () => Effect.void,
114 } satisfies ElectronWindow.ElectronWindow["Service"]);
115​
116 const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
117 id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
118 label: Effect.succeed("Windows"),
119 start: Effect.void,
120 stop: () => options.stopBackend ?? Effect.void,
121 currentConfig: Effect.succeed(Option.none()),
122 snapshot: Effect.succeed({
123 desiredRunning: false,
124 ready: false,
125 activePid: Option.none(),
126 restartAttempt: 0,
127 restartScheduled: false,
128 }),
129 waitForReady: () => Effect.succeed(true),
130 };
131 const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
132​
133 const environmentLayer = DesktopEnvironment.layer({
134 dirname: "/repo/apps/desktop/src",
135 homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
136 platform: "darwin",
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(
146 NodeServices.layer,
147 DesktopConfig.layerTest({
148 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
149 T3CODE_DESKTOP_MOCK_UPDATES: "true",
150 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
151 ...options.env,
152 }),
153 ),
154 ),
155 );
156​
157 let testSettings: DesktopAppSettings.DesktopSettings = {
158 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
159 };
160 const setUpdateChannelError = options.setUpdateChannelError;
161 const settingsLayer =
162 setUpdateChannelError || options.beforeSetUpdateChannel
163 ? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
164 get: Effect.sync(() => testSettings),
165 load: Effect.sync(() => testSettings),
166 setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
167 setServerExposureMode: () => Effect.die("unexpected server exposure update"),
168 setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
169 setUpdateChannel: (channel) =>
170 setUpdateChannelError
171 ? Effect.fail(setUpdateChannelError)
172 : (options.beforeSetUpdateChannel ?? Effect.void).pipe(
173 Effect.andThen(
174 Effect.sync(() => {
175 const changed = testSettings.updateChannel !== channel;
176 testSettings = {
177 ...testSettings,
178 updateChannel: channel,
179 updateChannelConfiguredByUser: true,
180 };
181 return { settings: testSettings, changed };
182 }),
183 ),
184 ),
185 setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
186 setWslDistro: () => Effect.die("unexpected WSL distro change"),
187 setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
188 applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
189 applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
190 } satisfies DesktopAppSettings.DesktopAppSettings["Service"])
191 : DesktopAppSettings.layer;
192​
193 const layer = DesktopUpdates.layer.pipe(
194 Layer.provideMerge(updaterLayer),
195 Layer.provideMerge(windowLayer),
196 Layer.provideMerge(backendLayer),
197 Layer.provideMerge(DesktopState.layer),
198 Layer.provideMerge(settingsLayer),
199 Layer.provideMerge(
200 DesktopConfig.layerTest({
201 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
202 T3CODE_DESKTOP_MOCK_UPDATES: "true",
203 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
204 ...options.env,
205 }),
206 ),
207 Layer.provideMerge(environmentLayer),
208 Layer.provideMerge(NodeServices.layer),
209 );
210​
211 return {
212 layer,
213 checkCount: () => checkCount,
214 feedUrls: () => feedUrls,
215 fullChangelog: () => fullChangelog,
216 listenerCount: () =>
217 Array.from(listeners.values()).reduce(
218 (total, eventListeners) => total + eventListeners.size,
219 0,
220 ),
221 sentStates,
222 emit: (eventName: string, payload?: unknown) => {
223 for (const listener of listeners.get(eventName) ?? []) {
224 listener(payload);
225 }
226 },
227 };
229​
230describe("DesktopUpdates", () => {
231 it("preserves complete causes for update poller and event failures", () => {
232 const cause = Cause.combine(
233 Cause.fail(new Error("updater failed")),
234 Cause.die(new Error("updater defect")),
235 );
236 const pollerError = new DesktopUpdates.DesktopUpdatePollerError({
237 poller: "startup",
238 cause,
239 });
240 const eventError = new DesktopUpdates.DesktopUpdateEventHandlingError({
241 event: "download-progress",
242 cause,
243 });
244 const reportedError = new DesktopUpdates.DesktopUpdaterReportedError({
245 operation: "download",
246 cause,
247 });
248 const unexpectedActionError = new DesktopUpdates.DesktopUpdateUnexpectedActionError({
249 action: "install",
250 cause,
251 });
252​
253 assert.strictEqual(pollerError.cause, cause);
254 assert.equal(pollerError.poller, "startup");
255 assert.equal(pollerError.message, "Desktop update startup poller failed.");
256 assert.strictEqual(eventError.cause, cause);
257 assert.equal(eventError.event, "download-progress");
258 assert.equal(eventError.message, "Failed to handle desktop update download-progress event.");
259 assert.strictEqual(reportedError.cause, cause);
260 assert.equal(reportedError.operation, "download");
261 assert.equal(reportedError.message, "Desktop updater download operation reported an error.");
262 assert.strictEqual(unexpectedActionError.cause, cause);
263 assert.equal(unexpectedActionError.action, "install");
264 assert.equal(
265 unexpectedActionError.message,
266 "Desktop update install action failed unexpectedly.",
267 );
268 });
269​
270 it.effect("configures the updater and runs startup checks on the test clock", () => {
271 const harness = makeHarness();
272​
273 return Effect.gen(function* () {
274 yield* Effect.scoped(
275 Effect.gen(function* () {
276 const updates = yield* DesktopUpdates.DesktopUpdates;
277 yield* updates.configure;
278​
279 const state = yield* updates.getState;
280 assert.equal(state.enabled, true);
281 assert.equal(state.status, "idle");
282 assert.deepEqual(harness.feedUrls(), [
283 { provider: "generic", url: "http://localhost:4141" },
284 ]);
285 assert.equal(harness.listenerCount(), 6);
286 assert.equal(harness.checkCount(), 0);
287​
288 yield* TestClock.adjust(Duration.millis(15_000));
289 assert.equal(harness.checkCount(), 1);
290 }),
291 );
292​
293 assert.equal(harness.listenerCount(), 0);
294 }).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
295 });
296​
297 it.effect("updates and broadcasts state from updater events", () => {
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 harness.emit("update-available", { version: "1.2.4" });
306 yield* flushCallbacks;
307​
308 const state = yield* updates.getState;
309 assert.equal(state.status, "available");
310 assert.equal(state.availableVersion, "1.2.4");
311 assert.isNotNull(state.checkedAt);
312 assert.equal(harness.sentStates.at(-1)?.status, "available");
313 }),
314 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
315 });
316​
317 it.effect("enables nightly full changelog release notes and broadcasts summaries", () => {
318 const harness = makeHarness();
319​
320 return Effect.scoped(
321 Effect.gen(function* () {
322 const updates = yield* DesktopUpdates.DesktopUpdates;
323 yield* updates.configure;
324​
325 yield* updates.setChannel("nightly");
326 assert.equal(harness.fullChangelog(), true);
327​
328 harness.emit("update-available", {
329 version: "1.2.4-nightly.20260709.766",
330 releaseNotes: [
331 {
332 version: "1.2.4-nightly.20260709.766",
333 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>`,
334 },
335 {
336 version: "1.2.4-nightly.20260709.765",
337 note: "- [codex] Upgrade Clerk stack by @juliusmarminge in #3821",
338 },
339 ],
340 });
341 yield* flushCallbacks;
342​
343 const state = yield* updates.getState;
344 assert.equal(state.status, "available");
345 assert.deepEqual(state.releaseNotes, [
346 {
347 version: "1.2.4-nightly.20260709.766",
348 items: ["feat(client): persist offline environment data by @juliusmarminge in #3795"],
349 },
350 {
351 version: "1.2.4-nightly.20260709.765",
352 items: ["[codex] Upgrade Clerk stack by @juliusmarminge in #3821"],
353 },
354 ]);
355 assert.deepEqual(harness.sentStates.at(-1)?.releaseNotes, state.releaseNotes);
356 }),
357 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
358 });
359​
360 it.effect("checks for newer releases after an update has been downloaded", () => {
361 const harness = makeHarness();
362​
363 return Effect.scoped(
364 Effect.gen(function* () {
365 const updates = yield* DesktopUpdates.DesktopUpdates;
366 yield* updates.configure;
367​
368 harness.emit("update-available", {
369 version: "1.2.4",
370 releaseNotes: "## What's changed\n- fix: queued update",
371 });
372 yield* flushCallbacks;
373 harness.emit("update-downloaded", { version: "1.2.4" });
374 yield* flushCallbacks;
375​
376 const result = yield* updates.check("poll");
377 assert.isTrue(result.checked);
378​
379 harness.emit("update-available", { version: "1.2.4" });
380 yield* flushCallbacks;
381​
382 const unchangedState = yield* updates.getState;
383 assert.equal(unchangedState.status, "downloaded");
384 assert.equal(unchangedState.downloadedVersion, "1.2.4");
385 assert.deepEqual(unchangedState.releaseNotes, [
386 { version: "1.2.4", items: ["fix: queued update"] },
387 ]);
388​
389 const nextResult = yield* updates.check("poll");
390 assert.isTrue(nextResult.checked);
391​
392 harness.emit("update-available", { version: "1.2.5" });
393 yield* flushCallbacks;
394​
395 const state = yield* updates.getState;
396 assert.equal(state.status, "available");
397 assert.equal(state.availableVersion, "1.2.5");
398 assert.isNull(state.downloadedVersion);
399 }),
400 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
401 });
402​
403 it.effect("preserves a queued installer when the feed has no update", () => {
404 const harness = makeHarness();
405​
406 return Effect.scoped(
407 Effect.gen(function* () {
408 const updates = yield* DesktopUpdates.DesktopUpdates;
409 yield* updates.configure;
410​
411 harness.emit("update-available", {
412 version: "1.2.4",
413 releaseNotes: "## What's changed\n- fix: queued update",
414 });
415 yield* flushCallbacks;
416 harness.emit("update-downloaded", { version: "1.2.4" });
417 yield* flushCallbacks;
418​
419 yield* updates.check("poll");
420 harness.emit("update-not-available");
421 yield* flushCallbacks;
422​
423 const state = yield* updates.getState;
424 assert.equal(state.status, "downloaded");
425 assert.equal(state.availableVersion, "1.2.4");
426 assert.equal(state.downloadedVersion, "1.2.4");
427 assert.deepEqual(state.releaseNotes, [{ version: "1.2.4", items: ["fix: queued update"] }]);
428 assert.equal(state.downloadPercent, 100);
429 }),
430 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
431 });
432​
433 it.effect("preserves a queued installer when the feed offers another channel", () => {
434 const harness = makeHarness();
435​
436 return Effect.scoped(
437 Effect.gen(function* () {
438 const updates = yield* DesktopUpdates.DesktopUpdates;
439 yield* updates.configure;
440​
441 harness.emit("update-available", {
442 version: "1.2.4",
443 releaseNotes: "## What's changed\n- fix: queued update",
444 });
445 yield* flushCallbacks;
446 harness.emit("update-downloaded", { version: "1.2.4" });
447 yield* flushCallbacks;
448​
449 yield* updates.check("poll");
450 harness.emit("update-available", { version: "1.2.5-nightly.20260710.1" });
451 yield* flushCallbacks;
452​
453 const state = yield* updates.getState;
454 assert.equal(state.status, "downloaded");
455 assert.equal(state.availableVersion, "1.2.4");
456 assert.equal(state.downloadedVersion, "1.2.4");
457 assert.deepEqual(state.releaseNotes, [{ version: "1.2.4", items: ["fix: queued update"] }]);
458 assert.equal(state.downloadPercent, 100);
459 }),
460 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
461 });
462​
463 it.effect(
464 "rejects install while a refresh check is in progress and releases the reservation",
465 () =>
466 Effect.gen(function* () {
467 const checkStarted = yield* Deferred.make<void>();
468 const releaseCheck = yield* Deferred.make<void>();
469 const harness = makeHarness({
470 checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe(
471 Effect.andThen(Deferred.await(releaseCheck)),
472 ),
473 });
474​
475 yield* Effect.scoped(
476 Effect.gen(function* () {
477 const updates = yield* DesktopUpdates.DesktopUpdates;
478 yield* updates.configure;
479 harness.emit("update-downloaded", { version: "1.2.4" });
480 yield* flushCallbacks;
481​
482 const checkFiber = yield* updates.check("manual").pipe(Effect.forkScoped);
483 yield* Deferred.await(checkStarted);
484​
485 const installResult = yield* updates.install;
486 assert.isFalse(installResult.accepted);
487​
488 yield* Deferred.succeed(releaseCheck, undefined);
489 const checkResult = yield* Fiber.join(checkFiber);
490 assert.isTrue(checkResult.checked);
491​
492 const followUpCheck = yield* updates.check("manual");
493 assert.isTrue(followUpCheck.checked);
494 assert.equal(harness.checkCount(), 2);
495 }),
496 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
497 }),
498 );
499​
500 it.effect("rejects refresh checks while install is in progress", () =>
501 Effect.gen(function* () {
502 const installStarted = yield* Deferred.make<void>();
503 const releaseInstall = yield* Deferred.make<void>();
504 const harness = makeHarness({
505 stopBackend: Deferred.succeed(installStarted, undefined).pipe(
506 Effect.andThen(Deferred.await(releaseInstall)),
507 ),
508 });
509​
510 yield* Effect.scoped(
511 Effect.gen(function* () {
512 const updates = yield* DesktopUpdates.DesktopUpdates;
513 yield* updates.configure;
514 harness.emit("update-downloaded", { version: "1.2.4" });
515 yield* flushCallbacks;
516​
517 const installFiber = yield* updates.install.pipe(Effect.forkScoped);
518 yield* Deferred.await(installStarted);
519​
520 const checkResult = yield* updates.check("manual");
521 assert.isFalse(checkResult.checked);
522 assert.equal(harness.checkCount(), 0);
523​
524 yield* Deferred.succeed(releaseInstall, undefined);
525 const installResult = yield* Fiber.join(installFiber);
526 assert.isTrue(installResult.accepted);
527 }),
528 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
529 }),
530 );
531​
532 it.effect("keeps raw updater event failures out of update state", () => {
533 const harness = makeHarness();
534 const cause = new Error(
535 "request failed for https://user:secret@example.com/update?token=secret",
536 );
537​
538 return Effect.scoped(
539 Effect.gen(function* () {
540 const updates = yield* DesktopUpdates.DesktopUpdates;
541 yield* updates.configure;
542​
543 harness.emit("error", cause);
544 yield* flushCallbacks;
545​
546 const state = yield* updates.getState;
547 assert.equal(state.status, "error");
548 assert.equal(state.message, "Desktop updater background operation reported an error.");
549 assert.notInclude(state.message ?? "", "secret");
550 }),
551 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
552 });
553​
554 it.effect("preserves a queued installer after a background updater error", () => {
555 const harness = makeHarness();
556​
557 return Effect.scoped(
558 Effect.gen(function* () {
559 const updates = yield* DesktopUpdates.DesktopUpdates;
560 yield* updates.configure;
561 harness.emit("update-downloaded", { version: "1.2.4" });
562 yield* flushCallbacks;
563​
564 harness.emit("error", new Error("background updater failure"));
565 yield* flushCallbacks;
566​
567 const state = yield* updates.getState;
568 assert.equal(state.status, "error");
569 assert.equal(state.downloadedVersion, "1.2.4");
570 assert.isNull(state.errorContext);
571​
572 const result = yield* updates.install;
573 assert.isTrue(result.accepted);
574 }),
575 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
576 });
577​
578 it.effect("logs bounded updater failure context without exposing the cause", () => {
579 const cause = new Error(
580 "request failed for https://user:secret@example.com/update?token=secret",
581 );
582 const updaterError = new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({
583 channel: null,
584 cause,
585 });
586 const harness = makeHarness({ checkForUpdates: Effect.fail(updaterError) });
587 const loggedAnnotations: Array<Record<string, unknown>> = [];
588 const logger = Logger.make(({ fiber }) => {
589 const annotations = fiber.getRef(References.CurrentLogAnnotations);
590 if (annotations.errorTag === "ElectronUpdaterCheckForUpdatesError") {
591 loggedAnnotations.push(annotations);
592 }
593 });
594​
595 return Effect.scoped(
596 Effect.gen(function* () {
597 const updates = yield* DesktopUpdates.DesktopUpdates;
598 yield* updates.configure;
599​
600 yield* updates.check("manual");
601​
602 const state = yield* updates.getState;
603 const loggedAnnotation = loggedAnnotations.at(-1);
604 assert.isDefined(loggedAnnotation);
605 assert.equal(loggedAnnotation.errorTag, "ElectronUpdaterCheckForUpdatesError");
606 assert.isNull(loggedAnnotation.channel);
607 assert.notProperty(loggedAnnotation, "error");
608 assert.notInclude(Object.values(loggedAnnotation).map(String).join(" "), "secret");
609 assert.equal(
610 state.message,
611 "Electron updater failed to check for updates on channel default.",
612 );
613 assert.notInclude(state.message ?? "", "secret");
614 }),
615 ).pipe(
616 Effect.provide(
617 Layer.mergeAll(
618 TestClock.layer(),
619 harness.layer,
620 Logger.layer([logger], { mergeWithExisting: false }),
621 ),
622 ),
623 );
624 });
625​
626 it.effect("recovers download state after an unexpected setup failure", () => {
627 let disableDifferentialCalls = 0;
628 const harness = makeHarness({
629 setDisableDifferentialDownload: Effect.suspend(() => {
630 disableDifferentialCalls += 1;
631 return disableDifferentialCalls === 1
632 ? Effect.void
633 : Effect.die(new Error("download setup failed"));
634 }),
635 });
636​
637 return Effect.scoped(
638 Effect.gen(function* () {
639 const updates = yield* DesktopUpdates.DesktopUpdates;
640 yield* updates.configure;
641 harness.emit("update-available", { version: "1.2.4" });
642 yield* flushCallbacks;
643​
644 const result = yield* updates.download;
645 assert.isTrue(result.accepted);
646 assert.isFalse(result.completed);
647​
648 const failedState = yield* updates.getState;
649 assert.equal(failedState.status, "available");
650 assert.equal(failedState.errorContext, "download");
651 assert.equal(failedState.message, "Desktop update download action failed unexpectedly.");
652​
653 const changedState = yield* updates.setChannel("nightly");
654 assert.equal(changedState.channel, "nightly");
655 }),
656 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
657 });
658​
659 it.effect("restores download state and permits retry after interruption", () =>
660 Effect.gen(function* () {
661 const actionStarted = yield* Deferred.make<void>();
662 let disableDifferentialCalls = 0;
663 const harness = makeHarness({
664 setDisableDifferentialDownload: Effect.suspend(() => {
665 disableDifferentialCalls += 1;
666 if (disableDifferentialCalls === 1) {
667 return Effect.void;
668 }
669 if (disableDifferentialCalls === 2) {
670 return Deferred.succeed(actionStarted, undefined).pipe(Effect.andThen(Effect.never));
671 }
672 return Effect.void;
673 }),
674 });
675​
676 yield* Effect.scoped(
677 Effect.gen(function* () {
678 const updates = yield* DesktopUpdates.DesktopUpdates;
679 yield* updates.configure;
680 harness.emit("update-available", { version: "1.2.4" });
681 yield* flushCallbacks;
682​
683 const downloadFiber = yield* updates.download.pipe(Effect.forkScoped);
684 yield* Deferred.await(actionStarted);
685 yield* Fiber.interrupt(downloadFiber);
686​
687 const interruptedState = yield* updates.getState;
688 assert.equal(interruptedState.status, "available");
689 assert.isNull(interruptedState.message);
690​
691 const retry = yield* updates.download;
692 assert.isTrue(retry.accepted);
693 assert.isTrue(retry.completed);
694 }),
695 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
696 }),
697 );
698​
699 it.effect("clears quitting state after an unexpected install setup failure", () => {
700 const harness = makeHarness({
701 stopBackend: Effect.die(new Error("backend stop failed")),
702 });
703​
704 return Effect.scoped(
705 Effect.gen(function* () {
706 const desktopState = yield* DesktopState.DesktopState;
707 const updates = yield* DesktopUpdates.DesktopUpdates;
708 yield* updates.configure;
709 harness.emit("update-downloaded", { version: "1.2.4" });
710 yield* flushCallbacks;
711​
712 const result = yield* updates.install;
713 assert.isTrue(result.accepted);
714 assert.isFalse(result.completed);
715 assert.isFalse(yield* Ref.get(desktopState.quitting));
716​
717 const failedState = yield* updates.getState;
718 assert.equal(failedState.status, "downloaded");
719 assert.equal(failedState.errorContext, "install");
720 assert.equal(failedState.message, "Desktop update install action failed unexpectedly.");
721​
722 const changedState = yield* updates.setChannel("nightly");
723 assert.equal(changedState.channel, "nightly");
724 }),
725 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
726 });
727​
728 it.effect("persists channel changes through the settings service", () => {
729 const harness = makeHarness();
730​
731 return Effect.scoped(
732 Effect.gen(function* () {
733 const settings = yield* DesktopAppSettings.DesktopAppSettings;
734 const updates = yield* DesktopUpdates.DesktopUpdates;
735 yield* updates.configure;
736​
737 const state = yield* updates.setChannel("nightly");
738 const persistedSettings = yield* settings.get;
739​
740 assert.equal(state.channel, "nightly");
741 assert.equal(persistedSettings.updateChannel, "nightly");
742 assert.equal(persistedSettings.updateChannelConfiguredByUser, true);
743 }),
744 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
745 });
746​
747 it.effect("does not persist an unchanged update channel as a user preference", () => {
748 const harness = makeHarness();
749​
750 return Effect.scoped(
751 Effect.gen(function* () {
752 const settings = yield* DesktopAppSettings.DesktopAppSettings;
753 const updates = yield* DesktopUpdates.DesktopUpdates;
754 yield* updates.configure;
755​
756 const state = yield* updates.setChannel("latest");
757 const persistedSettings = yield* settings.get;
758​
759 assert.equal(state.channel, "latest");
760 assert.equal(persistedSettings.updateChannel, "latest");
761 assert.equal(persistedSettings.updateChannelConfiguredByUser, false);
762 }),
763 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
764 });
765​
766 it.effect("fails channel changes with a typed error while a check is in progress", () =>
767 Effect.gen(function* () {
768 const checkStarted = yield* Deferred.make<void>();
769 const releaseCheck = yield* Deferred.make<void>();
770 const harness = makeHarness({
771 checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe(
772 Effect.andThen(Deferred.await(releaseCheck)),
773 ),
774 });
775​
776 yield* Effect.scoped(
777 Effect.gen(function* () {
778 const updates = yield* DesktopUpdates.DesktopUpdates;
779 yield* updates.configure;
780​
781 const checkFiber = yield* updates.check("manual").pipe(Effect.forkScoped);
782 yield* Deferred.await(checkStarted);
783​
784 const exit = yield* Effect.exit(updates.setChannel("nightly"));
785 assert.equal(exit._tag, "Failure");
786 if (exit._tag === "Failure") {
787 const error = Cause.squash(exit.cause);
788 assert.instanceOf(error, DesktopUpdates.DesktopUpdateActionInProgressError);
789 assert.equal(error.action, "check");
790 assert.equal(error.requestedChannel, "nightly");
791 }
792​
793 yield* Deferred.succeed(releaseCheck, undefined);
794 yield* Fiber.join(checkFiber);
795 }),
796 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
797 }),
798 );
799​
800 it.effect("rejects checks while an update channel change is being persisted", () =>
801 Effect.gen(function* () {
802 const channelChangeStarted = yield* Deferred.make<void>();
803 const releaseChannelChange = yield* Deferred.make<void>();
804 const harness = makeHarness({
805 beforeSetUpdateChannel: Deferred.succeed(channelChangeStarted, undefined).pipe(
806 Effect.andThen(Deferred.await(releaseChannelChange)),
807 ),
808 });
809​
810 yield* Effect.scoped(
811 Effect.gen(function* () {
812 const updates = yield* DesktopUpdates.DesktopUpdates;
813 yield* updates.configure;
814​
815 const channelFiber = yield* updates.setChannel("nightly").pipe(Effect.forkScoped);
816 yield* Deferred.await(channelChangeStarted);
817​
818 const checkResult = yield* updates.check("manual");
819 assert.isFalse(checkResult.checked);
820 assert.equal(harness.checkCount(), 0);
821​
822 yield* Deferred.succeed(releaseChannelChange, undefined);
823 const state = yield* Fiber.join(channelFiber);
824​
825 assert.equal(state.channel, "nightly");
826 assert.equal(harness.checkCount(), 1);
827 }),
828 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
829 }),
830 );
831​
832 it.effect("preserves settings failure context when an update channel cannot be persisted", () => {
833 const diskFailure = new Error("disk exploded");
834 const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
835 operation: "replace-settings-file",
836 path: "/tmp/settings.json",
837 cause: diskFailure,
838 });
839 const harness = makeHarness({ setUpdateChannelError: settingsFailure });
840​
841 return Effect.scoped(
842 Effect.gen(function* () {
843 const updates = yield* DesktopUpdates.DesktopUpdates;
844 yield* updates.configure;
845​
846 const error = yield* updates.setChannel("nightly").pipe(Effect.flip);
847​
848 assert.instanceOf(error, DesktopUpdates.DesktopUpdateChannelPersistenceError);
849 assert.isTrue(DesktopUpdates.isDesktopUpdateSetChannelError(error));
850 assert.equal(error.channel, "nightly");
851 assert.strictEqual(error.cause, settingsFailure);
852 assert.strictEqual(error.cause.cause, diskFailure);
853 assert.equal(error.message, "Failed to persist the nightly desktop update channel.");
854 assert.notInclude(error.message, diskFailure.message);
855​
856 const checkResult = yield* updates.check("manual");
857 assert.isTrue(checkResult.checked);
858 assert.equal(harness.checkCount(), 1);
859 }),
860 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
861 });
862});