@capgo/capacitor-updater 8.52.1 → 8.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. package/README.md +198 -66
  2. package/android/build.gradle +2 -1
  3. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +409 -148
  4. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +521 -197
  5. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +2 -1
  6. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +226 -105
  7. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +30 -10
  8. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +318 -0
  9. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  10. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +4 -4
  11. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +1 -1
  12. package/dist/docs.json +378 -27
  13. package/dist/esm/definitions.d.ts +206 -7
  14. package/dist/esm/definitions.js.map +1 -1
  15. package/dist/plugin.cjs.js.map +1 -1
  16. package/dist/plugin.js.map +1 -1
  17. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +104 -52
  18. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +292 -94
  19. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +156 -10
  20. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +2 -1
  21. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +202 -90
  22. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  23. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +5 -2
  24. package/package.json +7 -3
@@ -11,8 +11,11 @@ import android.content.Context;
11
11
  import android.content.SharedPreferences;
12
12
  import android.content.pm.PackageManager;
13
13
  import android.os.Build;
14
+ import android.os.Handler;
15
+ import android.os.Looper;
14
16
  import androidx.annotation.NonNull;
15
- import androidx.lifecycle.LifecycleOwner;
17
+ import androidx.lifecycle.LiveData;
18
+ import androidx.lifecycle.Observer;
16
19
  import androidx.work.Constraints;
17
20
  import androidx.work.Data;
18
21
  import androidx.work.ExistingPeriodicWorkPolicy;
@@ -33,6 +36,7 @@ import java.io.FilenameFilter;
33
36
  import java.io.IOException;
34
37
  import java.io.InputStreamReader;
35
38
  import java.nio.charset.StandardCharsets;
39
+ import java.nio.file.Files;
36
40
  import java.security.SecureRandom;
37
41
  import java.util.ArrayList;
38
42
  import java.util.Date;
@@ -49,8 +53,10 @@ import java.util.concurrent.ConcurrentHashMap;
49
53
  import java.util.concurrent.CopyOnWriteArrayList;
50
54
  import java.util.concurrent.ExecutorService;
51
55
  import java.util.concurrent.Executors;
56
+ import java.util.concurrent.LinkedBlockingQueue;
52
57
  import java.util.concurrent.ScheduledExecutorService;
53
58
  import java.util.concurrent.ScheduledFuture;
59
+ import java.util.concurrent.ThreadPoolExecutor;
54
60
  import java.util.concurrent.TimeUnit;
55
61
  import java.util.concurrent.atomic.AtomicBoolean;
56
62
  import java.util.zip.ZipEntry;
