openassistant: queued messages no longer leak into earlier turns
- Commit
3cf1174b6a96c6c112277ae7603df2c9589f695d- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-30 19:37 UTC (5 days ago)
- Parents
00be8a5
Sending twice in quick succession corrupted the conversation:
both user rows were persisted before the first inference job ran,
and loadHistory excluded only the text-matched 'just-sent echo',
so the queued second message leaked into the first turn's history
— the model saw 'second question' before its own current turn
'first question', then answered the second message again as its
own job. The same text-only match also silently failed when
screen context prepended text, leaving the echo in history.
The inserted row ID ('user_message_id') now threads from the UI
through the standard-inference queue into loadHistory, and the
new pure HistoryFit.historyForCurrentTurn drops every user row
after the echo while keeping non-user follow-ups; legacy senders
keep the text fallback. New regression test failed pre-fix (the
queued message leaked into history) and passes now. History
fitting, tool-call exactly-once, web tools, timeouts and settings
were audited and cleared. Verified: :openassistant:testDevUnitTest
201 JVM + 74 native tests pass; lint green.Diff
openassistant/src/main/java/com/vayunmathur/openassistant/domain/HistoryFit.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/HistoryFit.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/HistoryFit.ktindex ab0a6550fc..081b6b89e3 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/HistoryFit.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/HistoryFit.kt@@ -23,3 +23,29 @@ fun <T> fitConversation( } return history.drop(low).dropWhile { !isUserTurn(it) } + current }++/**+ * [stored] turns with the just-sent echo removed, ready to precede the current turn.+ *+ * The echo is named by its row [echoId] when supplied: text matching picks the last+ * matching user row, which is the wrong row when a later send is already stored (it+ * waits in the queue while this turn runs), so that later turn leaked ahead of its own+ * answer and then repeated as the next turn's current. User rows after the echo are+ * queued sends and stay out; non-user rows after it (a prior queued turn's reply, a+ * host confirmation) are real history and stay. Without a usable id, falls back to+ * dropping the last user row whose text is [echoText].+ */+fun <T> historyForCurrentTurn(+ stored: List<T>,+ echoId: Long,+ echoText: String,+ idOf: (T) -> Long,+ isUser: (T) -> Boolean,+ textOf: (T) -> String,+): List<T> =+ if (echoId > 0 && stored.any { idOf(it) == echoId }) {+ stored.filter { idOf(it) != echoId && !(isUser(it) && idOf(it) > echoId) }+ } else {+ val echoIndex = stored.indexOfLast { isUser(it) && textOf(it) == echoText }+ stored.filterIndexed { index, _ -> index != echoIndex }+ }
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantViewModel.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantViewModel.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantViewModel.ktindex 3ce0c36279..44ff2e3cf5 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantViewModel.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantViewModel.kt@@ -100,8 +100,8 @@ class AssistantViewModel( viewModelScope, onAction = { conversationId, text -> viewModelScope.launch {- upsertMessage(Message(conversationId, text, "user"))- requestInference(conversationId, text, emptyList(), null)+ val userMessageId = upsertMessage(Message(conversationId, text, "user"))+ requestInference(conversationId, text, emptyList(), null, userMessageId) } }, onHostAction = { conversationId, eventName, context ->@@ -156,8 +156,8 @@ class AssistantViewModel( }.toString() val text = "[HostSendMsg $payload]" viewModelScope.launch {- upsertMessage(Message(conversationId, text, "user"))- requestInference(conversationId, text, emptyList(), null)+ val userMessageId = upsertMessage(Message(conversationId, text, "user"))+ requestInference(conversationId, text, emptyList(), null, userMessageId) } return true }@@ -187,8 +187,8 @@ class AssistantViewModel( // (see AssistantWebTools), so index resolution works here. val fetched = AssistantWebTools().webReadResultText(index) val text = "[Web read $index: $fetched]"- upsertMessage(Message(conversationId, text, "user"))- requestInference(conversationId, text, emptyList(), null)+ val userMessageId = upsertMessage(Message(conversationId, text, "user"))+ requestInference(conversationId, text, emptyList(), null, userMessageId) } return true }@@ -203,8 +203,8 @@ class AssistantViewModel( if (id.isBlank()) return false val text = "[$marker $id]" viewModelScope.launch {- upsertMessage(Message(conversationId, text, "user"))- requestInference(conversationId, text, emptyList(), null)+ val userMessageId = upsertMessage(Message(conversationId, text, "user"))+ requestInference(conversationId, text, emptyList(), null, userMessageId) } return true }@@ -358,6 +358,10 @@ class AssistantViewModel( userText: String, imagePaths: List<String>, audioPath: String?,+ // Row id of the already-persisted user message, so the service can+ // name that exact echo (and any later queued sends) in its history+ // load instead of matching by text. Null for senders with no row.+ userMessageId: Long? = null, ) { val screenContext = pendingScreenContext pendingScreenContext = null@@ -372,6 +376,7 @@ class AssistantViewModel( putExtra("user_text", effectiveText) putExtra("image_paths", imagePaths.toTypedArray()) putExtra("audio_path", audioPath)+ if (userMessageId != null) putExtra("user_message_id", userMessageId) }) }
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 96815879d7..ed1b0a5058 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatUi.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatUi.kt@@ -168,8 +168,10 @@ fun LiteRTChatUi( currentId = assistantViewModel.upsertConversation(Conversation(newConv)) backStack.reset(Route.ConversationPage(currentId)) }- assistantViewModel.upsertMessage(Message(currentId, textToSend, "user", imagePaths, audioPath != null))- assistantViewModel.requestInference(currentId, textToSend, imagePaths, audioPath)+ val userMessageId = assistantViewModel.upsertMessage(+ Message(currentId, textToSend, "user", imagePaths, audioPath != null),+ )+ assistantViewModel.requestInference(currentId, textToSend, imagePaths, audioPath, userMessageId) 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 6342883f83..078f2ea053 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -53,6 +53,7 @@ import com.vayunmathur.openassistant.data.MessageDao import com.vayunmathur.openassistant.data.PendingToolCallDao import com.vayunmathur.openassistant.data.PendingToolCallEntity import com.vayunmathur.openassistant.domain.ParsedToolCall+import com.vayunmathur.openassistant.domain.historyForCurrentTurn import com.vayunmathur.openassistant.domain.PendingToolCall import com.vayunmathur.openassistant.domain.redactedArgsSummary import com.vayunmathur.openassistant.platform.A2uiTemplates@@ -153,6 +154,8 @@ class InferenceService : Service() { val userText: String, val imagePaths: Array<String>, val audioPath: String?,+ /** Persisted row id of the user message this job answers, or -1 when the sender did not supply one. */+ val userMessageId: Long = -1L, ) : InferenceJob() } @@ -248,6 +251,7 @@ class InferenceService : Service() { intent.setExtrasClassLoader(SecureResultReceiver::class.java.classLoader) val conversationId = intent.getLongExtra("conversation_id", -1L)+ val userMessageId = intent.getLongExtra("user_message_id", -1L) val userText = intent.getStringExtra("user_text") ?: "" val audioPath = intent.getStringExtra("audio_path") val schema = intent.getStringExtra("schema")@@ -268,7 +272,7 @@ class InferenceService : Service() { intentQueue.trySend(InferenceJob.Intent(userText, imagePaths, schema, receiver, nowMillis())) } else if (conversationId != -1L) { Log.dev("InferenceService", "Queueing standard inference for conversation: $conversationId")- standardQueue.trySend(InferenceJob.Standard(conversationId, userText, imagePaths, audioPath))+ standardQueue.trySend(InferenceJob.Standard(conversationId, userText, imagePaths, audioPath, userMessageId)) } } @@ -348,20 +352,16 @@ class InferenceService : Service() { } } - private suspend fun loadHistory(conversationId: Long, userText: String): List<HistoryTurn> {- 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 }+ // The just-sent echo is excluded by row id (see domain historyForCurrentTurn),+ // not the old 1 s recency window that kept it text-only on slow starts (#929).+ private suspend fun loadHistory(conversationId: Long, userText: String, userMessageId: Long = -1L): List<HistoryTurn> =+ historyForCurrentTurn(store.history(conversationId), userMessageId, userText, { it.id }, { it.role == "user" }, { it.text }) .map { HistoryTurn(it.role != "assistant", withA2uiBlock(it.text, it.a2ui), it.imagePaths) }- } private suspend fun executeStandardInference(job: InferenceJob.Standard) { try { ensureEngineInitialized()- runInferenceLoop(job.conversationId, job.userText, job.imagePaths, job.audioPath)+ runInferenceLoop(job.conversationId, job.userText, job.imagePaths, job.audioPath, job.userMessageId) } catch (e: CancellationException) { throw e } catch (expected: Exception) {@@ -379,7 +379,7 @@ class InferenceService : Service() { } try { ensureEngineInitialized()- runInferenceLoop(job.conversationId, job.userText, job.imagePaths, job.audioPath)+ runInferenceLoop(job.conversationId, job.userText, job.imagePaths, job.audioPath, job.userMessageId) } catch (e: CancellationException) { throw e } catch (retryExpected: Exception) {@@ -589,13 +589,14 @@ class InferenceService : Service() { userText: String, imagePaths: Array<String>, audioPath: String?,+ userMessageId: Long = -1L, ) { if (handleHostSendMarker(conversationId, userText)) return val chat = engine ?: failEngine() val effectiveUserText = handleHostMarker(conversationId, userText) ?: userText val request = ChatRequest( system = systemPrompt(),- history = loadHistory(conversationId, userText),+ history = loadHistory(conversationId, userText, userMessageId), userText = effectiveUserText, imagePaths = imagePaths.toList(), audioPath = audioPath?.takeIf { File(it).exists() },
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 759d21c945..47b98d2db6 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/HistoryFitTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/HistoryFitTest.kt@@ -31,6 +31,35 @@ class HistoryFitTest { assertNull(fitConversation(history, current, T::user, fitsUnder(4))) } + private data class Row(val id: Long, val user: Boolean, val text: String)++ private fun kept(rows: List<Row>, echoId: Long, echoText: String) =+ historyForCurrentTurn(rows, echoId, echoText, Row::id, Row::user, Row::text)++ @Test+ fun echoByIdDropsQueuedLaterUserTurnsButKeepsLaterReplies() {+ val rows = listOf(+ Row(1, true, "first question"),+ Row(2, true, "second question"),+ Row(3, false, "first answer"),+ )+ // First turn (only the two user rows exist yet): the queued second+ // question is not history.+ assertEquals(emptyList(), kept(rows.take(2), echoId = 1, echoText = "first question"))+ // Second turn: the first exchange is history, in order, no self-duplicate.+ assertEquals(listOf(rows[0], rows[2]), kept(rows, echoId = 2, echoText = "second question"))+ }++ @Test+ fun echoByIdBeatsDuplicateTextAndTextFallbackStillWorks() {+ val rows = listOf(Row(1, true, "repeat"), Row(2, false, "answer"), Row(3, true, "repeat"))+ assertEquals(listOf(rows[0], rows[1]), kept(rows, echoId = 3, echoText = "repeat"))+ // No id (legacy sender): last matching user row is the echo.+ assertEquals(listOf(rows[0], rows[1]), kept(rows, echoId = -1, echoText = "repeat"))+ // Unknown id falls back to text matching rather than dropping nothing.+ assertEquals(listOf(rows[0], rows[1]), kept(rows, echoId = 99, echoText = "repeat"))+ }+ @Test fun emptyHistory() { assertEquals(listOf(current), fitConversation(emptyList(), current, T::user, fitsUnder(5)))
openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantViewModelTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantViewModelTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantViewModelTest.ktindex 20ef67647a..aa871332a0 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantViewModelTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantViewModelTest.kt@@ -39,10 +39,11 @@ class AssistantViewModelTest { private fun nextService(): Intent = Shadows.shadowOf(app).nextStartedService @Test fun requestInferenceDispatchesExtras() {- vm.requestInference(42L, "hello there", listOf("/a.png", "/b.png"), "/audio.wav")+ vm.requestInference(42L, "hello there", listOf("/a.png", "/b.png"), "/audio.wav", 99L) val intent = nextService() assertEquals(InferenceService::class.java.name, intent.component?.className) assertEquals(42L, intent.getLongExtra("conversation_id", -1L))+ assertEquals(99L, intent.getLongExtra("user_message_id", -1L)) assertEquals("hello there", intent.getStringExtra("user_text")) assertEquals( listOf("/a.png", "/b.png"),
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 0506bfb0b1..d229a51f1f 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt@@ -182,6 +182,49 @@ class InferenceServiceFakeEngineTest { assertTrue(history.any { it.text == "earlier answer" && !it.fromUser }) } + // A second message sent while the first still waits for the engine (cold+ // start, or a reply still streaming) is already in the DB when the first+ // job loads history. It belongs to the next job: it must not appear as a+ // history turn before its own reply, nor again as that job's history.+ @Test fun queuedSecondMessageDoesNotLeakIntoFirstTurn() {+ val now = System.currentTimeMillis()+ var firstId = 0L+ var secondId = 0L+ kotlinx.coroutines.runBlocking {+ firstId = messageDao.upsert(Message(41L, "first question", "user", timestamp = now - 2_000))+ secondId = messageDao.upsert(Message(41L, "second question", "user", timestamp = now - 1_000))+ }+ val fake = FakeEngine()+ val service = startService(fake)+ val firstIntent = Intent(ctx, InferenceService::class.java).apply {+ putExtra("conversation_id", 41L); putExtra("user_text", "first question")+ putExtra("user_message_id", firstId)+ }+ service.onStartCommand(firstIntent, 0, 1)+ await("first reply") { fake.lastRequest != null && messageDao.assistantTexts(41L).contains("default reply") }+ val firstRequest = assertNotNull(fake.lastRequest)+ assertEquals("first question", firstRequest.userText)+ assertTrue(+ firstRequest.history.isEmpty(),+ "queued second message must not leak into the first turn: ${firstRequest.history}",+ )++ fake.lastRequest = null+ val secondIntent = Intent(ctx, InferenceService::class.java).apply {+ putExtra("conversation_id", 41L); putExtra("user_text", "second question")+ putExtra("user_message_id", secondId)+ }+ service.onStartCommand(secondIntent, 0, 2)+ await("second reply") { fake.lastRequest != null }+ val secondRequest = assertNotNull(fake.lastRequest)+ assertEquals("second question", secondRequest.userText)+ assertEquals(+ listOf("first question", "default reply"),+ secondRequest.history.map { it.text },+ "second turn keeps the first exchange, in order, with no duplicate of itself",+ )+ }+ @Test fun haltedReplyDeletesPlaceholder() { val fake = FakeEngine(chatBehavior = { _, _ -> ChatResult.Reply("partial", halted = true) }) val service = startService(fake)