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

DesktopUpdates.ts

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