@capgo/capacitor-updater 7.51.21 → 7.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 (29) hide show
  1. package/CapgoCapacitorUpdater.podspec +0 -3
  2. package/Package.swift +3 -11
  3. package/README.md +202 -67
  4. package/android/build.gradle +2 -3
  5. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +610 -177
  6. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +909 -196
  7. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +53 -19
  8. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +226 -106
  9. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +210 -58
  10. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +325 -0
  11. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +63 -4
  12. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  14. package/dist/docs.json +394 -27
  15. package/dist/esm/definitions.d.ts +220 -7
  16. package/dist/esm/definitions.js.map +1 -1
  17. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +104 -52
  18. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +562 -187
  19. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +162 -0
  20. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +564 -109
  21. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +11 -2
  22. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +204 -93
  23. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +75 -5
  24. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  25. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +53 -0
  26. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +9 -3
  27. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  28. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  29. 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;
@@ -48,12 +49,10 @@ import com.google.android.play.core.install.InstallStateUpdatedListener;
48
49
  import com.google.android.play.core.install.model.AppUpdateType;
49
50
  import com.google.android.play.core.install.model.InstallStatus;
50
51
  import com.google.android.play.core.install.model.UpdateAvailability;
51
- import io.github.g00fy2.versioncompare.Version;
52
52
  import java.io.ByteArrayOutputStream;
53
53
  import java.io.File;
54
54
  import java.io.IOException;
55
55
  import java.io.InputStream;
56
- import java.net.HttpURLConnection;
57
56
  import java.net.MalformedURLException;
58
57
  import java.net.URL;
59
58
  import java.nio.charset.StandardCharsets;
@@ -75,7 +74,11 @@ import java.util.concurrent.Semaphore;
75
74
  import java.util.concurrent.TimeUnit;
76
75
  import java.util.concurrent.TimeoutException;
77
76
  import java.util.concurrent.atomic.AtomicReference;
78
- // Removed OkHttpClient and Protocol imports - using shared client in DownloadService instead
77
+ import okhttp3.HttpUrl;
78
+ import okhttp3.OkHttpClient;
79
+ import okhttp3.Request;
80
+ import okhttp3.Response;
81
+ import okhttp3.ResponseBody;
79
82
  import org.json.JSONArray;
80
83
  import org.json.JSONException;
81
84
  import org.json.JSONObject;
