@capgo/capacitor-updater 5.50.2 → 5.51.17

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 (33) hide show
  1. package/CapgoCapacitorUpdater.podspec +1 -3
  2. package/Package.swift +5 -6
  3. package/README.md +53 -48
  4. package/android/build.gradle +7 -6
  5. package/android/src/main/java/ee/forgr/capacitor_updater/AppLifecycleObserver.java +29 -2
  6. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +7 -3
  7. package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +1 -0
  8. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +470 -146
  9. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +1354 -414
  10. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +102 -31
  11. package/android/src/main/java/ee/forgr/capacitor_updater/DataManager.java +23 -7
  12. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +2 -2
  13. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +11 -0
  14. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +540 -224
  15. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +103 -3
  16. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +1 -1
  17. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +131 -145
  18. package/dist/docs.json +32 -8
  19. package/dist/esm/definitions.d.ts +41 -17
  20. package/dist/esm/definitions.js.map +1 -1
  21. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +124 -0
  22. package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +9 -1
  23. package/ios/Sources/CapacitorUpdaterPlugin/BundleStatus.swift +3 -0
  24. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +807 -93
  25. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  26. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +1020 -270
  27. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +49 -31
  28. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +5 -5
  29. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +73 -251
  30. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +44 -20
  31. package/ios/Sources/CapacitorUpdaterPlugin/WebViewStatsReporter.swift +28 -0
  32. package/package.json +14 -8
  33. package/ios/Sources/CapacitorUpdaterPlugin/BigInt.swift +0 -39
@@ -50,6 +50,7 @@ import com.google.android.play.core.install.model.InstallStatus;
50
50
  import com.google.android.play.core.install.model.UpdateAvailability;
51
51
  import io.github.g00fy2.versioncompare.Version;
52
52
  import java.io.ByteArrayOutputStream;
53
+ import java.io.File;
53
54
  import java.io.IOException;
54
55
  import java.io.InputStream;
55
56
  import java.net.HttpURLConnection;
@@ -68,6 +69,7 @@ import java.util.Set;
68
69
  import java.util.TimeZone;
69
70
  import java.util.Timer;
70
71
  import java.util.TimerTask;
72
+ import java.util.concurrent.CountDownLatch;
71
73
  import java.util.concurrent.Phaser;
72
74
  import java.util.concurrent.Semaphore;
73
75
  import java.util.concurrent.TimeUnit;
@@ -103,6 +105,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
103
105
  private static final String CHANNEL_URL_PREF_KEY = "CapacitorUpdater.channelUrl";
104
106
  private static final String DEFAULT_CHANNEL_PREF_KEY = "CapacitorUpdater.defaultChannel";
105
107
  private static final String PREVIEW_SESSION_PREF_KEY = "CapacitorUpdater.previewSession";
108
+ private static final String DEFAULT_CHANNEL_INSTALL_MARKER_PREF_KEY = "CapacitorUpdater.defaultChannelInstallMarkerCreated";
109
+ private static final String DEFAULT_CHANNEL_INSTALL_MARKER_FILE = "CapacitorUpdater.defaultChannelInstallMarker";
106
110
  private static final String PREVIEW_PREVIOUS_SHAKE_MENU_PREF_KEY = "CapacitorUpdater.previewPreviousShakeMenu";
107
111
  private static final String PREVIEW_PREVIOUS_SHAKE_CHANNEL_SELECTOR_PREF_KEY = "CapacitorUpdater.previewPreviousShakeChannelSelector";
108
112
  private static final String PREVIEW_PREVIOUS_NEXT_BUNDLE_PREF_KEY = "CapacitorUpdater.previewPreviousNextBundle";
@@ -142,7 +146,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
142
146
  static final int APPLICATION_EXIT_REASON_USER_REQUESTED = 10;
143
147
  static final int APPLICATION_EXIT_REASON_DEPENDENCY_DIED = 12;
144
148
 
145
- private final String pluginVersion = "5.50.1";
149
+ private final String pluginVersion = "5.51.17";
146
150
  private static final String DELAY_CONDITION_PREFERENCES = "";
147
151
 
148
152
  private SharedPreferences.Editor editor;
@@ -151,6 +155,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
151
155
  protected CapgoUpdater implementation;
152
156
  private Boolean persistCustomId = false;
153
157
  private Boolean persistModifyUrl = false;
158
+ private Boolean persistDefaultChannelOnReinstall = true;
154
159
 
155
160
  private Integer appReadyTimeout = 10000;
156
161
  private Integer periodCheckDelay = 0;
@@ -215,6 +220,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
215
220
 
216
221
  private volatile Thread backgroundDownloadTask;
217
222
  private volatile Thread appReadyCheck;
223
+ // When true, sendReadyToJs should wait for notifyAppReady before hiding splash.
224
+ private volatile boolean pendingNotifyAppReadyWait = false;
225
+ private volatile int pendingNotifyAppReadyPhase = -1;
218
226
  private volatile long downloadStartTimeMs = 0;
219
227
  private static final long DOWNLOAD_TIMEOUT_MS = 600000; // 10 minute timeout
220
228
 
