fix: harden chat SSE handling to avoid crashes

This commit is contained in:
OpenClaw committed 2026-03-07 03:00:22 +08:00
1 parent b43e40a67e
commit 2595107244
2 files changed
+30 -8

No files matched your search

@@ -7,12 +7,16 @@ import cn.xiaobai.openclawapp.network.MobileGatewayApi
import cn.xiaobai.openclawapp.network.SessionSummaryDto
import cn.xiaobai.openclawapp.network.SseSessionStream
import cn.xiaobai.openclawapp.network.createDefaultHttpClient
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
class RemoteOpenClawRepository(
@@ -31,7 +35,7 @@ class RemoteOpenClawRepository(
tokenProvider = { config.token },
)
}
private val streamScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val streamScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
private var streamJob: Job? = null
override var availableAgents by mutableStateOf(listOf("main"))
@@ -124,10 +128,18 @@ class RemoteOpenClawRepository(
private fun subscribeSessionStream(sessionId: String) {
streamJob?.cancel()
streamJob = streamScope.launch {
sseStream.connect(sessionId).collectLatest { snapshot ->
messageStore = messageStore + (
sessionId to snapshot.messages.map { dto -> dto.toDomainMessage() }
)
while (currentCoroutineContext().isActive) {
try {
sseStream.connect(sessionId).collectLatest { snapshot ->
messageStore = messageStore + (
sessionId to snapshot.messages.map { dto -> dto.toDomainMessage() }
)
}
} catch (_: CancellationException) {
throw _
} catch (_: Throwable) {
delay(1500)
}
}
}
}
@@ -1,10 +1,11 @@
package cn.xiaobai.openclawapp.network
import io.ktor.client.HttpClient
import io.ktor.client.request.prepareGet
import io.ktor.client.request.header
import io.ktor.client.request.prepareGet
import io.ktor.client.statement.bodyAsChannel
import io.ktor.http.HttpHeaders
import io.ktor.http.isSuccess
import io.ktor.utils.io.readUTF8Line
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
@@ -15,6 +16,8 @@ class SseSessionStream(
private val baseUrl: String,
private val tokenProvider: () -> String,
) {
private val json = Json { ignoreUnknownKeys = true }
fun connect(sessionId: String): Flow<SessionSnapshotEventDto> = flow {
val url = "${baseUrl.trimEnd('/')}/api/sessions/${encodePath(sessionId)}/stream"
client.prepareGet(url) {
@@ -23,6 +26,10 @@ class SseSessionStream(
header(HttpHeaders.Authorization, "Bearer $token")
}
}.execute { response ->
if (!response.status.isSuccess()) {
throw IllegalStateException("SSE connect failed: HTTP ${response.status.value}")
}
val channel = response.bodyAsChannel()
var currentEvent: String? = null
val dataLines = mutableListOf<String>()
@@ -34,8 +41,11 @@ class SseSessionStream(
line.startsWith("data:") -> dataLines += line.removePrefix("data:").trim()
line.isBlank() -> {
if (currentEvent == "session.snapshot" && dataLines.isNotEmpty()) {
val dto = Json { ignoreUnknownKeys = true }.decodeFromString<SessionSnapshotEventDto>(dataLines.joinToString("\n"))
emit(dto)
runCatching {
json.decodeFromString<SessionSnapshotEventDto>(dataLines.joinToString("\n"))
}.onSuccess { dto ->
emit(dto)
}
}
currentEvent = null
dataLines.clear()