Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[mobile] Wire native background processing for internal users

laurenspriem389b996bf52c
diff --git a/mobile/apps/photos/android/app/build.gradle b/mobile/apps/photos/android/app/build.gradle
index a963ffcb28..c1faa29c0a 100644
--- a/mobile/apps/photos/android/app/build.gradle
+++ b/mobile/apps/photos/android/app/build.gradle
@@ -56,6 +56,9 @@ configurations.configureEach {
android {
namespace = "io.ente.photos"
+ buildFeatures {
+ buildConfig = true
+ }
compileOptions {
coreLibraryDesugaringEnabled = true
diff --git a/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/EnteApplication.kt b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/EnteApplication.kt
index 641988ebd1..25bc6c0742 100644
--- a/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/EnteApplication.kt
+++ b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/EnteApplication.kt
@@ -11,22 +11,32 @@ import dev.fluttercommunity.workmanager.TaskDebugInfo
import dev.fluttercommunity.workmanager.TaskResult
import dev.fluttercommunity.workmanager.WorkmanagerDebug
import dev.fluttercommunity.workmanager.pigeon.TaskStatus
-import org.json.JSONObject
+import io.ente.background.BackgroundManagerPlugin
import kotlin.random.Random
+import org.json.JSONObject
class EnteApplication : Application() {
override fun onCreate() {
super.onCreate()
WorkmanagerDebug.setCurrent(EnteWorkmanagerDebugHandler())
ForegroundHeartbeat.install(this)
+ BackgroundManagerPlugin.install(this) {
+ val prefs = getSharedPreferences(FLUTTER_SHARED_PREFERENCES, Context.MODE_PRIVATE)
+ !prefs.getBoolean(INTERNAL_USER_DISABLED_KEY, false) &&
+ (BuildConfig.DEBUG ||
+ runCatching {
+ JSONObject(prefs.getString(REMOTE_FLAGS_KEY, "{}") ?: "{}").opt("internalUser") ==
+ true
+ }
+ .getOrDefault(false))
+ }
}
companion object {
const val FLUTTER_SHARED_PREFERENCES = "FlutterSharedPreferences"
const val REMOTE_FLAGS_KEY = "flutter.remote_flags"
const val INTERNAL_USER_DISABLED_KEY = "flutter.ls.internal_user_disabled"
- const val BG_DEBUG_NOTIFICATIONS_ENABLED_KEY =
- "flutter.ls.bg_debug_notifications_enabled"
+ const val BG_DEBUG_NOTIFICATIONS_ENABLED_KEY = "flutter.ls.bg_debug_notifications_enabled"
const val TAG = "EnteApplication"
}
}
@@ -90,14 +100,15 @@ private class EnteWorkmanagerDebugHandler : WorkmanagerDebug() {
return runCatching {
JSONObject(remoteFlags).optBoolean("internalUser", false)
- }.getOrElse {
- Log.w(
- EnteApplication.TAG,
- "Failed to parse remote flags for Workmanager debug handler",
- it,
- )
- false
}
+ .getOrElse {
+ Log.w(
+ EnteApplication.TAG,
+ "Failed to parse remote flags for Workmanager debug handler",
+ it,
+ )
+ false
+ }
}
private fun formatNotification(
@@ -152,15 +163,16 @@ private class EnteWorkmanagerDebugHandler : WorkmanagerDebug() {
private fun ensureNotificationChannel(notificationManager: NotificationManager) {
val channel =
NotificationChannel(
- CHANNEL_ID,
- CHANNEL_NAME,
- NotificationManager.IMPORTANCE_MIN,
- ).apply {
- setSound(null, null)
- enableVibration(false)
- vibrationPattern = longArrayOf(0L)
- setShowBadge(false)
- }
+ CHANNEL_ID,
+ CHANNEL_NAME,
+ NotificationManager.IMPORTANCE_MIN,
+ )
+ .apply {
+ setSound(null, null)
+ enableVibration(false)
+ vibrationPattern = longArrayOf(0L)
+ setShowBadge(false)
+ }
notificationManager.createNotificationChannel(channel)
}
diff --git a/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/MainActivity.kt b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/MainActivity.kt
index e476242e4a..2b9af8571b 100644
--- a/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/MainActivity.kt
+++ b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/MainActivity.kt
@@ -1,11 +1,18 @@
package io.ente.photos
import android.content.Intent
+import android.os.Bundle
+import io.ente.background.BackgroundManagerPlugin
import io.flutter.embedding.android.FlutterFragmentActivity
import java.io.FileDescriptor
import java.io.PrintWriter
class MainActivity : FlutterFragmentActivity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ BackgroundManagerPlugin.onForeground()
+ super.onCreate(savedInstanceState)
+ }
+
override fun onNewIntent(intent: Intent) {
setIntent(intent)
super.onNewIntent(intent)
diff --git a/mobile/apps/photos/changes/native-background-processing.md b/mobile/apps/photos/changes/native-background-processing.md
new file mode 100644
index 0000000000..84220929a1
--- /dev/null
+++ b/mobile/apps/photos/changes/native-background-processing.md
@@ -0,0 +1 @@
+- Internal users now use Ente's native background manager for sync and ML processing, with cooperative stopping when the app opens. Other users continue using Workmanager.
diff --git a/mobile/apps/photos/ios/Podfile.lock b/mobile/apps/photos/ios/Podfile.lock
index c846dd5393..51c5b4f063 100644
--- a/mobile/apps/photos/ios/Podfile.lock
+++ b/mobile/apps/photos/ios/Podfile.lock
@@ -14,6 +14,8 @@ PODS:
- FlutterMacOS
- device_info_plus (0.0.1):
- Flutter
+ - ente_background_manager (0.0.1):
+ - Flutter
- ente_cast (0.0.1):
- Flutter
- ente_mail (0.0.1):
@@ -249,6 +251,7 @@ DEPENDENCIES:
- connectivity_plus (from `.symlinks/plugins/connectivity_plus/ios`)
- cupertino_http (from `.symlinks/plugins/cupertino_http/darwin`)
- device_info_plus (from `.symlinks/plugins/device_info_plus/ios`)
+ - ente_background_manager (from `.symlinks/plugins/ente_background_manager/ios`)
- ente_cast (from `.symlinks/plugins/ente_cast/ios`)
- ente_mail (from `.symlinks/plugins/ente_mail/ios`)
- ente_panorama_viewer (from `.symlinks/plugins/ente_panorama_viewer/ios`)
@@ -337,6 +340,8 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/cupertino_http/darwin"
device_info_plus:
:path: ".symlinks/plugins/device_info_plus/ios"
+ ente_background_manager:
+ :path: ".symlinks/plugins/ente_background_manager/ios"
ente_cast:
:path: ".symlinks/plugins/ente_cast/ios"
ente_mail:
@@ -448,6 +453,7 @@ SPEC CHECKSUMS:
connectivity_plus: cb623214f4e1f6ef8fe7403d580fdad517d2f7dd
cupertino_http: 94ac07f5ff090b8effa6c5e2c47871d48ab7c86c
device_info_plus: 21fcca2080fbcd348be798aa36c3e5ed849eefbe
+ ente_background_manager: f10e3bd64ccd32a3232f0fbacabdd5545af8d81e
ente_cast: a25feb3127397e5fc6aff03a12120916707757d4
ente_mail: 90753dd584f49ee092759a32d4143ca51db69641
ente_panorama_viewer: 87bb22e7868c3005314f80c05ee0787aa07edcd8
diff --git a/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj b/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
index ba96b8e348..5ad7e6f5d0 100644
--- a/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
+++ b/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
@@ -637,6 +637,7 @@
"${BUILT_PRODUCTS_DIR}/connectivity_plus/connectivity_plus.framework",
"${BUILT_PRODUCTS_DIR}/cupertino_http/cupertino_http.framework",
"${BUILT_PRODUCTS_DIR}/device_info_plus/device_info_plus.framework",
+ "${BUILT_PRODUCTS_DIR}/ente_background_manager/ente_background_manager.framework",
"${BUILT_PRODUCTS_DIR}/ente_cast/ente_cast.framework",
"${BUILT_PRODUCTS_DIR}/ente_mail/ente_mail.framework",
"${BUILT_PRODUCTS_DIR}/ente_panorama_viewer/ente_panorama_viewer.framework",
@@ -733,6 +734,7 @@
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/connectivity_plus.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/cupertino_http.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/device_info_plus.framework",
+ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_background_manager.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_cast.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_mail.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_panorama_viewer.framework",
@@ -1338,6 +1340,7 @@
PRODUCT_BUNDLE_IDENTIFIER = io.ente.frame.debug;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_ENABLE_EXPLICIT_MODULES = NO;
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
diff --git a/mobile/apps/photos/ios/Runner/AppDelegate.swift b/mobile/apps/photos/ios/Runner/AppDelegate.swift
index 12ce63d096..0fb4c63a5f 100644
--- a/mobile/apps/photos/ios/Runner/AppDelegate.swift
+++ b/mobile/apps/photos/ios/Runner/AppDelegate.swift
@@ -3,6 +3,7 @@ import Flutter
import UIKit
import UserNotifications
import app_links
+import ente_background_manager
import workmanager_apple
@main
@@ -33,6 +34,14 @@ import workmanager_apple
}
GeneratedPluginRegistrant.register(with: self)
+ BackgroundManagerPlugin.install(
+ isEnabled: { Self.shouldUseNativeBackgroundManager() },
+ registrant: { registry in GeneratedPluginRegistrant.register(with: registry) }
+ )
+ BackgroundManagerPlugin.registerTask(
+ identifier: "io.ente.photos.nativeBackgroundRefresh", processing: false)
+ BackgroundManagerPlugin.registerTask(
+ identifier: "io.ente.photos.nativeBackgroundProcessing", processing: true)
WorkmanagerPlugin.setPluginRegistrantCallback { registry in
GeneratedPluginRegistrant.register(with: registry)
}
@@ -63,19 +72,38 @@ import workmanager_apple
)
}
+ private static func shouldUseNativeBackgroundManager() -> Bool {
+ let defaults = UserDefaults.standard
+ guard !defaults.bool(forKey: "flutter.ls.internal_user_disabled") else {
+ return false
+ }
+ #if DEBUG
+ return true
+ #else
+ guard let remoteFlags = defaults.string(forKey: "flutter.remote_flags"),
+ let data = remoteFlags.data(using: .utf8),
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
+ else {
+ return false
+ }
+ return json["internalUser"] as? Bool ?? false
+ #endif
+ }
+
private func shouldEnableWorkmanagerDebugNotifications() -> Bool {
let defaults = UserDefaults.standard
if defaults.bool(forKey: "flutter.ls.internal_user_disabled") {
return false
}
- if !defaults.bool(forKey: "flutter.ls.bg_debug_notifications_enabled") &&
- defaults.object(forKey: "flutter.ls.bg_debug_notifications_enabled") != nil {
+ if !defaults.bool(forKey: "flutter.ls.bg_debug_notifications_enabled")
+ && defaults.object(forKey: "flutter.ls.bg_debug_notifications_enabled") != nil
+ {
return false
}
guard let remoteFlags = defaults.string(forKey: "flutter.remote_flags"),
- let data = remoteFlags.data(using: .utf8),
- let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
+ let data = remoteFlags.data(using: .utf8),
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
else {
return false
}
diff --git a/mobile/apps/photos/ios/Runner/Info.plist b/mobile/apps/photos/ios/Runner/Info.plist
index 9ed105b40f..6c1fe95679 100644
--- a/mobile/apps/photos/ios/Runner/Info.plist
+++ b/mobile/apps/photos/ios/Runner/Info.plist
@@ -6,6 +6,8 @@
<array>
<string>io.ente.frame.iOSBackgroundAppRefresh</string>
<string>io.ente.frame.iOSBackgroundProcessing</string>
+ <string>io.ente.photos.nativeBackgroundRefresh</string>
+ <string>io.ente.photos.nativeBackgroundProcessing</string>
</array>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
diff --git a/mobile/apps/photos/lib/app.dart b/mobile/apps/photos/lib/app.dart
index e35d4ab556..8d95b39578 100644
--- a/mobile/apps/photos/lib/app.dart
+++ b/mobile/apps/photos/lib/app.dart
@@ -27,7 +27,7 @@ import 'package:photos/services/sync/sync_service.dart';
import "package:photos/ui/picker/external_media_picker_page.dart";
import 'package:photos/ui/tabs/home_widget.dart';
import "package:photos/ui/viewer/actions/file_viewer.dart";
-import "package:photos/utils/bg_task_utils.dart";
+import "package:photos/utils/background_tasks.dart";
import "package:photos/utils/intent_util.dart";
class EnteApp extends StatefulWidget {
@@ -142,7 +142,7 @@ class _EnteAppState extends State<EnteApp> with WidgetsBindingObserver {
final lifecycleAction = _appLifecycleActionFor(mediaExtentionAction);
AppLifecycleService.instance.setMediaExtensionAction(lifecycleAction);
if (lifecycleAction.action == IntentAction.main) {
- unawaited(BgTaskUtils.configureWorkmanager());
+ unawaited(BackgroundTasks.configure().catchError((Object _) {}));
}
if (mediaExtentionAction.action == IntentAction.pick) {
return ExternalMediaPickerPage(
@@ -264,8 +264,8 @@ class _EnteAppState extends State<EnteApp> with WidgetsBindingObserver {
}
unawaited(_reloadCachesUpdatedInBackground(lastAppOpenTime));
SyncService.instance.sync();
+ unawaited(BackgroundTasks.configure().catchError((Object _) {}));
if (Platform.isIOS) {
- unawaited(BgTaskUtils.ensureIOSProcessingTaskScheduled());
MLService.instance.triggerML();
}
} else {
diff --git a/mobile/apps/photos/lib/core/configuration.dart b/mobile/apps/photos/lib/core/configuration.dart
index 7f35117f89..bc7819e7b9 100644
--- a/mobile/apps/photos/lib/core/configuration.dart
+++ b/mobile/apps/photos/lib/core/configuration.dart
@@ -5,6 +5,7 @@ import "dart:io";
import 'package:backup_exclusion/backup_exclusion.dart';
import 'package:bip39/bip39.dart' as bip39;
import 'package:ente_account_deletion/account_deletion.dart';
+import 'package:ente_background_manager/ente_background_manager.dart';
import 'package:ente_contacts/contacts.dart';
import "package:ente_crypto/ente_crypto.dart";
import 'package:ente_lock_screen/lock_screen_host.dart';
@@ -36,6 +37,7 @@ import 'package:photos/events/user_logged_out_event.dart';
import 'package:photos/gateways/users/models/key_attributes.dart';
import 'package:photos/gateways/users/models/key_gen_result.dart';
import 'package:photos/gateways/users/models/private_key_attributes.dart';
+import 'package:photos/main.dart' show isProcessBg;
import 'package:photos/module/upload/upload_artifact.dart';
import 'package:photos/service_locator.dart';
import 'package:photos/services/authenticated_session.dart';
@@ -196,6 +198,11 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
Future<void> logout({bool autoLogout = false}) async {
_logger.info("Logging out, autoLogout: $autoLogout");
MLService.instance.stopActiveRun(MlStopReason.logout);
+ if (isProcessBg) {
+ unawaited(BackgroundManager.stopActiveRun());
+ } else {
+ await BackgroundManager.stopActiveRun();
+ }
if (!autoLogout) {
if (flagService.stopStreamProcess) {
VideoPreviewService.instance.stop('logout');
diff --git a/mobile/apps/photos/lib/main.dart b/mobile/apps/photos/lib/main.dart
index 87272af4e3..da8e34f734 100644
--- a/mobile/apps/photos/lib/main.dart
+++ b/mobile/apps/photos/lib/main.dart
@@ -4,6 +4,7 @@ import 'dart:io';
import "package:adaptive_theme/adaptive_theme.dart";
import "package:computer/computer.dart";
import "package:ente_account_deletion/account_deletion.dart";
+import "package:ente_background_manager/ente_background_manager.dart";
import "package:ente_components/ente_components.dart" as components;
import 'package:ente_crypto/ente_crypto.dart';
import "package:ente_crypto_api/ente_crypto_api.dart" show registerCryptoApi;
@@ -46,6 +47,7 @@ import 'package:photos/services/collections_service.dart';
import 'package:photos/services/favorites_service.dart';
import 'package:photos/services/home_widget_service.dart';
import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
+import "package:photos/services/machine_learning/ml_process_lock.dart";
import "package:photos/services/machine_learning/ml_run_control.dart";
import 'package:photos/services/machine_learning/ml_service.dart';
import 'package:photos/services/machine_learning/semantic_search/semantic_search_service.dart';
@@ -65,6 +67,7 @@ import "package:photos/services/video_preview_service.dart";
import "package:photos/src/rust/api/log.dart" as photos_rust_log;
import "package:photos/src/rust/frb_generated.dart";
import 'package:photos/ui/wallpaper/wallpaper_page.dart';
+import "package:photos/utils/background_tasks.dart";
import "package:photos/utils/bg_task_utils.dart";
import "package:photos/utils/device_info.dart";
import "package:photos/utils/email_util.dart";
@@ -245,10 +248,33 @@ Future<void> runBackgroundTask(
String mode = 'normal',
Duration? mlSelfStop,
Duration? mlLockWait,
+ BackgroundTask? nativeTask,
}) async {
// Created at task start so a stop that fires before ML begins stays
// latched for the whole task.
final mlRunControl = MlRunControl();
+ var finished = false;
+ var switchingBackend = false;
+ bool shouldStop() =>
+ finished || switchingBackend || nativeTask?.isStopping == true;
+ void checkStop() {
+ if (shouldStop()) throw const BackgroundTaskStopped();
+ }
+
+ SyncService.instance.setBackgroundStopCheck(shouldStop);
+ if (nativeTask != null) {
+ unawaited(
+ nativeTask.stopped.then((reason) {
+ if (finished) return;
+ mlRunControl.requestStop(
+ reason == BackgroundStopReason.foreground
+ ? MlStopReason.foregroundActive
+ : MlStopReason.backgroundDeadline,
+ );
+ SyncService.instance.stopSync();
+ }),
+ );
+ }
final mlBudget =
mlSelfStop ??
(Platform.isIOS ? kBGTaskMLSelfStopIOS : kBGTaskMLSelfStopAndroid);
@@ -261,18 +287,26 @@ Future<void> runBackgroundTask(
() => mlRunControl.requestStop(MlStopReason.backgroundDeadline),
)
: null;
- final mlForegroundWatchTimer = Timer.periodic(
- const Duration(milliseconds: 500),
- (_) async {
- if (mlRunControl.stopRequested) return;
- if (await isForegroundEngineActive()) {
- mlRunControl.requestStop(MlStopReason.foregroundActive);
- }
- },
- );
+ final mlForegroundWatchTimer = nativeTask != null
+ ? null
+ : Timer.periodic(const Duration(milliseconds: 500), (_) async {
+ if (finished) return;
+ final prefs = await SharedPreferences.getInstance();
+ if (await BackgroundTasks.nativeEnabled(prefs)) {
+ switchingBackend = true;
+ mlRunControl.requestStop(MlStopReason.manual);
+ SyncService.instance.stopSync();
+ }
+ if (mlRunControl.stopRequested) return;
+ if (await isForegroundEngineActive()) {
+ mlRunControl.requestStop(MlStopReason.foregroundActive);
+ }
+ });
try {
- final isRunningInFG = await isForegroundEngineActive();
+ checkStop();
+ final isRunningInFG =
+ nativeTask == null && await isForegroundEngineActive();
if (isRunningInFG) {
_logger.info(
"[BG TASK] Foreground recently active, skipping background work",
@@ -284,10 +318,18 @@ Future<void> runBackgroundTask(
"[BG TASK] No recent foreground activity, proceeding with background work",
);
- await _runMinimally(taskId, tlog, mlRunControl, mlLockWait);
+ await _runMinimally(
+ taskId,
+ tlog,
+ mlRunControl,
+ mlLockWait,
+ checkStop: checkStop,
+ propagateFailure: nativeTask != null,
+ );
} finally {
+ finished = true;
mlSelfStopTimer?.cancel();
- mlForegroundWatchTimer.cancel();
+ mlForegroundWatchTimer?.cancel();
}
}
@@ -295,13 +337,18 @@ Future<void> _runMinimally(
String taskId,
TimeLogger tlog,
MlRunControl mlRunControl,
- Duration? mlLockWait,
-) async {
+ Duration? mlLockWait, {
+ required void Function() checkStop,
+ required bool propagateFailure,
+}) async {
try {
+ var successful = true;
+ checkStop();
final PackageInfo packageInfo = await PackageInfo.fromPlatform();
final SharedPreferences prefs = await SharedPreferences.getInstance();
await _scheduleHeartBeat(prefs, true);
await _ensureRustInitialized(via: 'workmanager:$taskId');
+ checkStop();
_logger.info("[BG TASK] NetworkClient init $tlog");
await NetworkClient.instance.init(packageInfo, prefs);
@@ -321,6 +368,7 @@ Future<void> _runMinimally(
_logger.info("(for debugging) Configuration init $tlog");
await Configuration.instance.init(prefs);
+ checkStop();
_logger.info("(for debugging) Configuration done $tlog");
AppLifecycleService.instance.init(prefs);
@@ -329,18 +377,22 @@ Future<void> _runMinimally(
);
await Computer.shared().turnOn(workersCount: 4);
+ checkStop();
CryptoUtil.init();
// Initialize early so thermal/battery listeners can warm up while the
// rest of background services are being initialized.
final controller = computeController;
await MemoryShareService.instance.init();
+ checkStop();
_logger.info("(for debugging) CollectionsService init $tlog");
await CollectionsService.instance.init(prefs);
+ checkStop();
_logger.info("(for debugging) CollectionsService init done $tlog");
await FileUploader.instance.init(prefs, true);
+ checkStop();
LocalFileUpdateService.instance.init(prefs);
await LocalSyncService.instance.init(prefs);
RemoteSyncService.instance.init(prefs);
@@ -348,18 +400,25 @@ Future<void> _runMinimally(
_isSyncInitialized = true;
await UserService.instance.init();
+ checkStop();
SocialNotificationCoordinator.instance.init(prefs);
await NotificationService.instance.initializeForBackground();
_logger.info("[BG TASK] update notification");
updateService.showUpdateNotification().ignore();
_logger.info("[BG TASK] sync starting");
- await _sync('bgTaskActiveProcess');
+ if (propagateFailure) {
+ successful = await SyncService.instance.sync();
+ } else {
+ await _sync('bgTaskActiveProcess');
+ }
+ checkStop();
_logger.info("[BG TASK] sync completed");
_logger.info("[BG TASK] locale fetch");
final locale = await getLocale();
await initializeDateFormatting(locale?.languageCode ?? "en");
+ checkStop();
_logger.info("[BG TASK] home widget sync");
if (!isLocalGalleryMode &&
hasGrantedMLConsent &&
@@ -377,10 +436,12 @@ Future<void> _runMinimally(
}
}
await _homeWidgetSync(true);
+ checkStop();
if ((isLocalGalleryMode || flagService.enableMLInBackground) &&
hasGrantedMLConsent) {
await controller.init();
+ checkStop();
final canRunML = controller.requestCompute(ml: true);
if (!canRunML) {
_logger.info(
@@ -397,17 +458,26 @@ Future<void> _runMinimally(
lockWait: mlLockWait,
);
_logger.info("[BG TASK] ML run disposition: ${disposition.name}");
+ if (disposition == MlRunDisposition.failed) successful = false;
} finally {
controller.releaseCompute(ml: true);
}
}
}
_logger.info("[BG TASK] smart albums sync");
+ checkStop();
await smartAlbumsService.syncSmartAlbums();
+ checkStop();
+ if (propagateFailure && !successful) {
+ throw StateError("Background work reported a failure");
+ }
_logger.info("[BG TASK] $taskId completed");
+ } on BackgroundTaskStopped {
+ if (propagateFailure) rethrow;
} catch (e, s) {
_logger.severe("[BG TASK] $taskId error", e, s);
+ if (propagateFailure) rethrow;
}
}
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
index 05feb84134..67e1ea3ade 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
@@ -607,7 +607,11 @@ class MLService {
);
}
final Stream<List<FileMLInstruction>> instructionStream =
- fetchEmbeddingsAndInstructions(fileDownloadMlLimit, mode: mode);
+ fetchEmbeddingsAndInstructions(
+ fileDownloadMlLimit,
+ mode: mode,
+ control: control,
+ );
int fileAnalyzedCount = 0;
final Stopwatch stopwatch = Stopwatch()..start();
diff --git a/mobile/apps/photos/lib/services/sync/local_sync_service.dart b/mobile/apps/photos/lib/services/sync/local_sync_service.dart
index a7d5302302..cd565102ec 100644
--- a/mobile/apps/photos/lib/services/sync/local_sync_service.dart
+++ b/mobile/apps/photos/lib/services/sync/local_sync_service.dart
@@ -26,6 +26,7 @@ import "package:photos/services/sync/import/diff.dart";
import "package:photos/services/sync/import/local_assets.dart";
import "package:photos/services/sync/import/model.dart";
import "package:photos/services/sync/origin_fetch_tracker.dart";
+import "package:photos/services/sync/sync_service.dart";
import "package:shared_preferences/shared_preferences.dart";
import "package:synchronized/synchronized.dart";
import "package:tuple/tuple.dart";
@@ -76,6 +77,7 @@ class LocalSyncService {
}
Future<void> sync() async {
+ if (SyncService.instance.backgroundWorkStopped) return;
if (!permissionService.hasGrantedPermissions()) {
_logger.info("Skipping local sync since permission has not been granted");
return;
@@ -101,7 +103,7 @@ class LocalSyncService {
// Local sync must not race downloads; that can create incorrect FilesDB
// rows.
- await _lock.synchronized(() async {
+ final localSync = _lock.synchronized(() async {
final existingLocalFileIDs = await _db.getExistingLocalFileIDs(ownerID);
_logger.info("${existingLocalFileIDs.length} localIDs were discovered");
@@ -122,6 +124,7 @@ class LocalSyncService {
var toYear = 2010;
var toTime = DateTime(toYear).microsecondsSinceEpoch;
while (toTime < syncStartTime) {
+ SyncService.instance.checkBackgroundWork();
await _loadAndStoreDiff(
existingLocalFileIDs,
fromTime: startTime,
@@ -160,9 +163,12 @@ class LocalSyncService {
final duration = Duration(microseconds: endTime - startTime);
_logger.info("Load took " + duration.inMilliseconds.toString() + "ms");
});
-
- _existingSync?.complete();
- _existingSync = null;
+ try {
+ await localSync;
+ } finally {
+ _existingSync?.complete();
+ _existingSync = null;
+ }
}
Future<bool> _refreshDeviceFolderCountAndCover({
@@ -182,6 +188,7 @@ class LocalSyncService {
}
Future<bool> syncAll() async {
+ if (SyncService.instance.backgroundWorkStopped) return false;
if (!Configuration.instance.isLoggedIn()) {
if (!isLocalGalleryMode) {
_logger.warning("syncAll called when user is not logged in");
@@ -193,6 +200,7 @@ class LocalSyncService {
final localAssets = await getAllLocalAssets(
needsTitle: isLocalGalleryMode ? true : null,
);
+ SyncService.instance.checkBackgroundWork();
_logger.info(
"Loading allLocalAssets ${localAssets.length} took ${stopwatch.elapsedMilliseconds}ms ",
);
@@ -210,6 +218,7 @@ class LocalSyncService {
existingLocalFileIDs,
pathToLocalIDs,
);
+ SyncService.instance.checkBackgroundWork();
bool hasAnyMappingChanged = false;
if (localDiffResult.newPathToLocalIDs?.isNotEmpty ?? false) {
await _db.insertPathIDToLocalIDMapping(
diff --git a/mobile/apps/photos/lib/services/sync/remote_sync_service.dart b/mobile/apps/photos/lib/services/sync/remote_sync_service.dart
index 00457b3ae9..b80952aa6a 100644
--- a/mobile/apps/photos/lib/services/sync/remote_sync_service.dart
+++ b/mobile/apps/photos/lib/services/sync/remote_sync_service.dart
@@ -99,6 +99,7 @@ class RemoteSyncService {
}
Future<void> sync({bool silently = false}) async {
+ if (SyncService.instance.backgroundWorkStopped) return;
if (!_config.hasConfiguredAccount()) {
_logger.info("Skipping remote sync since account is not configured");
return;
@@ -129,7 +130,9 @@ class RemoteSyncService {
await syncDeviceCollectionFilesForUpload();
}
await _pullDiff();
+ SyncService.instance.checkBackgroundWork();
await trashSyncService.syncTrash();
+ SyncService.instance.checkBackgroundWork();
await _collectionsService.movePendingRemovalActionsToUncategorized();
if (AppLifecycleService.instance.isForeground) {
@@ -154,7 +157,9 @@ class RemoteSyncService {
}
final filesToBeUploaded = await _getFilesToBeUploaded();
+ SyncService.instance.checkBackgroundWork();
final hasUploadedFiles = await _uploadFiles(filesToBeUploaded);
+ SyncService.instance.checkBackgroundWork();
if (filesToBeUploaded.isNotEmpty) {
_logger.info(
"Files ${filesToBeUploaded.length} queued for upload, completed: "
@@ -190,6 +195,10 @@ class RemoteSyncService {
_existingSync?.complete();
_existingSync = null;
}
+ } on SyncStopRequestedError {
+ _existingSync?.complete();
+ _existingSync = null;
+ rethrow;
} catch (e, s) {
_existingSync?.complete();
_existingSync = null;
@@ -256,6 +265,7 @@ class RemoteSyncService {
final Map<int, int> idsToRemoteUpdationTimeMap,
) async {
for (final cid in idsToRemoteUpdationTimeMap.keys) {
+ SyncService.instance.checkBackgroundWork();
await _syncCollectionDiff(
cid,
_collectionsService.getCollectionSyncTime(cid),
@@ -273,6 +283,7 @@ class RemoteSyncService {
_logger.info('re-setting all collections syncTime to: $resetSyncTime');
final collections = _collectionsService.getActiveCollections();
for (final c in collections) {
+ SyncService.instance.checkBackgroundWork();
final int newSyncTime = min(
_collectionsService.getCollectionSyncTime(c.id),
resetSyncTime,
@@ -282,6 +293,7 @@ class RemoteSyncService {
}
Future<void> _syncCollectionDiff(int collectionID, int sinceTime) async {
+ SyncService.instance.checkBackgroundWork();
_logger.info(
"[Collection-$collectionID] fetch diff silently: $_isExistingSyncSilent "
"since: $sinceTime",
@@ -392,6 +404,7 @@ class RemoteSyncService {
bool moreFilesMarkedForBackup = false;
for (final deviceCollection in deviceCollections) {
+ SyncService.instance.checkBackgroundWork();
final Set<String> localIDsToSync =
pathIdToLocalIDs[deviceCollection.id]?.toSet() ?? {};
if (deviceCollection.uploadStrategy == UploadStrategy.ifMissing) {
@@ -526,6 +539,7 @@ class RemoteSyncService {
Future<void> removeFilesQueuedForUpload(List<int> collectionIDs) async {
_logger.info("Removing files for collections $collectionIDs");
for (int collectionID in collectionIDs) {
+ SyncService.instance.checkBackgroundWork();
final List<EnteFile> pendingUploads = await _db
.getPendingUploadForCollection(collectionID);
if (pendingUploads.isEmpty) {
@@ -666,6 +680,7 @@ class RemoteSyncService {
}
for (final file in uploadQueue) {
+ if (SyncService.instance.shouldStopSync()) break;
if (shouldThrottleUpload &&
futures.length >= kMaximumPermissibleUploadsInThrottledMode) {
break;
@@ -682,6 +697,7 @@ class RemoteSyncService {
}
for (final uploadedFileID in updatedFileIDs) {
+ if (SyncService.instance.shouldStopSync()) break;
if (shouldThrottleUpload &&
futures.length >= kMaximumPermissibleUploadsInThrottledMode) {
break;
diff --git a/mobile/apps/photos/lib/services/sync/sync_service.dart b/mobile/apps/photos/lib/services/sync/sync_service.dart
index f3751c6c18..6580ecb0bd 100644
--- a/mobile/apps/photos/lib/services/sync/sync_service.dart
+++ b/mobile/apps/photos/lib/services/sync/sync_service.dart
@@ -33,6 +33,7 @@ class SyncService {
final _uploader = FileUploader.instance;
bool _syncStopRequested = false;
Completer<bool>? _existingSync;
+ bool Function()? _backgroundStopCheck;
late SharedPreferences _prefs;
SyncStatusUpdate? _lastSyncStatusEvent;
bool _isInitialized = false;
@@ -112,6 +113,7 @@ class SyncService {
}
Future<bool> sync() async {
+ if (_backgroundStopCheck?.call() == true) return false;
if (!_isInitialized) {
_logger.warning("Sync requested before init, skipping");
return false;
@@ -196,9 +198,19 @@ class SyncService {
}
bool shouldStopSync() {
- return _syncStopRequested;
+ return _syncStopRequested || _backgroundStopCheck?.call() == true;
}
+ void setBackgroundStopCheck(bool Function() check) {
+ _backgroundStopCheck = check;
+ }
+
+ void checkBackgroundWork() {
+ if (backgroundWorkStopped) throw SyncStopRequestedError();
+ }
+
+ bool get backgroundWorkStopped => _backgroundStopCheck?.call() == true;
+
bool isSyncInProgress() {
return _existingSync != null;
}
@@ -230,10 +242,13 @@ class SyncService {
}
Future<void> _doSync() async {
+ checkBackgroundWork();
_logger.info("[SYNC] Starting local sync");
await _localSyncService.sync();
+ checkBackgroundWork();
if (isLocalGalleryMode) {
await _localSyncService.syncAll();
+ checkBackgroundWork();
if (Platform.isAndroid) {
final processing = OfflineImportMetadataService.instance
.processPendingFiles(
@@ -260,8 +275,10 @@ class SyncService {
if (allowRemoteSync) {
_logger.info("[SYNC] Starting remote sync");
await _remoteSyncService.sync();
+ checkBackgroundWork();
final shouldSync = await _localSyncService.syncAll();
+ checkBackgroundWork();
if (shouldSync) {
_logger.info("[SYNC] Starting second remote sync");
await _remoteSyncService.sync();
diff --git a/mobile/apps/photos/lib/ui/settings/debug/debug_settings_page.dart b/mobile/apps/photos/lib/ui/settings/debug/debug_settings_page.dart
index 817463667d..7d9343645e 100644
--- a/mobile/apps/photos/lib/ui/settings/debug/debug_settings_page.dart
+++ b/mobile/apps/photos/lib/ui/settings/debug/debug_settings_page.dart
@@ -14,6 +14,7 @@ import "package:photos/ui/home/christmas/christmas_utils.dart";
import "package:photos/ui/notification/toast.dart";
import "package:photos/ui/notification/update/change_log_page.dart";
import "package:photos/ui/settings/debug/social_debug_screen.dart";
+import "package:photos/utils/background_tasks.dart";
class DebugSettingsPage extends StatefulWidget {
const DebugSettingsPage({super.key});
@@ -68,6 +69,9 @@ class _DebugSettingsPageState extends State<DebugSettingsPage> {
await localSettings.setInternalUserDisabled(
newValue,
);
+ await BackgroundTasks.configure().catchError(
+ (Object _) {},
+ );
if (!mounted) return;
setState(() {});
if (!context.mounted) return;
diff --git a/mobile/apps/photos/lib/utils/background_tasks.dart b/mobile/apps/photos/lib/utils/background_tasks.dart
new file mode 100644
index 0000000000..95a6f5b10b
--- /dev/null
+++ b/mobile/apps/photos/lib/utils/background_tasks.dart
@@ -0,0 +1,222 @@
+import "dart:async";
+import "dart:convert";
+import "dart:io";
+
+import "package:computer/computer.dart";
+import "package:ente_background_manager/ente_background_manager.dart";
+import "package:ente_photos_platform/ente_photos_platform.dart";
+import "package:ente_pure_utils/ente_pure_utils.dart";
+import "package:flutter/foundation.dart";
+import "package:logging/logging.dart";
+import "package:permission_handler/permission_handler.dart";
+import "package:photos/main.dart";
+import "package:photos/utils/bg_task_utils.dart";
+import "package:shared_preferences/shared_preferences.dart";
+import "package:workmanager/workmanager.dart" as legacy;
+
+@pragma("vm:entry-point")
+void nativeBackgroundDispatcher() {
+ unawaited(BackgroundManager.executeTask(BackgroundTasks.execute));
+}
+
+class BackgroundTasks {
+ static final _logger = Logger("BackgroundTasks");
+ static const refresh = "io.ente.photos.nativeBackgroundRefresh";
+ static const processing = "io.ente.photos.nativeBackgroundProcessing";
+ static Future<void> _configuration = Future.value();
+ static bool? _configuredNative;
+
+ static Future<void> configure() {
+ final next = _configuration.then((_) => _configure());
+ _configuration = next.catchError((Object error, StackTrace stack) {
+ _logger.warning("Background configuration failed", error, stack);
+ });
+ return next;
+ }
+
+ static Future<void> _configure() async {
+ final useNative = await nativeEnabled(
+ await SharedPreferences.getInstance(),
+ );
+ if (!useNative) {
+ if (_configuredNative != false) {
+ try {
+ await _configureNative(enabled: false);
+ } catch (error, stack) {
+ _logger.warning("Failed to disable native scheduling", error, stack);
+ }
+ await BgTaskUtils.configureWorkmanager();
+ _configuredNative = false;
+ } else if (Platform.isIOS) {
+ await BgTaskUtils.ensureIOSProcessingTaskScheduled();
+ }
+ return;
+ }
+ if (Platform.isIOS) await retireLegacySchedules();
+ await _configureNative(enabled: true);
+ _configuredNative = true;
+ if (Platform.isAndroid && !isProcessBg) {
+ final acquired = await ProcessLockClient.instance.tryAcquire(
+ name: "background_process",
+ origin: "fg",
+ operation: "backgroundBackendChange",
+ );
+ if (acquired) {
+ try {
+ await retireLegacySchedules();
+ } finally {
+ await ProcessLockClient.instance.release(name: "background_process");
+ }
+ }
+ }
+ }
+
+ static Future<void> _configureNative({required bool enabled}) async {
+ final allowRefresh =
+ enabled &&
+ (!Platform.isIOS || await Permission.backgroundRefresh.isGranted);
+ await BackgroundManager.configure(
+ dispatcher: nativeBackgroundDispatcher,
+ tasks: enabled
+ ? [
+ if (allowRefresh)
+ BackgroundTaskConfig(
+ identifier: refresh,
+ kind: BackgroundTaskKind.refresh,
+ frequency: Duration(minutes: Platform.isIOS ? 30 : 15),
+ initialDelay: kDebugMode
+ ? Duration.zero
+ : const Duration(minutes: 10),
+ requiresNetwork: Platform.isAndroid,
+ runBudget: Platform.isIOS
+ ? BgTaskUtils.taskTimeoutFor(
+ BgTaskUtils.iOSBackgroundAppRefreshTask,
+ )
+ : BgTaskUtils.mlSelfStopFor(
+ BgTaskUtils.androidPeriodicTask,
+ ),
+ ),
+ BackgroundTaskConfig(
+ identifier: processing,
+ kind: BackgroundTaskKind.processing,
+ frequency: Platform.isIOS
+ ? const Duration(minutes: 30)
+ : const Duration(hours: 2),
+ initialDelay: Platform.isIOS && !kDebugMode
+ ? const Duration(minutes: 30)
+ : Duration.zero,
+ flexInterval: Platform.isAndroid
+ ? const Duration(hours: 2)
+ : null,
+ requiresNetwork: true,
+ requiresCharging: true,
+ requiresDeviceIdle: Platform.isAndroid,
+ runBudget: Platform.isIOS
+ ? BgTaskUtils.taskTimeoutFor(
+ BgTaskUtils.iOSBackgroundProcessingTask,
+ )
+ : BgTaskUtils.mlSelfStopFor(
+ BgTaskUtils.androidBackgroundProcessingTask,
+ ),
+ ),
+ ]
+ : [],
+ enabled: enabled,
+ onOutcome: (outcome) {
+ _logger.info(
+ "${outcome.identifier}: ${outcome.outcome.name}"
+ "${outcome.reason == null ? '' : ' (${outcome.reason})'}"
+ "${outcome.error == null ? '' : ': ${outcome.error}'}",
+ );
+ },
+ );
+ }
+
+ static Future<bool> nativeEnabled(SharedPreferences prefs) async {
+ await prefs.reload();
+ if (prefs.getBool("ls.internal_user_disabled") == true) {
+ return false;
+ }
+ if (kDebugMode) return true;
+ try {
+ final flags = jsonDecode(prefs.getString("remote_flags") ?? "{}");
+ return flags is Map && flags["internalUser"] == true;
+ } catch (_) {
+ return false;
+ }
+ }
+
+ static Future<void> retireLegacySchedules() async {
+ BgTaskUtils.resetProcessingSchedule();
+ final identifiers = Platform.isIOS
+ ? [
+ BgTaskUtils.iOSBackgroundAppRefreshTask,
+ BgTaskUtils.iOSBackgroundProcessingTask,
+ ]
+ : [
+ BgTaskUtils.androidPeriodicTask,
+ BgTaskUtils.androidBackgroundProcessingTask,
+ ];
+ for (final identifier in identifiers) {
+ await legacy.Workmanager().cancelByUniqueName(identifier);
+ }
+ }
+
+ static Future<BackgroundTaskResult> execute(BackgroundTask task) async {
+ var result = BackgroundTaskResult.stopped;
+ await runWithLogs(
+ () async {
+ _logger.info("${task.identifier}: task started");
+ final prefs = await SharedPreferences.getInstance();
+ if (!await nativeEnabled(prefs)) {
+ _logger.info("${task.identifier}: skipped, native backend disabled");
+ result = BackgroundTaskResult.skipped;
+ return;
+ }
+ task.throwIfStopping();
+ final acquired = await ProcessLockClient.instance.tryAcquire(
+ name: "background_process",
+ origin: "bg",
+ operation: task.identifier,
+ );
+ if (!acquired) {
+ _logger.info("${task.identifier}: skipped, background pipeline busy");
+ result = BackgroundTaskResult.skipped;
+ return;
+ }
+ task.throwIfStopping();
+ await retireLegacySchedules();
+ final taskName = task.identifier == processing
+ ? (Platform.isIOS
+ ? BgTaskUtils.iOSBackgroundProcessingTask
+ : BgTaskUtils.androidBackgroundProcessingTask)
+ : (Platform.isIOS
+ ? BgTaskUtils.iOSBackgroundAppRefreshTask
+ : BgTaskUtils.androidPeriodicTask);
+ try {
+ await runBackgroundTask(
+ taskName,
+ TimeLogger(),
+ nativeTask: task,
+ mlSelfStop: BgTaskUtils.mlSelfStopFor(taskName) - task.elapsed,
+ mlLockWait: BgTaskUtils.mlLockWaitFor(taskName),
+ );
+ result = task.isStopping
+ ? BackgroundTaskResult.stopped
+ : BackgroundTaskResult.completed;
+ } on BackgroundTaskStopped {
+ result = BackgroundTaskResult.stopped;
+ } catch (error, stack) {
+ _logger.warning("${task.identifier}: task failed", error, stack);
+ result = BackgroundTaskResult.failed;
+ } finally {
+ await Computer.shared().turnOff();
+ }
+ _logger.info("${task.identifier}: task ${result.name}");
+ },
+ prefix: "[bg]",
+ sentryInitTimeout: const Duration(seconds: 5),
+ );
+ return result;
+ }
+}
diff --git a/mobile/apps/photos/lib/utils/bg_task_utils.dart b/mobile/apps/photos/lib/utils/bg_task_utils.dart
index 02442613dd..fa1255e45a 100644
--- a/mobile/apps/photos/lib/utils/bg_task_utils.dart
+++ b/mobile/apps/photos/lib/utils/bg_task_utils.dart
@@ -11,6 +11,7 @@ import "package:photos/db/upload_locks_db.dart";
import "package:photos/main.dart";
import "package:photos/module/upload/service/file_uploader.dart";
import "package:photos/services/process_activity.dart";
+import "package:photos/utils/background_tasks.dart";
import "package:shared_preferences/shared_preferences.dart";
import "package:workmanager/workmanager.dart" as workmanager;
@@ -37,6 +38,11 @@ void callbackDispatcher() {
() async {
try {
BgTaskUtils.$.info('Task started $tlog');
+ if (await BackgroundTasks.nativeEnabled(prefs)) {
+ await BackgroundTasks.configure();
+ failure = null;
+ return;
+ }
if (isIOSProcessingTask) {
await BgTaskUtils.scheduleIOSBackgroundProcessingTask();
}
@@ -50,6 +56,11 @@ void callbackDispatcher() {
failure = null;
return;
}
+ if (await BackgroundTasks.nativeEnabled(prefs)) {
+ await BackgroundTasks.configure();
+ failure = null;
+ return;
+ }
if (isIOSProcessingTask) {
await BgTaskUtils.markProcessingTaskStart(prefs);
}
@@ -103,6 +114,11 @@ void callbackDispatcher() {
return;
});
+ if (ownsPipeline &&
+ !timedOut &&
+ await BackgroundTasks.nativeEnabled(prefs)) {
+ await BackgroundTasks.configure().catchError((Object _) {});
+ }
final error = failure;
if (error != null) {
return Future.error(error);
@@ -262,7 +278,7 @@ class BgTaskUtils {
await prefs.remove(kLastBGTaskHeartBeatTime);
}
- static Future configureWorkmanager() async {
+ static Future<void> configureWorkmanager() async {
try {
await workmanager.Workmanager().initialize(callbackDispatcher);
if (Platform.isIOS) {
@@ -316,11 +332,16 @@ class BgTaskUtils {
}
} catch (e) {
$.warning("Failed to configure WorkManager: $e");
+ rethrow;
}
}
static bool _processingTaskArmedThisProcess = false;
+ static void resetProcessingSchedule() {
+ _processingTaskArmedThisProcess = false;
+ }
+
static Future<void> scheduleAndroidBackgroundProcessingTask() async {
await workmanager.Workmanager().registerPeriodicTask(
androidBackgroundProcessingTask,
@@ -348,6 +369,11 @@ class BgTaskUtils {
// Workmanager does not resubmit one-shot processing tasks.
static Future<bool> scheduleIOSBackgroundProcessingTask() async {
+ if (await BackgroundTasks.nativeEnabled(
+ await SharedPreferences.getInstance(),
+ )) {
+ return false;
+ }
try {
await workmanager.Workmanager().registerProcessingTask(
iOSBackgroundProcessingTask,
diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dart
index 022325edc7..74af09916c 100644
--- a/mobile/apps/photos/lib/utils/ml_util.dart
+++ b/mobile/apps/photos/lib/utils/ml_util.dart
@@ -407,12 +407,15 @@ Future<List<FileMLInstruction>> getLocalGalleryFilesForMlIndexing() async {
Stream<List<FileMLInstruction>> fetchEmbeddingsAndInstructions(
int yieldSize, {
required MLMode mode,
+ MlRunControl? control,
}) async* {
+ if (control?.stopRequested == true) return;
if (mode == MLMode.localGallery) {
final List<FileMLInstruction> filesToIndex =
await getLocalGalleryFilesForMlIndexing();
final List<List<FileMLInstruction>> chunks = filesToIndex.chunks(yieldSize);
for (final batch in chunks) {
+ if (control?.stopRequested == true) return;
yield batch;
}
return;
@@ -425,10 +428,12 @@ Stream<List<FileMLInstruction>> fetchEmbeddingsAndInstructions(
List<FileMLInstruction> batchToYield = [];
for (final chunk in chunks) {
+ if (control?.stopRequested == true) return;
if (!localSettings.remoteFetchEnabled) {
_logger.warning("remoteFetchEnabled is false, skiping embedding fetch");
final batches = chunk.chunks(yieldSize);
for (final batch in batches) {
+ if (control?.stopRequested == true) return;
yield batch;
}
continue;
@@ -437,6 +442,7 @@ Stream<List<FileMLInstruction>> fetchEmbeddingsAndInstructions(
chunk,
mlDataDB: mlDataDB,
);
+ if (control?.stopRequested == true) return;
for (final instruction in pendingInstructions) {
if (instruction.pendingML) {
batchToYield.add(instruction);
diff --git a/mobile/apps/photos/plugins/ente_background_manager/README.md b/mobile/apps/photos/plugins/ente_background_manager/README.md
index 73f7472712..65d5a51f1c 100644
--- a/mobile/apps/photos/plugins/ente_background_manager/README.md
+++ b/mobile/apps/photos/plugins/ente_background_manager/README.md
@@ -4,7 +4,7 @@ A Flutter plugin for native background scheduling and headless task execution. A
## Integration status
-The package is part of the mobile workspace. Photos does not depend on or initialize it yet; app integration is a separate change.
+Photos selects this plugin when `flagService.internalUser` is enabled. Other users retain the existing Workmanager integration. The app coordinates schedule migration and uses the existing process lock to exclude overlapping background work across backends. Foreground stopping is cooperative; Photos does not configure forced engine teardown.
## Consumer interface
diff --git a/mobile/apps/photos/pubspec.yaml b/mobile/apps/photos/pubspec.yaml
index 34ea9d1b33..dddce0908d 100644
--- a/mobile/apps/photos/pubspec.yaml
+++ b/mobile/apps/photos/pubspec.yaml
@@ -36,6 +36,8 @@ dependencies:
encrypt: 5.0.3
ente_account_deletion:
path: ../../packages/account_deletion
+ ente_background_manager:
+ path: plugins/ente_background_manager
ente_cast:
path: plugins/ente_cast
ente_components: