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