@capgo/capacitor-updater 8.54.2 → 9.0.1

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 (45) hide show
  1. package/CapgoCapacitorUpdater.podspec +2 -2
  2. package/Package.swift +3 -4
  3. package/README.md +162 -417
  4. package/android/build.gradle +7 -7
  5. package/android/consumer-rules.pro +48 -0
  6. package/android/proguard-rules.pro +1 -23
  7. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +1420 -404
  8. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +1100 -308
  9. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +102 -65
  10. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +155 -18
  11. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +22 -2
  12. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +82 -21
  13. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +356 -0
  14. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +553 -0
  15. package/dist/docs.json +44 -566
  16. package/dist/esm/definitions.d.ts +97 -215
  17. package/dist/esm/definitions.js.map +1 -1
  18. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +197 -84
  19. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +402 -139
  20. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +81 -55
  21. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +24 -0
  22. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +2 -1
  23. package/ios/Sources/CapacitorUpdaterPlugin/WKWebView+CapgoObjcBridge.swift +20 -0
  24. package/ios/Tests/CapacitorUpdaterPluginTests/BuiltinHashesTests.swift +210 -0
  25. package/ios/Tests/CapacitorUpdaterPluginTests/BundleHardeningTests.swift +292 -0
  26. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +3905 -0
  27. package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
  28. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +151 -0
  29. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +249 -0
  30. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +528 -0
  31. package/ios/Tests/CapacitorUpdaterPluginTests/InstallPerfTests.swift +174 -0
  32. package/ios/Tests/CapacitorUpdaterPluginTests/ListChannelsTests.swift +74 -0
  33. package/ios/Tests/CapacitorUpdaterPluginTests/LoggerSecurityTests.swift +149 -0
  34. package/ios/Tests/CapacitorUpdaterPluginTests/NativeContractTests.swift +160 -0
  35. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +1095 -0
  36. package/ios/Tests/CapacitorUpdaterPluginTests/PopulateDeltaCacheTests.swift +573 -0
  37. package/ios/Tests/CapacitorUpdaterPluginTests/RedirectPolicyTests.swift +63 -0
  38. package/ios/Tests/CapacitorUpdaterPluginTests/RsaContractTests.swift +281 -0
  39. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +192 -0
  40. package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
  41. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +454 -0
  42. package/ios/Tests/CapacitorUpdaterPluginTests/WebKitOverlayGuardTests.swift +32 -0
  43. package/ios/Tests/CapacitorUpdaterPluginTests/ZipArchiveReaderTests.swift +302 -0
  44. package/ios/Tests/CapacitorUpdaterPluginTests/ZipBundleExtractionTests.swift +122 -0
  45. package/package.json +15 -13
@@ -69,11 +69,11 @@ import java.util.TimeZone;
69
69
  import java.util.Timer;
70
70
  import java.util.TimerTask;
71
71
  import java.util.concurrent.CountDownLatch;
72
+ import java.util.concurrent.ExecutionException;
73
+ import java.util.concurrent.FutureTask;
72
74
  import java.util.concurrent.Phaser;
73
- import java.util.concurrent.Semaphore;
74
75
  import java.util.concurrent.TimeUnit;
75
76
  import java.util.concurrent.TimeoutException;
76
- import java.util.concurrent.atomic.AtomicReference;
77
77
  import okhttp3.HttpUrl;
78
78
  import okhttp3.OkHttpClient;
79
79
  import okhttp3.Request;
