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

DesktopUpdates.test.ts

560 lines21.1 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 DesktopBackendPool from "../backend/DesktopBackendPool.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 stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
111 id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
112 label: Effect.succeed("Windows"),
113 start: Effect.void,
114 stop: () => options.stopBackend ?? Effect.void,
115 currentConfig: Effect.succeed(Option.none()),
116 snapshot: Effect.succeed({
117 desiredRunning: false,
118 ready: false,
119 activePid: Option.none(),
120 restartAttempt: 0,
121 restartScheduled: false,
122 }),
123 waitForReady: () => Effect.succeed(true),
124 };
125 const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
126​
127 const environmentLayer = DesktopEnvironment.layer({
128 dirname: "/repo/apps/desktop/src",
129 homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
130 platform: "darwin",
131 processArch: "x64",
132 appVersion: "1.2.3",
133 appPath: "/repo",
134 isPackaged: true,
135 resourcesPath: "/missing/resources",
136 runningUnderArm64Translation: false,
137 }).pipe(
138 Layer.provide(
139 Layer.mergeAll(
140 NodeServices.layer,
141 DesktopConfig.layerTest({
142 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
143 T3CODE_DESKTOP_MOCK_UPDATES: "true",
144 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
145 ...options.env,
146 }),
147 ),
148 ),
149 );
150​
151 const setUpdateChannelError = options.setUpdateChannelError;
152 const settingsLayer = setUpdateChannelError
153 ? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
154 get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
155 load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
156 setServerExposureMode: () => Effect.die("unexpected server exposure update"),
157 setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
158 setUpdateChannel: () => Effect.fail(setUpdateChannelError),
159 setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
160 setWslDistro: () => Effect.die("unexpected WSL distro change"),
161 setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
162 applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
163 applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
164 } satisfies DesktopAppSettings.DesktopAppSettings["Service"])
165 : DesktopAppSettings.layer;
166​
167 const layer = DesktopUpdates.layer.pipe(
168 Layer.provideMerge(updaterLayer),
169 Layer.provideMerge(windowLayer),
170 Layer.provideMerge(backendLayer),
171 Layer.provideMerge(DesktopState.layer),
172 Layer.provideMerge(settingsLayer),
173 Layer.provideMerge(
174 DesktopConfig.layerTest({
175 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
176 T3CODE_DESKTOP_MOCK_UPDATES: "true",
177 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
178 ...options.env,
179 }),
180 ),
181 Layer.provideMerge(environmentLayer),
182 Layer.provideMerge(NodeServices.layer),
183 );
184​
185 return {
186 layer,
187 checkCount: () => checkCount,
188 feedUrls: () => feedUrls,
189 listenerCount: () =>
190 Array.from(listeners.values()).reduce(
191 (total, eventListeners) => total + eventListeners.size,
192 0,
193 ),
194 sentStates,
195 emit: (eventName: string, payload?: unknown) => {
196 for (const listener of listeners.get(eventName) ?? []) {
197 listener(payload);
198 }
199 },
200 };
202​
203describe("DesktopUpdates", () => {
204 it("preserves complete causes for update poller and event failures", () => {
205 const cause = Cause.combine(
206 Cause.fail(new Error("updater failed")),
207 Cause.die(new Error("updater defect")),
208 );
209 const pollerError = new DesktopUpdates.DesktopUpdatePollerError({
210 poller: "startup",
211 cause,
212 });
213 const eventError = new DesktopUpdates.DesktopUpdateEventHandlingError({
214 event: "download-progress",
215 cause,
216 });
217 const reportedError = new DesktopUpdates.DesktopUpdaterReportedError({
218 operation: "download",
219 cause,
220 });
221 const unexpectedActionError = new DesktopUpdates.DesktopUpdateUnexpectedActionError({
222 action: "install",
223 cause,
224 });
225​
226 assert.strictEqual(pollerError.cause, cause);
227 assert.equal(pollerError.poller, "startup");
228 assert.equal(pollerError.message, "Desktop update startup poller failed.");
229 assert.strictEqual(eventError.cause, cause);
230 assert.equal(eventError.event, "download-progress");
231 assert.equal(eventError.message, "Failed to handle desktop update download-progress event.");
232 assert.strictEqual(reportedError.cause, cause);
233 assert.equal(reportedError.operation, "download");
234 assert.equal(reportedError.message, "Desktop updater download operation reported an error.");
235 assert.strictEqual(unexpectedActionError.cause, cause);
236 assert.equal(unexpectedActionError.action, "install");
237 assert.equal(
238 unexpectedActionError.message,
239 "Desktop update install action failed unexpectedly.",
240 );
241 });
242​
243 it.effect("configures the updater and runs startup checks on the test clock", () => {
244 const harness = makeHarness();
245​
246 return Effect.gen(function* () {
247 yield* Effect.scoped(
248 Effect.gen(function* () {
249 const updates = yield* DesktopUpdates.DesktopUpdates;
250 yield* updates.configure;
251​
252 const state = yield* updates.getState;
253 assert.equal(state.enabled, true);
254 assert.equal(state.status, "idle");
255 assert.deepEqual(harness.feedUrls(), [
256 { provider: "generic", url: "http://localhost:4141" },
257 ]);
258 assert.equal(harness.listenerCount(), 6);
259 assert.equal(harness.checkCount(), 0);
260​
261 yield* TestClock.adjust(Duration.millis(15_000));
262 assert.equal(harness.checkCount(), 1);
263 }),
264 );
265​
266 assert.equal(harness.listenerCount(), 0);
267 }).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
268 });
269​
270 it.effect("updates and broadcasts state from updater events", () => {
271 const harness = makeHarness();
272​
273 return Effect.scoped(
274 Effect.gen(function* () {
275 const updates = yield* DesktopUpdates.DesktopUpdates;
276 yield* updates.configure;
277​
278 harness.emit("update-available", { version: "1.2.4" });
279 yield* flushCallbacks;
280​
281 const state = yield* updates.getState;
282 assert.equal(state.status, "available");
283 assert.equal(state.availableVersion, "1.2.4");
284 assert.isNotNull(state.checkedAt);
285 assert.equal(harness.sentStates.at(-1)?.status, "available");
286 }),
287 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
288 });
289​
290 it.effect("keeps raw updater event failures out of update state", () => {
291 const harness = makeHarness();
292 const cause = new Error(
293 "request failed for https://user:secret@example.com/update?token=secret",
294 );
295​
296 return Effect.scoped(
297 Effect.gen(function* () {
298 const updates = yield* DesktopUpdates.DesktopUpdates;
299 yield* updates.configure;
300​
301 harness.emit("error", cause);
302 yield* flushCallbacks;
303​
304 const state = yield* updates.getState;
305 assert.equal(state.status, "error");
306 assert.equal(state.message, "Desktop updater background operation reported an error.");
307 assert.notInclude(state.message ?? "", "secret");
308 }),
309 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
310 });
311​
312 it.effect("logs bounded updater failure context without exposing the cause", () => {
313 const cause = new Error(
314 "request failed for https://user:secret@example.com/update?token=secret",
315 );
316 const updaterError = new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({
317 channel: null,
318 cause,
319 });
320 const harness = makeHarness({ checkForUpdates: Effect.fail(updaterError) });
321 const loggedAnnotations: Array<Record<string, unknown>> = [];
322 const logger = Logger.make(({ fiber }) => {
323 const annotations = fiber.getRef(References.CurrentLogAnnotations);
324 if (annotations.errorTag === "ElectronUpdaterCheckForUpdatesError") {
325 loggedAnnotations.push(annotations);
326 }
327 });
328​
329 return Effect.scoped(
330 Effect.gen(function* () {
331 const updates = yield* DesktopUpdates.DesktopUpdates;
332 yield* updates.configure;
333​
334 yield* updates.check("manual");
335​
336 const state = yield* updates.getState;
337 const loggedAnnotation = loggedAnnotations.at(-1);
338 assert.isDefined(loggedAnnotation);
339 assert.equal(loggedAnnotation.errorTag, "ElectronUpdaterCheckForUpdatesError");
340 assert.isNull(loggedAnnotation.channel);
341 assert.notProperty(loggedAnnotation, "error");
342 assert.notInclude(Object.values(loggedAnnotation).map(String).join(" "), "secret");
343 assert.equal(
344 state.message,
345 "Electron updater failed to check for updates on channel default.",
346 );
347 assert.notInclude(state.message ?? "", "secret");
348 }),
349 ).pipe(
350 Effect.provide(
351 Layer.mergeAll(
352 TestClock.layer(),
353 harness.layer,
354 Logger.layer([logger], { mergeWithExisting: false }),
355 ),
356 ),
357 );
358 });
359​
360 it.effect("recovers download state after an unexpected setup failure", () => {
361 let disableDifferentialCalls = 0;
362 const harness = makeHarness({
363 setDisableDifferentialDownload: Effect.suspend(() => {
364 disableDifferentialCalls += 1;
365 return disableDifferentialCalls === 1
366 ? Effect.void
367 : Effect.die(new Error("download setup failed"));
368 }),
369 });
370​
371 return Effect.scoped(
372 Effect.gen(function* () {
373 const updates = yield* DesktopUpdates.DesktopUpdates;
374 yield* updates.configure;
375 harness.emit("update-available", { version: "1.2.4" });
376 yield* flushCallbacks;
377​
378 const result = yield* updates.download;
379 assert.isTrue(result.accepted);
380 assert.isFalse(result.completed);
381​
382 const failedState = yield* updates.getState;
383 assert.equal(failedState.status, "available");
384 assert.equal(failedState.errorContext, "download");
385 assert.equal(failedState.message, "Desktop update download 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("restores download state and permits retry after interruption", () =>
394 Effect.gen(function* () {
395 const actionStarted = yield* Deferred.make<void>();
396 let disableDifferentialCalls = 0;
397 const harness = makeHarness({
398 setDisableDifferentialDownload: Effect.suspend(() => {
399 disableDifferentialCalls += 1;
400 if (disableDifferentialCalls === 1) {
401 return Effect.void;
402 }
403 if (disableDifferentialCalls === 2) {
404 return Deferred.succeed(actionStarted, undefined).pipe(Effect.andThen(Effect.never));
405 }
406 return Effect.void;
407 }),
408 });
409​
410 yield* Effect.scoped(
411 Effect.gen(function* () {
412 const updates = yield* DesktopUpdates.DesktopUpdates;
413 yield* updates.configure;
414 harness.emit("update-available", { version: "1.2.4" });
415 yield* flushCallbacks;
416​
417 const downloadFiber = yield* updates.download.pipe(Effect.forkScoped);
418 yield* Deferred.await(actionStarted);
419 yield* Fiber.interrupt(downloadFiber);
420​
421 const interruptedState = yield* updates.getState;
422 assert.equal(interruptedState.status, "available");
423 assert.isNull(interruptedState.message);
424​
425 const retry = yield* updates.download;
426 assert.isTrue(retry.accepted);
427 assert.isTrue(retry.completed);
428 }),
429 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
430 }),
431 );
432​
433 it.effect("clears quitting state after an unexpected install setup failure", () => {
434 const harness = makeHarness({
435 stopBackend: Effect.die(new Error("backend stop failed")),
436 });
437​
438 return Effect.scoped(
439 Effect.gen(function* () {
440 const desktopState = yield* DesktopState.DesktopState;
441 const updates = yield* DesktopUpdates.DesktopUpdates;
442 yield* updates.configure;
443 harness.emit("update-downloaded", { version: "1.2.4" });
444 yield* flushCallbacks;
445​
446 const result = yield* updates.install;
447 assert.isTrue(result.accepted);
448 assert.isFalse(result.completed);
449 assert.isFalse(yield* Ref.get(desktopState.quitting));
450​
451 const failedState = yield* updates.getState;
452 assert.equal(failedState.status, "downloaded");
453 assert.equal(failedState.errorContext, "install");
454 assert.equal(failedState.message, "Desktop update install action failed unexpectedly.");
455​
456 const changedState = yield* updates.setChannel("nightly");
457 assert.equal(changedState.channel, "nightly");
458 }),
459 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
460 });
461​
462 it.effect("persists channel changes through the settings service", () => {
463 const harness = makeHarness();
464​
465 return Effect.scoped(
466 Effect.gen(function* () {
467 const settings = yield* DesktopAppSettings.DesktopAppSettings;
468 const updates = yield* DesktopUpdates.DesktopUpdates;
469 yield* updates.configure;
470​
471 const state = yield* updates.setChannel("nightly");
472 const persistedSettings = yield* settings.get;
473​
474 assert.equal(state.channel, "nightly");
475 assert.equal(persistedSettings.updateChannel, "nightly");
476 assert.equal(persistedSettings.updateChannelConfiguredByUser, true);
477 }),
478 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
479 });
480​
481 it.effect("does not persist an unchanged update channel as a user preference", () => {
482 const harness = makeHarness();
483​
484 return Effect.scoped(
485 Effect.gen(function* () {
486 const settings = yield* DesktopAppSettings.DesktopAppSettings;
487 const updates = yield* DesktopUpdates.DesktopUpdates;
488 yield* updates.configure;
489​
490 const state = yield* updates.setChannel("latest");
491 const persistedSettings = yield* settings.get;
492​
493 assert.equal(state.channel, "latest");
494 assert.equal(persistedSettings.updateChannel, "latest");
495 assert.equal(persistedSettings.updateChannelConfiguredByUser, false);
496 }),
497 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
498 });
499​
500 it.effect("fails channel changes with a typed error while a check is in progress", () =>
501 Effect.gen(function* () {
502 const checkStarted = yield* Deferred.make<void>();
503 const releaseCheck = yield* Deferred.make<void>();
504 const harness = makeHarness({
505 checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe(
506 Effect.andThen(Deferred.await(releaseCheck)),
507 ),
508 });
509​
510 yield* Effect.scoped(
511 Effect.gen(function* () {
512 const updates = yield* DesktopUpdates.DesktopUpdates;
513 yield* updates.configure;
514​
515 const checkFiber = yield* updates.check("manual").pipe(Effect.forkScoped);
516 yield* Deferred.await(checkStarted);
517​
518 const exit = yield* Effect.exit(updates.setChannel("nightly"));
519 assert.equal(exit._tag, "Failure");
520 if (exit._tag === "Failure") {
521 const error = Cause.squash(exit.cause);
522 assert.instanceOf(error, DesktopUpdates.DesktopUpdateActionInProgressError);
523 assert.equal(error.action, "check");
524 assert.equal(error.requestedChannel, "nightly");
525 }
526​
527 yield* Deferred.succeed(releaseCheck, undefined);
528 yield* Fiber.join(checkFiber);
529 }),
530 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
531 }),
532 );
533​
534 it.effect("preserves settings failure context when an update channel cannot be persisted", () => {
535 const diskFailure = new Error("disk exploded");
536 const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
537 operation: "replace-settings-file",
538 path: "/tmp/settings.json",
539 cause: diskFailure,
540 });
541 const harness = makeHarness({ setUpdateChannelError: settingsFailure });
542​
543 return Effect.scoped(
544 Effect.gen(function* () {
545 const updates = yield* DesktopUpdates.DesktopUpdates;
546 yield* updates.configure;
547​
548 const error = yield* updates.setChannel("nightly").pipe(Effect.flip);
549​
550 assert.instanceOf(error, DesktopUpdates.DesktopUpdateChannelPersistenceError);
551 assert.isTrue(DesktopUpdates.isDesktopUpdateSetChannelError(error));
552 assert.equal(error.channel, "nightly");
553 assert.strictEqual(error.cause, settingsFailure);
554 assert.strictEqual(error.cause.cause, diskFailure);
555 assert.equal(error.message, "Failed to persist the nightly desktop update channel.");
556 assert.notInclude(error.message, diskFailure.message);
557 }),
558 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
559 });
560});