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(agent): keep a chat run alive with a foreground service while Gotcha is in the background (#105)

Durganshuf8da471a4308
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 2f98173..68ba3d7 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -211,6 +211,18 @@
android:value="floating_assistant_overlay" />
</service>
+ <!-- Keeps the process alive while a chat run is in progress, so leaving Gotcha
+ mid-task does not let Android reclaim it (issue #105). specialUse: the run
+ is an on-device agent task, which none of the other types describe. -->
+ <service
+ android:name=".service.ChatRunService"
+ android:exported="false"
+ android:foregroundServiceType="specialUse">
+ <property
+ android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
+ android:value="agent_task_in_progress" />
+ </service>
+
<!-- Screenshot capture via MediaProjection (foreground service, one-shot). -->
<service
android:name=".service.MediaProjectionService"
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 8134ee1..cbe3163 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -42,6 +42,8 @@ import com.gotcha.notifications.LocalNotificationStore
import com.gotcha.notifications.NotificationCategory
import com.gotcha.notifications.NotificationTarget
import com.gotcha.notifications.RunOutcome
+import com.gotcha.service.ChatRunService
+import com.gotcha.service.RunningChat
import com.gotcha.tools.AgentMode
import com.gotcha.tools.DocumentError
import com.gotcha.tools.DocumentParser
@@ -440,6 +442,8 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
com.gotcha.data.SampleChatSeeder.seedIfNeeded(historyRepository, settingsRepository.prefs)
refreshSessions()
}
+ // Stop on the ongoing "Gotcha is working…" notification (issue #105).
+ viewModelScope.launch { ChatRunService.stopRequests.collect { stopAgent() } }
}
// ---- AgentEvents (engine → UI) ----
@@ -589,8 +593,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
}
val sessionId = state.runningSessionId ?: agentEngine.sessionId ?: return
// Issue #100: a chat kept out of notifications is not named, nor is its question.
- val named = settings.notificationsMentionChats &&
- !localNotificationStore.isChatSensitive(sessionId, agentEngine.sessionPersonaId)
+ val named = mayNameChat(sessionId)
attentionNotifier.notify(
sessionId = sessionId,
kind = kind,
@@ -819,6 +822,13 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
askNotificationPermission = it.askNotificationPermission || claimNotificationPermissionAsk()
)
}
+ // Issue #105: hold a foreground slot for the run, so Android keeps the
+ // process alive if the user leaves mid-task. Started here, while the user
+ // who just sent the message is still in Gotcha.
+ ChatRunService.start(
+ getApplication(),
+ RunningChat(runningId, agentEngine.currentTitle().takeIf { mayNameChat(runningId) })
+ )
runHadError = false
var stopped = false
try {
@@ -848,6 +858,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
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()
_uiState.update {
it.copy(
isBusy = false,
@@ -864,6 +877,11 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
}
}
+ /** Issue #100: whether a notification about the engine's chat [sessionId] may name it. */
+ private fun mayNameChat(sessionId: String): Boolean =
+ settings.notificationsMentionChats &&
+ !localNotificationStore.isChatSensitive(sessionId, agentEngine.sessionPersonaId)
+
private fun currentBackgroundHint(): String = backgroundHintText(
vibrate = settings.notifyVibrationEnabled,
chime = settings.notifyChimeEnabled,
@@ -885,8 +903,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
}?.text
// Issue #100: a chat kept out of notifications, or chats not to be named
// at all, get a notification that says only that a task finished.
- val named = settings.notificationsMentionChats &&
- !localNotificationStore.isChatSensitive(sessionId, agentEngine.sessionPersonaId)
+ val named = mayNameChat(sessionId)
val title = if (named) {
ChatCompletionNotifier.notificationTitle(agentEngine.currentTitle(), outcome)
} else {
diff --git a/app/src/main/java/com/gotcha/service/ChatRunService.kt b/app/src/main/java/com/gotcha/service/ChatRunService.kt
new file mode 100644
index 0000000..b76820c
--- /dev/null
+++ b/app/src/main/java/com/gotcha/service/ChatRunService.kt
@@ -0,0 +1,196 @@
+package com.gotcha.service
+
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.app.Service
+import android.content.Context
+import android.content.Intent
+import android.content.pm.ServiceInfo
+import android.os.Build
+import android.os.IBinder
+import android.util.Log
+import androidx.core.app.NotificationCompat
+import androidx.core.content.ContextCompat
+import com.gotcha.notifications.ChatCompletionNotifier
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.MainScope
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.SharedFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asSharedFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.launch
+
+/** The chat run the ongoing notification is about. [chatTitle] null: the chat may not be named (issue #100). */
+data class RunningChat(val sessionId: String, val chatTitle: String?)
+
+/**
+ * Keeps Gotcha's process alive while a chat run is in progress (issue #105).
+ * The run itself stays in `ChatViewModel`; this service only holds a foreground
+ * slot, with an ongoing "Gotcha is working…" notification, so Android does not
+ * reclaim the process once the user leaves the app mid-task.
+ *
+ * [start] and [stop] only set the wanted state; the service follows it. [stop]
+ * never stops the service directly, because a service started with
+ * 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.
+ */
+class ChatRunService : Service() {
+
+ private var scope: CoroutineScope? = null
+ private var follower: Job? = null
+ private var lastStartId = 0
+
+ override fun onBind(intent: Intent?): IBinder? = null
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ lastStartId = startId
+ if (intent?.action == ACTION_STOP_RUN) {
+ _stopRequests.tryEmit(Unit)
+ return START_NOT_STICKY
+ }
+ // Required within seconds of startForegroundService, even when the run has
+ // already ended: the follower below then takes the service straight down.
+ goForeground(_running.value)
+ if (follower == null) {
+ val serviceScope = MainScope().also { scope = it }
+ follower = serviceScope.launch {
+ _running.collect { chat ->
+ if (chat == null) {
+ stopForeground(STOP_FOREGROUND_REMOVE)
+ // Only if no newer start arrived meanwhile.
+ stopSelf(lastStartId)
+ } else {
+ goForeground(chat)
+ }
+ }
+ }
+ }
+ // A process killed mid-run has nothing to resume: the run died with it.
+ return START_NOT_STICKY
+ }
+
+ override fun onDestroy() {
+ scope?.cancel()
+ scope = null
+ follower = null
+ super.onDestroy()
+ }
+
+ private fun goForeground(chat: RunningChat?) {
+ ensureChannel(this)
+ 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)
+ } else {
+ startForeground(NOTIFICATION_ID, notification)
+ }
+ }
+
+ companion object {
+ private const val TAG = "ChatRunService"
+ const val CHANNEL_ID = "gotcha_chat_running"
+ const val ACTION_STOP_RUN = "com.gotcha.ACTION_STOP_CHAT_RUN"
+ internal const val NOTIFICATION_ID = 0x4A77_E8
+ private const val PUBLIC_TITLE = "Gotcha is working on a task…"
+
+ private val _running = MutableStateFlow<RunningChat?>(null)
+
+ /** The run the service is (or should be) keeping alive; null when none. */
+ val running: StateFlow<RunningChat?> = _running.asStateFlow()
+
+ private val _stopRequests = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
+
+ /** Emits when the user taps Stop on the ongoing notification. */
+ val stopRequests: SharedFlow<Unit> = _stopRequests.asSharedFlow()
+
+ /**
+ * Starts keeping the process alive for [chat]. Call it as the run starts,
+ * while Gotcha is still in the foreground: Android refuses to start a
+ * foreground service from the background, and then the run just goes on
+ * without one, as it did before.
+ */
+ fun start(context: Context, chat: RunningChat) {
+ _running.value = chat
+ try {
+ ContextCompat.startForegroundService(context, Intent(context, ChatRunService::class.java))
+ } catch (e: IllegalStateException) {
+ // ForegroundServiceStartNotAllowedException (API 31+) is one of these.
+ Log.w(TAG, "Could not keep the run alive in the background: ${e.message}")
+ } catch (e: SecurityException) {
+ Log.w(TAG, "Could not keep the run alive in the background: ${e.message}")
+ }
+ }
+
+ /** The run has ended: the service removes its notification and stops. */
+ fun stop() {
+ _running.value = null
+ }
+
+ internal fun title(chat: RunningChat?): String {
+ val name = chat?.chatTitle?.takeIf { it.isNotBlank() } ?: return PUBLIC_TITLE
+ return "Gotcha is working on “$name”…"
+ }
+
+ internal fun buildNotification(context: Context, chat: RunningChat?): android.app.Notification {
+ val builder = NotificationCompat.Builder(context, CHANNEL_ID)
+ .setSmallIcon(com.gotcha.R.drawable.ic_notification)
+ .setContentTitle(title(chat))
+ .setContentText("Tap to follow along. You can keep using your phone.")
+ .setCategory(NotificationCompat.CATEGORY_PROGRESS)
+ .setProgress(0, 0, true)
+ .setOngoing(true)
+ .setOnlyAlertOnce(true)
+ .setSilent(true)
+ // The chat's name can be personal: the lock screen gets a generic line only.
+ .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
+ .setPublicVersion(
+ NotificationCompat.Builder(context, CHANNEL_ID)
+ .setSmallIcon(com.gotcha.R.drawable.ic_notification)
+ .setContentTitle(PUBLIC_TITLE)
+ .build()
+ )
+ .addAction(0, "Stop", stopIntent(context))
+ chat?.let { builder.setContentIntent(openChatIntent(context, it.sessionId)) }
+ return builder.build()
+ }
+
+ private fun openChatIntent(context: Context, sessionId: String): PendingIntent {
+ val intent = Intent(context, com.gotcha.MainActivity::class.java).apply {
+ action = ChatCompletionNotifier.ACTION_OPEN_CHAT_SESSION
+ putExtra(ChatCompletionNotifier.EXTRA_OPEN_SESSION_ID, sessionId)
+ flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
+ }
+ return PendingIntent.getActivity(
+ context,
+ NOTIFICATION_ID,
+ intent,
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ )
+ }
+
+ private fun stopIntent(context: Context): PendingIntent = PendingIntent.getService(
+ context,
+ NOTIFICATION_ID,
+ Intent(context, ChatRunService::class.java).setAction(ACTION_STOP_RUN),
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ )
+
+ private fun ensureChannel(context: Context) {
+ val mgr = context.getSystemService(NotificationManager::class.java) ?: return
+ if (mgr.getNotificationChannel(CHANNEL_ID) != null) return
+ mgr.createNotificationChannel(
+ NotificationChannel(CHANNEL_ID, "Task in progress", NotificationManager.IMPORTANCE_LOW).apply {
+ description = "Shown while Gotcha works on a task, so Android keeps it running " +
+ "when you switch to another app"
+ setShowBadge(false)
+ }
+ )
+ }
+ }
+}
diff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelCompletionNotificationTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelCompletionNotificationTest.kt
index c6a2392..2c2fc70 100644
--- a/app/src/test/java/com/gotcha/agent/ChatViewModelCompletionNotificationTest.kt
+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelCompletionNotificationTest.kt
@@ -9,9 +9,16 @@ import com.gotcha.data.LlmProvider
import com.gotcha.data.Settings
import com.gotcha.data.SettingsRepository
import com.gotcha.notifications.ChatCompletionNotifier
+import com.gotcha.service.ChatRunService
+import com.gotcha.service.RunningChat
import com.gotcha.testsupport.FakeAndroidKeyStore
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.launch
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
@@ -55,6 +62,7 @@ class ChatViewModelCompletionNotificationTest {
@Before
fun clearTray() {
manager.cancelAll()
+ ChatRunService.stop()
}
private fun waitForRunToFinish() {
@@ -165,4 +173,38 @@ class ChatViewModelCompletionNotificationTest {
assertFalse(viewModel.uiState.value.askNotificationPermission)
waitForRunToFinish()
}
+
+ /** Every value [ChatRunService.running] takes, recorded as it is set. */
+ private fun recordRunning(): Pair<MutableList<RunningChat?>, Job> {
+ val seen = java.util.Collections.synchronizedList(mutableListOf<RunningChat?>())
+ val job = CoroutineScope(Dispatchers.Unconfined).launch { ChatRunService.running.collect { seen += it } }
+ return seen to job
+ }
+
+ @Test
+ fun `a run holds the keep-alive service until it ends`() {
+ start()
+ val (seen, job) = recordRunning()
+ viewModel.sendMessage("Hello")
+ waitForRunToFinish()
+ job.cancel()
+
+ val started = shadowOf(application).nextStartedService
+ assertEquals(ChatRunService::class.java.name, started?.component?.className)
+ assertEquals(viewModel.uiState.value.activeSessionId, seen.filterNotNull().single().sessionId)
+ assertNull(ChatRunService.running.value)
+ }
+
+ @Test
+ fun `the keep-alive notification does not name a chat when chats are not to be named`() {
+ start()
+ settingsRepository.save(settingsRepository.load().copy(notificationsMentionChats = false))
+ viewModel.refreshSettings()
+ val (seen, job) = recordRunning()
+ viewModel.sendMessage("Hello")
+ waitForRunToFinish()
+ job.cancel()
+
+ assertNull(seen.filterNotNull().single().chatTitle)
+ }
}
diff --git a/app/src/test/java/com/gotcha/service/ChatRunServiceTest.kt b/app/src/test/java/com/gotcha/service/ChatRunServiceTest.kt
new file mode 100644
index 0000000..84e73ca
--- /dev/null
+++ b/app/src/test/java/com/gotcha/service/ChatRunServiceTest.kt
@@ -0,0 +1,138 @@
+package com.gotcha.service
+
+import android.app.Application
+import android.app.Notification
+import android.content.Intent
+import androidx.core.app.NotificationCompat
+import androidx.test.core.app.ApplicationProvider
+import com.gotcha.notifications.ChatCompletionNotifier
+import kotlinx.coroutines.CoroutineStart
+import kotlinx.coroutines.async
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.runBlocking
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.Robolectric
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.Shadows.shadowOf
+import org.robolectric.android.controller.ServiceController
+import org.robolectric.annotation.Config
+import org.robolectric.shadows.ShadowLooper
+
+/** The keep-alive service for a chat run (issue #105). */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34])
+class ChatRunServiceTest {
+
+ private val application: Application = ApplicationProvider.getApplicationContext()
+ private val chat = RunningChat(sessionId = "session-1", chatTitle = "Plan my trip")
+
+ @Before
+ fun reset() {
+ ChatRunService.stop()
+ }
+
+ @After
+ fun tearDown() {
+ ChatRunService.stop()
+ }
+
+ private fun startedService(): ServiceController<ChatRunService> {
+ ChatRunService.start(application, chat)
+ val intent = Intent(application, ChatRunService::class.java)
+ val controller = Robolectric.buildService(ChatRunService::class.java, intent)
+ controller.create().startCommand(0, 1)
+ ShadowLooper.idleMainLooper()
+ return controller
+ }
+
+ private fun ServiceController<ChatRunService>.notification(): Notification =
+ shadowOf(get()).lastForegroundNotification
+
+ @Test
+ fun `start asks Android for the foreground service`() {
+ ChatRunService.start(application, chat)
+
+ val started = shadowOf(application).nextStartedService
+ assertEquals(ChatRunService::class.java.name, started.component?.className)
+ assertEquals(chat, ChatRunService.running.value)
+ }
+
+ @Test
+ fun `the ongoing notification names the chat and opens it`() {
+ val notification = startedService().notification()
+
+ assertEquals(
+ "Gotcha is working on “Plan my trip”…",
+ notification.extras.getString(NotificationCompat.EXTRA_TITLE)
+ )
+ assertTrue(notification.flags and Notification.FLAG_ONGOING_EVENT != 0)
+ val tap = shadowOf(notification.contentIntent).savedIntent
+ assertEquals(ChatCompletionNotifier.ACTION_OPEN_CHAT_SESSION, tap.action)
+ assertEquals("session-1", tap.getStringExtra(ChatCompletionNotifier.EXTRA_OPEN_SESSION_ID))
+ assertEquals(ChatRunService.CHANNEL_ID, notification.channelId)
+ }
+
+ @Test
+ fun `a chat that may not be named is not`() {
+ assertEquals("Gotcha is working on a task…", ChatRunService.title(chat.copy(chatTitle = null)))
+ }
+
+ @Test
+ fun `stop removes the notification and stops the service`() {
+ val controller = startedService()
+
+ ChatRunService.stop()
+ ShadowLooper.idleMainLooper()
+
+ assertTrue(shadowOf(controller.get()).isForegroundStopped)
+ assertTrue(shadowOf(controller.get()).isStoppedBySelf)
+ assertNull(ChatRunService.running.value)
+ }
+
+ @Test
+ fun `a run that ended before the service came up still goes foreground, then stops`() {
+ ChatRunService.start(application, chat)
+ ChatRunService.stop()
+
+ val controller = Robolectric.buildService(ChatRunService::class.java).create().startCommand(0, 1)
+ ShadowLooper.idleMainLooper()
+
+ // startForeground is owed to Android even so, or the app crashes.
+ assertEquals(ChatRunService.NOTIFICATION_ID, shadowOf(controller.get()).lastForegroundNotificationId)
+ assertTrue(shadowOf(controller.get()).isStoppedBySelf)
+ }
+
+ @Test
+ fun `a new run while the service is up keeps it running`() {
+ val controller = startedService()
+
+ ChatRunService.start(application, RunningChat("session-2", "Second"))
+ ShadowLooper.idleMainLooper()
+
+ assertFalse(shadowOf(controller.get()).isStoppedBySelf)
+ assertEquals(
+ "Gotcha is working on “Second”…",
+ controller.notification().extras.getString(NotificationCompat.EXTRA_TITLE)
+ )
+ }
+
+ @Test
+ fun `Stop on the notification asks for the run to be stopped`() = runBlocking {
+ val controller = startedService()
+ val stopAction = controller.notification().actions.single()
+ assertEquals("Stop", stopAction.title)
+ val request = async(start = CoroutineStart.UNDISPATCHED) { ChatRunService.stopRequests.first() }
+
+ controller.withIntent(shadowOf(stopAction.actionIntent).savedIntent).startCommand(0, 2)
+
+ request.await()
+ assertEquals(ChatRunService.ACTION_STOP_RUN, shadowOf(stopAction.actionIntent).savedIntent.action)
+ }
+}