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

DesktopUpdates.test.ts

1,050 lines40.1 KB

1import { assert, describe, it } from "@effect/vitest";
2import { DESKTOP_UPDATE_RESTART_MARKER_FILE } from "@t3tools/contracts";
3import * as Cause from "effect/Cause";
4import * as Deferred from "effect/Deferred";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as Layer from "effect/Layer";
9import * as Logger from "effect/Logger";
10import * as Option from "effect/Option";
11import * as References from "effect/References";
12import * as Ref from "effect/Ref";
13import * as Stream from "effect/Stream";
14import * as TestClock from "effect/testing/TestClock";
15​
16import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
17import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
18import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
19import * as DesktopState from "../app/DesktopState.ts";
20import * as DesktopUpdates from "./DesktopUpdates.ts";
21import { flushCallbacks, makeHarness } from "./updatesTestHarness.ts";
22​
23describe("DesktopUpdates", () => {
24 it("preserves complete causes for update poller and event failures", () => {
25 const cause = Cause.combine(
26 Cause.fail(new Error("updater failed")),
27 Cause.die(new Error("updater defect")),
28 );
29 const pollerError = new DesktopUpdates.DesktopUpdatePollerError({
30 poller: "startup",
31 cause,
32 });
33 const eventError = new DesktopUpdates.DesktopUpdateEventHandlingError({
34 event: "download-progress",
35 cause,
36 });
37 const reportedError = new DesktopUpdates.DesktopUpdaterReportedError({
38 operation: "download",
39 cause,
40 });
41 const unexpectedActionError = new DesktopUpdates.DesktopUpdateUnexpectedActionError({
42 action: "install",
43 cause,
44 });
45​
46 assert.strictEqual(pollerError.cause, cause);
47 assert.equal(pollerError.poller, "startup");
48 assert.equal(pollerError.message, "Desktop update startup poller failed.");
49 assert.strictEqual(eventError.cause, cause);
50 assert.equal(eventError.event, "download-progress");
51 assert.equal(eventError.message, "Failed to handle desktop update download-progress event.");
52 assert.strictEqual(reportedError.cause, cause);
53 assert.equal(reportedError.operation, "download");
54 assert.equal(reportedError.message, "Desktop updater download operation reported an error.");
55 assert.strictEqual(unexpectedActionError.cause, cause);
56 assert.equal(unexpectedActionError.action, "install");
57 assert.equal(
58 unexpectedActionError.message,
59 "Desktop update install action failed unexpectedly.",
60 );
61 });
62​
63 it.effect("configures the updater and runs startup checks on the test clock", () => {
64 const harness = makeHarness();
65​
66 return Effect.gen(function* () {
67 yield* Effect.scoped(
68 Effect.gen(function* () {
69 const updates = yield* DesktopUpdates.DesktopUpdates;
70 yield* updates.configure;
71​
72 const state = yield* updates.getState;
73 assert.equal(state.enabled, true);
74 assert.equal(state.status, "idle");
75 assert.deepEqual(harness.feedUrls(), [
76 { provider: "generic", url: "http://localhost:4141" },
77 ]);
78 assert.equal(harness.listenerCount(), 6);
79 assert.equal(harness.checkCount(), 0);
80​
81 yield* TestClock.adjust(Duration.millis(15_000));
82 assert.equal(harness.checkCount(), 1);
83 }),
84 );
85​
86 assert.equal(harness.listenerCount(), 0);
87 }).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
88 });
89​
90 it.effect("updates Linux .deb installs and leaves other non-AppImage installs off", () =>
91 Effect.gen(function* () {
92 const linuxState = (packageType: string | undefined) =>
93 Effect.scoped(
94 Effect.gen(function* () {
95 const updates = yield* DesktopUpdates.DesktopUpdates;
96 yield* updates.configure;
97 return yield* updates.getState;
98 }),
99 ).pipe(Effect.provide(makeHarness({ platform: "linux", packageType }).layer));
100​
101 const deb = yield* linuxState("deb\n");
102 assert.equal(deb.status, "idle");
103​
104 const unmarked = yield* linuxState(undefined);
105 assert.equal(unmarked.status, "disabled");
106 }),
107 );
108​
109 it.effect("subscribe delivers the latest state plus subsequent changes", () => {
110 const harness = makeHarness();
111​
112 return Effect.scoped(
113 Effect.gen(function* () {
114 const updates = yield* DesktopUpdates.DesktopUpdates;
115 yield* updates.configure;
116​
117 const { latest, changes } = yield* updates.subscribe;
118 assert.equal(latest.status, "idle");
119​
120 const nextState = yield* Stream.runHead(changes).pipe(Effect.forkChild);
121 yield* flushCallbacks;
122 harness.emit("update-available", { version: "1.2.4" });
123 yield* flushCallbacks;
124​
125 const observed = yield* Fiber.join(nextState);
126 assert.equal(Option.getOrThrow(observed).status, "available");
127 assert.equal(Option.getOrThrow(observed).availableVersion, "1.2.4");
128 }),
129 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
130 });
131​
132 it.effect("updates and broadcasts state from updater events", () => {
133 const harness = makeHarness();
134​
135 return Effect.scoped(
136 Effect.gen(function* () {
137 const updates = yield* DesktopUpdates.DesktopUpdates;
138 yield* updates.configure;
139​
140 harness.emit("update-available", { version: "1.2.4" });
141 yield* flushCallbacks;
142​
143 const state = yield* updates.getState;
144 assert.equal(state.status, "available");
145 assert.equal(state.availableVersion, "1.2.4");
146 assert.isNotNull(state.checkedAt);
147 assert.equal(harness.sentStates.at(-1)?.status, "available");
148 }),
149 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
150 });
151​
152 it.effect("enables nightly full changelog release notes and broadcasts summaries", () => {
153 const harness = makeHarness();
154​
155 return Effect.scoped(
156 Effect.gen(function* () {
157 const updates = yield* DesktopUpdates.DesktopUpdates;
158 yield* updates.configure;
159​
160 yield* updates.setChannel("nightly");
161 assert.equal(harness.fullChangelog(), true);
162​
163 harness.emit("update-available", {
164 version: "1.2.4-nightly.20260709.766",
165 releaseNotes: [
166 {
167 version: "1.2.4-nightly.20260709.766",
168 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>`,
169 },
170 {
171 version: "1.2.4-nightly.20260709.765",
172 note: "- [codex] Upgrade Clerk stack by @juliusmarminge in #3821",
173 },
174 { version: "1.2.4-nightly.20260709.764", note: "- Change 764" },
175 { version: "1.2.4-nightly.20260709.763", note: "- Change 763" },
176 { version: "1.2.4-nightly.20260709.762", note: "- Change 762" },
177 { version: "1.2.4-nightly.20260709.761", note: "- Change 761" },
178 { version: "1.2.4-nightly.20260709.760", note: "- Change 760" },
179 ],
180 });
181 yield* flushCallbacks;
182​
183 const state = yield* updates.getState;
184 assert.equal(state.status, "available");
185 assert.deepEqual(state.releaseNotes, [
186 {
187 version: "1.2.4-nightly.20260709.766",
188 items: ["feat(client): persist offline environment data by @juliusmarminge in #3795"],
189 totalItems: 1,
190 },
191 {
192 version: "1.2.4-nightly.20260709.765",
193 items: ["[codex] Upgrade Clerk stack by @juliusmarminge in #3821"],
194 totalItems: 1,
195 },
196 { version: "1.2.4-nightly.20260709.764", items: ["Change 764"], totalItems: 1 },
197 { version: "1.2.4-nightly.20260709.763", items: ["Change 763"], totalItems: 1 },
198 { version: "1.2.4-nightly.20260709.762", items: ["Change 762"], totalItems: 1 },
199 { version: "1.2.4-nightly.20260709.761", items: ["Change 761"], totalItems: 1 },
200 ]);
201 assert.equal(state.omittedReleaseCount, 1);
202 assert.deepEqual(harness.sentStates.at(-1)?.releaseNotes, state.releaseNotes);
203 assert.equal(harness.sentStates.at(-1)?.omittedReleaseCount, 1);
204 }),
205 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
206 });
207​
208 it.effect("checks for newer releases after an update has been downloaded", () => {
209 const harness = makeHarness();
210​
211 return Effect.scoped(
212 Effect.gen(function* () {
213 const updates = yield* DesktopUpdates.DesktopUpdates;
214 yield* updates.configure;
215​
216 harness.emit("update-available", {
217 version: "1.2.4",
218 releaseNotes: "## What's changed\n- fix: queued update",
219 });
220 yield* flushCallbacks;
221 harness.emit("update-downloaded", { version: "1.2.4" });
222 yield* flushCallbacks;
223​
224 const result = yield* updates.check("poll");
225 assert.isTrue(result.checked);
226​
227 harness.emit("update-available", { version: "1.2.4" });
228 yield* flushCallbacks;
229​
230 const unchangedState = yield* updates.getState;
231 assert.equal(unchangedState.status, "downloaded");
232 assert.equal(unchangedState.downloadedVersion, "1.2.4");
233 assert.deepEqual(unchangedState.releaseNotes, [
234 { version: "1.2.4", items: ["fix: queued update"], totalItems: 1 },
235 ]);
236 assert.equal(unchangedState.omittedReleaseCount, 0);
237​
238 const nextResult = yield* updates.check("poll");
239 assert.isTrue(nextResult.checked);
240​
241 harness.emit("update-available", { version: "1.2.5" });
242 yield* flushCallbacks;
243​
244 const state = yield* updates.getState;
245 assert.equal(state.status, "available");
246 assert.equal(state.availableVersion, "1.2.5");
247 assert.isNull(state.downloadedVersion);
248 }),
249 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
250 });
251​
252 it.effect("preserves a queued installer when the feed has no update", () => {
253 const harness = makeHarness();
254​
255 return Effect.scoped(
256 Effect.gen(function* () {
257 const updates = yield* DesktopUpdates.DesktopUpdates;
258 yield* updates.configure;
259​
260 harness.emit("update-available", {
261 version: "1.2.4",
262 releaseNotes: "## What's changed\n- fix: queued update",
263 });
264 yield* flushCallbacks;
265 harness.emit("update-downloaded", { version: "1.2.4" });
266 yield* flushCallbacks;
267​
268 yield* updates.check("poll");
269 harness.emit("update-not-available");
270 yield* flushCallbacks;
271​
272 const state = yield* updates.getState;
273 assert.equal(state.status, "downloaded");
274 assert.equal(state.availableVersion, "1.2.4");
275 assert.equal(state.downloadedVersion, "1.2.4");
276 assert.deepEqual(state.releaseNotes, [
277 { version: "1.2.4", items: ["fix: queued update"], totalItems: 1 },
278 ]);
279 assert.equal(state.omittedReleaseCount, 0);
280 assert.equal(state.downloadPercent, 100);
281 }),
282 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
283 });
284​
285 it.effect("preserves a queued installer when the feed offers another channel", () => {
286 const harness = makeHarness();
287​
288 return Effect.scoped(
289 Effect.gen(function* () {
290 const updates = yield* DesktopUpdates.DesktopUpdates;
291 yield* updates.configure;
292​
293 harness.emit("update-available", {
294 version: "1.2.4",
295 releaseNotes: "## What's changed\n- fix: queued update",
296 });
297 yield* flushCallbacks;
298 harness.emit("update-downloaded", { version: "1.2.4" });
299 yield* flushCallbacks;
300​
301 yield* updates.check("poll");
302 harness.emit("update-available", { version: "1.2.5-nightly.20260710.1" });
303 yield* flushCallbacks;
304​
305 const state = yield* updates.getState;
306 assert.equal(state.status, "downloaded");
307 assert.equal(state.availableVersion, "1.2.4");
308 assert.equal(state.downloadedVersion, "1.2.4");
309 assert.deepEqual(state.releaseNotes, [
310 { version: "1.2.4", items: ["fix: queued update"], totalItems: 1 },
311 ]);
312 assert.equal(state.omittedReleaseCount, 0);
313 assert.equal(state.downloadPercent, 100);
314 }),
315 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
316 });
317​
318 it.effect(
319 "rejects install while a refresh check is in progress and releases the reservation",
320 () =>
321 Effect.gen(function* () {
322 const checkStarted = yield* Deferred.make<void>();
323 const releaseCheck = yield* Deferred.make<void>();
324 const harness = makeHarness({
325 checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe(
326 Effect.andThen(Deferred.await(releaseCheck)),
327 ),
328 });
329​
330 yield* Effect.scoped(
331 Effect.gen(function* () {
332 const updates = yield* DesktopUpdates.DesktopUpdates;
333 yield* updates.configure;
334 harness.emit("update-downloaded", { version: "1.2.4" });
335 yield* flushCallbacks;
336​
337 const checkFiber = yield* updates.check("manual").pipe(Effect.forkScoped);
338 yield* Deferred.await(checkStarted);
339​
340 const installResult = yield* updates.install;
341 assert.isFalse(installResult.accepted);
342​
343 yield* Deferred.succeed(releaseCheck, undefined);
344 const checkResult = yield* Fiber.join(checkFiber);
345 assert.isTrue(checkResult.checked);
346​
347 const followUpCheck = yield* updates.check("manual");
348 assert.isTrue(followUpCheck.checked);
349 assert.equal(harness.checkCount(), 2);
350 }),
351 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
352 }),
353 );
354​
355 it.effect("rejects refresh checks while install is in progress", () =>
356 Effect.gen(function* () {
357 const installStarted = yield* Deferred.make<void>();
358 const releaseInstall = yield* Deferred.make<void>();
359 const harness = makeHarness({
360 stopBackend: Deferred.succeed(installStarted, undefined).pipe(
361 Effect.andThen(Deferred.await(releaseInstall)),
362 ),
363 });
364​
365 yield* Effect.scoped(
366 Effect.gen(function* () {
367 const updates = yield* DesktopUpdates.DesktopUpdates;
368 yield* updates.configure;
369 harness.emit("update-downloaded", { version: "1.2.4" });
370 yield* flushCallbacks;
371​
372 const installFiber = yield* updates.install.pipe(Effect.forkScoped);
373 yield* Deferred.await(installStarted);
374​
375 const checkResult = yield* updates.check("manual");
376 assert.isFalse(checkResult.checked);
377 assert.equal(harness.checkCount(), 0);
378​
379 yield* Deferred.succeed(releaseInstall, undefined);
380 const installResult = yield* Fiber.join(installFiber);
381 assert.isTrue(installResult.accepted);
382 }),
383 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
384 }),
385 );
386​
387 it.effect("keeps raw updater event failures out of update state", () => {
388 const harness = makeHarness();
389 const cause = new Error(
390 "request failed for https://user:secret@example.com/update?token=secret",
391 );
392​
393 return Effect.scoped(
394 Effect.gen(function* () {
395 const updates = yield* DesktopUpdates.DesktopUpdates;
396 yield* updates.configure;
397​
398 harness.emit("error", cause);
399 yield* flushCallbacks;
400​
401 const state = yield* updates.getState;
402 assert.equal(state.status, "error");
403 assert.equal(state.message, "Desktop updater background operation reported an error.");
404 assert.notInclude(state.message ?? "", "secret");
405 }),
406 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
407 });
408​
409 it.effect("preserves a queued installer after a background updater error", () => {
410 const harness = makeHarness();
411​
412 return Effect.scoped(
413 Effect.gen(function* () {
414 const updates = yield* DesktopUpdates.DesktopUpdates;
415 yield* updates.configure;
416 harness.emit("update-downloaded", { version: "1.2.4" });
417 yield* flushCallbacks;
418​
419 harness.emit("error", new Error("background updater failure"));
420 yield* flushCallbacks;
421​
422 const state = yield* updates.getState;
423 assert.equal(state.status, "error");
424 assert.equal(state.downloadedVersion, "1.2.4");
425 assert.isNull(state.errorContext);
426​
427 const result = yield* updates.install;
428 assert.isTrue(result.accepted);
429 }),
430 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
431 });
432​
433 it.effect("logs the redacted cause of a rejected update check", () => {
434 const cause = Object.assign(
435 new Error("request failed for https://user:secret@example.com/update?token=secret"),
436 { code: "ERR_UPDATER_LATEST_VERSION_NOT_FOUND" },
437 );
438 const updaterError = new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({
439 channel: null,
440 cause,
441 });
442 const harness = makeHarness({ checkForUpdates: Effect.fail(updaterError) });
443 const loggedAnnotations: Array<Record<string, unknown>> = [];
444 const logger = Logger.make(({ fiber }) => {
445 const annotations = fiber.getRef(References.CurrentLogAnnotations);
446 if (annotations.errorTag === "ElectronUpdaterCheckForUpdatesError") {
447 loggedAnnotations.push(annotations);
448 }
449 });
450​
451 return Effect.scoped(
452 Effect.gen(function* () {
453 const updates = yield* DesktopUpdates.DesktopUpdates;
454 yield* updates.configure;
455​
456 yield* updates.check("manual");
457​
458 const state = yield* updates.getState;
459 const loggedAnnotation = loggedAnnotations.at(-1);
460 assert.isDefined(loggedAnnotation);
461 assert.equal(loggedAnnotation.errorTag, "ElectronUpdaterCheckForUpdatesError");
462 assert.isNull(loggedAnnotation.channel);
463 assert.equal(
464 loggedAnnotation.cause,
465 "Error [ERR_UPDATER_LATEST_VERSION_NOT_FOUND]: request failed for [redacted URL]",
466 );
467 assert.notProperty(loggedAnnotation, "error");
468 assert.notInclude(Object.values(loggedAnnotation).map(String).join(" "), "secret");
469 assert.equal(
470 state.message,
471 "Electron updater failed to check for updates on channel default.",
472 );
473 assert.notInclude(state.message ?? "", "secret");
474 }),
475 ).pipe(
476 Effect.provide(
477 Layer.mergeAll(
478 TestClock.layer(),
479 harness.layer,
480 Logger.layer([logger], { mergeWithExisting: false }),
481 ),
482 ),
483 );
484 });
485​
486 it.effect("logs the redacted cause of an updater error event", () => {
487 const harness = makeHarness();
488 const cause = Object.assign(new Error("404 Not Found\nHeaders: authorization=secret"), {
489 code: "ERR_UPDATER_CHANNEL_FILE_NOT_FOUND",
490 });
491 const loggedAnnotations: Array<Record<string, unknown>> = [];
492 const logger = Logger.make(({ fiber }) => {
493 const annotations = fiber.getRef(References.CurrentLogAnnotations);
494 if (annotations.errorTag === "DesktopUpdaterReportedError") {
495 loggedAnnotations.push(annotations);
496 }
497 });
498​
499 return Effect.scoped(
500 Effect.gen(function* () {
501 const updates = yield* DesktopUpdates.DesktopUpdates;
502 yield* updates.configure;
503​
504 harness.emit("error", cause);
505 yield* flushCallbacks;
506​
507 const loggedAnnotation = loggedAnnotations.at(-1);
508 assert.isDefined(loggedAnnotation);
509 assert.equal(loggedAnnotation.operation, "background");
510 assert.equal(
511 loggedAnnotation.cause,
512 "Error [ERR_UPDATER_CHANNEL_FILE_NOT_FOUND]: 404 Not Found",
513 );
514 assert.notInclude(JSON.stringify(loggedAnnotations), "secret");
515 const state = yield* updates.getState;
516 assert.equal(state.message, "Desktop updater background operation reported an error.");
517 }),
518 ).pipe(
519 Effect.provide(
520 Layer.mergeAll(
521 TestClock.layer(),
522 harness.layer,
523 Logger.layer([logger], { mergeWithExisting: false }),
524 ),
525 ),
526 );
527 });
528​
529 it.effect("recovers download state after an unexpected setup failure", () => {
530 let disableDifferentialCalls = 0;
531 const harness = makeHarness({
532 setDisableDifferentialDownload: Effect.suspend(() => {
533 disableDifferentialCalls += 1;
534 return disableDifferentialCalls === 1
535 ? Effect.void
536 : Effect.die(new Error("download setup failed"));
537 }),
538 });
539​
540 return Effect.scoped(
541 Effect.gen(function* () {
542 const updates = yield* DesktopUpdates.DesktopUpdates;
543 yield* updates.configure;
544 harness.emit("update-available", { version: "1.2.4" });
545 yield* flushCallbacks;
546​
547 const result = yield* updates.download;
548 assert.isTrue(result.accepted);
549 assert.isFalse(result.completed);
550​
551 const failedState = yield* updates.getState;
552 assert.equal(failedState.status, "available");
553 assert.equal(failedState.errorContext, "download");
554 assert.equal(failedState.message, "Desktop update download action failed unexpectedly.");
555​
556 const changedState = yield* updates.setChannel("nightly");
557 assert.equal(changedState.channel, "nightly");
558 }),
559 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
560 });
561​
562 it.effect("restores download state and permits retry after interruption", () =>
563 Effect.gen(function* () {
564 const actionStarted = yield* Deferred.make<void>();
565 let disableDifferentialCalls = 0;
566 const harness = makeHarness({
567 setDisableDifferentialDownload: Effect.suspend(() => {
568 disableDifferentialCalls += 1;
569 if (disableDifferentialCalls === 1) {
570 return Effect.void;
571 }
572 if (disableDifferentialCalls === 2) {
573 return Deferred.succeed(actionStarted, undefined).pipe(Effect.andThen(Effect.never));
574 }
575 return Effect.void;
576 }),
577 });
578​
579 yield* Effect.scoped(
580 Effect.gen(function* () {
581 const updates = yield* DesktopUpdates.DesktopUpdates;
582 yield* updates.configure;
583 harness.emit("update-available", { version: "1.2.4" });
584 yield* flushCallbacks;
585​
586 const downloadFiber = yield* updates.download.pipe(Effect.forkScoped);
587 yield* Deferred.await(actionStarted);
588 yield* Fiber.interrupt(downloadFiber);
589​
590 const interruptedState = yield* updates.getState;
591 assert.equal(interruptedState.status, "available");
592 assert.isNull(interruptedState.message);
593​
594 const retry = yield* updates.download;
595 assert.isTrue(retry.accepted);
596 assert.isTrue(retry.completed);
597 }),
598 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
599 }),
600 );
601​
602 it.effect("clears quitting state after an unexpected install setup failure", () => {
603 const harness = makeHarness({
604 stopBackend: Effect.die(new Error("backend stop failed")),
605 });
606​
607 return Effect.scoped(
608 Effect.gen(function* () {
609 const desktopState = yield* DesktopState.DesktopState;
610 const updates = yield* DesktopUpdates.DesktopUpdates;
611 yield* updates.configure;
612 harness.emit("update-downloaded", { version: "1.2.4" });
613 yield* flushCallbacks;
614​
615 const result = yield* updates.install;
616 assert.isTrue(result.accepted);
617 assert.isFalse(result.completed);
618 assert.isFalse(yield* Ref.get(desktopState.quitting));
619​
620 const failedState = yield* updates.getState;
621 assert.equal(failedState.status, "downloaded");
622 assert.equal(failedState.errorContext, "install");
623 assert.equal(failedState.message, "Desktop update install action failed unexpectedly.");
624​
625 const changedState = yield* updates.setChannel("nightly");
626 assert.equal(changedState.channel, "nightly");
627 }),
628 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
629 });
630​
631 it.effect("marks the backend stop for an install as an update restart", () => {
632 let markersAtStop: ReadonlyArray<string> = [];
633 const harness = makeHarness({
634 stopBackend: Effect.sync(() => {
635 markersAtStop = [...harness.updateRestartMarkers];
636 }),
637 });
638​
639 return Effect.scoped(
640 Effect.gen(function* () {
641 const environment = yield* DesktopEnvironment.DesktopEnvironment;
642 const updates = yield* DesktopUpdates.DesktopUpdates;
643 yield* updates.configure;
644 harness.emit("update-downloaded", { version: "1.2.4" });
645 yield* flushCallbacks;
646​
647 assert.isTrue((yield* updates.install).accepted);
648 assert.deepEqual(markersAtStop, [
649 environment.path.join(environment.baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE),
650 ]);
651 }),
652 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
653 });
654​
655 it.effect("records the version an install hands to the installer", () => {
656 let recordsAtStop: ReadonlyArray<string> = [];
657 const harness = makeHarness({
658 stopBackend: Effect.sync(() => {
659 recordsAtStop = [...harness.installRecords.values()];
660 }),
661 });
662​
663 return Effect.scoped(
664 Effect.gen(function* () {
665 const updates = yield* DesktopUpdates.DesktopUpdates;
666 yield* updates.configure;
667 harness.emit("update-downloaded", { version: "1.2.4" });
668 yield* flushCallbacks;
669​
670 assert.isTrue((yield* updates.install).accepted);
671 assert.deepEqual(
672 recordsAtStop.map((record) => JSON.parse(record)),
673 [{ fromVersion: "1.2.3", targetVersion: "1.2.4" }],
674 );
675 }),
676 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
677 });
678​
679 it.effect("flags an install that did not apply and keeps the flag through checks", () => {
680 const harness = makeHarness({
681 installRecord: JSON.stringify({ fromVersion: "1.2.3", targetVersion: "1.2.4" }),
682 });
683​
684 return Effect.scoped(
685 Effect.gen(function* () {
686 const updates = yield* DesktopUpdates.DesktopUpdates;
687 yield* updates.configure;
688 assert.equal((yield* updates.getState).notAppliedVersion, "1.2.4");
689 assert.isDefined(harness.previousInstallRecord());
690​
691 harness.emit("update-available", { version: "1.2.4" });
692 yield* flushCallbacks;
693 const state = yield* updates.getState;
694 assert.equal(state.status, "available");
695 assert.equal(state.notAppliedVersion, "1.2.4");
696 }),
697 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
698 });
699​
700 it.effect("does not flag an install that applied", () => {
701 const harness = makeHarness({
702 installRecord: JSON.stringify({ fromVersion: "1.2.2", targetVersion: "1.2.3" }),
703 });
704​
705 return Effect.scoped(
706 Effect.gen(function* () {
707 const updates = yield* DesktopUpdates.DesktopUpdates;
708 yield* updates.configure;
709 assert.isUndefined((yield* updates.getState).notAppliedVersion);
710 assert.isUndefined(harness.previousInstallRecord());
711 }),
712 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
713 });
714​
715 it.effect("drops the update restart marker when an install is interrupted", () =>
716 Effect.gen(function* () {
717 const stopping = yield* Deferred.make<void>();
718 const harness = makeHarness({
719 stopBackend: Deferred.succeed(stopping, undefined).pipe(Effect.andThen(Effect.never)),
720 });
721​
722 yield* Effect.scoped(
723 Effect.gen(function* () {
724 const updates = yield* DesktopUpdates.DesktopUpdates;
725 yield* updates.configure;
726 harness.emit("update-downloaded", { version: "1.2.4" });
727 yield* flushCallbacks;
728​
729 const installFiber = yield* updates.install.pipe(Effect.forkScoped);
730 yield* Deferred.await(stopping);
731 assert.equal(harness.updateRestartMarkers.size, 1);
732​
733 yield* Fiber.interrupt(installFiber);
734 assert.equal(harness.updateRestartMarkers.size, 0);
735 }),
736 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
737 }),
738 );
739​
740 it.effect("keeps windows and restarts backends when quitAndInstall fails", () => {
741 const harness = makeHarness({
742 quitAndInstall: Effect.fail(
743 new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
744 channel: "latest",
745 isSilent: true,
746 isForceRunAfter: true,
747 cause: new Error("installer refused"),
748 }),
749 ),
750 });
751​
752 return Effect.scoped(
753 Effect.gen(function* () {
754 const desktopState = yield* DesktopState.DesktopState;
755 const updates = yield* DesktopUpdates.DesktopUpdates;
756 yield* updates.configure;
757 harness.emit("update-downloaded", { version: "1.2.4" });
758 yield* flushCallbacks;
759​
760 const result = yield* updates.install;
761 assert.isTrue(result.accepted);
762 assert.isFalse(yield* Ref.get(desktopState.quitting));
763 assert.deepEqual(harness.installSteps, ["quitAndInstall", "startBackend"]);
764 assert.equal(harness.updateRestartMarkers.size, 0);
765 assert.equal(harness.installRecords.size, 0);
766 }),
767 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
768 });
769​
770 it.effect("holds the install reservation until failed-install recovery finishes", () => {
771 const recoveryStarted = Deferred.makeUnsafe<void>();
772 const releaseRecovery = Deferred.makeUnsafe<void>();
773 const harness = makeHarness({
774 quitAndInstall: Effect.fail(
775 new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
776 channel: "latest",
777 isSilent: true,
778 isForceRunAfter: true,
779 cause: new Error("installer refused"),
780 }),
781 ),
782 startBackend: Deferred.succeed(recoveryStarted, undefined).pipe(
783 Effect.andThen(Deferred.await(releaseRecovery)),
784 ),
785 });
786​
787 return Effect.scoped(
788 Effect.gen(function* () {
789 const updates = yield* DesktopUpdates.DesktopUpdates;
790 yield* updates.configure;
791 harness.emit("update-downloaded", { version: "1.2.4" });
792 yield* flushCallbacks;
793​
794 const failedInstall = yield* updates.install.pipe(Effect.forkChild);
795 yield* Deferred.await(recoveryStarted);
796 assert.isFalse(yield* updates.isInstallActive);
797​
798 const overlappingInstall = yield* updates.install;
799 assert.isFalse(overlappingInstall.accepted);
800 assert.equal(harness.quitAndInstalls(), 1);
801 harness.emit("error", new Error("duplicate native installer error"));
802 yield* flushCallbacks;
803 assert.deepEqual(harness.installSteps, ["quitAndInstall", "startBackend"]);
804​
805 yield* Deferred.succeed(releaseRecovery, undefined);
806 const failedResult = yield* Fiber.join(failedInstall);
807 assert.equal(failedResult.state.errorContext, "install");
808​
809 const retry = yield* updates.install;
810 assert.isTrue(retry.accepted);
811 assert.equal(harness.quitAndInstalls(), 2);
812 }),
813 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
814 });
815​
816 it.effect("recovers when quitAndInstall reports failure through an updater event", () => {
817 const harness = makeHarness();
818​
819 return Effect.scoped(
820 Effect.gen(function* () {
821 const desktopState = yield* DesktopState.DesktopState;
822 const updates = yield* DesktopUpdates.DesktopUpdates;
823 yield* updates.configure;
824 harness.emit("update-downloaded", { version: "1.2.4" });
825 yield* flushCallbacks;
826​
827 yield* updates.install;
828 assert.deepEqual(harness.installSteps, ["quitAndInstall"]);
829 harness.emit("error", new Error("native installer refused"));
830 yield* flushCallbacks;
831​
832 assert.isFalse(yield* Ref.get(desktopState.quitting));
833 assert.deepEqual(harness.installSteps, ["quitAndInstall", "startBackend"]);
834 assert.equal((yield* updates.getState).errorContext, "install");
835 }),
836 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
837 });
838​
839 it.effect("rejects a prepared install when the downloaded version changed", () => {
840 const harness = makeHarness();
841​
842 return Effect.scoped(
843 Effect.gen(function* () {
844 const updates = yield* DesktopUpdates.DesktopUpdates;
845 yield* updates.configure;
846 harness.emit("update-downloaded", { version: "1.2.5" });
847 yield* flushCallbacks;
848​
849 const result = yield* updates.installPrepared("1.2.4");
850 assert.isFalse(result.accepted);
851 assert.equal(harness.quitAndInstalls(), 0);
852 }),
853 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
854 });
855​
856 it.effect("persists channel changes through the settings service", () => {
857 const harness = makeHarness();
858​
859 return Effect.scoped(
860 Effect.gen(function* () {
861 const settings = yield* DesktopAppSettings.DesktopAppSettings;
862 const updates = yield* DesktopUpdates.DesktopUpdates;
863 yield* updates.configure;
864​
865 const state = yield* updates.setChannel("nightly");
866 const persistedSettings = yield* settings.get;
867​
868 assert.equal(state.channel, "nightly");
869 assert.equal(persistedSettings.updateChannel, "nightly");
870 assert.equal(persistedSettings.updateChannelConfiguredByUser, true);
871 }),
872 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
873 });
874​
875 it.effect("does not persist an unchanged update channel as a user preference", () => {
876 const harness = makeHarness();
877​
878 return Effect.scoped(
879 Effect.gen(function* () {
880 const settings = yield* DesktopAppSettings.DesktopAppSettings;
881 const updates = yield* DesktopUpdates.DesktopUpdates;
882 yield* updates.configure;
883​
884 const state = yield* updates.setChannel("latest");
885 const persistedSettings = yield* settings.get;
886​
887 assert.equal(state.channel, "latest");
888 assert.equal(persistedSettings.updateChannel, "latest");
889 assert.equal(persistedSettings.updateChannelConfiguredByUser, false);
890 }),
891 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
892 });
893​
894 it.effect("fails channel changes with a typed error while a check is in progress", () =>
895 Effect.gen(function* () {
896 const checkStarted = yield* Deferred.make<void>();
897 const releaseCheck = yield* Deferred.make<void>();
898 const harness = makeHarness({
899 checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe(
900 Effect.andThen(Deferred.await(releaseCheck)),
901 ),
902 });
903​
904 yield* Effect.scoped(
905 Effect.gen(function* () {
906 const updates = yield* DesktopUpdates.DesktopUpdates;
907 yield* updates.configure;
908​
909 const checkFiber = yield* updates.check("manual").pipe(Effect.forkScoped);
910 yield* Deferred.await(checkStarted);
911​
912 const exit = yield* Effect.exit(updates.setChannel("nightly"));
913 assert.equal(exit._tag, "Failure");
914 if (exit._tag === "Failure") {
915 const error = Cause.squash(exit.cause);
916 assert.instanceOf(error, DesktopUpdates.DesktopUpdateActionInProgressError);
917 assert.equal(error.action, "check");
918 assert.equal(error.requestedChannel, "nightly");
919 }
920​
921 yield* Deferred.succeed(releaseCheck, undefined);
922 yield* Fiber.join(checkFiber);
923 }),
924 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
925 }),
926 );
927​
928 it.effect("rejects checks while an update channel change is being persisted", () =>
929 Effect.gen(function* () {
930 const channelChangeStarted = yield* Deferred.make<void>();
931 const releaseChannelChange = yield* Deferred.make<void>();
932 const harness = makeHarness({
933 beforeSetUpdateChannel: Deferred.succeed(channelChangeStarted, undefined).pipe(
934 Effect.andThen(Deferred.await(releaseChannelChange)),
935 ),
936 });
937​
938 yield* Effect.scoped(
939 Effect.gen(function* () {
940 const updates = yield* DesktopUpdates.DesktopUpdates;
941 yield* updates.configure;
942​
943 const channelFiber = yield* updates.setChannel("nightly").pipe(Effect.forkScoped);
944 yield* Deferred.await(channelChangeStarted);
945​
946 const checkResult = yield* updates.check("manual");
947 assert.isFalse(checkResult.checked);
948 assert.equal(harness.checkCount(), 0);
949​
950 yield* Deferred.succeed(releaseChannelChange, undefined);
951 const state = yield* Fiber.join(channelFiber);
952​
953 assert.equal(state.channel, "nightly");
954 assert.equal(harness.checkCount(), 1);
955 }),
956 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
957 }),
958 );
959​
960 it.effect("preserves settings failure context when an update channel cannot be persisted", () => {
961 const diskFailure = new Error("disk exploded");
962 const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
963 operation: "replace-settings-file",
964 path: "/tmp/settings.json",
965 cause: diskFailure,
966 });
967 const harness = makeHarness({ setUpdateChannelError: settingsFailure });
968​
969 return Effect.scoped(
970 Effect.gen(function* () {
971 const updates = yield* DesktopUpdates.DesktopUpdates;
972 yield* updates.configure;
973​
974 const error = yield* updates.setChannel("nightly").pipe(Effect.flip);
975​
976 assert.instanceOf(error, DesktopUpdates.DesktopUpdateChannelPersistenceError);
977 assert.equal(error.channel, "nightly");
978 assert.strictEqual(error.cause, settingsFailure);
979 assert.strictEqual(error.cause.cause, diskFailure);
980 assert.equal(error.message, "Failed to persist the nightly desktop update channel.");
981 assert.notInclude(error.message, diskFailure.message);
982​
983 const checkResult = yield* updates.check("manual");
984 assert.isTrue(checkResult.checked);
985 assert.equal(harness.checkCount(), 1);
986 }),
987 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
988 });
989});
990​
991describe("describeUpdateErrorCause", () => {
992 it("preserves network and nested failure reasons", () => {
993 const networkError = Object.assign(new Error("getaddrinfo ENOTFOUND updates.example.com"), {
994 code: "ENOTFOUND",
995 });
996 const cause = new Error("fetch failed", { cause: networkError });
997​
998 assert.equal(
999 DesktopUpdates.describeUpdateErrorCause(Cause.fail(cause)),
1000 "Error: fetch failed; caused by Error [ENOTFOUND]: getaddrinfo ENOTFOUND updates.example.com",
1001 );
1002 assert.include(DesktopUpdates.describeUpdateErrorCause(Cause.die(networkError)), "[ENOTFOUND]");
1003 });
1004​
1005 it("removes URLs, credentials, response bodies, and headers from summaries", () => {
1006 const messages = [
1007 "Cannot download https://user:url-secret@example.com/update?token=query-secret, status 403",
1008 "Request failed: Bearer bearer-secret",
1009 "Request failed: Basic basic-secret",
1010 "Request failed: Authorization: Bearer header-secret",
1011 "Request failed: Cookie=session-secret",
1012 "Request failed: api_key=\"key-secret\" password='password-secret' access_token=token-secret",
1013 '404 Not Found\n{"body":"body-secret"}\nHeaders: cookie=header-secret',
1014 "Request failed\rHeaders: cookie=header-secret",
1015 ];
1016​
1017 for (const message of messages) {
1018 const summary = DesktopUpdates.describeUpdateErrorCause(new Error(message));
1019 assert.include(summary, "Error:");
1020 assert.notInclude(summary, "secret");
1021 assert.notInclude(summary, "https://");
1022 assert.notInclude(summary, "Headers:");
1024 assert.equal(
1025 DesktopUpdates.describeUpdateErrorCause("404 Not Found\nbody-secret"),
1026 "404 Not Found",
1027 );
1028 });
1029​
1030 it("bounds long messages, parallel failures, and cyclic causes", () => {
1031 const longError = new Error("x".repeat(10_000));
1032 const parallel = Cause.combine(Cause.fail(longError), Cause.die(longError));
1033 assert.isAtMost(DesktopUpdates.describeUpdateErrorCause(parallel).length, 1024);
1034​
1035 const cyclic = new Error("retry failed");
1036 cyclic.cause = cyclic;
1037 assert.include(DesktopUpdates.describeUpdateErrorCause(cyclic), "[truncated cause]");
1038 assert.isAtMost(DesktopUpdates.describeUpdateErrorCause(cyclic).length, 1024);
1039 });
1040​
1041 it("does not serialize arbitrary payloads or let unreadable errors break logging", () => {
1042 assert.equal(DesktopUpdates.describeUpdateErrorCause({ payload: "secret" }), "object");
1043 const unreadable = Object.defineProperty({}, "message", {
1044 get() {
1045 throw new Error("unreadable error");
1046 },
1047 });
1048 assert.equal(DesktopUpdates.describeUpdateErrorCause(unreadable), "UnknownError");
1049 });
1050});