Compare commits
2
Commits
6158584b74
...
6c204d8a4e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6c204d8a4e | ||
|
|
22dec6953a |
No files matched your search
@@ -152,7 +152,7 @@ private fun OpenClawRoot(appState: OpenClawAppState) {
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
sessionTitle = activeSession.title,
|
||||
messages = appState.repository.messagesFor(activeSession.id),
|
||||
isSending = appState.isSending,
|
||||
isSending = appState.sendingSessionId == activeSession.id,
|
||||
isLoading = appState.isSyncing,
|
||||
errorMessage = appState.syncError,
|
||||
onBack = appState::closeChat,
|
||||
|
||||
@@ -19,7 +19,7 @@ class OpenClawAppState(
|
||||
var feedbackMessage by mutableStateOf<String?>(null)
|
||||
var themeMode by mutableStateOf(preferences.loadThemeMode())
|
||||
var isSyncing by mutableStateOf(false)
|
||||
var isSending by mutableStateOf(false)
|
||||
var sendingSessionId by mutableStateOf<String?>(null)
|
||||
var isConnecting by mutableStateOf(false)
|
||||
var syncError by mutableStateOf<String?>(null)
|
||||
var configError by mutableStateOf<String?>(null)
|
||||
@@ -101,14 +101,14 @@ class OpenClawAppState(
|
||||
|
||||
suspend fun sendMessage(sessionId: String, text: String) {
|
||||
val remote = repository as? RemoteOpenClawRepository ?: return
|
||||
isSending = true
|
||||
sendingSessionId = sessionId
|
||||
runCatching {
|
||||
remote.sendMessageRemote(sessionId, text)
|
||||
}.onFailure {
|
||||
syncError = it.message ?: "消息发送失败"
|
||||
feedbackMessage = "消息发送失败"
|
||||
}
|
||||
isSending = false
|
||||
sendingSessionId = null
|
||||
}
|
||||
|
||||
fun updateDefaultAgent(agent: String) {
|
||||
|
||||
+93
-7
@@ -67,6 +67,7 @@ class RemoteOpenClawRepository(
|
||||
sessions = sessions.map {
|
||||
if (it.id == sessionId) it.copy(unreadCount = 0) else it
|
||||
}
|
||||
resortSessions(prioritizeId = sessionId)
|
||||
subscribeSessionStream(sessionId)
|
||||
}
|
||||
|
||||
@@ -79,23 +80,30 @@ class RemoteOpenClawRepository(
|
||||
} else {
|
||||
it
|
||||
}
|
||||
}.sortedWith(compareByDescending<SessionSummary> { it.isPinned })
|
||||
}
|
||||
resortSessions(prioritizeId = recentSessionId)
|
||||
return pinned
|
||||
}
|
||||
|
||||
override fun sendMessage(sessionId: String, text: String) {
|
||||
val currentMessages = messageStore[sessionId].orEmpty()
|
||||
val hasQueuedUser = currentMessages.any {
|
||||
it.role == MessageRole.User && it.text == text && it.status == "queued"
|
||||
}
|
||||
if (hasQueuedUser) return
|
||||
|
||||
val withoutThinking = currentMessages.filterNot { it.id.startsWith("local-thinking-") }
|
||||
messageStore = messageStore + (
|
||||
sessionId to (currentMessages + listOf(
|
||||
sessionId to (withoutThinking + listOf(
|
||||
ChatMessage(
|
||||
id = "local-user-$sessionId-${currentMessages.size + 1}",
|
||||
id = "local-user-$sessionId-${withoutThinking.size + 1}",
|
||||
role = MessageRole.User,
|
||||
text = text,
|
||||
createdAt = "现在",
|
||||
status = "queued",
|
||||
),
|
||||
ChatMessage(
|
||||
id = "local-thinking-$sessionId-${currentMessages.size + 2}",
|
||||
id = "local-thinking-$sessionId-${withoutThinking.size + 2}",
|
||||
role = MessageRole.Assistant,
|
||||
text = "",
|
||||
createdAt = "现在",
|
||||
@@ -118,6 +126,7 @@ class RemoteOpenClawRepository(
|
||||
|
||||
suspend fun refreshSessions() {
|
||||
sessions = api.getSessions().map { dto -> dto.toDomain() }
|
||||
resortSessions(prioritizeId = recentSessionId)
|
||||
}
|
||||
|
||||
suspend fun refreshAgents() {
|
||||
@@ -128,11 +137,17 @@ class RemoteOpenClawRepository(
|
||||
suspend fun refreshMessages(sessionId: String) {
|
||||
val remoteMessages = api.getMessages(sessionId).map { dto -> dto.toDomainMessage() }
|
||||
messageStore = messageStore + (sessionId to remoteMessages)
|
||||
updateSessionPreview(sessionId, remoteMessages.lastOrNull())
|
||||
}
|
||||
|
||||
suspend fun sendMessageRemote(sessionId: String, text: String) {
|
||||
sendMessage(sessionId, text)
|
||||
runCatching {
|
||||
api.sendMessage(sessionId, text)
|
||||
}.onFailure {
|
||||
clearLocalPendingMessages(sessionId, text)
|
||||
throw it
|
||||
}
|
||||
}
|
||||
|
||||
private fun subscribeSessionStream(sessionId: String) {
|
||||
@@ -143,13 +158,16 @@ class RemoteOpenClawRepository(
|
||||
sseStream.connect(sessionId).collectLatest { event ->
|
||||
when (event) {
|
||||
is SessionStreamEvent.Snapshot -> {
|
||||
messageStore = messageStore + (
|
||||
sessionId to event.payload.messages.map { dto -> dto.toDomainMessage() }
|
||||
)
|
||||
val localPending = messageStore[sessionId].orEmpty().filter { it.id.startsWith("local-") }
|
||||
val remoteMessages = event.payload.messages.map { dto -> dto.toDomainMessage() }
|
||||
val merged = mergeSnapshotWithLocalPending(remoteMessages, localPending)
|
||||
messageStore = messageStore + (sessionId to merged)
|
||||
updateSessionPreview(sessionId, merged.lastOrNull())
|
||||
}
|
||||
|
||||
is SessionStreamEvent.Delta -> {
|
||||
val currentMessages = messageStore[sessionId].orEmpty()
|
||||
.filterNot { it.id.startsWith("local-thinking-") }
|
||||
val updated = currentMessages.map { message ->
|
||||
if (message.id == event.payload.id) {
|
||||
message.copy(
|
||||
@@ -173,6 +191,7 @@ class RemoteOpenClawRepository(
|
||||
)
|
||||
}
|
||||
messageStore = messageStore + (sessionId to next)
|
||||
updateSessionPreview(sessionId, next.lastOrNull())
|
||||
}
|
||||
|
||||
is SessionStreamEvent.Completed -> {
|
||||
@@ -186,6 +205,7 @@ class RemoteOpenClawRepository(
|
||||
currentMessages + completed
|
||||
}
|
||||
messageStore = messageStore + (sessionId to next)
|
||||
updateSessionPreview(sessionId, next.lastOrNull())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -203,6 +223,72 @@ class RemoteOpenClawRepository(
|
||||
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) {
|
||||
val currentMessages = messageStore[sessionId].orEmpty()
|
||||
val next = currentMessages.filterNot { message ->
|
||||
message.id.startsWith("local-thinking-") ||
|
||||
(message.role == MessageRole.User && message.text == text && message.status == "queued")
|
||||
}
|
||||
messageStore = messageStore + (sessionId to next)
|
||||
}
|
||||
|
||||
private fun mergeSnapshotWithLocalPending(
|
||||
remoteMessages: List<ChatMessage>,
|
||||
localPending: List<ChatMessage>,
|
||||
): List<ChatMessage> {
|
||||
val pendingUsers = localPending.filter { it.role == MessageRole.User && it.status == "queued" }
|
||||
val pendingThinking = localPending.filter { it.id.startsWith("local-thinking-") }
|
||||
|
||||
val unmatchedPendingUsers = pendingUsers.filter { pending ->
|
||||
remoteMessages.none { remote ->
|
||||
remote.role == MessageRole.User && remote.text == pending.text
|
||||
}
|
||||
}
|
||||
|
||||
val hasPendingUserReachedRemote = pendingUsers.any { pending ->
|
||||
remoteMessages.any { remote ->
|
||||
remote.role == MessageRole.User && remote.text == pending.text
|
||||
}
|
||||
}
|
||||
val shouldKeepThinking = pendingThinking.isNotEmpty() && (
|
||||
unmatchedPendingUsers.isNotEmpty() ||
|
||||
(hasPendingUserReachedRemote && remoteMessages.lastOrNull()?.role != MessageRole.Assistant)
|
||||
)
|
||||
|
||||
return buildList {
|
||||
addAll(remoteMessages)
|
||||
addAll(unmatchedPendingUsers)
|
||||
if (shouldKeepThinking) {
|
||||
addAll(pendingThinking)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun resortSessions(prioritizeId: String?) {
|
||||
sessions = sessions.sortedWith(
|
||||
compareByDescending<SessionSummary> { it.id == prioritizeId }
|
||||
.thenByDescending { it.isPinned }
|
||||
.thenByDescending { it.updatedAt }
|
||||
)
|
||||
}
|
||||
|
||||
private fun SessionSummaryDto.toDomain(): SessionSummary {
|
||||
return SessionSummary(
|
||||
id = id,
|
||||
|
||||
@@ -77,7 +77,7 @@ fun ChatScreen(
|
||||
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(sessionTitle, style = MaterialTheme.typography.titleLarge)
|
||||
Text(
|
||||
"当前先走 Mock 对话流,后面这里会接 SSE / WebSocket。",
|
||||
if (isSending) "消息请求已提交,正在等待 SSE 首帧…" else "当前会话已接入实时消息流(SSE)。",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
@@ -5,6 +5,7 @@ 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.encodeURLPathPart
|
||||
import io.ktor.http.isSuccess
|
||||
import io.ktor.utils.io.readUTF8Line
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
@@ -25,7 +26,7 @@ class SseSessionStream(
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
|
||||
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) {
|
||||
val token = tokenProvider().trim()
|
||||
if (token.isNotBlank()) {
|
||||
@@ -59,6 +60,8 @@ class SseSessionStream(
|
||||
"message.completed" -> runCatching {
|
||||
json.decodeFromString<ChatMessageDto>(raw)
|
||||
}.onSuccess { dto -> emit(SessionStreamEvent.Completed(dto)) }
|
||||
|
||||
"keepalive", null, "" -> Unit
|
||||
}
|
||||
currentEvent = null
|
||||
dataLines.clear()
|
||||
@@ -68,5 +71,4 @@ class SseSessionStream(
|
||||
}
|
||||
}
|
||||
|
||||
private fun encodePath(value: String): String = value.replace(":", "%3A")
|
||||
}
|
||||
Reference in new issue
Block a user