Upgrade SSE events and remove mock repository
This commit is contained in:
1 parent
5e5d3f6bbd
commit
3153fd5b98
8 files changed
+131
-202
No files matched your search
-150
@@ -1,150 +0,0 @@
|
||||
package cn.xiaobai.openclawapp.data
|
||||
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import kotlin.random.Random
|
||||
|
||||
class MockOpenClawRepository : OpenClawRepository {
|
||||
override var availableAgents by mutableStateOf(listOf("main", "pm", "rd-lead", "backend-dev"))
|
||||
|
||||
override var sessions by mutableStateOf(
|
||||
listOf(
|
||||
SessionSummary(
|
||||
id = "agent:main:main",
|
||||
title = "主会话",
|
||||
lastMessage = "先把移动端的接入方案定下来。",
|
||||
updatedAt = "刚刚",
|
||||
isPinned = true,
|
||||
),
|
||||
SessionSummary(
|
||||
id = "agent:main:rd-lead",
|
||||
title = "rd-lead",
|
||||
lastMessage = "架构方案已经同步。",
|
||||
updatedAt = "10 分钟前",
|
||||
unreadCount = 2,
|
||||
),
|
||||
SessionSummary(
|
||||
id = "agent:main:pm",
|
||||
title = "pm",
|
||||
lastMessage = "MVP 范围保持克制。",
|
||||
updatedAt = "1 小时前",
|
||||
unreadCount = 1,
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
override var status by mutableStateOf(
|
||||
ServerStatus(
|
||||
online = true,
|
||||
openClawVersion = "2026.2.26",
|
||||
currentModel = "cliproxy/gpt-5.4",
|
||||
defaultAgent = "main",
|
||||
updatedAt = "刚刚",
|
||||
)
|
||||
)
|
||||
|
||||
var recentSessionId by mutableStateOf("agent:main:main")
|
||||
private set
|
||||
|
||||
private var messageStore by mutableStateOf(
|
||||
mapOf(
|
||||
"agent:main:main" to listOf(
|
||||
ChatMessage("1", MessageRole.System, "已连接到 OpenClaw Mobile Gateway", "20:01", "connected"),
|
||||
ChatMessage("2", MessageRole.User, "帮我规划一下移动端接入方案。", "20:03"),
|
||||
ChatMessage("3", MessageRole.Assistant, "建议先做 App + BFF + OpenClaw 三层结构。", "20:03", "done"),
|
||||
),
|
||||
"agent:main:rd-lead" to listOf(
|
||||
ChatMessage("4", MessageRole.User, "架构文档准备好了没?", "19:40"),
|
||||
ChatMessage("5", MessageRole.Assistant, "已经整理成 ARCHITECTURE.md。", "19:41", "done"),
|
||||
),
|
||||
"agent:main:pm" to listOf(
|
||||
ChatMessage("6", MessageRole.Assistant, "先做会话、聊天、状态、设置四个页面。", "18:20", "done"),
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
override fun findSession(sessionId: String): SessionSummary? = sessions.firstOrNull { it.id == sessionId }
|
||||
|
||||
override fun messagesFor(sessionId: String): List<ChatMessage> = messageStore[sessionId].orEmpty()
|
||||
|
||||
override fun recentSession(): SessionSummary? = findSession(recentSessionId)
|
||||
|
||||
override fun pinnedCount(): Int = sessions.count { it.isPinned }
|
||||
|
||||
override fun markSessionOpened(sessionId: String) {
|
||||
recentSessionId = sessionId
|
||||
sessions = resortSessions(
|
||||
sessions.map {
|
||||
if (it.id == sessionId) it.copy(unreadCount = 0, updatedAt = "刚刚") else it
|
||||
},
|
||||
prioritizeId = sessionId,
|
||||
)
|
||||
}
|
||||
|
||||
override fun togglePinned(sessionId: String): Boolean {
|
||||
var pinned = false
|
||||
sessions = resortSessions(
|
||||
sessions.map {
|
||||
if (it.id == sessionId) {
|
||||
pinned = !it.isPinned
|
||||
it.copy(isPinned = pinned)
|
||||
} else {
|
||||
it
|
||||
}
|
||||
}
|
||||
)
|
||||
return pinned
|
||||
}
|
||||
|
||||
override fun sendMessage(sessionId: String, text: String) {
|
||||
val currentMessages = messageStore[sessionId].orEmpty()
|
||||
val assistantReply = mockAssistantReply(text)
|
||||
val newMessages = currentMessages + ChatMessage(
|
||||
id = Random.nextInt().toString(),
|
||||
role = MessageRole.User,
|
||||
text = text,
|
||||
createdAt = "现在",
|
||||
) + ChatMessage(
|
||||
id = Random.nextInt().toString(),
|
||||
role = MessageRole.System,
|
||||
text = "OpenClaw 正在组织回复…",
|
||||
createdAt = "现在",
|
||||
status = "thinking",
|
||||
) + ChatMessage(
|
||||
id = Random.nextInt().toString(),
|
||||
role = MessageRole.Assistant,
|
||||
text = assistantReply,
|
||||
createdAt = "现在",
|
||||
status = "stream-complete",
|
||||
)
|
||||
|
||||
messageStore = messageStore + (sessionId to newMessages)
|
||||
recentSessionId = sessionId
|
||||
sessions = resortSessions(
|
||||
sessions.map {
|
||||
if (it.id == sessionId) it.copy(lastMessage = text, updatedAt = "现在", unreadCount = 0) else it
|
||||
},
|
||||
prioritizeId = sessionId,
|
||||
)
|
||||
}
|
||||
|
||||
private fun resortSessions(items: List<SessionSummary>, prioritizeId: String? = null): List<SessionSummary> {
|
||||
val prioritized = items.firstOrNull { it.id == prioritizeId }
|
||||
val others = items.filterNot { it.id == prioritizeId }
|
||||
val base = buildList {
|
||||
if (prioritized != null) add(prioritized)
|
||||
addAll(others)
|
||||
}
|
||||
return base.sortedWith(compareByDescending<SessionSummary> { it.isPinned }.thenByDescending { it.id == prioritizeId })
|
||||
}
|
||||
|
||||
private fun mockAssistantReply(text: String): String {
|
||||
return when {
|
||||
text.contains("总结") -> "Mock 回复:当前会话重点是先把 App 体验打磨好,再接 BFF 和真实 OpenClaw。"
|
||||
text.contains("状态") -> "Mock 回复:当前链路状态正常,默认模型是 cliproxy/gpt-5.4。"
|
||||
text.contains("下一步") -> "Mock 回复:建议下一步开始定义 Repository 接口和 BFF API DTO。"
|
||||
else -> "Mock 回复:后面这里会替换成真实 BFF 流式消息。"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,13 +21,13 @@ data class ChatMessage(
|
||||
val text: String,
|
||||
val createdAt: String,
|
||||
val status: String? = null,
|
||||
val kind: MessageKind = MessageKind.Text,
|
||||
val toolName: String? = null,
|
||||
)
|
||||
|
||||
enum class MessageRole {
|
||||
User,
|
||||
Assistant,
|
||||
System,
|
||||
}
|
||||
enum class MessageRole { User, Assistant, System }
|
||||
|
||||
enum class MessageKind { Text, Thinking, Tool, ToolResult }
|
||||
|
||||
data class ServerStatus(
|
||||
val online: Boolean,
|
||||
|
||||
+54
-21
@@ -167,37 +167,53 @@ class RemoteOpenClawRepository(
|
||||
when (event) {
|
||||
is SessionStreamEvent.Snapshot -> {
|
||||
val localPending = messageStore[sessionId].orEmpty().filter { it.id.startsWith("local-") }
|
||||
val remoteMessages = event.payload.messages.map { dto -> dto.toDomainMessage() }
|
||||
val remoteMessages = event.payload.messages.map { it.toDomainMessage() }
|
||||
val merged = mergeSnapshotWithLocalPending(remoteMessages, localPending)
|
||||
messageStore = messageStore + (sessionId to merged)
|
||||
updateSessionPreview(sessionId, merged.lastOrNull())
|
||||
}
|
||||
|
||||
is SessionStreamEvent.Delta -> {
|
||||
is SessionStreamEvent.Started -> {
|
||||
val dto = event.payload
|
||||
val currentMessages = messageStore[sessionId].orEmpty()
|
||||
.filterNot { it.id.startsWith("local-thinking-") }
|
||||
val updated = currentMessages.map { message ->
|
||||
if (message.id == event.payload.id) {
|
||||
message.copy(
|
||||
text = event.payload.fullText,
|
||||
status = event.payload.status ?: "streaming",
|
||||
val exists = currentMessages.any { it.id == dto.id }
|
||||
if (!exists) {
|
||||
val next = currentMessages + ChatMessage(
|
||||
id = dto.id,
|
||||
role = dto.role.toMessageRole(),
|
||||
text = dto.text,
|
||||
createdAt = dto.createdAt,
|
||||
status = dto.status ?: "streaming",
|
||||
kind = dto.kind.toMessageKind(),
|
||||
toolName = dto.toolName,
|
||||
)
|
||||
} else {
|
||||
message
|
||||
messageStore = messageStore + (sessionId to next)
|
||||
}
|
||||
}
|
||||
val exists = updated.any { it.id == event.payload.id }
|
||||
val next = if (exists) {
|
||||
updated
|
||||
} else {
|
||||
updated + ChatMessage(
|
||||
id = event.payload.id,
|
||||
role = event.payload.role.toMessageRole(),
|
||||
text = event.payload.fullText,
|
||||
createdAt = event.payload.createdAt,
|
||||
status = event.payload.status ?: "streaming",
|
||||
|
||||
is SessionStreamEvent.Delta -> {
|
||||
val dto = event.payload
|
||||
val currentMessages = messageStore[sessionId].orEmpty()
|
||||
.filterNot { it.id.startsWith("local-thinking-") }
|
||||
val updated = currentMessages.map { msg ->
|
||||
if (msg.id == dto.id) msg.copy(
|
||||
text = dto.fullText,
|
||||
status = dto.status ?: "streaming",
|
||||
kind = dto.kind.toMessageKind(),
|
||||
toolName = dto.toolName,
|
||||
) else msg
|
||||
}
|
||||
val exists = updated.any { it.id == dto.id }
|
||||
val next = if (exists) updated else updated + ChatMessage(
|
||||
id = dto.id,
|
||||
role = dto.role.toMessageRole(),
|
||||
text = dto.fullText,
|
||||
createdAt = dto.createdAt,
|
||||
status = dto.status ?: "streaming",
|
||||
kind = dto.kind.toMessageKind(),
|
||||
toolName = dto.toolName,
|
||||
)
|
||||
}
|
||||
messageStore = messageStore + (sessionId to next)
|
||||
updateSessionPreview(sessionId, next.lastOrNull())
|
||||
}
|
||||
@@ -215,11 +231,17 @@ class RemoteOpenClawRepository(
|
||||
messageStore = messageStore + (sessionId to next)
|
||||
updateSessionPreview(sessionId, next.lastOrNull())
|
||||
}
|
||||
|
||||
is SessionStreamEvent.Failed -> {
|
||||
val dto = event.payload
|
||||
if (!dto.recoverable) return@collect
|
||||
// recoverable: will retry via outer while loop
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (t: Throwable) {
|
||||
} catch (_: Throwable) {
|
||||
delay(1500)
|
||||
}
|
||||
}
|
||||
@@ -313,6 +335,8 @@ class RemoteOpenClawRepository(
|
||||
text = text,
|
||||
createdAt = createdAt,
|
||||
status = status,
|
||||
kind = kind.toMessageKind(),
|
||||
toolName = toolName,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -323,4 +347,13 @@ class RemoteOpenClawRepository(
|
||||
else -> MessageRole.System
|
||||
}
|
||||
}
|
||||
|
||||
private fun String?.toMessageKind(): MessageKind {
|
||||
return when (this?.lowercase()) {
|
||||
"thinking" -> MessageKind.Thinking
|
||||
"tool" -> MessageKind.Tool
|
||||
"tool-result" -> MessageKind.ToolResult
|
||||
else -> MessageKind.Text
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
package cn.xiaobai.openclawapp.data
|
||||
|
||||
object RepositoryFactory {
|
||||
fun createMock(): OpenClawRepository = MockOpenClawRepository()
|
||||
|
||||
fun createRemote(config: ServerConfig): OpenClawRepository = RemoteOpenClawRepository(config)
|
||||
}
|
||||
+32
-19
@@ -31,6 +31,7 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.unit.dp
|
||||
import cn.xiaobai.openclawapp.data.ChatMessage
|
||||
import cn.xiaobai.openclawapp.data.MessageKind
|
||||
import cn.xiaobai.openclawapp.data.MessageRole
|
||||
import cn.xiaobai.openclawapp.ui.EmptyStateCard
|
||||
import cn.xiaobai.openclawapp.ui.StatusPill
|
||||
@@ -104,9 +105,7 @@ fun ChatScreen(
|
||||
modifier = Modifier.weight(1f),
|
||||
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||
)
|
||||
Button(onClick = onRetry) {
|
||||
Text("重试")
|
||||
}
|
||||
Button(onClick = onRetry) { Text("重试") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -142,10 +141,7 @@ fun ChatScreen(
|
||||
message.role == MessageRole.Assistant &&
|
||||
message.createdAt == "现在"
|
||||
|
||||
MessageBubble(
|
||||
message = message,
|
||||
animateText = shouldAnimate,
|
||||
)
|
||||
MessageBubble(message = message, animateText = shouldAnimate)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -185,11 +181,7 @@ fun ChatScreen(
|
||||
},
|
||||
enabled = !isSending,
|
||||
) {
|
||||
if (isSending) {
|
||||
CircularProgressIndicator()
|
||||
} else {
|
||||
Text("发送")
|
||||
}
|
||||
if (isSending) CircularProgressIndicator() else Text("发送")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -199,9 +191,7 @@ fun ChatScreen(
|
||||
|
||||
@Composable
|
||||
private fun RowScope.QuickActionButton(text: String, onClick: () -> Unit) {
|
||||
Button(onClick = onClick, modifier = Modifier.weight(1f)) {
|
||||
Text(text)
|
||||
}
|
||||
Button(onClick = onClick, modifier = Modifier.weight(1f)) { Text(text) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -223,7 +213,9 @@ private fun MessageBubble(
|
||||
MessageRole.Assistant -> "OpenClaw"
|
||||
MessageRole.System -> "系统"
|
||||
}
|
||||
val isThinking = message.status == "thinking"
|
||||
val isThinking = message.status == "thinking" || message.kind == MessageKind.Thinking
|
||||
val isTool = message.kind == MessageKind.Tool
|
||||
val isToolResult = message.kind == MessageKind.ToolResult
|
||||
var visibleChars by remember(message.id) { mutableIntStateOf(if (animateText) 0 else message.text.length) }
|
||||
|
||||
LaunchedEffect(message.id, animateText) {
|
||||
@@ -262,7 +254,8 @@ private fun MessageBubble(
|
||||
.padding(14.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
if (isThinking) {
|
||||
when {
|
||||
isThinking -> {
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
@@ -273,14 +266,34 @@ private fun MessageBubble(
|
||||
color = MaterialTheme.colorScheme.onSecondaryContainer,
|
||||
)
|
||||
Text(
|
||||
text = "正在思考…",
|
||||
text = if (message.text.isBlank()) "正在思考…" else message.text,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
}
|
||||
isTool -> {
|
||||
Text(
|
||||
text = "🛠 ${message.toolName ?: "工具调用"}",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
)
|
||||
Text(
|
||||
text = displayText.ifBlank { "工具正在执行…" },
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
isToolResult -> {
|
||||
Text(
|
||||
text = "工具结果",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
)
|
||||
Text(text = displayText, style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
else -> {
|
||||
Text(text = displayText, style = MaterialTheme.typography.bodyLarge)
|
||||
}
|
||||
}
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
|
||||
@@ -37,6 +37,8 @@ data class ChatMessageDto(
|
||||
val text: String,
|
||||
val createdAt: String,
|
||||
val status: String? = null,
|
||||
val kind: String? = null,
|
||||
val toolName: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
|
||||
@@ -7,6 +7,17 @@ data class SessionSnapshotEventDto(
|
||||
val messages: List<ChatMessageDto> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class MessageStartedEventDto(
|
||||
val id: String,
|
||||
val role: String,
|
||||
val text: String,
|
||||
val createdAt: String,
|
||||
val status: String? = null,
|
||||
val kind: String? = null,
|
||||
val toolName: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class MessageDeltaEventDto(
|
||||
val id: String,
|
||||
@@ -15,4 +26,12 @@ data class MessageDeltaEventDto(
|
||||
val role: String,
|
||||
val createdAt: String,
|
||||
val status: String? = null,
|
||||
val kind: String? = null,
|
||||
val toolName: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class RunFailedEventDto(
|
||||
val message: String,
|
||||
val recoverable: Boolean = true,
|
||||
)
|
||||
+19
-5
@@ -14,8 +14,10 @@ import kotlinx.serialization.json.Json
|
||||
|
||||
sealed interface SessionStreamEvent {
|
||||
data class Snapshot(val payload: SessionSnapshotEventDto) : SessionStreamEvent
|
||||
data class Started(val payload: MessageStartedEventDto) : SessionStreamEvent
|
||||
data class Delta(val payload: MessageDeltaEventDto) : SessionStreamEvent
|
||||
data class Completed(val payload: ChatMessageDto) : SessionStreamEvent
|
||||
data class Failed(val payload: RunFailedEventDto) : SessionStreamEvent
|
||||
}
|
||||
|
||||
class SseSessionStream(
|
||||
@@ -34,7 +36,12 @@ class SseSessionStream(
|
||||
}
|
||||
}.execute { response ->
|
||||
if (!response.status.isSuccess()) {
|
||||
throw IllegalStateException("SSE connect failed: HTTP ${response.status.value}")
|
||||
val dto = RunFailedEventDto(
|
||||
message = "SSE connect failed: HTTP ${response.status.value}",
|
||||
recoverable = response.status.value in 500..599,
|
||||
)
|
||||
emit(SessionStreamEvent.Failed(dto))
|
||||
return@execute
|
||||
}
|
||||
|
||||
val channel = response.bodyAsChannel()
|
||||
@@ -51,15 +58,23 @@ class SseSessionStream(
|
||||
when (currentEvent) {
|
||||
"session.snapshot" -> runCatching {
|
||||
json.decodeFromString<SessionSnapshotEventDto>(raw)
|
||||
}.onSuccess { dto -> emit(SessionStreamEvent.Snapshot(dto)) }
|
||||
}.onSuccess { emit(SessionStreamEvent.Snapshot(it)) }
|
||||
|
||||
"message.started" -> runCatching {
|
||||
json.decodeFromString<MessageStartedEventDto>(raw)
|
||||
}.onSuccess { emit(SessionStreamEvent.Started(it)) }
|
||||
|
||||
"message.delta" -> runCatching {
|
||||
json.decodeFromString<MessageDeltaEventDto>(raw)
|
||||
}.onSuccess { dto -> emit(SessionStreamEvent.Delta(dto)) }
|
||||
}.onSuccess { emit(SessionStreamEvent.Delta(it)) }
|
||||
|
||||
"message.completed" -> runCatching {
|
||||
json.decodeFromString<ChatMessageDto>(raw)
|
||||
}.onSuccess { dto -> emit(SessionStreamEvent.Completed(dto)) }
|
||||
}.onSuccess { emit(SessionStreamEvent.Completed(it)) }
|
||||
|
||||
"run.failed" -> runCatching {
|
||||
json.decodeFromString<RunFailedEventDto>(raw)
|
||||
}.onSuccess { emit(SessionStreamEvent.Failed(it)) }
|
||||
|
||||
"keepalive", null, "" -> Unit
|
||||
}
|
||||
@@ -70,5 +85,4 @@ class SseSessionStream(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user