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

DesktopUpdates.ts

667 lines24.7 KB

1import type {
2 DesktopRuntimeInfo,
3 DesktopUpdateActionResult,
4 DesktopUpdateChannel,
5 DesktopUpdateCheckResult,
6 DesktopUpdateState,
7} from "@t3tools/contracts";
8import * as Cause from "effect/Cause";
9import * as Context from "effect/Context";
10import * as Data from "effect/Data";
11import * as DateTime from "effect/DateTime";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Ref from "effect/Ref";
18import * as Schema from "effect/Schema";
19import * as Scope from "effect/Scope";
20​
21import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
22import * as DesktopConfig from "../app/DesktopConfig.ts";
23import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
24import * as DesktopObservability from "../app/DesktopObservability.ts";
25import * as DesktopState from "../app/DesktopState.ts";
26import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
27import * as ElectronWindow from "../electron/ElectronWindow.ts";
28import * as IpcChannels from "../ipc/channels.ts";
29import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
30import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
31import {
32 createInitialDesktopUpdateState,
33 reduceDesktopUpdateStateOnCheckFailure,
34 reduceDesktopUpdateStateOnCheckStart,
35 reduceDesktopUpdateStateOnDownloadComplete,
36 reduceDesktopUpdateStateOnDownloadFailure,
37 reduceDesktopUpdateStateOnDownloadProgress,
38 reduceDesktopUpdateStateOnDownloadStart,
39 reduceDesktopUpdateStateOnInstallFailure,
40 reduceDesktopUpdateStateOnNoUpdate,
41 reduceDesktopUpdateStateOnUpdateAvailable,
42} from "./updateMachine.ts";
43​
44const AUTO_UPDATE_STARTUP_DELAY = "15 seconds";
45const AUTO_UPDATE_POLL_INTERVAL = "4 minutes";
46​
47const AppUpdateYmlConfig = Schema.Record(Schema.String, Schema.String);
48type AppUpdateYmlConfig = typeof AppUpdateYmlConfig.Type;
49​
50const UpdateInfo = Schema.Struct({
51 version: Schema.String,
52});
53​
54const DownloadProgressInfo = Schema.Struct({
55 percent: Schema.Number,
56});
57const decodeAppUpdateYmlConfig = Schema.decodeUnknownEffect(AppUpdateYmlConfig);
58const decodeUpdateInfo = Schema.decodeUnknownEffect(UpdateInfo);
59const decodeDownloadProgressInfo = Schema.decodeUnknownEffect(DownloadProgressInfo);
60​
61const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
62​
63export class DesktopUpdateActionInProgressError extends Data.TaggedError(
64 "DesktopUpdateActionInProgressError",
65)<{
66 readonly action: "check" | "download" | "install";
67}> {
68 override get message() {
69 return `Cannot change update tracks while an update ${this.action} action is in progress.`;
70 }
72​
73export class DesktopUpdatePersistenceError extends Data.TaggedError(
74 "DesktopUpdatePersistenceError",
75)<{
76 readonly cause: DesktopAppSettings.DesktopSettingsWriteError;
77}> {
78 override get message() {
79 return "Failed to persist desktop update settings.";
80 }
82​
83export type DesktopUpdateConfigureError = never;
84​
85export type DesktopUpdateSetChannelError =
86 | DesktopUpdateActionInProgressError
87 | DesktopUpdatePersistenceError;
88​
89export interface DesktopUpdatesShape {
90 readonly getState: Effect.Effect<DesktopUpdateState>;
91 readonly emitState: Effect.Effect<void>;
92 readonly disabledReason: Effect.Effect<Option.Option<string>>;
93 readonly configure: Effect.Effect<void, DesktopUpdateConfigureError, Scope.Scope>;
94 readonly setChannel: (
95 channel: DesktopUpdateChannel,
96 ) => Effect.Effect<DesktopUpdateState, DesktopUpdateSetChannelError>;
97 readonly check: (reason: string) => Effect.Effect<DesktopUpdateCheckResult>;
98 readonly download: Effect.Effect<DesktopUpdateActionResult>;
99 readonly install: Effect.Effect<DesktopUpdateActionResult>;
101​
102export class DesktopUpdates extends Context.Service<DesktopUpdates, DesktopUpdatesShape>()(
103 "t3/desktop/Updates",
104) {}
105​
106const {
107 logInfo: logUpdaterInfo,
108 logWarning: logUpdaterWarning,
109 logError: logUpdaterError,
110} = DesktopObservability.makeComponentLogger("desktop-updater");
111​
112function parseAppUpdateYml(raw: string): Effect.Effect<Option.Option<AppUpdateYmlConfig>> {
113 const entries: Record<string, string> = {};
114 for (const line of raw.split("\n")) {
115 const match = line.match(/^(\w+):\s*(.+)$/);
116 if (match?.[1] && match[2]) {
117 entries[match[1]] = match[2].trim();
118 }
119 }
120​
121 return decodeAppUpdateYmlConfig(entries).pipe(
122 Effect.map((config) => (config.provider ? Option.some(config) : Option.none())),
123 Effect.catch(() => Effect.succeed(Option.none<AppUpdateYmlConfig>())),
124 );
126​
127function createBaseUpdateState(
128 channel: DesktopUpdateChannel,
129 enabled: boolean,
130 environment: DesktopEnvironment.DesktopEnvironmentShape,
131): DesktopUpdateState {
132 return {
133 ...createInitialDesktopUpdateState(environment.appVersion, environment.runtimeInfo, channel),
134 enabled,
135 status: enabled ? "idle" : "disabled",
136 };
138​
139function getCanRetryFromState(state: DesktopUpdateState): boolean {
140 return state.availableVersion !== null || state.downloadedVersion !== null;
142​
143function shouldBroadcastDownloadProgress(
144 currentState: DesktopUpdateState,
145 nextPercent: number,
146): boolean {
147 if (currentState.status !== "downloading") {
148 return true;
149 }
150​
151 const currentPercent = currentState.downloadPercent;
152 if (currentPercent === null) {
153 return true;
154 }
155​
156 const previousStep = Math.floor(currentPercent / 10);
157 const nextStep = Math.floor(nextPercent / 10);
158 return nextStep !== previousStep || nextPercent === 100;
160​
161function getAutoUpdateDisabledReason(args: {
162 isDevelopment: boolean;
163 isPackaged: boolean;
164 platform: NodeJS.Platform;
165 appImage?: string | undefined;
166 disabledByEnv: boolean;
167 hasUpdateFeedConfig: boolean;
168}): string | null {
169 if (!args.hasUpdateFeedConfig) {
170 return "Automatic updates are not available because no update feed is configured.";
171 }
172 if (args.isDevelopment || !args.isPackaged) {
173 return "Automatic updates are only available in packaged production builds.";
174 }
175 if (args.disabledByEnv) {
176 return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
177 }
178 if (args.platform === "linux" && !args.appImage) {
179 return "Automatic updates on Linux require running the AppImage build.";
180 }
181 return null;
183​
184function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean {
185 return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
187​
188const make = Effect.gen(function* () {
189 const config = yield* DesktopConfig.DesktopConfig;
190 const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
191 const desktopState = yield* DesktopState.DesktopState;
192 const electronUpdater = yield* ElectronUpdater.ElectronUpdater;
193 const electronWindow = yield* ElectronWindow.ElectronWindow;
194 const environment = yield* DesktopEnvironment.DesktopEnvironment;
195 const fileSystem = yield* FileSystem.FileSystem;
196 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
197​
198 const appUpdateYmlConfigRef = yield* Ref.make<Option.Option<AppUpdateYmlConfig>>(Option.none());
199 const updateCheckInFlightRef = yield* Ref.make(false);
200 const updateDownloadInFlightRef = yield* Ref.make(false);
201 const updateInstallInFlightRef = yield* Ref.make(false);
202 const updaterConfiguredRef = yield* Ref.make(false);
203 const lastLoggedDownloadMilestoneRef = yield* Ref.make(-1);
204 const updateStateRef = yield* Ref.make<DesktopUpdateState>(
205 createInitialDesktopUpdateState(
206 environment.appVersion,
207 environment.runtimeInfo,
208 environment.defaultDesktopSettings.updateChannel,
209 ),
210 );
211​
212 const emitState = Ref.get(updateStateRef).pipe(
213 Effect.flatMap((state) => electronWindow.sendAll(IpcChannels.UPDATE_STATE_CHANNEL, state)),
214 );
215​
216 const setState = (state: DesktopUpdateState): Effect.Effect<void> =>
217 Ref.set(updateStateRef, state).pipe(Effect.andThen(emitState));
218​
219 const updateState = (
220 f: (state: DesktopUpdateState) => DesktopUpdateState,
221 ): Effect.Effect<DesktopUpdateState> =>
222 Ref.get(updateStateRef).pipe(
223 Effect.flatMap((state) => {
224 const nextState = f(state);
225 return setState(nextState).pipe(Effect.as(nextState));
226 }),
227 );
228​
229 const readAppUpdateYml = fileSystem.readFileString(environment.appUpdateYmlPath, "utf-8").pipe(
230 Effect.option,
231 Effect.flatMap(
232 Option.match({
233 onNone: () => Effect.succeed(Option.none<AppUpdateYmlConfig>()),
234 onSome: parseAppUpdateYml,
235 }),
236 ),
237 );
238​
239 const hasUpdateFeedConfig = Ref.get(appUpdateYmlConfigRef).pipe(
240 Effect.map((appUpdateYmlConfig) => Option.isSome(appUpdateYmlConfig) || config.mockUpdates),
241 );
242​
243 const resolveDisabledReason = Effect.gen(function* () {
244 const hasFeedConfig = yield* hasUpdateFeedConfig;
245 return Option.fromNullishOr(
246 getAutoUpdateDisabledReason({
247 isDevelopment: environment.isDevelopment,
248 isPackaged: environment.isPackaged,
249 platform: environment.platform,
250 appImage: Option.getOrUndefined(config.appImagePath),
251 disabledByEnv: config.disableAutoUpdate,
252 hasUpdateFeedConfig: hasFeedConfig,
253 }),
254 );
255 });
256​
257 const resolveUpdaterErrorContext = Effect.gen(function* () {
258 if (yield* Ref.get(updateInstallInFlightRef)) return "install" as const;
259 if (yield* Ref.get(updateDownloadInFlightRef)) return "download" as const;
260 if (yield* Ref.get(updateCheckInFlightRef)) return "check" as const;
261 return (yield* Ref.get(updateStateRef)).errorContext;
262 });
263​
264 const activeUpdateAction = Effect.gen(function* () {
265 if (yield* Ref.get(updateInstallInFlightRef)) return Option.some("install" as const);
266 if (yield* Ref.get(updateDownloadInFlightRef)) return Option.some("download" as const);
267 if (yield* Ref.get(updateCheckInFlightRef)) return Option.some("check" as const);
268 return Option.none<"check" | "download" | "install">();
269 });
270​
271 const applyAutoUpdaterChannel = Effect.fn("desktop.updates.applyAutoUpdaterChannel")(function* (
272 channel: DesktopUpdateChannel,
273 ) {
274 yield* Effect.annotateCurrentSpan({ channel });
275 const allowsPrerelease = channel === "nightly";
276 yield* electronUpdater.setChannel(channel);
277 yield* electronUpdater.setAllowPrerelease(allowsPrerelease);
278 yield* electronUpdater.setAllowDowngrade(allowsPrerelease);
279 yield* logUpdaterInfo("using update channel", {
280 channel,
281 allowPrerelease: allowsPrerelease,
282 allowDowngrade: allowsPrerelease,
283 });
284 });
285​
286 const shouldEnableAutoUpdates = resolveDisabledReason.pipe(Effect.map(Option.isNone));
287​
288 const checkForUpdates = Effect.fn("desktop.updates.checkForUpdates")(function* (reason: string) {
289 yield* Effect.annotateCurrentSpan({ reason });
290 if (yield* Ref.get(desktopState.quitting)) return false;
291 if (!(yield* Ref.get(updaterConfiguredRef))) return false;
292 if (yield* Ref.get(updateCheckInFlightRef)) return false;
293​
294 const state = yield* Ref.get(updateStateRef);
295 if (state.status === "downloading" || state.status === "downloaded") {
296 yield* logUpdaterInfo("skipping update check while update is active", {
297 reason,
298 status: state.status,
299 });
300 return false;
301 }
302​
303 yield* Ref.set(updateCheckInFlightRef, true);
304 const checkedAt = yield* currentIsoTimestamp;
305 yield* setState(reduceDesktopUpdateStateOnCheckStart(state, checkedAt));
306 yield* logUpdaterInfo("checking for updates", { reason });
307​
308 return yield* electronUpdater.checkForUpdates.pipe(
309 Effect.as(true),
310 Effect.catch(
311 Effect.fn("desktop.updates.handleCheckForUpdatesFailure")(function* (error) {
312 const failedAt = yield* currentIsoTimestamp;
313 yield* updateState((current) =>
314 reduceDesktopUpdateStateOnCheckFailure(current, error.message, failedAt),
315 );
316 yield* logUpdaterError("failed to check for updates", { message: error.message });
317 return true;
318 }),
319 ),
320 Effect.ensuring(Ref.set(updateCheckInFlightRef, false)),
321 );
322 });
323​
324 const downloadAvailableUpdate = Effect.gen(function* () {
325 const state = yield* Ref.get(updateStateRef);
326 if (
327 !(yield* Ref.get(updaterConfiguredRef)) ||
328 (yield* Ref.get(updateDownloadInFlightRef)) ||
329 state.status !== "available"
330 ) {
331 return { accepted: false, completed: false };
332 }
333​
334 yield* Ref.set(updateDownloadInFlightRef, true);
335 return yield* Effect.gen(function* () {
336 yield* setState(reduceDesktopUpdateStateOnDownloadStart(state));
337 yield* electronUpdater.setDisableDifferentialDownload(
338 isArm64HostRunningIntelBuild(environment.runtimeInfo),
339 );
340 yield* logUpdaterInfo("downloading update");
341 yield* electronUpdater.downloadUpdate;
342 return { accepted: true, completed: true };
343 }).pipe(
344 Effect.catch(
345 Effect.fn("desktop.updates.handleDownloadFailure")(function* (error) {
346 yield* updateState((current) =>
347 reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
348 );
349 yield* logUpdaterError("failed to download update", { message: error.message });
350 return { accepted: true, completed: false };
351 }),
352 ),
353 Effect.ensuring(Ref.set(updateDownloadInFlightRef, false)),
354 );
355 }).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate"));
356​
357 const installDownloadedUpdate = Effect.gen(function* () {
358 const state = yield* Ref.get(updateStateRef);
359 if (
360 (yield* Ref.get(desktopState.quitting)) ||
361 !(yield* Ref.get(updaterConfiguredRef)) ||
362 state.status !== "downloaded"
363 ) {
364 return { accepted: false, completed: false };
365 }
366​
367 yield* Ref.set(desktopState.quitting, true);
368 yield* Ref.set(updateInstallInFlightRef, true);
369​
370 return yield* Effect.gen(function* () {
371 yield* backendManager.stop({ timeout: Duration.seconds(5) });
372 yield* electronWindow.destroyAll;
373 yield* electronUpdater.quitAndInstall({
374 isSilent: true,
375 isForceRunAfter: true,
376 });
377 return { accepted: true, completed: false };
378 }).pipe(
379 Effect.catch(
380 Effect.fn("desktop.updates.handleInstallFailure")(function* (error) {
381 yield* Ref.set(updateInstallInFlightRef, false);
382 yield* updateState((current) =>
383 reduceDesktopUpdateStateOnInstallFailure(current, error.message),
384 );
385 yield* Ref.set(desktopState.quitting, false);
386 yield* logUpdaterError("failed to install update", { message: error.message });
387 return { accepted: true, completed: false };
388 }),
389 ),
390 );
391 }).pipe(Effect.withSpan("desktop.updates.installDownloadedUpdate"));
392​
393 const startUpdatePollers: Effect.Effect<void, never, Scope.Scope> = Effect.gen(function* () {
394 yield* Effect.sleep(AUTO_UPDATE_STARTUP_DELAY).pipe(
395 Effect.andThen(checkForUpdates("startup")),
396 Effect.catchCause((cause) =>
397 logUpdaterError("startup update check failed", { cause: Cause.pretty(cause) }),
398 ),
399 Effect.forkScoped,
400 );
401 yield* Effect.sleep(AUTO_UPDATE_POLL_INTERVAL).pipe(
402 Effect.andThen(checkForUpdates("poll")),
403 Effect.forever,
404 Effect.catchCause((cause) =>
405 logUpdaterError("poll update check failed", { cause: Cause.pretty(cause) }),
406 ),
407 Effect.forkScoped,
408 );
409 }).pipe(Effect.withSpan("desktop.updates.startPollers"));
410​
411 const handleUpdateAvailable = Effect.fn("desktop.updates.handleUpdateAvailable")(function* (
412 raw: unknown,
413 ) {
414 yield* decodeUpdateInfo(raw).pipe(
415 Effect.flatMap(
416 Effect.fn("desktop.updates.applyUpdateAvailable")(function* (info) {
417 const state = yield* Ref.get(updateStateRef);
418 if (resolveDefaultDesktopUpdateChannel(info.version) !== state.channel) {
419 yield* logUpdaterInfo("ignoring update that does not match selected channel", {
420 version: info.version,
421 channel: state.channel,
422 });
423 const checkedAt = yield* currentIsoTimestamp;
424 yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt));
425 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
426 return;
427 }
428​
429 const checkedAt = yield* currentIsoTimestamp;
430 yield* setState(
431 reduceDesktopUpdateStateOnUpdateAvailable(state, info.version, checkedAt),
432 );
433 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
434 yield* logUpdaterInfo("update available", { version: info.version });
435 }),
436 ),
437 Effect.catchCause((cause) =>
438 logUpdaterWarning("ignored malformed update-available event", {
439 cause: Cause.pretty(cause),
440 }),
441 ),
442 );
443 });
444​
445 const handleUpdateNotAvailable = Effect.gen(function* () {
446 const checkedAt = yield* currentIsoTimestamp;
447 const state = yield* Ref.get(updateStateRef);
448 yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt));
449 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
450 yield* logUpdaterInfo("no updates available");
451 }).pipe(Effect.withSpan("desktop.updates.handleUpdateNotAvailable"));
452​
453 const handleUpdaterError = Effect.fn("desktop.updates.handleUpdaterError")(function* (
454 error: unknown,
455 ) {
456 const message = error instanceof Error ? error.message : String(error);
457 if (yield* Ref.get(updateInstallInFlightRef)) {
458 yield* Ref.set(updateInstallInFlightRef, false);
459 yield* Ref.set(desktopState.quitting, false);
460 yield* updateState((current) => reduceDesktopUpdateStateOnInstallFailure(current, message));
461 yield* logUpdaterError("updater error", { message });
462 return;
463 }
464​
465 if (!(yield* Ref.get(updateCheckInFlightRef)) && !(yield* Ref.get(updateDownloadInFlightRef))) {
466 const errorContext = yield* resolveUpdaterErrorContext;
467 const checkedAt = yield* currentIsoTimestamp;
468 yield* updateState((current) => ({
469 ...current,
470 status: "error",
471 message,
472 checkedAt,
473 downloadPercent: null,
474 errorContext,
475 canRetry: getCanRetryFromState(current),
476 }));
477 }
478​
479 yield* logUpdaterError("updater error", { message });
480 });
481​
482 const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
483 raw: unknown,
484 ) {
485 yield* decodeDownloadProgressInfo(raw).pipe(
486 Effect.flatMap(
487 Effect.fn("desktop.updates.applyDownloadProgress")(function* (progress) {
488 const state = yield* Ref.get(updateStateRef);
489 const percent = Math.floor(progress.percent);
490 if (shouldBroadcastDownloadProgress(state, progress.percent) || state.message !== null) {
491 yield* setState(reduceDesktopUpdateStateOnDownloadProgress(state, progress.percent));
492 }
493 const milestone = percent - (percent % 10);
494 const lastLoggedMilestone = yield* Ref.get(lastLoggedDownloadMilestoneRef);
495 if (milestone > lastLoggedMilestone) {
496 yield* Ref.set(lastLoggedDownloadMilestoneRef, milestone);
497 yield* logUpdaterInfo("download progress", { percent });
498 }
499 }),
500 ),
501 Effect.catchCause((cause) =>
502 logUpdaterWarning("ignored malformed download-progress event", {
503 cause: Cause.pretty(cause),
504 }),
505 ),
506 );
507 });
508​
509 const handleUpdateDownloaded = Effect.fn("desktop.updates.handleUpdateDownloaded")(function* (
510 raw: unknown,
511 ) {
512 yield* decodeUpdateInfo(raw).pipe(
513 Effect.flatMap(
514 Effect.fn("desktop.updates.applyUpdateDownloaded")(function* (info) {
515 const state = yield* Ref.get(updateStateRef);
516 yield* setState(reduceDesktopUpdateStateOnDownloadComplete(state, info.version));
517 yield* logUpdaterInfo("update downloaded", { version: info.version });
518 }),
519 ),
520 Effect.catchCause((cause) =>
521 logUpdaterWarning("ignored malformed update-downloaded event", {
522 cause: Cause.pretty(cause),
523 }),
524 ),
525 );
526 });
527​
528 return DesktopUpdates.of({
529 getState: Ref.get(updateStateRef),
530 emitState,
531 disabledReason: resolveDisabledReason,
532 configure: Effect.gen(function* () {
533 const context = yield* Effect.context<never>();
534 const runEffect = (effect: Effect.Effect<void>) => {
535 void Effect.runPromiseWith(context)(effect);
536 };
537​
538 const appUpdateYmlConfig = yield* readAppUpdateYml;
539 yield* Ref.set(appUpdateYmlConfigRef, appUpdateYmlConfig);
540​
541 if (config.mockUpdates) {
542 yield* electronUpdater.setFeedURL({
543 provider: "generic",
544 url: `http://localhost:${config.mockUpdateServerPort}`,
545 } as ElectronUpdater.ElectronUpdaterFeedUrl);
546 }
547​
548 const settings = yield* desktopSettings.get;
549 const enabled = yield* shouldEnableAutoUpdates;
550 yield* setState(createBaseUpdateState(settings.updateChannel, enabled, environment));
551 if (!enabled) {
552 return;
553 }
554 yield* Ref.set(updaterConfiguredRef, true);
555​
556 yield* electronUpdater.setAutoDownload(false);
557 yield* electronUpdater.setAutoInstallOnAppQuit(false);
558 yield* applyAutoUpdaterChannel(settings.updateChannel);
559 yield* electronUpdater.setDisableDifferentialDownload(
560 isArm64HostRunningIntelBuild(environment.runtimeInfo),
561 );
562​
563 if (isArm64HostRunningIntelBuild(environment.runtimeInfo)) {
564 yield* logUpdaterInfo(
565 "Apple Silicon host detected while running Intel build; updates will switch to arm64 packages",
566 );
567 }
568​
569 yield* electronUpdater.on("checking-for-update", () => {
570 runEffect(
571 logUpdaterInfo("looking for updates").pipe(
572 Effect.withSpan("desktop.updates.handleCheckingForUpdate"),
573 ),
574 );
575 });
576 yield* electronUpdater.on("update-available", (info: unknown) => {
577 runEffect(handleUpdateAvailable(info));
578 });
579 yield* electronUpdater.on("update-not-available", () => {
580 runEffect(handleUpdateNotAvailable);
581 });
582 yield* electronUpdater.on("error", (error: unknown) => {
583 runEffect(handleUpdaterError(error));
584 });
585 yield* electronUpdater.on("download-progress", (progress: unknown) => {
586 runEffect(handleDownloadProgress(progress));
587 });
588 yield* electronUpdater.on("update-downloaded", (info: unknown) => {
589 runEffect(handleUpdateDownloaded(info));
590 });
591​
592 yield* startUpdatePollers;
593 }).pipe(Effect.withSpan("desktop.updates.configure")),
594 setChannel: Effect.fn("desktop.updates.setChannel")(function* (
595 nextChannel: DesktopUpdateChannel,
596 ) {
597 yield* Effect.annotateCurrentSpan({ channel: nextChannel });
598 const activeAction = yield* activeUpdateAction;
599 if (Option.isSome(activeAction)) {
600 return yield* new DesktopUpdateActionInProgressError({ action: activeAction.value });
601 }
602​
603 const state = yield* Ref.get(updateStateRef);
604 if (nextChannel === state.channel) {
605 return state;
606 }
607​
608 yield* desktopSettings
609 .setUpdateChannel(nextChannel)
610 .pipe(Effect.mapError((cause) => new DesktopUpdatePersistenceError({ cause })));
611​
612 const enabled = yield* shouldEnableAutoUpdates;
613 yield* setState(createBaseUpdateState(nextChannel, enabled, environment));
614​
615 if (!enabled || !(yield* Ref.get(updaterConfiguredRef))) {
616 return yield* Ref.get(updateStateRef);
617 }
618​
619 yield* applyAutoUpdaterChannel(nextChannel);
620 const allowDowngrade = yield* electronUpdater.allowDowngrade;
621 yield* electronUpdater.setAllowDowngrade(true);
622 yield* checkForUpdates("channel-change").pipe(
623 Effect.ensuring(electronUpdater.setAllowDowngrade(allowDowngrade).pipe(Effect.ignore)),
624 );
625 return yield* Ref.get(updateStateRef);
626 }),
627 check: Effect.fn("desktop.updates.check")(function* (reason: string) {
628 yield* Effect.annotateCurrentSpan({ reason });
629 if (!(yield* Ref.get(updaterConfiguredRef))) {
630 return {
631 checked: false,
632 state: yield* Ref.get(updateStateRef),
633 };
634 }
635 const checked = yield* checkForUpdates(reason);
636 return {
637 checked,
638 state: yield* Ref.get(updateStateRef),
639 };
640 }),
641 download: Effect.gen(function* () {
642 const result = yield* downloadAvailableUpdate;
643 return {
644 accepted: result.accepted,
645 completed: result.completed,
646 state: yield* Ref.get(updateStateRef),
647 };
648 }).pipe(Effect.withSpan("desktop.updates.download")),
649 install: Effect.gen(function* () {
650 if (yield* Ref.get(desktopState.quitting)) {
651 return {
652 accepted: false,
653 completed: false,
654 state: yield* Ref.get(updateStateRef),
655 };
656 }
657 const result = yield* installDownloadedUpdate;
658 return {
659 accepted: result.accepted,
660 completed: result.completed,
661 state: yield* Ref.get(updateStateRef),
662 };
663 }).pipe(Effect.withSpan("desktop.updates.install")),
664 });
665});
666​
667export const layer = Layer.effect(DesktopUpdates, make);