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

DesktopUpdates.ts

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