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

DesktopUpdates.ts

872 lines31.6 KB

1import {
2 DesktopUpdateChannelSchema,
3 type DesktopRuntimeInfo,
4 type DesktopUpdateActionResult,
5 type DesktopUpdateChannel,
6 type DesktopUpdateCheckResult,
7 type DesktopUpdateState,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Context from "effect/Context";
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 DesktopBackendPool from "../backend/DesktopBackendPool.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 { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
31import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
32import {
33 createInitialDesktopUpdateState,
34 reduceDesktopUpdateStateOnCheckFailure,
35 reduceDesktopUpdateStateOnCheckStart,
36 reduceDesktopUpdateStateOnDownloadComplete,
37 reduceDesktopUpdateStateOnDownloadFailure,
38 reduceDesktopUpdateStateOnDownloadProgress,
39 reduceDesktopUpdateStateOnDownloadStart,
40 reduceDesktopUpdateStateOnInstallFailure,
41 reduceDesktopUpdateStateOnNoUpdate,
42 reduceDesktopUpdateStateOnUpdateAvailable,
43} from "./updateMachine.ts";
44​
45const AUTO_UPDATE_STARTUP_DELAY = "15 seconds";
46const AUTO_UPDATE_POLL_INTERVAL = "4 minutes";
47​
48type UpdateAction = "check" | "download" | "install" | "channel";
49​
50const AppUpdateYmlConfig = Schema.Record(Schema.String, Schema.String);
51type AppUpdateYmlConfig = typeof AppUpdateYmlConfig.Type;
52​
53const UpdateInfo = Schema.Struct({
54 version: Schema.String,
55 // Left unvalidated on purpose: a malformed release-notes payload must never
56 // fail the decode and block the update state transition. The shape is
57 // validated defensively in normalizeDesktopUpdateReleaseNotes.
58 releaseNotes: Schema.optional(Schema.Unknown),
59});
60​
61const DownloadProgressInfo = Schema.Struct({
62 percent: Schema.Number,
63});
64const decodeAppUpdateYmlConfig = Schema.decodeUnknownEffect(AppUpdateYmlConfig);
65const decodeUpdateInfo = Schema.decodeUnknownEffect(UpdateInfo);
66const decodeDownloadProgressInfo = Schema.decodeUnknownEffect(DownloadProgressInfo);
67​
68const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
69​
70export class DesktopUpdateActionInProgressError extends Schema.TaggedErrorClass<DesktopUpdateActionInProgressError>()(
71 "DesktopUpdateActionInProgressError",
72 {
73 action: Schema.Literals(["check", "download", "install", "channel"]),
74 requestedChannel: DesktopUpdateChannelSchema,
75 },
76) {
77 override get message(): string {
78 return `Cannot change the desktop update channel to ${this.requestedChannel} while an update ${this.action} action is in progress.`;
79 }
81​
82export class DesktopUpdateChannelPersistenceError extends Schema.TaggedErrorClass<DesktopUpdateChannelPersistenceError>()(
83 "DesktopUpdateChannelPersistenceError",
84 {
85 channel: DesktopUpdateChannelSchema,
86 cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
87 },
88) {
89 override get message(): string {
90 return `Failed to persist the ${this.channel} desktop update channel.`;
91 }
93​
94export class DesktopUpdatePollerError extends Schema.TaggedErrorClass<DesktopUpdatePollerError>()(
95 "DesktopUpdatePollerError",
96 {
97 poller: Schema.Literals(["startup", "poll"]),
98 cause: Schema.Defect(),
99 },
100) {
101 override get message(): string {
102 return `Desktop update ${this.poller} poller failed.`;
103 }
105​
106export class DesktopUpdateEventHandlingError extends Schema.TaggedErrorClass<DesktopUpdateEventHandlingError>()(
107 "DesktopUpdateEventHandlingError",
108 {
109 event: Schema.Literals(["update-available", "download-progress", "update-downloaded"]),
110 cause: Schema.Defect(),
111 },
112) {
113 override get message(): string {
114 return `Failed to handle desktop update ${this.event} event.`;
115 }
117​
118export class DesktopUpdaterReportedError extends Schema.TaggedErrorClass<DesktopUpdaterReportedError>()(
119 "DesktopUpdaterReportedError",
120 {
121 operation: Schema.Literals(["check", "download", "install", "channel", "background"]),
122 cause: Schema.Defect(),
123 },
124) {
125 override get message(): string {
126 return `Desktop updater ${this.operation} operation reported an error.`;
127 }
129​
130export class DesktopUpdateUnexpectedActionError extends Schema.TaggedErrorClass<DesktopUpdateUnexpectedActionError>()(
131 "DesktopUpdateUnexpectedActionError",
132 {
133 action: Schema.Literals(["download", "install"]),
134 cause: Schema.Defect(),
135 },
136) {
137 override get message(): string {
138 return `Desktop update ${this.action} action failed unexpectedly.`;
139 }
141​
142export type DesktopUpdateConfigureError = never;
143​
144export const DesktopUpdateSetChannelError = Schema.Union([
145 DesktopUpdateActionInProgressError,
146 DesktopUpdateChannelPersistenceError,
147]);
148export type DesktopUpdateSetChannelError = typeof DesktopUpdateSetChannelError.Type;
149export const isDesktopUpdateSetChannelError = Schema.is(DesktopUpdateSetChannelError);
150​
151export class DesktopUpdates extends Context.Service<
152 DesktopUpdates,
153 {
154 readonly getState: Effect.Effect<DesktopUpdateState>;
155 readonly emitState: Effect.Effect<void>;
156 readonly disabledReason: Effect.Effect<Option.Option<string>>;
157 readonly configure: Effect.Effect<void, DesktopUpdateConfigureError, Scope.Scope>;
158 readonly setChannel: (
159 channel: DesktopUpdateChannel,
160 ) => Effect.Effect<DesktopUpdateState, DesktopUpdateSetChannelError>;
161 readonly check: (reason: string) => Effect.Effect<DesktopUpdateCheckResult>;
162 readonly download: Effect.Effect<DesktopUpdateActionResult>;
163 readonly install: Effect.Effect<DesktopUpdateActionResult>;
164 }
165>()("@t3tools/desktop/updates/DesktopUpdates") {}
166​
167const {
168 logInfo: logUpdaterInfo,
169 logWarning: logUpdaterWarning,
170 logError: logUpdaterError,
171} = DesktopObservability.makeComponentLogger("desktop-updater");
172​
173function parseAppUpdateYml(raw: string): Effect.Effect<Option.Option<AppUpdateYmlConfig>> {
174 const entries: Record<string, string> = {};
175 for (const line of raw.split("\n")) {
176 const match = line.match(/^(\w+):\s*(.+)$/);
177 if (match?.[1] && match[2]) {
178 entries[match[1]] = match[2].trim();
179 }
180 }
181​
182 return decodeAppUpdateYmlConfig(entries).pipe(
183 Effect.map((config) => (config.provider ? Option.some(config) : Option.none())),
184 Effect.orElseSucceed(() => Option.none<AppUpdateYmlConfig>()),
185 );
187​
188function createBaseUpdateState(
189 channel: DesktopUpdateChannel,
190 enabled: boolean,
191 environment: DesktopEnvironment.DesktopEnvironment["Service"],
192): DesktopUpdateState {
193 return {
194 ...createInitialDesktopUpdateState(environment.appVersion, environment.runtimeInfo, channel),
195 enabled,
196 status: enabled ? "idle" : "disabled",
197 };
199​
200function getCanRetryFromState(state: DesktopUpdateState): boolean {
201 return state.availableVersion !== null || state.downloadedVersion !== null;
203​
204function shouldBroadcastDownloadProgress(
205 currentState: DesktopUpdateState,
206 nextPercent: number,
207): boolean {
208 if (currentState.status !== "downloading") {
209 return true;
210 }
211​
212 const currentPercent = currentState.downloadPercent;
213 if (currentPercent === null) {
214 return true;
215 }
216​
217 const previousStep = Math.floor(currentPercent / 10);
218 const nextStep = Math.floor(nextPercent / 10);
219 return nextStep !== previousStep || nextPercent === 100;
221​
222function getAutoUpdateDisabledReason(args: {
223 isDevelopment: boolean;
224 isPackaged: boolean;
225 platform: NodeJS.Platform;
226 appImage?: string | undefined;
227 disabledByEnv: boolean;
228 hasUpdateFeedConfig: boolean;
229}): string | null {
230 if (!args.hasUpdateFeedConfig) {
231 return "Automatic updates are not available because no update feed is configured.";
232 }
233 if (args.isDevelopment || !args.isPackaged) {
234 return "Automatic updates are only available in packaged production builds.";
235 }
236 if (args.disabledByEnv) {
237 return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
238 }
239 if (args.platform === "linux" && !args.appImage) {
240 return "Automatic updates on Linux require running the AppImage build.";
241 }
242 return null;
244​
245function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean {
246 return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
248​
249export const make = Effect.gen(function* () {
250 const config = yield* DesktopConfig.DesktopConfig;
251 const pool = yield* DesktopBackendPool.DesktopBackendPool;
252 const desktopState = yield* DesktopState.DesktopState;
253 const electronUpdater = yield* ElectronUpdater.ElectronUpdater;
254 const electronWindow = yield* ElectronWindow.ElectronWindow;
255 const environment = yield* DesktopEnvironment.DesktopEnvironment;
256 const fileSystem = yield* FileSystem.FileSystem;
257 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
258​
259 const appUpdateYmlConfigRef = yield* Ref.make<Option.Option<AppUpdateYmlConfig>>(Option.none());
260 const activeUpdateActionRef = yield* Ref.make<Option.Option<UpdateAction>>(Option.none());
261 const updaterConfiguredRef = yield* Ref.make(false);
262 const lastLoggedDownloadMilestoneRef = yield* Ref.make(-1);
263 const updateStateRef = yield* Ref.make<DesktopUpdateState>(
264 createInitialDesktopUpdateState(
265 environment.appVersion,
266 environment.runtimeInfo,
267 environment.defaultDesktopSettings.updateChannel,
268 ),
269 );
270​
271 const emitState = Ref.get(updateStateRef).pipe(
272 Effect.flatMap((state) => electronWindow.sendAll(IpcChannels.UPDATE_STATE_CHANNEL, state)),
273 );
274​
275 const setState = (state: DesktopUpdateState): Effect.Effect<void> =>
276 Ref.set(updateStateRef, state).pipe(Effect.andThen(emitState));
277​
278 const updateState = (
279 f: (state: DesktopUpdateState) => DesktopUpdateState,
280 ): Effect.Effect<DesktopUpdateState> =>
281 Ref.get(updateStateRef).pipe(
282 Effect.flatMap((state) => {
283 const nextState = f(state);
284 return setState(nextState).pipe(Effect.as(nextState));
285 }),
286 );
287​
288 const readAppUpdateYml = fileSystem.readFileString(environment.appUpdateYmlPath, "utf-8").pipe(
289 Effect.option,
290 Effect.flatMap(
291 Option.match({
292 onNone: () => Effect.succeed(Option.none<AppUpdateYmlConfig>()),
293 onSome: parseAppUpdateYml,
294 }),
295 ),
296 );
297​
298 const hasUpdateFeedConfig = Ref.get(appUpdateYmlConfigRef).pipe(
299 Effect.map((appUpdateYmlConfig) => Option.isSome(appUpdateYmlConfig) || config.mockUpdates),
300 );
301​
302 const resolveDisabledReason = Effect.gen(function* () {
303 const hasFeedConfig = yield* hasUpdateFeedConfig;
304 return Option.fromNullishOr(
305 getAutoUpdateDisabledReason({
306 isDevelopment: environment.isDevelopment,
307 isPackaged: environment.isPackaged,
308 platform: environment.platform,
309 appImage: Option.getOrUndefined(config.appImagePath),
310 disabledByEnv: config.disableAutoUpdate,
311 hasUpdateFeedConfig: hasFeedConfig,
312 }),
313 );
314 });
315​
316 const activeUpdateAction = Ref.get(activeUpdateActionRef);
317​
318 const tryStartUpdateAction = (action: UpdateAction): Effect.Effect<boolean> =>
319 Ref.modify(activeUpdateActionRef, (activeAction) =>
320 Option.isSome(activeAction) ? [false, activeAction] : [true, Option.some(action)],
321 );
322​
323 const tryStartChannelChange = Ref.modify(activeUpdateActionRef, (activeAction) =>
324 Option.isSome(activeAction)
325 ? [activeAction, activeAction]
326 : [Option.none<UpdateAction>(), Option.some<UpdateAction>("channel")],
327 );
328​
329 const finishUpdateAction = (action: UpdateAction): Effect.Effect<void> =>
330 Ref.update(activeUpdateActionRef, (activeAction) =>
331 Option.isSome(activeAction) && activeAction.value === action ? Option.none() : activeAction,
332 );
333​
334 const applyAutoUpdaterChannel = Effect.fn("desktop.updates.applyAutoUpdaterChannel")(function* (
335 channel: DesktopUpdateChannel,
336 ) {
337 yield* Effect.annotateCurrentSpan({ channel });
338 const allowsPrerelease = channel === "nightly";
339 yield* electronUpdater.setChannel(channel);
340 yield* electronUpdater.setAllowPrerelease(allowsPrerelease);
341 yield* electronUpdater.setAllowDowngrade(allowsPrerelease);
342 yield* electronUpdater.setFullChangelog(allowsPrerelease);
343 yield* logUpdaterInfo("using update channel", {
344 channel,
345 allowPrerelease: allowsPrerelease,
346 allowDowngrade: allowsPrerelease,
347 fullChangelog: allowsPrerelease,
348 });
349 });
350​
351 const shouldEnableAutoUpdates = resolveDisabledReason.pipe(Effect.map(Option.isNone));
352​
353 const checkForUpdates = Effect.fn("desktop.updates.checkForUpdates")(function* (
354 reason: string,
355 actionReservation: "acquire" | "held" = "acquire",
356 ) {
357 yield* Effect.annotateCurrentSpan({ reason });
358 if (yield* Ref.get(desktopState.quitting)) return false;
359 if (!(yield* Ref.get(updaterConfiguredRef))) return false;
360​
361 const state = yield* Ref.get(updateStateRef);
362 if (state.status === "downloading") {
363 yield* logUpdaterInfo("skipping update check while update is active", {
364 reason,
365 status: state.status,
366 });
367 return false;
368 }
369​
370 if (actionReservation === "acquire" && !(yield* tryStartUpdateAction("check"))) return false;
371​
372 const check = Effect.gen(function* () {
373 const checkedAt = yield* currentIsoTimestamp;
374 yield* setState(reduceDesktopUpdateStateOnCheckStart(state, checkedAt));
375 yield* logUpdaterInfo("checking for updates", { reason });
376​
377 return yield* electronUpdater.checkForUpdates.pipe(
378 Effect.as(true),
379 Effect.catchTags({
380 ElectronUpdaterCheckForUpdatesError: Effect.fn(
381 "desktop.updates.handleCheckForUpdatesFailure",
382 )(function* (error) {
383 const failedAt = yield* currentIsoTimestamp;
384 yield* updateState((current) =>
385 reduceDesktopUpdateStateOnCheckFailure(current, error.message, failedAt),
386 );
387 yield* logUpdaterError(error.message, {
388 errorTag: error._tag,
389 channel: error.channel,
390 });
391 return true;
392 }),
393 }),
394 );
395 });
396​
397 return yield* actionReservation === "held"
398 ? check
399 : check.pipe(Effect.ensuring(finishUpdateAction("check")));
400 });
401​
402 const downloadAvailableUpdate = Effect.gen(function* () {
403 const state = yield* Ref.get(updateStateRef);
404 if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") {
405 return { accepted: false, completed: false };
406 }
407​
408 if (!(yield* tryStartUpdateAction("download"))) {
409 return { accepted: false, completed: false };
410 }
411​
412 return yield* Effect.gen(function* () {
413 yield* setState(reduceDesktopUpdateStateOnDownloadStart(state));
414 yield* electronUpdater.setDisableDifferentialDownload(
415 isArm64HostRunningIntelBuild(environment.runtimeInfo),
416 );
417 yield* logUpdaterInfo("downloading update");
418 yield* electronUpdater.downloadUpdate;
419 return { accepted: true, completed: true };
420 }).pipe(
421 Effect.catchTags({
422 ElectronUpdaterDownloadUpdateError: Effect.fn("desktop.updates.handleDownloadFailure")(
423 function* (error) {
424 yield* updateState((current) =>
425 reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
426 );
427 yield* logUpdaterError(error.message, {
428 errorTag: error._tag,
429 channel: error.channel,
430 });
431 return { accepted: true, completed: false };
432 },
433 ),
434 }),
435 Effect.onInterrupt(() =>
436 updateState((current) => (current.status === "downloading" ? state : current)).pipe(
437 Effect.asVoid,
438 ),
439 ),
440 Effect.catchCause((cause) => {
441 if (Cause.hasInterruptsOnly(cause)) {
442 return Effect.failCause(cause);
443 }
444 const error = new DesktopUpdateUnexpectedActionError({ action: "download", cause });
445 return Effect.gen(function* () {
446 yield* updateState((current) =>
447 reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
448 );
449 yield* logUpdaterError(error.message, {
450 errorTag: error._tag,
451 action: error.action,
452 });
453 return { accepted: true, completed: false };
454 });
455 }),
456 Effect.ensuring(finishUpdateAction("download")),
457 );
458 }).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate"));
459​
460 const resetInstallAction = Effect.all(
461 [finishUpdateAction("install"), Ref.set(desktopState.quitting, false)],
462 { discard: true },
463 );
464​
465 const installDownloadedUpdate = Effect.gen(function* () {
466 const state = yield* Ref.get(updateStateRef);
467 const hasInstallableDownload =
468 state.downloadedVersion !== null &&
469 (state.status === "downloaded" ||
470 (state.status === "error" &&
471 (state.errorContext === null || state.errorContext === "install")));
472 if (
473 (yield* Ref.get(desktopState.quitting)) ||
474 !(yield* Ref.get(updaterConfiguredRef)) ||
475 !hasInstallableDownload
476 ) {
477 return { accepted: false, completed: false };
478 }
479​
480 if (!(yield* tryStartUpdateAction("install"))) {
481 return { accepted: false, completed: false };
482 }
483​
484 yield* Ref.set(desktopState.quitting, true);
485​
486 return yield* Effect.gen(function* () {
487 // Stop every backend in the pool, not just the primary. With
488 // parallel WSL + Windows backends, leaving the WSL instance up
489 // means quitAndInstall's app.quit() exits before the pool's
490 // scope cascade has a chance to run its stop finalizer, so the
491 // WSL child gets hard-killed by the OS instead of receiving
492 // SIGTERM + grace. Stops run concurrently with the same 5s
493 // budget the primary had on its own.
494 const instances = yield* pool.list;
495 yield* Effect.forEach(
496 instances,
497 (instance) => instance.stop({ timeout: Duration.seconds(5) }),
498 { concurrency: "unbounded" },
499 );
500 yield* electronWindow.destroyAll;
501 yield* electronUpdater.quitAndInstall({
502 isSilent: true,
503 isForceRunAfter: true,
504 });
505 return { accepted: true, completed: false };
506 }).pipe(
507 Effect.catchTags({
508 ElectronUpdaterQuitAndInstallError: Effect.fn("desktop.updates.handleInstallFailure")(
509 function* (error) {
510 yield* resetInstallAction;
511 yield* updateState((current) =>
512 reduceDesktopUpdateStateOnInstallFailure(current, error.message),
513 );
514 yield* logUpdaterError(error.message, {
515 errorTag: error._tag,
516 channel: error.channel,
517 isSilent: error.isSilent,
518 isForceRunAfter: error.isForceRunAfter,
519 });
520 return { accepted: true, completed: false };
521 },
522 ),
523 }),
524 Effect.onInterrupt(() => resetInstallAction),
525 Effect.catchCause((cause) =>
526 Effect.gen(function* () {
527 if (Cause.hasInterruptsOnly(cause)) {
528 return yield* Effect.failCause(cause);
529 }
530 yield* resetInstallAction;
531 const error = new DesktopUpdateUnexpectedActionError({ action: "install", cause });
532 yield* updateState((current) =>
533 reduceDesktopUpdateStateOnInstallFailure(current, error.message),
534 );
535 yield* logUpdaterError(error.message, {
536 errorTag: error._tag,
537 action: error.action,
538 });
539 return { accepted: true, completed: false };
540 }),
541 ),
542 );
543 }).pipe(Effect.withSpan("desktop.updates.installDownloadedUpdate"));
544​
545 const startUpdatePollers: Effect.Effect<void, never, Scope.Scope> = Effect.gen(function* () {
546 yield* Effect.sleep(AUTO_UPDATE_STARTUP_DELAY).pipe(
547 Effect.andThen(checkForUpdates("startup")),
548 Effect.catchCause((cause) => {
549 if (Cause.hasInterruptsOnly(cause)) {
550 return Effect.void;
551 }
552 const error = new DesktopUpdatePollerError({ poller: "startup", cause });
553 return logUpdaterError(error.message, {
554 errorTag: error._tag,
555 poller: error.poller,
556 });
557 }),
558 Effect.forkScoped,
559 );
560 yield* Effect.sleep(AUTO_UPDATE_POLL_INTERVAL).pipe(
561 Effect.andThen(checkForUpdates("poll")),
562 Effect.forever,
563 Effect.catchCause((cause) => {
564 if (Cause.hasInterruptsOnly(cause)) {
565 return Effect.void;
566 }
567 const error = new DesktopUpdatePollerError({ poller: "poll", cause });
568 return logUpdaterError(error.message, {
569 errorTag: error._tag,
570 poller: error.poller,
571 });
572 }),
573 Effect.forkScoped,
574 );
575 }).pipe(Effect.withSpan("desktop.updates.startPollers"));
576​
577 const handleUpdateAvailable = Effect.fn("desktop.updates.handleUpdateAvailable")(function* (
578 raw: unknown,
579 ) {
580 yield* decodeUpdateInfo(raw).pipe(
581 Effect.flatMap(
582 Effect.fn("desktop.updates.applyUpdateAvailable")(function* (info) {
583 const state = yield* Ref.get(updateStateRef);
584 if (resolveDefaultDesktopUpdateChannel(info.version) !== state.channel) {
585 yield* logUpdaterInfo("ignoring update that does not match selected channel", {
586 version: info.version,
587 channel: state.channel,
588 });
589 const checkedAt = yield* currentIsoTimestamp;
590 yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt));
591 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
592 return;
593 }
594​
595 const checkedAt = yield* currentIsoTimestamp;
596 const releaseNotes = normalizeDesktopUpdateReleaseNotes(info.releaseNotes, info.version);
597 yield* setState(
598 reduceDesktopUpdateStateOnUpdateAvailable(state, info.version, checkedAt, releaseNotes),
599 );
600 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
601 yield* logUpdaterInfo("update available", {
602 version: info.version,
603 releaseNoteGroups: releaseNotes.length,
604 });
605 }),
606 ),
607 Effect.catchCause((cause) => {
608 if (Cause.hasInterruptsOnly(cause)) {
609 return Effect.void;
610 }
611 const error = new DesktopUpdateEventHandlingError({ event: "update-available", cause });
612 return logUpdaterWarning(error.message, {
613 errorTag: error._tag,
614 event: error.event,
615 });
616 }),
617 );
618 });
619​
620 const handleUpdateNotAvailable = Effect.gen(function* () {
621 const checkedAt = yield* currentIsoTimestamp;
622 const state = yield* Ref.get(updateStateRef);
623 yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt));
624 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
625 yield* logUpdaterInfo("no updates available");
626 }).pipe(Effect.withSpan("desktop.updates.handleUpdateNotAvailable"));
627​
628 const handleUpdaterError = Effect.fn("desktop.updates.handleUpdaterError")(function* (
629 cause: unknown,
630 ) {
631 const activeAction = yield* activeUpdateAction;
632 const error = new DesktopUpdaterReportedError({
633 operation: Option.getOrElse(activeAction, () => "background" as const),
634 cause,
635 });
636 if (Option.isSome(activeAction) && activeAction.value === "install") {
637 yield* finishUpdateAction("install");
638 yield* Ref.set(desktopState.quitting, false);
639 yield* updateState((current) =>
640 reduceDesktopUpdateStateOnInstallFailure(current, error.message),
641 );
642 yield* logUpdaterError(error.message, {
643 errorTag: error._tag,
644 operation: error.operation,
645 });
646 return;
647 }
648​
649 if (Option.isNone(activeAction)) {
650 const checkedAt = yield* currentIsoTimestamp;
651 yield* updateState((current) => ({
652 ...current,
653 status: "error",
654 message: error.message,
655 checkedAt,
656 downloadPercent: null,
657 errorContext: current.errorContext,
658 canRetry: getCanRetryFromState(current),
659 }));
660 }
661​
662 yield* logUpdaterError(error.message, {
663 errorTag: error._tag,
664 operation: error.operation,
665 });
666 });
667​
668 const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
669 raw: unknown,
670 ) {
671 yield* decodeDownloadProgressInfo(raw).pipe(
672 Effect.flatMap(
673 Effect.fn("desktop.updates.applyDownloadProgress")(function* (progress) {
674 const state = yield* Ref.get(updateStateRef);
675 const percent = Math.floor(progress.percent);
676 if (shouldBroadcastDownloadProgress(state, progress.percent) || state.message !== null) {
677 yield* setState(reduceDesktopUpdateStateOnDownloadProgress(state, progress.percent));
678 }
679 const milestone = percent - (percent % 10);
680 const lastLoggedMilestone = yield* Ref.get(lastLoggedDownloadMilestoneRef);
681 if (milestone > lastLoggedMilestone) {
682 yield* Ref.set(lastLoggedDownloadMilestoneRef, milestone);
683 yield* logUpdaterInfo("download progress", { percent });
684 }
685 }),
686 ),
687 Effect.catchCause((cause) => {
688 if (Cause.hasInterruptsOnly(cause)) {
689 return Effect.void;
690 }
691 const error = new DesktopUpdateEventHandlingError({ event: "download-progress", cause });
692 return logUpdaterWarning(error.message, {
693 errorTag: error._tag,
694 event: error.event,
695 });
696 }),
697 );
698 });
699​
700 const handleUpdateDownloaded = Effect.fn("desktop.updates.handleUpdateDownloaded")(function* (
701 raw: unknown,
702 ) {
703 yield* decodeUpdateInfo(raw).pipe(
704 Effect.flatMap(
705 Effect.fn("desktop.updates.applyUpdateDownloaded")(function* (info) {
706 const state = yield* Ref.get(updateStateRef);
707 yield* setState(reduceDesktopUpdateStateOnDownloadComplete(state, info.version));
708 yield* logUpdaterInfo("update downloaded", { version: info.version });
709 }),
710 ),
711 Effect.catchCause((cause) => {
712 if (Cause.hasInterruptsOnly(cause)) {
713 return Effect.void;
714 }
715 const error = new DesktopUpdateEventHandlingError({ event: "update-downloaded", cause });
716 return logUpdaterWarning(error.message, {
717 errorTag: error._tag,
718 event: error.event,
719 });
720 }),
721 );
722 });
723​
724 return DesktopUpdates.of({
725 getState: Ref.get(updateStateRef),
726 emitState,
727 disabledReason: resolveDisabledReason,
728 configure: Effect.gen(function* () {
729 const context = yield* Effect.context<never>();
730 const runEffect = (effect: Effect.Effect<void>) => {
731 void Effect.runPromiseWith(context)(effect);
732 };
733​
734 const appUpdateYmlConfig = yield* readAppUpdateYml;
735 yield* Ref.set(appUpdateYmlConfigRef, appUpdateYmlConfig);
736​
737 if (config.mockUpdates) {
738 yield* electronUpdater.setFeedURL({
739 provider: "generic",
740 url: `http://localhost:${config.mockUpdateServerPort}`,
741 } as ElectronUpdater.ElectronUpdaterFeedUrl);
742 }
743​
744 const settings = yield* desktopSettings.get;
745 const enabled = yield* shouldEnableAutoUpdates;
746 yield* setState(createBaseUpdateState(settings.updateChannel, enabled, environment));
747 if (!enabled) {
748 return;
749 }
750 yield* Ref.set(updaterConfiguredRef, true);
751​
752 yield* electronUpdater.setAutoDownload(false);
753 yield* electronUpdater.setAutoInstallOnAppQuit(false);
754 yield* applyAutoUpdaterChannel(settings.updateChannel);
755 yield* electronUpdater.setDisableDifferentialDownload(
756 isArm64HostRunningIntelBuild(environment.runtimeInfo),
757 );
758​
759 if (isArm64HostRunningIntelBuild(environment.runtimeInfo)) {
760 yield* logUpdaterInfo(
761 "Apple Silicon host detected while running Intel build; updates will switch to arm64 packages",
762 );
763 }
764​
765 yield* electronUpdater.on("checking-for-update", () => {
766 runEffect(
767 logUpdaterInfo("looking for updates").pipe(
768 Effect.withSpan("desktop.updates.handleCheckingForUpdate"),
769 ),
770 );
771 });
772 yield* electronUpdater.on("update-available", (info: unknown) => {
773 runEffect(handleUpdateAvailable(info));
774 });
775 yield* electronUpdater.on("update-not-available", () => {
776 runEffect(handleUpdateNotAvailable);
777 });
778 yield* electronUpdater.on("error", (error: unknown) => {
779 runEffect(handleUpdaterError(error));
780 });
781 yield* electronUpdater.on("download-progress", (progress: unknown) => {
782 runEffect(handleDownloadProgress(progress));
783 });
784 yield* electronUpdater.on("update-downloaded", (info: unknown) => {
785 runEffect(handleUpdateDownloaded(info));
786 });
787​
788 yield* startUpdatePollers;
789 }).pipe(Effect.withSpan("desktop.updates.configure")),
790 setChannel: Effect.fn("desktop.updates.setChannel")(function* (
791 nextChannel: DesktopUpdateChannel,
792 ) {
793 yield* Effect.annotateCurrentSpan({ channel: nextChannel });
794 const activeAction = yield* tryStartChannelChange;
795 if (Option.isSome(activeAction)) {
796 return yield* new DesktopUpdateActionInProgressError({
797 action: activeAction.value,
798 requestedChannel: nextChannel,
799 });
800 }
801​
802 return yield* Effect.gen(function* () {
803 const state = yield* Ref.get(updateStateRef);
804 if (nextChannel === state.channel) {
805 return state;
806 }
807​
808 yield* desktopSettings
809 .setUpdateChannel(nextChannel)
810 .pipe(
811 Effect.mapError(
812 (cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }),
813 ),
814 );
815​
816 const enabled = yield* shouldEnableAutoUpdates;
817 yield* setState(createBaseUpdateState(nextChannel, enabled, environment));
818​
819 if (!enabled || !(yield* Ref.get(updaterConfiguredRef))) {
820 return yield* Ref.get(updateStateRef);
821 }
822​
823 yield* applyAutoUpdaterChannel(nextChannel);
824 const allowDowngrade = yield* electronUpdater.allowDowngrade;
825 yield* electronUpdater.setAllowDowngrade(true);
826 yield* checkForUpdates("channel-change", "held").pipe(
827 Effect.ensuring(electronUpdater.setAllowDowngrade(allowDowngrade).pipe(Effect.ignore)),
828 );
829 return yield* Ref.get(updateStateRef);
830 }).pipe(Effect.ensuring(finishUpdateAction("channel")));
831 }),
832 check: Effect.fn("desktop.updates.check")(function* (reason: string) {
833 yield* Effect.annotateCurrentSpan({ reason });
834 if (!(yield* Ref.get(updaterConfiguredRef))) {
835 return {
836 checked: false,
837 state: yield* Ref.get(updateStateRef),
838 };
839 }
840 const checked = yield* checkForUpdates(reason);
841 return {
842 checked,
843 state: yield* Ref.get(updateStateRef),
844 };
845 }),
846 download: Effect.gen(function* () {
847 const result = yield* downloadAvailableUpdate;
848 return {
849 accepted: result.accepted,
850 completed: result.completed,
851 state: yield* Ref.get(updateStateRef),
852 };
853 }).pipe(Effect.withSpan("desktop.updates.download")),
854 install: Effect.gen(function* () {
855 if (yield* Ref.get(desktopState.quitting)) {
856 return {
857 accepted: false,
858 completed: false,
859 state: yield* Ref.get(updateStateRef),
860 };
861 }
862 const result = yield* installDownloadedUpdate;
863 return {
864 accepted: result.accepted,
865 completed: result.completed,
866 state: yield* Ref.get(updateStateRef),
867 };
868 }).pipe(Effect.withSpan("desktop.updates.install")),
869 });
870});
871​
872export const layer = Layer.effect(DesktopUpdates, make);