From 22dec6953ab8249d34fcb22062ce6b648dd0d9f9 Mon Sep 17 00:00:00 2001 From: OpenClaw Date: Sat, 7 Mar 2026 03:54:17 +0800 Subject: [PATCH] Improve SSE chat state handling --- .../data/RemoteOpenClawRepository.kt | 68 +++++++++++++++++-- .../openclawapp/feature/chat/ChatScreen.kt | 2 +- .../openclawapp/network/SseSessionStream.kt | 2 + 3 files changed, 64 insertions(+), 8 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/RemoteOpenClawRepository.kt b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/RemoteOpenClawRepository.kt index a116fc0..7d317bd 100644 --- a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/RemoteOpenClawRepository.kt +++ b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/RemoteOpenClawRepository.kt @@ -85,17 +85,23 @@ class RemoteOpenClawRepository( override fun sendMessage(sessionId: String, text: String) { val currentMessages = messageStore[sessionId].orEmpty() + val hasQueuedUser = currentMessages.any { + it.role == MessageRole.User && it.text == text && it.status == "queued" + } + if (hasQueuedUser) return + + val withoutThinking = currentMessages.filterNot { it.id.startsWith("local-thinking-") } messageStore = messageStore + ( - sessionId to (currentMessages + listOf( + sessionId to (withoutThinking + listOf( ChatMessage( - id = "local-user-$sessionId-${currentMessages.size + 1}", + id = "local-user-$sessionId-${withoutThinking.size + 1}", role = MessageRole.User, text = text, createdAt = "现在", status = "queued", ), ChatMessage( - id = "local-thinking-$sessionId-${currentMessages.size + 2}", + id = "local-thinking-$sessionId-${withoutThinking.size + 2}", role = MessageRole.Assistant, text = "", createdAt = "现在", @@ -132,7 +138,12 @@ class RemoteOpenClawRepository( suspend fun sendMessageRemote(sessionId: String, text: String) { sendMessage(sessionId, text) - api.sendMessage(sessionId, text) + runCatching { + api.sendMessage(sessionId, text) + }.onFailure { + clearLocalPendingMessages(sessionId, text) + throw it + } } private fun subscribeSessionStream(sessionId: String) { @@ -143,13 +154,15 @@ class RemoteOpenClawRepository( sseStream.connect(sessionId).collectLatest { event -> when (event) { is SessionStreamEvent.Snapshot -> { - messageStore = messageStore + ( - sessionId to event.payload.messages.map { dto -> dto.toDomainMessage() } - ) + val localPending = messageStore[sessionId].orEmpty().filter { it.id.startsWith("local-") } + val remoteMessages = event.payload.messages.map { dto -> dto.toDomainMessage() } + val merged = mergeSnapshotWithLocalPending(remoteMessages, localPending) + messageStore = messageStore + (sessionId to merged) } is SessionStreamEvent.Delta -> { val currentMessages = messageStore[sessionId].orEmpty() + .filterNot { it.id.startsWith("local-thinking-") } val updated = currentMessages.map { message -> if (message.id == event.payload.id) { message.copy( @@ -203,6 +216,47 @@ class RemoteOpenClawRepository( streamScope.cancel() } + private fun clearLocalPendingMessages(sessionId: String, text: String) { + val currentMessages = messageStore[sessionId].orEmpty() + val next = currentMessages.filterNot { message -> + message.id.startsWith("local-thinking-") || + (message.role == MessageRole.User && message.text == text && message.status == "queued") + } + messageStore = messageStore + (sessionId to next) + } + + private fun mergeSnapshotWithLocalPending( + remoteMessages: List, + localPending: List, + ): List { + val pendingUsers = localPending.filter { it.role == MessageRole.User && it.status == "queued" } + val pendingThinking = localPending.filter { it.id.startsWith("local-thinking-") } + + val unmatchedPendingUsers = pendingUsers.filter { pending -> + remoteMessages.none { remote -> + remote.role == MessageRole.User && remote.text == pending.text + } + } + + val hasPendingUserReachedRemote = pendingUsers.any { pending -> + remoteMessages.any { remote -> + remote.role == MessageRole.User && remote.text == pending.text + } + } + val shouldKeepThinking = pendingThinking.isNotEmpty() && ( + unmatchedPendingUsers.isNotEmpty() || + (hasPendingUserReachedRemote && remoteMessages.lastOrNull()?.role != MessageRole.Assistant) + ) + + return buildList { + addAll(remoteMessages) + addAll(unmatchedPendingUsers) + if (shouldKeepThinking) { + addAll(pendingThinking) + } + } + } + private fun SessionSummaryDto.toDomain(): SessionSummary { return SessionSummary( id = id, diff --git a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/feature/chat/ChatScreen.kt b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/feature/chat/ChatScreen.kt index d3d54e7..1e2c06c 100644 --- a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/feature/chat/ChatScreen.kt +++ b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/feature/chat/ChatScreen.kt @@ -77,7 +77,7 @@ fun ChatScreen( Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { Text(sessionTitle, style = MaterialTheme.typography.titleLarge) Text( - "当前先走 Mock 对话流,后面这里会接 SSE / WebSocket。", + if (isSending) "消息已发出,正在等待 SSE 流式回复…" else "当前会话已接入实时消息流(SSE)。", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) diff --git a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/SseSessionStream.kt b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/SseSessionStream.kt index f107dfe..dc54357 100644 --- a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/SseSessionStream.kt +++ b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/SseSessionStream.kt @@ -59,6 +59,8 @@ class SseSessionStream( "message.completed" -> runCatching { json.decodeFromString(raw) }.onSuccess { dto -> emit(SessionStreamEvent.Completed(dto)) } + + "keepalive", null, "" -> Unit } currentEvent = null dataLines.clear()