Compare commits

..
104 Commits
Author SHA1 Message Date
OpenClaw 0c7aefee42 Add session bootstrap client path 2026-03-07 22:44:02 +08:00
OpenClaw 82c6d27075 Add unified delivery architecture skeleton 2026-03-07 22:39:13 +08:00
OpenClaw 1dc505c8d8 Clarify send and retry status copy 2026-03-07 22:21:32 +08:00
OpenClaw 6bb2d939a6 Differentiate manual sync feedback 2026-03-07 22:11:59 +08:00
OpenClaw 1764e03263 Add pull-to-refresh for chat 2026-03-07 22:09:04 +08:00
OpenClaw 7a0f745442 Add pull-to-refresh for sessions 2026-03-07 22:02:24 +08:00
OpenClaw ad1cae7f18 Add manual overview refresh actions 2026-03-07 21:53:52 +08:00
OpenClaw 6f7a4399e5 Fix multiplatform material icons dependency 2026-03-07 21:46:47 +08:00
OpenClaw f015717962 Refine transient chat message styling 2026-03-07 21:42:48 +08:00
OpenClaw cb357d9692 Compress session list header 2026-03-07 21:37:07 +08:00
OpenClaw c0d395eed2 Tighten session list hierarchy 2026-03-07 21:34:23 +08:00
OpenClaw 3b01b1c240 Reflow attachment message actions 2026-03-07 21:30:52 +08:00
OpenClaw 4bee45c8e0 Use material icons in chat app bar 2026-03-07 21:28:27 +08:00
OpenClaw 15e57ad1f9 Use symbolic chat app bar actions 2026-03-07 21:20:55 +08:00
OpenClaw f0379b9b4e Fix chat composer braces 2026-03-07 21:17:50 +08:00
OpenClaw c6b982b2b7 Reduce chat status noise 2026-03-07 21:16:28 +08:00
OpenClaw 02196c0f6e Collapse status into settings 2026-03-07 20:43:41 +08:00
OpenClaw 6557756e7a Tighten chat chrome and composer 2026-03-07 20:14:27 +08:00
OpenClaw 32d10933ef Keep cached session previews when available 2026-03-07 19:42:05 +08:00
OpenClaw 9146b7a863 Document startup cache optimization 2026-03-07 19:35:12 +08:00
OpenClaw 2754dada42 Parallelize initial overview sync 2026-03-07 16:14:57 +08:00
OpenClaw bba051bf14 Hide successful tool chatter by default 2026-03-07 16:08:48 +08:00
OpenClaw b9a16ec134 Clear stale local thinking placeholders 2026-03-07 16:05:58 +08:00
OpenClaw a1fd4a1f8a Tolerate attachment response field aliases 2026-03-07 15:50:33 +08:00
OpenClaw 270c0aa29e Expose attachment retry action 2026-03-07 15:43:36 +08:00
OpenClaw 662b4d24cd Fix chat screen call signature 2026-03-07 15:41:11 +08:00
OpenClaw dc7083507d Introduce explicit app routes 2026-03-07 15:38:55 +08:00
OpenClaw 6543f83b3a Restore detail navigation behavior 2026-03-07 15:30:49 +08:00
OpenClaw 3ebcf9761b Trim app chrome and simplify settings 2026-03-07 15:23:05 +08:00
OpenClaw 3b8d779138 Polish chat message hierarchy 2026-03-07 15:18:38 +08:00
OpenClaw 6c387eab7c Refine chat and session UI hierarchy 2026-03-07 15:10:40 +08:00
OpenClaw 1e110574d5 Simplify sessions and chat header UI 2026-03-07 14:45:20 +08:00
OpenClaw 1d5dad314a Differentiate SSE reconnect from upstream recovery 2026-03-07 14:31:29 +08:00
OpenClaw c26dc99ef1 Fix pending token compile regressions 2026-03-07 14:24:44 +08:00
OpenClaw dcd4b2adbd Add local client tokens for pending text matching 2026-03-07 14:04:12 +08:00
OpenClaw 485afdab02 Add attachment fingerprints for pending matching 2026-03-07 13:58:09 +08:00
OpenClaw 39f16a8119 Tighten pending message merge matching 2026-03-07 13:52:43 +08:00
OpenClaw 472bdef2a7 Expose queue recovery status in chat 2026-03-07 13:49:45 +08:00
OpenClaw f62e23ffcc Guard session queue recovery reentry 2026-03-07 13:45:18 +08:00
OpenClaw c5e85f1857 Retry pending queue after SSE recovery 2026-03-07 13:40:38 +08:00
OpenClaw 50601996af Use local phase helpers in retry edge cases 2026-03-07 13:37:26 +08:00
OpenClaw 7b56c88be9 Route local message writes through phase mapping 2026-03-07 13:35:39 +08:00
OpenClaw 85b974b900 Unify cache recovery with local message phases 2026-03-07 13:24:26 +08:00
OpenClaw a6119aeb46 Add derived local pending message phases 2026-03-07 13:21:42 +08:00
OpenClaw 9c006b8ed1 Retain pending queue states across snapshots 2026-03-07 13:15:00 +08:00
OpenClaw aa314ec084 Fix session sort key overload clash 2026-03-07 13:02:25 +08:00
OpenClaw b3f009d644 Align attachment queue drain states 2026-03-07 12:57:53 +08:00
OpenClaw 527fac9025 Persist pending attachment queue 2026-03-07 12:54:47 +08:00
OpenClaw ad4de3cbeb Expose pending queue status in chat 2026-03-07 12:49:56 +08:00
OpenClaw d8a20bad3a Tighten pending queue auto retry semantics 2026-03-07 12:46:15 +08:00
OpenClaw 11cd2d5b56 Show queue drain state in chat UI 2026-03-07 12:35:03 +08:00
OpenClaw e31b164e30 Drain pending text queue on sync and open 2026-03-07 12:32:09 +08:00
OpenClaw ca556cd1df Add persisted pending text send queue 2026-03-07 12:19:50 +08:00
OpenClaw 42d5b97d69 Unify session preview selection paths 2026-03-07 11:54:11 +08:00
OpenClaw 8218207065 Handle SSE reorder events 2026-03-07 11:45:07 +08:00
OpenClaw 56e15fd9b4 Persist session sort keys in overview cache 2026-03-07 11:37:46 +08:00
OpenClaw a4a6632707 Stabilize session sorting with sort keys 2026-03-07 11:35:31 +08:00
OpenClaw 439c0a4a7b Refresh session preview on local pending states 2026-03-07 11:33:02 +08:00
OpenClaw 7d7e0718f6 Keep session preview in sync after removals 2026-03-07 11:30:36 +08:00
OpenClaw ab172a6cfe Handle SSE message removed events 2026-03-07 11:27:59 +08:00
OpenClaw 595c0edb3b Show auto retry state in chat UI 2026-03-07 11:06:42 +08:00
OpenClaw 8762e2c805 Auto-retry restored queued messages on open 2026-03-07 11:04:28 +08:00
OpenClaw 946249d994 Retain failed local messages across refresh 2026-03-07 11:01:35 +08:00
OpenClaw 1f32f85190 Document recent app stability progress 2026-03-07 10:59:16 +08:00
OpenClaw 03ea1d959c Persist retryable message cache state 2026-03-07 10:55:13 +08:00
OpenClaw b3bcef7f79 Fix cached data compile errors 2026-03-07 10:50:08 +08:00
OpenClaw 5470e68e44 Show cached-data notices during cold start 2026-03-07 10:13:09 +08:00
OpenClaw 126e66ef6c Cache recent messages for up to three sessions 2026-03-07 10:09:21 +08:00
OpenClaw 4a82204e77 Cache recent session messages for cold starts 2026-03-07 10:06:43 +08:00
OpenClaw 75c93f36d0 Cache overview snapshot for cold starts 2026-03-07 10:01:51 +08:00
OpenClaw 0a261af380 Clarify expired attachment errors in app 2026-03-07 09:57:58 +08:00
OpenClaw 3db2077da3 Note attachment retention limits in progress doc 2026-03-07 09:56:15 +08:00
OpenClaw 606c8d51bc Add Android save-as flow for attachments 2026-03-07 09:53:08 +08:00
OpenClaw 471c23cf4a Update progress tracker for persisted attachments 2026-03-07 09:49:30 +08:00
OpenClaw 4260121f20 Fetch attachment bytes from BFF when opening 2026-03-07 09:47:34 +08:00
OpenClaw e55bd16253 Open cached attachments on Android 2026-03-07 09:42:27 +08:00
OpenClaw 64e992e8fa Add platform clipboard support for attachment actions 2026-03-07 09:38:27 +08:00
OpenClaw 9c22b2e99d Fix override default parameter in attachment upload 2026-03-07 09:36:14 +08:00
OpenClaw 1abb1961b8 Add attachment card actions and details panel 2026-03-07 09:34:11 +08:00
OpenClaw 2b21e56413 Add message retry UX and refresh controls 2026-03-07 09:31:55 +08:00
OpenClaw b441ac9cc6 Add retry flow for failed text messages 2026-03-07 09:29:42 +08:00
OpenClaw 6cba3154ba Add mobile MVP progress tracker 2026-03-07 09:25:27 +08:00
OpenClaw 3f607f6c1a Format session previews for attachment and tool events 2026-03-07 09:21:22 +08:00
OpenClaw f6159b0017 Add retry flow for failed attachment uploads 2026-03-07 09:17:59 +08:00
OpenClaw f4fe11e523 Show attachment metadata in chat cards 2026-03-07 09:11:56 +08:00
OpenClaw 88abe085d2 Add platform attachment picker abstraction 2026-03-07 09:08:37 +08:00
OpenClaw fbe64e3cdc Wire attachment uploads into chat timeline 2026-03-07 09:05:18 +08:00
OpenClaw 3672554706 Scaffold attachment actions in chat UI 2026-03-07 09:02:44 +08:00
OpenClaw e5e13a38f1 Tone down system notices in chat timeline 2026-03-07 08:58:13 +08:00
OpenClaw ae0bf93ed1 Show stream status in session list 2026-03-07 08:56:54 +08:00
OpenClaw 151d665061 Expose SSE stream status in chat header 2026-03-07 08:54:21 +08:00
OpenClaw d9582d9b86 Add structured output detection helper 2026-03-07 08:52:18 +08:00
OpenClaw c7ed167760 Tune structured tool output presentation 2026-03-07 08:51:29 +08:00
OpenClaw 7c3815f39a Style tool results as readable output blocks 2026-03-07 08:50:16 +08:00
OpenClaw b89eceef43 Add expandable tool result cards 2026-03-07 08:48:35 +08:00
OpenClaw a17d6bbfad Refine chat card hierarchy for tool events 2026-03-07 08:46:31 +08:00
OpenClaw 91b3b54b9d Link tool results to tool calls in chat UI 2026-03-07 08:45:08 +08:00
OpenClaw 38505e513a Improve tool cards and stream failure messaging 2026-03-07 08:41:54 +08:00
OpenClaw 3153fd5b98 Upgrade SSE events and remove mock repository 2026-03-07 08:39:01 +08:00
OpenClaw 5e5d3f6bbd Refresh remote state after switching default agent 2026-03-07 04:55:37 +08:00
OpenClaw c0a111ad5d Persist default agent changes via mobile gateway 2026-03-07 04:44:17 +08:00
OpenClaw 8daad78bf9 Improve mobile refresh loop and chat streaming UX 2026-03-07 04:29:05 +08:00
OpenClaw 6c204d8a4e Refine SSE session state updates 2026-03-07 03:58:39 +08:00
OpenClaw 22dec6953a Improve SSE chat state handling 2026-03-07 03:54:17 +08:00
53 changed files with 3812 additions and 454 deletions

No files matched your search

