Improve SSE chat state handling

This commit is contained in:
OpenClaw committed 2026-03-07 03:54:17 +08:00
1 parent 6158584b74
commit 22dec6953a
3 files changed
+64 -8

No files matched your search

@@ -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<ChatMessage>,
localPending: List<ChatMessage>,
): List<ChatMessage> {
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,
@@ -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,
)
@@ -59,6 +59,8 @@ class SseSessionStream(
"message.completed" -> runCatching {
json.decodeFromString<ChatMessageDto>(raw)
}.onSuccess { dto -> emit(SessionStreamEvent.Completed(dto)) }
"keepalive", null, "" -> Unit
}
currentEvent = null
dataLines.clear()