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