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