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(chat): support multiple image and file attachments per message (#94)
Durganshu2fa87a69e5d3
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex 057a298..fc1a9d9 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -870,8 +870,8 @@ class MainActivity : ComponentActivity() {}ChatScreen(state = state,- onSend = { text, imageBase64, attachment, isVoiceInput ->- chatViewModel.sendMessage(text, imageBase64, attachment, isVoiceInput)+ onSend = { text, attachments, isVoiceInput ->+ chatViewModel.sendMessage(text, attachments, isVoiceInput)},onStop = chatViewModel::stopAgent,onConfirm = chatViewModel::confirmPendingActions,@@ -879,8 +879,9 @@ class MainActivity : ComponentActivity() {onOpenDrawer = { scope.launch { drawerState.open() } },onOpenSettings = { currentRoute = Route.SETTINGS },sessionTitle = sessions.firstOrNull { it.id == state.activeSessionId }?.title,- onPickFile = chatViewModel::pickContent,- pickResults = chatViewModel.pickResults,+ onPickFiles = chatViewModel::addAttachments,+ onRemoveAttachment = chatViewModel::removeAttachment,+ onSetAttachments = chatViewModel::setAttachments,onSwitchAgent = chatViewModel::switchAgent,onSetAgent = chatViewModel::setAgent,onSetPersona = chatViewModel::setPersona,@@ -895,8 +896,8 @@ class MainActivity : ComponentActivity() {onCreateShareCard = {sharePoster.open(chatViewModel.activeSessionRunSummaries())},- onEditMessage = { id, text, imageBase64, attachment ->- chatViewModel.editMessage(id, text, imageBase64, attachment)+ onEditMessage = { id, text, attachments ->+ chatViewModel.editMessage(id, text, attachments)},onRevertMessage = { id -> chatViewModel.revertTo(id) })diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex 735dd96..9fb9a4d 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -22,9 +22,9 @@ import com.gotcha.data.SettingsRepositoryimport com.gotcha.i18n.Languageimport com.gotcha.i18n.SpokenPhrasesimport com.gotcha.llm.ChatMessage+import com.gotcha.llm.DocumentPartimport com.gotcha.llm.LLMClient-import com.gotcha.llm.documentUserMessage-import com.gotcha.llm.visionUserMessage+import com.gotcha.llm.attachmentsUserMessageimport com.gotcha.marketing.PosterRendererimport com.gotcha.marketing.PosterStatsBuilderimport com.gotcha.marketing.ShareCardClient@@ -52,7 +52,6 @@ import kotlinx.coroutines.flow.updateimport kotlinx.coroutines.launchimport kotlinx.coroutines.withContextimport kotlinx.coroutines.withTimeoutOrNull-import kotlinx.serialization.json.JsonArrayimport kotlinx.serialization.json.JsonPrimitive/**@@ -70,12 +69,58 @@ data class Attachment(val truncated: Boolean = false)-/** Result of the composer's picker: routed to either the image or the document pipeline. */-sealed class PickedFile {- data class Image(val base64: String) : PickedFile()- data class Document(val attachment: Attachment) : PickedFile()+/**+ * One file queued in the composer, or carried by a sent user message. Images are+ * already downscaled to JPEG base64; documents carry their extracted text. The+ * [id] is stable for the life of the attachment, so one can be removed from the+ * composer without disturbing the order of the rest.+ */+sealed class ComposerAttachment {+ abstract val id: String+ abstract val name: String++ @kotlinx.serialization.Serializable+ @kotlinx.serialization.SerialName("image")+ data class Image(+ override val id: String,+ override val name: String,+ val base64: String+ ) : ComposerAttachment()++ @kotlinx.serialization.Serializable+ @kotlinx.serialization.SerialName("document")+ data class Document(+ override val id: String,+ val attachment: Attachment+ ) : ComposerAttachment() {+ override val name: String get() = attachment.name+ }++ companion object {+ /**+ * Files per message. Images are downscaled to ~1024 px JPEG, so ten stay+ * far below every provider's request-size cap; the tighter per-request+ * image caps some providers apply (e.g. Groq's 3) surface as a readable+ * error from [HumanReadableError] instead of being guessed here.+ */+ const val MAX_PER_MESSAGE = 10++ /**+ * Extracted document text across one message. Each document is already+ * capped at [DocumentParser.MAX_EXTRACTED_CHARS]; this keeps several of+ * them from crowding the model's context window.+ */+ const val MAX_TOTAL_DOCUMENT_CHARS = 2 * DocumentParser.MAX_EXTRACTED_CHARS+ }}+/**+ * Transcript labels for a prompt that was only attachments. The composer treats+ * these as empty when a message is edited, so they never become the new prompt.+ */+internal val ATTACHMENT_PLACEHOLDERS = setOf("(image attached)", "(document attached)", "(files attached)")+@kotlinx.serialization.Serializabledata class UiMessage(val id: Long,@@ -85,7 +130,8 @@ data class UiMessage(val subAgentSteps: List<String> = emptyList(),val subAgentCollapsed: Boolean = true,val reasoningContent: String? = null,- val attachment: Attachment? = null+ /** Files the user sent with this message, in the order they were picked. */+ val attachments: List<ComposerAttachment> = emptyList())data class SubAgentStepUi(@@ -137,7 +183,13 @@ data class ChatUiState(val isTranscribing: Boolean = false,val isSpeaking: Boolean = false,val ttsModels: List<AudioModel> = emptyList(),- val sttModels: List<AudioModel> = emptyList()+ val sttModels: List<AudioModel> = emptyList(),+ /**+ * Files queued in the composer until the user taps Send. Held here rather+ * than in the composer's saved state: several base64 images would overflow+ * the saved-instance Bundle.+ */+ val pendingAttachments: List<ComposerAttachment> = emptyList())// In-app chat host: session/UI state, dialogs, and TTS/STT wiring. The agent@@ -492,12 +544,11 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Afun sendMessage(text: String,- imageBase64: String? = null,- attachment: Attachment? = null,+ attachments: List<ComposerAttachment> = emptyList(),isVoiceInput: Boolean = false) {val trimmed = text.trim()- if (trimmed.isEmpty() && imageBase64 == null && attachment == null) return+ if (trimmed.isEmpty() && attachments.isEmpty()) return// One agent runs at a time. Block sending while any run is in flight —// the user can browse other chats but must let the current run finish.if (_uiState.value.isBusy || _uiState.value.runningSessionId != null) return@@ -505,25 +556,22 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), AappendUi(MessageKind.ERROR, "No API key configured. Open settings to add one.")return}- val msg = buildUserMessage(trimmed, imageBase64, attachment)- launchUserRun(msg, imageBase64, attachment, trimmed, isVoiceInput)+ val msg = buildUserMessage(trimmed, attachments)+ launchUserRun(msg, attachments, trimmed, isVoiceInput)}/**- * Builds the LLM user message for the given prompt and optional attachments.- * A document takes precedence over an image (v1 limitation: an attachment is- * one kind per message).+ * Builds the LLM user message for the given prompt and attachments: every+ * document's text joins the prompt in the first text part, and every image+ * follows as its own image part.*/- private fun buildUserMessage(text: String, imageBase64: String?, attachment: Attachment?): ChatMessage = when {- attachment != null -> documentUserMessage(- userText = text,- fileName = attachment.name,- mimeType = attachment.mimeType,- extractedText = attachment.text,- pageCount = attachment.pageCount- )- imageBase64 != null -> visionUserMessage(text, imageBase64, "jpeg")- else -> ChatMessage(role = "user", content = JsonPrimitive(text))+ private fun buildUserMessage(text: String, attachments: List<ComposerAttachment>): ChatMessage {+ if (attachments.isEmpty()) return ChatMessage(role = "user", content = JsonPrimitive(text))+ val documents = attachments.filterIsInstance<ComposerAttachment.Document>().map {+ DocumentPart(it.attachment.name, it.attachment.mimeType, it.attachment.text, it.attachment.pageCount)+ }+ val images = attachments.filterIsInstance<ComposerAttachment.Image>().map { it.base64 }+ return attachmentsUserMessage(text, documents, images, imageFormat = "jpeg")}/**@@ -533,8 +581,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A*/private fun launchUserRun(msg: ChatMessage,- imageBase64: String?,- attachment: Attachment?,+ attachments: List<ComposerAttachment>,userText: String,isVoiceInput: Boolean) {@@ -550,9 +597,8 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), AagentEngine.history += msgappendEngineUi(MessageKind.USER,- userDisplayText(userText, msg, attachment),- imageBase64,- attachment = attachment+ userDisplayText(userText, msg, attachments),+ attachments = attachments)val runningId = agentEngine.sessionId ?: return@launch@@ -562,14 +608,17 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A/*** The transcript label for a sent message: the prompt text, or a placeholder- * when the message is attachment-only. Document messages show the prompt- * rather than the extracted body; images keep their historical behavior- * (the message's text part, default prompt when blank).+ * when the message is attachment-only. Messages with documents show the+ * prompt rather than the extracted bodies; image-only messages keep their+ * historical behavior (the message's text part, default prompt when blank).*/- private fun userDisplayText(userText: String, msg: ChatMessage, attachment: Attachment?): String = when {- attachment != null -> userText.ifEmpty { "(document attached)" }- else -> msg.textContent- }+ private fun userDisplayText(userText: String, msg: ChatMessage, attachments: List<ComposerAttachment>): String =+ when {+ attachments.none { it is ComposerAttachment.Document } -> msg.textContent+ else -> userText.ifEmpty {+ if (attachments.size == 1) "(document attached)" else "(files attached)"+ }+ }/*** The user's prompt portion of a document message's text part, or null when@@ -578,11 +627,28 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A* the user's own words.*/private fun documentPromptText(content: String): String? {- val marker = "\n[Attached file:"- val index = content.indexOf(marker)+ val index = content.indexOf(ATTACHED_FILE_MARKER)return if (index >= 0) content.substring(0, index).trim() else null}+ /** How many `[Attached file: …]` sections a user message's text part carries. */+ private fun countAttachedFiles(content: String): Int =+ content.split(ATTACHED_FILE_MARKER).size - 1++ /**+ * The export's note for a user message's attachments, e.g. "Image attached"+ * or "3 images, 1 document attached"; null when there are none.+ */+ private fun exportAttachmentLabel(documents: Int, images: Int): String? = when {+ documents == 0 && images == 0 -> null+ documents == 1 && images == 0 -> "Document attached"+ documents == 0 && images == 1 -> "Image attached"+ else -> listOfNotNull(+ images.takeIf { it > 0 }?.let { plural(it, "image") },+ documents.takeIf { it > 0 }?.let { plural(it, "document") }+ ).joinToString(", ") + " attached"+ }+/** Busy-marking + agent run + NonCancellable cleanup, from the old sendMessage body. */private suspend fun executeRun(agent: AgentMode, runningId: String) {val runningTitle = engineTranscript.firstOrNull { it.kind == MessageKind.USER }@@ -629,15 +695,15 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A}/**- * Replaces the user message [targetId] with [newText], keeping the original- * image attachment unless a new one was picked. The target's whole turn and+ * Replaces the user message [targetId] with [newText] and [attachments]; a+ * null [attachments] keeps the ones the original message was sent with. The target's whole turn and* everything after it are dropped from both the LLM history and the on-screen* transcript, then the agent re-runs immediately so a fresh reply is* generated from the edited history.*/- fun editMessage(targetId: Long, newText: String, imageBase64: String?, attachment: Attachment? = null) {+ fun editMessage(targetId: Long, newText: String, attachments: List<ComposerAttachment>? = null) {val trimmed = newText.trim()- if (trimmed.isEmpty() && imageBase64 == null && attachment == null) return+ if (trimmed.isEmpty() && attachments.isNullOrEmpty()) returnif (_uiState.value.isBusy || _uiState.value.runningSessionId != null) returnif (client == null) {appendUi(MessageKind.ERROR, "No API key configured. Open settings to add one.")@@ -676,17 +742,15 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A}// Never promote undone work on the share card.agentEngine.restoreRunSummaries(emptyList())- val editImage = imageBase64 ?: target.imageBase64// A previously-sent document keeps its extracted text (the file grant is// long gone); a newly-picked one carries its own.- val editAttachment = attachment ?: target.attachment- val msg = buildUserMessage(trimmed, editImage, editAttachment)+ val editAttachments = attachments ?: target.attachments+ val msg = buildUserMessage(trimmed, editAttachments)agentEngine.history += msgappendEngineUi(MessageKind.USER,- userDisplayText(trimmed, msg, editAttachment),- editImage,- attachment = editAttachment+ userDisplayText(trimmed, msg, editAttachments),+ attachments = editAttachments)executeRun(engineAgent, agentEngine.sessionId ?: return@launch)}@@ -819,57 +883,105 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A}/**- * Result of the composer's "+" pick, delivered asynchronously once the file- * has been read and parsed off the main thread. `null` means a failed pick- * (an ERROR bubble is appended first).+ * Entry point for the composer's "+" button. Each picked file is read and+ * parsed on [Dispatchers.IO] in the order it was picked, then appended to+ * [ChatUiState.pendingAttachments] — nothing already queued is replaced, and+ * nothing is sent until the user taps Send. Images reuse the image pipeline;+ * anything else goes through [loadDocument]. Files that fail to load, or that+ * would go past [ComposerAttachment.MAX_PER_MESSAGE] or+ * [ComposerAttachment.MAX_TOTAL_DOCUMENT_CHARS], are skipped with an ERROR+ * bubble saying why; the rest are still added.*/- private val _pickResults = MutableSharedFlow<PickedFile?>(extraBufferCapacity = 1)- val pickResults: SharedFlow<PickedFile?> = _pickResults.asSharedFlow()-- /**- * Entry point for the composer's "+" button. Routes by content type: images- * reuse the image pipeline; anything else goes through [loadDocument]. The- * read + parse runs on [Dispatchers.IO] so a large document never blocks the- * main thread; a failure surfaces as an ERROR bubble and the result (or- * null) is delivered on [pickResults].- */- fun pickContent(uri: Uri) {+ fun addAttachments(uris: List<Uri>) {+ if (uris.isEmpty()) returnviewModelScope.launch {- val (picked, error) = withContext(Dispatchers.IO) {- try {- val resolver = getApplication<Application>().contentResolver- val mime = resolver.getType(uri)- val picked = if (mime?.startsWith("image/") == true) {- loadImageBase64(uri)?.let { PickedFile.Image(it) }- } else {- loadDocument(uri)?.let { PickedFile.Document(it) }+ val room = ComposerAttachment.MAX_PER_MESSAGE - _uiState.value.pendingAttachments.size+ val toLoad = uris.take(room.coerceAtLeast(0))+ val loaded = withContext(Dispatchers.IO) { toLoad.map { loadAttachment(it) } }+ // Back on the main dispatcher. Re-check against the queue as it is now,+ // since another pick may have landed while these were loading.+ val errors = loaded.mapNotNull { it.exceptionOrNull()?.message }.toMutableList()+ var overCount = 0+ var overText = 0+ _uiState.update { state ->+ // update may retry this block, so the counts start over each time.+ overCount = uris.size - toLoad.size+ overText = 0+ val queue = state.pendingAttachments.toMutableList()+ var docChars = queue.documentChars()+ for (attachment in loaded.mapNotNull { it.getOrNull() }) {+ val chars = (attachment as? ComposerAttachment.Document)?.attachment?.text?.length ?: 0+ when {+ queue.size >= ComposerAttachment.MAX_PER_MESSAGE -> overCount+++ docChars + chars > ComposerAttachment.MAX_TOTAL_DOCUMENT_CHARS -> overText+++ else -> {+ queue += attachment+ docChars += chars+ }}- // Both loaders return null when the stream cannot be opened;- // treat that like any other failed pick so the user gets a- // visible error instead of a silent no-op.- if (picked != null) picked to null else null to "Could not read that file."- } catch (e: CancellationException) {- throw e- } catch (e: DocumentError) {- null to (e.message ?: "Could not read that file.")- } catch (e: Exception) {- null to "Could not read that file: ${HumanReadableError.format(e)}"}+ state.copy(pendingAttachments = queue)+ }+ if (overCount > 0) {+ errors += "You can attach up to ${ComposerAttachment.MAX_PER_MESSAGE} files per message — " ++ "skipped ${plural(overCount, "file")}."}- // Back on the main dispatcher: the error bubble lands before the pick- // result so a failed attachment explains itself in the transcript.- if (error != null) appendUi(MessageKind.ERROR, error)- _pickResults.tryEmit(picked)+ if (overText > 0) {+ errors += "The attached documents are too long to send together — " ++ "skipped ${plural(overText, "document")}. Send them in separate messages."+ }+ errors.forEach { appendUi(MessageKind.ERROR, it) }}}+ /** Removes one queued attachment from the composer. */+ fun removeAttachment(id: String) {+ _uiState.update { state -> state.copy(pendingAttachments = state.pendingAttachments.filterNot { it.id == id }) }+ }++ /** Replaces the composer's queue, e.g. with a message's attachments when it is edited. */+ fun setAttachments(attachments: List<ComposerAttachment>) {+ _uiState.update { it.copy(pendingAttachments = attachments) }+ }++ fun clearAttachments() = setAttachments(emptyList())++ private fun List<ComposerAttachment>.documentChars(): Int =+ sumOf { (it as? ComposerAttachment.Document)?.attachment?.text?.length ?: 0 }++ private fun plural(count: Int, noun: String): String = if (count == 1) "1 $noun" else "$count ${noun}s"++ /**+ * Reads one picked file into an attachment. A failure carries the message to+ * show the user, so one unreadable file never costs the rest of the pick.+ */+ private fun loadAttachment(uri: Uri): Result<ComposerAttachment> = try {+ val resolver = getApplication<Application>().contentResolver+ val id = java.util.UUID.randomUUID().toString()+ val attachment = if (resolver.getType(uri)?.startsWith("image/") == true) {+ loadImageBase64(uri)?.let { ComposerAttachment.Image(id, queryDisplayName(resolver, uri, "image"), it) }+ } else {+ loadDocument(uri)?.let { ComposerAttachment.Document(id, it) }+ }+ // Both loaders return null when the stream cannot be opened; treat that+ // like any other failed pick so the user gets a visible error instead of+ // a silent no-op.+ if (attachment != null) Result.success(attachment) else Result.failure(Exception("Could not read that file."))+ } catch (e: CancellationException) {+ throw e+ } catch (e: DocumentError) {+ Result.failure(Exception(e.message ?: "Could not read that file."))+ } catch (e: Exception) {+ Result.failure(Exception("Could not read that file: ${HumanReadableError.format(e)}"))+ }+/*** Load a document from a content:// URI: read the bytes and extract the text* via [DocumentParser]. The extracted text is carried on the returned* [Attachment], so the transient picker read grant is never needed again and* nothing is copied into the app cache. Returns null only when the stream* cannot be opened; unreadable/unsupported content throws [DocumentError],- * which [pickContent] surfaces as an ERROR bubble on the main thread.+ * which [addAttachments] surfaces as an ERROR bubble on the main thread.*/private fun loadDocument(uri: Uri): Attachment? {val app = getApplication<Application>()@@ -887,7 +999,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A)}- private fun queryDisplayName(resolver: ContentResolver, uri: Uri): String {+ private fun queryDisplayName(resolver: ContentResolver, uri: Uri, fallback: String = "document"): String {return try {resolver.query(uri, null, null, null, null)?.use { cursor ->if (!cursor.moveToFirst()) return@use null@@ -896,7 +1008,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A}} catch (_: Exception) {null- }?.takeIf { it.isNotBlank() } ?: "document"+ }?.takeIf { it.isNotBlank() } ?: fallback}fun stopAgent() {@@ -1380,7 +1492,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Akind: MessageKind,text: String,imageBase64: String? = null,- attachment: Attachment? = null,+ attachments: List<ComposerAttachment> = emptyList(),subAgentSteps: List<String> = emptyList(),reasoningContent: String? = null) {@@ -1395,7 +1507,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), AsubAgentSteps = subAgentSteps,subAgentCollapsed = true,reasoningContent = reasoningContent,- attachment = attachment+ attachments = attachments)engineTranscript = engineTranscript + messageif (viewing) {@@ -1499,13 +1611,10 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A"user" -> {val docPrompt = documentPromptText(text)sb.appendLine("### User")- if (docPrompt != null) {- if (docPrompt.isNotBlank()) sb.appendLine(docPrompt)- sb.appendLine("*(Document attached)*")- } else {- if (text.isNotBlank()) sb.appendLine(text)- if (msg.content is JsonArray) sb.appendLine("*(Image attached)*")- }+ val prompt = docPrompt ?: text+ if (prompt.isNotBlank()) sb.appendLine(prompt)+ exportAttachmentLabel(documents = countAttachedFiles(text), images = msg.imageCount)+ ?.let { sb.appendLine("*($it)*") }sb.appendLine()}"assistant" -> {@@ -1616,6 +1725,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Aprivate companion object {const val GATE_TIMEOUT_MS = 120_000L++ /** Starts each document section in a user message; see [documentPromptText]. */+ const val ATTACHED_FILE_MARKER = "\n[Attached file:"const val MIGRATED_CHAT_DIRS_KEY = "migrated_chat_dirs_v1"}}diff --git a/app/src/main/java/com/gotcha/llm/Models.kt b/app/src/main/java/com/gotcha/llm/Models.ktindex 08de628..bd9d35a 100644--- a/app/src/main/java/com/gotcha/llm/Models.kt+++ b/app/src/main/java/com/gotcha/llm/Models.kt@@ -47,6 +47,11 @@ data class ChatMessage(/** True when this message carries an image (vision) part. */val hasImage: Boolean get() = imageUrl() != null+ /** How many image (vision) parts this message carries. */+ val imageCount: Int get() = (content as? JsonArray)?.count { part ->+ ((part as? JsonObject)?.get("type") as? JsonPrimitive)?.content == "image_url"+ } ?: 0+/*** The data URI of this message's first image part (e.g.* "data:image/jpeg;base64,…"), or null when there is no image part.@@ -102,20 +107,68 @@ fun documentUserMessage(extractedText: String,pageCount: Int? = null): ChatMessage {+ val text = listOf(+ userText.ifBlank { "Answer questions about the attached file." },+ documentSection(DocumentPart(fileName, mimeType, extractedText, pageCount))+ ).joinToString("\n\n")+ return ChatMessage(+ role = "user",+ content = buildJsonArray {+ add(+ buildJsonObject {+ put("type", "text")+ put("text", text)+ }+ )+ }+ )+}++/** A document to inline into a user message: its name, type and extracted text. */+data class DocumentPart(+ val fileName: String,+ val mimeType: String,+ val extractedText: String,+ val pageCount: Int? = null+)++/** The `[Attached file: …]` header and extracted body for one document. */+private fun documentSection(doc: DocumentPart): String {val header = buildString {- append("[Attached file: $fileName")- append(if (mimeType.isNotBlank()) " ($mimeType" else " (document")- pageCount?.let { append(", $it pages") }+ append("[Attached file: ${doc.fileName}")+ append(if (doc.mimeType.isNotBlank()) " (${doc.mimeType}" else " (document")+ doc.pageCount?.let { append(", $it pages") }append(")]")}- val body = extractedText.ifBlank {+ val body = doc.extractedText.ifBlank {"(The document could not be read — ask the user for the details.)"}- val text = listOf(- userText.ifBlank { "Answer questions about the attached file." },- header,- body- ).joinToString("\n\n")+ return "$header\n\n$body"+}++/**+ * Build a user message carrying any number of documents and images, in the+ * order the user picked them within each kind.+ *+ * The prompt and every document's header + body share the FIRST text part, for+ * the same reason as [documentUserMessage]: [ChatMessage.textContent] only reads+ * that part. Each image then follows as its own `image_url` part, so the model+ * receives every image separately.+ */+fun attachmentsUserMessage(+ userText: String,+ documents: List<DocumentPart>,+ imagesBase64: List<String>,+ imageFormat: String = "jpeg"+): ChatMessage {+ val prompt = userText.ifBlank {+ when {+ documents.isNotEmpty() -> "Answer questions about the attached files."+ imagesBase64.size > 1 -> "What is in these images?"+ else -> "What is in this image?"+ }+ }+ val text = (listOf(prompt) + documents.map(::documentSection)).joinToString("\n\n")return ChatMessage(role = "user",content = buildJsonArray {@@ -125,6 +178,14 @@ fun documentUserMessage(put("text", text)})+ for (base64 in imagesBase64) {+ add(+ buildJsonObject {+ put("type", "image_url")+ putJsonObject("image_url") { put("url", "data:image/$imageFormat;base64,$base64") }+ }+ )+ }})}diff --git a/app/src/main/java/com/gotcha/ui/AttachmentViews.kt b/app/src/main/java/com/gotcha/ui/AttachmentViews.ktnew file mode 100644index 0000000..30c4f0d--- /dev/null+++ b/app/src/main/java/com/gotcha/ui/AttachmentViews.kt@@ -0,0 +1,239 @@+package com.gotcha.ui++import android.graphics.Bitmap+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+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.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Close+import androidx.compose.material.icons.filled.InsertDriveFile+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import com.gotcha.agent.Attachment+import com.gotcha.agent.ComposerAttachment+import com.gotcha.tools.FileResolver+import com.gotcha.ui.theme.LocalSkin++/** Decodes an attachment's base64 JPEG once per image, or null if it is unreadable. */+@Composable+private fun rememberThumbnail(base64: String): Bitmap? = remember(base64) {+ try {+ val bytes = android.util.Base64.decode(base64, android.util.Base64.DEFAULT)+ android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size)+ } catch (_: Exception) {+ null+ }+}++/**+ * The composer's queue of files waiting for Send, in picked order: image+ * thumbnails and document chips, each with its own remove button, plus a count+ * against [ComposerAttachment.MAX_PER_MESSAGE].+ */+@Composable+fun ComposerAttachmentStrip(+ attachments: List<ComposerAttachment>,+ onRemove: (String) -> Unit+) {+ val skin = LocalSkin.current+ Column(modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp)) {+ LazyRow(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ contentPadding = PaddingValues(horizontal = 12.dp),+ modifier = Modifier.testTag("composer_attachments")+ ) {+ items(attachments, key = { it.id }) { attachment ->+ when (attachment) {+ is ComposerAttachment.Image -> Box {+ val bitmap = rememberThumbnail(attachment.base64)+ if (bitmap != null) {+ Image(+ bitmap = bitmap.asImageBitmap(),+ contentDescription = attachment.name,+ modifier = Modifier+ .size(72.dp)+ .clip(RoundedCornerShape(skin.cornerSmall)),+ contentScale = ContentScale.Crop+ )+ } else {+ Box(+ modifier = Modifier+ .size(72.dp)+ .clip(RoundedCornerShape(skin.cornerSmall))+ .background(MaterialTheme.colorScheme.secondaryContainer)+ )+ }+ RemoveButton(+ name = attachment.name,+ onClick = { onRemove(attachment.id) },+ modifier = Modifier.align(Alignment.TopEnd)+ )+ }+ is ComposerAttachment.Document -> Row(+ modifier = Modifier+ .width(200.dp)+ .height(72.dp)+ .clip(RoundedCornerShape(skin.cornerSmall))+ .background(MaterialTheme.colorScheme.secondaryContainer)+ .padding(start = 10.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ DocumentSummary(+ attachment = attachment.attachment,+ color = MaterialTheme.colorScheme.onSecondaryContainer,+ modifier = Modifier.weight(1f)+ )+ IconButton(onClick = { onRemove(attachment.id) }) {+ Icon(+ Icons.Default.Close,+ contentDescription = "Remove ${attachment.name}",+ tint = MaterialTheme.colorScheme.onSecondaryContainer+ )+ }+ }+ }+ }+ }+ Text(+ "${attachments.size} / ${ComposerAttachment.MAX_PER_MESSAGE} files",+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(start = 16.dp, top = 2.dp)+ )+ }+}++/** Small round ✕ laid over an image thumbnail. */+@Composable+private fun RemoveButton(name: String, onClick: () -> Unit, modifier: Modifier = Modifier) {+ IconButton(onClick = onClick, modifier = modifier.size(28.dp)) {+ Box(+ modifier = Modifier+ .size(20.dp)+ .clip(CircleShape)+ .background(Color.Black.copy(alpha = 0.6f)),+ contentAlignment = Alignment.Center+ ) {+ Icon(+ Icons.Default.Close,+ contentDescription = "Remove $name",+ tint = Color.White,+ modifier = Modifier.size(14.dp)+ )+ }+ }+}++/**+ * The files a sent user message carried: images first (one full-width, or a+ * scrolling row of thumbnails when there are several), then a chip per document.+ */+@Composable+fun SentAttachments(attachments: List<ComposerAttachment>, contentColor: Color) {+ val skin = LocalSkin.current+ val images = attachments.filterIsInstance<ComposerAttachment.Image>()+ val documents = attachments.filterIsInstance<ComposerAttachment.Document>()+ if (images.size == 1) {+ SentImage(images.single(), Modifier.fillMaxWidth(), 160.dp, ContentScale.Fit)+ } else if (images.size > 1) {+ Row(+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ modifier = Modifier.horizontalScroll(rememberScrollState())+ ) {+ images.forEach { SentImage(it, Modifier.size(120.dp), 120.dp, ContentScale.Crop) }+ }+ }+ documents.forEachIndexed { index, document ->+ if (index > 0 || images.isNotEmpty()) Spacer(modifier = Modifier.height(6.dp))+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .clip(RoundedCornerShape(skin.cornerSmall))+ .background(contentColor.copy(alpha = 0.08f))+ .padding(horizontal = 10.dp, vertical = 8.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ DocumentSummary(document.attachment, contentColor, Modifier.weight(1f))+ }+ }+}++@Composable+private fun SentImage(image: ComposerAttachment.Image, modifier: Modifier, height: Dp, scale: ContentScale) {+ val bitmap = rememberThumbnail(image.base64) ?: return+ Image(+ bitmap = bitmap.asImageBitmap(),+ contentDescription = image.name,+ modifier = modifier+ .height(height)+ .clip(RoundedCornerShape(8.dp)),+ contentScale = scale+ )+}++/** File icon, name, and "type · size" line for a document attachment. */+@Composable+private fun DocumentSummary(attachment: Attachment, color: Color, modifier: Modifier = Modifier) {+ Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) {+ Icon(+ Icons.Filled.InsertDriveFile,+ contentDescription = null,+ modifier = Modifier.size(18.dp),+ tint = color.copy(alpha = 0.7f)+ )+ Spacer(modifier = Modifier.width(8.dp))+ Column {+ Text(+ attachment.name,+ style = MaterialTheme.typography.labelMedium,+ fontWeight = FontWeight.Medium,+ color = color,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ Text(+ buildString {+ append(attachment.mimeType.ifBlank { "document" })+ append(" · ")+ append(FileResolver.formatSizeStatic(attachment.size))+ if (attachment.truncated) append(" · truncated")+ },+ style = MaterialTheme.typography.bodySmall,+ color = color.copy(alpha = 0.7f),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+ }+}diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.ktindex 9d549e8..8f97eb4 100644--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt@@ -32,9 +32,7 @@ import androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.automirrored.filled.Sendimport androidx.compose.material.icons.automirrored.rounded.VolumeOffimport androidx.compose.material.icons.automirrored.rounded.VolumeUp-import androidx.compose.material.icons.filled.Closeimport androidx.compose.material.icons.filled.Edit-import androidx.compose.material.icons.filled.InsertDriveFileimport androidx.compose.material.icons.filled.Menuimport androidx.compose.material.icons.filled.Micimport androidx.compose.material.icons.filled.Share@@ -62,7 +60,6 @@ import androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember-import androidx.compose.runtime.saveable.Saverimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignment@@ -70,10 +67,8 @@ import androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.draw.shadowimport androidx.compose.ui.graphics.Color-import androidx.compose.ui.graphics.asImageBitmapimport androidx.compose.ui.graphics.compositeOverimport androidx.compose.ui.graphics.vector.ImageVector-import androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.testTagimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.text.font.FontWeight@@ -81,44 +76,32 @@ import androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport com.gotcha.R-import com.gotcha.agent.Attachment+import com.gotcha.agent.ATTACHMENT_PLACEHOLDERSimport com.gotcha.agent.ChatUiState-import com.gotcha.agent.PickedFile+import com.gotcha.agent.ComposerAttachmentimport com.gotcha.tools.AgentMode-import com.gotcha.tools.FileResolverimport com.gotcha.ui.theme.GotchaMonoimport com.gotcha.ui.theme.LocalSkinimport com.gotcha.ui.theme.SkinAlertDialogimport com.gotcha.ui.theme.SkinDropdownMenuimport com.gotcha.ui.theme.motionSpecimport kotlinx.coroutines.delay-import kotlinx.coroutines.flow.Flow-import kotlinx.serialization.json.Jsonimport androidx.compose.foundation.Image as ComposeImage-/** rememberSaveable saver for [Attachment]: JSON-encoded so rotation and process death keep it. */-private val AttachmentSaver = Saver<Attachment?, String>(- save = { attachment -> attachment?.let { Json.encodeToString(Attachment.serializer(), it) } },- restore = { encoded ->- encoded?.let {- runCatching { Json.decodeFromString(Attachment.serializer(), it) }.getOrNull()- }- }-)-@OptIn(ExperimentalMaterial3Api::class)@Composablefun ChatScreen(state: ChatUiState,- onSend: (String, String?, Attachment?, Boolean) -> Unit,+ onSend: (String, List<ComposerAttachment>, Boolean) -> Unit,onStop: () -> Unit,onConfirm: (Boolean) -> Unit,onAnswer: (String?) -> Unit,onOpenDrawer: () -> Unit,onOpenSettings: () -> Unit,sessionTitle: String? = null,- onPickFile: (Uri) -> Unit,- pickResults: Flow<PickedFile?>,+ onPickFiles: (List<Uri>) -> Unit,+ onRemoveAttachment: (String) -> Unit,+ onSetAttachments: (List<ComposerAttachment>) -> Unit,onSwitchAgent: () -> Unit,onSetAgent: (AgentMode) -> Unit = {},onSetPersona: (Persona?) -> Unit = {},@@ -129,7 +112,7 @@ fun ChatScreen(onExportChat: () -> Unit = {},onReturnToRunning: () -> Unit = {},onCreateShareCard: () -> Unit = {},- onEditMessage: (Long, String, String?, Attachment?) -> Unit = { _, _, _, _ -> },+ onEditMessage: (Long, String, List<ComposerAttachment>) -> Unit = { _, _, _ -> },onRevertMessage: (Long) -> Unit = { _ -> }) {val skin = LocalSkin.current@@ -140,10 +123,7 @@ fun ChatScreen(state.runningSessionId != state.activeSessionIdvar input by rememberSaveable { mutableStateOf("") }var inputWasVoice by rememberSaveable { mutableStateOf(false) }- var pendingImageBase64 by rememberSaveable { mutableStateOf<String?>(null) }- var pendingAttachment by rememberSaveable(stateSaver = AttachmentSaver) {- mutableStateOf<Attachment?>(null)- }+ val pendingAttachments = state.pendingAttachments// Id of the user message being edited (composer pre-filled until sent/cancelled).var editingMessageId by rememberSaveable { mutableStateOf<Long?>(null) }// Id of the user message pending a revert confirmation.@@ -158,29 +138,12 @@ fun ChatScreen(}val animatedIds = remember(state.activeSessionId) { mutableSetOf<Long>() }+ // Picked files are read/parsed off the main thread and queued on the+ // ViewModel (see ChatViewModel.addAttachments); they arrive via state.val filePickerLauncher = rememberLauncherForActivityResult(- contract = ActivityResultContracts.GetContent()- ) { uri: Uri? ->- if (uri != null) onPickFile(uri)- }-- // The picked file is read/parsed off the main thread (see ChatViewModel.pickContent);- // apply the result to the composer as soon as it arrives.- LaunchedEffect(Unit) {- pickResults.collect { picked ->- when (picked) {- is PickedFile.Image -> {- pendingImageBase64 = picked.base64- pendingAttachment = null- }- is PickedFile.Document -> {- pendingImageBase64 = null- pendingAttachment = picked.attachment- }- // A failed pick already surfaced its own error bubble.- null -> {}- }- }+ contract = ActivityResultContracts.GetMultipleContents()+ ) { uris: List<Uri> ->+ onPickFiles(uris)}LaunchedEffect(state.messages.size) {@@ -413,16 +376,11 @@ fun ChatScreen(onStopSpeaking = onStopSpeaking,onEdit = { target ->editingMessageId = target.id- // "(image attached)"/"(document attached)" are the display- // placeholders for attachment-only prompts; leave the- // composer empty for those.- input = when (target.text) {- "(image attached)", "(document attached)" -> ""- else -> target.text- }+ // The display placeholders for attachment-only prompts+ // leave the composer empty.+ input = if (target.text in ATTACHMENT_PLACEHOLDERS) "" else target.textinputWasVoice = false- pendingImageBase64 = target.imageBase64- pendingAttachment = target.attachment+ onSetAttachments(target.attachments)},onRevert = { target -> pendingRevertId = target.id })@@ -520,87 +478,11 @@ 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(skin.cornerSmall)),- contentScale = ContentScale.Fit- )- }- IconButton(- onClick = {- pendingImageBase64 = null- },- modifier = Modifier.align(Alignment.TopEnd)- ) {- Icon(Icons.Default.Close, contentDescription = "Remove image")- }- }- }-- // Document attachment preview chip- pendingAttachment?.let { attachment ->- Row(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 12.dp, vertical = 2.dp)- .clip(RoundedCornerShape(skin.cornerSmall))- .background(MaterialTheme.colorScheme.secondaryContainer)- .padding(start = 12.dp, end = 4.dp, top = 6.dp, bottom = 6.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Icon(- Icons.Filled.InsertDriveFile,- contentDescription = null,- modifier = Modifier.size(20.dp),- tint = MaterialTheme.colorScheme.onSecondaryContainer- )- Spacer(modifier = Modifier.width(10.dp))- Column(modifier = Modifier.weight(1f)) {- Text(- attachment.name,- style = MaterialTheme.typography.labelMedium,- fontWeight = FontWeight.Medium,- color = MaterialTheme.colorScheme.onSecondaryContainer,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- Text(- buildString {- append(attachment.mimeType.ifBlank { "document" })- append(" · ")- append(FileResolver.formatSizeStatic(attachment.size))- if (attachment.truncated) append(" · truncated")- },- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.7f),- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- }- IconButton(onClick = { pendingAttachment = null }) {- Icon(- Icons.Default.Close,- contentDescription = "Remove attachment",- tint = MaterialTheme.colorScheme.onSecondaryContainer- )- }- }+ if (pendingAttachments.isNotEmpty()) {+ ComposerAttachmentStrip(+ attachments = pendingAttachments,+ onRemove = onRemoveAttachment+ )}if (state.isSpeaking) {@@ -681,8 +563,7 @@ fun ChatScreen(TextButton(onClick = {editingMessageId = null- pendingImageBase64 = null- pendingAttachment = null+ onSetAttachments(emptyList())input = ""inputWasVoice = false}@@ -709,7 +590,8 @@ fun ChatScreen() {IconButton(onClick = { filePickerLauncher.launch("*/*") },- enabled = !state.isBusy && state.isConfigured && !otherChatRunning+ enabled = !state.isBusy && state.isConfigured && !otherChatRunning &&+ pendingAttachments.size < ComposerAttachment.MAX_PER_MESSAGE) {Text("+", style = MaterialTheme.typography.titleLarge)}@@ -800,7 +682,7 @@ fun ChatScreen(CircularProgressIndicator(modifier = Modifier.size(20.dp))}}- input.isBlank() && pendingImageBase64 == null && pendingAttachment == null &&+ input.isBlank() && pendingAttachments.isEmpty() &&editingMessageId == null -> {IconButton(onClick = onStartListening,@@ -815,19 +697,18 @@ fun ChatScreen(onClick = {val editTarget = editingMessageIdif (editTarget != null) {- onEditMessage(editTarget, input, pendingImageBase64, pendingAttachment)+ onEditMessage(editTarget, input, pendingAttachments)} else {- onSend(input, pendingImageBase64, pendingAttachment, inputWasVoice)+ onSend(input, pendingAttachments, inputWasVoice)}editingMessageId = nullinput = ""inputWasVoice = false- pendingImageBase64 = null- pendingAttachment = null+ onSetAttachments(emptyList())},modifier = Modifier.size(40.dp).testTag("send_button"),enabled = state.isConfigured && !otherChatRunning &&- (input.isNotBlank() || pendingImageBase64 != null || pendingAttachment != null)+ (input.isNotBlank() || pendingAttachments.isNotEmpty())) {Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send")}diff --git a/app/src/main/java/com/gotcha/ui/MessageBubble.kt b/app/src/main/java/com/gotcha/ui/MessageBubble.ktindex 5cf891d..adbcd36 100644--- a/app/src/main/java/com/gotcha/ui/MessageBubble.kt+++ b/app/src/main/java/com/gotcha/ui/MessageBubble.kt@@ -28,7 +28,6 @@ import androidx.compose.material.icons.automirrored.rounded.VolumeOffimport androidx.compose.material.icons.automirrored.rounded.VolumeUpimport androidx.compose.material.icons.filled.ExpandLessimport androidx.compose.material.icons.filled.ExpandMore-import androidx.compose.material.icons.filled.InsertDriveFileimport androidx.compose.material3.DropdownMenuItemimport androidx.compose.material3.HorizontalDividerimport androidx.compose.material3.Icon@@ -166,45 +165,8 @@ fun MessageBubble()}}- message.attachment?.let { attachment ->- Row(- modifier = Modifier- .fillMaxWidth()- .clip(RoundedCornerShape(skin.cornerSmall))- .background(contentColor.copy(alpha = 0.08f))- .padding(horizontal = 10.dp, vertical = 8.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Icon(- Icons.Filled.InsertDriveFile,- contentDescription = null,- modifier = Modifier.size(18.dp),- tint = contentColor.copy(alpha = 0.7f)- )- Spacer(modifier = Modifier.width(8.dp))- Column(modifier = Modifier.weight(1f)) {- Text(- attachment.name,- style = MaterialTheme.typography.labelMedium,- fontWeight = FontWeight.Medium,- color = contentColor,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- Text(- buildString {- append(attachment.mimeType.ifBlank { "document" })- append(" · ")- append(com.gotcha.tools.FileResolver.formatSizeStatic(attachment.size))- if (attachment.truncated) append(" · truncated")- },- style = MaterialTheme.typography.bodySmall,- color = contentColor.copy(alpha = 0.7f),- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- }- }+ if (message.attachments.isNotEmpty()) {+ SentAttachments(message.attachments, contentColor)}message.reasoningContent?.let { reasoning ->var reasoningExpanded by remember { mutableStateOf(false) }diff --git a/app/src/main/java/com/gotcha/util/HumanReadableError.kt b/app/src/main/java/com/gotcha/util/HumanReadableError.ktindex 39bc2da..c7c6448 100644--- a/app/src/main/java/com/gotcha/util/HumanReadableError.kt+++ b/app/src/main/java/com/gotcha/util/HumanReadableError.kt@@ -17,8 +17,22 @@ import java.net.UnknownHostException*/object HumanReadableError {- /** Maps HTTP status codes to human-readable explanations. */- fun fromHttpCode(code: Int, rawMessage: String? = null): String = when (code) {+ /**+ * Maps HTTP status codes to human-readable explanations. A rejection that+ * names images (e.g. a provider allowing fewer images per request than the+ * user attached) gets its own explanation, since the fix is on the user's side.+ */+ fun fromHttpCode(code: Int, rawMessage: String? = null): String = when {+ code in IMAGE_REJECTION_CODES && rawMessage?.contains("image", ignoreCase = true) == true ->+ "The model rejected the attached images (HTTP $code): $rawMessage. " ++ "It may accept fewer or smaller images per request — images from earlier in " ++ "this chat count too. Remove some attachments or start a new chat, then try again."+ else -> fromHttpCodeOnly(code, rawMessage)+ }++ private val IMAGE_REJECTION_CODES = setOf(400, 413, 422)++ private fun fromHttpCodeOnly(code: Int, rawMessage: String?): String = when (code) {400 -> "Bad request (HTTP 400). The request format or parameters sent to the API were invalid."401 -> "Authentication failed (HTTP 401). Please check your API key in Settings."403 -> {@@ -31,6 +45,7 @@ object HumanReadableError {}404 -> "Resource not found (HTTP 404). Check if the selected model ID or endpoint URL is correct in Settings."408 -> "Request timeout (HTTP 408). The server timed out waiting for the request."+ 413 -> "Request too large (HTTP 413). Try sending fewer or smaller attachments."429 -> "Rate limit or quota exceeded (HTTP 429). Please wait a moment or check your API usage limits."500 -> "Server error (HTTP 500). The remote AI service encountered an internal error. Please try again."502 -> "Bad gateway (HTTP 502). The proxy or upstream service received an invalid response."diff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelAttachmentTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelAttachmentTest.ktindex 61197e8..5bfdce1 100644--- a/app/src/test/java/com/gotcha/agent/ChatViewModelAttachmentTest.kt+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelAttachmentTest.kt@@ -1,6 +1,7 @@package com.gotcha.agentimport android.app.Application+import android.graphics.Bitmapimport android.net.Uriimport androidx.test.core.app.ApplicationProviderimport com.gotcha.data.LlmProvider@@ -8,24 +9,23 @@ import com.gotcha.data.Settingsimport com.gotcha.data.SettingsRepositoryimport com.gotcha.llm.ChatMessageimport com.gotcha.testsupport.FakeAndroidKeyStore-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.flow.first-import kotlinx.coroutines.launch-import kotlinx.coroutines.withTimeoutOrNull+import com.gotcha.testsupport.FakeFilesProvider+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitiveimport org.junit.Assert.assertEquals-import org.junit.Assert.assertNullimport org.junit.Assert.assertTrueimport org.junit.Beforeimport org.junit.Testimport org.junit.runner.RunWith+import org.robolectric.Robolectricimport org.robolectric.RobolectricTestRunnerimport org.robolectric.annotation.Configimport org.robolectric.shadows.ShadowLooper/**- * Document-attachment behaviour of [ChatViewModel]: the message built for the- * LLM, the transcript label, and the send gate. The LLM base URL points at a+ * Attachment behaviour of [ChatViewModel]: the composer queue, the message built+ * for the LLM, the transcript label, and the send gate. The LLM base URL points at a* port that refuses connections so the run fails fast and the test stays hermetic.*/@RunWith(RobolectricTestRunner::class)@@ -49,10 +49,46 @@ class ChatViewModelAttachmentTest {)viewModel = ChatViewModel(application)ShadowLooper.idleMainLooper()+ FakeFilesProvider.files.clear()+ Robolectric.buildContentProvider(FakeFilesProvider::class.java).create(FakeFilesProvider.AUTHORITY)}- private fun doc(name: String = "report.pdf", text: String = "PDF BODY"): Attachment =- Attachment(name, "application/pdf", text.length.toLong(), text, pageCount = 2)+ private fun doc(name: String = "report.pdf", text: String = "PDF BODY"): ComposerAttachment.Document =+ ComposerAttachment.Document(+ id = name,+ attachment = Attachment(name, "application/pdf", text.length.toLong(), text, pageCount = 2)+ )++ private fun image(id: String, base64: String = "IMG-$id"): ComposerAttachment.Image =+ ComposerAttachment.Image(id = id, name = "$id.jpg", base64 = base64)++ private fun textFile(key: String, body: String): Uri =+ FakeFilesProvider.add(key, "$key.txt", "text/plain", body.toByteArray())++ private fun pngFile(key: String): Uri {+ val bitmap = Bitmap.createBitmap(4, 4, Bitmap.Config.ARGB_8888)+ val bytes = java.io.ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }+ return FakeFilesProvider.add(key, "$key.png", "image/png", bytes.toByteArray())+ }++ private fun pending(): List<ComposerAttachment> = viewModel.uiState.value.pendingAttachments++ /** Image data URIs of [message]'s image parts, in order. */+ private fun imageUrls(message: ChatMessage): List<String> =+ (message.content as JsonArray)+ .map { it.jsonObject }+ .filter { it["type"]?.jsonPrimitive?.content == "image_url" }+ .map { it["image_url"]!!.jsonObject["url"]!!.jsonPrimitive.content }++ /** Drains the main looper until [condition] holds (the pick loads on Dispatchers.IO). */+ private fun waitUntil(condition: () -> Boolean) {+ val deadline = System.currentTimeMillis() + 5_000+ while (System.currentTimeMillis() < deadline && !condition()) {+ ShadowLooper.idleMainLooper()+ Thread.sleep(10)+ }+ ShadowLooper.idleMainLooper()+ }/** Reads the live engine history without hitting the network. */private fun engineHistory(): List<ChatMessage> {@@ -77,12 +113,12 @@ class ChatViewModelAttachmentTest {@Testfun `sendMessage with a document builds a document message in history`() {- viewModel.sendMessage("summarize", null, doc("report.pdf", "PDF BODY"))+ viewModel.sendMessage("summarize", listOf(doc("report.pdf", "PDF BODY")))ShadowLooper.idleMainLooper()val userBubble = viewModel.uiState.value.messages.first { it.kind == MessageKind.USER }assertEquals("summarize", userBubble.text)- assertEquals("report.pdf", userBubble.attachment?.name)+ assertEquals(listOf("report.pdf"), userBubble.attachments.map { it.name })val last = engineHistory().last()assertTrue(last.textContent.contains("[Attached file: report.pdf (application/pdf, 2 pages)]"))@@ -91,19 +127,19 @@ class ChatViewModelAttachmentTest {@Testfun `sendMessage with only a document shows the document placeholder`() {- viewModel.sendMessage("", null, doc("notes.txt", "hello"))+ viewModel.sendMessage("", listOf(doc("notes.txt", "hello")))ShadowLooper.idleMainLooper()val userBubble = viewModel.uiState.value.messages.first { it.kind == MessageKind.USER }assertEquals("(document attached)", userBubble.text)- assertEquals("notes.txt", userBubble.attachment?.name)+ assertEquals(listOf("notes.txt"), userBubble.attachments.map { it.name })}@Testfun `sendMessage is a no-op when input and attachments are all empty`() {val before = viewModel.uiState.value.messages.size- viewModel.sendMessage(" ", null, null)+ viewModel.sendMessage(" ", emptyList())ShadowLooper.idleMainLooper()assertEquals(before, viewModel.uiState.value.messages.size)@@ -111,43 +147,125 @@ class ChatViewModelAttachmentTest {}@Test- fun `pickContent parses off the caller thread and delivers on pickResults`() {- // A content URI with no provider behind it: the stream can't open, so the- // pick resolves to null and a visible error bubble is appended. The point- // is the plumbing — no work may run on the calling thread, and the result- // arrives asynchronously via pickResults.- val uri = Uri.parse("content://com.gotcha.missing.provider/attachments/missing.pdf")+ fun `sendMessage sends every image as its own image part, in order`() {+ viewModel.sendMessage("compare these", listOf(image("a"), image("b"), image("c")))+ ShadowLooper.idleMainLooper()++ val last = engineHistory().last()+ assertEquals("compare these", last.textContent)+ assertEquals(+ listOf("IMG-a", "IMG-b", "IMG-c").map { "data:image/jpeg;base64,$it" },+ imageUrls(last)+ )+ val userBubble = viewModel.uiState.value.messages.first { it.kind == MessageKind.USER }+ assertEquals(listOf("a", "b", "c"), userBubble.attachments.map { it.id })+ }++ @Test+ fun `sendMessage with documents and images keeps every document in the first text part`() {+ viewModel.sendMessage(+ "",+ listOf(doc("one.pdf", "FIRST BODY"), image("x"), doc("two.pdf", "SECOND BODY"))+ )+ ShadowLooper.idleMainLooper()++ val last = engineHistory().last()+ val text = last.textContent+ assertTrue(text.contains("[Attached file: one.pdf") && text.contains("FIRST BODY"))+ assertTrue(text.contains("[Attached file: two.pdf") && text.contains("SECOND BODY"))+ assertTrue("documents keep their order", text.indexOf("one.pdf") < text.indexOf("two.pdf"))+ assertEquals(listOf("data:image/jpeg;base64,IMG-x"), imageUrls(last))++ val userBubble = viewModel.uiState.value.messages.first { it.kind == MessageKind.USER }+ assertEquals("(files attached)", userBubble.text)+ }++ @Test+ fun `addAttachments queues files in picked order and keeps earlier ones`() {+ viewModel.addAttachments(listOf(textFile("first", "ONE"), textFile("second", "TWO")))+ waitUntil { pending().size == 2 }+ viewModel.addAttachments(listOf(textFile("third", "THREE")))+ waitUntil { pending().size == 3 }++ assertEquals(listOf("first.txt", "second.txt", "third.txt"), pending().map { it.name })+ val third = pending().last() as ComposerAttachment.Document+ assertEquals("THREE", third.attachment.text)+ // Picking files never sends anything.+ assertTrue(engineHistory().isEmpty())+ assertTrue(viewModel.uiState.value.messages.none { it.kind == MessageKind.USER })+ }++ @Test+ fun `addAttachments reads images through the image pipeline`() {+ viewModel.addAttachments(listOf(pngFile("photo"), textFile("notes", "NOTES")))+ waitUntil { pending().size == 2 }++ val first = pending().first()+ assertTrue("expected an image, got $first", first is ComposerAttachment.Image)+ assertEquals("photo.png", first.name)+ assertTrue((first as ComposerAttachment.Image).base64.isNotBlank())+ assertTrue(pending()[1] is ComposerAttachment.Document)+ }++ @Test+ fun `addAttachments skips an unreadable file with an error and keeps the rest`() {+ val missing = Uri.parse("content://com.gotcha.missing.provider/attachments/missing.pdf")- viewModel.pickContent(uri)+ viewModel.addAttachments(listOf(textFile("good", "GOOD"), missing))// No work ran synchronously on the calling thread.assertEquals(0, viewModel.uiState.value.messages.size)+ waitUntil { viewModel.uiState.value.messages.isNotEmpty() }- val deadline = System.currentTimeMillis() + 5_000- var result: PickedFile? = null- val collector = CoroutineScope(Dispatchers.Default).launch {- result = withTimeoutOrNull(5_000) { viewModel.pickResults.first() }- }- while (System.currentTimeMillis() < deadline && result == null) {- ShadowLooper.idleMainLooper()- Thread.sleep(10)- }- collector.cancel()-- assertNull("pick should resolve to null, got $result", result)- // The failed pick is never silent: an error bubble explains it in the chat.+ assertEquals(listOf("good.txt"), pending().map { it.name })val error = viewModel.uiState.value.messages.lastOrNull()assertEquals(MessageKind.ERROR, error?.kind)assertTrue(error?.text?.contains("Could not read that file") == true)}@Test- fun `editMessage re-sends the original document when none is picked`() {- viewModel.sendMessage("original question", null, doc("doc.pdf", "DOC BODY"))+ fun `addAttachments stops at the per-message limit with an error`() {+ val nine = (1..9).map { image("i$it") }+ viewModel.setAttachments(nine)++ viewModel.addAttachments(listOf(textFile("tenth", "10"), textFile("eleventh", "11"), textFile("twelfth", "12")))+ waitUntil { viewModel.uiState.value.messages.isNotEmpty() }++ assertEquals(ComposerAttachment.MAX_PER_MESSAGE, pending().size)+ assertEquals("tenth.txt", pending().last().name)+ val error = viewModel.uiState.value.messages.last()+ assertEquals(MessageKind.ERROR, error.kind)+ assertTrue(error.text, error.text.contains("up to 10 files") && error.text.contains("skipped 2 files"))+ }++ @Test+ fun `addAttachments rejects documents past the combined text budget`() {+ val big = "x".repeat(ComposerAttachment.MAX_TOTAL_DOCUMENT_CHARS - 10)+ viewModel.setAttachments(listOf(doc("big.pdf", big)))++ viewModel.addAttachments(listOf(textFile("more", "this pushes it over the budget")))+ waitUntil { viewModel.uiState.value.messages.isNotEmpty() }++ assertEquals(listOf("big.pdf"), pending().map { it.name })+ assertTrue(viewModel.uiState.value.messages.last().text.contains("too long to send together"))+ }++ @Test+ fun `removeAttachment drops only that file and keeps the order`() {+ viewModel.setAttachments(listOf(image("a"), doc("b.pdf"), image("c")))++ viewModel.removeAttachment("b.pdf")++ assertEquals(listOf("a", "c"), pending().map { it.id })+ }++ @Test+ fun `editMessage re-sends the original attachments when none are given`() {+ viewModel.sendMessage("original question", listOf(doc("doc.pdf", "DOC BODY"), image("p")))waitForRunToFinish()val targetId = viewModel.uiState.value.messages.first { it.kind == MessageKind.USER }.id- viewModel.editMessage(targetId = targetId, newText = "edited question", imageBase64 = null, attachment = null)+ viewModel.editMessage(targetId = targetId, newText = "edited question", attachments = null)waitForRunToFinish()val last = engineHistory().last()@@ -157,5 +275,20 @@ class ChatViewModelAttachmentTest {last.textContent.contains("[Attached file: doc.pdf"))assertTrue("edited message must keep the extracted body", last.textContent.contains("DOC BODY"))+ assertEquals(listOf("data:image/jpeg;base64,IMG-p"), imageUrls(last))+ }++ @Test+ fun `editMessage with an empty list drops the attachments`() {+ viewModel.sendMessage("original question", listOf(image("p")))+ waitForRunToFinish()+ val targetId = viewModel.uiState.value.messages.first { it.kind == MessageKind.USER }.id++ viewModel.editMessage(targetId = targetId, newText = "just text now", attachments = emptyList())+ waitForRunToFinish()++ val last = engineHistory().last()+ assertEquals("just text now", last.textContent)+ assertEquals(0, last.imageCount)}}diff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelEditRevertTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelEditRevertTest.ktindex 089cd7e..a10f6e3 100644--- a/app/src/test/java/com/gotcha/agent/ChatViewModelEditRevertTest.kt+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelEditRevertTest.kt@@ -70,7 +70,7 @@ class ChatViewModelEditRevertTest {setRunning(isBusy = true, runningSessionId = "session-A")val before = viewModel.uiState.value- viewModel.editMessage(targetId = 1L, newText = "Edited", imageBase64 = null)+ viewModel.editMessage(targetId = 1L, newText = "Edited")ShadowLooper.idleMainLooper()assertEquals(before.messages, viewModel.uiState.value.messages)@@ -82,7 +82,7 @@ class ChatViewModelEditRevertTest {setRunning(isBusy = false, runningSessionId = "session-other")val before = viewModel.uiState.value- viewModel.editMessage(targetId = 1L, newText = "Edited", imageBase64 = null)+ viewModel.editMessage(targetId = 1L, newText = "Edited")ShadowLooper.idleMainLooper()assertEquals(before.messages, viewModel.uiState.value.messages)@@ -105,7 +105,7 @@ class ChatViewModelEditRevertTest {fun `editMessage is a no-op when the input is blank and no image is attached`() {val before = viewModel.uiState.value- viewModel.editMessage(targetId = 1L, newText = " ", imageBase64 = null)+ viewModel.editMessage(targetId = 1L, newText = " ")ShadowLooper.idleMainLooper()assertEquals(before.messages, viewModel.uiState.value.messages)diff --git a/app/src/test/java/com/gotcha/llm/ModelsTest.kt b/app/src/test/java/com/gotcha/llm/ModelsTest.ktindex 8c1c3e3..aaa9659 100644--- a/app/src/test/java/com/gotcha/llm/ModelsTest.kt+++ b/app/src/test/java/com/gotcha/llm/ModelsTest.kt@@ -342,4 +342,52 @@ class ModelsTest {assertEquals(plain, plain.withValidToolCallArguments())assertEquals(noCalls, noCalls.withValidToolCallArguments())}++ @Test+ fun `attachmentsUserMessage with one document matches documentUserMessage`() {+ val single = attachmentsUserMessage(+ userText = "summarize",+ documents = listOf(DocumentPart("a.pdf", "application/pdf", "BODY", pageCount = 3)),+ imagesBase64 = emptyList()+ )+ val legacy = documentUserMessage("summarize", "a.pdf", "application/pdf", "BODY", pageCount = 3)+ assertEquals(legacy, single)+ }++ @Test+ fun `attachmentsUserMessage with one image matches visionUserMessage`() {+ assertEquals(+ visionUserMessage("", "QUJD", "jpeg"),+ attachmentsUserMessage("", emptyList(), listOf("QUJD"), imageFormat = "jpeg")+ )+ }++ @Test+ fun `attachmentsUserMessage puts documents in the first part and each image in its own part`() {+ val msg = attachmentsUserMessage(+ userText = "",+ documents = listOf(+ DocumentPart("one.txt", "text/plain", "FIRST"),+ DocumentPart("two.txt", "text/plain", "SECOND")+ ),+ imagesBase64 = listOf("AAA", "BBB")+ )+ val parts = msg.content as JsonArray+ assertEquals(3, parts.size)+ assertEquals(2, msg.imageCount)+ val text = msg.textContent+ assertTrue(text.startsWith("Answer questions about the attached files."))+ assertTrue(text.indexOf("[Attached file: one.txt") < text.indexOf("[Attached file: two.txt"))+ assertTrue(text.contains("FIRST") && text.contains("SECOND"))+ assertEquals(+ listOf("data:image/jpeg;base64,AAA", "data:image/jpeg;base64,BBB"),+ parts.drop(1).map { it.jsonObject["image_url"]!!.jsonObject["url"]!!.jsonPrimitive.content }+ )+ }++ @Test+ fun `attachmentsUserMessage defaults the prompt for several images`() {+ val msg = attachmentsUserMessage("", emptyList(), listOf("A", "B"))+ assertEquals("What is in these images?", msg.textContent)+ }}diff --git a/app/src/test/java/com/gotcha/testsupport/FakeFilesProvider.kt b/app/src/test/java/com/gotcha/testsupport/FakeFilesProvider.ktnew file mode 100644index 0000000..4aae43f--- /dev/null+++ b/app/src/test/java/com/gotcha/testsupport/FakeFilesProvider.kt@@ -0,0 +1,69 @@+package com.gotcha.testsupport++import android.content.ContentProvider+import android.content.ContentValues+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import android.os.ParcelFileDescriptor+import android.provider.OpenableColumns+import java.io.File++/**+ * A content provider standing in for the system file picker's documents: serves+ * [files] by path segment with a display name, MIME type and bytes. Register it+ * with `Robolectric.buildContentProvider(FakeFilesProvider::class.java).create(AUTHORITY)`+ * and hand out [uri]s.+ */+class FakeFilesProvider : ContentProvider() {++ data class FakeFile(val name: String, val mimeType: String, val bytes: ByteArray)++ override fun onCreate(): Boolean = true++ override fun getType(uri: Uri): String? = files[uri.lastPathSegment]?.mimeType++ override fun query(+ uri: Uri,+ projection: Array<out String>?,+ selection: String?,+ selectionArgs: Array<out String>?,+ sortOrder: String?+ ): Cursor? {+ val file = files[uri.lastPathSegment] ?: return null+ return MatrixCursor(arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE)).apply {+ addRow(arrayOf<Any>(file.name, file.bytes.size.toLong()))+ }+ }++ override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? {+ val file = files[uri.lastPathSegment] ?: return null+ val tmp = File.createTempFile("fake-files", null).apply {+ deleteOnExit()+ writeBytes(file.bytes)+ }+ return ParcelFileDescriptor.open(tmp, ParcelFileDescriptor.MODE_READ_ONLY)+ }++ override fun insert(uri: Uri, values: ContentValues?): Uri? = null+ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0+ override fun update(+ uri: Uri,+ values: ContentValues?,+ selection: String?,+ selectionArgs: Array<out String>?+ ): Int = 0++ companion object {+ const val AUTHORITY = "com.gotcha.test.files"+ val files = mutableMapOf<String, FakeFile>()++ /** Registers a file and returns the content:// URI that serves it. */+ fun add(key: String, name: String, mimeType: String, bytes: ByteArray): Uri {+ files[key] = FakeFile(name, mimeType, bytes)+ return uri(key)+ }++ fun uri(key: String): Uri = Uri.parse("content://$AUTHORITY/$key")+ }+}diff --git a/app/src/test/java/com/gotcha/util/HumanReadableErrorTest.kt b/app/src/test/java/com/gotcha/util/HumanReadableErrorTest.ktindex ed3eed1..af666a5 100644--- a/app/src/test/java/com/gotcha/util/HumanReadableErrorTest.kt+++ b/app/src/test/java/com/gotcha/util/HumanReadableErrorTest.kt@@ -120,4 +120,23 @@ class HumanReadableErrorTest {val emptyEx = RuntimeException("")assertTrue(HumanReadableError.format(emptyEx).contains("An unexpected error occurred"))}++ @Test+ fun `an HTTP rejection that names images explains how to recover`() {+ val msg = HumanReadableError.fromHttpCode(400, "Too many images in request. Max is 3.")+ assertTrue(msg.contains("rejected the attached images"))+ assertTrue(msg.contains("Too many images in request. Max is 3."))+ assertTrue(msg.contains("Remove some attachments"))++ val tooLarge = HumanReadableError.fromHttpCode(413, "image exceeds 5 MB maximum")+ assertTrue(tooLarge.contains("rejected the attached images"))+ }++ @Test+ fun `an HTTP rejection without images keeps its usual explanation`() {+ assertTrue(HumanReadableError.fromHttpCode(400, "bad json").contains("Bad request"))+ assertTrue(HumanReadableError.fromHttpCode(413).contains("Request too large"))+ // Only request errors are reinterpreted, not e.g. auth failures that mention images.+ assertTrue(HumanReadableError.fromHttpCode(401, "image model requires auth").contains("Authentication failed"))+ }}