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