diff --git a/app/android/app/src/main/AndroidManifest.xml b/app/android/app/src/main/AndroidManifest.xml index 8609352a..2e2bdf08 100644 --- a/app/android/app/src/main/AndroidManifest.xml +++ b/app/android/app/src/main/AndroidManifest.xml @@ -12,6 +12,11 @@ + + + @@ -69,6 +74,11 @@ android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE" android:value="Persistent connection to the user's self-hosted Pipelines server for instant notifications"/> + + diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ConnectWakeLock.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ConnectWakeLock.kt new file mode 100644 index 00000000..7d68e2df --- /dev/null +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ConnectWakeLock.kt @@ -0,0 +1,27 @@ +package net.awan.pipelines_app.notify + +import android.content.Context +import android.os.PowerManager + +/** + * A short partial wake lock held while the service opens its socket, so the + * CPU stays awake through the handshake. The timeout bounds it if no answer + * comes; [release] runs as soon as the socket opens or fails. + */ +class ConnectWakeLock(context: Context) { + private val lock = context.getSystemService(PowerManager::class.java) + .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "pipelines:connect") + .apply { setReferenceCounted(false) } + + fun hold() { + lock.acquire(HOLD_MILLIS) + } + + fun release() { + if (lock.isHeld) lock.release() + } + + companion object { + const val HOLD_MILLIS = 30_000L + } +} diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ConnectionLog.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ConnectionLog.kt new file mode 100644 index 00000000..2d9b85d9 --- /dev/null +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ConnectionLog.kt @@ -0,0 +1,73 @@ +package net.awan.pipelines_app.notify + +import org.json.JSONArray +import org.json.JSONException +import org.json.JSONObject + +/** One entry of the connection log: when, what happened, and the error or HTTP code. */ +data class ConnectionEvent( + val timeMillis: Long, + val event: String, + val error: String?, + val code: Int?, +) + +/** + * The last [CAPACITY] connection events, kept in the service's preferences so + * Settings can show why delivery stalled. Newest first. Error text is trimmed; + * the session cookie never reaches the log. + */ +class ConnectionLog( + private val store: LedgerStore, + private val clock: () -> Long = System::currentTimeMillis, +) { + /** Read-modify-write: the main thread (task removal) and the service thread both log. */ + @Synchronized + fun record(event: String, error: String? = null, code: Int? = null) { + val entry = ConnectionEvent(clock(), event, error?.take(MAX_ERROR_LENGTH), code) + store.putString(KEY, encode((listOf(entry) + entries()).take(CAPACITY))) + } + + fun entries(): List = decode(store.getString(KEY)) + + companion object { + const val CAPACITY = 50 + const val KEY = "connection.log" + private const val MAX_ERROR_LENGTH = 200 + + private fun encode(events: List): String { + val array = JSONArray() + for (event in events) { + array.put( + JSONObject() + .put("t", event.timeMillis) + .put("e", event.event) + .apply { + event.error?.let { put("x", it) } + event.code?.let { put("c", it) } + }, + ) + } + return array.toString() + } + + /** A corrupt log reads as empty rather than breaking Settings. */ + private fun decode(raw: String?): List { + if (raw.isNullOrEmpty()) return emptyList() + return try { + val array = JSONArray(raw) + (0 until array.length()).map { index -> + val item = array.getJSONObject(index) + ConnectionEvent( + timeMillis = item.getLong("t"), + event = item.getString("e"), + error = if (item.has("x")) item.getString("x") else null, + code = if (item.has("c")) item.getInt("c") else null, + ) + } + } catch (_: JSONException) { + emptyList() + } + } + } +} diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt index 4db340a1..ab2cddc1 100644 --- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt @@ -27,21 +27,16 @@ class NotificationPresenter(private val context: Context) { DeliveryStatus.CONNECTED -> "Pipelines is connected" DeliveryStatus.WAITING_FOR_NETWORK -> "Pipelines is waiting for a network" DeliveryStatus.CONNECTING -> "Pipelines is connecting…" + DeliveryStatus.SIGN_IN_REQUIRED -> "Pipelines needs you to sign in" else -> "Pipelines is reconnecting…" } - val open = PendingIntent.getActivity( - context, - 0, - Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), - PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, - ) return builder(CONNECTION_CHANNEL) .setSmallIcon(R.drawable.ic_stat_pipelines) .setContentTitle(text) .setContentText("Delivering notifications from your server") .setOngoing(true) .setShowWhen(false) - .setContentIntent(open) + .setContentIntent(openApp()) .setCategory(Notification.CATEGORY_SERVICE) .build() } @@ -50,6 +45,30 @@ class NotificationPresenter(private val context: Context) { manager.notify(CONNECTION_ID, connectionNotification(status)) } + /** Posted when the server refuses the session; cleared once a connection opens. */ + fun signInRequired() { + ensureChannel(ACCOUNT_CHANNEL, "Sign-in", NotificationManager.IMPORTANCE_DEFAULT, null) + val notification = builder(ACCOUNT_CHANNEL) + .setSmallIcon(R.drawable.ic_stat_pipelines) + .setContentTitle("Sign in to Pipelines again to keep notifications") + .setContentText("Notifications are paused until you sign in.") + .setAutoCancel(true) + .setContentIntent(openApp()) + .build() + manager.notify(SIGN_IN_ID, notification) + } + + fun clearSignIn() { + manager.cancel(SIGN_IN_ID) + } + + private fun openApp(): PendingIntent = PendingIntent.getActivity( + context, + 0, + Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + fun show(notification: ServerNotification) { val id = DeliveryLedger.notificationId(notification.id) val channel = channelFor(notification) @@ -182,6 +201,9 @@ class NotificationPresenter(private val context: Context) { companion object { const val CONNECTION_ID = 1 const val CONNECTION_CHANNEL = "pipelines.connection" + /** The "sign in again" notice; ids up to RESERVED_IDS are the service's own. */ + const val SIGN_IN_ID = 2 + const val ACCOUNT_CHANNEL = "pipelines.account" const val EXTRA_NOTIFICATION_ID = "net.awan.pipelines.notification_id" private val KIND_LABELS = mapOf( diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationService.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationService.kt index 870bb358..a029db52 100644 --- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationService.kt +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationService.kt @@ -24,6 +24,10 @@ import java.util.concurrent.TimeUnit * engine runs here. It subscribes with the replay cursor, posts each pushed * notification, mirrors cross-device clears and sends the user's own clears. * + * Reconnects are alarms (ReconnectAlarms), so they fire during Doze; a + * periodic NotificationWatchdog restarts the service if it is down. A refused + * session (HTTP 401/403) stops the retry loop until a fresh cookie arrives. + * * All state is confined to [handler]'s thread; OkHttp and connectivity * callbacks post onto it. */ @@ -31,6 +35,8 @@ class NotificationService : Service() { private lateinit var settings: ServiceSettings private lateinit var ledger: DeliveryLedger private lateinit var presenter: NotificationPresenter + private lateinit var log: ConnectionLog + private lateinit var wakeLock: ConnectWakeLock private lateinit var thread: HandlerThread private lateinit var handler: Handler private val client = OkHttpClient.Builder() @@ -48,7 +54,8 @@ class NotificationService : Service() { private var networkAvailable = true private var currentNetwork: Network? = null private var networkCallback: ConnectivityManager.NetworkCallback? = null - private val reconnect = Runnable { connect() } + /** A reconnect alarm is pending for the socket that is down. */ + private var reconnectPending = false override fun onBind(intent: Intent?): IBinder? = null @@ -57,6 +64,8 @@ class NotificationService : Service() { settings = ServiceSettings(this) ledger = DeliveryLedger(settings) presenter = NotificationPresenter(this) + log = ConnectionLog(settings) + wakeLock = ConnectWakeLock(this) thread = HandlerThread("pipelines-notifications").also { it.start() } handler = Handler(thread.looper) goForeground(DeliveryStatus.CONNECTING) @@ -66,16 +75,36 @@ class NotificationService : Service() { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { val action = intent?.action + // Alarms and the watchdog may start the service from the background; + // it must be foreground promptly, so do that before queuing the work. + goForeground(settings.status.let { if (it == DeliveryStatus.OFF) DeliveryStatus.CONNECTING else it }) handler.post { when { !settings.enabled || !settings.configured -> stopEverything() action == ACTION_FLUSH -> flushClears() + action == ACTION_WATCHDOG -> if (isDown()) { + log.record("watchdog_restart") + restart() + } + action == ACTION_RECONNECT -> if (socket == null && settings.status != DeliveryStatus.SIGN_IN_REQUIRED) connect() action == ACTION_RESTART || socket == null -> restart() } } return START_STICKY } + /** + * The app was swiped away. The foreground service keeps running, so this + * only queues a watchdog check shortly after, in case the process is lost. + */ + override fun onTaskRemoved(rootIntent: Intent?) { + log.record("task_removed") + if (settings.enabled && settings.configured) { + ReconnectAlarms.schedule(this, TASK_REMOVED_CHECK_MILLIS, ACTION_WATCHDOG) + } + super.onTaskRemoved(rootIntent) + } + override fun onDestroy() { running = null networkCallback?.let { @@ -87,6 +116,7 @@ class NotificationService : Service() { socket?.close(1000, "service stopped") socket = null } + wakeLock.release() thread.quitSafely() if (settings.status != DeliveryStatus.UNCONFIGURED) setStatus(DeliveryStatus.OFF, notify = false) super.onDestroy() @@ -109,22 +139,33 @@ class NotificationService : Service() { generation++ socket?.close(1000, "disabled") socket = null + cancelReconnect() + wakeLock.release() + log.record("stopped") setStatus(if (settings.configured) DeliveryStatus.OFF else DeliveryStatus.UNCONFIGURED, notify = false) stopForeground(STOP_FOREGROUND_REMOVE) stopSelf() } + /** + * Delivery is meant to be running but no socket is open or on its way. + * Waiting for the network and a refused session are deliberate states. + */ + private fun isDown(): Boolean = + socket == null && !reconnectPending && + settings.status != DeliveryStatus.SIGN_IN_REQUIRED && + settings.status != DeliveryStatus.WAITING_FOR_NETWORK + /** Server changed, credentials changed, or the first start: reopen now. */ private fun restart() { if (ledger.bindServer(settings.serverId)) presenter.cancelAll() - handler.removeCallbacks(reconnect) backoff.reset() endpointIndex = 0 connect() } private fun connect() { - handler.removeCallbacks(reconnect) + cancelReconnect() generation++ socket?.cancel() socket = null @@ -139,9 +180,12 @@ class NotificationService : Service() { }.build() } catch (error: IllegalArgumentException) { Log.w(TAG, "invalid endpoint $endpoint", error) + log.record("invalid_endpoint", endpoint) return scheduleReconnect() } setStatus(if (backoff.attempt == 0) DeliveryStatus.CONNECTING else DeliveryStatus.RECONNECTING) + log.record("connecting", endpoint) + wakeLock.hold() val current = generation socket = client.newWebSocket(request, Listener(current)) } @@ -151,15 +195,46 @@ class NotificationService : Service() { socket?.cancel() socket = null subscribeId = null - if (!networkAvailable) return setStatus(DeliveryStatus.WAITING_FOR_NETWORK) + wakeLock.release() + if (!networkAvailable) { + cancelReconnect() + return setStatus(DeliveryStatus.WAITING_FOR_NETWORK) + } setStatus(DeliveryStatus.RECONNECTING) // Rotate through the server's trusted aliases on each failure. endpointIndex++ - handler.postDelayed(reconnect, backoff.next()) + val delay = backoff.next() + reconnectPending = true + ReconnectAlarms.schedule(this, delay, ACTION_RECONNECT) + log.record("retry_scheduled", "in ${delay / 1000}s") + } + + private fun cancelReconnect() { + reconnectPending = false + ReconnectAlarms.cancel(this, ACTION_RECONNECT) + } + + /** + * The server refused the session cookie. Retrying cannot succeed, so the + * loop stops here; a fresh cookie from the app restarts it. + */ + private fun signInRequired(code: Int) { + generation++ + socket?.cancel() + socket = null + subscribeId = null + wakeLock.release() + cancelReconnect() + log.record("sign_in_required", "HTTP $code", code) + setStatus(DeliveryStatus.SIGN_IN_REQUIRED) + presenter.signInRequired() } private fun onOpen(webSocket: WebSocket) { backoff.reset() + wakeLock.release() + presenter.clearSignIn() + log.record("connected") val id = "notify-${++sequence}" subscribeId = id webSocket.send(NotificationProtocol.subscribe(id, ledger.cursor)) @@ -179,6 +254,7 @@ class NotificationService : Service() { is NotificationFrame.Cleared -> presenter.cancel(frame.ids) is NotificationFrame.Refused -> { Log.w(TAG, "subscribe_notifications refused: ${frame.error}") + log.record("refused", "${frame.error}") scheduleReconnect() } NotificationFrame.Ignored -> Unit @@ -212,13 +288,16 @@ class NotificationService : Service() { val previous = currentNetwork currentNetwork = network networkAvailable = true + log.record("network_available") // A new default network invalidates the old socket's route; // a returning network retries at once instead of waiting - // out the backoff. + // out the backoff. A refused session waits for a cookie. val moved = previous != null && previous != network val idle = settings.status == DeliveryStatus.WAITING_FOR_NETWORK || settings.status == DeliveryStatus.RECONNECTING - if (settings.configured && (moved || previous == null || idle)) { + if (settings.configured && settings.status != DeliveryStatus.SIGN_IN_REQUIRED && + (moved || previous == null || idle) + ) { backoff.reset() connect() } @@ -230,6 +309,7 @@ class NotificationService : Service() { if (network != currentNetwork) return@post currentNetwork = null networkAvailable = false + log.record("network_lost") scheduleReconnect() } } @@ -249,17 +329,27 @@ class NotificationService : Service() { webSocket.close(1000, null) } - override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = current { scheduleReconnect() } - override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = current { - Log.i(TAG, "socket failed (${response?.code}): ${t.message}") + override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = current { + log.record("closed", "close $code ${reason}".trim()) scheduleReconnect() } + + override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = current { + val code = response?.code + Log.i(TAG, "socket failed ($code): ${t.message}") + log.record("failed", t.message ?: t.javaClass.simpleName, code) + if (ReconnectPolicy.isAuthRejection(code) && code != null) signInRequired(code) + else scheduleReconnect() + } } companion object { private const val TAG = "PipelinesNotify" const val ACTION_RESTART = "net.awan.pipelines.notify.RESTART" const val ACTION_FLUSH = "net.awan.pipelines.notify.FLUSH" + const val ACTION_RECONNECT = "net.awan.pipelines.notify.RECONNECT" + const val ACTION_WATCHDOG = "net.awan.pipelines.notify.WATCHDOG" + private const val TASK_REMOVED_CHECK_MILLIS = 2_000L @Volatile var running: NotificationService? = null @@ -277,6 +367,7 @@ class NotificationService : Service() { return try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(intent) else context.startService(intent) + NotificationWatchdog.schedule(context) true } catch (error: Exception) { // Android 12+ refuses a foreground start from some background @@ -287,6 +378,9 @@ class NotificationService : Service() { } fun stop(context: Context) { + ReconnectAlarms.cancel(context, ACTION_RECONNECT) + ReconnectAlarms.cancel(context, ACTION_WATCHDOG) + NotificationWatchdog.cancel(context) context.stopService(Intent(context, NotificationService::class.java)) } } diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationServiceChannel.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationServiceChannel.kt index 17da5587..ee862c0f 100644 --- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationServiceChannel.kt +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationServiceChannel.kt @@ -52,10 +52,9 @@ class NotificationServiceChannel(private val activity: Activity, messenger: Bina return } val changed = settings.configure(serverId, endpoints, cookie) - val running = NotificationService.running != null - if (changed || !running) { - NotificationService.start(activity, if (changed) NotificationService.ACTION_RESTART else null) - } + // A null action still restarts a service whose socket is down, + // which is how a refused session resumes with a fresh cookie. + NotificationService.start(activity, if (changed) NotificationService.ACTION_RESTART else null) result.success(status()) } "setEnabled" -> { @@ -69,6 +68,7 @@ class NotificationServiceChannel(private val activity: Activity, messenger: Bina } result.success(status()) } + "connectionEvents" -> result.success(connectionEvents()) "requestBatteryExemption" -> { result.success(requestBatteryExemption()) } @@ -92,6 +92,17 @@ class NotificationServiceChannel(private val activity: Activity, messenger: Bina ) } + /** The last connection events, newest first, for Settings' diagnosis. */ + private fun connectionEvents(): List> = + ConnectionLog(settings).entries().map { event -> + buildMap { + put("time", event.timeMillis) + put("event", event.event) + event.error?.let { put("error", it) } + event.code?.let { put("code", it) } + } + } + private fun batteryExempt(): Boolean = activity.getSystemService(PowerManager::class.java).isIgnoringBatteryOptimizations(activity.packageName) diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationWatchdog.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationWatchdog.kt new file mode 100644 index 00000000..7aa1f8ad --- /dev/null +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationWatchdog.kt @@ -0,0 +1,46 @@ +package net.awan.pipelines_app.notify + +import android.app.job.JobInfo +import android.app.job.JobParameters +import android.app.job.JobScheduler +import android.app.job.JobService +import android.content.ComponentName +import android.content.Context + +/** + * A periodic check that the notification service is alive and connected while + * delivery is on. If the process was killed, or the socket is down with no + * reconnect pending, it starts the service again. JobScheduler defers jobs in + * Doze, so the reconnect alarms remain the primary path; this is the net under + * them. + */ +class NotificationWatchdog : JobService() { + override fun onStartJob(params: JobParameters?): Boolean { + val settings = ServiceSettings(this) + if (settings.enabled && settings.configured) { + NotificationService.start(this, NotificationService.ACTION_WATCHDOG) + } + return false + } + + override fun onStopJob(params: JobParameters?): Boolean = true + + companion object { + private const val JOB_ID = 4201 + private const val PERIOD_MILLIS = 15 * 60_000L + + fun schedule(context: Context) { + val scheduler = context.getSystemService(JobScheduler::class.java) + if (scheduler.getPendingJob(JOB_ID) != null) return + val job = JobInfo.Builder(JOB_ID, ComponentName(context, NotificationWatchdog::class.java)) + .setPeriodic(PERIOD_MILLIS) + .setPersisted(true) + .build() + scheduler.schedule(job) + } + + fun cancel(context: Context) { + context.getSystemService(JobScheduler::class.java).cancel(JOB_ID) + } + } +} diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ReconnectAlarms.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ReconnectAlarms.kt new file mode 100644 index 00000000..030a477b --- /dev/null +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ReconnectAlarms.kt @@ -0,0 +1,69 @@ +package net.awan.pipelines_app.notify + +import android.app.AlarmManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.SystemClock + +/** + * Wakes the notification service when a reconnect, restart or watchdog check + * is due. A Handler delay pauses while the device dozes; an alarm does not. + * Each action has one pending alarm: scheduling again replaces it. + */ +object ReconnectAlarms { + fun schedule(context: Context, delayMillis: Long, action: String) { + val manager = context.getSystemService(AlarmManager::class.java) + val at = SystemClock.elapsedRealtime() + delayMillis + val pending = pendingFor(context, action) + val exact = ReconnectPolicy.alarmMode(exactPermitted(context)) == + ReconnectPolicy.AlarmMode.EXACT_WHILE_IDLE + try { + if (exact) { + manager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, pending) + } else { + manager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, pending) + } + } catch (_: SecurityException) { + // The exact-alarm grant was revoked between the check and the call. + manager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, pending) + } + } + + fun cancel(context: Context, action: String) { + val existing = lookup(context, action) ?: return + context.getSystemService(AlarmManager::class.java).cancel(existing) + existing.cancel() + } + + fun exactPermitted(context: Context): Boolean = + Build.VERSION.SDK_INT < Build.VERSION_CODES.S || + context.getSystemService(AlarmManager::class.java).canScheduleExactAlarms() + + /** + * Schedule and cancel must build the same kind of PendingIntent (a + * foreground-service one on Android 8+), or a cancel matches nothing. + * An alarm may start the service from the background; on Android 8+ that + * must be a foreground start, which the service then satisfies. + */ + private fun pendingFor(context: Context, action: String): PendingIntent = + checkNotNull(build(context, action, PendingIntent.FLAG_UPDATE_CURRENT)) { + "FLAG_UPDATE_CURRENT always yields a PendingIntent" + } + + private fun lookup(context: Context, action: String): PendingIntent? = + build(context, action, PendingIntent.FLAG_NO_CREATE) + + private fun build(context: Context, action: String, mode: Int): PendingIntent? { + val intent = Intent(context, NotificationService::class.java).setAction(action) + val flags = PendingIntent.FLAG_IMMUTABLE or mode + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + PendingIntent.getForegroundService(context, requestCode(action), intent, flags) + } else { + PendingIntent.getService(context, requestCode(action), intent, flags) + } + } + + private fun requestCode(action: String): Int = action.hashCode() +} diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ReconnectPolicy.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ReconnectPolicy.kt new file mode 100644 index 00000000..0d39ab97 --- /dev/null +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ReconnectPolicy.kt @@ -0,0 +1,19 @@ +package net.awan.pipelines_app.notify + +/** Decisions the service makes on a failed socket, kept free of Android types. */ +object ReconnectPolicy { + /** + * HTTP 401/403 on the websocket handshake: the session cookie is no longer + * accepted. Retrying cannot succeed, so the service waits for a fresh cookie. + */ + fun isAuthRejection(code: Int?): Boolean = code == 401 || code == 403 + + /** + * Exact alarms need SCHEDULE_EXACT_ALARM (Android 12+, user-revocable). When + * it is not granted the reconnect still fires during Doze, just inexactly. + */ + fun alarmMode(exactPermitted: Boolean): AlarmMode = + if (exactPermitted) AlarmMode.EXACT_WHILE_IDLE else AlarmMode.WHILE_IDLE + + enum class AlarmMode { EXACT_WHILE_IDLE, WHILE_IDLE } +} diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ServiceSettings.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ServiceSettings.kt index 08984eec..51003d1f 100644 --- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ServiceSettings.kt +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ServiceSettings.kt @@ -11,6 +11,8 @@ enum class DeliveryStatus(val wire: String) { CONNECTED("connected"), RECONNECTING("reconnecting"), WAITING_FOR_NETWORK("waiting_for_network"), + /** The server refused the session; delivery resumes when the app hands over a fresh cookie. */ + SIGN_IN_REQUIRED("sign_in_required"), } /** diff --git a/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/ConnectionLogTest.kt b/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/ConnectionLogTest.kt new file mode 100644 index 00000000..efdd45ba --- /dev/null +++ b/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/ConnectionLogTest.kt @@ -0,0 +1,69 @@ +package net.awan.pipelines_app.notify + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class ConnectionLogTest { + private class MemoryStore : LedgerStore { + val values = mutableMapOf() + override fun getString(key: String) = values[key] + override fun putString(key: String, value: String?) { + if (value == null) values.remove(key) else values[key] = value + } + } + + private class Clock(var now: Long = 1_000L) { + fun tick(): Long = now++ + } + + @Test + fun keepsTheLastFiftyEventsNewestFirst() { + val store = MemoryStore() + val clock = Clock() + val log = ConnectionLog(store, clock::tick) + repeat(ConnectionLog.CAPACITY + 10) { index -> log.record("event-$index") } + val entries = log.entries() + assertEquals(ConnectionLog.CAPACITY, entries.size) + assertEquals("event-59", entries.first().event) + assertEquals("event-10", entries.last().event) + } + + @Test + fun errorAndCodeSurviveAReload() { + val store = MemoryStore() + ConnectionLog(store) { 42L }.record("failed", "Expected HTTP 101", 403) + val entry = ConnectionLog(store).entries().single() + assertEquals(42L, entry.timeMillis) + assertEquals("failed", entry.event) + assertEquals("Expected HTTP 101", entry.error) + assertEquals(403, entry.code) + } + + @Test + fun eventsWithoutErrorOrCodeReadBackAsNull() { + val store = MemoryStore() + ConnectionLog(store).record("connected") + val entry = ConnectionLog(store).entries().single() + assertNull(entry.error) + assertNull(entry.code) + } + + @Test + fun longErrorTextIsTrimmed() { + val store = MemoryStore() + ConnectionLog(store).record("failed", "x".repeat(500)) + val error = ConnectionLog(store).entries().single().error!! + assertEquals(200, error.length) + } + + @Test + fun corruptLogReadsAsEmptyInsteadOfThrowing() { + val store = MemoryStore() + store.values[ConnectionLog.KEY] = "not json" + assertTrue(ConnectionLog(store).entries().isEmpty()) + ConnectionLog(store).record("connected") + assertEquals("connected", ConnectionLog(store).entries().single().event) + } +} diff --git a/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/ReconnectPolicyTest.kt b/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/ReconnectPolicyTest.kt new file mode 100644 index 00000000..b78d1530 --- /dev/null +++ b/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/ReconnectPolicyTest.kt @@ -0,0 +1,29 @@ +package net.awan.pipelines_app.notify + +import net.awan.pipelines_app.notify.ReconnectPolicy.AlarmMode +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ReconnectPolicyTest { + @Test + fun http401And403StopTheRetryLoop() { + assertTrue(ReconnectPolicy.isAuthRejection(401)) + assertTrue(ReconnectPolicy.isAuthRejection(403)) + } + + @Test + fun otherFailuresKeepRetrying() { + assertFalse(ReconnectPolicy.isAuthRejection(null)) + assertFalse(ReconnectPolicy.isAuthRejection(500)) + assertFalse(ReconnectPolicy.isAuthRejection(503)) + assertFalse(ReconnectPolicy.isAuthRejection(404)) + } + + @Test + fun exactAlarmsWhenPermittedOtherwiseIdleTolerant() { + assertEquals(AlarmMode.EXACT_WHILE_IDLE, ReconnectPolicy.alarmMode(true)) + assertEquals(AlarmMode.WHILE_IDLE, ReconnectPolicy.alarmMode(false)) + } +} diff --git a/app/lib/features/notification_service/notification_service_bridge.dart b/app/lib/features/notification_service/notification_service_bridge.dart index 18dc289b..fa0f284d 100644 --- a/app/lib/features/notification_service/notification_service_bridge.dart +++ b/app/lib/features/notification_service/notification_service_bridge.dart @@ -4,8 +4,10 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'host_platform_stub.dart' if (dart.library.io) 'host_platform_io.dart'; +import 'notification_service_events.dart'; import 'notification_service_status.dart'; +export 'notification_service_events.dart'; export 'notification_service_status.dart'; /// The app's handle on Android background delivery: a native foreground @@ -35,6 +37,9 @@ abstract interface class NotificationServiceBridge { /// Opens Android's "ignore battery optimisations" prompt. Future requestBatteryExemption(); + + /// The service's recent connection events, newest first (at most 50). + Future> connectionEvents(); } /// The bridge for this platform. One instance owns the channel's handler. @@ -104,6 +109,16 @@ class MethodChannelNotificationServiceBridge @override Future requestBatteryExemption() async => await _channel.invokeMethod('requestBatteryExemption') ?? false; + + @override + Future> connectionEvents() async { + final reply = await _channel.invokeListMethod('connectionEvents'); + return [ + for (final item in reply ?? const []) + if (item is Map) + NotificationConnectionEvent.fromMap(item), + ]; + } } /// Web, iOS and desktop: no background service; nothing is pretended. @@ -136,4 +151,8 @@ class UnsupportedNotificationServiceBridge @override Future requestBatteryExemption() async => false; + + @override + Future> connectionEvents() async => + const []; } diff --git a/app/lib/features/notification_service/notification_service_controller.dart b/app/lib/features/notification_service/notification_service_controller.dart index 711e6a53..310ece5d 100644 --- a/app/lib/features/notification_service/notification_service_controller.dart +++ b/app/lib/features/notification_service/notification_service_controller.dart @@ -21,22 +21,52 @@ class NotificationServiceController extends ChangeNotifier { late final StreamSubscription _changes; NotificationServiceStatus? _status; + List _events = const []; bool _busy = false; String _error = ''; bool _disposed = false; NotificationServiceStatus? get status => _status; + + /// The service's connection log, newest first. + List get events => _events; bool get busy => _busy; String get error => _error; + bool _askedForExemption = false; + Future load() => _run(bridge.status); + /// Opens Settings: reads the status and, when delivery is already on but the + /// battery exemption is missing (existing users, upgrades), asks for it once + /// per controller. The warning row stays if the prompt is declined. + Future open() async { + await load(); + final current = _status; + if (current != null && + current.enabled && + !current.batteryExempt && + !_askedForExemption) { + _askedForExemption = true; + await allowBackgroundDelivery(); + } + } + /// Re-reads after returning from a system screen (permission, battery). + /// Never prompts again: a declined prompt is shown as the warning row. Future refresh() => load(); + /// Switching delivery on first asks for the battery exemption, so the + /// service starts with the prompt answered: delivery should not pause while + /// the phone is idle. Future setEnabled(bool enabled) => _run(() async { - if (enabled && _status?.notificationsAllowed == false) { - await requestNotificationPermission?.call(); + if (enabled) { + if (_status?.notificationsAllowed == false) { + await requestNotificationPermission?.call(); + } + if (_status?.batteryExempt == false) { + await bridge.requestBatteryExemption(); + } } return bridge.setEnabled(enabled); }); @@ -58,6 +88,7 @@ class NotificationServiceController extends ChangeNotifier { _notify(); try { _status = await action(); + _events = await bridge.connectionEvents(); } catch (error) { _error = 'Background delivery is unavailable: $error'; } finally { @@ -69,6 +100,17 @@ class NotificationServiceController extends ChangeNotifier { void _apply(NotificationServiceStatus status) { _status = status; _notify(); + // The service logs its own transitions; re-read so the log stays current. + unawaited(_refreshEvents()); + } + + Future _refreshEvents() async { + try { + _events = await bridge.connectionEvents(); + } catch (error) { + _error = 'Background delivery is unavailable: $error'; + } + _notify(); } void _notify() { diff --git a/app/lib/features/notification_service/notification_service_events.dart b/app/lib/features/notification_service/notification_service_events.dart new file mode 100644 index 00000000..3afd2fa3 --- /dev/null +++ b/app/lib/features/notification_service/notification_service_events.dart @@ -0,0 +1,64 @@ +/// One entry of the background service's connection log, as Settings shows +/// it for diagnosis. The service keeps the newest events first. +class NotificationConnectionEvent { + const NotificationConnectionEvent({ + required this.time, + required this.event, + this.error, + this.code, + }); + + final DateTime time; + + /// The service's wire name for what happened, e.g. `failed`. + final String event; + final String? error; + + /// The HTTP status of a failed handshake, when there was one. + final int? code; + + factory NotificationConnectionEvent.fromMap(Map map) => + NotificationConnectionEvent( + time: DateTime.fromMillisecondsSinceEpoch( + (map['time'] as num?)?.toInt() ?? 0, + ), + event: map['event'] as String? ?? 'unknown', + error: map['error'] as String?, + code: (map['code'] as num?)?.toInt(), + ); + + /// A short, plain name for the event. + String get title => switch (event) { + 'connecting' => 'Opening socket', + 'connected' => 'Socket opened', + 'closed' => 'Socket closed', + 'failed' => 'Socket failed', + 'retry_scheduled' => 'Retry scheduled', + 'sign_in_required' => 'Session refused', + 'refused' => 'Subscribe refused', + 'network_available' => 'Network available', + 'network_lost' => 'Network lost', + 'invalid_endpoint' => 'Invalid address', + 'watchdog_restart' => 'Watchdog restart', + 'task_removed' => 'App closed from recents', + 'stopped' => 'Stopped', + _ => event, + }; + + /// The HTTP code and error text, when there are any. + String? get detail { + final parts = [ + if (code != null) 'HTTP $code', + if (error != null && error!.isNotEmpty) error!, + ]; + return parts.isEmpty ? null : parts.join(' · '); + } + + /// Local time as `MM-DD HH:MM:SS`. + String get timeLabel { + String two(int value) => value.toString().padLeft(2, '0'); + final local = time.toLocal(); + return '${two(local.month)}-${two(local.day)} ' + '${two(local.hour)}:${two(local.minute)}:${two(local.second)}'; + } +} diff --git a/app/lib/features/notification_service/notification_service_status.dart b/app/lib/features/notification_service/notification_service_status.dart index d44d09e7..f1f1c3bf 100644 --- a/app/lib/features/notification_service/notification_service_status.dart +++ b/app/lib/features/notification_service/notification_service_status.dart @@ -5,7 +5,8 @@ enum DeliveryState { connecting('connecting'), connected('connected'), reconnecting('reconnecting'), - waitingForNetwork('waiting_for_network'); + waitingForNetwork('waiting_for_network'), + signInRequired('sign_in_required'); const DeliveryState(this.wire); @@ -59,6 +60,8 @@ class NotificationServiceStatus { DeliveryState.connecting => 'Connecting…', DeliveryState.reconnecting => 'Reconnecting…', DeliveryState.waitingForNetwork => 'Waiting for a network', + DeliveryState.signInRequired => + 'Sign in to Pipelines again to keep notifications', DeliveryState.unconfigured => 'Starts after the app connects to a server', DeliveryState.off => enabled ? 'Not running' : 'Off', }; diff --git a/app/lib/features/settings/settings_device_delivery_section.dart b/app/lib/features/settings/settings_device_delivery_section.dart index f5511c17..494b4ecb 100644 --- a/app/lib/features/settings/settings_device_delivery_section.dart +++ b/app/lib/features/settings/settings_device_delivery_section.dart @@ -16,11 +16,24 @@ const deviceDeliveryNote = 'quiet "Pipelines is connected" notification while it runs.'; const deviceDeliveryBatteryLabel = 'Allow background delivery'; const deviceDeliveryNotificationsLabel = 'Allow notifications'; +const deviceDeliveryWarningTitle = 'Delivery can pause while idle'; +const deviceDeliveryWarningText = + 'Android may pause Pipelines in the background, so notifications can ' + 'arrive late. Allow background delivery above.'; +const deviceDeliverySamsungNote = + 'Samsung phones: also add Pipelines under Settings › Battery › ' + 'Background usage limits › Never sleeping apps.'; +const deviceDeliveryLogTitle = 'Connection log'; +const deviceDeliveryLogEmpty = 'No connection events yet'; abstract final class DeviceDeliveryKeys { static const toggle = ValueKey('settings.deviceDelivery.toggle'); static const status = ValueKey('settings.deviceDelivery.status'); static const battery = ValueKey('settings.deviceDelivery.battery'); + static const batteryWarning = ValueKey( + 'settings.deviceDelivery.batteryWarning', + ); + static const log = ValueKey('settings.deviceDelivery.log'); static const permission = ValueKey( 'settings.deviceDelivery.permission', ); @@ -66,7 +79,7 @@ class _SettingsDeviceDeliverySectionState void initState() { super.initState(); _lifecycle; - unawaited(_controller.load()); + unawaited(_controller.open()); } @override @@ -136,7 +149,45 @@ class _SettingsDeviceDeliverySectionState enabled: !status.batteryExempt && !_controller.busy, onTap: () => unawaited(_controller.allowBackgroundDelivery()), ), + if (status != null && enabled && !status.batteryExempt) + SettingsRow( + key: DeviceDeliveryKeys.batteryWarning, + leading: Icon( + Icons.warning_amber_rounded, + color: settingsErrorColor(context), + ), + title: const Text(deviceDeliveryWarningTitle), + subtitle: Text( + '$deviceDeliveryWarningText\n$deviceDeliverySamsungNote', + ), + ), + if (status != null) + ExpansionTile( + key: DeviceDeliveryKeys.log, + title: const Text(deviceDeliveryLogTitle), + children: _logRows(), + ), ], ); } + + List _logRows() { + final events = _controller.events; + if (events.isEmpty) { + return const [ListTile(title: Text(deviceDeliveryLogEmpty))]; + } + return [ + for (final event in events) + ListTile( + dense: true, + title: Text(event.title), + subtitle: Text( + [ + event.timeLabel, + if (event.detail != null) event.detail!, + ].join('\n'), + ), + ), + ]; + } } diff --git a/app/notes/android-background-delivery-reliability.md b/app/notes/android-background-delivery-reliability.md new file mode 100644 index 00000000..d3b29b9c --- /dev/null +++ b/app/notes/android-background-delivery-reliability.md @@ -0,0 +1,91 @@ +# Android background delivery: survive Doze, sign-in, battery, diagnosis + +Stage 01-implement, run 20261112-0157. Source only; not committed, not installed. + +## What changed + +- **Reconnects are alarms, not handler delays.** `ReconnectAlarms` schedules + `setExactAndAllowWhileIdle` when `canScheduleExactAlarms()`, otherwise + `setAndAllowWhileIdle`. The alarm PendingIntent is a foreground-service intent + to `NotificationService` (`ACTION_RECONNECT`). The `Handler.postDelayed` + reconnect is gone. +- **Watchdog.** `NotificationWatchdog` (JobScheduler, periodic 15 min, + persisted) restarts the service when delivery is enabled and the socket is + down with no reconnect pending. It does not restart while signed out or + waiting for a network. Also scheduled by `NotificationService.start`. +- **Connect wake lock.** `ConnectWakeLock` holds a partial wake lock for 30 s + from `connect()` until the socket opens or fails. +- **Swipe away.** `onTaskRemoved` logs and queues a watchdog check 2 s later. +- **Battery exemption.** `SettingsDeviceDeliverySection` shows a persistent + warning row while delivery is on and the exemption is missing, with the + Samsung "Never sleeping apps" note. `setEnabled(true)` requests the + exemption before starting the service. Opening Settings with delivery already + on and the exemption missing asks once per open (`NotificationServiceController.open`); + resume refreshes never ask again. +- **HTTP 401/403.** The retry loop stops, status becomes `sign_in_required`, + and a "Sign in to Pipelines again to keep notifications" notice is posted + (channel `pipelines.account`, id 2). `configure` with a fresh cookie restarts + the service. +- **Connection log.** `ConnectionLog` keeps the last 50 events (time, event, + error, HTTP code) in the service preferences. The channel method + `connectionEvents` returns them. Settings shows them in an expandable + "Connection log" row. + +## Files + +- Kotlin (new): `ReconnectPolicy.kt`, `ReconnectAlarms.kt`, + `NotificationWatchdog.kt`, `ConnectWakeLock.kt`, `ConnectionLog.kt` +- Kotlin (changed): `NotificationService.kt`, `NotificationPresenter.kt`, + `NotificationServiceChannel.kt`, `ServiceSettings.kt`, `AndroidManifest.xml` + (WAKE_LOCK, SCHEDULE_EXACT_ALARM, watchdog service) +- Kotlin tests (new): `ConnectionLogTest.kt` (5), `ReconnectPolicyTest.kt` (3) +- Dart (new): `lib/features/notification_service/notification_service_events.dart` +- Dart (changed): `notification_service_bridge.dart`, + `notification_service_controller.dart`, `notification_service_status.dart`, + `lib/features/settings/settings_device_delivery_section.dart` +- Dart tests (changed): `test/features/settings/settings_device_delivery_section_test.dart` + (+8 cases), `test/features/notification_service/notification_service_bridge_test.dart` + (+3 cases), `test/features/notification_service/fake_notification_service.dart` + +## Focused results + +- Kotlin: `gradle :app:testDebugUnitTest --tests 'net.awan.pipelines_app.notify.*'` + BUILD SUCCESSFUL. 28 of 28 pass: ConnectionLogTest 5, ReconnectPolicyTest 3, + DeliveryLedgerTest 8, NotificationProtocolTest 12. Includes main-source compile. +- Flutter: `tool/memwatch/full.sh` on the four files below, PASS 35 passed, + 0 failed (run twice, once after formatting): + - test/features/settings/settings_device_delivery_section_test.dart + - test/features/notification_service/notification_service_bridge_test.dart + - test/features/notification_service/notification_service_handoff_test.dart + - test/features/attention/notify/notification_delivery_test.dart +- `tool/analyze.sh`: clean (run twice). + +## Affected UI states (for ui-review, not captured here) + +- Delivery on, exemption missing: warning row visible with Samsung note. +- Delivery on, exemption granted: warning row gone; battery row says "Allowed". +- Delivery off: no battery row, no warning row. +- Status "Sign in to Pipelines again to keep notifications". +- Connection log collapsed, expanded with events, expanded empty + ("No connection events yet"). Expansion needs an interactive check. + +## Limitations and decisions + +- **Not verified on a device.** Doze timing, alarm delivery, the + foreground-start exemption from alarms and the watchdog job, the swipe + restart, and the sign-in notice were not run. The Fold was not touched. +- **Exact alarms.** SCHEDULE_EXACT_ALARM is declared, but the app does not + send the user to grant it. Without the grant, reconnects use + idle-tolerant alarms. +- **Upgrade users are prompted when Settings opens, not at app start.** The + exemption is requested on switch-on, and on opening Settings while delivery + is on and the exemption is missing. The prompt is not fired from app start + because the section is the only place with the request context. A user who + declines is prompted again the next time Settings opens, then sees the + warning row. Users who never open Settings are not prompted. +- **JobScheduler is deferred in Doze**, so the watchdog is a backstop; the + alarms are the primary path. +- NotificationService.kt is 387 lines (aim is under 250; it was 293 before). + The reconnect alarms, watchdog, wake lock and log are in separate files, + but the socket state machine remains in the service; splitting it further is + a follow-up. diff --git a/app/test/features/notification_service/fake_notification_service.dart b/app/test/features/notification_service/fake_notification_service.dart index 050be179..511df52f 100644 --- a/app/test/features/notification_service/fake_notification_service.dart +++ b/app/test/features/notification_service/fake_notification_service.dart @@ -16,6 +16,7 @@ class FakeNotificationService implements NotificationServiceBridge { ); NotificationServiceStatus current; + List events = const []; final calls = <(String, Map)>[]; final _changes = StreamController.broadcast(); bool batteryGranted = true; @@ -85,4 +86,9 @@ class FakeNotificationService implements NotificationServiceBridge { if (batteryGranted) current = copy(batteryExempt: true); return true; } + + // Not recorded in [calls]: the log is re-read after every action, and the + // tests assert on the action calls themselves. + @override + Future> connectionEvents() async => events; } diff --git a/app/test/features/notification_service/notification_service_bridge_test.dart b/app/test/features/notification_service/notification_service_bridge_test.dart index da9fe55f..4c6b0365 100644 --- a/app/test/features/notification_service/notification_service_bridge_test.dart +++ b/app/test/features/notification_service/notification_service_bridge_test.dart @@ -92,5 +92,39 @@ void main() { final bridge = createNotificationServiceBridge(); expect(bridge.supported, isFalse); expect((await bridge.status()).state, DeliveryState.off); + expect(await bridge.connectionEvents(), isEmpty); + }); + + test('a refused session reports sign_in_required', () { + expect( + NotificationServiceStatus.fromMap({'status': 'sign_in_required'}).state, + DeliveryState.signInRequired, + ); + }); + + test('connectionEvents reads the service log, newest first', () async { + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'connectionEvents') { + return [ + { + 'time': 2000, + 'event': 'failed', + 'error': 'Expected HTTP 101', + 'code': 403, + }, + {'time': 1000, 'event': 'connected'}, + ]; + } + return reply(); + }); + final bridge = MethodChannelNotificationServiceBridge(channel); + final events = await bridge.connectionEvents(); + expect(events.map((event) => event.event), ['failed', 'connected']); + expect(events.first.code, 403); + expect(events.first.error, 'Expected HTTP 101'); + expect(events.first.detail, 'HTTP 403 · Expected HTTP 101'); + expect(events.last.code, isNull); + expect(events.last.error, isNull); + expect(events.last.time, DateTime.fromMillisecondsSinceEpoch(1000)); }); } diff --git a/app/test/features/settings/settings_device_delivery_section_test.dart b/app/test/features/settings/settings_device_delivery_section_test.dart index b6d9003d..42fba51f 100644 --- a/app/test/features/settings/settings_device_delivery_section_test.dart +++ b/app/test/features/settings/settings_device_delivery_section_test.dart @@ -18,6 +18,9 @@ Widget _host( return MaterialApp(home: Scaffold(body: body)); } +int _requests(FakeNotificationService service) => + service.calls.where((call) => call.$1 == 'requestBatteryExemption').length; + bool _switchValue(WidgetTester tester) { final tile = find.byKey(DeviceDeliveryKeys.toggle); return tester.widget(tile).value; @@ -62,9 +65,11 @@ void main() { testWidgets('allow background delivery asks for the exemption', ( tester, ) async { - final service = FakeNotificationService(); + final service = FakeNotificationService()..batteryGranted = false; await tester.pumpWidget(_host(service)); await tester.pumpAndSettle(); + // The open-time prompt was declined; the row is the user's second try. + service.batteryGranted = true; await tester.tap(find.text(deviceDeliveryBatteryLabel)); await tester.pumpAndSettle(); expect( @@ -125,6 +130,157 @@ void main() { await tester.pumpAndSettle(); expect(find.byKey(DeviceDeliveryKeys.error), findsOneWidget); }); + + testWidgets( + 'a missing battery exemption keeps a warning row with the Samsung note', + (tester) async { + // The open-time prompt is declined, so the exemption stays missing. + final service = FakeNotificationService()..batteryGranted = false; + await tester.pumpWidget(_host(service)); + await tester.pumpAndSettle(); + expect(find.byKey(DeviceDeliveryKeys.batteryWarning), findsOneWidget); + expect(find.text(deviceDeliveryWarningTitle), findsOneWidget); + expect(find.textContaining(deviceDeliverySamsungNote), findsOneWidget); + }, + ); + + testWidgets('the warning goes away once the exemption is granted', ( + tester, + ) async { + final service = FakeNotificationService()..batteryGranted = false; + await tester.pumpWidget(_host(service)); + await tester.pumpAndSettle(); + expect(find.byKey(DeviceDeliveryKeys.batteryWarning), findsOneWidget); + service.batteryGranted = true; + await tester.tap(find.text(deviceDeliveryBatteryLabel)); + await tester.pumpAndSettle(); + expect(find.byKey(DeviceDeliveryKeys.batteryWarning), findsNothing); + }); + + testWidgets('switching on asks for the battery exemption before starting', ( + tester, + ) async { + final service = FakeNotificationService(); + service.current = service.copy(enabled: false, state: DeliveryState.off); + await tester.pumpWidget(_host(service)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(DeviceDeliveryKeys.toggle)); + await tester.pumpAndSettle(); + final names = service.calls.map((call) => call.$1).toList(); + expect(names, contains('requestBatteryExemption')); + expect( + names.indexOf('requestBatteryExemption'), + lessThan(names.indexOf('setEnabled')), + ); + }); + + testWidgets( + 'opening Settings with delivery on and no exemption asks right away', + (tester) async { + final service = FakeNotificationService(); + await tester.pumpWidget(_host(service)); + await tester.pumpAndSettle(); + expect(_requests(service), 1); + expect( + find.text('Allowed: battery optimisation will not pause delivery'), + findsOneWidget, + ); + expect(find.byKey(DeviceDeliveryKeys.batteryWarning), findsNothing); + }, + ); + + testWidgets('a declined open-time prompt is not repeated on resume', ( + tester, + ) async { + final service = FakeNotificationService()..batteryGranted = false; + await tester.pumpWidget(_host(service)); + await tester.pumpAndSettle(); + expect(_requests(service), 1); + expect(find.byKey(DeviceDeliveryKeys.batteryWarning), findsOneWidget); + // Returning from the system screen re-reads the status only. + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pumpAndSettle(); + expect(_requests(service), 1); + expect(find.byKey(DeviceDeliveryKeys.batteryWarning), findsOneWidget); + }); + + testWidgets('no open-time prompt when the exemption is already granted', ( + tester, + ) async { + final service = FakeNotificationService(); + service.current = service.copy(batteryExempt: true); + await tester.pumpWidget(_host(service)); + await tester.pumpAndSettle(); + expect(_requests(service), 0); + }); + + testWidgets('no open-time prompt while delivery is off', (tester) async { + final service = FakeNotificationService(); + service.current = service.copy(enabled: false, state: DeliveryState.off); + await tester.pumpWidget(_host(service)); + await tester.pumpAndSettle(); + expect(_requests(service), 0); + }); + + testWidgets('no warning while delivery is off', (tester) async { + final service = FakeNotificationService(); + service.current = service.copy(enabled: false, state: DeliveryState.off); + await tester.pumpWidget(_host(service)); + await tester.pumpAndSettle(); + expect(find.byKey(DeviceDeliveryKeys.batteryWarning), findsNothing); + }); + + testWidgets('a refused session says the user must sign in again', ( + tester, + ) async { + final service = FakeNotificationService(); + service.current = service.copy(state: DeliveryState.signInRequired); + await tester.pumpWidget(_host(service)); + await tester.pumpAndSettle(); + expect( + find.text('Sign in to Pipelines again to keep notifications'), + findsOneWidget, + ); + }); + + testWidgets( + 'the connection log lists the service events, failures included', + (tester) async { + final service = FakeNotificationService(); + service.events = [ + NotificationConnectionEvent( + time: DateTime(2026, 11, 12, 9, 30, 5), + event: 'failed', + error: 'Expected HTTP 101', + code: 403, + ), + NotificationConnectionEvent( + time: DateTime(2026, 11, 12, 9, 29), + event: 'connected', + ), + ]; + await tester.pumpWidget(_host(service)); + await tester.pumpAndSettle(); + await tester.tap(find.text(deviceDeliveryLogTitle)); + await tester.pumpAndSettle(); + expect(find.text('Socket failed'), findsOneWidget); + expect( + find.textContaining('HTTP 403 · Expected HTTP 101'), + findsOneWidget, + ); + expect(find.text('Socket opened'), findsOneWidget); + }, + ); + + testWidgets('an empty connection log says so', (tester) async { + final service = FakeNotificationService(); + await tester.pumpWidget(_host(service)); + await tester.pumpAndSettle(); + await tester.tap(find.text(deviceDeliveryLogTitle)); + await tester.pumpAndSettle(); + expect(find.text(deviceDeliveryLogEmpty), findsOneWidget); + }); } class _FailingService extends FakeNotificationService {