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: implement image-based screenshot extraction from chat history and add UI toggle support
Rishabh Bajpai6b4c6bc5ee0f
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex 445ce81..42a5e99 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -795,6 +795,7 @@ class MainActivity : ComponentActivity() {loading = sharePoster.loading,preview = sharePoster.preview,error = sharePoster.error,+ hasImage = chatViewModel.activeSessionHasImage(),onGenerate = sharePoster::generate,onShare = { sharePoster.preview?.let { sharePoster.share(it) } },onSave = { sharePoster.preview?.let { sharePoster.save(it) } },diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex 2a4beed..0150a82 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -1097,41 +1097,41 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A}/**- * Best-effort screenshot for the poster thumbnail: the newest PNG in the- * engine session's working dir, else a fresh screen capture, else null.+ * Best-effort screenshot for the poster thumbnail: the newest image in the+ * engine session's chat history (a user-attached photo or an agent screen+ * capture), else null.*- * Guarded so a huge or malformed PNG can't OOM the decode: files over+ * Guarded so a huge or malformed image can't OOM the decode: files over* [MAX_SHARE_SCREENSHOT_BYTES] are skipped, and anything larger than* [MAX_SHARE_SCREENSHOT_DIM] on either side is downsampled before decoding* (the poster draws the thumbnail at 460×345, so full-res is wasteful).*/private fun loadShareScreenshot(): Bitmap? {- val dir = com.gotcha.data.GotchaStorage.subdir(- agentEngine.workingDir(),- com.gotcha.data.GotchaStorage.Kind.SCREENSHOTS- )- val newest = dir.listFiles { f -> f.isFile && f.extension.equals("png", true) }- ?.maxByOrNull { it.lastModified() }- if (newest != null) {- return try {- if (newest.length() > MAX_SHARE_SCREENSHOT_BYTES) return null- val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }- BitmapFactory.decodeFile(newest.absolutePath, bounds)- val w = bounds.outWidth- val h = bounds.outHeight- if (w <= 0 || h <= 0) return null- val options = BitmapFactory.Options().apply {- inSampleSize = when {- w <= MAX_SHARE_SCREENSHOT_DIM && h <= MAX_SHARE_SCREENSHOT_DIM -> 1- else -> maxOf(w, h) / MAX_SHARE_SCREENSHOT_DIM- }+ // Snapshot before scanning: the engine coroutine mutates history as it+ // runs, and this is read from the UI thread. asReversed() alone is a+ // live view, not a copy.+ val dataUri = agentEngine.history.toList().asReversed()+ .firstNotNullOfOrNull { it.imageUrl() }+ ?: return null+ val base64 = dataUri.substringAfter("base64,")+ return try {+ val bytes = android.util.Base64.decode(base64, android.util.Base64.DEFAULT)+ if (bytes.size > MAX_SHARE_SCREENSHOT_BYTES) return null+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)+ val w = bounds.outWidth+ val h = bounds.outHeight+ if (w <= 0 || h <= 0) return null+ val options = BitmapFactory.Options().apply {+ inSampleSize = when {+ w <= MAX_SHARE_SCREENSHOT_DIM && h <= MAX_SHARE_SCREENSHOT_DIM -> 1+ else -> maxOf(w, h) / MAX_SHARE_SCREENSHOT_DIM}- BitmapFactory.decodeFile(newest.absolutePath, options)- } catch (_: Exception) {- null}+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)+ } catch (_: Exception) {+ null}- return null}/**@@ -1151,6 +1151,18 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Areturn synthesizeRunSummariesFromHistory(snapshot, settings.model, engineAgent.name)}+ /**+ * True when the session currently bound to the engine has an image in its+ * history. Drives whether the poster sheet offers "Include a screenshot":+ * the option only makes sense when there is something to embed, and it must+ * disappear once the image is culled from history.+ */+ fun activeSessionHasImage(): Boolean {+ // Snapshot before reading: the engine coroutine mutates history as it+ // runs, and this is read from the UI thread.+ return agentEngine.history.toList().any { it.hasImage }+ }+/** Formats a SUBAGENT_STEPS tool message (description, steps, result) for chat export. */private fun appendSubAgentExport(sb: StringBuilder, text: String) {val descEnd = text.indexOf('\n', "SUBAGENT_STEPS:".length)diff --git a/app/src/main/java/com/gotcha/llm/Models.kt b/app/src/main/java/com/gotcha/llm/Models.ktindex c01dbf4..f85177b 100644--- a/app/src/main/java/com/gotcha/llm/Models.kt+++ b/app/src/main/java/com/gotcha/llm/Models.kt@@ -42,6 +42,25 @@ data class ChatMessage(/** True when this message has a non-blank text portion. */val hasText: Boolean get() = textContent.isNotBlank()++ /** True when this message carries an image (vision) part. */+ val hasImage: Boolean get() = imageUrl() != null++ /**+ * The data URI of this message's first image part (e.g.+ * "data:image/jpeg;base64,…"), or null when there is no image part.+ */+ fun imageUrl(): String? {+ val parts = content as? JsonArray ?: return null+ return parts.firstNotNullOfOrNull { part ->+ val obj = part as? JsonObject ?: return@firstNotNullOfOrNull null+ if ((obj["type"] as? JsonPrimitive)?.content != "image_url") {+ return@firstNotNullOfOrNull null+ }+ val img = obj["image_url"] as? JsonObject ?: return@firstNotNullOfOrNull null+ (img["url"] as? JsonPrimitive)?.content?.takeIf { it.isNotBlank() }+ }+ }}/** Build a vision-content ChatMessage with text + an image. */diff --git a/app/src/main/java/com/gotcha/marketing/PosterRenderer.kt b/app/src/main/java/com/gotcha/marketing/PosterRenderer.ktindex 4fbd6fb..d21c613 100644--- a/app/src/main/java/com/gotcha/marketing/PosterRenderer.kt+++ b/app/src/main/java/com/gotcha/marketing/PosterRenderer.kt@@ -198,13 +198,11 @@ object PosterRenderer {y += 46f// Body / screenshot / achievements. The CTA band starts 320px up- // from the bottom, so content above it must stop before that.+ // from the bottom, so content above it must stop before that. A+ // provided screenshot wins over everything else — the user opted+ // into embedding it, so it must never be silently dropped.val ctaBandTop = HEIGHT_PX - 320f - CTA_PILL_H - 120fwhen {- content.template == "recap" && content.achievements.isNotEmpty() -> {- y = drawAchievements(canvas, content.achievements, y, ctaBandTop)- y += 46f- }screenshot != null -> {val sw = 460fval sh = 345f@@ -230,6 +228,10 @@ object PosterRenderer {canvas.restore()y += sh + 40f}+ content.template == "recap" && content.achievements.isNotEmpty() -> {+ y = drawAchievements(canvas, content.achievements, y, ctaBandTop)+ y += 46f+ }content.body.isNotBlank() -> {y += drawWrapped(canvas,@@ -269,7 +271,7 @@ object PosterRenderer {hashtagPaint)canvas.drawText(- "Built with ${stats.model.ifBlank { "an AI agent" }} · on Android",+ "Built with Samosa AI · on Android",WIDTH_PX / 2f,pillTop + pillH + 132f,textPaint(36f, Color.argb(180, 255, 255, 255), center = true)@@ -344,7 +346,7 @@ object PosterRenderer {val chips = listOf("⚡ ${stats.durationDisplay}","🧰 ${stats.toolCount} tool" + if (stats.toolCount == 1) "" else "s",- "🤖 ${stats.model.take(14)}"+ "🤖 Samosa AI")val h = 88fval gap = 24fdiff --git a/app/src/main/java/com/gotcha/ui/SharePosterSheet.kt b/app/src/main/java/com/gotcha/ui/SharePosterSheet.ktindex 2fc6578..f7de8eb 100644--- a/app/src/main/java/com/gotcha/ui/SharePosterSheet.kt+++ b/app/src/main/java/com/gotcha/ui/SharePosterSheet.kt@@ -47,6 +47,7 @@ fun SharePosterSheet(loading: Boolean,preview: Bitmap?,error: String?,+ hasImage: Boolean,onGenerate: (includeScreenshot: Boolean) -> Unit,onShare: () -> Unit,onSave: () -> Unit,@@ -74,17 +75,22 @@ fun SharePosterSheet(style = MaterialTheme.typography.bodyMedium)- Row(- modifier = Modifier.fillMaxWidth(),- verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.SpaceBetween- ) {- Text("Include a screenshot", style = MaterialTheme.typography.bodyMedium)- Switch(- checked = includeScreenshot,- onCheckedChange = { includeScreenshot = it },- enabled = !loading- )+ // The screenshot toggle only makes sense when the chat history+ // actually holds an image the poster can embed; hide it otherwise+ // (e.g. the image was culled from the session).+ if (hasImage) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.SpaceBetween+ ) {+ Text("Include a screenshot", style = MaterialTheme.typography.bodyMedium)+ Switch(+ checked = includeScreenshot,+ onCheckedChange = { includeScreenshot = it },+ enabled = !loading+ )+ }}when {diff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelShareScreenshotTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelShareScreenshotTest.ktnew file mode 100644index 0000000..94ea373--- /dev/null+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelShareScreenshotTest.kt@@ -0,0 +1,82 @@+package com.gotcha.agent++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.gotcha.data.ChatHistoryRepository+import com.gotcha.data.Settings+import com.gotcha.data.SettingsRepository+import com.gotcha.llm.ChatMessage+import com.gotcha.llm.visionUserMessage+import com.gotcha.testsupport.FakeAndroidKeyStore+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.JsonPrimitive+import org.junit.After+import org.junit.Assert.assertFalse+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 poster sheet's "Include a screenshot" toggle must track the chat history:+ * present while a vision message is in the session, gone once it is removed.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ChatViewModelShareScreenshotTest {++ private val application: Application = ApplicationProvider.getApplicationContext()+ private lateinit var settingsRepository: SettingsRepository+ private lateinit var historyRepository: ChatHistoryRepository+ private lateinit var viewModel: ChatViewModel++ @Before+ fun setUp() {+ FakeAndroidKeyStore.setUp()+ settingsRepository = SettingsRepository(application)+ historyRepository = ChatHistoryRepository(application, "share-screenshot-test-chats")+ settingsRepository.save(Settings(apiKey = "test-key"))+ viewModel = ChatViewModel(application)+ ShadowLooper.idleMainLooper()+ }++ @After+ fun tearDown() {+ runBlocking { historyRepository.deleteSession("session") }+ }++ private fun engineHistory(): MutableList<ChatMessage> {+ val engineField = ChatViewModel::class.java.getDeclaredField("agentEngine")+ .apply { isAccessible = true }+ @Suppress("UNCHECKED_CAST")+ return (engineField.get(viewModel) as AgentEngine).history+ }++ @Test+ fun `hasImage is false on an empty or text-only history`() {+ assertFalse(viewModel.activeSessionHasImage())++ engineHistory() += ChatMessage(role = "user", content = JsonPrimitive("hello"))+ assertFalse(viewModel.activeSessionHasImage())+ }++ @Test+ fun `hasImage is true once a vision message lands in history`() {+ engineHistory() += visionUserMessage("what is this", "QUJD", imageFormat = "jpeg")+ assertTrue(viewModel.activeSessionHasImage())+ }++ @Test+ fun `hasImage flips back to false when the image is culled from history`() {+ val history = engineHistory()+ history += visionUserMessage("what is this", "QUJD", imageFormat = "jpeg")+ assertTrue(viewModel.activeSessionHasImage())++ // Simulate the image being retracted / culled from the session.+ history.removeAll { it.hasImage }+ assertFalse(viewModel.activeSessionHasImage())+ }+}diff --git a/app/src/test/java/com/gotcha/llm/ModelsTest.kt b/app/src/test/java/com/gotcha/llm/ModelsTest.ktindex 12f694c..d2198de 100644--- a/app/src/test/java/com/gotcha/llm/ModelsTest.kt+++ b/app/src/test/java/com/gotcha/llm/ModelsTest.kt@@ -3,9 +3,12 @@ package com.gotcha.llmimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonArrayimport kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.buildJsonArray+import kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.jsonArrayimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.putimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertNull@@ -78,6 +81,37 @@ class ModelsTest {assertEquals("What is in this image?", msg.textContent)}+ @Test+ fun `hasImage is true for vision messages and imageUrl returns the data uri`() {+ val msg = visionUserMessage("look", "QUJD", imageFormat = "jpeg")+ assertTrue(msg.hasImage)+ assertEquals("data:image/jpeg;base64,QUJD", msg.imageUrl())+ }++ @Test+ fun `hasImage is false and imageUrl null for text-only messages`() {+ assertFalse(ChatMessage(role = "user", content = JsonPrimitive("hi")).hasImage)+ assertNull(ChatMessage(role = "user", content = JsonPrimitive("hi")).imageUrl())+ assertNull(ChatMessage(role = "assistant", content = null).imageUrl())+ }++ @Test+ fun `imageUrl returns null when the content array has no image part`() {+ val msg = ChatMessage(+ role = "user",+ content = buildJsonArray {+ add(+ buildJsonObject {+ put("type", "text")+ put("text", "no image here")+ }+ )+ }+ )+ assertFalse(msg.hasImage)+ assertNull(msg.imageUrl())+ }+@Testfun `tool call type is always encoded even with encodeDefaults off`() {val call = ToolCall(id = "call_1", function = FunctionCall(name = "dial_number", arguments = "{}"))