@capgo/capacitor-updater 8.52.1 → 8.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. package/README.md +198 -66
  2. package/android/build.gradle +2 -1
  3. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +409 -148
  4. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +521 -197
  5. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +2 -1
  6. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +226 -105
  7. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +30 -10
  8. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +318 -0
  9. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  10. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +4 -4
  11. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +1 -1
  12. package/dist/docs.json +378 -27
  13. package/dist/esm/definitions.d.ts +206 -7
  14. package/dist/esm/definitions.js.map +1 -1
  15. package/dist/plugin.cjs.js.map +1 -1
  16. package/dist/plugin.js.map +1 -1
  17. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +104 -52
  18. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +292 -94
  19. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +156 -10
  20. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +2 -1
  21. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +202 -90
  22. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  23. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +5 -2
  24. package/package.json +7 -3
@@ -31,6 +31,7 @@ import com.getcapacitor.JSArray;
31
31
  import com.getcapacitor.JSObject;
32
32
  import com.getcapacitor.Plugin;
33
33
  import com.getcapacitor.PluginCall;
34
+ import com.getcapacitor.PluginConfig;
34
35
  import com.getcapacitor.PluginHandle;
35
36
  import com.getcapacitor.PluginMethod;
36
37
  import com.getcapacitor.PluginResult;