@@ -93,18 +96,27 @@ public class CapacitorUpdaterPlugin extends Plugin {
93
96
  private static final String AUTO_UPDATE_MODE_ALWAYS = "always";
94
97
  private static final String AUTO_UPDATE_MODE_ONLY_DOWNLOAD = "onlyDownload";
95
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
+
96
108
  private Logger logger;
97
109
 
98
- private static final String updateUrlDefault = "https://plugin.capgo.app/updates";
99
- private static final String statsUrlDefault = "https://plugin.capgo.app/stats";
100
- 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";
101
113
  private static final String KEEP_URL_FLAG_KEY = "__capgo_keep_url_path_after_reload";
102
- private static final String CUSTOM_ID_PREF_KEY = "CapacitorUpdater.customId";
103
- private static final String UPDATE_URL_PREF_KEY = "CapacitorUpdater.updateUrl";
104
- private static final String STATS_URL_PREF_KEY = "CapacitorUpdater.statsUrl";
105
- private static final String CHANNEL_URL_PREF_KEY = "CapacitorUpdater.channelUrl";
106
- private static final String DEFAULT_CHANNEL_PREF_KEY = "CapacitorUpdater.defaultChannel";
107
- 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";
108
120
  private static final String DEFAULT_CHANNEL_INSTALL_MARKER_PREF_KEY = "CapacitorUpdater.defaultChannelInstallMarkerCreated";
109
121
  private static final String DEFAULT_CHANNEL_INSTALL_MARKER_FILE = "CapacitorUpdater.defaultChannelInstallMarker";
110
122
  private static final String PREVIEW_PREVIOUS_SHAKE_MENU_PREF_KEY = "CapacitorUpdater.previewPreviousShakeMenu";
@@ -146,7 +158,11 @@ public class CapacitorUpdaterPlugin extends Plugin {
146
158
  static final int APPLICATION_EXIT_REASON_USER_REQUESTED = 10;
147
159
  static final int APPLICATION_EXIT_REASON_DEPENDENCY_DIED = 12;
148
160
 
149
- private final String pluginVersion = "7.51.21";
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;
150
166
  private static final String DELAY_CONDITION_PREFERENCES = "";
151
167
 
152
168
  private SharedPreferences.Editor editor;
@@ -220,8 +236,15 @@ public class CapacitorUpdaterPlugin extends Plugin {
220
236
 
221
237
  private volatile Thread backgroundDownloadTask;
222
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;
223
242
  // When true, sendReadyToJs should wait for notifyAppReady before hiding splash.
224
243
  private volatile boolean pendingNotifyAppReadyWait = false;
244
+ // Armed only after a reload. The next document stamps this generation into notifyAppReady.
245
+ private final Object readyGuardLock = new Object();
246
+ private volatile int readyGeneration = 0;
247
+ private volatile boolean readyGuardArmed = false;
225
248
  private volatile int pendingNotifyAppReadyPhase = -1;
226
249
  private volatile long downloadStartTimeMs = 0;
227
250
  private static final long DOWNLOAD_TIMEOUT_MS = 600000; // 10 minute timeout
@@ -241,6 +264,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
241
264
  private volatile boolean defaultChannelCleanupMustRetry = false;
242
265
 
243
266
  private int lastNotifiedStatPercent = 0;
267
+ private String lastNotifiedStatBundleId = null;
268
+ private final Object downloadStatLock = new Object();
244
269
 
245
270
  private DelayUpdateUtils delayUpdateUtils;
246
271
 
@@ -292,8 +317,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
292
317
  private AppUpdateManager appUpdateManager;
293
318
  private PluginCall pendingAppUpdateCall;
294
319
  private AppUpdateInfo cachedAppUpdateInfo;
295
- private static final int APP_UPDATE_REQUEST_CODE = 9001;
320
+ static final int APP_UPDATE_REQUEST_CODE = 9001;
296
321
  private InstallStateUpdatedListener installStateUpdatedListener;
322
+ private NativeUpdatePrompt nativeUpdatePrompt;
297
323
 
298
324
  private PackageInfo getCurrentPackageInfo() throws PackageManager.NameNotFoundException {
299
325
  final PackageManager packageManager = this.getContext().getPackageManager();
@@ -315,28 +341,21 @@ public class CapacitorUpdaterPlugin extends Plugin {
315
341
  for (final String eventName : BREAKING_EVENT_NAMES) {
316
342
  final JSObject payload = new JSObject();
317
343
  payload.put("version", version);
318
- CapacitorUpdaterPlugin.this.notifyListeners(eventName, payload);
344
+ CapacitorUpdaterPlugin.this.notifyListeners(eventName, payload, false);
319
345
  }
320
346
  }
321
347
 
322
348
  private boolean shouldNotifyBreakingEvents(final JSObject response) {
323
- if (response == null) {
324
- return false;
325
- }
326
-
327
- if (response.optBoolean("breaking", false)) {
328
- return true;
329
- }
330
-
331
- final String error = response.optString("error", "");
332
- final String message = response.optString("message", "");
333
- return "disable_auto_update_to_major".equals(error) || "store_update_required".equals(message);
349
+ return NativeUpdatePrompt.isNativeStoreUpdateBlock(response);
334
350
  }
335
351
 
336
352
  private void notifyBreakingEventsIfNeeded(final JSObject response, final String version) {
337
353
  if (shouldNotifyBreakingEvents(response)) {
338
354
  notifyBreakingEvents(version);
339
355
  }
356
+ if (this.nativeUpdatePrompt != null) {
357
+ this.nativeUpdatePrompt.maybeShowForUpdateBlock(response);
358
+ }
340
359
  }
341
360
 
342
361
  private void persistLastFailedBundle(BundleInfo bundle) {
@@ -679,9 +698,46 @@ public class CapacitorUpdaterPlugin extends Plugin {
679
698
  return startNewThread(function, 0);
680
699
  }
681
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
+
682
737
  @Override
683
738
  public void load() {
684
739
  super.load();
740
+ instanceLoaded = true;
685
741
 
686
742
  // Initialize logger with osLogging config
687
743
  // Default to true for both platforms to enable system logging by default
@@ -710,11 +766,21 @@ public class CapacitorUpdaterPlugin extends Plugin {
710
766
  CapacitorUpdaterPlugin.this.scheduleDirectUpdateFinish(latest);
711
767
  }
712
768
 
769
+ @Override
770
+ public void backgroundDownloadSettled(final BundleInfo bundle, final String status) {
771
+ CapacitorUpdaterPlugin.this.emitLaunchDownloadReady(bundle, status);
772
+ }
773
+
774
+ @Override
775
+ public void nextBundleReady(final BundleInfo bundle) {
776
+ CapacitorUpdaterPlugin.this.installNextIfInBackground();
777
+ }
778
+
713
779
  @Override
714
780
  public void notifyListeners(final String id, final Map<String, Object> res) {
715
781
  if (activity != null) {
716
782
  activity.runOnUiThread(() -> {
717
- CapacitorUpdaterPlugin.this.notifyListeners(id, InternalUtils.mapToJSObject(res));
783
+ CapacitorUpdaterPlugin.this.notifyListeners(id, InternalUtils.mapToJSObject(res), false);
718
784
  });
719
785
  } else {
720
786
  logger.warn("notifyListeners: Activity is null, skipping notification for event: " + id);
@@ -723,11 +789,11 @@ public class CapacitorUpdaterPlugin extends Plugin {
723
789
  };
724
790
  final PackageInfo pInfo = this.getCurrentPackageInfo();
725
791
  this.implementation.activity = this.getActivity();
792
+ this.implementation.appContext = this.getContext().getApplicationContext();
726
793
  this.implementation.versionBuild = this.getConfig().getString("version", pInfo.versionName);
727
794
  this.implementation.CAP_SERVER_PATH = WebView.CAP_SERVER_PATH;
728
795
  this.implementation.pluginVersion = this.pluginVersion;
729
796
  this.implementation.versionCode = this.getVersionCode(pInfo);
730
- // Removed unused OkHttpClient creation - using shared client in DownloadService instead
731
797
  this.currentVersionNative = new Version(this.getConfig().getString("version", pInfo.versionName));
732
798
  this.currentBuildVersion = this.getVersionCode(pInfo);
733
799
  this.delayUpdateUtils = new DelayUpdateUtils(this.prefs, this.editor, this.currentVersionNative, logger);
@@ -847,6 +913,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
847
913
  // Use DeviceIdHelper to get or create device ID that persists across reinstalls
848
914
  this.implementation.deviceID = DeviceIdHelper.getOrCreateDeviceId(this.getContext(), this.prefs);
849
915
  this.implementation.restorePendingStats();
916
+ this.implementation.claimStatsOwnership();
850
917
 
851
918
  // Update User-Agent for shared OkHttpClient with OS version
852
919
  DownloadService.updateUserAgent(this.implementation.appId, this.pluginVersion, this.implementation.versionOs);
@@ -860,7 +927,6 @@ public class CapacitorUpdaterPlugin extends Plugin {
860
927
  }
861
928
  logger.info("init for device " + this.implementation.deviceID);
862
929
  logger.info("version native " + this.currentVersionNative.getOriginalString());
863
- this.reportAppLaunchStart();
864
930
  this.autoDeleteFailed = this.getConfig().getBoolean("autoDeleteFailed", true);
865
931
  this.autoDeletePrevious = this.getConfig().getBoolean("autoDeletePrevious", true);
866
932
  this.updateUrl = this.getConfig().getString("updateUrl", updateUrlDefault);
@@ -886,9 +952,46 @@ public class CapacitorUpdaterPlugin extends Plugin {
886
952
  long responseTimeoutMillis = responseTimeoutSeconds > 0 ? (long) responseTimeoutSeconds * 1000L : 20_000L;
887
953
  this.implementation.timeout = (int) Math.min(Integer.MAX_VALUE, responseTimeoutMillis);
888
954
  DownloadService.applyHttpTimeouts(this.implementation.timeout);
955
+ DownloadService.setAllowHttpsToHttpRedirect(this.getConfig().getBoolean("allowHttpsToHttpRedirect", false));
889
956
  this.shakeMenuEnabled = this.getConfig().getBoolean("shakeMenu", false);
890
957
  this.shakeChannelSelectorEnabled = this.getConfig().getBoolean("allowShakeChannelSelector", false);
891
958
  this.shakeMenuGesture = normalizedShakeMenuGesture(this.getConfig().getString("shakeMenuGesture", SHAKE_MENU_GESTURE_SHAKE));
959
+ this.nativeUpdatePrompt = new NativeUpdatePrompt(
960
+ this.getConfig(),
961
+ this.prefs,
962
+ this.logger,
963
+ new NativeUpdatePrompt.NativeUpdatePromptHost() {
964
+ @Override
965
+ public Activity getActivity() {
966
+ return CapacitorUpdaterPlugin.this.getActivity();
967
+ }
968
+
969
+ @Override
970
+ public String getNativeBuildVersion() {
971
+ return CapacitorUpdaterPlugin.this.currentBuildVersion;
972
+ }
973
+
974
+ @Override
975
+ public AppUpdateManager getAppUpdateManager() {
976
+ return CapacitorUpdaterPlugin.this.getAppUpdateManager();
977
+ }
978
+
979
+ @Override
980
+ public AppUpdateInfo getCachedAppUpdateInfo() {
981
+ return CapacitorUpdaterPlugin.this.cachedAppUpdateInfo;
982
+ }
983
+
984
+ @Override
985
+ public void setCachedAppUpdateInfo(final AppUpdateInfo info) {
986
+ CapacitorUpdaterPlugin.this.cachedAppUpdateInfo = info;
987
+ }
988
+
989
+ @Override
990
+ public String getPackageNameForStore() {
991
+ return CapacitorUpdaterPlugin.this.getContext().getPackageName();
992
+ }
993
+ }
994
+ );
892
995
  this.previewSessionEnabled = Boolean.TRUE.equals(this.allowPreview) && this.prefs.getBoolean(PREVIEW_SESSION_PREF_KEY, false);
893
996
  if (!Boolean.TRUE.equals(this.allowPreview) && this.prefs.getBoolean(PREVIEW_SESSION_PREF_KEY, false)) {
894
997
  this.clearPreviewSessionBecauseDisabled();
@@ -912,11 +1015,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
912
1015
  // Check if app was recently installed/updated BEFORE cleanupObsoleteVersions updates LatestVersionNative
913
1016
  this.wasRecentlyInstalledOrUpdated = this.checkIfRecentlyInstalledOrUpdated();
914
1017
 
915
- this.implementation.autoReset(this.currentBuildVersion, resetWhenUpdate);
916
- if (nativeBuildVersionChanged) {
917
- this.clearPreviewSessionForNativeBuildChange();
918
- }
919
- this.leavePreviewSessionForLaunchIntentIfNeeded();
1018
+ this.resetStartupBundleAndReportAppLaunchStart(resetWhenUpdate, nativeBuildVersionChanged);
920
1019
  this.reportNativeVersionStatsIfChanged();
921
1020
  this.reportPreviousAppExitReasons();
922
1021
  this.reportPreviousWebViewRenderProcessGone();
@@ -2128,33 +2227,35 @@ public class CapacitorUpdaterPlugin extends Plugin {
2128
2227
  }
2129
2228
 
2130
2229
  private void configureAutoUpdateModeFromConfig() {
2131
- final String configuredMode = this.getConfig().getString("autoUpdate", null);
2230
+ this.autoUpdateMode = autoUpdateModeFromConfig(this.getConfig(), logger);
2231
+ this.autoUpdate = isAutoUpdateModeEnabled(this.autoUpdateMode);
2232
+ this.directUpdateMode = directUpdateModeForAutoUpdateMode(this.autoUpdateMode);
2233
+ this.implementation.directUpdate = isDirectUpdateMode(this.directUpdateMode);
2234
+ }
2235
+
2236
+ /** Resolves autoUpdate (and the legacy directUpdate) from the plugin config. Shared with the headless update check. */
2237
+ static String autoUpdateModeFromConfig(final PluginConfig pluginConfig, final Logger logger) {
2238
+ final String configuredMode = pluginConfig.getString("autoUpdate", null);
2132
2239
  if (configuredMode != null && !configuredMode.isEmpty() && !"true".equals(configuredMode) && !"false".equals(configuredMode)) {
2133
- this.autoUpdateMode = normalizedAutoUpdateMode(configuredMode);
2134
- if (!this.autoUpdateMode.equals(configuredMode)) {
2240
+ final String mode = normalizedAutoUpdateMode(configuredMode);
2241
+ if (!mode.equals(configuredMode) && logger != null) {
2135
2242
  logger.error(
2136
2243
  "Invalid autoUpdate value: \"" +
2137
2244
  configuredMode +
2138
2245
  "\". Supported values are: true, false, \"off\", \"atBackground\", \"atInstall\", \"onLaunch\", \"always\", \"onlyDownload\". Defaulting to \"atBackground\"."
2139
2246
  );
2140
2247
  }
2141
- } else {
2142
- final boolean enabled =
2143
- configuredMode != null
2144
- ? "true".equals(configuredMode)
2145
- : Boolean.TRUE.equals(this.getConfig().getBoolean("autoUpdate", true));
2146
- this.autoUpdateMode = enabled
2147
- ? autoUpdateModeForLegacyDirectUpdateMode(this.resolveLegacyDirectUpdateModeFromConfig())
2148
- : AUTO_UPDATE_MODE_OFF;
2248
+ return mode;
2149
2249
  }
2150
-
2151
- this.autoUpdate = isAutoUpdateModeEnabled(this.autoUpdateMode);
2152
- this.directUpdateMode = directUpdateModeForAutoUpdateMode(this.autoUpdateMode);
2153
- this.implementation.directUpdate = isDirectUpdateMode(this.directUpdateMode);
2250
+ final boolean enabled =
2251
+ configuredMode != null ? "true".equals(configuredMode) : Boolean.TRUE.equals(pluginConfig.getBoolean("autoUpdate", true));
2252
+ return enabled
2253
+ ? autoUpdateModeForLegacyDirectUpdateMode(resolveLegacyDirectUpdateModeFromConfig(pluginConfig, logger))
2254
+ : AUTO_UPDATE_MODE_OFF;
2154
2255
  }
2155
2256
 
2156
- private String resolveLegacyDirectUpdateModeFromConfig() {
2157
- final String directUpdateConfig = this.getConfig().getString("directUpdate", null);
2257
+ private static String resolveLegacyDirectUpdateModeFromConfig(final PluginConfig pluginConfig, final Logger logger) {
2258
+ final String directUpdateConfig = pluginConfig.getString("directUpdate", null);
2158
2259
  if (directUpdateConfig != null) {
2159
2260
  if ("true".equals(directUpdateConfig)) {
2160
2261
  return AUTO_UPDATE_MODE_ALWAYS;
@@ -2162,15 +2263,17 @@ public class CapacitorUpdaterPlugin extends Plugin {
2162
2263
  if ("false".equals(directUpdateConfig) || isDirectUpdateMode(directUpdateConfig)) {
2163
2264
  return directUpdateConfig;
2164
2265
  }
2165
- logger.error(
2166
- "Invalid directUpdate value: \"" +
2167
- directUpdateConfig +
2168
- "\". Supported values are: false, true, \"always\", \"atInstall\", \"onLaunch\". Defaulting to \"false\"."
2169
- );
2266
+ if (logger != null) {
2267
+ logger.error(
2268
+ "Invalid directUpdate value: \"" +
2269
+ directUpdateConfig +
2270
+ "\". Supported values are: false, true, \"always\", \"atInstall\", \"onLaunch\". Defaulting to \"false\"."
2271
+ );
2272
+ }
2170
2273
  return "false";
2171
2274
  }
2172
2275
 
2173
- return Boolean.TRUE.equals(this.getConfig().getBoolean("directUpdate", false)) ? AUTO_UPDATE_MODE_ALWAYS : "false";
2276
+ return Boolean.TRUE.equals(pluginConfig.getBoolean("directUpdate", false)) ? AUTO_UPDATE_MODE_ALWAYS : "false";
2174
2277
  }
2175
2278
 
2176
2279
  static String normalizedAutoUpdateMode(final String value) {
@@ -2332,10 +2435,49 @@ public class CapacitorUpdaterPlugin extends Plugin {
2332
2435
  this.logger = logger;
2333
2436
  }
2334
2437
 
2438
+ void reportAppLaunchStartForTesting() {
2439
+ this.reportAppLaunchStart();
2440
+ }
2441
+
2442
+ void setCurrentBuildVersionForTesting(final String currentBuildVersion) {
2443
+ this.currentBuildVersion = currentBuildVersion;
2444
+ }
2445
+
2446
+ void resetStartupBundleAndReportAppLaunchStartForTesting(final boolean resetWhenUpdate, final boolean nativeBuildVersionChanged) {
2447
+ this.resetStartupBundleAndReportAppLaunchStart(resetWhenUpdate, nativeBuildVersionChanged);
2448
+ }
2449
+
2450
+ private void resetStartupBundleAndReportAppLaunchStart(final boolean resetWhenUpdate, final boolean nativeBuildVersionChanged) {
2451
+ this.implementation.autoReset(this.currentBuildVersion, resetWhenUpdate);
2452
+ if (nativeBuildVersionChanged) {
2453
+ this.clearPreviewSessionForNativeBuildChange();
2454
+ }
2455
+ this.leavePreviewSessionForLaunchIntentIfNeeded();
2456
+ this.reportAppLaunchStart();
2457
+ }
2458
+
2335
2459
  void completeBackgroundTaskForTesting(final BundleInfo current, final boolean plannedDirectUpdate) {
2336
2460
  this.endBackGroundTaskWithNotif("test", current.getVersionName(), current, false, plannedDirectUpdate);
2337
2461
  }
2338
2462
 
2463
+ void emitLaunchDownloadReady(final BundleInfo bundle, final String status) {
2464
+ final BundleInfo readyBundle = bundle != null ? bundle : this.implementation.getCurrentBundle();
2465
+ if (readyBundle == null) {
2466
+ return;
2467
+ }
2468
+ this.endBackGroundTaskWithNotif(
2469
+ status,
2470
+ readyBundle.getVersionName(),
2471
+ readyBundle,
2472
+ false,
2473
+ false,
2474
+ "download_fail",
2475
+ "downloadFailed",
2476
+ false,
2477
+ false
2478
+ );
2479
+ }
2480
+
2339
2481
  void scheduleDirectUpdateFinish(final BundleInfo latest) {
2340
2482
  startNewThread(() -> {
2341
2483
  try {
@@ -2377,7 +2519,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
2377
2519
  this.implementation.setNextBundle(latest.getId());
2378
2520
  final JSObject ret = new JSObject();
2379
2521
  ret.put("bundle", InternalUtils.mapToJSObject(latest.toJSONMap()));
2380
- this.notifyListeners("updateAvailable", ret);
2522
+ this.notifyListeners("updateAvailable", ret, false);
2381
2523
  sendReadyToJs(
2382
2524
  this.implementation.getCurrentBundle(),
2383
2525
  "Direct update reload failed, update will install next background",
@@ -2447,6 +2589,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
2447
2589
  final Set<String> allowedIds = this.implementation.allowedBundleIdsForCleanup();
2448
2590
  this.implementation.cleanupDownloadDirectories(allowedIds);
2449
2591
  this.implementation.cleanupOrphanedTempFolders(null);
2592
+ this.implementation.cleanupOrphanedManifestStagingFolders(null);
2450
2593
 
2451
2594
  this.persistCurrentNativeBuildVersion();
2452
2595
  } catch (Exception e) {
@@ -2495,24 +2638,49 @@ public class CapacitorUpdaterPlugin extends Plugin {
2495
2638
  logger.info("Cleanup finished, proceeding with download");
2496
2639
  }
2497
2640
 
2641
+ /**
2642
+ * Returns the {@code download_N} stat to send for this progress, or null. Buckets are tracked per
2643
+ * download: a new download (percent 0 or another bundle id) starts from zero again.
2644
+ */
2645
+ String nextDownloadStatAction(final String id, final int percent) {
2646
+ synchronized (this.downloadStatLock) {
2647
+ if (percent == 0 || !Objects.equals(id, this.lastNotifiedStatBundleId)) {
2648
+ this.lastNotifiedStatBundleId = id;
2649
+ this.lastNotifiedStatPercent = 0;
2650
+ }
2651
+ final int currentStatPercent = (percent / 10) * 10; // Round down to nearest 10
2652
+ if (currentStatPercent <= this.lastNotifiedStatPercent) {
2653
+ return null;
2654
+ }
2655
+ this.lastNotifiedStatPercent = currentStatPercent;
2656
+ return "download_" + currentStatPercent;
2657
+ }
2658
+ }
2659
+
2660
+ private void markDownloadStatPercent(final String id, final int percent) {
2661
+ synchronized (this.downloadStatLock) {
2662
+ this.lastNotifiedStatBundleId = id;
2663
+ this.lastNotifiedStatPercent = percent;
2664
+ }
2665
+ }
2666
+
2498
2667
  public void notifyDownload(final String id, final int percent) {
2499
2668
  try {
2500
2669
  final JSObject ret = new JSObject();
2501
2670
  ret.put("percent", percent);
2502
2671
  final BundleInfo bundleInfo = this.implementation.getBundleInfo(id);
2503
2672
  ret.put("bundle", InternalUtils.mapToJSObject(bundleInfo.toJSONMap()));
2504
- this.notifyListeners("download", ret);
2673
+ this.notifyListeners("download", ret, false);
2505
2674
 
2506
2675
  if (percent == 100) {
2507
2676
  final JSObject retDownloadComplete = new JSObject(ret, new String[] { "bundle" });
2508
- this.notifyListeners("downloadComplete", retDownloadComplete);
2677
+ this.notifyListeners("downloadComplete", retDownloadComplete, false);
2509
2678
  this.implementation.sendStats("download_complete", bundleInfo.getVersionName());
2510
- lastNotifiedStatPercent = 100;
2679
+ this.markDownloadStatPercent(id, 100);
2511
2680
  } else {
2512
- int currentStatPercent = (percent / 10) * 10; // Round down to nearest 10
2513
- if (currentStatPercent > lastNotifiedStatPercent) {
2514
- this.implementation.sendStats("download_" + currentStatPercent, bundleInfo.getVersionName());
2515
- lastNotifiedStatPercent = currentStatPercent;
2681
+ final String statAction = this.nextDownloadStatAction(id, percent);
2682
+ if (statAction != null) {
2683
+ this.implementation.sendStats(statAction, bundleInfo.getVersionName());
2516
2684
  }
2517
2685
  }
2518
2686
  } catch (final Exception e) {
@@ -2663,6 +2831,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
2663
2831
  CapacitorUpdaterPlugin.this.editor,
2664
2832
  DEFAULT_CHANNEL_PREF_KEY,
2665
2833
  configDefaultChannel,
2834
+ CapacitorUpdaterPlugin.this.allowSetDefaultChannel,
2666
2835
  (res) -> {
2667
2836
  JSObject jsRes = InternalUtils.mapToJSObject(res);
2668
2837
  if (jsRes.has("error")) {
@@ -2731,7 +2900,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
2731
2900
  JSObject eventData = new JSObject();
2732
2901
  eventData.put("channel", channel);
2733
2902
  eventData.put("message", errorMessage);
2734
- notifyListeners("channelPrivate", eventData);
2903
+ notifyListeners("channelPrivate", eventData, false);
2735
2904
  }
2736
2905
 
2737
2906
  JSObject errorObj = new JSObject();
@@ -2842,6 +3011,16 @@ public class CapacitorUpdaterPlugin extends Plugin {
2842
3011
  final String checksum,
2843
3012
  final JSONArray manifest
2844
3013
  ) throws IOException {
3014
+ if (!this.implementation.publicKey.isEmpty() && !CryptoCipher.isValidSessionKey(sessionKey)) {
3015
+ logger.error("Public key present but no valid session key provided");
3016
+ this.implementation.sendStats("session_key_required");
3017
+ throw new IOException("Session key required when public key is present");
3018
+ }
3019
+ if (manifest == null && (checksum == null || checksum.isEmpty())) {
3020
+ logger.error("No checksum provided");
3021
+ this.implementation.sendStats("checksum_required");
3022
+ throw new IOException("Checksum required");
3023
+ }
2845
3024
  // Manual/preview downloads must wait too — launch orphan sweep can delete their temps.
2846
3025
  waitForCleanupIfNeeded();
2847
3026
  if (manifest != null) {
@@ -2881,24 +3060,28 @@ public class CapacitorUpdaterPlugin extends Plugin {
2881
3060
  } catch (final Exception e) {
2882
3061
  logger.error("Failed to download from: " + url + " " + e.getMessage());
2883
3062
  call.reject("Failed to download from: " + url, e);
2884
- final JSObject ret = new JSObject();
2885
- ret.put("version", version);
2886
- CapacitorUpdaterPlugin.this.notifyListeners("downloadFailed", ret);
2887
- final BundleInfo current = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
2888
- CapacitorUpdaterPlugin.this.implementation.sendStats("download_fail", current.getVersionName());
3063
+ CapacitorUpdaterPlugin.this.notifyManualDownloadFailed(version, e);
2889
3064
  }
2890
3065
  });
2891
3066
  } catch (final Exception e) {
2892
3067
  logger.error("Failed to download from: " + url + " " + e.getMessage());
2893
3068
  call.reject("Failed to download from: " + url, e);
2894
- final JSObject ret = new JSObject();
2895
- ret.put("version", version);
2896
- CapacitorUpdaterPlugin.this.notifyListeners("downloadFailed", ret);
2897
- final BundleInfo current = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
2898
- CapacitorUpdaterPlugin.this.implementation.sendStats("download_fail", current.getVersionName());
3069
+ this.notifyManualDownloadFailed(version, e);
2899
3070
  }
2900
3071
  }
2901
3072
 
3073
+ /** Emits downloadFailed + download_fail once: the updater already did it for worker failures. */
3074
+ void notifyManualDownloadFailed(final String version, final Exception error) {
3075
+ if (error instanceof CapgoUpdater.ReportedDownloadFailureException) {
3076
+ return;
3077
+ }
3078
+ final JSObject ret = new JSObject();
3079
+ ret.put("version", version);
3080
+ this.notifyListeners("downloadFailed", ret, false);
3081
+ final BundleInfo current = this.implementation.getCurrentBundle();
3082
+ this.implementation.sendStats("download_fail", current.getVersionName());
3083
+ }
3084
+
2902
3085
  private void syncKeepUrlPathFlag(final boolean enabled) {
2903
3086
  if (this.bridge == null || this.bridge.getWebView() == null) {
2904
3087
  return;
@@ -2914,6 +3097,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
2914
3097
  }
2915
3098
 
2916
3099
  private void applyCurrentBundleToBridge() {
3100
+ this.stampReadyGenerationBeforeReload();
2917
3101
  final String path = this.implementation.getCurrentBundlePath();
2918
3102
  final boolean usingBuiltin = this.implementation.isUsingBuiltin();
2919
3103
  if (this.keepUrlPathAfterReload) {
@@ -3017,6 +3201,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
3017
3201
  }
3018
3202
 
3019
3203
  protected boolean _reload() {
3204
+ if (this.appInBackground) {
3205
+ return this.reloadInBackground();
3206
+ }
3020
3207
  // Drop any launch pending wait; this reload owns notifyAppReady synchronization.
3021
3208
  this.clearPendingNotifyAppReadyWait();
3022
3209
  final int phase = this.semaphoreUp();
@@ -3024,18 +3211,29 @@ public class CapacitorUpdaterPlugin extends Plugin {
3024
3211
 
3025
3212
  final long waitTimeMs = this.resolveAppReadyCheckTimeoutMs();
3026
3213
  this.checkAppReady(waitTimeMs);
3027
- this.notifyListeners("appReloaded", new JSObject());
3214
+ this.notifyListeners("appReloaded", new JSObject(), false);
3028
3215
 
3029
3216
  // Wait for the reload to complete (until notifyAppReady is called)
3030
3217
  return this.semaphoreWait(phase, waitTimeMs);
3031
3218
  }
3032
3219
 
3220
+ /**
3221
+ * A backgrounded app is frozen by Android: the reloaded page cannot call notifyAppReady before the
3222
+ * next foreground, so waiting here would only time out. Apply the bundle, and let the next appReady
3223
+ * wait for the page instead (the next foreground also arms a fresh rollback check).
3224
+ */
3225
+ private boolean reloadInBackground() {
3226
+ logger.info("App is in background, reload does not wait for notifyAppReady");
3227
+ this.armPendingNotifyAppReadyWait();
3228
+ return this.reloadWithoutWaitingForAppReady();
3229
+ }
3230
+
3033
3231
  protected boolean reloadWithoutWaitingForAppReady() {
3034
3232
  this.applyCurrentBundleToBridge();
3035
3233
 
3036
3234
  final long waitTimeMs = this.resolveAppReadyCheckTimeoutMs();
3037
3235
  this.checkAppReady(waitTimeMs);
3038
- this.notifyListeners("appReloaded", new JSObject());
3236
+ this.notifyListeners("appReloaded", new JSObject(), false);
3039
3237
  return true;
3040
3238
  }
3041
3239
 
@@ -3126,7 +3324,11 @@ public class CapacitorUpdaterPlugin extends Plugin {
3126
3324
  if (!this.implementation.set(id)) {
3127
3325
  logger.info("No such bundle " + id);
3128
3326
  call.reject("Update failed, id " + id + " does not exist.");
3129
- } else if (Boolean.TRUE.equals(this.previewSessionEnabled)) {
3327
+ return;
3328
+ }
3329
+ // The bundle is now active: it must not stay reported as the pending next bundle.
3330
+ this.implementation.clearNextBundleIfCurrent();
3331
+ if (Boolean.TRUE.equals(this.previewSessionEnabled)) {
3130
3332
  logger.info("Preview session set active bundle " + id + " without waiting for preview app readiness");
3131
3333
  final BundleInfo bundle = this.implementation.getBundleInfo(id);
3132
3334
  this.recordPreviewBundle(bundle);
@@ -3556,7 +3758,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
3556
3758
  }
3557
3759
 
3558
3760
  private void leavePreviewSessionForLaunchIntentIfNeeded() {
3559
- final Intent intent = getActivity() == null ? null : getActivity().getIntent();
3761
+ final Bridge bridge = getBridge();
3762
+ final Activity launchActivity = bridge == null ? null : bridge.getActivity();
3763
+ final Intent intent = launchActivity == null ? null : launchActivity.getIntent();
3560
3764
  if (
3561
3765
  intent == null ||
3562
3766
  !Intent.ACTION_VIEW.equals(intent.getAction()) ||
@@ -3851,17 +4055,22 @@ public class CapacitorUpdaterPlugin extends Plugin {
3851
4055
  }
3852
4056
 
3853
4057
  private JSONObject fetchPreviewPayload(final String payloadUrl) throws IOException, JSONException {
3854
- final HttpURLConnection connection = (HttpURLConnection) new URL(payloadUrl).openConnection();
3855
- connection.setRequestMethod("GET");
3856
- connection.setRequestProperty("Accept", "application/json");
3857
- connection.setConnectTimeout(30000);
3858
- connection.setReadTimeout(60000);
3859
-
3860
- try {
3861
- final int statusCode = connection.getResponseCode();
3862
- final String body = this.readResponseBody(
3863
- statusCode >= 200 && statusCode < 300 ? connection.getInputStream() : connection.getErrorStream()
3864
- );
4058
+ final HttpUrl url = payloadUrl != null ? HttpUrl.parse(payloadUrl) : null;
4059
+ if (url == null) {
4060
+ throw new MalformedURLException("Expected an http or https preview payload URL");
4061
+ }
4062
+ // Shared client: no cookies, Capgo User-Agent.
4063
+ final OkHttpClient client = DownloadService.sharedClient
4064
+ .newBuilder()
4065
+ .connectTimeout(30, TimeUnit.SECONDS)
4066
+ .readTimeout(60, TimeUnit.SECONDS)
4067
+ .build();
4068
+ final Request request = new Request.Builder().url(url).get().header("Accept", "application/json").build();
4069
+
4070
+ try (Response response = client.newCall(request).execute()) {
4071
+ final int statusCode = response.code();
4072
+ final ResponseBody responseBody = response.body();
4073
+ final String body = this.readResponseBody(responseBody != null ? responseBody.byteStream() : null);
3865
4074
  final JSONObject payload = new JSONObject(body);
3866
4075
  if (statusCode < 200 || statusCode >= 300) {
3867
4076
  throw new IOException(
@@ -3869,8 +4078,6 @@ public class CapacitorUpdaterPlugin extends Plugin {
3869
4078
  );
3870
4079
  }
3871
4080
  return payload;
3872
- } finally {
3873
- connection.disconnect();
3874
4081
  }
3875
4082
  }
3876
4083
 
@@ -4243,8 +4450,13 @@ public class CapacitorUpdaterPlugin extends Plugin {
4243
4450
  logger.error("Error no url or wrong format");
4244
4451
  return "unavailable";
4245
4452
  }
4453
+ // The TS contract only knows queued / already_running / unavailable.
4246
4454
  if (this.shouldBlockAutoUpdateForPreviewSession()) {
4247
- return "preview_session";
4455
+ return "unavailable";
4456
+ }
4457
+ if (!this._isAutoUpdateEnabled()) {
4458
+ logger.info("Auto update is disabled, update check not triggered");
4459
+ return "unavailable";
4248
4460
  }
4249
4461
  synchronized (this) {
4250
4462
  final Thread previousTask = this.backgroundDownloadTask;
@@ -4377,6 +4589,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
4377
4589
  @PluginMethod
4378
4590
  public void getNextBundle(final PluginCall call) {
4379
4591
  try {
4592
+ // Heals a next bundle left stored after it was activated (set() did not clear it before).
4593
+ this.implementation.clearNextBundleIfCurrent();
4380
4594
  final BundleInfo bundle = this.implementation.getNextBundle();
4381
4595
  if (bundle == null) {
4382
4596
  call.resolve(null);
@@ -4419,59 +4633,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4419
4633
  new TimerTask() {
4420
4634
  @Override
4421
4635
  public void run() {
4422
- try {
4423
- if (CapacitorUpdaterPlugin.this.shouldBlockAutoUpdateForPreviewSession()) {
4424
- return;
4425
- }
4426
- CapacitorUpdaterPlugin.this.implementation.getLatest(CapacitorUpdaterPlugin.this.updateUrl, null, (res) -> {
4427
- if (CapacitorUpdaterPlugin.this.shouldBlockAutoUpdateForPreviewSession()) {
4428
- return;
4429
- }
4430
- JSObject jsRes = InternalUtils.mapToJSObject(res);
4431
- if (jsRes.has("error") || jsRes.has("kind")) {
4432
- final BundleInfo current = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
4433
- String error = jsRes.has("error") ? jsRes.getString("error") : "";
4434
- String errorMessage = jsRes.has("message")
4435
- ? jsRes.getString("message")
4436
- : "server did not provide a message";
4437
- int statusCode = jsRes.has("statusCode") ? jsRes.optInt("statusCode", 0) : 0;
4438
- String kind = CapacitorUpdaterPlugin.this.getUpdateResponseKind(
4439
- jsRes.has("kind") ? jsRes.getString("kind") : null
4440
- );
4441
- String latestVersion = jsRes.has("version") ? jsRes.getString("version") : current.getVersionName();
4442
- CapacitorUpdaterPlugin.this.notifyUpdateCheckResult(
4443
- kind,
4444
- error,
4445
- errorMessage,
4446
- statusCode,
4447
- latestVersion,
4448
- current
4449
- );
4450
-
4451
- if ("failed".equals(kind)) {
4452
- logger.error("getLatest failed with error: " + error + ", message: " + errorMessage);
4453
- } else if ("blocked".equals(kind)) {
4454
- logger.info("Update check blocked with error: " + error);
4455
- } else {
4456
- logger.info("No new version available");
4457
- }
4458
- } else if (jsRes.has("version")) {
4459
- String newVersion = jsRes.getString("version");
4460
- String currentVersion = String.valueOf(CapacitorUpdaterPlugin.this.implementation.getCurrentBundle());
4461
- if (!Objects.equals(newVersion, currentVersion)) {
4462
- logger.info("New version found: " + newVersion);
4463
- // Check if download is already in progress (with timeout protection)
4464
- if (!CapacitorUpdaterPlugin.this.isDownloadStuckOrTimedOut()) {
4465
- CapacitorUpdaterPlugin.this.backgroundDownload();
4466
- } else {
4467
- logger.info("Download already in progress, skipping duplicate download request");
4468
- }
4469
- }
4470
- }
4471
- });
4472
- } catch (final Exception e) {
4473
- logger.error("Failed to check for update " + e.getMessage());
4474
- }
4636
+ CapacitorUpdaterPlugin.this.runPeriodicUpdateCheck();
4475
4637
  }
4476
4638
  },
4477
4639
  this.periodCheckDelay,
@@ -4479,10 +4641,165 @@ public class CapacitorUpdaterPlugin extends Plugin {
4479
4641
  );
4480
4642
  }
4481
4643
 
4644
+ void runPeriodicUpdateCheck() {
4645
+ try {
4646
+ if (this.shouldBlockAutoUpdateForPreviewSession()) {
4647
+ return;
4648
+ }
4649
+ this.implementation.getLatest(this.updateUrl, null, (res) -> {
4650
+ if (this.shouldBlockAutoUpdateForPreviewSession()) {
4651
+ return;
4652
+ }
4653
+ JSObject jsRes = InternalUtils.mapToJSObject(res);
4654
+ if (jsRes.has("error") || jsRes.has("kind")) {
4655
+ final BundleInfo current = this.implementation.getCurrentBundle();
4656
+ String error = jsRes.has("error") ? jsRes.getString("error") : "";
4657
+ String errorMessage = jsRes.has("message") ? jsRes.getString("message") : "server did not provide a message";
4658
+ int statusCode = jsRes.has("statusCode") ? jsRes.optInt("statusCode", 0) : 0;
4659
+ String kind = this.getUpdateResponseKind(jsRes.has("kind") ? jsRes.getString("kind") : null);
4660
+ String latestVersion = jsRes.has("version") ? jsRes.getString("version") : current.getVersionName();
4661
+ this.notifyUpdateCheckResult(kind, error, errorMessage, statusCode, latestVersion, current);
4662
+
4663
+ if ("failed".equals(kind)) {
4664
+ logger.error("getLatest failed with error: " + error + ", message: " + errorMessage);
4665
+ } else if ("blocked".equals(kind)) {
4666
+ logger.info("Update check blocked with error: " + error);
4667
+ } else {
4668
+ logger.info("No new version available");
4669
+ }
4670
+ } else if (jsRes.has("version")) {
4671
+ String newVersion = jsRes.getString("version");
4672
+ String currentVersion = this.implementation.getCurrentBundle().getVersionName();
4673
+ if (!Objects.equals(newVersion, currentVersion)) {
4674
+ logger.info("New version found: " + newVersion);
4675
+ // Check if download is already in progress (with timeout protection)
4676
+ if (!this.isDownloadStuckOrTimedOut()) {
4677
+ this.backgroundDownload();
4678
+ } else {
4679
+ logger.info("Download already in progress, skipping duplicate download request");
4680
+ }
4681
+ }
4682
+ }
4683
+ });
4684
+ } catch (final Exception e) {
4685
+ logger.error("Failed to check for update " + e.getMessage());
4686
+ }
4687
+ }
4688
+
4689
+ static boolean shouldAcceptReadyCall(
4690
+ final boolean guardArmed,
4691
+ final int expectedGeneration,
4692
+ final boolean hasGeneration,
4693
+ final int reportedGeneration
4694
+ ) {
4695
+ if (!guardArmed) {
4696
+ return true;
4697
+ }
4698
+ return hasGeneration && reportedGeneration == expectedGeneration;
4699
+ }
4700
+
4701
+ static String readyGenerationScript(final int generation) {
4702
+ // Wrap Capacitor.nativePromise, not the plugin proxy. registerPlugin's get trap
4703
+ // ignores assignments to notifyAppReady. Each document keeps its own generation.
4704
+ return (
4705
+ "(function(){window.__CAPGO_READY_GEN=" +
4706
+ generation +
4707
+ ";if(window.__capgoReadyBridge)return;" +
4708
+ "function arm(){var cap=window.Capacitor;if(!cap||typeof cap.nativePromise!=='function'||cap.__capgoNativePromise)return false;" +
4709
+ "var orig=cap.nativePromise.bind(cap);" +
4710
+ "cap.nativePromise=function(pluginName,methodName,options){if(pluginName==='CapacitorUpdater'&&methodName==='notifyAppReady'){" +
4711
+ "var next={};if(options&&typeof options==='object'){for(var k in options){if(Object.prototype.hasOwnProperty.call(options,k))next[k]=options[k];}}" +
4712
+ "next.loadGeneration=window.__CAPGO_READY_GEN;options=next;}return orig(pluginName,methodName,options);};" +
4713
+ "cap.__capgoNativePromise=true;window.__capgoReadyBridge=true;return true;}" +
4714
+ "if(!arm()){var n=0;var t=setInterval(function(){if(arm()||++n>100)clearInterval(t);},20);}" +
4715
+ "})();"
4716
+ );
4717
+ }
4718
+
4719
+ private int armReadyGuard() {
4720
+ synchronized (this.readyGuardLock) {
4721
+ this.readyGeneration = this.readyGeneration + 1;
4722
+ this.readyGuardArmed = true;
4723
+ return this.readyGeneration;
4724
+ }
4725
+ }
4726
+
4727
+ private void disarmReadyGuard(final int generation) {
4728
+ synchronized (this.readyGuardLock) {
4729
+ if (this.readyGeneration == generation) {
4730
+ this.readyGuardArmed = false;
4731
+ logger.warn("Could not stamp notifyAppReady for the next page. Readiness guard disabled for this reload.");
4732
+ }
4733
+ }
4734
+ }
4735
+
4736
+ private void stampReadyGenerationBeforeReload() {
4737
+ final int generation = this.armReadyGuard();
4738
+ final android.webkit.WebView webView = this.bridge != null ? this.bridge.getWebView() : null;
4739
+ if (webView == null) {
4740
+ this.disarmReadyGuard(generation);
4741
+ return;
4742
+ }
4743
+ webView.post(() -> {
4744
+ if (!this.installReadyGenerationScript(webView, generation)) {
4745
+ this.disarmReadyGuard(generation);
4746
+ }
4747
+ });
4748
+ }
4749
+
4750
+ private boolean installReadyGenerationScript(final android.webkit.WebView webView, final int generation) {
4751
+ try {
4752
+ final Class<?> webViewFeature = Class.forName("androidx.webkit.WebViewFeature");
4753
+ final String feature = (String) webViewFeature.getField("DOCUMENT_START_SCRIPT").get(null);
4754
+ final Boolean supported = (Boolean) webViewFeature.getMethod("isFeatureSupported", String.class).invoke(null, feature);
4755
+ if (!Boolean.TRUE.equals(supported)) {
4756
+ return false;
4757
+ }
4758
+ if (this.bridge == null || this.bridge.getAppUrl() == null) {
4759
+ return false;
4760
+ }
4761
+ final String allowedOrigin = Uri.parse(this.bridge.getAppUrl())
4762
+ .buildUpon()
4763
+ .path(null)
4764
+ .fragment(null)
4765
+ .clearQuery()
4766
+ .build()
4767
+ .toString();
4768
+ final Class<?> webViewCompat = Class.forName("androidx.webkit.WebViewCompat");
4769
+ webViewCompat
4770
+ .getMethod("addDocumentStartJavaScript", android.webkit.WebView.class, String.class, Set.class)
4771
+ .invoke(null, webView, readyGenerationScript(generation), java.util.Collections.singleton(allowedOrigin));
4772
+ return true;
4773
+ } catch (final Exception e) {
4774
+ logger.warn("Unable to stamp notifyAppReady generation: " + e.getMessage());
4775
+ return false;
4776
+ }
4777
+ }
4778
+
4779
+ private boolean acceptsReadyCall(final PluginCall call) {
4780
+ if (!this.readyGuardArmed) {
4781
+ return true;
4782
+ }
4783
+ final JSObject data = call.getData();
4784
+ final boolean hasGeneration = data != null && data.has("loadGeneration");
4785
+ final int reported = hasGeneration ? data.optInt("loadGeneration", -1) : -1;
4786
+ return shouldAcceptReadyCall(this.readyGuardArmed, this.readyGeneration, hasGeneration, reported);
4787
+ }
4788
+
4482
4789
  @PluginMethod
4483
4790
  public void notifyAppReady(final PluginCall call) {
4484
4791
  ensureBridgeSet();
4485
4792
  try {
4793
+ if (!this.acceptsReadyCall(call)) {
4794
+ logger.info("Ignoring notifyAppReady from a page that is no longer current");
4795
+ final BundleInfo current = this.implementation.getCurrentBundle();
4796
+ final JSObject ignored = new JSObject();
4797
+ if (current != null) {
4798
+ ignored.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
4799
+ }
4800
+ call.resolve(ignored);
4801
+ return;
4802
+ }
4486
4803
  final BundleInfo bundle = this.implementation.getCurrentBundle();
4487
4804
  this.implementation.setSuccess(bundle, this.autoDeletePrevious);
4488
4805
  this.reportAppLaunchReady(bundle);
@@ -4518,11 +4835,27 @@ public class CapacitorUpdaterPlugin extends Plugin {
4518
4835
  }
4519
4836
  }
4520
4837
 
4521
- if (this.delayUpdateUtils.setMultiDelay(delayConditions.toString())) {
4522
- call.resolve();
4523
- } else {
4838
+ final String conditionMode = call.getData().optString("conditionMode", DelayUpdateUtils.DELAY_CONDITION_MODE_AND);
4839
+ final String previousConditions = prefs.getString(DelayUpdateUtils.DELAY_CONDITION_PREFERENCES, "[]");
4840
+ final String previousMode = this.delayUpdateUtils.getConditionMode();
4841
+ if (!this.delayUpdateUtils.setMultiDelay(delayConditions.toString())) {
4842
+ if (!this.delayUpdateUtils.setMultiDelay(previousConditions)) {
4843
+ logger.error("Failed to restore previous delay conditions after setMultiDelay failure");
4844
+ }
4524
4845
  call.reject("Failed to delay update");
4846
+ return;
4525
4847
  }
4848
+ if (!this.delayUpdateUtils.setConditionMode(conditionMode)) {
4849
+ if (!this.delayUpdateUtils.setMultiDelay(previousConditions)) {
4850
+ logger.error("Failed to restore previous delay conditions after setConditionMode failure");
4851
+ }
4852
+ if (!this.delayUpdateUtils.setConditionMode(previousMode)) {
4853
+ logger.error("Failed to restore previous delay condition mode after setConditionMode failure");
4854
+ }
4855
+ call.reject("Failed to delay update");
4856
+ return;
4857
+ }
4858
+ call.resolve();
4526
4859
  } catch (final Exception e) {
4527
4860
  logger.error("Failed to delay update, [Error calling 'setMultiDelay()'] " + e.getMessage());
4528
4861
  call.reject("Failed to delay update", e);
@@ -4643,11 +4976,11 @@ public class CapacitorUpdaterPlugin extends Plugin {
4643
4976
  ret.put("statusCode", statusCode);
4644
4977
  ret.put("version", version);
4645
4978
  ret.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
4646
- this.notifyListeners("updateCheckResult", ret);
4979
+ this.notifyListeners("updateCheckResult", ret, false);
4647
4980
  }
4648
4981
 
4649
4982
  private void ensureBridgeSet() {
4650
- if (this.bridge != null && this.bridge.getWebView() != null) {
4983
+ if (this.bridge != null && this.bridge.getWebView() != null && !this.getConfig().getBoolean("disableJSLogging", false)) {
4651
4984
  logger.setBridge(this.bridge);
4652
4985
  }
4653
4986
  }
@@ -4727,12 +5060,12 @@ public class CapacitorUpdaterPlugin extends Plugin {
4727
5060
  }
4728
5061
  final JSObject ret = new JSObject();
4729
5062
  ret.put("version", latestVersionName);
4730
- this.notifyListeners(failureEvent, ret);
5063
+ this.notifyListeners(failureEvent, ret, false);
4731
5064
  }
4732
5065
  if (shouldNotifyNoNeedUpdate) {
4733
5066
  final JSObject ret = new JSObject();
4734
5067
  ret.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
4735
- this.notifyListeners("noNeedUpdate", ret);
5068
+ this.notifyListeners("noNeedUpdate", ret, false);
4736
5069
  }
4737
5070
  this.sendReadyToJs(current, msg, plannedDirectUpdate);
4738
5071
  this.backgroundDownloadTask = null;
@@ -4770,6 +5103,26 @@ public class CapacitorUpdaterPlugin extends Plugin {
4770
5103
  return true;
4771
5104
  }
4772
5105
 
5106
+ /**
5107
+ * Security gates of an auto-update download, checked before it starts. Returns the cycle status
5108
+ * when the download must not start (after sending its stat), or null.
5109
+ */
5110
+ private String autoUpdateDownloadBlockedReason(final JSObject latest, final String latestVersionName) {
5111
+ final String sessionKey = latest.getString("sessionKey", "");
5112
+ if (!this.implementation.publicKey.isEmpty() && !CryptoCipher.isValidSessionKey(sessionKey)) {
5113
+ logger.error("Public key present but no valid session key provided");
5114
+ this.implementation.sendStats("session_key_required", latestVersionName);
5115
+ return "Session key required when public key is present";
5116
+ }
5117
+ final String checksum = latest.getString("checksum", "");
5118
+ if (!latest.has("manifest") && (checksum == null || checksum.isEmpty())) {
5119
+ logger.error("No checksum provided");
5120
+ this.implementation.sendStats("checksum_required", latestVersionName);
5121
+ return "Checksum required";
5122
+ }
5123
+ return null;
5124
+ }
5125
+
4773
5126
  private synchronized Thread backgroundDownload() {
4774
5127
  if (this.shouldBlockAutoUpdateForPreviewSession()) {
4775
5128
  return null;
@@ -4831,6 +5184,16 @@ public class CapacitorUpdaterPlugin extends Plugin {
4831
5184
  }
4832
5185
 
4833
5186
  boolean isFailure = "failed".equals(kind);
5187
+ if (isFailure) {
5188
+ // The check itself failed (offline, timeout, unreadable response, 429 block):
5189
+ // nothing was downloaded, so report it apart from download_fail.
5190
+ CapacitorUpdaterPlugin.this.implementation.sendStats(
5191
+ UPDATE_CHECK_ERROR_ACTION,
5192
+ currentBeforeCleanup.getVersionName(),
5193
+ "",
5194
+ updateCheckErrorMetadata(error, statusCode)
5195
+ );
5196
+ }
4834
5197
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
4835
5198
  errorMessage,
4836
5199
  latestVersion,
@@ -4839,7 +5202,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4839
5202
  plannedDirectUpdate,
4840
5203
  "download_fail",
4841
5204
  "downloadFailed",
4842
- isFailure
5205
+ false
4843
5206
  );
4844
5207
  return;
4845
5208
  }
@@ -4888,7 +5251,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4888
5251
  BundleInfo.ID_BUILTIN
4889
5252
  );
4890
5253
  ret.put("bundle", InternalUtils.mapToJSObject(builtinBundle.toJSONMap()));
4891
- CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret);
5254
+ CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, false);
4892
5255
  }
4893
5256
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
4894
5257
  "Latest version is builtin, autoUpdate onlyDownload",
@@ -4936,7 +5299,13 @@ public class CapacitorUpdaterPlugin extends Plugin {
4936
5299
  );
4937
5300
  return;
4938
5301
  }
4939
- if (latest.isDownloaded() && BundleStatus.DOWNLOADING != latest.getStatus()) {
5302
+ final String latestSessionKey = jsRes.has("sessionKey") ? jsRes.getString("sessionKey") : "";
5303
+ if (
5304
+ latest.isDownloaded() &&
5305
+ BundleStatus.DOWNLOADING != latest.getStatus() &&
5306
+ (CapacitorUpdaterPlugin.this.implementation.publicKey.isEmpty() ||
5307
+ CryptoCipher.isValidSessionKey(latestSessionKey))
5308
+ ) {
4940
5309
  logger.info("Latest bundle already exists and download is NOT required. " + messageUpdate);
4941
5310
  final boolean directUpdateAllowedNow = CapacitorUpdaterPlugin.this.isDirectUpdateCurrentlyAllowed(
4942
5311
  plannedDirectUpdate
@@ -4983,7 +5352,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4983
5352
  "Direct update skipped because splashscreen timeout occurred. Update will install on next background."
4984
5353
  );
4985
5354
  }
4986
- CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret);
5355
+ CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, false);
4987
5356
  CapacitorUpdaterPlugin.this.implementation.setNextBundle(latest.getId());
4988
5357
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
4989
5358
  "update downloaded, will install next background",
@@ -4994,7 +5363,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4994
5363
  );
4995
5364
  } else {
4996
5365
  logger.info("autoUpdate is set to onlyDownload, downloaded update will not be set as next bundle");
4997
- CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret);
5366
+ CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, false);
4998
5367
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
4999
5368
  "update downloaded, autoUpdate onlyDownload",
5000
5369
  latestVersionName,
@@ -5021,6 +5390,22 @@ public class CapacitorUpdaterPlugin extends Plugin {
5021
5390
  }
5022
5391
  }
5023
5392
  }
5393
+ // The store refuses these downloads without a callback, so end the cycle here
5394
+ // (appReady, splash hide) like iOS does.
5395
+ final String downloadBlockedReason = CapacitorUpdaterPlugin.this.autoUpdateDownloadBlockedReason(
5396
+ jsRes,
5397
+ latestVersionName
5398
+ );
5399
+ if (downloadBlockedReason != null) {
5400
+ CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
5401
+ downloadBlockedReason,
5402
+ latestVersionName,
5403
+ current,
5404
+ true,
5405
+ plannedDirectUpdate
5406
+ );
5407
+ return;
5408
+ }
5024
5409
  final boolean retryingInFlightDownload =
5025
5410
  latest != null &&
5026
5411
  BundleStatus.DOWNLOADING == latest.getStatus() &&
@@ -5119,6 +5504,19 @@ public class CapacitorUpdaterPlugin extends Plugin {
5119
5504
  return newTask;
5120
5505
  }
5121
5506
 
5507
+ /**
5508
+ * A download that finished while the app is in the background (for example after an
5509
+ * update-check push) would otherwise wait for the next foreground/background cycle, so the
5510
+ * user would open the old version once more. Install it now, like a background transition.
5511
+ */
5512
+ void installNextIfInBackground() {
5513
+ if (!this.appInBackground) {
5514
+ return;
5515
+ }
5516
+ logger.info("Next bundle downloaded while in background, installing it now");
5517
+ this.installNext();
5518
+ }
5519
+
5122
5520
  private void installNext() {
5123
5521
  try {
5124
5522
  if (this.shouldBlockAutoUpdateForPreviewSession()) {
@@ -5171,33 +5569,51 @@ public class CapacitorUpdaterPlugin extends Plugin {
5171
5569
  final JSObject ret = new JSObject();
5172
5570
  ret.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
5173
5571
  this.persistLastFailedBundle(current);
5174
- this.notifyListeners("updateFailed", ret);
5572
+ this.notifyListeners("updateFailed", ret, false);
5175
5573
  this.reportAppLaunchTimeout(current);
5176
5574
  this.implementation.sendStats("update_fail", current.getVersionName());
5177
5575
  this.implementation.setError(current);
5178
5576
  this.performReset(true, false, true);
5179
5577
  if (CapacitorUpdaterPlugin.this.autoDeleteFailed && !current.isBuiltin()) {
5180
5578
  final String failedId = current.getId();
5181
- final String failedVersion = current.getVersionName();
5182
- logger.info("Deleting failing bundle: " + failedVersion);
5183
- // Mark before async work so kill/OOM still resumes via drainPendingDeletes.
5184
- CapacitorUpdaterPlugin.this.implementation.saveBundleInfo(failedId, current.setStatus(BundleStatus.DELETING));
5185
- startNewThread(() -> {
5186
- try {
5187
- final Boolean res = CapacitorUpdaterPlugin.this.implementation.delete(failedId, false, false);
5188
- if (Boolean.TRUE.equals(res)) {
5189
- logger.info("Failed bundle deleted: " + failedVersion);
5579
+ final BundleInfo latest = this.implementation.getBundleInfo(failedId);
5580
+ final boolean stillCurrent = failedId.equals(this.implementation.getCurrentBundle().getId());
5581
+ // performReset waits for notifyAppReady. Resetting onto this same bundle writes
5582
+ // SUCCESS before we get here, so the pre-reset snapshot must not become DELETING.
5583
+ if (latest == null || BundleStatus.ERROR != latest.getStatus() || stillCurrent) {
5584
+ logger.info("Skip deleting bundle " + failedId + " after reset");
5585
+ } else {
5586
+ final String failedVersion = latest.getVersionName();
5587
+ logger.info("Deleting failing bundle: " + failedVersion);
5588
+ // Mark before async work so kill/OOM still resumes via drainPendingDeletes.
5589
+ CapacitorUpdaterPlugin.this.implementation.saveBundleInfo(failedId, latest.setStatus(BundleStatus.DELETING));
5590
+ startNewThread(() -> {
5591
+ try {
5592
+ final Boolean res = CapacitorUpdaterPlugin.this.implementation.delete(failedId, false, false);
5593
+ if (Boolean.TRUE.equals(res)) {
5594
+ logger.info("Failed bundle deleted: " + failedVersion);
5595
+ }
5596
+ } catch (final IOException e) {
5597
+ logger.error("Failed to delete failed bundle: " + failedVersion + " " + e.getMessage());
5190
5598
  }
5191
- } catch (final IOException e) {
5192
- logger.error("Failed to delete failed bundle: " + failedVersion + " " + e.getMessage());
5193
- }
5194
- });
5599
+ });
5600
+ }
5195
5601
  }
5196
5602
  } else {
5197
5603
  logger.info("notifyAppReady was called. This is fine: " + current.getId());
5198
5604
  }
5199
5605
  }
5200
5606
 
5607
+ void runDeferredAppReadyCheck() {
5608
+ // A frozen app wakes up with its sleep already expired, before appMovedToForeground re-arms
5609
+ // the check: its page could not run yet, so wait for the fresh check of the next foreground.
5610
+ if (this.appInBackground) {
5611
+ logger.info("App is in background, notifyAppReady check deferred to the next foreground");
5612
+ return;
5613
+ }
5614
+ this.checkRevert();
5615
+ }
5616
+
5201
5617
  private class DeferredNotifyAppReadyCheck implements Runnable {
5202
5618
 
5203
5619
  private final long waitTimeMs;
@@ -5212,7 +5628,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5212
5628
  try {
5213
5629
  logger.info("Wait for " + this.waitTimeMs + "ms, then check for notifyAppReady");
5214
5630
  Thread.sleep(this.waitTimeMs);
5215
- CapacitorUpdaterPlugin.this.checkRevert();
5631
+ CapacitorUpdaterPlugin.this.runDeferredAppReadyCheck();
5216
5632
  CapacitorUpdaterPlugin.this.clearAppReadyCheckIfCurrent(currentThread);
5217
5633
  } catch (final InterruptedException e) {
5218
5634
  CapacitorUpdaterPlugin.this.clearAppReadyCheckIfCurrent(currentThread);
@@ -5222,6 +5638,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5222
5638
  }
5223
5639
 
5224
5640
  public void appMovedToForeground() {
5641
+ this.appInBackground = false;
5225
5642
  // Ensure activity reference is up-to-date before proceeding
5226
5643
  // This is critical for callbacks that may be invoked during background operations
5227
5644
  try {
@@ -5240,8 +5657,13 @@ public class CapacitorUpdaterPlugin extends Plugin {
5240
5657
  this.delayUpdateUtils.checkCancelDelay(DelayUpdateUtils.CancelDelaySource.FOREGROUND);
5241
5658
  this.delayUpdateUtils.unsetBackgroundTimestamp();
5242
5659
 
5243
- if (CapacitorUpdaterPlugin.this._isAutoUpdateEnabled() && !this.isDownloadStuckOrTimedOut()) {
5244
- this.backgroundDownload();
5660
+ if (CapacitorUpdaterPlugin.this._isAutoUpdateEnabled()) {
5661
+ if (!this.isDownloadStuckOrTimedOut()) {
5662
+ this.backgroundDownload();
5663
+ } else {
5664
+ // The running cycle sends appReady when it ends.
5665
+ logger.info("Download already in progress, skipping duplicate download request");
5666
+ }
5245
5667
  } else {
5246
5668
  final CapConfig config = CapConfig.loadDefault(this.getActivity());
5247
5669
  String serverUrl = config.getServerUrl();
@@ -5255,6 +5677,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5255
5677
  }
5256
5678
 
5257
5679
  public void appMovedToBackground() {
5680
+ this.appInBackground = true;
5258
5681
  // Reset timeout flag at start of each background cycle
5259
5682
  this.autoSplashscreenTimedOut = false;
5260
5683
 
@@ -5609,6 +6032,12 @@ public class CapacitorUpdaterPlugin extends Plugin {
5609
6032
  result.put("installStatus", appUpdateInfo.installStatus());
5610
6033
 
5611
6034
  call.resolve(result);
6035
+ if (
6036
+ appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE &&
6037
+ CapacitorUpdaterPlugin.this.nativeUpdatePrompt != null
6038
+ ) {
6039
+ CapacitorUpdaterPlugin.this.nativeUpdatePrompt.maybeShowForStoreUpdateAvailable();
6040
+ }
5612
6041
  })
5613
6042
  .addOnFailureListener((e) -> {
5614
6043
  logger.error("Failed to get app update info: " + e.getMessage());
@@ -5753,7 +6182,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5753
6182
  eventData.put("totalBytesToDownload", state.totalBytesToDownload());
5754
6183
  }
5755
6184
 
5756
- notifyListeners("onFlexibleUpdateStateChange", eventData);
6185
+ notifyListeners("onFlexibleUpdateStateChange", eventData, false);
5757
6186
  };
5758
6187
 
5759
6188
  manager.registerListener(installStateUpdatedListener);
@@ -5840,6 +6269,10 @@ public class CapacitorUpdaterPlugin extends Plugin {
5840
6269
  }
5841
6270
 
5842
6271
  private void handleOnDestroyInternal() {
6272
+ instanceLoaded = false;
6273
+ if (this.implementation != null) {
6274
+ this.implementation.releaseStatsOwnership();
6275
+ }
5843
6276
  // Original handleOnDestroy code
5844
6277
  try {
5845
6278
  logger.info("onActivityDestroyed " + getActivity().getClass().getName());