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(agent): culling old images keeps the user's prompt and attached document text (#102)
Durganshua5219d77185b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 64b741a..d841f49 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -219,6 +219,14 @@ All notable changes to Gotcha are documented here.the ball is on or off instead of only once it is already too late.### Fixed+- **Gotcha remembers what you asked about an earlier photo** (#102). To save+ space, Gotcha drops older images from what it sends the model. It used to+ drop the whole message with them, so a question you sent with a photo, or the+ text of a file you attached next to it, disappeared too. Now only the images+ go, replaced by a short note, and your words and the file's text stay. Your+ own images also no longer compete with the screenshots Gotcha takes while it+ works: your 4 most recent image messages keep their images however many+ screenshots come after them.- **Readable release notes in the update check** (#70). When Settings → Aboutfound a new version, its notes were shown as raw Markdown, with `###`, `**`and backticks spelled out and lines broken mid-sentence. They are nowdiff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex 4ce99b1..a3d1c3a 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -37,7 +37,6 @@ import kotlinx.serialization.json.JsonArrayimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.contentOrNull-import kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitive/** Outcome of the sensitive-action confirmation step. */@@ -1779,8 +1778,7 @@ class AgentEngine(}val pathNote = if (savedPath != null) "\n\nSaved to: $savedPath" else ""val visionMsg = visionUserMessage(- "Screen text:\n$screenText\n\nThe assistant captured a " +- "full-resolution screenshot for visual detail.$pathNote",+ "Screen text:\n$screenText\n\n$FULL_RES_SCREENSHOT_NOTE for visual detail.$pathNote",screenshot.base64,screenshot.format)@@ -1793,39 +1791,84 @@ class AgentEngine(companion object {/**- * Returns a copy of [messages] with old vision images and bulky UI hierarchy- * screen observations replaced by text-only summaries.- * Retains full content for the 4 most recent screen perception turns.- * The original list (and [history]) is NOT modified.+ * Returns a copy of [messages] with old screen observations and old images+ * culled. The original list (and [history]) is NOT modified.+ *+ * Two separate windows, so an agent loop that screenshots every step never+ * pushes out an image the user is still asking about:+ * - screen observations (screenshots + UI dumps the agent captured): the+ * [OBSERVATION_WINDOW] newest keep full content; older ones are replaced+ * by a one-line note.+ * - any other message with images (user attachments, voice-call turns,+ * image files the agent read): the [IMAGE_MESSAGE_WINDOW] newest keep+ * their images; older ones lose only the images and keep their text —+ * the user's prompt and any `[Attached file: …]` bodies.*/internal fun cullOldObservations(messages: List<ChatMessage>): List<ChatMessage> {- val observationMsgIndices = messages.indices.filter { i ->- val msg = messages[i]- val content = msg.content- val isVisionArray = content is JsonArray && content.any { part ->- part.jsonObject["type"]?.jsonPrimitive?.content == "image_url"- }- val text = msg.textContent- val isScreenObservation = text.contains("[Screen State]") ||- text.contains("── UI Elements ──") ||- text.contains("read_screen_raw:")- isVisionArray || isScreenObservation+ val observations = messages.indices.filter { isScreenObservation(messages[it]) }+ val imageMessages = messages.indices.filter { i ->+ messages[i].imageCount > 0 && !isScreenObservation(messages[i])}- val toCull = observationMsgIndices.dropLast(4).toSet()- if (toCull.isEmpty()) return messages+ val cullObservation = observations.dropLast(OBSERVATION_WINDOW).toSet()+ val stripImages = imageMessages.dropLast(IMAGE_MESSAGE_WINDOW).toSet()+ if (cullObservation.isEmpty() && stripImages.isEmpty()) return messagesreturn messages.mapIndexed { idx, msg ->- if (idx in toCull) {- msg.copy(+ when (idx) {+ in cullObservation -> msg.copy(content = JsonPrimitive("[Previous screen observation removed to save context. Only the 4 most recent are retained.]"))- } else {- msg+ in stripImages -> withoutImages(msg)+ else -> msg}}}++ /** How many of the newest screen observations keep their full content. */+ private const val OBSERVATION_WINDOW = 4++ /** How many of the newest non-observation image messages keep their images. */+ private const val IMAGE_MESSAGE_WINDOW = 4++ /**+ * Text of the full-resolution `read_screen_raw` screenshot message, so it is+ * recognised as a screen observation (its text carries none of the other markers).+ */+ internal const val FULL_RES_SCREENSHOT_NOTE = "The assistant captured a full-resolution screenshot"++ /** True for a message the agent captured of the screen (screenshot and/or UI dump). */+ internal fun isScreenObservation(msg: ChatMessage): Boolean {+ val text = msg.textContent+ return text.contains("[Screen State]") ||+ text.contains("── UI Elements ──") ||+ text.contains("read_screen_raw:") ||+ text.contains(FULL_RES_SCREENSHOT_NOTE)+ }++ /**+ * [msg] with its `image_url` parts dropped and a note saying how many were+ * removed. Every other part is kept in order, so the prompt stays the first+ * part ([ChatMessage.textContent] reads only that one).+ */+ private fun withoutImages(msg: ChatMessage): ChatMessage {+ val parts = msg.content as? JsonArray ?: return msg+ val kept = parts.filterNot { part ->+ ((part as? JsonObject)?.get("type") as? JsonPrimitive)?.content == "image_url"+ }+ val removed = parts.size - kept.size+ val note = if (removed == 1) {+ "[1 earlier image removed to save context]"+ } else {+ "[$removed earlier images removed to save context]"+ }+ return msg.copy(+ content = JsonArray(+ kept + JsonObject(mapOf("type" to JsonPrimitive("text"), "text" to JsonPrimitive(note)))+ )+ )+ }private const val TAG = "Gotcha"private const val INTER_CALL_DELAY_MS = 400Ldiff --git a/app/src/test/java/com/gotcha/agent/PromptCacheAndTokenOptimizationTest.kt b/app/src/test/java/com/gotcha/agent/PromptCacheAndTokenOptimizationTest.ktindex fbea458..f76ad94 100644--- a/app/src/test/java/com/gotcha/agent/PromptCacheAndTokenOptimizationTest.kt+++ b/app/src/test/java/com/gotcha/agent/PromptCacheAndTokenOptimizationTest.kt@@ -284,6 +284,87 @@ class PromptCacheAndTokenOptimizationTest {assertTrue(culled[5].textContent.contains("Turn 6"))}+ private fun screenObservation(i: Int) = com.gotcha.llm.visionUserMessage(+ "[Screen State]\nTurn $i observation\n── UI Elements ──",+ "abc$i",+ "jpeg"+ )++ private fun imageParts(msg: ChatMessage) =+ (msg.content as kotlinx.serialization.json.JsonArray).filter {+ (it as kotlinx.serialization.json.JsonObject)["type"].toString().contains("image_url")+ }++ private fun allText(msg: ChatMessage) =+ (msg.content as kotlinx.serialization.json.JsonArray).joinToString("\n") {+ (it as kotlinx.serialization.json.JsonObject)["text"]?.toString().orEmpty()+ }++ @Test+ fun `AgentEngine cullOldObservations keeps the text of a culled user image message`() {+ val userImages = (1..5).map { com.gotcha.llm.visionUserMessage("What is in photo $it?", "img$it", "jpeg") }++ val culled = AgentEngine.cullOldObservations(userImages)++ // The oldest falls outside the 4-message window: images gone, prompt kept.+ assertEquals("What is in photo 1?", culled[0].textContent)+ assertTrue(imageParts(culled[0]).isEmpty())+ assertTrue(allText(culled[0]).contains("[1 earlier image removed to save context]"))+ // The 4 newest are untouched.+ for (i in 1..4) assertEquals(userImages[i], culled[i])+ }++ @Test+ fun `AgentEngine cullOldObservations keeps document text of a culled mixed attachment message`() {+ val mixed = com.gotcha.llm.attachmentsUserMessage(+ "Compare the report with these photos",+ listOf(com.gotcha.llm.DocumentPart("report.pdf", "application/pdf", "Quarterly revenue rose 12%.")),+ listOf("imgA", "imgB")+ )+ val later = (1..4).map { com.gotcha.llm.visionUserMessage("Photo $it", "img$it", "jpeg") }++ val culled = AgentEngine.cullOldObservations(listOf(mixed) + later)++ assertEquals(mixed.textContent, culled[0].textContent)+ assertTrue(culled[0].textContent.contains("[Attached file: report.pdf"))+ assertTrue(culled[0].textContent.contains("Quarterly revenue rose 12%."))+ assertTrue(imageParts(culled[0]).isEmpty())+ assertTrue(allText(culled[0]).contains("[2 earlier images removed to save context]"))+ }++ @Test+ fun `AgentEngine cullOldObservations fully replaces a culled full-resolution screenshot`() {+ val fullRes = com.gotcha.llm.visionUserMessage(+ "Screen text:\nInbox\n\n${AgentEngine.FULL_RES_SCREENSHOT_NOTE} for visual detail.",+ "raw",+ "png"+ )+ val culled = AgentEngine.cullOldObservations(listOf(fullRes) + (1..4).map(::screenObservation))++ assertEquals(+ "[Previous screen observation removed to save context. Only the 4 most recent are retained.]",+ culled[0].textContent+ )+ assertTrue(culled[0].content is kotlinx.serialization.json.JsonPrimitive)+ }++ @Test+ fun `AgentEngine cullOldObservations keeps user images and screen observations in separate windows`() {+ val userImage = com.gotcha.llm.visionUserMessage("Fix the colour of this", "photo", "jpeg")+ val messages = listOf(userImage) + (1..6).map(::screenObservation)+ val before = messages.toList()++ val culled = AgentEngine.cullOldObservations(messages)++ // Six newer screenshots do not push out the user's image.+ assertEquals(userImage, culled[0])+ assertTrue(culled[1].textContent.contains("[Previous screen observation removed"))+ assertTrue(culled[2].textContent.contains("[Previous screen observation removed"))+ assertEquals(messages.drop(3), culled.drop(3))+ // The input list is never mutated.+ assertEquals(before, messages)+ }+@Testfun `AgentEngine systemPromptMessage combines instructions and environment into Index 0 System message`() {com.gotcha.testsupport.FakeAndroidKeyStore.setUp()