diff --git a/notifications/src/main/java/com/rousecontext/notifications/NotificationChannels.kt b/notifications/src/main/java/com/rousecontext/notifications/NotificationChannels.kt index 9526ee67..b17567fb 100644 --- a/notifications/src/main/java/com/rousecontext/notifications/NotificationChannels.kt +++ b/notifications/src/main/java/com/rousecontext/notifications/NotificationChannels.kt @@ -16,6 +16,7 @@ object NotificationChannels { const val AUTH_REQUEST_CHANNEL_ID = "rouse_auth_request" const val SESSION_SUMMARY_CHANNEL_ID = "rouse_session_summary" const val OUTREACH_LAUNCH_CHANNEL_ID = "rouse_outreach_launch" + const val FGS_LIMIT_CHANNEL_ID = "rouse_fgs_limit" /** * Create all notification channels. Safe to call multiple times; @@ -25,60 +26,67 @@ object NotificationChannels { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return val manager = context.getSystemService(NotificationManager::class.java) + buildChannels().forEach { manager.createNotificationChannel(it) } + } - val channels = listOf( - NotificationChannel( - FOREGROUND_CHANNEL_ID, - "Foreground Service", - NotificationManager.IMPORTANCE_LOW - ).apply { - description = "Ongoing notification while an integration is active" - }, - NotificationChannel( - SESSION_CHANNEL_ID, - "Session Activity", - NotificationManager.IMPORTANCE_DEFAULT - ).apply { - description = "Session summaries and tool call notifications" - }, - NotificationChannel( - ERROR_CHANNEL_ID, - "Errors", - NotificationManager.IMPORTANCE_HIGH - ).apply { - description = "Connection and certificate errors" - }, - NotificationChannel( - ALERT_CHANNEL_ID, - "Security Alerts", - NotificationManager.IMPORTANCE_HIGH - ).apply { - description = "Security-related alerts requiring attention" - }, - NotificationChannel( - AUTH_REQUEST_CHANNEL_ID, - "Authorization Requests", - NotificationManager.IMPORTANCE_DEFAULT - ).apply { - description = "Approval requests for new AI clients" - }, - NotificationChannel( - SESSION_SUMMARY_CHANNEL_ID, - "Session Summaries", - NotificationManager.IMPORTANCE_LOW - ).apply { - description = "Summary of tool calls after an MCP session ends" - }, - NotificationChannel( - OUTREACH_LAUNCH_CHANNEL_ID, - "Outreach Launch Requests", - NotificationManager.IMPORTANCE_DEFAULT - ).apply { - description = "Tap-to-launch fallback when an AI client requests " + - "opening an app or link and the app cannot launch it directly" - } + private fun buildChannels(): List = listOf( + channel( + FOREGROUND_CHANNEL_ID, + "Foreground Service", + NotificationManager.IMPORTANCE_LOW, + "Ongoing notification while an integration is active" + ), + channel( + SESSION_CHANNEL_ID, + "Session Activity", + NotificationManager.IMPORTANCE_DEFAULT, + "Session summaries and tool call notifications" + ), + channel( + ERROR_CHANNEL_ID, + "Errors", + NotificationManager.IMPORTANCE_HIGH, + "Connection and certificate errors" + ), + channel( + ALERT_CHANNEL_ID, + "Security Alerts", + NotificationManager.IMPORTANCE_HIGH, + "Security-related alerts requiring attention" + ), + channel( + AUTH_REQUEST_CHANNEL_ID, + "Authorization Requests", + NotificationManager.IMPORTANCE_DEFAULT, + "Approval requests for new AI clients" + ), + channel( + SESSION_SUMMARY_CHANNEL_ID, + "Session Summaries", + NotificationManager.IMPORTANCE_LOW, + "Summary of tool calls after an MCP session ends" + ), + channel( + OUTREACH_LAUNCH_CHANNEL_ID, + "Outreach Launch Requests", + NotificationManager.IMPORTANCE_DEFAULT, + "Tap-to-launch fallback when an AI client requests " + + "opening an app or link and the app cannot launch it directly" + ), + channel( + FGS_LIMIT_CHANNEL_ID, + "Foreground Service Limit", + NotificationManager.IMPORTANCE_HIGH, + "Android 6-hour foreground service limit alerts" ) + ) - channels.forEach { manager.createNotificationChannel(it) } + private fun channel( + id: String, + name: String, + importance: Int, + desc: String + ): NotificationChannel = NotificationChannel(id, name, importance).apply { + description = desc } } diff --git a/notifications/src/test/java/com/rousecontext/notifications/NotificationChannelsTest.kt b/notifications/src/test/java/com/rousecontext/notifications/NotificationChannelsTest.kt index 3ab9ce68..c2185943 100644 --- a/notifications/src/test/java/com/rousecontext/notifications/NotificationChannelsTest.kt +++ b/notifications/src/test/java/com/rousecontext/notifications/NotificationChannelsTest.kt @@ -20,7 +20,7 @@ class NotificationChannelsTest { NotificationChannels.createAll(context) val channels = manager.notificationChannels - assertEquals(7, channels.size) + assertEquals(8, channels.size) } @Test @@ -94,12 +94,23 @@ class NotificationChannelsTest { assertEquals("Outreach Launch Requests", channel.name.toString()) } + @Test + fun `createAll registers FGS limit channel with high importance`() { + NotificationChannels.createAll(context) + + val channel = manager.getNotificationChannel( + NotificationChannels.FGS_LIMIT_CHANNEL_ID + ) + assertNotNull(channel) + assertEquals(NotificationManager.IMPORTANCE_HIGH, channel.importance) + } + @Test fun `createAll is idempotent`() { NotificationChannels.createAll(context) NotificationChannels.createAll(context) val channels = manager.notificationChannels - assertEquals(7, channels.size) + assertEquals(8, channels.size) } } diff --git a/work/src/main/kotlin/com/rousecontext/work/FgsLimitHandler.kt b/work/src/main/kotlin/com/rousecontext/work/FgsLimitHandler.kt new file mode 100644 index 00000000..13156256 --- /dev/null +++ b/work/src/main/kotlin/com/rousecontext/work/FgsLimitHandler.kt @@ -0,0 +1,48 @@ +package com.rousecontext.work + +import android.app.NotificationManager +import android.content.Context +import androidx.core.app.NotificationCompat +import com.rousecontext.api.R as ApiR +import com.rousecontext.notifications.NotificationChannels + +/** + * Handles the Android 6-hour daily foreground service (`dataSync`) time-limit + * exhaustion case. + * + * When `startForeground` throws `ForegroundServiceStartNotAllowedException` + * because the cumulative daily FGS budget is exhausted, we post a user-visible + * notification so the user knows why wakes have stopped being served, and then + * stop the service. There is no retry — the next FCM wake will naturally attempt + * `startForeground` again, and when the 24-hour rolling window gives the budget + * back, the service will start normally. + * + * A fixed notification id is used so repeated exhausted wakes update the same + * notification rather than spamming the shade. + */ +object FgsLimitHandler { + /** Fixed id so repeated posts replace instead of stacking. */ + const val NOTIFICATION_ID = 4201 + + private const val TITLE = "Rouse Context paused" + private const val TEXT = + "Rouse Context hit Android's 6-hour daily service limit. " + + "Wake requests won't be served until the limit resets. " + + "This usually means something is waking the app too often." + + fun postLimitReachedNotification(context: Context) { + val notification = NotificationCompat + .Builder(context, NotificationChannels.FGS_LIMIT_CHANNEL_ID) + .setContentTitle(TITLE) + .setContentText(TEXT) + .setStyle(NotificationCompat.BigTextStyle().bigText(TEXT)) + .setSmallIcon(ApiR.drawable.ic_stat_rouse) + .setColor(0xFF0a1628.toInt()) + .setPriority(NotificationCompat.PRIORITY_HIGH) + .setAutoCancel(true) + .build() + + val manager = context.getSystemService(NotificationManager::class.java) + manager.notify(NOTIFICATION_ID, notification) + } +} diff --git a/work/src/main/kotlin/com/rousecontext/work/TunnelForegroundService.kt b/work/src/main/kotlin/com/rousecontext/work/TunnelForegroundService.kt index e96c30f9..c8a856b9 100644 --- a/work/src/main/kotlin/com/rousecontext/work/TunnelForegroundService.kt +++ b/work/src/main/kotlin/com/rousecontext/work/TunnelForegroundService.kt @@ -1,5 +1,6 @@ package com.rousecontext.work +import android.app.ForegroundServiceStartNotAllowedException import android.content.Context import android.content.Intent import android.content.pm.ServiceInfo @@ -61,15 +62,12 @@ class TunnelForegroundService : LifecycleService() { super.onCreate() NotificationChannels.createAll(this) - val notification = createForegroundNotification(this, "Connecting...") - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - startForeground( - NOTIFICATION_ID, - notification, - ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC - ) - } else { - startForeground(NOTIFICATION_ID, notification) + if (!startForegroundSafely()) { + // FGS daily time-limit exhausted. User notification already posted; + // stop the service. The next FCM wake will naturally retry + // startForeground when the 24h rolling budget gives us time back. + stopSelf() + return } // Launch observer coroutines exactly once. These collect StateFlows and @@ -85,6 +83,47 @@ class TunnelForegroundService : LifecycleService() { Log.i(TAG, "TunnelForegroundService created") } + /** + * Attempts to enter the foreground. Returns true on success, false if the + * Android 6-hour daily dataSync FGS budget is exhausted (API 31+). On + * failure, a user-visible notification is posted explaining the situation. + */ + private fun startForegroundSafely(): Boolean { + val notification = createForegroundNotification(this, "Connecting...") + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + return startForegroundApi31OrHigher(notification) + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + startForeground( + NOTIFICATION_ID, + notification, + ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC + ) + } else { + startForeground(NOTIFICATION_ID, notification) + } + return true + } + + private fun startForegroundApi31OrHigher(notification: android.app.Notification): Boolean = + try { + startForeground( + NOTIFICATION_ID, + notification, + ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC + ) + true + } catch (e: ForegroundServiceStartNotAllowedException) { + Log.w( + TAG, + "startForeground blocked — FGS daily time limit exhausted. " + + "Posting user notification and stopping service.", + e + ) + FgsLimitHandler.postLimitReachedNotification(this) + false + } + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { super.onStartCommand(intent, flags, startId) diff --git a/work/src/test/kotlin/com/rousecontext/work/FgsLimitHandlerTest.kt b/work/src/test/kotlin/com/rousecontext/work/FgsLimitHandlerTest.kt new file mode 100644 index 00000000..0aae9ae6 --- /dev/null +++ b/work/src/test/kotlin/com/rousecontext/work/FgsLimitHandlerTest.kt @@ -0,0 +1,84 @@ +package com.rousecontext.work + +import android.app.NotificationManager +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import com.rousecontext.notifications.NotificationChannels +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class FgsLimitHandlerTest { + + private val context: Context = ApplicationProvider.getApplicationContext() + private val manager = context.getSystemService(NotificationManager::class.java) + + @Test + fun `postLimitReachedNotification posts on FGS limit channel`() { + NotificationChannels.createAll(context) + + FgsLimitHandler.postLimitReachedNotification(context) + + val active = manager.activeNotifications + assertEquals(1, active.size) + val posted = active.single() + assertEquals( + NotificationChannels.FGS_LIMIT_CHANNEL_ID, + posted.notification.channelId + ) + } + + @Test + fun `postLimitReachedNotification uses fixed id so repeated posts update same notification`() { + NotificationChannels.createAll(context) + + FgsLimitHandler.postLimitReachedNotification(context) + FgsLimitHandler.postLimitReachedNotification(context) + FgsLimitHandler.postLimitReachedNotification(context) + + val active = manager.activeNotifications + assertEquals( + "Repeated posts should replace, not stack", + 1, + active.size + ) + assertEquals(FgsLimitHandler.NOTIFICATION_ID, active.single().id) + } + + @Test + fun `postLimitReachedNotification uses expected copy`() { + NotificationChannels.createAll(context) + + FgsLimitHandler.postLimitReachedNotification(context) + + val active = manager.activeNotifications.single() + val text = active.notification.extras.getCharSequence( + android.app.Notification.EXTRA_TEXT + )?.toString().orEmpty() + assertTrue( + "Notification text should mention the 6-hour limit: <$text>", + text.contains("6-hour") + ) + assertTrue( + "Notification text should explain wake requests aren't served: <$text>", + text.contains("Wake requests won't be served") + ) + } + + @Test + fun `channel is registered before posting`() { + // createAll is required — but the handler should not crash if called + // before channels exist. Calling createAll separately is the integration + // contract; document that here. + NotificationChannels.createAll(context) + + val channel = manager.getNotificationChannel( + NotificationChannels.FGS_LIMIT_CHANNEL_ID + ) + assertNotNull(channel) + } +}