Open History to see the last commit
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;
69}
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 }
108}
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 }
120}
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 }
132}
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 }
144}
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 }
156}
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 }
168}
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 }
180}
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);
243}
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}`;
275}
276
277export function describeUpdateErrorCause(cause: unknown): string {
278 try {
279 return summarizeCause(cause, 0).slice(0, 1024);
280 } catch {
281 return "UnknownError";
282 }
283}
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 );
298}
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 };
312}
313
314function getCanRetryFromState(state: DesktopUpdateState): boolean {
315 return state.availableVersion !== null || state.downloadedVersion !== null;
316}
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;
334}
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;
362}
363
364function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean {
365 return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
366}
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 yield* updateState((current) =>
618 reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
619 );
620 yield* logUpdaterError(error.message, {
621 errorTag: error._tag,
622 cause: describeUpdateErrorCause(error.cause),
623 channel: error.channel,
624 });
625 return { accepted: true, completed: false };
626 },
627 ),
628 }),
629 Effect.onInterrupt(() =>
630 updateState((current) => (current.status === "downloading" ? state : current)).pipe(
631 Effect.asVoid,
632 ),
633 ),
634 Effect.catchCause((cause) => {
635 if (Cause.hasInterruptsOnly(cause)) {
636 return Effect.failCause(cause);
637 }
638 const error = new DesktopUpdateUnexpectedActionError({ action: "download", cause });
639 return Effect.gen(function* () {
640 yield* updateState((current) =>
641 reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
642 );
643 yield* logUpdaterError(error.message, {
644 errorTag: error._tag,
645 cause: describeUpdateErrorCause(error.cause),
646 action: error.action,
647 });
648 return { accepted: true, completed: false };
649 });
650 }),
651 Effect.ensuring(finishUpdateAction("download")),
652 );
653 }).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate"));
654
655 const updateRestartMarkerDir = environment.path.join(environment.baseDir, "runtime");
656 const updateRestartMarkerPath = environment.path.join(
657 updateRestartMarkerDir,
658 DESKTOP_UPDATE_RESTART_MARKER_FILE,
659 );
660 const writeUpdateRestartMarker = fileSystem
661 .makeDirectory(updateRestartMarkerDir, { recursive: true })
662 .pipe(
663 Effect.andThen(fileSystem.writeFileString(updateRestartMarkerPath, "")),
664 Effect.catch((error) =>
665 logUpdaterWarning("Could not write the update restart marker.", { errorTag: error._tag }),
666 ),
667 );
668
669 // Failed or interrupted installs leave no replacement backend; later quits must release the tunnel.
670 const removeUpdateRestartMarker = fileSystem
671 .remove(updateRestartMarkerPath, { force: true })
672 .pipe(Effect.ignore);
673
674 const installRecordPath = environment.path.join(
675 updateRestartMarkerDir,
676 DESKTOP_UPDATE_INSTALL_RECORD_FILE,
677 );
678 const writeInstallRecord = (targetVersion: string) =>
679 encodeInstallRecord({ fromVersion: environment.appVersion, targetVersion }).pipe(
680 Effect.flatMap((text) => fileSystem.writeFileString(installRecordPath, text)),
681 Effect.catch((error) =>
682 logUpdaterWarning("Could not record the update install.", { errorTag: error._tag }),
683 ),
684 );
685 const removeInstallRecord = fileSystem
686 .remove(installRecordPath, { force: true })
687 .pipe(Effect.ignore);
688
689 const readNotAppliedInstallVersion = fileSystem.readFileString(installRecordPath).pipe(
690 Effect.flatMap(decodeInstallRecord),
691 Effect.option,
692 Effect.map((record) =>
693 Option.flatMap(record, (value) =>
694 Option.fromNullishOr(resolveNotAppliedInstallVersion(value, environment.appVersion)),
695 ),
696 ),
697 Effect.tap((notAppliedVersion) =>
698 Option.isNone(notAppliedVersion) ? removeInstallRecord : Effect.void,
699 ),
700 );
701
702 const baseUpdateState = (channel: DesktopUpdateChannel, disabledReason: Option.Option<string>) =>
703 Ref.get(notAppliedVersionRef).pipe(
704 Effect.map((notAppliedVersion) => ({
705 ...createBaseUpdateState(channel, disabledReason, environment),
706 // Callers fall back to the channel's reason only when nothing else turns updates off.
707 ...(Option.isSome(disabledReason) &&
708 disabledReason.value === Option.getOrUndefined(channelBlockedReason(channel))
709 ? { channelBlockedByPolicy: true as const }
710 : {}),
711 ...Option.match(notAppliedVersion, {
712 onNone: () => ({}),
713 onSome: (version) => ({ notAppliedVersion: version }),
714 }),
715 })),
716 );
717
718 const resetInstallAction = Effect.all(
719 [
720 finishUpdateAction("install"),
721 Ref.set(desktopState.quitting, false),
722 Ref.set(installRunningBackendsRef, []),
723 removeUpdateRestartMarker,
724 removeInstallRecord,
725 ],
726 { discard: true },
727 );
728
729 const recoverFailedInstall = Effect.fn("desktop.updates.recoverFailedInstall")(function* (
730 message: string,
731 ) {
732 const ownsRecovery = yield* Ref.modify(activeUpdateActionRef, (activeAction) =>
733 Option.isSome(activeAction) && activeAction.value === "install"
734 ? ([true, Option.some<UpdateAction>("install-recovery")] as const)
735 : ([false, activeAction] as const),
736 );
737 if (!ownsRecovery) return;
738
739 yield* Ref.set(desktopState.quitting, false);
740 yield* removeUpdateRestartMarker;
741 yield* removeInstallRecord;
742 yield* Effect.gen(function* () {
743 const runningInstances = yield* Ref.getAndSet(installRunningBackendsRef, []);
744 const instances = (yield* pool.list).filter((instance) =>
745 runningInstances.includes(instance),
746 );
747 const restartExit = yield* Effect.forEach(instances, (instance) => instance.start, {
748 concurrency: "unbounded",
749 discard: true,
750 }).pipe(Effect.exit);
751 yield* updateState((current) => reduceDesktopUpdateStateOnInstallFailure(current, message));
752 if (Exit.isFailure(restartExit)) {
753 yield* logUpdaterError("Desktop update install recovery could not restart every backend.");
754 }
755 }).pipe(
756 Effect.catchCause(() =>
757 logUpdaterError("Desktop update install recovery failed unexpectedly."),
758 ),
759 Effect.ensuring(finishUpdateAction("install-recovery")),
760 );
761 });
762
763 const installDownloadedUpdate = (expectedVersion?: string) =>
764 Effect.scoped(
765 Effect.gen(function* () {
766 const actionCompletions = yield* PubSub.subscribe(finishedUpdateActions);
767 let admission: "admitted" | "refused" | "wait-for-check" = "wait-for-check";
768 while (admission === "wait-for-check") {
769 admission = yield* stateMutex.withPermits(1)(
770 Effect.gen(function* () {
771 const state = yield* Ref.get(updateStateRef);
772 const activeAction = yield* Ref.get(activeUpdateActionRef);
773 const hasExpectedDownload =
774 state.downloadedVersion !== null &&
775 (expectedVersion === undefined || state.downloadedVersion === expectedVersion);
776 if (
777 (yield* Ref.get(desktopState.quitting)) ||
778 !(yield* Ref.get(updaterConfiguredRef)) ||
779 !hasExpectedDownload
780 ) {
781 return "refused" as const;
782 }
783 if (Option.isSome(activeAction)) {
784 return activeAction.value === "check" && expectedVersion !== undefined
785 ? ("wait-for-check" as const)
786 : ("refused" as const);
787 }
788 const hasInstallableDownload =
789 state.status === "downloaded" ||
790 (state.status === "error" &&
791 (state.errorContext === null || state.errorContext === "install"));
792 if (!hasInstallableDownload) return "refused" as const;
793 return (yield* tryStartUpdateAction("install"))
794 ? ("admitted" as const)
795 : ("refused" as const);
796 }),
797 );
798 if (admission === "wait-for-check") {
799 const finishedAction = yield* PubSub.take(actionCompletions).pipe(
800 Effect.timeoutOption(PREPARED_INSTALL_CHECK_WAIT),
801 );
802 if (Option.isNone(finishedAction)) {
803 admission = "refused";
804 }
805 }
806 }
807 if (admission === "refused") {
808 return { accepted: false, completed: false, failed: false };
809 }
810
811 yield* Ref.set(desktopState.quitting, true);
812 yield* Ref.set(installRunningBackendsRef, []);
813
814 return yield* Effect.gen(function* () {
815 yield* writeUpdateRestartMarker;
816 const { downloadedVersion } = yield* Ref.get(updateStateRef);
817 if (downloadedVersion !== null) yield* writeInstallRecord(downloadedVersion);
818 // Stop pooled backends before quitAndInstall can outrun their scope finalizers.
819 const instances = yield* pool.list;
820 // stop clears desiredRunning, so retain the recovery set beforehand.
821 const runningInstances = yield* Effect.filter(instances, (instance) =>
822 instance.snapshot.pipe(Effect.map((snapshot) => snapshot.desiredRunning)),
823 );
824 yield* Ref.set(installRunningBackendsRef, runningInstances);
825 yield* Effect.forEach(
826 instances,
827 (instance) =>
828 instance.stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT }),
829 { concurrency: "unbounded" },
830 );
831 yield* electronUpdater.quitAndInstall({
832 isSilent: true,
833 isForceRunAfter: true,
834 });
835 return { accepted: true, completed: false, failed: false };
836 }).pipe(
837 Effect.catchTags({
838 ElectronUpdaterQuitAndInstallError: Effect.fn("desktop.updates.handleInstallFailure")(
839 function* (error) {
840 yield* recoverFailedInstall(error.message);
841 yield* logUpdaterError(error.message, {
842 errorTag: error._tag,
843 cause: describeUpdateErrorCause(error.cause),
844 channel: error.channel,
845 isSilent: error.isSilent,
846 isForceRunAfter: error.isForceRunAfter,
847 });
848 return { accepted: true, completed: false, failed: true };
849 },
850 ),
851 }),
852 Effect.onInterrupt(() => resetInstallAction),
853 Effect.catchCause((cause) =>
854 Effect.gen(function* () {
855 if (Cause.hasInterruptsOnly(cause)) {
856 return yield* Effect.failCause(cause);
857 }
858 const error = new DesktopUpdateUnexpectedActionError({ action: "install", cause });
859 yield* recoverFailedInstall(error.message);
860 yield* logUpdaterError(error.message, {
861 errorTag: error._tag,
862 cause: describeUpdateErrorCause(error.cause),
863 action: error.action,
864 });
865 return { accepted: true, completed: false, failed: true };
866 }),
867 ),
868 );
869 }),
870 ).pipe(Effect.withSpan("desktop.updates.installDownloadedUpdate"));
871
872 const installWithExpectedVersion = Effect.fn("desktop.updates.install")(function* (
873 expectedVersion?: string,
874 ) {
875 if (yield* Ref.get(desktopState.quitting)) {
876 return {
877 accepted: false,
878 completed: false,
879 failed: false,
880 state: yield* Ref.get(updateStateRef),
881 };
882 }
883 const result = yield* installDownloadedUpdate(expectedVersion);
884 return {
885 accepted: result.accepted,
886 completed: result.completed,
887 failed: result.failed,
888 state: yield* Ref.get(updateStateRef),
889 };
890 });
891
892 const startUpdatePollers: Effect.Effect<void, never, Scope.Scope> = Effect.gen(function* () {
893 yield* Effect.sleep(AUTO_UPDATE_STARTUP_DELAY).pipe(
894 Effect.andThen(checkForUpdates("startup")),
895 Effect.catchCause((cause) => {
896 if (Cause.hasInterruptsOnly(cause)) {
897 return Effect.void;
898 }
899 const error = new DesktopUpdatePollerError({ poller: "startup", cause });
900 return logUpdaterError(error.message, {
901 errorTag: error._tag,
902 cause: describeUpdateErrorCause(error.cause),
903 poller: error.poller,
904 });
905 }),
906 Effect.forkScoped,
907 );
908 yield* Effect.sleep(AUTO_UPDATE_POLL_INTERVAL).pipe(
909 Effect.andThen(checkForUpdates("poll")),
910 Effect.forever,
911 Effect.catchCause((cause) => {
912 if (Cause.hasInterruptsOnly(cause)) {
913 return Effect.void;
914 }
915 const error = new DesktopUpdatePollerError({ poller: "poll", cause });
916 return logUpdaterError(error.message, {
917 errorTag: error._tag,
918 cause: describeUpdateErrorCause(error.cause),
919 poller: error.poller,
920 });
921 }),
922 Effect.forkScoped,
923 );
924 }).pipe(Effect.withSpan("desktop.updates.startPollers"));
925
926 const handleUpdateAvailable = Effect.fn("desktop.updates.handleUpdateAvailable")(function* (
927 raw: unknown,
928 ) {
929 yield* decodeUpdateInfo(raw).pipe(
930 Effect.flatMap(
931 Effect.fn("desktop.updates.applyUpdateAvailable")(function* (info) {
932 const state = yield* Ref.get(updateStateRef);
933 if (!(yield* offerable(info.version, state))) {
934 yield* logUpdaterInfo("ignoring update outside the selected channel or its floor", {
935 version: info.version,
936 channel: state.channel,
937 });
938 const checkedAt = yield* currentIsoTimestamp;
939 yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt));
940 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
941 return;
942 }
943
944 const checkedAt = yield* currentIsoTimestamp;
945 const { releaseNotes, omittedReleaseCount } = normalizeDesktopUpdateReleaseNotes(
946 releaseNotesOfOfferedVersion(info),
947 info.version,
948 state.channel,
949 info.releaseDate,
950 );
951 yield* setState(
952 reduceDesktopUpdateStateOnUpdateAvailable(
953 state,
954 info.version,
955 checkedAt,
956 releaseNotes,
957 omittedReleaseCount,
958 ),
959 );
960 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
961 yield* logUpdaterInfo("update available", {
962 version: info.version,
963 releaseNoteGroups: releaseNotes.length,
964 omittedReleaseCount,
965 });
966 }),
967 ),
968 Effect.catchCause((cause) => {
969 if (Cause.hasInterruptsOnly(cause)) {
970 return Effect.void;
971 }
972 const error = new DesktopUpdateEventHandlingError({ event: "update-available", cause });
973 return logUpdaterWarning(error.message, {
974 errorTag: error._tag,
975 cause: describeUpdateErrorCause(error.cause),
976 event: error.event,
977 });
978 }),
979 );
980 });
981
982 const handleUpdateNotAvailable = Effect.gen(function* () {
983 const checkedAt = yield* currentIsoTimestamp;
984 const state = yield* Ref.get(updateStateRef);
985 yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt));
986 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
987 yield* logUpdaterInfo("no updates available");
988 }).pipe(Effect.withSpan("desktop.updates.handleUpdateNotAvailable"));
989
990 const handleUpdaterError = Effect.fn("desktop.updates.handleUpdaterError")(function* (
991 cause: unknown,
992 ) {
993 const activeAction = yield* activeUpdateAction;
994 const error = new DesktopUpdaterReportedError({
995 operation: Option.match(activeAction, {
996 onNone: () => "background" as const,
997 onSome: (action) => (action === "install-recovery" ? "install" : action),
998 }),
999 cause,
1000 });
1001 if (Option.isSome(activeAction) && activeAction.value === "install") {
1002 yield* recoverFailedInstall(error.message);
1003 yield* logUpdaterError(error.message, {
1004 errorTag: error._tag,
1005 cause: describeUpdateErrorCause(error.cause),
1006 operation: error.operation,
1007 });
1008 return;
1009 }
1010
1011 if (Option.isNone(activeAction)) {
1012 const checkedAt = yield* currentIsoTimestamp;
1013 yield* updateState((current) => ({
1014 ...current,
1015 status: "error",
1016 message: error.message,
1017 checkedAt,
1018 downloadPercent: null,
1019 errorContext: current.errorContext,
1020 canRetry: getCanRetryFromState(current),
1021 }));
1022 }
1023
1024 yield* logUpdaterError(error.message, {
1025 errorTag: error._tag,
1026 cause: describeUpdateErrorCause(error.cause),
1027 operation: error.operation,
1028 });
1029 });
1030
1031 const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
1032 raw: unknown,
1033 ) {
1034 yield* decodeDownloadProgressInfo(raw).pipe(
1035 Effect.flatMap(
1036 Effect.fn("desktop.updates.applyDownloadProgress")(function* (progress) {
1037 const state = yield* Ref.get(updateStateRef);
1038 const percent = Math.floor(progress.percent);
1039 if (shouldBroadcastDownloadProgress(state, progress.percent) || state.message !== null) {
1040 yield* setState(reduceDesktopUpdateStateOnDownloadProgress(state, progress.percent));
1041 }
1042 const milestone = percent - (percent % 10);
1043 const lastLoggedMilestone = yield* Ref.get(lastLoggedDownloadMilestoneRef);
1044 if (milestone > lastLoggedMilestone) {
1045 yield* Ref.set(lastLoggedDownloadMilestoneRef, milestone);
1046 yield* logUpdaterInfo("download progress", { percent });
1047 }
1048 }),
1049 ),
1050 Effect.catchCause((cause) => {
1051 if (Cause.hasInterruptsOnly(cause)) {
1052 return Effect.void;
1053 }
1054 const error = new DesktopUpdateEventHandlingError({ event: "download-progress", cause });
1055 return logUpdaterWarning(error.message, {
1056 errorTag: error._tag,
1057 cause: describeUpdateErrorCause(error.cause),
1058 event: error.event,
1059 });
1060 }),
1061 );
1062 });
1063
1064 const handleUpdateDownloaded = Effect.fn("desktop.updates.handleUpdateDownloaded")(function* (
1065 raw: unknown,
1066 ) {
1067 yield* decodeUpdateInfo(raw).pipe(
1068 Effect.flatMap(
1069 Effect.fn("desktop.updates.applyUpdateDownloaded")(function* (info) {
1070 const state = yield* Ref.get(updateStateRef);
1071 // A download can finish after its track switch moved on; never offer that build.
1072 if (!(yield* offerable(info.version, state))) {
1073 yield* logUpdaterInfo("ignoring download outside the selected channel or its floor", {
1074 version: info.version,
1075 channel: state.channel,
1076 });
1077 // Its progress events left the updater "downloading", which would block every check.
1078 if (state.status === "downloading") {
1079 yield* setState(
1080 reduceDesktopUpdateStateOnNoUpdate(state, yield* currentIsoTimestamp),
1081 );
1082 }
1083 return;
1084 }
1085 yield* setState(reduceDesktopUpdateStateOnDownloadComplete(state, info.version));
1086 yield* logUpdaterInfo("update downloaded", { version: info.version });
1087 }),
1088 ),
1089 Effect.catchCause((cause) => {
1090 if (Cause.hasInterruptsOnly(cause)) {
1091 return Effect.void;
1092 }
1093 const error = new DesktopUpdateEventHandlingError({ event: "update-downloaded", cause });
1094 return logUpdaterWarning(error.message, {
1095 errorTag: error._tag,
1096 cause: describeUpdateErrorCause(error.cause),
1097 event: error.event,
1098 });
1099 }),
1100 );
1101 });
1102
1103 return DesktopUpdates.of({
1104 getState: Ref.get(updateStateRef),
1105 isActionActive: activeUpdateAction.pipe(Effect.map(Option.isSome)),
1106 isInstallActive: activeUpdateAction.pipe(
1107 Effect.map((action) => Option.isSome(action) && action.value === "install"),
1108 ),
1109 subscribe: stateMutex.withPermits(1)(
1110 Effect.gen(function* () {
1111 const subscription = yield* PubSub.subscribe(stateChanges);
1112 const latest = yield* Ref.get(updateStateRef);
1113 return { latest, changes: Stream.fromSubscription(subscription) };
1114 }),
1115 ),
1116 emitState,
1117 disabledReason: Ref.get(updateStateRef).pipe(
1118 Effect.flatMap((state) => resolveStateDisabledReason(state.channel)),
1119 ),
1120 configure: Effect.gen(function* () {
1121 const context = yield* Effect.context<never>();
1122 const runEffect = (effect: Effect.Effect<void>) => {
1123 void Effect.runPromiseWith(context)(effect);
1124 };
1125
1126 const appUpdateYmlConfig = yield* readAppUpdateYml;
1127 yield* Ref.set(appUpdateYmlConfigRef, appUpdateYmlConfig);
1128
1129 const notAppliedVersion = yield* readNotAppliedInstallVersion;
1130 yield* Ref.set(notAppliedVersionRef, notAppliedVersion);
1131 if (Option.isSome(notAppliedVersion)) {
1132 yield* logUpdaterWarning("the last update install did not apply", {
1133 version: environment.appVersion,
1134 targetVersion: notAppliedVersion.value,
1135 });
1136 }
1137
1138 if (mockUpdates) {
1139 yield* electronUpdater.setFeedURL({
1140 provider: "generic",
1141 url: `http://localhost:${config.mockUpdateServerPort}`,
1142 } as ElectronUpdater.ElectronUpdaterFeedUrl);
1143 } else if (policy.feedUrl !== undefined) {
1144 // The administrator's mirror replaces the GitHub feed baked into app-update.yml.
1145 yield* electronUpdater.setFeedURL({
1146 provider: "generic",
1147 url: policy.feedUrl,
1148 } as ElectronUpdater.ElectronUpdaterFeedUrl);
1149 }
1150
1151 const settings = yield* desktopSettings.get;
1152 const disabledReason = yield* resolveDisabledReason;
1153 yield* setState(
1154 yield* baseUpdateState(
1155 settings.updateChannel,
1156 Option.orElse(disabledReason, () => channelBlockedReason(settings.updateChannel)),
1157 ),
1158 );
1159 if (Option.isSome(disabledReason)) {
1160 return;
1161 }
1162 yield* Ref.set(updaterConfiguredRef, true);
1163
1164 yield* electronUpdater.setAutoDownload(false);
1165 yield* electronUpdater.setAutoInstallOnAppQuit(false);
1166 yield* applyAutoUpdaterChannel(settings.updateChannel);
1167 yield* electronUpdater.setDisableDifferentialDownload(
1168 isArm64HostRunningIntelBuild(environment.runtimeInfo),
1169 );
1170
1171 if (isArm64HostRunningIntelBuild(environment.runtimeInfo)) {
1172 yield* logUpdaterInfo(
1173 "Apple Silicon host detected while running Intel build; updates will switch to arm64 packages",
1174 );
1175 }
1176
1177 yield* electronUpdater.on("checking-for-update", () => {
1178 runEffect(
1179 logUpdaterInfo("looking for updates").pipe(
1180 Effect.withSpan("desktop.updates.handleCheckingForUpdate"),
1181 ),
1182 );
1183 });
1184 yield* electronUpdater.on("update-available", (info: unknown) => {
1185 runEffect(handleUpdateAvailable(info));
1186 });
1187 yield* electronUpdater.on("update-not-available", () => {
1188 runEffect(handleUpdateNotAvailable);
1189 });
1190 yield* electronUpdater.on("error", (error: unknown) => {
1191 runEffect(handleUpdaterError(error));
1192 });
1193 yield* electronUpdater.on("download-progress", (progress: unknown) => {
1194 runEffect(handleDownloadProgress(progress));
1195 });
1196 yield* electronUpdater.on("update-downloaded", (info: unknown) => {
1197 runEffect(handleUpdateDownloaded(info));
1198 });
1199
1200 yield* startUpdatePollers;
1201 }).pipe(Effect.withSpan("desktop.updates.configure")),
1202 setChannel: Effect.fn("desktop.updates.setChannel")(function* (
1203 nextChannel: DesktopUpdateChannel,
1204 options?: { readonly minimumVersion?: string | undefined },
1205 ) {
1206 yield* Effect.annotateCurrentSpan({ channel: nextChannel });
1207 if (Option.isSome(channelBlockedReason(nextChannel))) {
1208 return yield* new DesktopUpdateChannelManagedError({
1209 channel: nextChannel,
1210 policyMessage: policy.message ?? "Your administrator manages T3 Code updates.",
1211 });
1212 }
1213 // A background check holds the updater only briefly, so wait it out instead of refusing.
1214 const activeAction = yield* tryStartChannelChange.pipe(
1215 Effect.repeat({
1216 while: (active) => Option.isSome(active) && active.value === "check",
1217 schedule: Schedule.spaced(CHANNEL_CHANGE_RETRY_DELAY),
1218 times: CHANNEL_CHANGE_RETRIES,
1219 }),
1220 );
1221 if (Option.isSome(activeAction)) {
1222 return yield* new DesktopUpdateActionInProgressError({
1223 action: activeAction.value === "install-recovery" ? "install" : activeAction.value,
1224 requestedChannel: nextChannel,
1225 });
1226 }
1227
1228 return yield* Effect.gen(function* () {
1229 yield* Ref.set(releaseFloorRef, Option.fromNullishOr(options?.minimumVersion));
1230 const state = yield* Ref.get(updateStateRef);
1231 const retained = state.downloadedVersion ?? state.availableVersion;
1232 // A build from another track re-checks, so retrying a track switch finds an older release.
1233 // So does a retained offer below the new floor, which must not install.
1234 if (
1235 nextChannel === state.channel &&
1236 nextChannel === desktopUpdateChannelOf(environment.appVersion) &&
1237 (retained === null || (yield* offerable(retained, state)))
1238 ) {
1239 return state;
1240 }
1241
1242 yield* desktopSettings
1243 .setUpdateChannel(nextChannel)
1244 .pipe(
1245 Effect.mapError(
1246 (cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }),
1247 ),
1248 );
1249
1250 const disabledReason = yield* resolveDisabledReason;
1251 yield* setState(yield* baseUpdateState(nextChannel, disabledReason));
1252
1253 if (Option.isSome(disabledReason) || !(yield* Ref.get(updaterConfiguredRef))) {
1254 return yield* Ref.get(updateStateRef);
1255 }
1256
1257 yield* applyAutoUpdaterChannel(nextChannel);
1258 // Only leaving the running build's track can need an older release.
1259 yield* checkForUpdates(
1260 "channel-change",
1261 "held",
1262 nextChannel !== desktopUpdateChannelOf(environment.appVersion),
1263 );
1264 return yield* Ref.get(updateStateRef);
1265 }).pipe(Effect.ensuring(finishUpdateAction("channel")));
1266 }),
1267 check: Effect.fn("desktop.updates.check")(function* (
1268 reason: string,
1269 options?: { readonly allowDowngrade?: boolean },
1270 ) {
1271 yield* Effect.annotateCurrentSpan({ reason });
1272 if (!(yield* Ref.get(updaterConfiguredRef))) {
1273 return {
1274 checked: false,
1275 state: yield* Ref.get(updateStateRef),
1276 };
1277 }
1278 const checked = yield* checkForUpdates(reason, "acquire", options?.allowDowngrade === true);
1279 return {
1280 checked,
1281 state: yield* Ref.get(updateStateRef),
1282 };
1283 }),
1284 download: Effect.gen(function* () {
1285 const result = yield* downloadAvailableUpdate;
1286 return {
1287 accepted: result.accepted,
1288 completed: result.completed,
1289 state: yield* Ref.get(updateStateRef),
1290 };
1291 }).pipe(Effect.withSpan("desktop.updates.download")),
1292 install: installWithExpectedVersion().pipe(
1293 Effect.map(({ accepted, completed, state }) => ({ accepted, completed, state })),
1294 ),
1295 installPrepared: Effect.fn("DesktopUpdates.installPrepared")(function (expectedVersion) {
1296 return installWithExpectedVersion(expectedVersion);
1297 }),
1298 });
1299});
1300
1301export const layer = Layer.effect(DesktopUpdates, make);