@@ -95,18 +96,27 @@ public class CapacitorUpdaterPlugin extends Plugin {
95
96
  private static final String AUTO_UPDATE_MODE_ALWAYS = "always";
96
97
  private static final String AUTO_UPDATE_MODE_ONLY_DOWNLOAD = "onlyDownload";
97
98
 
99
+ // Stats action for a failed update check (offline, timeout, unreadable response, 429 block).
100
+ // Nothing was downloaded, so it is reported apart from download_fail.
101
+ static final String UPDATE_CHECK_ERROR_ACTION = "update_check_error";
102
+
103
+ // Single listener that receives every plugin event as { type, data }.
104
+ static final String UPDATER_EVENT = "updaterEvent";
105
+ // Deprecated alias emitted next to breakingAvailable; not forwarded to avoid duplicates.
106
+ private static final String DEPRECATED_MAJOR_AVAILABLE_EVENT = "majorAvailable";
107
+
98
108
  private Logger logger;
99
109
 
100
- private static final String updateUrlDefault = "https://plugin.capgo.app/updates";
101
- private static final String statsUrlDefault = "https://plugin.capgo.app/stats";
102
- private static final String channelUrlDefault = "https://plugin.capgo.app/channel_self";
110
+ static final String updateUrlDefault = "https://plugin.capgo.app/updates";
111
+ static final String statsUrlDefault = "https://plugin.capgo.app/stats";
112
+ static final String channelUrlDefault = "https://plugin.capgo.app/channel_self";
103
113
  private static final String KEEP_URL_FLAG_KEY = "__capgo_keep_url_path_after_reload";
104
- private static final String CUSTOM_ID_PREF_KEY = "CapacitorUpdater.customId";
105
- private static final String UPDATE_URL_PREF_KEY = "CapacitorUpdater.updateUrl";
106
- private static final String STATS_URL_PREF_KEY = "CapacitorUpdater.statsUrl";
107
- private static final String CHANNEL_URL_PREF_KEY = "CapacitorUpdater.channelUrl";
108
- private static final String DEFAULT_CHANNEL_PREF_KEY = "CapacitorUpdater.defaultChannel";
109
- private static final String PREVIEW_SESSION_PREF_KEY = "CapacitorUpdater.previewSession";
114
+ static final String CUSTOM_ID_PREF_KEY = "CapacitorUpdater.customId";
115
+ static final String UPDATE_URL_PREF_KEY = "CapacitorUpdater.updateUrl";
116
+ static final String STATS_URL_PREF_KEY = "CapacitorUpdater.statsUrl";
117
+ static final String CHANNEL_URL_PREF_KEY = "CapacitorUpdater.channelUrl";
118
+ static final String DEFAULT_CHANNEL_PREF_KEY = "CapacitorUpdater.defaultChannel";
119
+ static final String PREVIEW_SESSION_PREF_KEY = "CapacitorUpdater.previewSession";
110
120
  private static final String DEFAULT_CHANNEL_INSTALL_MARKER_PREF_KEY = "CapacitorUpdater.defaultChannelInstallMarkerCreated";
111
121
  private static final String DEFAULT_CHANNEL_INSTALL_MARKER_FILE = "CapacitorUpdater.defaultChannelInstallMarker";
112
122
  private static final String PREVIEW_PREVIOUS_SHAKE_MENU_PREF_KEY = "CapacitorUpdater.previewPreviousShakeMenu";
@@ -148,7 +158,11 @@ public class CapacitorUpdaterPlugin extends Plugin {
148
158
  static final int APPLICATION_EXIT_REASON_USER_REQUESTED = 10;
149
159
  static final int APPLICATION_EXIT_REASON_DEPENDENCY_DIED = 12;
150
160
 
151
- private final String pluginVersion = "8.52.1";
161
+ static final String PLUGIN_VERSION = "8.52.1";
162
+ // Set while a plugin instance (with its bridge) runs in this process. The headless update
163
+ // check then leaves installing to that instance instead of swapping bundles under it.
164
+ static volatile boolean instanceLoaded = false;
165
+ private final String pluginVersion = PLUGIN_VERSION;
152
166
  private static final String DELAY_CONDITION_PREFERENCES = "";
153
167
 
154
168
  private SharedPreferences.Editor editor;
@@ -222,6 +236,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
222
236
 
223
237
  private volatile Thread backgroundDownloadTask;
224
238
  private volatile Thread appReadyCheck;
239
+ // Between appMovedToBackground and appMovedToForeground. Android freezes backgrounded apps, so the
240
+ // page cannot call notifyAppReady until the next foreground, which arms a fresh rollback check.
241
+ private volatile boolean appInBackground = false;
225
242
  // When true, sendReadyToJs should wait for notifyAppReady before hiding splash.
226
243
  private volatile boolean pendingNotifyAppReadyWait = false;
227
244
  // Armed only after a reload. The next document stamps this generation into notifyAppReady.
@@ -247,6 +264,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
247
264
  private volatile boolean defaultChannelCleanupMustRetry = false;
248
265
 
249
266
  private int lastNotifiedStatPercent = 0;
267
+ private String lastNotifiedStatBundleId = null;
268
+ private final Object downloadStatLock = new Object();
250
269
 
251
270
  private DelayUpdateUtils delayUpdateUtils;
252
271
 
@@ -298,8 +317,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
298
317
  private AppUpdateManager appUpdateManager;
299
318
  private PluginCall pendingAppUpdateCall;
300
319
  private AppUpdateInfo cachedAppUpdateInfo;
301
- private static final int APP_UPDATE_REQUEST_CODE = 9001;
320
+ static final int APP_UPDATE_REQUEST_CODE = 9001;
302
321
  private InstallStateUpdatedListener installStateUpdatedListener;
322
+ private NativeUpdatePrompt nativeUpdatePrompt;
303
323
 
304
324
  private PackageInfo getCurrentPackageInfo() throws PackageManager.NameNotFoundException {
305
325
  final PackageManager packageManager = this.getContext().getPackageManager();
@@ -321,28 +341,21 @@ public class CapacitorUpdaterPlugin extends Plugin {
321
341
  for (final String eventName : BREAKING_EVENT_NAMES) {
322
342
  final JSObject payload = new JSObject();
323
343
  payload.put("version", version);
324
- CapacitorUpdaterPlugin.this.notifyListeners(eventName, payload);
344
+ CapacitorUpdaterPlugin.this.notifyListeners(eventName, payload, false);
325
345
  }
326
346
  }
327
347
 
328
348
  private boolean shouldNotifyBreakingEvents(final JSObject response) {
329
- if (response == null) {
330
- return false;
331
- }
332
-
333
- if (response.optBoolean("breaking", false)) {
334
- return true;
335
- }
336
-
337
- final String error = response.optString("error", "");
338
- final String message = response.optString("message", "");
339
- return "disable_auto_update_to_major".equals(error) || "store_update_required".equals(message);
349
+ return NativeUpdatePrompt.isNativeStoreUpdateBlock(response);
340
350
  }
341
351
 
342
352
  private void notifyBreakingEventsIfNeeded(final JSObject response, final String version) {
343
353
  if (shouldNotifyBreakingEvents(response)) {
344
354
  notifyBreakingEvents(version);
345
355
  }
356
+ if (this.nativeUpdatePrompt != null) {
357
+ this.nativeUpdatePrompt.maybeShowForUpdateBlock(response);
358
+ }
346
359
  }
347
360
 
348
361
  private void persistLastFailedBundle(BundleInfo bundle) {
@@ -685,9 +698,46 @@ public class CapacitorUpdaterPlugin extends Plugin {
685
698
  return startNewThread(function, 0);
686
699
  }
687
700
 
701
+ static Map<String, String> updateCheckErrorMetadata(final String error, final int statusCode) {
702
+ final Map<String, String> metadata = new HashMap<>();
703
+ metadata.put("error", error == null || error.isEmpty() ? "unknown" : error);
704
+ if (statusCode > 0) {
705
+ metadata.put("status_code", String.valueOf(statusCode));
706
+ }
707
+ return metadata;
708
+ }
709
+
710
+ static JSObject updaterEventPayload(final String eventName, final JSObject data) {
711
+ final JSObject payload = new JSObject();
712
+ payload.put("type", eventName);
713
+ payload.put("data", data != null ? data : new JSObject());
714
+ return payload;
715
+ }
716
+
717
+ static boolean shouldForwardToUpdaterEvent(final String eventName) {
718
+ return !UPDATER_EVENT.equals(eventName) && !DEPRECATED_MAJOR_AVAILABLE_EVENT.equals(eventName);
719
+ }
720
+
721
+ // Capacitor replays retained events through this overload when a listener attaches. They were
722
+ // already forwarded to updaterEvent when emitted, so skip forwarding here. Plugin code must emit
723
+ // through the three-argument overload.
724
+ @Override
725
+ protected void notifyListeners(final String eventName, final JSObject data) {
726
+ super.notifyListeners(eventName, data, false);
727
+ }
728
+
729
+ @Override
730
+ protected void notifyListeners(final String eventName, final JSObject data, final boolean retainUntilConsumed) {
731
+ super.notifyListeners(eventName, data, retainUntilConsumed);
732
+ if (shouldForwardToUpdaterEvent(eventName)) {
733
+ super.notifyListeners(UPDATER_EVENT, updaterEventPayload(eventName, data), retainUntilConsumed);
734
+ }
735
+ }
736
+
688
737
  @Override
689
738
  public void load() {
690
739
  super.load();
740
+ instanceLoaded = true;
691
741
 
692
742
  // Initialize logger with osLogging config
693
743
  // Default to true for both platforms to enable system logging by default
@@ -721,11 +771,16 @@ public class CapacitorUpdaterPlugin extends Plugin {
721
771
  CapacitorUpdaterPlugin.this.emitLaunchDownloadReady(bundle, status);
722
772
  }
723
773
 
774
+ @Override
775
+ public void nextBundleReady(final BundleInfo bundle) {
776
+ CapacitorUpdaterPlugin.this.installNextIfInBackground();
777
+ }
778
+
724
779
  @Override
725
780
  public void notifyListeners(final String id, final Map<String, Object> res) {
726
781
  if (activity != null) {
727
782
  activity.runOnUiThread(() -> {
728
- CapacitorUpdaterPlugin.this.notifyListeners(id, InternalUtils.mapToJSObject(res));
783
+ CapacitorUpdaterPlugin.this.notifyListeners(id, InternalUtils.mapToJSObject(res), false);
729
784
  });
730
785
  } else {
731
786
  logger.warn("notifyListeners: Activity is null, skipping notification for event: " + id);
@@ -734,6 +789,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
734
789
  };
735
790
  final PackageInfo pInfo = this.getCurrentPackageInfo();
736
791
  this.implementation.activity = this.getActivity();
792
+ this.implementation.appContext = this.getContext().getApplicationContext();
737
793
  this.implementation.versionBuild = this.getConfig().getString("version", pInfo.versionName);
738
794
  this.implementation.CAP_SERVER_PATH = WebView.CAP_SERVER_PATH;
739
795
  this.implementation.pluginVersion = this.pluginVersion;
@@ -870,7 +926,6 @@ public class CapacitorUpdaterPlugin extends Plugin {
870
926
  }
871
927
  logger.info("init for device " + this.implementation.deviceID);
872
928
  logger.info("version native " + this.currentVersionNative.getOriginalString());
873
- this.reportAppLaunchStart();
874
929
  this.autoDeleteFailed = this.getConfig().getBoolean("autoDeleteFailed", true);
875
930
  this.autoDeletePrevious = this.getConfig().getBoolean("autoDeletePrevious", true);
876
931
  this.updateUrl = this.getConfig().getString("updateUrl", updateUrlDefault);
@@ -900,6 +955,42 @@ public class CapacitorUpdaterPlugin extends Plugin {
900
955
  this.shakeMenuEnabled = this.getConfig().getBoolean("shakeMenu", false);
901
956
  this.shakeChannelSelectorEnabled = this.getConfig().getBoolean("allowShakeChannelSelector", false);
902
957
  this.shakeMenuGesture = normalizedShakeMenuGesture(this.getConfig().getString("shakeMenuGesture", SHAKE_MENU_GESTURE_SHAKE));
958
+ this.nativeUpdatePrompt = new NativeUpdatePrompt(
959
+ this.getConfig(),
960
+ this.prefs,
961
+ this.logger,
962
+ new NativeUpdatePrompt.NativeUpdatePromptHost() {
963
+ @Override
964
+ public Activity getActivity() {
965
+ return CapacitorUpdaterPlugin.this.getActivity();
966
+ }
967
+
968
+ @Override
969
+ public String getNativeBuildVersion() {
970
+ return CapacitorUpdaterPlugin.this.currentBuildVersion;
971
+ }
972
+
973
+ @Override
974
+ public AppUpdateManager getAppUpdateManager() {
975
+ return CapacitorUpdaterPlugin.this.getAppUpdateManager();
976
+ }
977
+
978
+ @Override
979
+ public AppUpdateInfo getCachedAppUpdateInfo() {
980
+ return CapacitorUpdaterPlugin.this.cachedAppUpdateInfo;
981
+ }
982
+
983
+ @Override
984
+ public void setCachedAppUpdateInfo(final AppUpdateInfo info) {
985
+ CapacitorUpdaterPlugin.this.cachedAppUpdateInfo = info;
986
+ }
987
+
988
+ @Override
989
+ public String getPackageNameForStore() {
990
+ return CapacitorUpdaterPlugin.this.getContext().getPackageName();
991
+ }
992
+ }
993
+ );
903
994
  this.previewSessionEnabled = Boolean.TRUE.equals(this.allowPreview) && this.prefs.getBoolean(PREVIEW_SESSION_PREF_KEY, false);
904
995
  if (!Boolean.TRUE.equals(this.allowPreview) && this.prefs.getBoolean(PREVIEW_SESSION_PREF_KEY, false)) {
905
996
  this.clearPreviewSessionBecauseDisabled();
@@ -923,11 +1014,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
923
1014
  // Check if app was recently installed/updated BEFORE cleanupObsoleteVersions updates LatestVersionNative
924
1015
  this.wasRecentlyInstalledOrUpdated = this.checkIfRecentlyInstalledOrUpdated();
925
1016
 
926
- this.implementation.autoReset(this.currentBuildVersion, resetWhenUpdate);
927
- if (nativeBuildVersionChanged) {
928
- this.clearPreviewSessionForNativeBuildChange();
929
- }
930
- this.leavePreviewSessionForLaunchIntentIfNeeded();
1017
+ this.resetStartupBundleAndReportAppLaunchStart(resetWhenUpdate, nativeBuildVersionChanged);
931
1018
  this.reportNativeVersionStatsIfChanged();
932
1019
  this.reportPreviousAppExitReasons();
933
1020
  this.reportPreviousWebViewRenderProcessGone();
@@ -2139,33 +2226,35 @@ public class CapacitorUpdaterPlugin extends Plugin {
2139
2226
  }
2140
2227
 
2141
2228
  private void configureAutoUpdateModeFromConfig() {
2142
- final String configuredMode = this.getConfig().getString("autoUpdate", null);
2229
+ this.autoUpdateMode = autoUpdateModeFromConfig(this.getConfig(), logger);
2230
+ this.autoUpdate = isAutoUpdateModeEnabled(this.autoUpdateMode);
2231
+ this.directUpdateMode = directUpdateModeForAutoUpdateMode(this.autoUpdateMode);
2232
+ this.implementation.directUpdate = isDirectUpdateMode(this.directUpdateMode);
2233
+ }
2234
+
2235
+ /** Resolves autoUpdate (and the legacy directUpdate) from the plugin config. Shared with the headless update check. */
2236
+ static String autoUpdateModeFromConfig(final PluginConfig pluginConfig, final Logger logger) {
2237
+ final String configuredMode = pluginConfig.getString("autoUpdate", null);
2143
2238
  if (configuredMode != null && !configuredMode.isEmpty() && !"true".equals(configuredMode) && !"false".equals(configuredMode)) {
2144
- this.autoUpdateMode = normalizedAutoUpdateMode(configuredMode);
2145
- if (!this.autoUpdateMode.equals(configuredMode)) {
2239
+ final String mode = normalizedAutoUpdateMode(configuredMode);
2240
+ if (!mode.equals(configuredMode) && logger != null) {
2146
2241
  logger.error(
2147
2242
  "Invalid autoUpdate value: \"" +
2148
2243
  configuredMode +
2149
2244
  "\". Supported values are: true, false, \"off\", \"atBackground\", \"atInstall\", \"onLaunch\", \"always\", \"onlyDownload\". Defaulting to \"atBackground\"."
2150
2245
  );
2151
2246
  }
2152
- } else {
2153
- final boolean enabled =
2154
- configuredMode != null
2155
- ? "true".equals(configuredMode)
2156
- : Boolean.TRUE.equals(this.getConfig().getBoolean("autoUpdate", true));
2157
- this.autoUpdateMode = enabled
2158
- ? autoUpdateModeForLegacyDirectUpdateMode(this.resolveLegacyDirectUpdateModeFromConfig())
2159
- : AUTO_UPDATE_MODE_OFF;
2247
+ return mode;
2160
2248
  }
2161
-
2162
- this.autoUpdate = isAutoUpdateModeEnabled(this.autoUpdateMode);
2163
- this.directUpdateMode = directUpdateModeForAutoUpdateMode(this.autoUpdateMode);
2164
- this.implementation.directUpdate = isDirectUpdateMode(this.directUpdateMode);
2249
+ final boolean enabled =
2250
+ configuredMode != null ? "true".equals(configuredMode) : Boolean.TRUE.equals(pluginConfig.getBoolean("autoUpdate", true));
2251
+ return enabled
2252
+ ? autoUpdateModeForLegacyDirectUpdateMode(resolveLegacyDirectUpdateModeFromConfig(pluginConfig, logger))
2253
+ : AUTO_UPDATE_MODE_OFF;
2165
2254
  }
2166
2255
 
2167
- private String resolveLegacyDirectUpdateModeFromConfig() {
2168
- final String directUpdateConfig = this.getConfig().getString("directUpdate", null);
2256
+ private static String resolveLegacyDirectUpdateModeFromConfig(final PluginConfig pluginConfig, final Logger logger) {
2257
+ final String directUpdateConfig = pluginConfig.getString("directUpdate", null);
2169
2258
  if (directUpdateConfig != null) {
2170
2259
  if ("true".equals(directUpdateConfig)) {
2171
2260
  return AUTO_UPDATE_MODE_ALWAYS;
@@ -2173,15 +2262,17 @@ public class CapacitorUpdaterPlugin extends Plugin {
2173
2262
  if ("false".equals(directUpdateConfig) || isDirectUpdateMode(directUpdateConfig)) {
2174
2263
  return directUpdateConfig;
2175
2264
  }
2176
- logger.error(
2177
- "Invalid directUpdate value: \"" +
2178
- directUpdateConfig +
2179
- "\". Supported values are: false, true, \"always\", \"atInstall\", \"onLaunch\". Defaulting to \"false\"."
2180
- );
2265
+ if (logger != null) {
2266
+ logger.error(
2267
+ "Invalid directUpdate value: \"" +
2268
+ directUpdateConfig +
2269
+ "\". Supported values are: false, true, \"always\", \"atInstall\", \"onLaunch\". Defaulting to \"false\"."
2270
+ );
2271
+ }
2181
2272
  return "false";
2182
2273
  }
2183
2274
 
2184
- return Boolean.TRUE.equals(this.getConfig().getBoolean("directUpdate", false)) ? AUTO_UPDATE_MODE_ALWAYS : "false";
2275
+ return Boolean.TRUE.equals(pluginConfig.getBoolean("directUpdate", false)) ? AUTO_UPDATE_MODE_ALWAYS : "false";
2185
2276
  }
2186
2277
 
2187
2278
  static String normalizedAutoUpdateMode(final String value) {
@@ -2343,6 +2434,27 @@ public class CapacitorUpdaterPlugin extends Plugin {
2343
2434
  this.logger = logger;
2344
2435
  }
2345
2436
 
2437
+ void reportAppLaunchStartForTesting() {
2438
+ this.reportAppLaunchStart();
2439
+ }
2440
+
2441
+ void setCurrentBuildVersionForTesting(final String currentBuildVersion) {
2442
+ this.currentBuildVersion = currentBuildVersion;
2443
+ }
2444
+
2445
+ void resetStartupBundleAndReportAppLaunchStartForTesting(final boolean resetWhenUpdate, final boolean nativeBuildVersionChanged) {
2446
+ this.resetStartupBundleAndReportAppLaunchStart(resetWhenUpdate, nativeBuildVersionChanged);
2447
+ }
2448
+
2449
+ private void resetStartupBundleAndReportAppLaunchStart(final boolean resetWhenUpdate, final boolean nativeBuildVersionChanged) {
2450
+ this.implementation.autoReset(this.currentBuildVersion, resetWhenUpdate);
2451
+ if (nativeBuildVersionChanged) {
2452
+ this.clearPreviewSessionForNativeBuildChange();
2453
+ }
2454
+ this.leavePreviewSessionForLaunchIntentIfNeeded();
2455
+ this.reportAppLaunchStart();
2456
+ }
2457
+
2346
2458
  void completeBackgroundTaskForTesting(final BundleInfo current, final boolean plannedDirectUpdate) {
2347
2459
  this.endBackGroundTaskWithNotif("test", current.getVersionName(), current, false, plannedDirectUpdate);
2348
2460
  }
@@ -2406,7 +2518,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
2406
2518
  this.implementation.setNextBundle(latest.getId());
2407
2519
  final JSObject ret = new JSObject();
2408
2520
  ret.put("bundle", InternalUtils.mapToJSObject(latest.toJSONMap()));
2409
- this.notifyListeners("updateAvailable", ret);
2521
+ this.notifyListeners("updateAvailable", ret, false);
2410
2522
  sendReadyToJs(
2411
2523
  this.implementation.getCurrentBundle(),
2412
2524
  "Direct update reload failed, update will install next background",
@@ -2476,6 +2588,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
2476
2588
  final Set<String> allowedIds = this.implementation.allowedBundleIdsForCleanup();
2477
2589
  this.implementation.cleanupDownloadDirectories(allowedIds);
2478
2590
  this.implementation.cleanupOrphanedTempFolders(null);
2591
+ this.implementation.cleanupOrphanedManifestStagingFolders(null);
2479
2592
 
2480
2593
  this.persistCurrentNativeBuildVersion();
2481
2594
  } catch (Exception e) {
@@ -2524,24 +2637,49 @@ public class CapacitorUpdaterPlugin extends Plugin {
2524
2637
  logger.info("Cleanup finished, proceeding with download");
2525
2638
  }
2526
2639
 
2640
+ /**
2641
+ * Returns the {@code download_N} stat to send for this progress, or null. Buckets are tracked per
2642
+ * download: a new download (percent 0 or another bundle id) starts from zero again.
2643
+ */
2644
+ String nextDownloadStatAction(final String id, final int percent) {
2645
+ synchronized (this.downloadStatLock) {
2646
+ if (percent == 0 || !Objects.equals(id, this.lastNotifiedStatBundleId)) {
2647
+ this.lastNotifiedStatBundleId = id;
2648
+ this.lastNotifiedStatPercent = 0;
2649
+ }
2650
+ final int currentStatPercent = (percent / 10) * 10; // Round down to nearest 10
2651
+ if (currentStatPercent <= this.lastNotifiedStatPercent) {
2652
+ return null;
2653
+ }
2654
+ this.lastNotifiedStatPercent = currentStatPercent;
2655
+ return "download_" + currentStatPercent;
2656
+ }
2657
+ }
2658
+
2659
+ private void markDownloadStatPercent(final String id, final int percent) {
2660
+ synchronized (this.downloadStatLock) {
2661
+ this.lastNotifiedStatBundleId = id;
2662
+ this.lastNotifiedStatPercent = percent;
2663
+ }
2664
+ }
2665
+
2527
2666
  public void notifyDownload(final String id, final int percent) {
2528
2667
  try {
2529
2668
  final JSObject ret = new JSObject();
2530
2669
  ret.put("percent", percent);
2531
2670
  final BundleInfo bundleInfo = this.implementation.getBundleInfo(id);
2532
2671
  ret.put("bundle", InternalUtils.mapToJSObject(bundleInfo.toJSONMap()));
2533
- this.notifyListeners("download", ret);
2672
+ this.notifyListeners("download", ret, false);
2534
2673
 
2535
2674
  if (percent == 100) {
2536
2675
  final JSObject retDownloadComplete = new JSObject(ret, new String[] { "bundle" });
2537
- this.notifyListeners("downloadComplete", retDownloadComplete);
2676
+ this.notifyListeners("downloadComplete", retDownloadComplete, false);
2538
2677
  this.implementation.sendStats("download_complete", bundleInfo.getVersionName());
2539
- lastNotifiedStatPercent = 100;
2678
+ this.markDownloadStatPercent(id, 100);
2540
2679
  } else {
2541
- int currentStatPercent = (percent / 10) * 10; // Round down to nearest 10
2542
- if (currentStatPercent > lastNotifiedStatPercent) {
2543
- this.implementation.sendStats("download_" + currentStatPercent, bundleInfo.getVersionName());
2544
- lastNotifiedStatPercent = currentStatPercent;
2680
+ final String statAction = this.nextDownloadStatAction(id, percent);
2681
+ if (statAction != null) {
2682
+ this.implementation.sendStats(statAction, bundleInfo.getVersionName());
2545
2683
  }
2546
2684
  }
2547
2685
  } catch (final Exception e) {
@@ -2761,7 +2899,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
2761
2899
  JSObject eventData = new JSObject();
2762
2900
  eventData.put("channel", channel);
2763
2901
  eventData.put("message", errorMessage);
2764
- notifyListeners("channelPrivate", eventData);
2902
+ notifyListeners("channelPrivate", eventData, false);
2765
2903
  }
2766
2904
 
2767
2905
  JSObject errorObj = new JSObject();
@@ -2921,22 +3059,26 @@ public class CapacitorUpdaterPlugin extends Plugin {
2921
3059
  } catch (final Exception e) {
2922
3060
  logger.error("Failed to download from: " + url + " " + e.getMessage());
2923
3061
  call.reject("Failed to download from: " + url, e);
2924
- final JSObject ret = new JSObject();
2925
- ret.put("version", version);
2926
- CapacitorUpdaterPlugin.this.notifyListeners("downloadFailed", ret);
2927
- final BundleInfo current = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
2928
- CapacitorUpdaterPlugin.this.implementation.sendStats("download_fail", current.getVersionName());
3062
+ CapacitorUpdaterPlugin.this.notifyManualDownloadFailed(version, e);
2929
3063
  }
2930
3064
  });
2931
3065
  } catch (final Exception e) {
2932
3066
  logger.error("Failed to download from: " + url + " " + e.getMessage());
2933
3067
  call.reject("Failed to download from: " + url, e);
2934
- final JSObject ret = new JSObject();
2935
- ret.put("version", version);
2936
- CapacitorUpdaterPlugin.this.notifyListeners("downloadFailed", ret);
2937
- final BundleInfo current = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
2938
- CapacitorUpdaterPlugin.this.implementation.sendStats("download_fail", current.getVersionName());
3068
+ this.notifyManualDownloadFailed(version, e);
3069
+ }
3070
+ }
3071
+
3072
+ /** Emits downloadFailed + download_fail once: the updater already did it for worker failures. */
3073
+ void notifyManualDownloadFailed(final String version, final Exception error) {
3074
+ if (error instanceof CapgoUpdater.ReportedDownloadFailureException) {
3075
+ return;
2939
3076
  }
3077
+ final JSObject ret = new JSObject();
3078
+ ret.put("version", version);
3079
+ this.notifyListeners("downloadFailed", ret, false);
3080
+ final BundleInfo current = this.implementation.getCurrentBundle();
3081
+ this.implementation.sendStats("download_fail", current.getVersionName());
2940
3082
  }
2941
3083
 
2942
3084
  private void syncKeepUrlPathFlag(final boolean enabled) {
@@ -3058,6 +3200,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
3058
3200
  }
3059
3201
 
3060
3202
  protected boolean _reload() {
3203
+ if (this.appInBackground) {
3204
+ return this.reloadInBackground();
3205
+ }
3061
3206
  // Drop any launch pending wait; this reload owns notifyAppReady synchronization.
3062
3207
  this.clearPendingNotifyAppReadyWait();
3063
3208
  final int phase = this.semaphoreUp();
@@ -3065,18 +3210,29 @@ public class CapacitorUpdaterPlugin extends Plugin {
3065
3210
 
3066
3211
  final long waitTimeMs = this.resolveAppReadyCheckTimeoutMs();
3067
3212
  this.checkAppReady(waitTimeMs);
3068
- this.notifyListeners("appReloaded", new JSObject());
3213
+ this.notifyListeners("appReloaded", new JSObject(), false);
3069
3214
 
3070
3215
  // Wait for the reload to complete (until notifyAppReady is called)
3071
3216
  return this.semaphoreWait(phase, waitTimeMs);
3072
3217
  }
3073
3218
 
3219
+ /**
3220
+ * A backgrounded app is frozen by Android: the reloaded page cannot call notifyAppReady before the
3221
+ * next foreground, so waiting here would only time out. Apply the bundle, and let the next appReady
3222
+ * wait for the page instead (the next foreground also arms a fresh rollback check).
3223
+ */
3224
+ private boolean reloadInBackground() {
3225
+ logger.info("App is in background, reload does not wait for notifyAppReady");
3226
+ this.armPendingNotifyAppReadyWait();
3227
+ return this.reloadWithoutWaitingForAppReady();
3228
+ }
3229
+
3074
3230
  protected boolean reloadWithoutWaitingForAppReady() {
3075
3231
  this.applyCurrentBundleToBridge();
3076
3232
 
3077
3233
  final long waitTimeMs = this.resolveAppReadyCheckTimeoutMs();
3078
3234
  this.checkAppReady(waitTimeMs);
3079
- this.notifyListeners("appReloaded", new JSObject());
3235
+ this.notifyListeners("appReloaded", new JSObject(), false);
3080
3236
  return true;
3081
3237
  }
3082
3238
 
@@ -3167,7 +3323,11 @@ public class CapacitorUpdaterPlugin extends Plugin {
3167
3323
  if (!this.implementation.set(id)) {
3168
3324
  logger.info("No such bundle " + id);
3169
3325
  call.reject("Update failed, id " + id + " does not exist.");
3170
- } else if (Boolean.TRUE.equals(this.previewSessionEnabled)) {
3326
+ return;
3327
+ }
3328
+ // The bundle is now active: it must not stay reported as the pending next bundle.
3329
+ this.implementation.clearNextBundleIfCurrent();
3330
+ if (Boolean.TRUE.equals(this.previewSessionEnabled)) {
3171
3331
  logger.info("Preview session set active bundle " + id + " without waiting for preview app readiness");
3172
3332
  final BundleInfo bundle = this.implementation.getBundleInfo(id);
3173
3333
  this.recordPreviewBundle(bundle);
@@ -3597,7 +3757,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
3597
3757
  }
3598
3758
 
3599
3759
  private void leavePreviewSessionForLaunchIntentIfNeeded() {
3600
- final Intent intent = getActivity() == null ? null : getActivity().getIntent();
3760
+ final Bridge bridge = getBridge();
3761
+ final Activity launchActivity = bridge == null ? null : bridge.getActivity();
3762
+ final Intent intent = launchActivity == null ? null : launchActivity.getIntent();
3601
3763
  if (
3602
3764
  intent == null ||
3603
3765
  !Intent.ACTION_VIEW.equals(intent.getAction()) ||
@@ -4287,8 +4449,13 @@ public class CapacitorUpdaterPlugin extends Plugin {
4287
4449
  logger.error("Error no url or wrong format");
4288
4450
  return "unavailable";
4289
4451
  }
4452
+ // The TS contract only knows queued / already_running / unavailable.
4290
4453
  if (this.shouldBlockAutoUpdateForPreviewSession()) {
4291
- return "preview_session";
4454
+ return "unavailable";
4455
+ }
4456
+ if (!this._isAutoUpdateEnabled()) {
4457
+ logger.info("Auto update is disabled, update check not triggered");
4458
+ return "unavailable";
4292
4459
  }
4293
4460
  synchronized (this) {
4294
4461
  final Thread previousTask = this.backgroundDownloadTask;
@@ -4421,6 +4588,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
4421
4588
  @PluginMethod
4422
4589
  public void getNextBundle(final PluginCall call) {
4423
4590
  try {
4591
+ // Heals a next bundle left stored after it was activated (set() did not clear it before).
4592
+ this.implementation.clearNextBundleIfCurrent();
4424
4593
  final BundleInfo bundle = this.implementation.getNextBundle();
4425
4594
  if (bundle == null) {
4426
4595
  call.resolve(null);
@@ -4463,59 +4632,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4463
4632
  new TimerTask() {
4464
4633
  @Override
4465
4634
  public void run() {
4466
- try {
4467
- if (CapacitorUpdaterPlugin.this.shouldBlockAutoUpdateForPreviewSession()) {
4468
- return;
4469
- }
4470
- CapacitorUpdaterPlugin.this.implementation.getLatest(CapacitorUpdaterPlugin.this.updateUrl, null, (res) -> {
4471
- if (CapacitorUpdaterPlugin.this.shouldBlockAutoUpdateForPreviewSession()) {
4472
- return;
4473
- }
4474
- JSObject jsRes = InternalUtils.mapToJSObject(res);
4475
- if (jsRes.has("error") || jsRes.has("kind")) {
4476
- final BundleInfo current = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
4477
- String error = jsRes.has("error") ? jsRes.getString("error") : "";
4478
- String errorMessage = jsRes.has("message")
4479
- ? jsRes.getString("message")
4480
- : "server did not provide a message";
4481
- int statusCode = jsRes.has("statusCode") ? jsRes.optInt("statusCode", 0) : 0;
4482
- String kind = CapacitorUpdaterPlugin.this.getUpdateResponseKind(
4483
- jsRes.has("kind") ? jsRes.getString("kind") : null
4484
- );
4485
- String latestVersion = jsRes.has("version") ? jsRes.getString("version") : current.getVersionName();
4486
- CapacitorUpdaterPlugin.this.notifyUpdateCheckResult(
4487
- kind,
4488
- error,
4489
- errorMessage,
4490
- statusCode,
4491
- latestVersion,
4492
- current
4493
- );
4494
-
4495
- if ("failed".equals(kind)) {
4496
- logger.error("getLatest failed with error: " + error + ", message: " + errorMessage);
4497
- } else if ("blocked".equals(kind)) {
4498
- logger.info("Update check blocked with error: " + error);
4499
- } else {
4500
- logger.info("No new version available");
4501
- }
4502
- } else if (jsRes.has("version")) {
4503
- String newVersion = jsRes.getString("version");
4504
- String currentVersion = String.valueOf(CapacitorUpdaterPlugin.this.implementation.getCurrentBundle());
4505
- if (!Objects.equals(newVersion, currentVersion)) {
4506
- logger.info("New version found: " + newVersion);
4507
- // Check if download is already in progress (with timeout protection)
4508
- if (!CapacitorUpdaterPlugin.this.isDownloadStuckOrTimedOut()) {
4509
- CapacitorUpdaterPlugin.this.backgroundDownload();
4510
- } else {
4511
- logger.info("Download already in progress, skipping duplicate download request");
4512
- }
4513
- }
4514
- }
4515
- });
4516
- } catch (final Exception e) {
4517
- logger.error("Failed to check for update " + e.getMessage());
4518
- }
4635
+ CapacitorUpdaterPlugin.this.runPeriodicUpdateCheck();
4519
4636
  }
4520
4637
  },
4521
4638
  this.periodCheckDelay,
@@ -4523,6 +4640,51 @@ public class CapacitorUpdaterPlugin extends Plugin {
4523
4640
  );
4524
4641
  }
4525
4642
 
4643
+ void runPeriodicUpdateCheck() {
4644
+ try {
4645
+ if (this.shouldBlockAutoUpdateForPreviewSession()) {
4646
+ return;
4647
+ }
4648
+ this.implementation.getLatest(this.updateUrl, null, (res) -> {
4649
+ if (this.shouldBlockAutoUpdateForPreviewSession()) {
4650
+ return;
4651
+ }
4652
+ JSObject jsRes = InternalUtils.mapToJSObject(res);
4653
+ if (jsRes.has("error") || jsRes.has("kind")) {
4654
+ final BundleInfo current = this.implementation.getCurrentBundle();
4655
+ String error = jsRes.has("error") ? jsRes.getString("error") : "";
4656
+ String errorMessage = jsRes.has("message") ? jsRes.getString("message") : "server did not provide a message";
4657
+ int statusCode = jsRes.has("statusCode") ? jsRes.optInt("statusCode", 0) : 0;
4658
+ String kind = this.getUpdateResponseKind(jsRes.has("kind") ? jsRes.getString("kind") : null);
4659
+ String latestVersion = jsRes.has("version") ? jsRes.getString("version") : current.getVersionName();
4660
+ this.notifyUpdateCheckResult(kind, error, errorMessage, statusCode, latestVersion, current);
4661
+
4662
+ if ("failed".equals(kind)) {
4663
+ logger.error("getLatest failed with error: " + error + ", message: " + errorMessage);
4664
+ } else if ("blocked".equals(kind)) {
4665
+ logger.info("Update check blocked with error: " + error);
4666
+ } else {
4667
+ logger.info("No new version available");
4668
+ }
4669
+ } else if (jsRes.has("version")) {
4670
+ String newVersion = jsRes.getString("version");
4671
+ String currentVersion = this.implementation.getCurrentBundle().getVersionName();
4672
+ if (!Objects.equals(newVersion, currentVersion)) {
4673
+ logger.info("New version found: " + newVersion);
4674
+ // Check if download is already in progress (with timeout protection)
4675
+ if (!this.isDownloadStuckOrTimedOut()) {
4676
+ this.backgroundDownload();
4677
+ } else {
4678
+ logger.info("Download already in progress, skipping duplicate download request");
4679
+ }
4680
+ }
4681
+ }
4682
+ });
4683
+ } catch (final Exception e) {
4684
+ logger.error("Failed to check for update " + e.getMessage());
4685
+ }
4686
+ }
4687
+
4526
4688
  static boolean shouldAcceptReadyCall(
4527
4689
  final boolean guardArmed,
4528
4690
  final int expectedGeneration,
@@ -4672,11 +4834,27 @@ public class CapacitorUpdaterPlugin extends Plugin {
4672
4834
  }
4673
4835
  }
4674
4836
 
4675
- if (this.delayUpdateUtils.setMultiDelay(delayConditions.toString())) {
4676
- call.resolve();
4677
- } else {
4837
+ final String conditionMode = call.getData().optString("conditionMode", DelayUpdateUtils.DELAY_CONDITION_MODE_AND);
4838
+ final String previousConditions = prefs.getString(DelayUpdateUtils.DELAY_CONDITION_PREFERENCES, "[]");
4839
+ final String previousMode = this.delayUpdateUtils.getConditionMode();
4840
+ if (!this.delayUpdateUtils.setMultiDelay(delayConditions.toString())) {
4841
+ if (!this.delayUpdateUtils.setMultiDelay(previousConditions)) {
4842
+ logger.error("Failed to restore previous delay conditions after setMultiDelay failure");
4843
+ }
4678
4844
  call.reject("Failed to delay update");
4845
+ return;
4846
+ }
4847
+ if (!this.delayUpdateUtils.setConditionMode(conditionMode)) {
4848
+ if (!this.delayUpdateUtils.setMultiDelay(previousConditions)) {
4849
+ logger.error("Failed to restore previous delay conditions after setConditionMode failure");
4850
+ }
4851
+ if (!this.delayUpdateUtils.setConditionMode(previousMode)) {
4852
+ logger.error("Failed to restore previous delay condition mode after setConditionMode failure");
4853
+ }
4854
+ call.reject("Failed to delay update");
4855
+ return;
4679
4856
  }
4857
+ call.resolve();
4680
4858
  } catch (final Exception e) {
4681
4859
  logger.error("Failed to delay update, [Error calling 'setMultiDelay()'] " + e.getMessage());
4682
4860
  call.reject("Failed to delay update", e);
@@ -4797,11 +4975,11 @@ public class CapacitorUpdaterPlugin extends Plugin {
4797
4975
  ret.put("statusCode", statusCode);
4798
4976
  ret.put("version", version);
4799
4977
  ret.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
4800
- this.notifyListeners("updateCheckResult", ret);
4978
+ this.notifyListeners("updateCheckResult", ret, false);
4801
4979
  }
4802
4980
 
4803
4981
  private void ensureBridgeSet() {
4804
- if (this.bridge != null && this.bridge.getWebView() != null) {
4982
+ if (this.bridge != null && this.bridge.getWebView() != null && !this.getConfig().getBoolean("disableJSLogging", false)) {
4805
4983
  logger.setBridge(this.bridge);
4806
4984
  }
4807
4985
  }
@@ -4881,12 +5059,12 @@ public class CapacitorUpdaterPlugin extends Plugin {
4881
5059
  }
4882
5060
  final JSObject ret = new JSObject();
4883
5061
  ret.put("version", latestVersionName);
4884
- this.notifyListeners(failureEvent, ret);
5062
+ this.notifyListeners(failureEvent, ret, false);
4885
5063
  }
4886
5064
  if (shouldNotifyNoNeedUpdate) {
4887
5065
  final JSObject ret = new JSObject();
4888
5066
  ret.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
4889
- this.notifyListeners("noNeedUpdate", ret);
5067
+ this.notifyListeners("noNeedUpdate", ret, false);
4890
5068
  }
4891
5069
  this.sendReadyToJs(current, msg, plannedDirectUpdate);
4892
5070
  this.backgroundDownloadTask = null;
@@ -4924,6 +5102,26 @@ public class CapacitorUpdaterPlugin extends Plugin {
4924
5102
  return true;
4925
5103
  }
4926
5104
 
5105
+ /**
5106
+ * Security gates of an auto-update download, checked before it starts. Returns the cycle status
5107
+ * when the download must not start (after sending its stat), or null.
5108
+ */
5109
+ private String autoUpdateDownloadBlockedReason(final JSObject latest, final String latestVersionName) {
5110
+ final String sessionKey = latest.getString("sessionKey", "");
5111
+ if (!this.implementation.publicKey.isEmpty() && !CryptoCipher.isValidSessionKey(sessionKey)) {
5112
+ logger.error("Public key present but no valid session key provided");
5113
+ this.implementation.sendStats("session_key_required", latestVersionName);
5114
+ return "Session key required when public key is present";
5115
+ }
5116
+ final String checksum = latest.getString("checksum", "");
5117
+ if (!latest.has("manifest") && (checksum == null || checksum.isEmpty())) {
5118
+ logger.error("No checksum provided");
5119
+ this.implementation.sendStats("checksum_required", latestVersionName);
5120
+ return "Checksum required";
5121
+ }
5122
+ return null;
5123
+ }
5124
+
4927
5125
  private synchronized Thread backgroundDownload() {
4928
5126
  if (this.shouldBlockAutoUpdateForPreviewSession()) {
4929
5127
  return null;
@@ -4937,8 +5135,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
4937
5135
  final String messageUpdate = initialDirectUpdateAllowed
4938
5136
  ? "Update will occur now."
4939
5137
  : this.shouldAutoSetNextBundle()
4940
- ? "Update will occur next time app moves to background."
4941
- : "Update will be downloaded and made available.";
5138
+ ? "Update will occur next time app moves to background."
5139
+ : "Update will be downloaded and made available.";
4942
5140
  Thread newTask = startNewThread(() -> {
4943
5141
  if (CapacitorUpdaterPlugin.this.shouldBlockAutoUpdateForPreviewSession()) {
4944
5142
  CapacitorUpdaterPlugin.this.clearBackgroundDownloadState();
@@ -4985,6 +5183,16 @@ public class CapacitorUpdaterPlugin extends Plugin {
4985
5183
  }
4986
5184
 
4987
5185
  boolean isFailure = "failed".equals(kind);
5186
+ if (isFailure) {
5187
+ // The check itself failed (offline, timeout, unreadable response, 429 block):
5188
+ // nothing was downloaded, so report it apart from download_fail.
5189
+ CapacitorUpdaterPlugin.this.implementation.sendStats(
5190
+ UPDATE_CHECK_ERROR_ACTION,
5191
+ currentBeforeCleanup.getVersionName(),
5192
+ "",
5193
+ updateCheckErrorMetadata(error, statusCode)
5194
+ );
5195
+ }
4988
5196
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
4989
5197
  errorMessage,
4990
5198
  latestVersion,
@@ -4993,7 +5201,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4993
5201
  plannedDirectUpdate,
4994
5202
  "download_fail",
4995
5203
  "downloadFailed",
4996
- isFailure
5204
+ false
4997
5205
  );
4998
5206
  return;
4999
5207
  }
@@ -5042,7 +5250,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5042
5250
  BundleInfo.ID_BUILTIN
5043
5251
  );
5044
5252
  ret.put("bundle", InternalUtils.mapToJSObject(builtinBundle.toJSONMap()));
5045
- CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret);
5253
+ CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, false);
5046
5254
  }
5047
5255
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
5048
5256
  "Latest version is builtin, autoUpdate onlyDownload",
@@ -5143,7 +5351,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5143
5351
  "Direct update skipped because splashscreen timeout occurred. Update will install on next background."
5144
5352
  );
5145
5353
  }
5146
- CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret);
5354
+ CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, false);
5147
5355
  CapacitorUpdaterPlugin.this.implementation.setNextBundle(latest.getId());
5148
5356
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
5149
5357
  "update downloaded, will install next background",
@@ -5154,7 +5362,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5154
5362
  );
5155
5363
  } else {
5156
5364
  logger.info("autoUpdate is set to onlyDownload, downloaded update will not be set as next bundle");
5157
- CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret);
5365
+ CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, false);
5158
5366
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
5159
5367
  "update downloaded, autoUpdate onlyDownload",
5160
5368
  latestVersionName,
@@ -5181,6 +5389,22 @@ public class CapacitorUpdaterPlugin extends Plugin {
5181
5389
  }
5182
5390
  }
5183
5391
  }
5392
+ // The store refuses these downloads without a callback, so end the cycle here
5393
+ // (appReady, splash hide) like iOS does.
5394
+ final String downloadBlockedReason = CapacitorUpdaterPlugin.this.autoUpdateDownloadBlockedReason(
5395
+ jsRes,
5396
+ latestVersionName
5397
+ );
5398
+ if (downloadBlockedReason != null) {
5399
+ CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
5400
+ downloadBlockedReason,
5401
+ latestVersionName,
5402
+ current,
5403
+ true,
5404
+ plannedDirectUpdate
5405
+ );
5406
+ return;
5407
+ }
5184
5408
  final boolean retryingInFlightDownload =
5185
5409
  latest != null &&
5186
5410
  BundleStatus.DOWNLOADING == latest.getStatus() &&
@@ -5279,6 +5503,19 @@ public class CapacitorUpdaterPlugin extends Plugin {
5279
5503
  return newTask;
5280
5504
  }
5281
5505
 
5506
+ /**
5507
+ * A download that finished while the app is in the background (for example after an
5508
+ * update-check push) would otherwise wait for the next foreground/background cycle, so the
5509
+ * user would open the old version once more. Install it now, like a background transition.
5510
+ */
5511
+ void installNextIfInBackground() {
5512
+ if (!this.appInBackground) {
5513
+ return;
5514
+ }
5515
+ logger.info("Next bundle downloaded while in background, installing it now");
5516
+ this.installNext();
5517
+ }
5518
+
5282
5519
  private void installNext() {
5283
5520
  try {
5284
5521
  if (this.shouldBlockAutoUpdateForPreviewSession()) {
@@ -5331,7 +5568,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5331
5568
  final JSObject ret = new JSObject();
5332
5569
  ret.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
5333
5570
  this.persistLastFailedBundle(current);
5334
- this.notifyListeners("updateFailed", ret);
5571
+ this.notifyListeners("updateFailed", ret, false);
5335
5572
  this.reportAppLaunchTimeout(current);
5336
5573
  this.implementation.sendStats("update_fail", current.getVersionName());
5337
5574
  this.implementation.setError(current);
@@ -5366,6 +5603,16 @@ public class CapacitorUpdaterPlugin extends Plugin {
5366
5603
  }
5367
5604
  }
5368
5605
 
5606
+ void runDeferredAppReadyCheck() {
5607
+ // A frozen app wakes up with its sleep already expired, before appMovedToForeground re-arms
5608
+ // the check: its page could not run yet, so wait for the fresh check of the next foreground.
5609
+ if (this.appInBackground) {
5610
+ logger.info("App is in background, notifyAppReady check deferred to the next foreground");
5611
+ return;
5612
+ }
5613
+ this.checkRevert();
5614
+ }
5615
+
5369
5616
  private class DeferredNotifyAppReadyCheck implements Runnable {
5370
5617
 
5371
5618
  private final long waitTimeMs;
@@ -5380,7 +5627,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5380
5627
  try {
5381
5628
  logger.info("Wait for " + this.waitTimeMs + "ms, then check for notifyAppReady");
5382
5629
  Thread.sleep(this.waitTimeMs);
5383
- CapacitorUpdaterPlugin.this.checkRevert();
5630
+ CapacitorUpdaterPlugin.this.runDeferredAppReadyCheck();
5384
5631
  CapacitorUpdaterPlugin.this.clearAppReadyCheckIfCurrent(currentThread);
5385
5632
  } catch (final InterruptedException e) {
5386
5633
  CapacitorUpdaterPlugin.this.clearAppReadyCheckIfCurrent(currentThread);
@@ -5390,6 +5637,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5390
5637
  }
5391
5638
 
5392
5639
  public void appMovedToForeground() {
5640
+ this.appInBackground = false;
5393
5641
  // Ensure activity reference is up-to-date before proceeding
5394
5642
  // This is critical for callbacks that may be invoked during background operations
5395
5643
  try {
@@ -5408,8 +5656,13 @@ public class CapacitorUpdaterPlugin extends Plugin {
5408
5656
  this.delayUpdateUtils.checkCancelDelay(DelayUpdateUtils.CancelDelaySource.FOREGROUND);
5409
5657
  this.delayUpdateUtils.unsetBackgroundTimestamp();
5410
5658
 
5411
- if (CapacitorUpdaterPlugin.this._isAutoUpdateEnabled() && !this.isDownloadStuckOrTimedOut()) {
5412
- this.backgroundDownload();
5659
+ if (CapacitorUpdaterPlugin.this._isAutoUpdateEnabled()) {
5660
+ if (!this.isDownloadStuckOrTimedOut()) {
5661
+ this.backgroundDownload();
5662
+ } else {
5663
+ // The running cycle sends appReady when it ends.
5664
+ logger.info("Download already in progress, skipping duplicate download request");
5665
+ }
5413
5666
  } else {
5414
5667
  final CapConfig config = CapConfig.loadDefault(this.getActivity());
5415
5668
  String serverUrl = config.getServerUrl();
@@ -5423,6 +5676,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5423
5676
  }
5424
5677
 
5425
5678
  public void appMovedToBackground() {
5679
+ this.appInBackground = true;
5426
5680
  // Reset timeout flag at start of each background cycle
5427
5681
  this.autoSplashscreenTimedOut = false;
5428
5682
 
@@ -5777,6 +6031,12 @@ public class CapacitorUpdaterPlugin extends Plugin {
5777
6031
  result.put("installStatus", appUpdateInfo.installStatus());
5778
6032
 
5779
6033
  call.resolve(result);
6034
+ if (
6035
+ appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE &&
6036
+ CapacitorUpdaterPlugin.this.nativeUpdatePrompt != null
6037
+ ) {
6038
+ CapacitorUpdaterPlugin.this.nativeUpdatePrompt.maybeShowForStoreUpdateAvailable();
6039
+ }
5780
6040
  })
5781
6041
  .addOnFailureListener((e) -> {
5782
6042
  logger.error("Failed to get app update info: " + e.getMessage());
@@ -5921,7 +6181,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5921
6181
  eventData.put("totalBytesToDownload", state.totalBytesToDownload());
5922
6182
  }
5923
6183
 
5924
- notifyListeners("onFlexibleUpdateStateChange", eventData);
6184
+ notifyListeners("onFlexibleUpdateStateChange", eventData, false);
5925
6185
  };
5926
6186
 
5927
6187
  manager.registerListener(installStateUpdatedListener);
@@ -6008,6 +6268,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
6008
6268
  }
6009
6269
 
6010
6270
  private void handleOnDestroyInternal() {
6271
+ instanceLoaded = false;
6011
6272
  // Original handleOnDestroy code
6012
6273
  try {
6013
6274
  logger.info("onActivityDestroyed " + getActivity().getClass().getName());