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

DesktopUpdates.test.ts

1,053 lines40.4 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 // Kept, so the next start on 1.2.3 still knows 1.2.4 did not apply.
690 assert.isDefined(harness.previousInstallRecord());
691​
692 harness.emit("update-available", { version: "1.2.4" });
693 yield* flushCallbacks;
694 const state = yield* updates.getState;
695 assert.equal(state.status, "available");
696 assert.equal(state.notAppliedVersion, "1.2.4");
697 }),
698 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
699 });
700​
701 it.effect("does not flag an install that applied", () => {
702 const harness = makeHarness({
703 installRecord: JSON.stringify({ fromVersion: "1.2.2", targetVersion: "1.2.3" }),
704 });
705​
706 return Effect.scoped(
707 Effect.gen(function* () {
708 const updates = yield* DesktopUpdates.DesktopUpdates;
709 yield* updates.configure;
710 assert.isUndefined((yield* updates.getState).notAppliedVersion);
711 assert.isUndefined(harness.previousInstallRecord());
712 }),
713 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
714 });
715​
716 it.effect("drops the update restart marker when an install is interrupted", () =>
717 Effect.gen(function* () {
718 const stopping = yield* Deferred.make<void>();
719 const harness = makeHarness({
720 stopBackend: Deferred.succeed(stopping, undefined).pipe(Effect.andThen(Effect.never)),
721 });
722​
723 yield* Effect.scoped(
724 Effect.gen(function* () {
725 const updates = yield* DesktopUpdates.DesktopUpdates;
726 yield* updates.configure;
727 harness.emit("update-downloaded", { version: "1.2.4" });
728 yield* flushCallbacks;
729​
730 const installFiber = yield* updates.install.pipe(Effect.forkScoped);
731 yield* Deferred.await(stopping);
732 assert.equal(harness.updateRestartMarkers.size, 1);
733​
734 yield* Fiber.interrupt(installFiber);
735 assert.equal(harness.updateRestartMarkers.size, 0);
736 }),
737 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
738 }),
739 );
740​
741 it.effect("keeps windows and restarts backends when quitAndInstall fails", () => {
742 const harness = makeHarness({
743 quitAndInstall: Effect.fail(
744 new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
745 channel: "latest",
746 isSilent: true,
747 isForceRunAfter: true,
748 cause: new Error("installer refused"),
749 }),
750 ),
751 });
752​
753 return Effect.scoped(
754 Effect.gen(function* () {
755 const desktopState = yield* DesktopState.DesktopState;
756 const updates = yield* DesktopUpdates.DesktopUpdates;
757 yield* updates.configure;
758 harness.emit("update-downloaded", { version: "1.2.4" });
759 yield* flushCallbacks;
760​
761 const result = yield* updates.install;
762 assert.isTrue(result.accepted);
763 assert.isFalse(yield* Ref.get(desktopState.quitting));
764 assert.deepEqual(harness.installSteps, ["quitAndInstall", "startBackend"]);
765 // The restarted old backend must release its tunnel on a later quit.
766 assert.equal(harness.updateRestartMarkers.size, 0);
767 // The app never quit, so the next start must not report an unapplied install.
768 assert.equal(harness.installRecords.size, 0);
769 }),
770 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
771 });
772​
773 it.effect("holds the install reservation until failed-install recovery finishes", () => {
774 const recoveryStarted = Deferred.makeUnsafe<void>();
775 const releaseRecovery = Deferred.makeUnsafe<void>();
776 const harness = makeHarness({
777 quitAndInstall: Effect.fail(
778 new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
779 channel: "latest",
780 isSilent: true,
781 isForceRunAfter: true,
782 cause: new Error("installer refused"),
783 }),
784 ),
785 startBackend: Deferred.succeed(recoveryStarted, undefined).pipe(
786 Effect.andThen(Deferred.await(releaseRecovery)),
787 ),
788 });
789​
790 return Effect.scoped(
791 Effect.gen(function* () {
792 const updates = yield* DesktopUpdates.DesktopUpdates;
793 yield* updates.configure;
794 harness.emit("update-downloaded", { version: "1.2.4" });
795 yield* flushCallbacks;
796​
797 const failedInstall = yield* updates.install.pipe(Effect.forkChild);
798 yield* Deferred.await(recoveryStarted);
799 assert.isFalse(yield* updates.isInstallActive);
800​
801 const overlappingInstall = yield* updates.install;
802 assert.isFalse(overlappingInstall.accepted);
803 assert.equal(harness.quitAndInstalls(), 1);
804 harness.emit("error", new Error("duplicate native installer error"));
805 yield* flushCallbacks;
806 assert.deepEqual(harness.installSteps, ["quitAndInstall", "startBackend"]);
807​
808 yield* Deferred.succeed(releaseRecovery, undefined);
809 const failedResult = yield* Fiber.join(failedInstall);
810 assert.equal(failedResult.state.errorContext, "install");
811​
812 const retry = yield* updates.install;
813 assert.isTrue(retry.accepted);
814 assert.equal(harness.quitAndInstalls(), 2);
815 }),
816 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
817 });
818​
819 it.effect("recovers when quitAndInstall reports failure through an updater event", () => {
820 const harness = makeHarness();
821​
822 return Effect.scoped(
823 Effect.gen(function* () {
824 const desktopState = yield* DesktopState.DesktopState;
825 const updates = yield* DesktopUpdates.DesktopUpdates;
826 yield* updates.configure;
827 harness.emit("update-downloaded", { version: "1.2.4" });
828 yield* flushCallbacks;
829​
830 yield* updates.install;
831 assert.deepEqual(harness.installSteps, ["quitAndInstall"]);
832 harness.emit("error", new Error("native installer refused"));
833 yield* flushCallbacks;
834​
835 assert.isFalse(yield* Ref.get(desktopState.quitting));
836 assert.deepEqual(harness.installSteps, ["quitAndInstall", "startBackend"]);
837 assert.equal((yield* updates.getState).errorContext, "install");
838 }),
839 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
840 });
841​
842 it.effect("rejects a prepared install when the downloaded version changed", () => {
843 const harness = makeHarness();
844​
845 return Effect.scoped(
846 Effect.gen(function* () {
847 const updates = yield* DesktopUpdates.DesktopUpdates;
848 yield* updates.configure;
849 harness.emit("update-downloaded", { version: "1.2.5" });
850 yield* flushCallbacks;
851​
852 const result = yield* updates.installPrepared("1.2.4");
853 assert.isFalse(result.accepted);
854 assert.equal(harness.quitAndInstalls(), 0);
855 }),
856 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
857 });
858​
859 it.effect("persists channel changes through the settings service", () => {
860 const harness = makeHarness();
861​
862 return Effect.scoped(
863 Effect.gen(function* () {
864 const settings = yield* DesktopAppSettings.DesktopAppSettings;
865 const updates = yield* DesktopUpdates.DesktopUpdates;
866 yield* updates.configure;
867​
868 const state = yield* updates.setChannel("nightly");
869 const persistedSettings = yield* settings.get;
870​
871 assert.equal(state.channel, "nightly");
872 assert.equal(persistedSettings.updateChannel, "nightly");
873 assert.equal(persistedSettings.updateChannelConfiguredByUser, true);
874 }),
875 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
876 });
877​
878 it.effect("does not persist an unchanged update channel as a user preference", () => {
879 const harness = makeHarness();
880​
881 return Effect.scoped(
882 Effect.gen(function* () {
883 const settings = yield* DesktopAppSettings.DesktopAppSettings;
884 const updates = yield* DesktopUpdates.DesktopUpdates;
885 yield* updates.configure;
886​
887 const state = yield* updates.setChannel("latest");
888 const persistedSettings = yield* settings.get;
889​
890 assert.equal(state.channel, "latest");
891 assert.equal(persistedSettings.updateChannel, "latest");
892 assert.equal(persistedSettings.updateChannelConfiguredByUser, false);
893 }),
894 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
895 });
896​
897 it.effect("fails channel changes with a typed error while a check is in progress", () =>
898 Effect.gen(function* () {
899 const checkStarted = yield* Deferred.make<void>();
900 const releaseCheck = yield* Deferred.make<void>();
901 const harness = makeHarness({
902 checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe(
903 Effect.andThen(Deferred.await(releaseCheck)),
904 ),
905 });
906​
907 yield* Effect.scoped(
908 Effect.gen(function* () {
909 const updates = yield* DesktopUpdates.DesktopUpdates;
910 yield* updates.configure;
911​
912 const checkFiber = yield* updates.check("manual").pipe(Effect.forkScoped);
913 yield* Deferred.await(checkStarted);
914​
915 const exit = yield* Effect.exit(updates.setChannel("nightly"));
916 assert.equal(exit._tag, "Failure");
917 if (exit._tag === "Failure") {
918 const error = Cause.squash(exit.cause);
919 assert.instanceOf(error, DesktopUpdates.DesktopUpdateActionInProgressError);
920 assert.equal(error.action, "check");
921 assert.equal(error.requestedChannel, "nightly");
922 }
923​
924 yield* Deferred.succeed(releaseCheck, undefined);
925 yield* Fiber.join(checkFiber);
926 }),
927 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
928 }),
929 );
930​
931 it.effect("rejects checks while an update channel change is being persisted", () =>
932 Effect.gen(function* () {
933 const channelChangeStarted = yield* Deferred.make<void>();
934 const releaseChannelChange = yield* Deferred.make<void>();
935 const harness = makeHarness({
936 beforeSetUpdateChannel: Deferred.succeed(channelChangeStarted, undefined).pipe(
937 Effect.andThen(Deferred.await(releaseChannelChange)),
938 ),
939 });
940​
941 yield* Effect.scoped(
942 Effect.gen(function* () {
943 const updates = yield* DesktopUpdates.DesktopUpdates;
944 yield* updates.configure;
945​
946 const channelFiber = yield* updates.setChannel("nightly").pipe(Effect.forkScoped);
947 yield* Deferred.await(channelChangeStarted);
948​
949 const checkResult = yield* updates.check("manual");
950 assert.isFalse(checkResult.checked);
951 assert.equal(harness.checkCount(), 0);
952​
953 yield* Deferred.succeed(releaseChannelChange, undefined);
954 const state = yield* Fiber.join(channelFiber);
955​
956 assert.equal(state.channel, "nightly");
957 assert.equal(harness.checkCount(), 1);
958 }),
959 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
960 }),
961 );
962​
963 it.effect("preserves settings failure context when an update channel cannot be persisted", () => {
964 const diskFailure = new Error("disk exploded");
965 const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
966 operation: "replace-settings-file",
967 path: "/tmp/settings.json",
968 cause: diskFailure,
969 });
970 const harness = makeHarness({ setUpdateChannelError: settingsFailure });
971​
972 return Effect.scoped(
973 Effect.gen(function* () {
974 const updates = yield* DesktopUpdates.DesktopUpdates;
975 yield* updates.configure;
976​
977 const error = yield* updates.setChannel("nightly").pipe(Effect.flip);
978​
979 assert.instanceOf(error, DesktopUpdates.DesktopUpdateChannelPersistenceError);
980 assert.equal(error.channel, "nightly");
981 assert.strictEqual(error.cause, settingsFailure);
982 assert.strictEqual(error.cause.cause, diskFailure);
983 assert.equal(error.message, "Failed to persist the nightly desktop update channel.");
984 assert.notInclude(error.message, diskFailure.message);
985​
986 const checkResult = yield* updates.check("manual");
987 assert.isTrue(checkResult.checked);
988 assert.equal(harness.checkCount(), 1);
989 }),
990 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
991 });
992});
993​
994describe("describeUpdateErrorCause", () => {
995 it("preserves network and nested failure reasons", () => {
996 const networkError = Object.assign(new Error("getaddrinfo ENOTFOUND updates.example.com"), {
997 code: "ENOTFOUND",
998 });
999 const cause = new Error("fetch failed", { cause: networkError });
1000​
1001 assert.equal(
1002 DesktopUpdates.describeUpdateErrorCause(Cause.fail(cause)),
1003 "Error: fetch failed; caused by Error [ENOTFOUND]: getaddrinfo ENOTFOUND updates.example.com",
1004 );
1005 assert.include(DesktopUpdates.describeUpdateErrorCause(Cause.die(networkError)), "[ENOTFOUND]");
1006 });
1007​
1008 it("removes URLs, credentials, response bodies, and headers from summaries", () => {
1009 const messages = [
1010 "Cannot download https://user:url-secret@example.com/update?token=query-secret, status 403",
1011 "Request failed: Bearer bearer-secret",
1012 "Request failed: Basic basic-secret",
1013 "Request failed: Authorization: Bearer header-secret",
1014 "Request failed: Cookie=session-secret",
1015 "Request failed: api_key=\"key-secret\" password='password-secret' access_token=token-secret",
1016 '404 Not Found\n{"body":"body-secret"}\nHeaders: cookie=header-secret',
1017 "Request failed\rHeaders: cookie=header-secret",
1018 ];
1019​
1020 for (const message of messages) {
1021 const summary = DesktopUpdates.describeUpdateErrorCause(new Error(message));
1022 assert.include(summary, "Error:");
1023 assert.notInclude(summary, "secret");
1024 assert.notInclude(summary, "https://");
1025 assert.notInclude(summary, "Headers:");
1027 assert.equal(
1028 DesktopUpdates.describeUpdateErrorCause("404 Not Found\nbody-secret"),
1029 "404 Not Found",
1030 );
1031 });
1032​
1033 it("bounds long messages, parallel failures, and cyclic causes", () => {
1034 const longError = new Error("x".repeat(10_000));
1035 const parallel = Cause.combine(Cause.fail(longError), Cause.die(longError));
1036 assert.isAtMost(DesktopUpdates.describeUpdateErrorCause(parallel).length, 1024);
1037​
1038 const cyclic = new Error("retry failed");
1039 cyclic.cause = cyclic;
1040 assert.include(DesktopUpdates.describeUpdateErrorCause(cyclic), "[truncated cause]");
1041 assert.isAtMost(DesktopUpdates.describeUpdateErrorCause(cyclic).length, 1024);
1042 });
1043​
1044 it("does not serialize arbitrary payloads or let unreadable errors break logging", () => {
1045 assert.equal(DesktopUpdates.describeUpdateErrorCause({ payload: "secret" }), "object");
1046 const unreadable = Object.defineProperty({}, "message", {
1047 get() {
1048 throw new Error("unreadable error");
1049 },
1050 });
1051 assert.equal(DesktopUpdates.describeUpdateErrorCause(unreadable), "UnknownError");
1052 });
1053});