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.
fix(chat): address review findings on background runs
Durganshu444a3bbf285f
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex e86b8a9..b959818 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -1113,7 +1113,7 @@ class MainActivity : ComponentActivity() {state.runningSessionId?.let { chatViewModel.openSession(it) }},onCreateShareCard = {- sharePoster.open(chatViewModel.activeSessionRunSummaries())+ lifecycleScope.launch { sharePoster.open(chatViewModel.activeSessionRunSummaries()) }},onEditMessage = { id, text, attachments ->chatViewModel.editMessage(id, text, attachments)diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex 69e33f2..4004fb8 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -296,6 +296,16 @@ class AgentEngine(private var lastModelRequestFailed = false/** Falls back to [ChatTitle.fallback] until [generatedTitle] is set. */+ /** Chats deleted while this engine could still save them; see [discardSession]. */+ private val discardedSessionIds = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()++ /** Chat [id] is being deleted: [saveCurrentSession] leaves it alone from now on. */+ fun discardSession(id: String) {+ discardedSessionIds += id+ }++ fun isDiscarded(id: String): Boolean = id in discardedSessionIds+fun currentTitle(): String = generatedTitle ?: ChatTitle.fallback(history)/**@@ -367,6 +377,8 @@ class AgentEngine(*/suspend fun saveCurrentSession(generateTitle: Boolean = true) {val id = sessionId ?: return+ // A deleted chat is never written again, or a run's late save brings it back.+ if (id in discardedSessionIds) returnif (generateTitle) clientProvider()?.let { generateTitleIfNeeded(it) }val title = currentTitle()historyRepository.saveSession(diff --git a/app/src/main/java/com/gotcha/agent/ChatRunner.kt b/app/src/main/java/com/gotcha/agent/ChatRunner.ktindex 7918dc9..f1cfac0 100644--- a/app/src/main/java/com/gotcha/agent/ChatRunner.kt+++ b/app/src/main/java/com/gotcha/agent/ChatRunner.kt@@ -541,6 +541,20 @@ class ChatRunner(private val app: Application) : AgentEvents {agentJob?.cancel()}+ /**+ * Chat [sessionId] is being deleted. If it is the engine's chat, a run in it+ * is stopped and waited for, and nothing of it is saved or notified after,+ * so the run can't bring the deleted chat back or keep working in it.+ */+ internal suspend fun discard(sessionId: String) {+ if (engine.sessionId != sessionId && _state.value.runningSessionId != sessionId) return+ engine.discardSession(sessionId)+ agentJob?.let {+ it.cancel()+ it.join()+ }+ }+/** Busy-marking + agent run + NonCancellable cleanup. */private suspend fun executeRun(agent: AgentMode, runningId: String) {val runningTitle = _state.value.transcript.firstOrNull { it.kind == MessageKind.USER }@@ -586,14 +600,19 @@ class ChatRunner(private val app: Application) : AgentEvents {// own sanitize still gets repaired here before persisting.engine.sanitizeLastOrphanedAssistant()engine.saveCurrentSession()- val finished = runFinishedNotification(- sessionId = runningId,- outcome = when {- stopped -> RunOutcome.STOPPED- runEndedOnError -> RunOutcome.FAILED- else -> RunOutcome.DONE- }- )+ // A chat deleted mid-run gets no notification or inbox entry.+ val finished = if (engine.isDiscarded(runningId)) {+ null+ } else {+ runFinishedNotification(+ sessionId = runningId,+ outcome = when {+ stopped -> RunOutcome.STOPPED+ runEndedOnError -> RunOutcome.FAILED+ else -> RunOutcome.DONE+ }+ )+ }// In the background the ongoing notification turns into the// finished one, in the same slot (issue #115).if (finished != null) {@@ -884,19 +903,11 @@ class ChatRunner(private val app: Application) : AgentEvents {val gate = CompletableDeferred<Boolean>()foregroundControlGate = gatesetState { it.copy(activity = null, pendingForegroundControl = request) }- if (!appInForeground && confirmationOverlay.canShow()) {- confirmationOverlay.show(- summary = request.promptText(),- onAllow = { gate.complete(true) },- onDeny = { gate.complete(false) },- title = request.title,- allowLabel = ForegroundControlRequest.ALLOW_LABEL,- denyLabel = ForegroundControlRequest.DENY_LABEL- )- }+ if (!appInForeground) notifyNeedsInput()return try {withTimeoutOrNull(GATE_TIMEOUT_MS) { gate.await() } ?: false} finally {+ attentionNotifier.cancel()confirmationOverlay.dismiss()setState { it.copy(pendingForegroundControl = null) }foregroundControlGate = null@@ -927,14 +938,30 @@ class ChatRunner(private val app: Application) : AgentEvents {/*** Tells the user, out of the app, that the run is paused on a question or- * confirmation they can't see (issue #108). The foreground-control ask- * needs none: it is drawn over whatever app is in front.+ * confirmation they can't see (issue #108). The foreground-control ask is+ * drawn over whatever app is in front instead; without "Display over other+ * apps" it gets the notification too, or the run would sit out the gate's+ * timeout with nothing on screen.*/private fun notifyNeedsInput() {val state = _state.value+ val foregroundControl = state.pendingForegroundControl+ val gate = foregroundControlGate+ if (foregroundControl != null && gate != null && confirmationOverlay.canShow()) {+ confirmationOverlay.show(+ summary = foregroundControl.promptText(),+ onAllow = { gate.complete(true) },+ onDeny = { gate.complete(false) },+ title = foregroundControl.title,+ allowLabel = ForegroundControlRequest.ALLOW_LABEL,+ denyLabel = ForegroundControlRequest.DENY_LABEL+ )+ return+ }val kind = when {state.pendingQuestion != null -> AttentionKind.QUESTIONstate.pendingConfirmation != null -> AttentionKind.CONFIRMATION+ foregroundControl != null -> AttentionKind.CONFIRMATIONelse -> return}val sessionId = state.runningSessionId ?: engine.sessionId ?: returndiff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex d26c227..0c9e708 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -1071,13 +1071,20 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Cfun deleteSession(id: String) {viewModelScope.launch {+ // First, so a run in this chat is over before its files and record go.+ val wasBound = runner.engine.sessionId == id+ runner.discard(id)withContext(Dispatchers.IO) {com.gotcha.data.GotchaStorage.archiveChatDir(id)}historyRepository.deleteSession(id)localNotificationStore.forgetChat(id)- if (runner.engine.sessionId == id) {+ if (_uiState.value.activeSessionId == id) {clearChat()+ } else if (wasBound) {+ // Viewing another chat: the engine lets go of the deleted one+ // without moving the screen.+ runner.bindFresh(java.util.UUID.randomUUID().toString(), AgentMode.MONITOR)}// Drop any live overlay entry for the deleted session so the// drawer doesn't keep showing a token count for a chat that no@@ -1192,12 +1199,52 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), C}fun exportChat() {- val markdown = ChatMarkdown.export(- history = runner.engine.history.toList(),- sessionId = runner.engine.sessionId ?: "unknown",- title = runner.engine.currentTitle()+ viewModelScope.launch {+ val markdown = viewedSessionSnapshot()?.let { chat ->+ ChatMarkdown.export(history = chat.history, sessionId = chat.id, title = chat.title)+ } ?: return@launch+ _exportContent.tryEmit(markdown)+ }+ }++ /** What [exportChat] and the share card read: the chat on screen, as saved or live. */+ private class ViewedSessionSnapshot(+ val id: String,+ val title: String,+ val history: List<ChatMessage>,+ val runSummaries: List<RunSummary>,+ val agentName: String+ )++ /**+ * The chat on screen, which is not always the one bound to the engine: while+ * a run goes on, and after it until the next send, other chats are opened+ * view-only. Reading the engine then would export or share the running chat+ * instead of the one the user is looking at.+ */+ private suspend fun viewedSessionSnapshot(): ViewedSessionSnapshot? {+ val id = _uiState.value.activeSessionId ?: return null+ if (id == runner.engine.sessionId) {+ // Snapshot the history before iterating: the engine coroutine mutates+ // it as it runs, and this is read from the UI thread.+ return ViewedSessionSnapshot(+ id = id,+ title = runner.engine.currentTitle(),+ history = runner.engine.history.toList(),+ runSummaries = runner.engine.runSummaries.toList(),+ agentName = runner.engineAgent.name+ )+ }+ // A chat opened view-only is on disk; one that isn't is a new, empty one.+ val session = historyRepository.loadSession(id)+ ?: return ViewedSessionSnapshot(id, "New Chat", emptyList(), emptyList(), _uiState.value.activeAgent.name)+ return ViewedSessionSnapshot(+ id = session.id,+ title = session.title,+ history = session.messages,+ runSummaries = session.runSummaries,+ agentName = session.agentMode ?: _uiState.value.activeAgent.name)- _exportContent.tryEmit(markdown)}// ---- Chat backup and import (issue #83) ----@@ -1356,7 +1403,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), C}/**- * Run summaries for the session currently bound to the engine.+ * Run summaries for the chat on screen (see [viewedSessionSnapshot]).** Returns the recorded summaries when present. Chats created before the* run-summary feature landed have none persisted, so fall back to@@ -1367,13 +1414,10 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), C* recomposition, and the synthesis walk only trims text content — cheaper* than fingerprinting the history (which would hash vision base64 payloads).*/- fun activeSessionRunSummaries(): List<RunSummary> {- val recorded = runner.engine.runSummaries- if (recorded.isNotEmpty()) return recorded.toList()- // Snapshot the history before iterating: the engine coroutine mutates it- // as it runs, and this is read from the UI thread.- val snapshot = runner.engine.history.toList()- return synthesizeRunSummariesFromHistory(snapshot, settings.model, runner.engineAgent.name)+ suspend fun activeSessionRunSummaries(): List<RunSummary> {+ val chat = viewedSessionSnapshot() ?: return emptyList()+ if (chat.runSummaries.isNotEmpty()) return chat.runSummaries+ return synthesizeRunSummariesFromHistory(chat.history, settings.model, chat.agentName)}private companion object {diff --git a/app/src/main/java/com/gotcha/service/ChatRunService.kt b/app/src/main/java/com/gotcha/service/ChatRunService.ktindex 89af93b..e41dd72 100644--- a/app/src/main/java/com/gotcha/service/ChatRunService.kt+++ b/app/src/main/java/com/gotcha/service/ChatRunService.kt@@ -72,9 +72,11 @@ class ChatRunService : Service() {follower = serviceScope.launch {_running.collect { chat ->if (chat == null) {- leaveForeground()- // Only if no newer start arrived meanwhile.- stopSelf(lastStartId)+ val startId = lastStartId+ // Stopped only once the finished notification is up: the+ // service keeps the process from being reclaimed until then.+ // stopSelf(startId) does nothing if a newer start arrived meanwhile.+ leaveForeground { stopSelf(startId) }} else {goForeground(chat)}@@ -115,18 +117,20 @@ class ChatRunService : Service() {* 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.+ * keeps no foreground-service flags. [then] runs once that is done, which+ * for a completion can be up to two seconds later.*/- private fun leaveForeground() {+ private fun leaveForeground(then: () -> Unit = {}) {val id = foregroundIdval pending = completionforegroundId = nullcompletion = nullif (id != null && pending != null) {stopForeground(STOP_FOREGROUND_DETACH)- postWhenDetached(applicationContext, id, pending, DETACH_POLLS)+ postWhenDetached(applicationContext, id, pending, DETACH_POLLS, then)} else {stopForeground(STOP_FOREGROUND_REMOVE)+ then()}}@@ -190,23 +194,33 @@ class ChatRunService : Service() {* 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.+ * new run has taken the slot meanwhile. [then] runs after, either way.*/@Suppress("MissingPermission") // ChatCompletionNotifier.build checked it.- private fun postWhenDetached(context: Context, id: Int, notification: Notification, pollsLeft: Int) {- if (foregroundId == id) return+ private fun postWhenDetached(+ context: Context,+ id: Int,+ notification: Notification,+ pollsLeft: Int,+ then: () -> Unit+ ) {+ if (foregroundId == id) {+ then()+ 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) },+ { postWhenDetached(context, id, notification, pollsLeft - 1, then) },DETACH_POLL_MS)return}NotificationManagerCompat.from(context).notify(id, notification)+ then()}/** The run has ended: the service removes its notification and stops. */diff --git a/app/src/test/java/com/gotcha/agent/ChatRunnerLifecycleTest.kt b/app/src/test/java/com/gotcha/agent/ChatRunnerLifecycleTest.ktindex 0edea72..8664df2 100644--- a/app/src/test/java/com/gotcha/agent/ChatRunnerLifecycleTest.kt+++ b/app/src/test/java/com/gotcha/agent/ChatRunnerLifecycleTest.kt@@ -11,6 +11,9 @@ import androidx.test.core.app.ApplicationProviderimport com.gotcha.GotchaAppimport com.gotcha.data.ChatHistoryRepositoryimport com.gotcha.data.ChatSession+import com.gotcha.data.RunSummary+import com.gotcha.llm.ChatMessage+import com.gotcha.notifications.AttentionNotifierimport com.gotcha.data.LlmProviderimport com.gotcha.data.Settingsimport com.gotcha.data.SettingsRepository@@ -20,7 +23,9 @@ import com.gotcha.testsupport.FakeAndroidKeyStoreimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.async+import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.JsonPrimitiveimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertNotEquals@@ -155,11 +160,12 @@ class ChatRunnerLifecycleTest {assertTrue(state.messages.isEmpty())}- @Test- fun `stop on the ongoing notification works with no screen`() {- // A server that takes the run's request and never answers, so the run is- // still waiting on the model when Stop arrives. Later requests (the chat- // title, made as the stopped run saves) are dropped.+ /**+ * Runs [block] against a model that takes the run's request and never+ * answers, so the run is still waiting on it. Later requests (the chat+ * title, made as a stopped run saves) are dropped.+ */+ private fun withSilentModel(block: (requestHeld: CountDownLatch) -> Unit) {val requestHeld = CountDownLatch(1)ServerSocket(0).use { silent ->thread(isDaemon = true) {@@ -175,27 +181,122 @@ class ChatRunnerLifecycleTest {baseUrl = "http://127.0.0.1:${silent.localPort}/v1"))- val screen = Screen(application)- screen.viewModel.sendMessage("Hello")- val sessionId = screen.viewModel.uiState.value.runningSessionId!!- screen.finish()+ block(requestHeld)+ }+ }++ /** The run saves the chat before it asks the model; waits for that ask. */+ private fun awaitModelRequest(requestHeld: CountDownLatch) {+ val deadline = System.currentTimeMillis() + 5_000+ while (System.currentTimeMillis() < deadline && !requestHeld.await(10, TimeUnit.MILLISECONDS)) {ShadowLooper.idleMainLooper()- assertTrue(runner().isRunning)- // The run saves the chat before it asks the model; Stop is meant for- // the wait on the model, not that moment.- val deadline = System.currentTimeMillis() + 5_000- while (System.currentTimeMillis() < deadline && !requestHeld.await(10, TimeUnit.MILLISECONDS)) {- ShadowLooper.idleMainLooper()- }+ }+ }++ /** Lets the ViewModel's coroutines (opening a chat, deleting one) run to the end. */+ private fun settle() {+ repeat(20) {+ ShadowLooper.idleMainLooper()+ Thread.sleep(10)+ }+ }++ @Test+ fun `stop on the ongoing notification works with no screen`() = withSilentModel { requestHeld ->+ val screen = Screen(application)+ screen.viewModel.sendMessage("Hello")+ val sessionId = screen.viewModel.uiState.value.runningSessionId!!+ screen.finish()+ ShadowLooper.idleMainLooper()+ assertTrue(runner().isRunning)+ // Stop is meant for the wait on the model, not the save before it.+ awaitModelRequest(requestHeld)++ Robolectric.buildService(ChatRunService::class.java, Intent().setAction(ChatRunService.ACTION_STOP_RUN))+ .create()+ .startCommand(0, 1)+ waitForRunToFinish()++ assertFalse(runner().isRunning)+ assertEquals("Agent was interrupted by the user.", savedTranscript(sessionId).last().text)+ }++ @Test+ fun `deleting the running chat stops the run and the chat stays deleted`() = withSilentModel { requestHeld ->+ val viewModel = Screen(application).viewModel+ viewModel.setForeground(true)+ viewModel.sendMessage("Hello")+ val sessionId = viewModel.uiState.value.runningSessionId!!+ awaitModelRequest(requestHeld)- Robolectric.buildService(ChatRunService::class.java, Intent().setAction(ChatRunService.ACTION_STOP_RUN))- .create()- .startCommand(0, 1)- waitForRunToFinish()+ viewModel.deleteSession(sessionId)+ waitForRunToFinish()+ settle()++ assertFalse(runner().isRunning)+ val saved = runBlocking { historyRepository.loadSession(sessionId) }+ assertNull("the run's last save brought the chat back", saved)+ assertNotEquals(sessionId, viewModel.uiState.value.activeSessionId)+ assertTrue(shadowOf(manager).allNotifications.isEmpty())+ }- assertFalse(runner().isRunning)- assertEquals("Agent was interrupted by the user.", savedTranscript(sessionId).last().text)+ @Test+ fun `export and the share card read the chat on screen, not the running one`() = withSilentModel { requestHeld ->+ val summary = RunSummary(+ startedAt = 1L,+ endedAt = 2L,+ userPrompt = "Viewed request",+ finalReply = "Viewed reply",+ model = "m",+ agentMode = "MONITOR",+ delegated = false,+ succeeded = true+ )+ runBlocking {+ historyRepository.saveSession(+ ChatSession(+ id = "viewed",+ title = "Viewed chat",+ lastModified = 0L,+ messages = listOf(ChatMessage(role = "user", content = JsonPrimitive("Viewed request"))),+ runSummaries = listOf(summary)+ )+ )}+ val viewModel = Screen(application).viewModel+ viewModel.sendMessage("Running request")+ awaitModelRequest(requestHeld)+ viewModel.openSession("viewed")+ settle()+ assertEquals("viewed", viewModel.uiState.value.activeSessionId)++ val exported = CoroutineScope(Dispatchers.Unconfined).async { viewModel.exportContent.first() }+ viewModel.exportChat()+ settle()+ val markdown = runBlocking { exported.await() }++ assertTrue(markdown, markdown.contains("Viewed request"))+ assertFalse(markdown, markdown.contains("Running request"))+ assertEquals(listOf(summary), runBlocking { viewModel.activeSessionRunSummaries() })+ viewModel.stopAgent()+ waitForRunToFinish()+ }++ @Test+ fun `a control ask out of the app without the overlay says so in a notification`() {+ val screen = Screen(application)+ screen.viewModel.setForeground(true)+ screen.viewModel.setForeground(false)+ val gate = CoroutineScope(Dispatchers.Unconfined).async {+ runner().awaitForegroundControl(ForegroundControlRequest("open_app", "Settings", "Turn on Wi-Fi"))+ }++ val attention = shadowOf(manager).allNotifications.single()+ assertEquals(AttentionNotifier.CHANNEL_ID, attention.channelId)++ runner().answerForegroundControl(false)+ assertFalse(runBlocking { gate.await() })+ assertTrue(shadowOf(manager).allNotifications.isEmpty())}@Testdiff --git a/app/src/test/java/com/gotcha/service/ChatRunServiceTest.kt b/app/src/test/java/com/gotcha/service/ChatRunServiceTest.ktindex d507bc4..d397101 100644--- a/app/src/test/java/com/gotcha/service/ChatRunServiceTest.kt+++ b/app/src/test/java/com/gotcha/service/ChatRunServiceTest.kt@@ -192,6 +192,8 @@ class ChatRunServiceTest {assertTrue(shadowOf(controller.get()).isForegroundStopped)assertFalse(shadowOf(controller.get()).notificationShouldRemoved)assertEquals(controller.notification(), posted(slot))+ // Still started until the finished notification is up, so the process lives to post it.+ assertFalse(shadowOf(controller.get()).isStoppedBySelf)androidDetaches(slot)ShadowLooper.idleMainLooper(100, TimeUnit.MILLISECONDS)assertEquals("Done: Plan my trip", posted(slot)?.extras?.getString(NotificationCompat.EXTRA_TITLE))