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