openassistant: attached photos actually reach the model (#929)
- Commit
6fa2c66418034ec0ff4ed1730674ab7a14102b3a- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-28 06:27 UTC (8 days ago)
- Parents
b612071
Two compounding breaks dropped photos from the conversation. (1) The composer kept picked photos in a separate async file-copy list and send() read it at click time, so type-question-then-attach-then-send dispatched before large photos finished copying: Message.imagePaths and the intent extra were both empty even though the Uri thumbnail showed in the composer. send() now awaits the per-photo Deferred copy jobs (in pick order) before building imagePaths, and remove-by-index cancels the right job. (2) HistoryTurn was text-only and InferenceService.loadHistory never read Message.imagePaths; the just-sent echo was excluded only by a 1-second recency window, so on a first message with slow service start the photo message came back as a text-only history turn. loadHistory now excludes exactly the just-sent echo by position and carries imagePaths into HistoryTurn, and MamlChatEngine encodes history photos through the vision tower (counted in fitting, dropped whole oldest-first). No DB change — Message.imagePaths already persisted correctly; the engine already handled image soft-tokens, it simply never received them. Regression: 7 new tests (first-message photo reaches the model as a vision input, history photos stay vision inputs on later turns, slow-service-start first message, image parts survive HistoryFit). Verified: :openassistant:testDevUnitTest (199+73) and :openassistant:lint green.
Diff
openassistant/AGENTS.md
diff --git a/openassistant/AGENTS.md b/openassistant/AGENTS.mdindex 34a0e1dff2..ca8ecce595 100644--- a/openassistant/AGENTS.md+++ b/openassistant/AGENTS.md@@ -26,6 +26,7 @@ _Install: ./install openassistant (dev by default)._ - `StubRecognitionService` is a placeholder voice-recognition hook, not a real recognizer - Tool names are snake_case (`get_notes`, `add_to_memory`), matching what LiteRT-LM exposed; the system prompt references them. Add a tool in `domain/AssistantToolSpecs.kt` AND `platform/AssistantTools.kt` (an init check fails if they disagree) - Model files live in `getExternalFilesDir(null)/gemma4/` (text, embed, head, vision, audio, tokenizer); the vision/audio towers load lazily and unload after 3 idle minutes+- Photo attachments: Send in `ui/LiteRTChatUi` awaits the picker copy jobs before dispatching, so the photos shown in the composer are the files bound to the sent `Message.imagePaths` and the inference request. Stored image paths ride `HistoryTurn.imagePaths` through `domain/HistoryFit` (oldest turns drop whole when the history no longer fits) and are re-encoded by the vision tower on each turn, so a photo stays visible to the model on later turns - `util/` is NOT a closed package root — don't add more files there (it holds only `InferenceService`); assistant surfaces are in `service/` - A2UI: the model writes only ```` ```a2ui {"components":[...],"data":{...}} ```` and `domain/A2uiEnvelope` adds the protocol envelope. Surface id is `m<messageId>`; the block is stored in `Message.a2ui` (DB v4) and replayed by `platform/A2uiController.sync`. androidx.a2ui ships no renderer — `ui/A2uiSurfaceView` is ours. Add a component in `platform/AssistantCatalog` (schema + prompt line together) AND the `when` in `A2uiSurfaceView` - `AssistantCatalog.PROMPT_SECTION` is appended to every system prompt, so changing it (or the catalog) invalidates the baked `gemma4_prefix.kv`: still correct, but first turns prefill until it is rebaked with `bake_gemma4_prefix`
openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.ktindex f0d156ec55..0f6440d05e 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt@@ -29,8 +29,15 @@ import kotlinx.coroutines.withContext import java.io.File import java.util.concurrent.Executors -/** One stored message, text only: media is only ever attached to the current turn. */-data class HistoryTurn(val fromUser: Boolean, val text: String)+/**+ * One stored message. A user turn keeps the paths of the photos attached to+ * it, so the picture stays part of the conversation: the engine re-encodes+ * them with the vision tower on each turn and [fitConversation] drops the+ * oldest turns (images included) when the whole history no longer fits.+ * Dropping them here instead made the model answer as if no photo had ever+ * been sent (#929).+ */+data class HistoryTurn(val fromUser: Boolean, val text: String, val imagePaths: List<String> = emptyList()) /** Immutable value describing chat request. */ data class ChatRequest(@@ -76,6 +83,14 @@ open class MamlChatEngine(private val modelDir: File) : AutoCloseable { */ internal var textModelOpener: ((File) -> Pair<TextModel?, String?>)? = null + /**+ * Behavior-preserving test seam for the vision tower: production leaves+ * this null and encodes through [Gemma4VisionHandle]; tests substitute a+ * fake encoder because the tower cannot load on the JVM. A null result+ * drops that image, like a failed encode does in production.+ */+ internal var imageEncoder: ((String) -> FloatArray?)? = null+ /** The text-generation surface [MamlChatEngine] needs from the model. */ internal interface TextModel { val available: Boolean@@ -145,9 +160,11 @@ open class MamlChatEngine(private val modelDir: File) : AutoCloseable { mutex.withLock { val model = withContext(engineThread) { model() } ?: return@withLock ChatResult.Unavailable val declarations = tools.declarations- val current = withContext(engineThread) { currentTurn(request) }- val history = request.history.map {- Gemma4Handle.Turn(if (it.fromUser) Gemma4Handle.Role.USER else Gemma4Handle.Role.MODEL, it.text)+ // History turns are built on the engine thread too: encoding a+ // kept photo runs the vision tower, which is not thread-safe.+ val (current, history) = withContext(engineThread) {+ val builtHistory = request.history.map { historyTurn(it) }+ currentTurn(request) to builtHistory } val conversation = withContext(engineThread) { seedPrefix(model, request.system, declarations)@@ -265,7 +282,19 @@ open class MamlChatEngine(private val modelDir: File) : AutoCloseable { return Gemma4Handle.Turn(Gemma4Handle.Role.USER, request.userText, images, clips) } + /** A stored turn as the model sees it, attached photos encoded as vision inputs. */+ private fun historyTurn(turn: HistoryTurn): Gemma4Handle.Turn {+ val images = if (turn.imagePaths.isEmpty()) emptyList() else encodeImages(turn.imagePaths)+ if (turn.imagePaths.isNotEmpty()) scheduleTowerUnload()+ return Gemma4Handle.Turn(+ if (turn.fromUser) Gemma4Handle.Role.USER else Gemma4Handle.Role.MODEL,+ turn.text,+ images,+ )+ }+ private fun encodeImages(paths: List<String>): List<FloatArray> {+ imageEncoder?.let { encode -> return paths.mapNotNull(encode) } val tower = vision?.takeIf { it.isAvailable } ?: Gemma4VisionHandle.inDirectory(modelDir).also { vision = it } if (!tower.isAvailable) {
openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatUi.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatUi.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatUi.ktindex 572fe90953..96815879d7 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatUi.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatUi.kt@@ -44,9 +44,11 @@ import com.vayunmathur.library.util.NavBackStack import androidx.window.core.layout.WindowSizeClass.Companion.WIDTH_DP_EXPANDED_LOWER_BOUND import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.openassistant.platform.copyUriToFile+import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext import java.io.File /**@@ -75,7 +77,14 @@ fun LiteRTChatUi( var inputText by remember { mutableStateOf("") } val selectedImageUris = remember { mutableStateListOf<Uri>() }- val selectedImageFiles = remember { mutableStateListOf<File>() }+ // One copy job per picked Uri, in pick order. The Uri (and its thumbnail+ // and the enabled Send button) lands synchronously, but the file the+ // model can read only exists once copyUriToFile finishes — so Send must+ // await these jobs, exactly as it awaits the WAV writer. Reading a+ // separately filled file list at Send time could capture zero files+ // for a photo that is visibly attached, and the message then reached+ // the model text-only (#929).+ val selectedImageCopies = remember { mutableStateListOf<Deferred<File?>>() } val recordAudioPermission = rememberPermissionRequest(Manifest.permission.RECORD_AUDIO) { isGranted -> if (isGranted) {@@ -91,12 +100,7 @@ fun LiteRTChatUi( val imagePicker = rememberLauncherForActivityResult(ActivityResultContracts.GetMultipleContents()) { uris -> uris.forEach { uri -> selectedImageUris.add(uri)- scope.launch(Dispatchers.IO) {- val file = copyUriToFile(context, uri)- if(file != null) {- withContext(Dispatchers.Main) { selectedImageFiles.add(file) }- }- }+ selectedImageCopies.add(scope.async(Dispatchers.IO) { copyUriToFile(context, uri) }) } } @@ -129,7 +133,10 @@ fun LiteRTChatUi( val idx = selectedImageUris.indexOf(uri) if (idx != -1) { selectedImageUris.removeAt(idx)- if (idx < selectedImageFiles.size) selectedImageFiles.removeAt(idx)+ // Both lists are appended to in the same pick callback, so+ // the same index names this Uri's copy job — even while the+ // copy is still in flight.+ if (idx < selectedImageCopies.size) selectedImageCopies.removeAt(idx).cancel() } } @@ -138,19 +145,24 @@ fun LiteRTChatUi( } override fun cancelMedia() {- selectedImageUris.clear(); selectedImageFiles.clear()+ selectedImageUris.clear()+ selectedImageCopies.forEach { it.cancel() }; selectedImageCopies.clear() assistantViewModel.cancelRecording() } override fun send() { if (isRecording) assistantViewModel.stopRecording() val newConv = resources.getString(R.string.new_conversation)- val imagePaths = selectedImageFiles.map { it.absolutePath }+ // Snapshot the pending copies at click time: awaiting them below+ // binds exactly the photos shown in the composer to this message,+ // however long their copies take (#929).+ val pendingImageCopies = selectedImageCopies.toList() val textToSend = inputText scope.launch { // Awaited rather than read: the WAV is written after stopRecording() returns, so // reading the path here would dispatch one to a file that does not exist yet. val audioPath = assistantViewModel.awaitRecordedAudio()+ val imagePaths = pendingImageCopies.awaitAll().filterNotNull().map { it.absolutePath } var currentId = conversationId if (currentId == 0L) { currentId = assistantViewModel.upsertConversation(Conversation(newConv))@@ -158,7 +170,7 @@ fun LiteRTChatUi( } assistantViewModel.upsertMessage(Message(currentId, textToSend, "user", imagePaths, audioPath != null)) assistantViewModel.requestInference(currentId, textToSend, imagePaths, audioPath)- inputText = ""; selectedImageFiles.clear(); selectedImageUris.clear()+ inputText = ""; selectedImageCopies.clear(); selectedImageUris.clear() assistantViewModel.consumeRecordedAudio() } }
openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.ktindex 0e05c07cbe..6342883f83 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -95,7 +95,6 @@ class InferenceService : Service() { private const val INTENT_TIMEOUT_MILLIS = 45000L private const val STANDARD_INFERENCE_TIMEOUT_MILLIS = 300_000L private const val INTENT_QUEUE_TTL_MILLIS = 45000L- private const val HISTORY_RECENCY_MILLIS = 1000L private const val DB_WRITE_INTERVAL_MILLIS = 100L private const val AUDIT_OUTCOME_CHARS = 200 private val HOST_CONFIRM = Regex("""\[HostConfirm ([^\]]+)]""")@@ -350,10 +349,13 @@ class InferenceService : Service() { } private suspend fun loadHistory(conversationId: Long, userText: String): List<HistoryTurn> {- val cutoff = Clock.System.now().toEpochMilliseconds() - HISTORY_RECENCY_MILLIS- return store.history(conversationId)- .filter { it.text != userText || it.timestamp < cutoff }- .map { HistoryTurn(fromUser = it.role != "assistant", text = withA2uiBlock(it.text, it.a2ui)) }+ val stored = store.history(conversationId)+ // Exclude exactly the just-sent echo by position, not the old 1 s+ // recency window: a slow first service/model load kept that echo as a+ // text-only history turn and its photo never reached the model (#929).+ val echoIndex = stored.indexOfLast { it.role == "user" && it.text == userText }+ return stored.filterIndexed { index, _ -> index != echoIndex }+ .map { HistoryTurn(it.role != "assistant", withA2uiBlock(it.text, it.a2ui), it.imagePaths) } } private suspend fun executeStandardInference(job: InferenceJob.Standard) {
openassistant/src/test/java/com/vayunmathur/openassistant/domain/HistoryFitTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/HistoryFitTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/HistoryFitTest.ktindex d25f6c4f05..759d21c945 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/HistoryFitTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/HistoryFitTest.kt@@ -35,4 +35,48 @@ class HistoryFitTest { fun emptyHistory() { assertEquals(listOf(current), fitConversation(emptyList(), current, T::user, fitsUnder(5))) }++ // #929: a turn's image parts are part of the turn. Fitting must keep them+ // on the turns it keeps — trimming may drop whole turns, never strip a+ // kept turn down to text only.+ private data class ImgTurn(val user: Boolean, val cost: Int, val images: List<String>)++ @Test+ fun imagePartsSurviveFittingOnKeptTurns() {+ val imgHistory = listOf(+ ImgTurn(true, 10, listOf("/photos/first.jpg")),+ ImgTurn(false, 10, emptyList()),+ ImgTurn(true, 10, listOf("/photos/second.jpg")),+ ImgTurn(false, 10, emptyList()),+ )+ val imgCurrent = ImgTurn(true, 5, listOf("/photos/current.jpg"))+ assertEquals(+ imgHistory + imgCurrent,+ fitConversation(imgHistory, imgCurrent, ImgTurn::user, { turns -> turns.sumOf { it.cost } <= 100 }),+ )+ // Trimmed to the newest user turn + current: both keep their images.+ assertEquals(+ listOf(imgHistory[2], imgHistory[3], imgCurrent),+ fitConversation(imgHistory, imgCurrent, ImgTurn::user, { turns -> turns.sumOf { it.cost } <= 30 }),+ )+ }++ @Test+ fun firstMessageWithImageKeepsItsImage() {+ // First message of a conversation: no history, the attached photo is+ // on the current turn and must reach the model with its text.+ val imgCurrent = ImgTurn(true, 5, listOf("/photos/first.jpg"))+ val fitted = fitConversation(emptyList(), imgCurrent, ImgTurn::user, { turns -> turns.sumOf { it.cost } <= 5 })+ assertEquals(listOf(imgCurrent), fitted)+ assertEquals(listOf("/photos/first.jpg"), fitted!!.single().images)+ }++ @Test+ fun currentImageTurnIsNeverStrippedWhenHistoryIsTrimmedAway() {+ val imgHistory = listOf(ImgTurn(true, 10, listOf("/photos/old.jpg")), ImgTurn(false, 10, emptyList()))+ val imgCurrent = ImgTurn(true, 5, listOf("/photos/current.jpg"))+ val fitted = fitConversation(imgHistory, imgCurrent, ImgTurn::user, { turns -> turns.sumOf { it.cost } <= 5 })+ assertEquals(listOf(imgCurrent), fitted)+ assertEquals(listOf("/photos/current.jpg"), fitted!!.single().images)+ } }
openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.ktindex 13ccf0bf0b..e639500022 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt@@ -291,6 +291,48 @@ class MamlChatEngineFakeModelTest { e.close() } + // #929: an attached photo must reach the model as a vision input on its+ // turn, with its text — on the first message and on later ones alike.+ // The tower cannot load on the JVM, so the fake encoder stands in for it+ // and the fake text model captures the exact turns it was handed.+ private fun visionEngine(fake: FakeTextModel): MamlChatEngine {+ val e = engine(fake)+ e.imageEncoder = { path -> FloatArray(1536) { i -> if (i == 0) path.length.toFloat() else 0f } }+ return e+ }++ @Test fun firstMessagePhotoReachesModelAsVisionInput() = runBlocking {+ val fake = FakeTextModel()+ val e = visionEngine(fake)+ val result = e.chat(+ ChatRequest("sys", emptyList(), "what is in this photo?", imagePaths = listOf("/photos/first.jpg")),+ tools(),+ ) { true }+ assertEquals(ChatResult.Reply("plain answer", halted = false), result)+ val turn = fake.lastConversation.single()+ assertEquals("what is in this photo?", turn.text)+ assertEquals(1, turn.images.size, "first-message photo must be a vision input, got ${turn.images.size}")+ assertEquals(1536, turn.images.single().size)+ e.close()+ }++ @Test fun historyPhotoReachesModelAsVisionInputOnLaterTurns() = runBlocking {+ val fake = FakeTextModel()+ val e = visionEngine(fake)+ val history = listOf(+ HistoryTurn(true, "what is in this photo?", imagePaths = listOf("/photos/first.jpg")),+ HistoryTurn(false, "a dog"),+ )+ val result = e.chat(ChatRequest("sys", history, "what colour is it?"), tools()) { true }+ assertEquals(ChatResult.Reply("plain answer", halted = false), result)+ val photoTurn = fake.lastConversation.first()+ assertEquals("what is in this photo?", photoTurn.text)+ assertEquals(1, photoTurn.images.size, "history photo must stay a vision input, got ${photoTurn.images.size}")+ // The follow-up turn itself is text-only, as sent.+ assertTrue(fake.lastConversation.last().images.isEmpty())+ e.close()+ }+ @Test fun historyIsTrimmedWhenItCannotFit() = runBlocking { val fake = FakeTextModel() fake.script = { _, onToken -> onToken("ok"); "ok" }
openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.ktindex 27b539ffe6..0506bfb0b1 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt@@ -1,5 +1,7 @@ package com.vayunmathur.openassistant.util +// FIXTURE RELATIVE-TIME EXCEPTION: timestamps are seeded relative to the wall clock the code under test reads internally, so the fresh/expired/relative-time branch under test keeps its meaning; a fixed past instant would silently change that branch.+ import android.content.Intent import android.os.Bundle import android.os.Handler@@ -335,6 +337,58 @@ class InferenceServiceFakeEngineTest { assertTrue(File(paths[1]).exists(), "copied image should exist: ${paths[1]}") } + // #929: the first message of a conversation, photo attached. The stored+ // user row is minutes old by the time a cold service has loaded the+ // model, so the old 1 s recency window kept it as a text-only history+ // echo and its photo never reached the model. The echo is now excluded+ // by position and the photo rides the current turn.+ @Test fun firstMessagePhotoSurvivesSlowServiceStart() {+ val now = System.currentTimeMillis()+ kotlinx.coroutines.runBlocking {+ messageDao.upsert(+ Message(31L, "what is in this photo?", "user", imagePaths = listOf("/photos/first.jpg"), timestamp = now - 300_000),+ )+ }+ val fake = FakeEngine()+ val service = startService(fake)+ val intent = Intent(ctx, InferenceService::class.java).apply {+ putExtra("conversation_id", 31L); putExtra("user_text", "what is in this photo?")+ putExtra("image_paths", arrayOf("/photos/first.jpg"))+ }+ service.onStartCommand(intent, 0, 1)+ await("reply") { fake.lastRequest != null && messageDao.assistantTexts(31L).contains("default reply") }+ val req = assertNotNull(fake.lastRequest)+ assertTrue(req.history.isEmpty(), "just-sent echo must not reappear as history: ${req.history}")+ assertEquals(listOf("/photos/first.jpg"), req.imagePaths)+ assertEquals("what is in this photo?", req.userText)+ }++ // #929: a photo attached to an earlier message stays part of the+ // conversation — HistoryTurn carries imagePaths from the stored row, so+ // a later text-only follow-up still reaches the model with the photo as+ // a vision input on its original turn.+ @Test fun earlierPhotoIsCarriedIntoLaterTurnHistory() {+ val now = System.currentTimeMillis()+ kotlinx.coroutines.runBlocking {+ messageDao.upsert(+ Message(32L, "what is in this photo?", "user", imagePaths = listOf("/photos/first.jpg"), timestamp = now - 300_000),+ )+ messageDao.upsert(Message(32L, "a dog on a beach", "assistant", timestamp = now - 290_000))+ messageDao.upsert(Message(32L, "what colour is it?", "user", timestamp = now))+ }+ val fake = FakeEngine()+ val service = startService(fake)+ service.onStartCommand(standardIntent(32L, "what colour is it?"), 0, 1)+ await("reply") { fake.lastRequest != null && messageDao.assistantTexts(32L).contains("default reply") }+ val req = assertNotNull(fake.lastRequest)+ assertEquals(2, req.history.size)+ val photoTurn = req.history.first()+ assertTrue(photoTurn.fromUser)+ assertEquals("what is in this photo?", photoTurn.text)+ assertEquals(listOf("/photos/first.jpg"), photoTurn.imagePaths)+ assertTrue(req.imagePaths.isEmpty(), "follow-up sent no new photo: ${req.imagePaths}")+ }+ @Test fun customSystemPromptIsUsed() { kotlinx.coroutines.runBlocking { com.vayunmathur.library.util.DataStoreUtils.getInstance(ctx)