Skip to content

Commit 485446a

Browse files
committed
fix(android): keep sent chat messages in history
1 parent 81f4fe6 commit 485446a

7 files changed

Lines changed: 368 additions & 82 deletions

File tree

‎apps/android/app/src/main/java/ai/openclaw/app/chat/ChatController.kt‎

Lines changed: 62 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,7 @@ class ChatController(
227227
role = "user",
228228
content = userContent,
229229
timestampMs = System.currentTimeMillis(),
230+
idempotencyKey = "$runId:user",
230231
)
231232
optimisticMessagesByRunId[runId] = optimisticMessage
232233
_messages.value = _messages.value + optimisticMessage
@@ -352,6 +353,7 @@ class ChatController(
352353
)
353354
if (!isCurrentHistoryLoad(sessionKey, _sessionKey.value, generation, historyLoadGeneration.get())) return
354355
val history = parseHistory(historyJson, sessionKey = sessionKey, previousMessages = _messages.value)
356+
prunePersistedOptimisticMessages(history.messages)
355357
_messages.value = mergeOptimisticMessages(incoming = history.messages, optimistic = optimisticMessagesByRunId.values)
356358
_sessionId.value = history.sessionId
357359
_historyLoading.value = false
@@ -424,10 +426,8 @@ class ChatController(
424426
}
425427
if (runId != null) {
426428
clearPendingRun(runId)
427-
optimisticMessagesByRunId.remove(runId)
428429
} else {
429-
clearPendingRuns()
430-
optimisticMessagesByRunId.clear()
430+
clearPendingRuns(clearOptimisticMessages = false)
431431
}
432432
pendingToolCallsById.clear()
433433
publishPendingToolCalls()
@@ -457,6 +457,7 @@ class ChatController(
457457
sessionKey = currentSessionKey,
458458
previousMessages = _messages.value,
459459
)
460+
prunePersistedOptimisticMessages(history.messages)
460461
_messages.value = mergeOptimisticMessages(incoming = history.messages, optimistic = optimisticMessagesByRunId.values)
461462
_sessionId.value = history.sessionId
462463
history.thinkingLevel
@@ -563,12 +564,14 @@ class ChatController(
563564
}
564565
}
565566

