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

DesktopUpdates.test.ts

795 lines30.3 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 Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as Layer from "effect/Layer";
8import * as Logger from "effect/Logger";
9import * as Option from "effect/Option";
10import * as References from "effect/References";
11import * as Ref from "effect/Ref";
12import * as Stream from "effect/Stream";
13import * as TestClock from "effect/testing/TestClock";
14​
15import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
16import * as DesktopBackendPool from "../backend/DesktopBackendPool.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.effect("updates Linux .deb installs and leaves other non-AppImage installs off", () =>
25 Effect.gen(function* () {
26 const linuxState = (packageType: string | undefined) =>
27 Effect.scoped(
28 Effect.gen(function* () {
29 const updates = yield* DesktopUpdates.DesktopUpdates;
30 yield* updates.configure;
31 return yield* updates.getState;
32 }),
33 ).pipe(Effect.provide(makeHarness({ platform: "linux", packageType }).layer));
34​
35 const deb = yield* linuxState("deb\n");
36 assert.equal(deb.status, "idle");
37​
38 const unmarked = yield* linuxState(undefined);
39 assert.equal(unmarked.status, "disabled");
40 }),
41 );
42​
43 it.effect("keeps the disabled reason available after configuration and channel changes", () => {
44 const harness = makeHarness({ env: { T3CODE_DISABLE_AUTO_UPDATE: "true" } });
45 const reason = "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
46​
47 return Effect.scoped(
48 Effect.gen(function* () {
49 const updates = yield* DesktopUpdates.DesktopUpdates;
50 yield* updates.configure;
51​
52 const configured = yield* updates.getState;
53 assert.equal(configured.message, reason);
54​
55 const changed = yield* updates.setChannel("nightly");
56 assert.equal(changed.channel, "nightly");
57 assert.equal(changed.enabled, false);
58 assert.equal(changed.status, "disabled");
59 assert.equal(changed.message, reason);
60 assert.equal(harness.sentStates.at(-1)?.message, reason);
61 assert.equal(harness.checkCount(), 0);
62 }),
63 ).pipe(Effect.provide(harness.layer));
64 });
65​
66 it.effect("checks for newer releases after an update has been downloaded", () => {
67 const harness = makeHarness();
68​
69 return Effect.scoped(
70 Effect.gen(function* () {
71 const updates = yield* DesktopUpdates.DesktopUpdates;
72 yield* updates.configure;
73​
74 harness.emit("update-available", {
75 version: "1.2.4",
76 releaseNotes: "## What's changed\n- fix: queued update",
77 });
78 yield* flushCallbacks;
79 harness.emit("update-downloaded", { version: "1.2.4" });
80 yield* flushCallbacks;
81​
82 const result = yield* updates.check("poll");
83 assert.isTrue(result.checked);
84​
85 harness.emit("update-available", { version: "1.2.4" });
86 yield* flushCallbacks;
87​
88 const unchangedState = yield* updates.getState;
89 assert.equal(unchangedState.status, "downloaded");
90 assert.equal(unchangedState.downloadedVersion, "1.2.4");
91 assert.deepEqual(unchangedState.releaseNotes, [
92 { version: "1.2.4", items: ["fix: queued update"], totalItems: 1 },
93 ]);
94 assert.equal(unchangedState.omittedReleaseCount, 0);
95​
96 const nextResult = yield* updates.check("poll");
97 assert.isTrue(nextResult.checked);
98​
99 harness.emit("update-available", { version: "1.2.5" });
100 yield* flushCallbacks;
101​
102 const state = yield* updates.getState;
103 assert.equal(state.status, "available");
104 assert.equal(state.availableVersion, "1.2.5");
105 assert.isNull(state.downloadedVersion);
106 }),
107 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
108 });
109​
110 it.effect("preserves a queued installer when the feed has no update", () => {
111 const harness = makeHarness();
112​
113 return Effect.scoped(
114 Effect.gen(function* () {
115 const updates = yield* DesktopUpdates.DesktopUpdates;
116 yield* updates.configure;
117​
118 harness.emit("update-available", {
119 version: "1.2.4",
120 releaseNotes: "## What's changed\n- fix: queued update",
121 });
122 yield* flushCallbacks;
123 harness.emit("update-downloaded", { version: "1.2.4" });
124 yield* flushCallbacks;
125​
126 yield* updates.check("poll");
127 harness.emit("update-not-available");
128 yield* flushCallbacks;
129​
130 const state = yield* updates.getState;
131 assert.equal(state.status, "downloaded");
132 assert.equal(state.availableVersion, "1.2.4");
133 assert.equal(state.downloadedVersion, "1.2.4");
134 assert.deepEqual(state.releaseNotes, [
135 { version: "1.2.4", items: ["fix: queued update"], totalItems: 1 },
136 ]);
137 assert.equal(state.omittedReleaseCount, 0);
138 assert.equal(state.downloadPercent, 100);
139 }),
140 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
141 });
142​
143 it.effect(
144 "rejects install while a refresh check is in progress and releases the reservation",
145 () =>
146 Effect.gen(function* () {
147 const checkStarted = yield* Deferred.make<void>();
148 const releaseCheck = yield* Deferred.make<void>();
149 const harness = makeHarness({
150 checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe(
151 Effect.andThen(Deferred.await(releaseCheck)),
152 ),
153 });
154​
155 yield* Effect.scoped(
156 Effect.gen(function* () {
157 const updates = yield* DesktopUpdates.DesktopUpdates;
158 yield* updates.configure;
159 harness.emit("update-downloaded", { version: "1.2.4" });
160 yield* flushCallbacks;
161​
162 const checkFiber = yield* updates.check("manual").pipe(Effect.forkScoped);
163 yield* Deferred.await(checkStarted);
164​
165 const installResult = yield* updates.install;
166 assert.isFalse(installResult.accepted);
167​
168 yield* Deferred.succeed(releaseCheck, undefined);
169 const checkResult = yield* Fiber.join(checkFiber);
170 assert.isTrue(checkResult.checked);
171​
172 const followUpCheck = yield* updates.check("manual");
173 assert.isTrue(followUpCheck.checked);
174 assert.equal(harness.checkCount(), 2);
175 }),
176 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
177 }),
178 );
179​
180 it.effect("rejects refresh checks while install is in progress", () =>
181 Effect.gen(function* () {
182 const installStarted = yield* Deferred.make<void>();
183 const releaseInstall = yield* Deferred.make<void>();
184 const harness = makeHarness({
185 stopBackend: Deferred.succeed(installStarted, undefined).pipe(
186 Effect.andThen(Deferred.await(releaseInstall)),
187 ),
188 });
189​
190 yield* Effect.scoped(
191 Effect.gen(function* () {
192 const updates = yield* DesktopUpdates.DesktopUpdates;
193 yield* updates.configure;
194 harness.emit("update-downloaded", { version: "1.2.4" });
195 yield* flushCallbacks;
196​
197 const installFiber = yield* updates.install.pipe(Effect.forkScoped);
198 yield* Deferred.await(installStarted);
199​
200 const checkResult = yield* updates.check("manual");
201 assert.isFalse(checkResult.checked);
202 assert.equal(harness.checkCount(), 0);
203​
204 yield* Deferred.succeed(releaseInstall, undefined);
205 const installResult = yield* Fiber.join(installFiber);
206 assert.isTrue(installResult.accepted);
207 }),
208 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
209 }),
210 );
211​
212 it.effect("preserves a queued installer after a background updater error", () => {
213 const harness = makeHarness();
214​
215 return Effect.scoped(
216 Effect.gen(function* () {
217 const updates = yield* DesktopUpdates.DesktopUpdates;
218 yield* updates.configure;
219 harness.emit("update-downloaded", { version: "1.2.4" });
220 yield* flushCallbacks;
221​
222 harness.emit("error", new Error("background updater failure"));
223 yield* flushCallbacks;
224​
225 const state = yield* updates.getState;
226 assert.equal(state.status, "error");
227 assert.equal(state.downloadedVersion, "1.2.4");
228 assert.isNull(state.errorContext);
229​
230 const result = yield* updates.install;
231 assert.isTrue(result.accepted);
232 }),
233 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
234 });
235​
236 it.effect("logs the redacted cause of a rejected update check", () => {
237 const cause = Object.assign(
238 new Error("request failed for https://user:secret@example.com/update?token=secret"),
239 { code: "ERR_UPDATER_LATEST_VERSION_NOT_FOUND" },
240 );
241 const updaterError = new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({
242 channel: null,
243 cause,
244 });
245 const harness = makeHarness({ checkForUpdates: Effect.fail(updaterError) });
246 const loggedAnnotations: Array<Record<string, unknown>> = [];
247 const logger = Logger.make(({ fiber }) => {
248 const annotations = fiber.getRef(References.CurrentLogAnnotations);
249 if (annotations.errorTag === "ElectronUpdaterCheckForUpdatesError") {
250 loggedAnnotations.push(annotations);
251 }
252 });
253​
254 return Effect.scoped(
255 Effect.gen(function* () {
256 const updates = yield* DesktopUpdates.DesktopUpdates;
257 yield* updates.configure;
258​
259 yield* updates.check("manual");
260​
261 const state = yield* updates.getState;
262 const loggedAnnotation = loggedAnnotations.at(-1);
263 assert.isDefined(loggedAnnotation);
264 assert.equal(loggedAnnotation.errorTag, "ElectronUpdaterCheckForUpdatesError");
265 assert.isNull(loggedAnnotation.channel);
266 assert.equal(
267 loggedAnnotation.cause,
268 "Error [ERR_UPDATER_LATEST_VERSION_NOT_FOUND]: request failed for [redacted URL]",
269 );
270 assert.notProperty(loggedAnnotation, "error");
271 assert.notInclude(Object.values(loggedAnnotation).map(String).join(" "), "secret");
272 assert.equal(
273 state.message,
274 "Electron updater failed to check for updates on channel default.",
275 );
276 assert.notInclude(state.message ?? "", "secret");
277 }),
278 ).pipe(
279 Effect.provide(
280 Layer.mergeAll(
281 TestClock.layer(),
282 harness.layer,
283 Logger.layer([logger], { mergeWithExisting: false }),
284 ),
285 ),
286 );
287 });
288​
289 it.effect("recovers download state after an unexpected setup failure", () => {
290 let disableDifferentialCalls = 0;
291 const harness = makeHarness({
292 setDisableDifferentialDownload: Effect.suspend(() => {
293 disableDifferentialCalls += 1;
294 return disableDifferentialCalls === 1
295 ? Effect.void
296 : Effect.die(new Error("download setup failed"));
297 }),
298 });
299​
300 return Effect.scoped(
301 Effect.gen(function* () {
302 const updates = yield* DesktopUpdates.DesktopUpdates;
303 yield* updates.configure;
304 harness.emit("update-available", { version: "1.2.4" });
305 yield* flushCallbacks;
306​
307 const result = yield* updates.download;
308 assert.isTrue(result.accepted);
309 assert.isFalse(result.completed);
310​
311 const failedState = yield* updates.getState;
312 assert.equal(failedState.status, "available");
313 assert.equal(failedState.errorContext, "download");
314 assert.equal(failedState.message, "Desktop update download action failed unexpectedly.");
315​
316 const changedState = yield* updates.setChannel("nightly");
317 assert.equal(changedState.channel, "nightly");
318 }),
319 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
320 });
321​
322 it.effect("restores download state and permits retry after interruption", () =>
323 Effect.gen(function* () {
324 const actionStarted = yield* Deferred.make<void>();
325 let disableDifferentialCalls = 0;
326 const harness = makeHarness({
327 setDisableDifferentialDownload: Effect.suspend(() => {
328 disableDifferentialCalls += 1;
329 if (disableDifferentialCalls === 1) {
330 return Effect.void;
331 }
332 if (disableDifferentialCalls === 2) {
333 return Deferred.succeed(actionStarted, undefined).pipe(Effect.andThen(Effect.never));
334 }
335 return Effect.void;
336 }),
337 });
338​
339 yield* Effect.scoped(
340 Effect.gen(function* () {
341 const updates = yield* DesktopUpdates.DesktopUpdates;
342 yield* updates.configure;
343 harness.emit("update-available", { version: "1.2.4" });
344 yield* flushCallbacks;
345​
346 const downloadFiber = yield* updates.download.pipe(Effect.forkScoped);
347 yield* Deferred.await(actionStarted);
348 yield* Fiber.interrupt(downloadFiber);
349​
350 const interruptedState = yield* updates.getState;
351 assert.equal(interruptedState.status, "available");
352 assert.isNull(interruptedState.message);
353​
354 const retry = yield* updates.download;
355 assert.isTrue(retry.accepted);
356 assert.isTrue(retry.completed);
357 }),
358 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
359 }),
360 );
361​
362 it.effect("clears quitting state after an unexpected install setup failure", () => {
363 const harness = makeHarness({
364 stopBackend: Effect.die(new Error("backend stop failed")),
365 });
366​
367 return Effect.scoped(
368 Effect.gen(function* () {
369 const desktopState = yield* DesktopState.DesktopState;
370 const updates = yield* DesktopUpdates.DesktopUpdates;
371 yield* updates.configure;
372 harness.emit("update-downloaded", { version: "1.2.4" });
373 yield* flushCallbacks;
374​
375 const result = yield* updates.install;
376 assert.isTrue(result.accepted);
377 assert.isFalse(result.completed);
378 assert.isFalse(yield* Ref.get(desktopState.quitting));
379​
380 const failedState = yield* updates.getState;
381 assert.equal(failedState.status, "downloaded");
382 assert.equal(failedState.errorContext, "install");
383 assert.equal(failedState.message, "Desktop update install action failed unexpectedly.");
384​
385 const changedState = yield* updates.setChannel("nightly");
386 assert.equal(changedState.channel, "nightly");
387 }),
388 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
389 });
390​
391 it.effect("marks the backend stop for an install as an update restart", () => {
392 let markersAtStop: ReadonlyArray<string> = [];
393 const harness = makeHarness({
394 stopBackend: Effect.sync(() => {
395 markersAtStop = [...harness.updateRestartMarkers];
396 }),
397 });
398​
399 return Effect.scoped(
400 Effect.gen(function* () {
401 const environment = yield* DesktopEnvironment.DesktopEnvironment;
402 const updates = yield* DesktopUpdates.DesktopUpdates;
403 yield* updates.configure;
404 harness.emit("update-downloaded", { version: "1.2.4" });
405 yield* flushCallbacks;
406​
407 assert.isTrue((yield* updates.install).accepted);
408 assert.deepEqual(markersAtStop, [
409 environment.path.join(environment.baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE),
410 ]);
411 }),
412 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
413 });
414​
415 it.effect("records the version an install hands to the installer", () => {
416 let recordsAtStop: ReadonlyArray<string> = [];
417 const harness = makeHarness({
418 stopBackend: Effect.sync(() => {
419 recordsAtStop = [...harness.installRecords.values()];
420 }),
421 });
422​
423 return Effect.scoped(
424 Effect.gen(function* () {
425 const updates = yield* DesktopUpdates.DesktopUpdates;
426 yield* updates.configure;
427 harness.emit("update-downloaded", { version: "1.2.4" });
428 yield* flushCallbacks;
429​
430 assert.isTrue((yield* updates.install).accepted);
431 assert.deepEqual(
432 recordsAtStop.map((record) => JSON.parse(record)),
433 [{ fromVersion: "1.2.3", targetVersion: "1.2.4" }],
434 );
435 }),
436 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
437 });
438​
439 it.effect("flags an install that did not apply and keeps the flag through checks", () => {
440 const harness = makeHarness({
441 installRecord: JSON.stringify({ fromVersion: "1.2.3", targetVersion: "1.2.4" }),
442 });
443​
444 return Effect.scoped(
445 Effect.gen(function* () {
446 const updates = yield* DesktopUpdates.DesktopUpdates;
447 yield* updates.configure;
448 assert.equal((yield* updates.getState).notAppliedVersion, "1.2.4");
449 assert.isDefined(harness.previousInstallRecord());
450​
451 harness.emit("update-available", { version: "1.2.4" });
452 yield* flushCallbacks;
453 const state = yield* updates.getState;
454 assert.equal(state.status, "available");
455 assert.equal(state.notAppliedVersion, "1.2.4");
456 }),
457 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
458 });
459​
460 // regression: #19291 an install that did apply was still flagged as not applied
461 it.effect("does not flag an install that applied", () => {
462 const harness = makeHarness({
463 installRecord: JSON.stringify({ fromVersion: "1.2.2", targetVersion: "1.2.3" }),
464 });
465​
466 return Effect.scoped(
467 Effect.gen(function* () {
468 const updates = yield* DesktopUpdates.DesktopUpdates;
469 yield* updates.configure;
470 assert.isUndefined((yield* updates.getState).notAppliedVersion);
471 assert.isUndefined(harness.previousInstallRecord());
472 }),
473 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
474 });
475​
476 it.effect("drops the update restart marker when an install is interrupted", () =>
477 Effect.gen(function* () {
478 const stopping = yield* Deferred.make<void>();
479 const harness = makeHarness({
480 stopBackend: Deferred.succeed(stopping, undefined).pipe(Effect.andThen(Effect.never)),
481 });
482​
483 yield* Effect.scoped(
484 Effect.gen(function* () {
485 const updates = yield* DesktopUpdates.DesktopUpdates;
486 yield* updates.configure;
487 harness.emit("update-downloaded", { version: "1.2.4" });
488 yield* flushCallbacks;
489​
490 const installFiber = yield* updates.install.pipe(Effect.forkScoped);
491 yield* Deferred.await(stopping);
492 assert.equal(harness.updateRestartMarkers.size, 1);
493​
494 yield* Fiber.interrupt(installFiber);
495 assert.equal(harness.updateRestartMarkers.size, 0);
496 }),
497 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
498 }),
499 );
500​
501 it.effect("keeps windows and restarts backends when quitAndInstall fails", () => {
502 const harness = makeHarness({
503 quitAndInstall: Effect.fail(
504 new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
505 channel: "latest",
506 isSilent: true,
507 isForceRunAfter: true,
508 cause: new Error("installer refused"),
509 }),
510 ),
511 });
512​
513 return Effect.scoped(
514 Effect.gen(function* () {
515 const desktopState = yield* DesktopState.DesktopState;
516 const updates = yield* DesktopUpdates.DesktopUpdates;
517 yield* updates.configure;
518 harness.emit("update-downloaded", { version: "1.2.4" });
519 yield* flushCallbacks;
520​
521 const result = yield* updates.install;
522 assert.isTrue(result.accepted);
523 assert.isFalse(yield* Ref.get(desktopState.quitting));
524 assert.deepEqual(harness.installSteps, ["quitAndInstall", "startBackend"]);
525 assert.equal(harness.updateRestartMarkers.size, 0);
526 assert.equal(harness.installRecords.size, 0);
527 }),
528 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
529 });
530​
531 it.effect("keeps the disabled primary stopped when quitAndInstall fails", () => {
532 const harness = makeHarness({
533 backendDesiredRunning: false,
534 quitAndInstall: Effect.fail(
535 new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
536 channel: "latest",
537 isSilent: true,
538 isForceRunAfter: true,
539 cause: new Error("installer refused"),
540 }),
541 ),
542 });
543​
544 return Effect.scoped(
545 Effect.gen(function* () {
546 const updates = yield* DesktopUpdates.DesktopUpdates;
547 const pool = yield* DesktopBackendPool.DesktopBackendPool;
548 yield* updates.configure;
549 harness.emit("update-downloaded", { version: "1.2.4" });
550 yield* flushCallbacks;
551​
552 const result = yield* updates.install;
553 assert.equal(result.state.errorContext, "install");
554 assert.deepEqual(harness.installSteps, ["quitAndInstall"]);
555 assert.isFalse((yield* (yield* pool.primary).snapshot).desiredRunning);
556 }),
557 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
558 });
559​
560 it.effect("restores only desired-running instances after an installer error event", () => {
561 const starts: string[] = [];
562 const stops: string[] = [];
563 const makeInstance = (id: DesktopBackendPool.BackendInstanceId, initiallyRunning: boolean) => {
564 let desiredRunning = initiallyRunning;
565 return {
566 id,
567 label: Effect.succeed(id),
568 currentConfig: Effect.succeedNone,
569 start: Effect.sync(() => {
570 starts.push(id);
571 desiredRunning = true;
572 }),
573 stop: () =>
574 Effect.sync(() => {
575 stops.push(id);
576 desiredRunning = false;
577 }),
578 snapshot: Effect.sync(() => ({
579 desiredRunning,
580 ready: false,
581 activePid: Option.none(),
582 restartAttempt: 0,
583 restartScheduled: false,
584 })),
585 waitForReady: () => Effect.succeed(true),
586 } satisfies DesktopBackendPool.DesktopBackendInstance;
587 };
588 const primary = makeInstance(DesktopBackendPool.PRIMARY_INSTANCE_ID, false);
589 const wsl = makeInstance(DesktopBackendPool.BackendInstanceId("wsl:default"), true);
590 const harness = makeHarness({ backendInstances: [primary, wsl] });
591​
592 return Effect.scoped(
593 Effect.gen(function* () {
594 const updates = yield* DesktopUpdates.DesktopUpdates;
595 yield* updates.configure;
596 harness.emit("update-downloaded", { version: "1.2.4" });
597 yield* flushCallbacks;
598​
599 yield* updates.install;
600 assert.sameMembers(stops, [primary.id, wsl.id]);
601 assert.isFalse((yield* wsl.snapshot).desiredRunning);
602 const { changes } = yield* updates.subscribe;
603 const recovered = yield* Stream.runHead(changes).pipe(Effect.forkChild);
604 yield* flushCallbacks;
605 harness.emit("error", new Error("native installer refused"));
606 assert.equal(Option.getOrThrow(yield* Fiber.join(recovered)).errorContext, "install");
607​
608 assert.deepEqual(starts, [wsl.id]);
609 assert.isFalse((yield* primary.snapshot).desiredRunning);
610 assert.isTrue((yield* wsl.snapshot).desiredRunning);
611 }),
612 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
613 });
614​
615 it.effect("holds the install reservation until failed-install recovery finishes", () => {
616 const recoveryStarted = Deferred.makeUnsafe<void>();
617 const releaseRecovery = Deferred.makeUnsafe<void>();
618 const harness = makeHarness({
619 quitAndInstall: Effect.fail(
620 new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
621 channel: "latest",
622 isSilent: true,
623 isForceRunAfter: true,
624 cause: new Error("installer refused"),
625 }),
626 ),
627 startBackend: Deferred.succeed(recoveryStarted, undefined).pipe(
628 Effect.andThen(Deferred.await(releaseRecovery)),
629 ),
630 });
631​
632 return Effect.scoped(
633 Effect.gen(function* () {
634 const updates = yield* DesktopUpdates.DesktopUpdates;
635 yield* updates.configure;
636 harness.emit("update-downloaded", { version: "1.2.4" });
637 yield* flushCallbacks;
638​
639 const failedInstall = yield* updates.install.pipe(Effect.forkChild);
640 yield* Deferred.await(recoveryStarted);
641 assert.isFalse(yield* updates.isInstallActive);
642​
643 const overlappingInstall = yield* updates.install;
644 assert.isFalse(overlappingInstall.accepted);
645 assert.equal(harness.quitAndInstalls(), 1);
646 harness.emit("error", new Error("duplicate native installer error"));
647 yield* flushCallbacks;
648 assert.deepEqual(harness.installSteps, ["quitAndInstall", "startBackend"]);
649​
650 yield* Deferred.succeed(releaseRecovery, undefined);
651 const failedResult = yield* Fiber.join(failedInstall);
652 assert.equal(failedResult.state.errorContext, "install");
653​
654 const retry = yield* updates.install;
655 assert.isTrue(retry.accepted);
656 assert.equal(harness.quitAndInstalls(), 2);
657 }),
658 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
659 });
660​
661 it.effect("rejects a prepared install when the downloaded version changed", () => {
662 const harness = makeHarness();
663​
664 return Effect.scoped(
665 Effect.gen(function* () {
666 const updates = yield* DesktopUpdates.DesktopUpdates;
667 yield* updates.configure;
668 harness.emit("update-downloaded", { version: "1.2.5" });
669 yield* flushCallbacks;
670​
671 const result = yield* updates.installPrepared("1.2.4");
672 assert.isFalse(result.accepted);
673 assert.equal(harness.quitAndInstalls(), 0);
674 }),
675 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
676 });
677​
678 it.effect("persists channel changes through the settings service", () => {
679 const harness = makeHarness();
680​
681 return Effect.scoped(
682 Effect.gen(function* () {
683 const settings = yield* DesktopAppSettings.DesktopAppSettings;
684 const updates = yield* DesktopUpdates.DesktopUpdates;
685 yield* updates.configure;
686​
687 const state = yield* updates.setChannel("nightly");
688 const persistedSettings = yield* settings.get;
689​
690 assert.equal(state.channel, "nightly");
691 assert.equal(persistedSettings.updateChannel, "nightly");
692 assert.equal(persistedSettings.updateChannelConfiguredByUser, true);
693 }),
694 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
695 });
696​
697 it.effect("does not persist an unchanged update channel as a user preference", () => {
698 const harness = makeHarness();
699​
700 return Effect.scoped(
701 Effect.gen(function* () {
702 const settings = yield* DesktopAppSettings.DesktopAppSettings;
703 const updates = yield* DesktopUpdates.DesktopUpdates;
704 yield* updates.configure;
705​
706 const state = yield* updates.setChannel("latest");
707 const persistedSettings = yield* settings.get;
708​
709 assert.equal(state.channel, "latest");
710 assert.equal(persistedSettings.updateChannel, "latest");
711 assert.equal(persistedSettings.updateChannelConfiguredByUser, false);
712 }),
713 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
714 });
715​
716 it.effect("rejects checks while an update channel change is being persisted", () =>
717 Effect.gen(function* () {
718 const channelChangeStarted = yield* Deferred.make<void>();
719 const releaseChannelChange = yield* Deferred.make<void>();
720 const harness = makeHarness({
721 beforeSetUpdateChannel: Deferred.succeed(channelChangeStarted, undefined).pipe(
722 Effect.andThen(Deferred.await(releaseChannelChange)),
723 ),
724 });
725​
726 yield* Effect.scoped(
727 Effect.gen(function* () {
728 const updates = yield* DesktopUpdates.DesktopUpdates;
729 yield* updates.configure;
730​
731 const channelFiber = yield* updates.setChannel("nightly").pipe(Effect.forkScoped);
732 yield* Deferred.await(channelChangeStarted);
733​
734 const checkResult = yield* updates.check("manual");
735 assert.isFalse(checkResult.checked);
736 assert.equal(harness.checkCount(), 0);
737​
738 yield* Deferred.succeed(releaseChannelChange, undefined);
739 const state = yield* Fiber.join(channelFiber);
740​
741 assert.equal(state.channel, "nightly");
742 assert.equal(harness.checkCount(), 1);
743 }),
744 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
745 }),
746 );
747});
748​
749describe("describeUpdateErrorCause", () => {
750 it("removes URLs, credentials, response bodies, and headers from summaries", () => {
751 const messages = [
752 "Cannot download https://user:url-secret@example.com/update?token=query-secret, status 403",
753 "Request failed: Bearer bearer-secret",
754 "Request failed: Basic basic-secret",
755 "Request failed: Authorization: Bearer header-secret",
756 "Request failed: Cookie=session-secret",
757 "Request failed: api_key=\"key-secret\" password='password-secret' access_token=token-secret",
758 '404 Not Found\n{"body":"body-secret"}\nHeaders: cookie=header-secret',
759 "Request failed\rHeaders: cookie=header-secret",
760 ];
761​
762 for (const message of messages) {
763 const summary = DesktopUpdates.describeUpdateErrorCause(new Error(message));
764 assert.include(summary, "Error:");
765 assert.notInclude(summary, "secret");
766 assert.notInclude(summary, "https://");
767 assert.notInclude(summary, "Headers:");
768 }
769 assert.equal(
770 DesktopUpdates.describeUpdateErrorCause("404 Not Found\nbody-secret"),
771 "404 Not Found",
772 );
773 });
774​
775 it("bounds long messages, parallel failures, and cyclic causes", () => {
776 const longError = new Error("x".repeat(10_000));
777 const parallel = Cause.combine(Cause.fail(longError), Cause.die(longError));
778 assert.isAtMost(DesktopUpdates.describeUpdateErrorCause(parallel).length, 1024);
779​
780 const cyclic = new Error("retry failed");
781 cyclic.cause = cyclic;
782 assert.include(DesktopUpdates.describeUpdateErrorCause(cyclic), "[truncated cause]");
783 assert.isAtMost(DesktopUpdates.describeUpdateErrorCause(cyclic).length, 1024);
784 });
785​
786 it("does not serialize arbitrary payloads or let unreadable errors break logging", () => {
787 assert.equal(DesktopUpdates.describeUpdateErrorCause({ payload: "secret" }), "object");
788 const unreadable = Object.defineProperty({}, "message", {
789 get() {
790 throw new Error("unreadable error");
791 },
792 });
793 assert.equal(DesktopUpdates.describeUpdateErrorCause(unreadable), "UnknownError");
794 });
795});