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): say so when Android closed Gotcha in the middle of a task (#105)

Durganshuc8252e0a1b31
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 4352d83..917e1d0 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -274,6 +274,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
private val completionNotifier = ChatCompletionNotifier(application)
private val attentionNotifier = AttentionNotifier(application)
private val localNotificationStore = LocalNotificationStore(application)
+ private val runMarker = RunInProgressMarker(settingsRepository.prefs)
private var settings: Settings = Settings()
private var client: LLMClient? = null
@@ -449,6 +450,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
updateContextUsage()
migrateChatDirsIfNeeded()
com.gotcha.data.SampleChatSeeder.seedIfNeeded(historyRepository, settingsRepository.prefs)
+ reportInterruptedRun()
refreshSessions()
}
// Stop on the ongoing "Gotcha is working…" notification (issue #105).
@@ -837,6 +839,8 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
// 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))
+ // Survives the process: if Android kills it mid-run, the next start says so.
+ withContext(Dispatchers.IO) { runMarker.mark(runningId) }
runHadError = false
var stopped = false
try {
@@ -869,6 +873,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
// After the finished notification is up, so in the background the
// ongoing one is replaced by it rather than leaving a gap.
ChatRunService.stop()
+ withContext(Dispatchers.IO) { runMarker.clear() }
_uiState.update {
it.copy(
isBusy = false,
@@ -890,6 +895,39 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
settings.notificationsMentionChats &&
!localNotificationStore.isChatSensitive(sessionId, agentEngine.sessionPersonaId)
+ /**
+ * Issue #105: the last run died with the process, most likely killed by
+ * Android while Gotcha was in the background. Its chat gets a notice at the
+ * end, its history is repaired so the chat can go on, and the inbox gets an
+ * entry that opens it. Gotcha still starts on a fresh chat, as always.
+ */
+ private suspend fun reportInterruptedRun() {
+ val sessionId = runMarker.interruptedSession() ?: return
+ historyRepository.loadSession(sessionId)?.let { session ->
+ // A legacy chat without a saved transcript is rebuilt from its history on
+ // open; a lone notice would replace all of it.
+ val shown = if (session.displayMessages.isEmpty()) {
+ session.displayMessages
+ } else {
+ val nextId = session.displayMessages.maxOf { it.id } + 1
+ session.displayMessages + UiMessage(nextId, MessageKind.ERROR, INTERRUPTED_NOTICE)
+ }
+ historyRepository.saveSession(
+ session.copy(messages = closeOrphanedToolCalls(session.messages), displayMessages = shown),
+ touch = false
+ )
+ val named = settings.notificationsMentionChats &&
+ !localNotificationStore.isChatSensitive(sessionId, session.personaId)
+ localNotificationStore.addEntry(
+ category = NotificationCategory.TASK_FINISHED,
+ title = if (named) "Interrupted: ${session.title}" else "Task interrupted",
+ body = INTERRUPTED_INBOX_BODY,
+ target = NotificationTarget.Chat(sessionId)
+ )
+ }
+ withContext(Dispatchers.IO) { runMarker.clear() }
+ }
+
/**
* The run in [sessionId] as its ongoing notification shows it: the chat's
* title once one is generated, until then the start of the first message,
@@ -2124,6 +2162,12 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
const val KEY_NOTIFICATION_PERMISSION_ASKED = "chat_notification_permission_asked"
const val MIGRATED_CHAT_DIRS_KEY = "migrated_chat_dirs_v1"
+
+ /** Ends the chat of a run that died with the process; see [reportInterruptedRun]. */
+ const val INTERRUPTED_NOTICE = "This task was interrupted: Android closed Gotcha while it was " +
+ "working, usually to free memory. Send a message to pick up where it left off."
+ const val INTERRUPTED_INBOX_BODY = "Android closed Gotcha while it was working on this task. " +
+ "Tap to open the chat and pick up where it left off."
}
}
diff --git a/app/src/main/java/com/gotcha/agent/RunInProgressMarker.kt b/app/src/main/java/com/gotcha/agent/RunInProgressMarker.kt
new file mode 100644
index 0000000..9f7182d
--- /dev/null
+++ b/app/src/main/java/com/gotcha/agent/RunInProgressMarker.kt
@@ -0,0 +1,62 @@
+package com.gotcha.agent
+
+import android.content.SharedPreferences
+import android.os.Process
+import com.gotcha.llm.ChatMessage
+import kotlinx.serialization.json.JsonPrimitive
+
+/**
+ * Notes on disk which chat has a run in progress, so a run that died with the
+ * process is noticed on the next start instead of leaving a half-finished chat
+ * with no explanation (issue #105). Written synchronously, because the process
+ * can die right after.
+ *
+ * Tagged with the process that wrote it: a run whose ViewModel was cleared while
+ * the process lives on is ended, and its marker cleared, by the run's own
+ * cleanup, so only a marker left by another process means one was killed.
+ */
+class RunInProgressMarker(
+ private val prefs: SharedPreferences,
+ private val processToken: () -> String = { "${Process.myPid()}:${Process.getStartElapsedRealtime()}" }
+) {
+
+ fun mark(sessionId: String) {
+ prefs.edit().putString(KEY_SESSION, sessionId).putString(KEY_PROCESS, processToken()).commit()
+ }
+
+ fun clear() {
+ prefs.edit().remove(KEY_SESSION).remove(KEY_PROCESS).commit()
+ }
+
+ /** The chat whose run an earlier process was killed in, or null. */
+ fun interruptedSession(): String? {
+ val sessionId = prefs.getString(KEY_SESSION, null) ?: return null
+ return sessionId.takeIf { prefs.getString(KEY_PROCESS, null) != processToken() }
+ }
+
+ companion object {
+ private const val KEY_SESSION = "run_in_progress_session"
+ private const val KEY_PROCESS = "run_in_progress_process"
+ }
+}
+
+/**
+ * [history] with a result for every tool call of its last assistant turn. A run
+ * killed mid-round can leave calls without results, which the provider rejects
+ * on every later request of the chat.
+ */
+internal fun closeOrphanedToolCalls(history: List<ChatMessage>): List<ChatMessage> {
+ val lastUser = history.indexOfLast { it.role == "user" }
+ val assistantIdx = history.indexOfLast { it.role == "assistant" && !it.toolCalls.isNullOrEmpty() }
+ if (assistantIdx < 0 || assistantIdx < lastUser) return history
+ val answered = history.drop(assistantIdx + 1).filter { it.role == "tool" }.mapNotNull { it.toolCallId }.toSet()
+ val missing = history[assistantIdx].toolCalls.orEmpty().filter { it.id !in answered }
+ if (missing.isEmpty()) return history
+ return history + missing.map {
+ ChatMessage(
+ role = "tool",
+ content = JsonPrimitive("Cancelled: Gotcha was closed by Android before this tool completed."),
+ toolCallId = it.id
+ )
+ }
+}
diff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelInterruptedRunTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelInterruptedRunTest.kt
new file mode 100644
index 0000000..f676437
--- /dev/null
+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelInterruptedRunTest.kt
@@ -0,0 +1,135 @@
+package com.gotcha.agent
+
+import android.app.Application
+import androidx.test.core.app.ApplicationProvider
+import com.gotcha.data.ChatHistoryRepository
+import com.gotcha.data.ChatSession
+import com.gotcha.data.LlmProvider
+import com.gotcha.data.Settings
+import com.gotcha.data.SettingsRepository
+import com.gotcha.llm.ChatMessage
+import com.gotcha.llm.FunctionCall
+import com.gotcha.llm.ToolCall
+import com.gotcha.notifications.LocalNotificationStore
+import com.gotcha.notifications.NotificationTarget
+import com.gotcha.testsupport.FakeAndroidKeyStore
+import kotlinx.coroutines.runBlocking
+import kotlinx.serialization.json.JsonPrimitive
+import org.junit.After
+import org.junit.Assert.assertEquals
+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.RobolectricTestRunner
+import org.robolectric.annotation.Config
+import org.robolectric.shadows.ShadowLooper
+
+/** The next start after a run died with the process (issue #105). */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34])
+class ChatViewModelInterruptedRunTest {
+
+ private val application: Application = ApplicationProvider.getApplicationContext()
+ private lateinit var settingsRepository: SettingsRepository
+ private lateinit var historyRepository: ChatHistoryRepository
+ private lateinit var inbox: LocalNotificationStore
+ private val sessionId = "interrupted-session"
+
+ @Before
+ fun setUp() {
+ FakeAndroidKeyStore.setUp()
+ settingsRepository = SettingsRepository(application)
+ historyRepository = ChatHistoryRepository(application)
+ inbox = LocalNotificationStore(application)
+ inbox.clearHistory()
+ settingsRepository.save(
+ Settings(provider = LlmProvider.OPENAI_COMPATIBLE, apiKey = "test-key", baseUrl = "http://127.0.0.1:1/v1")
+ )
+ }
+
+ @After
+ fun tearDown() {
+ runBlocking { historyRepository.deleteSession(sessionId) }
+ }
+
+ /** A chat saved mid-round: the model asked for a tool whose result never came. */
+ private fun saveHalfFinishedChat() = runBlocking {
+ historyRepository.saveSession(
+ ChatSession(
+ id = sessionId,
+ title = "Big files",
+ lastModified = 1L,
+ messages = listOf(
+ ChatMessage(role = "user", content = JsonPrimitive("Find big files")),
+ ChatMessage(
+ role = "assistant",
+ toolCalls = listOf(ToolCall(id = "call-1", function = FunctionCall("list_files", "{}")))
+ )
+ ),
+ displayMessages = listOf(UiMessage(1, MessageKind.USER, "Find big files"))
+ )
+ )
+ }
+
+ private fun startGotcha(): ChatViewModel {
+ val viewModel = ChatViewModel(application)
+ val deadline = System.currentTimeMillis() + 5_000
+ while (System.currentTimeMillis() < deadline && viewModel.sessions.value.isEmpty()) {
+ ShadowLooper.idleMainLooper()
+ Thread.sleep(10)
+ }
+ ShadowLooper.idleMainLooper()
+ return viewModel
+ }
+
+ private fun anotherProcess() = RunInProgressMarker(settingsRepository.prefs) { "killed-process" }
+
+ @Test
+ fun `a run killed with the process is reported in its chat and the inbox`() {
+ saveHalfFinishedChat()
+ anotherProcess().mark(sessionId)
+
+ startGotcha()
+
+ val session = runBlocking { historyRepository.loadSession(sessionId) }!!
+ assertEquals(MessageKind.ERROR, session.displayMessages.last().kind)
+ assertTrue(session.displayMessages.last().text.startsWith("This task was interrupted"))
+ assertEquals("call-1", session.messages.last().toolCallId)
+ val entry = inbox.entries().single()
+ assertEquals("Interrupted: Big files", entry.title)
+ assertEquals(NotificationTarget.Chat(sessionId), entry.target)
+ assertNull(anotherProcess().interruptedSession())
+ }
+
+ @Test
+ fun `it is reported once`() {
+ saveHalfFinishedChat()
+ anotherProcess().mark(sessionId)
+ startGotcha()
+
+ startGotcha()
+
+ assertEquals(1, inbox.entries().size)
+ val notices = runBlocking { historyRepository.loadSession(sessionId) }!!
+ .displayMessages.count { it.kind == MessageKind.ERROR }
+ assertEquals(1, notices)
+ }
+
+ @Test
+ fun `a run that ends normally leaves no marker`() {
+ val viewModel = startGotcha()
+ viewModel.sendMessage("Hello")
+ val deadline = System.currentTimeMillis() + 5_000
+ ShadowLooper.idleMainLooper()
+ while (System.currentTimeMillis() < deadline && viewModel.uiState.value.isBusy) {
+ ShadowLooper.idleMainLooper()
+ Thread.sleep(10)
+ }
+ ShadowLooper.idleMainLooper()
+
+ assertNull(anotherProcess().interruptedSession())
+ assertTrue(inbox.entries().isEmpty())
+ }
+}
diff --git a/app/src/test/java/com/gotcha/agent/RunInProgressMarkerTest.kt b/app/src/test/java/com/gotcha/agent/RunInProgressMarkerTest.kt
new file mode 100644
index 0000000..07805da
--- /dev/null
+++ b/app/src/test/java/com/gotcha/agent/RunInProgressMarkerTest.kt
@@ -0,0 +1,89 @@
+package com.gotcha.agent
+
+import android.app.Application
+import android.content.Context
+import androidx.test.core.app.ApplicationProvider
+import com.gotcha.llm.ChatMessage
+import com.gotcha.llm.FunctionCall
+import com.gotcha.llm.ToolCall
+import kotlinx.serialization.json.JsonPrimitive
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertSame
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+
+/** Noticing a run that died with the process (issue #105). */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34])
+class RunInProgressMarkerTest {
+
+ private val prefs = ApplicationProvider.getApplicationContext<Application>()
+ .getSharedPreferences("marker-test", Context.MODE_PRIVATE)
+
+ private fun marker(process: String) = RunInProgressMarker(prefs) { process }
+
+ @Test
+ fun `a marker left by another process is an interrupted run`() {
+ marker("dead").mark("chat-1")
+
+ assertEquals("chat-1", marker("new").interruptedSession())
+ }
+
+ @Test
+ fun `a marker of this process is not`() {
+ marker("same").mark("chat-1")
+
+ assertNull(marker("same").interruptedSession())
+ }
+
+ @Test
+ fun `a cleared marker is nothing`() {
+ marker("dead").mark("chat-1")
+ marker("dead").clear()
+
+ assertNull(marker("new").interruptedSession())
+ }
+
+ private fun call(id: String) = ToolCall(id = id, function = FunctionCall("list_files", "{}"))
+ private fun user(text: String) = ChatMessage(role = "user", content = JsonPrimitive(text))
+ private fun result(id: String) = ChatMessage(role = "tool", content = JsonPrimitive("ok"), toolCallId = id)
+
+ @Test
+ fun `tool calls left without results get one each`() {
+ val history = listOf(
+ user("Find big files"),
+ ChatMessage(role = "assistant", toolCalls = listOf(call("a"), call("b"))),
+ result("a")
+ )
+
+ val closed = closeOrphanedToolCalls(history)
+
+ assertEquals(4, closed.size)
+ assertEquals("b", closed.last().toolCallId)
+ assertEquals("tool", closed.last().role)
+ }
+
+ @Test
+ fun `a complete history is left alone`() {
+ val history = listOf(
+ user("Find big files"),
+ ChatMessage(role = "assistant", toolCalls = listOf(call("a"))),
+ result("a")
+ )
+
+ assertSame(history, closeOrphanedToolCalls(history))
+ }
+
+ @Test
+ fun `tool calls before the last user message are not this run's`() {
+ val history = listOf(
+ ChatMessage(role = "assistant", toolCalls = listOf(call("a"))),
+ user("Something else")
+ )
+
+ assertSame(history, closeOrphanedToolCalls(history))
+ }
+}