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

DesktopUpdates.ts

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