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: implement vision support by adding image base64 processing to chat interactions

Rishabh Bajpaib4891a4067ed
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index b8a7901..f6cac57 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -29,6 +29,7 @@ import com.gotcha.data.Settings
import com.gotcha.data.SettingsRepository
import com.gotcha.llm.ChatMessage
import com.gotcha.llm.LLMClient
+import kotlinx.serialization.json.JsonPrimitive
import com.gotcha.service.GotchaDeviceAdminReceiver
import com.gotcha.tools.ToolResult
import com.gotcha.ui.ChatScreen
@@ -188,14 +189,15 @@ class MainActivity : ComponentActivity() {
Route.CHAT -> {
ChatScreen(
state = state,
- onSend = chatViewModel::sendMessage,
+ onSend = { text, imageBase64 -> chatViewModel.sendMessage(text, imageBase64) },
onStop = chatViewModel::stopAgent,
onConfirm = chatViewModel::confirmPendingActions,
onBack = {
chatViewModel.refreshSessions()
currentRoute = Route.SESSIONS
},
- onOpenSettings = { currentRoute = Route.SETTINGS }
+ onOpenSettings = { currentRoute = Route.SETTINGS },
+ onPickImage = { uri -> chatViewModel.loadImageBase64(uri) }
)
}
}
@@ -211,9 +213,9 @@ class MainActivity : ComponentActivity() {
apiTimeoutSeconds = settings.apiTimeoutSeconds
)
val response = client.chat(
- messages = listOf(ChatMessage(role = "user", content = "Reply with the single word: pong")),
+ messages = listOf(ChatMessage(role = "user", content = JsonPrimitive("Reply with the single word: pong"))),
temperature = 0f
)
- response.choices.firstOrNull()?.message?.content?.take(60) ?: "empty response"
+ response.choices.firstOrNull()?.message?.textContent?.take(60) ?: "empty response"
}
}
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 9ab5bb6..e9c26e0 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -1,6 +1,9 @@
package com.gotcha.agent
import android.app.Application
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.net.Uri
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.gotcha.data.ChatHistoryRepository
@@ -10,6 +13,7 @@ import com.gotcha.llm.ChatMessage
import com.gotcha.data.ChatSession
import com.gotcha.llm.LLMClient
import com.gotcha.llm.ToolCall
+import com.gotcha.llm.visionUserMessage
import com.gotcha.tools.ToolExecutor
import com.gotcha.tools.ToolRegistry
import com.gotcha.tools.ToolResult
@@ -18,6 +22,8 @@ import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.withContext
+import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
@@ -29,6 +35,8 @@ import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import java.io.ByteArrayOutputStream
enum class MessageKind { USER, ASSISTANT, TOOL, ERROR }
@@ -38,7 +46,8 @@ private enum class ConfirmDecision { APPROVED, DENIED, TIMED_OUT }
data class UiMessage(
val id: Long,
val kind: MessageKind,
- val text: String
+ val text: String,
+ val imageBase64: String? = null
)
/** A batch of tool calls waiting for the user's confirm/deny (Phase 7). */
@@ -131,15 +140,21 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
_uiState.update { it.copy(isConfigured = settings.isConfigured) }
}
- fun sendMessage(text: String) {
+ fun sendMessage(text: String, imageBase64: String? = null) {
val trimmed = text.trim()
- if (trimmed.isEmpty() || _uiState.value.isBusy) return
+ if (trimmed.isEmpty() && imageBase64 == null) return
+ if (_uiState.value.isBusy) return
if (client == null) {
appendUi(MessageKind.ERROR, "No API key configured. Open settings to add one.")
return
}
- llmHistory += ChatMessage(role = "user", content = trimmed)
- appendUi(MessageKind.USER, trimmed)
+ val msg = if (imageBase64 != null) {
+ visionUserMessage(trimmed, imageBase64)
+ } else {
+ ChatMessage(role = "user", content = JsonPrimitive(trimmed))
+ }
+ llmHistory += msg
+ appendUi(MessageKind.USER, msg.textContent.ifEmpty { "(image attached)" }, imageBase64)
agentJob = viewModelScope.launch {
_uiState.update { it.copy(isBusy = true) }
try {
@@ -147,7 +162,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
} catch (e: CancellationException) {
appendUi(MessageKind.ERROR, "Agent was interrupted by the user.")
} finally {
- kotlinx.coroutines.withContext(kotlinx.coroutines.NonCancellable) {
+ withContext(NonCancellable) {
saveCurrentSession()
_uiState.update { it.copy(isBusy = false, activity = null) }
agentJob = null
@@ -156,6 +171,32 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
}
}
+ /** Load an image from a content:// URI, downscale, and return base64. */
+ fun loadImageBase64(uri: Uri, maxDimension: Int = 1024): String? {
+ return try {
+ val resolver = getApplication<Application>().contentResolver
+ val inputStream = resolver.openInputStream(uri) ?: return null
+ val bytes = inputStream.use { it.readBytes() }
+
+ val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return null
+
+ val (w, h) = if (bitmap.width > maxDimension || bitmap.height > maxDimension) {
+ val ratio = minOf(maxDimension.toFloat() / bitmap.width, maxDimension.toFloat() / bitmap.height)
+ (bitmap.width * ratio).toInt() to (bitmap.height * ratio).toInt()
+ } else bitmap.width to bitmap.height
+
+ val scaled = Bitmap.createScaledBitmap(bitmap, w, h, true)
+ if (scaled != bitmap) bitmap.recycle()
+
+ val output = ByteArrayOutputStream()
+ scaled.compress(android.graphics.Bitmap.CompressFormat.JPEG, 85, output)
+ scaled.recycle()
+ android.util.Base64.encodeToString(output.toByteArray(), android.util.Base64.NO_WRAP)
+ } catch (e: Exception) {
+ null
+ }
+ }
+
fun stopAgent() {
agentJob?.cancel()
}
@@ -224,7 +265,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
private suspend fun saveCurrentSession() {
val id = activeSessionId ?: return
- val title = llmHistory.firstOrNull { it.role == "user" }?.content?.take(30) ?: "New Chat"
+ val title = llmHistory.firstOrNull { it.role == "user" }?.textContent?.take(30) ?: "New Chat"
historyRepository.saveSession(ChatSession(id, title, System.currentTimeMillis(), llmHistory.toList(), activeSessionTokenCount))
}
@@ -242,33 +283,35 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
_uiState.update { it.copy(activity = "Compacting history…") }
val compactionSystem = ChatMessage(
role = "system",
- content = "You are an advanced context compaction agent. Your task is to compress the preceding conversation history into a highly dense, structured continuation summary. You must preserve critical context, decisions, and codebase states while eliminating conversational filler and repetitive tool logs.\n\nGenerate a structured summary containing exactly the following sections:\n1. **Goal**: What is the ultimate objective of this engineering session?\n2. **Instructions & Constraints**: What specific guidelines, patterns, user preferences, or technical limitations have been established?\n3. **Discoveries & Architecture**: What have we learned about the codebase? Detail any symbol mappings, logic structures, or debugging conclusions.\n4. **Accomplished**: What changes have already been completely implemented, verified, or fixed?\n5. **Relevant Files**: Which files are currently being modified or are active in the workspace?\n\nCRITICAL: Do not lose technical specifics, user-stated constraints, or deep investigation states.\n\nContinue if you have next steps, or stop and ask for clarification if you are unsure how to proceed."
+ content = JsonPrimitive("You are an advanced context compaction agent. Your task is to compress the preceding conversation history into a highly dense, structured continuation summary. You must preserve critical context, decisions, and codebase states while eliminating conversational filler and repetitive tool logs.\n\nGenerate a structured summary containing exactly the following sections:\n1. **Goal**: What is the ultimate objective of this engineering session?\n2. **Instructions & Constraints**: What specific guidelines, patterns, user preferences, or technical limitations have been established?\n3. **Discoveries & Architecture**: What have we learned about the codebase? Detail any symbol mappings, logic structures, or debugging conclusions.\n4. **Accomplished**: What changes have already been completely implemented, verified, or fixed?\n5. **Relevant Files**: Which files are currently being modified or are active in the workspace?\n\nCRITICAL: Do not lose technical specifics, user-stated constraints, or deep investigation states.\n\nContinue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.")
)
val historyText = trimmedHistory().joinToString("\n\n") { msg ->
val role = msg.role.uppercase()
- val content = msg.content ?: if (!msg.toolCalls.isNullOrEmpty()) {
- "Called tools: " + msg.toolCalls.joinToString(", ") { it.function.name }
- } else ""
- "[$role]: $content"
+ val text = msg.textContent.ifEmpty {
+ if (!msg.toolCalls.isNullOrEmpty()) {
+ "Called tools: " + msg.toolCalls.joinToString(", ") { it.function.name }
+ } else ""
+ }
+ "[$role]: $text"
}
val requestMessage = ChatMessage(
role = "user",
- content = "Please summarize the following conversation history according to the system prompt instructions:\n\n$historyText"
+ content = JsonPrimitive("Please summarize the following conversation history according to the system prompt instructions:\n\n$historyText")
)
try {
val response = llm.chat(listOf(compactionSystem, requestMessage))
- val summary = response.choices.firstOrNull()?.message?.content
+ val summary = response.choices.firstOrNull()?.message?.textContent
if (!summary.isNullOrBlank()) {
llmHistory.clear()
- llmHistory.add(ChatMessage(role = "assistant", content = summary))
+ llmHistory.add(ChatMessage(role = "assistant", content = JsonPrimitive(summary)))
if (preserveLast != null) {
llmHistory.add(preserveLast)
}
// The new token count is roughly the size of the summary + preserved message
- val newTokensApprox = (summary.length / 4) + ((preserveLast?.content?.length ?: 0) / 4)
+ val newTokensApprox = (summary.length / 4) + ((preserveLast?.textContent?.length ?: 0) / 4)
activeSessionTokenCount = newTokensApprox
updateContextUsage()
// Show the compacted message in the chat UI as an assistant message
@@ -315,15 +358,16 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
val toolCalls = message.toolCalls.orEmpty()
if (toolCalls.isEmpty()) {
- val content = message.content ?: "(no reply)"
- llmHistory += ChatMessage(role = "assistant", content = content)
+ val content = message.textContent.ifEmpty { "(no reply)" }
+ llmHistory += ChatMessage(role = "assistant", content = JsonPrimitive(content))
appendUi(MessageKind.ASSISTANT, content)
return
}
llmHistory += message
- message.content?.takeIf { it.isNotBlank() }
- ?.let { appendUi(MessageKind.ASSISTANT, it) }
+ if (message.hasText) {
+ appendUi(MessageKind.ASSISTANT, message.textContent)
+ }
val decision = requestConfirmation(toolCalls)
for (call in toolCalls) {
@@ -338,7 +382,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
}
llmHistory += ChatMessage(
role = "tool",
- content = result.message,
+ content = JsonPrimitive(result.message),
toolCallId = call.id
)
appendUi(
@@ -417,11 +461,13 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
private fun systemPrompt() = listOf(
ChatMessage(
role = "system",
- content = "You are Gotcha, an assistant running on the user's Android phone. " +
+ content = JsonPrimitive(
+ "You are Gotcha, an assistant running on the user's Android phone. " +
"You control the device only through the provided tools; never invent tool names or " +
"capabilities. If a tool reports a missing permission, explain to the user what to " +
"grant and suggest retrying. Keep replies short and conversational. " +
"After changing device state, confirm what was done based on the tool results."
+ )
)
)
@@ -433,7 +479,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
var start = llmHistory.size - 1
while (start >= 0) {
- currentTokens += (llmHistory[start].content?.length ?: 0) / 4
+ currentTokens += llmHistory[start].textContent.length / 4
if (currentTokens > maxTokens) {
start++
break
@@ -450,7 +496,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
// Many LLM APIs strictly require history to start with a user message.
// If our truncation or compaction leaves an assistant message first, prepend a dummy user message.
if (trimmed.isNotEmpty() && trimmed.first().role == "assistant") {
- return listOf(ChatMessage(role = "user", content = "[System Note: Conversation context restored from previous turn]")) + trimmed
+ return listOf(ChatMessage(role = "user", content = JsonPrimitive("[System Note: Conversation context restored from previous turn]"))) + trimmed
}
return trimmed
}
@@ -465,19 +511,19 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
else -> "Something went wrong: ${e.message}"
}
- private fun appendUi(kind: MessageKind, text: String) {
+ private fun appendUi(kind: MessageKind, text: String, imageBase64: String? = null) {
_uiState.update {
- it.copy(messages = it.messages + UiMessage(nextId++, kind, text))
+ it.copy(messages = it.messages + UiMessage(nextId++, kind, text, imageBase64))
}
}
private fun rebuildUiMessages() {
val rebuilt = llmHistory.mapNotNull { msg ->
when {
- msg.role == "user" -> UiMessage(nextId++, MessageKind.USER, msg.content ?: "")
- msg.role == "assistant" && !msg.content.isNullOrBlank() ->
- UiMessage(nextId++, MessageKind.ASSISTANT, msg.content)
- msg.role == "tool" -> UiMessage(nextId++, MessageKind.TOOL, msg.content ?: "")
+ msg.role == "user" -> UiMessage(nextId++, MessageKind.USER, msg.textContent.ifEmpty { "(image attached)" })
+ msg.role == "assistant" && msg.hasText ->
+ UiMessage(nextId++, MessageKind.ASSISTANT, msg.textContent)
+ msg.role == "tool" -> UiMessage(nextId++, MessageKind.TOOL, msg.textContent.ifEmpty { "(no result)" })
else -> null
}
}
diff --git a/app/src/main/java/com/gotcha/llm/Models.kt b/app/src/main/java/com/gotcha/llm/Models.kt
index d2e93ce..410063a 100644
--- a/app/src/main/java/com/gotcha/llm/Models.kt
+++ b/app/src/main/java/com/gotcha/llm/Models.kt
@@ -4,17 +4,62 @@ import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.buildJsonArray
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.put
+import kotlinx.serialization.json.putJsonObject
+/**
+ * A chat message sent to or received from the LLM API.
+ * [content] is either a string (JsonPrimitive) for text-only messages, or a
+ * JsonArray of content parts for vision/multi-modal messages following the
+ * OpenAI format: [{"type":"text","text":"..."},{"type":"image_url","image_url":{"url":"data:..."}}].
+ */
@Serializable
data class ChatMessage(
val role: String,
- val content: String? = null,
+ val content: JsonElement? = null,
@SerialName("tool_calls")
val toolCalls: List<ToolCall>? = null,
@SerialName("tool_call_id")
val toolCallId: String? = null
-)
+) {
+ /** The plain-text portion of this message, or empty string if there is none. */
+ val textContent: String get() = when (content) {
+ is JsonPrimitive -> content.content
+ is JsonArray -> content.firstOrNull()
+ ?.jsonObject?.get("text")?.jsonPrimitive?.content ?: ""
+ else -> ""
+ }
+
+ /** True when this message has a non-blank text portion. */
+ val hasText: Boolean get() = textContent.isNotBlank()
+}
+
+/** Build a vision-content ChatMessage with text + an image. */
+fun visionUserMessage(text: String, imageBase64: String, imageFormat: String = "png"): ChatMessage {
+ val dataUri = "data:image/$imageFormat;base64,$imageBase64"
+ return ChatMessage(
+ role = "user",
+ content = buildJsonArray {
+ add(buildJsonObject {
+ put("type", "text")
+ put("text", text.ifBlank { "What is in this image?" })
+ })
+ add(buildJsonObject {
+ put("type", "image_url")
+ putJsonObject("image_url") { put("url", dataUri) }
+ })
+ }
+ )
+}
@Serializable
data class ToolCall(
diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
index 5421e79..b614f81 100644
--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
@@ -1,20 +1,30 @@
package com.gotcha.ui
+import android.net.Uri
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.foundation.Image as ComposeImage
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.ArrowBack
+import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
-import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
@@ -33,6 +43,9 @@ import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import com.gotcha.agent.ChatUiState
@@ -40,15 +53,27 @@ import com.gotcha.agent.ChatUiState
@Composable
fun ChatScreen(
state: ChatUiState,
- onSend: (String) -> Unit,
+ onSend: (String, String?) -> Unit,
onStop: () -> Unit,
onConfirm: (Boolean) -> Unit,
onBack: () -> Unit,
- onOpenSettings: () -> Unit
+ onOpenSettings: () -> Unit,
+ onPickImage: (Uri) -> String?
) {
var input by rememberSaveable { mutableStateOf("") }
+ var pendingImageUri by rememberSaveable { mutableStateOf<Uri?>(null) }
+ var pendingImageBase64 by rememberSaveable { mutableStateOf<String?>(null) }
val listState = rememberLazyListState()
+ val imagePickerLauncher = rememberLauncherForActivityResult(
+ contract = ActivityResultContracts.GetContent()
+ ) { uri: Uri? ->
+ if (uri != null) {
+ pendingImageUri = uri
+ pendingImageBase64 = onPickImage(uri)
+ }
+ }
+
LaunchedEffect(state.messages.size) {
if (state.messages.isNotEmpty()) {
listState.animateScrollToItem(state.messages.size - 1)
@@ -105,10 +130,50 @@ fun ChatScreen(
}
}
+ // Image attachment preview
+ if (pendingImageBase64 != null) {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 8.dp, vertical = 2.dp),
+ contentAlignment = Alignment.CenterStart
+ ) {
+ val bitmap = try {
+ val bytes = android.util.Base64.decode(pendingImageBase64, android.util.Base64.DEFAULT)
+ android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
+ } catch (_: Exception) { null }
+ if (bitmap != null) {
+ ComposeImage(
+ bitmap = bitmap.asImageBitmap(),
+ contentDescription = "Attached image",
+ modifier = Modifier
+ .height(120.dp)
+ .clip(RoundedCornerShape(8.dp)),
+ contentScale = ContentScale.Fit
+ )
+ }
+ IconButton(
+ onClick = {
+ pendingImageUri = null
+ pendingImageBase64 = null
+ },
+ modifier = Modifier.align(Alignment.TopEnd)
+ ) {
+ Icon(Icons.Default.Close, contentDescription = "Remove image")
+ }
+ }
+ }
+
Row(
modifier = Modifier.fillMaxWidth().padding(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
+ IconButton(
+ onClick = { imagePickerLauncher.launch("image/*") },
+ enabled = !state.isBusy && state.isConfigured
+ ) {
+ Text("+", style = MaterialTheme.typography.titleLarge)
+ }
OutlinedTextField(
value = input,
onValueChange = { input = it },
@@ -125,10 +190,12 @@ fun ChatScreen(
} else {
Button(
onClick = {
- onSend(input)
+ onSend(input, pendingImageBase64)
input = ""
+ pendingImageUri = null
+ pendingImageBase64 = null
},
- enabled = state.isConfigured && input.isNotBlank()
+ enabled = state.isConfigured && (input.isNotBlank() || pendingImageBase64 != null)
) {
Text("Send")
}
diff --git a/app/src/main/java/com/gotcha/ui/MessageBubble.kt b/app/src/main/java/com/gotcha/ui/MessageBubble.kt
index 39ae238..99873a7 100644
--- a/app/src/main/java/com/gotcha/ui/MessageBubble.kt
+++ b/app/src/main/java/com/gotcha/ui/MessageBubble.kt
@@ -1,9 +1,12 @@
package com.gotcha.ui
+import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -11,7 +14,11 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import com.gotcha.agent.MessageKind
import com.gotcha.agent.UiMessage
@@ -20,7 +27,7 @@ import com.gotcha.agent.UiMessage
fun MessageBubble(message: UiMessage) {
val isUser = message.kind == MessageKind.USER
val colors = MaterialTheme.colorScheme
- val (container, content) = when (message.kind) {
+ val (container, contentColor) = when (message.kind) {
MessageKind.USER -> colors.primaryContainer to colors.onPrimaryContainer
MessageKind.ASSISTANT -> colors.surfaceVariant to colors.onSurfaceVariant
MessageKind.TOOL -> colors.secondaryContainer to colors.onSecondaryContainer
@@ -35,7 +42,7 @@ fun MessageBubble(message: UiMessage) {
) {
Surface(
color = container,
- contentColor = content,
+ contentColor = contentColor,
shape = RoundedCornerShape(
topStart = 16.dp,
topEnd = 16.dp,
@@ -43,17 +50,37 @@ fun MessageBubble(message: UiMessage) {
bottomEnd = if (isUser) 4.dp else 16.dp
)
) {
- Box(modifier = Modifier.widthIn(max = 300.dp).padding(12.dp)) {
- Text(
- text = when (message.kind) {
- MessageKind.TOOL -> "🔧 ${message.text}"
- else -> message.text
- },
- style = when (message.kind) {
- MessageKind.TOOL -> MaterialTheme.typography.bodySmall
- else -> MaterialTheme.typography.bodyMedium
+ Column(modifier = Modifier.widthIn(max = 300.dp).padding(12.dp)) {
+ // Show attached image if present
+ message.imageBase64?.let { base64 ->
+ val bitmap = try {
+ val bytes = android.util.Base64.decode(base64, android.util.Base64.DEFAULT)
+ android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
+ } catch (_: Exception) { null }
+ if (bitmap != null) {
+ Image(
+ bitmap = bitmap.asImageBitmap(),
+ contentDescription = "Attached image",
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(160.dp)
+ .clip(RoundedCornerShape(8.dp)),
+ contentScale = ContentScale.Fit
+ )
}
- )
+ }
+ if (message.text.isNotEmpty()) {
+ Text(
+ text = when (message.kind) {
+ MessageKind.TOOL -> "🔧 ${message.text}"
+ else -> message.text
+ },
+ style = when (message.kind) {
+ MessageKind.TOOL -> MaterialTheme.typography.bodySmall
+ else -> MaterialTheme.typography.bodyMedium
+ }
+ )
+ }
}
}
}
diff --git a/app/src/test/java/com/gotcha/llm/LLMClientTest.kt b/app/src/test/java/com/gotcha/llm/LLMClientTest.kt
index ff04246..4d305d3 100644
--- a/app/src/test/java/com/gotcha/llm/LLMClientTest.kt
+++ b/app/src/test/java/com/gotcha/llm/LLMClientTest.kt
@@ -1,6 +1,7 @@
package com.gotcha.llm
import kotlinx.coroutines.test.runTest
+import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import okhttp3.mockwebserver.MockResponse
@@ -71,7 +72,7 @@ class LLMClientTest {
)
val response = client.chat(
- messages = listOf(ChatMessage(role = "user", content = "Call mom")),
+ messages = listOf(ChatMessage(role = "user", content = JsonPrimitive("Call mom"))),
tools = listOf(dummyTool)
)
@@ -90,10 +91,10 @@ class LLMClientTest {
)
val response = client.chat(
- messages = listOf(ChatMessage(role = "user", content = "Hello"))
+ messages = listOf(ChatMessage(role = "user", content = JsonPrimitive("Hello")))
)
- assertEquals("Hi there", response.choices.single().message.content)
+ assertEquals("Hi there", response.choices.single().message.textContent)
}
@Test
@@ -104,13 +105,13 @@ class LLMClientTest {
).setHeader("Content-Type", "application/json")
)
- val messages = listOf(ChatMessage(role = "user", content = "What is 2+2?"))
+ val messages = listOf(ChatMessage(role = "user", content = JsonPrimitive("What is 2+2?")))
val first = client.chat(messages = messages)
val second = client.chat(messages = messages)
- assertEquals("cached answer", first.choices.single().message.content)
- assertEquals(first.choices.single().message.content, second.choices.single().message.content)
+ assertEquals("cached answer", first.choices.single().message.textContent)
+ assertEquals(first.choices.single().message.textContent, second.choices.single().message.textContent)
assertEquals(1, server.requestCount)
}
@@ -137,7 +138,7 @@ class LLMClientTest {
server.enqueue(MockResponse().setBody(toolCallBody).setHeader("Content-Type", "application/json"))
server.enqueue(MockResponse().setBody(toolCallBody).setHeader("Content-Type", "application/json"))
- val messages = listOf(ChatMessage(role = "user", content = "Call mom"))
+ val messages = listOf(ChatMessage(role = "user", content = JsonPrimitive("Call mom")))
client.chat(messages = messages, tools = listOf(dummyTool))
client.chat(messages = messages, tools = listOf(dummyTool))