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

DesktopUpdates.ts

1,262 lines47.4 KB

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