@capgo/capacitor-updater 7.50.2 → 7.51.16

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 (32) hide show
  1. package/CapgoCapacitorUpdater.podspec +0 -2
  2. package/Package.swift +4 -5
  3. package/README.md +53 -48
  4. package/android/build.gradle +6 -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 +427 -116
  9. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +1108 -182
  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 +513 -201
  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 +115 -133
  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 +806 -92
  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/RSA.swift +73 -251
  29. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +44 -20
  30. package/ios/Sources/CapacitorUpdaterPlugin/WebViewStatsReporter.swift +28 -0
  31. package/package.json +13 -8
  32. 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 = "7.50.1";
149
+ private final String pluginVersion = "7.51.16";
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,6 +284,10 @@ 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;
273
293
  private AppUpdateInfo cachedAppUpdateInfo;
@@ -747,6 +767,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
747
767
 
748
768
  this.persistCustomId = this.getConfig().getBoolean("persistCustomId", false);
749
769
  this.persistModifyUrl = this.getConfig().getBoolean("persistModifyUrl", false);
770
+ this.persistDefaultChannelOnReinstall = this.getConfig().getBoolean("persistDefaultChannelOnReinstall", true);
750
771
  this.allowSetDefaultChannel = this.getConfig().getBoolean("allowSetDefaultChannel", true);
751
772
  this.implementation.setPublicKey(this.getConfig().getString("publicKey", ""));
752
773
  // Log public key prefix if encryption is enabled
@@ -773,6 +794,35 @@ public class CapacitorUpdaterPlugin extends Plugin {
773
794
  }
774
795
  }
775
796
 
797
+ final boolean resetWhenUpdate = this.getConfig().getBoolean("resetWhenUpdate", true);
798
+ final boolean nativeBuildVersionChanged = this.hasNativeBuildVersionChanged();
799
+ final boolean defaultChannelPersistenceDisabled = !Boolean.TRUE.equals(this.persistDefaultChannelOnReinstall);
800
+ final boolean restoredReinstall = defaultChannelPersistenceDisabled && this.isRestoredReinstall();
801
+ boolean installMarkerCanBePrepared = true;
802
+ if (
803
+ shouldClearPersistedDefaultChannel(
804
+ Boolean.TRUE.equals(this.persistDefaultChannelOnReinstall),
805
+ resetWhenUpdate,
806
+ nativeBuildVersionChanged,
807
+ restoredReinstall
808
+ )
809
+ ) {
810
+ installMarkerCanBePrepared = clearPersistedDefaultChannel(this.editor);
811
+ if (installMarkerCanBePrepared) {
812
+ logger.info("Cleared persisted defaultChannel because reinstall persistence is disabled");
813
+ } else {
814
+ logger.warn("Cannot durably clear persisted defaultChannel");
815
+ this.defaultChannelCleanupMustRetry = true;
816
+ if (!invalidateDefaultChannelInstallMarker(this.defaultChannelInstallMarker())) {
817
+ logger.warn("Cannot invalidate default channel install marker for cleanup retry");
818
+ }
819
+ }
820
+ }
821
+ if (defaultChannelPersistenceDisabled && installMarkerCanBePrepared) {
822
+ this.prepareDefaultChannelInstallMarker();
823
+ }
824
+
825
+ final String configDefaultChannel = this.getConfig().getString("defaultChannel", "");
776
826
  // Load defaultChannel: first try from persistent storage (set via setChannel), then fall back to config
777
827
  if (this.prefs.contains(DEFAULT_CHANNEL_PREF_KEY)) {
778
828
  final String storedDefaultChannel = this.prefs.getString(DEFAULT_CHANNEL_PREF_KEY, "");
@@ -780,20 +830,22 @@ public class CapacitorUpdaterPlugin extends Plugin {
780
830
  this.implementation.defaultChannel = storedDefaultChannel;
781
831
  logger.info("Loaded persisted defaultChannel from setChannel()");
782
832
  } else {
783
- this.implementation.defaultChannel = this.getConfig().getString("defaultChannel", "");
833
+ this.implementation.defaultChannel = configDefaultChannel;
784
834
  }
785
835
  } else {
786
- this.implementation.defaultChannel = this.getConfig().getString("defaultChannel", "");
836
+ this.implementation.defaultChannel = configDefaultChannel;
787
837
  }
788
838
 
789
839
  this.periodCheckDelay = normalizedPeriodCheckDelayMs(this.getConfig().getInt("periodCheckDelay", 0));
790
840
 
