From c9faf62f09ce6ecbc4886b9bdc8813cc7711c25e Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 12:53:44 +0200 Subject: [PATCH] feat: Android syncs every fifteen minutes while closed (notifications, Phase 10) A WorkManager worker runs the full pass with a nine-minute deadline, scheduled from the application behind ExperimentalFeatures.backgroundSync. The settings screen says what each platform does while closed, and when it last did it. Co-Authored-By: Claude Opus 5.5 --- composeApp/build.gradle.kts | 5 ++ .../mobi/giza/android/GizaApplication.kt | 15 +++++ .../background/BackgroundSyncWorker.kt | 53 +++++++++++++++++ .../BackgroundSyncSection.android.kt | 16 +++++ .../composeResources/values/strings.xml | 7 +++ .../mobi/giza/compose/ExperimentalFeatures.kt | 12 ++++ .../compose/managers/BackgroundSyncPass.kt | 3 + .../notifications/BackgroundSyncSection.kt | 59 +++++++++++++++++++ .../composable/NotificationSettingsScreen.kt | 6 +- .../BackgroundSyncSection.ios.kt | 30 ++++++++++ .../BackgroundSyncSection.jvm.kt | 16 +++++ .../managers/BackgroundSyncPassJvmTest.kt | 8 +++ gradle/libs.versions.toml | 2 + 13 files changed, 229 insertions(+), 3 deletions(-) create mode 100644 composeApp/src/androidMain/kotlin/mobi/giza/android/background/BackgroundSyncWorker.kt create mode 100644 composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.android.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.kt create mode 100644 composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.ios.kt create mode 100644 composeApp/src/jvmMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.jvm.kt diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index fc55a404..87cf83d6 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -63,6 +63,11 @@ kotlin { implementation("fr.acinq.secp256k1:secp256k1-kmp-jni-android:0.24.0") implementation(libs.androidx.activity.compose) + + // The periodic background sync (docs/notifications-and-background-sync.md, Phase 10): + // WorkManager reschedules itself across reboots and respects Doze, which a hand-made + // alarm would have to relearn. + implementation(libs.androidx.work.runtime) implementation(libs.compose.uiToolingPreview) implementation(libs.sqldelight.android.driver) diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/android/GizaApplication.kt b/composeApp/src/androidMain/kotlin/mobi/giza/android/GizaApplication.kt index 7b01d78d..b0cd90c7 100644 --- a/composeApp/src/androidMain/kotlin/mobi/giza/android/GizaApplication.kt +++ b/composeApp/src/androidMain/kotlin/mobi/giza/android/GizaApplication.kt @@ -8,6 +8,9 @@ import androidx.datastore.preferences.preferencesDataStore import fr.acinq.phoenix.PhoenixGlobal import fr.acinq.phoenix.utils.PlatformContext import fr.acinq.phoenix.utils.preferences.GlobalPrefs +import mobi.giza.android.background.BackgroundSyncWorker +import mobi.giza.compose.AppLifecycle +import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.GizaGlobal import mobi.giza.compose.GizaRuntime @@ -30,6 +33,10 @@ class GizaApplication: Application() { override fun onCreate() { super.onCreate() + // Nobody is looking until an activity says so. A process started for the background sync + // has no activity at all, and the pass declines to run while the app is "visible". + AppLifecycle.enteredBackground() + phoenixGlobal = PhoenixGlobal(PlatformContext(applicationContext)) globalPrefs = GlobalPrefs(applicationContext.globalPrefs) @@ -41,6 +48,14 @@ class GizaApplication: Application() { phoenixGlobal = phoenixGlobal, ) } + + // Every launch, so a schedule lost to a cleared app or a reinstall comes back. KEEP leaves + // one already there alone. docs/notifications-and-background-sync.md, Phase 10. + if (ExperimentalFeatures.backgroundSync) { + BackgroundSyncWorker.schedule(this) + } else { + BackgroundSyncWorker.cancel(this) + } } fun getGlobalPrefs(): GlobalPrefs { diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/android/background/BackgroundSyncWorker.kt b/composeApp/src/androidMain/kotlin/mobi/giza/android/background/BackgroundSyncWorker.kt new file mode 100644 index 00000000..6567f049 --- /dev/null +++ b/composeApp/src/androidMain/kotlin/mobi/giza/android/background/BackgroundSyncWorker.kt @@ -0,0 +1,53 @@ +package mobi.giza.android.background + +import android.content.Context +import androidx.work.Constraints +import androidx.work.CoroutineWorker +import androidx.work.ExistingPeriodicWorkPolicy +import androidx.work.NetworkType +import androidx.work.PeriodicWorkRequestBuilder +import androidx.work.WorkManager +import androidx.work.WorkerParameters +import java.util.concurrent.TimeUnit +import kotlin.time.Duration.Companion.minutes +import mobi.giza.android.GizaApplication +import mobi.giza.compose.managers.BackgroundSyncPass + +/** + * Android's background sync: the full pass, every fifteen minutes at best, deferred by Doze to + * its maintenance windows. docs/notifications-and-background-sync.md, Phase 10. + * + * Always reports success. A pass that could not reach a relay is not a failure WorkManager could + * do better by retrying sooner -- the next period is the retry -- and its outcome is on the ledger. + */ +class BackgroundSyncWorker(context: Context, parameters: WorkerParameters) : CoroutineWorker(context, parameters) { + + override suspend fun doWork(): Result { + val runtime = (applicationContext as GizaApplication).runtime + // Inside WorkManager's ten minutes, so the pass ends itself rather than being stopped. + runtime.backgroundSync.run(BackgroundSyncPass.Kind.Full, deadline = 9.minutes) + return Result.success() + } + + companion object { + private const val UNIQUE_NAME = "giza-background-sync" + + /** Asks for the pass every fifteen minutes, with a network. Keeps a schedule already there. */ + fun schedule(context: Context) { + val request = PeriodicWorkRequestBuilder(15, TimeUnit.MINUTES) + .setConstraints( + Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .setRequiresBatteryNotLow(true) + .build() + ) + .build() + WorkManager.getInstance(context) + .enqueueUniquePeriodicWork(UNIQUE_NAME, ExistingPeriodicWorkPolicy.KEEP, request) + } + + fun cancel(context: Context) { + WorkManager.getInstance(context).cancelUniqueWork(UNIQUE_NAME) + } + } +} diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.android.kt b/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.android.kt new file mode 100644 index 00000000..00b6c174 --- /dev/null +++ b/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.android.kt @@ -0,0 +1,16 @@ +package mobi.giza.compose.notifications + +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.background_android_explanation +import org.jetbrains.compose.resources.stringResource + +@Composable +actual fun PlatformBackgroundExplanation() { + Text(stringResource(Res.string.background_android_explanation), style = MaterialTheme.typography.bodyMedium) +} + +@Composable +actual fun PlatformBackgroundSettings() = Unit diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index b0bb1928..553062f5 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -820,4 +820,11 @@ Off, a notification says only that a message arrived Mute notifications Unread messages are still counted + Background sync + Last checked while closed: %1$s + Not checked while closed yet + While Giza is closed, Android lets it check for messages about every 15 minutes, and less often while the phone is idle. + While Giza is closed, iOS decides when it may check for messages: sometimes within minutes, sometimes a few times a day, and not at all after Giza is swiped away. + Background App Refresh is off for Giza, so it cannot check for messages while closed. You can turn it on in the Settings app. + Giza checks for messages while it is running, minimised or not. Closed, it checks nothing. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt index 38495efb..73435fe0 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt @@ -41,6 +41,18 @@ object ExperimentalFeatures { */ val groupInbox: Boolean get() = groupInboxOverride ?: isDevelopmentBuild() + + /** Set by a test that has to see the build a release would be. */ + var backgroundSyncOverride: Boolean? = null + + /** + * Syncing while the app is off screen (docs/notifications-and-background-sync.md, D12): the + * WorkManager worker, the iOS background tasks, Android's Stay connected and the desktop tray. + * Off in a release until a device run says the pass behaves. Notifications while the app runs + * are not behind it: they carry no protocol risk. + */ + val backgroundSync: Boolean + get() = backgroundSyncOverride ?: isDevelopmentBuild() } /** Whether this is a debug or development build of the app, rather than a release. */ diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt index 59cebf64..e880161d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt @@ -76,6 +76,8 @@ class BackgroundSyncPass( /** The app is on screen; its own subscriptions already cover this. */ Visible("visible"), NoIdentity("noIdentity"), + /** The profile's notifications are switched off, so there is nobody to sync for. */ + Disabled("disabled"), /** Another pass is running in this process. */ AlreadyRunning("alreadyRunning"), Failed("failed"), @@ -90,6 +92,7 @@ class BackgroundSyncPass( val identity = running ?: loadDefaultIdentity() ?: return Outcome.NoIdentity val publicKey = identity.nostrPublicKey val activatedHere = running == null + if (ledger.getLedger(publicKey)?.enabled == false) return Outcome.Disabled logger.i { "Background ${kind.wire} pass for $publicKey, deadline $deadline" } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.kt new file mode 100644 index 00000000..36f5f506 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.kt @@ -0,0 +1,59 @@ +package mobi.giza.compose.notifications + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import mobi.giza.compose.database.model.NotificationLedger +import mobi.giza.compose.extensions.toChatListTimestampString +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.background_last_checked +import mobi.giza.compose.resources.background_never_checked +import mobi.giza.compose.resources.background_sync +import mobi.giza.compose.ui.theme.spacing +import org.jetbrains.compose.resources.stringResource + +/** + * What this platform does while the app is closed, said plainly, and when it last did it. + * docs/notifications-and-background-sync.md, D10. + * + * The time is what a "my notifications are late" report starts from, which is why it is on the + * screen and not only in a log. + */ +@Composable +fun BackgroundSyncSection(ledger: NotificationLedger) { + Column( + modifier = Modifier.fillMaxWidth().padding( + horizontal = MaterialTheme.spacing.screenMargin, + vertical = MaterialTheme.spacing.itemGap, + ), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), + ) { + Text( + text = stringResource(Res.string.background_sync), + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.primary, + ) + PlatformBackgroundExplanation() + Text( + text = ledger.lastBackgroundSyncAt + ?.let { stringResource(Res.string.background_last_checked, it.toChatListTimestampString()) } + ?: stringResource(Res.string.background_never_checked), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + PlatformBackgroundSettings() +} + +/** The sentence for this platform's background behaviour. */ +@Composable +expect fun PlatformBackgroundExplanation() + +/** Switches only this platform has (Android's Stay connected). Nothing elsewhere. */ +@Composable +expect fun PlatformBackgroundSettings() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/NotificationSettingsScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/NotificationSettingsScreen.kt index 00a0650b..97383088 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/NotificationSettingsScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/NotificationSettingsScreen.kt @@ -26,7 +26,9 @@ import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.Role import kotlinx.coroutines.launch +import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.database.model.NotificationLedger +import mobi.giza.compose.notifications.BackgroundSyncSection import mobi.giza.compose.notifications.NotificationSettings import mobi.giza.compose.notifications.NotificationSettingsStore import mobi.giza.compose.notifications.rememberNotificationPermission @@ -72,8 +74,6 @@ fun NotificationSettingsScreen( activeUserPublicKey: String, store: NotificationSettingsStore, onNavigateBack: () -> Unit, - /** Extra rows from the platform's background sync (Part B); nothing until it exists. */ - backgroundSection: @Composable () -> Unit = {}, ) { val ledgerState by remember(activeUserPublicKey) { store.observe(activeUserPublicKey) } .collectAsState(initial = Unit) @@ -170,7 +170,7 @@ fun NotificationSettingsScreen( enabled = settings.enabled && settings.messages, ) { save(settings.copy(showMessageText = it)) } } - item { backgroundSection() } + if (ExperimentalFeatures.backgroundSync) item { BackgroundSyncSection(state.ledger) } } } } diff --git a/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.ios.kt b/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.ios.kt new file mode 100644 index 00000000..87b5df3b --- /dev/null +++ b/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.ios.kt @@ -0,0 +1,30 @@ +package mobi.giza.compose.notifications + +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.background_ios_explanation +import mobi.giza.compose.resources.background_ios_refresh_off +import org.jetbrains.compose.resources.stringResource +import platform.UIKit.UIApplication +import platform.UIKit.UIBackgroundRefreshStatus + +@Composable +actual fun PlatformBackgroundExplanation() { + Text(stringResource(Res.string.background_ios_explanation), style = MaterialTheme.typography.bodyMedium) + val refreshOff = remember { + UIApplication.sharedApplication.backgroundRefreshStatus != UIBackgroundRefreshStatus.UIBackgroundRefreshStatusAvailable + } + if (refreshOff) { + Text( + stringResource(Res.string.background_ios_refresh_off), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + ) + } +} + +@Composable +actual fun PlatformBackgroundSettings() = Unit diff --git a/composeApp/src/jvmMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.jvm.kt b/composeApp/src/jvmMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.jvm.kt new file mode 100644 index 00000000..ebb74184 --- /dev/null +++ b/composeApp/src/jvmMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.jvm.kt @@ -0,0 +1,16 @@ +package mobi.giza.compose.notifications + +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.background_desktop_explanation +import org.jetbrains.compose.resources.stringResource + +@Composable +actual fun PlatformBackgroundExplanation() { + Text(stringResource(Res.string.background_desktop_explanation), style = MaterialTheme.typography.bodyMedium) +} + +@Composable +actual fun PlatformBackgroundSettings() = Unit diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt index aedf1b57..91f65165 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt @@ -151,6 +151,14 @@ class BackgroundSyncPassJvmTest { assertEquals(0, enginesStarted) } + @Test + fun `nothing runs for a profile whose notifications are off`() = runBlocking { + seed() + db.notificationDao().setSettings(user, enabled = false, messages = true, needsYou = true, groupActivity = false, showMessageText = true) + assertEquals(BackgroundSyncPass.Outcome.Disabled, pass().run(BackgroundSyncPass.Kind.Full, 5.seconds)) + assertEquals(0, enginesStarted) + } + /** The pass's whole job, in one: activate, hold, notice the delivery, post it, let go, record. */ @Test fun `a message delivered during the pass is posted, and the pass puts everything back`() = runBlocking { diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 270b4a96..08be3216 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -4,6 +4,7 @@ android-compileSdk = "37" android-minSdk = "26" android-targetSdk = "37" androidx-activity = "1.13.0" +androidx-work = "2.11.1" androidx-lifecycle = "2.11.0" coilCompose = "3.6.3" composeHotReload = "1.3.0" @@ -60,6 +61,7 @@ sqlite = "2.7.1" [libraries] androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activity" } +androidx-work-runtime = { module = "androidx.work:work-runtime", version.ref = "androidx-work" } androidx-datastore = { module = "androidx.datastore:datastore", version.ref = "datastorePreferences" } androidx-datastore-preferences = { module = "androidx.datastore:datastore-preferences", version.ref = "datastorePreferences" } androidx-sqlite-bundled = { module = "androidx.sqlite:sqlite-bundled", version.ref = "sqlite" }