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.

fix: a double send can't start two runs; the reminder check keeps only chat digests in memory

Durganshu0f87e35b7548
diff --git a/app/src/main/java/com/gotcha/agent/ChatRunner.kt b/app/src/main/java/com/gotcha/agent/ChatRunner.kt
index 38de0df..5b70e40 100644
--- a/app/src/main/java/com/gotcha/agent/ChatRunner.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatRunner.kt
@@ -417,6 +417,11 @@ class ChatRunner(private val app: Application) : AgentEvents {
/** Sends [text] with [attachments] in [view] and runs the agent on it. */
internal fun send(view: ViewedChat, text: String, attachments: List<ComposerAttachment>, isVoice: Boolean) {
+ // The caller checked isRunning, but a run only shows as busy once
+ // executeRun starts, after the viewed chat is loaded from disk. Until then
+ // the job itself is the claim, so a second send (a double tap) is refused
+ // rather than appended to the same history and run alongside it.
+ if (isRunning || agentJob?.isActive == true) return
currentRunIsVoice = isVoice
agentJob = scope.launch {
// Ensure the engine is bound to the session being viewed. After a
diff --git a/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt
index c7b4b37..c28f61a 100644
--- a/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt
+++ b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt
@@ -80,6 +80,28 @@ class ChatHistoryRepository internal constructor(private val chatsDir: File) {
?: emptyList()
}
+ /**
+ * [transform] of every saved session, newest first, decoding one file at a
+ * time and keeping only what [transform] returns. For a caller that needs a
+ * few fields of every chat, such as the background reminder check, without
+ * holding every transcript (images included) in memory at once.
+ */
+ suspend fun <T> mapSessions(transform: (ChatSession) -> T): List<T> = withContext(Dispatchers.IO) {
+ chatsDir.listFiles()
+ ?.filter { it.extension == "json" }
+ ?.mapNotNull { file ->
+ try {
+ val session = json.decodeFromString(serializer, file.readText())
+ session.lastModified to transform(session)
+ } catch (_: Exception) {
+ null
+ }
+ }
+ ?.sortedByDescending { it.first }
+ ?.map { it.second }
+ ?: emptyList()
+ }
+
suspend fun loadSession(id: String): ChatSession? = withContext(Dispatchers.IO) {
val file = File(chatsDir, "$id.json")
if (!file.exists()) return@withContext null
diff --git a/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.kt b/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.kt
index 10cc76c..47f41cc 100644
--- a/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.kt
+++ b/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.kt
@@ -144,16 +144,21 @@ internal suspend fun runLocalNotificationCheck(
val store = LocalNotificationStore(context)
val zone = ZoneId.systemDefault()
- // Seeded samples are demos, not the user's own use.
- val sessions = ChatHistoryRepository(context).listSessions().filterNot { it.isSample }
- val chats = sessions.map { session ->
- ChatDigest(
- id = session.id,
- title = session.title,
- sensitive = store.isChatSensitive(session.id, session.personaId),
- runs = session.runSummaries
- )
- }
+ // Seeded samples are demos, not the user's own use. Only the digest of each
+ // chat is kept, so a phone full of image-heavy chats isn't read into memory
+ // all at once by a receiver running in the background.
+ val chats = ChatHistoryRepository(context).mapSessions { session ->
+ if (session.isSample) {
+ null
+ } else {
+ ChatDigest(
+ id = session.id,
+ title = session.title,
+ sensitive = store.isChatSensitive(session.id, session.personaId),
+ runs = session.runSummaries
+ )
+ }
+ }.filterNotNull()
val lastOpenedAt = store.lastOpenedAt()
var tip: DailyTip? = null
@@ -172,9 +177,9 @@ internal suspend fun runLocalNotificationCheck(
)
}
// Nor, on a day they have already used it, a tip.
- val lastRun = sessions.flatMap { it.runSummaries }.maxOfOrNull { it.endedAt }
+ val lastRun = chats.flatMap { it.runs }.maxOfOrNull { it.endedAt }
if (includeTip && !usedToday(lastRun, now, zone)) {
- val usedTools = sessions.flatMap { s -> s.runSummaries.flatMap { run -> run.toolCalls.map { it.name } } }
+ val usedTools = chats.flatMap { c -> c.runs.flatMap { run -> run.toolCalls.map { it.name } } }
tip = pickDailyTip(DAILY_TIPS, recentTips(repo), usedTools.toSet())
tip?.let { add(tipCandidate(it, now, zone)) }
}
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index c87b1f3..ac1a94d 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -777,7 +777,7 @@ class ToolExecutor(
private fun parseTodoStatus(s: String): TodoStatus = when (s.lowercase().trim()) {
"in_progress", "in progress", "inprogress" -> TodoStatus.IN_PROGRESS
"completed", "done", "complete" -> TodoStatus.COMPLETED
- "cancelled", "canceled", "cancelled" -> TodoStatus.CANCELLED
+ "cancelled", "canceled" -> TodoStatus.CANCELLED
else -> TodoStatus.PENDING
}
}
diff --git a/app/src/test/java/com/gotcha/agent/ChatRunnerLifecycleTest.kt b/app/src/test/java/com/gotcha/agent/ChatRunnerLifecycleTest.kt
index 785b860..4c38e9d 100644
--- a/app/src/test/java/com/gotcha/agent/ChatRunnerLifecycleTest.kt
+++ b/app/src/test/java/com/gotcha/agent/ChatRunnerLifecycleTest.kt
@@ -10,10 +10,12 @@ import androidx.lifecycle.ViewModelStore
import androidx.test.core.app.ApplicationProvider
import com.gotcha.GotchaApp
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.service.ChatRunService
+import com.gotcha.tools.AgentMode
import com.gotcha.testsupport.FakeAndroidKeyStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -217,4 +219,27 @@ class ChatRunnerLifecycleTest {
assertEquals("Downloads", runBlocking { gate.await() })
assertNull(second.uiState.value.pendingQuestion)
}
+
+ @Test
+ fun `a second send before the first run starts is refused`() {
+ // Saved, and not the chat the engine is on, so the first send suspends
+ // loading it from disk before the run shows as busy.
+ runBlocking {
+ historyRepository.saveSession(ChatSession(id = "double-tap", title = "Saved", lastModified = 0L, messages = emptyList()))
+ }
+ runner().bindFresh("elsewhere", AgentMode.MONITOR)
+ val view = ViewedChat("double-tap", emptyList(), AgentMode.MONITOR, personaId = null)
+
+ runner().send(view, "first", emptyList(), isVoice = false)
+ runner().send(view, "second", emptyList(), isVoice = false)
+ val deadline = System.currentTimeMillis() + 5_000
+ while (System.currentTimeMillis() < deadline && !runner().isRunning) {
+ ShadowLooper.idleMainLooper()
+ Thread.sleep(10)
+ }
+ waitForRunToFinish()
+
+ val userTexts = savedTranscript("double-tap").filter { it.kind == MessageKind.USER }.map { it.text }
+ assertEquals(listOf("first"), userTexts)
+ }
}