Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat(notifications): chat-run notifications show running, done, failed and stopped (#115)

Durganshuc1bc2a399805
diff --git a/app/src/main/java/com/gotcha/agent/ChatRunner.kt b/app/src/main/java/com/gotcha/agent/ChatRunner.kt
index 2521035..7918dc9 100644
--- a/app/src/main/java/com/gotcha/agent/ChatRunner.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatRunner.kt
@@ -1,6 +1,7 @@
package com.gotcha.agent
import android.app.Application
+import android.app.Notification
import com.gotcha.GotchaApp
import com.gotcha.audio.AudioModel
import com.gotcha.audio.AudioProvider
@@ -585,7 +586,7 @@ class ChatRunner(private val app: Application) : AgentEvents {
// own sanitize still gets repaired here before persisting.
engine.sanitizeLastOrphanedAssistant()
engine.saveCurrentSession()
- notifyRunFinished(
+ val finished = runFinishedNotification(
sessionId = runningId,
outcome = when {
stopped -> RunOutcome.STOPPED
@@ -593,9 +594,13 @@ class ChatRunner(private val app: Application) : AgentEvents {
else -> RunOutcome.DONE
}
)
- // After the finished notification is up, so in the background the
- // ongoing one is replaced by it rather than leaving a gap.
- ChatRunService.stop()
+ // In the background the ongoing notification turns into the
+ // finished one, in the same slot (issue #115).
+ if (finished != null) {
+ ChatRunService.finish(app, runningId, finished)
+ } else {
+ ChatRunService.stop()
+ }
withContext(Dispatchers.IO) { runMarker.clear() }
setState {
it.copy(
@@ -986,15 +991,16 @@ class ChatRunner(private val app: Application) : AgentEvents {
}
/**
- * The run in [sessionId] just ended. Posts the task-finished notification
- * when the user is away from Gotcha; in the foreground the reply buzz is
- * enough. Called once per run, from [executeRun]'s cleanup, so a run never
- * produces two — the engine reports text mid-run too, which is why this is
- * not driven by [onAssistantReply].
+ * The run in [sessionId] just ended. Returns the task-finished notification,
+ * with its inbox entry added, when the user is away from Gotcha; in the
+ * foreground the reply buzz is enough, and this returns null. Called once
+ * per run, from [executeRun]'s cleanup, so a run never produces two — the
+ * engine reports text mid-run too, which is why this is not driven by
+ * [onAssistantReply].
*/
- private fun notifyRunFinished(sessionId: String, outcome: RunOutcome) {
- if (appInForeground || !settings.chatCompletionNotificationsEnabled) return
- if (!completionNotifier.canPost()) return
+ private fun runFinishedNotification(sessionId: String, outcome: RunOutcome): Notification? {
+ if (appInForeground || !settings.chatCompletionNotificationsEnabled) return null
+ if (!completionNotifier.canPost()) return null
val reply = _state.value.transcript.lastOrNull {
it.kind == MessageKind.ASSISTANT || it.kind == MessageKind.ERROR
}?.text
@@ -1012,7 +1018,7 @@ class ChatRunner(private val app: Application) : AgentEvents {
body = ChatCompletionNotifier.defaultBody(outcome),
target = NotificationTarget.Chat(sessionId)
)
- completionNotifier.notify(
+ return completionNotifier.build(
sessionId = sessionId,
chatTitle = engine.currentTitle(),
outcome = outcome,
diff --git a/app/src/main/java/com/gotcha/notifications/ChatCompletionNotifier.kt b/app/src/main/java/com/gotcha/notifications/ChatCompletionNotifier.kt
index 5c8f0aa..aefbb14 100644
--- a/app/src/main/java/com/gotcha/notifications/ChatCompletionNotifier.kt
+++ b/app/src/main/java/com/gotcha/notifications/ChatCompletionNotifier.kt
@@ -1,6 +1,7 @@
package com.gotcha.notifications
import android.Manifest
+import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
@@ -11,7 +12,9 @@ import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
+import com.gotcha.R
import com.gotcha.data.CompletionPreview
+import com.gotcha.service.ChatRunService
/** How a chat run ended, as the task-finished notification reports it. */
enum class RunOutcome { DONE, FAILED, STOPPED }
@@ -43,7 +46,7 @@ class ChatCompletionNotifier(private val context: Context) {
* [inboxEntryId] is the inbox entry a tap marks read. Returns false when
* nothing was posted.
*/
- @Suppress("MissingPermission") // canPost() checks it.
+ @Suppress("MissingPermission") // build() checks canPost().
fun notify(
sessionId: String,
chatTitle: String,
@@ -53,7 +56,27 @@ class ChatCompletionNotifier(private val context: Context) {
named: Boolean = true,
inboxEntryId: String? = null
): Boolean {
- if (!canPost()) return false
+ val notification = build(sessionId, chatTitle, outcome, reply, preview, named, inboxEntryId) ?: return false
+ NotificationManagerCompat.from(context).notify(notificationId(sessionId), notification)
+ return true
+ }
+
+ /**
+ * The notification [notify] would post, without posting it, or null when
+ * Android would not show it. For a run that ended in the background,
+ * `ChatRunService` posts it in the slot of the ongoing notification, so one
+ * notification turns from "working" into "done" (issue #115).
+ */
+ fun build(
+ sessionId: String,
+ chatTitle: String,
+ outcome: RunOutcome,
+ reply: String?,
+ preview: CompletionPreview,
+ named: Boolean = true,
+ inboxEntryId: String? = null
+ ): Notification? {
+ if (!canPost()) return null
ensureChannel()
val notifyId = notificationId(sessionId)
val title = if (named) notificationTitle(chatTitle, outcome) else anonymousTitle(outcome)
@@ -61,7 +84,7 @@ class ChatCompletionNotifier(private val context: Context) {
val body = previewText(reply, shown) ?: defaultBody(outcome)
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
- .setSmallIcon(com.gotcha.R.drawable.ic_notification)
+ .setSmallIcon(smallIcon(outcome))
.setContentTitle(title)
.setContentText(body)
.setCategory(NotificationCompat.CATEGORY_STATUS)
@@ -69,7 +92,7 @@ class ChatCompletionNotifier(private val context: Context) {
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setPublicVersion(
NotificationCompat.Builder(context, CHANNEL_ID)
- .setSmallIcon(com.gotcha.R.drawable.ic_notification)
+ .setSmallIcon(smallIcon(outcome))
.setContentTitle(PUBLIC_TITLE)
.build()
)
@@ -78,12 +101,16 @@ class ChatCompletionNotifier(private val context: Context) {
if (shown == CompletionPreview.FULL) {
builder.setStyle(NotificationCompat.BigTextStyle().bigText(body))
}
- NotificationManagerCompat.from(context).notify(notifyId, builder.build())
- return true
+ return builder.build()
}
- /** Clears [sessionId]'s notification, e.g. once the user has opened that chat. */
+ /**
+ * Clears [sessionId]'s notification, e.g. once the user has opened that chat.
+ * Not while a run in that chat is going: the slot then holds its ongoing
+ * notification, which only `ChatRunService` takes down.
+ */
fun cancel(sessionId: String) {
+ if (ChatRunService.running.value?.sessionId == sessionId) return
NotificationManagerCompat.from(context).cancel(notificationId(sessionId))
}
@@ -119,7 +146,10 @@ class ChatCompletionNotifier(private val context: Context) {
private const val PUBLIC_TITLE = "Gotcha finished a task"
private const val SHORT_PREVIEW_CHARS = 140
- /** Stable per chat, so a later run's notification replaces the earlier one. */
+ /**
+ * Stable per chat, so a later run's notification replaces the earlier one.
+ * The ongoing notification of a run in the chat uses it too (issue #115).
+ */
internal fun notificationId(sessionId: String): Int = "chat:$sessionId".hashCode() and 0x7FFF_FFFF
internal fun notificationTitle(chatTitle: String, outcome: RunOutcome): String {
@@ -131,6 +161,13 @@ class ChatCompletionNotifier(private val context: Context) {
}
}
+ /** The status-bar icon, so the outcome shows without pulling down the shade (issue #115). */
+ internal fun smallIcon(outcome: RunOutcome): Int = when (outcome) {
+ RunOutcome.DONE -> R.drawable.ic_notification_done
+ RunOutcome.FAILED -> R.drawable.ic_notification_failed
+ RunOutcome.STOPPED -> R.drawable.ic_notification_stopped
+ }
+
/** The title when the chat may not be named. */
internal fun anonymousTitle(outcome: RunOutcome): String = when (outcome) {
RunOutcome.DONE -> "Task finished"
diff --git a/app/src/main/java/com/gotcha/service/ChatRunService.kt b/app/src/main/java/com/gotcha/service/ChatRunService.kt
index 4fbc0c2..89af93b 100644
--- a/app/src/main/java/com/gotcha/service/ChatRunService.kt
+++ b/app/src/main/java/com/gotcha/service/ChatRunService.kt
@@ -1,5 +1,6 @@
package com.gotcha.service
+import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
@@ -8,9 +9,12 @@ import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
+import android.os.Handler
import android.os.IBinder
+import android.os.Looper
import android.util.Log
import androidx.core.app.NotificationCompat
+import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import com.gotcha.notifications.ChatCompletionNotifier
import kotlinx.coroutines.CoroutineScope
@@ -40,6 +44,11 @@ data class RunningChat(val sessionId: String, val chatTitle: String?)
* startForegroundService that is brought down before it has called
* startForeground crashes the app, and a quickly failing run can end before the
* service is up.
+ *
+ * The notification sits in its chat's slot ([ChatCompletionNotifier.notificationId]).
+ * A run that ends in the background hands its task-finished notification to
+ * [finish], and the service posts it into that slot as it leaves the foreground,
+ * so the user sees one notification turn from "working" into "done" (issue #115).
*/
class ChatRunService : Service() {
@@ -63,7 +72,7 @@ class ChatRunService : Service() {
follower = serviceScope.launch {
_running.collect { chat ->
if (chat == null) {
- stopForeground(STOP_FOREGROUND_REMOVE)
+ leaveForeground()
// Only if no newer start arrived meanwhile.
stopSelf(lastStartId)
} else {
@@ -77,6 +86,8 @@ class ChatRunService : Service() {
}
override fun onDestroy() {
+ // Normally already done by the follower; the system can stop the service before it runs.
+ leaveForeground()
scope?.cancel()
scope = null
follower = null
@@ -85,11 +96,37 @@ class ChatRunService : Service() {
private fun goForeground(chat: RunningChat?) {
ensureChannel(this)
+ val id = chat?.let { ChatCompletionNotifier.notificationId(it.sessionId) } ?: NOTIFICATION_ID
+ // A new run in another chat while the service is still up: the last
+ // run's slot is let go first, or it would be left behind.
+ if (foregroundId != null && foregroundId != id) leaveForeground()
val notification = buildNotification(this, chat)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
- startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE)
+ startForeground(id, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE)
+ } else {
+ startForeground(id, notification)
+ }
+ foregroundId = id
+ // Same slot, new run: what the last run left to post is out of date.
+ completion = null
+ }
+
+ /**
+ * Gives up the foreground. With a [completion] waiting, the ongoing
+ * notification is detached and replaced by it in place; otherwise removed.
+ * Detached first, so the completion is posted as a plain notification and
+ * keeps no foreground-service flags.
+ */
+ private fun leaveForeground() {
+ val id = foregroundId
+ val pending = completion
+ foregroundId = null
+ completion = null
+ if (id != null && pending != null) {
+ stopForeground(STOP_FOREGROUND_DETACH)
+ postWhenDetached(applicationContext, id, pending, DETACH_POLLS)
} else {
- startForeground(NOTIFICATION_ID, notification)
+ stopForeground(STOP_FOREGROUND_REMOVE)
}
}
@@ -102,6 +139,17 @@ class ChatRunService : Service() {
private val _running = MutableStateFlow<RunningChat?>(null)
+ private val mainHandler = Handler(Looper.getMainLooper())
+ private const val DETACH_POLLS = 40
+ private const val DETACH_POLL_MS = 50L
+
+ // Main thread only, like the follower and the runner's cleanup.
+ /** The notification id the service holds the foreground with; null when it holds none. */
+ private var foregroundId: Int? = null
+
+ /** The task-finished notification to put in [foregroundId]'s slot as the service leaves the foreground. */
+ private var completion: Notification? = null
+
/** The run the service is (or should be) keeping alive; null when none. */
val running: StateFlow<RunningChat?> = _running.asStateFlow()
@@ -136,20 +184,62 @@ class ChatRunService : Service() {
_running.update { current -> if (current?.sessionId == chat.sessionId) chat else current }
}
+ /**
+ * Posts [notification] in slot [id] once Android has detached the ongoing
+ * one there. Android does that later, by posting its own copy of the
+ * ongoing notification again without the foreground-service flag; posted
+ * before that, the completion would be overwritten by it (seen on Android 16).
+ * Gives up waiting after about two seconds, and drops [notification] if a
+ * new run has taken the slot meanwhile.
+ */
+ @Suppress("MissingPermission") // ChatCompletionNotifier.build checked it.
+ private fun postWhenDetached(context: Context, id: Int, notification: Notification, pollsLeft: Int) {
+ if (foregroundId == id) return
+ val manager = context.getSystemService(NotificationManager::class.java)
+ val stillForeground = manager?.activeNotifications.orEmpty().any {
+ it.id == id && it.notification.flags and Notification.FLAG_FOREGROUND_SERVICE != 0
+ }
+ if (stillForeground && pollsLeft > 0) {
+ mainHandler.postDelayed(
+ { postWhenDetached(context, id, notification, pollsLeft - 1) },
+ DETACH_POLL_MS
+ )
+ return
+ }
+ NotificationManagerCompat.from(context).notify(id, notification)
+ }
+
/** The run has ended: the service removes its notification and stops. */
fun stop() {
_running.value = null
}
+ /**
+ * The run in [sessionId] has ended and [notification] reports it. When the
+ * service holds that chat's slot, the notification takes the ongoing one's
+ * place as the service stops; otherwise (the service never got to the
+ * foreground) it is posted as is.
+ */
+ @Suppress("MissingPermission") // ChatCompletionNotifier.build checked it.
+ fun finish(context: Context, sessionId: String, notification: Notification) {
+ val id = ChatCompletionNotifier.notificationId(sessionId)
+ if (_running.value?.sessionId == sessionId && foregroundId == id) {
+ completion = notification
+ } else {
+ NotificationManagerCompat.from(context).notify(id, notification)
+ }
+ stop()
+ }
+
internal fun title(chat: RunningChat?): String {
val name = chat?.chatTitle?.takeIf { it.isNotBlank() } ?: return PUBLIC_TITLE
// A name already cut short with "…" doesn't need a second one.
return if (name.endsWith("…")) "Gotcha is working on “$name”" else "Gotcha is working on “$name”…"
}
- internal fun buildNotification(context: Context, chat: RunningChat?): android.app.Notification {
+ internal fun buildNotification(context: Context, chat: RunningChat?): Notification {
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
- .setSmallIcon(com.gotcha.R.drawable.ic_notification)
+ .setSmallIcon(com.gotcha.R.drawable.ic_notification_running)
.setContentTitle(title(chat))
.setContentText("Tap to follow along. You can keep using your phone.")
.setCategory(NotificationCompat.CATEGORY_PROGRESS)
@@ -161,7 +251,7 @@ class ChatRunService : Service() {
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setPublicVersion(
NotificationCompat.Builder(context, CHANNEL_ID)
- .setSmallIcon(com.gotcha.R.drawable.ic_notification)
+ .setSmallIcon(com.gotcha.R.drawable.ic_notification_running)
.setContentTitle(PUBLIC_TITLE)
.build()
)
diff --git a/app/src/main/res/drawable/ic_notification_done.xml b/app/src/main/res/drawable/ic_notification_done.xml
new file mode 100644
index 0000000..f8860c9
--- /dev/null
+++ b/app/src/main/res/drawable/ic_notification_done.xml
@@ -0,0 +1,12 @@
+<!--
+ Material "check_circle": the status-bar icon of a chat run that finished (issue #115).
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM10,17l-5,-5 1.41,-1.41L10,14.17l7.59,-7.59L19,8l-9,9z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_notification_failed.xml b/app/src/main/res/drawable/ic_notification_failed.xml
new file mode 100644
index 0000000..c765cda
--- /dev/null
+++ b/app/src/main/res/drawable/ic_notification_failed.xml
@@ -0,0 +1,12 @@
+<!--
+ Material "error": the status-bar icon of a chat run that failed (issue #115).
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM13,17h-2v-2h2v2zM13,13h-2L11,7h2v6z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_notification_running.xml b/app/src/main/res/drawable/ic_notification_running.xml
new file mode 100644
index 0000000..38d2cd2
--- /dev/null
+++ b/app/src/main/res/drawable/ic_notification_running.xml
@@ -0,0 +1,12 @@
+<!--
+ Material "sync": the status-bar icon of a chat run in progress (issue #115).
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M12,4V1L8,5l4,4V6c3.31,0 6,2.69 6,6 0,1.01 -0.25,1.97 -0.7,2.8l1.46,1.46C19.54,15.03 20,13.57 20,12c0,-4.42 -3.58,-8 -8,-8zM12,18c-3.31,0 -6,-2.69 -6,-6 0,-1.01 0.25,-1.97 0.7,-2.8L5.24,7.74C4.46,8.97 4,10.43 4,12c0,4.42 3.58,8 8,8v3l4,-4 -4,-4v3z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_notification_stopped.xml b/app/src/main/res/drawable/ic_notification_stopped.xml
new file mode 100644
index 0000000..a33b3b9
--- /dev/null
+++ b/app/src/main/res/drawable/ic_notification_stopped.xml
@@ -0,0 +1,12 @@
+<!--
+ Material "stop_circle": the status-bar icon of a chat run that was stopped (issue #115).
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM16,16H8V8h8v8z" />
+</vector>
diff --git a/app/src/test/java/com/gotcha/notifications/ChatCompletionNotifierTest.kt b/app/src/test/java/com/gotcha/notifications/ChatCompletionNotifierTest.kt
index 3284c24..3500904 100644
--- a/app/src/test/java/com/gotcha/notifications/ChatCompletionNotifierTest.kt
+++ b/app/src/test/java/com/gotcha/notifications/ChatCompletionNotifierTest.kt
@@ -5,6 +5,7 @@ import android.app.Application
import android.app.NotificationManager
import androidx.core.app.NotificationCompat
import androidx.test.core.app.ApplicationProvider
+import com.gotcha.R
import com.gotcha.data.CompletionPreview
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@@ -112,4 +113,24 @@ class ChatCompletionNotifierTest {
val text = posted().single().extras.getCharSequence(NotificationCompat.EXTRA_TEXT).toString()
assertEquals(ChatCompletionNotifier.defaultBody(RunOutcome.FAILED), text)
}
+
+ @Test
+ fun `each outcome has its own status-bar icon, on the lock-screen version too`() {
+ val icons = RunOutcome.entries.map(ChatCompletionNotifier::smallIcon)
+ assertEquals(icons.size, icons.toSet().size)
+
+ notifier.notify("s1", "Chat", RunOutcome.FAILED, "oops", CompletionPreview.SHORT)
+ val notification = posted().single()
+ assertEquals(R.drawable.ic_notification_failed, notification.smallIcon.resId)
+ assertEquals(R.drawable.ic_notification_failed, notification.publicVersion.smallIcon.resId)
+ assertEquals("Gotcha finished a task", notification.publicVersion.extras.getString(NotificationCompat.EXTRA_TITLE))
+ }
+
+ @Test
+ fun `build makes the notification without posting it`() {
+ val notification = notifier.build("s1", "Chat", RunOutcome.DONE, "reply", CompletionPreview.SHORT)
+
+ assertEquals("Done: Chat", notification?.extras?.getString(NotificationCompat.EXTRA_TITLE))
+ assertTrue(posted().isEmpty())
+ }
}
diff --git a/app/src/test/java/com/gotcha/service/ChatRunServiceTest.kt b/app/src/test/java/com/gotcha/service/ChatRunServiceTest.kt
index 686f2ab..d507bc4 100644
--- a/app/src/test/java/com/gotcha/service/ChatRunServiceTest.kt
+++ b/app/src/test/java/com/gotcha/service/ChatRunServiceTest.kt
@@ -2,10 +2,13 @@ package com.gotcha.service
import android.app.Application
import android.app.Notification
+import android.app.NotificationManager
import android.content.Intent
import androidx.core.app.NotificationCompat
import androidx.test.core.app.ApplicationProvider
+import com.gotcha.R
import com.gotcha.notifications.ChatCompletionNotifier
+import java.util.concurrent.TimeUnit
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.first
@@ -38,9 +41,13 @@ class ChatRunServiceTest {
ChatRunService.stop()
}
+ private val services = mutableListOf<ServiceController<ChatRunService>>()
+
@After
fun tearDown() {
ChatRunService.stop()
+ // The service's foreground state is shared, as in the app: one left up would leak into the next test.
+ services.forEach { it.destroy() }
}
private fun startedService(): ServiceController<ChatRunService> {
@@ -49,6 +56,7 @@ class ChatRunServiceTest {
val controller = Robolectric.buildService(ChatRunService::class.java, intent)
controller.create().startCommand(0, 1)
ShadowLooper.idleMainLooper()
+ services += controller
return controller
}
@@ -160,6 +168,107 @@ class ChatRunServiceTest {
assertEquals(chat, ChatRunService.running.value)
}
+ @Test
+ fun `the ongoing notification sits in its chat's slot with the running icon`() {
+ val controller = startedService()
+
+ assertEquals(
+ ChatCompletionNotifier.notificationId("session-1"),
+ shadowOf(controller.get()).lastForegroundNotificationId
+ )
+ assertEquals(R.drawable.ic_notification_running, controller.notification().smallIcon.resId)
+ }
+
+ @Test
+ fun `finish turns the ongoing notification into the finished one, in place`() {
+ val controller = startedService()
+ val slot = ChatCompletionNotifier.notificationId("session-1")
+
+ ChatRunService.finish(application, "session-1", finished("Done: Plan my trip"))
+ ShadowLooper.idleMainLooper()
+
+ // Detached, not removed. Posted only once Android has re-posted the
+ // detached notification, or that copy would cover the finished one.
+ assertTrue(shadowOf(controller.get()).isForegroundStopped)
+ assertFalse(shadowOf(controller.get()).notificationShouldRemoved)
+ assertEquals(controller.notification(), posted(slot))
+ androidDetaches(slot)
+ ShadowLooper.idleMainLooper(100, TimeUnit.MILLISECONDS)
+ assertEquals("Done: Plan my trip", posted(slot)?.extras?.getString(NotificationCompat.EXTRA_TITLE))
+ assertTrue(shadowOf(controller.get()).isStoppedBySelf)
+ assertNull(ChatRunService.running.value)
+ }
+
+ @Test
+ fun `the finished notification still comes when Android is slow to detach`() {
+ startedService()
+
+ ChatRunService.finish(application, "session-1", finished("Done: Plan my trip"))
+ ShadowLooper.idleMainLooper(3, TimeUnit.SECONDS)
+
+ assertEquals(
+ "Done: Plan my trip",
+ posted(ChatCompletionNotifier.notificationId("session-1"))?.extras?.getString(NotificationCompat.EXTRA_TITLE)
+ )
+ }
+
+ @Test
+ fun `finish without the service in the foreground posts the notification itself`() {
+ ChatRunService.start(application, chat)
+
+ ChatRunService.finish(application, "session-1", finished("Failed: Plan my trip"))
+
+ assertEquals(
+ "Failed: Plan my trip",
+ posted(ChatCompletionNotifier.notificationId("session-1"))?.extras?.getString(NotificationCompat.EXTRA_TITLE)
+ )
+ assertNull(ChatRunService.running.value)
+ }
+
+ @Test
+ fun `a finished run followed at once by one in another chat still leaves its notification`() {
+ val controller = startedService()
+
+ ChatRunService.finish(application, "session-1", finished("Done: Plan my trip"))
+ ChatRunService.start(application, RunningChat("session-2", "Second"))
+ controller.startCommand(0, 2)
+ ShadowLooper.idleMainLooper()
+ androidDetaches(ChatCompletionNotifier.notificationId("session-1"))
+ ShadowLooper.idleMainLooper(100, TimeUnit.MILLISECONDS)
+
+ assertEquals(
+ "Done: Plan my trip",
+ posted(ChatCompletionNotifier.notificationId("session-1"))?.extras?.getString(NotificationCompat.EXTRA_TITLE)
+ )
+ assertEquals(ChatCompletionNotifier.notificationId("session-2"), shadowOf(controller.get()).lastForegroundNotificationId)
+ assertFalse(shadowOf(controller.get()).isStoppedBySelf)
+ }
+
+ @Test
+ fun `opening the chat of the run in progress leaves its notification alone`() {
+ val controller = startedService()
+
+ ChatCompletionNotifier(application).cancel("session-1")
+
+ assertEquals(controller.notification(), posted(ChatCompletionNotifier.notificationId("session-1")))
+ }
+
+ private fun finished(title: String): Notification =
+ NotificationCompat.Builder(application, ChatCompletionNotifier.CHANNEL_ID)
+ .setSmallIcon(R.drawable.ic_notification_done)
+ .setContentTitle(title)
+ .build()
+
+ /** What Android does some time after stopForeground(DETACH), and Robolectric doesn't: the flag goes. */
+ private fun androidDetaches(id: Int) {
+ val detached = Notification.Builder.recoverBuilder(application, posted(id)).build()
+ detached.flags = detached.flags and Notification.FLAG_FOREGROUND_SERVICE.inv()
+ application.getSystemService(NotificationManager::class.java).notify(id, detached)
+ }
+
+ private fun posted(id: Int): Notification? =
+ shadowOf(application.getSystemService(NotificationManager::class.java)).getNotification(id)
+
@Test
fun `a name cut short keeps a single ellipsis`() {
assertEquals(