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.

Add document attachments to chat mode.

Rishabh Bajpai2f4e443fceca
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0fe0301..6a95e2d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,25 @@ All notable changes to Gotcha are documented here.
## [Unreleased]
+### Added — Document attachments in chat (#24)
+
+- **Attach more than images.** The composer's "+" now opens a picker that accepts
+ documents as well as images: PDF, Word (`.docx`), Excel (`.xlsx`),
+ PowerPoint (`.pptx`) and plain text (TXT/CSV/MD/JSON/HTML). A new
+ `DocumentParser` (pure Kotlin, ZIP + XML for Office files, pdfbox-android for
+ PDF, jsoup for HTML) extracts the file's text; legacy `.doc`/`.xls` and
+ unsupported formats show a clear error instead of failing silently.
+- **The model reads the file.** Attaching a document sends an
+ `[Attached file: name (type, N pages)]` header plus the extracted text (capped
+ at ~40k chars, ~10k tokens) as the message's single text part, so token
+ accounting, history trimming and compaction all count it correctly. The bytes
+ are copied into the app cache at pick time so a revoked content grant can't
+ break a later send.
+- **Attachment UI.** Pending attachments show as a chip (name, type, size,
+ truncated flag) instead of a bitmap preview; sent messages render the same
+ chip. Attachment metadata persists with the session, so editing a sent
+ document message re-sends the extracted text without re-reading the file.
+
### Fixed — Malformed tool call no longer bricks the chat (#13)
- **A tool call with invalid `arguments` JSON can no longer poison a chat.** When
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 7947c5c..b90a799 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -338,6 +338,13 @@ dependencies {
// HTML parsing for webfetch tool
implementation("org.jsoup:jsoup:1.17.2")
+ // PDF text extraction for document attachments (DocumentParser). bouncycastle
+ // is pulled in only for encrypted/signed PDFs, which are out of scope; the
+ // text path never touches it, so exclude it to keep the dependency lean.
+ implementation("com.tom-roush:pdfbox-android:2.0.27.0") {
+ exclude(group = "org.bouncycastle")
+ }
+
// Connectors: Custom Tabs for the BYO-OAuth consent flow
implementation("androidx.browser:browser:1.8.0")
diff --git a/app/src/main/java/com/gotcha/GotchaApp.kt b/app/src/main/java/com/gotcha/GotchaApp.kt
index d8a85eb..1c03105 100644
--- a/app/src/main/java/com/gotcha/GotchaApp.kt
+++ b/app/src/main/java/com/gotcha/GotchaApp.kt
@@ -23,6 +23,9 @@ class GotchaApp : Application() {
override fun onCreate() {
super.onCreate()
+ // pdfbox ships its glyph tables as Android assets; the resource loader
+ // needs a Context before the first PDF text extraction (DocumentParser).
+ com.gotcha.tools.DocumentParser.init(this)
setupUncaughtExceptionHandler()
}
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index bc56346..caccffd 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -748,8 +748,8 @@ class MainActivity : ComponentActivity() {
}
ChatScreen(
state = state,
- onSend = { text, imageBase64, isVoiceInput ->
- chatViewModel.sendMessage(text, imageBase64, isVoiceInput)
+ onSend = { text, imageBase64, attachment, isVoiceInput ->
+ chatViewModel.sendMessage(text, imageBase64, attachment, isVoiceInput)
},
onStop = chatViewModel::stopAgent,
onConfirm = chatViewModel::confirmPendingActions,
@@ -757,7 +757,7 @@ class MainActivity : ComponentActivity() {
onOpenDrawer = { scope.launch { drawerState.open() } },
onOpenSettings = { currentRoute = Route.SETTINGS },
sessionTitle = sessions.firstOrNull { it.id == state.activeSessionId }?.title,
- onPickImage = { uri -> chatViewModel.loadImageBase64(uri) },
+ onPickFile = { uri -> chatViewModel.pickContent(uri) },
onSwitchAgent = chatViewModel::switchAgent,
onSetAgent = chatViewModel::setAgent,
onSpeak = chatViewModel::speak,
@@ -771,8 +771,8 @@ class MainActivity : ComponentActivity() {
onCreateShareCard = {
sharePoster.open(chatViewModel.activeSessionRunSummaries())
},
- onEditMessage = { id, text, imageBase64 ->
- chatViewModel.editMessage(id, text, imageBase64)
+ onEditMessage = { id, text, imageBase64, attachment ->
+ chatViewModel.editMessage(id, text, imageBase64, attachment)
},
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.kt
index c0560de..242919e 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -1,9 +1,11 @@
package com.gotcha.agent
import android.app.Application
+import android.content.ContentResolver
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
+import android.provider.OpenableColumns
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.gotcha.audio.AudioModel
@@ -21,11 +23,14 @@ import com.gotcha.i18n.Language
import com.gotcha.i18n.SpokenPhrases
import com.gotcha.llm.ChatMessage
import com.gotcha.llm.LLMClient
+import com.gotcha.llm.documentUserMessage
import com.gotcha.llm.visionUserMessage
import com.gotcha.marketing.PosterRenderer
import com.gotcha.marketing.PosterStatsBuilder
import com.gotcha.marketing.ShareCardClient
import com.gotcha.tools.AgentMode
+import com.gotcha.tools.DocumentError
+import com.gotcha.tools.DocumentParser
import com.gotcha.tools.ScreenPerception
import com.gotcha.tools.ToolResult
import com.gotcha.tools.mergeProfileUpdate
@@ -48,6 +53,28 @@ import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonPrimitive
+import java.io.File
+
+/**
+ * A document the user picked from the system picker. The extracted [text] is what
+ * gets sent to the model; it is also kept on the [com.gotcha.agent.UiMessage] so
+ * re-editing a sent message can rebuild the request without re-reading the file.
+ */
+data class Attachment(
+ val name: String,
+ val mimeType: String,
+ val size: Long,
+ val text: String,
+ val pageCount: Int? = null,
+ 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()
+}
@kotlinx.serialization.Serializable
data class UiMessage(
@@ -57,7 +84,8 @@ data class UiMessage(
val imageBase64: String? = null,
val subAgentSteps: List<String> = emptyList(),
val subAgentCollapsed: Boolean = true,
- val reasoningContent: String? = null
+ val reasoningContent: String? = null,
+ val attachment: Attachment? = null
)
data class SubAgentStepUi(
@@ -258,7 +286,13 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
subAgentSteps: List<String>,
reasoningContent: String?
) {
- appendEngineUi(kind, text, imageBase64, subAgentSteps, reasoningContent)
+ appendEngineUi(
+ kind = kind,
+ text = text,
+ imageBase64 = imageBase64,
+ subAgentSteps = subAgentSteps,
+ reasoningContent = reasoningContent
+ )
}
override fun onActivity(activity: String?) {
@@ -401,9 +435,14 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
return client.listModels()
}
- fun sendMessage(text: String, imageBase64: String? = null, isVoiceInput: Boolean = false) {
+ fun sendMessage(
+ text: String,
+ imageBase64: String? = null,
+ attachment: Attachment? = null,
+ isVoiceInput: Boolean = false
+ ) {
val trimmed = text.trim()
- if (trimmed.isEmpty() && imageBase64 == null) return
+ if (trimmed.isEmpty() && imageBase64 == null && attachment == null) 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
@@ -411,12 +450,25 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
appendUi(MessageKind.ERROR, "No API key configured. Open settings to add one.")
return
}
- val msg = if (imageBase64 != null) {
- visionUserMessage(trimmed, imageBase64, "jpeg")
- } else {
- ChatMessage(role = "user", content = JsonPrimitive(trimmed))
- }
- launchUserRun(msg, imageBase64, isVoiceInput)
+ val msg = buildUserMessage(trimmed, imageBase64, attachment)
+ launchUserRun(msg, imageBase64, attachment, 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).
+ */
+ 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))
}
/**
@@ -424,7 +476,13 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
* and starts an agent run. Shared by [sendMessage] and [editMessage], so both
* paths go through the same busy-marking, run, and NonCancellable cleanup.
*/
- private fun launchUserRun(msg: ChatMessage, imageBase64: String?, isVoiceInput: Boolean) {
+ private fun launchUserRun(
+ msg: ChatMessage,
+ imageBase64: String?,
+ attachment: Attachment?,
+ userText: String,
+ isVoiceInput: Boolean
+ ) {
currentRunIsVoice = isVoiceInput || lastInputWasVoice
lastInputWasVoice = false
val viewedId = _uiState.value.activeSessionId
@@ -435,13 +493,41 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
bindEngineToViewedSession(viewedId)
agentEngine.history += msg
- appendEngineUi(MessageKind.USER, msg.textContent.ifEmpty { "(image attached)" }, imageBase64)
+ appendEngineUi(
+ MessageKind.USER,
+ userDisplayText(userText, msg, attachment),
+ imageBase64,
+ attachment = attachment
+ )
val runningId = agentEngine.sessionId ?: return@launch
executeRun(engineAgent, runningId)
}
}
+ /**
+ * 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).
+ */
+ private fun userDisplayText(userText: String, msg: ChatMessage, attachment: Attachment?): String = when {
+ attachment != null -> userText.ifEmpty { "(document attached)" }
+ else -> msg.textContent
+ }
+
+ /**
+ * The user's prompt portion of a document message's text part, or null when
+ * [content] is not a document message. Document messages put
+ * `[Attached file: …]` on its own line, so everything before that marker is
+ * the user's own words.
+ */
+ private fun documentPromptText(content: String): String? {
+ val marker = "\n[Attached file:"
+ val index = content.indexOf(marker)
+ return if (index >= 0) content.substring(0, index).trim() else null
+ }
+
/** 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 }
@@ -485,9 +571,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
* 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?) {
+ fun editMessage(targetId: Long, newText: String, imageBase64: String?, attachment: Attachment? = null) {
val trimmed = newText.trim()
- if (trimmed.isEmpty() && imageBase64 == null) return
+ if (trimmed.isEmpty() && imageBase64 == null && attachment == null) return
if (_uiState.value.isBusy || _uiState.value.runningSessionId != null) return
if (client == null) {
appendUi(MessageKind.ERROR, "No API key configured. Open settings to add one.")
@@ -527,13 +613,17 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
// Never promote undone work on the share card.
agentEngine.restoreRunSummaries(emptyList())
val editImage = imageBase64 ?: target.imageBase64
- val msg = if (editImage != null) {
- visionUserMessage(trimmed, editImage, "jpeg")
- } else {
- ChatMessage(role = "user", content = JsonPrimitive(trimmed))
- }
+ // 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)
agentEngine.history += msg
- appendEngineUi(MessageKind.USER, msg.textContent.ifEmpty { "(image attached)" }, editImage)
+ appendEngineUi(
+ MessageKind.USER,
+ userDisplayText(trimmed, msg, editAttachment),
+ editImage,
+ attachment = editAttachment
+ )
executeRun(engineAgent, agentEngine.sessionId ?: return@launch)
}
}
@@ -657,6 +747,69 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
}
}
+ /**
+ * Entry point for the composer's "+" button. Routes by content type: images
+ * reuse the image pipeline; anything else goes through [loadDocument]. Errors
+ * surface as an ERROR bubble so an oversized or unsupported file explains
+ * itself instead of silently doing nothing.
+ */
+ fun pickContent(uri: Uri): PickedFile? {
+ val resolver = getApplication<Application>().contentResolver
+ val mime = resolver.getType(uri)
+ return if (mime?.startsWith("image/") == true) {
+ loadImageBase64(uri)?.let { PickedFile.Image(it) }
+ } else {
+ loadDocument(uri)?.let { PickedFile.Document(it) }
+ }
+ }
+
+ /**
+ * Load a document from a content:// URI: read the bytes, extract the text via
+ * [DocumentParser], and copy the bytes into the app cache immediately — the
+ * transient picker read grant must not be relied on at send time. Returns null
+ * (after surfacing a message) when the file is unreadable or unsupported.
+ */
+ fun loadDocument(uri: Uri): Attachment? {
+ return try {
+ val app = getApplication<Application>()
+ val resolver = app.contentResolver
+ val bytes = resolver.openInputStream(uri)?.use { it.readBytes() } ?: return null
+ val name = queryDisplayName(resolver, uri)
+ val extracted = DocumentParser.extract(bytes, name, resolver.getType(uri))
+ val cached = File(app.cacheDir, "attach-${System.currentTimeMillis()}-${safeName(name)}")
+ cached.writeBytes(bytes)
+ Attachment(
+ name = name,
+ mimeType = extracted.mimeType,
+ size = bytes.size.toLong(),
+ text = extracted.text,
+ pageCount = extracted.pageCount,
+ truncated = extracted.truncated
+ )
+ } catch (e: DocumentError) {
+ appendUi(MessageKind.ERROR, e.message ?: "Could not read that file.")
+ null
+ } catch (e: Exception) {
+ appendUi(MessageKind.ERROR, "Could not read that file: ${HumanReadableError.format(e)}")
+ null
+ }
+ }
+
+ private fun queryDisplayName(resolver: ContentResolver, uri: Uri): String {
+ return try {
+ resolver.query(uri, null, null, null, null)?.use { cursor ->
+ if (!cursor.moveToFirst()) return@use null
+ val index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
+ if (index >= 0) cursor.getString(index) else null
+ }
+ } catch (_: Exception) {
+ null
+ }?.takeIf { it.isNotBlank() } ?: "document"
+ }
+
+ private fun safeName(name: String): String =
+ name.replace(Regex("[^A-Za-z0-9._-]"), "_").take(80).ifBlank { "doc" }
+
fun stopAgent() {
agentJob?.cancel()
}
@@ -1099,13 +1252,23 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
kind: MessageKind,
text: String,
imageBase64: String? = null,
+ attachment: Attachment? = null,
subAgentSteps: List<String> = emptyList(),
reasoningContent: String? = null
) {
val viewing = viewingEngineSession()
val id = if (viewing) nextId++ else engineNextId++
if (kind == MessageKind.ERROR) runHadError = true
- val message = UiMessage(id, kind, text, imageBase64, subAgentSteps, subAgentCollapsed = true, reasoningContent)
+ val message = UiMessage(
+ id = id,
+ kind = kind,
+ text = text,
+ imageBase64 = imageBase64,
+ subAgentSteps = subAgentSteps,
+ subAgentCollapsed = true,
+ reasoningContent = reasoningContent,
+ attachment = attachment
+ )
engineTranscript = engineTranscript + message
if (viewing) {
_uiState.update { it.copy(messages = it.messages + message) }
@@ -1125,7 +1288,19 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
}
UiMessage(nextId++, MessageKind.ASSISTANT, msgText)
}
- msg.role == "user" -> UiMessage(nextId++, MessageKind.USER, text.ifEmpty { "(image attached)" })
+ msg.role == "user" -> {
+ val text = msg.textContent
+ val docPrompt = documentPromptText(text)
+ UiMessage(
+ nextId++,
+ MessageKind.USER,
+ if (docPrompt != null) {
+ docPrompt.ifEmpty { "(document attached)" }
+ } else {
+ text.ifEmpty { "(image attached)" }
+ }
+ )
+ }
msg.role == "assistant" && text.isNotBlank() ->
UiMessage(nextId++, MessageKind.ASSISTANT, text, reasoningContent = msg.reasoningContent)
msg.role == "assistant" && !msg.reasoningContent.isNullOrBlank() ->
@@ -1194,10 +1369,15 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
when (role) {
"user" -> {
- val isVision = msg.content is JsonArray
+ val docPrompt = documentPromptText(text)
sb.appendLine("### User")
- if (text.isNotBlank()) sb.appendLine(text)
- if (isVision) sb.appendLine("*(Image attached)*")
+ 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)*")
+ }
sb.appendLine()
}
"assistant" -> {
diff --git a/app/src/main/java/com/gotcha/llm/Models.kt b/app/src/main/java/com/gotcha/llm/Models.kt
index 50684c4..08de628 100644
--- a/app/src/main/java/com/gotcha/llm/Models.kt
+++ b/app/src/main/java/com/gotcha/llm/Models.kt
@@ -86,6 +86,49 @@ fun visionUserMessage(text: String, imageBase64: String, imageFormat: String = "
)
}
+/**
+ * Build a document-content ChatMessage: a single text part carrying the user's
+ * question, an `[Attached file: …]` header, and the extracted document text.
+ *
+ * The header + body deliberately live in the FIRST (and only) text part: token
+ * accounting, history trimming and compaction all read [ChatMessage.textContent],
+ * which returns the first text part — a second part would silently disappear
+ * from token counts and compaction summaries.
+ */
+fun documentUserMessage(
+ userText: String,
+ fileName: String,
+ mimeType: String,
+ extractedText: String,
+ pageCount: Int? = null
+): ChatMessage {
+ val header = buildString {
+ append("[Attached file: $fileName")
+ append(if (mimeType.isNotBlank()) " ($mimeType" else " (document")
+ pageCount?.let { append(", $it pages") }
+ append(")]")
+ }
+ val body = 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 ChatMessage(
+ role = "user",
+ content = buildJsonArray {
+ add(
+ buildJsonObject {
+ put("type", "text")
+ put("text", text)
+ }
+ )
+ }
+ )
+}
+
@Serializable
data class ToolCall(
val id: String,
diff --git a/app/src/main/java/com/gotcha/tools/DocumentParser.kt b/app/src/main/java/com/gotcha/tools/DocumentParser.kt
new file mode 100644
index 0000000..8e536a0
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/DocumentParser.kt
@@ -0,0 +1,333 @@
+package com.gotcha.tools
+
+import com.tom_roush.pdfbox.pdmodel.PDDocument
+import com.tom_roush.pdfbox.text.PDFTextStripper
+import org.jsoup.Jsoup
+import org.w3c.dom.Document
+import org.w3c.dom.Element
+import org.w3c.dom.Node
+import java.io.File
+import java.io.InputStream
+import java.util.zip.ZipFile
+import javax.xml.parsers.DocumentBuilderFactory
+
+/**
+ * The text pulled out of an attached document, already truncated to fit the
+ * model's context window ([DocumentParser.MAX_EXTRACTED_CHARS]).
+ */
+data class ExtractedDocument(
+ val fileName: String,
+ val mimeType: String,
+ /** The extracted text, truncated with a visible note when needed. */
+ val text: String,
+ val pageCount: Int? = null,
+ val truncated: Boolean = false
+)
+
+/** A document that could not be used as an attachment, with a human-readable message. */
+sealed class DocumentError(message: String, cause: Throwable? = null) : Exception(message, cause) {
+ class UnsupportedFormat(detail: String) : DocumentError(
+ "Unsupported document format: ${detail.ifBlank { "unknown" }}. " +
+ "Supported: PDF, DOCX, XLSX, PPTX and plain text (TXT/CSV/MD/JSON/HTML). " +
+ "Legacy .doc and .xls files are not supported."
+ )
+
+ class TooLarge(size: Long) : DocumentError(
+ "File too large (${FileResolver.formatSizeStatic(
+ size
+ )}). Max: ${DocumentParser.MAX_DOC_BYTES / 1024 / 1024} MB."
+ )
+
+ class Corrupt(detail: String, cause: Throwable? = null) : DocumentError(
+ "Could not read this document: ${detail.ifBlank { "unrecognized content" }}",
+ cause
+ )
+}
+
+/**
+ * Maps MIME type / extension to the plain text of a document, so attached files
+ * can be fed to the model as a regular text part.
+ *
+ * Pure JVM-compatible for everything except PDF, which uses pdfbox-android (only
+ * reachable through [extract] on a PDF — the Android runtime and Robolectric both
+ * provide the `android.util.Log` the library needs). No Android framework APIs are
+ * used directly, so the ZIP/XML branches are plain-JVM unit-testable.
+ */
+@Suppress("TooManyFunctions")
+object DocumentParser {
+
+ /** Mirror of [FileTool]'s binary cap. */
+ const val MAX_DOC_BYTES = 20L * 1024 * 1024
+
+ /**
+ * Cap on extracted text (~10k tokens at 4 chars/token). The header the
+ * message builder prepends is a few dozen chars, so this dominates the budget.
+ */
+ const val MAX_EXTRACTED_CHARS = 40_000
+
+ /**
+ * One-time pdfbox resource-loading initialisation. pdfbox ships its glyph
+ * tables as Android assets (via [com.tom_roush.pdfbox.android.PDFBoxResourceLoader]),
+ * so this must be called with a Context before any PDF is parsed. Idempotent;
+ * call from app startup.
+ */
+ fun init(context: android.content.Context) {
+ com.tom_roush.pdfbox.android.PDFBoxResourceLoader.init(context)
+ }
+
+ private const val DOCX_MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
+ private const val XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
+ private const val PPTX_MIME = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
+
+ private val TEXT_EXTS = setOf(
+ "txt", "text", "csv", "tsv", "md", "markdown", "json", "xml", "log",
+ "yml", "yaml", "ini", "cfg", "conf", "properties", "env", "gitignore",
+ "sh", "py", "java", "kt", "js", "ts", "css", "sql", "rtf"
+ )
+
+ private const val TRUNCATION_NOTE = "\n\n[Note: document text was truncated to fit the model's context window]"
+
+ /**
+ * Extracts the text of [fileName] from [bytes]. [mimeType] is optional; when
+ * missing (or generic, e.g. `application/octet-stream`) the extension decides.
+ * Throws [DocumentError] for oversized, unsupported or corrupt files.
+ */
+ fun extract(bytes: ByteArray, fileName: String, mimeType: String?): ExtractedDocument {
+ if (bytes.size.toLong() > MAX_DOC_BYTES) throw DocumentError.TooLarge(bytes.size.toLong())
+ val ext = fileName.substringAfterLast('.', "").lowercase()
+ val mime = (mimeType ?: extensionMime(ext)).trim().lowercase()
+
+ val parsedPdf = if (isPdf(mime, ext)) pdfTextAndPagesOrThrow(bytes) else null
+ val raw = parsedPdf?.first ?: extractTextOrThrow(mime, ext, bytes)
+
+ val (text, truncated) = truncate(normalizeWhitespace(raw))
+ return ExtractedDocument(
+ fileName = fileName,
+ mimeType = mime.ifBlank { ext },
+ text = text,
+ pageCount = parsedPdf?.second,
+ truncated = truncated
+ )
+ }
+
+ /** Runs the format branch, mapping any non-[DocumentError] failure to [DocumentError.Corrupt]. */
+ private fun extractTextOrThrow(mime: String, ext: String, bytes: ByteArray): String {
+ return try {
+ extractByFormat(mime, ext, bytes)
+ } catch (e: DocumentError) {
+ throw e
+ } catch (e: Exception) {
+ throw DocumentError.Corrupt(e.message ?: e.javaClass.simpleName, e)
+ }
+ }
+
+ private fun extractByFormat(mime: String, ext: String, bytes: ByteArray): String = when {
+ isDocx(mime, ext) -> docxText(bytes)
+ isXlsx(mime, ext) -> xlsxText(bytes)
+ isPptx(mime, ext) -> pptxText(bytes)
+ isHtml(mime, ext) -> Jsoup.parse(decodeText(bytes)).text()
+ isText(mime, ext) -> decodeText(bytes)
+ else -> throw DocumentError.UnsupportedFormat(mime.ifBlank { ext })
+ }
+
+ // ---- format detection ----
+
+ private fun isPdf(mime: String, ext: String): Boolean =
+ mime == "application/pdf" || ext == "pdf"
+
+ private fun isDocx(mime: String, ext: String): Boolean =
+ mime.startsWith("application/vnd.openxmlformats-officedocument.wordprocessingml") || ext == "docx"
+
+ private fun isXlsx(mime: String, ext: String): Boolean =
+ mime.startsWith("application/vnd.openxmlformats-officedocument.spreadsheetml") || ext == "xlsx"
+
+ private fun isPptx(mime: String, ext: String): Boolean =
+ mime.startsWith("application/vnd.openxmlformats-officedocument.presentationml") || ext == "pptx"
+
+ private fun isHtml(mime: String, ext: String): Boolean =
+ mime == "text/html" || mime == "application/xhtml+xml" || ext == "html" || ext == "htm"
+
+ private fun isText(mime: String, ext: String): Boolean =
+ mime.startsWith("text/") || mime == "application/json" || mime == "application/xml" ||
+ mime == "application/javascript" || ext in TEXT_EXTS
+
+ private fun extensionMime(ext: String): String = when (ext) {
+ "pdf" -> "application/pdf"
+ "docx" -> DOCX_MIME
+ "xlsx" -> XLSX_MIME
+ "pptx" -> PPTX_MIME
+ "html", "htm" -> "text/html"
+ in TEXT_EXTS -> "text/plain"
+ else -> ""
+ }
+
+ // ---- PDF (pdfbox-android) ----
+
+ /** Maps a pdfbox failure to [DocumentError.Corrupt] so [extract] stays a single error type. */
+ private fun pdfTextAndPagesOrThrow(bytes: ByteArray): Pair<String, Int?> {
+ return try {
+ pdfTextAndPages(bytes)
+ } catch (e: Exception) {
+ throw DocumentError.Corrupt(e.message ?: e.javaClass.simpleName, e)
+ }
+ }
+
+ private fun pdfTextAndPages(bytes: ByteArray): Pair<String, Int?> {
+ val doc = PDDocument.load(bytes)
+ return try {
+ PDFTextStripper().getText(doc) to doc.numberOfPages
+ } finally {
+ doc.close()
+ }
+ }
+
+ // ---- Office documents (ZIP + XML, zero-dependency) ----
+
+ private fun docxText(bytes: ByteArray): String = zipEntryText(bytes, "word/document.xml") { doc ->
+ val paragraphs = doc.getElementsByTagNameNS("*", "p")
+ (0 until paragraphs.length).joinToString("\n") { i ->
+ val paragraph = paragraphs.item(i) as Element
+ val runs = paragraph.getElementsByTagNameNS("*", "t")
+ (0 until runs.length).joinToString("") { runs.item(it).textContent }
+ }
+ }
+
+ private fun xlsxText(bytes: ByteArray): String = zipFile(bytes) { zf ->
+ val shared = readSharedStrings(zf)
+ val sheets = zf.entries().asSequence().mapNotNull { it.name }
+ .filter { it.startsWith("xl/worksheets/") && it.endsWith(".xml") }
+ .sorted()
+ .toList()
+ if (sheets.isEmpty()) throw DocumentError.Corrupt("archive is missing its worksheets")
+ sheets.joinToString("\n\n") { sheet ->
+ val doc = parseXml(zf.getInputStream(zf.getEntry(sheet)!!))
+ val rows = doc.getElementsByTagNameNS("*", "row")
+ (0 until rows.length).joinToString("\n") { r ->
+ val row = rows.item(r) as Element
+ val cells = row.getElementsByTagNameNS("*", "c")
+ (0 until cells.length).joinToString(" | ") { c -> cellText(cells.item(c), shared) }
+ }
+ }
+ }
+
+ private fun pptxText(bytes: ByteArray): String = zipFile(bytes) { zf ->
+ val slides = zf.entries().asSequence().mapNotNull { it.name }
+ .filter { it.startsWith("ppt/slides/slide") && it.endsWith(".xml") }
+ .sorted()
+ .toList()
+ if (slides.isEmpty()) throw DocumentError.Corrupt("archive is missing its slides")
+ slides.joinToString("\n\n") { slide ->
+ val doc = parseXml(zf.getInputStream(zf.getEntry(slide)!!))
+ val texts = doc.getElementsByTagNameNS("*", "t")
+ (0 until texts.length).joinToString(" ") { texts.item(it).textContent }
+ }
+ }
+
+ private fun readSharedStrings(zf: ZipFile): List<String> {
+ val entry = zf.getEntry("xl/sharedStrings.xml") ?: return emptyList()
+ val doc = parseXml(zf.getInputStream(entry))
+ val items = doc.getElementsByTagNameNS("*", "si")
+ return (0 until items.length).map { i ->
+ val item = items.item(i) as Element
+ val ts = item.getElementsByTagNameNS("*", "t")
+ (0 until ts.length).joinToString("") { ts.item(it).textContent }
+ }
+ }
+
+ private fun cellText(cell: Node, shared: List<String>): String {
+ val inline = firstByLocalName(cell, "is")?.let { inlineElement ->
+ val ts = inlineElement.getElementsByTagNameNS("*", "t")
+ (0 until ts.length).joinToString("") { ts.item(it).textContent }
+ }
+ if (!inline.isNullOrEmpty()) return inline
+ val v = firstByLocalName(cell, "v")?.textContent?.trim().orEmpty()
+ if (v.isEmpty()) return ""
+ return when ((cell as? Element)?.getAttribute("t")) {
+ "s" -> shared.getOrNull(v.toIntOrNull() ?: return "") ?: ""
+ "str", "inlineStr" -> v
+ else -> v
+ }
+ }
+
+ private fun firstByLocalName(node: Node, localName: String): Element? {
+ val found = (node as? Element)?.getElementsByTagNameNS("*", localName) ?: return null
+ return if (found.length > 0) found.item(0) as? Element else null
+ }
+
+ // ---- ZIP/XML plumbing ----
+
+ private fun zipEntryText(bytes: ByteArray, entryName: String, parse: (Document) -> String): String =
+ zipFile(bytes) { zf ->
+ val entry = zf.getEntry(entryName)
+ ?: throw DocumentError.Corrupt("archive is missing '$entryName'")
+ parse(parseXml(zf.getInputStream(entry)))
+ }
+
+ private fun <T> zipFile(bytes: ByteArray, block: (ZipFile) -> T): T {
+ val file = File.createTempFile("gotcha-doc", ".tmp")
+ try {
+ file.writeBytes(bytes)
+ return ZipFile(file).use { block(it) }
+ } finally {
+ file.delete()
+ }
+ }
+
+ @Suppress("SwallowedException")
+ private fun parseXml(stream: InputStream): Document {
+ val factory = DocumentBuilderFactory.newInstance()
+ factory.isNamespaceAware = true
+ // Best-effort XXE hardening: a DOCTYPE-bearing or entity-referencing
+ // payload is rejected (or at worst parsed without entity expansion) rather
+ // than resolved against local files or network URLs. Some parsers don't
+ // recognize every feature, so a rejected feature must not break parsing.
+ setFeatureSafely(factory, "http://apache.org/xml/features/disallow-doctype-decl", true)
+ setFeatureSafely(factory, "http://xml.org/sax/features/external-general-entities", false)
+ setFeatureSafely(factory, "http://xml.org/sax/features/external-parameter-entities", false)
+ try {
+ factory.setXIncludeAware(false)
+ factory.setExpandEntityReferences(false)
+ } catch (_: Exception) {
+ // Non-fatal: hardening is best-effort on unsupported parsers.
+ }
+ return try {
+ factory.newDocumentBuilder().parse(stream)
+ } catch (e: Exception) {
+ throw DocumentError.Corrupt("invalid XML: ${e.message ?: e.javaClass.simpleName}", e)
+ }
+ }
+
+ @Suppress("SwallowedException")
+ private fun setFeatureSafely(factory: DocumentBuilderFactory, feature: String, enabled: Boolean) {
+ try {
+ factory.setFeature(feature, enabled)
+ } catch (_: Exception) {
+ // Unsupported by this parser — degrade gracefully.
+ }
+ }
+
+ // ---- plain text ----
+
+ private fun decodeText(bytes: ByteArray): String {
+ if (bytes.size >= 3 &&
+ bytes[0] == 0xEF.toByte() && bytes[1] == 0xBB.toByte() && bytes[2] == 0xBF.toByte()
+ ) {
+ // Strip a UTF-8 BOM so it never leaks into the model input.
+ return String(bytes, 3, bytes.size - 3, Charsets.UTF_8)
+ }
+ return String(bytes, Charsets.UTF_8)
+ }
+
+ private fun normalizeWhitespace(raw: String): String = raw
+ .replace("\u0000", "")
+ .replace(Regex("[\\t\\r\\x0B\\x0C]+"), " ")
+ .replace(Regex("[ ]{2,}"), " ")
+ .replace(Regex("( *\n *){3,}"), "\n\n")
+ .trim()
+
+ private fun truncate(text: String): Pair<String, Boolean> {
+ if (text.length <= MAX_EXTRACTED_CHARS) return text to false
+ val budget = (MAX_EXTRACTED_CHARS - TRUNCATION_NOTE.length).coerceAtLeast(1)
+ return (text.take(budget).trimEnd() + TRUNCATION_NOTE) to true
+ }
+}
diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
index 98a4542..77f3fe5 100644
--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
@@ -30,6 +30,7 @@ import androidx.compose.material.icons.automirrored.rounded.VolumeOff
import androidx.compose.material.icons.automirrored.rounded.VolumeUp
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Edit
+import androidx.compose.material.icons.filled.InsertDriveFile
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.Share
@@ -57,6 +58,7 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
@@ -75,28 +77,42 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.gotcha.R
+import com.gotcha.agent.Attachment
import com.gotcha.agent.ChatUiState
+import com.gotcha.agent.PickedFile
import com.gotcha.tools.AgentMode
+import com.gotcha.tools.FileResolver
import com.gotcha.ui.theme.GotchaMono
import com.gotcha.ui.theme.LocalSkin
import com.gotcha.ui.theme.SkinAlertDialog
import com.gotcha.ui.theme.SkinDropdownMenu
import com.gotcha.ui.theme.motionSpec
import kotlinx.coroutines.delay
+import kotlinx.serialization.json.Json
import 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)
@Composable
fun ChatScreen(
state: ChatUiState,
- onSend: (String, String?, Boolean) -> Unit,
+ onSend: (String, String?, Attachment?, Boolean) -> Unit,
onStop: () -> Unit,
onConfirm: (Boolean) -> Unit,
onAnswer: (String?) -> Unit,
onOpenDrawer: () -> Unit,
onOpenSettings: () -> Unit,
sessionTitle: String? = null,
- onPickImage: (Uri) -> String?,
+ onPickFile: (Uri) -> PickedFile?,
onSwitchAgent: () -> Unit,
onSetAgent: (AgentMode) -> Unit = {},
onSpeak: (String) -> Unit = {},
@@ -106,7 +122,7 @@ fun ChatScreen(
onExportChat: () -> Unit = {},
onReturnToRunning: () -> Unit = {},
onCreateShareCard: () -> Unit = {},
- onEditMessage: (Long, String, String?) -> Unit = { _, _, _ -> },
+ onEditMessage: (Long, String, String?, Attachment?) -> Unit = { _, _, _, _ -> },
onRevertMessage: (Long) -> Unit = { _ -> }
) {
val skin = LocalSkin.current
@@ -119,6 +135,9 @@ fun ChatScreen(
var inputWasVoice by rememberSaveable { mutableStateOf(false) }
var pendingImageUri by rememberSaveable { mutableStateOf<Uri?>(null) }
var pendingImageBase64 by rememberSaveable { mutableStateOf<String?>(null) }
+ var pendingAttachment by rememberSaveable(stateSaver = AttachmentSaver) {
+ mutableStateOf<Attachment?>(null)
+ }
// 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.
@@ -133,12 +152,24 @@ fun ChatScreen(
}
val animatedIds = remember(state.activeSessionId) { mutableSetOf<Long>() }
- val imagePickerLauncher = rememberLauncherForActivityResult(
+ val filePickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.GetContent()
) { uri: Uri? ->
if (uri != null) {
- pendingImageUri = uri
- pendingImageBase64 = onPickImage(uri)
+ when (val picked = onPickFile(uri)) {
+ is PickedFile.Image -> {
+ pendingImageUri = uri
+ pendingImageBase64 = picked.base64
+ pendingAttachment = null
+ }
+ is PickedFile.Document -> {
+ pendingImageUri = null
+ pendingImageBase64 = null
+ pendingAttachment = picked.attachment
+ }
+ // A failed pick already surfaced its own error bubble.
+ null -> {}
+ }
}
}
@@ -303,12 +334,17 @@ fun ChatScreen(
onStopSpeaking = onStopSpeaking,
onEdit = { target ->
editingMessageId = target.id
- // "(image attached)" is the display placeholder for an
- // image-only prompt; leave the composer empty for those.
- input = if (target.text == "(image attached)") "" else target.text
+ // "(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
+ }
inputWasVoice = false
pendingImageUri = null
pendingImageBase64 = target.imageBase64
+ pendingAttachment = target.attachment
},
onRevert = { target -> pendingRevertId = target.id }
)
@@ -440,6 +476,56 @@ fun ChatScreen(
}
}
+ // 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 (state.isSpeaking) {
Surface(
color = MaterialTheme.colorScheme.errorContainer,
@@ -520,6 +606,7 @@ fun ChatScreen(
editingMessageId = null
pendingImageUri = null
pendingImageBase64 = null
+ pendingAttachment = null
input = ""
inputWasVoice = false
}
@@ -545,7 +632,7 @@ fun ChatScreen(
verticalAlignment = Alignment.CenterVertically
) {
IconButton(
- onClick = { imagePickerLauncher.launch("image/*") },
+ onClick = { filePickerLauncher.launch("*/*") },
enabled = !state.isBusy && state.isConfigured && !otherChatRunning
) {
Text("+", style = MaterialTheme.typography.titleLarge)
@@ -637,7 +724,8 @@ fun ChatScreen(
CircularProgressIndicator(modifier = Modifier.size(20.dp))
}
}
- input.isBlank() && pendingImageBase64 == null && editingMessageId == null -> {
+ input.isBlank() && pendingImageBase64 == null && pendingAttachment == null &&
+ editingMessageId == null -> {
IconButton(
onClick = onStartListening,
modifier = Modifier.size(40.dp),
@@ -651,19 +739,20 @@ fun ChatScreen(
onClick = {
val editTarget = editingMessageId
if (editTarget != null) {
- onEditMessage(editTarget, input, pendingImageBase64)
+ onEditMessage(editTarget, input, pendingImageBase64, pendingAttachment)
} else {
- onSend(input, pendingImageBase64, inputWasVoice)
+ onSend(input, pendingImageBase64, pendingAttachment, inputWasVoice)
}
editingMessageId = null
input = ""
inputWasVoice = false
pendingImageUri = null
pendingImageBase64 = null
+ pendingAttachment = null
},
modifier = Modifier.size(40.dp).testTag("send_button"),
enabled = state.isConfigured && !otherChatRunning &&
- (input.isNotBlank() || pendingImageBase64 != null)
+ (input.isNotBlank() || pendingImageBase64 != null || pendingAttachment != null)
) {
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.kt
index 67f9a54..2a2c938 100644
--- a/app/src/main/java/com/gotcha/ui/MessageBubble.kt
+++ b/app/src/main/java/com/gotcha/ui/MessageBubble.kt
@@ -28,6 +28,7 @@ import androidx.compose.material.icons.automirrored.rounded.VolumeOff
import androidx.compose.material.icons.automirrored.rounded.VolumeUp
import androidx.compose.material.icons.filled.ExpandLess
import androidx.compose.material.icons.filled.ExpandMore
+import androidx.compose.material.icons.filled.InsertDriveFile
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
@@ -163,6 +164,46 @@ 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
+ )
+ }
+ }
+ }
message.reasoningContent?.let { reasoning ->
var reasoningExpanded by remember { mutableStateOf(false) }
Column(
diff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelAttachmentTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelAttachmentTest.kt
new file mode 100644
index 0000000..51c80ab
--- /dev/null
+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelAttachmentTest.kt
@@ -0,0 +1,123 @@
+package com.gotcha.agent
+
+import android.app.Application
+import androidx.test.core.app.ApplicationProvider
+import com.gotcha.data.LlmProvider
+import com.gotcha.data.Settings
+import com.gotcha.data.SettingsRepository
+import com.gotcha.llm.ChatMessage
+import com.gotcha.testsupport.FakeAndroidKeyStore
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+import org.robolectric.shadows.ShadowLooper
+
+/**
+ * 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
+ * port that refuses connections so the run fails fast and the test stays hermetic.
+ */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34])
+class ChatViewModelAttachmentTest {
+
+ private val application: Application = ApplicationProvider.getApplicationContext()
+ private lateinit var settingsRepository: SettingsRepository
+ private lateinit var viewModel: ChatViewModel
+
+ @Before
+ fun setUp() {
+ FakeAndroidKeyStore.setUp()
+ settingsRepository = SettingsRepository(application)
+ settingsRepository.save(
+ Settings(
+ provider = LlmProvider.OPENAI_COMPATIBLE,
+ apiKey = "test-key",
+ baseUrl = "http://127.0.0.1:1/v1"
+ )
+ )
+ viewModel = ChatViewModel(application)
+ ShadowLooper.idleMainLooper()
+ }
+
+ private fun doc(name: String = "report.pdf", text: String = "PDF BODY"): Attachment =
+ Attachment(name, "application/pdf", text.length.toLong(), text, pageCount = 2)
+
+ /** Reads the live engine history without hitting the network. */
+ private fun engineHistory(): List<ChatMessage> {
+ val field = ChatViewModel::class.java.getDeclaredField("agentEngine")
+ .apply { isAccessible = true }
+ return (field.get(viewModel) as AgentEngine).history.toList()
+ }
+
+ /**
+ * Drains the main looper until the run in flight finishes (the refused
+ * connection fails fast), so a follow-up action is not swallowed by the
+ * busy gate.
+ */
+ private fun waitForRunToFinish() {
+ val deadline = System.currentTimeMillis() + 5_000
+ while (System.currentTimeMillis() < deadline && viewModel.uiState.value.isBusy) {
+ ShadowLooper.idleMainLooper()
+ Thread.sleep(10)
+ }
+ ShadowLooper.idleMainLooper()
+ }
+
+ @Test
+ fun `sendMessage with a document builds a document message in history`() {
+ viewModel.sendMessage("summarize", null, 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)
+
+ val last = engineHistory().last()
+ assertTrue(last.textContent.contains("[Attached file: report.pdf (application/pdf, 2 pages)]"))
+ assertTrue(last.textContent.contains("PDF BODY"))
+ }
+
+ @Test
+ fun `sendMessage with only a document shows the document placeholder`() {
+ viewModel.sendMessage("", null, 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)
+ }
+
+ @Test
+ fun `sendMessage is a no-op when input and attachments are all empty`() {
+ val before = viewModel.uiState.value.messages.size
+
+ viewModel.sendMessage(" ", null, null)
+ ShadowLooper.idleMainLooper()
+
+ assertEquals(before, viewModel.uiState.value.messages.size)
+ assertTrue(engineHistory().isEmpty())
+ }
+
+ @Test
+ fun `editMessage re-sends the original document when none is picked`() {
+ viewModel.sendMessage("original question", null, doc("doc.pdf", "DOC BODY"))
+ waitForRunToFinish()
+ val targetId = viewModel.uiState.value.messages.first { it.kind == MessageKind.USER }.id
+
+ viewModel.editMessage(targetId = targetId, newText = "edited question", imageBase64 = null, attachment = null)
+ waitForRunToFinish()
+
+ val last = engineHistory().last()
+ assertTrue(last.textContent.contains("edited question"))
+ assertTrue(
+ "edited message must keep the original attachment",
+ last.textContent.contains("[Attached file: doc.pdf")
+ )
+ assertTrue("edited message must keep the extracted body", last.textContent.contains("DOC BODY"))
+ }
+}
diff --git a/app/src/test/java/com/gotcha/llm/ModelsTest.kt b/app/src/test/java/com/gotcha/llm/ModelsTest.kt
index cb96bf3..8c1c3e3 100644
--- a/app/src/test/java/com/gotcha/llm/ModelsTest.kt
+++ b/app/src/test/java/com/gotcha/llm/ModelsTest.kt
@@ -95,6 +95,76 @@ class ModelsTest {
assertNull(ChatMessage(role = "assistant", content = null).imageUrl())
}
+ // ---- document attachments ----
+
+ @Test
+ fun `documentUserMessage puts header and body in the single first text part`() {
+ val msg = documentUserMessage("summarize this", "report.pdf", "application/pdf", "Page one body", pageCount = 3)
+
+ assertEquals("user", msg.role)
+ val parts = (msg.content as JsonArray)
+ assertEquals("one text part only — a second part would break token accounting", 1, parts.size)
+
+ val textPart = parts[0].jsonObject
+ assertEquals("text", textPart["type"]!!.jsonPrimitive.content)
+ val text = textPart["text"]!!.jsonPrimitive.content
+ assertTrue(text.startsWith("summarize this"))
+ assertTrue(text.contains("[Attached file: report.pdf (application/pdf, 3 pages)]"))
+ assertTrue(text.contains("Page one body"))
+ }
+
+ @Test
+ fun `documentUserMessage textContent returns header and body for token accounting`() {
+ val msg =
+ documentUserMessage(
+ "Q",
+ "doc.docx",
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ "BODY"
+ )
+ // The critical contract: textContent must see the whole payload so token
+ // counts, trimmedHistory and compaction don't silently drop the document.
+ assertTrue(msg.textContent.contains("[Attached file: doc.docx"))
+ assertTrue(msg.textContent.contains("BODY"))
+ }
+
+ @Test
+ fun `documentUserMessage falls back to a default prompt for blank text`() {
+ val msg = documentUserMessage(" ", "x.pdf", "application/pdf", "body")
+ assertTrue(msg.textContent.contains("Answer questions about the attached file."))
+ }
+
+ @Test
+ fun `documentUserMessage uses a placeholder body when extraction is empty`() {
+ val msg = documentUserMessage("q", "x.pdf", "application/pdf", "")
+ assertTrue(msg.textContent.contains("could not be read"))
+ }
+
+ @Test
+ fun `documentUserMessage omits page count when null`() {
+ val msg = documentUserMessage("q", "x.txt", "text/plain", "body")
+ assertTrue(msg.textContent.contains("[Attached file: x.txt (text/plain)]"))
+ assertFalse(msg.textContent.contains("pages"))
+ }
+
+ @Test
+ fun `document message content survives a serialization round-trip`() {
+ val original =
+ documentUserMessage(
+ "q",
+ "x.xlsx",
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ "A1 | 42",
+ pageCount = null
+ )
+ val decoded = json.decodeFromString(
+ ChatMessage.serializer(),
+ json.encodeToString(ChatMessage.serializer(), original)
+ )
+ assertEquals(original, decoded)
+ assertEquals(1, decoded.content!!.jsonArray.size)
+ }
+
@Test
fun `imageUrl returns null when the content array has no image part`() {
val msg = ChatMessage(
diff --git a/app/src/test/java/com/gotcha/tools/DocumentParserPdfTest.kt b/app/src/test/java/com/gotcha/tools/DocumentParserPdfTest.kt
new file mode 100644
index 0000000..9e89787
--- /dev/null
+++ b/app/src/test/java/com/gotcha/tools/DocumentParserPdfTest.kt
@@ -0,0 +1,87 @@
+package com.gotcha.tools
+
+import androidx.test.core.app.ApplicationProvider
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Assert.fail
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+
+/**
+ * PDF extraction via pdfbox-android. pdfbox-android calls `android.util.Log` and
+ * loads its glyph tables from Android assets, so this tier runs under
+ * Robolectric (which provides both) rather than plain JVM.
+ */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34])
+class DocumentParserPdfTest {
+
+ @Before
+ fun setUp() {
+ // Point pdfbox's resource loader at the (merged) app assets.
+ DocumentParser.init(ApplicationProvider.getApplicationContext())
+ }
+
+ @Test
+ fun `pdf text is extracted and page count reported`() {
+ val doc = DocumentParser.extract(minimalPdf("Hello PDF World"), "report.pdf", "application/pdf")
+ assertTrue(
+ "extracted text should contain the page content, got: '${doc.text}'",
+ doc.text.contains("Hello PDF World")
+ )
+ assertEquals(1, doc.pageCount)
+ assertEquals("application/pdf", doc.mimeType)
+ }
+
+ @Test
+ fun `pdf is recognised by extension alone`() {
+ val doc = DocumentParser.extract(minimalPdf("Extension based"), "file.pdf", null)
+ assertTrue(doc.text.contains("Extension based"))
+ assertEquals(1, doc.pageCount)
+ }
+
+ @Test
+ fun `corrupt pdf throws Corrupt`() {
+ try {
+ DocumentParser.extract("this is not a pdf".toByteArray(), "broken.pdf", "application/pdf")
+ fail("expected Corrupt")
+ } catch (e: DocumentError.Corrupt) {
+ assertTrue(e.message!!.isNotBlank())
+ }
+ }
+
+ /**
+ * Builds a minimal one-page PDF (Catalog → Pages → Page → Contents) with a
+ * single Helvetica text run, computing correct xref byte offsets so any
+ * strict parser can read it without the repair-fallback path.
+ */
+ private fun minimalPdf(text: String): ByteArray {
+ val stream = "BT /F1 24 Tf 100 700 Td ($text) Tj ET"
+ val objects = listOf(
+ "<< /Type /Catalog /Pages 2 0 R >>",
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] " +
+ "/Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>",
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ "<< /Length ${stream.toByteArray().size} >>\nstream\n$stream\nendstream"
+ )
+
+ val sb = StringBuilder("%PDF-1.4\n")
+ val offsets = mutableListOf<Int>()
+ for ((index, obj) in objects.withIndex()) {
+ offsets.add(sb.length)
+ sb.append("${index + 1} 0 obj\n$obj\nendobj\n")
+ }
+ val xrefOffset = sb.length
+ sb.append("xref\n0 ${objects.size + 1}\n")
+ sb.append("0000000000 65535 f \n")
+ for (offset in offsets) {
+ sb.append(offset.toString().padStart(10, '0')).append(" 00000 n \n")
+ }
+ sb.append("trailer\n<< /Size ${objects.size + 1} /Root 1 0 R >>\nstartxref\n$xrefOffset\n%%EOF\n")
+ return sb.toString().toByteArray()
+ }
+}
diff --git a/app/src/test/java/com/gotcha/tools/DocumentParserTest.kt b/app/src/test/java/com/gotcha/tools/DocumentParserTest.kt
new file mode 100644
index 0000000..d07474a
--- /dev/null
+++ b/app/src/test/java/com/gotcha/tools/DocumentParserTest.kt
@@ -0,0 +1,261 @@
+package com.gotcha.tools
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Assert.fail
+import org.junit.Test
+import java.io.ByteArrayOutputStream
+import java.util.zip.ZipEntry
+import java.util.zip.ZipOutputStream
+
+/**
+ * Pure-JVM behaviour for [DocumentParser] — everything except PDF (which needs
+ * pdfbox-android and lives in [DocumentParserPdfTest] under Robolectric).
+ *
+ * Fixtures are built programmatically (in-memory ZIPs for Office files) so no
+ * binary test assets are committed.
+ */
+class DocumentParserTest {
+
+ // ---- text formats ----
+
+ @Test
+ fun `plain text file extracts as-is`() {
+ val doc = DocumentParser.extract("hello world".toByteArray(), "notes.txt", "text/plain")
+ assertEquals("hello world", doc.text)
+ assertEquals("text/plain", doc.mimeType)
+ assertFalse(doc.truncated)
+ assertNull(doc.pageCount)
+ }
+
+ @Test
+ fun `text file is recognised by extension when mime is generic`() {
+ val doc = DocumentParser.extract("a,b\n1,2".toByteArray(), "data.csv", "application/octet-stream")
+ assertEquals("a,b\n1,2", doc.text)
+ }
+
+ @Test
+ fun `UTF-8 BOM is stripped from text files`() {
+ val bytes = byteArrayOf(0xEF.toByte(), 0xBB.toByte(), 0xBF.toByte()) + "content".toByteArray()
+ val doc = DocumentParser.extract(bytes, "bom.txt", "text/plain")
+ assertEquals("content", doc.text)
+ }
+
+ @Test
+ fun `unknown extension with no mime is unsupported`() {
+ try {
+ DocumentParser.extract("binary?".toByteArray(), "weird.xyz", null)
+ fail("expected UnsupportedFormat")
+ } catch (e: DocumentError.UnsupportedFormat) {
+ assertTrue(e.message!!.contains("xyz"))
+ }
+ }
+
+ // ---- HTML (jsoup) ----
+
+ @Test
+ fun `html is reduced to its text`() {
+ val html = "<html><body><h1>Title</h1><p>Some <b>bold</b> text.</p></body></html>"
+ val doc = DocumentParser.extract(html.toByteArray(), "page.html", "text/html")
+ assertEquals("Title Some bold text.", doc.text)
+ }
+
+ // ---- .docx ----
+
+ @Test
+ fun `docx concatenates text runs per paragraph`() {
+ val bytes = zipWith(
+ "word/document.xml" to
+ """<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
+ <w:body>
+ <w:p><w:r><w:t>Hello </w:t></w:r><w:r><w:t>world</w:t></w:r></w:p>
+ <w:p><w:r><w:t>Second paragraph</w:t></w:r></w:p>
+ </w:body>
+ </w:document>"""
+ )
+ val doc = DocumentParser.extract(bytes, "notes.docx", null)
+ assertEquals("Hello world\nSecond paragraph", doc.text)
+ assertEquals("application/vnd.openxmlformats-officedocument.wordprocessingml.document", doc.mimeType)
+ }
+
+ @Test
+ fun `docx without the document part is corrupt`() {
+ val bytes = zipWith("word/stuff.xml" to "<x/>")
+ try {
+ DocumentParser.extract(bytes, "broken.docx", null)
+ fail("expected Corrupt")
+ } catch (e: DocumentError.Corrupt) {
+ assertTrue(e.message!!.contains("word/document.xml"))
+ }
+ }
+
+ @Test
+ fun `docx with a doctype entity is rejected`() {
+ val malicious = zipWith(
+ "word/document.xml" to
+ """<?xml version="1.0"?>
+ <!DOCTYPE w:document [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
+ <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
+ <w:body><w:p><w:r><w:t>&xxe;</w:t></w:r></w:p></w:body>
+ </w:document>"""
+ )
+ try {
+ DocumentParser.extract(malicious, "evil.docx", null)
+ fail("expected Corrupt for doctype-bearing docx")
+ } catch (e: DocumentError.Corrupt) {
+ // The entity must never be resolved; a parse failure is the safe outcome.
+ assertTrue(e.message!!.contains("invalid XML"))
+ }
+ }
+
+ @Test
+ fun `empty docx yields empty text`() {
+ val bytes = zipWith(
+ "word/document.xml" to
+ """<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
+ <w:body><w:p><w:r><w:t> </w:t></w:r></w:p></w:body>
+ </w:document>"""
+ )
+ assertEquals("", DocumentParser.extract(bytes, "empty.docx", null).text)
+ }
+
+ // ---- .xlsx ----
+
+ @Test
+ fun `xlsx resolves shared strings and inline strings by row`() {
+ val bytes = zipWith(
+ "xl/sharedStrings.xml" to
+ """<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="2" uniqueCount="2">
+ <si><t>Alpha</t></si><si><t>Beta</t></si>
+ </sst>""",
+ "xl/worksheets/sheet1.xml" to
+ """<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
+ <sheetData>
+ <row r="1"><c r="A1" t="s"><v>0</v></c><c r="B1"><v>42</v></c></row>
+ <row r="2"><c r="A2" t="s"><v>1</v></c><c r="B2" t="inlineStr"><is><t>inline text</t></is></c></row>
+ </sheetData>
+ </worksheet>"""
+ )
+ val doc = DocumentParser.extract(bytes, "data.xlsx", null)
+ assertEquals("Alpha | 42\nBeta | inline text", doc.text)
+ assertEquals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", doc.mimeType)
+ }
+
+ @Test
+ fun `xlsx with no worksheets is corrupt`() {
+ val bytes = zipWith("xl/sharedStrings.xml" to "<sst xmlns=\"x\"/>")
+ try {
+ DocumentParser.extract(bytes, "empty.xlsx", null)
+ fail("expected Corrupt")
+ } catch (e: DocumentError.Corrupt) {
+ assertTrue(e.message!!.contains("worksheets"))
+ }
+ }
+
+ // ---- .pptx ----
+
+ @Test
+ fun `pptx joins slide text`() {
+ val bytes = zipWith(
+ "ppt/slides/slide1.xml" to
+ """<p:sld xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"
+ xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
+ <p:cSld><p:spTree>
+ <p:sp><p:txBody><a:p><a:r><a:t>Slide </a:t></a:r><a:r><a:t>one</a:t></a:r></a:p></p:txBody></p:sp>
+ </p:spTree></p:cSld>
+ </p:sld>"""
+ )
+ val doc = DocumentParser.extract(bytes, "deck.pptx", null)
+ assertEquals("Slide one", doc.text)
+ }
+
+ // ---- errors ----
+
+ @Test
+ fun `legacy doc and xls are unsupported with a helpful message`() {
+ for (name in listOf("old.doc", "old.xls")) {
+ try {
+ DocumentParser.extract("not a real office file".toByteArray(), name, null)
+ fail("expected UnsupportedFormat for $name")
+ } catch (e: DocumentError.UnsupportedFormat) {
+ assertTrue(e.message!!.contains("not supported"))
+ }
+ }
+ }
+
+ @Test
+ fun `a zip that is not an office file is unsupported`() {
+ val bytes = zipWith("random.txt" to "hi")
+ try {
+ DocumentParser.extract(bytes, "archive.zip", "application/zip")
+ fail("expected UnsupportedFormat")
+ } catch (e: DocumentError.UnsupportedFormat) {
+ assertTrue(e.message!!.contains("application/zip"))
+ }
+ }
+
+ @Test
+ fun `oversized files throw TooLarge`() {
+ val bytes = ByteArray(DocumentParser.MAX_DOC_BYTES.toInt() + 1)
+ try {
+ DocumentParser.extract(bytes, "big.pdf", "application/pdf")
+ fail("expected TooLarge")
+ } catch (e: DocumentError.TooLarge) {
+ assertTrue(e.message!!.contains("20 MB"))
+ }
+ }
+
+ @Test
+ fun `garbage bytes for a pdf-looking file are corrupt`() {
+ try {
+ DocumentParser.extract("not a pdf at all".toByteArray(), "broken.pdf", "application/pdf")
+ fail("expected Corrupt")
+ } catch (e: DocumentError.Corrupt) {
+ // pdfbox fails cleanly on non-PDF input.
+ assertTrue(e.message!!.isNotBlank())
+ }
+ }
+
+ // ---- truncation ----
+
+ @Test
+ fun `long text is truncated with a visible note`() {
+ val longText = "a".repeat(50_000)
+ val doc = DocumentParser.extract(longText.toByteArray(), "big.txt", "text/plain")
+ assertTrue(doc.truncated)
+ assertTrue(
+ "truncated text must stay at or under the cap",
+ doc.text.length <= DocumentParser.MAX_EXTRACTED_CHARS
+ )
+ assertTrue("truncation must be visible", doc.text.contains("truncated"))
+ }
+
+ @Test
+ fun `short text is not truncated`() {
+ val doc = DocumentParser.extract("short".toByteArray(), "short.txt", "text/plain")
+ assertFalse(doc.truncated)
+ assertEquals("short", doc.text)
+ }
+
+ @Test
+ fun `mime is canonicalised to lowercase`() {
+ val doc = DocumentParser.extract("hi".toByteArray(), "note.TXT", "Text/Plain")
+ assertEquals("text/plain", doc.mimeType)
+ }
+
+ // ---- helpers ----
+
+ private fun zipWith(vararg entries: Pair<String, String>): ByteArray {
+ val baos = ByteArrayOutputStream()
+ ZipOutputStream(baos).use { zos ->
+ for ((name, content) in entries) {
+ zos.putNextEntry(ZipEntry(name))
+ zos.write(content.toByteArray(Charsets.UTF_8))
+ zos.closeEntry()
+ }
+ }
+ return baos.toByteArray()
+ }
+}