@@ -227,8 +235,10 @@ public class CapacitorUpdaterPlugin extends Plugin {
227
235
 
228
236
  // Lock to ensure cleanup completes before downloads start
229
237
  private final Object cleanupLock = new Object();
238
+ private volatile CountDownLatch cleanupLatch = new CountDownLatch(0);
230
239
  private volatile boolean cleanupComplete = false;
231
240
  private volatile Thread cleanupThread = null;
241
+ private volatile boolean defaultChannelCleanupMustRetry = false;
232
242
 
233
243
  private int lastNotifiedStatPercent = 0;
234
244
 
@@ -236,6 +246,12 @@ public class CapacitorUpdaterPlugin extends Plugin {
236
246
 
237
247
  private ShakeMenu shakeMenu;
238
248
  private final Handler mainHandler = new Handler(Looper.getMainLooper());
249
+ private final long launchStartedAtMs = System.currentTimeMillis();
250
+ private volatile long webViewPageStartedAtMs = 0;
251
+ private volatile boolean launchStartReported = false;
252
+ private volatile boolean launchReadyReported = false;
253
+ private volatile boolean launchTimeoutReported = false;
254
+ private final Object launchReportLock = new Object();
239
255
  private FrameLayout splashscreenLoaderOverlay;
240
256
  private Runnable splashscreenTimeoutRunnable;
241
257
  private FrameLayout previewTransitionLoaderOverlay;
@@ -268,8 +284,13 @@ public class CapacitorUpdaterPlugin extends Plugin {
268
284
  // App lifecycle observer using ProcessLifecycleOwner for reliable foreground/background detection
269
285
  private AppLifecycleObserver appLifecycleObserver;
270
286
 
287
+ private boolean isProcessLifecycleObserverActive() {
288
+ return this.appLifecycleObserver != null && this.appLifecycleObserver.isRegistered();
289
+ }
290
+
271
291
  // Play Store In-App Updates
272
292
  private AppUpdateManager appUpdateManager;
293
+ private PluginCall pendingAppUpdateCall;
273
294
  private AppUpdateInfo cachedAppUpdateInfo;
274
295
  private static final int APP_UPDATE_REQUEST_CODE = 9001;
275
296
  private InstallStateUpdatedListener installStateUpdatedListener;
@@ -747,6 +768,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
747
768
 
748
769
  this.persistCustomId = this.getConfig().getBoolean("persistCustomId", false);
749
770
  this.persistModifyUrl = this.getConfig().getBoolean("persistModifyUrl", false);
771
+ this.persistDefaultChannelOnReinstall = this.getConfig().getBoolean("persistDefaultChannelOnReinstall", true);
750
772
  this.allowSetDefaultChannel = this.getConfig().getBoolean("allowSetDefaultChannel", true);
751
773
  this.implementation.setPublicKey(this.getConfig().getString("publicKey", ""));
752
774
  // Log public key prefix if encryption is enabled
@@ -773,6 +795,35 @@ public class CapacitorUpdaterPlugin extends Plugin {
773
795
  }
774
796
  }
775
797
 
798
+ final boolean resetWhenUpdate = this.getConfig().getBoolean("resetWhenUpdate", true);
799
+ final boolean nativeBuildVersionChanged = this.hasNativeBuildVersionChanged();
800
+ final boolean defaultChannelPersistenceDisabled = !Boolean.TRUE.equals(this.persistDefaultChannelOnReinstall);
801
+ final boolean restoredReinstall = defaultChannelPersistenceDisabled && this.isRestoredReinstall();
802
+ boolean installMarkerCanBePrepared = true;
803
+ if (
804
+ shouldClearPersistedDefaultChannel(
805
+ Boolean.TRUE.equals(this.persistDefaultChannelOnReinstall),
806
+ resetWhenUpdate,
807
+ nativeBuildVersionChanged,
808
+ restoredReinstall
809
+ )
810
+ ) {
811
+ installMarkerCanBePrepared = clearPersistedDefaultChannel(this.editor);
812
+ if (installMarkerCanBePrepared) {
813
+ logger.info("Cleared persisted defaultChannel because reinstall persistence is disabled");
814
+ } else {
815
+ logger.warn("Cannot durably clear persisted defaultChannel");
816
+ this.defaultChannelCleanupMustRetry = true;
817
+ if (!invalidateDefaultChannelInstallMarker(this.defaultChannelInstallMarker())) {
818
+ logger.warn("Cannot invalidate default channel install marker for cleanup retry");
819
+ }
820
+ }
821
+ }
822
+ if (defaultChannelPersistenceDisabled && installMarkerCanBePrepared) {
823
+ this.prepareDefaultChannelInstallMarker();
824
+ }
825
+
826
+ final String configDefaultChannel = this.getConfig().getString("defaultChannel", "");
776
827
  // Load defaultChannel: first try from persistent storage (set via setChannel), then fall back to config
777
828
  if (this.prefs.contains(DEFAULT_CHANNEL_PREF_KEY)) {
778
829
  final String storedDefaultChannel = this.prefs.getString(DEFAULT_CHANNEL_PREF_KEY, "");
@@ -780,20 +831,22 @@ public class CapacitorUpdaterPlugin extends Plugin {
780
831
  this.implementation.defaultChannel = storedDefaultChannel;
781
832
  logger.info("Loaded persisted defaultChannel from setChannel()");
782
833
  } else {
783
- this.implementation.defaultChannel = this.getConfig().getString("defaultChannel", "");
834
+ this.implementation.defaultChannel = configDefaultChannel;
784
835
  }
785
836
  } else {
786
- this.implementation.defaultChannel = this.getConfig().getString("defaultChannel", "");
837
+ this.implementation.defaultChannel = configDefaultChannel;
787
838
  }
788
839
 
789
840
  this.periodCheckDelay = normalizedPeriodCheckDelayMs(this.getConfig().getInt("periodCheckDelay", 0));
790
841
 
791
842
  this.implementation.documentsDir = this.getContext().getFilesDir();
843
+ this.implementation.noBackupDir = this.getContext().getNoBackupFilesDir();
792
844
  this.implementation.prefs = this.prefs;
793
845
  this.implementation.editor = this.editor;
794
846
  this.implementation.versionOs = Build.VERSION.RELEASE;
795
847
  // Use DeviceIdHelper to get or create device ID that persists across reinstalls
796
848
  this.implementation.deviceID = DeviceIdHelper.getOrCreateDeviceId(this.getContext(), this.prefs);
849
+ this.implementation.restorePendingStats();
797
850
 
798
851
  // Update User-Agent for shared OkHttpClient with OS version
799
852
  DownloadService.updateUserAgent(this.implementation.appId, this.pluginVersion, this.implementation.versionOs);
@@ -807,6 +860,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
807
860
  }
808
861
  logger.info("init for device " + this.implementation.deviceID);
809
862
  logger.info("version native " + this.currentVersionNative.getOriginalString());
863
+ this.reportAppLaunchStart();
810
864
  this.autoDeleteFailed = this.getConfig().getBoolean("autoDeleteFailed", true);
811
865
  this.autoDeletePrevious = this.getConfig().getBoolean("autoDeletePrevious", true);
812
866
  this.updateUrl = this.getConfig().getString("updateUrl", updateUrlDefault);
@@ -828,7 +882,10 @@ public class CapacitorUpdaterPlugin extends Plugin {
828
882
  this.autoSplashscreenLoader = this.getConfig().getBoolean("autoSplashscreenLoader", false);
829
883
  int splashscreenTimeoutValue = this.getConfig().getInt("autoSplashscreenTimeout", 10000);
830
884
  this.autoSplashscreenTimeout = Math.max(0, splashscreenTimeoutValue);
831
- this.implementation.timeout = this.getConfig().getInt("responseTimeout", 20) * 1000;
885
+ int responseTimeoutSeconds = this.getConfig().getInt("responseTimeout", 20);
886
+ long responseTimeoutMillis = responseTimeoutSeconds > 0 ? (long) responseTimeoutSeconds * 1000L : 20_000L;
887
+ this.implementation.timeout = (int) Math.min(Integer.MAX_VALUE, responseTimeoutMillis);
888
+ DownloadService.applyHttpTimeouts(this.implementation.timeout);
832
889
  this.shakeMenuEnabled = this.getConfig().getBoolean("shakeMenu", false);
833
890
  this.shakeChannelSelectorEnabled = this.getConfig().getBoolean("allowShakeChannelSelector", false);
834
891
  this.shakeMenuGesture = normalizedShakeMenuGesture(this.getConfig().getString("shakeMenuGesture", SHAKE_MENU_GESTURE_SHAKE));
@@ -851,11 +908,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
851
908
  ? this.prefs.getBoolean(PREVIEW_PREVIOUS_SHAKE_CHANNEL_SELECTOR_PREF_KEY, false)
852
909
  : this.shakeChannelSelectorEnabled;
853
910
  }
854
- boolean resetWhenUpdate = this.getConfig().getBoolean("resetWhenUpdate", true);
855
911
 
856
912
  // Check if app was recently installed/updated BEFORE cleanupObsoleteVersions updates LatestVersionNative
857
913
  this.wasRecentlyInstalledOrUpdated = this.checkIfRecentlyInstalledOrUpdated();
858
- final boolean nativeBuildVersionChanged = this.hasNativeBuildVersionChanged();
859
914
 
860
915
  this.implementation.autoReset(this.currentBuildVersion, resetWhenUpdate);
861
916
  if (nativeBuildVersionChanged) {
@@ -866,11 +921,14 @@ public class CapacitorUpdaterPlugin extends Plugin {
866
921
  this.reportPreviousAppExitReasons();
867
922
  this.reportPreviousWebViewRenderProcessGone();
868
923
  this.installWebViewStatsReporter();
869
- if (resetWhenUpdate) {
870
- this.cleanupObsoleteVersions();
871
- } else {
924
+ // Downloads (including shake-menu / CapgoUpdater entry points) wait on this gate.
925
+ this.implementation.downloadGate = this::waitForCleanupIfNeeded;
926
+ // Always run async cleanup: delete obsolete bundles on native update (when enabled)
927
+ // and sweep orphan folders every launch. Must not block app startup.
928
+ if (!resetWhenUpdate) {
872
929
  this.persistCurrentNativeBuildVersion();
873
930
  }
931
+ this.cleanupObsoleteVersions(resetWhenUpdate);
874
932
 
875
933
  // Check for 'kill' delay condition on app launch
876
934
  // This handles cases where the app was killed by the system (onDestroy is not reliable)
@@ -899,11 +957,18 @@ public class CapacitorUpdaterPlugin extends Plugin {
899
957
  },
900
958
  logger
901
959
  );
902
- this.appLifecycleObserver.register();
903
- logger.info("Using ProcessLifecycleOwner for foreground/background detection (Android 14+)");
960
+ this.appLifecycleObserver.register(this.getContext());
961
+ if (!this.appLifecycleObserver.isRegistered()) {
962
+ logger.warn("ProcessLifecycleOwner unavailable; using activity lifecycle callbacks");
963
+ } else {
964
+ logger.info("Using ProcessLifecycleOwner for foreground/background detection (Android 14+)");
965
+ }
904
966
  } else {
905
967
  logger.info("Using activity lifecycle callbacks for foreground/background detection (Android <14)");
906
968
  }
969
+
970
+ // Expect notifyAppReady before the first appReady/splash hide (same idea as iOS).
971
+ this.armPendingNotifyAppReadyWait();
907
972
  }
908
973
 
909
974
  private boolean semaphoreWait(final int phase, Number waitTime) {
@@ -946,6 +1011,32 @@ public class CapacitorUpdaterPlugin extends Plugin {
946
1011
  semaphoreReady.arriveAndDeregister();
947
1012
  }
948
1013
 
1014
+ private void armPendingNotifyAppReadyWait() {
1015
+ this.clearPendingNotifyAppReadyWait();
1016
+ this.pendingNotifyAppReadyPhase = this.semaphoreUp();
1017
+ this.pendingNotifyAppReadyWait = true;
1018
+ }
1019
+
1020
+ private void clearPendingNotifyAppReadyWait() {
1021
+ if (!this.pendingNotifyAppReadyWait) {
1022
+ return;
1023
+ }
1024
+ final int phase = this.pendingNotifyAppReadyPhase;
1025
+ this.pendingNotifyAppReadyWait = false;
1026
+ this.pendingNotifyAppReadyPhase = -1;
1027
+ this.cleanupTimedOutSemaphoreWait(phase);
1028
+ }
1029
+
1030
+ private boolean consumePendingNotifyAppReadyWait(final int[] phaseOut) {
1031
+ if (!this.pendingNotifyAppReadyWait) {
1032
+ return false;
1033
+ }
1034
+ phaseOut[0] = this.pendingNotifyAppReadyPhase;
1035
+ this.pendingNotifyAppReadyWait = false;
1036
+ this.pendingNotifyAppReadyPhase = -1;
1037
+ return true;
1038
+ }
1039
+
949
1040
  protected long getMinimumPendingBundleAppReadyTimeoutMs() {
950
1041
  return PENDING_BUNDLE_APP_READY_MIN_TIMEOUT_MS;
951
1042
  }
@@ -984,19 +1075,40 @@ public class CapacitorUpdaterPlugin extends Plugin {
984
1075
 
985
1076
  private void sendReadyToJs(final BundleInfo current, final String msg, final boolean isDirectUpdate) {
986
1077
  logger.info("sendReadyToJs: " + msg);
987
- final JSObject ret = new JSObject();
988
- ret.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
989
- ret.put("status", msg);
1078
+ final int[] pendingPhase = new int[] { -1 };
1079
+ final boolean shouldWait = this.consumePendingNotifyAppReadyWait(pendingPhase);
1080
+
1081
+ final Runnable emitReady = () -> {
1082
+ final JSObject ret = new JSObject();
1083
+ ret.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
1084
+ ret.put("status", msg);
990
1085
 
991
- // No need to wait for semaphore anymore since _reload() has already waited
992
- this.notifyListeners("appReady", ret, true);
1086
+ this.notifyListeners("appReady", ret, true);
993
1087
 
994
- // Auto hide splashscreen if enabled
995
- // We show it on background when conditions are met, so we should hide it on foreground regardless of update outcome
996
- if (this.autoSplashscreen) {
997
- this.hideSplashscreen();
1088
+ // Auto hide splashscreen if enabled
1089
+ // We show it on background when conditions are met, so we should hide it on foreground regardless of update outcome
1090
+ if (this.autoSplashscreen) {
1091
+ this.hideSplashscreen();
1092
+ }
1093
+ this.hidePreviewTransitionLoader("app-ready");
1094
+ };
1095
+
1096
+ if (!shouldWait) {
1097
+ emitReady.run();
1098
+ return;
998
1099
  }
999
- this.hidePreviewTransitionLoader("app-ready");
1100
+
1101
+ // Never block the UI thread waiting for notifyAppReady (JS needs it).
1102
+ if (Looper.myLooper() == Looper.getMainLooper()) {
1103
+ startNewThread(() -> {
1104
+ this.semaphoreWait(pendingPhase[0], this.appReadyTimeout);
1105
+ emitReady.run();
1106
+ });
1107
+ return;
1108
+ }
1109
+
1110
+ this.semaphoreWait(pendingPhase[0], this.appReadyTimeout);
1111
+ emitReady.run();
1000
1112
  }
1001
1113
 
1002
1114
  private void hideSplashscreen() {
@@ -1300,6 +1412,74 @@ public class CapacitorUpdaterPlugin extends Plugin {
1300
1412
  return false;
1301
1413
  }
1302
1414
 
1415
+ static boolean shouldClearPersistedDefaultChannel(
1416
+ final boolean persistDefaultChannelOnReinstall,
1417
+ final boolean resetWhenUpdate,
1418
+ final boolean nativeBuildVersionChanged,
1419
+ final boolean restoredReinstall
1420
+ ) {
1421
+ return !persistDefaultChannelOnReinstall && (restoredReinstall || (resetWhenUpdate && nativeBuildVersionChanged));
1422
+ }
1423
+
1424
+ static boolean clearPersistedDefaultChannel(final SharedPreferences.Editor editor) {
1425
+ editor.remove(DEFAULT_CHANNEL_PREF_KEY);
1426
+ editor.remove(PREVIEW_PREVIOUS_DEFAULT_CHANNEL_PREF_KEY);
1427
+ editor.remove(PREVIEW_PREVIOUS_DEFAULT_CHANNEL_WAS_SET_PREF_KEY);
1428
+ return editor.commit();
1429
+ }
1430
+
1431
+ private File defaultChannelInstallMarker() {
1432
+ return new File(this.getContext().getNoBackupFilesDir(), DEFAULT_CHANNEL_INSTALL_MARKER_FILE);
1433
+ }
1434
+
1435
+ static boolean invalidateDefaultChannelInstallMarker(final File marker) {
1436
+ return !marker.exists() || marker.delete();
1437
+ }
1438
+
1439
+ private boolean isRestoredReinstall() {
1440
+ return isRestoredReinstall(
1441
+ this.defaultChannelInstallMarker(),
1442
+ this.prefs.getBoolean(DEFAULT_CHANNEL_INSTALL_MARKER_PREF_KEY, false)
1443
+ );
1444
+ }
1445
+
1446
+ static boolean isRestoredReinstall(final File marker, final boolean markerWasCreated) {
1447
+ return markerWasCreated && !marker.exists();
1448
+ }
1449
+
1450
+ private void prepareDefaultChannelInstallMarker() {
1451
+ prepareDefaultChannelInstallMarker(
1452
+ this.defaultChannelInstallMarker(),
1453
+ this.prefs.getBoolean(DEFAULT_CHANNEL_INSTALL_MARKER_PREF_KEY, false),
1454
+ this.editor,
1455
+ this.logger
1456
+ );
1457
+ }
1458
+
1459
+ static void prepareDefaultChannelInstallMarker(
1460
+ final File marker,
1461
+ final boolean markerWasCreated,
1462
+ final SharedPreferences.Editor editor,
1463
+ final Logger logger
1464
+ ) {
1465
+ if (!marker.exists()) {
1466
+ try {
1467
+ if (!marker.createNewFile() && !marker.exists()) {
1468
+ throw new IOException("Marker file was not created");
1469
+ }
1470
+ } catch (final IOException e) {
1471
+ logger.warn("Cannot create default channel install marker: " + e.getMessage());
1472
+ editor.remove(DEFAULT_CHANNEL_INSTALL_MARKER_PREF_KEY);
1473
+ editor.commit();
1474
+ return;
1475
+ }
1476
+ }
1477
+ if (!markerWasCreated) {
1478
+ editor.putBoolean(DEFAULT_CHANNEL_INSTALL_MARKER_PREF_KEY, true);
1479
+ editor.apply();
1480
+ }
1481
+ }
1482
+
1303
1483
  private boolean hasNativeBuildVersionChanged() {
1304
1484
  final String lastKnownVersion = this.getStoredNativeBuildVersion();
1305
1485
  return !lastKnownVersion.isEmpty() && !lastKnownVersion.equals(this.currentBuildVersion);
@@ -1486,11 +1666,13 @@ public class CapacitorUpdaterPlugin extends Plugin {
1486
1666
  this.webViewStatsListener = new WebViewListener() {
1487
1667
  @Override
1488
1668
  public void onPageStarted(final android.webkit.WebView view) {
1669
+ CapacitorUpdaterPlugin.this.webViewPageStartedAtMs = System.currentTimeMillis();
1489
1670
  CapacitorUpdaterPlugin.this.evaluateWebViewStatsReporterScript(view, script);
1490
1671
  }
1491
1672
 
1492
1673
  @Override
1493
1674
  public void onPageLoaded(final android.webkit.WebView view) {
1675
+ CapacitorUpdaterPlugin.this.reportWebViewPageLoaded(view);
1494
1676
  CapacitorUpdaterPlugin.this.evaluateWebViewStatsReporterScript(view, script);
1495
1677
  }
1496
1678
  };
@@ -1556,6 +1738,83 @@ public class CapacitorUpdaterPlugin extends Plugin {
1556
1738
  });
1557
1739
  }
1558
1740
 
1741
+ private void reportAppLaunchStart() {
1742
+ if (
1743
+ this.implementation == null ||
1744
+ this.implementation.statsUrl == null ||
1745
+ this.implementation.statsUrl.isEmpty() ||
1746
+ this.launchStartReported
1747
+ ) {
1748
+ return;
1749
+ }
1750
+
1751
+ this.launchStartReported = true;
1752
+ final BundleInfo current = this.implementation.getCurrentBundle();
1753
+ final Map<String, String> metadata = new HashMap<>();
1754
+ metadata.put("launch_started_at", Long.toString(this.launchStartedAtMs));
1755
+ metadata.put("source", "plugin_load");
1756
+ this.implementation.sendStats("app_launch_start", current == null ? "" : current.getVersionName(), "", metadata);
1757
+ }
1758
+
1759
+ private void reportAppLaunchReady(final BundleInfo bundle) {
1760
+ synchronized (this.launchReportLock) {
1761
+ if (
1762
+ this.implementation == null ||
1763
+ this.implementation.statsUrl == null ||
1764
+ this.implementation.statsUrl.isEmpty() ||
1765
+ this.launchReadyReported ||
1766
+ this.launchTimeoutReported
1767
+ ) {
1768
+ return;
1769
+ }
1770
+ this.launchReadyReported = true;
1771
+ }
1772
+ final Map<String, String> metadata = new HashMap<>();
1773
+ metadata.put("duration_ms", Long.toString(Math.max(0, System.currentTimeMillis() - this.launchStartedAtMs)));
1774
+ metadata.put("launch_started_at", Long.toString(this.launchStartedAtMs));
1775
+ metadata.put("source", "notify_app_ready");
1776
+ this.implementation.sendStats("app_launch_ready", bundle == null ? "" : bundle.getVersionName(), "", metadata);
1777
+ }
1778
+
1779
+ private void reportAppLaunchTimeout(final BundleInfo bundle) {
1780
+ synchronized (this.launchReportLock) {
1781
+ if (
1782
+ this.implementation == null ||
1783
+ this.implementation.statsUrl == null ||
1784
+ this.implementation.statsUrl.isEmpty() ||
1785
+ this.launchReadyReported ||
1786
+ this.launchTimeoutReported
1787
+ ) {
1788
+ return;
1789
+ }
1790
+ this.launchTimeoutReported = true;
1791
+ }
1792
+ final Map<String, String> metadata = new HashMap<>();
1793
+ metadata.put("duration_ms", Long.toString(Math.max(0, System.currentTimeMillis() - this.launchStartedAtMs)));
1794
+ metadata.put("launch_started_at", Long.toString(this.launchStartedAtMs));
1795
+ metadata.put("timeout_ms", Long.toString(this.resolveAppReadyCheckTimeoutMs()));
1796
+ metadata.put("source", "app_ready_timeout");
1797
+ this.implementation.sendStats("app_launch_timeout", bundle == null ? "" : bundle.getVersionName(), "", metadata);
1798
+ }
1799
+
1800
+ private void reportWebViewPageLoaded(final android.webkit.WebView view) {
1801
+ if (this.implementation == null || this.implementation.statsUrl == null || this.implementation.statsUrl.isEmpty()) {
1802
+ return;
1803
+ }
1804
+
1805
+ final Map<String, String> metadata = new HashMap<>();
1806
+ metadata.put("source", "android_webview_listener");
1807
+ final long pageStartedAt = this.webViewPageStartedAtMs;
1808
+ if (pageStartedAt > 0) {
1809
+ metadata.put("duration_ms", Long.toString(Math.max(0, System.currentTimeMillis() - pageStartedAt)));
1810
+ metadata.put("page_started_at", Long.toString(pageStartedAt));
1811
+ }
1812
+ if (view != null && view.getUrl() != null && !view.getUrl().isEmpty()) {
1813
+ metadata.put("href", truncateStatsMetadataValue(sanitizeStatsMetadataUrl(view.getUrl()), 512));
1814
+ }
1815
+ this.reportWebViewStats("webview_page_loaded", metadata);
1816
+ }
1817
+
1559
1818
  private Map<String, String> buildWebViewRenderProcessGoneMetadata(final Object detailObj) {
1560
1819
  final Map<String, String> metadata = new HashMap<>();
1561
1820
  metadata.put("error_type", "render_process_gone");
@@ -1664,6 +1923,10 @@ public class CapacitorUpdaterPlugin extends Plugin {
1664
1923
  return "webview_render_process_gone";
1665
1924
  case "web_content_process_terminated":
1666
1925
  return "webview_content_process_terminated";
1926
+ case "webview_dom_content_loaded":
1927
+ return "webview_dom_content_loaded";
1928
+ case "webview_page_loaded":
1929
+ return "webview_page_loaded";
1667
1930
  case "javascript_error":
1668
1931
  default:
1669
1932
  return "webview_javascript_error";
@@ -1682,6 +1945,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
1682
1945
  putStatsMetadataValue(metadata, "href", sanitizeStatsMetadataUrl(data.optString("href", "")), 512);
1683
1946
  putStatsMetadataValue(metadata, "user_agent", data.optString("user_agent", ""), 256);
1684
1947
  putStatsMetadataValue(metadata, "session_id", data.optString("session_id", ""), 128);
1948
+ putStatsMetadataValue(metadata, "duration_ms", data.optString("duration_ms", ""), 32);
1949
+ putStatsMetadataValue(metadata, "page_started_at", data.optString("page_started_at", ""), 64);
1685
1950
  putStatsMetadataValue(metadata, "previous_session_id", data.optString("previous_session_id", ""), 128);
1686
1951
  putStatsMetadataValue(metadata, "previous_href", sanitizeStatsMetadataUrl(data.optString("previous_href", "")), 512);
1687
1952
  putStatsMetadataValue(metadata, "previous_started_at", data.optString("previous_started_at", ""), 64);
@@ -1814,12 +2079,14 @@ public class CapacitorUpdaterPlugin extends Plugin {
1814
2079
  "if(previous&&previous.active){send({type:'webview_unclean_restart',message:'WebView restarted without a clean page unload',previous_session_id:s(previous.id),previous_href:s(previous.href),previous_started_at:s(previous.started_at),previous_updated_at:s(previous.updated_at)});}" +
1815
2080
  "writeSession(true);" +
1816
2081
  "setInterval(function(){writeSession(true);},15000);" +
2082
+ "function pageDuration(){var started=Number(window.__capgoWebViewSessionStartedAt||Date.now());return String(Math.max(0,Date.now()-started));}" +
1817
2083
  "function markClean(){writeSession(false);}" +
1818
2084
  "window.addEventListener('pagehide',markClean,true);" +
1819
2085
  "window.addEventListener('beforeunload',markClean,true);" +
1820
2086
  "window.addEventListener('error',function(event){var target=event&&event.target;if(target&&target!==window&&(target.src||target.href)){send({type:'resource_error',message:'Resource failed to load',source:s(target.src||target.href),tag_name:s(target.tagName)});return;}send({type:'javascript_error',message:s((event&&event.message)||(event&&event.error)),source:s(event&&event.filename),line:s(event&&event.lineno),column:s(event&&event.colno),stack:stack(event&&event.error)});},true);" +
1821
2087
  "window.addEventListener('unhandledrejection',function(event){var reason=event&&event.reason;send({type:'unhandled_rejection',message:s(reason),stack:stack(reason)});},true);" +
1822
2088
  "document.addEventListener('securitypolicyviolation',function(event){send({type:'security_policy_violation',message:s(event&&event.violatedDirective),source:s(event&&event.blockedURI)});},true);" +
2089
+ "document.addEventListener('DOMContentLoaded',function(){send({type:'webview_dom_content_loaded',message:'WebView DOM content loaded',duration_ms:pageDuration(),page_started_at:String(window.__capgoWebViewSessionStartedAt)});},true);" +
1823
2090
  "document.addEventListener('deviceready',scheduleFlush,false);" +
1824
2091
  "setTimeout(scheduleFlush,0);" +
1825
2092
  "})();"
@@ -1872,10 +2139,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
1872
2139
  );
1873
2140
  }
1874
2141
  } else {
1875
- final boolean enabled =
1876
- configuredMode != null
1877
- ? "true".equals(configuredMode)
1878
- : Boolean.TRUE.equals(this.getConfig().getBoolean("autoUpdate", true));
2142
+ final boolean enabled = configuredMode != null
2143
+ ? "true".equals(configuredMode)
2144
+ : Boolean.TRUE.equals(this.getConfig().getBoolean("autoUpdate", true));
1879
2145
  this.autoUpdateMode = enabled
1880
2146
  ? autoUpdateModeForLegacyDirectUpdateMode(this.resolveLegacyDirectUpdateModeFromConfig())
1881
2147
  : AUTO_UPDATE_MODE_OFF;
@@ -2140,67 +2406,57 @@ public class CapacitorUpdaterPlugin extends Plugin {
2140
2406
  return false;
2141
2407
  }
2142
2408
 
2143
- private void cleanupObsoleteVersions() {
2409
+ private void cleanupObsoleteVersions(final boolean resetWhenUpdate) {
2410
+ // Latch created before start so waiters never race past an unstarted cleanup thread.
2411
+ final CountDownLatch latch = new CountDownLatch(1);
2412
+ this.cleanupComplete = false;
2413
+ this.cleanupLatch = latch;
2144
2414
  cleanupThread = startNewThread(() -> {
2145
- synchronized (cleanupLock) {
2146
- try {
2147
- final String previous = this.getStoredNativeBuildVersion();
2148
- if (!"".equals(previous) && !Objects.equals(this.currentBuildVersion, previous)) {
2149
- logger.info("New native build version detected: " + this.currentBuildVersion);
2150
- this.implementation.reset(true);
2151
- final List<BundleInfo> installed = this.implementation.list(false);
2152
- for (final BundleInfo bundle : installed) {
2153
- // Check if thread was interrupted (cancelled)
2154
- if (Thread.currentThread().isInterrupted()) {
2155
- logger.warn("Cleanup was cancelled, stopping");
2156
- return;
2157
- }
2158
- try {
2159
- logger.info("Deleting obsolete bundle: " + bundle.getId());
2160
- this.implementation.delete(bundle.getId());
2161
- } catch (final Exception e) {
2162
- logger.error("Failed to delete: " + bundle.getId() + " " + e.getMessage());
2163
- }
2164
- }
2165
- final List<BundleInfo> storedBundles = this.implementation.list(true);
2166
- final Set<String> allowedIds = new HashSet<>();
2167
- for (final BundleInfo info : storedBundles) {
2168
- if (info != null && info.getId() != null && !info.getId().isEmpty()) {
2169
- allowedIds.add(info.getId());
2415
+ try {
2416
+ synchronized (cleanupLock) {
2417
+ try {
2418
+ final String previous = this.getStoredNativeBuildVersion();
2419
+ final boolean nativeVersionChanged = !"".equals(previous) && !Objects.equals(this.currentBuildVersion, previous);
2420
+ if (resetWhenUpdate && nativeVersionChanged) {
2421
+ logger.info("New native build version detected: " + this.currentBuildVersion);
2422
+ this.implementation.reset(true);
2423
+ final List<BundleInfo> installed = this.implementation.list(false);
2424
+ for (final BundleInfo bundle : installed) {
2425
+ try {
2426
+ logger.info("Deleting obsolete bundle: " + bundle.getId());
2427
+ this.implementation.delete(bundle.getId());
2428
+ } catch (final Exception e) {
2429
+ logger.error("Failed to delete: " + bundle.getId() + " " + e.getMessage());
2430
+ }
2431
+ try {
2432
+ Thread.sleep(75L);
2433
+ } catch (final InterruptedException ie) {
2434
+ Thread.currentThread().interrupt();
2435
+ return;
2436
+ }
2170
2437
  }
2438
+ this.implementation.cleanupDeltaCache();
2171
2439
  }
2172
- this.implementation.cleanupDownloadDirectories(allowedIds, Thread.currentThread());
2173
- this.implementation.cleanupOrphanedTempFolders(Thread.currentThread());
2174
2440
 
2175
- // Check again before the expensive delta cache cleanup
2176
- if (Thread.currentThread().isInterrupted()) {
2177
- logger.warn("Cleanup was cancelled before delta cache cleanup");
2178
- return;
2179
- }
2180
- this.implementation.cleanupDeltaCache(Thread.currentThread());
2181
- }
2182
- this.editor.putString("LatestNativeBuildVersion", this.currentBuildVersion);
2183
- this.editor.apply();
2184
- } catch (Exception e) {
2185
- logger.error("Error during cleanupObsoleteVersions: " + e.getMessage());
2186
- } finally {
2187
- cleanupComplete = true;
2188
- logger.info("Cleanup complete");
2189
- }
2190
- }
2191
- });
2441
+ // Resume any DELETING leftovers from prior kills, one-by-one.
2442
+ this.implementation.drainPendingDeletes();
2192
2443
 
2193
- // Start a timeout watchdog thread to cancel cleanup if it takes too long
2194
- final long timeout = this.appReadyTimeout / 2;
2195
- startNewThread(() -> {
2196
- try {
2197
- Thread.sleep(timeout);
2198
- if (cleanupThread != null && cleanupThread.isAlive() && !cleanupComplete) {
2199
- logger.warn("Cleanup timeout exceeded (" + timeout + "ms), interrupting cleanup thread");
2200
- cleanupThread.interrupt();
2444
+ // Always sweep orphan folders so incomplete prior cleanups (or failed deletes)
2445
+ // cannot leave hundreds of MB behind across launches.
2446
+ final Set<String> allowedIds = this.implementation.allowedBundleIdsForCleanup();
2447
+ this.implementation.cleanupDownloadDirectories(allowedIds);
2448
+ this.implementation.cleanupOrphanedTempFolders(null);
2449
+
2450
+ this.persistCurrentNativeBuildVersion();
2451
+ } catch (Exception e) {
2452
+ logger.error("Error during cleanupObsoleteVersions: " + e.getMessage());
2453
+ } finally {
2454
+ cleanupComplete = true;
2455
+ logger.info("Cleanup complete");
2456
+ }
2201
2457
  }
2202
- } catch (InterruptedException e) {
2203
- // Watchdog thread was interrupted, that's fine
2458
+ } finally {
2459
+ latch.countDown();
2204
2460
  }
2205
2461
  });
2206
2462
  }
@@ -2214,6 +2470,10 @@ public class CapacitorUpdaterPlugin extends Plugin {
2214
2470
  }
2215
2471
 
2216
2472
  void persistCurrentNativeBuildVersion() {
2473
+ if (this.defaultChannelCleanupMustRetry) {
2474
+ logger.warn("Keeping the previous native build version so default channel cleanup retries");
2475
+ return;
2476
+ }
2217
2477
  this.editor.putString("LatestNativeBuildVersion", this.currentBuildVersion);
2218
2478
  this.editor.apply();
2219
2479
  }
@@ -2224,11 +2484,14 @@ public class CapacitorUpdaterPlugin extends Plugin {
2224
2484
  }
2225
2485
 
2226
2486
  logger.info("Waiting for cleanup to complete before starting download...");
2227
-
2228
- // Wait for cleanup to complete - blocks until lock is released
2229
- synchronized (cleanupLock) {
2230
- logger.info("Cleanup finished, proceeding with download");
2487
+ try {
2488
+ this.cleanupLatch.await();
2489
+ } catch (final InterruptedException e) {
2490
+ Thread.currentThread().interrupt();
2491
+ logger.warn("Interrupted while waiting for cleanup");
2492
+ throw new IllegalStateException("Interrupted while waiting for cleanup");
2231
2493
  }
2494
+ logger.info("Cleanup finished, proceeding with download");
2232
2495
  }
2233
2496
 
2234
2497
  public void notifyDownload(final String id, final int percent) {
@@ -2269,11 +2532,15 @@ public class CapacitorUpdaterPlugin extends Plugin {
2269
2532
  call.reject("setUpdateUrl called without url");
2270
2533
  return;
2271
2534
  }
2272
- this.updateUrl = url;
2273
2535
  if (Boolean.TRUE.equals(this.persistModifyUrl)) {
2274
2536
  this.editor.putString(UPDATE_URL_PREF_KEY, url);
2275
- this.editor.apply();
2537
+ if (!this.editor.commit()) {
2538
+ logger.error("Failed to persist updateUrl");
2539
+ call.reject("Failed to persist updateUrl");
2540
+ return;
2541
+ }
2276
2542
  }
2543
+ this.updateUrl = url;
2277
2544
  call.resolve();
2278
2545
  }
2279
2546
 
@@ -2290,11 +2557,15 @@ public class CapacitorUpdaterPlugin extends Plugin {
2290
2557
  call.reject("setStatsUrl called without url");
2291
2558
  return;
2292
2559
  }
2293
- this.implementation.statsUrl = url;
2294
2560
  if (Boolean.TRUE.equals(this.persistModifyUrl)) {
2295
2561
  this.editor.putString(STATS_URL_PREF_KEY, url);
2296
- this.editor.apply();
2562
+ if (!this.editor.commit()) {
2563
+ logger.error("Failed to persist statsUrl");
2564
+ call.reject("Failed to persist statsUrl");
2565
+ return;
2566
+ }
2297
2567
  }
2568
+ this.implementation.statsUrl = url;
2298
2569
  call.resolve();
2299
2570
  }
2300
2571
 
@@ -2311,11 +2582,15 @@ public class CapacitorUpdaterPlugin extends Plugin {
2311
2582
  call.reject("setChannelUrl called without url");
2312
2583
  return;
2313
2584
  }
2314
- this.implementation.channelUrl = url;
2315
2585
  if (Boolean.TRUE.equals(this.persistModifyUrl)) {
2316
2586
  this.editor.putString(CHANNEL_URL_PREF_KEY, url);
2317
- this.editor.apply();
2587
+ if (!this.editor.commit()) {
2588
+ logger.error("Failed to persist channelUrl");
2589
+ call.reject("Failed to persist channelUrl");
2590
+ return;
2591
+ }
2318
2592
  }
2593
+ this.implementation.channelUrl = url;
2319
2594
  call.resolve();
2320
2595
  }
2321
2596
 
@@ -2566,6 +2841,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
2566
2841
  final String checksum,
2567
2842
  final JSONArray manifest
2568
2843
  ) throws IOException {
2844
+ // Manual/preview downloads must wait too — launch orphan sweep can delete their temps.
2845
+ waitForCleanupIfNeeded();
2569
2846
  if (manifest != null) {
2570
2847
  return this.implementation.downloadManifest(url, version, sessionKey, checksum, manifest);
2571
2848
  }
@@ -2739,6 +3016,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
2739
3016
  }
2740
3017
 
2741
3018
  protected boolean _reload() {
3019
+ // Drop any launch pending wait; this reload owns notifyAppReady synchronization.
3020
+ this.clearPendingNotifyAppReadyWait();
2742
3021
  final int phase = this.semaphoreUp();
2743
3022
  this.applyCurrentBundleToBridge();
2744
3023
 
@@ -3734,30 +4013,33 @@ public class CapacitorUpdaterPlugin extends Plugin {
3734
4013
  this.editor.putBoolean(PREVIEW_SESSION_ALERT_PENDING_PREF_KEY, false);
3735
4014
  this.editor.apply();
3736
4015
 
3737
- new Handler(Looper.getMainLooper()).postDelayed(() -> {
3738
- try {
3739
- if (!Boolean.TRUE.equals(this.previewSessionEnabled)) {
3740
- return;
3741
- }
3742
- if (getActivity() == null || getActivity().isFinishing()) {
4016
+ new Handler(Looper.getMainLooper()).postDelayed(
4017
+ () -> {
4018
+ try {
4019
+ if (!Boolean.TRUE.equals(this.previewSessionEnabled)) {
4020
+ return;
4021
+ }
4022
+ if (getActivity() == null || getActivity().isFinishing()) {
4023
+ this.previewSessionAlertPending = true;
4024
+ this.editor.putBoolean(PREVIEW_SESSION_ALERT_PENDING_PREF_KEY, true);
4025
+ this.editor.apply();
4026
+ return;
4027
+ }
4028
+
4029
+ new AlertDialog.Builder(getActivity())
4030
+ .setTitle("Preview started")
4031
+ .setMessage("shake".equals(this.shakeMenuGesture) ? "Shake to open menu." : "Three-finger pinch to open menu.")
4032
+ .setPositiveButton("Got it", (dialog, which) -> dialog.dismiss())
4033
+ .show();
4034
+ } catch (final Exception e) {
3743
4035
  this.previewSessionAlertPending = true;
3744
4036
  this.editor.putBoolean(PREVIEW_SESSION_ALERT_PENDING_PREF_KEY, true);
3745
4037
  this.editor.apply();
3746
- return;
4038
+ logger.warn("Could not show preview session notice: " + e.getMessage());
3747
4039
  }
3748
-
3749
- new AlertDialog.Builder(getActivity())
3750
- .setTitle("Preview started")
3751
- .setMessage("Shake your device anytime to reload or leave the test app.")
3752
- .setPositiveButton("Got it", (dialog, which) -> dialog.dismiss())
3753
- .show();
3754
- } catch (final Exception e) {
3755
- this.previewSessionAlertPending = true;
3756
- this.editor.putBoolean(PREVIEW_SESSION_ALERT_PENDING_PREF_KEY, true);
3757
- this.editor.apply();
3758
- logger.warn("Could not show preview session notice: " + e.getMessage());
3759
- }
3760
- }, 600);
4040
+ },
4041
+ 600
4042
+ );
3761
4043
  }
3762
4044
 
3763
4045
  @PluginMethod
@@ -3966,12 +4248,18 @@ public class CapacitorUpdaterPlugin extends Plugin {
3966
4248
  if (this.shouldBlockAutoUpdateForPreviewSession()) {
3967
4249
  return "preview_session";
3968
4250
  }
3969
- if (this.isDownloadStuckOrTimedOut()) {
3970
- logger.info("Download already in progress, skipping duplicate download request");
3971
- return "already_running";
4251
+ synchronized (this) {
4252
+ final Thread previousTask = this.backgroundDownloadTask;
4253
+ final Thread task = this.backgroundDownload();
4254
+ if (task == null) {
4255
+ return "unavailable";
4256
+ }
4257
+ if (previousTask != null && previousTask == task) {
4258
+ logger.info("Download already in progress, skipping duplicate download request");
4259
+ return "already_running";
4260
+ }
4261
+ return "queued";
3972
4262
  }
3973
- this.backgroundDownload();
3974
- return "queued";
3975
4263
  }
3976
4264
 
3977
4265
  @PluginMethod
@@ -4199,6 +4487,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4199
4487
  try {
4200
4488
  final BundleInfo bundle = this.implementation.getCurrentBundle();
4201
4489
  this.implementation.setSuccess(bundle, this.autoDeletePrevious);
4490
+ this.reportAppLaunchReady(bundle);
4202
4491
  logger.info("Current bundle loaded successfully. ['notifyAppReady()' was called] " + bundle);
4203
4492
  logger.info("semaphoreReady countDown");
4204
4493
  this.semaphoreDown();
@@ -4483,10 +4772,14 @@ public class CapacitorUpdaterPlugin extends Plugin {
4483
4772
  return true;
4484
4773
  }
4485
4774
 
4486
- private Thread backgroundDownload() {
4775
+ private synchronized Thread backgroundDownload() {
4487
4776
  if (this.shouldBlockAutoUpdateForPreviewSession()) {
4488
4777
  return null;
4489
4778
  }
4779
+ if (this.isDownloadStuckOrTimedOut()) {
4780
+ logger.info("Download already in progress, skipping duplicate download request");
4781
+ return this.backgroundDownloadTask;
4782
+ }
4490
4783
  final boolean plannedDirectUpdate = this.shouldUseDirectUpdate();
4491
4784
  final boolean initialDirectUpdateAllowed = this.isDirectUpdateCurrentlyAllowed(plannedDirectUpdate);
4492
4785
  final String messageUpdate = initialDirectUpdateAllowed
@@ -4495,8 +4788,6 @@ public class CapacitorUpdaterPlugin extends Plugin {
4495
4788
  ? "Update will occur next time app moves to background."
4496
4789
  : "Update will be downloaded and made available.";
4497
4790
  Thread newTask = startNewThread(() -> {
4498
- // Wait for cleanup to complete before starting download
4499
- waitForCleanupIfNeeded();
4500
4791
  if (CapacitorUpdaterPlugin.this.shouldBlockAutoUpdateForPreviewSession()) {
4501
4792
  CapacitorUpdaterPlugin.this.clearBackgroundDownloadState();
4502
4793
  return;
@@ -4509,7 +4800,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4509
4800
  return;
4510
4801
  }
4511
4802
  JSObject jsRes = InternalUtils.mapToJSObject(res);
4512
- final BundleInfo current = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
4803
+ final BundleInfo currentBeforeCleanup = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
4513
4804
 
4514
4805
  // Handle network errors and other failures first
4515
4806
  if (jsRes.has("error") || jsRes.has("kind")) {
@@ -4517,8 +4808,15 @@ public class CapacitorUpdaterPlugin extends Plugin {
4517
4808
  String errorMessage = jsRes.has("message") ? jsRes.getString("message") : "server did not provide a message";
4518
4809
  int statusCode = jsRes.has("statusCode") ? jsRes.optInt("statusCode", 0) : 0;
4519
4810
  String kind = CapacitorUpdaterPlugin.this.getUpdateResponseKind(jsRes.has("kind") ? jsRes.getString("kind") : null);
4520
- String latestVersion = jsRes.has("version") ? jsRes.getString("version") : current.getVersionName();
4521
- CapacitorUpdaterPlugin.this.notifyUpdateCheckResult(kind, error, errorMessage, statusCode, latestVersion, current);
4811
+ String latestVersion = jsRes.has("version") ? jsRes.getString("version") : currentBeforeCleanup.getVersionName();
4812
+ CapacitorUpdaterPlugin.this.notifyUpdateCheckResult(
4813
+ kind,
4814
+ error,
4815
+ errorMessage,
4816
+ statusCode,
4817
+ latestVersion,
4818
+ currentBeforeCleanup
4819
+ );
4522
4820
  CapacitorUpdaterPlugin.this.notifyBreakingEventsIfNeeded(
4523
4821
  jsRes,
4524
4822
  jsRes.has("version") ? jsRes.getString("version") : ""
@@ -4538,7 +4836,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4538
4836
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
4539
4837
  errorMessage,
4540
4838
  latestVersion,
4541
- current,
4839
+ currentBeforeCleanup,
4542
4840
  isFailure,
4543
4841
  plannedDirectUpdate,
4544
4842
  "download_fail",
@@ -4548,6 +4846,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
4548
4846
  return;
4549
4847
  }
4550
4848
  try {
4849
+ // File mutations wait here. getLatest already ran in parallel with cleanup.
4850
+ waitForCleanupIfNeeded();
4851
+ final BundleInfo current = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
4551
4852
  final String latestVersionName = jsRes.getString("version");
4552
4853
 
4553
4854
  if ("builtin".equals(latestVersionName)) {
@@ -4796,8 +5097,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
4796
5097
  logger.error("error in update check " + e.getMessage());
4797
5098
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
4798
5099
  "Error in update check",
4799
- current.getVersionName(),
4800
- current,
5100
+ currentBeforeCleanup.getVersionName(),
5101
+ currentBeforeCleanup,
4801
5102
  true,
4802
5103
  plannedDirectUpdate
4803
5104
  );
@@ -4873,19 +5174,26 @@ public class CapacitorUpdaterPlugin extends Plugin {
4873
5174
  ret.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
4874
5175
  this.persistLastFailedBundle(current);
4875
5176
  this.notifyListeners("updateFailed", ret);
5177
+ this.reportAppLaunchTimeout(current);
4876
5178
  this.implementation.sendStats("update_fail", current.getVersionName());
4877
5179
  this.implementation.setError(current);
4878
5180
  this.performReset(true, false, true);
4879
5181
  if (CapacitorUpdaterPlugin.this.autoDeleteFailed && !current.isBuiltin()) {
4880
- logger.info("Deleting failing bundle: " + current.getVersionName());
4881
- try {
4882
- final Boolean res = this.implementation.delete(current.getId(), false);
4883
- if (res) {
4884
- logger.info("Failed bundle deleted: " + current.getVersionName());
5182
+ final String failedId = current.getId();
5183
+ final String failedVersion = current.getVersionName();
5184
+ logger.info("Deleting failing bundle: " + failedVersion);
5185
+ // Mark before async work so kill/OOM still resumes via drainPendingDeletes.
5186
+ CapacitorUpdaterPlugin.this.implementation.saveBundleInfo(failedId, current.setStatus(BundleStatus.DELETING));
5187
+ startNewThread(() -> {
5188
+ try {
5189
+ final Boolean res = CapacitorUpdaterPlugin.this.implementation.delete(failedId, false, false);
5190
+ if (Boolean.TRUE.equals(res)) {
5191
+ logger.info("Failed bundle deleted: " + failedVersion);
5192
+ }
5193
+ } catch (final IOException e) {
5194
+ logger.error("Failed to delete failed bundle: " + failedVersion + " " + e.getMessage());
4885
5195
  }
4886
- } catch (final IOException e) {
4887
- logger.error("Failed to delete failed bundle: " + current.getVersionName() + " " + e.getMessage());
4888
- }
5196
+ });
4889
5197
  }
4890
5198
  } else {
4891
5199
  logger.info("notifyAppReady was called. This is fine: " + current.getId());
@@ -5000,6 +5308,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5000
5308
 
5001
5309
  // Do other background work after splashscreen is shown
5002
5310
  CapacitorUpdaterPlugin.this.implementation.sendStats("app_moved_to_background", current.getVersionName());
5311
+ CapacitorUpdaterPlugin.this.implementation.persistPendingStats();
5003
5312
  logger.info("Checking for pending update");
5004
5313
 
5005
5314
  try {
@@ -5075,9 +5384,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
5075
5384
 
5076
5385
  // On Android < 14, use activity lifecycle for foreground detection
5077
5386
  // On Android 14+, ProcessLifecycleOwner handles this via AppLifecycleObserver
5078
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
5079
- if (isPreviousMainActivity) {
5080
- logger.info("handleOnStart: appMovedToForeground (Android <14 path)");
5387
+ if (!this.isProcessLifecycleObserverActive()) {
5388
+ if (isPreviousMainActivity || Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
5389
+ logger.info("handleOnStart: appMovedToForeground");
5081
5390
  this.appMovedToForeground();
5082
5391
  }
5083
5392
  isPreviousMainActivity = true;
@@ -5096,11 +5405,16 @@ public class CapacitorUpdaterPlugin extends Plugin {
5096
5405
 
5097
5406
  // On Android < 14, use activity lifecycle for background detection
5098
5407
  // On Android 14+, ProcessLifecycleOwner handles this via AppLifecycleObserver
5099
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
5100
- isPreviousMainActivity = isMainActivity();
5101
- if (isPreviousMainActivity) {
5102
- logger.info("handleOnStop: appMovedToBackground (Android <14 path)");
5408
+ if (!this.isProcessLifecycleObserverActive()) {
5409
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
5410
+ logger.info("handleOnStop: appMovedToBackground");
5103
5411
  this.appMovedToBackground();
5412
+ } else {
5413
+ isPreviousMainActivity = isMainActivity();
5414
+ if (isPreviousMainActivity) {
5415
+ logger.info("handleOnStop: appMovedToBackground (Android <14 path)");
5416
+ this.appMovedToBackground();
5417
+ }
5104
5418
  }
5105
5419
  }
5106
5420
  } catch (Exception e) {
@@ -5368,8 +5682,13 @@ public class CapacitorUpdaterPlugin extends Plugin {
5368
5682
  return;
5369
5683
  }
5370
5684
 
5371
- // Save the call for later resolution
5372
- bridge.saveCall(call);
5685
+ if (pendingAppUpdateCall != null) {
5686
+ call.reject("An app update flow is already in progress");
5687
+ return;
5688
+ }
5689
+
5690
+ call.setKeepAlive(true);
5691
+ pendingAppUpdateCall = call;
5373
5692
 
5374
5693
  AppUpdateManager manager = getAppUpdateManager();
5375
5694
  manager.startUpdateFlowForResult(
@@ -5441,8 +5760,13 @@ public class CapacitorUpdaterPlugin extends Plugin {
5441
5760
 
5442
5761
  manager.registerListener(installStateUpdatedListener);
5443
5762
 
5444
- // Save the call for later resolution
5445
- bridge.saveCall(call);
5763
+ if (pendingAppUpdateCall != null) {
5764
+ call.reject("An app update flow is already in progress");
5765
+ return;
5766
+ }
5767
+
5768
+ call.setKeepAlive(true);
5769
+ pendingAppUpdateCall = call;
5446
5770
 
5447
5771
  manager.startUpdateFlowForResult(
5448
5772
  cachedAppUpdateInfo,
@@ -5483,11 +5807,11 @@ public class CapacitorUpdaterPlugin extends Plugin {
5483
5807
  super.handleOnActivityResult(requestCode, resultCode, data);
5484
5808
 
5485
5809
  if (requestCode == APP_UPDATE_REQUEST_CODE) {
5486
- PluginCall savedCall = bridge.getSavedCall("com.getcapacitor.PluginCall");
5810
+ PluginCall savedCall = pendingAppUpdateCall;
5487
5811
  if (savedCall == null) {
5488
- // Try to get any saved call (for backward compatibility)
5489
5812
  return;
5490
5813
  }
5814
+ pendingAppUpdateCall = null;
5491
5815
 
5492
5816
  JSObject result = new JSObject();
5493
5817
  if (resultCode == Activity.RESULT_OK) {
@@ -5497,8 +5821,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
5497
5821
  } else {
5498
5822
  result.put("code", RESULT_FAILED);
5499
5823
  }
5824
+ savedCall.setKeepAlive(false);
5500
5825
  savedCall.resolve(result);
5501
- bridge.releaseCall(savedCall);
5502
5826
  }
5503
5827
  }
5504
5828