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