791
841
  this.implementation.documentsDir = this.getContext().getFilesDir();
842
+ this.implementation.noBackupDir = this.getContext().getNoBackupFilesDir();
792
843
  this.implementation.prefs = this.prefs;
793
844
  this.implementation.editor = this.editor;
794
845
  this.implementation.versionOs = Build.VERSION.RELEASE;
795
846
  // Use DeviceIdHelper to get or create device ID that persists across reinstalls
796
847
  this.implementation.deviceID = DeviceIdHelper.getOrCreateDeviceId(this.getContext(), this.prefs);
848
+ this.implementation.restorePendingStats();
797
849
 
798
850
  // Update User-Agent for shared OkHttpClient with OS version
799
851
  DownloadService.updateUserAgent(this.implementation.appId, this.pluginVersion, this.implementation.versionOs);
@@ -807,6 +859,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
807
859
  }
808
860
  logger.info("init for device " + this.implementation.deviceID);
809
861
  logger.info("version native " + this.currentVersionNative.getOriginalString());
862
+ this.reportAppLaunchStart();
810
863
  this.autoDeleteFailed = this.getConfig().getBoolean("autoDeleteFailed", true);
811
864
  this.autoDeletePrevious = this.getConfig().getBoolean("autoDeletePrevious", true);
812
865
  this.updateUrl = this.getConfig().getString("updateUrl", updateUrlDefault);
@@ -828,7 +881,10 @@ public class CapacitorUpdaterPlugin extends Plugin {
828
881
  this.autoSplashscreenLoader = this.getConfig().getBoolean("autoSplashscreenLoader", false);
829
882
  int splashscreenTimeoutValue = this.getConfig().getInt("autoSplashscreenTimeout", 10000);
830
883
  this.autoSplashscreenTimeout = Math.max(0, splashscreenTimeoutValue);
831
- this.implementation.timeout = this.getConfig().getInt("responseTimeout", 20) * 1000;
884
+ int responseTimeoutSeconds = this.getConfig().getInt("responseTimeout", 20);
885
+ long responseTimeoutMillis = responseTimeoutSeconds > 0 ? (long) responseTimeoutSeconds * 1000L : 20_000L;
886
+ this.implementation.timeout = (int) Math.min(Integer.MAX_VALUE, responseTimeoutMillis);
887
+ DownloadService.applyHttpTimeouts(this.implementation.timeout);
832
888
  this.shakeMenuEnabled = this.getConfig().getBoolean("shakeMenu", false);
833
889
  this.shakeChannelSelectorEnabled = this.getConfig().getBoolean("allowShakeChannelSelector", false);
834
890
  this.shakeMenuGesture = normalizedShakeMenuGesture(this.getConfig().getString("shakeMenuGesture", SHAKE_MENU_GESTURE_SHAKE));
@@ -851,11 +907,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
851
907
  ? this.prefs.getBoolean(PREVIEW_PREVIOUS_SHAKE_CHANNEL_SELECTOR_PREF_KEY, false)
852
908
  : this.shakeChannelSelectorEnabled;
853
909
  }
854
- boolean resetWhenUpdate = this.getConfig().getBoolean("resetWhenUpdate", true);
855
910
 
856
911
  // Check if app was recently installed/updated BEFORE cleanupObsoleteVersions updates LatestVersionNative
857
912
  this.wasRecentlyInstalledOrUpdated = this.checkIfRecentlyInstalledOrUpdated();
858
- final boolean nativeBuildVersionChanged = this.hasNativeBuildVersionChanged();
859
913
 
860
914
  this.implementation.autoReset(this.currentBuildVersion, resetWhenUpdate);