@@ -76,6 +82,9 @@ public class CapgoUpdater {
76
82
  private static final String PENDING_DELETE_IDS = "pendingDeleteIds";
77
83
  private static final String bundleDirectory = "versions";
78
84
  private static final String TEMP_UNZIP_PREFIX = "capgo_unzip_";
85
+ static final String MANIFEST_STAGING_PREFIX = "capgo_manifest_";
86
+ static final String MANIFEST_DEST_SUFFIX = "_manifest_dest";
87
+ private static final String LEGACY_MANIFEST_STAGING_FOLDER_PATTERN = "^[0-9A-Za-z]{10}$";
79
88
  private static final long DELETE_PACE_MS = 75L;
80
89
  private final Object deleteLock = new Object();
81
90
  private static final String CAPACITOR_CONFIG_ASSET = "capacitor.config.json";
@@ -93,6 +102,9 @@ public class CapgoUpdater {
93
102
  public File noBackupDir;
94
103
  public Boolean directUpdate = false;
95
104
  public Activity activity;
105
+ // Application context: lets downloads run and finish without an Activity (app in the
106
+ // background, or a process woken by a push with no UI at all).
107
+ public Context appContext;
96
108
  public String pluginVersion = "";
97
109
  public String versionBuild = "";
98
110
  public String versionCode = "";
@@ -150,10 +162,27 @@ public class CapgoUpdater {
150
162
  }
151
163
 
152
164
  private final Map<String, CompletableFuture<BundleInfo>> downloadFutures = new ConcurrentHashMap<>();
165
+
166
+ /** A download failure whose downloadFailed event and stats were already sent by the updater. */
167
+ static final class ReportedDownloadFailureException extends IOException {
168
+
169
+ ReportedDownloadFailureException(final String message) {
170
+ super(message);
171
+ }
172
+ }
173
+
153
174
  // Versions whose WorkManager download is observed by this process. WorkManager persists work across a
154
175
  // process kill, but the observer that finishes the download does not survive it.
155
176
  private final Set<String> observedDownloadVersions = ConcurrentHashMap.newKeySet();
156
- private final ExecutorService io = Executors.newSingleThreadExecutor();
177
+ private final ExecutorService io = createIoExecutor();
178
+
179
+ private static ExecutorService createIoExecutor() {
180
+ final ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
181
+ executor.allowCoreThreadTimeOut(true);
182
+ return executor;
183
+ }
184
+
185
+ private volatile Handler mainHandler;
157
186
 
158
187
  public CapgoUpdater(Logger logger) {
159
188
  this.logger = logger;
@@ -164,12 +193,22 @@ public class CapgoUpdater {
164
193
  return !name.startsWith("__MACOSX") && !name.startsWith(".") && !name.startsWith(".DS_Store");
165
194
  };
166
195
 
196
+ /** The Activity when the app has one, otherwise the application context. */
197
+ Context context() {
198
+ final Activity current = this.activity;
199
+ if (current != null) {
200
+ return current;
201
+ }
202
+ return this.appContext;
203
+ }
204
+
167
205
  private boolean isProd() {
168
206
  try {
169
- if (activity == null) {
170
- return true; // Default to production if no activity context
207
+ final Context context = this.context();
208
+ if (context == null) {
209
+ return true; // Default to production if no context
171
210
  }
172
- return (activity.getApplicationInfo().flags & android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE) == 0;
211
+ return (context.getApplicationInfo().flags & android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE) == 0;
173
212
  } catch (Exception e) {
174
213
  return true; // Default to production if we can't determine
175
214
  }
@@ -197,13 +236,14 @@ public class CapgoUpdater {
197
236
 
198
237
  @SuppressWarnings("deprecation")
199
238
  private String getInstallSource() {
200
- if (activity == null) {
239
+ final Context context = this.context();
240
+ if (context == null) {
201
241
  return "";
202
242
  }
203
243
 
204
244
  try {
205
- PackageManager packageManager = activity.getPackageManager();
206
- String packageName = activity.getPackageName();
245
+ PackageManager packageManager = context.getPackageManager();
246
+ String packageName = context.getPackageName();
207
247
  String installerPackageName;
208
248
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
209
249
  android.content.pm.InstallSourceInfo installSourceInfo = packageManager.getInstallSourceInfo(packageName);
@@ -263,6 +303,9 @@ public class CapgoUpdater {
263
303
 
264
304
  void notifyListeners(final String id, final Map<String, Object> res) {}
265
305
 
306
+ /** A downloaded bundle was stored as next bundle and waits for its install moment. */
307
+ void nextBundleReady(final BundleInfo bundle) {}
308
+
266
309
  static boolean shouldNotifyLaunchDownloadReady(
267
310
  final boolean awaitedByCaller,
268
311
  final boolean success,
@@ -307,6 +350,249 @@ public class CapgoUpdater {
307
350
  return sb.toString();
308
351
  }
309
352
 
353
+ static boolean isManifestStagingFolderName(final String name) {
354
+ if (name == null || !name.startsWith(MANIFEST_STAGING_PREFIX)) {
355
+ return false;
356
+ }
357
+ final String suffix = name.substring(MANIFEST_STAGING_PREFIX.length());
358
+ return suffix.length() == 10 && suffix.matches("[0-9A-Za-z]{10}");
359
+ }
360
+
361
+ String manifestStagingDest() {
362
+ return MANIFEST_STAGING_PREFIX + this.randomString();
363
+ }
364
+
365
+ private static boolean isLegacyBareManifestStagingFolderName(final String name) {
366
+ return name != null && name.matches(LEGACY_MANIFEST_STAGING_FOLDER_PATTERN);
367
+ }
368
+
369
+ private static boolean isSymbolicLinkEntry(final File file) {
370
+ return Files.isSymbolicLink(file.toPath());
371
+ }
372
+
373
+ private static boolean isRegularFileEntry(final File file) {
374
+ return file.isFile() && !isSymbolicLinkEntry(file);
375
+ }
376
+
377
+ private static boolean isRegularDirectoryEntry(final File file) {
378
+ return file.isDirectory() && !isSymbolicLinkEntry(file);
379
+ }
380
+
381
+ private static final long LEGACY_MANIFEST_STAGING_MIN_AGE_MS = 24L * 60L * 60L * 1000L;
382
+
383
+ private static boolean looksLikeLeakedManifestStaging(final File dir) {
384
+ if (dir == null || !isRegularDirectoryEntry(dir)) {
385
+ return false;
386
+ }
387
+ if (isRegularFileEntry(new File(dir, "index.html"))) {
388
+ return true;
389
+ }
390
+ if (isRegularDirectoryEntry(new File(dir, "assets"))) {
391
+ return true;
392
+ }
393
+ return isRegularDirectoryEntry(new File(dir, "www"));
394
+ }
395
+
396
+ private static boolean isOldEnoughForLegacyManifestCleanup(final File dir) {
397
+ final long ageMs = System.currentTimeMillis() - dir.lastModified();
398
+ return ageMs >= LEGACY_MANIFEST_STAGING_MIN_AGE_MS;
399
+ }
400
+
401
+ void saveManifestStagingDest(final String bundleId, final String dest) {
402
+ if (this.editor == null || bundleId == null || dest == null || dest.isEmpty()) {
403
+ return;
404
+ }
405
+ this.editor.putString(bundleId + MANIFEST_DEST_SUFFIX, dest);
406
+ this.editor.commit();
407
+ }
408
+
409
+ void clearManifestStagingDest(final String bundleId) {
410
+ if (this.editor == null || bundleId == null) {
411
+ return;
412
+ }
413
+ this.editor.remove(bundleId + MANIFEST_DEST_SUFFIX);
414
+ this.editor.commit();
415
+ }
416
+
417
+ void cleanupManifestStagingAfterDownloadFailed(final String bundleId, final String failedDest, final boolean failedManifest) {
418
+ if (failedManifest) {
419
+ this.deleteManifestStagingFolder(failedDest);
420
+ }
421
+ this.clearManifestStagingDest(bundleId);
422
+ }
423
+
424
+ void cleanupManifestStagingAfterDownloadCancelled(final String bundleId) {
425
+ final String cancelledDest = this.prefs != null ? this.prefs.getString(bundleId + MANIFEST_DEST_SUFFIX, null) : null;
426
+ this.deleteManifestStagingFolder(cancelledDest);
427
+ this.clearManifestStagingDest(bundleId);
428
+ }
429
+
430
+ Set<String> activeManifestStagingDests() {
431
+ final Set<String> activeDests = new HashSet<>();
432
+ if (this.prefs == null) {
433
+ return activeDests;
434
+ }
435
+ for (final BundleInfo info : this.list(true)) {
436
+ if (info == null || info.getId() == null || info.getId().isEmpty()) {
437
+ continue;
438
+ }
439
+ if (info.getStatus() != BundleStatus.DOWNLOADING) {
440
+ continue;
441
+ }
442
+ final String dest = this.prefs.getString(info.getId() + MANIFEST_DEST_SUFFIX, null);
443
+ if (dest != null && !dest.isEmpty()) {
444
+ activeDests.add(dest);
445
+ }
446
+ }
447
+ return activeDests;
448
+ }
449
+
450
+ public void deleteManifestStagingFolder(final String dest) {
451
+ if (this.documentsDir == null || dest == null || dest.isEmpty() || !isManifestStagingFolderName(dest)) {
452
+ return;
453
+ }
454
+ final File folder = new File(this.documentsDir, dest);
455
+ try {
456
+ this.assertPathInsideDocumentsDir(folder);
457
+ deleteManifestStagingTree(folder);
458
+ } catch (IOException e) {
459
+ logger.warn("Failed to delete manifest staging folder: " + e.getMessage());
460
+ }
461
+ }
462
+
463
+ static void deleteManifestStagingFolderAt(final File documentsDir, final String dest, final Logger log) {
464
+ if (documentsDir == null || dest == null || dest.isEmpty() || !isManifestStagingFolderName(dest)) {
465
+ return;
466
+ }
467
+ final File folder = new File(documentsDir, dest);
468
+ if (!folder.exists()) {
469
+ return;
470
+ }
471
+ try {
472
+ final File canonicalBase = documentsDir.getCanonicalFile();
473
+ final File canonicalTarget = folder.getCanonicalFile();
474
+ final String basePath = canonicalBase.getPath();
475
+ final String normalizedBasePath = basePath.endsWith(File.separator) ? basePath : basePath + File.separator;
476
+ final String targetPath = canonicalTarget.getPath();
477
+ if (!targetPath.equals(basePath) && !targetPath.startsWith(normalizedBasePath)) {
478
+ if (log != null) {
479
+ log.warn("Refusing unsafe manifest staging delete: " + folder.getAbsolutePath());
480
+ }
481
+ return;
482
+ }
483
+ if (canonicalTarget.isDirectory()) {
484
+ deleteManifestStagingTree(canonicalTarget);
485
+ } else if (!canonicalTarget.delete()) {
486
+ if (log != null) {
487
+ log.warn("Failed to delete manifest staging file: " + canonicalTarget.getAbsolutePath());
488
+ }
489
+ }
490
+ } catch (IOException e) {
491
+ if (log != null) {
492
+ log.warn("Failed to delete manifest staging folder: " + e.getMessage());
493
+ }
494
+ }
495
+ }
496
+
497
+ private static void deleteManifestStagingTree(final File file) throws IOException {
498
+ if (isSymbolicLinkEntry(file)) {
499
+ if (!file.delete()) {
500
+ throw new IOException("Failed to delete symlink: " + file);
501
+ }
502
+ return;
503
+ }
504
+ if (file.isDirectory()) {
505
+ final File[] entries = file.listFiles();
506
+ if (entries != null) {
507
+ for (final File entry : entries) {
508
+ deleteManifestStagingTree(entry);
509
+ }
510
+ }
511
+ }
512
+ if (!file.delete()) {
513
+ throw new IOException("Failed to delete: " + file);
514
+ }
515
+ }
516
+
517
+ public void cleanupOrphanedManifestStagingFolders(final Thread threadToCheck) {
518
+ if (this.documentsDir == null) {
519
+ logger.warn("Documents directory is null, skipping manifest staging cleanup");
520
+ return;
521
+ }
522
+
523
+ final File[] entries = this.documentsDir.listFiles();
524
+ if (entries == null) {
525
+ return;
526
+ }
527
+
528
+ final Set<String> protectedDests = this.activeManifestStagingDests();
529
+
530
+ for (final File entry : entries) {
531
+ if (threadToCheck != null && threadToCheck.isInterrupted()) {
532
+ logger.warn("cleanupOrphanedManifestStagingFolders was cancelled");
533
+ return;
534
+ }
535
+ if (!entry.isDirectory()) {
536
+ continue;
537
+ }
538
+ final String folderName = entry.getName();
539
+ if (!isManifestStagingFolderName(folderName)) {
540
+ continue;
541
+ }
542
+ if (protectedDests.contains(folderName)) {
543
+ continue;
544
+ }
545
+ try {
546
+ deleteManifestStagingTree(entry);
547
+ logger.info("Deleted orphaned manifest staging folder");
548
+ logger.debug("Folder: " + folderName);
549
+ } catch (IOException e) {
550
+ logger.error("Failed to delete orphaned manifest staging folder");
551
+ logger.debug("Folder: " + folderName + ", Error: " + e.getMessage());
552
+ }
553
+ }
554
+
555
+ this.cleanupLegacyBareManifestStagingFolders(threadToCheck, protectedDests);
556
+ }
557
+
558
+ private void cleanupLegacyBareManifestStagingFolders(final Thread threadToCheck, final Set<String> protectedDests) {
559
+ final File[] entries = this.documentsDir.listFiles();
560
+ if (entries == null) {
561
+ return;
562
+ }
563
+
564
+ for (final File entry : entries) {
565
+ if (threadToCheck != null && threadToCheck.isInterrupted()) {
566
+ logger.warn("cleanupLegacyBareManifestStagingFolders was cancelled");
567
+ return;
568
+ }
569
+ if (!entry.isDirectory()) {
570
+ continue;
571
+ }
572
+ final String folderName = entry.getName();
573
+ if (!isLegacyBareManifestStagingFolderName(folderName)) {
574
+ continue;
575
+ }
576
+ if (protectedDests.contains(folderName)) {
577
+ continue;
578
+ }
579
+ if (!looksLikeLeakedManifestStaging(entry)) {
580
+ continue;
581
+ }
582
+ if (!isOldEnoughForLegacyManifestCleanup(entry)) {
583
+ continue;
584
+ }
585
+ try {
586
+ deleteManifestStagingTree(entry);
587
+ logger.info("Deleted legacy bare manifest staging folder");
588
+ logger.debug("Folder: " + folderName);
589
+ } catch (IOException e) {
590
+ logger.error("Failed to delete legacy bare manifest staging folder");
591
+ logger.debug("Folder: " + folderName + ", Error: " + e.getMessage());
592
+ }
593
+ }
594
+ }
595
+
310
596
  public void setPublicKey(String publicKey) {
311
597
  // Empty string means no encryption - proceed normally
312
598
  if (publicKey == null || publicKey.isEmpty()) {
@@ -481,8 +767,8 @@ public class CapgoUpdater {
481
767
  }
482
768
 
483
769
  void cacheBundleFiles(final String id) {
484
- if (this.activity == null) {
485
- logger.debug("Skip delta cache population: activity is null");
770
+ if (this.context() == null) {
771
+ logger.debug("Skip delta cache population: no context");
486
772
  return;
487
773
  }
488
774
 
@@ -498,7 +784,7 @@ public class CapgoUpdater {
498
784
  return;
499
785
  }
500
786
 
501
- final File cacheDir = new File(this.activity.getCacheDir(), "capgo_downloads");
787
+ final File cacheDir = new File(this.context().getCacheDir(), "capgo_downloads");
502
788
  if (cacheDir.exists() && !cacheDir.isDirectory()) {
503
789
  logger.debug("Skip delta cache population: cache dir is not a directory");
504
790
  return;
@@ -508,7 +794,7 @@ public class CapgoUpdater {
508
794
  return;
509
795
  }
510
796
 
511
- final File builtinFolder = new File(this.activity.getFilesDir(), "public");
797
+ final File builtinFolder = new File(this.context().getFilesDir(), "public");
512
798
 
513
799
  final List<File> files = new ArrayList<>();
514
800
  collectFiles(bundleDir, files);
@@ -598,16 +884,16 @@ public class CapgoUpdater {
598
884
  private boolean isManifestEntryAvailableLocally(final JSONObject entry, final String sessionKey) {
599
885
  final String fileName = entry.optString("file_name", "");
600
886
  final String fileHash = resolveManifestFileHash(entry, sessionKey);
601
- if (fileName.isEmpty() || fileHash.isEmpty() || this.activity == null) {
887
+ if (fileName.isEmpty() || fileHash.isEmpty() || this.context() == null) {
602
888
  return false;
603
889
  }
604
890
 
605
- if (DownloadService.builtinAssetMatches(this.activity.getAssets(), fileName, fileHash)) {
891
+ if (DownloadService.builtinAssetMatches(this.context().getAssets(), fileName, fileHash)) {
606
892
  return true;
607
893
  }
608
894
 
609
895
  try {
610
- final File builtinFile = DownloadService.resolveManifestBuiltinFile(new File(this.activity.getFilesDir(), "public"), fileName);
896
+ final File builtinFile = DownloadService.resolveManifestBuiltinFile(new File(this.context().getFilesDir(), "public"), fileName);
611
897
  if (verifyChecksum(builtinFile, fileHash)) {
612
898
  return true;
613
899
  }
@@ -619,7 +905,7 @@ public class CapgoUpdater {
619
905
  final String fileNameWithoutPath = new File(fileName).getName();
620
906
  final String cacheBaseName = isBrotli ? fileNameWithoutPath.substring(0, fileNameWithoutPath.length() - 3) : fileNameWithoutPath;
621
907
  if (isSafeCacheHash(fileHash)) {
622
- final File cacheFolder = new File(this.activity.getCacheDir(), "capgo_downloads");
908
+ final File cacheFolder = new File(this.context().getCacheDir(), "capgo_downloads");
623
909
  final File cacheFile = new File(cacheFolder, fileHash + "_" + cacheBaseName);
624
910
  // Cache files are named `{hash}_{filename}` and were checksum-verified
625
911
  // when written. Re-hashing every hit re-reads the whole bundle and
@@ -762,155 +1048,168 @@ public class CapgoUpdater {
762
1048
  this.backgroundDownloadSettled(readyBundle, launchDownloadReadyStatus(success, setNext));
763
1049
  }
764
1050
 
765
- private void observeWorkProgress(Context context, String id, String observedVersion, boolean setNext) {
766
- if (!(context instanceof LifecycleOwner)) {
767
- logger.error("Context is not a LifecycleOwner, cannot observe work progress");
768
- return;
1051
+ // Created on first use: plain JVM unit tests construct CapgoUpdater without a main Looper.
1052
+ private Handler mainHandler() {
1053
+ Handler handler = this.mainHandler;
1054
+ if (handler == null) {
1055
+ handler = new Handler(Looper.getMainLooper());
1056
+ this.mainHandler = handler;
769
1057
  }
1058
+ return handler;
1059
+ }
770
1060
 
1061
+ @SuppressWarnings("unchecked")
1062
+ private void observeWorkProgress(Context context, String id, String observedVersion, boolean setNext) {
771
1063
  final AtomicBoolean terminalHandled = new AtomicBoolean(false);
772
1064
  final AtomicBoolean launchReleasedWhileRetrying = new AtomicBoolean(false);
773
- activity.runOnUiThread(() -> {
774
- WorkManager.getInstance(context)
775
- .getWorkInfosByTagLiveData(id)
776
- .observe((LifecycleOwner) context, (workInfos) -> {
777
- if (workInfos == null || workInfos.isEmpty()) return;
778
-
779
- WorkInfo workInfo = workInfos.get(0);
780
- Data progress = workInfo.getProgress();
781
-
782
- switch (workInfo.getState()) {
783
- case ENQUEUED:
784
- // A run attempt already happened, so WorkManager scheduled a retry (network lost midway,
785
- // 5xx, ...). Retries back off without limit, so a direct install must not keep the launch
786
- // (and its splashscreen) blocked until the network comes back.
787
- if (
788
- workInfo.getRunAttemptCount() > 0 &&
789
- shouldReleaseLaunchWhileRetrying(
790
- downloadFutures.containsKey(id),
791
- setNext,
792
- Boolean.TRUE.equals(CapgoUpdater.this.directUpdate),
793
- CapgoUpdater.this.previewSession
794
- ) &&
795
- launchReleasedWhileRetrying.compareAndSet(false, true)
796
- ) {
797
- logger.warn("Direct update download is retrying, continuing launch on the current bundle");
798
- // Same fallback as the autoSplashscreen timeout: a later success installs on next background.
799
- CapgoUpdater.this.directUpdate = false;
800
- io.execute(() -> backgroundDownloadSettled(getCurrentBundle(), launchDownloadReadyStatus(false, false)));
1065
+ final LiveData<List<WorkInfo>> workInfosLiveData = WorkManager.getInstance(
1066
+ context.getApplicationContext()
1067
+ ).getWorkInfosByTagLiveData(id);
1068
+ // observeForever, not observe(activity): a stopped Activity pauses LiveData, so a download
1069
+ // that completes while the app is in the background would only be finished once the user
1070
+ // opens the app again. The observer removes itself on a terminal state.
1071
+ final Observer<List<WorkInfo>>[] observerRef = new Observer[1];
1072
+ final Runnable removeObserver = () -> mainHandler().post(() -> workInfosLiveData.removeObserver(observerRef[0]));
1073
+ mainHandler().post(() -> {
1074
+ observerRef[0] = (workInfos) -> {
1075
+ if (workInfos == null || workInfos.isEmpty()) return;
1076
+
1077
+ WorkInfo workInfo = workInfos.get(0);
1078
+ Data progress = workInfo.getProgress();
1079
+
1080
+ switch (workInfo.getState()) {
1081
+ case ENQUEUED:
1082
+ // A run attempt already happened, so WorkManager scheduled a retry (network lost midway,
1083
+ // 5xx, ...). Retries back off without limit, so a direct install must not keep the launch
1084
+ // (and its splashscreen) blocked until the network comes back.
1085
+ if (
1086
+ workInfo.getRunAttemptCount() > 0 &&
1087
+ shouldReleaseLaunchWhileRetrying(
1088
+ downloadFutures.containsKey(id),
1089
+ setNext,
1090
+ Boolean.TRUE.equals(CapgoUpdater.this.directUpdate),
1091
+ CapgoUpdater.this.previewSession
1092
+ ) &&
1093
+ launchReleasedWhileRetrying.compareAndSet(false, true)
1094
+ ) {
1095
+ logger.warn("Direct update download is retrying, continuing launch on the current bundle");
1096
+ // Same fallback as the autoSplashscreen timeout: a later success installs on next background.
1097
+ CapgoUpdater.this.directUpdate = false;
1098
+ io.execute(() -> backgroundDownloadSettled(getCurrentBundle(), launchDownloadReadyStatus(false, false)));
1099
+ }
1100
+ break;
1101
+ case RUNNING:
1102
+ int percent = progress.getInt(DownloadService.PERCENT, 0);
1103
+ notifyDownload(id, percent);
1104
+ break;
1105
+ case SUCCEEDED:
1106
+ if (!terminalHandled.compareAndSet(false, true)) break;
1107
+ removeObserver.run();
1108
+ observedDownloadVersions.remove(observedVersion);
1109
+ logger.info("Download succeeded: " + workInfo.getState());
1110
+ Data outputData = workInfo.getOutputData();
1111
+ String dest = outputData.getString(DownloadService.FILEDEST);
1112
+ String version = outputData.getString(DownloadService.VERSION);
1113
+ String sessionKey = outputData.getString(DownloadService.SESSIONKEY);
1114
+ String checksum = outputData.getString(DownloadService.CHECKSUM);
1115
+ boolean isManifest = outputData.getBoolean(DownloadService.IS_MANIFEST, false);
1116
+
1117
+ io.execute(() -> {
1118
+ // finishDownload clears directUpdate, so read the install plan first.
1119
+ final boolean directInstall =
1120
+ setNext && Boolean.TRUE.equals(CapgoUpdater.this.directUpdate) && !CapgoUpdater.this.previewSession;
1121
+ final boolean previewSession = CapgoUpdater.this.previewSession;
1122
+ boolean success = finishDownload(id, dest, version, sessionKey, checksum, setNext, isManifest);
1123
+ BundleInfo resultBundle;
1124
+ if (!success) {
1125
+ logger.error("Finish download failed");
1126
+ logger.debug("Version: " + version);
1127
+ resultBundle = new BundleInfo(id, version, BundleStatus.ERROR, new Date(System.currentTimeMillis()), "");
1128
+ saveBundleInfo(id, resultBundle);
1129
+ // Cleanup download tracking
1130
+ DownloadWorkerManager.cancelBundleDownload(context, id, version);
1131
+ sendStats("finish_download_fail", version);
1132
+ // finishDownload already emitted downloadFailed for this failure.
1133
+ } else {
1134
+ // Successful download - cleanup tracking
1135
+ DownloadWorkerManager.cancelBundleDownload(context, id, version);
1136
+ resultBundle = getBundleInfo(id);
801
1137
  }
802
- break;
803
- case RUNNING:
804
- int percent = progress.getInt(DownloadService.PERCENT, 0);
805
- notifyDownload(id, percent);
806
- break;
807
- case SUCCEEDED:
808
- if (!terminalHandled.compareAndSet(false, true)) break;
809
- observedDownloadVersions.remove(observedVersion);
810
- logger.info("Download succeeded: " + workInfo.getState());
811
- Data outputData = workInfo.getOutputData();
812
- String dest = outputData.getString(DownloadService.FILEDEST);
813
- String version = outputData.getString(DownloadService.VERSION);
814
- String sessionKey = outputData.getString(DownloadService.SESSIONKEY);
815
- String checksum = outputData.getString(DownloadService.CHECKSUM);
816
- boolean isManifest = outputData.getBoolean(DownloadService.IS_MANIFEST, false);
817
-
818
- io.execute(() -> {
819
- // finishDownload clears directUpdate, so read the install plan first.
820
- final boolean directInstall =
821
- setNext && Boolean.TRUE.equals(CapgoUpdater.this.directUpdate) && !CapgoUpdater.this.previewSession;
822
- final boolean previewSession = CapgoUpdater.this.previewSession;
823
- boolean success = finishDownload(id, dest, version, sessionKey, checksum, setNext, isManifest);
824
- BundleInfo resultBundle;
825
- if (!success) {
826
- logger.error("Finish download failed");
827
- logger.debug("Version: " + version);
828
- resultBundle = new BundleInfo(
829
- id,
830
- version,
831
- BundleStatus.ERROR,
832
- new Date(System.currentTimeMillis()),
833
- ""
834
- );
835
- saveBundleInfo(id, resultBundle);
836
- // Cleanup download tracking
837
- DownloadWorkerManager.cancelBundleDownload(activity, id, version);
838
- Map<String, Object> ret = new HashMap<>();
839
- ret.put("version", version);
840
- ret.put("error", "finish_download_fail");
841
- sendStats("finish_download_fail", version);
842
- notifyListeners("downloadFailed", ret);
843
- } else {
844
- // Successful download - cleanup tracking
845
- DownloadWorkerManager.cancelBundleDownload(activity, id, version);
846
- resultBundle = getBundleInfo(id);
847
- }
848
1138
 
849
- // Complete the future if it exists. download() waits on it.
850
- // downloadBackground does not, so the launch check must emit appReady here.
851
- CompletableFuture<BundleInfo> future = downloadFutures.remove(id);
852
- if (future != null) {
853
- future.complete(resultBundle);
854
- }
855
- final BundleInfo readyBundle = success && setNext ? resultBundle : null;
856
- if (!launchReleasedWhileRetrying.get()) {
857
- notifyLaunchDownloadReady(future != null, success, directInstall, previewSession, setNext, readyBundle);
858
- }
859
- });
860
- break;
861
- case FAILED:
862
- if (!terminalHandled.compareAndSet(false, true)) break;
863
- observedDownloadVersions.remove(observedVersion);
864
- Data failedData = workInfo.getOutputData();
865
- String error = failedData.getString(DownloadService.ERROR);
866
- logger.error("Download failed");
867
- logger.debug("Error: " + error + ", State: " + workInfo.getState());
868
- String failedVersion = failedData.getString(DownloadService.VERSION);
869
-
870
- io.execute(() -> {
871
- BundleInfo failedBundle = new BundleInfo(
872
- id,
873
- failedVersion,
874
- BundleStatus.ERROR,
875
- new Date(System.currentTimeMillis()),
876
- ""
877
- );
878
- saveBundleInfo(id, failedBundle);
879
- // Cleanup download tracking for failed downloads
880
- DownloadWorkerManager.cancelBundleDownload(activity, id, failedVersion);
881
- Map<String, Object> ret = new HashMap<>();
882
- ret.put("version", failedVersion);
883
- if ("low_mem_fail".equals(error)) {
884
- sendStats("low_mem_fail", failedVersion);
885
- }
886
- if ("insufficient_disk_space".equals(error)) {
887
- sendStats("insufficient_disk_space", failedVersion);
888
- }
889
- ret.put("error", error != null ? error : "download_fail");
890
- sendStats("download_fail", failedVersion);
891
- notifyListeners("downloadFailed", ret);
892
-
893
- // Complete the future with error status
894
- CompletableFuture<BundleInfo> failedFuture = downloadFutures.remove(id);
895
- if (failedFuture != null) {
896
- failedFuture.complete(failedBundle);
897
- }
898
- if (!launchReleasedWhileRetrying.get()) {
899
- notifyLaunchDownloadReady(failedFuture != null, false, false, false, false, null);
900
- }
901
- });
902
- break;
903
- case CANCELLED:
904
- if (!terminalHandled.compareAndSet(false, true)) break;
905
- observedDownloadVersions.remove(observedVersion);
906
- DataManager.getInstance().clearManifest(id);
907
- CompletableFuture<BundleInfo> cancelledFuture = downloadFutures.remove(id);
908
- if (cancelledFuture != null) {
909
- cancelledFuture.cancel(true);
1139
+ CapgoUpdater.this.clearManifestStagingDest(id);
1140
+
1141
+ // Complete the future if it exists. download() waits on it.
1142
+ // downloadBackground does not, so the launch check must emit appReady here.
1143
+ CompletableFuture<BundleInfo> future = downloadFutures.remove(id);
1144
+ if (future != null) {
1145
+ future.complete(resultBundle);
910
1146
  }
911
- break;
912
- }
913
- });
1147
+ final BundleInfo readyBundle = success && setNext ? resultBundle : null;
1148
+ if (!launchReleasedWhileRetrying.get()) {
1149
+ notifyLaunchDownloadReady(future != null, success, directInstall, previewSession, setNext, readyBundle);
1150
+ }
1151
+ });
1152
+ break;
1153
+ case FAILED:
1154
+ if (!terminalHandled.compareAndSet(false, true)) break;
1155
+ removeObserver.run();
1156
+ observedDownloadVersions.remove(observedVersion);
1157
+ Data failedData = workInfo.getOutputData();
1158
+ String error = failedData.getString(DownloadService.ERROR);
1159
+ logger.error("Download failed");
1160
+ logger.debug("Error: " + error + ", State: " + workInfo.getState());
1161
+ String failedVersion = failedData.getString(DownloadService.VERSION);
1162
+ final String failedDest = failedData.getString(DownloadService.FILEDEST);
1163
+ final boolean failedManifest = failedData.getBoolean(DownloadService.IS_MANIFEST, false);
1164
+
1165
+ io.execute(() -> {
1166
+ CapgoUpdater.this.cleanupManifestStagingAfterDownloadFailed(id, failedDest, failedManifest);
1167
+ BundleInfo failedBundle = new BundleInfo(
1168
+ id,
1169
+ failedVersion,
1170
+ BundleStatus.ERROR,
1171
+ new Date(System.currentTimeMillis()),
1172
+ ""
1173
+ );
1174
+ saveBundleInfo(id, failedBundle);
1175
+ // Cleanup download tracking for failed downloads
1176
+ DownloadWorkerManager.cancelBundleDownload(context, id, failedVersion);
1177
+ Map<String, Object> ret = new HashMap<>();
1178
+ ret.put("version", failedVersion);
1179
+ if ("low_mem_fail".equals(error)) {
1180
+ sendStats("low_mem_fail", failedVersion);
1181
+ }
1182
+ if ("insufficient_disk_space".equals(error)) {
1183
+ sendStats("insufficient_disk_space", failedVersion);
1184
+ }
1185
+ ret.put("error", error != null ? error : "download_fail");
1186
+ sendStats("download_fail", failedVersion);
1187
+ notifyListeners("downloadFailed", ret);
1188
+
1189
+ // Complete the future with error status
1190
+ CompletableFuture<BundleInfo> failedFuture = downloadFutures.remove(id);
1191
+ if (failedFuture != null) {
1192
+ failedFuture.complete(failedBundle);
1193
+ }
1194
+ if (!launchReleasedWhileRetrying.get()) {
1195
+ notifyLaunchDownloadReady(failedFuture != null, false, false, false, false, null);
1196
+ }
1197
+ });
1198
+ break;
1199
+ case CANCELLED:
1200
+ if (!terminalHandled.compareAndSet(false, true)) break;
1201
+ removeObserver.run();
1202
+ observedDownloadVersions.remove(observedVersion);
1203
+ DataManager.getInstance().clearManifest(id);
1204
+ io.execute(() -> CapgoUpdater.this.cleanupManifestStagingAfterDownloadCancelled(id));
1205
+ CompletableFuture<BundleInfo> cancelledFuture = downloadFutures.remove(id);
1206
+ if (cancelledFuture != null) {
1207
+ cancelledFuture.cancel(true);
1208
+ }
1209
+ break;
1210
+ }
1211
+ };
1212
+ workInfosLiveData.observeForever(observerRef[0]);
914
1213
  });
915
1214
  }
916
1215
 
@@ -924,19 +1223,21 @@ public class CapgoUpdater {
924
1223
  final JSONArray manifest,
925
1224
  final boolean setNext
926
1225
  ) {
927
- if (this.activity == null) {
928
- logger.error("Activity is null, cannot observe work progress");
1226
+ final Context context = this.context();
1227
+ if (context == null) {
1228
+ logger.error("No context, cannot observe work progress");
929
1229
  return;
930
1230
  }
931
1231
  observedDownloadVersions.add(version);
932
- observeWorkProgress(this.activity, id, version, setNext);
1232
+ observeWorkProgress(context, id, version, setNext);
933
1233
 
934
1234
  if (manifest != null) {
935
1235
  DataManager.getInstance().setManifest(id, manifest);
1236
+ this.saveManifestStagingDest(id, dest);
936
1237
  }
937
1238
 
938
1239
  DownloadWorkerManager.enqueueDownload(
939
- this.activity,
1240
+ context,
940
1241
  url,
941
1242
  id,
942
1243
  this.documentsDir.getAbsolutePath(),
@@ -999,9 +1300,7 @@ public class CapgoUpdater {
999
1300
  }
1000
1301
  // Remove the decryption for manifest downloads
1001
1302
  } catch (Exception e) {
1002
- if (!isManifest) {
1003
- safeDelete(downloaded);
1004
- }
1303
+ safeDelete(downloaded);
1005
1304
  final Boolean res = this.delete(id);
1006
1305
  if (!res) {
1007
1306
  logger.info("Failed to cleanup after error");
@@ -1048,14 +1347,14 @@ public class CapgoUpdater {
1048
1347
  this.directUpdate = false;
1049
1348
  } else {
1050
1349
  logger.info("directUpdate: " + this.directUpdate);
1051
- this.setNextBundle(next.getId());
1350
+ if (this.setNextBundle(next.getId())) {
1351
+ this.nextBundleReady(next);
1352
+ }
1052
1353
  }
1053
1354
  }
1054
1355
  } catch (IOException e) {
1055
- if (!isManifest) {
1056
- safeDelete(extractedDir);
1057
- safeDelete(downloaded);
1058
- }
1356
+ safeDelete(extractedDir);
1357
+ safeDelete(downloaded);
1059
1358
  e.printStackTrace();
1060
1359
  final Map<String, Object> ret = new HashMap<>();
1061
1360
  ret.put("version", version);
@@ -1097,11 +1396,11 @@ public class CapgoUpdater {
1097
1396
  }
1098
1397
 
1099
1398
  public void cleanupDeltaCache(final Thread threadToCheck) {
1100
- if (this.activity == null) {
1399
+ if (this.context() == null) {
1101
1400
  logger.warn("Activity is null, skipping delta cache cleanup");
1102
1401
  return;
1103
1402
  }
1104
- final File cacheFolder = new File(this.activity.getCacheDir(), "capgo_downloads");
1403
+ final File cacheFolder = new File(this.context().getCacheDir(), "capgo_downloads");
1105
1404
  if (!cacheFolder.exists()) {
1106
1405
  return;
1107
1406
  }
@@ -1367,7 +1666,7 @@ public class CapgoUpdater {
1367
1666
  final StringBuilder buffer = new StringBuilder();
1368
1667
  try (
1369
1668
  final BufferedReader reader = new BufferedReader(
1370
- new InputStreamReader(this.activity.getAssets().open(assetPath), StandardCharsets.UTF_8)
1669
+ new InputStreamReader(this.context().getAssets().open(assetPath), StandardCharsets.UTF_8)
1371
1670
  )
1372
1671
  ) {
1373
1672
  String line;
@@ -1405,7 +1704,7 @@ public class CapgoUpdater {
1405
1704
  }
1406
1705
 
1407
1706
  private void syncBackgroundRunnerScriptFromBundle(final File bundle, final BackgroundRunnerWorkConfig config) {
1408
- if (this.activity == null || bundle == null || config == null || config.src == null || config.src.isEmpty()) {
1707
+ if (this.context() == null || bundle == null || config == null || config.src == null || config.src.isEmpty()) {
1409
1708
  return;
1410
1709
  }
1411
1710
 
@@ -1419,7 +1718,7 @@ public class CapgoUpdater {
1419
1718
  return;
1420
1719
  }
1421
1720
 
1422
- final File publicDir = new File(this.activity.getFilesDir(), "public");
1721
+ final File publicDir = new File(this.context().getFilesDir(), "public");
1423
1722
  final File dest = resolvePathInsideDirectory(publicDir, config.src);
1424
1723
  this.copyFileAtomically(source, dest);
1425
1724
  logger.info("Synced Background Runner script into native public storage before bundle switch.");
@@ -1430,7 +1729,7 @@ public class CapgoUpdater {
1430
1729
  }
1431
1730
 
1432
1731
  private void resetBackgroundRunnerWorkForBundleSwitch(final File bundle) {
1433
- if (this.activity == null) {
1732
+ if (this.context() == null) {
1434
1733
  return;
1435
1734
  }
1436
1735
 
@@ -1446,7 +1745,7 @@ public class CapgoUpdater {
1446
1745
  }
1447
1746
 
1448
1747
  try {
1449
- final WorkManager workManager = WorkManager.getInstance(this.activity.getApplicationContext());
1748
+ final WorkManager workManager = WorkManager.getInstance(this.context().getApplicationContext());
1450
1749
  workManager.cancelUniqueWork(config.label);
1451
1750
  workManager.cancelAllWorkByTag(config.label);
1452
1751
  logger.info("Cancelled Background Runner work before bundle switch.");
@@ -1476,7 +1775,7 @@ public class CapgoUpdater {
1476
1775
  .putString("event", config.event)
1477
1776
  .build();
1478
1777
  final Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();
1479
- final WorkManager workManager = WorkManager.getInstance(this.activity.getApplicationContext());
1778
+ final WorkManager workManager = WorkManager.getInstance(this.context().getApplicationContext());
1480
1779
 
1481
1780
  if (!config.repeat) {
1482
1781
  final OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(workerClass)
@@ -1546,7 +1845,7 @@ public class CapgoUpdater {
1546
1845
  downloadBackground(url, version, sessionKey, checksum, manifest, true);
1547
1846
  }
1548
1847
 
1549
- public void downloadBackground(
1848
+ public String downloadBackground(
1550
1849
  final String url,
1551
1850
  final String version,
1552
1851
  final String sessionKey,
@@ -1561,34 +1860,45 @@ public class CapgoUpdater {
1561
1860
  }
1562
1861
  } catch (final IOException e) {
1563
1862
  logger.error("Download blocked: " + e.getMessage());
1564
- return;
1863
+ return null;
1565
1864
  }
1566
1865
  if (!this.runDownloadGateQuiet()) {
1567
- return;
1866
+ return null;
1568
1867
  }
1569
1868
  final String id = this.randomString();
1570
1869
 
1571
1870
  // Check if version is already downloading, but allow retry if previous download failed
1572
- if (this.activity != null && DownloadWorkerManager.isVersionDownloading(this.activity, version)) {
1871
+ if (this.context() != null && DownloadWorkerManager.isVersionDownloading(this.context(), version)) {
1573
1872
  // Check if there's an existing bundle with error status that we can retry
1574
1873
  BundleInfo existingBundle = this.getBundleInfoByName(version);
1575
1874
  if (existingBundle != null && existingBundle.isErrorStatus()) {
1576
1875
  // Cancel the failed download and allow retry
1577
- if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.activity, version)) {
1876
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.context(), version)) {
1578
1877
  logger.error("Failed to cancel previous download before retry");
1579
- return;
1878
+ return null;
1580
1879
  }
1581
1880
  logger.info("Retrying failed download for version: " + version);
1582
1881
  } else if (shouldRestartOrphanedDownload(observedDownloadVersions.contains(version))) {
1583
1882
  // Left over from a killed process: nothing would finish it or release the launch, so start over.
1584
- if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.activity, version)) {
1883
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.context(), version)) {
1585
1884
  logger.error("Failed to cancel orphaned download before restarting it");
1586
- return;
1885
+ return null;
1886
+ }
1887
+ BundleInfo orphanedBundle = null;
1888
+ for (final BundleInfo info : this.list(true)) {
1889
+ if (info != null && info.getStatus() == BundleStatus.DOWNLOADING && version.equals(info.getVersionName())) {
1890
+ orphanedBundle = info;
1891
+ break;
1892
+ }
1893
+ }
1894
+ if (orphanedBundle != null) {
1895
+ this.cleanupManifestStagingAfterDownloadCancelled(orphanedBundle.getId());
1896
+ this.saveBundleInfo(orphanedBundle.getId(), orphanedBundle.setStatus(BundleStatus.ERROR));
1587
1897
  }
1588
1898
  logger.info("Restarting download orphaned by a previous process for version: " + version);
1589
1899
  } else {
1590
1900
  logger.info("Version already downloading: " + version);
1591
- return;
1901
+ return null;
1592
1902
  }
1593
1903
  }
1594
1904
 
@@ -1596,7 +1906,9 @@ public class CapgoUpdater {
1596
1906
  this.notifyDownload(id, 0);
1597
1907
  this.notifyDownload(id, 5);
1598
1908
 
1599
- this.download(id, url, this.randomString(), version, sessionKey, checksum, manifest, setNext);
1909
+ final String dest = manifest != null ? this.manifestStagingDest() : this.randomString();
1910
+ this.download(id, url, dest, version, sessionKey, checksum, manifest, setNext);
1911
+ return id;
1600
1912
  }
1601
1913
 
1602
1914
  public BundleInfo download(final String url, final String version, final String sessionKey, final String checksum) throws IOException {
@@ -1629,7 +1941,8 @@ public class CapgoUpdater {
1629
1941
  try {
1630
1942
  BundleInfo result = downloadFuture.get();
1631
1943
  if (result.isErrorStatus()) {
1632
- throw new IOException("Download failed with status: " + result.getStatus());
1944
+ // The download observer already emitted downloadFailed and its stats.
1945
+ throw new ReportedDownloadFailureException("Download failed with status: " + result.getStatus());
1633
1946
  }
1634
1947
  return result;
1635
1948
  } catch (Exception e) {
@@ -1672,7 +1985,7 @@ public class CapgoUpdater {
1672
1985
  saveBundleInfo(id, new BundleInfo(id, version, BundleStatus.DOWNLOADING, new Date(System.currentTimeMillis()), ""));
1673
1986
  this.notifyDownload(id, 0);
1674
1987
  this.notifyDownload(id, 5);
1675
- final String dest = this.randomString();
1988
+ final String dest = this.manifestStagingDest();
1676
1989
 
1677
1990
  // Create a CompletableFuture to track download completion
1678
1991
  CompletableFuture<BundleInfo> downloadFuture = new CompletableFuture<>();
@@ -1685,7 +1998,8 @@ public class CapgoUpdater {
1685
1998
  try {
1686
1999
  BundleInfo result = downloadFuture.get();
1687
2000
  if (result.isErrorStatus()) {
1688
- throw new IOException("Download failed with status: " + result.getStatus());
2001
+ // The download observer already emitted downloadFailed and its stats.
2002
+ throw new ReportedDownloadFailureException("Download failed with status: " + result.getStatus());
1689
2003
  }
1690
2004
  return result;
1691
2005
  } catch (Exception e) {
@@ -1786,8 +2100,8 @@ public class CapgoUpdater {
1786
2100
  }
1787
2101
 
1788
2102
  // Cancel download for this version if active
1789
- if (cancelActiveDownload && this.activity != null) {
1790
- if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.activity, deleted.getVersionName())) {
2103
+ if (cancelActiveDownload && this.context() != null) {
2104
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.context(), deleted.getVersionName())) {
1791
2105
  logger.error("Failed to cancel active download before delete");
1792
2106
  return false;
1793
2107
  }
@@ -1980,8 +2294,8 @@ public class CapgoUpdater {
1980
2294
  }
1981
2295
 
1982
2296
  void finalizeResetTransition(final String previousBundleName, final boolean internal) {
1983
- if (this.activity != null) {
1984
- DownloadWorkerManager.cancelAllDownloads(this.activity);
2297
+ if (this.context() != null) {
2298
+ DownloadWorkerManager.cancelAllDownloads(this.context());
1985
2299
  }
1986
2300
  if (!internal) {
1987
2301
  this.sendStats("reset", this.getCurrentBundle().getVersionName(), previousBundleName);
@@ -2159,8 +2473,8 @@ public class CapgoUpdater {
2159
2473
  final String asyncPreviousFallbackId = previousFallbackId;
2160
2474
  final String asyncPreviousFallbackVersion = previousFallbackVersion;
2161
2475
  io.execute(() -> {
2162
- if (this.activity != null) {
2163
- if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.activity, asyncPreviousFallbackVersion)) {
2476
+ if (this.context() != null) {
2477
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.context(), asyncPreviousFallbackVersion)) {
2164
2478
  logger.error("Failed to cancel previous version download before delete");
2165
2479
  return;
2166
2480
  }
@@ -3542,6 +3856,16 @@ public class CapgoUpdater {
3542
3856
  return this.getBundleInfo(id);
3543
3857
  }
3544
3858
 
3859
+ public boolean clearNextBundleIfCurrent() {
3860
+ final BundleInfo next = this.getNextBundle();
3861
+ if (next == null || !next.getId().equals(this.getCurrentBundle().getId())) {
3862
+ return false;
3863
+ }
3864
+ logger.info("Next bundle " + next.getId() + " is already the current bundle. Clearing next.");
3865
+ this.setNextBundle(null);
3866
+ return true;
3867
+ }
3868
+
3545
3869
  public BundleInfo getPreviewFallbackBundle() {
3546
3870
  final String id = this.prefs.getString(PREVIEW_FALLBACK_VERSION, null);
3547
3871
  if (id == null) return null;