feat: add SSE session stream client skeleton
This commit is contained in:
1 parent
eeff16a4ca
commit
b43e40a67e
4 files changed
+106
-13
No files matched your search
+47
-11
@@ -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<List<SessionSummary>>(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
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package cn.xiaobai.openclawapp.network
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class SessionSnapshotEventDto(
|
||||
val messages: List<ChatMessageDto> = emptyList(),
|
||||
)
|
||||
@@ -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<SessionSnapshotEventDto> = 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<String>()
|
||||
|
||||
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<SessionSnapshotEventDto>(dataLines.joinToString("\n"))
|
||||
emit(dto)
|
||||
}
|
||||
currentEvent = null
|
||||
dataLines.clear()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun encodePath(value: String): String = value.replace(":", "%3A")
|
||||
}
|
||||
Reference in new issue
Block a user