From cc1f5990f5509aed97c6b4fd494f3777b0e304bd Mon Sep 17 00:00:00 2001 From: OpenClaw Date: Sat, 7 Mar 2026 03:14:06 +0800 Subject: [PATCH] feat: render chat updates from delta SSE events --- .../data/RemoteOpenClawRepository.kt | 61 ++++++++++++++++--- .../xiaobai/openclawapp/network/SseModels.kt | 10 +++ .../openclawapp/network/SseSessionStream.kt | 27 +++++--- 3 files changed, 83 insertions(+), 15 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 3dbddc6..7bbfdbb 100644 --- a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/RemoteOpenClawRepository.kt +++ b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/RemoteOpenClawRepository.kt @@ -5,6 +5,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import cn.xiaobai.openclawapp.network.MobileGatewayApi import cn.xiaobai.openclawapp.network.SessionSummaryDto +import cn.xiaobai.openclawapp.network.SessionStreamEvent import cn.xiaobai.openclawapp.network.SseSessionStream import cn.xiaobai.openclawapp.network.createDefaultHttpClient import kotlinx.coroutines.CancellationException @@ -95,8 +96,8 @@ class RemoteOpenClawRepository( ), ChatMessage( id = "local-thinking-$sessionId-${currentMessages.size + 2}", - role = MessageRole.System, - text = "OpenClaw 正在思考中…", + role = MessageRole.Assistant, + text = "", createdAt = "现在", status = "thinking", ), @@ -139,13 +140,57 @@ class RemoteOpenClawRepository( streamJob = streamScope.launch { while (currentCoroutineContext().isActive) { try { - sseStream.connect(sessionId).collectLatest { snapshot -> - messageStore = messageStore + ( - sessionId to snapshot.messages.map { dto -> dto.toDomainMessage() } - ) + sseStream.connect(sessionId).collectLatest { event -> + when (event) { + is SessionStreamEvent.Snapshot -> { + messageStore = messageStore + ( + sessionId to event.payload.messages.map { dto -> dto.toDomainMessage() } + ) + } + + is SessionStreamEvent.Delta -> { + val currentMessages = messageStore[sessionId].orEmpty() + val updated = currentMessages.map { message -> + if (message.id == event.payload.id) { + message.copy( + text = event.payload.fullText, + status = event.payload.status ?: "streaming", + ) + } else { + message + } + } + val exists = updated.any { it.id == event.payload.id } + val next = if (exists) { + updated + } else { + updated + ChatMessage( + id = event.payload.id, + role = event.payload.role.toMessageRole(), + text = event.payload.fullText, + createdAt = event.payload.createdAt, + status = event.payload.status ?: "streaming", + ) + } + messageStore = messageStore + (sessionId to next) + } + + is SessionStreamEvent.Completed -> { + val completed = event.payload.toDomainMessage() + val currentMessages = messageStore[sessionId].orEmpty() + .filterNot { it.id.startsWith("local-thinking-") } + val exists = currentMessages.any { it.id == completed.id } + val next = if (exists) { + currentMessages.map { if (it.id == completed.id) completed else it } + } else { + currentMessages + completed + } + messageStore = messageStore + (sessionId to next) + } + } } - } catch (e: CancellationException) { - throw e + } catch (_: CancellationException) { + throw _ } catch (_: Throwable) { delay(1500) } diff --git a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/SseModels.kt b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/SseModels.kt index a8e083a..e725a6a 100644 --- a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/SseModels.kt +++ b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/SseModels.kt @@ -6,3 +6,13 @@ import kotlinx.serialization.Serializable data class SessionSnapshotEventDto( val messages: List = emptyList(), ) + +@Serializable +data class MessageDeltaEventDto( + val id: String, + val delta: String, + val fullText: String, + val role: String, + val createdAt: String, + val status: String? = null, +) 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 be54648..f107dfe 100644 --- a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/SseSessionStream.kt +++ b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/SseSessionStream.kt @@ -11,6 +11,12 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.serialization.json.Json +sealed interface SessionStreamEvent { + data class Snapshot(val payload: SessionSnapshotEventDto) : SessionStreamEvent + data class Delta(val payload: MessageDeltaEventDto) : SessionStreamEvent + data class Completed(val payload: ChatMessageDto) : SessionStreamEvent +} + class SseSessionStream( private val client: HttpClient, private val baseUrl: String, @@ -18,7 +24,7 @@ class SseSessionStream( ) { private val json = Json { ignoreUnknownKeys = true } - fun connect(sessionId: String): Flow = flow { + fun connect(sessionId: String): Flow = flow { val url = "${baseUrl.trimEnd('/')}/api/sessions/${encodePath(sessionId)}/stream" client.prepareGet(url) { val token = tokenProvider().trim() @@ -40,12 +46,19 @@ class SseSessionStream( line.startsWith("event:") -> currentEvent = line.removePrefix("event:").trim() line.startsWith("data:") -> dataLines += line.removePrefix("data:").trim() line.isBlank() -> { - if (currentEvent == "session.snapshot" && dataLines.isNotEmpty()) { - runCatching { - json.decodeFromString(dataLines.joinToString("\n")) - }.onSuccess { dto -> - emit(dto) - } + val raw = dataLines.joinToString("\n") + when (currentEvent) { + "session.snapshot" -> runCatching { + json.decodeFromString(raw) + }.onSuccess { dto -> emit(SessionStreamEvent.Snapshot(dto)) } + + "message.delta" -> runCatching { + json.decodeFromString(raw) + }.onSuccess { dto -> emit(SessionStreamEvent.Delta(dto)) } + + "message.completed" -> runCatching { + json.decodeFromString(raw) + }.onSuccess { dto -> emit(SessionStreamEvent.Completed(dto)) } } currentEvent = null dataLines.clear()