566-
private fun clearPendingRuns() {
567+
private fun clearPendingRuns(clearOptimisticMessages: Boolean = true) {
567568
for ((_, job) in pendingRunTimeoutJobs) {
568569
job.cancel()
569570
}
570571
pendingRunTimeoutJobs.clear()
571-
optimisticMessagesByRunId.clear()
572+
if (clearOptimisticMessages) {
573+
optimisticMessagesByRunId.clear()
574+
}
572575
synchronized(pendingRuns) {
573576
pendingRuns.clear()
574577
_pendingRunCount.value = 0
@@ -580,6 +583,15 @@ class ChatController(
580583
_messages.value = _messages.value.filterNot { it.id == message.id }
581584
}
582585

586+
private fun prunePersistedOptimisticMessages(incoming: List<ChatMessage>) {
587+
val retained =
588+
retainUnmatchedOptimisticMessages(
589+
incoming = incoming,
590+
optimistic = optimisticMessagesByRunId.values,
591+
).toSet()
592+
optimisticMessagesByRunId.entries.removeAll { entry -> entry.value !in retained }
593+
}
594+
583595
private fun parseHistory(
584596
historyJson: String,
585597
sessionKey: String,
@@ -594,13 +606,14 @@ class ChatController(
594606
array.mapNotNull { item ->
595607
val obj = item.asObjectOrNull() ?: return@mapNotNull null
596608
val role = obj["role"].asStringOrNull() ?: return@mapNotNull null
597-
val content = obj["content"].asArrayOrNull()?.mapNotNull(::parseChatMessageContent) ?: emptyList()
609+
val content = parseChatMessageContents(obj)
598610
val ts = obj["timestamp"].asLongOrNull()
599611
ChatMessage(
600612
id = UUID.randomUUID().toString(),
601613
role = role,
602614
content = content,
603615
timestampMs = ts,
616+
idempotencyKey = obj["idempotencyKey"].asStringOrNull(),
604617
)
605618
}
606619

@@ -676,6 +689,19 @@ internal fun parseChatMessageContent(el: JsonElement): ChatMessageContent? {
676689
}
677690
}
678691

692+
internal fun parseChatMessageContents(obj: JsonObject): List<ChatMessageContent> {
693+
obj["content"].asArrayOrNull()?.let { content ->
694+
return content.mapNotNull(::parseChatMessageContent)
695+
}
696+
obj["content"].asStringOrNull()?.let { text ->
697+
return listOf(ChatMessageContent(type = "text", text = text))
698+
}
699+
obj["text"].asStringOrNull()?.let { text ->
700+
return listOf(ChatMessageContent(type = "text", text = text))
701+
}
702+
return emptyList()
703+
}
704+
679705
internal data class MainSessionState(
680706
val currentSessionKey: String,
681707
val appliedMainSessionKey: String,
@@ -734,29 +760,41 @@ internal fun mergeOptimisticMessages(
734760
): List<ChatMessage> {
735761
if (optimistic.isEmpty()) return incoming
736762

737-
val unmatchedIncoming = incoming.toMutableList()
738-
val missingOptimistic =
739-
optimistic.filter { message ->
740-
val matchIndex =
741-
unmatchedIncoming.indexOfFirst { incomingMessage ->
742-
incomingMessageConsumesOptimistic(incomingMessage, message)
743-
}
744-
if (matchIndex >= 0) {
745-
unmatchedIncoming.removeAt(matchIndex)
746-
false
747-
} else {
748-
true
749-
}
750-
}
763+
val missingOptimistic = retainUnmatchedOptimisticMessages(incoming = incoming, optimistic = optimistic)
751764
if (missingOptimistic.isEmpty()) return incoming
752765

753766
return (incoming + missingOptimistic).sortedWith(compareBy<ChatMessage> { it.timestampMs ?: Long.MAX_VALUE }.thenBy { it.id })
754767
}
755768

769+
internal fun retainUnmatchedOptimisticMessages(
770+
incoming: List<ChatMessage>,
771+
optimistic: Collection<ChatMessage>,
772+
): List<ChatMessage> {
773+
if (optimistic.isEmpty()) return emptyList()
774+
775+
val unmatchedIncoming = incoming.toMutableList()
776+
return optimistic.filter { message ->
777+
val matchIndex =
778+
unmatchedIncoming.indexOfFirst { incomingMessage ->
779+
incomingMessageConsumesOptimistic(incomingMessage, message)
780+
}
781+
if (matchIndex >= 0) {
782+
unmatchedIncoming.removeAt(matchIndex)
783+
false
784+
} else {
785+
true
786+
}
787+
}
788+
}
789+
756790
/**
757791
* Message identity used only for refresh reconciliation; it avoids exposing gateway ids as UI keys.
758792
*/
759793
internal fun messageIdentityKey(message: ChatMessage): String? {
794+
val idempotencyKey = message.idempotencyKey?.trim().orEmpty()
795+
if (idempotencyKey.isNotEmpty()) {
796+
return listOf(message.role.trim().lowercase(), idempotencyKey).joinToString(separator = "|")
797+
}
760798
val contentKey = messageContentIdentityKey(message) ?: return null
761799
val timestamp = message.timestampMs?.toString().orEmpty()
762800
if (timestamp.isEmpty() && contentKey.isEmpty()) return null
@@ -769,6 +807,10 @@ private fun incomingMessageConsumesOptimistic(
769807
incoming: ChatMessage,
770808
optimistic: ChatMessage,
771809
): Boolean {
810+
val optimisticIdempotencyKey = optimistic.idempotencyKey?.trim().orEmpty()
811+
if (optimisticIdempotencyKey.isNotEmpty()) {
812+
return incoming.idempotencyKey?.trim() == optimisticIdempotencyKey
813+
}
772814
if (optimisticMessageIdentityKey(incoming) != optimisticMessageIdentityKey(optimistic)) return false
773815
val incomingTimestamp = incoming.timestampMs ?: return false
774816
val optimisticTimestamp = optimistic.timestampMs ?: return true

‎apps/android/app/src/main/java/ai/openclaw/app/chat/ChatModels.kt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ data class ChatMessage(
88
val role: String,
99
val content: List<ChatMessageContent>,
1010
val timestampMs: Long?,
11+
val idempotencyKey: String? = null,
1112
)
1213

1314
/**

‎apps/android/app/src/main/java/ai/openclaw/app/ui/chat/ChatMessageListCard.kt‎

Lines changed: 20 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import androidx.compose.foundation.layout.fillMaxSize
1515
import androidx.compose.foundation.layout.fillMaxWidth
1616
import androidx.compose.foundation.layout.padding
1717
import androidx.compose.foundation.lazy.LazyColumn
18-
import androidx.compose.foundation.lazy.items
18+
import androidx.compose.foundation.lazy.itemsIndexed
1919
import androidx.compose.foundation.lazy.rememberLazyListState
2020
import androidx.compose.foundation.shape.RoundedCornerShape
2121
import androidx.compose.material3.CircularProgressIndicator
@@ -40,17 +40,19 @@ fun ChatMessageListCard(
4040
modifier: Modifier = Modifier,
4141
) {
4242
val listState = rememberLazyListState()
43-
val displayMessages = remember(messages) { messages.asReversed() }
44-
val stream = streamingAssistantText?.trim()
43+
val timeline =
44+
remember(messages, pendingRunCount, pendingToolCalls, streamingAssistantText) {
45+
buildChatTimeline(
46+
messages = messages,
47+
pendingRunCount = pendingRunCount,
48+
pendingToolCalls = pendingToolCalls,
49+
streamingAssistantText = streamingAssistantText,
50+
)
51+
}
4552

46-
// New list items/tool rows should animate into view, but token streaming should not restart
47-
// that animation on every delta.
48-
LaunchedEffect(messages.size, pendingRunCount, pendingToolCalls.size) {
49-
listState.animateScrollToItem(index = 0)
50-
}
51-
LaunchedEffect(stream) {
52-
if (!stream.isNullOrEmpty()) {
53-
listState.scrollToItem(index = 0)
53+
LaunchedEffect(timeline.scrollTargetIndex, timeline.items.size, pendingRunCount, pendingToolCalls.size) {
54+
timeline.scrollTargetIndex?.let { index ->
55+
listState.animateScrollToItem(index = index)
5456
}
5557
}
5658

@@ -64,32 +66,17 @@ fun ChatMessageListCard(
6466
androidx.compose.foundation.layout
6567
.PaddingValues(bottom = 8.dp),
6668
) {
67-
// With reverseLayout = true, index 0 renders at the BOTTOM.
68-
// So we emit newest items first: streaming → tools → typing → messages (newest→oldest).
69-
if (!stream.isNullOrEmpty()) {
70-
item(key = "stream") {
71-
ChatStreamingAssistantBubble(text = stream)
72-
}
73-
}
74-
75-
if (pendingToolCalls.isNotEmpty()) {
76-
item(key = "tools") {
77-
ChatPendingToolsBubble(toolCalls = pendingToolCalls)
69+
itemsIndexed(items = timeline.items, key = { _, item -> chatTimelineItemKey(item) }) { _, item ->
70+
when (item) {
71+
is ChatTimelineItem.Message -> ChatMessageBubble(message = item.message)
72+
is ChatTimelineItem.PendingTools -> ChatPendingToolsBubble(toolCalls = item.toolCalls)
73+
is ChatTimelineItem.StreamingAssistant -> ChatStreamingAssistantBubble(text = item.text)
74+
ChatTimelineItem.Thinking -> ChatTypingIndicatorBubble()
7875
}
7976
}
80-
81-
if (pendingRunCount > 0) {
82-
item(key = "typing") {
83-
ChatTypingIndicatorBubble()
84-
}
85-
}
86-
87-
items(items = displayMessages, key = { it.id }) { message ->
88-
ChatMessageBubble(message = message)
89-
}
9077
}
9178

92-
if (messages.isEmpty() && pendingRunCount == 0 && pendingToolCalls.isEmpty() && streamingAssistantText.isNullOrBlank()) {
79+
if (timeline.items.isEmpty()) {
9380
if (historyLoading) {
9481
LoadingChatHint(modifier = Modifier.align(Alignment.Center))
9582
} else {

‎apps/android/app/src/main/java/ai/openclaw/app/ui/chat/ChatScreen.kt‎

Lines changed: 32 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ import androidx.compose.foundation.layout.padding
3131
import androidx.compose.foundation.layout.size
3232
import androidx.compose.foundation.layout.width
3333
import androidx.compose.foundation.lazy.LazyColumn
34-
import androidx.compose.foundation.lazy.items
34+
import androidx.compose.foundation.lazy.itemsIndexed
3535
import androidx.compose.foundation.lazy.rememberLazyListState
3636
import androidx.compose.foundation.rememberScrollState
3737
import androidx.compose.foundation.shape.CircleShape
@@ -406,15 +406,19 @@ private fun ChatMessageList(
406406
modifier: Modifier = Modifier,
407407
) {
408408
val listState = rememberLazyListState()
409-
val displayMessages = remember(messages) { messages.asReversed() }
410-
val stream = streamingAssistantText?.trim()
409+
val timeline =
410+
remember(messages, pendingRunCount, pendingToolCalls, streamingAssistantText) {
411+
buildChatTimeline(
412+
messages = messages,
413+
pendingRunCount = pendingRunCount,
414+
pendingToolCalls = pendingToolCalls,
415+
streamingAssistantText = streamingAssistantText,
416+
)
417+
}
411418

412-
LaunchedEffect(messages.size, pendingRunCount, pendingToolCalls.size) {
413-
listState.animateScrollToItem(index = 0)
414-
}
415-
LaunchedEffect(stream) {
416-
if (!stream.isNullOrEmpty()) {
417-
listState.scrollToItem(index = 0)
419+
LaunchedEffect(timeline.scrollTargetIndex, timeline.items.size, pendingRunCount, pendingToolCalls.size) {
420+
timeline.scrollTargetIndex?.let { index ->
421+
listState.animateScrollToItem(index = index)
418422
}
419423
}
420424

@@ -426,30 +430,29 @@ private fun ChatMessageList(
426430
verticalArrangement = Arrangement.spacedBy(5.dp),
427431
contentPadding = PaddingValues(top = 6.dp, bottom = 3.dp),
428432
) {
429-
if (!stream.isNullOrEmpty()) {
430-
item(key = "stream") {
431-
ChatBubble(role = "assistant", live = true, content = listOf(ChatMessageContent(text = stream)), timestampMs = null)
432-
}
433-
}
434-
435-
if (pendingToolCalls.isNotEmpty()) {
436-
item(key = "tools") {
437-
ToolBubble(toolCalls = pendingToolCalls)
438-
}
439-
}
440-
441-
if (pendingRunCount > 0) {
442-
item(key = "thinking") {
443-
ChatThinkingBubble()
433+
itemsIndexed(items = timeline.items, key = { _, item -> chatTimelineItemKey(item) }) { _, item ->
434+
when (item) {
435+
is ChatTimelineItem.Message ->
436+
ChatBubble(
437+
role = item.message.role,
438+
live = false,
439+
content = item.message.content,
440+
timestampMs = item.message.timestampMs,
441+
)
442+
is ChatTimelineItem.PendingTools -> ToolBubble(toolCalls = item.toolCalls)
443+
is ChatTimelineItem.StreamingAssistant ->
444+
ChatBubble(
445+
role = "assistant",
446+
live = true,
447+
content = listOf(ChatMessageContent(text = item.text)),
448+
timestampMs = null,
449+
)
450+
ChatTimelineItem.Thinking -> ChatThinkingBubble()
444451
}
445452
}
446-
447-
items(items = displayMessages, key = { it.id }) { message ->
448-
ChatBubble(role = message.role, live = false, content = message.content, timestampMs = message.timestampMs)
449-
}
450453
}
451454

452-
if (messages.isEmpty() && pendingRunCount == 0 && pendingToolCalls.isEmpty() && stream.isNullOrBlank()) {
455+
if (timeline.items.isEmpty()) {
453456
if (historyLoading) {
454457
ClawLoadingState(title = "Loading session", modifier = Modifier.align(Alignment.Center))
455458
} else {

0 commit comments

Comments
 (0)