@@ -102,8 +102,10 @@ public class CapacitorUpdaterPlugin extends Plugin {
102
102
 
103
103
  // Single listener that receives every plugin event as { type, data }.
104
104
  static final String UPDATER_EVENT = "updaterEvent";
105
- // Deprecated alias emitted next to breakingAvailable; not forwarded to avoid duplicates.
106
- private static final String DEPRECATED_MAJOR_AVAILABLE_EVENT = "majorAvailable";
105
+ // Config key removed in 9.0.0. Still read once at load to warn apps that kept it.
106
+ static final String REMOVED_DIRECT_UPDATE_CONFIG_KEY = "directUpdate";
107
+ static final String REMOVED_DIRECT_UPDATE_CONFIG_MESSAGE =
108
+ "The directUpdate config option was removed in 9.0.0 and is ignored. Use autoUpdate: \"atInstall\", \"onLaunch\" or \"always\" instead.";
107
109
 
108
110
  private Logger logger;
109
111
 
@@ -116,6 +118,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
116
118
  static final String STATS_URL_PREF_KEY = "CapacitorUpdater.statsUrl";
117
119
  static final String CHANNEL_URL_PREF_KEY = "CapacitorUpdater.channelUrl";
118
120
  static final String DEFAULT_CHANNEL_PREF_KEY = "CapacitorUpdater.defaultChannel";
121
+ static final String DEFAULT_CHANNEL_FROM_SET_CHANNEL_PREF_KEY = "CapacitorUpdater.defaultChannelFromSetChannel";
119
122
  static final String PREVIEW_SESSION_PREF_KEY = "CapacitorUpdater.previewSession";
120
123
  private static final String DEFAULT_CHANNEL_INSTALL_MARKER_PREF_KEY = "CapacitorUpdater.defaultChannelInstallMarkerCreated";
121
124
  private static final String DEFAULT_CHANNEL_INSTALL_MARKER_FILE = "CapacitorUpdater.defaultChannelInstallMarker";
@@ -131,7 +134,6 @@ public class CapacitorUpdaterPlugin extends Plugin {
131
134
  private static final String PREVIEW_SOURCE_PREF_KEY = "CapacitorUpdater.previewSource";
132
135
  private static final String PREVIEW_SESSIONS_PREF_KEY = "CapacitorUpdater.previewSessions";
133
136
  private static final String PREVIEW_SESSION_ALERT_PENDING_PREF_KEY = "CapacitorUpdater.previewSessionAlertPending";
134
- private static final String[] BREAKING_EVENT_NAMES = { "breakingAvailable", "majorAvailable" };
135
137
  private static final String LAST_FAILED_BUNDLE_PREF_KEY = "CapacitorUpdater.lastFailedBundle";
136
138
  private static final String LAST_REPORTED_APP_EXIT_TIMESTAMP_PREF_KEY = "CapacitorUpdater.lastReportedAppExitTimestamp";
137
139
  private static final String LAST_WEBVIEW_RENDER_PROCESS_GONE_PREF_KEY = "CapacitorUpdater.lastWebViewRenderProcessGone";
@@ -143,7 +145,6 @@ public class CapacitorUpdaterPlugin extends Plugin {
143
145
  private static final String SPLASH_SCREEN_PLUGIN_ID = "SplashScreen";
144
146
  private static final int SPLASH_SCREEN_RETRY_DELAY_MS = 100;
145
147
  private static final int SPLASH_SCREEN_MAX_RETRIES = 20;
146
- private static final long PENDING_BUNDLE_APP_READY_MIN_TIMEOUT_MS = 30000L;
147
148
  private static final long PREVIEW_TRANSITION_LOADER_TIMEOUT_MS = 60000L;
148
149
  static final int APPLICATION_EXIT_REASON_UNKNOWN = 0;
149
150
  static final int APPLICATION_EXIT_REASON_EXIT_SELF = 1;
@@ -158,10 +159,18 @@ public class CapacitorUpdaterPlugin extends Plugin {
158
159
  static final int APPLICATION_EXIT_REASON_USER_REQUESTED = 10;
159
160
  static final int APPLICATION_EXIT_REASON_DEPENDENCY_DIED = 12;
160
161
 
161
- static final String PLUGIN_VERSION = "8.52.1";
162
+ static final String PLUGIN_VERSION = "9.0.1";
162
163
  // Set while a plugin instance (with its bridge) runs in this process. The headless update
163
164
  // check then leaves installing to that instance instead of swapping bundles under it.
165
+ static final Object INSTANCE_LOADED_LOCK = new Object();
164
166
  static volatile boolean instanceLoaded = false;
167
+
168
+ static boolean isInstanceLoaded() {
169
+ synchronized (INSTANCE_LOADED_LOCK) {
170
+ return instanceLoaded;
171
+ }
172
+ }
173
+
165
174
  private final String pluginVersion = PLUGIN_VERSION;
166
175
  private static final String DELAY_CONDITION_PREFERENCES = "";
167
176
 
@@ -169,7 +178,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
169
178
  private SharedPreferences prefs;
170
179
  private final Object previewSessionsLock = new Object();
171
180
  protected CapgoUpdater implementation;
172
- private Boolean persistCustomId = false;
181
+ private Boolean persistCustomId = true;
173
182
  private Boolean persistModifyUrl = false;
174
183
  private Boolean persistDefaultChannelOnReinstall = true;
175
184
 
@@ -188,7 +197,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
188
197
  private Boolean autoSplashscreen = false;
189
198
  private Boolean autoSplashscreenLoader = false;
190
199
  private Integer autoSplashscreenTimeout = 10000;
191
- private Boolean autoSplashscreenTimedOut = false;
200
+ private volatile Boolean autoSplashscreenTimedOut = false;
192
201
  private int splashscreenInvocationToken = 0;
193
202
  private String directUpdateMode = "false";
194
203
  private Boolean wasRecentlyInstalledOrUpdated = false;
@@ -236,16 +245,68 @@ public class CapacitorUpdaterPlugin extends Plugin {
236
245
  private Boolean isPreviousMainActivity = true;
237
246
 
238
247
  private volatile Thread backgroundDownloadTask;
248
+ // Guarded by this. Check readiness and accepted update work have separate owners.
249
+ private CapgoUpdater.BackgroundDownloadContext backgroundDownloadContext;
250
+ private CapgoUpdater.BackgroundDownloadContext backgroundUpdateContext;
251
+ private long backgroundCheckSequence;
252
+ private long acceptedBackgroundCheckSequence;
253
+ private BackgroundReadyState backgroundReadyState = new BackgroundReadyState(-1);
254
+
255
+ private static final class BackgroundReadyState {
256
+
257
+ boolean claimed;
258
+ int pendingCompletions;
259
+ int waitPhase;
260
+ boolean pageReplaced;
261
+
262
+ BackgroundReadyState(final int waitPhase) {
263
+ this.waitPhase = waitPhase;
264
+ }
265
+ }
266
+
267
+ private static final class ReloadReadyWait {
268
+
269
+ final int phase;
270
+ volatile boolean notified;
271
+
272
+ ReloadReadyWait(final int phase) {
273
+ this.phase = phase;
274
+ }
275
+ }
276
+
277
+ // A phase can advance because it was retired, without its page ever reporting ready.
278
+ private final Map<Integer, ReloadReadyWait> reloadReadyWaits = new HashMap<>();
279
+ private final ThreadLocal<Boolean> reloadSupersededByPageReplacement = ThreadLocal.withInitial(() -> false);
239
280
  private volatile Thread appReadyCheck;
240
281
  // Between appMovedToBackground and appMovedToForeground. Android freezes backgrounded apps, so the
241
282
  // page cannot call notifyAppReady until the next foreground, which arms a fresh rollback check.
242
283
  private volatile boolean appInBackground = false;
284
+ private final Object automaticInstallLock = new Object();
285
+ private boolean automaticInstallInProgress = false;
286
+ private int automaticInstallPageGeneration = -1;
287
+ private boolean watchdogRollbackInProgress = false;
243
288
  // When true, sendReadyToJs should wait for notifyAppReady before hiding splash.
244
289
  private volatile boolean pendingNotifyAppReadyWait = false;
245
- // Armed only after a reload. The next document stamps this generation into notifyAppReady.
290
+ // Armed before staging or reload. The next document stamps this generation into notifyAppReady.
246
291
  private final Object readyGuardLock = new Object();
247
292
  private volatile int readyGeneration = 0;
248
293
  private volatile boolean readyGuardArmed = false;
294
+ // The document actually dispatched to the WebView, not a bundle staged for a future load.
295
+ private ReadyPageState liveReadyPage;
296
+
297
+ private static final class ReadyPageState {
298
+
299
+ final String bundlePath;
300
+ final int generation;
301
+ final boolean guardArmed;
302
+
303
+ ReadyPageState(final String bundlePath, final int generation, final boolean guardArmed) {
304
+ this.bundlePath = bundlePath;
305
+ this.generation = generation;
306
+ this.guardArmed = guardArmed;
307
+ }
308
+ }
309
+
249
310
  private volatile int pendingNotifyAppReadyPhase = -1;
250
311
  private volatile long downloadStartTimeMs = 0;
251
312
  private static final long DOWNLOAD_TIMEOUT_MS = 600000; // 10 minute timeout
@@ -279,7 +340,10 @@ public class CapacitorUpdaterPlugin extends Plugin {
279
340
  private volatile boolean launchTimeoutReported = false;
280
341
  private final Object launchReportLock = new Object();
281
342
  private FrameLayout splashscreenLoaderOverlay;
282
- private Runnable splashscreenTimeoutRunnable;
343
+ private final Object splashscreenTimeoutLock = new Object();
344
+ private SplashscreenTimeout splashscreenTimeoutRunnable;
345
+ // Unlike the foreground flag, this keeps expired work invalid after a background reset.
346
+ private long splashscreenTimeoutGeneration = 0;
283
347
  private FrameLayout previewTransitionLoaderOverlay;
284
348
  private Runnable previewTransitionLoaderTimeoutRunnable;
285
349
  private boolean previewTransitionLoaderRequested = false;
@@ -335,15 +399,14 @@ public class CapacitorUpdaterPlugin extends Plugin {
335
399
  return Long.toString(PackageInfoCompat.getLongVersionCode(packageInfo));
336
400
  }
337
401
 
402
+ /** Emits the breakingAvailable updater event for {@code version}. Empty versions are skipped. */
338
403
  private void notifyBreakingEvents(final String version) {
339
404
  if (version == null || version.isEmpty()) {
340
405
  return;
341
406
  }
342
- for (final String eventName : BREAKING_EVENT_NAMES) {
343
- final JSObject payload = new JSObject();
344
- payload.put("version", version);
345
- CapacitorUpdaterPlugin.this.notifyListeners(eventName, payload, false);
346
- }
407
+ final JSObject payload = new JSObject();
408
+ payload.put("version", version);
409
+ CapacitorUpdaterPlugin.this.notifyListeners("breakingAvailable", payload, false);
347
410
  }
348
411
 
349
412
  private boolean shouldNotifyBreakingEvents(final JSObject response) {
@@ -715,30 +778,36 @@ public class CapacitorUpdaterPlugin extends Plugin {
715
778
  return payload;
716
779
  }
717
780
 
718
- static boolean shouldForwardToUpdaterEvent(final String eventName) {
719
- return !UPDATER_EVENT.equals(eventName) && !DEPRECATED_MAJOR_AVAILABLE_EVENT.equals(eventName);
720
- }
721
-
722
- // Capacitor replays retained events through this overload when a listener attaches. They were
723
- // already forwarded to updaterEvent when emitted, so skip forwarding here. Plugin code must emit
724
- // through the three-argument overload.
781
+ /** Emits {@code eventName} as an updaterEvent without retaining it. See the three-argument overload. */
725
782
  @Override
726
783
  protected void notifyListeners(final String eventName, final JSObject data) {
727
- super.notifyListeners(eventName, data, false);
784
+ this.notifyListeners(eventName, data, false);
728
785
  }
729
786
 
787
+ /**
788
+ * Every plugin event reaches JavaScript as a single updaterEvent with { type, data }. eventName is the
789
+ * event type (download, appReady, ...). The per-event listeners were removed in 9.0.0.
790
+ */
730
791
  @Override
731
792
  protected void notifyListeners(final String eventName, final JSObject data, final boolean retainUntilConsumed) {
732
- super.notifyListeners(eventName, data, retainUntilConsumed);
733
- if (shouldForwardToUpdaterEvent(eventName)) {
734
- super.notifyListeners(UPDATER_EVENT, updaterEventPayload(eventName, data), retainUntilConsumed);
793
+ if (UPDATER_EVENT.equals(eventName)) {
794
+ // Already wrapped: Capacitor replays retained updaterEvent payloads through this path.
795
+ super.notifyListeners(eventName, data, retainUntilConsumed);
796
+ return;
735
797
  }
798
+ super.notifyListeners(UPDATER_EVENT, updaterEventPayload(eventName, data), retainUntilConsumed);
736
799
  }
737
800
 
801
+ /**
802
+ * Reads the plugin config, applies its defaults (httpsOnly, builtinMinimum and persistCustomId are on unless
803
+ * the app opts out) and starts the updater.
804
+ */
738
805
  @Override
739
806
  public void load() {
740
807
  super.load();
741
- instanceLoaded = true;
808
+ synchronized (INSTANCE_LOADED_LOCK) {
809
+ instanceLoaded = true;
810
+ }
742
811
 
743
812
  // Initialize logger with osLogging config
744
813
  // Default to true for both platforms to enable system logging by default
@@ -767,11 +836,38 @@ public class CapacitorUpdaterPlugin extends Plugin {
767
836
  CapacitorUpdaterPlugin.this.scheduleDirectUpdateFinish(latest);
768
837
  }
769
838
 
839
+ @Override
840
+ public void directUpdateFinish(final BundleInfo latest, final CapgoUpdater.BackgroundDownloadContext downloadContext) {
841
+ CapacitorUpdaterPlugin.this.scheduleDirectUpdateFinish(latest, downloadContext);
842
+ }
843
+
770
844
  @Override
771
845
  public void backgroundDownloadSettled(final BundleInfo bundle, final String status) {
772
846
  CapacitorUpdaterPlugin.this.emitLaunchDownloadReady(bundle, status);
773
847
  }
774
848
 
849
+ @Override
850
+ public void backgroundDownloadSettled(
851
+ final BundleInfo bundle,
852
+ final String status,
853
+ final CapgoUpdater.BackgroundDownloadContext downloadContext
854
+ ) {
855
+ CapacitorUpdaterPlugin.this.emitLaunchDownloadReady(bundle, status, downloadContext);
856
+ }
857
+
858
+ @Override
859
+ public void backgroundDownloadStarted(final CapgoUpdater.BackgroundDownloadContext downloadContext) {
860
+ CapacitorUpdaterPlugin.this.acceptBackgroundUpdate(downloadContext);
861
+ }
862
+
863
+ @Override
864
+ public void backgroundDownloadReused(
865
+ final CapgoUpdater.BackgroundDownloadContext original,
866
+ final CapgoUpdater.BackgroundDownloadContext replacement
867
+ ) {
868
+ CapacitorUpdaterPlugin.this.reuseBackgroundDownload(original, replacement);
869
+ }
870
+
775
871
  @Override
776
872
  public void nextBundleReady(final BundleInfo bundle) {
777
873
  CapacitorUpdaterPlugin.this.installNextIfInBackground();
@@ -832,7 +928,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
832
928
  this.allowPreview = this.getConfig().getBoolean("allowPreview", false);
833
929
  logger.info("appId: " + implementation.appId);
834
930
 
835
- this.persistCustomId = this.getConfig().getBoolean("persistCustomId", false);
931
+ this.persistCustomId = this.getConfig().getBoolean("persistCustomId", true);
836
932
  this.persistModifyUrl = this.getConfig().getBoolean("persistModifyUrl", false);
837
933
  this.persistDefaultChannelOnReinstall = this.getConfig().getBoolean("persistDefaultChannelOnReinstall", true);
838
934
  this.allowSetDefaultChannel = this.getConfig().getBoolean("allowSetDefaultChannel", true);
@@ -953,11 +1049,12 @@ public class CapacitorUpdaterPlugin extends Plugin {
953
1049
  this.implementation.timeout = (int) Math.min(Integer.MAX_VALUE, responseTimeoutMillis);
954
1050
  DownloadService.applyHttpTimeouts(this.implementation.timeout);
955
1051
  DownloadService.setAllowHttpsToHttpRedirect(this.getConfig().getBoolean("allowHttpsToHttpRedirect", false));
1052
+ Http3.setEnabled(this.getConfig().getBoolean("http3", true));
956
1053
  // httpsOnly overrides allowHttpsToHttpRedirect: no hop may leave https while it is on.
957
1054
  final boolean httpsOnly = this.getConfig().getBoolean("httpsOnly", true);
958
1055
  this.implementation.httpsOnly = httpsOnly;
959
1056
  DownloadService.setHttpsOnly(httpsOnly);
960
- this.implementation.builtinMinimum = this.getConfig().getBoolean("builtinMinimum", false);
1057
+ this.implementation.builtinMinimum = this.getConfig().getBoolean("builtinMinimum", true);
961
1058
  // Do not crash at load: requests to a non-https URL fail later with the same message.
962
1059
  this.warnIfNotHttps("updateUrl", this.updateUrl);
963
1060
  this.warnIfNotHttps("statsUrl", this.implementation.statsUrl);
@@ -1025,6 +1122,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
1025
1122
  this.wasRecentlyInstalledOrUpdated = this.checkIfRecentlyInstalledOrUpdated();
1026
1123
 
1027
1124
  this.resetStartupBundleAndReportAppLaunchStart(resetWhenUpdate, nativeBuildVersionChanged);
1125
+ this.captureInitialReadyPage();
1028
1126
  this.reportNativeVersionStatsIfChanged();
1029
1127
  this.reportPreviousAppExitReasons();
1030
1128
  this.reportPreviousWebViewRenderProcessGone();
@@ -1093,12 +1191,12 @@ public class CapacitorUpdaterPlugin extends Plugin {
1093
1191
  return true;
1094
1192
  } catch (InterruptedException e) {
1095
1193
  logger.info("semaphoreWait InterruptedException");
1096
- cleanupTimedOutSemaphoreWait(phase);
1194
+ cleanupFailedSemaphoreWait(phase, trackReloadAppReadyTimeout);
1097
1195
  Thread.currentThread().interrupt(); // Restore interrupted status
1098
1196
  return false;
1099
1197
  } catch (TimeoutException e) {
1100
1198
  logger.error("Semaphore timeout: " + e.getMessage());
1101
- cleanupTimedOutSemaphoreWait(phase);
1199
+ cleanupFailedSemaphoreWait(phase, trackReloadAppReadyTimeout);
1102
1200
  if (trackReloadAppReadyTimeout) {
1103
1201
  CapacitorUpdaterPlugin.reloadFailedDueToAppReadyTimeout.set(true);
1104
1202
  }
@@ -1141,38 +1239,78 @@ public class CapacitorUpdaterPlugin extends Plugin {
1141
1239
  return semaphoreReady.register();
1142
1240
  }
1143
1241
 
1144
- private void semaphoreDown() {
1242
+ private synchronized void semaphoreDown() {
1145
1243
  if (semaphoreReady.getRegisteredParties() == 0) {
1146
1244
  logger.info("semaphoreDown skipped, no pending app ready wait");
1147
1245
  return;
1148
1246
  }
1149
1247
  logger.info("semaphoreDown");
1150
1248
  logger.info("semaphoreDown count " + semaphoreReady.getPhase());
1249
+ final int phase = semaphoreReady.getPhase();
1250
+ final ReloadReadyWait reloadWait = this.reloadReadyWaits.get(phase);
1251
+ if (reloadWait != null) {
1252
+ reloadWait.notified = true;
1253
+ }
1151
1254
  semaphoreReady.arriveAndDeregister();
1255
+ this.retirePendingNotifyAppReadyPhase(phase);
1256
+ }
1257
+
1258
+ private synchronized void cleanupFailedSemaphoreWait(final int phase, final boolean reloadWait) {
1259
+ if (reloadWait || !this.reloadReadyWaits.containsKey(phase)) {
1260
+ this.cleanupTimedOutSemaphoreWait(phase);
1261
+ }
1262
+ }
1263
+
1264
+ private synchronized ReloadReadyWait armReloadReadyWait() {
1265
+ final ReloadReadyWait wait = new ReloadReadyWait(this.armPendingNotifyAppReadyWait());
1266
+ this.reloadReadyWaits.put(wait.phase, wait);
1267
+ return wait;
1152
1268
  }
1153
1269
 
1154
- private void cleanupTimedOutSemaphoreWait(final int phase) {
1270
+ private synchronized void cleanupTimedOutSemaphoreWait(final int phase) {
1155
1271
  if (semaphoreReady.getPhase() != phase || semaphoreReady.getRegisteredParties() == 0) {
1156
1272
  return;
1157
1273
  }
1158
1274
  logger.info("Cleaning up stale app ready wait for phase " + phase);
1159
1275
  semaphoreReady.arriveAndDeregister();
1276
+ this.retirePendingNotifyAppReadyPhase(phase);
1277
+ }
1278
+
1279
+ private void retirePendingNotifyAppReadyPhase(final int phase) {
1280
+ if (this.pendingNotifyAppReadyPhase == phase) {
1281
+ this.pendingNotifyAppReadyWait = false;
1282
+ this.pendingNotifyAppReadyPhase = -1;
1283
+ }
1160
1284
  }
1161
1285
 
1162
- private void armPendingNotifyAppReadyWait() {
1286
+ private synchronized int armPendingNotifyAppReadyWait() {
1287
+ final BackgroundReadyState readyState = this.backgroundReadyState;
1288
+ final boolean carryCompletion =
1289
+ readyState.pendingCompletions > 0 &&
1290
+ readyState.waitPhase >= 0 &&
1291
+ this.semaphoreReady.getPhase() == readyState.waitPhase &&
1292
+ this.semaphoreReady.getRegisteredParties() > 0;
1163
1293
  this.clearPendingNotifyAppReadyWait();
1164
1294
  this.pendingNotifyAppReadyPhase = this.semaphoreUp();
1165
1295
  this.pendingNotifyAppReadyWait = true;
1296
+ if (carryCompletion) {
1297
+ // This check still owns a completion, even if a different check initiated the reload.
1298
+ readyState.waitPhase = this.pendingNotifyAppReadyPhase;
1299
+ readyState.pageReplaced = true;
1300
+ this.backgroundReadyState = readyState;
1301
+ }
1302
+ return this.pendingNotifyAppReadyPhase;
1166
1303
  }
1167
1304
 
1168
- private void clearPendingNotifyAppReadyWait() {
1169
- if (!this.pendingNotifyAppReadyWait) {
1170
- return;
1171
- }
1305
+ private synchronized void clearPendingNotifyAppReadyWait() {
1172
1306
  final int phase = this.pendingNotifyAppReadyPhase;
1173
1307
  this.pendingNotifyAppReadyWait = false;
1174
1308
  this.pendingNotifyAppReadyPhase = -1;
1175
- this.cleanupTimedOutSemaphoreWait(phase);
1309
+ // Invalidate old page completions before releasing their waiters.
1310
+ this.backgroundReadyState = new BackgroundReadyState(-1);
1311
+ if (phase >= 0) {
1312
+ this.cleanupTimedOutSemaphoreWait(phase);
1313
+ }
1176
1314
  }
1177
1315
 
1178
1316
  private boolean consumePendingNotifyAppReadyWait(final int[] phaseOut) {
@@ -1181,31 +1319,12 @@ public class CapacitorUpdaterPlugin extends Plugin {
1181
1319
  }
1182
1320
  phaseOut[0] = this.pendingNotifyAppReadyPhase;
1183
1321
  this.pendingNotifyAppReadyWait = false;
1184
- this.pendingNotifyAppReadyPhase = -1;
1322
+ // Retain the phase until the page is replaced, even after a completion claims its wait.
1185
1323
  return true;
1186
1324
  }
1187
1325
 
1188
- protected long getMinimumPendingBundleAppReadyTimeoutMs() {
1189
- return PENDING_BUNDLE_APP_READY_MIN_TIMEOUT_MS;
1190
- }
1191
-
1192
1326
  private long resolveAppReadyCheckTimeoutMs() {
1193
- long configuredTimeoutMs = this.appReadyTimeout.longValue();
1194
- try {
1195
- if (this.implementation == null) {
1196
- return configuredTimeoutMs;
1197
- }
1198
-
1199
- final BundleInfo current = this.implementation.getCurrentBundle();
1200
- if (current == null || BundleStatus.SUCCESS == current.getStatus()) {
1201
- return configuredTimeoutMs;
1202
- }
1203
-
1204
- return Math.max(configuredTimeoutMs, this.getMinimumPendingBundleAppReadyTimeoutMs());
1205
- } catch (final Exception e) {
1206
- logger.warn("Falling back to configured appReadyTimeout: " + e.getMessage());
1207
- return configuredTimeoutMs;
1208
- }
1327
+ return this.appReadyTimeout.longValue();
1209
1328
  }
1210
1329
 
1211
1330
  private void sendReadyToJs(final BundleInfo current, final String msg) {
@@ -1222,23 +1341,89 @@ public class CapacitorUpdaterPlugin extends Plugin {
1222
1341
  }
1223
1342
 
1224
1343
  private void sendReadyToJs(final BundleInfo current, final String msg, final boolean isDirectUpdate) {
1344
+ this.sendReadyToJs(current, msg, isDirectUpdate, null);
1345
+ }
1346
+
1347
+ private void sendReadyToJs(
1348
+ final BundleInfo current,
1349
+ final String msg,
1350
+ final boolean isDirectUpdate,
1351
+ final CapgoUpdater.BackgroundDownloadContext downloadContext
1352
+ ) {
1225
1353
  logger.info("sendReadyToJs: " + msg);
1226
1354
  final int[] pendingPhase = new int[] { -1 };
1227
- final boolean shouldWait = this.consumePendingNotifyAppReadyWait(pendingPhase);
1355
+ final BackgroundReadyState readyState;
1356
+ boolean shouldWait;
1357
+ synchronized (this) {
1358
+ if (!this.ownsBackgroundDownload(downloadContext)) {
1359
+ return;
1360
+ }
1361
+ readyState = this.backgroundReadyState;
1362
+ if (downloadContext != null) {
1363
+ if (readyState.claimed) {
1364
+ return;
1365
+ }
1366
+ readyState.claimed = true;
1367
+ }
1368
+ shouldWait = this.consumePendingNotifyAppReadyWait(pendingPhase);
1369
+ if (shouldWait) {
1370
+ readyState.waitPhase = pendingPhase[0];
1371
+ } else if (
1372
+ readyState.waitPhase >= 0 &&
1373
+ this.semaphoreReady.getPhase() == readyState.waitPhase &&
1374
+ this.semaphoreReady.getRegisteredParties() > 0
1375
+ ) {
1376
+ // Consuming a waiter does not release the page's gate, including for contextless completions.
1377
+ pendingPhase[0] = readyState.waitPhase;
1378
+ shouldWait = true;
1379
+ }
1380
+ if (shouldWait) {
1381
+ readyState.pendingCompletions++;
1382
+ }
1383
+ }
1228
1384
 
1229
1385
  final Runnable emitReady = () -> {
1230
- final JSObject ret = new JSObject();
1231
- ret.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
1232
- ret.put("status", msg);
1233
-
1234
- this.notifyListeners("appReady", ret, true);
1386
+ synchronized (this) {
1387
+ if (!this.ownsBackgroundReadiness(downloadContext, readyState)) {
1388
+ return;
1389
+ }
1390
+ final BundleInfo readyBundle = readyState.pageReplaced ? this.implementation.getCurrentBundle() : current;
1391
+ final JSObject ret = new JSObject();
1392
+ ret.put("bundle", InternalUtils.mapToJSObject(readyBundle.toJSONMap()));
1393
+ ret.put("status", msg);
1394
+ this.notifyListeners("appReady", ret, true);
1395
+ // A listener can synchronously start another check on this same thread.
1396
+ if (!this.ownsBackgroundReadiness(downloadContext, readyState)) {
1397
+ return;
1398
+ }
1399
+ if (
1400
+ !this.autoSplashscreen &&
1401
+ !this.previewTransitionLoaderRequested &&
1402
+ this.previewTransitionLoaderOverlay == null &&
1403
+ this.previewTransitionLoaderTimeoutRunnable == null
1404
+ ) {
1405
+ return;
1406
+ }
1407
+ }
1235
1408
 
1236
- // Auto hide splashscreen if enabled
1237
- // We show it on background when conditions are met, so we should hide it on foreground regardless of update outcome
1238
- if (this.autoSplashscreen) {
1239
- this.hideSplashscreen();
1409
+ final Runnable hideReadyLoaders = () -> {
1410
+ synchronized (this) {
1411
+ if (!this.ownsBackgroundReadiness(downloadContext, readyState)) {
1412
+ return;
1413
+ }
1414
+ if (this.autoSplashscreen) {
1415
+ this.hideSplashscreenInternal(downloadContext, readyState);
1416
+ }
1417
+ if (this.ownsBackgroundReadiness(downloadContext, readyState)) {
1418
+ this.hidePreviewTransitionLoader("app-ready");
1419
+ }
1420
+ }
1421
+ };
1422
+ if (Looper.myLooper() == Looper.getMainLooper()) {
1423
+ hideReadyLoaders.run();
1424
+ } else {
1425
+ this.mainHandler.post(hideReadyLoaders);
1240
1426
  }
1241
- this.hidePreviewTransitionLoader("app-ready");
1242
1427
  };
1243
1428
 
1244
1429
  if (!shouldWait) {
@@ -1246,17 +1431,44 @@ public class CapacitorUpdaterPlugin extends Plugin {
1246
1431
  return;
1247
1432
  }
1248
1433
 
1249
- // Never block the UI thread waiting for notifyAppReady (JS needs it).
1250
- if (Looper.myLooper() == Looper.getMainLooper()) {
1434
+ // Completion callers may hold download ownership locks or still need to dispatch an install.
1435
+ // Keep every readiness wait off their stack, not only waits originating on the UI thread.
1436
+ final java.util.concurrent.atomic.AtomicBoolean completionReleased = new java.util.concurrent.atomic.AtomicBoolean();
1437
+ try {
1251
1438
  startNewThread(() -> {
1252
- this.semaphoreWait(pendingPhase[0], this.appReadyTimeout);
1253
- emitReady.run();
1439
+ try {
1440
+ int phase = pendingPhase[0];
1441
+ while (true) {
1442
+ this.semaphoreWait(phase, this.appReadyTimeout);
1443
+ synchronized (this) {
1444
+ if (!this.ownsBackgroundReadiness(downloadContext, readyState)) {
1445
+ return;
1446
+ }
1447
+ if (phase == readyState.waitPhase) {
1448
+ emitReady.run();
1449
+ return;
1450
+ }
1451
+ // Page replacement retires the old party without completing this check.
1452
+ phase = readyState.waitPhase;
1453
+ }
1454
+ }
1455
+ } finally {
1456
+ this.releasePendingReadyCompletion(readyState, completionReleased);
1457
+ }
1254
1458
  });
1255
- return;
1459
+ } catch (final RuntimeException e) {
1460
+ this.releasePendingReadyCompletion(readyState, completionReleased);
1461
+ throw e;
1256
1462
  }
1463
+ }
1257
1464
 
1258
- this.semaphoreWait(pendingPhase[0], this.appReadyTimeout);
1259
- emitReady.run();
1465
+ private synchronized void releasePendingReadyCompletion(
1466
+ final BackgroundReadyState readyState,
1467
+ final java.util.concurrent.atomic.AtomicBoolean released
1468
+ ) {
1469
+ if (released.compareAndSet(false, true)) {
1470
+ readyState.pendingCompletions--;
1471
+ }
1260
1472
  }
1261
1473
 
1262
1474
  private void hideSplashscreen() {
@@ -1268,9 +1480,23 @@ public class CapacitorUpdaterPlugin extends Plugin {
1268
1480
  }
1269
1481
 
1270
1482
  private void hideSplashscreenInternal() {
1483
+ this.hideSplashscreenInternal(null, null);
1484
+ }
1485
+
1486
+ private void hideSplashscreenInternal(
1487
+ final CapgoUpdater.BackgroundDownloadContext downloadContext,
1488
+ final BackgroundReadyState readyState
1489
+ ) {
1271
1490
  cancelSplashscreenTimeout();
1272
1491
  removeSplashscreenLoader();
1273
- invokeSplashScreenPluginMethod("hide", new JSObject(), SPLASH_SCREEN_MAX_RETRIES, ++this.splashscreenInvocationToken);
1492
+ invokeSplashScreenPluginMethod(
1493
+ "hide",
1494
+ new JSObject(),
1495
+ SPLASH_SCREEN_MAX_RETRIES,
1496
+ ++this.splashscreenInvocationToken,
1497
+ downloadContext,
1498
+ readyState
1499
+ );
1274
1500
  }
1275
1501
 
1276
1502
  private void showSplashscreen() {
@@ -1299,7 +1525,21 @@ public class CapacitorUpdaterPlugin extends Plugin {
1299
1525
  final int retriesRemaining,
1300
1526
  final int requestToken
1301
1527
  ) {
1302
- if (requestToken != this.splashscreenInvocationToken) {
1528
+ this.invokeSplashScreenPluginMethod(methodName, options, retriesRemaining, requestToken, null, null);
1529
+ }
1530
+
1531
+ private synchronized void invokeSplashScreenPluginMethod(
1532
+ final String methodName,
1533
+ final JSObject options,
1534
+ final int retriesRemaining,
1535
+ final int requestToken,
1536
+ final CapgoUpdater.BackgroundDownloadContext downloadContext,
1537
+ final BackgroundReadyState readyState
1538
+ ) {
1539
+ if (
1540
+ requestToken != this.splashscreenInvocationToken ||
1541
+ (readyState != null && !this.ownsBackgroundReadiness(downloadContext, readyState))
1542
+ ) {
1303
1543
  return;
1304
1544
  }
1305
1545
 
@@ -1311,6 +1551,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
1311
1551
  options,
1312
1552
  retriesRemaining,
1313
1553
  requestToken,
1554
+ downloadContext,
1555
+ readyState,
1314
1556
  "Bridge not ready for " + ("show".equals(methodName) ? "showing" : "hiding") + " splashscreen"
1315
1557
  );
1316
1558
  return;
@@ -1323,6 +1565,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
1323
1565
  options,
1324
1566
  retriesRemaining,
1325
1567
  requestToken,
1568
+ downloadContext,
1569
+ readyState,
1326
1570
  "autoSplashscreen: SplashScreen plugin not found. Install @capacitor/splash-screen plugin."
1327
1571
  );
1328
1572
  return;
@@ -1336,6 +1580,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
1336
1580
  options,
1337
1581
  retriesRemaining,
1338
1582
  requestToken,
1583
+ downloadContext,
1584
+ readyState,
1339
1585
  "Failed to call SplashScreen " + methodName + " method: " + e.getMessage()
1340
1586
  );
1341
1587
  }
@@ -1346,12 +1592,14 @@ public class CapacitorUpdaterPlugin extends Plugin {
1346
1592
  final JSObject options,
1347
1593
  final int retriesRemaining,
1348
1594
  final int requestToken,
1595
+ final CapgoUpdater.BackgroundDownloadContext downloadContext,
1596
+ final BackgroundReadyState readyState,
1349
1597
  final String message
1350
1598
  ) {
1351
1599
  if (retriesRemaining > 0) {
1352
1600
  logger.info(message + ". Retrying.");
1353
1601
  this.mainHandler.postDelayed(
1354
- () -> invokeSplashScreenPluginMethod(methodName, options, retriesRemaining - 1, requestToken),
1602
+ () -> invokeSplashScreenPluginMethod(methodName, options, retriesRemaining - 1, requestToken, downloadContext, readyState),
1355
1603
  SPLASH_SCREEN_RETRY_DELAY_MS
1356
1604
  );
1357
1605
  return;
@@ -1521,27 +1769,127 @@ public class CapacitorUpdaterPlugin extends Plugin {
1521
1769
  }
1522
1770
  }
1523
1771
 
1772
+ private boolean isDirectUpdateEligibleForLaunchSplashTimeout() {
1773
+ if (!Boolean.TRUE.equals(this.autoUpdate) || AUTO_UPDATE_MODE_ONLY_DOWNLOAD.equals(this.autoUpdateMode)) {
1774
+ return false;
1775
+ }
1776
+ if (Boolean.TRUE.equals(this.autoSplashscreenTimedOut)) {
1777
+ return false;
1778
+ }
1779
+ switch (this.directUpdateMode) {
1780
+ case "false":
1781
+ return false;
1782
+ case "always":
1783
+ return true;
1784
+ case "atInstall":
1785
+ return Boolean.TRUE.equals(this.wasRecentlyInstalledOrUpdated);
1786
+ case "onLaunch":
1787
+ return !this.onLaunchDirectUpdateUsed;
1788
+ default:
1789
+ return false;
1790
+ }
1791
+ }
1792
+
1793
+ private void scheduleLaunchSplashscreenTimeoutIfNeeded() {
1794
+ synchronized (this.splashscreenTimeoutLock) {
1795
+ if (
1796
+ this.splashscreenTimeoutRunnable != null ||
1797
+ !Boolean.TRUE.equals(this.autoSplashscreen) ||
1798
+ !this.isDirectUpdateEligibleForLaunchSplashTimeout()
1799
+ ) {
1800
+ return;
1801
+ }
1802
+ this.scheduleSplashscreenTimeout();
1803
+ }
1804
+ }
1805
+
1806
+ boolean hasSplashscreenTimeoutScheduledForTesting() {
1807
+ synchronized (this.splashscreenTimeoutLock) {
1808
+ return this.splashscreenTimeoutRunnable != null;
1809
+ }
1810
+ }
1811
+
1812
+ void scheduleLaunchSplashscreenTimeoutIfNeededForTesting() {
1813
+ this.scheduleLaunchSplashscreenTimeoutIfNeeded();
1814
+ }
1815
+
1524
1816
  private void scheduleSplashscreenTimeout() {
1525
1817
  if (this.autoSplashscreenTimeout == null || this.autoSplashscreenTimeout <= 0) {
1526
1818
  return;
1527
1819
  }
1528
1820
 
1529
- cancelSplashscreenTimeout();
1821
+ synchronized (this.splashscreenTimeoutLock) {
1822
+ cancelSplashscreenTimeout();
1823
+ this.splashscreenTimeoutRunnable = new SplashscreenTimeout();
1824
+ this.mainHandler.postDelayed(this.splashscreenTimeoutRunnable, this.autoSplashscreenTimeout);
1825
+ }
1826
+ }
1827
+
1828
+ private final class SplashscreenTimeout implements Runnable {
1829
+
1830
+ private boolean installStarted;
1530
1831
 
1531
- this.splashscreenTimeoutRunnable = () -> {
1832
+ @Override
1833
+ public void run() {
1834
+ synchronized (splashscreenTimeoutLock) {
1835
+ if (splashscreenTimeoutRunnable != this) {
1836
+ return;
1837
+ }
1838
+ splashscreenTimeoutRunnable = null;
1839
+ splashscreenTimeoutGeneration++;
1840
+ autoSplashscreenTimedOut = true;
1841
+ if (!this.installStarted) {
1842
+ implementation.directUpdate = false;
1843
+ }
1844
+ }
1532
1845
  logger.info("autoSplashscreen timeout reached, hiding splashscreen");
1533
- this.autoSplashscreenTimedOut = true;
1534
- this.implementation.directUpdate = false;
1535
1846
  hideSplashscreen();
1536
- };
1847
+ }
1848
+ }
1537
1849
 
1538
- this.mainHandler.postDelayed(this.splashscreenTimeoutRunnable, this.autoSplashscreenTimeout);
1850
+ private long getSplashscreenTimeoutGeneration() {
1851
+ synchronized (this.splashscreenTimeoutLock) {
1852
+ return this.splashscreenTimeoutGeneration;
1853
+ }
1539
1854
  }
1540
1855
 
1541
1856
  private void cancelSplashscreenTimeout() {
1542
- if (this.splashscreenTimeoutRunnable != null) {
1543
- this.mainHandler.removeCallbacks(this.splashscreenTimeoutRunnable);
1544
- this.splashscreenTimeoutRunnable = null;
1857
+ synchronized (this.splashscreenTimeoutLock) {
1858
+ if (this.splashscreenTimeoutRunnable != null) {
1859
+ this.mainHandler.removeCallbacks(this.splashscreenTimeoutRunnable);
1860
+ this.splashscreenTimeoutRunnable = null;
1861
+ }
1862
+ }
1863
+ }
1864
+
1865
+ private boolean claimDirectUpdateInstall(final long timeoutGeneration, final BundleInfo candidate) {
1866
+ synchronized (this.automaticInstallLock) {
1867
+ if (this.automaticInstallInProgress || this.watchdogRollbackInProgress) {
1868
+ return false;
1869
+ }
1870
+ final java.util.function.BooleanSupplier admitInstall = () ->
1871
+ this.implementation.clearNextBundleForDirectInstall(candidate, () ->
1872
+ this.beginDirectUpdateInstallBeforeTimeout(timeoutGeneration)
1873
+ );
1874
+ if (!(candidate.isBuiltin() ? this.implementation.admitBuiltinInstall(admitInstall) : admitInstall.getAsBoolean())) {
1875
+ return false;
1876
+ }
1877
+ this.automaticInstallInProgress = true;
1878
+ this.automaticInstallPageGeneration = -1;
1879
+ return true;
1880
+ }
1881
+ }
1882
+
1883
+ private boolean beginDirectUpdateInstallBeforeTimeout(final long timeoutGeneration) {
1884
+ synchronized (this.splashscreenTimeoutLock) {
1885
+ if (!this.isDirectUpdateCurrentlyAllowed(true, timeoutGeneration)) {
1886
+ return false;
1887
+ }
1888
+ // Keep the hide deadline while an admitted install waits for JS readiness.
1889
+ if (this.splashscreenTimeoutRunnable != null) {
1890
+ this.splashscreenTimeoutRunnable.installStarted = true;
1891
+ }
1892
+ return true;
1545
1893
  }
1546
1894
  }
1547
1895
 
@@ -1571,6 +1919,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
1571
1919
 
1572
1920
  static boolean clearPersistedDefaultChannel(final SharedPreferences.Editor editor) {
1573
1921
  editor.remove(DEFAULT_CHANNEL_PREF_KEY);
1922
+ editor.remove(DEFAULT_CHANNEL_FROM_SET_CHANNEL_PREF_KEY);
1574
1923
  editor.remove(PREVIEW_PREVIOUS_DEFAULT_CHANNEL_PREF_KEY);
1575
1924
  editor.remove(PREVIEW_PREVIOUS_DEFAULT_CHANNEL_WAS_SET_PREF_KEY);
1576
1925
  return editor.commit();
@@ -2282,8 +2631,12 @@ public class CapacitorUpdaterPlugin extends Plugin {
2282
2631
  this.implementation.directUpdate = isDirectUpdateMode(this.directUpdateMode);
2283
2632
  }
2284
2633
 
2285
- /** Resolves autoUpdate (and the legacy directUpdate) from the plugin config. Shared with the headless update check. */
2634
+ /** Resolves autoUpdate from the plugin config. Shared with the headless update check. */
2286
2635
  static String autoUpdateModeFromConfig(final PluginConfig pluginConfig, final Logger logger) {
2636
+ final JSONObject rawConfig = pluginConfig.getConfigJSON();
2637
+ if (logger != null && rawConfig != null && rawConfig.has(REMOVED_DIRECT_UPDATE_CONFIG_KEY)) {
2638
+ logger.error(REMOVED_DIRECT_UPDATE_CONFIG_MESSAGE);
2639
+ }
2287
2640
  final String configuredMode = pluginConfig.getString("autoUpdate", null);
2288
2641
  if (configuredMode != null && !configuredMode.isEmpty() && !"true".equals(configuredMode) && !"false".equals(configuredMode)) {
2289
2642
  final String mode = normalizedAutoUpdateMode(configuredMode);
@@ -2298,31 +2651,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
2298
2651
  }
2299
2652
  final boolean enabled =
2300
2653
  configuredMode != null ? "true".equals(configuredMode) : Boolean.TRUE.equals(pluginConfig.getBoolean("autoUpdate", true));
2301
- return enabled
2302
- ? autoUpdateModeForLegacyDirectUpdateMode(resolveLegacyDirectUpdateModeFromConfig(pluginConfig, logger))
2303
- : AUTO_UPDATE_MODE_OFF;
2304
- }
2305
-
2306
- private static String resolveLegacyDirectUpdateModeFromConfig(final PluginConfig pluginConfig, final Logger logger) {
2307
- final String directUpdateConfig = pluginConfig.getString("directUpdate", null);
2308
- if (directUpdateConfig != null) {
2309
- if ("true".equals(directUpdateConfig)) {
2310
- return AUTO_UPDATE_MODE_ALWAYS;
2311
- }
2312
- if ("false".equals(directUpdateConfig) || isDirectUpdateMode(directUpdateConfig)) {
2313
- return directUpdateConfig;
2314
- }
2315
- if (logger != null) {
2316
- logger.error(
2317
- "Invalid directUpdate value: \"" +
2318
- directUpdateConfig +
2319
- "\". Supported values are: false, true, \"always\", \"atInstall\", \"onLaunch\". Defaulting to \"false\"."
2320
- );
2321
- }
2322
- return "false";
2323
- }
2324
-
2325
- return Boolean.TRUE.equals(pluginConfig.getBoolean("directUpdate", false)) ? AUTO_UPDATE_MODE_ALWAYS : "false";
2654
+ return enabled ? AUTO_UPDATE_MODE_BACKGROUND : AUTO_UPDATE_MODE_OFF;
2326
2655
  }
2327
2656
 
2328
2657
  static String normalizedAutoUpdateMode(final String value) {
@@ -2368,18 +2697,6 @@ public class CapacitorUpdaterPlugin extends Plugin {
2368
2697
  return SHAKE_MENU_GESTURE_SHAKE.equals(normalized) || SHAKE_MENU_GESTURE_THREE_FINGER_PINCH.equals(normalized);
2369
2698
  }
2370
2699
 
2371
- static String autoUpdateModeForLegacyDirectUpdateMode(final String directUpdateMode) {
2372
- switch (directUpdateMode) {
2373
- case AUTO_UPDATE_MODE_INSTALL:
2374
- case AUTO_UPDATE_MODE_LAUNCH:
2375
- case AUTO_UPDATE_MODE_ALWAYS:
2376
- return directUpdateMode;
2377
- case "false":
2378
- default:
2379
- return AUTO_UPDATE_MODE_BACKGROUND;
2380
- }
2381
- }
2382
-
2383
2700
  static String directUpdateModeForAutoUpdateMode(final String autoUpdateMode) {
2384
2701
  switch (autoUpdateMode) {
2385
2702
  case AUTO_UPDATE_MODE_INSTALL:
@@ -2411,8 +2728,10 @@ public class CapacitorUpdaterPlugin extends Plugin {
2411
2728
  return shouldAutoUpdateModeSetNextBundle(this.autoUpdateMode);
2412
2729
  }
2413
2730
 
2414
- private boolean isDirectUpdateCurrentlyAllowed(final boolean plannedDirectUpdate) {
2415
- return plannedDirectUpdate && !Boolean.TRUE.equals(this.autoSplashscreenTimedOut);
2731
+ private boolean isDirectUpdateCurrentlyAllowed(final boolean plannedDirectUpdate, final long timeoutGeneration) {
2732
+ synchronized (this.splashscreenTimeoutLock) {
2733
+ return plannedDirectUpdate && timeoutGeneration == this.splashscreenTimeoutGeneration && !this.autoSplashscreenTimedOut;
2734
+ }
2416
2735
  }
2417
2736
 
2418
2737
  static boolean shouldConsumeOnLaunchDirectUpdate(final String directUpdateMode, final boolean plannedDirectUpdate) {
@@ -2443,9 +2762,13 @@ public class CapacitorUpdaterPlugin extends Plugin {
2443
2762
  this.onLaunchDirectUpdateUsed = true;
2444
2763
  }
2445
2764
 
2765
+ /**
2766
+ * Test hook: sets an instant apply mode ("false", "always", "atInstall", "onLaunch") and the matching
2767
+ * autoUpdate mode, as if it came from the config.
2768
+ */
2446
2769
  void configureDirectUpdateModeForTesting(final String directUpdateMode, final boolean onLaunchDirectUpdateUsed) {
2447
2770
  this.directUpdateMode = directUpdateMode;
2448
- this.autoUpdateMode = autoUpdateModeForLegacyDirectUpdateMode(directUpdateMode);
2771
+ this.autoUpdateMode = isDirectUpdateMode(directUpdateMode) ? directUpdateMode : AUTO_UPDATE_MODE_BACKGROUND;
2449
2772
  this.autoUpdate = isAutoUpdateModeEnabled(this.autoUpdateMode);
2450
2773
  if (this.implementation != null) {
2451
2774
  this.implementation.directUpdate = isDirectUpdateMode(this.directUpdateMode);
@@ -2502,6 +2825,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
2502
2825
  this.clearPreviewSessionForNativeBuildChange();
2503
2826
  }
2504
2827
  this.leavePreviewSessionForLaunchIntentIfNeeded();
2828
+ this.implementation.enforceStartupVersionFloor();
2505
2829
  this.reportAppLaunchStart();
2506
2830
  }
2507
2831
 
@@ -2528,12 +2852,96 @@ public class CapacitorUpdaterPlugin extends Plugin {
2528
2852
  }
2529
2853
 
2530
2854
  void scheduleDirectUpdateFinish(final BundleInfo latest) {
2855
+ this.scheduleDirectUpdateFinish(latest, null);
2856
+ }
2857
+
2858
+ private synchronized boolean ownsBackgroundDownload(final CapgoUpdater.BackgroundDownloadContext downloadContext) {
2859
+ return downloadContext == null || this.backgroundDownloadContext == downloadContext;
2860
+ }
2861
+
2862
+ synchronized void acceptBackgroundUpdate(final CapgoUpdater.BackgroundDownloadContext downloadContext) {
2863
+ if (downloadContext.checkSequence < this.acceptedBackgroundCheckSequence) {
2864
+ return;
2865
+ }
2866
+ // A later pending check does not discard accepted work, but a later accepted update does.
2867
+ this.backgroundUpdateContext = downloadContext;
2868
+ this.acceptedBackgroundCheckSequence = downloadContext.checkSequence;
2869
+ }
2870
+
2871
+ private synchronized boolean canFinishBackgroundDownload(final CapgoUpdater.BackgroundDownloadContext downloadContext) {
2872
+ return this.ownsBackgroundDownload(downloadContext) || this.backgroundUpdateContext == downloadContext;
2873
+ }
2874
+
2875
+ private synchronized boolean ownsBackgroundReadiness(
2876
+ final CapgoUpdater.BackgroundDownloadContext downloadContext,
2877
+ final BackgroundReadyState readyState
2878
+ ) {
2879
+ return this.ownsBackgroundDownload(downloadContext) && this.backgroundReadyState == readyState;
2880
+ }
2881
+
2882
+ void reuseBackgroundDownload(
2883
+ final CapgoUpdater.BackgroundDownloadContext original,
2884
+ final CapgoUpdater.BackgroundDownloadContext replacement
2885
+ ) {
2886
+ final boolean releaseRetry;
2887
+ synchronized (this) {
2888
+ if (!this.ownsBackgroundDownload(replacement)) {
2889
+ return;
2890
+ }
2891
+ this.backgroundDownloadContext = original;
2892
+ this.backgroundUpdateContext = original;
2893
+ this.acceptedBackgroundCheckSequence = replacement.checkSequence;
2894
+ releaseRetry = original.deferredForRetry;
2895
+ this.implementation.directUpdate =
2896
+ !releaseRetry && this.isDirectUpdateCurrentlyAllowed(original.directUpdate, original.timeoutGeneration);
2897
+ }
2898
+ if (releaseRetry) {
2899
+ // The retry notification may have been discarded while this check owned a different context.
2900
+ this.emitLaunchDownloadReady(null, CapgoUpdater.launchDownloadReadyStatus(false, false), original);
2901
+ }
2902
+ }
2903
+
2904
+ void emitLaunchDownloadReady(
2905
+ final BundleInfo bundle,
2906
+ final String status,
2907
+ final CapgoUpdater.BackgroundDownloadContext downloadContext
2908
+ ) {
2909
+ if (downloadContext == null) {
2910
+ this.emitLaunchDownloadReady(bundle, status);
2911
+ return;
2912
+ }
2913
+ final BundleInfo readyBundle = bundle != null ? bundle : this.implementation.getCurrentBundle();
2914
+ if (readyBundle == null) {
2915
+ return;
2916
+ }
2917
+ synchronized (this) {
2918
+ if (!this.ownsBackgroundDownload(downloadContext)) {
2919
+ return;
2920
+ }
2921
+ this.implementation.directUpdate = false;
2922
+ this.clearBackgroundDownloadState();
2923
+ }
2924
+ this.sendReadyToJs(readyBundle, status, false, downloadContext);
2925
+ }
2926
+
2927
+ void scheduleDirectUpdateFinish(final BundleInfo latest, final CapgoUpdater.BackgroundDownloadContext downloadContext) {
2928
+ final long timeoutGeneration;
2929
+ final Thread downloadTask;
2930
+ synchronized (this) {
2931
+ if (!this.canFinishBackgroundDownload(downloadContext)) {
2932
+ return;
2933
+ }
2934
+ timeoutGeneration = downloadContext != null ? downloadContext.timeoutGeneration : this.getSplashscreenTimeoutGeneration();
2935
+ downloadTask = this.backgroundDownloadTask;
2936
+ }
2531
2937
  startNewThread(() -> {
2532
2938
  try {
2939
+ if (!this.canFinishBackgroundDownload(downloadContext)) {
2940
+ return;
2941
+ }
2533
2942
  if (this.shouldBlockAutoUpdateForPreviewSession()) {
2534
2943
  logger.info("Skipping direct update install while preview session state is active");
2535
- this.implementation.directUpdate = false;
2536
- this.clearBackgroundDownloadState();
2944
+ this.clearDirectUpdateDownloadState(downloadTask, downloadContext);
2537
2945
  return;
2538
2946
  }
2539
2947
  Activity currentActivity = this.getActivity();
@@ -2542,49 +2950,111 @@ public class CapacitorUpdaterPlugin extends Plugin {
2542
2950
  } else {
2543
2951
  logger.warn("directUpdateFinish: Activity is null, proceeding without refreshing the activity reference");
2544
2952
  }
2545
- this.directUpdateFinish(latest);
2953
+ this.directUpdateFinish(latest, timeoutGeneration, downloadTask, downloadContext);
2546
2954
  } catch (final Exception e) {
2547
2955
  logger.error("directUpdateFinish failed: " + e.getMessage());
2548
2956
  }
2549
2957
  });
2550
2958
  }
2551
2959
 
2552
- private void directUpdateFinish(final BundleInfo latest) {
2960
+ private void directUpdateFinish(
2961
+ final BundleInfo latest,
2962
+ final long timeoutGeneration,
2963
+ final Thread downloadTask,
2964
+ final CapgoUpdater.BackgroundDownloadContext downloadContext
2965
+ ) {
2553
2966
  if (this.shouldBlockAutoUpdateForPreviewSession()) {
2554
2967
  logger.info("Skipping direct update finish while preview session state is active");
2555
- this.implementation.directUpdate = false;
2556
- this.clearBackgroundDownloadState();
2968
+ this.clearDirectUpdateDownloadState(downloadTask, downloadContext);
2557
2969
  return;
2558
2970
  }
2559
- if ("onLaunch".equals(this.directUpdateMode)) {
2560
- this.onLaunchDirectUpdateUsed = true;
2561
- this.implementation.directUpdate = false;
2971
+ final String delayUpdatePreferences = this.prefs.getString(DelayUpdateUtils.DELAY_CONDITION_PREFERENCES, "[]");
2972
+ final ArrayList<DelayCondition> delayConditionList = this.delayUpdateUtils.parseDelayConditions(delayUpdatePreferences);
2973
+ if (!delayConditionList.isEmpty()) {
2974
+ logger.info("Update delayed until delay conditions met");
2975
+ if (!this.queueDeferredDirectUpdate(latest, downloadTask, downloadContext)) {
2976
+ return;
2977
+ }
2978
+ if ("onLaunch".equals(this.directUpdateMode) && this.ownsBackgroundDownload(downloadContext)) {
2979
+ this.onLaunchDirectUpdateUsed = true;
2980
+ }
2981
+ this.sendReadyToJs(this.implementation.getCurrentBundle(), "Update delayed until delay conditions met", true, downloadContext);
2982
+ this.installNextIfInBackground();
2983
+ return;
2562
2984
  }
2563
- if (this.applyDownloadedBundleForDirectUpdate(latest)) {
2564
- this.implementation.setNextBundle(null);
2565
- this.notifyBundleSet(latest);
2566
- sendReadyToJs(latest, "update installed", true);
2567
- } else {
2568
- this.implementation.setNextBundle(latest.getId());
2569
- final JSObject ret = new JSObject();
2570
- ret.put("bundle", InternalUtils.mapToJSObject(latest.toJSONMap()));
2571
- this.notifyListeners("updateAvailable", ret, false);
2572
- sendReadyToJs(
2573
- this.implementation.getCurrentBundle(),
2574
- "Direct update reload failed, update will install next background",
2575
- false
2576
- );
2985
+ boolean installAdmitted = false;
2986
+ boolean installed = false;
2987
+ try {
2988
+ synchronized (this) {
2989
+ final boolean directUpdateAllowed =
2990
+ this.ownsBackgroundDownload(downloadContext) &&
2991
+ this.backgroundDownloadTask == downloadTask &&
2992
+ (downloadContext == null || (downloadContext.directUpdate && !downloadContext.deferredForRetry));
2993
+ installAdmitted = directUpdateAllowed && this.claimDirectUpdateInstall(timeoutGeneration, latest);
2994
+ if (installAdmitted) {
2995
+ this.implementation.directUpdate = false;
2996
+ }
2997
+ }
2998
+ if (!installAdmitted) {
2999
+ if (!this.queueDeferredDirectUpdate(latest, downloadTask, downloadContext)) {
3000
+ return;
3001
+ }
3002
+ this.sendReadyToJs(
3003
+ this.implementation.getCurrentBundle(),
3004
+ "update downloaded, will install next background",
3005
+ true,
3006
+ downloadContext
3007
+ );
3008
+ this.installNextIfInBackground();
3009
+ return;
3010
+ }
3011
+ if ("onLaunch".equals(this.directUpdateMode)) {
3012
+ this.onLaunchDirectUpdateUsed = true;
3013
+ this.implementation.directUpdate = false;
3014
+ }
3015
+ installed = this.applyDownloadedBundleForDirectUpdate(latest);
3016
+ if (installed) {
3017
+ this.implementation.clearNextBundleIfMatches(latest.getId());
3018
+ this.notifyBundleSet(latest);
3019
+ sendReadyToJs(latest, "update installed", true, downloadContext);
3020
+ } else {
3021
+ final boolean queued =
3022
+ !CapacitorUpdaterPlugin.reloadFailedDueToAppReadyTimeout.get() &&
3023
+ !this.reloadSupersededByPageReplacement.get() &&
3024
+ this.implementation.setNextBundleIfEmpty(latest.getId());
3025
+ if (queued) {
3026
+ final JSObject ret = new JSObject();
3027
+ ret.put("bundle", InternalUtils.mapToJSObject(latest.toJSONMap()));
3028
+ this.notifyListeners("updateAvailable", ret, false);
3029
+ }
3030
+ sendReadyToJs(
3031
+ this.implementation.getCurrentBundle(),
3032
+ queued ? "Direct update reload failed, update will install next background" : "Direct update reload failed",
3033
+ false,
3034
+ downloadContext
3035
+ );
3036
+ }
3037
+ } finally {
3038
+ if (installAdmitted) {
3039
+ this.releaseAutomaticInstall();
3040
+ this.installNextIfInBackground(installed ? null : latest.getId());
3041
+ }
2577
3042
  }
2578
3043
  }
2579
3044
 
2580
3045
  private boolean applyDownloadedBundleForDirectUpdate(final BundleInfo latest) {
2581
- final CapgoUpdater.ResetState previousState = this.implementation.captureResetState();
2582
- final String previousBundleName = this.implementation.getCurrentBundle().getVersionName();
2583
-
2584
- if (!this.implementation.stagePendingReload(latest)) {
2585
- this.implementation.restoreResetState(previousState);
2586
- logger.error("Direct update failed to stage downloaded bundle: " + latest.toString());
2587
- return false;
3046
+ CapacitorUpdaterPlugin.reloadFailedDueToAppReadyTimeout.set(false);
3047
+ this.reloadSupersededByPageReplacement.set(false);
3048
+ final CapgoUpdater.ResetState previousState;
3049
+ final String previousBundleName;
3050
+ synchronized (this) {
3051
+ previousState = this.implementation.captureResetState();
3052
+ previousBundleName = this.implementation.getCurrentBundle().getVersionName();
3053
+ if (!this.stageBundleForReload(() -> this.implementation.stagePendingReload(latest))) {
3054
+ this.implementation.restoreResetStatePreservingNextBundle(previousState);
3055
+ logger.error("Direct update failed to stage downloaded bundle: " + latest.toString());
3056
+ return false;
3057
+ }
2588
3058
  }
2589
3059
 
2590
3060
  if (this._reload()) {
@@ -2593,6 +3063,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
2593
3063
  }
2594
3064
 
2595
3065
  if (
3066
+ !this.reloadSupersededByPageReplacement.get() &&
2596
3067
  CapacitorUpdaterPlugin.shouldRestoreStateAfterPendingBundleReloadFailure(
2597
3068
  CapacitorUpdaterPlugin.reloadFailedDueToAppReadyTimeout.get(),
2598
3069
  latest,
@@ -2601,7 +3072,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
2601
3072
  false
2602
3073
  )
2603
3074
  ) {
2604
- this.implementation.restoreResetState(previousState);
3075
+ this.implementation.restoreResetStatePreservingNextBundle(previousState);
2605
3076
  this.restoreLiveBundleStateAfterFailedReload();
2606
3077
  }
2607
3078
  logger.error("Direct update reload failed after staging bundle: " + latest.toString());
@@ -2734,12 +3205,22 @@ public class CapacitorUpdaterPlugin extends Plugin {
2734
3205
  if (percent == 100) {
2735
3206
  final JSObject retDownloadComplete = new JSObject(ret, new String[] { "bundle" });
2736
3207
  this.notifyListeners("downloadComplete", retDownloadComplete, false);
2737
- this.implementation.sendStats("download_complete", bundleInfo.getVersionName());
3208
+ this.implementation.sendStats(
3209
+ "download_complete",
3210
+ bundleInfo.getVersionName(),
3211
+ "",
3212
+ java.util.Collections.singletonMap("attempt_id", id)
3213
+ );
2738
3214
  this.markDownloadStatPercent(id, 100);
2739
3215
  } else {
2740
3216
  final String statAction = this.nextDownloadStatAction(id, percent);
2741
3217
  if (statAction != null) {
2742
- this.implementation.sendStats(statAction, bundleInfo.getVersionName());
3218
+ this.implementation.sendStats(
3219
+ statAction,
3220
+ bundleInfo.getVersionName(),
3221
+ "",
3222
+ java.util.Collections.singletonMap("attempt_id", id)
3223
+ );
2743
3224
  }
2744
3225
  }
2745
3226
  } catch (final Exception e) {
@@ -2864,12 +3345,11 @@ public class CapacitorUpdaterPlugin extends Plugin {
2864
3345
  return;
2865
3346
  }
2866
3347
  this.implementation.customId = customId;
2867
- if (Boolean.TRUE.equals(this.persistCustomId)) {
2868
- if (customId.isEmpty()) {
2869
- this.editor.remove(CUSTOM_ID_PREF_KEY);
2870
- } else {
2871
- this.editor.putString(CUSTOM_ID_PREF_KEY, customId);
2872
- }
3348
+ if (customId.isEmpty()) {
3349
+ this.editor.remove(CUSTOM_ID_PREF_KEY);
3350
+ this.editor.apply();
3351
+ } else if (Boolean.TRUE.equals(this.persistCustomId)) {
3352
+ this.editor.putString(CUSTOM_ID_PREF_KEY, customId);
2873
3353
  this.editor.apply();
2874
3354
  }
2875
3355
  call.resolve();
@@ -3019,7 +3499,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
3019
3499
  }
3020
3500
  },
3021
3501
  CapacitorUpdaterPlugin.this.editor,
3022
- DEFAULT_CHANNEL_PREF_KEY
3502
+ DEFAULT_CHANNEL_PREF_KEY,
3503
+ DEFAULT_CHANNEL_FROM_SET_CHANNEL_PREF_KEY,
3504
+ CapacitorUpdaterPlugin.this.getConfig().getString("defaultChannel", "")
3023
3505
  )
3024
3506
  );
3025
3507
  } catch (final Exception e) {
@@ -3163,103 +3645,94 @@ public class CapacitorUpdaterPlugin extends Plugin {
3163
3645
  : "(function(){try{localStorage.removeItem('" +
3164
3646
  KEEP_URL_FLAG_KEY +
3165
3647
  "');}catch(e){}delete window.__capgoKeepUrlPathAfterReload;var evt;try{evt=new CustomEvent('CapacitorUpdaterKeepUrlPathAfterReload',{detail:{enabled:false}});}catch(err){evt=document.createEvent('CustomEvent');evt.initCustomEvent('CapacitorUpdaterKeepUrlPathAfterReload',false,false,{enabled:false});}window.dispatchEvent(evt);})();";
3166
- this.bridge.getWebView().post(() -> this.bridge.getWebView().evaluateJavascript(script, null));
3648
+ final Runnable syncFlag = () -> this.bridge.getWebView().evaluateJavascript(script, null);
3649
+ if (Looper.myLooper() == Looper.getMainLooper()) {
3650
+ syncFlag.run();
3651
+ } else {
3652
+ this.bridge.getWebView().post(syncFlag);
3653
+ }
3167
3654
  }
3168
3655
 
3169
- private void applyCurrentBundleToBridge() {
3170
- this.stampReadyGenerationBeforeReload();
3656
+ private boolean applyCurrentBundleToBridge() {
3171
3657
  final String path = this.implementation.getCurrentBundlePath();
3172
3658
  final boolean usingBuiltin = this.implementation.isUsingBuiltin();
3173
- if (this.keepUrlPathAfterReload) {
3174
- this.syncKeepUrlPathFlag(true);
3659
+ final android.webkit.WebView webView = this.bridge == null ? null : this.bridge.getWebView();
3660
+ if (webView == null) {
3661
+ logger.error("Cannot reload without a WebView");
3662
+ return false;
3175
3663
  }
3176
- logger.info("Reloading: " + path);
3177
-
3178
- AtomicReference<URL> url = new AtomicReference<>();
3179
- if (this.keepUrlPathAfterReload) {
3180
- try {
3181
- if (Looper.myLooper() != Looper.getMainLooper()) {
3182
- Semaphore mainThreadSemaphore = new Semaphore(0);
3183
- this.bridge.executeOnMainThread(() -> {
3184
- try {
3185
- if (this.bridge != null && this.bridge.getWebView() != null) {
3186
- String currentUrl = this.bridge.getWebView().getUrl();
3187
- if (currentUrl != null) {
3188
- url.set(new URL(currentUrl));
3189
- }
3190
- }
3191
- } catch (Exception e) {
3192
- logger.error("Error executing on main thread " + e.getMessage());
3193
- }
3194
- mainThreadSemaphore.release();
3195
- });
3196
-
3197
- // Add timeout to prevent indefinite blocking
3198
- if (!mainThreadSemaphore.tryAcquire(10, TimeUnit.SECONDS)) {
3199
- logger.error("Timeout waiting for main thread operation");
3200
- }
3201
- } else {
3202
- try {
3203
- if (this.bridge != null && this.bridge.getWebView() != null) {
3204
- String currentUrl = this.bridge.getWebView().getUrl();
3205
- if (currentUrl != null) {
3206
- url.set(new URL(currentUrl));
3207
- }
3208
- }
3209
- } catch (Exception e) {
3210
- logger.error("Error executing on main thread " + e.getMessage());
3664
+ // Reject the previous document while the main-thread reload is still queued.
3665
+ final int generation = this.armReloadReadyGuard();
3666
+ final Object dispatchLock = new Object();
3667
+ final FutureTask<Void> dispatch = new FutureTask<>(() -> {
3668
+ final boolean guardArmed = this.stampReadyGenerationBeforeReload(generation);
3669
+ String targetUrl = this.bridge.getAppUrl();
3670
+ if (this.keepUrlPathAfterReload) {
3671
+ this.syncKeepUrlPathFlag(true);
3672
+ try {
3673
+ final String currentUrl = webView.getUrl();
3674
+ if (currentUrl != null) {
3675
+ final URL appUrl = new URL(targetUrl);
3676
+ targetUrl = new URL(
3677
+ appUrl.getProtocol(),
3678
+ appUrl.getHost(),
3679
+ appUrl.getPort(),
3680
+ new URL(currentUrl).getPath()
3681
+ ).toString();
3211
3682
  }
3683
+ } catch (final MalformedURLException e) {
3684
+ logger.warn("Cannot preserve the current URL path: " + e.getMessage());
3212
3685
  }
3213
- } catch (InterruptedException e) {
3214
- logger.error("Error waiting for main thread or getting the current URL from webview " + e.getMessage());
3215
- Thread.currentThread().interrupt(); // Restore interrupted status
3216
3686
  }
3217
- }
3218
-
3219
- if (url.get() != null) {
3687
+ logger.info("Reloading: " + path);
3688
+ // Bridge.setServer*Path posts another load. Keep hosting and loadUrl in this dispatch
3689
+ // so automatic-install admission cannot be released between them.
3220
3690
  if (usingBuiltin) {
3221
3691
  this.bridge.getLocalServer().hostAssets(path);
3222
3692
  } else {
3223
3693
  this.bridge.getLocalServer().hostFiles(path);
3224
3694
  }
3225
-
3226
- try {
3227
- URL finalUrl = null;
3228
- finalUrl = new URL(this.bridge.getAppUrl());
3229
- finalUrl = new URL(finalUrl.getProtocol(), finalUrl.getHost(), finalUrl.getPort(), url.get().getPath());
3230
- URL finalUrl1 = finalUrl;
3231
- this.bridge.getWebView().post(() -> {
3232
- this.bridge.getWebView().loadUrl(finalUrl1.toString());
3233
- if (!this.keepUrlPathAfterReload) {
3234
- this.bridge.getWebView().clearHistory();
3235
- }
3236
- });
3237
- } catch (MalformedURLException e) {
3238
- logger.error("Cannot get finalUrl from capacitor bridge " + e.getMessage());
3239
-
3240
- if (usingBuiltin) {
3241
- this.bridge.setServerAssetPath(path);
3242
- } else {
3243
- this.bridge.setServerBasePath(path);
3244
- }
3695
+ webView.loadUrl(targetUrl);
3696
+ synchronized (this.readyGuardLock) {
3697
+ this.liveReadyPage = new ReadyPageState(path, generation, guardArmed);
3245
3698
  }
3246
- } else {
3247
- if (usingBuiltin) {
3248
- this.bridge.setServerAssetPath(path);
3249
- } else {
3250
- this.bridge.setServerBasePath(path);
3251
- }
3252
- if (this.bridge != null && this.bridge.getWebView() != null) {
3253
- this.bridge.getWebView().post(() -> {
3254
- if (this.bridge.getWebView() != null) {
3255
- this.bridge.getWebView().loadUrl(this.bridge.getAppUrl());
3256
- if (!this.keepUrlPathAfterReload) {
3257
- this.bridge.getWebView().clearHistory();
3258
- }
3699
+ if (!this.keepUrlPathAfterReload) {
3700
+ webView.clearHistory();
3701
+ }
3702
+ return null;
3703
+ });
3704
+ try {
3705
+ if (Looper.myLooper() == Looper.getMainLooper()) {
3706
+ dispatch.run();
3707
+ } else if (
3708
+ !webView.post(() -> {
3709
+ synchronized (dispatchLock) {
3710
+ dispatch.run();
3259
3711
  }
3260
- });
3712
+ })
3713
+ ) {
3714
+ logger.error("WebView rejected reload dispatch");
3715
+ return false;
3716
+ }
3717
+ dispatch.get(10, TimeUnit.SECONDS);
3718
+ return true;
3719
+ } catch (final InterruptedException e) {
3720
+ Thread.currentThread().interrupt();
3721
+ logger.error("Interrupted waiting for WebView reload dispatch");
3722
+ } catch (final ExecutionException | TimeoutException | RuntimeException e) {
3723
+ logger.error("WebView reload dispatch failed: " + e.getMessage());
3724
+ } finally {
3725
+ // Cancel a queued dispatch before releasing install admission. If it has started,
3726
+ // let its short native loadUrl call finish before another bundle can be staged.
3727
+ final boolean cancelled;
3728
+ synchronized (dispatchLock) {
3729
+ cancelled = dispatch.cancel(false);
3730
+ }
3731
+ if (cancelled) {
3732
+ this.restoreUndispatchedReadyGuard(generation);
3261
3733
  }
3262
3734
  }
3735
+ return false;
3263
3736
  }
3264
3737
 
3265
3738
  protected void restoreLiveBundleStateAfterFailedReload() {
@@ -3267,24 +3740,43 @@ public class CapacitorUpdaterPlugin extends Plugin {
3267
3740
  this.applyCurrentBundleToBridge();
3268
3741
  } catch (final Exception e) {
3269
3742
  logger.warn("Failed to restore live bundle after rejected reload: " + e.getMessage());
3743
+ } finally {
3744
+ // The prior watchdog may have expired or belong to an older page generation.
3745
+ // A rejected recovery dispatch still leaves the restored bundle needing validation.
3746
+ this.checkAppReady();
3270
3747
  }
3271
3748
  }
3272
3749
 
3273
3750
  protected boolean _reload() {
3751
+ CapacitorUpdaterPlugin.reloadFailedDueToAppReadyTimeout.set(false);
3752
+ this.reloadSupersededByPageReplacement.set(false);
3274
3753
  if (this.appInBackground) {
3275
3754
  return this.reloadInBackground();
3276
3755
  }
3277
- // Drop any launch pending wait; this reload owns notifyAppReady synchronization.
3278
- this.clearPendingNotifyAppReadyWait();
3279
- final int phase = this.semaphoreUp();
3280
- this.applyCurrentBundleToBridge();
3756
+ // Register reload ownership before a carried notification waiter can time out.
3757
+ final ReloadReadyWait readyWait = this.armReloadReadyWait();
3758
+ try {
3759
+ if (!this.applyCurrentBundleToBridge()) {
3760
+ this.cleanupTimedOutSemaphoreWait(readyWait.phase);
3761
+ return false;
3762
+ }
3281
3763
 
3282
- final long waitTimeMs = this.resolveAppReadyCheckTimeoutMs();
3283
- this.checkAppReady(waitTimeMs);
3284
- this.notifyListeners("appReloaded", new JSObject(), false);
3764
+ final long waitTimeMs = this.resolveAppReadyCheckTimeoutMs();
3765
+ this.checkAppReady(waitTimeMs);
3766
+ this.notifyListeners("appReloaded", new JSObject(), false);
3285
3767
 
3286
- // Wait for the reload to complete (until notifyAppReady is called)
3287
- return this.semaphoreWait(phase, waitTimeMs, true);
3768
+ // Retirement and timeout cleanup can advance a phase too. Only the page's
3769
+ // notifyAppReady acknowledgement makes this installation successful.
3770
+ final boolean advanced = this.semaphoreWait(readyWait.phase, waitTimeMs, true);
3771
+ if (advanced && !readyWait.notified) {
3772
+ this.reloadSupersededByPageReplacement.set(true);
3773
+ }
3774
+ return advanced && readyWait.notified;
3775
+ } finally {
3776
+ synchronized (this) {
3777
+ this.reloadReadyWaits.remove(readyWait.phase);
3778
+ }
3779
+ }
3288
3780
  }
3289
3781
 
3290
3782
  /**
@@ -3295,11 +3787,17 @@ public class CapacitorUpdaterPlugin extends Plugin {
3295
3787
  private boolean reloadInBackground() {
3296
3788
  logger.info("App is in background, reload does not wait for notifyAppReady");
3297
3789
  this.armPendingNotifyAppReadyWait();
3298
- return this.reloadWithoutWaitingForAppReady();
3790
+ if (this.reloadWithoutWaitingForAppReady()) {
3791
+ return true;
3792
+ }
3793
+ this.clearPendingNotifyAppReadyWait();
3794
+ return false;
3299
3795
  }
3300
3796
 
3301
3797
  protected boolean reloadWithoutWaitingForAppReady() {
3302
- this.applyCurrentBundleToBridge();
3798
+ if (!this.applyCurrentBundleToBridge()) {
3799
+ return false;
3800
+ }
3303
3801
 
3304
3802
  final long waitTimeMs = this.resolveAppReadyCheckTimeoutMs();
3305
3803
  this.checkAppReady(waitTimeMs);
@@ -3307,6 +3805,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
3307
3805
  return true;
3308
3806
  }
3309
3807
 
3808
+ /** Reloads the app, rejecting an incompatible pending bundle with VERSION_BELOW_NATIVE before changing state. */
3310
3809
  @PluginMethod
3311
3810
  public void reload(final PluginCall call) {
3312
3811
  startNewThread(() -> {
@@ -3315,6 +3814,14 @@ public class CapacitorUpdaterPlugin extends Plugin {
3315
3814
  final BundleInfo next = this.implementation.getNextBundle();
3316
3815
 
3317
3816
  if (!this.isPreviewSessionStateActive() && next != null && !next.isErrorStatus() && !next.getId().equals(current.getId())) {
3817
+ if (!next.isBuiltin()) {
3818
+ try {
3819
+ this.implementation.requireVersionNotBelowBuiltin(next.getVersionName());
3820
+ } catch (IOException e) {
3821
+ call.reject(e.getMessage(), "VERSION_BELOW_NATIVE", e);
3822
+ return;
3823
+ }
3824
+ }
3318
3825
  final CapgoUpdater.ResetState previousState = this.implementation.captureResetState();
3319
3826
  final String previousBundleName = this.implementation.getCurrentBundle().getVersionName();
3320
3827
  logger.info("Applying pending bundle before reload: " + next.getVersionName());
@@ -3338,6 +3845,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
3338
3845
  return;
3339
3846
  }
3340
3847
  if (
3848
+ !this.reloadSupersededByPageReplacement.get() &&
3341
3849
  CapacitorUpdaterPlugin.shouldRestoreStateAfterPendingBundleReloadFailure(
3342
3850
  CapacitorUpdaterPlugin.reloadFailedDueToAppReadyTimeout.get(),
3343
3851
  this.implementation.getCurrentBundle(),
@@ -3402,6 +3910,15 @@ public class CapacitorUpdaterPlugin extends Plugin {
3402
3910
  try {
3403
3911
  logger.info("Setting active bundle " + id);
3404
3912
  if (!this.implementation.set(id)) {
3913
+ final BundleInfo bundle = this.implementation.getBundleInfo(id);
3914
+ if (!bundle.isBuiltin() && this.implementation.bundleExists(id)) {
3915
+ try {
3916
+ this.implementation.requireVersionNotBelowBuiltin(bundle.getVersionName());
3917
+ } catch (IOException e) {
3918
+ call.reject(e.getMessage(), "VERSION_BELOW_NATIVE", e);
3919
+ return;
3920
+ }
3921
+ }
3405
3922
  logger.info("No such bundle " + id);
3406
3923
  call.reject("Update failed, id " + id + " does not exist.");
3407
3924
  return;
@@ -3412,7 +3929,11 @@ public class CapacitorUpdaterPlugin extends Plugin {
3412
3929
  logger.info("Preview session set active bundle " + id + " without waiting for preview app readiness");
3413
3930
  final BundleInfo bundle = this.implementation.getBundleInfo(id);
3414
3931
  this.recordPreviewBundle(bundle);
3415
- this.reloadWithoutWaitingForAppReady();
3932
+ if (!this.reloadWithoutWaitingForAppReady()) {
3933
+ logger.error("Reload failed after setting bundle " + id);
3934
+ call.reject("Reload failed after setting bundle " + id);
3935
+ return;
3936
+ }
3416
3937
  this.notifyBundleSet(bundle);
3417
3938
  this.showPreviewSessionNoticeIfNeeded();
3418
3939
  call.resolve();
@@ -4045,6 +4566,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4045
4566
  }
4046
4567
 
4047
4568
  this.editor.remove(DEFAULT_CHANNEL_PREF_KEY);
4569
+ this.editor.remove(DEFAULT_CHANNEL_FROM_SET_CHANNEL_PREF_KEY);
4048
4570
  this.implementation.defaultChannel = configDefaultChannel;
4049
4571
  this.editor.apply();
4050
4572
  logger.info("Restored defaultChannel after preview to config value");
@@ -4570,6 +5092,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4570
5092
  }
4571
5093
 
4572
5094
  private boolean performResetBody(final Boolean toLastSuccessful, final Boolean usePendingBundle, final boolean internal) {
5095
+ this.reloadSupersededByPageReplacement.set(false);
4573
5096
  final BundleInfo fallback = this.implementation.getFallbackBundle();
4574
5097
  final BundleInfo pending = this.implementation.getNextBundle();
4575
5098
  final CapgoUpdater.ResetState previousState = this.implementation.captureResetState();
@@ -4602,6 +5125,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4602
5125
  return true;
4603
5126
  }
4604
5127
  if (
5128
+ !this.reloadSupersededByPageReplacement.get() &&
4605
5129
  CapacitorUpdaterPlugin.shouldRestoreStateAfterPendingBundleReloadFailure(
4606
5130
  CapacitorUpdaterPlugin.reloadFailedDueToAppReadyTimeout.get(),
4607
5131
  this.implementation.getCurrentBundle(),
@@ -4632,6 +5156,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4632
5156
  }
4633
5157
  if (
4634
5158
  !internal &&
5159
+ !this.reloadSupersededByPageReplacement.get() &&
4635
5160
  CapacitorUpdaterPlugin.shouldRestoreStateAfterPendingBundleReloadFailure(
4636
5161
  CapacitorUpdaterPlugin.reloadFailedDueToAppReadyTimeout.get(),
4637
5162
  this.implementation.getCurrentBundle(),
@@ -4644,7 +5169,10 @@ public class CapacitorUpdaterPlugin extends Plugin {
4644
5169
  this.restoreLiveBundleStateAfterFailedReload();
4645
5170
  return false;
4646
5171
  }
4647
- if (!internal && CapacitorUpdaterPlugin.reloadFailedDueToAppReadyTimeout.get()) {
5172
+ if (
5173
+ this.reloadSupersededByPageReplacement.get() ||
5174
+ (!internal && CapacitorUpdaterPlugin.reloadFailedDueToAppReadyTimeout.get())
5175
+ ) {
4648
5176
  return false;
4649
5177
  }
4650
5178
  } else if (!internal) {
@@ -4665,6 +5193,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4665
5193
  }
4666
5194
  if (
4667
5195
  !internal &&
5196
+ !this.reloadSupersededByPageReplacement.get() &&
4668
5197
  CapacitorUpdaterPlugin.shouldRestoreStateAfterPendingBundleReloadFailure(
4669
5198
  CapacitorUpdaterPlugin.reloadFailedDueToAppReadyTimeout.get(),
4670
5199
  this.implementation.getCurrentBundle(),
@@ -4717,7 +5246,11 @@ public class CapacitorUpdaterPlugin extends Plugin {
4717
5246
  public void getNextBundle(final PluginCall call) {
4718
5247
  try {
4719
5248
  // Heals a next bundle left stored after it was activated (set() did not clear it before).
4720
- this.implementation.clearNextBundleIfCurrent();
5249
+ synchronized (this.automaticInstallLock) {
5250
+ if (!this.automaticInstallInProgress) {
5251
+ this.implementation.clearNextBundleIfCurrent();
5252
+ }
5253
+ }
4721
5254
  final BundleInfo bundle = this.implementation.getNextBundle();
4722
5255
  if (bundle == null) {
4723
5256
  call.resolve(null);
@@ -4843,14 +5376,75 @@ public class CapacitorUpdaterPlugin extends Plugin {
4843
5376
  );
4844
5377
  }
4845
5378
 
5379
+ private synchronized boolean stageBundleForReload(final java.util.function.BooleanSupplier stage) {
5380
+ final int previousGeneration = this.readyGeneration;
5381
+ final boolean previousGuardArmed = this.readyGuardArmed;
5382
+ this.armReadyGuard();
5383
+ boolean staged = false;
5384
+ try {
5385
+ staged = stage.getAsBoolean();
5386
+ return staged;
5387
+ } finally {
5388
+ if (!staged) {
5389
+ // No document was dispatched. The existing page must remain able to report ready.
5390
+ synchronized (this.readyGuardLock) {
5391
+ this.readyGeneration = previousGeneration;
5392
+ this.readyGuardArmed = previousGuardArmed;
5393
+ }
5394
+ }
5395
+ }
5396
+ }
5397
+
5398
+ private synchronized int armReloadReadyGuard() {
5399
+ final int generation = this.armReadyGuard();
5400
+ synchronized (this.automaticInstallLock) {
5401
+ if (this.automaticInstallInProgress && !this.watchdogRollbackInProgress) {
5402
+ this.automaticInstallPageGeneration = generation;
5403
+ }
5404
+ }
5405
+ return generation;
5406
+ }
5407
+
4846
5408
  private int armReadyGuard() {
4847
5409
  synchronized (this.readyGuardLock) {
5410
+ this.captureInitialReadyPage();
4848
5411
  this.readyGeneration = this.readyGeneration + 1;
4849
5412
  this.readyGuardArmed = true;
4850
5413
  return this.readyGeneration;
4851
5414
  }
4852
5415
  }
4853
5416
 
5417
+ private void captureInitialReadyPage() {
5418
+ synchronized (this.readyGuardLock) {
5419
+ if (this.liveReadyPage == null && this.implementation != null) {
5420
+ try {
5421
+ final String path = this.implementation.getCurrentBundlePath();
5422
+ if (path != null) {
5423
+ this.liveReadyPage = new ReadyPageState(path, this.readyGeneration, this.readyGuardArmed);
5424
+ }
5425
+ } catch (final RuntimeException e) {
5426
+ // Without a known live path, a failed dispatch must keep rejecting stale readiness.
5427
+ logger.warn("Cannot capture live page readiness: " + e.getMessage());
5428
+ }
5429
+ }
5430
+ }
5431
+ }
5432
+
5433
+ private synchronized void restoreUndispatchedReadyGuard(final int generation) {
5434
+ synchronized (this.readyGuardLock) {
5435
+ final ReadyPageState livePage = this.liveReadyPage;
5436
+ if (
5437
+ this.readyGeneration == generation &&
5438
+ livePage != null &&
5439
+ livePage.bundlePath.equals(this.implementation.getCurrentBundlePath())
5440
+ ) {
5441
+ // A staged replacement must be restored before its predecessor can report ready.
5442
+ this.readyGeneration = livePage.generation;
5443
+ this.readyGuardArmed = livePage.guardArmed;
5444
+ }
5445
+ }
5446
+ }
5447
+
4854
5448
  private void disarmReadyGuard(final int generation) {
4855
5449
  synchronized (this.readyGuardLock) {
4856
5450
  if (this.readyGeneration == generation) {
@@ -4860,18 +5454,17 @@ public class CapacitorUpdaterPlugin extends Plugin {
4860
5454
  }
4861
5455
  }
4862
5456
 
4863
- private void stampReadyGenerationBeforeReload() {
4864
- final int generation = this.armReadyGuard();
5457
+ private boolean stampReadyGenerationBeforeReload(final int generation) {
4865
5458
  final android.webkit.WebView webView = this.bridge != null ? this.bridge.getWebView() : null;
4866
5459
  if (webView == null) {
4867
5460
  this.disarmReadyGuard(generation);
4868
- return;
5461
+ return false;
4869
5462
  }
4870
- webView.post(() -> {
4871
- if (!this.installReadyGenerationScript(webView, generation)) {
4872
- this.disarmReadyGuard(generation);
4873
- }
4874
- });
5463
+ if (!this.installReadyGenerationScript(webView, generation)) {
5464
+ this.disarmReadyGuard(generation);
5465
+ return false;
5466
+ }
5467
+ return true;
4875
5468
  }
4876
5469
 
4877
5470
  private boolean installReadyGenerationScript(final android.webkit.WebView webView, final int generation) {
@@ -4914,7 +5507,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4914
5507
  }
4915
5508
 
4916
5509
  @PluginMethod
4917
- public void notifyAppReady(final PluginCall call) {
5510
+ public synchronized void notifyAppReady(final PluginCall call) {
4918
5511
  ensureBridgeSet();
4919
5512
  try {
4920
5513
  if (!this.acceptsReadyCall(call)) {
@@ -5193,7 +5786,86 @@ public class CapacitorUpdaterPlugin extends Plugin {
5193
5786
  boolean shouldSendStats,
5194
5787
  boolean shouldNotifyNoNeedUpdate
5195
5788
  ) {
5196
- this.consumeOnLaunchDirectUpdateAttempt(Boolean.TRUE.equals(plannedDirectUpdate));
5789
+ endBackGroundTaskWithNotif(
5790
+ msg,
5791
+ latestVersionName,
5792
+ current,
5793
+ error,
5794
+ plannedDirectUpdate,
5795
+ failureAction,
5796
+ failureEvent,
5797
+ shouldSendStats,
5798
+ shouldNotifyNoNeedUpdate,
5799
+ null
5800
+ );
5801
+ }
5802
+
5803
+ private void endBackGroundTaskWithNotif(
5804
+ String msg,
5805
+ String latestVersionName,
5806
+ BundleInfo current,
5807
+ Boolean error,
5808
+ Boolean plannedDirectUpdate,
5809
+ CapgoUpdater.BackgroundDownloadContext downloadContext
5810
+ ) {
5811
+ endBackGroundTaskWithNotif(
5812
+ msg,
5813
+ latestVersionName,
5814
+ current,
5815
+ error,
5816
+ plannedDirectUpdate,
5817
+ "download_fail",
5818
+ "downloadFailed",
5819
+ true,
5820
+ true,
5821
+ downloadContext
5822
+ );
5823
+ }
5824
+
5825
+ private void endBackGroundTaskWithNotif(
5826
+ String msg,
5827
+ String latestVersionName,
5828
+ BundleInfo current,
5829
+ Boolean error,
5830
+ Boolean plannedDirectUpdate,
5831
+ String failureAction,
5832
+ String failureEvent,
5833
+ boolean shouldSendStats,
5834
+ CapgoUpdater.BackgroundDownloadContext downloadContext
5835
+ ) {
5836
+ endBackGroundTaskWithNotif(
5837
+ msg,
5838
+ latestVersionName,
5839
+ current,
5840
+ error,
5841
+ plannedDirectUpdate,
5842
+ failureAction,
5843
+ failureEvent,
5844
+ shouldSendStats,
5845
+ true,
5846
+ downloadContext
5847
+ );
5848
+ }
5849
+
5850
+ private void endBackGroundTaskWithNotif(
5851
+ String msg,
5852
+ String latestVersionName,
5853
+ BundleInfo current,
5854
+ Boolean error,
5855
+ Boolean plannedDirectUpdate,
5856
+ String failureAction,
5857
+ String failureEvent,
5858
+ boolean shouldSendStats,
5859
+ boolean shouldNotifyNoNeedUpdate,
5860
+ CapgoUpdater.BackgroundDownloadContext downloadContext
5861
+ ) {
5862
+ synchronized (this) {
5863
+ if (!this.ownsBackgroundDownload(downloadContext)) {
5864
+ return;
5865
+ }
5866
+ this.consumeOnLaunchDirectUpdateAttempt(Boolean.TRUE.equals(plannedDirectUpdate));
5867
+ this.clearBackgroundDownloadState();
5868
+ }
5197
5869
  if (error) {
5198
5870
  logger.info(
5199
5871
  "endBackGroundTaskWithNotif error: " +
@@ -5208,24 +5880,207 @@ public class CapacitorUpdaterPlugin extends Plugin {
5208
5880
  }
5209
5881
  final JSObject ret = new JSObject();
5210
5882
  ret.put("version", latestVersionName);
5211
- this.notifyListeners(failureEvent, ret, false);
5883
+ if (!this.notifyBackgroundDownloadListeners(failureEvent, ret, downloadContext)) {
5884
+ return;
5885
+ }
5212
5886
  }
5213
5887
  if (shouldNotifyNoNeedUpdate) {
5214
5888
  final JSObject ret = new JSObject();
5215
5889
  ret.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
5216
- this.notifyListeners("noNeedUpdate", ret, false);
5890
+ if (!this.notifyBackgroundDownloadListeners("noNeedUpdate", ret, downloadContext)) {
5891
+ return;
5892
+ }
5217
5893
  }
5218
- this.sendReadyToJs(current, msg, plannedDirectUpdate);
5219
- this.backgroundDownloadTask = null;
5220
- this.downloadStartTimeMs = 0;
5894
+ this.sendReadyToJs(current, msg, plannedDirectUpdate, downloadContext);
5221
5895
  logger.info("endBackGroundTaskWithNotif " + msg);
5222
5896
  }
5223
5897
 
5898
+ private synchronized boolean notifyBackgroundDownloadListeners(
5899
+ final String event,
5900
+ final JSObject data,
5901
+ final CapgoUpdater.BackgroundDownloadContext downloadContext
5902
+ ) {
5903
+ if (!this.ownsBackgroundDownload(downloadContext)) {
5904
+ return false;
5905
+ }
5906
+ // Admit delivery before another thread can replace this check's ownership.
5907
+ this.notifyListeners(event, data, false);
5908
+ return true;
5909
+ }
5910
+
5911
+ private synchronized boolean queueBackgroundUpdateResponse(
5912
+ final String bundleId,
5913
+ final boolean plannedDirectUpdate,
5914
+ final CapgoUpdater.BackgroundDownloadContext downloadContext
5915
+ ) {
5916
+ if (!this.ownsBackgroundDownload(downloadContext)) {
5917
+ return false;
5918
+ }
5919
+ this.consumeOnLaunchDirectUpdateAttempt(plannedDirectUpdate);
5920
+ this.clearBackgroundDownloadState();
5921
+ this.acceptBackgroundUpdate(downloadContext);
5922
+ this.implementation.setNextBundle(bundleId);
5923
+ // A current response still completes readiness if the bundle is no longer queueable.
5924
+ return true;
5925
+ }
5926
+
5927
+ /** Returns false when the current response must defer for its deadline or an active install. */
5928
+ private boolean tryInstallBackgroundUpdateResponse(
5929
+ final BundleInfo bundle,
5930
+ final CapgoUpdater.BackgroundDownloadContext downloadContext
5931
+ ) {
5932
+ boolean installAdmitted = false;
5933
+ boolean installed = false;
5934
+ try {
5935
+ final CapgoUpdater.ResetState previousState;
5936
+ final String previousBundleName;
5937
+ final boolean staged;
5938
+ synchronized (this) {
5939
+ if (!this.ownsBackgroundDownload(downloadContext)) {
5940
+ return true;
5941
+ }
5942
+ if (!this.claimDirectUpdateInstall(downloadContext.timeoutGeneration, bundle)) {
5943
+ return false;
5944
+ }
5945
+ installAdmitted = true;
5946
+ this.acceptBackgroundUpdate(downloadContext);
5947
+ previousState = this.implementation.captureResetState();
5948
+ previousBundleName = this.implementation.getCurrentBundle().getVersionName();
5949
+ this.consumeOnLaunchDirectUpdateAttempt(true);
5950
+ this.clearBackgroundDownloadState();
5951
+ staged = this.stageBundleForReload(() -> {
5952
+ if (bundle.isBuiltin()) {
5953
+ this.implementation.prepareBuiltinTransition();
5954
+ return true;
5955
+ }
5956
+ return this.implementation.set(bundle);
5957
+ });
5958
+ }
5959
+ // Reload can wait for the bridge; it must not hold the ownership monitor.
5960
+ installed = staged && this.reloadAutomaticBundle(bundle, previousState);
5961
+ if (installed) {
5962
+ if (bundle.isBuiltin()) {
5963
+ this.implementation.finalizeBuiltinUpdate(previousBundleName);
5964
+ } else {
5965
+ this.implementation.clearNextBundleIfMatches(bundle.getId());
5966
+ this.notifyBundleSet(bundle);
5967
+ }
5968
+ }
5969
+ this.endBackGroundTaskWithNotif(
5970
+ installed ? (bundle.isBuiltin() ? "Updated to builtin version" : "Update installed") : "Update install failed",
5971
+ bundle.getVersionName(),
5972
+ bundle.isBuiltin() ? this.implementation.getCurrentBundle() : bundle,
5973
+ !installed,
5974
+ true,
5975
+ downloadContext
5976
+ );
5977
+ return true;
5978
+ } finally {
5979
+ if (installAdmitted) {
5980
+ this.releaseAutomaticInstall();
5981
+ this.installNextIfInBackground(installed ? null : bundle.getId());
5982
+ }
5983
+ }
5984
+ }
5985
+
5986
+ private boolean reloadAutomaticBundle(final BundleInfo bundle, final CapgoUpdater.ResetState previousState) {
5987
+ boolean reloaded = false;
5988
+ try {
5989
+ reloaded = this._reload();
5990
+ return reloaded;
5991
+ } finally {
5992
+ if (
5993
+ !reloaded &&
5994
+ !this.reloadSupersededByPageReplacement.get() &&
5995
+ CapacitorUpdaterPlugin.shouldRestoreStateAfterPendingBundleReloadFailure(
5996
+ CapacitorUpdaterPlugin.reloadFailedDueToAppReadyTimeout.get(),
5997
+ this.implementation.getCurrentBundle(),
5998
+ false,
5999
+ bundle,
6000
+ this.isPreviewSessionStateActive()
6001
+ )
6002
+ ) {
6003
+ this.implementation.restoreResetStatePreservingNextBundle(previousState);
6004
+ this.restoreLiveBundleStateAfterFailedReload();
6005
+ }
6006
+ }
6007
+ }
6008
+
6009
+ private void endFailedBackgroundDownload(
6010
+ final String latestVersionName,
6011
+ final boolean plannedDirectUpdate,
6012
+ final CapgoUpdater.BackgroundDownloadContext downloadContext
6013
+ ) {
6014
+ final BundleInfo current;
6015
+ synchronized (this) {
6016
+ if (!this.ownsBackgroundDownload(downloadContext)) {
6017
+ return;
6018
+ }
6019
+ current = this.implementation.getCurrentBundle();
6020
+ this.consumeOnLaunchDirectUpdateAttempt(plannedDirectUpdate);
6021
+ this.implementation.directUpdate = false;
6022
+ this.clearBackgroundDownloadState();
6023
+ }
6024
+ this.implementation.sendStats("download_fail", current.getVersionName());
6025
+ final JSObject failure = new JSObject();
6026
+ failure.put("version", latestVersionName);
6027
+ if (!this.notifyBackgroundDownloadListeners("downloadFailed", failure, downloadContext)) {
6028
+ return;
6029
+ }
6030
+ final JSObject noUpdate = new JSObject();
6031
+ noUpdate.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
6032
+ if (!this.notifyBackgroundDownloadListeners("noNeedUpdate", noUpdate, downloadContext)) {
6033
+ return;
6034
+ }
6035
+ this.sendReadyToJs(current, "Error downloading file", plannedDirectUpdate, downloadContext);
6036
+ }
6037
+
6038
+ private synchronized boolean queueDeferredDirectUpdate(
6039
+ final BundleInfo latest,
6040
+ final Thread downloadTask,
6041
+ final CapgoUpdater.BackgroundDownloadContext downloadContext
6042
+ ) {
6043
+ if (!this.ownsBackgroundDownload(downloadContext)) {
6044
+ // A pending or failed check does not supersede accepted work. Preserve its result,
6045
+ // without changing that check's readiness, timer, direct-install plan, or newer queue.
6046
+ return (
6047
+ downloadContext != null &&
6048
+ this.backgroundUpdateContext == downloadContext &&
6049
+ this.implementation.setNextBundleIfEmpty(latest.getId())
6050
+ );
6051
+ }
6052
+ if (!this.clearDirectUpdateDownloadState(downloadTask, downloadContext)) {
6053
+ return false;
6054
+ }
6055
+ this.implementation.setNextBundle(latest.getId());
6056
+ return true;
6057
+ }
6058
+
6059
+ private synchronized boolean clearDirectUpdateDownloadState(
6060
+ final Thread downloadTask,
6061
+ final CapgoUpdater.BackgroundDownloadContext downloadContext
6062
+ ) {
6063
+ if (!this.ownsBackgroundDownload(downloadContext) || this.backgroundDownloadTask != downloadTask) {
6064
+ // The newer cycle owns direct-update state and will emit appReady/hide its splash.
6065
+ logger.info("Preserving background download state owned by a newer update check");
6066
+ return false;
6067
+ }
6068
+ this.implementation.directUpdate = false;
6069
+ this.clearBackgroundDownloadState();
6070
+ return true;
6071
+ }
6072
+
5224
6073
  private void clearBackgroundDownloadState() {
5225
6074
  this.backgroundDownloadTask = null;
5226
6075
  this.downloadStartTimeMs = 0;
5227
6076
  }
5228
6077
 
6078
+ private synchronized void clearBackgroundDownloadState(final CapgoUpdater.BackgroundDownloadContext downloadContext) {
6079
+ if (this.ownsBackgroundDownload(downloadContext)) {
6080
+ this.clearBackgroundDownloadState();
6081
+ }
6082
+ }
6083
+
5229
6084
  private boolean isDownloadStuckOrTimedOut() {
5230
6085
  if (this.backgroundDownloadTask == null || !this.backgroundDownloadTask.isAlive()) {
5231
6086
  return false;
@@ -5288,8 +6143,17 @@ public class CapacitorUpdaterPlugin extends Plugin {
5288
6143
  logger.info("Download already in progress, skipping duplicate download request");
5289
6144
  return this.backgroundDownloadTask;
5290
6145
  }
6146
+ final long timeoutGeneration = this.getSplashscreenTimeoutGeneration();
5291
6147
  final boolean plannedDirectUpdate = this.shouldUseDirectUpdate();
5292
- final boolean initialDirectUpdateAllowed = this.isDirectUpdateCurrentlyAllowed(plannedDirectUpdate);
6148
+ final boolean initialDirectUpdateAllowed = this.isDirectUpdateCurrentlyAllowed(plannedDirectUpdate, timeoutGeneration);
6149
+ final CapgoUpdater.BackgroundDownloadContext downloadContext = new CapgoUpdater.BackgroundDownloadContext(
6150
+ timeoutGeneration,
6151
+ initialDirectUpdateAllowed,
6152
+ ++this.backgroundCheckSequence
6153
+ );
6154
+ this.backgroundDownloadContext = downloadContext;
6155
+ // Download identity survives reuse; readiness belongs to each individual check.
6156
+ this.backgroundReadyState = new BackgroundReadyState(this.backgroundReadyState.waitPhase);
5293
6157
  final String messageUpdate = initialDirectUpdateAllowed
5294
6158
  ? "Update will occur now."
5295
6159
  : this.shouldAutoSetNextBundle()
@@ -5297,18 +6161,24 @@ public class CapacitorUpdaterPlugin extends Plugin {
5297
6161
  : "Update will be downloaded and made available.";
5298
6162
  Thread newTask = startNewThread(() -> {
5299
6163
  if (CapacitorUpdaterPlugin.this.shouldBlockAutoUpdateForPreviewSession()) {
5300
- CapacitorUpdaterPlugin.this.clearBackgroundDownloadState();
6164
+ CapacitorUpdaterPlugin.this.clearBackgroundDownloadState(downloadContext);
5301
6165
  return;
5302
6166
  }
5303
6167
  logger.info("Check for update via: " + CapacitorUpdaterPlugin.this.updateUrl);
5304
6168
  try {
5305
6169
  CapacitorUpdaterPlugin.this.implementation.getLatest(CapacitorUpdaterPlugin.this.updateUrl, null, (res) -> {
6170
+ if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6171
+ return;
6172
+ }
5306
6173
  if (CapacitorUpdaterPlugin.this.shouldBlockAutoUpdateForPreviewSession()) {
5307
- CapacitorUpdaterPlugin.this.clearBackgroundDownloadState();
6174
+ CapacitorUpdaterPlugin.this.clearBackgroundDownloadState(downloadContext);
5308
6175
  return;
5309
6176
  }
5310
6177
  JSObject jsRes = InternalUtils.mapToJSObject(res);
5311
6178
  final BundleInfo currentBeforeCleanup = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
6179
+ if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6180
+ return;
6181
+ }
5312
6182
 
5313
6183
  // Handle network errors and other failures first
5314
6184
  if (jsRes.has("error") || jsRes.has("kind")) {
@@ -5325,6 +6195,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
5325
6195
  latestVersion,
5326
6196
  currentBeforeCleanup
5327
6197
  );
6198
+ if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6199
+ return;
6200
+ }
5328
6201
  CapacitorUpdaterPlugin.this.notifyBreakingEventsIfNeeded(
5329
6202
  jsRes,
5330
6203
  jsRes.has("version") ? jsRes.getString("version") : ""
@@ -5359,46 +6232,57 @@ public class CapacitorUpdaterPlugin extends Plugin {
5359
6232
  plannedDirectUpdate,
5360
6233
  "download_fail",
5361
6234
  "downloadFailed",
5362
- false
6235
+ false,
6236
+ downloadContext
5363
6237
  );
5364
6238
  return;
5365
6239
  }
5366
6240
  try {
5367
6241
  // File mutations wait here. getLatest already ran in parallel with cleanup.
5368
6242
  waitForCleanupIfNeeded();
6243
+ if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6244
+ return;
6245
+ }
5369
6246
  final BundleInfo current = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
5370
6247
  final String latestVersionName = jsRes.getString("version");
5371
6248
 
5372
6249
  if ("builtin".equals(latestVersionName)) {
5373
6250
  logger.info("Latest version is builtin");
5374
- final boolean directUpdateAllowedNow = CapacitorUpdaterPlugin.this.isDirectUpdateCurrentlyAllowed(
5375
- plannedDirectUpdate
5376
- );
5377
- if (directUpdateAllowedNow) {
5378
- logger.info("Direct update to builtin version");
5379
- this._reset(false, false);
5380
- CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
5381
- "Updated to builtin version",
5382
- latestVersionName,
5383
- CapacitorUpdaterPlugin.this.implementation.getCurrentBundle(),
5384
- false,
5385
- true
5386
- );
5387
- } else if (CapacitorUpdaterPlugin.this.shouldAutoSetNextBundle()) {
5388
- if (plannedDirectUpdate && !directUpdateAllowedNow) {
5389
- logger.info(
5390
- "Direct update skipped because splashscreen timeout occurred. Update will be applied later."
5391
- );
6251
+ if (
6252
+ plannedDirectUpdate &&
6253
+ CapacitorUpdaterPlugin.this.delayUpdateUtils
6254
+ .parseDelayConditions(prefs.getString(DelayUpdateUtils.DELAY_CONDITION_PREFERENCES, "[]"))
6255
+ .isEmpty() &&
6256
+ CapacitorUpdaterPlugin.this.tryInstallBackgroundUpdateResponse(
6257
+ CapacitorUpdaterPlugin.this.implementation.getBundleInfo(BundleInfo.ID_BUILTIN),
6258
+ downloadContext
6259
+ )
6260
+ ) {
6261
+ return;
6262
+ }
6263
+ if (CapacitorUpdaterPlugin.this.shouldAutoSetNextBundle()) {
6264
+ if (plannedDirectUpdate) {
6265
+ logger.info("Direct installation is unavailable. Update will be applied later.");
5392
6266
  }
5393
6267
  logger.info("Setting next bundle to builtin");
5394
- CapacitorUpdaterPlugin.this.implementation.setNextBundle(BundleInfo.ID_BUILTIN);
6268
+ if (
6269
+ !CapacitorUpdaterPlugin.this.queueBackgroundUpdateResponse(
6270
+ BundleInfo.ID_BUILTIN,
6271
+ plannedDirectUpdate,
6272
+ downloadContext
6273
+ )
6274
+ ) {
6275
+ return;
6276
+ }
5395
6277
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
5396
6278
  "Next update will be to builtin version",
5397
6279
  latestVersionName,
5398
6280
  current,
5399
6281
  false,
5400
- plannedDirectUpdate
6282
+ plannedDirectUpdate,
6283
+ downloadContext
5401
6284
  );
6285
+ CapacitorUpdaterPlugin.this.installNextIfInBackground();
5402
6286
  } else {
5403
6287
  logger.info("autoUpdate is set to onlyDownload, builtin version will not be set as next bundle");
5404
6288
  final boolean builtinUpdateAvailable = !current.isBuiltin();
@@ -5408,6 +6292,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
5408
6292
  BundleInfo.ID_BUILTIN
5409
6293
  );
5410
6294
  ret.put("bundle", InternalUtils.mapToJSObject(builtinBundle.toJSONMap()));
6295
+ if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6296
+ return;
6297
+ }
5411
6298
  CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, false);
5412
6299
  }
5413
6300
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
@@ -5419,7 +6306,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
5419
6306
  "download_fail",
5420
6307
  "downloadFailed",
5421
6308
  true,
5422
- !builtinUpdateAvailable
6309
+ !builtinUpdateAvailable,
6310
+ downloadContext
5423
6311
  );
5424
6312
  }
5425
6313
  return;
@@ -5433,7 +6321,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
5433
6321
  current.getVersionName(),
5434
6322
  current,
5435
6323
  true,
5436
- plannedDirectUpdate
6324
+ plannedDirectUpdate,
6325
+ downloadContext
5437
6326
  );
5438
6327
  return;
5439
6328
  }
@@ -5450,10 +6339,16 @@ public class CapacitorUpdaterPlugin extends Plugin {
5450
6339
  latestVersionName,
5451
6340
  current,
5452
6341
  true,
5453
- plannedDirectUpdate
6342
+ plannedDirectUpdate,
6343
+ downloadContext
5454
6344
  );
5455
6345
  return;
5456
6346
  }
6347
+ // Reuse the observer and original deadline of work already admitted through the download gates.
6348
+ if (CapacitorUpdaterPlugin.this.implementation.reuseBackgroundDownload(latestVersionName, downloadContext)) {
6349
+ logger.info("Reusing automatic download for version: " + latestVersionName);
6350
+ return;
6351
+ }
5457
6352
  final BundleInfo latest = CapacitorUpdaterPlugin.this.implementation.getBundleInfoByName(latestVersionName);
5458
6353
  if (latest != null) {
5459
6354
  final JSObject ret = new JSObject();
@@ -5465,7 +6360,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
5465
6360
  latestVersionName,
5466
6361
  current,
5467
6362
  true,
5468
- plannedDirectUpdate
6363
+ plannedDirectUpdate,
6364
+ downloadContext
5469
6365
  );
5470
6366
  return;
5471
6367
  }
@@ -5478,7 +6374,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
5478
6374
  ) {
5479
6375
  logger.info("Latest bundle already exists and download is NOT required. " + messageUpdate);
5480
6376
  final boolean directUpdateAllowedNow = CapacitorUpdaterPlugin.this.isDirectUpdateCurrentlyAllowed(
5481
- plannedDirectUpdate
6377
+ plannedDirectUpdate,
6378
+ timeoutGeneration
5482
6379
  );
5483
6380
  if (directUpdateAllowedNow) {
5484
6381
  String delayUpdatePreferences = prefs.getString(DelayUpdateUtils.DELAY_CONDITION_PREFERENCES, "[]");
@@ -5492,47 +6389,46 @@ public class CapacitorUpdaterPlugin extends Plugin {
5492
6389
  latestVersionName,
5493
6390
  latest,
5494
6391
  false,
5495
- plannedDirectUpdate
6392
+ plannedDirectUpdate,
6393
+ downloadContext
5496
6394
  );
5497
6395
  return;
5498
6396
  }
6397
+ if (CapacitorUpdaterPlugin.this.tryInstallBackgroundUpdateResponse(latest, downloadContext)) {
6398
+ return;
6399
+ }
6400
+ }
6401
+ if (CapacitorUpdaterPlugin.this.shouldAutoSetNextBundle()) {
6402
+ if (plannedDirectUpdate) {
6403
+ logger.info("Direct installation is unavailable. Update will install on next background.");
6404
+ }
5499
6405
  if (
5500
- CapacitorUpdaterPlugin.this.implementation.set(latest) && CapacitorUpdaterPlugin.this._reload()
6406
+ !CapacitorUpdaterPlugin.this.queueBackgroundUpdateResponse(
6407
+ latest.getId(),
6408
+ plannedDirectUpdate,
6409
+ downloadContext
6410
+ )
5501
6411
  ) {
5502
- CapacitorUpdaterPlugin.this.notifyBundleSet(latest);
5503
- CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
5504
- "Update installed",
5505
- latestVersionName,
5506
- latest,
5507
- false,
5508
- true
5509
- );
5510
- } else {
5511
- CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
5512
- "Update install failed",
5513
- latestVersionName,
5514
- latest,
5515
- true,
5516
- true
5517
- );
6412
+ return;
5518
6413
  }
5519
- } else if (CapacitorUpdaterPlugin.this.shouldAutoSetNextBundle()) {
5520
- if (plannedDirectUpdate && !directUpdateAllowedNow) {
5521
- logger.info(
5522
- "Direct update skipped because splashscreen timeout occurred. Update will install on next background."
5523
- );
6414
+ if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6415
+ return;
5524
6416
  }
5525
6417
  CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, false);
5526
- CapacitorUpdaterPlugin.this.implementation.setNextBundle(latest.getId());
5527
6418
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
5528
6419
  "update downloaded, will install next background",
5529
6420
  latestVersionName,
5530
6421
  latest,
5531
6422
  false,
5532
- plannedDirectUpdate
6423
+ plannedDirectUpdate,
6424
+ downloadContext
5533
6425
  );
6426
+ CapacitorUpdaterPlugin.this.installNextIfInBackground();
5534
6427
  } else {
5535
6428
  logger.info("autoUpdate is set to onlyDownload, downloaded update will not be set as next bundle");
6429
+ if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6430
+ return;
6431
+ }
5536
6432
  CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, false);
5537
6433
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
5538
6434
  "update downloaded, autoUpdate onlyDownload",
@@ -5543,21 +6439,30 @@ public class CapacitorUpdaterPlugin extends Plugin {
5543
6439
  "download_fail",
5544
6440
  "downloadFailed",
5545
6441
  true,
5546
- false
6442
+ false,
6443
+ downloadContext
5547
6444
  );
5548
6445
  }
5549
6446
  return;
5550
6447
  }
5551
6448
  if (latest.isDeleted()) {
5552
6449
  logger.info("Latest bundle already exists and will be deleted, download will overwrite it.");
6450
+ if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6451
+ return;
6452
+ }
5553
6453
  try {
5554
- final Boolean deleted = CapacitorUpdaterPlugin.this.implementation.delete(latest.getId(), true);
6454
+ final boolean deleted = CapacitorUpdaterPlugin.this.implementation.deleteDeletedBundle(
6455
+ latest.getId()
6456
+ );
5555
6457
  if (deleted) {
5556
6458
  logger.info("Failed bundle deleted: " + latest.getVersionName());
5557
6459
  }
5558
6460
  } catch (final IOException e) {
5559
6461
  logger.error("Failed to delete failed bundle: " + latest.getVersionName() + " " + e.getMessage());
5560
6462
  }
6463
+ if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6464
+ return;
6465
+ }
5561
6466
  }
5562
6467
  }
5563
6468
  // The store refuses these downloads without a callback, so end the cycle here
@@ -5572,7 +6477,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
5572
6477
  latestVersionName,
5573
6478
  current,
5574
6479
  true,
5575
- plannedDirectUpdate
6480
+ plannedDirectUpdate,
6481
+ downloadContext
5576
6482
  );
5577
6483
  return;
5578
6484
  }
@@ -5580,14 +6486,27 @@ public class CapacitorUpdaterPlugin extends Plugin {
5580
6486
  latest != null &&
5581
6487
  BundleStatus.DOWNLOADING == latest.getStatus() &&
5582
6488
  CapacitorUpdaterPlugin.this.isVersionDownloadInProgress(latest.getVersionName());
5583
- CapacitorUpdaterPlugin.this.consumeOnLaunchDirectUpdateAttempt(plannedDirectUpdate);
5584
- CapacitorUpdaterPlugin.this.implementation.directUpdate = retryingInFlightDownload
5585
- ? Boolean.TRUE.equals(CapacitorUpdaterPlugin.this.implementation.directUpdate) || initialDirectUpdateAllowed
5586
- : initialDirectUpdateAllowed;
6489
+ synchronized (CapacitorUpdaterPlugin.this) {
6490
+ if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6491
+ return;
6492
+ }
6493
+ CapacitorUpdaterPlugin.this.consumeOnLaunchDirectUpdateAttempt(plannedDirectUpdate);
6494
+ final boolean directUpdateStillAllowed = CapacitorUpdaterPlugin.this.isDirectUpdateCurrentlyAllowed(
6495
+ initialDirectUpdateAllowed,
6496
+ timeoutGeneration
6497
+ );
6498
+ CapacitorUpdaterPlugin.this.implementation.directUpdate = retryingInFlightDownload
6499
+ ? Boolean.TRUE.equals(CapacitorUpdaterPlugin.this.implementation.directUpdate) ||
6500
+ directUpdateStillAllowed
6501
+ : directUpdateStillAllowed;
6502
+ }
5587
6503
  startNewThread(() -> {
5588
6504
  try {
6505
+ if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6506
+ return;
6507
+ }
5589
6508
  if (CapacitorUpdaterPlugin.this.shouldBlockAutoUpdateForPreviewSession()) {
5590
- CapacitorUpdaterPlugin.this.clearBackgroundDownloadState();
6509
+ CapacitorUpdaterPlugin.this.clearBackgroundDownloadState(downloadContext);
5591
6510
  return;
5592
6511
  }
5593
6512
  logger.info(
@@ -5603,36 +6522,30 @@ public class CapacitorUpdaterPlugin extends Plugin {
5603
6522
  final String sessionKey = jsRes.has("sessionKey") ? jsRes.getString("sessionKey") : "";
5604
6523
  final String checksum = jsRes.has("checksum") ? jsRes.getString("checksum") : "";
5605
6524
 
5606
- if (jsRes.has("manifest")) {
5607
- // Handle manifest-based download
5608
- JSONArray manifest = jsRes.getJSONArray("manifest");
6525
+ final JSONArray manifest = jsRes.has("manifest") ? jsRes.getJSONArray("manifest") : null;
6526
+ final CapgoUpdater.BackgroundDownloadResult result =
5609
6527
  CapacitorUpdaterPlugin.this.implementation.downloadBackground(
5610
6528
  url,
5611
6529
  latestVersionName,
5612
6530
  sessionKey,
5613
6531
  checksum,
5614
6532
  manifest,
5615
- CapacitorUpdaterPlugin.this.shouldAutoSetNextBundle()
6533
+ CapacitorUpdaterPlugin.this.shouldAutoSetNextBundle(),
6534
+ downloadContext
5616
6535
  );
5617
- } else {
5618
- // Handle single file download (existing code)
5619
- CapacitorUpdaterPlugin.this.implementation.downloadBackground(
5620
- url,
6536
+ if (result.status == CapgoUpdater.BackgroundDownloadResult.Status.NOT_STARTED) {
6537
+ CapacitorUpdaterPlugin.this.endFailedBackgroundDownload(
5621
6538
  latestVersionName,
5622
- sessionKey,
5623
- checksum,
5624
- null,
5625
- CapacitorUpdaterPlugin.this.shouldAutoSetNextBundle()
6539
+ plannedDirectUpdate,
6540
+ downloadContext
5626
6541
  );
5627
6542
  }
5628
6543
  } catch (final Exception e) {
5629
6544
  logger.error("error downloading file " + e.getMessage());
5630
- CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
5631
- "Error downloading file",
6545
+ CapacitorUpdaterPlugin.this.endFailedBackgroundDownload(
5632
6546
  latestVersionName,
5633
- CapacitorUpdaterPlugin.this.implementation.getCurrentBundle(),
5634
- true,
5635
- plannedDirectUpdate
6547
+ plannedDirectUpdate,
6548
+ downloadContext
5636
6549
  );
5637
6550
  }
5638
6551
  });
@@ -5643,7 +6556,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
5643
6556
  latestVersionName,
5644
6557
  current,
5645
6558
  false,
5646
- plannedDirectUpdate
6559
+ plannedDirectUpdate,
6560
+ downloadContext
5647
6561
  );
5648
6562
  }
5649
6563
  } catch (final Exception e) {
@@ -5653,7 +6567,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
5653
6567
  currentBeforeCleanup.getVersionName(),
5654
6568
  currentBeforeCleanup,
5655
6569
  true,
5656
- plannedDirectUpdate
6570
+ plannedDirectUpdate,
6571
+ downloadContext
5657
6572
  );
5658
6573
  }
5659
6574
  });
@@ -5665,7 +6580,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
5665
6580
  current.getVersionName(),
5666
6581
  current,
5667
6582
  true,
5668
- plannedDirectUpdate
6583
+ plannedDirectUpdate,
6584
+ downloadContext
5669
6585
  );
5670
6586
  }
5671
6587
  });
@@ -5680,60 +6596,150 @@ public class CapacitorUpdaterPlugin extends Plugin {
5680
6596
  * user would open the old version once more. Install it now, like a background transition.
5681
6597
  */
5682
6598
  void installNextIfInBackground() {
6599
+ this.installNextIfInBackground(null);
6600
+ }
6601
+
6602
+ private void installNextIfInBackground(final String excludedBundleId) {
5683
6603
  if (!this.appInBackground) {
5684
6604
  return;
5685
6605
  }
5686
6606
  logger.info("Next bundle downloaded while in background, installing it now");
5687
- this.installNext();
6607
+ this.installNext(excludedBundleId);
5688
6608
  }
5689
6609
 
5690
- private void installNext() {
5691
- try {
5692
- if (this.shouldBlockAutoUpdateForPreviewSession()) {
5693
- return;
6610
+ private BundleInfo claimNextBundleInstall(final String excludedBundleId) {
6611
+ synchronized (this.automaticInstallLock) {
6612
+ if (this.automaticInstallInProgress || this.watchdogRollbackInProgress || this.shouldBlockAutoUpdateForPreviewSession()) {
6613
+ return null;
5694
6614
  }
5695
- String delayUpdatePreferences = prefs.getString(DelayUpdateUtils.DELAY_CONDITION_PREFERENCES, "[]");
5696
- ArrayList<DelayCondition> delayConditionList = delayUpdateUtils.parseDelayConditions(delayUpdatePreferences);
5697
- if (!delayConditionList.isEmpty()) {
6615
+ final String delayUpdatePreferences = this.prefs.getString(DelayUpdateUtils.DELAY_CONDITION_PREFERENCES, "[]");
6616
+ final ArrayList<DelayCondition> delayConditions = this.delayUpdateUtils.parseDelayConditions(delayUpdatePreferences);
6617
+ if (!delayConditions.isEmpty()) {
5698
6618
  logger.info("Update delayed until delay conditions met");
5699
- return;
6619
+ return null;
5700
6620
  }
5701
6621
  final BundleInfo current = this.implementation.getCurrentBundle();
5702
6622
  final BundleInfo next = this.implementation.getNextBundle();
6623
+ if (next == null || next.isErrorStatus() || next.getId().equals(current.getId()) || next.getId().equals(excludedBundleId)) {
6624
+ return null;
6625
+ }
6626
+ if (
6627
+ next.isBuiltin() &&
6628
+ !this.implementation.admitBuiltinInstall(() -> {
6629
+ final BundleInfo queued = this.implementation.getNextBundle();
6630
+ return queued != null && queued.isBuiltin();
6631
+ })
6632
+ ) {
6633
+ return null;
6634
+ }
6635
+ this.automaticInstallInProgress = true;
6636
+ this.automaticInstallPageGeneration = -1;
6637
+ return next;
6638
+ }
6639
+ }
6640
+
6641
+ private void releaseAutomaticInstall() {
6642
+ synchronized (this.automaticInstallLock) {
6643
+ this.automaticInstallInProgress = false;
6644
+ this.automaticInstallPageGeneration = -1;
6645
+ }
6646
+ }
6647
+
6648
+ private void installNext() {
6649
+ this.installNext(null);
6650
+ }
5703
6651
 
5704
- if (next != null && !next.isErrorStatus() && !next.getId().equals(current.getId())) {
5705
- // There is a next bundle waiting for activation
6652
+ private void installNext(final String excludedBundleId) {
6653
+ try {
6654
+ final BundleInfo next = this.claimNextBundleInstall(excludedBundleId);
6655
+ if (next == null) {
6656
+ return;
6657
+ }
6658
+ boolean dispatched = false;
6659
+ try {
5706
6660
  logger.debug("Next bundle is: " + next.getVersionName());
5707
6661
  startNewThread(() -> {
5708
- if (this.implementation.set(next) && this._reload()) {
5709
- logger.info("Updated to bundle: " + next.getVersionName());
5710
- this.notifyBundleSet(next);
5711
- this.implementation.setNextBundle(null);
5712
- } else {
5713
- logger.error("Update to bundle: " + next.getVersionName() + " Failed!");
6662
+ boolean installed = false;
6663
+ boolean deferredForForeground = false;
6664
+ try {
6665
+ if (!this.appInBackground) {
6666
+ deferredForForeground = true;
6667
+ logger.info("App returned to foreground before deferred install, keeping bundle queued");
6668
+ return;
6669
+ }
6670
+ final CapgoUpdater.ResetState previousState;
6671
+ final String previousBundleName;
6672
+ final boolean staged;
6673
+ synchronized (this) {
6674
+ previousState = this.implementation.captureResetState();
6675
+ previousBundleName = this.implementation.getCurrentBundle().getVersionName();
6676
+ staged = this.stageBundleForReload(() -> this.implementation.setQueuedBundle(next));
6677
+ }
6678
+ if (staged && this.reloadAutomaticBundle(next, previousState)) {
6679
+ if (next.isBuiltin()) {
6680
+ this.implementation.finalizeBuiltinUpdate(previousBundleName);
6681
+ }
6682
+ logger.info("Updated to bundle: " + next.getVersionName());
6683
+ this.notifyBundleSet(next);
6684
+ this.implementation.clearNextBundleIfMatches(next.getId());
6685
+ installed = true;
6686
+ } else {
6687
+ logger.error("Update to bundle: " + next.getVersionName() + " Failed!");
6688
+ }
6689
+ } catch (final Exception e) {
6690
+ logger.error("Error during installNext " + e);
6691
+ } finally {
6692
+ this.releaseAutomaticInstall();
6693
+ // A download or background transition may have arrived while admission was held.
6694
+ this.installNextIfInBackground(installed || deferredForForeground ? null : next.getId());
5714
6695
  }
5715
6696
  });
6697
+ dispatched = true;
6698
+ } finally {
6699
+ if (!dispatched) {
6700
+ this.releaseAutomaticInstall();
6701
+ this.installNextIfInBackground(next.getId());
6702
+ }
5716
6703
  }
5717
6704
  } catch (final Exception e) {
5718
6705
  logger.error("Error during installNext " + e);
5719
6706
  }
5720
6707
  }
5721
6708
 
5722
- private void checkRevert() {
5723
- // Automatically roll back to fallback version if notifyAppReady has not been called yet
5724
- final BundleInfo current = this.implementation.getCurrentBundle();
6709
+ private void checkRevert(final BundleInfo current) {
6710
+ this.checkRevert(current.getId(), this.readyGeneration);
6711
+ }
5725
6712
 
5726
- if (current.isBuiltin()) {
5727
- logger.info("Built-in bundle is active. We skip the check for notifyAppReady.");
5728
- return;
5729
- }
5730
- if (this.isPreviewSessionStateActive()) {
5731
- logger.info("Preview session is active. We skip the check for notifyAppReady.");
5732
- return;
6713
+ private void checkRevert(final String expectedBundleId, final int expectedGeneration) {
6714
+ final BundleInfo current;
6715
+ synchronized (this) {
6716
+ if (this.appInBackground) {
6717
+ logger.info("App is in background, notifyAppReady check deferred to the next foreground");
6718
+ return;
6719
+ }
6720
+ current = this.implementation.getCurrentBundle();
6721
+ if (current == null || !current.getId().equals(expectedBundleId) || this.readyGeneration != expectedGeneration) {
6722
+ logger.info("Skipping notifyAppReady check for a bundle or page that is no longer current");
6723
+ return;
6724
+ }
6725
+ if (current.isBuiltin() || current.getStatus() == BundleStatus.SUCCESS || this.isPreviewSessionStateActive()) {
6726
+ return;
6727
+ }
6728
+ synchronized (this.automaticInstallLock) {
6729
+ if (
6730
+ this.watchdogRollbackInProgress ||
6731
+ (this.automaticInstallInProgress && this.automaticInstallPageGeneration != expectedGeneration)
6732
+ ) {
6733
+ // An admitted replacement has not dispatched its page yet. Its own watchdog
6734
+ // will check readiness; the previous page must not reset that installation.
6735
+ return;
6736
+ }
6737
+ this.watchdogRollbackInProgress = true;
6738
+ }
6739
+ // Reject readiness from the failed page throughout rollback staging and dispatch.
6740
+ this.armReadyGuard();
5733
6741
  }
5734
- logger.debug("Current bundle is: " + current);
5735
-
5736
- if (BundleStatus.SUCCESS != current.getStatus()) {
6742
+ try {
5737
6743
  logger.error("notifyAppReady was not called, roll back current bundle: " + current.getId());
5738
6744
  logger.info("Did you forget to call 'notifyAppReady()' in your Capacitor App code?");
5739
6745
  final JSObject ret = new JSObject();
@@ -5769,27 +6775,34 @@ public class CapacitorUpdaterPlugin extends Plugin {
5769
6775
  });
5770
6776
  }
5771
6777
  }
5772
- } else {
5773
- logger.info("notifyAppReady was called. This is fine: " + current.getId());
6778
+ } finally {
6779
+ synchronized (this.automaticInstallLock) {
6780
+ this.watchdogRollbackInProgress = false;
6781
+ }
6782
+ this.installNextIfInBackground();
5774
6783
  }
5775
6784
  }
5776
6785
 
5777
- void runDeferredAppReadyCheck() {
5778
- // A frozen app wakes up with its sleep already expired, before appMovedToForeground re-arms
5779
- // the check: its page could not run yet, so wait for the fresh check of the next foreground.
6786
+ private void runDeferredAppReadyCheck(final String expectedBundleId, final int expectedGeneration) {
6787
+ // A frozen page gets a fresh deadline on foreground.
5780
6788
  if (this.appInBackground) {
5781
6789
  logger.info("App is in background, notifyAppReady check deferred to the next foreground");
5782
6790
  return;
5783
6791
  }
5784
- this.checkRevert();
6792
+ this.checkRevert(expectedBundleId, expectedGeneration);
5785
6793
  }
5786
6794
 
5787
6795
  private class DeferredNotifyAppReadyCheck implements Runnable {
5788
6796
 
5789
6797
  private final long waitTimeMs;
6798
+ private final String bundleId;
6799
+ private final int generation;
5790
6800
 
5791
6801
  DeferredNotifyAppReadyCheck(final long waitTimeMs) {
5792
6802
  this.waitTimeMs = waitTimeMs;
6803
+ final BundleInfo current = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
6804
+ this.bundleId = current == null ? null : current.getId();
6805
+ this.generation = CapacitorUpdaterPlugin.this.readyGeneration;
5793
6806
  }
5794
6807
 
5795
6808
  @Override
@@ -5798,7 +6811,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5798
6811
  try {
5799
6812
  logger.info("Wait for " + this.waitTimeMs + "ms, then check for notifyAppReady");
5800
6813
  Thread.sleep(this.waitTimeMs);
5801
- CapacitorUpdaterPlugin.this.runDeferredAppReadyCheck();
6814
+ CapacitorUpdaterPlugin.this.runDeferredAppReadyCheck(this.bundleId, this.generation);
5802
6815
  CapacitorUpdaterPlugin.this.clearAppReadyCheckIfCurrent(currentThread);
5803
6816
  } catch (final InterruptedException e) {
5804
6817
  CapacitorUpdaterPlugin.this.clearAppReadyCheckIfCurrent(currentThread);
@@ -5828,6 +6841,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5828
6841
  this.delayUpdateUtils.unsetBackgroundTimestamp();
5829
6842
 
5830
6843
  if (CapacitorUpdaterPlugin.this._isAutoUpdateEnabled()) {
6844
+ this.scheduleLaunchSplashscreenTimeoutIfNeeded();
5831
6845
  if (!this.isDownloadStuckOrTimedOut()) {
5832
6846
  this.backgroundDownload();
5833
6847
  } else {
@@ -5879,12 +6893,12 @@ public class CapacitorUpdaterPlugin extends Plugin {
5879
6893
  if (!this.shouldUseDirectUpdate()) {
5880
6894
  if ("false".equals(this.directUpdateMode)) {
5881
6895
  logger.warn(
5882
- "autoSplashscreen is enabled but directUpdate is not configured for immediate updates. Set directUpdate to 'always' or disable autoSplashscreen."
6896
+ "autoSplashscreen is enabled but autoUpdate is not configured for immediate updates. Set autoUpdate to 'always' or disable autoSplashscreen."
5883
6897
  );
5884
6898
  } else if ("atInstall".equals(this.directUpdateMode) || "onLaunch".equals(this.directUpdateMode)) {
5885
6899
  logger.info(
5886
- "autoSplashscreen is enabled but directUpdate is set to \"" +
5887
- this.directUpdateMode +
6900
+ "autoSplashscreen is enabled but autoUpdate is set to \"" +
6901
+ this.autoUpdateMode +
5888
6902
  "\". This is normal. Skipping autoSplashscreen logic."
5889
6903
  );
5890
6904
  }
@@ -6439,7 +7453,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
6439
7453
  }
6440
7454
 
6441
7455
  private void handleOnDestroyInternal() {
6442
- instanceLoaded = false;
7456
+ synchronized (INSTANCE_LOADED_LOCK) {
7457
+ instanceLoaded = false;
7458
+ }
6443
7459
  if (this.implementation != null) {
6444
7460
  this.implementation.releaseStatsOwnership();
6445
7461
  }