@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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