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