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

DesktopUpdates.ts

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