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

DesktopUpdates.test.ts

1,440 lines55.2 KB

1import * as NodeModule from "node:module";
2​
3import { assert, describe, it } from "@effect/vitest";
4import { DESKTOP_UPDATE_RESTART_MARKER_FILE, DesktopUpdateStateSchema } from "@t3tools/contracts";
5import { computeReleaseNotes } from "electron-updater/out/providers/GitHubProvider.js";
6import * as Cause from "effect/Cause";
7import * as Deferred from "effect/Deferred";
8import * as Duration from "effect/Duration";
9import * as Effect from "effect/Effect";
10import * as Fiber from "effect/Fiber";
11import * as Layer from "effect/Layer";
12import * as Logger from "effect/Logger";
13import * as Option from "effect/Option";
14import * as References from "effect/References";
15import * as Ref from "effect/Ref";
16import * as Schema from "effect/Schema";
17import * as Stream from "effect/Stream";
18import * as TestClock from "effect/testing/TestClock";
19​
20import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
21import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
22import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
23import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
24import * as DesktopState from "../app/DesktopState.ts";
25import * as DesktopUpdatePolicy from "./DesktopUpdatePolicy.ts";
26import * as DesktopUpdates from "./DesktopUpdates.ts";
27import { flushCallbacks, makeHarness } from "./updatesTestHarness.ts";
28​
29const encodeUpdateState = Schema.encodeEffect(DesktopUpdateStateSchema);
30​
31type ReleaseFeed = Parameters<typeof computeReleaseNotes>[2];
32type RunningVersion = Parameters<typeof computeReleaseNotes>[0];
33​
34// electron-updater's own dependencies, which apps/desktop does not declare.
35const requireFromUpdater = NodeModule.createRequire(
36 NodeModule.createRequire(import.meta.url).resolve("electron-updater"),
37);
38const { parseXml } = requireFromUpdater("builder-util-runtime") as {
39 parseXml: (xml: string) => ReleaseFeed;
40};
41const semver = requireFromUpdater("semver") as { parse: (version: string) => RunningVersion };
42​
43const releaseTitle = (version: string) =>
44 version.includes("-nightly.")
45 ? `T3 Code Nightly ${version} (0123456789ab)`
46 : `T3 Code v${version}`;
47​
48const releaseFeed = (...versions: ReadonlyArray<string>) =>
49 parseXml(
50 `<feed xmlns="http://www.w3.org/2005/Atom">${versions
51 .map(
52 (version) =>
53 `<entry><link rel="alternate" type="text/html" href="https://github.com/pingdotgg/t3code/releases/tag/v${version}"/><title>${releaseTitle(version)}</title><content type="html">&lt;ul&gt;&lt;li&gt;${version} change&lt;/li&gt;&lt;/ul&gt;</content></entry>`,
54 )
55 .join("")}</feed>`,
56 );
57​
58/** The update info electron-updater's GitHub provider reports when /releases/latest names `version`. */
59const stableUpdateInfo = (
60 feed: ReleaseFeed,
61 version: string,
62 runningVersion: string,
63 fullChangelog: boolean,
64) => {
65 const latestRelease =
66 feed
67 .getElements("entry")
68 .find((entry) => entry.element("link").attribute("href").endsWith(`/tag/v${version}`)) ??
69 feed.element("entry");
70 return {
71 version,
72 releaseName: latestRelease.elementValueOrEmpty("title"),
73 releaseNotes: computeReleaseNotes(
74 semver.parse(runningVersion),
75 fullChangelog,
76 feed,
77 latestRelease,
78 ),
79 };
80};
81​
82describe("DesktopUpdates", () => {
83 it.effect("updates Linux .deb installs and leaves other non-AppImage installs off", () =>
84 Effect.gen(function* () {
85 const linuxState = (packageType: string | undefined) =>
86 Effect.scoped(
87 Effect.gen(function* () {
88 const updates = yield* DesktopUpdates.DesktopUpdates;
89 const desktopState = yield* DesktopState.DesktopState;
90 yield* updates.configure;
91 return {
92 state: yield* updates.getState,
93 canInstallUpdates: yield* Ref.get(desktopState.canInstallUpdates),
94 };
95 }),
96 ).pipe(Effect.provide(makeHarness({ platform: "linux", packageType }).layer));
97​
98 const deb = yield* linuxState("deb\n");
99 assert.equal(deb.state.status, "idle");
100 assert.isTrue(deb.canInstallUpdates);
101​
102 const unmarked = yield* linuxState(undefined);
103 assert.equal(unmarked.state.status, "disabled");
104 assert.isFalse(unmarked.canInstallUpdates);
105 }),
106 );
107​
108 it.effect("keeps the disabled reason available after configuration and channel changes", () => {
109 const harness = makeHarness({ env: { T3CODE_DISABLE_AUTO_UPDATE: "true" } });
110 const reason = "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
111​
112 return Effect.scoped(
113 Effect.gen(function* () {
114 const updates = yield* DesktopUpdates.DesktopUpdates;
115 yield* updates.configure;
116​
117 const configured = yield* updates.getState;
118 assert.equal(configured.message, reason);
119​
120 const changed = yield* updates.setChannel("nightly");
121 assert.equal(changed.channel, "nightly");
122 assert.equal(changed.enabled, false);
123 assert.equal(changed.status, "disabled");
124 assert.equal(changed.message, reason);
125 assert.equal(harness.sentStates.at(-1)?.message, reason);
126 assert.equal(harness.checkCount(), 0);
127 }),
128 ).pipe(Effect.provide(harness.layer));
129 });
130​
131 it.effect("re-checks an offered update without announcing it again", () => {
132 const harness = makeHarness();
133​
134 return Effect.scoped(
135 Effect.gen(function* () {
136 const updates = yield* DesktopUpdates.DesktopUpdates;
137 yield* updates.configure;
138​
139 harness.emit("update-available", {
140 version: "1.2.4",
141 releaseNotes: "## What's changed\n- fix: queued update",
142 });
143 yield* flushCallbacks;
144 const offeredStates = harness.sentStates.length;
145​
146 yield* updates.check("poll");
147 harness.emit("update-available", { version: "1.2.4" });
148 yield* flushCallbacks;
149 assert.equal(harness.sentStates.length, offeredStates);
150​
151 harness.emit("update-downloaded", { version: "1.2.4" });
152 yield* flushCallbacks;
153 const downloadedStates = harness.sentStates.length;
154​
155 const result = yield* updates.check("poll");
156 assert.isTrue(result.checked);
157​
158 harness.emit("update-available", { version: "1.2.4" });
159 yield* flushCallbacks;
160 assert.equal(harness.sentStates.length, downloadedStates);
161​
162 const unchangedState = yield* updates.getState;
163 assert.equal(unchangedState.status, "downloaded");
164 assert.equal(unchangedState.downloadedVersion, "1.2.4");
165 assert.deepEqual(unchangedState.releaseNotes, [
166 { version: "1.2.4", items: ["fix: queued update"], totalItems: 1 },
167 ]);
168 assert.equal(unchangedState.omittedReleaseCount, 0);
169​
170 const nextResult = yield* updates.check("poll");
171 assert.isTrue(nextResult.checked);
172​
173 harness.emit("update-available", { version: "1.2.5" });
174 yield* flushCallbacks;
175​
176 const state = yield* updates.getState;
177 assert.equal(state.status, "available");
178 assert.equal(state.availableVersion, "1.2.5");
179 assert.isNull(state.downloadedVersion);
180 }),
181 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
182 });
183​
184 it.effect.each([
185 {
186 name: "shows no notes for a Stable release missing from the releases feed",
187 runningVersion: "1.2.3",
188 feedVersions: ["1.2.5-nightly.20261102.1", "1.2.5-nightly.20261101.1"],
189 expected: [],
190 },
191 {
192 name: "shows a Stable release's own notes from the releases feed",
193 runningVersion: "1.2.3",
194 feedVersions: ["1.2.5-nightly.20261102.1", "1.2.4", "1.2.4-nightly.20261030.1"],
195 expected: [{ version: "1.2.4", items: ["1.2.4 change"], totalItems: 1 }],
196 },
197 {
198 name: "shows a Stable release's notes when switching down from a newer Nightly",
199 runningVersion: "1.2.5-nightly.20261027.1",
200 feedVersions: ["1.2.5-nightly.20261102.1", "1.2.4"],
201 expected: [{ version: "1.2.4", items: ["1.2.4 change"], totalItems: 1 }],
202 },
203 ])("$name", ({ runningVersion, feedVersions, expected }) => {
204 const harness = makeHarness();
205​
206 return Effect.scoped(
207 Effect.gen(function* () {
208 const updates = yield* DesktopUpdates.DesktopUpdates;
209 yield* updates.configure;
210​
211 harness.emit(
212 "update-available",
213 stableUpdateInfo(
214 releaseFeed(...feedVersions),
215 "1.2.4",
216 runningVersion,
217 harness.fullChangelog(),
218 ),
219 );
220 yield* flushCallbacks;
221​
222 const state = yield* updates.getState;
223 assert.equal(state.availableVersion, "1.2.4");
224 assert.deepEqual(state.releaseNotes, expected);
225 }),
226 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
227 });
228​
229 it.effect("preserves a queued installer when the feed has no update", () => {
230 const harness = makeHarness();
231​
232 return Effect.scoped(
233 Effect.gen(function* () {
234 const updates = yield* DesktopUpdates.DesktopUpdates;
235 yield* updates.configure;
236​
237 harness.emit("update-available", {
238 version: "1.2.4",
239 releaseNotes: "## What's changed\n- fix: queued update",
240 });
241 yield* flushCallbacks;
242 harness.emit("update-downloaded", { version: "1.2.4" });
243 yield* flushCallbacks;
244​
245 yield* updates.check("poll");
246 harness.emit("update-not-available");
247 yield* flushCallbacks;
248​
249 const state = yield* updates.getState;
250 assert.equal(state.status, "downloaded");
251 assert.equal(state.availableVersion, "1.2.4");
252 assert.equal(state.downloadedVersion, "1.2.4");
253 assert.deepEqual(state.releaseNotes, [
254 { version: "1.2.4", items: ["fix: queued update"], totalItems: 1 },
255 ]);
256 assert.equal(state.omittedReleaseCount, 0);
257 assert.equal(state.downloadPercent, 100);
258 }),
259 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
260 });
261​
262 it.effect("checks shortly after startup and then every four hours", () => {
263 const harness = makeHarness();
264​
265 return Effect.scoped(
266 Effect.gen(function* () {
267 const updates = yield* DesktopUpdates.DesktopUpdates;
268 yield* updates.configure;
269​
270 yield* TestClock.adjust("15 seconds");
271 assert.equal(harness.checkCount(), 1);
272​
273 yield* TestClock.adjust("3 hours");
274 assert.equal(harness.checkCount(), 1);
275​
276 yield* TestClock.adjust("1 hour");
277 assert.equal(harness.checkCount(), 2);
278 }),
279 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
280 });
281​
282 it.effect.each([
283 { action: "download", offer: "update-available", found: null, accepted: true },
284 { action: "install", offer: "update-downloaded", found: null, accepted: true },
285 { action: "download", offer: "update-available", found: "1.2.5", accepted: true },
286 { action: "install", offer: "update-downloaded", found: "1.2.5", accepted: false },
287 ] as const)(
288 "a $action waiting out a refresh check acts on what it found ($found)",
289 ({ action, offer, found, accepted }) =>
290 Effect.gen(function* () {
291 const checkStarted = yield* Deferred.make<void>();
292 const releaseCheck = yield* Deferred.make<void>();
293 const harness = makeHarness({
294 checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe(
295 Effect.andThen(Deferred.await(releaseCheck)),
296 // electron-updater emits the check's outcome before its promise resolves.
297 Effect.andThen(
298 Effect.sync(() => {
299 if (found !== null) harness.emit("update-available", { version: found });
300 }),
301 ),
302 ),
303 });
304​
305 yield* Effect.scoped(
306 Effect.gen(function* () {
307 const updates = yield* DesktopUpdates.DesktopUpdates;
308 yield* updates.configure;
309 harness.emit(offer, { version: "1.2.4" });
310 yield* flushCallbacks;
311​
312 const checkFiber = yield* updates.check("poll").pipe(Effect.forkScoped);
313 yield* Deferred.await(checkStarted);
314 const actionFiber = yield* updates[action].pipe(Effect.forkScoped);
315 yield* flushCallbacks;
316​
317 yield* Deferred.succeed(releaseCheck, undefined);
318 assert.isTrue((yield* Fiber.join(checkFiber)).checked);
319 assert.equal((yield* Fiber.join(actionFiber)).accepted, accepted);
320 const state = yield* updates.getState;
321 assert.equal(state.availableVersion, found ?? "1.2.4");
322 if (action === "download") assert.equal(state.status, "downloading");
323 }),
324 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
325 }),
326 );
327​
328 it.effect("rejects refresh checks while install is in progress", () =>
329 Effect.gen(function* () {
330 const installStarted = yield* Deferred.make<void>();
331 const releaseInstall = yield* Deferred.make<void>();
332 const harness = makeHarness({
333 stopBackend: Deferred.succeed(installStarted, undefined).pipe(
334 Effect.andThen(Deferred.await(releaseInstall)),
335 ),
336 });
337​
338 yield* Effect.scoped(
339 Effect.gen(function* () {
340 const updates = yield* DesktopUpdates.DesktopUpdates;
341 yield* updates.configure;
342 harness.emit("update-downloaded", { version: "1.2.4" });
343 yield* flushCallbacks;
344​
345 const installFiber = yield* updates.install.pipe(Effect.forkScoped);
346 yield* Deferred.await(installStarted);
347 const checksBefore = harness.checkCount();
348​
349 const checkResult = yield* updates.check("manual");
350 assert.isFalse(checkResult.checked);
351 assert.equal(harness.checkCount(), checksBefore);
352​
353 yield* Deferred.succeed(releaseInstall, undefined);
354 const installResult = yield* Fiber.join(installFiber);
355 assert.isTrue(installResult.accepted);
356 }),
357 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
358 }),
359 );
360​
361 it.effect("preserves a queued installer after a background updater error", () => {
362 const harness = makeHarness({
363 checkForUpdates: Effect.sync(() => harness.emit("update-not-available")),
364 });
365​
366 return 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 harness.emit("error", new Error("background updater failure"));
374 yield* flushCallbacks;
375​
376 const state = yield* updates.getState;
377 assert.equal(state.status, "error");
378 assert.equal(state.downloadedVersion, "1.2.4");
379 assert.isNull(state.errorContext);
380​
381 const result = yield* updates.install;
382 assert.isTrue(result.accepted);
383 }),
384 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
385 });
386​
387 it.effect("logs the redacted cause of a rejected update check", () => {
388 const cause = Object.assign(
389 new Error("request failed for https://user:secret@example.com/update?token=secret"),
390 { code: "ERR_UPDATER_LATEST_VERSION_NOT_FOUND" },
391 );
392 const updaterError = new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({
393 channel: null,
394 cause,
395 });
396 const harness = makeHarness({ checkForUpdates: Effect.fail(updaterError) });
397 const loggedAnnotations: Array<Record<string, unknown>> = [];
398 const logger = Logger.make(({ fiber }) => {
399 const annotations = fiber.getRef(References.CurrentLogAnnotations);
400 if (annotations.errorTag === "ElectronUpdaterCheckForUpdatesError") {
401 loggedAnnotations.push(annotations);
402 }
403 });
404​
405 return Effect.scoped(
406 Effect.gen(function* () {
407 const updates = yield* DesktopUpdates.DesktopUpdates;
408 yield* updates.configure;
409​
410 yield* updates.check("manual");
411​
412 const state = yield* updates.getState;
413 const loggedAnnotation = loggedAnnotations.at(-1);
414 assert.isDefined(loggedAnnotation);
415 assert.equal(loggedAnnotation.errorTag, "ElectronUpdaterCheckForUpdatesError");
416 assert.isNull(loggedAnnotation.channel);
417 assert.equal(
418 loggedAnnotation.cause,
419 "Error [ERR_UPDATER_LATEST_VERSION_NOT_FOUND]: request failed for [redacted URL]",
420 );
421 assert.notProperty(loggedAnnotation, "error");
422 assert.notInclude(Object.values(loggedAnnotation).map(String).join(" "), "secret");
423 assert.equal(
424 state.message,
425 "Electron updater failed to check for updates on channel default.",
426 );
427 assert.notInclude(state.message ?? "", "secret");
428 }),
429 ).pipe(
430 Effect.provide(
431 Layer.mergeAll(
432 TestClock.layer(),
433 harness.layer,
434 Logger.layer([logger], { mergeWithExisting: false }),
435 ),
436 ),
437 );
438 });
439​
440 it.effect("recovers download state after an unexpected setup failure", () => {
441 let disableDifferentialCalls = 0;
442 const harness = makeHarness({
443 setDisableDifferentialDownload: Effect.suspend(() => {
444 disableDifferentialCalls += 1;
445 return disableDifferentialCalls === 1
446 ? Effect.void
447 : Effect.die(new Error("download setup failed"));
448 }),
449 });
450​
451 return Effect.scoped(
452 Effect.gen(function* () {
453 const updates = yield* DesktopUpdates.DesktopUpdates;
454 yield* updates.configure;
455 harness.emit("update-available", { version: "1.2.4" });
456 yield* flushCallbacks;
457​
458 const result = yield* updates.download;
459 assert.isTrue(result.accepted);
460 assert.isFalse(result.completed);
461​
462 const failedState = yield* updates.getState;
463 assert.equal(failedState.status, "available");
464 assert.equal(failedState.errorContext, "download");
465 assert.equal(failedState.message, "Desktop update download action failed unexpectedly.");
466​
467 const changedState = yield* updates.setChannel("nightly");
468 assert.equal(changedState.channel, "nightly");
469 }),
470 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
471 });
472​
473 it.effect("shows why a download failed, not only the channel", () => {
474 const harness = makeHarness({
475 downloadUpdate: Effect.fail(
476 new ElectronUpdater.ElectronUpdaterDownloadUpdateError({
477 channel: "nightly",
478 cause: new Error("net::ERR_CONTENT_LENGTH_MISMATCH"),
479 }),
480 ),
481 });
482​
483 return Effect.scoped(
484 Effect.gen(function* () {
485 const updates = yield* DesktopUpdates.DesktopUpdates;
486 yield* updates.configure;
487 harness.emit("update-available", { version: "1.2.4" });
488 yield* flushCallbacks;
489​
490 const result = yield* updates.download;
491 assert.isFalse(result.completed);
492​
493 const state = yield* updates.getState;
494 assert.equal(state.errorContext, "download");
495 assert.include(state.message ?? "", "ERR_CONTENT_LENGTH_MISMATCH");
496 }),
497 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
498 });
499​
500 it.effect("downloads the newest release published since the last check", () => {
501 // electron-updater downloads the release its last checkForUpdates found.
502 let published = "1.2.4";
503 let lastChecked: string | undefined;
504 const harness = makeHarness({
505 checkForUpdates: Effect.sync(() => {
506 lastChecked = published;
507 harness.emit("update-available", { version: published });
508 }),
509 downloadUpdate: Effect.sync(() => {
510 harness.emit("update-downloaded", { version: lastChecked });
511 }),
512 });
513​
514 return Effect.scoped(
515 Effect.gen(function* () {
516 const updates = yield* DesktopUpdates.DesktopUpdates;
517 yield* updates.configure;
518 yield* updates.check("poll");
519 yield* flushCallbacks;
520 assert.equal((yield* updates.getState).availableVersion, "1.2.4");
521​
522 published = "1.2.5";
523 const result = yield* updates.download;
524 yield* flushCallbacks;
525 assert.isTrue(result.completed);
526 assert.equal((yield* updates.getState).downloadedVersion, "1.2.5");
527 }),
528 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
529 });
530​
531 it.effect("installs a release published after the retained download", () => {
532 let published = "1.2.4";
533 let lastChecked: string | undefined;
534 let installedVersion: string | null | undefined;
535 const harness = makeHarness({
536 checkForUpdates: Effect.sync(() => {
537 lastChecked = published;
538 harness.emit("update-available", { version: published });
539 }),
540 downloadUpdate: Effect.sync(() => {
541 harness.emit("update-downloaded", { version: lastChecked });
542 }),
543 quitAndInstall: Effect.sync(() => {
544 installedVersion = harness.sentStates.at(-1)?.downloadedVersion;
545 }),
546 });
547​
548 return Effect.scoped(
549 Effect.gen(function* () {
550 const updates = yield* DesktopUpdates.DesktopUpdates;
551 yield* updates.configure;
552 yield* updates.check("poll");
553 yield* flushCallbacks;
554 yield* updates.download;
555 yield* flushCallbacks;
556 assert.equal((yield* updates.getState).downloadedVersion, "1.2.4");
557​
558 published = "1.2.5";
559 const checksBefore = harness.checkCount();
560 const result = yield* updates.installPrepared("1.2.4");
561 assert.isTrue(result.accepted);
562 // A second check before downloading could find a stale feed's older release.
563 assert.equal(harness.checkCount(), checksBefore + 1);
564 assert.equal(harness.quitAndInstalls(), 1);
565 assert.equal(installedVersion, "1.2.5");
566 }),
567 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
568 });
569​
570 it.effect("downloads the known offer when the check before downloading fails", () => {
571 let checks = 0;
572 const harness = makeHarness({
573 checkForUpdates: Effect.suspend(() => {
574 checks += 1;
575 if (checks > 1) {
576 return Effect.fail(
577 new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({
578 channel: null,
579 cause: new Error("offline"),
580 }),
581 );
582 }
583 harness.emit("update-available", { version: "1.2.4" });
584 return Effect.void;
585 }),
586 downloadUpdate: Effect.sync(() => {
587 harness.emit("update-downloaded", { version: "1.2.4" });
588 }),
589 });
590​
591 return Effect.scoped(
592 Effect.gen(function* () {
593 const updates = yield* DesktopUpdates.DesktopUpdates;
594 yield* updates.configure;
595 yield* updates.check("poll");
596 yield* flushCallbacks;
597​
598 const result = yield* updates.download;
599 yield* flushCallbacks;
600 assert.isTrue(result.completed);
601 assert.equal((yield* updates.getState).downloadedVersion, "1.2.4");
602 // Remote requests treat a published error after their own check as final.
603 assert.notInclude(
604 harness.sentStates.map((state) => state.status),
605 "error",
606 );
607 }),
608 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
609 });
610​
611 it.effect("installs the retained download when a stale feed offers an older release", () => {
612 let published = "1.2.5";
613 let installedVersion: string | null | undefined;
614 const harness = makeHarness({
615 checkForUpdates: Effect.sync(() => harness.emit("update-available", { version: published })),
616 downloadUpdate: Effect.sync(() => harness.emit("update-downloaded", { version: "1.2.5" })),
617 quitAndInstall: Effect.sync(() => {
618 installedVersion = harness.sentStates.at(-1)?.downloadedVersion;
619 }),
620 });
621​
622 return Effect.scoped(
623 Effect.gen(function* () {
624 const updates = yield* DesktopUpdates.DesktopUpdates;
625 yield* updates.configure;
626 yield* updates.check("poll");
627 yield* updates.download;
628 yield* flushCallbacks;
629​
630 published = "1.2.4";
631 const result = yield* updates.installPrepared("1.2.5");
632 assert.isTrue(result.accepted);
633 assert.equal(harness.downloadCount(), 1);
634 assert.equal(installedVersion, "1.2.5");
635 }),
636 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
637 });
638​
639 it.effect("restores download state and permits retry after interruption", () =>
640 Effect.gen(function* () {
641 const actionStarted = yield* Deferred.make<void>();
642 let disableDifferentialCalls = 0;
643 const harness = makeHarness({
644 setDisableDifferentialDownload: Effect.suspend(() => {
645 disableDifferentialCalls += 1;
646 if (disableDifferentialCalls === 1) {
647 return Effect.void;
648 }
649 if (disableDifferentialCalls === 2) {
650 return Deferred.succeed(actionStarted, undefined).pipe(Effect.andThen(Effect.never));
651 }
652 return Effect.void;
653 }),
654 });
655​
656 yield* Effect.scoped(
657 Effect.gen(function* () {
658 const updates = yield* DesktopUpdates.DesktopUpdates;
659 yield* updates.configure;
660 harness.emit("update-available", { version: "1.2.4" });
661 yield* flushCallbacks;
662​
663 const downloadFiber = yield* updates.download.pipe(Effect.forkScoped);
664 yield* Deferred.await(actionStarted);
665 yield* Fiber.interrupt(downloadFiber);
666​
667 const interruptedState = yield* updates.getState;
668 assert.equal(interruptedState.status, "available");
669 assert.isNull(interruptedState.message);
670​
671 const retry = yield* updates.download;
672 assert.isTrue(retry.accepted);
673 assert.isTrue(retry.completed);
674 }),
675 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
676 }),
677 );
678​
679 it.effect("clears quitting state after an unexpected install setup failure", () => {
680 const harness = makeHarness({
681 stopBackend: Effect.die(new Error("backend stop failed")),
682 });
683​
684 return Effect.scoped(
685 Effect.gen(function* () {
686 const desktopState = yield* DesktopState.DesktopState;
687 const updates = yield* DesktopUpdates.DesktopUpdates;
688 yield* updates.configure;
689 harness.emit("update-downloaded", { version: "1.2.4" });
690 yield* flushCallbacks;
691​
692 const result = yield* updates.install;
693 assert.isTrue(result.accepted);
694 assert.isFalse(result.completed);
695 assert.isFalse(yield* Ref.get(desktopState.quitting));
696​
697 const failedState = yield* updates.getState;
698 assert.equal(failedState.status, "downloaded");
699 assert.equal(failedState.errorContext, "install");
700 assert.equal(failedState.message, "Desktop update install action failed unexpectedly.");
701​
702 const changedState = yield* updates.setChannel("nightly");
703 assert.equal(changedState.channel, "nightly");
704 }),
705 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
706 });
707​
708 it.effect("marks the backend stop for an install as an update restart", () => {
709 let markersAtStop: ReadonlyArray<string> = [];
710 let inProgressAtStop: string | undefined;
711 const harness = makeHarness({
712 stopBackend: Effect.sync(() => {
713 markersAtStop = [...harness.updateRestartMarkers];
714 inProgressAtStop = harness.updateInProgressMarker();
715 }),
716 });
717​
718 return Effect.scoped(
719 Effect.gen(function* () {
720 yield* TestClock.setTime(1_000);
721 const environment = yield* DesktopEnvironment.DesktopEnvironment;
722 const updates = yield* DesktopUpdates.DesktopUpdates;
723 yield* updates.configure;
724 harness.emit("update-downloaded", { version: "1.2.4" });
725 yield* flushCallbacks;
726​
727 assert.isTrue((yield* updates.install).accepted);
728 assert.deepEqual(markersAtStop, [
729 environment.path.join(environment.baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE),
730 ]);
731 // SSH launchers wait on this until the replacement backend publishes its runtime.
732 assert.deepEqual(JSON.parse(inProgressAtStop ?? "null"), {
733 startedAt: 1_000,
734 expiresAt: 61_000,
735 });
736 assert.isDefined(harness.updateInProgressMarker());
737 }),
738 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
739 });
740​
741 it.effect("records the version an install hands to the installer", () => {
742 let recordsAtStop: ReadonlyArray<string> = [];
743 const harness = makeHarness({
744 stopBackend: Effect.sync(() => {
745 recordsAtStop = [...harness.installRecords.values()];
746 }),
747 });
748​
749 return Effect.scoped(
750 Effect.gen(function* () {
751 const updates = yield* DesktopUpdates.DesktopUpdates;
752 yield* updates.configure;
753 harness.emit("update-downloaded", { version: "1.2.4" });
754 yield* flushCallbacks;
755​
756 assert.isTrue((yield* updates.install).accepted);
757 assert.deepEqual(
758 recordsAtStop.map((record) => JSON.parse(record)),
759 [{ fromVersion: "1.2.3", targetVersion: "1.2.4" }],
760 );
761 }),
762 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
763 });
764​
765 it.effect("flags an install that did not apply and keeps the flag through checks", () => {
766 const harness = makeHarness({
767 installRecord: JSON.stringify({ fromVersion: "1.2.3", targetVersion: "1.2.4" }),
768 });
769​
770 return Effect.scoped(
771 Effect.gen(function* () {
772 const updates = yield* DesktopUpdates.DesktopUpdates;
773 yield* updates.configure;
774 assert.equal((yield* updates.getState).notAppliedVersion, "1.2.4");
775 assert.isDefined(harness.previousInstallRecord());
776​
777 harness.emit("update-available", { version: "1.2.4" });
778 yield* flushCallbacks;
779 const state = yield* updates.getState;
780 assert.equal(state.status, "available");
781 assert.equal(state.notAppliedVersion, "1.2.4");
782 }),
783 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
784 });
785​
786 // regression: #19291 an install that did apply was still flagged as not applied
787 it.effect("does not flag an install that applied", () => {
788 const harness = makeHarness({
789 installRecord: JSON.stringify({ fromVersion: "1.2.2", targetVersion: "1.2.3" }),
790 });
791​
792 return Effect.scoped(
793 Effect.gen(function* () {
794 const updates = yield* DesktopUpdates.DesktopUpdates;
795 yield* updates.configure;
796 assert.isUndefined((yield* updates.getState).notAppliedVersion);
797 assert.isUndefined(harness.previousInstallRecord());
798 }),
799 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
800 });
801​
802 it.effect("drops the update restart marker when an install is interrupted", () =>
803 Effect.gen(function* () {
804 const stopping = yield* Deferred.make<void>();
805 const harness = makeHarness({
806 stopBackend: Deferred.succeed(stopping, undefined).pipe(Effect.andThen(Effect.never)),
807 });
808​
809 yield* Effect.scoped(
810 Effect.gen(function* () {
811 const updates = yield* DesktopUpdates.DesktopUpdates;
812 yield* updates.configure;
813 harness.emit("update-downloaded", { version: "1.2.4" });
814 yield* flushCallbacks;
815​
816 const installFiber = yield* updates.install.pipe(Effect.forkScoped);
817 yield* Deferred.await(stopping);
818 assert.equal(harness.updateRestartMarkers.size, 1);
819 assert.isDefined(harness.updateInProgressMarker());
820​
821 yield* Fiber.interrupt(installFiber);
822 assert.equal(harness.updateRestartMarkers.size, 0);
823 assert.isUndefined(harness.updateInProgressMarker());
824 }),
825 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
826 }),
827 );
828​
829 it.effect("keeps windows and restarts backends when quitAndInstall fails", () => {
830 const harness = makeHarness({
831 quitAndInstall: Effect.fail(
832 new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
833 channel: "latest",
834 isSilent: true,
835 isForceRunAfter: true,
836 cause: new Error("installer refused"),
837 }),
838 ),
839 });
840​
841 return Effect.scoped(
842 Effect.gen(function* () {
843 const desktopState = yield* DesktopState.DesktopState;
844 const updates = yield* DesktopUpdates.DesktopUpdates;
845 yield* updates.configure;
846 harness.emit("update-downloaded", { version: "1.2.4" });
847 yield* flushCallbacks;
848​
849 const result = yield* updates.install;
850 assert.isTrue(result.accepted);
851 assert.isFalse(yield* Ref.get(desktopState.quitting));
852 assert.deepEqual(harness.installSteps, [
853 "closeSshTunnels",
854 "quitAndInstall",
855 "startBackend",
856 ]);
857 assert.equal(harness.updateRestartMarkers.size, 0);
858 assert.isUndefined(harness.updateInProgressMarker());
859 assert.equal(harness.installRecords.size, 0);
860 }),
861 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
862 });
863​
864 it.effect("keeps the disabled primary stopped when quitAndInstall fails", () => {
865 const harness = makeHarness({
866 backendDesiredRunning: false,
867 quitAndInstall: Effect.fail(
868 new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
869 channel: "latest",
870 isSilent: true,
871 isForceRunAfter: true,
872 cause: new Error("installer refused"),
873 }),
874 ),
875 });
876​
877 return Effect.scoped(
878 Effect.gen(function* () {
879 const updates = yield* DesktopUpdates.DesktopUpdates;
880 const pool = yield* DesktopBackendPool.DesktopBackendPool;
881 yield* updates.configure;
882 harness.emit("update-downloaded", { version: "1.2.4" });
883 yield* flushCallbacks;
884​
885 const result = yield* updates.install;
886 assert.equal(result.state.errorContext, "install");
887 assert.deepEqual(harness.installSteps, ["closeSshTunnels", "quitAndInstall"]);
888 assert.isFalse((yield* (yield* pool.primary).snapshot).desiredRunning);
889 }),
890 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
891 });
892​
893 it.effect("restores only desired-running instances after an installer error event", () => {
894 const starts: string[] = [];
895 const stops: string[] = [];
896 const makeInstance = (id: DesktopBackendPool.BackendInstanceId, initiallyRunning: boolean) => {
897 let desiredRunning = initiallyRunning;
898 return {
899 id,
900 label: Effect.succeed(id),
901 currentConfig: Effect.succeedNone,
902 start: Effect.sync(() => {
903 starts.push(id);
904 desiredRunning = true;
905 }),
906 stop: () =>
907 Effect.sync(() => {
908 stops.push(id);
909 desiredRunning = false;
910 }),
911 snapshot: Effect.sync(() => ({
912 desiredRunning,
913 ready: false,
914 activePid: Option.none(),
915 restartAttempt: 0,
916 restartScheduled: false,
917 })),
918 waitForReady: () => Effect.succeed(true),
919 } satisfies DesktopBackendPool.DesktopBackendInstance;
920 };
921 const primary = makeInstance(DesktopBackendPool.PRIMARY_INSTANCE_ID, false);
922 const wsl = makeInstance(DesktopBackendPool.BackendInstanceId("wsl:default"), true);
923 const harness = makeHarness({ backendInstances: [primary, wsl] });
924​
925 return Effect.scoped(
926 Effect.gen(function* () {
927 const updates = yield* DesktopUpdates.DesktopUpdates;
928 yield* updates.configure;
929 harness.emit("update-downloaded", { version: "1.2.4" });
930 yield* flushCallbacks;
931​
932 yield* updates.install;
933 assert.sameMembers(stops, [primary.id, wsl.id]);
934 assert.isFalse((yield* wsl.snapshot).desiredRunning);
935 const { changes } = yield* updates.subscribe;
936 const recovered = yield* Stream.runHead(changes).pipe(Effect.forkChild);
937 yield* flushCallbacks;
938 harness.emit("error", new Error("native installer refused"));
939 assert.equal(Option.getOrThrow(yield* Fiber.join(recovered)).errorContext, "install");
940​
941 assert.deepEqual(starts, [wsl.id]);
942 assert.isFalse((yield* primary.snapshot).desiredRunning);
943 assert.isTrue((yield* wsl.snapshot).desiredRunning);
944 }),
945 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
946 });
947​
948 it.effect("holds the install reservation until failed-install recovery finishes", () => {
949 const recoveryStarted = Deferred.makeUnsafe<void>();
950 const releaseRecovery = Deferred.makeUnsafe<void>();
951 const harness = makeHarness({
952 quitAndInstall: Effect.fail(
953 new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
954 channel: "latest",
955 isSilent: true,
956 isForceRunAfter: true,
957 cause: new Error("installer refused"),
958 }),
959 ),
960 startBackend: Deferred.succeed(recoveryStarted, undefined).pipe(
961 Effect.andThen(Deferred.await(releaseRecovery)),
962 ),
963 });
964​
965 return Effect.scoped(
966 Effect.gen(function* () {
967 const updates = yield* DesktopUpdates.DesktopUpdates;
968 yield* updates.configure;
969 harness.emit("update-downloaded", { version: "1.2.4" });
970 yield* flushCallbacks;
971​
972 const failedInstall = yield* updates.install.pipe(Effect.forkChild);
973 yield* Deferred.await(recoveryStarted);
974 assert.isFalse(yield* updates.isInstallActive);
975​
976 const overlappingInstall = yield* updates.install;
977 assert.isFalse(overlappingInstall.accepted);
978 assert.equal(harness.quitAndInstalls(), 1);
979 harness.emit("error", new Error("duplicate native installer error"));
980 yield* flushCallbacks;
981 assert.deepEqual(harness.installSteps, [
982 "closeSshTunnels",
983 "quitAndInstall",
984 "startBackend",
985 ]);
986​
987 yield* Deferred.succeed(releaseRecovery, undefined);
988 const failedResult = yield* Fiber.join(failedInstall);
989 assert.equal(failedResult.state.errorContext, "install");
990​
991 const retry = yield* updates.install;
992 assert.isTrue(retry.accepted);
993 assert.equal(harness.quitAndInstalls(), 2);
994 }),
995 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
996 });
997​
998 it.effect("rejects a prepared install when the downloaded version changed", () => {
999 const harness = makeHarness();
1000​
1001 return Effect.scoped(
1002 Effect.gen(function* () {
1003 const updates = yield* DesktopUpdates.DesktopUpdates;
1004 yield* updates.configure;
1005 harness.emit("update-downloaded", { version: "1.2.5" });
1006 yield* flushCallbacks;
1007​
1008 const result = yield* updates.installPrepared("1.2.4");
1009 assert.isFalse(result.accepted);
1010 assert.equal(harness.quitAndInstalls(), 0);
1011 }),
1012 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1013 });
1014​
1015 it.effect("persists channel changes through the settings service", () => {
1016 const harness = makeHarness();
1017​
1018 return Effect.scoped(
1019 Effect.gen(function* () {
1020 const settings = yield* DesktopAppSettings.DesktopAppSettings;
1021 const updates = yield* DesktopUpdates.DesktopUpdates;
1022 yield* updates.configure;
1023​
1024 const state = yield* updates.setChannel("nightly");
1025 const persistedSettings = yield* settings.get;
1026​
1027 assert.equal(state.channel, "nightly");
1028 assert.equal(persistedSettings.updateChannel, "nightly");
1029 assert.equal(persistedSettings.updateChannelConfiguredByUser, true);
1030 }),
1031 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1032 });
1033​
1034 it.effect("ignores a finished download from a track it no longer follows", () => {
1035 const harness = makeHarness();
1036​
1037 return Effect.scoped(
1038 Effect.gen(function* () {
1039 const updates = yield* DesktopUpdates.DesktopUpdates;
1040 yield* updates.configure;
1041 // A backed-out switch's download keeps reporting progress until it finishes.
1042 harness.emit("download-progress", { percent: 40 });
1043 yield* flushCallbacks;
1044 harness.emit("update-downloaded", { version: "1.2.4-nightly.20261027.1" });
1045 yield* flushCallbacks;
1046​
1047 const state = yield* updates.getState;
1048 assert.equal(state.downloadedVersion, null);
1049 assert.notEqual(state.status, "downloading");
1050 }),
1051 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1052 });
1053​
1054 it.effect("offers older releases only to checks that leave the running build's track", () => {
1055 const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });
1056​
1057 return Effect.scoped(
1058 Effect.gen(function* () {
1059 const updates = yield* DesktopUpdates.DesktopUpdates;
1060 yield* updates.configure;
1061 const before = harness.checkAllowedDowngrade.length;
1062 yield* updates.setChannel("nightly");
1063 yield* updates.setChannel("latest");
1064 yield* updates.check("remote-update", { allowDowngrade: true });
1065​
1066 // Back on its own Stable track the build never needs an older release.
1067 assert.deepEqual(harness.checkAllowedDowngrade.slice(before), [true, false, true]);
1068 assert.isFalse(harness.allowDowngrade());
1069 }),
1070 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1071 });
1072​
1073 it.effect("re-checks a saved track that differs from the running build's track", () => {
1074 const harness = makeHarness({
1075 appVersion: "1.2.4-nightly.20261027.1",
1076 beforeSetUpdateChannel: Effect.void,
1077 });
1078​
1079 return Effect.scoped(
1080 Effect.gen(function* () {
1081 const updates = yield* DesktopUpdates.DesktopUpdates;
1082 yield* updates.configure;
1083 yield* updates.setChannel("latest");
1084 const checks = harness.checkCount();
1085​
1086 yield* updates.setChannel("latest");
1087​
1088 assert.equal(harness.checkCount(), checks + 1);
1089 }),
1090 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1091 });
1092​
1093 it.effect("does not persist an unchanged update channel as a user preference", () => {
1094 const harness = makeHarness();
1095​
1096 return Effect.scoped(
1097 Effect.gen(function* () {
1098 const settings = yield* DesktopAppSettings.DesktopAppSettings;
1099 const updates = yield* DesktopUpdates.DesktopUpdates;
1100 yield* updates.configure;
1101​
1102 const state = yield* updates.setChannel("latest");
1103 const persistedSettings = yield* settings.get;
1104​
1105 assert.equal(state.channel, "latest");
1106 assert.equal(persistedSettings.updateChannel, "latest");
1107 assert.equal(persistedSettings.updateChannelConfiguredByUser, false);
1108 }),
1109 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1110 });
1111​
1112 it.effect("offers nothing below a track switch's checked release", () => {
1113 const harness = makeHarness({
1114 appVersion: "1.2.4-nightly.20261027.1",
1115 beforeSetUpdateChannel: Effect.void,
1116 });
1117​
1118 return Effect.scoped(
1119 Effect.gen(function* () {
1120 const updates = yield* DesktopUpdates.DesktopUpdates;
1121 yield* updates.configure;
1122 yield* updates.setChannel("latest", { minimumVersion: "1.2.3" });
1123​
1124 harness.emit("update-available", { version: "1.2.2" });
1125 yield* flushCallbacks;
1126 assert.isNull((yield* updates.getState).availableVersion);
1127 harness.emit("update-downloaded", { version: "1.2.2" });
1128 yield* flushCallbacks;
1129 assert.isNull((yield* updates.getState).downloadedVersion);
1130​
1131 harness.emit("update-available", { version: "1.2.3" });
1132 yield* flushCallbacks;
1133 assert.equal((yield* updates.getState).availableVersion, "1.2.3");
1134 }),
1135 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1136 });
1137​
1138 it.effect("keeps the current track's offers when a track switch fails to save", () => {
1139 const harness = makeHarness({
1140 setUpdateChannelError: new DesktopAppSettings.DesktopSettingsWriteError({
1141 operation: "replace-settings-file",
1142 path: "desktop-settings.json",
1143 cause: new Error("rename failed"),
1144 }),
1145 });
1146​
1147 return Effect.scoped(
1148 Effect.gen(function* () {
1149 const updates = yield* DesktopUpdates.DesktopUpdates;
1150 yield* updates.configure;
1151 const error = yield* updates
1152 .setChannel("nightly", { minimumVersion: "1.2.5-nightly.20261028.1" })
1153 .pipe(Effect.flip);
1154 assert.equal(error._tag, "DesktopUpdateChannelPersistenceError");
1155 assert.equal((yield* updates.getState).channel, "latest");
1156​
1157 harness.emit("update-available", { version: "1.2.4" });
1158 yield* flushCallbacks;
1159 assert.equal((yield* updates.getState).availableVersion, "1.2.4");
1160 }),
1161 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1162 });
1163​
1164 it.effect("keeps a saved Stable track across a restart without offering an older release", () => {
1165 // A Nightly build whose switch to Stable did not finish before the app quit.
1166 const harness = makeHarness({ appVersion: "1.2.4-nightly.20261027.1", savedChannel: "latest" });
1167​
1168 return Effect.scoped(
1169 Effect.gen(function* () {
1170 const updates = yield* DesktopUpdates.DesktopUpdates;
1171 yield* updates.configure;
1172 yield* updates.check("startup");
1173​
1174 assert.equal((yield* updates.getState).channel, "latest");
1175 assert.deepEqual(harness.checkAllowedDowngrade, [false]);
1176 // Semver ranks Stable 1.2.4 above this Nightly, but a Nightly built before the release's
1177 // version bump can hold migrations 1.2.4 lacks. Crossing needs a guarded switch.
1178 harness.emit("update-available", { version: "1.2.4" });
1179 yield* flushCallbacks;
1180 assert.isNull((yield* updates.getState).availableVersion);
1181 }),
1182 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1183 });
1184​
1185 it.effect("keeps a saved Nightly track across a restart without crossing on its own", () => {
1186 // A Stable build whose switch to Nightly was refused before the app quit; its floor is gone.
1187 const harness = makeHarness({ savedChannel: "nightly" });
1188​
1189 return Effect.scoped(
1190 Effect.gen(function* () {
1191 const updates = yield* DesktopUpdates.DesktopUpdates;
1192 yield* updates.configure;
1193 yield* updates.check("startup");
1194 harness.emit("update-available", { version: "1.2.4-nightly.20261027.1" });
1195 yield* flushCallbacks;
1196​
1197 assert.equal((yield* updates.getState).channel, "nightly");
1198 assert.isNull((yield* updates.getState).availableVersion);
1199 assert.deepEqual(harness.checkAllowedDowngrade, [false]);
1200 }),
1201 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1202 });
1203​
1204 it.effect("never offers an older Nightly to a Nightly build's own checks", () => {
1205 const harness = makeHarness({ appVersion: "1.2.4-nightly.20261027.1" });
1206​
1207 return Effect.scoped(
1208 Effect.gen(function* () {
1209 const updates = yield* DesktopUpdates.DesktopUpdates;
1210 yield* updates.configure;
1211 yield* updates.check("poll");
1212​
1213 assert.equal((yield* updates.getState).channel, "nightly");
1214 assert.deepEqual(harness.checkAllowedDowngrade, [false]);
1215 }),
1216 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1217 });
1218​
1219 it.effect("waits out a background check instead of refusing a track change", () =>
1220 Effect.gen(function* () {
1221 const checkStarted = yield* Deferred.make<void>();
1222 const releaseCheck = yield* Deferred.make<void>();
1223 const harness = makeHarness({
1224 beforeSetUpdateChannel: Effect.void,
1225 checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe(
1226 Effect.andThen(Deferred.await(releaseCheck)),
1227 ),
1228 });
1229​
1230 yield* Effect.scoped(
1231 Effect.gen(function* () {
1232 const updates = yield* DesktopUpdates.DesktopUpdates;
1233 yield* updates.configure;
1234 yield* updates.check("poll").pipe(Effect.forkScoped);
1235 yield* Deferred.await(checkStarted);
1236​
1237 const channelFiber = yield* updates.setChannel("nightly").pipe(Effect.forkScoped);
1238 yield* Deferred.succeed(releaseCheck, undefined);
1239 yield* TestClock.adjust(Duration.seconds(2));
1240 const state = yield* Fiber.join(channelFiber);
1241​
1242 assert.equal(state.channel, "nightly");
1243 }),
1244 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1245 }),
1246 );
1247​
1248 it.effect("rejects checks while an update channel change is being persisted", () =>
1249 Effect.gen(function* () {
1250 const channelChangeStarted = yield* Deferred.make<void>();
1251 const releaseChannelChange = yield* Deferred.make<void>();
1252 const harness = makeHarness({
1253 beforeSetUpdateChannel: Deferred.succeed(channelChangeStarted, undefined).pipe(
1254 Effect.andThen(Deferred.await(releaseChannelChange)),
1255 ),
1256 });
1257​
1258 yield* Effect.scoped(
1259 Effect.gen(function* () {
1260 const updates = yield* DesktopUpdates.DesktopUpdates;
1261 yield* updates.configure;
1262​
1263 const channelFiber = yield* updates.setChannel("nightly").pipe(Effect.forkScoped);
1264 yield* Deferred.await(channelChangeStarted);
1265​
1266 const checkResult = yield* updates.check("manual");
1267 assert.isFalse(checkResult.checked);
1268 assert.equal(harness.checkCount(), 0);
1269​
1270 yield* Deferred.succeed(releaseChannelChange, undefined);
1271 const state = yield* Fiber.join(channelFiber);
1272​
1273 assert.equal(state.channel, "nightly");
1274 assert.equal(harness.checkCount(), 1);
1275 }),
1276 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1277 }),
1278 );
1279});
1280​
1281describe("describeUpdateErrorCause", () => {
1282 it("removes URLs, credentials, response bodies, and headers from summaries", () => {
1283 const messages = [
1284 "Cannot download https://user:url-secret@example.com/update?token=query-secret, status 403",
1285 "Request failed: Bearer bearer-secret",
1286 "Request failed: Basic basic-secret",
1287 "Request failed: Authorization: Bearer header-secret",
1288 "Request failed: Cookie=session-secret",
1289 "Request failed: api_key=\"key-secret\" password='password-secret' access_token=token-secret",
1290 '404 Not Found\n{"body":"body-secret"}\nHeaders: cookie=header-secret',
1291 "Request failed\rHeaders: cookie=header-secret",
1292 ];
1293​
1294 for (const message of messages) {
1295 const summary = DesktopUpdates.describeUpdateErrorCause(new Error(message));
1296 assert.include(summary, "Error:");
1297 assert.notInclude(summary, "secret");
1298 assert.notInclude(summary, "https://");
1299 assert.notInclude(summary, "Headers:");
1301 assert.equal(
1302 DesktopUpdates.describeUpdateErrorCause("404 Not Found\nbody-secret"),
1303 "404 Not Found",
1304 );
1305 });
1306​
1307 it("bounds long messages, parallel failures, and cyclic causes", () => {
1308 const longError = new Error("x".repeat(10_000));
1309 const parallel = Cause.combine(Cause.fail(longError), Cause.die(longError));
1310 assert.isAtMost(DesktopUpdates.describeUpdateErrorCause(parallel).length, 1024);
1311​
1312 const cyclic = new Error("retry failed");
1313 cyclic.cause = cyclic;
1314 assert.include(DesktopUpdates.describeUpdateErrorCause(cyclic), "[truncated cause]");
1315 assert.isAtMost(DesktopUpdates.describeUpdateErrorCause(cyclic).length, 1024);
1316 });
1317​
1318 it("does not serialize arbitrary payloads or let unreadable errors break logging", () => {
1319 assert.equal(DesktopUpdates.describeUpdateErrorCause({ payload: "secret" }), "object");
1320 const unreadable = Object.defineProperty({}, "message", {
1321 get() {
1322 throw new Error("unreadable error");
1323 },
1324 });
1325 assert.equal(DesktopUpdates.describeUpdateErrorCause(unreadable), "UnknownError");
1326 });
1327});
1328​
1329describe("DesktopUpdates under a managed policy", () => {
1330 const message = "Example Corp manages T3 Code updates.";
1331 const managed = (
1332 policy: Partial<DesktopUpdatePolicy.UpdatePolicy>,
1333 ): DesktopUpdatePolicy.UpdatePolicy => ({
1334 ...DesktopUpdatePolicy.unmanagedUpdatePolicy,
1335 message,
1336 ...policy,
1337 });
1338​
1339 it.effect("never checks when updates are off", () => {
1340 const harness = makeHarness({ policy: managed({ mode: "off" }) });
1341​
1342 return Effect.scoped(
1343 Effect.gen(function* () {
1344 const updates = yield* DesktopUpdates.DesktopUpdates;
1345 yield* updates.configure;
1346 yield* TestClock.adjust("10 minutes");
1347​
1348 const state = yield* updates.getState;
1349 assert.equal(state.status, "disabled");
1350 assert.equal(state.message, message);
1351 assert.isFalse((yield* updates.check("menu")).checked);
1352 assert.deepEqual(yield* updates.disabledReason, Option.some(message));
1353 assert.equal(harness.checkCount(), 0);
1354 assert.equal(harness.listenerCount(), 0);
1355 }),
1356 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1357 });
1358​
1359 it.effect("updates from the administrator's feed", () => {
1360 const harness = makeHarness({
1361 // Any user can set the mock flag; it must not redirect a managed feed.
1362 env: { T3CODE_DESKTOP_MOCK_UPDATES: "true" },
1363 policy: managed({ feedUrl: "https://updates.example.com/t3code" }),
1364 });
1365​
1366 return Effect.scoped(
1367 Effect.gen(function* () {
1368 const updates = yield* DesktopUpdates.DesktopUpdates;
1369 yield* updates.configure;
1370 assert.equal((yield* updates.getState).status, "idle");
1371 assert.deepEqual(harness.feedUrls(), [
1372 { provider: "generic", url: "https://updates.example.com/t3code" },
1373 ]);
1374 }),
1375 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1376 });
1377​
1378 it.effect("refuses the nightly channel without nightly", () => {
1379 const harness = makeHarness({ policy: managed({ allowNightly: false }) });
1380​
1381 return Effect.scoped(
1382 Effect.gen(function* () {
1383 const updates = yield* DesktopUpdates.DesktopUpdates;
1384 yield* updates.configure;
1385 const error = yield* updates.setChannel("nightly").pipe(Effect.flip);
1386 assert.equal(error._tag, "DesktopUpdateChannelManagedError");
1387 assert.equal((yield* updates.getState).channel, "latest");
1388 }),
1389 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1390 });
1391​
1392 it.effect("does not report the channel as the only block when updates are off anyway", () => {
1393 const harness = makeHarness({
1394 appVersion: "1.2.3-nightly.20261028.1",
1395 env: { T3CODE_DISABLE_AUTO_UPDATE: "true" },
1396 policy: managed({ allowNightly: false, feedUrl: "https://updates.example.com/t3code" }),
1397 });
1398​
1399 return Effect.scoped(
1400 Effect.gen(function* () {
1401 const updates = yield* DesktopUpdates.DesktopUpdates;
1402 yield* updates.configure;
1403 const state = yield* updates.getState;
1404 assert.isFalse(state.enabled);
1405 assert.isUndefined(state.channelBlockedByPolicy);
1406 }),
1407 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1408 });
1409​
1410 it.effect("holds a nightly install until its user switches to stable", () => {
1411 const harness = makeHarness({
1412 appVersion: "1.2.3-nightly.20261028.1",
1413 // A managed app ignores the mock feed, so give it a real one.
1414 policy: managed({ allowNightly: false, feedUrl: "https://updates.example.com/t3code" }),
1415 });
1416​
1417 return Effect.scoped(
1418 Effect.gen(function* () {
1419 const updates = yield* DesktopUpdates.DesktopUpdates;
1420 yield* updates.configure;
1421 yield* TestClock.adjust("10 minutes");
1422​
1423 const held = yield* updates.getState;
1424 assert.equal(held.channel, "nightly");
1425 assert.equal(held.status, "disabled");
1426 assert.include(held.message ?? "", message);
1427 assert.isTrue(held.channelBlockedByPolicy);
1428 assert.isTrue((yield* encodeUpdateState(held)).channelBlockedByPolicy);
1429 assert.isFalse((yield* updates.check("menu")).checked);
1430 assert.equal(harness.checkCount(), 0);
1431​
1432 const stable = yield* updates.setChannel("latest");
1433 assert.equal(stable.channel, "latest");
1434 assert.isTrue(stable.enabled);
1435 assert.isUndefined(stable.channelBlockedByPolicy);
1436 assert.equal(harness.checkCount(), 1);
1437 }),
1438 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1439 });
1440});