+1
View File
@@ -17,3 +17,4 @@ captures
!*.xcworkspace/contents.xcworkspacedata !*.xcworkspace/contents.xcworkspacedata
**/xcshareddata/WorkspaceSettings.xcsettings **/xcshareddata/WorkspaceSettings.xcsettings
node_modules/ node_modules/
/bff/
+1
View File
@@ -53,6 +53,7 @@ kotlin {
implementation(libs.compose.runtime) implementation(libs.compose.runtime)
implementation(libs.compose.foundation) implementation(libs.compose.foundation)
implementation(libs.compose.material3) implementation(libs.compose.material3)
implementation(compose.materialIconsExtended)
implementation(libs.compose.ui) implementation(libs.compose.ui)
implementation(libs.compose.components.resources) implementation(libs.compose.components.resources)
implementation(libs.compose.uiToolingPreview) implementation(libs.compose.uiToolingPreview)
@@ -13,6 +13,16 @@
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@android:style/Theme.Material.Light.NoActionBar" android:theme="@android:style/Theme.Material.Light.NoActionBar"
android:usesCleartextTraffic="true"> android:usesCleartextTraffic="true">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<activity <activity
android:exported="true" android:exported="true"
android:name=".MainActivity"> android:name=".MainActivity">
@@ -0,0 +1,42 @@
package cn.xiaobai.openclawapp.platform
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.FileProvider
import cn.xiaobai.openclawapp.data.AttachmentOpenPayload
import java.io.File
@Composable
actual fun rememberAttachmentOpener(
onResult: (String) -> Unit,
): (AttachmentOpenPayload) -> Unit {
val context = LocalContext.current
return remember(context, onResult) {
{ payload ->
runCatching {
val file = File(context.cacheDir, "attachments/${payload.fileName}")
file.parentFile?.mkdirs()
file.writeBytes(payload.bytes)
val uri = FileProvider.getUriForFile(
context,
context.packageName + ".fileprovider",
file,
)
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, payload.contentType ?: "*/*")
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
context.startActivity(intent)
onResult("正在打开:${payload.fileName}")
}.onFailure {
val msg = if (it is ActivityNotFoundException) "没有可用应用打开该附件" else (it.message ?: "打开附件失败")
onResult(msg)
}
}
}
}
@@ -0,0 +1,39 @@
package cn.xiaobai.openclawapp.platform
import android.provider.OpenableColumns
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
@Composable
actual fun rememberAttachmentPicker(
onPicked: (PickedAttachment) -> Unit,
onError: (String) -> Unit,
): () -> Unit {
val context = LocalContext.current
val resolver = context.contentResolver
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
if (uri == null) return@rememberLauncherForActivityResult
runCatching {
val name = resolver.query(uri, null, null, null, null)?.use { cursor ->
val index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
if (index >= 0 && cursor.moveToFirst()) cursor.getString(index) else null
} ?: "attachment"
val mimeType = resolver.getType(uri)
val bytes = resolver.openInputStream(uri)?.use { it.readBytes() }
?: error("无法读取所选文件")
PickedAttachment(
fileName = name,
bytes = bytes,
contentType = mimeType,
)
}.onSuccess(onPicked).onFailure {
onError(it.message ?: "文件选择失败")
}
}
return remember(launcher) {
{ launcher.launch("*/*") }
}
}
@@ -0,0 +1,37 @@
package cn.xiaobai.openclawapp.platform
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import cn.xiaobai.openclawapp.data.AttachmentOpenPayload
@Composable
actual fun rememberAttachmentSaver(
onResult: (String) -> Unit,
): (AttachmentOpenPayload) -> Unit {
val context = LocalContext.current
var pending by remember { mutableStateOf<AttachmentOpenPayload?>(null) }
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("*/*")) { uri ->
val payload = pending
if (uri == null || payload == null) return@rememberLauncherForActivityResult
runCatching {
context.contentResolver.openOutputStream(uri)?.use { it.write(payload.bytes) }
?: error("无法写入目标文件")
onResult("已保存附件:${payload.fileName}")
}.onFailure {
onResult(it.message ?: "保存附件失败")
}
pending = null
}
return remember(launcher) {
{ payload ->
pending = payload
launcher.launch(payload.fileName)
}
}
}
@@ -0,0 +1,9 @@
package cn.xiaobai.openclawapp.platform
import androidx.activity.compose.BackHandler
import androidx.compose.runtime.Composable
@Composable
actual fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit) {
BackHandler(enabled = enabled, onBack = onBack)
}
@@ -0,0 +1,26 @@
package cn.xiaobai.openclawapp.platform
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
@Composable
actual fun rememberClipboardSetter(
onResult: (String) -> Unit,
): (String) -> Unit {
val context = LocalContext.current
return remember(context, onResult) {
{ text ->
runCatching {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipboard.setPrimaryClip(ClipData.newPlainText("OpenClaw", text))
onResult("已复制到剪贴板:$text")
}.onFailure {
onResult(it.message ?: "复制失败")
}
}
}
}
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<cache-path name="attachments" path="attachments/" />
</paths>
@@ -3,8 +3,14 @@ package cn.xiaobai.openclawapp
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.AttachFile
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.NavigationBar import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
@@ -18,17 +24,22 @@ import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import cn.xiaobai.openclawapp.app.MainTab import cn.xiaobai.openclawapp.app.AppRoute
import cn.xiaobai.openclawapp.app.OpenClawAppState import cn.xiaobai.openclawapp.app.OpenClawAppState
import cn.xiaobai.openclawapp.data.ServerConfig import cn.xiaobai.openclawapp.data.ServerConfig
import cn.xiaobai.openclawapp.feature.chat.ChatScreen import cn.xiaobai.openclawapp.feature.chat.ChatScreen
import cn.xiaobai.openclawapp.feature.config.ServerConfigScreen import cn.xiaobai.openclawapp.feature.config.ServerConfigScreen
import cn.xiaobai.openclawapp.feature.sessions.SessionListScreen import cn.xiaobai.openclawapp.feature.sessions.SessionListScreen
import cn.xiaobai.openclawapp.feature.settings.SettingsScreen import cn.xiaobai.openclawapp.feature.settings.SettingsScreen
import cn.xiaobai.openclawapp.feature.status.StatusScreen import cn.xiaobai.openclawapp.platform.PlatformBackHandler
import cn.xiaobai.openclawapp.platform.rememberAttachmentOpener
import cn.xiaobai.openclawapp.platform.rememberAttachmentPicker
import cn.xiaobai.openclawapp.platform.rememberAttachmentSaver
import cn.xiaobai.openclawapp.platform.rememberClipboardSetter
import cn.xiaobai.openclawapp.ui.OpenClawTheme import cn.xiaobai.openclawapp.ui.OpenClawTheme
import cn.xiaobai.openclawapp.ui.StatusPill import cn.xiaobai.openclawapp.ui.StatusPill
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@Composable @Composable
@@ -77,8 +88,37 @@ fun App() {
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
private fun OpenClawRoot(appState: OpenClawAppState) { private fun OpenClawRoot(appState: OpenClawAppState) {
val activeSession = appState.activeSessionId?.let(appState.repository::findSession) val activeSession = (appState.currentRoute as? AppRoute.Chat)?.sessionId?.let(appState.repository::findSession)
val coroutineScope = rememberCoroutineScope() val coroutineScope = rememberCoroutineScope()
val pickAttachment = rememberAttachmentPicker(
onPicked = { picked ->
val sessionId = activeSession?.id ?: return@rememberAttachmentPicker
coroutineScope.launch {
appState.uploadAttachmentStub(
sessionId = sessionId,
fileName = picked.fileName,
bytes = picked.bytes,
contentType = picked.contentType,
)
}
},
onError = { message ->
appState.feedbackMessage = message
},
)
val copyToClipboard = rememberClipboardSetter { message ->
appState.feedbackMessage = message
}
val openAttachment = rememberAttachmentOpener { message ->
appState.feedbackMessage = message
}
val saveAttachment = rememberAttachmentSaver { message ->
appState.feedbackMessage = message
}
PlatformBackHandler(enabled = appState.currentRoute is AppRoute.Chat) {
appState.navigateBack()
}
LaunchedEffect(appState.feedbackMessage) { LaunchedEffect(appState.feedbackMessage) {
if (appState.feedbackMessage != null) { if (appState.feedbackMessage != null) {
@@ -89,44 +129,76 @@ private fun OpenClawRoot(appState: OpenClawAppState) {
LaunchedEffect(appState.isConfigured) { LaunchedEffect(appState.isConfigured) {
if (appState.isConfigured) { if (appState.isConfigured) {
appState.syncRemoteIfNeeded() appState.syncRemoteIfNeeded(trigger = cn.xiaobai.openclawapp.app.SyncTrigger.Initial)
}
}
LaunchedEffect(appState.isConfigured) {
if (!appState.isConfigured) return@LaunchedEffect
while (isActive) {
delay(30_000)
appState.refreshOverviewSilently()
} }
} }
Scaffold( Scaffold(
topBar = { topBar = {
when (val route = appState.currentRoute) {
is AppRoute.Chat -> {
CenterAlignedTopAppBar( CenterAlignedTopAppBar(
title = { title = {
Text( Text(
text = when { text = activeSession?.title ?: "会话",
activeSession != null -> activeSession.title style = androidx.compose.material3.MaterialTheme.typography.titleMedium,
appState.selectedTab == MainTab.Sessions -> "OpenClaw"
appState.selectedTab == MainTab.Status -> "运行状态"
appState.selectedTab == MainTab.Settings -> "设置"
else -> ""
}
) )
}, },
navigationIcon = {
IconButton(onClick = appState::closeChat) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = "返回",
) )
}
},
actions = {
IconButton(onClick = { pickAttachment() }) {
Icon(
imageVector = Icons.Filled.AttachFile,
contentDescription = "附件",
)
}
IconButton(onClick = {
activeSession?.id?.let { sessionId ->
coroutineScope.launch {
appState.clearSyncError()
appState.openSession(sessionId)
}
}
}) {
Icon(
imageVector = Icons.Filled.Refresh,
contentDescription = if (appState.repository.streamStatusFor(route.sessionId) == "failed") "重连" else "刷新",
)
}
},
)
}
else -> Unit
}
}, },
bottomBar = { bottomBar = {
if (activeSession == null) { if (appState.currentRoute !is AppRoute.Chat) {
NavigationBar { NavigationBar {
NavigationBarItem( NavigationBarItem(
selected = appState.selectedTab == MainTab.Sessions, selected = appState.currentRoute == AppRoute.Sessions,
onClick = { appState.selectedTab = MainTab.Sessions }, onClick = { appState.navigateTo(AppRoute.Sessions) },
icon = { Text("💬") }, icon = { Text("💬") },
label = { Text("会话") }, label = { Text("会话") },
) )
NavigationBarItem( NavigationBarItem(
selected = appState.selectedTab == MainTab.Status, selected = appState.currentRoute == AppRoute.Settings,
onClick = { appState.selectedTab = MainTab.Status }, onClick = { appState.navigateTo(AppRoute.Settings) },
icon = { Text("📡") },
label = { Text("状态") },
)
NavigationBarItem(
selected = appState.selectedTab == MainTab.Settings,
onClick = { appState.selectedTab = MainTab.Settings },
icon = { Text("⚙️") }, icon = { Text("⚙️") },
label = { Text("设置") }, label = { Text("设置") },
) )
@@ -147,29 +219,87 @@ private fun OpenClawRoot(appState: OpenClawAppState) {
) )
} }
when { when (val route = appState.currentRoute) {
activeSession != null -> ChatScreen( is AppRoute.Chat -> {
val session = activeSession ?: return@Column
ChatScreen(
modifier = Modifier.fillMaxSize(), modifier = Modifier.fillMaxSize(),
sessionTitle = activeSession.title, sessionTitle = session.title,
messages = appState.repository.messagesFor(activeSession.id), messages = appState.repository.messagesFor(session.id),
isSending = appState.isSending, isSending = appState.sendingSessionId == session.id,
isLoading = appState.isSyncing, isLoading = appState.isSyncing,
errorMessage = appState.syncError, errorMessage = appState.syncError,
onBack = appState::closeChat, streamStatus = appState.repository.streamStatusFor(session.id),
pendingQueueStatus = appState.repository.pendingQueueStatus(session.id).let { queue ->
when {
queue.recoveryInFlight && queue.sessionCount > 0 -> "当前会话还有 ${queue.sessionCount} 条待发项,系统正在恢复并继续处理本地队列。"
queue.recoveryRecentlySkipped && queue.sessionCount > 0 -> "当前会话的待发队列刚刚已处理过一轮,本次先跳过重复恢复。"
queue.isDraining && queue.sessionCount > 0 -> "当前会话还有 ${queue.sessionCount} 条待发项,系统正在按本地队列继续处理。"
queue.sessionCount > 0 -> "当前会话还有 ${queue.sessionCount} 条待发项未完成,可继续重试或等待下一次自动处理。"
else -> null
}
},
cacheNotice = if (appState.isShowingCachedData) {
"当前展示的是本地缓存${appState.cacheSavedAt?.let { "(保存于 $it)" } ?: ""},正在等待最新数据。"
} else null,
onRetry = { onRetry = {
coroutineScope.launch { coroutineScope.launch {
appState.clearSyncError() appState.clearSyncError()
appState.openSession(activeSession.id) appState.openSession(session.id)
} }
}, },
onSend = { text -> onSend = { text ->
coroutineScope.launch { coroutineScope.launch {
appState.sendMessage(activeSession.id, text) appState.sendMessage(session.id, text)
}
},
onRetryAttachment = { messageId ->
coroutineScope.launch {
appState.retryAttachment(session.id, messageId)
}
},
onRetryMessage = { messageId ->
coroutineScope.launch {
appState.retryMessage(session.id, messageId)
}
},
onCopyAttachmentName = { fileName ->
copyToClipboard(fileName)
},
onOpenAttachment = { messageId ->
coroutineScope.launch {
runCatching {
appState.repository.ensureAttachmentOpenPayload(session.id, messageId)
}.onSuccess { payload ->
if (payload != null) {
openAttachment(payload)
} else {
appState.feedbackMessage = "当前附件暂无可打开内容"
}
}.onFailure {
appState.feedbackMessage = it.message ?: "打开附件失败"
}
}
},
onDownloadAttachment = { messageId ->
coroutineScope.launch {
runCatching {
appState.repository.ensureAttachmentOpenPayload(session.id, messageId)
}.onSuccess { payload ->
if (payload != null) {
saveAttachment(payload)
} else {
appState.feedbackMessage = "当前附件暂无可下载内容"
}
}.onFailure {
appState.feedbackMessage = it.message ?: "下载附件失败"
}
} }
}, },
) )
}
appState.selectedTab == MainTab.Sessions -> SessionListScreen( AppRoute.Sessions -> SessionListScreen(
modifier = Modifier.fillMaxSize(), modifier = Modifier.fillMaxSize(),
sessions = appState.repository.sessions, sessions = appState.repository.sessions,
recentSession = appState.repository.recentSession(), recentSession = appState.repository.recentSession(),
@@ -185,24 +315,52 @@ private fun OpenClawRoot(appState: OpenClawAppState) {
onRetry = { onRetry = {
coroutineScope.launch { coroutineScope.launch {
appState.clearSyncError() appState.clearSyncError()
appState.syncRemoteIfNeeded() appState.syncRemoteIfNeeded(trigger = cn.xiaobai.openclawapp.app.SyncTrigger.Manual)
} }
}, },
) )
appState.selectedTab == MainTab.Status -> StatusScreen( AppRoute.Status -> SettingsScreen(
modifier = Modifier.fillMaxSize(),
status = appState.repository.status,
)
appState.selectedTab == MainTab.Settings -> SettingsScreen(
modifier = Modifier.fillMaxSize(), modifier = Modifier.fillMaxSize(),
serverConfig = appState.serverConfig, serverConfig = appState.serverConfig,
currentModel = appState.repository.status.currentModel, status = appState.repository.status,
availableAgents = appState.repository.availableAgents, availableAgents = appState.repository.availableAgents,
currentTheme = appState.themeMode, currentTheme = appState.themeMode,
onSelectAgent = appState::updateDefaultAgent, isRefreshing = appState.isSyncing,
onSelectAgent = { agent ->
coroutineScope.launch {
appState.updateDefaultAgent(agent)
}
},
onSelectTheme = appState::updateTheme, onSelectTheme = appState::updateTheme,
onRefreshOverview = {
coroutineScope.launch {
appState.clearSyncError()
appState.syncRemoteIfNeeded(trigger = cn.xiaobai.openclawapp.app.SyncTrigger.Manual)
}
},
onDisconnect = appState::disconnect,
)
AppRoute.Settings -> SettingsScreen(
modifier = Modifier.fillMaxSize(),
serverConfig = appState.serverConfig,
status = appState.repository.status,
availableAgents = appState.repository.availableAgents,
currentTheme = appState.themeMode,
isRefreshing = appState.isSyncing,
onSelectAgent = { agent ->
coroutineScope.launch {
appState.updateDefaultAgent(agent)
}
},
onSelectTheme = appState::updateTheme,
onRefreshOverview = {
coroutineScope.launch {
appState.clearSyncError()
appState.syncRemoteIfNeeded(trigger = cn.xiaobai.openclawapp.app.SyncTrigger.Manual)
}
},
onDisconnect = appState::disconnect, onDisconnect = appState::disconnect,
) )
} }
@@ -9,23 +9,54 @@ import cn.xiaobai.openclawapp.data.RemoteOpenClawRepository
import cn.xiaobai.openclawapp.data.RepositoryFactory import cn.xiaobai.openclawapp.data.RepositoryFactory
import cn.xiaobai.openclawapp.data.ServerConfig import cn.xiaobai.openclawapp.data.ServerConfig
import cn.xiaobai.openclawapp.network.MobileGatewayApi import cn.xiaobai.openclawapp.network.MobileGatewayApi
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
enum class SyncTrigger {
Initial,
Manual,
Background,
}
class OpenClawAppState( class OpenClawAppState(
private val preferences: AppPreferences = AppPreferences(), private val preferences: AppPreferences = AppPreferences(),
) { ) {
var selectedTab by mutableStateOf(MainTab.Sessions) var currentRoute by mutableStateOf<AppRoute>(AppRoute.Sessions)
var activeSessionId by mutableStateOf<String?>(null) val activeSessionId: String?
get() = (currentRoute as? AppRoute.Chat)?.sessionId
var serverConfig by mutableStateOf(preferences.loadServerConfig()) var serverConfig by mutableStateOf(preferences.loadServerConfig())
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 isShowingCachedData by mutableStateOf(false)
var cacheSavedAt by mutableStateOf<String?>(null)
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)
var repository: OpenClawRepository by mutableStateOf(RepositoryFactory.createRemote(serverConfig)) var repository: OpenClawRepository by mutableStateOf(RepositoryFactory.createRemote(serverConfig))
var isConfigured by mutableStateOf(serverConfig.baseUrl.isNotBlank() && serverConfig.token.isNotBlank()) var isConfigured by mutableStateOf(serverConfig.baseUrl.isNotBlank() && serverConfig.token.isNotBlank())
init {
var hydrated = false
preferences.loadOverviewSnapshot()?.let { snapshot ->
repository.hydrateOverview(snapshot)
cacheSavedAt = snapshot.savedAt.ifBlank { null }
hydrated = true
}
preferences.loadPendingSendQueue()?.let { queue ->
repository.hydratePendingSendQueue(queue)
}
preferences.loadRecentMessageSnapshotBucket()?.let { bucket ->
repository.hydrateRecentMessages(bucket)
if (cacheSavedAt == null) {
cacheSavedAt = bucket.savedAt.ifBlank { null }
}
hydrated = true
}
isShowingCachedData = hydrated
}
suspend fun connect(config: ServerConfig, password: String) { suspend fun connect(config: ServerConfig, password: String) {
isConnecting = true isConnecting = true
configError = null configError = null
@@ -56,8 +87,7 @@ class OpenClawAppState(
fun disconnect() { fun disconnect() {
isConfigured = false isConfigured = false
activeSessionId = null currentRoute = AppRoute.Sessions
selectedTab = MainTab.Sessions
syncError = null syncError = null
configError = null configError = null
serverConfig = serverConfig.copy(token = "") serverConfig = serverConfig.copy(token = "")
@@ -66,28 +96,80 @@ class OpenClawAppState(
feedbackMessage = "连接已断开" feedbackMessage = "连接已断开"
} }
suspend fun syncRemoteIfNeeded() { fun navigateTo(route: AppRoute) {
currentRoute = route
}
fun navigateBack(): Boolean {
return if (currentRoute is AppRoute.Chat) {
currentRoute = AppRoute.Sessions
true
} else {
false
}
}
suspend fun syncRemoteIfNeeded(trigger: SyncTrigger = SyncTrigger.Initial) {
val remote = repository as? RemoteOpenClawRepository ?: return val remote = repository as? RemoteOpenClawRepository ?: return
isSyncing = true isSyncing = true
syncError = null syncError = null
runCatching { runCatching {
remote.refreshStatus() coroutineScope {
remote.refreshAgents() val statusDeferred = async { remote.refreshStatus() }
remote.refreshSessions() val agentsDeferred = async { remote.refreshAgents() }
val sessionsDeferred = async { remote.refreshSessions() }
statusDeferred.await()
agentsDeferred.await()
sessionsDeferred.await()
}
val drainedText = remote.drainPendingTextQueue()
val drainedAttachments = remote.drainPendingAttachmentQueue()
preferences.saveOverviewSnapshot(remote.exportOverviewSnapshot())
persistRecentMessageCache(remote)
persistPendingSendQueue(remote)
when {
drainedText || drainedAttachments -> {
feedbackMessage = "已尝试继续处理本地待发队列"
}
trigger == SyncTrigger.Manual -> {
feedbackMessage = "已同步最新状态"
}
}
isShowingCachedData = false
}.onFailure { }.onFailure {
syncError = it.message ?: "远程同步失败" syncError = it.message ?: "远程同步失败"
feedbackMessage = "Remote 同步失败" feedbackMessage = if (trigger == SyncTrigger.Background) {
syncError
} else {
"同步失败"
}
} }
isSyncing = false isSyncing = false
} }
suspend fun refreshOverviewSilently() {
val remote = repository as? RemoteOpenClawRepository ?: return
if (isSyncing || sendingSessionId != null) return
syncRemoteIfNeeded(trigger = SyncTrigger.Background)
}
suspend fun openSession(sessionId: String) { suspend fun openSession(sessionId: String) {
repository.markSessionOpened(sessionId) repository.markSessionOpened(sessionId)
activeSessionId = sessionId currentRoute = AppRoute.Chat(sessionId)
val remote = repository as? RemoteOpenClawRepository ?: return val remote = repository as? RemoteOpenClawRepository ?: return
isSyncing = true isSyncing = true
runCatching { runCatching {
remote.refreshMessages(sessionId) remote.refreshMessages(sessionId)
val recovery = remote.recoverPendingQueueForSession(sessionId, allowAutoRetry = true)
persistRecentMessageCache(remote, preferredSessionId = sessionId)
persistPendingSendQueue(remote)
if (recovery.autoRetried) {
feedbackMessage = "已自动重试恢复的待发消息"
} else if (recovery.drained) {
feedbackMessage = "已尝试继续处理当前会话的待发队列"
} else if (recovery.skipped) {
feedbackMessage = "当前会话刚刚处理过待发队列,这次先跳过重复恢复"
}
}.onFailure { }.onFailure {
syncError = it.message ?: "会话消息加载失败" syncError = it.message ?: "会话消息加载失败"
feedbackMessage = "消息加载失败" feedbackMessage = "消息加载失败"
@@ -96,26 +178,98 @@ class OpenClawAppState(
} }
fun closeChat() { fun closeChat() {
activeSessionId = null navigateBack()
} }
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)
persistRecentMessageCache(remote, preferredSessionId = sessionId)
persistPendingSendQueue(remote)
}.onFailure { }.onFailure {
persistRecentMessageCache(remote, preferredSessionId = sessionId)
persistPendingSendQueue(remote)
syncError = it.message ?: "消息发送失败" syncError = it.message ?: "消息发送失败"
feedbackMessage = "消息发送失败" feedbackMessage = "消息发送失败"
} }
isSending = false sendingSessionId = null
} }
fun updateDefaultAgent(agent: String) { suspend fun retryMessage(sessionId: String, messageId: String) {
sendingSessionId = sessionId
runCatching {
repository.retryMessage(sessionId, messageId)
(repository as? RemoteOpenClawRepository)?.let {
persistRecentMessageCache(it, preferredSessionId = sessionId)
persistPendingSendQueue(it)
}
feedbackMessage = "已重新发送消息"
}.onFailure {
(repository as? RemoteOpenClawRepository)?.let {
persistRecentMessageCache(it, preferredSessionId = sessionId)
persistPendingSendQueue(it)
}
syncError = it.message ?: "消息重试失败"
feedbackMessage = "消息重试失败"
}
sendingSessionId = null
}
suspend fun updateDefaultAgent(agent: String) {
runCatching {
repository.updateDefaultAgent(agent)
serverConfig = serverConfig.copy(defaultAgent = agent) serverConfig = serverConfig.copy(defaultAgent = agent)
preferences.saveServerConfig(serverConfig) preferences.saveServerConfig(serverConfig)
repository.status = repository.status.copy(defaultAgent = agent) repository.status = repository.status.copy(defaultAgent = agent)
syncRemoteIfNeeded(trigger = SyncTrigger.Manual)
feedbackMessage = "默认 Agent 已切换到 $agent" feedbackMessage = "默认 Agent 已切换到 $agent"
}.onFailure {
syncError = it.message ?: "默认 Agent 切换失败"
feedbackMessage = "默认 Agent 切换失败"
}
}
suspend fun uploadAttachmentStub(
sessionId: String,
fileName: String,
bytes: ByteArray,
contentType: String? = null,
) {
runCatching {
repository.uploadAttachmentStub(sessionId, fileName, bytes, contentType)
(repository as? RemoteOpenClawRepository)?.let {
persistRecentMessageCache(it, preferredSessionId = sessionId)
persistPendingSendQueue(it)
}
feedbackMessage = "附件已加入发送队列"
}.onFailure {
(repository as? RemoteOpenClawRepository)?.let {
persistRecentMessageCache(it, preferredSessionId = sessionId)
persistPendingSendQueue(it)
}
syncError = it.message ?: "附件上传失败"
feedbackMessage = "附件上传失败"
}
}
suspend fun retryAttachment(sessionId: String, messageId: String) {
runCatching {
repository.retryAttachment(sessionId, messageId)
(repository as? RemoteOpenClawRepository)?.let {
persistRecentMessageCache(it, preferredSessionId = sessionId)
persistPendingSendQueue(it)
}
feedbackMessage = "已重新发起附件上传"
}.onFailure {
(repository as? RemoteOpenClawRepository)?.let {
persistRecentMessageCache(it, preferredSessionId = sessionId)
persistPendingSendQueue(it)
}
syncError = it.message ?: "附件重试失败"
feedbackMessage = "附件重试失败"
}
} }
fun updateTheme(theme: AppThemeMode) { fun updateTheme(theme: AppThemeMode) {
@@ -143,12 +297,28 @@ class OpenClawAppState(
fun clearConfigError() { fun clearConfigError() {
configError = null configError = null
} }
private fun persistRecentMessageCache(
remote: RemoteOpenClawRepository,
preferredSessionId: String? = activeSessionId,
) {
val recentIds = listOfNotNull(preferredSessionId, remote.recentSession()?.id)
.plus(repository.sessions.map { it.id })
.distinct()
.take(3)
preferences.saveRecentMessageSnapshotBucket(remote.exportRecentMessageSnapshotBucket(recentIds))
} }
enum class MainTab { private fun persistPendingSendQueue(remote: RemoteOpenClawRepository) {
Sessions, preferences.savePendingSendQueue(remote.exportPendingSendQueue())
Status, }
Settings, }
sealed interface AppRoute {
data object Sessions : AppRoute
data object Status : AppRoute
data object Settings : AppRoute
data class Chat(val sessionId: String) : AppRoute
} }
enum class AppThemeMode(val label: String) { enum class AppThemeMode(val label: String) {
@@ -2,10 +2,12 @@ package cn.xiaobai.openclawapp.data
import cn.xiaobai.openclawapp.app.AppThemeMode import cn.xiaobai.openclawapp.app.AppThemeMode
import com.russhwolf.settings.Settings import com.russhwolf.settings.Settings
import kotlinx.serialization.json.Json
class AppPreferences( class AppPreferences(
private val settings: Settings = Settings(), private val settings: Settings = Settings(),
) { ) {
private val json = Json { ignoreUnknownKeys = true }
fun loadServerConfig(): ServerConfig { fun loadServerConfig(): ServerConfig {
return ServerConfig( return ServerConfig(
baseUrl = settings.getStringOrNull(KEY_BASE_URL) ?: "http://192.168.31.116:8788", baseUrl = settings.getStringOrNull(KEY_BASE_URL) ?: "http://192.168.31.116:8788",
@@ -35,10 +37,40 @@ class AppPreferences(
settings.putString(KEY_THEME_MODE, themeMode.name) settings.putString(KEY_THEME_MODE, themeMode.name)
} }
fun loadOverviewSnapshot(): OverviewSnapshot? {
val raw = settings.getStringOrNull(KEY_OVERVIEW_SNAPSHOT) ?: return null
return runCatching { json.decodeFromString<OverviewSnapshot>(raw) }.getOrNull()
}
fun saveOverviewSnapshot(snapshot: OverviewSnapshot) {
settings.putString(KEY_OVERVIEW_SNAPSHOT, json.encodeToString(OverviewSnapshot.serializer(), snapshot))
}
fun loadRecentMessageSnapshotBucket(): MessageCacheBucket? {
val raw = settings.getStringOrNull(KEY_RECENT_MESSAGE_SNAPSHOT) ?: return null
return runCatching { json.decodeFromString<MessageCacheBucket>(raw) }.getOrNull()
}
fun saveRecentMessageSnapshotBucket(bucket: MessageCacheBucket) {
settings.putString(KEY_RECENT_MESSAGE_SNAPSHOT, json.encodeToString(MessageCacheBucket.serializer(), bucket))
}
fun loadPendingSendQueue(): PendingSendQueue? {
val raw = settings.getStringOrNull(KEY_PENDING_SEND_QUEUE) ?: return null
return runCatching { json.decodeFromString<PendingSendQueue>(raw) }.getOrNull()
}
fun savePendingSendQueue(queue: PendingSendQueue) {
settings.putString(KEY_PENDING_SEND_QUEUE, json.encodeToString(PendingSendQueue.serializer(), queue))
}
companion object { companion object {
private const val KEY_BASE_URL = "server.base_url" private const val KEY_BASE_URL = "server.base_url"
private const val KEY_TOKEN = "server.token" private const val KEY_TOKEN = "server.token"
private const val KEY_DEFAULT_AGENT = "server.default_agent" private const val KEY_DEFAULT_AGENT = "server.default_agent"
private const val KEY_THEME_MODE = "ui.theme_mode" private const val KEY_THEME_MODE = "ui.theme_mode"
private const val KEY_OVERVIEW_SNAPSHOT = "cache.overview_snapshot"
private const val KEY_RECENT_MESSAGE_SNAPSHOT = "cache.recent_message_snapshot_bucket"
private const val KEY_PENDING_SEND_QUEUE = "queue.pending_send"
} }
} }
@@ -0,0 +1,84 @@
package cn.xiaobai.openclawapp.data
import kotlinx.serialization.Serializable
@Serializable
data class MessageCacheBucket(
val items: List<MessageCacheSnapshot> = emptyList(),
val savedAt: String = "",
)
@Serializable
data class MessageCacheSnapshot(
val sessionId: String,
val messages: List<MessageCacheItem> = emptyList(),
)
@Serializable
data class MessageCacheItem(
val id: String,
val role: String,
val text: String,
val createdAt: String,
val status: String? = null,
val kind: String? = null,
val toolName: String? = null,
val toolCallId: String? = null,
val contentType: String? = null,
val sizeBytes: Int? = null,
val clientToken: String? = null,
val fingerprint: String? = null,
val retryable: Boolean = false,
)
fun ChatMessage.toCacheItem(): MessageCacheItem = MessageCacheItem(
id = id,
role = when (role) {
MessageRole.User -> "user"
MessageRole.Assistant -> "assistant"
MessageRole.System -> "system"
},
text = text,
createdAt = createdAt,
status = status,
kind = when (kind) {
MessageKind.Text -> "text"
MessageKind.Thinking -> "thinking"
MessageKind.Tool -> "tool"
MessageKind.ToolResult -> "tool-result"
MessageKind.Attachment -> "attachment"
},
toolName = toolName,
toolCallId = toolCallId,
contentType = contentType,
sizeBytes = sizeBytes,
clientToken = clientToken,
fingerprint = attachmentFingerprint,
retryable = retryable,
)
fun MessageCacheItem.toDomain(): ChatMessage = ChatMessage(
id = id,
role = when (role.lowercase()) {
"user" -> MessageRole.User
"assistant" -> MessageRole.Assistant
else -> MessageRole.System
},
text = text,
createdAt = createdAt,
status = status,
kind = when (kind?.lowercase()) {
"thinking" -> MessageKind.Thinking
"tool" -> MessageKind.Tool
"tool-result" -> MessageKind.ToolResult
"attachment" -> MessageKind.Attachment
else -> MessageKind.Text
},
toolName = toolName,
toolCallId = toolCallId,
contentType = contentType,
sizeBytes = sizeBytes,
clientToken = clientToken,
attachmentFingerprint = fingerprint,
retryable = retryable,
)
@@ -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 流式消息。"
}
}
}
@@ -13,6 +13,7 @@ data class SessionSummary(
val updatedAt: String, val updatedAt: String,
val isPinned: Boolean = false, val isPinned: Boolean = false,
val unreadCount: Int = 0, val unreadCount: Int = 0,
val streamStatus: String? = null,
) )
data class ChatMessage( data class ChatMessage(
@@ -21,13 +22,19 @@ data class ChatMessage(
val text: String, val text: String,
val createdAt: String, val createdAt: String,
val status: String? = null, val status: String? = null,
val kind: MessageKind = MessageKind.Text,
val toolName: String? = null,
val toolCallId: String? = null,
val contentType: String? = null,
val sizeBytes: Int? = null,
val clientToken: String? = null,
val attachmentFingerprint: String? = null,
val retryable: Boolean = false,
) )
enum class MessageRole { enum class MessageRole { User, Assistant, System }
User,
Assistant, enum class MessageKind { Text, Thinking, Tool, ToolResult, Attachment }
System,
}
data class ServerStatus( data class ServerStatus(
val online: Boolean, val online: Boolean,
@@ -36,3 +43,79 @@ data class ServerStatus(
val defaultAgent: String, val defaultAgent: String,
val updatedAt: String, val updatedAt: String,
) )
data class PendingQueueStatus(
val totalCount: Int = 0,
val sessionCount: Int = 0,
val isDraining: Boolean = false,
val recoveryInFlight: Boolean = false,
val recoveryRecentlySkipped: Boolean = false,
)
enum class LocalMessagePhase {
Idle,
QueueProcessing,
AutoRetrying,
ManualProcessing,
Failed,
Completed,
}
fun ChatMessage.localMessagePhase(): LocalMessagePhase {
return when (status) {
"queue-draining" -> LocalMessagePhase.QueueProcessing
"retrying-auto" -> LocalMessagePhase.AutoRetrying
"queued", "uploading" -> LocalMessagePhase.ManualProcessing
"send-failed", "upload-failed" -> LocalMessagePhase.Failed
"uploaded" -> LocalMessagePhase.Completed
else -> LocalMessagePhase.Idle
}
}
fun ChatMessage.isLocalPendingActive(): Boolean {
return localMessagePhase() in setOf(
LocalMessagePhase.QueueProcessing,
LocalMessagePhase.AutoRetrying,
LocalMessagePhase.ManualProcessing,
)
}
fun ChatMessage.isLocalFailure(): Boolean {
return localMessagePhase() == LocalMessagePhase.Failed
}
fun ChatMessage.isManualLocalProcessing(): Boolean {
return localMessagePhase() == LocalMessagePhase.ManualProcessing
}
fun ChatMessage.isAutoRetryCandidate(): Boolean {
return kind == MessageKind.Text &&
role == MessageRole.User &&
localMessagePhase() == LocalMessagePhase.Failed
}
fun textStatusForLocalPhase(
phase: LocalMessagePhase,
fallback: String = "queued",
): String {
return when (phase) {
LocalMessagePhase.QueueProcessing -> "queue-draining"
LocalMessagePhase.AutoRetrying -> "retrying-auto"
LocalMessagePhase.ManualProcessing -> "queued"
LocalMessagePhase.Failed -> "send-failed"
else -> fallback
}
}
fun attachmentStatusForLocalPhase(
phase: LocalMessagePhase,
fallback: String = "uploading",
): String {
return when (phase) {
LocalMessagePhase.QueueProcessing -> "queue-draining"
LocalMessagePhase.ManualProcessing -> "uploading"
LocalMessagePhase.Failed -> "upload-failed"
LocalMessagePhase.Completed -> "uploaded"
else -> fallback
}
}
@@ -4,12 +4,36 @@ interface OpenClawRepository {
var availableAgents: List<String> var availableAgents: List<String>
val sessions: List<SessionSummary> val sessions: List<SessionSummary>
var status: ServerStatus var status: ServerStatus
fun streamStatusFor(sessionId: String): String?
fun hydrateOverview(snapshot: OverviewSnapshot)
fun hydrateRecentMessages(bucket: MessageCacheBucket)
fun hydratePendingSendQueue(queue: PendingSendQueue)
fun findSession(sessionId: String): SessionSummary? fun findSession(sessionId: String): SessionSummary?
fun messagesFor(sessionId: String): List<ChatMessage> fun messagesFor(sessionId: String): List<ChatMessage>
fun pendingQueueStatus(sessionId: String? = null): PendingQueueStatus
fun recentSession(): SessionSummary? fun recentSession(): SessionSummary?
fun pinnedCount(): Int fun pinnedCount(): Int
fun markSessionOpened(sessionId: String) fun markSessionOpened(sessionId: String)
fun togglePinned(sessionId: String): Boolean fun togglePinned(sessionId: String): Boolean
fun sendMessage(sessionId: String, text: String) fun sendMessage(sessionId: String, text: String)
suspend fun retryMessage(sessionId: String, messageId: String)
suspend fun drainPendingTextQueue(sessionId: String? = null): Boolean
suspend fun drainPendingAttachmentQueue(sessionId: String? = null): Boolean
suspend fun updateDefaultAgent(agent: String)
suspend fun uploadAttachmentStub(
sessionId: String,
fileName: String,
bytes: ByteArray,
contentType: String? = null,
)
suspend fun retryAttachment(sessionId: String, messageId: String)
fun attachmentOpenPayload(messageId: String): AttachmentOpenPayload?
suspend fun ensureAttachmentOpenPayload(sessionId: String, messageId: String): AttachmentOpenPayload?
} }
data class AttachmentOpenPayload(
val fileName: String,
val bytes: ByteArray,
val contentType: String? = null,
)
@@ -0,0 +1,69 @@
package cn.xiaobai.openclawapp.data
import kotlinx.serialization.Serializable
@Serializable
data class OverviewSnapshot(
val availableAgents: List<String> = emptyList(),
val sessions: List<OverviewSessionSnapshot> = emptyList(),
val status: OverviewStatusSnapshot = OverviewStatusSnapshot(),
val savedAt: String = "",
)
@Serializable
data class OverviewSessionSnapshot(
val id: String,
val title: String,
val lastMessage: String,
val updatedAt: String,
val sortKey: Long? = null,
val isPinned: Boolean = false,
val unreadCount: Int = 0,
val streamStatus: String? = null,
)
@Serializable
data class OverviewStatusSnapshot(
val online: Boolean = false,
val openClawVersion: String = "-",
val currentModel: String = "-",
val defaultAgent: String = "main",
val updatedAt: String = "-",
)
fun ServerStatus.toSnapshot(): OverviewStatusSnapshot = OverviewStatusSnapshot(
online = online,
openClawVersion = openClawVersion,
currentModel = currentModel,
defaultAgent = defaultAgent,
updatedAt = updatedAt,
)
fun SessionSummary.toSnapshot(sortKey: Long? = null): OverviewSessionSnapshot = OverviewSessionSnapshot(
id = id,
title = title,
lastMessage = lastMessage,
updatedAt = updatedAt,
sortKey = sortKey,
isPinned = isPinned,
unreadCount = unreadCount,
streamStatus = streamStatus,
)
fun OverviewStatusSnapshot.toDomain(): ServerStatus = ServerStatus(
online = online,
openClawVersion = openClawVersion,
currentModel = currentModel,
defaultAgent = defaultAgent,
updatedAt = updatedAt,
)
fun OverviewSessionSnapshot.toDomain(): SessionSummary = SessionSummary(
id = id,
title = title,
lastMessage = lastMessage,
updatedAt = updatedAt,
isPinned = isPinned,
unreadCount = unreadCount,
streamStatus = streamStatus,
)
@@ -0,0 +1,31 @@
package cn.xiaobai.openclawapp.data
import kotlinx.serialization.Serializable
@Serializable
data class PendingSendQueue(
val items: List<PendingSendItem> = emptyList(),
val savedAt: String = "",
)
@Serializable
enum class PendingSendKind {
Text,
Attachment,
}
@Serializable
data class PendingSendItem(
val messageId: String,
val sessionId: String,
val createdAt: String,
val kind: PendingSendKind = PendingSendKind.Text,
val text: String = "",
val autoRetryEligible: Boolean = true,
val clientToken: String? = null,
val fileName: String = "",
val contentType: String? = null,
val base64Data: String? = null,
val sizeBytes: Int? = null,
val fingerprint: String? = null,
)
@@ -1,7 +1,5 @@
package cn.xiaobai.openclawapp.data package cn.xiaobai.openclawapp.data
object RepositoryFactory { object RepositoryFactory {
fun createMock(): OpenClawRepository = MockOpenClawRepository()
fun createRemote(config: ServerConfig): OpenClawRepository = RemoteOpenClawRepository(config) fun createRemote(config: ServerConfig): OpenClawRepository = RemoteOpenClawRepository(config)
} }
@@ -0,0 +1,126 @@
package cn.xiaobai.openclawapp.data
sealed interface DeliveryOperationType {
data object SendText : DeliveryOperationType
data object SendAttachment : DeliveryOperationType
}
enum class DeliveryOperationState {
Accepted,
Persisted,
Dispatching,
AwaitingRemoteEcho,
Materialized,
FailedRetryable,
FailedTerminal,
Cancelled,
}
data class DeliveryOperation(
val opId: String,
val sessionId: String,
val type: DeliveryOperationType,
val state: DeliveryOperationState,
val createdAtMs: Long,
val clientRequestId: String,
val payloadSummary: String,
val attemptCount: Int = 0,
val lastError: String? = null,
val correlationToken: String? = null,
val materializedMessageIds: List<String> = emptyList(),
)
enum class SessionSyncState {
Idle,
Bootstrapping,
Refreshing,
Failed,
}
enum class SessionStreamState {
Idle,
Connecting,
Live,
Recovering,
Failed,
}
sealed interface MessageTimelineItem {
data class RemoteMessage(val message: ChatMessage) : MessageTimelineItem
data class PendingOperation(val operation: DeliveryOperation) : MessageTimelineItem
data class SystemNotice(val id: String, val text: String) : MessageTimelineItem
}
data class SessionDetailState(
val sessionId: String,
val timeline: List<MessageTimelineItem> = emptyList(),
val operations: List<DeliveryOperation> = emptyList(),
val syncState: SessionSyncState = SessionSyncState.Idle,
val streamState: SessionStreamState = SessionStreamState.Idle,
val lastBootstrapAtMs: Long? = null,
val lastError: String? = null,
)
sealed interface SessionDetailEvent {
data class BootstrapLoaded(
val sessionId: String,
val timeline: List<MessageTimelineItem>,
val operations: List<DeliveryOperation>,
val loadedAtMs: Long,
) : SessionDetailEvent
data class OperationUpserted(val operation: DeliveryOperation) : SessionDetailEvent
data class OperationRemoved(val opId: String) : SessionDetailEvent
data class MessageUpserted(val message: ChatMessage) : SessionDetailEvent
data class MessageRemoved(val messageId: String) : SessionDetailEvent
data class SyncStateChanged(val syncState: SessionSyncState, val error: String? = null) : SessionDetailEvent
data class StreamStateChanged(val streamState: SessionStreamState) : SessionDetailEvent
}
fun reduceSessionDetailState(
previous: SessionDetailState,
event: SessionDetailEvent,
): SessionDetailState {
return when (event) {
is SessionDetailEvent.BootstrapLoaded -> previous.copy(
sessionId = event.sessionId,
timeline = event.timeline,
operations = event.operations,
syncState = SessionSyncState.Idle,
lastBootstrapAtMs = event.loadedAtMs,
lastError = null,
)
is SessionDetailEvent.OperationUpserted -> {
val nextOps = previous.operations
.filterNot { it.opId == event.operation.opId } + event.operation
previous.copy(operations = nextOps)
}
is SessionDetailEvent.OperationRemoved -> previous.copy(
operations = previous.operations.filterNot { it.opId == event.opId }
)
is SessionDetailEvent.MessageUpserted -> {
val nextTimeline = previous.timeline.filterNot {
it is MessageTimelineItem.RemoteMessage && it.message.id == event.message.id
} + MessageTimelineItem.RemoteMessage(event.message)
previous.copy(timeline = nextTimeline)
}
is SessionDetailEvent.MessageRemoved -> previous.copy(
timeline = previous.timeline.filterNot {
it is MessageTimelineItem.RemoteMessage && it.message.id == event.messageId
}
)
is SessionDetailEvent.SyncStateChanged -> previous.copy(
syncState = event.syncState,
lastError = event.error,
)
is SessionDetailEvent.StreamStateChanged -> previous.copy(
streamState = event.streamState,
)
}
}
@@ -1,6 +1,7 @@
package cn.xiaobai.openclawapp.feature.chat package cn.xiaobai.openclawapp.feature.chat
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
@@ -8,6 +9,7 @@ import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.lazy.rememberLazyListState
@@ -17,7 +19,9 @@ import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.PullToRefreshBox
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
@@ -28,11 +32,16 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import cn.xiaobai.openclawapp.data.ChatMessage import cn.xiaobai.openclawapp.data.ChatMessage
import cn.xiaobai.openclawapp.data.LocalMessagePhase
import cn.xiaobai.openclawapp.data.MessageKind
import cn.xiaobai.openclawapp.data.MessageRole import cn.xiaobai.openclawapp.data.MessageRole
import cn.xiaobai.openclawapp.data.localMessagePhase
import cn.xiaobai.openclawapp.ui.EmptyStateCard import cn.xiaobai.openclawapp.ui.EmptyStateCard
import cn.xiaobai.openclawapp.ui.StatusPill import cn.xiaobai.openclawapp.ui.StatusPill
import cn.xiaobai.openclawapp.ui.StatusPillTone
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
@Composable @Composable
@@ -43,90 +52,60 @@ fun ChatScreen(
isSending: Boolean, isSending: Boolean,
isLoading: Boolean, isLoading: Boolean,
errorMessage: String?, errorMessage: String?,
onBack: () -> Unit, streamStatus: String?,
pendingQueueStatus: String?,
cacheNotice: String?,
onRetry: () -> Unit, onRetry: () -> Unit,
onSend: (String) -> Unit, onSend: (String) -> Unit,
onRetryAttachment: (String) -> Unit,
onRetryMessage: (String) -> Unit,
onCopyAttachmentName: (String) -> Unit,
onOpenAttachment: (String) -> Unit,
onDownloadAttachment: (String) -> Unit,
) { ) {
var input by remember { mutableStateOf("") } var input by remember { mutableStateOf("") }
val listState = rememberLazyListState() val listState = rememberLazyListState()
val visibleMessages = remember(messages) {
LaunchedEffect(messages.size) { messages.filterNot { message ->
if (messages.isNotEmpty()) { message.kind == MessageKind.Tool ||
listState.animateScrollToItem(messages.lastIndex) (message.kind == MessageKind.ToolResult && message.status != "tool-error")
} }
} }
LaunchedEffect(visibleMessages.size) {
if (visibleMessages.isNotEmpty()) {
listState.animateScrollToItem(visibleMessages.lastIndex)
}
}
val topStatus = remember(isSending, isLoading, streamStatus, pendingQueueStatus, cacheNotice, errorMessage) {
buildChatTopStatus(
isSending = isSending,
isLoading = isLoading,
streamStatus = streamStatus,
pendingQueueStatus = pendingQueueStatus,
cacheNotice = cacheNotice,
errorMessage = errorMessage,
)
}
PullToRefreshBox(
isRefreshing = isLoading,
onRefresh = onRetry,
modifier = modifier,
) {
Column( Column(
modifier = modifier.padding(16.dp), modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(12.dp),
) { ) {
Card( if (topStatus.visible) {
modifier = Modifier.fillMaxWidth(), ChatStatusBanner(topStatus = topStatus)
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceContainerLow,
),
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(14.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Button(onClick = onBack) { Text("返回") }
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(sessionTitle, style = MaterialTheme.typography.titleLarge)
Text(
"当前先走 Mock 对话流,后面这里会接 SSE / WebSocket。",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
StatusPill(text = if (isLoading) "同步中" else "在线", highlighted = true)
}
} }
if (errorMessage != null) { if (visibleMessages.isEmpty() && !isLoading) {
Card(
modifier = Modifier.fillMaxWidth(),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer),
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(14.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
errorMessage,
modifier = Modifier.weight(1f),
color = MaterialTheme.colorScheme.onErrorContainer,
)
Button(onClick = onRetry) {
Text("重试")
}
}
}
}
Card(modifier = Modifier.fillMaxWidth()) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
QuickActionButton("帮我总结") { onSend("帮我总结一下当前会话") }
QuickActionButton("看状态") { onSend("看一下当前状态") }
QuickActionButton("下一步") { onSend("下一步建议做什么") }
}
}
if (messages.isEmpty() && !isLoading) {
EmptyStateCard( EmptyStateCard(
title = "还没有消息", title = "还没有消息",
subtitle = "这里以后会展示真实的会话历史、流式回复和工具执行状态。", subtitle = "进入会话后,这里会显示历史消息、回复进度和关键错误。",
) )
} else { } else {
LazyColumn( LazyColumn(
@@ -136,34 +115,48 @@ fun ChatScreen(
state = listState, state = listState,
verticalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
) { ) {
itemsIndexed(messages, key = { _, message -> message.id }) { index, message -> itemsIndexed(visibleMessages, key = { _, message -> message.id }) { index, message ->
val shouldAnimate = index == messages.lastIndex && val shouldAnimate = index == visibleMessages.lastIndex &&
message.role == MessageRole.Assistant && message.role == MessageRole.Assistant &&
message.createdAt == "现在" message.createdAt == "现在"
val linkedTool = if (message.kind == MessageKind.ToolResult) {
messages.lastOrNull {
it.kind == MessageKind.Tool &&
it.toolCallId != null &&
it.toolCallId == message.toolCallId
}
} else null
MessageBubble( MessageBubble(
message = message, message = message,
animateText = shouldAnimate, animateText = shouldAnimate,
linkedToolName = linkedTool?.toolName,
onRetryAttachment = onRetryAttachment,
onRetryMessage = onRetryMessage,
onCopyAttachmentName = onCopyAttachmentName,
onOpenAttachment = onOpenAttachment,
onDownloadAttachment = onDownloadAttachment,
) )
} }
} }
} }
Card(modifier = Modifier.fillMaxWidth()) { if (visibleMessages.isEmpty() && !isLoading) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Text(
if (isSending) "正在发送消息…" else "直接发一条消息给当前会话",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
QuickActionButton("帮我总结") { onSend("帮我总结一下当前会话") }
QuickActionButton("看状态") { onSend("看一下当前状态") }
}
}
Card(modifier = Modifier.fillMaxWidth()) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp, vertical = 10.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.Bottom, verticalAlignment = Alignment.Bottom,
) { ) {
OutlinedTextField( OutlinedTextField(
@@ -171,8 +164,8 @@ fun ChatScreen(
onValueChange = { input = it }, onValueChange = { input = it },
modifier = Modifier.weight(1f), modifier = Modifier.weight(1f),
label = { Text("输入消息") }, label = { Text("输入消息") },
placeholder = { Text("给 OpenClaw 发一句话") }, placeholder = { Text("给 $sessionTitle 发一句话") },
maxLines = 4, maxLines = 3,
enabled = !isSending, enabled = !isSending,
) )
Button( Button(
@@ -184,45 +177,174 @@ fun ChatScreen(
}, },
enabled = !isSending, enabled = !isSending,
) { ) {
if (isSending) { if (isSending) CircularProgressIndicator() else Text("发送")
CircularProgressIndicator()
} else {
Text("发送")
} }
} }
} }
} }
} }
} }
private data class ChatTopStatus(
val text: String,
val tone: StatusPillTone,
val visible: Boolean = true,
)
private fun buildChatTopStatus(
isSending: Boolean,
isLoading: Boolean,
streamStatus: String?,
pendingQueueStatus: String?,
cacheNotice: String?,
errorMessage: String?,
): ChatTopStatus {
return when {
errorMessage != null -> ChatTopStatus(
text = errorMessage,
tone = StatusPillTone.Error,
)
pendingQueueStatus != null -> ChatTopStatus(
text = "正在处理待发消息",
tone = StatusPillTone.Warning,
)
cacheNotice != null -> ChatTopStatus(
text = "当前显示本地缓存",
tone = StatusPillTone.Warning,
)
isSending -> ChatTopStatus(
text = "正在等待回复",
tone = StatusPillTone.Info,
)
isLoading -> ChatTopStatus(
text = "正在同步消息",
tone = StatusPillTone.Info,
)
streamStatus == "recovering" -> ChatTopStatus(
text = "连接恢复中",
tone = StatusPillTone.Warning,
)
streamStatus == "reconnecting" -> ChatTopStatus(
text = "正在重连",
tone = StatusPillTone.Warning,
)
streamStatus == "failed" -> ChatTopStatus(
text = "实时流已断开",
tone = StatusPillTone.Error,
)
streamStatus == "connecting" -> ChatTopStatus(
text = "正在连接",
tone = StatusPillTone.Info,
)
else -> ChatTopStatus(
text = "在线",
tone = StatusPillTone.Success,
visible = false,
)
}
}
@Composable
private fun ChatStatusBanner(
topStatus: ChatTopStatus,
) {
Card(
modifier = Modifier.fillMaxWidth(),
colors = CardDefaults.cardColors(
containerColor = when (topStatus.tone) {
StatusPillTone.Error -> MaterialTheme.colorScheme.errorContainer
StatusPillTone.Warning -> MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.55f)
StatusPillTone.Success -> MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.55f)
StatusPillTone.Info -> MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.5f)
StatusPillTone.Neutral -> MaterialTheme.colorScheme.surfaceContainerHigh
},
),
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 10.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
StatusPill(
text = when (topStatus.tone) {
StatusPillTone.Error -> "需处理"
StatusPillTone.Warning -> "处理中"
StatusPillTone.Success -> "在线"
StatusPillTone.Info -> "同步中"
StatusPillTone.Neutral -> "提示"
},
tone = topStatus.tone,
)
Text(
text = topStatus.text,
style = MaterialTheme.typography.bodySmall,
color = when (topStatus.tone) {
StatusPillTone.Error -> MaterialTheme.colorScheme.onErrorContainer
StatusPillTone.Warning -> MaterialTheme.colorScheme.onTertiaryContainer
StatusPillTone.Success -> MaterialTheme.colorScheme.onSecondaryContainer
StatusPillTone.Info -> MaterialTheme.colorScheme.onPrimaryContainer
StatusPillTone.Neutral -> MaterialTheme.colorScheme.onSurfaceVariant
},
modifier = Modifier.weight(1f),
)
}
}
} }
@Composable @Composable
private fun RowScope.QuickActionButton(text: String, onClick: () -> Unit) { private fun RowScope.QuickActionButton(text: String, onClick: () -> Unit) {
Button(onClick = onClick, modifier = Modifier.weight(1f)) { Button(onClick = onClick, modifier = Modifier.weight(1f)) { Text(text) }
Text(text)
}
} }
@Composable @Composable
private fun MessageBubble( private fun MessageBubble(
message: ChatMessage, message: ChatMessage,
animateText: Boolean = false, animateText: Boolean = false,
linkedToolName: String? = null,
onRetryAttachment: (String) -> Unit,
onRetryMessage: (String) -> Unit,
onCopyAttachmentName: (String) -> Unit,
onOpenAttachment: (String) -> Unit,
onDownloadAttachment: (String) -> Unit,
) { ) {
val alignment = when (message.role) { val alignment = when (message.role) {
MessageRole.User -> Alignment.CenterEnd MessageRole.User -> Alignment.CenterEnd
else -> Alignment.CenterStart else -> Alignment.CenterStart
} }
val bubbleColor = when (message.role) {
MessageRole.User -> MaterialTheme.colorScheme.primaryContainer
MessageRole.Assistant -> MaterialTheme.colorScheme.secondaryContainer
MessageRole.System -> MaterialTheme.colorScheme.surfaceVariant
}
val label = when (message.role) { val label = when (message.role) {
MessageRole.User -> "你" MessageRole.User -> "你"
MessageRole.Assistant -> "OpenClaw" MessageRole.Assistant -> "OpenClaw"
MessageRole.System -> "系统" MessageRole.System -> "系统"
} }
val isThinking = message.status == "thinking" || message.kind == MessageKind.Thinking
val isTool = message.kind == MessageKind.Tool
val isToolResult = message.kind == MessageKind.ToolResult
val isAttachment = message.kind == MessageKind.Attachment
val isSystemNotice = message.role == MessageRole.System && !isToolResult && !isTool && !isAttachment
val bubbleColor = when {
isSystemNotice -> MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.6f)
message.role == MessageRole.User -> MaterialTheme.colorScheme.primaryContainer
isToolResult && message.status == "tool-error" -> MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.5f)
isToolResult -> MaterialTheme.colorScheme.surfaceContainer
isTool -> MaterialTheme.colorScheme.surfaceContainerLow
isAttachment && message.status == "upload-failed" -> MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.24f)
isAttachment -> MaterialTheme.colorScheme.surfaceContainerLow
else -> MaterialTheme.colorScheme.surface
}
var visibleChars by remember(message.id) { mutableIntStateOf(if (animateText) 0 else message.text.length) } var visibleChars by remember(message.id) { mutableIntStateOf(if (animateText) 0 else message.text.length) }
var expanded by remember(message.id) { mutableStateOf(false) }
var attachmentDetailsExpanded by remember(message.id) { mutableStateOf(false) }
LaunchedEffect(message.id, animateText) { LaunchedEffect(message.id, animateText) {
if (animateText) { if (animateText) {
@@ -237,30 +359,218 @@ private fun MessageBubble(
} }
val displayText = message.text.take(visibleChars) val displayText = message.text.take(visibleChars)
val isStructuredOutput = isToolResult && looksStructuredOutput(displayText)
val shouldCollapseToolResult = isToolResult && displayText.length > 240
val toolResultText = if (shouldCollapseToolResult && !expanded) displayText.take(240).trimEnd() + "…" else displayText
val localPhase = message.localMessagePhase()
val displayStatus = when { val displayStatus = when {
animateText && visibleChars < message.text.length -> "streaming" animateText && visibleChars < message.text.length -> "生成中"
else -> message.status localPhase == LocalMessagePhase.QueueProcessing && message.kind == MessageKind.Attachment -> "上传队列中"
localPhase == LocalMessagePhase.QueueProcessing -> "发送队列中"
localPhase == LocalMessagePhase.AutoRetrying -> "自动重试中"
message.status == "queued" -> "发送中"
message.status == "uploading" -> "上传中"
message.status == "send-failed" -> "发送失败"
message.status == "upload-failed" -> "上传失败"
message.status == "tool-running" -> "执行中"
message.status == "tool-error" -> "执行失败"
message.status == "stream-failed" -> "生成失败"
localPhase == LocalMessagePhase.Completed && message.kind == MessageKind.Attachment -> "已完成"
message.status == "tool-done" -> "已完成"
else -> null
}
val statusTone = when (displayStatus) {
"生成中", "发送队列中", "上传队列中", "自动重试中", "发送中", "上传中", "执行中" -> StatusPillTone.Warning
"发送失败", "上传失败", "执行失败", "生成失败" -> StatusPillTone.Error
"已完成" -> StatusPillTone.Success
else -> StatusPillTone.Neutral
} }
Box(modifier = Modifier.fillMaxWidth(), contentAlignment = alignment) { Box(modifier = Modifier.fillMaxWidth(), contentAlignment = alignment) {
Column( Column(
modifier = Modifier.fillMaxWidth(0.88f), modifier = if (isSystemNotice) Modifier.fillMaxWidth() else Modifier.fillMaxWidth(if (isToolResult) 0.94f else 0.86f),
verticalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp),
horizontalAlignment = if (message.role == MessageRole.User) Alignment.End else Alignment.Start, horizontalAlignment = if (isSystemNotice) Alignment.CenterHorizontally else if (message.role == MessageRole.User) Alignment.End else Alignment.Start,
) { ) {
if (!isSystemNotice && message.role != MessageRole.User) {
Text( Text(
text = label, text = label,
style = MaterialTheme.typography.labelMedium, style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
}
Column( Column(
modifier = Modifier modifier = Modifier
.clip(androidx.compose.foundation.shape.RoundedCornerShape(20.dp)) .clip(androidx.compose.foundation.shape.RoundedCornerShape(if (isSystemNotice) 12.dp else 18.dp))
.border(
width = when {
isSystemNotice -> 0.dp
isTool || isToolResult || isAttachment -> 1.dp
else -> 0.dp
},
color = when {
isToolResult && message.status == "tool-error" -> MaterialTheme.colorScheme.error
isToolResult -> MaterialTheme.colorScheme.outlineVariant
isTool -> MaterialTheme.colorScheme.secondary
isAttachment && message.status == "upload-failed" -> MaterialTheme.colorScheme.error
isAttachment -> MaterialTheme.colorScheme.outlineVariant
else -> MaterialTheme.colorScheme.surfaceVariant
},
shape = androidx.compose.foundation.shape.RoundedCornerShape(if (isSystemNotice) 14.dp else 18.dp),
)
.background(bubbleColor) .background(bubbleColor)
.padding(14.dp), .padding(if (isSystemNotice) 8.dp else 14.dp),
verticalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp),
) { ) {
Text(text = displayText, style = MaterialTheme.typography.bodyLarge) when {
isThinking -> {
Row(
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
CircularProgressIndicator(
modifier = Modifier.size(18.dp),
strokeWidth = 2.dp,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
text = if (message.text.isBlank()) "正在思考…" else message.text,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
isAttachment -> {
StatusPill(text = "附件", tone = if (message.status == "upload-failed") StatusPillTone.Error else StatusPillTone.Neutral)
Text(
text = displayText,
style = MaterialTheme.typography.bodyLarge,
)
val meta = buildList {
message.contentType?.takeIf { it.isNotBlank() }?.let { add(it) }
message.sizeBytes?.let { add(formatBytes(it)) }
}.joinToString(" · ")
if (meta.isNotBlank()) {
Text(
text = meta,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (message.retryable && message.status == "upload-failed") {
Button(onClick = { onRetryAttachment(message.id) }) {
Text("重新发送附件")
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
TextButton(onClick = { onOpenAttachment(message.id) }, modifier = Modifier.weight(1f)) {
Text("打开")
}
TextButton(onClick = { onDownloadAttachment(message.id) }, modifier = Modifier.weight(1f)) {
Text("下载")
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
TextButton(onClick = { onCopyAttachmentName(message.text) }, modifier = Modifier.weight(1f)) {
Text("复制文件名")
}
TextButton(onClick = { attachmentDetailsExpanded = !attachmentDetailsExpanded }, modifier = Modifier.weight(1f)) {
Text(if (attachmentDetailsExpanded) "收起详情" else "查看详情")
}
}
if (attachmentDetailsExpanded) {
Column(
modifier = Modifier
.fillMaxWidth()
.clip(androidx.compose.foundation.shape.RoundedCornerShape(12.dp))
.background(MaterialTheme.colorScheme.surface.copy(alpha = 0.4f))
.padding(10.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Text("文件名:${message.text}", style = MaterialTheme.typography.bodySmall)
Text("类型:${message.contentType ?: "unknown"}", style = MaterialTheme.typography.bodySmall)
Text("大小:${message.sizeBytes?.let(::formatBytes) ?: "unknown"}", style = MaterialTheme.typography.bodySmall)
Text("状态:${displayStatus ?: "已同步"}", style = MaterialTheme.typography.bodySmall)
}
}
}
isTool -> {
StatusPill(text = "工具调用", tone = if (message.status == "tool-error") StatusPillTone.Error else StatusPillTone.Neutral)
Text(
text = message.toolName ?: "工具调用",
style = MaterialTheme.typography.titleSmall,
)
Text(
text = when (message.status) {
"tool-done" -> "工具执行完成"
"tool-error" -> "工具执行失败"
else -> displayText.ifBlank { "工具正在执行…" }
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
isToolResult -> {
StatusPill(
text = if (message.status == "tool-error") "执行失败" else "工具结果",
tone = if (message.status == "tool-error") StatusPillTone.Error else StatusPillTone.Neutral,
)
if (!linkedToolName.isNullOrBlank()) {
Text(
text = linkedToolName,
style = MaterialTheme.typography.titleSmall,
)
}
Column(
modifier = Modifier
.fillMaxWidth()
.clip(androidx.compose.foundation.shape.RoundedCornerShape(12.dp))
.background(
if (message.status == "tool-error") {
MaterialTheme.colorScheme.error.copy(alpha = 0.08f)
} else {
MaterialTheme.colorScheme.surface.copy(alpha = 0.45f)
}
)
.padding(12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
text = toolResultText,
style = if (isStructuredOutput) {
MaterialTheme.typography.bodySmall
} else {
MaterialTheme.typography.bodyMedium
},
maxLines = if (expanded) Int.MAX_VALUE else 12,
overflow = TextOverflow.Ellipsis,
)
if (shouldCollapseToolResult) {
TextButton(onClick = { expanded = !expanded }) {
Text(if (expanded) "收起" else "展开完整结果")
}
}
}
}
else -> {
Text(
text = displayText,
style = if (isSystemNotice) MaterialTheme.typography.bodyMedium else MaterialTheme.typography.bodyLarge,
color = if (isSystemNotice) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onSurface,
)
if (message.retryable && localPhase == LocalMessagePhase.Failed && message.status == "send-failed") {
TextButton(onClick = { onRetryMessage(message.id) }) {
Text("重试")
}
}
}
}
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp),
@@ -272,11 +582,30 @@ private fun MessageBubble(
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.weight(1f), modifier = Modifier.weight(1f),
) )
if (displayStatus != null) { if (displayStatus != null && !isSystemNotice && displayStatus != "已完成") {
StatusPill(text = displayStatus) StatusPill(text = displayStatus, tone = statusTone)
} }
} }
} }
} }
} }
} }
private fun looksStructuredOutput(text: String): Boolean {
val trimmed = text.trim()
if (trimmed.isEmpty()) return false
if ((trimmed.startsWith("{") && trimmed.endsWith("}")) || (trimmed.startsWith("[") && trimmed.endsWith("]"))) {
return true
}
val lineCount = trimmed.lines().size
return lineCount >= 4 || trimmed.contains("\n ") || trimmed.contains("\t")
}
private fun formatBytes(bytes: Int): String {
val value = bytes.toLong().coerceAtLeast(0)
return when {
value >= 1024L * 1024L -> String.format("%.1f MB", value / 1024f / 1024f)
value >= 1024L -> String.format("%.1f KB", value / 1024f)
else -> "$value B"
}
}
@@ -14,7 +14,9 @@ import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.PullToRefreshBox
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
@@ -22,12 +24,13 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import cn.xiaobai.openclawapp.data.SessionSummary import cn.xiaobai.openclawapp.data.SessionSummary
import cn.xiaobai.openclawapp.ui.EmptyStateCard import cn.xiaobai.openclawapp.ui.EmptyStateCard
import cn.xiaobai.openclawapp.ui.HeroCard import cn.xiaobai.openclawapp.ui.SectionHeader
import cn.xiaobai.openclawapp.ui.MetricCard
import cn.xiaobai.openclawapp.ui.StatusPill import cn.xiaobai.openclawapp.ui.StatusPill
import cn.xiaobai.openclawapp.ui.StatusPillTone
@Composable @Composable
fun SessionListScreen( fun SessionListScreen(
@@ -49,23 +52,49 @@ fun SessionListScreen(
it.lastMessage.contains(query, ignoreCase = true) it.lastMessage.contains(query, ignoreCase = true)
} }
PullToRefreshBox(
isRefreshing = isLoading,
onRefresh = onRetry,
modifier = modifier,
) {
LazyColumn( LazyColumn(
modifier = modifier.padding(16.dp), modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(14.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
) { ) {
item { item {
HeroCard( SectionHeader(
title = "OpenClaw Mobile", title = "会话",
subtitle = "先把会话体验打磨得像个真正可用的 App,再接真实消息流。这样后面联调会轻松很多。", subtitle = when {
badge = "${if (isLoading) "Syncing" else "Ready"}", isLoading -> "正在同步…"
query.isNotBlank() -> "${filteredSessions.size} 条匹配结果"
else -> "${sessions.size} 条会话 · ${pinnedCount} 条置顶"
},
) )
} }
item { item {
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { Row(
MetricCard(title = "总会话", value = sessions.size.toString(), modifier = Modifier.weight(1f)) modifier = Modifier.fillMaxWidth(),
MetricCard(title = "已置顶", value = pinnedCount.toString(), modifier = Modifier.weight(1f)) horizontalArrangement = Arrangement.spacedBy(8.dp),
MetricCard(title = "筛选结果", value = filteredSessions.size.toString(), modifier = Modifier.weight(1f)) verticalAlignment = Alignment.CenterVertically,
) {
if (isLoading) {
CircularProgressIndicator(modifier = Modifier.padding(end = 4.dp))
Text(
text = "同步中",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.weight(1f),
)
} else {
Text(
text = "",
modifier = Modifier.weight(1f),
)
}
TextButton(onClick = onRetry, enabled = !isLoading) {
Text("刷新")
}
} }
} }
@@ -113,24 +142,31 @@ fun SessionListScreen(
Card( Card(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
colors = CardDefaults.cardColors( colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.tertiaryContainer, containerColor = MaterialTheme.colorScheme.surfaceContainerLow,
), ),
) { ) {
Column( Row(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(16.dp), .padding(horizontal = 14.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.CenterVertically,
) { ) {
Text("最近访问", style = MaterialTheme.typography.labelLarge) Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(recentSession.title, style = MaterialTheme.typography.titleMedium) Text("最近访问", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(recentSession.title, style = MaterialTheme.typography.titleSmall, maxLines = 1)
recentSession.lastMessage.takeIf { it.isNotBlank() }?.let { summary ->
Text( Text(
recentSession.lastMessage, summary,
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
) )
Button(onClick = { onOpenSession(recentSession.id) }) { }
Text("继续查看") }
TextButton(onClick = { onOpenSession(recentSession.id) }) {
Text("打开")
} }
} }
} }
@@ -143,20 +179,40 @@ fun SessionListScreen(
onValueChange = { query = it }, onValueChange = { query = it },
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
singleLine = true, singleLine = true,
label = { Text("搜索会话") }, placeholder = { Text("搜索会话") },
placeholder = { Text("按标题、ID 或最后一条消息搜索") },
) )
} }
if (filteredSessions.isEmpty() && !isLoading) { if (filteredSessions.isEmpty() && !isLoading) {
item { item {
EmptyStateCard( EmptyStateCard(
title = "没有匹配的会话", title = if (query.isBlank()) "暂时还没有可显示的会话" else "没有匹配的会话",
subtitle = "如果你当前走的是 Remote 模式,那下一步就该检查 BFF 接口返回和 DTO 映射了。", subtitle = if (query.isBlank()) {
"稍后刷新,或先检查连接地址和登录状态。"
} else {
"换个关键词试试,或清空搜索后查看全部会话。"
},
) )
} }
} else { } else {
items(filteredSessions, key = { it.id }) { session -> items(filteredSessions, key = { it.id }) { session ->
SessionRow(
session = session,
onOpen = { onOpenSession(session.id) },
onTogglePin = { onTogglePin(session.id) },
)
}
}
}
}
}
@Composable
private fun SessionRow(
session: SessionSummary,
onOpen: () -> Unit,
onTogglePin: () -> Unit,
) {
Card( Card(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
colors = CardDefaults.cardColors( colors = CardDefaults.cardColors(
@@ -166,52 +222,71 @@ fun SessionListScreen(
Column( Column(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.clickable { onOpenSession(session.id) } .clickable(onClick = onOpen)
.padding(16.dp), .padding(horizontal = 14.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(8.dp),
) { ) {
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
) { ) {
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
Text( Text(
text = session.title, text = session.title,
style = MaterialTheme.typography.titleMedium, style = MaterialTheme.typography.titleMedium,
modifier = Modifier.weight(1f),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
) )
if (session.isPinned) {
StatusPill(text = "置顶")
}
if (session.unreadCount > 0) {
StatusPill(text = "${session.unreadCount} 未读", highlighted = true)
}
}
Text( Text(
text = session.id, text = session.updatedAt,
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
} }
StatusPill(text = session.updatedAt, highlighted = true)
} session.lastMessage.takeIf { it.isNotBlank() }?.let { summary ->
Text( Text(
text = session.lastMessage, text = summary,
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
) )
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Button(onClick = { onOpenSession(session.id) }) {
Text("打开")
}
Button(onClick = { onTogglePin(session.id) }) {
Text(if (session.isPinned) "取消置顶" else "置顶")
} }
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
if (session.isPinned) {
StatusPill(text = "置顶", tone = StatusPillTone.Neutral)
}
if (session.unreadCount > 0) {
StatusPill(text = "${session.unreadCount}", tone = StatusPillTone.Info)
}
session.streamStatus?.let { streamStatus ->
val (label, tone) = streamStatusLabelAndTone(streamStatus)
if (label != null) {
StatusPill(text = label, tone = tone)
}
}
TextButton(onClick = onTogglePin) {
Text(if (session.isPinned) "★" else "☆")
} }
} }
} }
} }
} }
private fun streamStatusLabelAndTone(streamStatus: String): Pair<String?, StatusPillTone> {
return when (streamStatus) {
"recovering" -> "恢复中" to StatusPillTone.Warning
"reconnecting" -> "重连中" to StatusPillTone.Warning
"failed" -> "已断流" to StatusPillTone.Error
"connecting" -> "连接中" to StatusPillTone.Warning
"live" -> "在线" to StatusPillTone.Success
else -> null to StatusPillTone.Neutral
} }
} }
@@ -14,19 +14,24 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import cn.xiaobai.openclawapp.app.AppThemeMode import cn.xiaobai.openclawapp.app.AppThemeMode
import cn.xiaobai.openclawapp.data.ServerConfig import cn.xiaobai.openclawapp.data.ServerConfig
import cn.xiaobai.openclawapp.ui.HeroCard import cn.xiaobai.openclawapp.data.ServerStatus
import cn.xiaobai.openclawapp.ui.LabelValueCard import cn.xiaobai.openclawapp.ui.LabelValueCard
import cn.xiaobai.openclawapp.ui.SectionHeader
import cn.xiaobai.openclawapp.ui.SelectableRowCard import cn.xiaobai.openclawapp.ui.SelectableRowCard
import cn.xiaobai.openclawapp.ui.StatusPill
import cn.xiaobai.openclawapp.ui.StatusPillTone
@Composable @Composable
fun SettingsScreen( fun SettingsScreen(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
serverConfig: ServerConfig, serverConfig: ServerConfig,
currentModel: String, status: ServerStatus,
availableAgents: List<String>, availableAgents: List<String>,
currentTheme: AppThemeMode, currentTheme: AppThemeMode,
isRefreshing: Boolean,
onSelectAgent: (String) -> Unit, onSelectAgent: (String) -> Unit,
onSelectTheme: (AppThemeMode) -> Unit, onSelectTheme: (AppThemeMode) -> Unit,
onRefreshOverview: () -> Unit,
onDisconnect: () -> Unit, onDisconnect: () -> Unit,
) { ) {
LazyColumn( LazyColumn(
@@ -34,25 +39,55 @@ fun SettingsScreen(
verticalArrangement = Arrangement.spacedBy(14.dp), verticalArrangement = Arrangement.spacedBy(14.dp),
) { ) {
item { item {
HeroCard( SectionHeader(
title = "连接配置", title = "设置",
subtitle = "现在 app 默认只走真实 BFF。这里主要管理地址、token 状态、默认 Agent 和主题。", subtitle = "这里管理连接、默认 Agent、外观和基础诊断信息。",
badge = "Settings",
) )
} }
item { item {
LabelValueCard(label = "服务器地址", value = serverConfig.baseUrl) Text("连接与账号", style = MaterialTheme.typography.titleMedium)
} }
item { item {
LabelValueCard(label = "当前模型", value = currentModel) LabelValueCard(
label = "服务器地址",
value = serverConfig.baseUrl,
supporting = "当前 app 通过 BFF 连接 OpenClaw。",
)
} }
item { item {
LabelValueCard(label = "访问令牌", value = if (serverConfig.token.isBlank()) "未设置" else "已持久化") LabelValueCard(
label = "访问令牌",
value = if (serverConfig.token.isBlank()) "未设置" else "已登录",
supporting = if (serverConfig.token.isBlank()) "可返回登录页重新配置。" else "如需切换账号或服务器,可退出登录后重新连接。",
)
} }
item { item {
Text("主题", style = MaterialTheme.typography.titleMedium) Text("默认 Agent", style = MaterialTheme.typography.titleMedium)
}
if (availableAgents.isEmpty()) {
item {
LabelValueCard(
label = "当前状态",
value = "暂未拉到可用 Agent",
supporting = "稍后刷新状态页,或检查当前连接是否正常。",
)
}
} else {
items(availableAgents) { agent ->
SelectableRowCard(
title = agent,
trailing = if (serverConfig.defaultAgent == agent) "当前" else null,
selected = serverConfig.defaultAgent == agent,
modifier = Modifier.clickable { onSelectAgent(agent) },
)
}
}
item {
Text("外观", style = MaterialTheme.typography.titleMedium)
} }
items(AppThemeMode.entries) { theme -> items(AppThemeMode.entries) { theme ->
@@ -65,21 +100,55 @@ fun SettingsScreen(
} }
item { item {
Text("切换默认 Agent", style = MaterialTheme.typography.titleMedium) Text("诊断信息", style = MaterialTheme.typography.titleMedium)
} }
item {
items(availableAgents) { agent -> LabelValueCard(
SelectableRowCard( label = "连接状态",
title = agent, value = if (status.online) "在线" else "离线",
trailing = if (serverConfig.defaultAgent == agent) "当前" else null, supporting = "这里汇总原状态页的核心诊断信息。",
selected = serverConfig.defaultAgent == agent, )
modifier = Modifier.clickable { onSelectAgent(agent) }, }
item {
LabelValueCard(
label = "当前模型",
value = status.currentModel,
)
}
item {
LabelValueCard(
label = "默认 Agent",
value = status.defaultAgent,
)
}
item {
LabelValueCard(
label = "OpenClaw 版本",
value = status.openClawVersion,
)
}
item {
LabelValueCard(
label = "最后更新时间",
value = status.updatedAt,
)
}
item {
StatusPill(
text = if (status.online) "已连接" else "连接异常",
tone = if (status.online) StatusPillTone.Success else StatusPillTone.Warning,
) )
} }
item {
Button(onClick = onRefreshOverview, modifier = Modifier.fillMaxWidth(), enabled = !isRefreshing) {
Text(if (isRefreshing) "同步中…" else "立即同步")
}
}
item { item {
Button(onClick = onDisconnect, modifier = Modifier.fillMaxWidth()) { Button(onClick = onDisconnect, modifier = Modifier.fillMaxWidth()) {
Text("退出登录") Text("退出登录并重新连接")
} }
} }
} }
@@ -10,7 +10,6 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import cn.xiaobai.openclawapp.data.ServerStatus import cn.xiaobai.openclawapp.data.ServerStatus
import cn.xiaobai.openclawapp.ui.HeroCard
import cn.xiaobai.openclawapp.ui.LabelValueCard import cn.xiaobai.openclawapp.ui.LabelValueCard
import cn.xiaobai.openclawapp.ui.MetricCard import cn.xiaobai.openclawapp.ui.MetricCard
@@ -24,10 +23,9 @@ fun StatusScreen(
verticalArrangement = Arrangement.spacedBy(14.dp), verticalArrangement = Arrangement.spacedBy(14.dp),
) { ) {
item { item {
HeroCard( Text(
title = if (status.online) "链路正常" else "连接异常", text = if (status.online) "链路正常" else "连接异常",
subtitle = "状态页后面会扩展成 OpenClaw、BFF、消息流和推送链路的统一面板。现在先把最关键的几个信号放清楚。", style = MaterialTheme.typography.headlineMedium,
badge = if (status.online) "Online" else "Offline",
) )
} }
@@ -3,11 +3,17 @@ package cn.xiaobai.openclawapp.network
import io.ktor.client.HttpClient import io.ktor.client.HttpClient
import io.ktor.client.call.body import io.ktor.client.call.body
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.ClientRequestException
import io.ktor.client.request.get import io.ktor.client.request.get
import io.ktor.client.request.header import io.ktor.client.request.header
import io.ktor.client.request.post import io.ktor.client.request.post
import io.ktor.client.request.forms.MultiPartFormDataContent
import io.ktor.client.request.forms.formData
import io.ktor.client.request.put
import io.ktor.client.request.setBody import io.ktor.client.request.setBody
import io.ktor.http.ContentDisposition
import io.ktor.http.ContentType import io.ktor.http.ContentType
import io.ktor.http.Headers
import io.ktor.http.HttpHeaders import io.ktor.http.HttpHeaders
import io.ktor.http.contentType import io.ktor.http.contentType
import io.ktor.http.encodeURLPathPart import io.ktor.http.encodeURLPathPart
@@ -45,6 +51,13 @@ class MobileGatewayApi(
}.body() }.body()
} }
suspend fun getSessionBootstrap(sessionId: String): SessionBootstrapResponseDto {
val encodedId = sessionId.encodeURLPathPart()
return client.get("${baseUrl.trimEnd('/')}/api/sessions/$encodedId/bootstrap") {
authHeader()
}.body()
}
suspend fun sendMessage(sessionId: String, message: String): SendMessageResponseDto { suspend fun sendMessage(sessionId: String, message: String): SendMessageResponseDto {
val encodedId = sessionId.encodeURLPathPart() val encodedId = sessionId.encodeURLPathPart()
return client.post("${baseUrl.trimEnd('/')}/api/sessions/$encodedId/messages") { return client.post("${baseUrl.trimEnd('/')}/api/sessions/$encodedId/messages") {
@@ -60,6 +73,57 @@ class MobileGatewayApi(
}.body() }.body()
} }
suspend fun updateDefaultAgent(agentId: String): UpdateDefaultAgentResponseDto {
return client.put("${baseUrl.trimEnd('/')}/api/settings/default-agent") {
authHeader()
contentType(ContentType.Application.Json)
setBody(UpdateDefaultAgentRequestDto(agentId = agentId))
}.body()
}
suspend fun uploadAttachment(
sessionId: String,
fileName: String,
bytes: ByteArray,
contentType: ContentType = ContentType.Application.OctetStream,
): UploadAttachmentResponseDto {
val encodedId = sessionId.encodeURLPathPart()
return client.post("${baseUrl.trimEnd('/')}/api/sessions/$encodedId/attachments") {
authHeader()
setBody(
MultiPartFormDataContent(
formData {
append(
key = "file",
value = bytes,
headers = Headers.build {
append(HttpHeaders.ContentType, contentType.toString())
append(HttpHeaders.ContentDisposition, ContentDisposition.File.withParameter(ContentDisposition.Parameters.FileName, fileName).toString())
},
)
},
),
)
}.body()
}
suspend fun readAttachment(sessionId: String, attachmentId: String): AttachmentReadResponseDto {
val encodedId = sessionId.encodeURLPathPart()
val encodedAttachmentId = attachmentId.encodeURLPathPart()
return try {
client.get("${baseUrl.trimEnd('/')}/api/sessions/$encodedId/attachments/$encodedAttachmentId") {
authHeader()
}.body()
} catch (e: ClientRequestException) {
val message = when (e.response.status.value) {
403 -> "该附件不属于当前会话"
404 -> "附件不存在或已过期"
else -> "读取附件失败(HTTP ${e.response.status.value})"
}
throw IllegalStateException(message, e)
}
}
private fun io.ktor.client.request.HttpRequestBuilder.authHeader() { private fun io.ktor.client.request.HttpRequestBuilder.authHeader() {
val token = tokenProvider().trim() val token = tokenProvider().trim()
if (token.isNotBlank()) { if (token.isNotBlank()) {
@@ -1,6 +1,7 @@
package cn.xiaobai.openclawapp.network package cn.xiaobai.openclawapp.network
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonNames
@Serializable @Serializable
data class LoginRequestDto( data class LoginRequestDto(
@@ -37,6 +38,11 @@ data class ChatMessageDto(
val text: String, val text: String,
val createdAt: String, val createdAt: String,
val status: String? = null, val status: String? = null,
val kind: String? = null,
val toolName: String? = null,
val toolCallId: String? = null,
val contentType: String? = null,
val sizeBytes: Int? = null,
) )
@Serializable @Serializable
@@ -55,3 +61,66 @@ data class AgentDto(
val id: String, val id: String,
val name: String, val name: String,
) )
@Serializable
data class UpdateDefaultAgentRequestDto(
val agentId: String,
)
@Serializable
data class UpdateDefaultAgentResponseDto(
val accepted: Boolean,
val defaultAgent: String,
val updatedAt: String,
)
@Serializable
data class SessionBootstrapResponseDto(
val sessionId: String,
val messages: List<ChatMessageDto> = emptyList(),
val operations: List<SessionBootstrapOperationDto> = emptyList(),
val streamState: String = "idle",
val serverTs: Long = 0,
)
@Serializable
data class SessionBootstrapOperationDto(
val opId: String,
val sessionId: String,
val type: String,
val state: String,
val createdAtMs: Long,
val clientRequestId: String,
val payloadSummary: String,
val attemptCount: Int = 0,
val lastError: String? = null,
val correlationToken: String? = null,
val materializedMessageIds: List<String> = emptyList(),
)
@Serializable
data class UploadAttachmentResponseDto(
@JsonNames("accepted", "accept")
val accepted: Boolean,
@JsonNames("sessionId", "session_id")
val sessionId: String,
@JsonNames("attachmentId", "attachment_id")
val attachmentId: String,
@JsonNames("fileName", "filename", "file_name")
val fileName: String,
@JsonNames("contentType", "content_type")
val contentType: String? = null,
@JsonNames("sizeBytes", "sizebytes", "size_bytes")
val sizeBytes: Int,
@JsonNames("queuedAt", "queued_at")
val queuedAt: String,
)
@Serializable
data class AttachmentReadResponseDto(
val attachmentId: String,
val fileName: String,
val contentType: String? = null,
val sizeBytes: Int,
val base64Data: String,
)
@@ -7,6 +7,18 @@ data class SessionSnapshotEventDto(
val messages: List<ChatMessageDto> = emptyList(), 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,
val toolCallId: String? = null,
)
@Serializable @Serializable
data class MessageDeltaEventDto( data class MessageDeltaEventDto(
val id: String, val id: String,
@@ -15,4 +27,23 @@ data class MessageDeltaEventDto(
val role: String, val role: String,
val createdAt: String, val createdAt: String,
val status: String? = null, val status: String? = null,
val kind: String? = null,
val toolName: String? = null,
val toolCallId: String? = null,
)
@Serializable
data class MessageRemovedEventDto(
val id: String,
)
@Serializable
data class MessageReorderedEventDto(
val ids: List<String> = emptyList(),
)
@Serializable
data class RunFailedEventDto(
val message: String,
val recoverable: Boolean = true,
) )
@@ -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
@@ -13,8 +14,12 @@ import kotlinx.serialization.json.Json
sealed interface SessionStreamEvent { sealed interface SessionStreamEvent {
data class Snapshot(val payload: SessionSnapshotEventDto) : SessionStreamEvent data class Snapshot(val payload: SessionSnapshotEventDto) : SessionStreamEvent
data class Started(val payload: MessageStartedEventDto) : SessionStreamEvent
data class Delta(val payload: MessageDeltaEventDto) : SessionStreamEvent data class Delta(val payload: MessageDeltaEventDto) : SessionStreamEvent
data class Completed(val payload: ChatMessageDto) : SessionStreamEvent data class Completed(val payload: ChatMessageDto) : SessionStreamEvent
data class Removed(val payload: MessageRemovedEventDto) : SessionStreamEvent
data class Reordered(val payload: MessageReorderedEventDto) : SessionStreamEvent
data class Failed(val payload: RunFailedEventDto) : SessionStreamEvent
} }
class SseSessionStream( class SseSessionStream(
@@ -25,7 +30,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()) {
@@ -33,7 +38,12 @@ class SseSessionStream(
} }
}.execute { response -> }.execute { response ->
if (!response.status.isSuccess()) { 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() val channel = response.bodyAsChannel()
@@ -50,15 +60,33 @@ class SseSessionStream(
when (currentEvent) { when (currentEvent) {
"session.snapshot" -> runCatching { "session.snapshot" -> runCatching {
json.decodeFromString<SessionSnapshotEventDto>(raw) 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 { "message.delta" -> runCatching {
json.decodeFromString<MessageDeltaEventDto>(raw) json.decodeFromString<MessageDeltaEventDto>(raw)
}.onSuccess { dto -> emit(SessionStreamEvent.Delta(dto)) } }.onSuccess { emit(SessionStreamEvent.Delta(it)) }
"message.completed" -> runCatching { "message.completed" -> runCatching {
json.decodeFromString<ChatMessageDto>(raw) json.decodeFromString<ChatMessageDto>(raw)
}.onSuccess { dto -> emit(SessionStreamEvent.Completed(dto)) } }.onSuccess { emit(SessionStreamEvent.Completed(it)) }
"message.removed" -> runCatching {
json.decodeFromString<MessageRemovedEventDto>(raw)
}.onSuccess { emit(SessionStreamEvent.Removed(it)) }
"message.reordered" -> runCatching {
json.decodeFromString<MessageReorderedEventDto>(raw)
}.onSuccess { emit(SessionStreamEvent.Reordered(it)) }
"run.failed" -> runCatching {
json.decodeFromString<RunFailedEventDto>(raw)
}.onSuccess { emit(SessionStreamEvent.Failed(it)) }
"keepalive", null, "" -> Unit
} }
currentEvent = null currentEvent = null
dataLines.clear() dataLines.clear()
@@ -67,6 +95,4 @@ class SseSessionStream(
} }
} }
} }
private fun encodePath(value: String): String = value.replace(":", "%3A")
} }
@@ -0,0 +1,9 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
import cn.xiaobai.openclawapp.data.AttachmentOpenPayload
@Composable
expect fun rememberAttachmentOpener(
onResult: (String) -> Unit = {},
): (AttachmentOpenPayload) -> Unit
@@ -0,0 +1,15 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
data class PickedAttachment(
val fileName: String,
val bytes: ByteArray,
val contentType: String? = null,
)
@Composable
expect fun rememberAttachmentPicker(
onPicked: (PickedAttachment) -> Unit,
onError: (String) -> Unit,
): () -> Unit
@@ -0,0 +1,9 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
import cn.xiaobai.openclawapp.data.AttachmentOpenPayload
@Composable
expect fun rememberAttachmentSaver(
onResult: (String) -> Unit = {},
): (AttachmentOpenPayload) -> Unit
@@ -0,0 +1,6 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
@Composable
expect fun PlatformBackHandler(enabled: Boolean = true, onBack: () -> Unit)
@@ -0,0 +1,8 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
@Composable
expect fun rememberClipboardSetter(
onResult: (String) -> Unit = {},
): (String) -> Unit
@@ -28,9 +28,9 @@ fun SectionHeader(
) { ) {
Column( Column(
modifier = modifier.fillMaxWidth(), modifier = modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(4.dp), verticalArrangement = Arrangement.spacedBy(2.dp),
) { ) {
Text(title, style = MaterialTheme.typography.headlineMedium) Text(title, style = MaterialTheme.typography.headlineSmall)
if (!subtitle.isNullOrBlank()) { if (!subtitle.isNullOrBlank()) {
Text( Text(
subtitle, subtitle,
@@ -62,7 +62,7 @@ fun HeroCard(
verticalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
) { ) {
if (!badge.isNullOrBlank()) { if (!badge.isNullOrBlank()) {
StatusPill(text = badge, highlighted = true) StatusPill(text = badge, tone = StatusPillTone.Info)
} }
Text( Text(
title, title,
@@ -146,21 +146,28 @@ fun MetricCard(
} }
} }
enum class StatusPillTone {
Neutral,
Info,
Success,
Warning,
Error,
}
@Composable @Composable
fun StatusPill( fun StatusPill(
text: String, text: String,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
highlighted: Boolean = false, highlighted: Boolean = false,
tone: StatusPillTone? = null,
) { ) {
val containerColor = if (highlighted) { val resolvedTone = tone ?: if (highlighted) StatusPillTone.Info else StatusPillTone.Neutral
MaterialTheme.colorScheme.primaryContainer val (containerColor, textColor) = when (resolvedTone) {
} else { StatusPillTone.Neutral -> MaterialTheme.colorScheme.surfaceVariant to MaterialTheme.colorScheme.onSurfaceVariant
MaterialTheme.colorScheme.surfaceVariant StatusPillTone.Info -> MaterialTheme.colorScheme.primaryContainer to MaterialTheme.colorScheme.onPrimaryContainer
} StatusPillTone.Success -> MaterialTheme.colorScheme.secondaryContainer to MaterialTheme.colorScheme.onSecondaryContainer
val textColor = if (highlighted) { StatusPillTone.Warning -> MaterialTheme.colorScheme.tertiaryContainer to MaterialTheme.colorScheme.onTertiaryContainer
MaterialTheme.colorScheme.onPrimaryContainer StatusPillTone.Error -> MaterialTheme.colorScheme.errorContainer to MaterialTheme.colorScheme.onErrorContainer
} else {
MaterialTheme.colorScheme.onSurfaceVariant
} }
Box( Box(
@@ -209,7 +216,10 @@ fun SelectableRowCard(
modifier = Modifier.weight(1f), modifier = Modifier.weight(1f),
) )
if (!trailing.isNullOrBlank()) { if (!trailing.isNullOrBlank()) {
StatusPill(text = trailing, highlighted = selected) StatusPill(
text = trailing,
tone = if (selected) StatusPillTone.Info else StatusPillTone.Neutral,
)
} }
} }
} }
@@ -0,0 +1,12 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import cn.xiaobai.openclawapp.data.AttachmentOpenPayload
@Composable
actual fun rememberAttachmentOpener(
onResult: (String) -> Unit,
): (AttachmentOpenPayload) -> Unit = remember(onResult) {
{ payload -> onResult("iOS 附件打开还没接好:${payload.fileName}") }
}
@@ -0,0 +1,12 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
@Composable
actual fun rememberAttachmentPicker(
onPicked: (PickedAttachment) -> Unit,
onError: (String) -> Unit,
): () -> Unit = remember(onPicked, onError) {
{ onError("iOS 文件选择器还没接好") }
}
@@ -0,0 +1,12 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import cn.xiaobai.openclawapp.data.AttachmentOpenPayload
@Composable
actual fun rememberAttachmentSaver(
onResult: (String) -> Unit,
): (AttachmentOpenPayload) -> Unit = remember(onResult) {
{ payload -> onResult("iOS 附件下载还没接好:${payload.fileName}") }
}
@@ -0,0 +1,6 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
@Composable
actual fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit) = Unit
@@ -0,0 +1,11 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
@Composable
actual fun rememberClipboardSetter(
onResult: (String) -> Unit,
): (String) -> Unit = remember(onResult) {
{ text -> onResult("iOS 剪贴板还没接好:$text") }
}
@@ -0,0 +1,12 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import cn.xiaobai.openclawapp.data.AttachmentOpenPayload
@Composable
actual fun rememberAttachmentOpener(
onResult: (String) -> Unit,
): (AttachmentOpenPayload) -> Unit = remember(onResult) {
{ payload -> onResult("Web 附件打开还没接好:${payload.fileName}") }
}
@@ -0,0 +1,12 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
@Composable
actual fun rememberAttachmentPicker(
onPicked: (PickedAttachment) -> Unit,
onError: (String) -> Unit,
): () -> Unit = remember(onPicked, onError) {
{ onError("Web 文件选择器还没接好") }
}
@@ -0,0 +1,12 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import cn.xiaobai.openclawapp.data.AttachmentOpenPayload
@Composable
actual fun rememberAttachmentSaver(
onResult: (String) -> Unit,
): (AttachmentOpenPayload) -> Unit = remember(onResult) {
{ payload -> onResult("Web 附件下载还没接好:${payload.fileName}") }
}
@@ -0,0 +1,6 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
@Composable
actual fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit) = Unit
@@ -0,0 +1,11 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
@Composable
actual fun rememberClipboardSetter(
onResult: (String) -> Unit,
): (String) -> Unit = remember(onResult) {
{ text -> onResult("Web 剪贴板还没接好:$text") }
}
@@ -0,0 +1,12 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import cn.xiaobai.openclawapp.data.AttachmentOpenPayload
@Composable
actual fun rememberAttachmentOpener(
onResult: (String) -> Unit,
): (AttachmentOpenPayload) -> Unit = remember(onResult) {
{ payload -> onResult("Wasm 附件打开还没接好:${payload.fileName}") }
}
@@ -0,0 +1,12 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
@Composable
actual fun rememberAttachmentPicker(
onPicked: (PickedAttachment) -> Unit,
onError: (String) -> Unit,
): () -> Unit = remember(onPicked, onError) {
{ onError("Wasm 文件选择器还没接好") }
}
@@ -0,0 +1,12 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import cn.xiaobai.openclawapp.data.AttachmentOpenPayload
@Composable
actual fun rememberAttachmentSaver(
onResult: (String) -> Unit,
): (AttachmentOpenPayload) -> Unit = remember(onResult) {
{ payload -> onResult("Wasm 附件下载还没接好:${payload.fileName}") }
}
@@ -0,0 +1,6 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
@Composable
actual fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit) = Unit
@@ -0,0 +1,11 @@
package cn.xiaobai.openclawapp.platform
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
@Composable
actual fun rememberClipboardSetter(
onResult: (String) -> Unit,
): (String) -> Unit = remember(onResult) {
{ text -> onResult("Wasm 剪贴板还没接好:$text") }
}
+466
View File
@@ -0,0 +1,466 @@
# OpenClaw Mobile MVP 进度文档
_更新时间:2026-03-07_
这份文档不是架构设想,而是**当前真实开发进度**。
目标:回答 3 个问题:
1. 现在做到哪了
2. 还有多少没做
3. 接下来应该按什么顺序做
---
## 1. 当前项目结构
```text
openclawapp # 移动端 App(KMP / Compose)
openclawapp-bff # 面向移动端的 BFF / Mobile Gateway
```
当前链路:
```text
Android/iOS App
-> openclawapp-bff
-> local OpenClaw bridge / gateway / CLI
```
---
## 2. 当前已完成(Done)
### 2.1 连接与登录
- [x] App 可配置 BFF 地址
- [x] App 支持通过密码登录 BFF,换取 token
- [x] App 本地持久化:
- token
- 服务端配置
- 默认 agent
- 主题配置
### 2.2 会话基础能力
- [x] 通过 BFF 拉取真实 sessions 列表
- [x] 本地缓存最近一次 overview(status + sessions + agents)用于冷启动兜底
- [x] 本地缓存最近打开会话的消息列表用于聊天页冷启动兜底
- [x] 本地缓存最近打开会话的消息列表用于聊天页冷启动兜底
- [x] 通过 BFF 拉取真实 chat history
- [x] 会话列表支持:
- 搜索
- 最近访问
- 置顶
- 基础摘要显示
- [x] 列表摘要已支持特殊消息前缀:
- `[附件]`
- `[工具]`
- `[工具结果]`
- `[工具错误]`
- `[思考中]`
- `[系统]`
- `[断流]`
### 2.3 聊天与流式消息
- [x] 文本消息发送
- [x] 文本消息失败重试
- [x] BFF SSE 流式推送基础链路
- [x] App 支持 SSE 事件:
- `session.snapshot`
- `message.started`
- `message.delta`
- `message.completed`
- `run.failed`
- [x] 聊天页可展示:
- 普通文本
- thinking
- tool 调用
- tool result
- tool error
- stream failure
- [x] 聊天页顶部可显示流状态:
- 连接中
- 在线
- 重连中
- 已断流
- [x] 会话列表也能看到每个 session 的流状态
### 2.4 默认 Agent 设置
- [x] 设置页可切默认 agent
- [x] 不再只是本地改显示
- [x] 已打通链路:
- App -> BFF -> OpenClaw config
- [x] BFF 已增加 agent id 校验
### 2.5 Tool / Result 展示
- [x] BFF 将 history 拆成结构化消息,而不是只压平成纯文本
- [x] toolCall 和 toolResult 已通过 `toolCallId` 关联
- [x] App 聊天页已支持:
- 工具调用卡片
- 工具结果卡片
- 工具错误卡片
- [x] 长 tool result 支持折叠 / 展开
- [x] 结构化输出(JSON / 多行日志)已有更适合阅读的展示
### 2.6 附件链路(第一版)
- [x] BFF 已有附件上传 API skeleton:
- `POST /api/sessions/{session_id}/attachments`
- [x] App 已有附件上传 API 调用
- [x] Android 已接真实文件选择器
- [x] 点击“发附件”会打开系统文件选择
- [x] 上传后会在聊天时间线中显示附件消息
- [x] 附件消息支持状态:
- 上传中
- 已上传
- 上传失败
- [x] 附件消息支持元信息展示:
- 文件名
- contentType
- sizeBytes
- [x] 上传失败支持重试
- [x] 聊天页支持手动刷新 / 重新连接入口
- [x] BFF 已将附件 overlay 合并进:
- history 返回
- SSE 流
- 最近消息摘要
- [x] BFF 已补附件 overlay 的稳定排序:不再简单 append 到时间线末尾,而是按时间顺序参与 history/SSE 合并
- [x] BFF 附件 overlay 清理时,会同步移除过期附件对应的时间线占位,避免聊天里仍显示一个必然 404 的附件
- [x] BFF 已补附件 overlay 与远端原生附件消息的前向兼容归并:若远端开始返回原生附件消息,可按附件特征归并,避免双份展示,并把本地附件读取能力迁移挂到远端 message id 上
---
## 3. 当前部分完成(Partial)
这些已经不是 0%,但还没到真正完成。
### 3.1 SSE 链路
现状:
- App / BFF / UI 都已经跑起来
- 但 BFF 目前仍然是**基于 history 轮询 + diff** 来产生 SSE 事件
这意味着:
- 能用
- 但还不是最理想的“原生事件流”
结论:**可用,但后面还要继续稳固。**
补充:BFF 已开始补 diff 细节稳定性。当前已修一类典型误判——当同一条消息在一次轮询里既发生文本增长、又发生状态/类型元数据变化时,BFF 现在会同时补发 `message.completed`,避免前端只收到 delta 后停留在半完成状态。并且,BFF 也开始收敛“新消息一次性出现”的事件噪音:不再对所有新消息都连发 `started + completed`,而是仅对明显仍在进行中的消息发 `started`,其余直接发 `completed`。另外,消息消失时已不再默认整包 `session.snapshot` 重刷,而是优先发精确的 `message.removed` 事件,由 App 按 id 删除对应消息;同时 App 的 session 列表摘要也会随精确删除同步回退,不再顽固保留已被删掉的最后一条消息摘要。并且,App 现在会在本地 queued / thinking 占位写入和 SSE `message.started` 首帧到达时,同步刷新 session 列表摘要,减少“聊天页已变但列表还停在旧内容”的延迟。session 列表排序也开始从“直接比较显示字符串”过渡到独立维护的时间 sort key,降低 `现在` / `刚刚` / 格式化时间混排时的排序抖动。并且,这个 sort key 现在也会跟 overview snapshot 一起持久化,减少冷启动缓存态与热态排序不一致带来的首帧跳动。SSE 这边也继续补了一层顺序一致性:对于“消息集合没变、只是顺序变了”的场景,BFF / App 现在改用更细的 `message.reordered` 事件来纠正时间线顺序,而不是整包 `session.snapshot`。另外,在消息逐条被 `message.removed` 删空的场景下,BFF 也不再额外补一个重复的空 snapshot,避免无意义重刷。App 侧的 session 摘要选择逻辑也继续统一:更多更新路径已改为优先走 `previewMessage()`,尽量忽略本地 thinking 占位,降低摘要跳到空白/占位状态的概率。
### 3.2 附件能力
现状:
- Android 侧已经能真选文件、真上传、真显示
- 但 BFF 现在只是先把附件并进自己的 overlay
- 还**没有真正写进 OpenClaw 原生消息体系**
结论:**移动端体验已可用,后端归档仍是过渡方案。**
补充:虽然附件仍是 overlay 方案,但 BFF 现在至少已经把 overlay 的排序问题收了一步,不会再因为简单 append 导致附件和文本的时间线顺序错乱;同时,过期/被淘汰的附件也会从 overlay 时间线里同步摘除,不再出现“列表里看得到、点开必 404”的假附件。并且,BFF 已提前铺好一层前向兼容归并逻辑:若后续 OpenClaw history 返回原生附件消息,BFF 会优先尝试把 overlay 附件与远端附件归并,减少未来迁移时的双份展示风险。除此之外,BFF 的 session 列表摘要现在也开始按消息类型生成预览文案(如 `[附件]` / `[工具]` / `[工具结果]`),不再只是裸文本,和聊天页的预览语义更一致。进一步地,被远端原生附件消息“收编”后的本地附件 payload 现在会以读取 alias 形式持久化,而不会在重启后重新作为 overlay 假消息塞回时间线;BFF 侧也开始显式维护旧 attachment id 到新远端 message id 的 alias 映射,让 read_attachment 的查找语义更明确。现在 source stub 被收编后,还会留下轻量 redirect 元数据,因此重启后旧 id 也仍可解析到新远端 id,不再只靠内存里的 alias 表。同时,目标 payload 一旦过期/被淘汰,指向它的 redirect meta 也会同步清掉,避免留下永远只会 404 的旧 alias 入口。
### 3.3 多平台文件选择器
现状:
- Android:已完成
- iOS / JS / wasm:只有降级占位
结论:**Android 先可用,其它平台未完成。**
---
## 4. 当前未完成(Todo)
下面这些是明确还没做,或者只做了很薄的一层。
### 4.1 消息重试统一机制
目前:
- [x] 附件上传失败可重试
- [x] 普通文本消息失败可重试
- [x] 最近 3 个会话的本地消息缓存会在发送/重试后及时刷新落盘
- [x] App 重启后,缓存里的 `queued` 文本会恢复成可重试的 `send-failed`
- [x] App 重启后,缓存里的 `uploading` 附件会恢复成明确失败态,避免假性卡死
- [x] 手动刷新/重新进入会话时,会保留本地尚未被远端确认的失败消息,避免刷新后直接消失
- [x] 从缓存恢复出来的 `queued` 文本,在重新进入会话时会自动尝试补发一次
- [x] 聊天页已显式区分“自动重试中”和普通手动发送中状态
- [x] 已有第一版本地文本发送队列雏形:待发送文本会独立持久化,App 重启后可恢复并继续进入自动补发/手动重试链路
- [x] 已收紧文本队列自动补发语义:仅“从缓存恢复出的旧 queued 文本”保留一次自动补发资格;queue drain / 手动重试失败后会回到手动可重试,不再在同一次进入会话时被连打两次
- [x] 聊天页已新增轻量 pending queue 状态提示:可看到当前会话剩余待发条数,以及系统是否正在按本地队列继续发送
- [x] 已有保守版 queue drain:`openSession()` 会尝试继续发送当前会话的待发文本,`syncRemoteIfNeeded()` 会顺序尝试全局待发文本,失败即停
- [x] 聊天页已显式区分 queue drain 状态:队列自动处理中的文本会显示“队列发送中”
- [x] pending queue 已开始同时覆盖文本与附件:附件待上传项也会独立持久化,并在重新进入会话或手动同步时继续尝试上传
- [x] 附件上传状态已开始对齐队列语义:队列自动处理中的附件会显示“队列上传中”,与手动上传中的“上传中”分开
- [x] 已修复 `RemoteOpenClawRepository` 的 JVM 重载撞签名:原先两个 `rebuildSessionSortKeys(List<...>)` 因泛型擦除冲突,现已拆成 `rebuildSessionSortKeysFromSnapshot(...)` / `rebuildSessionSortKeysFromSessions(...)`
- [x] 已补本地 pending 保留逻辑:refresh / SSE snapshot 不再只保留 `queued` 文本;`queue-draining` / `retrying-auto` / 本地附件 pending 也会保留,避免队列处理中消息被快照冲掉
- [x] 已抽出本地 pending 派生状态:新增 `LocalMessagePhase` 与 `localMessagePhase()` / `isLocalPendingActive()`,开始统一 UI 与本地保留逻辑对 pending 状态的判断,减少散落的字符串分支
- [x] 缓存恢复逻辑也已开始接入派生状态:本地文本若在 `queue-draining` / `retrying-auto` 时被杀掉,重启后会统一恢复为可手动重试的 `send-failed`;附件同理会统一回落为 `upload-failed`
- [x] Repository 的核心写状态入口已开始复用派生状态映射:新增 `textStatusForLocalPhase()` / `attachmentStatusForLocalPhase()`,用于统一写入手动处理中、队列处理中、失败态、完成态,减少散落的状态字符串
- [x] 又收了一轮边角判断:文本入队去重、auto-retry 候选过滤、本地 retainable/failure 判定开始复用派生状态辅助函数,继续减少裸 `status == ...` 分支
- [ ] 还没有完整的离线发送队列(当前已覆盖文本 + 附件,但还没有更完整的网络感知、后台 drain 与统一淘汰策略)
- [x] 已补第一版“网络恢复后继续处理待发队列”:当会话 SSE 从 recoverable failed / reconnecting 回到 live 时,会顺手尝试 auto-retry + drain 当前会话的文本/附件 pending
- [x] 已给 session 级自动恢复补简易防重入/短节流:`openSession()` 和 SSE recovery 现在共用 `recoverPendingQueueForSession(...)`,避免短时间内对同一会话重复触发 queue recovery
- [x] 已补 queue recovery 轻量可观测性:pending queue 状态里会暴露“正在恢复中 / 刚因节流跳过”,聊天页和反馈文案能区分“真在跑”和“刚跑过所以先跳过”
- [x] 已区分“SSE 传输层重连”和“BFF 上游轮询恢复中”:`run.failed(recoverable=true)` 不再一律显示成“SSE 连接中断”,而是显示为上游恢复中,减少会话详情页的假断流提示
- [x] 已开始收紧本地 pending 与远端消息的匹配条件:文本 pending 不再只看裸文本;附件 pending 除文件名外还会参考 `contentType/sizeBytes`,降低同文案/同文件名重发时的误合并风险
- [x] 已给附件 pending 增加本地匹配指纹:基于 `fileName/contentType/sizeBytes/bytes 前缀 hash` 生成轻量 fingerprint,并随 pending queue / message cache 持久化,进一步降低同名附件重传时的误匹配概率
- [x] 已给文本 pending 增加本地 client token:本地发送/失败回落/缓存恢复/队列持久化都会带上 token,文本 pending 与远端消息归并时优先参考 token,降低“同文案连续发送”时的误匹配概率
- [ ] 还没有更完整的网络恢复策略(目前先基于会话 SSE 恢复触发,不含更底层网络监听或全局后台队列调度)
### 4.2 附件后端主链路
目前:
- 附件消息进入了 BFF overlay
- 但还没有真正桥接进 OpenClaw 原生历史 / 原生附件能力
- [x] BFF 启动期已补一轮 redirect 自愈:`_load_attachment_index()` 恢复 redirect-only meta 时会检查目标 payload 是否仍存在;若目标已丢失,会直接清理历史 redirect 空壳,避免保留“结构可解析、读取必 404”的假入口
### 4.3 附件交互动作
目前:
- [x] 复制文件名(Android 真剪贴板)
- [x] 查看附件详情
- [x] 点击附件打开(Android,优先本地缓存;无缓存时经 BFF 回源读取)
- [x] BFF 附件 overlay 落盘,重启后仍可读取最近附件
- [x] 下载附件(Android,系统另存为)
- [x] 附件过期/越权读取在前端已有明确提示文案
- [ ] iOS / Web 剪贴板
- [ ] iOS / Web 附件打开
### 4.4 iOS / Web 文件选择器
还未接。
### 4.5 更完整的任务/工具状态可视化
- [x] 已先做一轮减法 UI 收拾:会话列表去掉大 Hero/指标卡堆头,详情页顶部改成更轻的标题+状态+动作区,先把“信息一坨”拆开
虽然聊天页已经能看到 tool 状态,但还没有:
- 更完整的 tool timeline
- 更细的开始/结束/失败原因展示
- 任务级别的状态聚合
### 4.6 推送链路
当前还没有做:
- FCM / APNs token 注册
- 后台通知
- 会话级消息推送
### 4.7 发送队列 / 离线能力
当前还没有:
- 离线发送队列
- 网络恢复后的自动补发
- 更完善的本地缓存策略
- BFF attachment overlay 目前只有轻量 TTL / 数量清理,还没有更高级的淘汰策略
---
## 5. 当前真实状态判断
如果按 MVP 完成度粗估:
### App 侧
- **基础可用度:75% 左右**
- 已经不是 demo UI 了
- 已有真实会话 / 真消息 / 真流 / 真附件上传入口
### BFF 侧
- **基础可用度:70% 左右**
- 已具备移动端所需核心接口
- 但附件和 SSE 仍有“过渡实现”成分
### 整体 MVP
- **整体约 70% 左右**
- 已经进入“补完整和补稳定性”阶段
- 不再是“从 0 到 1”阶段
---
## 6. 推荐后续顺序(按优先级)
这是我建议接下来继续开发的顺序。
### P1:把发送链路补完整
1. 普通文本消息失败重试
2. 附件消息动作(重试 / 打开 / 复制文件名)
3. 聊天页错误态进一步统一
### P2:把附件从“过渡实现”补到“主链路实现”
1. BFF 真正桥接 OpenClaw 附件能力(如果底层支持)
2. 附件真正进入原生 history
3. SSE 中回放附件时不再依赖 overlay 兜底
### P3:补移动端体验
1. 下拉刷新 / 手动重连
2. 更完整的 system/error 交互
3. 会话列表和聊天页更多状态统一
### P4:补平台能力
1. iOS 文件选择器
2. Web 文件选择器
3. 平台差异处理
### P5:推送与后台能力
1. Push token 注册
2. BFF 推送下发
3. 新消息通知
---
## 7. 一个最直白的结论
如果你问:
### “现在能不能用了?”
能用,尤其是 Android 真机上:
- 能登录
- 能看会话
- 能看消息
- 能发文本
- 能收流式回复
- 能看工具消息
- 能切默认 agent
- 能选文件上传
- 附件失败还能重试
### “是不是已经做完了?”
没做完。
当前更准确的状态是:
> **核心主链路已经打通,正在补完整性、稳定性和产品细节。**
---
## 8. 你现在最关心的一句版本
### 已做完的大头
- 真实会话
- 真实消息
- SSE 流
- tool/result 展示
- 默认 agent 切换
- Android 真附件选择与上传
- 附件失败重试
- 普通文本消息失败重试
### 还没做完的大头
- 普通消息失败重试
- 附件真正进入 OpenClaw 原生附件主链路
- iOS/Web 文件选择器
- 推送链路
---
## 9. 文档用途
以后如果你问:
- 做到哪了
- 还有多少没做
- 该先做什么
就先看这份文档。
后续我会继续更新它,而不是只靠聊天记录滚动。
另外,从 2026-03-07 这轮开发开始,约定为:
- **每推进一步实际代码改动,都同步更新这份文档**
- 让后续恢复上下文时,不必过度依赖聊天记录 compaction
- 文档里优先记录:
- 新完成了什么
- 真实状态有没有变化
- 下一步建议顺序有没有变化
### 9.1 本轮新增进展补记
- 2026-03-07:修复了 cached-data 相关编译错误:补回 `OpenClawAppState` 中缺失的 `isShowingCachedData` / `cacheSavedAt` 状态字段,并移除了 `MobileGatewayApi` 中未使用且不兼容的 `decodeBase64Bytes` import。
- 2026-03-07:补强发送失败状态缓存:发送/重试消息、上传/重试附件后会及时刷新最近消息缓存;App 重启后,缓存中的 `queued` 文本会转成可重试失败态,缓存中的 `uploading` 附件会转成明确失败态,避免 UI 长时间停留在假性发送中。
- 2026-03-07:补强消息刷新合并逻辑:手动刷新或重新进入会话时,若某条本地失败消息尚未被远端 history 确认,不会被 `refreshMessages()` 直接覆盖掉,而是继续保留在时间线里供用户重试。
- 2026-03-07:新增第一版自动恢复补发:仅针对“从缓存恢复出来、原本处于 `queued` 的文本消息”,在重新进入会话时自动尝试补发一次;若仍失败,则继续保留为可手动重试状态。
- 2026-03-07:聊天页补充自动恢复状态文案:自动补发中的文本消息会明确显示“自动重试中”,避免和普通发送中的状态混淆。
- 2026-03-07:BFF 补强附件 overlay 合并顺序:附件上传后写入 overlay 时记录精确时间戳;history / SSE / 最近摘要合并时改为统一按时间排序,避免附件消息总被硬追加到末尾导致时间线错乱。
- 2026-03-07:BFF 补强附件 overlay 清理一致性:TTL/数量清理删除附件文件时,会同步移除对应 overlay message 和排序索引,避免聊天时间线残留已失效附件。
- 2026-03-07:BFF 新增附件前向兼容归并准备层:开始识别 history 内容中的原生附件型 item(attachment/file/image/document);若其与 overlay 附件满足同名/同类型/同大小/时间接近等条件,则优先归并并把本地二进制读取能力迁移挂到远端 message id 上,降低未来切换到原生附件消息时的双份展示风险。
- 2026-03-07:BFF 补强 SSE diff 细节:当同一条消息在一次 poll 中既发生文本增量、又发生状态/类型/工具字段变化时,除了 `message.delta` 外还会补发 `message.completed`,避免前端停留在半完成状态。
- 2026-03-07:BFF 收敛 SSE 新消息噪音:对于“一次 poll 才第一次看到”的新消息,不再默认连发 `message.started + message.completed`;现在仅对明显仍在进行中的 thinking/tool-running 等消息发 `started`,其余直接发 `completed`,减少前端不必要的瞬时状态抖动。
- 2026-03-07:BFF/App 联动补 `message.removed`:当某条消息在新一轮 history 中消失时,BFF 优先发精确删除事件,App 按 id 从当前时间线里移除对应消息;只有极端场景(如整个会话消息清空)才再补空 snapshot。这样比“消息一消失就整包 snapshot”更细、更稳,也更像真实事件流。
- 2026-03-07:App 补 session 摘要一致性:当 SSE 精确删除命中最后一条消息时,会话列表摘要不再保留旧值,而是同步清空/回退到当前真实最后一条,避免“聊天删了但列表还显示旧摘要”。
- 2026-03-07:继续补 session 摘要一致性:本地发送插入 queued/thinking 占位,以及 SSE `message.started` 首帧到达时,会话列表摘要现在会立即同步刷新;同时摘要优先忽略 `local-thinking-*` 占位,尽量展示真实最后一条可读消息。
- 2026-03-07:开始补 session 列表排序稳定性:App 不再只按 `updatedAt` 显示字符串排序,而是额外维护独立的 session sort key;`现在` / `刚刚` 会映射为递增排序值,格式化时间则尽量解析成稳定数值,减少列表在本地 pending / SSE 更新下的错序与抖动。
- 2026-03-07:补齐 session sort key 持久化:overview snapshot 现在会把每个 session 的 sort key 一并保存并在 hydrate 时恢复,减少冷启动缓存态和热态之间的排序跳变。
- 2026-03-07:继续统一 session 摘要选择逻辑:更多 preview 更新路径改为复用 `previewMessage()`,避免在 retry / snapshot merge / SSE completed / stream failed 等场景下直接拿 `lastOrNull()` 导致摘要被 thinking 占位或瞬时系统消息抢走。
- 2026-03-07:开始补真正的本地发送队列雏形:新增独立的 `PendingSendQueue` 持久化结构,与 recent message cache 分离;文本待发送项现在会单独入队、在 hydrate 时恢复,并在发送成功/失败/重试后同步维护,减少“只有界面缓存、没有真实队列语义”的不一致。
- 2026-03-07:补上第一版 queue drain:App 现在会在 `openSession()` 时尝试继续发送当前会话的待发文本,在 `syncRemoteIfNeeded()` 时顺序尝试全局待发文本;一旦某条失败就停止,避免激进乱冲。
- 2026-03-07:补充 queue drain 的显式状态:被本地发送队列自动处理的文本消息现在会进入 `queue-draining` 状态,聊天页明确显示“队列发送中”,避免和手动发送/自动恢复重试混淆。
- 2026-03-07:继续补 SSE 顺序一致性:当消息集合未变、只是顺序发生变化时,BFF / App 现已改为通过 `message.reordered` 精确纠正顺序,避免因为 diff 只看 id/内容变化而静默漏掉重排,也避免为单纯重排走整包 snapshot。
- 2026-03-07:继续收缩 SSE 重刷范围:在消息通过 `message.removed` 逐条删空时,BFF 不再额外补发重复的空 `session.snapshot`,减少无意义整包刷新。
- 2026-03-07:补强 BFF 会话摘要语义:session 列表里的 lastMessage 预览现在会按消息类型生成前缀与截断文案(附件/工具/工具结果/思考中/系统/断流),不再只是返回裸 `text`,让附件 overlay、工具消息和聊天页预览语义更一致。
- 2026-03-07:补强附件 alias 生命周期:当 overlay 附件被远端原生附件消息归并收编后,BFF 会把本地二进制 payload 以“不可见 alias”形式持久化到目标远端 message id;重启后它仍可被读取,但不会再被重建成 overlay 假消息重新塞回时间线。
- 2026-03-07:继续收清附件读取语义:BFF 开始显式维护旧 attachment id 到新远端 message id 的 alias 映射,`read_attachment()` 会先走 alias 解析再读 payload,不再完全依赖“请求 id 恰好就是 payload 主键”。
- 2026-03-07:补齐附件 alias 持久化入口:source stub 被远端消息收编后,BFF 会保留一份轻量 redirect 元数据;重启后旧 attachment id 仍能恢复 alias 解析,而不会因为 alias 只存在内存里而失效。
- 2026-03-07:补齐 alias 清理一致性:当目标附件 payload 过期或被数量策略淘汰时,BFF 会同步清掉所有指向它的 redirect meta / alias 入口,避免旧 attachment id 虽还能解析但最终只会稳定 404。
- 2026-03-07:按产品/设计 review 收了一轮聊天与会话页 UI:聊天页顶部把返回/标题/状态/刷新/附件入口收成更轻的两层结构,并把缓存/队列/断流/同步等提示合并为一条统一状态栏;快捷动作只在空会话时展示,减少首屏被系统说明挤压。
- 2026-03-07:会话列表做了一轮信息减法:去掉重复摘要,默认不再在主列表暴露 session id,更新时间从高亮 pill 降为普通辅助文本;最近访问卡和置顶操作也改轻,优先突出“标题 + 摘要 + 关键状态”。
- 2026-03-07:开始统一状态视觉语义:`StatusPill` 新增 neutral/info/success/warning/error tone,列表流状态、聊天顶部状态、消息气泡状态都开始按“在线 / 处理中 / 失败 / 普通标签”区分,减少此前一套高亮样式混用时间、状态、标签造成的噪音。
- 2026-03-07:聊天页消息前台状态文案先收敛到用户视角:把 queue-draining / retrying-auto / uploading / send-failed 等内部细状态,前台统一归并到“处理中 / 需重试 / 已完成”这一层,细分恢复机制不再在时间线里处处抢注意力。
- 2026-03-07:继续收聊天时间线的“聊天产品感”:聊天页内部去掉重复会话标题,顶部动作区进一步压轻;消息气泡开始按“用户主色 / 助手中性 / 工具与附件中性容器 + 标签”分层,减少此前不同类型整块上色过多导致的彩虹感。
- 2026-03-07:继续统一消息卡片层级:用户消息不再重复显示角色标签,普通已发用户消息会补轻量“已发送”提示;thinking / tool / tool result / attachment 开始统一走标签 + 内容区的结构,而不是每种类型都靠大面积底色来强调。
- 2026-03-07:应用壳层继续减法:去掉全局顶部标题栏,避免在会话/状态/设置页上方长期占一条大高度却只重复页面标题;当前页面改为直接从内容区进入,聊天页只保留内部轻量返回/动作条。
- 2026-03-07:设置页重做为分组式连接中心:移除 HeroCard 式说明块,改成“连接与账号 / 默认 Agent / 外观 / 诊断信息”四组,减少说明书感,重点回到用户真正能查看和切换的配置项。
- 2026-03-07:顺手把状态页头部也收轻:去掉大 HeroCard,改为直接标题 + 指标卡 + 详情卡,避免多个页面同时维持两套厚重的页头语言。
- 2026-03-07:补了一轮真正的详情页导航语义:聊天详情页重新加回明确的顶部导航头(返回 / 标题 / 附件 / 刷新),不再只是内容区里塞一个“返回”按钮;同时抽了一个轻量 `PlatformBackHandler`,先在 Android 接上系统返回,让详情页能正常退回首页/列表。
- 2026-03-07:进一步把页面切换从“状态变量拼页面”收成显式 route:`OpenClawAppState` 现在用 `AppRoute`(Sessions / Status / Settings / Chat(sessionId))管理当前页面,详情页与首页切换不再依赖 `selectedTab + activeSessionId` 的隐式组合,后续继续加真正导航能力会顺很多。
- 2026-03-07:把详情页顶部导航头正式迁回 `Scaffold.topBar`:聊天页内部不再自己伪造导航栏,而是由 app 壳层根据 route 决定顶栏标题、返回、附件、刷新动作;这样详情页终于有了正经的二级页面导航结构。
- 2026-03-07:修正附件失败态的重试可见性:之前“重试”混在一排附件操作按钮最右侧,窄屏上很容易被挤掉;现在失败附件会单独前置一个主按钮“重新发送附件”,避免用户知道失败了却找不到怎么重发。
- 2026-03-07:补了一层附件上传响应 DTO 兼容:客户端 `UploadAttachmentResponseDto` 现在同时接受 `accepted/accept`、`fileName/filename`、`sizeBytes/sizebytes`、camelCase/snake_case 等字段名,先兜住线上回包字段不一致导致的反序列化失败。
- 2026-03-07:收口一处“最后一条一直转圈”的本地状态残留:文本消息被服务端接受后,如果当前会话已经没有待发文本,就会立刻清掉本地 `thinking` 占位消息,避免附件已完成但时间线尾部仍像一直在生成回复。
- 2026-03-07:默认收起成功的工具调用噪音:聊天页时间线不再直接展示普通 `toolCall` 和成功 `toolResult`,优先保留用户/助手正文、附件与关键错误;工具失败仍继续显示,避免用户正常发一条消息却被一串内部工具事件刷屏。
- 2026-03-07:首屏远程同步提速第一轮:App 端把 `status / agents / sessions` 从串行改成并行;BFF 端 `list_sessions()` 去掉每条 session 再补 `chat.history(limit=1)` 的 N+1 回查,首页先快速拿列表,避免刚打开就被会话摘要回查拖慢。
- 2026-03-07:首屏远程同步提速第二轮:BFF 给 `/api/status`、`/api/agents`、`/api/sessions` 补了短 TTL 缓存,并让 `status` / `agents` 共享同一份 `openclaw status --json` 结果;热缓存下三个接口都压到了毫秒级,避免刚打开或短时间来回切页时反复打慢 CLI。
- 2026-03-07:补一轮列表摘要降级策略:远端 session 列表不再回查摘要后,客户端刷新会优先沿用本地已有摘要;如果当前确实拿不到摘要,UI 直接留白而不是整屏显示“暂无摘要”,避免性能优化后的列表观感像异常状态。
- 2026-03-07:按最新交互反馈继续收聊天页壳层:非会话页移除 TopAppBar,只在会话详情保留顶部导航;会话页顶栏返回/附件/刷新改成更明确的按钮,标题字号再收小;输入栏去掉“继续当前会话”说明并压缩整体高度,减少底部控件占屏。
- 2026-03-07:信息架构继续做减法:底部导航先从三栏收成两栏(会话 / 设置),把原状态页的核心诊断信息并进设置页的“诊断信息”分组,避免低频诊断页长期占一个一级入口。
- 2026-03-07:继续给聊天页降噪:正常在线时顶部状态条不再常驻,只在同步 / 发送 / 恢复 / 断流等需要用户感知时才显示;状态文案改成更短的移动端提示,同时去掉用户消息“已发送”和附件“已完成”这类长期占位但信息价值不高的状态露出。
- 2026-03-07:会话页顶栏操作再收成图标化按钮:返回 / 附件 / 刷新不再显示整词文本,而是先用轻量符号按钮(← / + / ↻/⟳)表达,减少顶栏横向拥挤;后续如果需要,再统一切成正式 Material Icons 资源。
- 2026-03-07:把会话页顶栏的占位符号按钮升级为正式 Material Icons:返回改为 `ArrowBack`,附件改为 `AttachFile`,刷新/重连改为 `Refresh`,让导航头从临时占位过渡到更像成品的视觉语义。
- 2026-03-07:继续优化附件卡片操作区:失败态仍保留前置主按钮“重新发送附件”,其余常用动作从一排横向按钮改成两行等宽次级操作(打开 / 下载 / 复制文件名 / 查看详情),避免窄屏下一排动作挤爆、主次不分。
- 2026-03-07:继续收会话列表层级:最近访问卡降级成更轻的普通卡片,入口文案从“继续”改成“打开”;列表项把更新时间提到标题行右侧,底部只保留必要状态,置顶操作从文字按钮降成星标符号按钮,减少每项底部操作重量。
- 2026-03-07:继续压缩会话页头部:SectionHeader 标题字号和行距再收一档,统计文案改成更短的辅助信息;列表整体纵向间距减小,搜索框去掉表单式 label,改成更轻的 placeholder 搜索,减少头部在首屏占用的垂直空间。
- 2026-03-07:继续细化聊天时间线层级:system notice 改成更轻的窄条样式,thinking 去掉大 pill 改为更轻的 loading 行,tool error 文案收成“执行失败”并统一到更明显的错误容器语义,让过渡态 / 系统态 / 错误态和正式聊天消息的层级更清楚。
- 2026-03-07:开始补主动自救能力:会话页新增常驻“刷新”入口,不再只有报错卡里才有重试;设置页新增“立即同步”入口,让用户能主动拉取状态 / agents / 会话列表,而不是只能等后台轮询或进详情页触发刷新。
- 2026-03-07:会话页补上真正的下拉刷新:基于 Material3 `PullToRefreshBox` 接 `onRetry`,让列表页除了常驻“刷新”按钮外,也支持更符合移动端习惯的手势刷新。
- 2026-03-07:聊天页也补上下拉刷新:沿用同一套 `PullToRefreshBox + onRetry` 机制,让会话详情除了顶栏刷新/重连外,也支持直接下拉拉取最新消息与状态。
- 2026-03-07:同步反馈开始区分触发来源:把远端同步拆成 `Initial / Manual / Background` 三种触发语义,用户主动刷新成功时会明确提示“已同步最新状态”,后台静默刷新则尽量不打扰,避免轮询也频繁弹反馈,同时让手动操作的结果更可感知。
- 2026-03-07:开始统一发送反馈语言:聊天时间线里把文本/附件/工具的状态从泛化的“处理中 / 失败”细化成用户更能理解的产品文案,如“发送中 / 上传中 / 发送队列中 / 自动重试中 / 执行中 / 发送失败 / 上传失败 / 生成失败”,让用户更清楚当前到底卡在哪一环。
- 2026-03-07:正式启动“统一机制”重构 Phase 1:新增 `docs/UNIFIED_DELIVERY_ARCHITECTURE.md` 作为设计稿;App 新增 `UnifiedDeliveryModels.kt`,定义 `DeliveryOperation / SessionDetailState / SessionDetailEvent / reducer` 骨架;BFF 新增 `unified_models.py` 并预留 `/api/sessions/{session_id}/bootstrap` 响应模型与空接口,先把新主干立起来,后续再逐步把旧 pending/SSE/refresh 逻辑迁过去。
- 2026-03-07:继续推进 Phase 1:BFF 已把 `/api/sessions/{session_id}/bootstrap` 接成真实数据骨架(当前返回 canonical messages + 空 operations + streamState/serverTs);App 已补上 `SessionBootstrapResponseDto`、`getSessionBootstrap()` 和 `fetchSessionBootstrap()` 入口,开始具备并行验证新 bootstrap 流程的能力,但尚未切换 UI 到新模型。
+244
View File
@@ -0,0 +1,244 @@
# Unified Delivery Architecture
## 背景
当前 openclawapp 已具备可用主链路,但消息、pending queue、SSE、refresh、附件、重试之间的机制耦合严重:
- `ChatMessage.status` 混合承载本地待发、上传、重试、远端生成、工具执行、流失败等多种维度
- App 侧同时维护 `messageStore`、`pendingTextQueue`、`pendingAttachmentQueue`、retry stores、stream status stores
- BFF 侧同时维护 history diff SSE、attachment overlay、alias/redirect、stub message
- refresh / SSE / local pending / retry 都会直接影响时间线,导致没有单一真相源
核心问题不是某个 reconnect 按钮不够好,而是:
> **消息结果(Message)与待发操作(Operation)没有分层,App 与 BFF 又同时在做 reconciliation。**
## 目标
建立统一机制:
1. **Message 是结果,不是过程**
2. **Operation 是过程,不是消息**
3. **BFF 成为 operation/outbox 与 canonical message projection 的唯一协调层**
4. **App 只消费 bootstrap + event stream,并用 reducer 应用状态**
---
## 目标模型
### Message
表示会话时间线里的正式实体。
建议字段:
- `messageId`
- `sessionId`
- `role`
- `kind`
- `text`
- `createdAtMs`
- `orderKey`
- `remoteState`:`streaming | final | failed`
- `toolName`
- `toolCallId`
- `attachmentRef`
### Operation
表示本地/边车待发操作。文本和附件统一纳入同一个 outbox 模型。
建议字段:
- `opId`
- `sessionId`
- `type`: `send_text | send_attachment`
- `clientRequestId`
- `createdAtMs`
- `state`
- `attemptCount`
- `lastError`
- `payloadRef`
- `correlationToken`
- `materializedMessageIds`
建议状态:
- `accepted`
- `persisted`
- `dispatching`
- `awaiting_remote_echo`
- `materialized`
- `failed_retryable`
- `failed_terminal`
- `cancelled`
### SessionDetailState
App 侧以会话为单位维护聚合状态,不再让 UI 直接消费多套散落 store。
字段建议:
- `sessionId`
- `messages: List<MessageTimelineItem>`
- `operations: List<DeliveryOperation>`
- `syncState`
- `streamState`
- `lastBootstrapAtMs`
- `lastError`
### Timeline 投影
UI 时间线不直接渲染底层 message/op,而是渲染投影:
- `MessageTimelineItem.RemoteMessage`
- `MessageTimelineItem.PendingOperation`
- `MessageTimelineItem.SystemNotice`
这样 “发送中/上传中/失败重试” 就是 operation card,不再伪装成正式 message。
---
## 协议建议
### Bootstrap API
新增或演进:
`GET /api/sessions/{sessionId}/bootstrap`
返回:
- `messages[]`
- `operations[]`
- `sessionMeta`
- `streamState`
- `serverTs`
### SSE v2
不再暴露 history diff 细碎补丁,而是统一实体事件:
- `session.bootstrap`
- `message.upsert`
- `message.removed`
- `operation.upsert`
- `operation.removed`
- `session.state`
- `stream.health`
如果有文本流式增量,可以作为 `message.patch`,但不再强依赖 started/delta/completed 三件套分散落地。
---
## 边界划分
### App
负责:
- UI 渲染
- 本地缓存 bootstrap 结果
- 用户命令发起
- reducer 应用事件
不再负责:
- pending/retry 真相判定
- heuristics 匹配远端是否承认本地消息
- overlay/alias 语义理解
### BFF
负责:
- operation 持久化
- 附件 payload 生命周期
- 与 OpenClaw 的消息/附件对接
- canonical timeline 投影
- SSE 事件生成
---
## 迁移计划
### Phase 1:立模型,不切旧逻辑
#### App
- 新增 `DeliveryOperation` / `SessionDetailState` / reducer skeleton
- 先不替换现有 UI,只把新模型放进代码库
#### BFF
- 新增 `OperationRecord` / `OperationPayloadRef` / `SessionBootstrapResponse` 模型草案
- 新增 bootstrap / operation DTO 草案(可先不对外开放)
#### 收益
- 统一机制正式有“落脚点”
- 后续不再继续给旧字符串状态扩容
#### 风险
- 这阶段功能收益不明显,主要是架构铺路
### Phase 2:BFF 接管 outbox
- 文本发送、附件上传都先创建 operation record
- App 保留现有接口,但 response 里开始带 `operationId`
- retry/recovery 由 BFF 驱动
### Phase 3:App 详情页切到 reducer 投影
- 会话详情改读 `SessionDetailState`
- operation card 替代 local-thinking / fake uploaded message
- refresh 与 SSE 都只喂 reducer
### Phase 4:删旧逻辑
#### App 待删
- `pendingTextQueue`
- `pendingAttachmentQueue`
- `textRetryStore`
- `attachmentRetryStore`
- `autoRetryMessageIds`
- `mergeSnapshotWithLocalPending()`
- `retainedLocalMessages()`
- `matchesPendingLocalText()/Attachment()`
- `local-thinking-*`
#### BFF 待删/冻结
- `_session_overlays`
- `_attachment_aliases`
- `stub-*` uploaded message 过渡语义
- history diff 补丁事件继续扩张
---
## 当前阶段的执行原则
从现在开始:
1. 冻结 `ChatMessage.status` 新字符串扩张
2. 冻结新的 pending/retry heuristic
3. 新能力优先落在新模型上,而不是继续补旧模型
4. UI 小修只做阻塞性 bug,不再继续围绕旧机制做大量打补丁优化
---
## 当前这一轮要落地的最小骨架
### App
- 定义 `DeliveryOperation`
- 定义 `SessionDetailState`
- 定义 `SessionDetailEvent`
- 定义 `reduceSessionDetailState()`
### BFF
- 定义 `OperationRecord`
- 定义 `SessionBootstrapResponse`
- 预留 `/api/sessions/{session_id}/bootstrap` 的 response model
- 后续再逐步接真实数据流
+22
View File
@@ -3,6 +3,14 @@ enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")
pluginManagement { pluginManagement {
repositories { repositories {
maven("https://maven.aliyun.com/repository/google") {
name = "AliyunGoogle"
mavenContent {
includeGroupAndSubgroups("androidx")
includeGroupAndSubgroups("com.android")
includeGroupAndSubgroups("com.google")
}
}
google { google {
mavenContent { mavenContent {
includeGroupAndSubgroups("androidx") includeGroupAndSubgroups("androidx")
@@ -10,6 +18,9 @@ pluginManagement {
includeGroupAndSubgroups("com.google") includeGroupAndSubgroups("com.google")
} }
} }
maven("https://maven.aliyun.com/repository/public") {
name = "AliyunPublic"
}
mavenCentral() mavenCentral()
gradlePluginPortal() gradlePluginPortal()
} }
@@ -20,6 +31,14 @@ plugins {
dependencyResolutionManagement { dependencyResolutionManagement {
repositories { repositories {
maven("https://maven.aliyun.com/repository/google") {
name = "AliyunGoogle"
mavenContent {
includeGroupAndSubgroups("androidx")
includeGroupAndSubgroups("com.android")
includeGroupAndSubgroups("com.google")
}
}
google { google {
mavenContent { mavenContent {
includeGroupAndSubgroups("androidx") includeGroupAndSubgroups("androidx")
@@ -27,6 +46,9 @@ dependencyResolutionManagement {
includeGroupAndSubgroups("com.google") includeGroupAndSubgroups("com.google")
} }
} }
maven("https://maven.aliyun.com/repository/public") {
name = "AliyunPublic"
}
mavenCentral() mavenCentral()
} }
} }