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

DesktopUpdates.ts

1,442 lines55.2 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 UPDATE_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 isOffered(state: DesktopUpdateState): boolean {
322 return state.status === "available" || state.status === "downloaded";
324​
325function shouldBroadcastDownloadProgress(
326 currentState: DesktopUpdateState,
327 nextPercent: number,
328): boolean {
329 if (currentState.status !== "downloading") {
330 return true;
331 }
332​
333 const currentPercent = currentState.downloadPercent;
334 if (currentPercent === null) {
335 return true;
336 }
337​
338 const previousStep = Math.floor(currentPercent / 10);
339 const nextStep = Math.floor(nextPercent / 10);
340 return nextStep !== previousStep || nextPercent === 100;
342​
343function getAutoUpdateDisabledReason(args: {
344 policy: DesktopUpdatePolicy.UpdatePolicy;
345 isDevelopment: boolean;
346 isPackaged: boolean;
347 platform: NodeJS.Platform;
348 appImage?: string | undefined;
349 isDebPackage: boolean;
350 disabledByEnv: boolean;
351 hasUpdateFeedConfig: boolean;
352}): string | null {
353 if (args.policy.mode === "off") {
354 return args.policy.message ?? "Updates are turned off on this machine.";
355 }
356 if (!args.hasUpdateFeedConfig) {
357 return "Automatic updates are not available because no update feed is configured.";
358 }
359 if (args.isDevelopment || !args.isPackaged) {
360 return "Automatic updates are only available in packaged production builds.";
361 }
362 if (args.disabledByEnv) {
363 return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
364 }
365 if (args.platform === "linux" && !args.appImage && !args.isDebPackage) {
366 return "Automatic updates on Linux require the AppImage or the .deb package.";
367 }
368 return null;
370​
371function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean {
372 return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
374​
375/** @public */
376export const make = Effect.gen(function* () {
377 const config = yield* DesktopConfig.DesktopConfig;
378 const pool = yield* DesktopBackendPool.DesktopBackendPool;
379 const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
380 const desktopState = yield* DesktopState.DesktopState;
381 const electronUpdater = yield* ElectronUpdater.ElectronUpdater;
382 const electronWindow = yield* ElectronWindow.ElectronWindow;
383 const environment = yield* DesktopEnvironment.DesktopEnvironment;
384 const fileSystem = yield* FileSystem.FileSystem;
385 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
386 const policy = yield* DesktopUpdatePolicy.DesktopUpdatePolicy;
387 // Any user can set the mock flag, so it never replaces an administrator's update source.
388 const mockUpdates = config.mockUpdates && policy.message === null;
389​
390 const appUpdateYmlConfigRef = yield* Ref.make<Option.Option<AppUpdateYmlConfig>>(Option.none());
391 const activeUpdateActionRef = yield* Ref.make<Option.Option<UpdateAction>>(Option.none());
392 const installRunningBackendsRef = yield* Ref.make<
393 ReadonlyArray<DesktopBackendPool.DesktopBackendInstance>
394 >([]);
395 const finishedUpdateActions = yield* PubSub.unbounded<UpdateAction>();
396 const updaterConfiguredRef = yield* Ref.make(false);
397 const lastLoggedDownloadMilestoneRef = yield* Ref.make(-1);
398 const notAppliedVersionRef = yield* Ref.make(Option.none<string>());
399 // The release a track switch's database check cleared. A build crosses to another track only
400 // through such a switch, and never below that release: version order alone cannot tell whether
401 // a Stable knows a Nightly's migrations.
402 const releaseFloorRef = yield* Ref.make(Option.none<string>());
403 const offerable = (version: string, state: DesktopUpdateState) =>
404 Ref.get(releaseFloorRef).pipe(
405 Effect.map(
406 (floor) =>
407 desktopUpdateChannelOf(version) === state.channel &&
408 (Option.isSome(floor)
409 ? compareSemverVersions(version, floor.value) >= 0
410 : desktopUpdateChannelOf(environment.appVersion) === state.channel),
411 ),
412 );
413 const updateStateRef = yield* Ref.make<DesktopUpdateState>(
414 createInitialDesktopUpdateState(
415 environment.appVersion,
416 environment.runtimeInfo,
417 environment.defaultDesktopSettings.updateChannel,
418 ),
419 );
420​
421 const stateChanges = yield* PubSub.sliding<DesktopUpdateState>(16);
422 // Serialize writes and publishes against subscription so snapshots cannot overlap the first change.
423 const stateMutex = yield* Semaphore.make(1);
424​
425 const emitState = Ref.get(updateStateRef).pipe(
426 Effect.flatMap((state) => electronWindow.sendAll(IpcChannels.UPDATE_STATE_CHANNEL, state)),
427 );
428​
429 const setState = (state: DesktopUpdateState): Effect.Effect<void> =>
430 stateMutex
431 .withPermits(1)(
432 Ref.set(updateStateRef, state).pipe(Effect.andThen(PubSub.publish(stateChanges, state))),
433 )
434 .pipe(Effect.andThen(emitState));
435​
436 const updateState = (
437 f: (state: DesktopUpdateState) => DesktopUpdateState,
438 ): Effect.Effect<DesktopUpdateState> =>
439 Ref.get(updateStateRef).pipe(
440 Effect.flatMap((state) => {
441 const nextState = f(state);
442 return setState(nextState).pipe(Effect.as(nextState));
443 }),
444 );
445​
446 const readAppUpdateYml = fileSystem.readFileString(environment.appUpdateYmlPath, "utf-8").pipe(
447 Effect.option,
448 Effect.flatMap(
449 Option.match({
450 onNone: () => Effect.succeed(Option.none<AppUpdateYmlConfig>()),
451 onSome: parseAppUpdateYml,
452 }),
453 ),
454 );
455​
456 // electron-updater uses this marker to install .deb updates with dpkg.
457 const isDebPackage =
458 environment.platform === "linux" && environment.isPackaged
459 ? yield* fileSystem
460 .readFileString(environment.path.join(environment.resourcesPath, "package-type"))
461 .pipe(
462 Effect.map((packageType) => packageType.trim() === "deb"),
463 Effect.orElseSucceed(() => false),
464 )
465 : false;
466​
467 const hasUpdateFeedConfig = Ref.get(appUpdateYmlConfigRef).pipe(
468 Effect.map(
469 (appUpdateYmlConfig) =>
470 Option.isSome(appUpdateYmlConfig) || mockUpdates || policy.feedUrl !== undefined,
471 ),
472 );
473​
474 const resolveDisabledReason = Effect.gen(function* () {
475 const hasFeedConfig = yield* hasUpdateFeedConfig;
476 return Option.fromNullishOr(
477 getAutoUpdateDisabledReason({
478 policy,
479 isDevelopment: environment.isDevelopment,
480 isPackaged: environment.isPackaged,
481 platform: environment.platform,
482 appImage: Option.getOrUndefined(config.appImagePath),
483 isDebPackage,
484 disabledByEnv: config.disableAutoUpdate,
485 hasUpdateFeedConfig: hasFeedConfig,
486 }),
487 );
488 });
489​
490 // Without nightly, an install on that channel stays put until its user picks stable: moving it
491 // silently would be a downgrade nobody asked for, and checking nightly would break the policy.
492 const channelBlockedReason = (channel: DesktopUpdateChannel): Option.Option<string> =>
493 channel === "nightly" && !policy.allowNightly
494 ? Option.some(
495 `${policy.message ?? "Nightly updates are turned off on this machine."} Switch to the stable channel to keep getting updates.`,
496 )
497 : Option.none();
498​
499 const resolveStateDisabledReason = (channel: DesktopUpdateChannel) =>
500 resolveDisabledReason.pipe(Effect.map(Option.orElse(() => channelBlockedReason(channel))));
501​
502 const activeUpdateAction = Ref.get(activeUpdateActionRef);
503​
504 const tryStartUpdateAction = (action: UpdateAction): Effect.Effect<boolean> =>
505 Ref.modify(activeUpdateActionRef, (activeAction) =>
506 Option.isSome(activeAction) ? [false, activeAction] : [true, Option.some(action)],
507 );
508​
509 const tryStartChannelChange = Ref.modify(activeUpdateActionRef, (activeAction) =>
510 Option.isSome(activeAction)
511 ? [activeAction, activeAction]
512 : [Option.none<UpdateAction>(), Option.some<UpdateAction>("channel")],
513 );
514​
515 const finishUpdateAction = (action: UpdateAction): Effect.Effect<void> =>
516 Ref.modify(activeUpdateActionRef, (activeAction) => {
517 const finished = Option.isSome(activeAction) && activeAction.value === action;
518 return [finished, finished ? Option.none() : activeAction] as const;
519 }).pipe(
520 Effect.flatMap((finished) =>
521 finished ? PubSub.publish(finishedUpdateActions, action).pipe(Effect.asVoid) : Effect.void,
522 ),
523 );
524​
525 // Re-runs admit after each finished action, so a caller waiting on a check decides on its result.
526 const admitAfterCheck = Effect.fn("desktop.updates.admitAfterCheck")(function* (
527 admit: Effect.Effect<"admitted" | "refused" | "wait-for-check">,
528 ) {
529 const actionCompletions = yield* PubSub.subscribe(finishedUpdateActions);
530 let admission = yield* stateMutex.withPermits(1)(admit);
531 while (admission === "wait-for-check") {
532 const finishedAction = yield* PubSub.take(actionCompletions).pipe(
533 Effect.timeoutOption(UPDATE_CHECK_WAIT),
534 );
535 admission = Option.isNone(finishedAction)
536 ? "refused"
537 : yield* stateMutex.withPermits(1)(admit);
538 }
539 return admission;
540 });
541​
542 const applyAutoUpdaterChannel = Effect.fn("desktop.updates.applyAutoUpdaterChannel")(function* (
543 channel: DesktopUpdateChannel,
544 ) {
545 yield* Effect.annotateCurrentSpan({ channel });
546 const allowsPrerelease = channel === "nightly";
547 yield* electronUpdater.setChannel(channel);
548 yield* electronUpdater.setAllowPrerelease(allowsPrerelease);
549 // An older build can lack migrations this one ran. Only a guarded track switch's own check
550 // may offer one.
551 yield* electronUpdater.setAllowDowngrade(false);
552 yield* electronUpdater.setFullChangelog(allowsPrerelease);
553 yield* logUpdaterInfo("using update channel", {
554 channel,
555 allowPrerelease: allowsPrerelease,
556 fullChangelog: allowsPrerelease,
557 });
558 });
559​
560 // The flag is shared updater state, so callers flip it only while holding a reservation.
561 const runUpdaterCheck = Effect.fn("desktop.updates.runUpdaterCheck")(function* (
562 allowDowngrade: boolean,
563 ) {
564 const restoreDowngrade = yield* electronUpdater.allowDowngrade;
565 if (allowDowngrade) yield* electronUpdater.setAllowDowngrade(true);
566 return yield* electronUpdater.checkForUpdates.pipe(
567 Effect.ensuring(electronUpdater.setAllowDowngrade(restoreDowngrade).pipe(Effect.ignore)),
568 );
569 });
570​
571 const checkForUpdates = Effect.fn("desktop.updates.checkForUpdates")(function* (
572 reason: string,
573 actionReservation: "acquire" | "held" = "acquire",
574 allowDowngrade = false,
575 ) {
576 yield* Effect.annotateCurrentSpan({ reason });
577 if (yield* Ref.get(desktopState.quitting)) return false;
578 if (!(yield* Ref.get(updaterConfiguredRef))) return false;
579​
580 const state = yield* Ref.get(updateStateRef);
581 // A configured updater is disabled only by a channel the managed policy blocks.
582 if (state.status === "disabled") return false;
583 if (state.status === "downloading") {
584 yield* logUpdaterInfo("skipping update check while update is active", {
585 reason,
586 status: state.status,
587 });
588 return false;
589 }
590​
591 if (actionReservation === "acquire" && !(yield* tryStartUpdateAction("check"))) return false;
592​
593 const check = Effect.gen(function* () {
594 // An offer stays on screen while re-checking, so finding it again changes nothing.
595 if (!isOffered(state)) {
596 yield* setState(reduceDesktopUpdateStateOnCheckStart(state, yield* currentIsoTimestamp));
597 }
598 yield* logUpdaterInfo("checking for updates", { reason });
599​
600 return yield* runUpdaterCheck(allowDowngrade).pipe(
601 Effect.as(true),
602 Effect.catchTags({
603 ElectronUpdaterCheckForUpdatesError: Effect.fn(
604 "desktop.updates.handleCheckForUpdatesFailure",
605 )(function* (error) {
606 const failedAt = yield* currentIsoTimestamp;
607 yield* updateState((current) =>
608 reduceDesktopUpdateStateOnCheckFailure(current, error.message, failedAt),
609 );
610 yield* logUpdaterError(error.message, {
611 errorTag: error._tag,
612 cause: describeUpdateErrorCause(error.cause),
613 channel: error.channel,
614 });
615 return true;
616 }),
617 }),
618 );
619 });
620​
621 return yield* actionReservation === "held"
622 ? check
623 : check.pipe(
624 Effect.onInterrupt(() => setState(state)),
625 Effect.ensuring(finishUpdateAction("check")),
626 );
627 });
628​
629 // Install refreshes before downloading, and a second check could pick a stale, older release.
630 const downloadAvailableUpdate = Effect.fn("desktop.updates.downloadAvailableUpdate")(function* (
631 refresh: boolean,
632 ) {
633 const admission = yield* Effect.scoped(
634 admitAfterCheck(
635 Effect.gen(function* () {
636 const state = yield* Ref.get(updateStateRef);
637 if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") {
638 return "refused" as const;
639 }
640 const activeAction = yield* Ref.get(activeUpdateActionRef);
641 if (Option.isSome(activeAction)) {
642 return activeAction.value === "check"
643 ? ("wait-for-check" as const)
644 : ("refused" as const);
645 }
646 return (yield* tryStartUpdateAction("download"))
647 ? ("admitted" as const)
648 : ("refused" as const);
649 }),
650 ),
651 );
652 if (admission === "refused") {
653 return { accepted: false, completed: false };
654 }
655​
656 const offered = yield* Ref.get(updateStateRef);
657 let state = offered;
658 return yield* Effect.gen(function* () {
659 if (refresh) {
660 // electron-updater downloads what its last check found, which can be hours old.
661 yield* logUpdaterInfo("checking for updates", { reason: "download" });
662 yield* runUpdaterCheck(
663 offered.channel !== desktopUpdateChannelOf(environment.appVersion),
664 ).pipe(
665 // A failed check keeps electron-updater's earlier result, so the known offer still downloads.
666 Effect.catchTags({
667 ElectronUpdaterCheckForUpdatesError: (error) =>
668 logUpdaterWarning(error.message, {
669 errorTag: error._tag,
670 cause: describeUpdateErrorCause(error.cause),
671 }),
672 }),
673 );
674 }
675 state = yield* Ref.get(updateStateRef);
676 if (state.status !== "available") {
677 return { accepted: true, completed: false };
678 }
679 yield* setState(reduceDesktopUpdateStateOnDownloadStart(state));
680 yield* electronUpdater.setDisableDifferentialDownload(
681 isArm64HostRunningIntelBuild(environment.runtimeInfo),
682 );
683 yield* logUpdaterInfo("downloading update");
684 yield* electronUpdater.downloadUpdate;
685 return { accepted: true, completed: true };
686 }).pipe(
687 Effect.catchTags({
688 ElectronUpdaterDownloadUpdateError: Effect.fn("desktop.updates.handleDownloadFailure")(
689 function* (error) {
690 const cause = describeUpdateErrorCause(error.cause);
691 yield* updateState((current) =>
692 reduceDesktopUpdateStateOnDownloadFailure(current, `${error.message} ${cause}`),
693 );
694 yield* logUpdaterError(error.message, {
695 errorTag: error._tag,
696 cause,
697 channel: error.channel,
698 });
699 return { accepted: true, completed: false };
700 },
701 ),
702 }),
703 Effect.onInterrupt(() =>
704 updateState((current) => (current.status === "downloading" ? state : current)).pipe(
705 Effect.asVoid,
706 ),
707 ),
708 Effect.catchCause((cause) => {
709 if (Cause.hasInterruptsOnly(cause)) {
710 return Effect.failCause(cause);
711 }
712 const error = new DesktopUpdateUnexpectedActionError({ action: "download", cause });
713 return Effect.gen(function* () {
714 yield* updateState((current) =>
715 reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
716 );
717 yield* logUpdaterError(error.message, {
718 errorTag: error._tag,
719 cause: describeUpdateErrorCause(error.cause),
720 action: error.action,
721 });
722 return { accepted: true, completed: false };
723 });
724 }),
725 Effect.ensuring(finishUpdateAction("download")),
726 );
727 });
728​
729 const updateRestartMarkerDir = environment.path.join(environment.baseDir, "runtime");
730 const updateRestartMarkerPath = environment.path.join(
731 updateRestartMarkerDir,
732 DESKTOP_UPDATE_RESTART_MARKER_FILE,
733 );
734 const writeUpdateRestartMarker = fileSystem
735 .makeDirectory(updateRestartMarkerDir, { recursive: true })
736 .pipe(
737 Effect.andThen(fileSystem.writeFileString(updateRestartMarkerPath, "")),
738 Effect.catch((error) =>
739 logUpdaterWarning("Could not write the update restart marker.", { errorTag: error._tag }),
740 ),
741 );
742​
743 const updateInProgressMarkerPath = environment.path.join(
744 updateRestartMarkerDir,
745 DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE,
746 );
747 const encodeUpdateMarker = Schema.encodeEffect(
748 Schema.fromJsonString(Schema.Struct({ startedAt: Schema.Number, expiresAt: Schema.Number })),
749 );
750 const updateInProgressTempPath = `${updateInProgressMarkerPath}.tmp`;
751 const writeUpdateInProgressMarker = Effect.gen(function* () {
752 const startedAt = DateTime.toEpochMillis(yield* DateTime.now);
753 const contents = yield* encodeUpdateMarker({
754 startedAt,
755 expiresAt: startedAt + DESKTOP_UPDATE_IN_PROGRESS_TTL_MS,
756 });
757 yield* fileSystem.writeFileString(updateInProgressTempPath, contents);
758 yield* fileSystem.rename(updateInProgressTempPath, updateInProgressMarkerPath);
759 }).pipe(
760 Effect.ensuring(
761 fileSystem.remove(updateInProgressTempPath, { force: true }).pipe(Effect.ignore),
762 ),
763 Effect.catch((error) =>
764 logUpdaterWarning("Could not write the update-in-progress marker.", { errorTag: error._tag }),
765 ),
766 );
767 const removeUpdateInProgressMarker = fileSystem
768 .remove(updateInProgressMarkerPath, { force: true })
769 .pipe(Effect.ignore);
770​
771 // Failed or interrupted installs leave no replacement backend; later quits must release the tunnel.
772 const removeUpdateRestartMarker = fileSystem
773 .remove(updateRestartMarkerPath, { force: true })
774 .pipe(Effect.ignore);
775​
776 const installRecordPath = environment.path.join(
777 updateRestartMarkerDir,
778 DESKTOP_UPDATE_INSTALL_RECORD_FILE,
779 );
780 const writeInstallRecord = (targetVersion: string) =>
781 encodeInstallRecord({ fromVersion: environment.appVersion, targetVersion }).pipe(
782 Effect.flatMap((text) => fileSystem.writeFileString(installRecordPath, text)),
783 Effect.catch((error) =>
784 logUpdaterWarning("Could not record the update install.", { errorTag: error._tag }),
785 ),
786 );
787 const removeInstallRecord = fileSystem
788 .remove(installRecordPath, { force: true })
789 .pipe(Effect.ignore);
790​
791 const readNotAppliedInstallVersion = fileSystem.readFileString(installRecordPath).pipe(
792 Effect.flatMap(decodeInstallRecord),
793 Effect.option,
794 Effect.map((record) =>
795 Option.flatMap(record, (value) =>
796 Option.fromNullishOr(resolveNotAppliedInstallVersion(value, environment.appVersion)),
797 ),
798 ),
799 Effect.tap((notAppliedVersion) =>
800 Option.isNone(notAppliedVersion) ? removeInstallRecord : Effect.void,
801 ),
802 );
803​
804 const baseUpdateState = (channel: DesktopUpdateChannel, disabledReason: Option.Option<string>) =>
805 Ref.get(notAppliedVersionRef).pipe(
806 Effect.map((notAppliedVersion) => ({
807 ...createBaseUpdateState(channel, disabledReason, environment),
808 // Callers fall back to the channel's reason only when nothing else turns updates off.
809 ...(Option.isSome(disabledReason) &&
810 disabledReason.value === Option.getOrUndefined(channelBlockedReason(channel))
811 ? { channelBlockedByPolicy: true as const }
812 : {}),
813 ...Option.match(notAppliedVersion, {
814 onNone: () => ({}),
815 onSome: (version) => ({ notAppliedVersion: version }),
816 }),
817 })),
818 );
819​
820 const resetInstallAction = Effect.all(
821 [
822 finishUpdateAction("install"),
823 Ref.set(desktopState.quitting, false),
824 Ref.set(installRunningBackendsRef, []),
825 removeUpdateRestartMarker,
826 removeUpdateInProgressMarker,
827 removeInstallRecord,
828 ],
829 { discard: true },
830 );
831​
832 const recoverFailedInstall = Effect.fn("desktop.updates.recoverFailedInstall")(function* (
833 message: string,
834 ) {
835 const ownsRecovery = yield* Ref.modify(activeUpdateActionRef, (activeAction) =>
836 Option.isSome(activeAction) && activeAction.value === "install"
837 ? ([true, Option.some<UpdateAction>("install-recovery")] as const)
838 : ([false, activeAction] as const),
839 );
840 if (!ownsRecovery) return;
841​
842 yield* Ref.set(desktopState.quitting, false);
843 yield* removeUpdateRestartMarker;
844 yield* removeUpdateInProgressMarker;
845 yield* removeInstallRecord;
846 yield* Effect.gen(function* () {
847 const runningInstances = yield* Ref.getAndSet(installRunningBackendsRef, []);
848 const instances = (yield* pool.list).filter((instance) =>
849 runningInstances.includes(instance),
850 );
851 const restartExit = yield* Effect.forEach(instances, (instance) => instance.start, {
852 concurrency: "unbounded",
853 discard: true,
854 }).pipe(Effect.exit);
855 yield* updateState((current) => reduceDesktopUpdateStateOnInstallFailure(current, message));
856 if (Exit.isFailure(restartExit)) {
857 yield* logUpdaterError("Desktop update install recovery could not restart every backend.");
858 }
859 }).pipe(
860 Effect.catchCause(() =>
861 logUpdaterError("Desktop update install recovery failed unexpectedly."),
862 ),
863 Effect.ensuring(finishUpdateAction("install-recovery")),
864 );
865 });
866​
867 const installDownloadedUpdate = (expectedVersion?: string) =>
868 Effect.scoped(
869 Effect.gen(function* () {
870 const admission = yield* admitAfterCheck(
871 Effect.gen(function* () {
872 const state = yield* Ref.get(updateStateRef);
873 const activeAction = yield* Ref.get(activeUpdateActionRef);
874 const hasExpectedDownload =
875 state.downloadedVersion !== null &&
876 (expectedVersion === undefined || state.downloadedVersion === expectedVersion);
877 if (
878 (yield* Ref.get(desktopState.quitting)) ||
879 !(yield* Ref.get(updaterConfiguredRef)) ||
880 !hasExpectedDownload
881 ) {
882 return "refused" as const;
883 }
884 if (Option.isSome(activeAction)) {
885 return activeAction.value === "check"
886 ? ("wait-for-check" as const)
887 : ("refused" as const);
888 }
889 const hasInstallableDownload =
890 state.status === "downloaded" ||
891 (state.status === "error" &&
892 (state.errorContext === null || state.errorContext === "install"));
893 if (!hasInstallableDownload) return "refused" as const;
894 return (yield* tryStartUpdateAction("install"))
895 ? ("admitted" as const)
896 : ("refused" as const);
897 }),
898 );
899 if (admission === "refused") {
900 return { accepted: false, completed: false, failed: false };
901 }
902​
903 yield* Ref.set(desktopState.quitting, true);
904 yield* Ref.set(installRunningBackendsRef, []);
905​
906 return yield* Effect.gen(function* () {
907 yield* writeUpdateRestartMarker;
908 yield* writeUpdateInProgressMarker;
909 const { downloadedVersion } = yield* Ref.get(updateStateRef);
910 if (downloadedVersion !== null) yield* writeInstallRecord(downloadedVersion);
911 // Stop pooled backends and SSH tunnels before quitAndInstall can outrun their scope finalizers.
912 const instances = yield* pool.list;
913 // stop clears desiredRunning, so retain the recovery set beforehand.
914 const runningInstances = yield* Effect.filter(instances, (instance) =>
915 instance.snapshot.pipe(Effect.map((snapshot) => snapshot.desiredRunning)),
916 );
917 yield* Ref.set(installRunningBackendsRef, runningInstances);
918 yield* Effect.all(
919 [
920 Effect.forEach(
921 instances,
922 (instance) =>
923 instance.stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT }),
924 { concurrency: "unbounded" },
925 ),
926 sshEnvironment.closeAllTunnels,
927 ],
928 { concurrency: "unbounded" },
929 );
930 yield* electronUpdater.quitAndInstall({
931 isSilent: true,
932 isForceRunAfter: true,
933 });
934 return { accepted: true, completed: false, failed: false };
935 }).pipe(
936 Effect.catchTags({
937 ElectronUpdaterQuitAndInstallError: Effect.fn("desktop.updates.handleInstallFailure")(
938 function* (error) {
939 yield* recoverFailedInstall(error.message);
940 yield* logUpdaterError(error.message, {
941 errorTag: error._tag,
942 cause: describeUpdateErrorCause(error.cause),
943 channel: error.channel,
944 isSilent: error.isSilent,
945 isForceRunAfter: error.isForceRunAfter,
946 });
947 return { accepted: true, completed: false, failed: true };
948 },
949 ),
950 }),
951 Effect.onInterrupt(() => resetInstallAction),
952 Effect.catchCause((cause) =>
953 Effect.gen(function* () {
954 if (Cause.hasInterruptsOnly(cause)) {
955 return yield* Effect.failCause(cause);
956 }
957 const error = new DesktopUpdateUnexpectedActionError({ action: "install", cause });
958 yield* recoverFailedInstall(error.message);
959 yield* logUpdaterError(error.message, {
960 errorTag: error._tag,
961 cause: describeUpdateErrorCause(error.cause),
962 action: error.action,
963 });
964 return { accepted: true, completed: false, failed: true };
965 }),
966 ),
967 );
968 }),
969 ).pipe(Effect.withSpan("desktop.updates.installDownloadedUpdate"));
970​
971 const installWithExpectedVersion = Effect.fn("desktop.updates.install")(function* (
972 expectedVersion?: string,
973 ) {
974 if (yield* Ref.get(desktopState.quitting)) {
975 return {
976 accepted: false,
977 completed: false,
978 failed: false,
979 state: yield* Ref.get(updateStateRef),
980 };
981 }
982 let installVersion = expectedVersion;
983 // A download can be hours old: a release published since replaces it before restarting.
984 const retained = yield* Ref.get(updateStateRef);
985 if (
986 retained.downloadedVersion !== null &&
987 (expectedVersion === undefined || retained.downloadedVersion === expectedVersion) &&
988 (yield* checkForUpdates(
989 "install",
990 "acquire",
991 retained.channel !== desktopUpdateChannelOf(environment.appVersion),
992 )) &&
993 (yield* Ref.get(updateStateRef)).status === "available"
994 ) {
995 const refreshed = yield* Ref.get(updateStateRef);
996 // electron-updater compares a stale feed with the running build, not the retained download.
997 if (
998 refreshed.availableVersion === null ||
999 compareSemverVersions(refreshed.availableVersion, retained.downloadedVersion) <= 0
1000 ) {
1001 yield* setState(retained);
1002 } else {
1003 const download = yield* downloadAvailableUpdate(false);
1004 if (!download.completed) {
1005 return {
1006 accepted: download.accepted,
1007 completed: false,
1008 failed: download.accepted,
1009 state: yield* Ref.get(updateStateRef),
1010 };
1012 if (expectedVersion !== undefined) {
1013 installVersion = (yield* Ref.get(updateStateRef)).downloadedVersion ?? expectedVersion;
1017 const result = yield* installDownloadedUpdate(installVersion);
1018 return {
1019 accepted: result.accepted,
1020 completed: result.completed,
1021 failed: result.failed,
1022 state: yield* Ref.get(updateStateRef),
1023 };
1024 });
1025​
1026 const startUpdatePollers: Effect.Effect<void, never, Scope.Scope> = Effect.gen(function* () {
1027 yield* Effect.sleep(AUTO_UPDATE_STARTUP_DELAY).pipe(
1028 Effect.andThen(checkForUpdates("startup")),
1029 Effect.catchCause((cause) => {
1030 if (Cause.hasInterruptsOnly(cause)) {
1031 return Effect.void;
1033 const error = new DesktopUpdatePollerError({ poller: "startup", cause });
1034 return logUpdaterError(error.message, {
1035 errorTag: error._tag,
1036 cause: describeUpdateErrorCause(error.cause),
1037 poller: error.poller,
1038 });
1039 }),
1040 Effect.forkScoped,
1041 );
1042 yield* Effect.sleep(AUTO_UPDATE_POLL_INTERVAL).pipe(
1043 Effect.andThen(checkForUpdates("poll")),
1044 Effect.forever,
1045 Effect.catchCause((cause) => {
1046 if (Cause.hasInterruptsOnly(cause)) {
1047 return Effect.void;
1049 const error = new DesktopUpdatePollerError({ poller: "poll", cause });
1050 return logUpdaterError(error.message, {
1051 errorTag: error._tag,
1052 cause: describeUpdateErrorCause(error.cause),
1053 poller: error.poller,
1054 });
1055 }),
1056 Effect.forkScoped,
1057 );
1058 }).pipe(Effect.withSpan("desktop.updates.startPollers"));
1059​
1060 const handleUpdateAvailable = Effect.fn("desktop.updates.handleUpdateAvailable")(function* (
1061 raw: unknown,
1062 ) {
1063 yield* decodeUpdateInfo(raw).pipe(
1064 Effect.flatMap(
1065 Effect.fn("desktop.updates.applyUpdateAvailable")(function* (info) {
1066 const state = yield* Ref.get(updateStateRef);
1067 if (!(yield* offerable(info.version, state))) {
1068 yield* logUpdaterInfo("ignoring update outside the selected channel or its floor", {
1069 version: info.version,
1070 channel: state.channel,
1071 });
1072 const checkedAt = yield* currentIsoTimestamp;
1073 yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt));
1074 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
1075 return;
1077 if (isOffered(state) && state.availableVersion === info.version) return;
1078​
1079 const checkedAt = yield* currentIsoTimestamp;
1080 const { releaseNotes, omittedReleaseCount } = normalizeDesktopUpdateReleaseNotes(
1081 releaseNotesOfOfferedVersion(info),
1082 info.version,
1083 state.channel,
1084 info.releaseDate,
1085 );
1086 yield* setState(
1087 reduceDesktopUpdateStateOnUpdateAvailable(
1088 state,
1089 info.version,
1090 checkedAt,
1091 releaseNotes,
1092 omittedReleaseCount,
1093 ),
1094 );
1095 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
1096 yield* logUpdaterInfo("update available", {
1097 version: info.version,
1098 releaseNoteGroups: releaseNotes.length,
1099 omittedReleaseCount,
1100 });
1101 }),
1102 ),
1103 Effect.catchCause((cause) => {
1104 if (Cause.hasInterruptsOnly(cause)) {
1105 return Effect.void;
1107 const error = new DesktopUpdateEventHandlingError({ event: "update-available", cause });
1108 return logUpdaterWarning(error.message, {
1109 errorTag: error._tag,
1110 cause: describeUpdateErrorCause(error.cause),
1111 event: error.event,
1112 });
1113 }),
1114 );
1115 });
1116​
1117 const handleUpdateNotAvailable = Effect.gen(function* () {
1118 const checkedAt = yield* currentIsoTimestamp;
1119 const state = yield* Ref.get(updateStateRef);
1120 yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt));
1121 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
1122 yield* logUpdaterInfo("no updates available");
1123 }).pipe(Effect.withSpan("desktop.updates.handleUpdateNotAvailable"));
1124​
1125 const handleUpdaterError = Effect.fn("desktop.updates.handleUpdaterError")(function* (
1126 cause: unknown,
1127 ) {
1128 const activeAction = yield* activeUpdateAction;
1129 const error = new DesktopUpdaterReportedError({
1130 operation: Option.match(activeAction, {
1131 onNone: () => "background" as const,
1132 onSome: (action) => (action === "install-recovery" ? "install" : action),
1133 }),
1134 cause,
1135 });
1136 if (Option.isSome(activeAction) && activeAction.value === "install") {
1137 yield* recoverFailedInstall(error.message);
1138 yield* logUpdaterError(error.message, {
1139 errorTag: error._tag,
1140 cause: describeUpdateErrorCause(error.cause),
1141 operation: error.operation,
1142 });
1143 return;
1145​
1146 if (Option.isNone(activeAction)) {
1147 const checkedAt = yield* currentIsoTimestamp;
1148 yield* updateState((current) => ({
1149 ...current,
1150 status: "error",
1151 message: error.message,
1152 checkedAt,
1153 downloadPercent: null,
1154 errorContext: current.errorContext,
1155 canRetry: getCanRetryFromState(current),
1156 }));
1158​
1159 yield* logUpdaterError(error.message, {
1160 errorTag: error._tag,
1161 cause: describeUpdateErrorCause(error.cause),
1162 operation: error.operation,
1163 });
1164 });
1165​
1166 const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
1167 raw: unknown,
1168 ) {
1169 yield* decodeDownloadProgressInfo(raw).pipe(
1170 Effect.flatMap(
1171 Effect.fn("desktop.updates.applyDownloadProgress")(function* (progress) {
1172 const state = yield* Ref.get(updateStateRef);
1173 const percent = Math.floor(progress.percent);
1174 if (shouldBroadcastDownloadProgress(state, progress.percent) || state.message !== null) {
1175 yield* setState(reduceDesktopUpdateStateOnDownloadProgress(state, progress.percent));
1177 const milestone = percent - (percent % 10);
1178 const lastLoggedMilestone = yield* Ref.get(lastLoggedDownloadMilestoneRef);
1179 if (milestone > lastLoggedMilestone) {
1180 yield* Ref.set(lastLoggedDownloadMilestoneRef, milestone);
1181 yield* logUpdaterInfo("download progress", { percent });
1183 }),
1184 ),
1185 Effect.catchCause((cause) => {
1186 if (Cause.hasInterruptsOnly(cause)) {
1187 return Effect.void;
1189 const error = new DesktopUpdateEventHandlingError({ event: "download-progress", cause });
1190 return logUpdaterWarning(error.message, {
1191 errorTag: error._tag,
1192 cause: describeUpdateErrorCause(error.cause),
1193 event: error.event,
1194 });
1195 }),
1196 );
1197 });
1198​
1199 const handleUpdateDownloaded = Effect.fn("desktop.updates.handleUpdateDownloaded")(function* (
1200 raw: unknown,
1201 ) {
1202 yield* decodeUpdateInfo(raw).pipe(
1203 Effect.flatMap(
1204 Effect.fn("desktop.updates.applyUpdateDownloaded")(function* (info) {
1205 const state = yield* Ref.get(updateStateRef);
1206 // A download can finish after its track switch moved on; never offer that build.
1207 if (!(yield* offerable(info.version, state))) {
1208 yield* logUpdaterInfo("ignoring download outside the selected channel or its floor", {
1209 version: info.version,
1210 channel: state.channel,
1211 });
1212 // Its progress events left the updater "downloading", which would block every check.
1213 if (state.status === "downloading") {
1214 yield* setState(
1215 reduceDesktopUpdateStateOnNoUpdate(state, yield* currentIsoTimestamp),
1216 );
1218 return;
1220 yield* setState(reduceDesktopUpdateStateOnDownloadComplete(state, info.version));
1221 yield* logUpdaterInfo("update downloaded", { version: info.version });
1222 }),
1223 ),
1224 Effect.catchCause((cause) => {
1225 if (Cause.hasInterruptsOnly(cause)) {
1226 return Effect.void;
1228 const error = new DesktopUpdateEventHandlingError({ event: "update-downloaded", cause });
1229 return logUpdaterWarning(error.message, {
1230 errorTag: error._tag,
1231 cause: describeUpdateErrorCause(error.cause),
1232 event: error.event,
1233 });
1234 }),
1235 );
1236 });
1237​
1238 return DesktopUpdates.of({
1239 getState: Ref.get(updateStateRef),
1240 isActionActive: activeUpdateAction.pipe(Effect.map(Option.isSome)),
1241 isInstallActive: activeUpdateAction.pipe(
1242 Effect.map((action) => Option.isSome(action) && action.value === "install"),
1243 ),
1244 subscribe: stateMutex.withPermits(1)(
1245 Effect.gen(function* () {
1246 const subscription = yield* PubSub.subscribe(stateChanges);
1247 const latest = yield* Ref.get(updateStateRef);
1248 return { latest, changes: Stream.fromSubscription(subscription) };
1249 }),
1250 ),
1251 emitState,
1252 disabledReason: Ref.get(updateStateRef).pipe(
1253 Effect.flatMap((state) => resolveStateDisabledReason(state.channel)),
1254 ),
1255 configure: Effect.gen(function* () {
1256 const context = yield* Effect.context<never>();
1257 // Runs synchronously up to the first await, so a check's outcome is applied before the
1258 // check's promise resolves and wakes the actions waiting on it.
1259 const runEffect = (effect: Effect.Effect<void>) => {
1260 void Effect.runPromiseWith(context)(effect);
1261 };
1262​
1263 const appUpdateYmlConfig = yield* readAppUpdateYml;
1264 yield* Ref.set(appUpdateYmlConfigRef, appUpdateYmlConfig);
1265​
1266 const notAppliedVersion = yield* readNotAppliedInstallVersion;
1267 yield* Ref.set(notAppliedVersionRef, notAppliedVersion);
1268 if (Option.isSome(notAppliedVersion)) {
1269 yield* logUpdaterWarning("the last update install did not apply", {
1270 version: environment.appVersion,
1271 targetVersion: notAppliedVersion.value,
1272 });
1274​
1275 if (mockUpdates) {
1276 yield* electronUpdater.setFeedURL({
1277 provider: "generic",
1278 url: `http://localhost:${config.mockUpdateServerPort}`,
1279 } as ElectronUpdater.ElectronUpdaterFeedUrl);
1280 } else if (policy.feedUrl !== undefined) {
1281 // The administrator's mirror replaces the GitHub feed baked into app-update.yml.
1282 yield* electronUpdater.setFeedURL({
1283 provider: "generic",
1284 url: policy.feedUrl,
1285 } as ElectronUpdater.ElectronUpdaterFeedUrl);
1287​
1288 const settings = yield* desktopSettings.get;
1289 const disabledReason = yield* resolveDisabledReason;
1290 // A blocked nightly channel still lets the user switch back to stable, so it stays updatable.
1291 yield* Ref.set(desktopState.canInstallUpdates, Option.isNone(disabledReason));
1292 yield* setState(
1293 yield* baseUpdateState(
1294 settings.updateChannel,
1295 Option.orElse(disabledReason, () => channelBlockedReason(settings.updateChannel)),
1296 ),
1297 );
1298 if (Option.isSome(disabledReason)) {
1299 return;
1301 yield* Ref.set(updaterConfiguredRef, true);
1302​
1303 yield* electronUpdater.setAutoDownload(false);
1304 yield* electronUpdater.setAutoInstallOnAppQuit(false);
1305 yield* applyAutoUpdaterChannel(settings.updateChannel);
1306 yield* electronUpdater.setDisableDifferentialDownload(
1307 isArm64HostRunningIntelBuild(environment.runtimeInfo),
1308 );
1309​
1310 if (isArm64HostRunningIntelBuild(environment.runtimeInfo)) {
1311 yield* logUpdaterInfo(
1312 "Apple Silicon host detected while running Intel build; updates will switch to arm64 packages",
1313 );
1315​
1316 yield* electronUpdater.on("checking-for-update", () => {
1317 runEffect(
1318 logUpdaterInfo("looking for updates").pipe(
1319 Effect.withSpan("desktop.updates.handleCheckingForUpdate"),
1320 ),
1321 );
1322 });
1323 yield* electronUpdater.on("update-available", (info: unknown) => {
1324 runEffect(handleUpdateAvailable(info));
1325 });
1326 yield* electronUpdater.on("update-not-available", () => {
1327 runEffect(handleUpdateNotAvailable);
1328 });
1329 yield* electronUpdater.on("error", (error: unknown) => {
1330 runEffect(handleUpdaterError(error));
1331 });
1332 yield* electronUpdater.on("download-progress", (progress: unknown) => {
1333 runEffect(handleDownloadProgress(progress));
1334 });
1335 yield* electronUpdater.on("update-downloaded", (info: unknown) => {
1336 runEffect(handleUpdateDownloaded(info));
1337 });
1338​
1339 yield* startUpdatePollers;
1340 }).pipe(Effect.withSpan("desktop.updates.configure")),
1341 setChannel: Effect.fn("desktop.updates.setChannel")(function* (
1342 nextChannel: DesktopUpdateChannel,
1343 options?: { readonly minimumVersion?: string | undefined },
1344 ) {
1345 yield* Effect.annotateCurrentSpan({ channel: nextChannel });
1346 if (Option.isSome(channelBlockedReason(nextChannel))) {
1347 return yield* new DesktopUpdateChannelManagedError({
1348 channel: nextChannel,
1349 policyMessage: policy.message ?? "Your administrator manages T3 Code updates.",
1350 });
1352 // A background check holds the updater only briefly, so wait it out instead of refusing.
1353 const activeAction = yield* tryStartChannelChange.pipe(
1354 Effect.repeat({
1355 while: (active) => Option.isSome(active) && active.value === "check",
1356 schedule: Schedule.spaced(CHANNEL_CHANGE_RETRY_DELAY),
1357 times: CHANNEL_CHANGE_RETRIES,
1358 }),
1359 );
1360 if (Option.isSome(activeAction)) {
1361 return yield* new DesktopUpdateActionInProgressError({
1362 action: activeAction.value === "install-recovery" ? "install" : activeAction.value,
1363 requestedChannel: nextChannel,
1364 });
1366​
1367 return yield* Effect.gen(function* () {
1368 const previousFloor = yield* Ref.getAndSet(
1369 releaseFloorRef,
1370 Option.fromNullishOr(options?.minimumVersion),
1371 );
1372 const state = yield* Ref.get(updateStateRef);
1373 const retained = state.downloadedVersion ?? state.availableVersion;
1374 // A build from another track re-checks, so retrying a track switch finds an older release.
1375 // So does a retained offer below the new floor, which must not install.
1376 if (
1377 nextChannel === state.channel &&
1378 nextChannel === desktopUpdateChannelOf(environment.appVersion) &&
1379 (retained === null || (yield* offerable(retained, state)))
1380 ) {
1381 return state;
1383​
1384 yield* desktopSettings.setUpdateChannel(nextChannel).pipe(
1385 Effect.onError(() => Ref.set(releaseFloorRef, previousFloor)),
1386 Effect.mapError(
1387 (cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }),
1388 ),
1389 );
1390​
1391 const disabledReason = yield* resolveDisabledReason;
1392 yield* setState(yield* baseUpdateState(nextChannel, disabledReason));
1393​
1394 if (Option.isSome(disabledReason) || !(yield* Ref.get(updaterConfiguredRef))) {
1395 return yield* Ref.get(updateStateRef);
1397​
1398 yield* applyAutoUpdaterChannel(nextChannel);
1399 // Only leaving the running build's track can need an older release.
1400 yield* checkForUpdates(
1401 "channel-change",
1402 "held",
1403 nextChannel !== desktopUpdateChannelOf(environment.appVersion),
1404 );
1405 return yield* Ref.get(updateStateRef);
1406 }).pipe(Effect.ensuring(finishUpdateAction("channel")));
1407 }),
1408 check: Effect.fn("desktop.updates.check")(function* (
1409 reason: string,
1410 options?: { readonly allowDowngrade?: boolean },
1411 ) {
1412 yield* Effect.annotateCurrentSpan({ reason });
1413 if (!(yield* Ref.get(updaterConfiguredRef))) {
1414 return {
1415 checked: false,
1416 state: yield* Ref.get(updateStateRef),
1417 };
1419 const checked = yield* checkForUpdates(reason, "acquire", options?.allowDowngrade === true);
1420 return {
1421 checked,
1422 state: yield* Ref.get(updateStateRef),
1423 };
1424 }),
1425 download: Effect.gen(function* () {
1426 const result = yield* downloadAvailableUpdate(true);
1427 return {
1428 accepted: result.accepted,
1429 completed: result.completed,
1430 state: yield* Ref.get(updateStateRef),
1431 };
1432 }).pipe(Effect.withSpan("desktop.updates.download")),
1433 install: installWithExpectedVersion().pipe(
1434 Effect.map(({ accepted, completed, state }) => ({ accepted, completed, state })),
1435 ),
1436 installPrepared: Effect.fn("DesktopUpdates.installPrepared")(function (expectedVersion) {
1437 return installWithExpectedVersion(expectedVersion);
1438 }),
1439 });
1440});
1441​
1442export const layer = Layer.effect(DesktopUpdates, make);