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

DesktopUpdates.ts

1,232 lines46.6 KB

1import {
2 DESKTOP_UPDATE_RESTART_MARKER_FILE,
3 DesktopUpdateChannelSchema,
4 type DesktopRuntimeInfo,
5 type DesktopUpdateActionResult,
6 type DesktopUpdateChannel,
7 type DesktopUpdateCheckResult,
8 type DesktopUpdateState,
9} from "@t3tools/contracts";
10import { errorTag } from "@t3tools/shared/observability";
11import * as Cause from "effect/Cause";
12import * as Context from "effect/Context";
13import * as DateTime from "effect/DateTime";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as PubSub from "effect/PubSub";
21import * as Ref from "effect/Ref";
22import * as Schedule from "effect/Schedule";
23import * as Schema from "effect/Schema";
24import * as Scope from "effect/Scope";
25import * as Semaphore from "effect/Semaphore";
26import * as Stream from "effect/Stream";
27​
28import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
29import * as DesktopConfig from "../app/DesktopConfig.ts";
30import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
31import * as DesktopObservability from "../app/DesktopObservability.ts";
32import * as DesktopState from "../app/DesktopState.ts";
33import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
34import * as ElectronWindow from "../electron/ElectronWindow.ts";
35import * as IpcChannels from "../ipc/channels.ts";
36import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
37import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
38import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
39import { compareSemverVersions } from "@t3tools/shared/semver";
40import {
41 createInitialDesktopUpdateState,
42 reduceDesktopUpdateStateOnCheckFailure,
43 reduceDesktopUpdateStateOnCheckStart,
44 reduceDesktopUpdateStateOnDownloadComplete,
45 reduceDesktopUpdateStateOnDownloadFailure,
46 reduceDesktopUpdateStateOnDownloadProgress,
47 reduceDesktopUpdateStateOnDownloadStart,
48 reduceDesktopUpdateStateOnInstallFailure,
49 reduceDesktopUpdateStateOnNoUpdate,
50 reduceDesktopUpdateStateOnUpdateAvailable,
51 resolveNotAppliedInstallVersion,
52} from "./updateMachine.ts";
53​
54const CHANNEL_CHANGE_RETRY_DELAY = Duration.seconds(1);
55const CHANNEL_CHANGE_RETRIES = 30;
56const AUTO_UPDATE_STARTUP_DELAY = "15 seconds";
57const AUTO_UPDATE_POLL_INTERVAL = "4 minutes";
58const PREPARED_INSTALL_CHECK_WAIT = Duration.seconds(90);
59​
60type UpdateAction = "check" | "download" | "install" | "install-recovery" | "channel";
61​
62interface DesktopPreparedUpdateInstallResult extends DesktopUpdateActionResult {
63 readonly failed: boolean;
65​
66const AppUpdateYmlConfig = Schema.Record(Schema.String, Schema.String);
67type AppUpdateYmlConfig = typeof AppUpdateYmlConfig.Type;
68​
69const UpdateInfo = Schema.Struct({
70 version: Schema.String,
71 // Malformed notes must not block update-state decoding; normalizeDesktopUpdateReleaseNotes validates separately.
72 releaseNotes: Schema.optional(Schema.Unknown),
73 releaseDate: Schema.optional(Schema.String),
74});
75​
76const DownloadProgressInfo = Schema.Struct({
77 percent: Schema.Number,
78});
79export const DESKTOP_UPDATE_INSTALL_RECORD_FILE = "desktop-update-install.json";
80const DesktopUpdateInstallRecord = Schema.fromJsonString(
81 Schema.Struct({ fromVersion: Schema.String, targetVersion: Schema.String }),
82);
83const decodeInstallRecord = Schema.decodeUnknownEffect(DesktopUpdateInstallRecord);
84const encodeInstallRecord = Schema.encodeEffect(DesktopUpdateInstallRecord);
85​
86const decodeAppUpdateYmlConfig = Schema.decodeUnknownEffect(AppUpdateYmlConfig);
87const decodeUpdateInfo = Schema.decodeUnknownEffect(UpdateInfo);
88const decodeDownloadProgressInfo = Schema.decodeUnknownEffect(DownloadProgressInfo);
89​
90const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
91​
92export class DesktopUpdateActionInProgressError extends Schema.TaggedError<DesktopUpdateActionInProgressError>()(
93 "DesktopUpdateActionInProgressError",
94 {
95 action: Schema.Literals(["check", "download", "install", "channel"]),
96 requestedChannel: DesktopUpdateChannelSchema,
97 },
98) {
99 override get message(): string {
100 return `Cannot change the desktop update channel to ${this.requestedChannel} while an update ${this.action} action is in progress.`;
101 }
103​
104export class DesktopUpdateChannelPersistenceError extends Schema.TaggedError<DesktopUpdateChannelPersistenceError>()(
105 "DesktopUpdateChannelPersistenceError",
106 {
107 channel: DesktopUpdateChannelSchema,
108 cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
109 },
110) {
111 override get message(): string {
112 return `Failed to persist the ${this.channel} desktop update channel.`;
113 }
115​
116export class DesktopUpdatePollerError extends Schema.TaggedError<DesktopUpdatePollerError>()(
117 "DesktopUpdatePollerError",
118 {
119 poller: Schema.Literals(["startup", "poll"]),
120 cause: Schema.Defect(),
121 },
122) {
123 override get message(): string {
124 return `Desktop update ${this.poller} poller failed.`;
125 }
127​
128export class DesktopUpdateEventHandlingError extends Schema.TaggedError<DesktopUpdateEventHandlingError>()(
129 "DesktopUpdateEventHandlingError",
130 {
131 event: Schema.Literals(["update-available", "download-progress", "update-downloaded"]),
132 cause: Schema.Defect(),
133 },
134) {
135 override get message(): string {
136 return `Failed to handle desktop update ${this.event} event.`;
137 }
139​
140export class DesktopUpdaterReportedError extends Schema.TaggedError<DesktopUpdaterReportedError>()(
141 "DesktopUpdaterReportedError",
142 {
143 operation: Schema.Literals(["check", "download", "install", "channel", "background"]),
144 cause: Schema.Defect(),
145 },
146) {
147 override get message(): string {
148 return `Desktop updater ${this.operation} operation reported an error.`;
149 }
151​
152export class DesktopUpdateUnexpectedActionError extends Schema.TaggedError<DesktopUpdateUnexpectedActionError>()(
153 "DesktopUpdateUnexpectedActionError",
154 {
155 action: Schema.Literals(["download", "install"]),
156 cause: Schema.Defect(),
157 },
158) {
159 override get message(): string {
160 return `Desktop update ${this.action} action failed unexpectedly.`;
161 }
163​
164export const DesktopUpdateSetChannelError = Schema.Union([
165 DesktopUpdateActionInProgressError,
166 DesktopUpdateChannelPersistenceError,
167]);
168export type DesktopUpdateSetChannelError = typeof DesktopUpdateSetChannelError.Type;
169​
170export class DesktopUpdates extends Context.Service<
171 DesktopUpdates,
172 {
173 readonly getState: Effect.Effect<DesktopUpdateState>;
174 readonly isActionActive: Effect.Effect<boolean>;
175 readonly isInstallActive: Effect.Effect<boolean>;
176 readonly subscribe: Effect.Effect<
177 {
178 readonly latest: DesktopUpdateState;
179 readonly changes: Stream.Stream<DesktopUpdateState>;
180 },
181 never,
182 Scope.Scope
183 >;
184 readonly emitState: Effect.Effect<void>;
185 readonly disabledReason: Effect.Effect<Option.Option<string>>;
186 readonly configure: Effect.Effect<void, never, Scope.Scope>;
187 /** `minimumVersion` is a track switch's checked release; nothing older is offered after. */
188 readonly setChannel: (
189 channel: DesktopUpdateChannel,
190 options?: { readonly minimumVersion?: string | undefined },
191 ) => Effect.Effect<DesktopUpdateState, DesktopUpdateSetChannelError>;
192 /** `allowDowngrade` is for a guarded track switch, which checked that older release. */
193 readonly check: (
194 reason: string,
195 options?: { readonly allowDowngrade?: boolean },
196 ) => Effect.Effect<DesktopUpdateCheckResult>;
197 readonly download: Effect.Effect<DesktopUpdateActionResult>;
198 readonly install: Effect.Effect<DesktopUpdateActionResult>;
199 readonly installPrepared: (
200 expectedVersion: string,
201 ) => Effect.Effect<DesktopPreparedUpdateInstallResult>;
202 }
203>()("@t3tools/desktop/updates/DesktopUpdates") {}
204​
205const {
206 logInfo: logUpdaterInfo,
207 logWarning: logUpdaterWarning,
208 logError: logUpdaterError,
209} = DesktopObservability.makeComponentLogger("desktop-updater");
210​
211function redactMessage(message: string): string {
212 return (message.split(/[\r\n]/, 1)[0] ?? "")
213 .replace(/\b(?:https?|file):\/\/[^\s"'<>]+/gi, "[redacted URL]")
214 .replace(/\b(?:Bearer|Basic)\s+[^\s,;]+/gi, "[redacted credential]")
215 .replace(
216 /\b(?:authorization|proxy-authorization|cookie|set-cookie)\s*[:=].*$/gi,
217 "[redacted header]",
218 )
219 .replace(
220 /\b[\w-]*(?:token|password|secret|credential|api[_-]?key)[\w-]*\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,
221 "[redacted credential]",
222 )
223 .slice(0, 512);
225​
226function summarizeCause(cause: unknown, depth: number): string {
227 if (depth >= 3) return "[truncated cause]";
228 if (Cause.isCause(cause)) {
229 return cause.reasons
230 .slice(0, 3)
231 .map((reason) =>
232 reason._tag === "Fail"
233 ? summarizeCause(reason.error, depth + 1)
234 : reason._tag === "Die"
235 ? summarizeCause(reason.defect, depth + 1)
236 : "Interrupted",
237 )
238 .join("; ");
239 }
240 if (typeof cause === "string") return redactMessage(cause);
241 if (typeof cause !== "object" || cause === null) return errorTag(cause);
242​
243 const error = cause as {
244 readonly message?: unknown;
245 readonly code?: unknown;
246 readonly cause?: unknown;
247 };
248 const code =
249 typeof error.code === "string" && /^[A-Z][A-Z0-9_]{0,127}$/.test(error.code)
250 ? ` [${error.code}]`
251 : "";
252 const message = typeof error.message === "string" ? `: ${redactMessage(error.message)}` : "";
253 const nested =
254 error.cause === undefined ? "" : `; caused by ${summarizeCause(error.cause, depth + 1)}`;
255 return `${errorTag(cause)}${code}${message}${nested}`;
257​
258export function describeUpdateErrorCause(cause: unknown): string {
259 try {
260 return summarizeCause(cause, 0).slice(0, 1024);
261 } catch {
262 return "UnknownError";
263 }
265​
266function parseAppUpdateYml(raw: string): Effect.Effect<Option.Option<AppUpdateYmlConfig>> {
267 const entries: Record<string, string> = {};
268 for (const line of raw.split("\n")) {
269 const match = line.match(/^(\w+):\s*(.+)$/);
270 if (match?.[1] && match[2]) {
271 entries[match[1]] = match[2].trim();
272 }
273 }
274​
275 return decodeAppUpdateYmlConfig(entries).pipe(
276 Effect.map((config) => (config.provider ? Option.some(config) : Option.none())),
277 Effect.orElseSucceed(() => Option.none<AppUpdateYmlConfig>()),
278 );
280​
281function createBaseUpdateState(
282 channel: DesktopUpdateChannel,
283 disabledReason: Option.Option<string>,
284 environment: DesktopEnvironment.DesktopEnvironment["Service"],
285): DesktopUpdateState {
286 const enabled = Option.isNone(disabledReason);
287 return {
288 ...createInitialDesktopUpdateState(environment.appVersion, environment.runtimeInfo, channel),
289 enabled,
290 status: enabled ? "idle" : "disabled",
291 message: Option.getOrNull(disabledReason),
292 };
294​
295function getCanRetryFromState(state: DesktopUpdateState): boolean {
296 return state.availableVersion !== null || state.downloadedVersion !== null;
298​
299function shouldBroadcastDownloadProgress(
300 currentState: DesktopUpdateState,
301 nextPercent: number,
302): boolean {
303 if (currentState.status !== "downloading") {
304 return true;
305 }
306​
307 const currentPercent = currentState.downloadPercent;
308 if (currentPercent === null) {
309 return true;
310 }
311​
312 const previousStep = Math.floor(currentPercent / 10);
313 const nextStep = Math.floor(nextPercent / 10);
314 return nextStep !== previousStep || nextPercent === 100;
316​
317function getAutoUpdateDisabledReason(args: {
318 isDevelopment: boolean;
319 isPackaged: boolean;
320 platform: NodeJS.Platform;
321 appImage?: string | undefined;
322 isDebPackage: boolean;
323 disabledByEnv: boolean;
324 hasUpdateFeedConfig: boolean;
325}): string | null {
326 if (!args.hasUpdateFeedConfig) {
327 return "Automatic updates are not available because no update feed is configured.";
328 }
329 if (args.isDevelopment || !args.isPackaged) {
330 return "Automatic updates are only available in packaged production builds.";
331 }
332 if (args.disabledByEnv) {
333 return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
334 }
335 if (args.platform === "linux" && !args.appImage && !args.isDebPackage) {
336 return "Automatic updates on Linux require the AppImage or the .deb package.";
337 }
338 return null;
340​
341function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean {
342 return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
344​
345/** @public */
346export const make = Effect.gen(function* () {
347 const config = yield* DesktopConfig.DesktopConfig;
348 const pool = yield* DesktopBackendPool.DesktopBackendPool;
349 const desktopState = yield* DesktopState.DesktopState;
350 const electronUpdater = yield* ElectronUpdater.ElectronUpdater;
351 const electronWindow = yield* ElectronWindow.ElectronWindow;
352 const environment = yield* DesktopEnvironment.DesktopEnvironment;
353 const fileSystem = yield* FileSystem.FileSystem;
354 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
355​
356 const appUpdateYmlConfigRef = yield* Ref.make<Option.Option<AppUpdateYmlConfig>>(Option.none());
357 const activeUpdateActionRef = yield* Ref.make<Option.Option<UpdateAction>>(Option.none());
358 const installRunningBackendsRef = yield* Ref.make<
359 ReadonlyArray<DesktopBackendPool.DesktopBackendInstance>
360 >([]);
361 const finishedUpdateActions = yield* PubSub.unbounded<UpdateAction>();
362 const updaterConfiguredRef = yield* Ref.make(false);
363 const lastLoggedDownloadMilestoneRef = yield* Ref.make(-1);
364 const notAppliedVersionRef = yield* Ref.make(Option.none<string>());
365 // The release a track switch's database check cleared. A build crosses to another track only
366 // through such a switch, and never below that release: version order alone cannot tell whether
367 // a Stable knows a Nightly's migrations.
368 const releaseFloorRef = yield* Ref.make(Option.none<string>());
369 const offerable = (version: string, state: DesktopUpdateState) =>
370 Ref.get(releaseFloorRef).pipe(
371 Effect.map(
372 (floor) =>
373 desktopUpdateChannelOf(version) === state.channel &&
374 (Option.isSome(floor)
375 ? compareSemverVersions(version, floor.value) >= 0
376 : desktopUpdateChannelOf(environment.appVersion) === state.channel),
377 ),
378 );
379 const updateStateRef = yield* Ref.make<DesktopUpdateState>(
380 createInitialDesktopUpdateState(
381 environment.appVersion,
382 environment.runtimeInfo,
383 environment.defaultDesktopSettings.updateChannel,
384 ),
385 );
386​
387 const stateChanges = yield* PubSub.sliding<DesktopUpdateState>(16);
388 // Serialize writes and publishes against subscription so snapshots cannot overlap the first change.
389 const stateMutex = yield* Semaphore.make(1);
390​
391 const emitState = Ref.get(updateStateRef).pipe(
392 Effect.flatMap((state) => electronWindow.sendAll(IpcChannels.UPDATE_STATE_CHANNEL, state)),
393 );
394​
395 const setState = (state: DesktopUpdateState): Effect.Effect<void> =>
396 stateMutex
397 .withPermits(1)(
398 Ref.set(updateStateRef, state).pipe(Effect.andThen(PubSub.publish(stateChanges, state))),
399 )
400 .pipe(Effect.andThen(emitState));
401​
402 const updateState = (
403 f: (state: DesktopUpdateState) => DesktopUpdateState,
404 ): Effect.Effect<DesktopUpdateState> =>
405 Ref.get(updateStateRef).pipe(
406 Effect.flatMap((state) => {
407 const nextState = f(state);
408 return setState(nextState).pipe(Effect.as(nextState));
409 }),
410 );
411​
412 const readAppUpdateYml = fileSystem.readFileString(environment.appUpdateYmlPath, "utf-8").pipe(
413 Effect.option,
414 Effect.flatMap(
415 Option.match({
416 onNone: () => Effect.succeed(Option.none<AppUpdateYmlConfig>()),
417 onSome: parseAppUpdateYml,
418 }),
419 ),
420 );
421​
422 // electron-updater uses this marker to install .deb updates with dpkg.
423 const isDebPackage =
424 environment.platform === "linux" && environment.isPackaged
425 ? yield* fileSystem
426 .readFileString(environment.path.join(environment.resourcesPath, "package-type"))
427 .pipe(
428 Effect.map((packageType) => packageType.trim() === "deb"),
429 Effect.orElseSucceed(() => false),
430 )
431 : false;
432​
433 const hasUpdateFeedConfig = Ref.get(appUpdateYmlConfigRef).pipe(
434 Effect.map((appUpdateYmlConfig) => Option.isSome(appUpdateYmlConfig) || config.mockUpdates),
435 );
436​
437 const resolveDisabledReason = Effect.gen(function* () {
438 const hasFeedConfig = yield* hasUpdateFeedConfig;
439 return Option.fromNullishOr(
440 getAutoUpdateDisabledReason({
441 isDevelopment: environment.isDevelopment,
442 isPackaged: environment.isPackaged,
443 platform: environment.platform,
444 appImage: Option.getOrUndefined(config.appImagePath),
445 isDebPackage,
446 disabledByEnv: config.disableAutoUpdate,
447 hasUpdateFeedConfig: hasFeedConfig,
448 }),
449 );
450 });
451​
452 const activeUpdateAction = Ref.get(activeUpdateActionRef);
453​
454 const tryStartUpdateAction = (action: UpdateAction): Effect.Effect<boolean> =>
455 Ref.modify(activeUpdateActionRef, (activeAction) =>
456 Option.isSome(activeAction) ? [false, activeAction] : [true, Option.some(action)],
457 );
458​
459 const tryStartChannelChange = Ref.modify(activeUpdateActionRef, (activeAction) =>
460 Option.isSome(activeAction)
461 ? [activeAction, activeAction]
462 : [Option.none<UpdateAction>(), Option.some<UpdateAction>("channel")],
463 );
464​
465 const finishUpdateAction = (action: UpdateAction): Effect.Effect<void> =>
466 Ref.modify(activeUpdateActionRef, (activeAction) => {
467 const finished = Option.isSome(activeAction) && activeAction.value === action;
468 return [finished, finished ? Option.none() : activeAction] as const;
469 }).pipe(
470 Effect.flatMap((finished) =>
471 finished ? PubSub.publish(finishedUpdateActions, action).pipe(Effect.asVoid) : Effect.void,
472 ),
473 );
474​
475 const applyAutoUpdaterChannel = Effect.fn("desktop.updates.applyAutoUpdaterChannel")(function* (
476 channel: DesktopUpdateChannel,
477 ) {
478 yield* Effect.annotateCurrentSpan({ channel });
479 const allowsPrerelease = channel === "nightly";
480 yield* electronUpdater.setChannel(channel);
481 yield* electronUpdater.setAllowPrerelease(allowsPrerelease);
482 // An older build can lack migrations this one ran. Only a guarded track switch's own check
483 // may offer one.
484 yield* electronUpdater.setAllowDowngrade(false);
485 yield* electronUpdater.setFullChangelog(allowsPrerelease);
486 yield* logUpdaterInfo("using update channel", {
487 channel,
488 allowPrerelease: allowsPrerelease,
489 fullChangelog: allowsPrerelease,
490 });
491 });
492​
493 const checkForUpdates = Effect.fn("desktop.updates.checkForUpdates")(function* (
494 reason: string,
495 actionReservation: "acquire" | "held" = "acquire",
496 allowDowngrade = false,
497 ) {
498 yield* Effect.annotateCurrentSpan({ reason });
499 if (yield* Ref.get(desktopState.quitting)) return false;
500 if (!(yield* Ref.get(updaterConfiguredRef))) return false;
501​
502 const state = yield* Ref.get(updateStateRef);
503 if (state.status === "downloading") {
504 yield* logUpdaterInfo("skipping update check while update is active", {
505 reason,
506 status: state.status,
507 });
508 return false;
509 }
510​
511 if (actionReservation === "acquire" && !(yield* tryStartUpdateAction("check"))) return false;
512​
513 const check = Effect.gen(function* () {
514 const checkedAt = yield* currentIsoTimestamp;
515 yield* setState(reduceDesktopUpdateStateOnCheckStart(state, checkedAt));
516 yield* logUpdaterInfo("checking for updates", { reason });
517​
518 // The flag is shared updater state, so it flips only while this check holds the reservation.
519 const restoreDowngrade = yield* electronUpdater.allowDowngrade;
520 if (allowDowngrade) yield* electronUpdater.setAllowDowngrade(true);
521 return yield* electronUpdater.checkForUpdates.pipe(
522 Effect.ensuring(electronUpdater.setAllowDowngrade(restoreDowngrade).pipe(Effect.ignore)),
523 Effect.as(true),
524 Effect.catchTags({
525 ElectronUpdaterCheckForUpdatesError: Effect.fn(
526 "desktop.updates.handleCheckForUpdatesFailure",
527 )(function* (error) {
528 const failedAt = yield* currentIsoTimestamp;
529 yield* updateState((current) =>
530 reduceDesktopUpdateStateOnCheckFailure(current, error.message, failedAt),
531 );
532 yield* logUpdaterError(error.message, {
533 errorTag: error._tag,
534 cause: describeUpdateErrorCause(error.cause),
535 channel: error.channel,
536 });
537 return true;
538 }),
539 }),
540 );
541 });
542​
543 return yield* actionReservation === "held"
544 ? check
545 : check.pipe(
546 Effect.onInterrupt(() => setState(state)),
547 Effect.ensuring(finishUpdateAction("check")),
548 );
549 });
550​
551 const downloadAvailableUpdate = Effect.gen(function* () {
552 const state = yield* Ref.get(updateStateRef);
553 if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") {
554 return { accepted: false, completed: false };
555 }
556​
557 if (!(yield* tryStartUpdateAction("download"))) {
558 return { accepted: false, completed: false };
559 }
560​
561 return yield* Effect.gen(function* () {
562 yield* setState(reduceDesktopUpdateStateOnDownloadStart(state));
563 yield* electronUpdater.setDisableDifferentialDownload(
564 isArm64HostRunningIntelBuild(environment.runtimeInfo),
565 );
566 yield* logUpdaterInfo("downloading update");
567 yield* electronUpdater.downloadUpdate;
568 return { accepted: true, completed: true };
569 }).pipe(
570 Effect.catchTags({
571 ElectronUpdaterDownloadUpdateError: Effect.fn("desktop.updates.handleDownloadFailure")(
572 function* (error) {
573 yield* updateState((current) =>
574 reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
575 );
576 yield* logUpdaterError(error.message, {
577 errorTag: error._tag,
578 cause: describeUpdateErrorCause(error.cause),
579 channel: error.channel,
580 });
581 return { accepted: true, completed: false };
582 },
583 ),
584 }),
585 Effect.onInterrupt(() =>
586 updateState((current) => (current.status === "downloading" ? state : current)).pipe(
587 Effect.asVoid,
588 ),
589 ),
590 Effect.catchCause((cause) => {
591 if (Cause.hasInterruptsOnly(cause)) {
592 return Effect.failCause(cause);
593 }
594 const error = new DesktopUpdateUnexpectedActionError({ action: "download", cause });
595 return Effect.gen(function* () {
596 yield* updateState((current) =>
597 reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
598 );
599 yield* logUpdaterError(error.message, {
600 errorTag: error._tag,
601 cause: describeUpdateErrorCause(error.cause),
602 action: error.action,
603 });
604 return { accepted: true, completed: false };
605 });
606 }),
607 Effect.ensuring(finishUpdateAction("download")),
608 );
609 }).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate"));
610​
611 const updateRestartMarkerDir = environment.path.join(environment.baseDir, "runtime");
612 const updateRestartMarkerPath = environment.path.join(
613 updateRestartMarkerDir,
614 DESKTOP_UPDATE_RESTART_MARKER_FILE,
615 );
616 const writeUpdateRestartMarker = fileSystem
617 .makeDirectory(updateRestartMarkerDir, { recursive: true })
618 .pipe(
619 Effect.andThen(fileSystem.writeFileString(updateRestartMarkerPath, "")),
620 Effect.catch((error) =>
621 logUpdaterWarning("Could not write the update restart marker.", { errorTag: error._tag }),
622 ),
623 );
624​
625 // Failed or interrupted installs leave no replacement backend; later quits must release the tunnel.
626 const removeUpdateRestartMarker = fileSystem
627 .remove(updateRestartMarkerPath, { force: true })
628 .pipe(Effect.ignore);
629​
630 const installRecordPath = environment.path.join(
631 updateRestartMarkerDir,
632 DESKTOP_UPDATE_INSTALL_RECORD_FILE,
633 );
634 const writeInstallRecord = (targetVersion: string) =>
635 encodeInstallRecord({ fromVersion: environment.appVersion, targetVersion }).pipe(
636 Effect.flatMap((text) => fileSystem.writeFileString(installRecordPath, text)),
637 Effect.catch((error) =>
638 logUpdaterWarning("Could not record the update install.", { errorTag: error._tag }),
639 ),
640 );
641 const removeInstallRecord = fileSystem
642 .remove(installRecordPath, { force: true })
643 .pipe(Effect.ignore);
644​
645 const readNotAppliedInstallVersion = fileSystem.readFileString(installRecordPath).pipe(
646 Effect.flatMap(decodeInstallRecord),
647 Effect.option,
648 Effect.map((record) =>
649 Option.flatMap(record, (value) =>
650 Option.fromNullishOr(resolveNotAppliedInstallVersion(value, environment.appVersion)),
651 ),
652 ),
653 Effect.tap((notAppliedVersion) =>
654 Option.isNone(notAppliedVersion) ? removeInstallRecord : Effect.void,
655 ),
656 );
657​
658 const baseUpdateState = (channel: DesktopUpdateChannel, disabledReason: Option.Option<string>) =>
659 Ref.get(notAppliedVersionRef).pipe(
660 Effect.map((notAppliedVersion) => ({
661 ...createBaseUpdateState(channel, disabledReason, environment),
662 ...Option.match(notAppliedVersion, {
663 onNone: () => ({}),
664 onSome: (version) => ({ notAppliedVersion: version }),
665 }),
666 })),
667 );
668​
669 const resetInstallAction = Effect.all(
670 [
671 finishUpdateAction("install"),
672 Ref.set(desktopState.quitting, false),
673 Ref.set(installRunningBackendsRef, []),
674 removeUpdateRestartMarker,
675 removeInstallRecord,
676 ],
677 { discard: true },
678 );
679​
680 const recoverFailedInstall = Effect.fn("desktop.updates.recoverFailedInstall")(function* (
681 message: string,
682 ) {
683 const ownsRecovery = yield* Ref.modify(activeUpdateActionRef, (activeAction) =>
684 Option.isSome(activeAction) && activeAction.value === "install"
685 ? ([true, Option.some<UpdateAction>("install-recovery")] as const)
686 : ([false, activeAction] as const),
687 );
688 if (!ownsRecovery) return;
689​
690 yield* Ref.set(desktopState.quitting, false);
691 yield* removeUpdateRestartMarker;
692 yield* removeInstallRecord;
693 yield* Effect.gen(function* () {
694 const runningInstances = yield* Ref.getAndSet(installRunningBackendsRef, []);
695 const instances = (yield* pool.list).filter((instance) =>
696 runningInstances.includes(instance),
697 );
698 const restartExit = yield* Effect.forEach(instances, (instance) => instance.start, {
699 concurrency: "unbounded",
700 discard: true,
701 }).pipe(Effect.exit);
702 yield* updateState((current) => reduceDesktopUpdateStateOnInstallFailure(current, message));
703 if (Exit.isFailure(restartExit)) {
704 yield* logUpdaterError("Desktop update install recovery could not restart every backend.");
705 }
706 }).pipe(
707 Effect.catchCause(() =>
708 logUpdaterError("Desktop update install recovery failed unexpectedly."),
709 ),
710 Effect.ensuring(finishUpdateAction("install-recovery")),
711 );
712 });
713​
714 const installDownloadedUpdate = (expectedVersion?: string) =>
715 Effect.scoped(
716 Effect.gen(function* () {
717 const actionCompletions = yield* PubSub.subscribe(finishedUpdateActions);
718 let admission: "admitted" | "refused" | "wait-for-check" = "wait-for-check";
719 while (admission === "wait-for-check") {
720 admission = yield* stateMutex.withPermits(1)(
721 Effect.gen(function* () {
722 const state = yield* Ref.get(updateStateRef);
723 const activeAction = yield* Ref.get(activeUpdateActionRef);
724 const hasExpectedDownload =
725 state.downloadedVersion !== null &&
726 (expectedVersion === undefined || state.downloadedVersion === expectedVersion);
727 if (
728 (yield* Ref.get(desktopState.quitting)) ||
729 !(yield* Ref.get(updaterConfiguredRef)) ||
730 !hasExpectedDownload
731 ) {
732 return "refused" as const;
733 }
734 if (Option.isSome(activeAction)) {
735 return activeAction.value === "check" && expectedVersion !== undefined
736 ? ("wait-for-check" as const)
737 : ("refused" as const);
738 }
739 const hasInstallableDownload =
740 state.status === "downloaded" ||
741 (state.status === "error" &&
742 (state.errorContext === null || state.errorContext === "install"));
743 if (!hasInstallableDownload) return "refused" as const;
744 return (yield* tryStartUpdateAction("install"))
745 ? ("admitted" as const)
746 : ("refused" as const);
747 }),
748 );
749 if (admission === "wait-for-check") {
750 const finishedAction = yield* PubSub.take(actionCompletions).pipe(
751 Effect.timeoutOption(PREPARED_INSTALL_CHECK_WAIT),
752 );
753 if (Option.isNone(finishedAction)) {
754 admission = "refused";
755 }
756 }
757 }
758 if (admission === "refused") {
759 return { accepted: false, completed: false, failed: false };
760 }
761​
762 yield* Ref.set(desktopState.quitting, true);
763 yield* Ref.set(installRunningBackendsRef, []);
764​
765 return yield* Effect.gen(function* () {
766 yield* writeUpdateRestartMarker;
767 const { downloadedVersion } = yield* Ref.get(updateStateRef);
768 if (downloadedVersion !== null) yield* writeInstallRecord(downloadedVersion);
769 // Stop pooled backends before quitAndInstall can outrun their scope finalizers.
770 const instances = yield* pool.list;
771 // stop clears desiredRunning, so retain the recovery set beforehand.
772 const runningInstances = yield* Effect.filter(instances, (instance) =>
773 instance.snapshot.pipe(Effect.map((snapshot) => snapshot.desiredRunning)),
774 );
775 yield* Ref.set(installRunningBackendsRef, runningInstances);
776 yield* Effect.forEach(
777 instances,
778 (instance) => instance.stop({ timeout: Duration.seconds(5) }),
779 { concurrency: "unbounded" },
780 );
781 yield* electronUpdater.quitAndInstall({
782 isSilent: true,
783 isForceRunAfter: true,
784 });
785 return { accepted: true, completed: false, failed: false };
786 }).pipe(
787 Effect.catchTags({
788 ElectronUpdaterQuitAndInstallError: Effect.fn("desktop.updates.handleInstallFailure")(
789 function* (error) {
790 yield* recoverFailedInstall(error.message);
791 yield* logUpdaterError(error.message, {
792 errorTag: error._tag,
793 cause: describeUpdateErrorCause(error.cause),
794 channel: error.channel,
795 isSilent: error.isSilent,
796 isForceRunAfter: error.isForceRunAfter,
797 });
798 return { accepted: true, completed: false, failed: true };
799 },
800 ),
801 }),
802 Effect.onInterrupt(() => resetInstallAction),
803 Effect.catchCause((cause) =>
804 Effect.gen(function* () {
805 if (Cause.hasInterruptsOnly(cause)) {
806 return yield* Effect.failCause(cause);
807 }
808 const error = new DesktopUpdateUnexpectedActionError({ action: "install", cause });
809 yield* recoverFailedInstall(error.message);
810 yield* logUpdaterError(error.message, {
811 errorTag: error._tag,
812 cause: describeUpdateErrorCause(error.cause),
813 action: error.action,
814 });
815 return { accepted: true, completed: false, failed: true };
816 }),
817 ),
818 );
819 }),
820 ).pipe(Effect.withSpan("desktop.updates.installDownloadedUpdate"));
821​
822 const installWithExpectedVersion = Effect.fn("desktop.updates.install")(function* (
823 expectedVersion?: string,
824 ) {
825 if (yield* Ref.get(desktopState.quitting)) {
826 return {
827 accepted: false,
828 completed: false,
829 failed: false,
830 state: yield* Ref.get(updateStateRef),
831 };
832 }
833 const result = yield* installDownloadedUpdate(expectedVersion);
834 return {
835 accepted: result.accepted,
836 completed: result.completed,
837 failed: result.failed,
838 state: yield* Ref.get(updateStateRef),
839 };
840 });
841​
842 const startUpdatePollers: Effect.Effect<void, never, Scope.Scope> = Effect.gen(function* () {
843 yield* Effect.sleep(AUTO_UPDATE_STARTUP_DELAY).pipe(
844 Effect.andThen(checkForUpdates("startup")),
845 Effect.catchCause((cause) => {
846 if (Cause.hasInterruptsOnly(cause)) {
847 return Effect.void;
848 }
849 const error = new DesktopUpdatePollerError({ poller: "startup", cause });
850 return logUpdaterError(error.message, {
851 errorTag: error._tag,
852 cause: describeUpdateErrorCause(error.cause),
853 poller: error.poller,
854 });
855 }),
856 Effect.forkScoped,
857 );
858 yield* Effect.sleep(AUTO_UPDATE_POLL_INTERVAL).pipe(
859 Effect.andThen(checkForUpdates("poll")),
860 Effect.forever,
861 Effect.catchCause((cause) => {
862 if (Cause.hasInterruptsOnly(cause)) {
863 return Effect.void;
864 }
865 const error = new DesktopUpdatePollerError({ poller: "poll", cause });
866 return logUpdaterError(error.message, {
867 errorTag: error._tag,
868 cause: describeUpdateErrorCause(error.cause),
869 poller: error.poller,
870 });
871 }),
872 Effect.forkScoped,
873 );
874 }).pipe(Effect.withSpan("desktop.updates.startPollers"));
875​
876 const handleUpdateAvailable = Effect.fn("desktop.updates.handleUpdateAvailable")(function* (
877 raw: unknown,
878 ) {
879 yield* decodeUpdateInfo(raw).pipe(
880 Effect.flatMap(
881 Effect.fn("desktop.updates.applyUpdateAvailable")(function* (info) {
882 const state = yield* Ref.get(updateStateRef);
883 if (!(yield* offerable(info.version, state))) {
884 yield* logUpdaterInfo("ignoring update outside the selected channel or its floor", {
885 version: info.version,
886 channel: state.channel,
887 });
888 const checkedAt = yield* currentIsoTimestamp;
889 yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt));
890 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
891 return;
892 }
893​
894 const checkedAt = yield* currentIsoTimestamp;
895 const { releaseNotes, omittedReleaseCount } = normalizeDesktopUpdateReleaseNotes(
896 info.releaseNotes,
897 info.version,
898 state.channel,
899 info.releaseDate,
900 );
901 yield* setState(
902 reduceDesktopUpdateStateOnUpdateAvailable(
903 state,
904 info.version,
905 checkedAt,
906 releaseNotes,
907 omittedReleaseCount,
908 ),
909 );
910 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
911 yield* logUpdaterInfo("update available", {
912 version: info.version,
913 releaseNoteGroups: releaseNotes.length,
914 omittedReleaseCount,
915 });
916 }),
917 ),
918 Effect.catchCause((cause) => {
919 if (Cause.hasInterruptsOnly(cause)) {
920 return Effect.void;
921 }
922 const error = new DesktopUpdateEventHandlingError({ event: "update-available", cause });
923 return logUpdaterWarning(error.message, {
924 errorTag: error._tag,
925 cause: describeUpdateErrorCause(error.cause),
926 event: error.event,
927 });
928 }),
929 );
930 });
931​
932 const handleUpdateNotAvailable = Effect.gen(function* () {
933 const checkedAt = yield* currentIsoTimestamp;
934 const state = yield* Ref.get(updateStateRef);
935 yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt));
936 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
937 yield* logUpdaterInfo("no updates available");
938 }).pipe(Effect.withSpan("desktop.updates.handleUpdateNotAvailable"));
939​
940 const handleUpdaterError = Effect.fn("desktop.updates.handleUpdaterError")(function* (
941 cause: unknown,
942 ) {
943 const activeAction = yield* activeUpdateAction;
944 const error = new DesktopUpdaterReportedError({
945 operation: Option.match(activeAction, {
946 onNone: () => "background" as const,
947 onSome: (action) => (action === "install-recovery" ? "install" : action),
948 }),
949 cause,
950 });
951 if (Option.isSome(activeAction) && activeAction.value === "install") {
952 yield* recoverFailedInstall(error.message);
953 yield* logUpdaterError(error.message, {
954 errorTag: error._tag,
955 cause: describeUpdateErrorCause(error.cause),
956 operation: error.operation,
957 });
958 return;
959 }
960​
961 if (Option.isNone(activeAction)) {
962 const checkedAt = yield* currentIsoTimestamp;
963 yield* updateState((current) => ({
964 ...current,
965 status: "error",
966 message: error.message,
967 checkedAt,
968 downloadPercent: null,
969 errorContext: current.errorContext,
970 canRetry: getCanRetryFromState(current),
971 }));
972 }
973​
974 yield* logUpdaterError(error.message, {
975 errorTag: error._tag,
976 cause: describeUpdateErrorCause(error.cause),
977 operation: error.operation,
978 });
979 });
980​
981 const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
982 raw: unknown,
983 ) {
984 yield* decodeDownloadProgressInfo(raw).pipe(
985 Effect.flatMap(
986 Effect.fn("desktop.updates.applyDownloadProgress")(function* (progress) {
987 const state = yield* Ref.get(updateStateRef);
988 const percent = Math.floor(progress.percent);
989 if (shouldBroadcastDownloadProgress(state, progress.percent) || state.message !== null) {
990 yield* setState(reduceDesktopUpdateStateOnDownloadProgress(state, progress.percent));
991 }
992 const milestone = percent - (percent % 10);
993 const lastLoggedMilestone = yield* Ref.get(lastLoggedDownloadMilestoneRef);
994 if (milestone > lastLoggedMilestone) {
995 yield* Ref.set(lastLoggedDownloadMilestoneRef, milestone);
996 yield* logUpdaterInfo("download progress", { percent });
997 }
998 }),
999 ),
1000 Effect.catchCause((cause) => {
1001 if (Cause.hasInterruptsOnly(cause)) {
1002 return Effect.void;
1004 const error = new DesktopUpdateEventHandlingError({ event: "download-progress", cause });
1005 return logUpdaterWarning(error.message, {
1006 errorTag: error._tag,
1007 cause: describeUpdateErrorCause(error.cause),
1008 event: error.event,
1009 });
1010 }),
1011 );
1012 });
1013​
1014 const handleUpdateDownloaded = Effect.fn("desktop.updates.handleUpdateDownloaded")(function* (
1015 raw: unknown,
1016 ) {
1017 yield* decodeUpdateInfo(raw).pipe(
1018 Effect.flatMap(
1019 Effect.fn("desktop.updates.applyUpdateDownloaded")(function* (info) {
1020 const state = yield* Ref.get(updateStateRef);
1021 // A download can finish after its track switch moved on; never offer that build.
1022 if (!(yield* offerable(info.version, state))) {
1023 yield* logUpdaterInfo("ignoring download outside the selected channel or its floor", {
1024 version: info.version,
1025 channel: state.channel,
1026 });
1027 // Its progress events left the updater "downloading", which would block every check.
1028 if (state.status === "downloading") {
1029 yield* setState(
1030 reduceDesktopUpdateStateOnNoUpdate(state, yield* currentIsoTimestamp),
1031 );
1033 return;
1035 yield* setState(reduceDesktopUpdateStateOnDownloadComplete(state, info.version));
1036 yield* logUpdaterInfo("update downloaded", { version: info.version });
1037 }),
1038 ),
1039 Effect.catchCause((cause) => {
1040 if (Cause.hasInterruptsOnly(cause)) {
1041 return Effect.void;
1043 const error = new DesktopUpdateEventHandlingError({ event: "update-downloaded", cause });
1044 return logUpdaterWarning(error.message, {
1045 errorTag: error._tag,
1046 cause: describeUpdateErrorCause(error.cause),
1047 event: error.event,
1048 });
1049 }),
1050 );
1051 });
1052​
1053 return DesktopUpdates.of({
1054 getState: Ref.get(updateStateRef),
1055 isActionActive: activeUpdateAction.pipe(Effect.map(Option.isSome)),
1056 isInstallActive: activeUpdateAction.pipe(
1057 Effect.map((action) => Option.isSome(action) && action.value === "install"),
1058 ),
1059 subscribe: stateMutex.withPermits(1)(
1060 Effect.gen(function* () {
1061 const subscription = yield* PubSub.subscribe(stateChanges);
1062 const latest = yield* Ref.get(updateStateRef);
1063 return { latest, changes: Stream.fromSubscription(subscription) };
1064 }),
1065 ),
1066 emitState,
1067 disabledReason: resolveDisabledReason,
1068 configure: Effect.gen(function* () {
1069 const context = yield* Effect.context<never>();
1070 const runEffect = (effect: Effect.Effect<void>) => {
1071 void Effect.runPromiseWith(context)(effect);
1072 };
1073​
1074 const appUpdateYmlConfig = yield* readAppUpdateYml;
1075 yield* Ref.set(appUpdateYmlConfigRef, appUpdateYmlConfig);
1076​
1077 const notAppliedVersion = yield* readNotAppliedInstallVersion;
1078 yield* Ref.set(notAppliedVersionRef, notAppliedVersion);
1079 if (Option.isSome(notAppliedVersion)) {
1080 yield* logUpdaterWarning("the last update install did not apply", {
1081 version: environment.appVersion,
1082 targetVersion: notAppliedVersion.value,
1083 });
1085​
1086 if (config.mockUpdates) {
1087 yield* electronUpdater.setFeedURL({
1088 provider: "generic",
1089 url: `http://localhost:${config.mockUpdateServerPort}`,
1090 } as ElectronUpdater.ElectronUpdaterFeedUrl);
1092​
1093 const settings = yield* desktopSettings.get;
1094 const disabledReason = yield* resolveDisabledReason;
1095 yield* setState(yield* baseUpdateState(settings.updateChannel, disabledReason));
1096 if (Option.isSome(disabledReason)) {
1097 return;
1099 yield* Ref.set(updaterConfiguredRef, true);
1100​
1101 yield* electronUpdater.setAutoDownload(false);
1102 yield* electronUpdater.setAutoInstallOnAppQuit(false);
1103 yield* applyAutoUpdaterChannel(settings.updateChannel);
1104 yield* electronUpdater.setDisableDifferentialDownload(
1105 isArm64HostRunningIntelBuild(environment.runtimeInfo),
1106 );
1107​
1108 if (isArm64HostRunningIntelBuild(environment.runtimeInfo)) {
1109 yield* logUpdaterInfo(
1110 "Apple Silicon host detected while running Intel build; updates will switch to arm64 packages",
1111 );
1113​
1114 yield* electronUpdater.on("checking-for-update", () => {
1115 runEffect(
1116 logUpdaterInfo("looking for updates").pipe(
1117 Effect.withSpan("desktop.updates.handleCheckingForUpdate"),
1118 ),
1119 );
1120 });
1121 yield* electronUpdater.on("update-available", (info: unknown) => {
1122 runEffect(handleUpdateAvailable(info));
1123 });
1124 yield* electronUpdater.on("update-not-available", () => {
1125 runEffect(handleUpdateNotAvailable);
1126 });
1127 yield* electronUpdater.on("error", (error: unknown) => {
1128 runEffect(handleUpdaterError(error));
1129 });
1130 yield* electronUpdater.on("download-progress", (progress: unknown) => {
1131 runEffect(handleDownloadProgress(progress));
1132 });
1133 yield* electronUpdater.on("update-downloaded", (info: unknown) => {
1134 runEffect(handleUpdateDownloaded(info));
1135 });
1136​
1137 yield* startUpdatePollers;
1138 }).pipe(Effect.withSpan("desktop.updates.configure")),
1139 setChannel: Effect.fn("desktop.updates.setChannel")(function* (
1140 nextChannel: DesktopUpdateChannel,
1141 options?: { readonly minimumVersion?: string | undefined },
1142 ) {
1143 yield* Effect.annotateCurrentSpan({ channel: nextChannel });
1144 // A background check holds the updater only briefly, so wait it out instead of refusing.
1145 const activeAction = yield* tryStartChannelChange.pipe(
1146 Effect.repeat({
1147 while: (active) => Option.isSome(active) && active.value === "check",
1148 schedule: Schedule.spaced(CHANNEL_CHANGE_RETRY_DELAY),
1149 times: CHANNEL_CHANGE_RETRIES,
1150 }),
1151 );
1152 if (Option.isSome(activeAction)) {
1153 return yield* new DesktopUpdateActionInProgressError({
1154 action: activeAction.value === "install-recovery" ? "install" : activeAction.value,
1155 requestedChannel: nextChannel,
1156 });
1158​
1159 return yield* Effect.gen(function* () {
1160 yield* Ref.set(releaseFloorRef, Option.fromNullishOr(options?.minimumVersion));
1161 const state = yield* Ref.get(updateStateRef);
1162 const retained = state.downloadedVersion ?? state.availableVersion;
1163 // A build from another track re-checks, so retrying a track switch finds an older release.
1164 // So does a retained offer below the new floor, which must not install.
1165 if (
1166 nextChannel === state.channel &&
1167 nextChannel === desktopUpdateChannelOf(environment.appVersion) &&
1168 (retained === null || (yield* offerable(retained, state)))
1169 ) {
1170 return state;
1172​
1173 yield* desktopSettings
1174 .setUpdateChannel(nextChannel)
1175 .pipe(
1176 Effect.mapError(
1177 (cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }),
1178 ),
1179 );
1180​
1181 const disabledReason = yield* resolveDisabledReason;
1182 yield* setState(yield* baseUpdateState(nextChannel, disabledReason));
1183​
1184 if (Option.isSome(disabledReason) || !(yield* Ref.get(updaterConfiguredRef))) {
1185 return yield* Ref.get(updateStateRef);
1187​
1188 yield* applyAutoUpdaterChannel(nextChannel);
1189 // Only leaving the running build's track can need an older release.
1190 yield* checkForUpdates(
1191 "channel-change",
1192 "held",
1193 nextChannel !== desktopUpdateChannelOf(environment.appVersion),
1194 );
1195 return yield* Ref.get(updateStateRef);
1196 }).pipe(Effect.ensuring(finishUpdateAction("channel")));
1197 }),
1198 check: Effect.fn("desktop.updates.check")(function* (
1199 reason: string,
1200 options?: { readonly allowDowngrade?: boolean },
1201 ) {
1202 yield* Effect.annotateCurrentSpan({ reason });
1203 if (!(yield* Ref.get(updaterConfiguredRef))) {
1204 return {
1205 checked: false,
1206 state: yield* Ref.get(updateStateRef),
1207 };
1209 const checked = yield* checkForUpdates(reason, "acquire", options?.allowDowngrade === true);
1210 return {
1211 checked,
1212 state: yield* Ref.get(updateStateRef),
1213 };
1214 }),
1215 download: Effect.gen(function* () {
1216 const result = yield* downloadAvailableUpdate;
1217 return {
1218 accepted: result.accepted,
1219 completed: result.completed,
1220 state: yield* Ref.get(updateStateRef),
1221 };
1222 }).pipe(Effect.withSpan("desktop.updates.download")),
1223 install: installWithExpectedVersion().pipe(
1224 Effect.map(({ accepted, completed, state }) => ({ accepted, completed, state })),
1225 ),
1226 installPrepared: Effect.fn("DesktopUpdates.installPrepared")(function (expectedVersion) {
1227 return installWithExpectedVersion(expectedVersion);
1228 }),
1229 });
1230});
1231​
1232export const layer = Layer.effect(DesktopUpdates, make);