861
915
  if (nativeBuildVersionChanged) {
@@ -866,11 +920,14 @@ public class CapacitorUpdaterPlugin extends Plugin {
866
920
  this.reportPreviousAppExitReasons();
867
921
  this.reportPreviousWebViewRenderProcessGone();
868
922
  this.installWebViewStatsReporter();
869
- if (resetWhenUpdate) {
870
- this.cleanupObsoleteVersions();
871
- } else {
923
+ // Downloads (including shake-menu / CapgoUpdater entry points) wait on this gate.
924
+ this.implementation.downloadGate = this::waitForCleanupIfNeeded;
925
+ // Always run async cleanup: delete obsolete bundles on native update (when enabled)
926
+ // and sweep orphan folders every launch. Must not block app startup.
927
+ if (!resetWhenUpdate) {
872
928
  this.persistCurrentNativeBuildVersion();
873
929
  }
930
+ this.cleanupObsoleteVersions(resetWhenUpdate);
874
931
 
875
932
  // Check for 'kill' delay condition on app launch
876
933
  // This handles cases where the app was killed by the system (onDestroy is not reliable)
@@ -899,11 +956,18 @@ public class CapacitorUpdaterPlugin extends Plugin {
899
956
  },
900
957
  logger
901
958
  );
902
- this.appLifecycleObserver.register();
903
- logger.info("Using ProcessLifecycleOwner for foreground/background detection (Android 14+)");
959
+ this.appLifecycleObserver.register(this.getContext());
960
+ if (!this.appLifecycleObserver.isRegistered()) {
961
+ logger.warn("ProcessLifecycleOwner unavailable; using activity lifecycle callbacks");
962
+ } else {
963
+ logger.info("Using ProcessLifecycleOwner for foreground/background detection (Android 14+)");
964
+ }
904
965
  } else {
905
966
  logger.info("Using activity lifecycle callbacks for foreground/background detection (Android <14)");
906
967
  }
968
+
969
+ // Expect notifyAppReady before the first appReady/splash hide (same idea as iOS).
970
+ this.armPendingNotifyAppReadyWait();
907
971
  }
908
972
 
