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

DesktopUpdates.test.ts

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