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

DesktopUpdates.test.ts

551 lines20.5 KB

1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import type { DesktopUpdateState } from "@t3tools/contracts";
4import * as Cause from "effect/Cause";
5import * as Deferred from "effect/Deferred";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as Layer from "effect/Layer";
10import * as Logger from "effect/Logger";
11import * as Option from "effect/Option";
12import * as References from "effect/References";
13import * as Ref from "effect/Ref";
14import * as TestClock from "effect/testing/TestClock";
15​
16import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
17import * as DesktopConfig from "../app/DesktopConfig.ts";
18import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
19import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
20import * as ElectronWindow from "../electron/ElectronWindow.ts";
21import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
22import * as DesktopState from "../app/DesktopState.ts";
23import * as DesktopUpdates from "./DesktopUpdates.ts";
24​
25interface UpdatesHarnessOptions {
26 readonly checkForUpdates?: Effect.Effect<
27 void,
28 ElectronUpdater.ElectronUpdaterCheckForUpdatesError
29 >;
30 readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
31 readonly setDisableDifferentialDownload?: Effect.Effect<void>;
32 readonly stopBackend?: Effect.Effect<void>;
33 readonly env?: Record<string, string | undefined>;
35​
36const flushCallbacks = Effect.yieldNow;
37​
38function makeHarness(options: UpdatesHarnessOptions = {}) {
39 let checkCount = 0;
40 let allowDowngrade = false;
41 const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
42 const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
43 const sentStates: DesktopUpdateState[] = [];
44​
45 const addListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
46 const eventListeners = listeners.get(eventName) ?? new Set();
47 eventListeners.add(listener);
48 listeners.set(eventName, eventListeners);
49 };
50​
51 const removeListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
52 const eventListeners = listeners.get(eventName);
53 if (!eventListeners) {
54 return;
55 }
56 eventListeners.delete(listener);
57 if (eventListeners.size === 0) {
58 listeners.delete(eventName);
59 }
60 };
61​
62 const updaterLayer = Layer.succeed(ElectronUpdater.ElectronUpdater, {
63 setFeedURL: (options) =>
64 Effect.sync(() => {
65 feedUrls.push(options);
66 }),
67 setAutoDownload: () => Effect.void,
68 setAutoInstallOnAppQuit: () => Effect.void,
69 setChannel: () => Effect.void,
70 setAllowPrerelease: () => Effect.void,
71 allowDowngrade: Effect.sync(() => allowDowngrade),
72 setAllowDowngrade: (value) =>
73 Effect.sync(() => {
74 allowDowngrade = value;
75 }),
76 setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
77 checkForUpdates: Effect.sync(() => {
78 checkCount += 1;
79 }).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
80 downloadUpdate: Effect.void,
81 quitAndInstall: () => Effect.void,
82 on: (eventName, listener) =>
83 Effect.acquireRelease(
84 Effect.sync(() => {
85 addListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
86 }),
87 () =>
88 Effect.sync(() => {
89 removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
90 }),
91 ).pipe(Effect.asVoid),
92 } satisfies ElectronUpdater.ElectronUpdater["Service"]);
93​
94 const windowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
95 create: () => Effect.die("unexpected BrowserWindow creation"),
96 main: Effect.succeed(Option.none()),
97 currentMainOrFirst: Effect.succeed(Option.none()),
98 focusedMainOrFirst: Effect.succeed(Option.none()),
99 setMain: () => Effect.void,
100 clearMain: () => Effect.void,
101 reveal: () => Effect.void,
102 sendAll: (_channel, state) =>
103 Effect.sync(() => {
104 sentStates.push(state as DesktopUpdateState);
105 }),
106 destroyAll: Effect.void,
107 syncAllAppearance: () => Effect.void,
108 } satisfies ElectronWindow.ElectronWindow["Service"]);
109​
110 const backendLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
111 start: Effect.void,
112 stop: () => options.stopBackend ?? Effect.void,
113 currentConfig: Effect.succeed(Option.none()),
114 snapshot: Effect.succeed({
115 desiredRunning: false,
116 ready: false,
117 activePid: Option.none(),
118 restartAttempt: 0,
119 restartScheduled: false,
120 }),
121 });
122​
123 const environmentLayer = DesktopEnvironment.layer({
124 dirname: "/repo/apps/desktop/src",
125 homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
126 platform: "darwin",
127 processArch: "x64",
128 appVersion: "1.2.3",
129 appPath: "/repo",
130 isPackaged: true,
131 resourcesPath: "/missing/resources",
132 runningUnderArm64Translation: false,
133 }).pipe(
134 Layer.provide(
135 Layer.mergeAll(
136 NodeServices.layer,
137 DesktopConfig.layerTest({
138 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
139 T3CODE_DESKTOP_MOCK_UPDATES: "true",
140 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
141 ...options.env,
142 }),
143 ),
144 ),
145 );
146​
147 const setUpdateChannelError = options.setUpdateChannelError;
148 const settingsLayer = setUpdateChannelError
149 ? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
150 get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
151 load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
152 setServerExposureMode: () => Effect.die("unexpected server exposure update"),
153 setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
154 setUpdateChannel: () => Effect.fail(setUpdateChannelError),
155 } satisfies DesktopAppSettings.DesktopAppSettings["Service"])
156 : DesktopAppSettings.layer;
157​
158 const layer = DesktopUpdates.layer.pipe(
159 Layer.provideMerge(updaterLayer),
160 Layer.provideMerge(windowLayer),
161 Layer.provideMerge(backendLayer),
162 Layer.provideMerge(DesktopState.layer),
163 Layer.provideMerge(settingsLayer),
164 Layer.provideMerge(
165 DesktopConfig.layerTest({
166 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
167 T3CODE_DESKTOP_MOCK_UPDATES: "true",
168 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
169 ...options.env,
170 }),
171 ),
172 Layer.provideMerge(environmentLayer),
173 Layer.provideMerge(NodeServices.layer),
174 );
175​
176 return {
177 layer,
178 checkCount: () => checkCount,
179 feedUrls: () => feedUrls,
180 listenerCount: () =>
181 Array.from(listeners.values()).reduce(
182 (total, eventListeners) => total + eventListeners.size,
183 0,
184 ),
185 sentStates,
186 emit: (eventName: string, payload?: unknown) => {
187 for (const listener of listeners.get(eventName) ?? []) {
188 listener(payload);
189 }
190 },
191 };
193​
194describe("DesktopUpdates", () => {
195 it("preserves complete causes for update poller and event failures", () => {
196 const cause = Cause.combine(
197 Cause.fail(new Error("updater failed")),
198 Cause.die(new Error("updater defect")),
199 );
200 const pollerError = new DesktopUpdates.DesktopUpdatePollerError({
201 poller: "startup",
202 cause,
203 });
204 const eventError = new DesktopUpdates.DesktopUpdateEventHandlingError({
205 event: "download-progress",
206 cause,
207 });
208 const reportedError = new DesktopUpdates.DesktopUpdaterReportedError({
209 operation: "download",
210 cause,
211 });
212 const unexpectedActionError = new DesktopUpdates.DesktopUpdateUnexpectedActionError({
213 action: "install",
214 cause,
215 });
216​
217 assert.strictEqual(pollerError.cause, cause);
218 assert.equal(pollerError.poller, "startup");
219 assert.equal(pollerError.message, "Desktop update startup poller failed.");
220 assert.strictEqual(eventError.cause, cause);
221 assert.equal(eventError.event, "download-progress");
222 assert.equal(eventError.message, "Failed to handle desktop update download-progress event.");
223 assert.strictEqual(reportedError.cause, cause);
224 assert.equal(reportedError.operation, "download");
225 assert.equal(reportedError.message, "Desktop updater download operation reported an error.");
226 assert.strictEqual(unexpectedActionError.cause, cause);
227 assert.equal(unexpectedActionError.action, "install");
228 assert.equal(
229 unexpectedActionError.message,
230 "Desktop update install action failed unexpectedly.",
231 );
232 });
233​
234 it.effect("configures the updater and runs startup checks on the test clock", () => {
235 const harness = makeHarness();
236​
237 return Effect.gen(function* () {
238 yield* Effect.scoped(
239 Effect.gen(function* () {
240 const updates = yield* DesktopUpdates.DesktopUpdates;
241 yield* updates.configure;
242​
243 const state = yield* updates.getState;
244 assert.equal(state.enabled, true);
245 assert.equal(state.status, "idle");
246 assert.deepEqual(harness.feedUrls(), [
247 { provider: "generic", url: "http://localhost:4141" },
248 ]);
249 assert.equal(harness.listenerCount(), 6);
250 assert.equal(harness.checkCount(), 0);
251​
252 yield* TestClock.adjust(Duration.millis(15_000));
253 assert.equal(harness.checkCount(), 1);
254 }),
255 );
256​
257 assert.equal(harness.listenerCount(), 0);
258 }).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
259 });
260​
261 it.effect("updates and broadcasts state from updater events", () => {
262 const harness = makeHarness();
263​
264 return Effect.scoped(
265 Effect.gen(function* () {
266 const updates = yield* DesktopUpdates.DesktopUpdates;
267 yield* updates.configure;
268​
269 harness.emit("update-available", { version: "1.2.4" });
270 yield* flushCallbacks;
271​
272 const state = yield* updates.getState;
273 assert.equal(state.status, "available");
274 assert.equal(state.availableVersion, "1.2.4");
275 assert.isNotNull(state.checkedAt);
276 assert.equal(harness.sentStates.at(-1)?.status, "available");
277 }),
278 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
279 });
280​
281 it.effect("keeps raw updater event failures out of update state", () => {
282 const harness = makeHarness();
283 const cause = new Error(
284 "request failed for https://user:secret@example.com/update?token=secret",
285 );
286​
287 return Effect.scoped(
288 Effect.gen(function* () {
289 const updates = yield* DesktopUpdates.DesktopUpdates;
290 yield* updates.configure;
291​
292 harness.emit("error", cause);
293 yield* flushCallbacks;
294​
295 const state = yield* updates.getState;
296 assert.equal(state.status, "error");
297 assert.equal(state.message, "Desktop updater background operation reported an error.");
298 assert.notInclude(state.message ?? "", "secret");
299 }),
300 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
301 });
302​
303 it.effect("logs bounded updater failure context without exposing the cause", () => {
304 const cause = new Error(
305 "request failed for https://user:secret@example.com/update?token=secret",
306 );
307 const updaterError = new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({
308 channel: null,
309 cause,
310 });
311 const harness = makeHarness({ checkForUpdates: Effect.fail(updaterError) });
312 const loggedAnnotations: Array<Record<string, unknown>> = [];
313 const logger = Logger.make(({ fiber }) => {
314 const annotations = fiber.getRef(References.CurrentLogAnnotations);
315 if (annotations.errorTag === "ElectronUpdaterCheckForUpdatesError") {
316 loggedAnnotations.push(annotations);
317 }
318 });
319​
320 return Effect.scoped(
321 Effect.gen(function* () {
322 const updates = yield* DesktopUpdates.DesktopUpdates;
323 yield* updates.configure;
324​
325 yield* updates.check("manual");
326​
327 const state = yield* updates.getState;
328 const loggedAnnotation = loggedAnnotations.at(-1);
329 assert.isDefined(loggedAnnotation);
330 assert.equal(loggedAnnotation.errorTag, "ElectronUpdaterCheckForUpdatesError");
331 assert.isNull(loggedAnnotation.channel);
332 assert.notProperty(loggedAnnotation, "error");
333 assert.notInclude(Object.values(loggedAnnotation).map(String).join(" "), "secret");
334 assert.equal(
335 state.message,
336 "Electron updater failed to check for updates on channel default.",
337 );
338 assert.notInclude(state.message ?? "", "secret");
339 }),
340 ).pipe(
341 Effect.provide(
342 Layer.mergeAll(
343 TestClock.layer(),
344 harness.layer,
345 Logger.layer([logger], { mergeWithExisting: false }),
346 ),
347 ),
348 );
349 });
350​
351 it.effect("recovers download state after an unexpected setup failure", () => {
352 let disableDifferentialCalls = 0;
353 const harness = makeHarness({
354 setDisableDifferentialDownload: Effect.suspend(() => {
355 disableDifferentialCalls += 1;
356 return disableDifferentialCalls === 1
357 ? Effect.void
358 : Effect.die(new Error("download setup failed"));
359 }),
360 });
361​
362 return Effect.scoped(
363 Effect.gen(function* () {
364 const updates = yield* DesktopUpdates.DesktopUpdates;
365 yield* updates.configure;
366 harness.emit("update-available", { version: "1.2.4" });
367 yield* flushCallbacks;
368​
369 const result = yield* updates.download;
370 assert.isTrue(result.accepted);
371 assert.isFalse(result.completed);
372​
373 const failedState = yield* updates.getState;
374 assert.equal(failedState.status, "available");
375 assert.equal(failedState.errorContext, "download");
376 assert.equal(failedState.message, "Desktop update download action failed unexpectedly.");
377​
378 const changedState = yield* updates.setChannel("nightly");
379 assert.equal(changedState.channel, "nightly");
380 }),
381 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
382 });
383​
384 it.effect("restores download state and permits retry after interruption", () =>
385 Effect.gen(function* () {
386 const actionStarted = yield* Deferred.make<void>();
387 let disableDifferentialCalls = 0;
388 const harness = makeHarness({
389 setDisableDifferentialDownload: Effect.suspend(() => {
390 disableDifferentialCalls += 1;
391 if (disableDifferentialCalls === 1) {
392 return Effect.void;
393 }
394 if (disableDifferentialCalls === 2) {
395 return Deferred.succeed(actionStarted, undefined).pipe(Effect.andThen(Effect.never));
396 }
397 return Effect.void;
398 }),
399 });
400​
401 yield* Effect.scoped(
402 Effect.gen(function* () {
403 const updates = yield* DesktopUpdates.DesktopUpdates;
404 yield* updates.configure;
405 harness.emit("update-available", { version: "1.2.4" });
406 yield* flushCallbacks;
407​
408 const downloadFiber = yield* updates.download.pipe(Effect.forkScoped);
409 yield* Deferred.await(actionStarted);
410 yield* Fiber.interrupt(downloadFiber);
411​
412 const interruptedState = yield* updates.getState;
413 assert.equal(interruptedState.status, "available");
414 assert.isNull(interruptedState.message);
415​
416 const retry = yield* updates.download;
417 assert.isTrue(retry.accepted);
418 assert.isTrue(retry.completed);
419 }),
420 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
421 }),
422 );
423​
424 it.effect("clears quitting state after an unexpected install setup failure", () => {
425 const harness = makeHarness({
426 stopBackend: Effect.die(new Error("backend stop failed")),
427 });
428​
429 return Effect.scoped(
430 Effect.gen(function* () {
431 const desktopState = yield* DesktopState.DesktopState;
432 const updates = yield* DesktopUpdates.DesktopUpdates;
433 yield* updates.configure;
434 harness.emit("update-downloaded", { version: "1.2.4" });
435 yield* flushCallbacks;
436​
437 const result = yield* updates.install;
438 assert.isTrue(result.accepted);
439 assert.isFalse(result.completed);
440 assert.isFalse(yield* Ref.get(desktopState.quitting));
441​
442 const failedState = yield* updates.getState;
443 assert.equal(failedState.status, "downloaded");
444 assert.equal(failedState.errorContext, "install");
445 assert.equal(failedState.message, "Desktop update install action failed unexpectedly.");
446​
447 const changedState = yield* updates.setChannel("nightly");
448 assert.equal(changedState.channel, "nightly");
449 }),
450 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
451 });
452​
453 it.effect("persists channel changes through the settings service", () => {
454 const harness = makeHarness();
455​
456 return Effect.scoped(
457 Effect.gen(function* () {
458 const settings = yield* DesktopAppSettings.DesktopAppSettings;
459 const updates = yield* DesktopUpdates.DesktopUpdates;
460 yield* updates.configure;
461​
462 const state = yield* updates.setChannel("nightly");
463 const persistedSettings = yield* settings.get;
464​
465 assert.equal(state.channel, "nightly");
466 assert.equal(persistedSettings.updateChannel, "nightly");
467 assert.equal(persistedSettings.updateChannelConfiguredByUser, true);
468 }),
469 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
470 });
471​
472 it.effect("does not persist an unchanged update channel as a user preference", () => {
473 const harness = makeHarness();
474​
475 return Effect.scoped(
476 Effect.gen(function* () {
477 const settings = yield* DesktopAppSettings.DesktopAppSettings;
478 const updates = yield* DesktopUpdates.DesktopUpdates;
479 yield* updates.configure;
480​
481 const state = yield* updates.setChannel("latest");
482 const persistedSettings = yield* settings.get;
483​
484 assert.equal(state.channel, "latest");
485 assert.equal(persistedSettings.updateChannel, "latest");
486 assert.equal(persistedSettings.updateChannelConfiguredByUser, false);
487 }),
488 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
489 });
490​
491 it.effect("fails channel changes with a typed error while a check is in progress", () =>
492 Effect.gen(function* () {
493 const checkStarted = yield* Deferred.make<void>();
494 const releaseCheck = yield* Deferred.make<void>();
495 const harness = makeHarness({
496 checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe(
497 Effect.andThen(Deferred.await(releaseCheck)),
498 ),
499 });
500​
501 yield* Effect.scoped(
502 Effect.gen(function* () {
503 const updates = yield* DesktopUpdates.DesktopUpdates;
504 yield* updates.configure;
505​
506 const checkFiber = yield* updates.check("manual").pipe(Effect.forkScoped);
507 yield* Deferred.await(checkStarted);
508​
509 const exit = yield* Effect.exit(updates.setChannel("nightly"));
510 assert.equal(exit._tag, "Failure");
511 if (exit._tag === "Failure") {
512 const error = Cause.squash(exit.cause);
513 assert.instanceOf(error, DesktopUpdates.DesktopUpdateActionInProgressError);
514 assert.equal(error.action, "check");
515 assert.equal(error.requestedChannel, "nightly");
516 }
517​
518 yield* Deferred.succeed(releaseCheck, undefined);
519 yield* Fiber.join(checkFiber);
520 }),
521 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
522 }),
523 );
524​
525 it.effect("preserves settings failure context when an update channel cannot be persisted", () => {
526 const diskFailure = new Error("disk exploded");
527 const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
528 operation: "replace-settings-file",
529 path: "/tmp/settings.json",
530 cause: diskFailure,
531 });
532 const harness = makeHarness({ setUpdateChannelError: settingsFailure });
533​
534 return Effect.scoped(
535 Effect.gen(function* () {
536 const updates = yield* DesktopUpdates.DesktopUpdates;
537 yield* updates.configure;
538​
539 const error = yield* updates.setChannel("nightly").pipe(Effect.flip);
540​
541 assert.instanceOf(error, DesktopUpdates.DesktopUpdateChannelPersistenceError);
542 assert.isTrue(DesktopUpdates.isDesktopUpdateSetChannelError(error));
543 assert.equal(error.channel, "nightly");
544 assert.strictEqual(error.cause, settingsFailure);
545 assert.strictEqual(error.cause.cause, diskFailure);
546 assert.equal(error.message, "Failed to persist the nightly desktop update channel.");
547 assert.notInclude(error.message, diskFailure.message);
548 }),
549 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
550 });
551});