Refine SSE session state updates

This commit is contained in:
OpenClaw committed 2026-03-07 03:58:39 +08:00
1 parent 22dec6953a
commit 6c204d8a4e
5 files changed
+40 -8

No files matched your search

@@ -152,7 +152,7 @@ private fun OpenClawRoot(appState: OpenClawAppState) {
modifier = Modifier.fillMaxSize(), modifier = Modifier.fillMaxSize(),
sessionTitle = activeSession.title, sessionTitle = activeSession.title,
messages = appState.repository.messagesFor(activeSession.id), messages = appState.repository.messagesFor(activeSession.id),
isSending = appState.isSending, isSending = appState.sendingSessionId == activeSession.id,
isLoading = appState.isSyncing, isLoading = appState.isSyncing,
errorMessage = appState.syncError, errorMessage = appState.syncError,
onBack = appState::closeChat, onBack = appState::closeChat,
@@ -19,7 +19,7 @@ class OpenClawAppState(
var feedbackMessage by mutableStateOf<String?>(null) var feedbackMessage by mutableStateOf<String?>(null)
var themeMode by mutableStateOf(preferences.loadThemeMode()) var themeMode by mutableStateOf(preferences.loadThemeMode())
var isSyncing by mutableStateOf(false) var isSyncing by mutableStateOf(false)
var isSending by mutableStateOf(false) var sendingSessionId by mutableStateOf<String?>(null)
var isConnecting by mutableStateOf(false) var isConnecting by mutableStateOf(false)
var syncError by mutableStateOf<String?>(null) var syncError by mutableStateOf<String?>(null)
var configError by mutableStateOf<String?>(null) var configError by mutableStateOf<String?>(null)
@@ -101,14 +101,14 @@ class OpenClawAppState(
suspend fun sendMessage(sessionId: String, text: String) { suspend fun sendMessage(sessionId: String, text: String) {
val remote = repository as? RemoteOpenClawRepository ?: return val remote = repository as? RemoteOpenClawRepository ?: return
isSending = true sendingSessionId = sessionId
runCatching { runCatching {
remote.sendMessageRemote(sessionId, text) remote.sendMessageRemote(sessionId, text)
}.onFailure { }.onFailure {
syncError = it.message ?: "消息发送失败" syncError = it.message ?: "消息发送失败"
feedbackMessage = "消息发送失败" feedbackMessage = "消息发送失败"
} }
isSending = false sendingSessionId = null
} }
fun updateDefaultAgent(agent: String) { fun updateDefaultAgent(agent: String) {
@@ -67,6 +67,7 @@ class RemoteOpenClawRepository(
sessions = sessions.map { sessions = sessions.map {
if (it.id == sessionId) it.copy(unreadCount = 0) else it if (it.id == sessionId) it.copy(unreadCount = 0) else it
} }
resortSessions(prioritizeId = sessionId)
subscribeSessionStream(sessionId) subscribeSessionStream(sessionId)
} }
@@ -79,7 +80,8 @@ class RemoteOpenClawRepository(
} else { } else {
it it
} }
}.sortedWith(compareByDescending<SessionSummary> { it.isPinned }) }
resortSessions(prioritizeId = recentSessionId)
return pinned return pinned
} }
@@ -124,6 +126,7 @@ class RemoteOpenClawRepository(
suspend fun refreshSessions() { suspend fun refreshSessions() {
sessions = api.getSessions().map { dto -> dto.toDomain() } sessions = api.getSessions().map { dto -> dto.toDomain() }
resortSessions(prioritizeId = recentSessionId)
} }
suspend fun refreshAgents() { suspend fun refreshAgents() {
@@ -134,6 +137,7 @@ class RemoteOpenClawRepository(
suspend fun refreshMessages(sessionId: String) { suspend fun refreshMessages(sessionId: String) {
val remoteMessages = api.getMessages(sessionId).map { dto -> dto.toDomainMessage() } val remoteMessages = api.getMessages(sessionId).map { dto -> dto.toDomainMessage() }
messageStore = messageStore + (sessionId to remoteMessages) messageStore = messageStore + (sessionId to remoteMessages)
updateSessionPreview(sessionId, remoteMessages.lastOrNull())
} }
suspend fun sendMessageRemote(sessionId: String, text: String) { suspend fun sendMessageRemote(sessionId: String, text: String) {
@@ -158,6 +162,7 @@ class RemoteOpenClawRepository(
val remoteMessages = event.payload.messages.map { dto -> dto.toDomainMessage() } val remoteMessages = event.payload.messages.map { dto -> dto.toDomainMessage() }
val merged = mergeSnapshotWithLocalPending(remoteMessages, localPending) val merged = mergeSnapshotWithLocalPending(remoteMessages, localPending)
messageStore = messageStore + (sessionId to merged) messageStore = messageStore + (sessionId to merged)
updateSessionPreview(sessionId, merged.lastOrNull())
} }
is SessionStreamEvent.Delta -> { is SessionStreamEvent.Delta -> {
@@ -186,6 +191,7 @@ class RemoteOpenClawRepository(
) )
} }
messageStore = messageStore + (sessionId to next) messageStore = messageStore + (sessionId to next)
updateSessionPreview(sessionId, next.lastOrNull())
} }
is SessionStreamEvent.Completed -> { is SessionStreamEvent.Completed -> {
@@ -199,6 +205,7 @@ class RemoteOpenClawRepository(
currentMessages + completed currentMessages + completed
} }
messageStore = messageStore + (sessionId to next) messageStore = messageStore + (sessionId to next)
updateSessionPreview(sessionId, next.lastOrNull())
} }
} }
} }
@@ -216,6 +223,23 @@ class RemoteOpenClawRepository(
streamScope.cancel() streamScope.cancel()
} }
private fun updateSessionPreview(sessionId: String, lastMessage: ChatMessage?) {
val preview = lastMessage?.text?.trim().orEmpty()
val updatedAt = lastMessage?.createdAt ?: "刚刚"
sessions = sessions.map { session ->
if (session.id == sessionId) {
session.copy(
lastMessage = preview.ifBlank { session.lastMessage },
updatedAt = updatedAt,
unreadCount = 0,
)
} else {
session
}
}
resortSessions(prioritizeId = recentSessionId)
}
private fun clearLocalPendingMessages(sessionId: String, text: String) { private fun clearLocalPendingMessages(sessionId: String, text: String) {
val currentMessages = messageStore[sessionId].orEmpty() val currentMessages = messageStore[sessionId].orEmpty()
val next = currentMessages.filterNot { message -> val next = currentMessages.filterNot { message ->
@@ -257,6 +281,14 @@ class RemoteOpenClawRepository(
} }
} }
private fun resortSessions(prioritizeId: String?) {
sessions = sessions.sortedWith(
compareByDescending<SessionSummary> { it.id == prioritizeId }
.thenByDescending { it.isPinned }
.thenByDescending { it.updatedAt }
)
}
private fun SessionSummaryDto.toDomain(): SessionSummary { private fun SessionSummaryDto.toDomain(): SessionSummary {
return SessionSummary( return SessionSummary(
id = id, id = id,
@@ -77,7 +77,7 @@ fun ChatScreen(
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(sessionTitle, style = MaterialTheme.typography.titleLarge) Text(sessionTitle, style = MaterialTheme.typography.titleLarge)
Text( Text(
if (isSending) "消息已发出,正在等待 SSE 流式回复…" else "当前会话已接入实时消息流(SSE)。", if (isSending) "消息请求已提交,正在等待 SSE 首帧…" else "当前会话已接入实时消息流(SSE)。",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
@@ -5,6 +5,7 @@ import io.ktor.client.request.header
import io.ktor.client.request.prepareGet import io.ktor.client.request.prepareGet
import io.ktor.client.statement.bodyAsChannel import io.ktor.client.statement.bodyAsChannel
import io.ktor.http.HttpHeaders import io.ktor.http.HttpHeaders
import io.ktor.http.encodeURLPathPart
import io.ktor.http.isSuccess import io.ktor.http.isSuccess
import io.ktor.utils.io.readUTF8Line import io.ktor.utils.io.readUTF8Line
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@@ -25,7 +26,7 @@ class SseSessionStream(
private val json = Json { ignoreUnknownKeys = true } private val json = Json { ignoreUnknownKeys = true }
fun connect(sessionId: String): Flow<SessionStreamEvent> = flow { fun connect(sessionId: String): Flow<SessionStreamEvent> = flow {
val url = "${baseUrl.trimEnd('/')}/api/sessions/${encodePath(sessionId)}/stream" val url = "${baseUrl.trimEnd('/')}/api/sessions/${sessionId.encodeURLPathPart()}/stream"
client.prepareGet(url) { client.prepareGet(url) {
val token = tokenProvider().trim() val token = tokenProvider().trim()
if (token.isNotBlank()) { if (token.isNotBlank()) {
@@ -70,5 +71,4 @@ class SseSessionStream(
} }
} }
private fun encodePath(value: String): String = value.replace(":", "%3A")
} }