909
973
  private boolean semaphoreWait(final int phase, Number waitTime) {
@@ -946,6 +1010,32 @@ public class CapacitorUpdaterPlugin extends Plugin {
946
1010
  semaphoreReady.arriveAndDeregister();
947
1011
  }
948
1012
 
1013
+ private void armPendingNotifyAppReadyWait() {
1014
+ this.clearPendingNotifyAppReadyWait();
1015
+ this.pendingNotifyAppReadyPhase = this.semaphoreUp();
1016
+ this.pendingNotifyAppReadyWait = true;
1017
+ }
1018
+
1019
+ private void clearPendingNotifyAppReadyWait() {
1020
+ if (!this.pendingNotifyAppReadyWait) {
1021
+ return;
1022
+ }
1023
+ final int phase = this.pendingNotifyAppReadyPhase;
1024
+ this.pendingNotifyAppReadyWait = false;
1025
+ this.pendingNotifyAppReadyPhase = -1;
1026
+ this.cleanupTimedOutSemaphoreWait(phase);
1027
+ }
1028
+
1029
+ private boolean consumePendingNotifyAppReadyWait(final int[] phaseOut) {
1030
+ if (!this.pendingNotifyAppReadyWait) {
1031
+ return false;
1032
+ }
1033
+ phaseOut[0] = this.pendingNotifyAppReadyPhase;
1034
+ this.pendingNotifyAppReadyWait = false;
1035
+ this.pendingNotifyAppReadyPhase = -1;
1036
+ return true;
1037
+ }
1038
+
949
1039
  protected long getMinimumPendingBundleAppReadyTimeoutMs() {
950
1040
  return PENDING_BUNDLE_APP_READY_MIN_TIMEOUT_MS;
951
1041
  }
@@ -984,19 +1074,40 @@ public class CapacitorUpdaterPlugin extends Plugin {
984
1074
 
985
1075
  private void sendReadyToJs(final BundleInfo current, final String msg, final boolean isDirectUpdate) {
986
1076
  logger.info("sendReadyToJs: " + msg);
987
- final JSObject ret = new JSObject();
988
- ret.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
989
- ret.put("status", msg);
1077
+ final int[] pendingPhase = new int[] { -1 };
1078
+ final boolean shouldWait = this.consumePendingNotifyAppReadyWait(pendingPhase);
1079
+
1080
+ final Runnable emitReady = () -> {
1081
+ final JSObject ret = new JSObject();
1082
+ ret.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
1083
+ ret.put("status", msg);
990
1084
 
991
- // No need to wait for semaphore anymore since _reload() has already waited
992
- this.notifyListeners("appReady", ret, true);
1085
+ this.notifyListeners("appReady", ret, true);
993
1086
 
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();
1087
+ // Auto hide splashscreen if enabled
1088
+ // We show it on background when conditions are met, so we should hide it on foreground regardless of update outcome
1089
+ if (this.autoSplashscreen) {
1090
+ this.hideSplashscreen();
1091
+ }
1092
+ this.hidePreviewTransitionLoader("app-ready");
1093
+ };
1094
+
1095
+ if (!shouldWait) {
1096
+ emitReady.run();
1097
+ return;
998
1098
  }
999
- this.hidePreviewTransitionLoader("app-ready");
1099
+
1100
+ // Never block the UI thread waiting for notifyAppReady (JS needs it).
1101
+ if (Looper.myLooper() == Looper.getMainLooper()) {
1102
+ startNewThread(() -> {
1103
+ this.semaphoreWait(pendingPhase[0], this.appReadyTimeout);
1104
+ emitReady.run();
1105
+ });
1106
+ return;
1107
+ }
1108
+
1109
+ this.semaphoreWait(pendingPhase[0], this.appReadyTimeout);
1110
+ emitReady.run();
1000
1111
  }
1001
1112
 
1002
1113
  private void hideSplashscreen() {
@@ -1300,6 +1411,74 @@ public class CapacitorUpdaterPlugin extends Plugin {
1300
1411
  return false;
1301
1412
  }
1302
1413
 
1414
+ static boolean shouldClearPersistedDefaultChannel(
1415
+ final boolean persistDefaultChannelOnReinstall,
1416
+ final boolean resetWhenUpdate,
1417
+ final boolean nativeBuildVersionChanged,
1418
+ final boolean restoredReinstall
1419
+ ) {
1420
+ return !persistDefaultChannelOnReinstall && (restoredReinstall || (resetWhenUpdate && nativeBuildVersionChanged));
1421
+ }
1422
+
1423
+ static boolean clearPersistedDefaultChannel(final SharedPreferences.Editor editor) {
1424
+ editor.remove(DEFAULT_CHANNEL_PREF_KEY);
1425
+ editor.remove(PREVIEW_PREVIOUS_DEFAULT_CHANNEL_PREF_KEY);
1426
+ editor.remove(PREVIEW_PREVIOUS_DEFAULT_CHANNEL_WAS_SET_PREF_KEY);
1427
+ return editor.commit();
1428
+ }
1429
+
1430
+ private File defaultChannelInstallMarker() {
1431
+ return new File(this.getContext().getNoBackupFilesDir(), DEFAULT_CHANNEL_INSTALL_MARKER_FILE);
1432
+ }
1433
+
1434
+ static boolean invalidateDefaultChannelInstallMarker(final File marker) {
1435
+ return !marker.exists() || marker.delete();
1436
+ }
1437
+
1438
+ private boolean isRestoredReinstall() {
1439
+ return isRestoredReinstall(
1440
+ this.defaultChannelInstallMarker(),
1441
+ this.prefs.getBoolean(DEFAULT_CHANNEL_INSTALL_MARKER_PREF_KEY, false)
1442
+ );
1443
+ }
1444
+
1445
+ static boolean isRestoredReinstall(final File marker, final boolean markerWasCreated) {
1446
+ return markerWasCreated && !marker.exists();
1447
+ }
1448
+
1449
+ private void prepareDefaultChannelInstallMarker() {
1450
+ prepareDefaultChannelInstallMarker(
1451
+ this.defaultChannelInstallMarker(),
1452
+ this.prefs.getBoolean(DEFAULT_CHANNEL_INSTALL_MARKER_PREF_KEY, false),
1453
+ this.editor,
1454
+ this.logger
1455
+ );
1456
+ }
1457
+
1458
+ static void prepareDefaultChannelInstallMarker(
1459
+ final File marker,
1460
+ final boolean markerWasCreated,
1461
+ final SharedPreferences.Editor editor,
1462
+ final Logger logger
1463
+ ) {
1464
+ if (!marker.exists()) {
1465
+ try {
1466
+ if (!marker.createNewFile() && !marker.exists()) {
1467
+ throw new IOException("Marker file was not created");
1468
+ }
1469
+ } catch (final IOException e) {
1470
+ logger.warn("Cannot create default channel install marker: " + e.getMessage());
1471
+ editor.remove(DEFAULT_CHANNEL_INSTALL_MARKER_PREF_KEY);
1472
+ editor.commit();
1473
+ return;
1474
+ }
1475
+ }
1476
+ if (!markerWasCreated) {
1477
+ editor.putBoolean(DEFAULT_CHANNEL_INSTALL_MARKER_PREF_KEY, true);
1478
+ editor.apply();
1479
+ }
1480
+ }
1481
+
1303
1482
  private boolean hasNativeBuildVersionChanged() {
1304
1483
  final String lastKnownVersion = this.getStoredNativeBuildVersion();
1305
1484
  return !lastKnownVersion.isEmpty() && !lastKnownVersion.equals(this.currentBuildVersion);
@@ -1486,11 +1665,13 @@ public class CapacitorUpdaterPlugin extends Plugin {
1486
1665
  this.webViewStatsListener = new WebViewListener() {
1487
1666
  @Override
1488
1667
  public void onPageStarted(final android.webkit.WebView view) {
1668
+ CapacitorUpdaterPlugin.this.webViewPageStartedAtMs = System.currentTimeMillis();
1489
1669
  CapacitorUpdaterPlugin.this.evaluateWebViewStatsReporterScript(view, script);
1490
1670
  }
1491
1671
 
1492
1672
  @Override
1493
1673
  public void onPageLoaded(final android.webkit.WebView view) {
1674
+ CapacitorUpdaterPlugin.this.reportWebViewPageLoaded(view);
1494
1675
  CapacitorUpdaterPlugin.this.evaluateWebViewStatsReporterScript(view, script);
1495
1676
  }
1496
1677
  };
@@ -1556,6 +1737,83 @@ public class CapacitorUpdaterPlugin extends Plugin {
1556
1737
  });
1557
1738
  }
1558
1739
 
1740
+ private void reportAppLaunchStart() {
1741
+ if (
1742
+ this.implementation == null ||
1743
+ this.implementation.statsUrl == null ||
1744
+ this.implementation.statsUrl.isEmpty() ||
1745
+ this.launchStartReported
1746
+ ) {
1747
+ return;
1748
+ }
1749
+
1750
+ this.launchStartReported = true;
1751
+ final BundleInfo current = this.implementation.getCurrentBundle();
1752
+ final Map<String, String> metadata = new HashMap<>();
1753
+ metadata.put("launch_started_at", Long.toString(this.launchStartedAtMs));
1754
+ metadata.put("source", "plugin_load");
1755
+ this.implementation.sendStats("app_launch_start", current == null ? "" : current.getVersionName(), "", metadata);
1756
+ }
1757
+
1758
+ private void reportAppLaunchReady(final BundleInfo bundle) {
1759
+ synchronized (this.launchReportLock) {
1760
+ if (
1761
+ this.implementation == null ||
1762
+ this.implementation.statsUrl == null ||
1763
+ this.implementation.statsUrl.isEmpty() ||
1764
+ this.launchReadyReported ||
1765
+ this.launchTimeoutReported
1766
+ ) {
1767
+ return;
1768
+ }
1769
+ this.launchReadyReported = true;
1770
+ }
1771
+ final Map<String, String> metadata = new HashMap<>();
1772
+ metadata.put("duration_ms", Long.toString(Math.max(0, System.currentTimeMillis() - this.launchStartedAtMs)));
1773
+ metadata.put("launch_started_at", Long.toString(this.launchStartedAtMs));
1774
+ metadata.put("source", "notify_app_ready");
1775
+ this.implementation.sendStats("app_launch_ready", bundle == null ? "" : bundle.getVersionName(), "", metadata);
1776
+ }
1777
+
1778
+ private void reportAppLaunchTimeout(final BundleInfo bundle) {
1779
+ synchronized (this.launchReportLock) {
1780
+ if (
1781
+ this.implementation == null ||
1782
+ this.implementation.statsUrl == null ||
1783
+ this.implementation.statsUrl.isEmpty() ||
1784
+ this.launchReadyReported ||
1785
+ this.launchTimeoutReported
1786
+ ) {
1787
+ return;
1788
+ }
1789
+ this.launchTimeoutReported = true;
1790
+ }
1791
+ final Map<String, String> metadata = new HashMap<>();
1792
+ metadata.put("duration_ms", Long.toString(Math.max(0, System.currentTimeMillis() - this.launchStartedAtMs)));
1793
+ metadata.put("launch_started_at", Long.toString(this.launchStartedAtMs));
1794
+ metadata.put("timeout_ms", Long.toString(this.resolveAppReadyCheckTimeoutMs()));
1795
+ metadata.put("source", "app_ready_timeout");
1796
+ this.implementation.sendStats("app_launch_timeout", bundle == null ? "" : bundle.getVersionName(), "", metadata);
1797
+ }
1798
+
1799
+ private void reportWebViewPageLoaded(final android.webkit.WebView view) {
1800
+ if (this.implementation == null || this.implementation.statsUrl == null || this.implementation.statsUrl.isEmpty()) {
1801
+ return;
1802
+ }
1803
+
1804
+ final Map<String, String> metadata = new HashMap<>();
1805
+ metadata.put("source", "android_webview_listener");
1806
+ final long pageStartedAt = this.webViewPageStartedAtMs;
1807
+ if (pageStartedAt > 0) {
1808
+ metadata.put("duration_ms", Long.toString(Math.max(0, System.currentTimeMillis() - pageStartedAt)));
1809
+ metadata.put("page_started_at", Long.toString(pageStartedAt));
1810
+ }
1811
+ if (view != null && view.getUrl() != null && !view.getUrl().isEmpty()) {
1812
+ metadata.put("href", truncateStatsMetadataValue(sanitizeStatsMetadataUrl(view.getUrl()), 512));
1813
+ }
1814
+ this.reportWebViewStats("webview_page_loaded", metadata);
1815
+ }
1816
+
1559
1817
  private Map<String, String> buildWebViewRenderProcessGoneMetadata(final Object detailObj) {
1560
1818
  final Map<String, String> metadata = new HashMap<>();
1561
1819
  metadata.put("error_type", "render_process_gone");
@@ -1664,6 +1922,10 @@ public class CapacitorUpdaterPlugin extends Plugin {
1664
1922
  return "webview_render_process_gone";
1665
1923
  case "web_content_process_terminated":
1666
1924
  return "webview_content_process_terminated";
1925
+ case "webview_dom_content_loaded":
1926
+ return "webview_dom_content_loaded";
1927
+ case "webview_page_loaded":
1928
+ return "webview_page_loaded";
1667
1929
  case "javascript_error":
1668
1930
  default:
1669
1931
  return "webview_javascript_error";
@@ -1682,6 +1944,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
1682
1944
  putStatsMetadataValue(metadata, "href", sanitizeStatsMetadataUrl(data.optString("href", "")), 512);
1683
1945
  putStatsMetadataValue(metadata, "user_agent", data.optString("user_agent", ""), 256);
1684
1946
  putStatsMetadataValue(metadata, "session_id", data.optString("session_id", ""), 128);
1947
+ putStatsMetadataValue(metadata, "duration_ms", data.optString("duration_ms", ""), 32);
1948
+ putStatsMetadataValue(metadata, "page_started_at", data.optString("page_started_at", ""), 64);
1685
1949
  putStatsMetadataValue(metadata, "previous_session_id", data.optString("previous_session_id", ""), 128);
1686
1950
  putStatsMetadataValue(metadata, "previous_href", sanitizeStatsMetadataUrl(data.optString("previous_href", "")), 512);
1687
1951
  putStatsMetadataValue(metadata, "previous_started_at", data.optString("previous_started_at", ""), 64);
@@ -1814,12 +2078,14 @@ public class CapacitorUpdaterPlugin extends Plugin {
1814
2078
  "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
2079
  "writeSession(true);" +
1816
2080
  "setInterval(function(){writeSession(true);},15000);" +
2081
+ "function pageDuration(){var started=Number(window.__capgoWebViewSessionStartedAt||Date.now());return String(Math.max(0,Date.now()-started));}" +
1817
2082
  "function markClean(){writeSession(false);}" +
1818
2083
  "window.addEventListener('pagehide',markClean,true);" +
1819
2084
  "window.addEventListener('beforeunload',markClean,true);" +
1820
2085
  "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
2086
  "window.addEventListener('unhandledrejection',function(event){var reason=event&&event.reason;send({type:'unhandled_rejection',message:s(reason),stack:stack(reason)});},true);" +
1822
2087
  "document.addEventListener('securitypolicyviolation',function(event){send({type:'security_policy_violation',message:s(event&&event.violatedDirective),source:s(event&&event.blockedURI)});},true);" +
2088
+ "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
2089
  "document.addEventListener('deviceready',scheduleFlush,false);" +
1824
2090
  "setTimeout(scheduleFlush,0);" +
1825
2091
  "})();"
@@ -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
 
@@ -3748,7 +4027,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
3748
4027
 
3749
4028
  new AlertDialog.Builder(getActivity())
3750
4029
  .setTitle("Preview started")
3751
- .setMessage("Shake your device anytime to reload or leave the test app.")
4030
+ .setMessage("shake".equals(this.shakeMenuGesture) ? "Shake to open menu." : "Three-finger pinch to open menu.")
3752
4031
  .setPositiveButton("Got it", (dialog, which) -> dialog.dismiss())
3753
4032
  .show();
3754
4033
  } catch (final Exception e) {
@@ -3966,12 +4245,18 @@ public class CapacitorUpdaterPlugin extends Plugin {
3966
4245
  if (this.shouldBlockAutoUpdateForPreviewSession()) {
3967
4246
  return "preview_session";
3968
4247
  }
3969
- if (this.isDownloadStuckOrTimedOut()) {
3970
- logger.info("Download already in progress, skipping duplicate download request");
3971
- return "already_running";
4248
+ synchronized (this) {
4249
+ final Thread previousTask = this.backgroundDownloadTask;
4250
+ final Thread task = this.backgroundDownload();
4251
+ if (task == null) {
4252
+ return "unavailable";
4253
+ }
4254
+ if (previousTask != null && previousTask == task) {
4255
+ logger.info("Download already in progress, skipping duplicate download request");
4256
+ return "already_running";
4257
+ }
4258
+ return "queued";
3972
4259
  }
3973
- this.backgroundDownload();
3974
- return "queued";
3975
4260
  }
3976
4261
 
3977
4262
  @PluginMethod
@@ -4199,6 +4484,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4199
4484
  try {
4200
4485
  final BundleInfo bundle = this.implementation.getCurrentBundle();
4201
4486
  this.implementation.setSuccess(bundle, this.autoDeletePrevious);
4487
+ this.reportAppLaunchReady(bundle);
4202
4488
  logger.info("Current bundle loaded successfully. ['notifyAppReady()' was called] " + bundle);
4203
4489
  logger.info("semaphoreReady countDown");
4204
4490
  this.semaphoreDown();
@@ -4483,10 +4769,14 @@ public class CapacitorUpdaterPlugin extends Plugin {
4483
4769
  return true;
4484
4770
  }
4485
4771
 
4486
- private Thread backgroundDownload() {
4772
+ private synchronized Thread backgroundDownload() {
4487
4773
  if (this.shouldBlockAutoUpdateForPreviewSession()) {
4488
4774
  return null;
4489
4775
  }
4776
+ if (this.isDownloadStuckOrTimedOut()) {
4777
+ logger.info("Download already in progress, skipping duplicate download request");
4778
+ return this.backgroundDownloadTask;
4779
+ }
4490
4780
  final boolean plannedDirectUpdate = this.shouldUseDirectUpdate();
4491
4781
  final boolean initialDirectUpdateAllowed = this.isDirectUpdateCurrentlyAllowed(plannedDirectUpdate);
4492
4782
  final String messageUpdate = initialDirectUpdateAllowed
@@ -4495,8 +4785,6 @@ public class CapacitorUpdaterPlugin extends Plugin {
4495
4785
  ? "Update will occur next time app moves to background."
4496
4786
  : "Update will be downloaded and made available.";
4497
4787
  Thread newTask = startNewThread(() -> {
4498
- // Wait for cleanup to complete before starting download
4499
- waitForCleanupIfNeeded();
4500
4788
  if (CapacitorUpdaterPlugin.this.shouldBlockAutoUpdateForPreviewSession()) {
4501
4789
  CapacitorUpdaterPlugin.this.clearBackgroundDownloadState();
4502
4790
  return;
@@ -4509,7 +4797,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4509
4797
  return;
4510
4798
  }
4511
4799
  JSObject jsRes = InternalUtils.mapToJSObject(res);
4512
- final BundleInfo current = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
4800
+ final BundleInfo currentBeforeCleanup = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
4513
4801
 
4514
4802
  // Handle network errors and other failures first
4515
4803
  if (jsRes.has("error") || jsRes.has("kind")) {
@@ -4517,8 +4805,15 @@ public class CapacitorUpdaterPlugin extends Plugin {
4517
4805
  String errorMessage = jsRes.has("message") ? jsRes.getString("message") : "server did not provide a message";
4518
4806
  int statusCode = jsRes.has("statusCode") ? jsRes.optInt("statusCode", 0) : 0;
4519
4807
  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);
4808
+ String latestVersion = jsRes.has("version") ? jsRes.getString("version") : currentBeforeCleanup.getVersionName();
4809
+ CapacitorUpdaterPlugin.this.notifyUpdateCheckResult(
4810
+ kind,
4811
+ error,
4812
+ errorMessage,
4813
+ statusCode,
4814
+ latestVersion,
4815
+ currentBeforeCleanup
4816
+ );
4522
4817
  CapacitorUpdaterPlugin.this.notifyBreakingEventsIfNeeded(
4523
4818
  jsRes,
4524
4819
  jsRes.has("version") ? jsRes.getString("version") : ""
@@ -4538,7 +4833,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4538
4833
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
4539
4834
  errorMessage,
4540
4835
  latestVersion,
4541
- current,
4836
+ currentBeforeCleanup,
4542
4837
  isFailure,
4543
4838
  plannedDirectUpdate,
4544
4839
  "download_fail",
@@ -4548,6 +4843,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
4548
4843
  return;
4549
4844
  }
4550
4845
  try {
4846
+ // File mutations wait here. getLatest already ran in parallel with cleanup.
4847
+ waitForCleanupIfNeeded();
4848
+ final BundleInfo current = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
4551
4849
  final String latestVersionName = jsRes.getString("version");
4552
4850
 
4553
4851
  if ("builtin".equals(latestVersionName)) {
@@ -4796,8 +5094,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
4796
5094
  logger.error("error in update check " + e.getMessage());
4797
5095
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
4798
5096
  "Error in update check",
4799
- current.getVersionName(),
4800
- current,
5097
+ currentBeforeCleanup.getVersionName(),
5098
+ currentBeforeCleanup,
4801
5099
  true,
4802
5100
  plannedDirectUpdate
4803
5101
  );
@@ -4873,19 +5171,26 @@ public class CapacitorUpdaterPlugin extends Plugin {
4873
5171
  ret.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
4874
5172
  this.persistLastFailedBundle(current);
4875
5173
  this.notifyListeners("updateFailed", ret);
5174
+ this.reportAppLaunchTimeout(current);
4876
5175
  this.implementation.sendStats("update_fail", current.getVersionName());
4877
5176
  this.implementation.setError(current);
4878
5177
  this.performReset(true, false, true);
4879
5178
  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());
5179
+ final String failedId = current.getId();
5180
+ final String failedVersion = current.getVersionName();
5181
+ logger.info("Deleting failing bundle: " + failedVersion);
5182
+ // Mark before async work so kill/OOM still resumes via drainPendingDeletes.
5183
+ CapacitorUpdaterPlugin.this.implementation.saveBundleInfo(failedId, current.setStatus(BundleStatus.DELETING));
5184
+ startNewThread(() -> {
5185
+ try {
5186
+ final Boolean res = CapacitorUpdaterPlugin.this.implementation.delete(failedId, false, false);
5187
+ if (Boolean.TRUE.equals(res)) {
5188
+ logger.info("Failed bundle deleted: " + failedVersion);
5189
+ }
5190
+ } catch (final IOException e) {
5191
+ logger.error("Failed to delete failed bundle: " + failedVersion + " " + e.getMessage());
4885
5192
  }
4886
- } catch (final IOException e) {
4887
- logger.error("Failed to delete failed bundle: " + current.getVersionName() + " " + e.getMessage());
4888
- }
5193
+ });
4889
5194
  }
4890
5195
  } else {
4891
5196
  logger.info("notifyAppReady was called. This is fine: " + current.getId());
@@ -5000,6 +5305,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5000
5305
 
5001
5306
  // Do other background work after splashscreen is shown
5002
5307
  CapacitorUpdaterPlugin.this.implementation.sendStats("app_moved_to_background", current.getVersionName());
5308
+ CapacitorUpdaterPlugin.this.implementation.persistPendingStats();
5003
5309
  logger.info("Checking for pending update");
5004
5310
 
5005
5311
  try {
@@ -5075,9 +5381,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
5075
5381
 
5076
5382
  // On Android < 14, use activity lifecycle for foreground detection
5077
5383
  // 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)");
5384
+ if (!this.isProcessLifecycleObserverActive()) {
5385
+ if (isPreviousMainActivity || Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
5386
+ logger.info("handleOnStart: appMovedToForeground");
5081
5387
  this.appMovedToForeground();
5082
5388
  }
5083
5389
  isPreviousMainActivity = true;
@@ -5096,11 +5402,16 @@ public class CapacitorUpdaterPlugin extends Plugin {
5096
5402
 
5097
5403
  // On Android < 14, use activity lifecycle for background detection
5098
5404
  // 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)");
5405
+ if (!this.isProcessLifecycleObserverActive()) {
5406
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
5407
+ logger.info("handleOnStop: appMovedToBackground");
5103
5408
  this.appMovedToBackground();
5409
+ } else {
5410
+ isPreviousMainActivity = isMainActivity();
5411
+ if (isPreviousMainActivity) {
5412
+ logger.info("handleOnStop: appMovedToBackground (Android <14 path)");
5413
+ this.appMovedToBackground();
5414
+ }
5104
5415
  }
5105
5416
  }
5106
5417
  } catch (Exception e) {