Fix unbound CoroutineScope in NotificationReplyReceiver (#265) (#331)

This commit addresses issue #265 where the NotificationReplyReceiver
used an unbound CoroutineScope when handling asynchronous reply saves
to the Room database. If the DAO operation hangs, the PendingResult.finish()
method is never called, which could lead to an Application Not Responding (ANR)
error.

Changes made:
- Wrapped the Room upsert operation inside a `withTimeout(5000L)` block
  within the IO coroutine in `NotificationReplyReceiver.kt`.
- Ensures that if the operation exceeds 5 seconds, a TimeoutCancellationException
  is thrown and caught, allowing `pendingResult.finish()` to execute in the
  `finally` block.
- Added a unit test in `NotificationReplyReceiverTest.kt` to verify that
  if the mock DAO hangs indefinitely, the PendingResult is still correctly finished
  after the timeout.

Impact:
- Prevents potential ANRs caused by stuck local DB transactions during inline
  notification replies.
This commit is contained in:
M57 authored and GitHub committed 2026-06-23 11:56:10 +03:00
1 parent 557e438dc7
commit 7ea8698db9
2 files changed
+39 -16

No files matched your search

@@ -53,22 +53,24 @@ open class NotificationReplyReceiver : BroadcastReceiver() {
val pendingResult = goAsyncCompat()
kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO).launch {
try {
val db =
com.m57.hermescontrol.data.local.HermesDatabase
.get(context)
val dao = db.chatMessageDao()
val entity =
com.m57.hermescontrol.data.local.ChatMessageEntity(
id =
java.util.UUID
.randomUUID()
.toString(),
sessionId = sessionId,
role = "USER",
content = replyText,
timestamp = System.currentTimeMillis(),
)
dao.upsert(entity)
kotlinx.coroutines.withTimeout(5000L) {
val db =
com.m57.hermescontrol.data.local.HermesDatabase
.get(context)
val dao = db.chatMessageDao()
val entity =
com.m57.hermescontrol.data.local.ChatMessageEntity(
id =
java.util.UUID
.randomUUID()
.toString(),
sessionId = sessionId,
role = "USER",
content = replyText,
timestamp = System.currentTimeMillis(),
)
dao.upsert(entity)
}
} catch (e: Exception) {
android.util.Log.e("NotificationReply", "Failed to save replied message to Room DB", e)
} finally {