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