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 e95579e..4bb4574 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,15 @@ 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.SseSessionStream +import cn.xiaobai.openclawapp.network.createDefaultHttpClient +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.launch class RemoteOpenClawRepository( private val config: ServerConfig, @@ -15,8 +24,17 @@ class RemoteOpenClawRepository( tokenProvider = { config.token }, ) } - override var availableAgents by mutableStateOf(listOf("main")) + private val sseStream by lazy { + SseSessionStream( + client = createDefaultHttpClient(), + baseUrl = config.baseUrl, + tokenProvider = { config.token }, + ) + } + private val streamScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private var streamJob: Job? = null + override var availableAgents by mutableStateOf(listOf("main")) override var sessions by mutableStateOf>(emptyList()) override var status by mutableStateOf( ServerStatus( @@ -44,6 +62,7 @@ class RemoteOpenClawRepository( sessions = sessions.map { if (it.id == sessionId) it.copy(unreadCount = 0) else it } + subscribeSessionStream(sessionId) } override fun togglePinned(sessionId: String): Boolean { @@ -93,22 +112,29 @@ class RemoteOpenClawRepository( } suspend fun refreshMessages(sessionId: String) { - val remoteMessages = api.getMessages(sessionId).map { dto -> - ChatMessage( - id = dto.id, - role = dto.role.toMessageRole(), - text = dto.text, - createdAt = dto.createdAt, - status = dto.status, - ) - } + val remoteMessages = api.getMessages(sessionId).map { dto -> dto.toDomainMessage() } messageStore = messageStore + (sessionId to remoteMessages) } suspend fun sendMessageRemote(sessionId: String, text: String) { sendMessage(sessionId, text) api.sendMessage(sessionId, text) - refreshMessages(sessionId) + } + + 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() } + ) + } + } + } + + fun dispose() { + streamJob?.cancel() + streamScope.cancel() } private fun SessionSummaryDto.toDomain(): SessionSummary { @@ -120,6 +146,16 @@ class RemoteOpenClawRepository( ) } + private fun cn.xiaobai.openclawapp.network.ChatMessageDto.toDomainMessage(): ChatMessage { + return ChatMessage( + id = id, + role = role.toMessageRole(), + text = text, + createdAt = createdAt, + status = status, + ) + } + private fun String.toMessageRole(): MessageRole { return when (lowercase()) { "user" -> MessageRole.User diff --git a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/MobileGatewayApi.kt b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/MobileGatewayApi.kt index 88a97d5..975e6ec 100644 --- a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/MobileGatewayApi.kt +++ b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/MobileGatewayApi.kt @@ -17,7 +17,7 @@ import kotlinx.serialization.json.Json class MobileGatewayApi( private val baseUrl: String, private val tokenProvider: () -> String, - private val client: HttpClient = defaultHttpClient(), + private val client: HttpClient = createDefaultHttpClient(), ) { suspend fun login(password: String): LoginResponseDto { return client.post("${baseUrl.trimEnd('/')}/api/auth/login") { @@ -68,7 +68,7 @@ class MobileGatewayApi( } } -private fun defaultHttpClient(): HttpClient { +fun createDefaultHttpClient(): HttpClient { return HttpClient { install(ContentNegotiation) { json( diff --git a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/SseModels.kt b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/SseModels.kt new file mode 100644 index 0000000..a8e083a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/SseModels.kt @@ -0,0 +1,8 @@ +package cn.xiaobai.openclawapp.network + +import kotlinx.serialization.Serializable + +@Serializable +data class SessionSnapshotEventDto( + val messages: List = emptyList(), +) diff --git a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/SseSessionStream.kt b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/SseSessionStream.kt new file mode 100644 index 0000000..7742b88 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/network/SseSessionStream.kt @@ -0,0 +1,49 @@ +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.statement.bodyAsChannel +import io.ktor.http.HttpHeaders +import io.ktor.utils.io.readUTF8Line +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flow +import kotlinx.serialization.json.Json + +class SseSessionStream( + private val client: HttpClient, + private val baseUrl: String, + private val tokenProvider: () -> String, +) { + fun connect(sessionId: String): Flow = flow { + val url = "${baseUrl.trimEnd('/')}/api/sessions/${encodePath(sessionId)}/stream" + client.prepareGet(url) { + val token = tokenProvider().trim() + if (token.isNotBlank()) { + header(HttpHeaders.Authorization, "Bearer $token") + } + }.execute { response -> + val channel = response.bodyAsChannel() + var currentEvent: String? = null + val dataLines = mutableListOf() + + while (!channel.isClosedForRead) { + val line = channel.readUTF8Line() ?: break + when { + line.startsWith("event:") -> currentEvent = line.removePrefix("event:").trim() + line.startsWith("data:") -> dataLines += line.removePrefix("data:").trim() + line.isBlank() -> { + if (currentEvent == "session.snapshot" && dataLines.isNotEmpty()) { + val dto = Json { ignoreUnknownKeys = true }.decodeFromString(dataLines.joinToString("\n")) + emit(dto) + } + currentEvent = null + dataLines.clear() + } + } + } + } + } + + private fun encodePath(value: String): String = value.replace(":", "%3A") +}