Open History to see the last commit
1import {
2 DesktopUpdateChannelSchema,
3 type DesktopRuntimeInfo,
4 type DesktopUpdateActionResult,
5 type DesktopUpdateChannel,
6 type DesktopUpdateCheckResult,
7 type DesktopUpdateState,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Context from "effect/Context";
11import * as DateTime from "effect/DateTime";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as Exit from "effect/Exit";
15import * as FileSystem from "effect/FileSystem";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as PubSub from "effect/PubSub";
19import * as Ref from "effect/Ref";
20import * as Schema from "effect/Schema";
21import * as Scope from "effect/Scope";
22import * as Semaphore from "effect/Semaphore";
23import * as Stream from "effect/Stream";
24
25import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
26import * as DesktopConfig from "../app/DesktopConfig.ts";
27import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
28import * as DesktopObservability from "../app/DesktopObservability.ts";
29import * as DesktopState from "../app/DesktopState.ts";
30import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
31import * as ElectronWindow from "../electron/ElectronWindow.ts";
32import * as IpcChannels from "../ipc/channels.ts";
33import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
34import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
35import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
36import {
37 createInitialDesktopUpdateState,
38 reduceDesktopUpdateStateOnCheckFailure,
39 reduceDesktopUpdateStateOnCheckStart,
40 reduceDesktopUpdateStateOnDownloadComplete,
41 reduceDesktopUpdateStateOnDownloadFailure,
42 reduceDesktopUpdateStateOnDownloadProgress,
43 reduceDesktopUpdateStateOnDownloadStart,
44 reduceDesktopUpdateStateOnInstallFailure,
45 reduceDesktopUpdateStateOnNoUpdate,
46 reduceDesktopUpdateStateOnUpdateAvailable,
47} from "./updateMachine.ts";
48
49const AUTO_UPDATE_STARTUP_DELAY = "15 seconds";
50const AUTO_UPDATE_POLL_INTERVAL = "4 minutes";
51const PREPARED_INSTALL_CHECK_WAIT = Duration.seconds(90);
52
53type UpdateAction = "check" | "download" | "install" | "install-recovery" | "channel";
54
55interface DesktopPreparedUpdateInstallResult extends DesktopUpdateActionResult {
56 readonly failed: boolean;
57}
58
59const AppUpdateYmlConfig = Schema.Record(Schema.String, Schema.String);
60type AppUpdateYmlConfig = typeof AppUpdateYmlConfig.Type;
61
62const UpdateInfo = Schema.Struct({
63 version: Schema.String,
64 // Left unvalidated on purpose: a malformed release-notes payload must never
65 // fail the decode and block the update state transition. The shape is
66 // validated defensively in normalizeDesktopUpdateReleaseNotes.
67 releaseNotes: Schema.optional(Schema.Unknown),
68});
69
70const DownloadProgressInfo = Schema.Struct({
71 percent: Schema.Number,
72});
73const decodeAppUpdateYmlConfig = Schema.decodeUnknownEffect(AppUpdateYmlConfig);
74const decodeUpdateInfo = Schema.decodeUnknownEffect(UpdateInfo);
75const decodeDownloadProgressInfo = Schema.decodeUnknownEffect(DownloadProgressInfo);
76
77const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
78
79export class DesktopUpdateActionInProgressError extends Schema.TaggedError<DesktopUpdateActionInProgressError>()(
80 "DesktopUpdateActionInProgressError",
81 {
82 action: Schema.Literals(["check", "download", "install", "channel"]),
83 requestedChannel: DesktopUpdateChannelSchema,
84 },
85) {
86 override get message(): string {
87 return `Cannot change the desktop update channel to ${this.requestedChannel} while an update ${this.action} action is in progress.`;
88 }
89}
90
91export class DesktopUpdateChannelPersistenceError extends Schema.TaggedError<DesktopUpdateChannelPersistenceError>()(
92 "DesktopUpdateChannelPersistenceError",
93 {
94 channel: DesktopUpdateChannelSchema,
95 cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
96 },
97) {
98 override get message(): string {
99 return `Failed to persist the ${this.channel} desktop update channel.`;
100 }
101}
102
103export class DesktopUpdatePollerError extends Schema.TaggedError<DesktopUpdatePollerError>()(
104 "DesktopUpdatePollerError",
105 {
106 poller: Schema.Literals(["startup", "poll"]),
107 cause: Schema.Defect(),
108 },
109) {
110 override get message(): string {
111 return `Desktop update ${this.poller} poller failed.`;
112 }
113}
114
115export class DesktopUpdateEventHandlingError extends Schema.TaggedError<DesktopUpdateEventHandlingError>()(
116 "DesktopUpdateEventHandlingError",
117 {
118 event: Schema.Literals(["update-available", "download-progress", "update-downloaded"]),
119 cause: Schema.Defect(),
120 },
121) {
122 override get message(): string {
123 return `Failed to handle desktop update ${this.event} event.`;
124 }
125}
126
127export class DesktopUpdaterReportedError extends Schema.TaggedError<DesktopUpdaterReportedError>()(
128 "DesktopUpdaterReportedError",
129 {
130 operation: Schema.Literals(["check", "download", "install", "channel", "background"]),
131 cause: Schema.Defect(),
132 },
133) {
134 override get message(): string {
135 return `Desktop updater ${this.operation} operation reported an error.`;
136 }
137}
138
139export class DesktopUpdateUnexpectedActionError extends Schema.TaggedError<DesktopUpdateUnexpectedActionError>()(
140 "DesktopUpdateUnexpectedActionError",
141 {
142 action: Schema.Literals(["download", "install"]),
143 cause: Schema.Defect(),
144 },
145) {
146 override get message(): string {
147 return `Desktop update ${this.action} action failed unexpectedly.`;
148 }
149}
150
151export type DesktopUpdateConfigureError = never;
152
153export const DesktopUpdateSetChannelError = Schema.Union([
154 DesktopUpdateActionInProgressError,
155 DesktopUpdateChannelPersistenceError,
156]);
157export type DesktopUpdateSetChannelError = typeof DesktopUpdateSetChannelError.Type;
158
159export class DesktopUpdates extends Context.Service<
160 DesktopUpdates,
161 {
162 readonly getState: Effect.Effect<DesktopUpdateState>;
163 /** True while a check, download, install, or channel change holds the
164 updater's single action reservation. */
165 readonly isActionActive: Effect.Effect<boolean>;
166 /** True only while an install owns the updater action reservation. */
167 readonly isInstallActive: Effect.Effect<boolean>;
168 /** Current state plus a stream of every later state change. */
169 readonly subscribe: Effect.Effect<
170 {
171 readonly latest: DesktopUpdateState;
172 readonly changes: Stream.Stream<DesktopUpdateState>;
173 },
174 never,
175 Scope.Scope
176 >;
177 readonly emitState: Effect.Effect<void>;
178 readonly disabledReason: Effect.Effect<Option.Option<string>>;
179 readonly configure: Effect.Effect<void, DesktopUpdateConfigureError, Scope.Scope>;
180 readonly setChannel: (
181 channel: DesktopUpdateChannel,
182 ) => Effect.Effect<DesktopUpdateState, DesktopUpdateSetChannelError>;
183 readonly check: (reason: string) => Effect.Effect<DesktopUpdateCheckResult>;
184 readonly download: Effect.Effect<DesktopUpdateActionResult>;
185 readonly install: Effect.Effect<DesktopUpdateActionResult>;
186 readonly installPrepared: (
187 expectedVersion: string,
188 ) => Effect.Effect<DesktopPreparedUpdateInstallResult>;
189 }
190>()("@t3tools/desktop/updates/DesktopUpdates") {}
191
192const {
193 logInfo: logUpdaterInfo,
194 logWarning: logUpdaterWarning,
195 logError: logUpdaterError,
196} = DesktopObservability.makeComponentLogger("desktop-updater");
197
198function parseAppUpdateYml(raw: string): Effect.Effect<Option.Option<AppUpdateYmlConfig>> {
199 const entries: Record<string, string> = {};
200 for (const line of raw.split("\n")) {
201 const match = line.match(/^(\w+):\s*(.+)$/);
202 if (match?.[1] && match[2]) {
203 entries[match[1]] = match[2].trim();
204 }
205 }
206
207 return decodeAppUpdateYmlConfig(entries).pipe(
208 Effect.map((config) => (config.provider ? Option.some(config) : Option.none())),
209 Effect.orElseSucceed(() => Option.none<AppUpdateYmlConfig>()),
210 );
211}
212
213function createBaseUpdateState(
214 channel: DesktopUpdateChannel,
215 enabled: boolean,
216 environment: DesktopEnvironment.DesktopEnvironment["Service"],
217): DesktopUpdateState {
218 return {
219 ...createInitialDesktopUpdateState(environment.appVersion, environment.runtimeInfo, channel),
220 enabled,
221 status: enabled ? "idle" : "disabled",
222 };
223}
224
225function getCanRetryFromState(state: DesktopUpdateState): boolean {
226 return state.availableVersion !== null || state.downloadedVersion !== null;
227}
228
229function shouldBroadcastDownloadProgress(
230 currentState: DesktopUpdateState,
231 nextPercent: number,
232): boolean {
233 if (currentState.status !== "downloading") {
234 return true;
235 }
236
237 const currentPercent = currentState.downloadPercent;
238 if (currentPercent === null) {
239 return true;
240 }
241
242 const previousStep = Math.floor(currentPercent / 10);
243 const nextStep = Math.floor(nextPercent / 10);
244 return nextStep !== previousStep || nextPercent === 100;
245}
246
247function getAutoUpdateDisabledReason(args: {
248 isDevelopment: boolean;
249 isPackaged: boolean;
250 platform: NodeJS.Platform;
251 appImage?: string | undefined;
252 disabledByEnv: boolean;
253 hasUpdateFeedConfig: boolean;
254}): string | null {
255 if (!args.hasUpdateFeedConfig) {
256 return "Automatic updates are not available because no update feed is configured.";
257 }
258 if (args.isDevelopment || !args.isPackaged) {
259 return "Automatic updates are only available in packaged production builds.";
260 }
261 if (args.disabledByEnv) {
262 return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
263 }
264 if (args.platform === "linux" && !args.appImage) {
265 return "Automatic updates on Linux require running the AppImage build.";
266 }
267 return null;
268}
269
270function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean {
271 return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
272}
273
274/** @public Service construction is part of the canonical Effect module API. */
275export const make = Effect.gen(function* () {
276 const config = yield* DesktopConfig.DesktopConfig;
277 const pool = yield* DesktopBackendPool.DesktopBackendPool;
278 const desktopState = yield* DesktopState.DesktopState;
279 const electronUpdater = yield* ElectronUpdater.ElectronUpdater;
280 const electronWindow = yield* ElectronWindow.ElectronWindow;
281 const environment = yield* DesktopEnvironment.DesktopEnvironment;
282 const fileSystem = yield* FileSystem.FileSystem;
283 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
284
285 const appUpdateYmlConfigRef = yield* Ref.make<Option.Option<AppUpdateYmlConfig>>(Option.none());
286 const activeUpdateActionRef = yield* Ref.make<Option.Option<UpdateAction>>(Option.none());
287 const finishedUpdateActions = yield* PubSub.unbounded<UpdateAction>();
288 const updaterConfiguredRef = yield* Ref.make(false);
289 const lastLoggedDownloadMilestoneRef = yield* Ref.make(-1);
290 const updateStateRef = yield* Ref.make<DesktopUpdateState>(
291 createInitialDesktopUpdateState(
292 environment.appVersion,
293 environment.runtimeInfo,
294 environment.defaultDesktopSettings.updateChannel,
295 ),
296 );
297
298 const stateChanges = yield* PubSub.sliding<DesktopUpdateState>(16);
299 // Makes ref writes + publishes atomic against subscribe, so a snapshot
300 // never overlaps with the first change a subscriber receives.
301 const stateMutex = yield* Semaphore.make(1);
302
303 const emitState = Ref.get(updateStateRef).pipe(
304 Effect.flatMap((state) => electronWindow.sendAll(IpcChannels.UPDATE_STATE_CHANNEL, state)),
305 );
306
307 const setState = (state: DesktopUpdateState): Effect.Effect<void> =>
308 stateMutex
309 .withPermits(1)(
310 Ref.set(updateStateRef, state).pipe(Effect.andThen(PubSub.publish(stateChanges, state))),
311 )
312 .pipe(Effect.andThen(emitState));
313
314 const updateState = (
315 f: (state: DesktopUpdateState) => DesktopUpdateState,
316 ): Effect.Effect<DesktopUpdateState> =>
317 Ref.get(updateStateRef).pipe(
318 Effect.flatMap((state) => {
319 const nextState = f(state);
320 return setState(nextState).pipe(Effect.as(nextState));
321 }),
322 );
323
324 const readAppUpdateYml = fileSystem.readFileString(environment.appUpdateYmlPath, "utf-8").pipe(
325 Effect.option,
326 Effect.flatMap(
327 Option.match({
328 onNone: () => Effect.succeed(Option.none<AppUpdateYmlConfig>()),
329 onSome: parseAppUpdateYml,
330 }),
331 ),
332 );
333
334 const hasUpdateFeedConfig = Ref.get(appUpdateYmlConfigRef).pipe(
335 Effect.map((appUpdateYmlConfig) => Option.isSome(appUpdateYmlConfig) || config.mockUpdates),
336 );
337
338 const resolveDisabledReason = Effect.gen(function* () {
339 const hasFeedConfig = yield* hasUpdateFeedConfig;
340 return Option.fromNullishOr(
341 getAutoUpdateDisabledReason({
342 isDevelopment: environment.isDevelopment,
343 isPackaged: environment.isPackaged,
344 platform: environment.platform,
345 appImage: Option.getOrUndefined(config.appImagePath),
346 disabledByEnv: config.disableAutoUpdate,
347 hasUpdateFeedConfig: hasFeedConfig,
348 }),
349 );
350 });
351
352 const activeUpdateAction = Ref.get(activeUpdateActionRef);
353
354 const tryStartUpdateAction = (action: UpdateAction): Effect.Effect<boolean> =>
355 Ref.modify(activeUpdateActionRef, (activeAction) =>
356 Option.isSome(activeAction) ? [false, activeAction] : [true, Option.some(action)],
357 );
358
359 const tryStartChannelChange = Ref.modify(activeUpdateActionRef, (activeAction) =>
360 Option.isSome(activeAction)
361 ? [activeAction, activeAction]
362 : [Option.none<UpdateAction>(), Option.some<UpdateAction>("channel")],
363 );
364
365 const finishUpdateAction = (action: UpdateAction): Effect.Effect<void> =>
366 Ref.modify(activeUpdateActionRef, (activeAction) => {
367 const finished = Option.isSome(activeAction) && activeAction.value === action;
368 return [finished, finished ? Option.none() : activeAction] as const;
369 }).pipe(
370 Effect.flatMap((finished) =>
371 finished ? PubSub.publish(finishedUpdateActions, action).pipe(Effect.asVoid) : Effect.void,
372 ),
373 );
374
375 const applyAutoUpdaterChannel = Effect.fn("desktop.updates.applyAutoUpdaterChannel")(function* (
376 channel: DesktopUpdateChannel,
377 ) {
378 yield* Effect.annotateCurrentSpan({ channel });
379 const allowsPrerelease = channel === "nightly";
380 yield* electronUpdater.setChannel(channel);
381 yield* electronUpdater.setAllowPrerelease(allowsPrerelease);
382 yield* electronUpdater.setAllowDowngrade(allowsPrerelease);
383 yield* electronUpdater.setFullChangelog(allowsPrerelease);
384 yield* logUpdaterInfo("using update channel", {
385 channel,
386 allowPrerelease: allowsPrerelease,
387 allowDowngrade: allowsPrerelease,
388 fullChangelog: allowsPrerelease,
389 });
390 });
391
392 const shouldEnableAutoUpdates = resolveDisabledReason.pipe(Effect.map(Option.isNone));
393
394 const checkForUpdates = Effect.fn("desktop.updates.checkForUpdates")(function* (
395 reason: string,
396 actionReservation: "acquire" | "held" = "acquire",
397 ) {
398 yield* Effect.annotateCurrentSpan({ reason });
399 if (yield* Ref.get(desktopState.quitting)) return false;
400 if (!(yield* Ref.get(updaterConfiguredRef))) return false;
401
402 const state = yield* Ref.get(updateStateRef);
403 if (state.status === "downloading") {
404 yield* logUpdaterInfo("skipping update check while update is active", {
405 reason,
406 status: state.status,
407 });
408 return false;
409 }
410
411 if (actionReservation === "acquire" && !(yield* tryStartUpdateAction("check"))) return false;
412
413 const check = Effect.gen(function* () {
414 const checkedAt = yield* currentIsoTimestamp;
415 yield* setState(reduceDesktopUpdateStateOnCheckStart(state, checkedAt));
416 yield* logUpdaterInfo("checking for updates", { reason });
417
418 return yield* electronUpdater.checkForUpdates.pipe(
419 Effect.as(true),
420 Effect.catchTags({
421 ElectronUpdaterCheckForUpdatesError: Effect.fn(
422 "desktop.updates.handleCheckForUpdatesFailure",
423 )(function* (error) {
424 const failedAt = yield* currentIsoTimestamp;
425 yield* updateState((current) =>
426 reduceDesktopUpdateStateOnCheckFailure(current, error.message, failedAt),
427 );
428 yield* logUpdaterError(error.message, {
429 errorTag: error._tag,
430 channel: error.channel,
431 });
432 return true;
433 }),
434 }),
435 );
436 });
437
438 return yield* actionReservation === "held"
439 ? check
440 : check.pipe(
441 Effect.onInterrupt(() => setState(state)),
442 Effect.ensuring(finishUpdateAction("check")),
443 );
444 });
445
446 const downloadAvailableUpdate = Effect.gen(function* () {
447 const state = yield* Ref.get(updateStateRef);
448 if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") {
449 return { accepted: false, completed: false };
450 }
451
452 if (!(yield* tryStartUpdateAction("download"))) {
453 return { accepted: false, completed: false };
454 }
455
456 return yield* Effect.gen(function* () {
457 yield* setState(reduceDesktopUpdateStateOnDownloadStart(state));
458 yield* electronUpdater.setDisableDifferentialDownload(
459 isArm64HostRunningIntelBuild(environment.runtimeInfo),
460 );
461 yield* logUpdaterInfo("downloading update");
462 yield* electronUpdater.downloadUpdate;
463 return { accepted: true, completed: true };
464 }).pipe(
465 Effect.catchTags({
466 ElectronUpdaterDownloadUpdateError: Effect.fn("desktop.updates.handleDownloadFailure")(
467 function* (error) {
468 yield* updateState((current) =>
469 reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
470 );
471 yield* logUpdaterError(error.message, {
472 errorTag: error._tag,
473 channel: error.channel,
474 });
475 return { accepted: true, completed: false };
476 },
477 ),
478 }),
479 Effect.onInterrupt(() =>
480 updateState((current) => (current.status === "downloading" ? state : current)).pipe(
481 Effect.asVoid,
482 ),
483 ),
484 Effect.catchCause((cause) => {
485 if (Cause.hasInterruptsOnly(cause)) {
486 return Effect.failCause(cause);
487 }
488 const error = new DesktopUpdateUnexpectedActionError({ action: "download", cause });
489 return Effect.gen(function* () {
490 yield* updateState((current) =>
491 reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
492 );
493 yield* logUpdaterError(error.message, {
494 errorTag: error._tag,
495 action: error.action,
496 });
497 return { accepted: true, completed: false };
498 });
499 }),
500 Effect.ensuring(finishUpdateAction("download")),
501 );
502 }).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate"));
503
504 const resetInstallAction = Effect.all(
505 [finishUpdateAction("install"), Ref.set(desktopState.quitting, false)],
506 { discard: true },
507 );
508
509 const recoverFailedInstall = Effect.fn("desktop.updates.recoverFailedInstall")(function* (
510 message: string,
511 ) {
512 const ownsRecovery = yield* Ref.modify(activeUpdateActionRef, (activeAction) =>
513 Option.isSome(activeAction) && activeAction.value === "install"
514 ? ([true, Option.some<UpdateAction>("install-recovery")] as const)
515 : ([false, activeAction] as const),
516 );
517 if (!ownsRecovery) return;
518
519 yield* Ref.set(desktopState.quitting, false);
520 yield* Effect.gen(function* () {
521 const instances = yield* pool.list;
522 const restartExit = yield* Effect.forEach(instances, (instance) => instance.start, {
523 concurrency: "unbounded",
524 discard: true,
525 }).pipe(Effect.exit);
526 yield* updateState((current) => reduceDesktopUpdateStateOnInstallFailure(current, message));
527 if (Exit.isFailure(restartExit)) {
528 yield* logUpdaterError("Desktop update install recovery could not restart every backend.");
529 }
530 }).pipe(
531 Effect.catchCause(() =>
532 logUpdaterError("Desktop update install recovery failed unexpectedly."),
533 ),
534 Effect.ensuring(finishUpdateAction("install-recovery")),
535 );
536 });
537
538 const installDownloadedUpdate = (expectedVersion?: string) =>
539 Effect.scoped(
540 Effect.gen(function* () {
541 const actionCompletions = yield* PubSub.subscribe(finishedUpdateActions);
542 let admission: "admitted" | "refused" | "wait-for-check" = "wait-for-check";
543 while (admission === "wait-for-check") {
544 admission = yield* stateMutex.withPermits(1)(
545 Effect.gen(function* () {
546 const state = yield* Ref.get(updateStateRef);
547 const activeAction = yield* Ref.get(activeUpdateActionRef);
548 const hasExpectedDownload =
549 state.downloadedVersion !== null &&
550 (expectedVersion === undefined || state.downloadedVersion === expectedVersion);
551 if (
552 (yield* Ref.get(desktopState.quitting)) ||
553 !(yield* Ref.get(updaterConfiguredRef)) ||
554 !hasExpectedDownload
555 ) {
556 return "refused" as const;
557 }
558 if (Option.isSome(activeAction)) {
559 return activeAction.value === "check" && expectedVersion !== undefined
560 ? ("wait-for-check" as const)
561 : ("refused" as const);
562 }
563 const hasInstallableDownload =
564 state.status === "downloaded" ||
565 (state.status === "error" &&
566 (state.errorContext === null || state.errorContext === "install"));
567 if (!hasInstallableDownload) return "refused" as const;
568 return (yield* tryStartUpdateAction("install"))
569 ? ("admitted" as const)
570 : ("refused" as const);
571 }),
572 );
573 if (admission === "wait-for-check") {
574 const finishedAction = yield* PubSub.take(actionCompletions).pipe(
575 Effect.timeoutOption(PREPARED_INSTALL_CHECK_WAIT),
576 );
577 if (Option.isNone(finishedAction)) {
578 admission = "refused";
579 }
580 }
581 }
582 if (admission === "refused") {
583 return { accepted: false, completed: false, failed: false };
584 }
585
586 yield* Ref.set(desktopState.quitting, true);
587
588 return yield* Effect.gen(function* () {
589 // Stop every backend in the pool, not just the primary. With
590 // parallel WSL + Windows backends, leaving the WSL instance up
591 // means quitAndInstall's app.quit() exits before the pool's
592 // scope cascade has a chance to run its stop finalizer, so the
593 // WSL child gets hard-killed by the OS instead of receiving
594 // SIGTERM + grace. Stops run concurrently with the same 5s
595 // budget the primary had on its own.
596 const instances = yield* pool.list;
597 yield* Effect.forEach(
598 instances,
599 (instance) => instance.stop({ timeout: Duration.seconds(5) }),
600 { concurrency: "unbounded" },
601 );
602 yield* electronUpdater.quitAndInstall({
603 isSilent: true,
604 isForceRunAfter: true,
605 });
606 return { accepted: true, completed: false, failed: false };
607 }).pipe(
608 Effect.catchTags({
609 ElectronUpdaterQuitAndInstallError: Effect.fn("desktop.updates.handleInstallFailure")(
610 function* (error) {
611 yield* recoverFailedInstall(error.message);
612 yield* logUpdaterError(error.message, {
613 errorTag: error._tag,
614 channel: error.channel,
615 isSilent: error.isSilent,
616 isForceRunAfter: error.isForceRunAfter,
617 });
618 return { accepted: true, completed: false, failed: true };
619 },
620 ),
621 }),
622 Effect.onInterrupt(() => resetInstallAction),
623 Effect.catchCause((cause) =>
624 Effect.gen(function* () {
625 if (Cause.hasInterruptsOnly(cause)) {
626 return yield* Effect.failCause(cause);
627 }
628 const error = new DesktopUpdateUnexpectedActionError({ action: "install", cause });
629 yield* recoverFailedInstall(error.message);
630 yield* logUpdaterError(error.message, {
631 errorTag: error._tag,
632 action: error.action,
633 });
634 return { accepted: true, completed: false, failed: true };
635 }),
636 ),
637 );
638 }),
639 ).pipe(Effect.withSpan("desktop.updates.installDownloadedUpdate"));
640
641 const installWithExpectedVersion = (expectedVersion?: string) =>
642 Effect.gen(function* () {
643 if (yield* Ref.get(desktopState.quitting)) {
644 return {
645 accepted: false,
646 completed: false,
647 failed: false,
648 state: yield* Ref.get(updateStateRef),
649 };
650 }
651 const result = yield* installDownloadedUpdate(expectedVersion);
652 return {
653 accepted: result.accepted,
654 completed: result.completed,
655 failed: result.failed,
656 state: yield* Ref.get(updateStateRef),
657 };
658 }).pipe(Effect.withSpan("desktop.updates.install"));
659
660 const startUpdatePollers: Effect.Effect<void, never, Scope.Scope> = Effect.gen(function* () {
661 yield* Effect.sleep(AUTO_UPDATE_STARTUP_DELAY).pipe(
662 Effect.andThen(checkForUpdates("startup")),
663 Effect.catchCause((cause) => {
664 if (Cause.hasInterruptsOnly(cause)) {
665 return Effect.void;
666 }
667 const error = new DesktopUpdatePollerError({ poller: "startup", cause });
668 return logUpdaterError(error.message, {
669 errorTag: error._tag,
670 poller: error.poller,
671 });
672 }),
673 Effect.forkScoped,
674 );
675 yield* Effect.sleep(AUTO_UPDATE_POLL_INTERVAL).pipe(
676 Effect.andThen(checkForUpdates("poll")),
677 Effect.forever,
678 Effect.catchCause((cause) => {
679 if (Cause.hasInterruptsOnly(cause)) {
680 return Effect.void;
681 }
682 const error = new DesktopUpdatePollerError({ poller: "poll", cause });
683 return logUpdaterError(error.message, {
684 errorTag: error._tag,
685 poller: error.poller,
686 });
687 }),
688 Effect.forkScoped,
689 );
690 }).pipe(Effect.withSpan("desktop.updates.startPollers"));
691
692 const handleUpdateAvailable = Effect.fn("desktop.updates.handleUpdateAvailable")(function* (
693 raw: unknown,
694 ) {
695 yield* decodeUpdateInfo(raw).pipe(
696 Effect.flatMap(
697 Effect.fn("desktop.updates.applyUpdateAvailable")(function* (info) {
698 const state = yield* Ref.get(updateStateRef);
699 if (resolveDefaultDesktopUpdateChannel(info.version) !== state.channel) {
700 yield* logUpdaterInfo("ignoring update that does not match selected channel", {
701 version: info.version,
702 channel: state.channel,
703 });
704 const checkedAt = yield* currentIsoTimestamp;
705 yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt));
706 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
707 return;
708 }
709
710 const checkedAt = yield* currentIsoTimestamp;
711 const { releaseNotes, omittedReleaseCount } = normalizeDesktopUpdateReleaseNotes(
712 info.releaseNotes,
713 info.version,
714 );
715 yield* setState(
716 reduceDesktopUpdateStateOnUpdateAvailable(
717 state,
718 info.version,
719 checkedAt,
720 releaseNotes,
721 omittedReleaseCount,
722 ),
723 );
724 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
725 yield* logUpdaterInfo("update available", {
726 version: info.version,
727 releaseNoteGroups: releaseNotes.length,
728 omittedReleaseCount,
729 });
730 }),
731 ),
732 Effect.catchCause((cause) => {
733 if (Cause.hasInterruptsOnly(cause)) {
734 return Effect.void;
735 }
736 const error = new DesktopUpdateEventHandlingError({ event: "update-available", cause });
737 return logUpdaterWarning(error.message, {
738 errorTag: error._tag,
739 event: error.event,
740 });
741 }),
742 );
743 });
744
745 const handleUpdateNotAvailable = Effect.gen(function* () {
746 const checkedAt = yield* currentIsoTimestamp;
747 const state = yield* Ref.get(updateStateRef);
748 yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt));
749 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
750 yield* logUpdaterInfo("no updates available");
751 }).pipe(Effect.withSpan("desktop.updates.handleUpdateNotAvailable"));
752
753 const handleUpdaterError = Effect.fn("desktop.updates.handleUpdaterError")(function* (
754 cause: unknown,
755 ) {
756 const activeAction = yield* activeUpdateAction;
757 const error = new DesktopUpdaterReportedError({
758 operation: Option.match(activeAction, {
759 onNone: () => "background" as const,
760 onSome: (action) => (action === "install-recovery" ? "install" : action),
761 }),
762 cause,
763 });
764 if (Option.isSome(activeAction) && activeAction.value === "install") {
765 yield* recoverFailedInstall(error.message);
766 yield* logUpdaterError(error.message, {
767 errorTag: error._tag,
768 operation: error.operation,
769 });
770 return;
771 }
772
773 if (Option.isNone(activeAction)) {
774 const checkedAt = yield* currentIsoTimestamp;
775 yield* updateState((current) => ({
776 ...current,
777 status: "error",
778 message: error.message,
779 checkedAt,
780 downloadPercent: null,
781 errorContext: current.errorContext,
782 canRetry: getCanRetryFromState(current),
783 }));
784 }
785
786 yield* logUpdaterError(error.message, {
787 errorTag: error._tag,
788 operation: error.operation,
789 });
790 });
791
792 const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
793 raw: unknown,
794 ) {
795 yield* decodeDownloadProgressInfo(raw).pipe(
796 Effect.flatMap(
797 Effect.fn("desktop.updates.applyDownloadProgress")(function* (progress) {
798 const state = yield* Ref.get(updateStateRef);
799 const percent = Math.floor(progress.percent);
800 if (shouldBroadcastDownloadProgress(state, progress.percent) || state.message !== null) {
801 yield* setState(reduceDesktopUpdateStateOnDownloadProgress(state, progress.percent));
802 }
803 const milestone = percent - (percent % 10);
804 const lastLoggedMilestone = yield* Ref.get(lastLoggedDownloadMilestoneRef);
805 if (milestone > lastLoggedMilestone) {
806 yield* Ref.set(lastLoggedDownloadMilestoneRef, milestone);
807 yield* logUpdaterInfo("download progress", { percent });
808 }
809 }),
810 ),
811 Effect.catchCause((cause) => {
812 if (Cause.hasInterruptsOnly(cause)) {
813 return Effect.void;
814 }
815 const error = new DesktopUpdateEventHandlingError({ event: "download-progress", cause });
816 return logUpdaterWarning(error.message, {
817 errorTag: error._tag,
818 event: error.event,
819 });
820 }),
821 );
822 });
823
824 const handleUpdateDownloaded = Effect.fn("desktop.updates.handleUpdateDownloaded")(function* (
825 raw: unknown,
826 ) {
827 yield* decodeUpdateInfo(raw).pipe(
828 Effect.flatMap(
829 Effect.fn("desktop.updates.applyUpdateDownloaded")(function* (info) {
830 const state = yield* Ref.get(updateStateRef);
831 yield* setState(reduceDesktopUpdateStateOnDownloadComplete(state, info.version));
832 yield* logUpdaterInfo("update downloaded", { version: info.version });
833 }),
834 ),
835 Effect.catchCause((cause) => {
836 if (Cause.hasInterruptsOnly(cause)) {
837 return Effect.void;
838 }
839 const error = new DesktopUpdateEventHandlingError({ event: "update-downloaded", cause });
840 return logUpdaterWarning(error.message, {
841 errorTag: error._tag,
842 event: error.event,
843 });
844 }),
845 );
846 });
847
848 return DesktopUpdates.of({
849 getState: Ref.get(updateStateRef),
850 isActionActive: activeUpdateAction.pipe(Effect.map(Option.isSome)),
851 isInstallActive: activeUpdateAction.pipe(
852 Effect.map((action) => Option.isSome(action) && action.value === "install"),
853 ),
854 subscribe: stateMutex.withPermits(1)(
855 Effect.gen(function* () {
856 const subscription = yield* PubSub.subscribe(stateChanges);
857 const latest = yield* Ref.get(updateStateRef);
858 return { latest, changes: Stream.fromSubscription(subscription) };
859 }),
860 ),
861 emitState,
862 disabledReason: resolveDisabledReason,
863 configure: Effect.gen(function* () {
864 const context = yield* Effect.context<never>();
865 const runEffect = (effect: Effect.Effect<void>) => {
866 void Effect.runPromiseWith(context)(effect);
867 };
868
869 const appUpdateYmlConfig = yield* readAppUpdateYml;
870 yield* Ref.set(appUpdateYmlConfigRef, appUpdateYmlConfig);
871
872 if (config.mockUpdates) {
873 yield* electronUpdater.setFeedURL({
874 provider: "generic",
875 url: `http://localhost:${config.mockUpdateServerPort}`,
876 } as ElectronUpdater.ElectronUpdaterFeedUrl);
877 }
878
879 const settings = yield* desktopSettings.get;
880 const enabled = yield* shouldEnableAutoUpdates;
881 yield* setState(createBaseUpdateState(settings.updateChannel, enabled, environment));
882 if (!enabled) {
883 return;
884 }
885 yield* Ref.set(updaterConfiguredRef, true);
886
887 yield* electronUpdater.setAutoDownload(false);
888 yield* electronUpdater.setAutoInstallOnAppQuit(false);
889 yield* applyAutoUpdaterChannel(settings.updateChannel);
890 yield* electronUpdater.setDisableDifferentialDownload(
891 isArm64HostRunningIntelBuild(environment.runtimeInfo),
892 );
893
894 if (isArm64HostRunningIntelBuild(environment.runtimeInfo)) {
895 yield* logUpdaterInfo(
896 "Apple Silicon host detected while running Intel build; updates will switch to arm64 packages",
897 );
898 }
899
900 yield* electronUpdater.on("checking-for-update", () => {
901 runEffect(
902 logUpdaterInfo("looking for updates").pipe(
903 Effect.withSpan("desktop.updates.handleCheckingForUpdate"),
904 ),
905 );
906 });
907 yield* electronUpdater.on("update-available", (info: unknown) => {
908 runEffect(handleUpdateAvailable(info));
909 });
910 yield* electronUpdater.on("update-not-available", () => {
911 runEffect(handleUpdateNotAvailable);
912 });
913 yield* electronUpdater.on("error", (error: unknown) => {
914 runEffect(handleUpdaterError(error));
915 });
916 yield* electronUpdater.on("download-progress", (progress: unknown) => {
917 runEffect(handleDownloadProgress(progress));
918 });
919 yield* electronUpdater.on("update-downloaded", (info: unknown) => {
920 runEffect(handleUpdateDownloaded(info));
921 });
922
923 yield* startUpdatePollers;
924 }).pipe(Effect.withSpan("desktop.updates.configure")),
925 setChannel: Effect.fn("desktop.updates.setChannel")(function* (
926 nextChannel: DesktopUpdateChannel,
927 ) {
928 yield* Effect.annotateCurrentSpan({ channel: nextChannel });
929 const activeAction = yield* tryStartChannelChange;
930 if (Option.isSome(activeAction)) {
931 return yield* new DesktopUpdateActionInProgressError({
932 action: activeAction.value === "install-recovery" ? "install" : activeAction.value,
933 requestedChannel: nextChannel,
934 });
935 }
936
937 return yield* Effect.gen(function* () {
938 const state = yield* Ref.get(updateStateRef);
939 if (nextChannel === state.channel) {
940 return state;
941 }
942
943 yield* desktopSettings
944 .setUpdateChannel(nextChannel)
945 .pipe(
946 Effect.mapError(
947 (cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }),
948 ),
949 );
950
951 const enabled = yield* shouldEnableAutoUpdates;
952 yield* setState(createBaseUpdateState(nextChannel, enabled, environment));
953
954 if (!enabled || !(yield* Ref.get(updaterConfiguredRef))) {
955 return yield* Ref.get(updateStateRef);
956 }
957
958 yield* applyAutoUpdaterChannel(nextChannel);
959 const allowDowngrade = yield* electronUpdater.allowDowngrade;
960 yield* electronUpdater.setAllowDowngrade(true);
961 yield* checkForUpdates("channel-change", "held").pipe(
962 Effect.ensuring(electronUpdater.setAllowDowngrade(allowDowngrade).pipe(Effect.ignore)),
963 );
964 return yield* Ref.get(updateStateRef);
965 }).pipe(Effect.ensuring(finishUpdateAction("channel")));
966 }),
967 check: Effect.fn("desktop.updates.check")(function* (reason: string) {
968 yield* Effect.annotateCurrentSpan({ reason });
969 if (!(yield* Ref.get(updaterConfiguredRef))) {
970 return {
971 checked: false,
972 state: yield* Ref.get(updateStateRef),
973 };
974 }
975 const checked = yield* checkForUpdates(reason);
976 return {
977 checked,
978 state: yield* Ref.get(updateStateRef),
979 };
980 }),
981 download: Effect.gen(function* () {
982 const result = yield* downloadAvailableUpdate;
983 return {
984 accepted: result.accepted,
985 completed: result.completed,
986 state: yield* Ref.get(updateStateRef),
987 };
988 }).pipe(Effect.withSpan("desktop.updates.download")),
989 install: installWithExpectedVersion().pipe(
990 Effect.map(({ accepted, completed, state }) => ({ accepted, completed, state })),
991 ),
992 installPrepared: (expectedVersion) => installWithExpectedVersion(expectedVersion),
993 });
994});
995
996export const layer = Layer.effect(DesktopUpdates, make);