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