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

DesktopUpdates.ts

1,347 lines51.6 KB

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