Compare commits

..
28 Commits
Author SHA1 Message Date
OpenClaw 6158584b74 fix: replace invalid underscore catches in Kotlin 2026-03-07 03:17:59 +08:00
OpenClaw cc1f5990f5 feat: render chat updates from delta SSE events 2026-03-07 03:14:06 +08:00
xiaobai 8b9b17cd84 修复报错 2026-03-07 03:08:16 +08:00
OpenClaw c01e4623b7 feat: show thinking placeholder during remote send 2026-03-07 03:03:51 +08:00
OpenClaw 2595107244 fix: harden chat SSE handling to avoid crashes 2026-03-07 03:00:22 +08:00
OpenClaw b43e40a67e feat: add SSE session stream client skeleton 2026-03-07 02:53:12 +08:00
OpenClaw eeff16a4ca feat: persist login state and remove mock entry flow 2026-03-07 02:45:29 +08:00
OpenClaw 6ec824f078 feat: add BFF login flow for remote mode 2026-03-07 02:39:24 +08:00
OpenClaw d8442b42e2 fix: enable Android network access and cleartext HTTP 2026-03-07 02:33:37 +08:00
OpenClaw 015f7ac52a chore: move bff out to separate repository 2026-03-07 02:12:56 +08:00
OpenClaw 591fd991fa feat: add BFF backend scaffold for mobile app 2026-03-07 02:08:25 +08:00
xiaobai 03d21f607f 修复报错 2026-03-07 02:04:35 +08:00
OpenClaw 905049691c fix: resolve repository extension reference compile error 2026-03-07 02:03:11 +08:00
OpenClaw d921919174 feat: enable remote sync flow with loading and error states 2026-03-07 01:57:54 +08:00
OpenClaw 2d14cc5cc8 feat: scaffold repository and mobile gateway network layer 2026-03-07 01:47:12 +08:00
OpenClaw a4d0f97839 feat: add app theme system and theme switching 2026-03-07 01:40:54 +08:00
OpenClaw e21afbf583 feat: add mock streaming and auto-scroll in chat 2026-03-07 01:37:31 +08:00
xiaobai 2e20eb3f7b 修复报错 2026-03-07 01:36:15 +08:00
OpenClaw a7f05b56ed fix: resolve weight scope bug and add feedback banners 2026-03-07 01:34:10 +08:00
OpenClaw 4acc08e2f8 feat: add interactive mock session behaviors 2026-03-07 01:28:44 +08:00
OpenClaw 5c2ae565c8 feat: refine mobile UI layout and empty states 2026-03-07 01:22:57 +08:00
OpenClaw 9bc9b0f318 feat: polish mobile app UI 2026-03-07 01:18:09 +08:00
xiaobai 6298ab223b 更新依赖 2026-03-07 01:13:08 +08:00
OpenClaw c8cb3b5812 feat: add mobile app skeleton with mock chat flow 2026-03-07 00:50:52 +08:00
OpenClaw a017533b96 docs: add architecture plan for OpenClaw mobile app 2026-03-07 00:26:13 +08:00
xiaobai 403a538fda 首次提交 2026-03-07 00:10:33 +08:00
xiaobai dbb3c196fe 删除 README.md 2026-03-07 00:08:24 +08:00
xiaobai eb52531b61 Initial commit 2026-03-07 00:02:02 +08:00
29 changed files with 2762 additions and 87 deletions

No files matched your search

+49 -52
View File
@@ -1,63 +1,60 @@
This is a Kotlin Multiplatform project targeting Android, iOS, Web. # OpenClawApp
* [/composeApp](./composeApp/src) is for code that will be shared across your Compose Multiplatform applications. OpenClawApp 是一个面向 **Android / iOS / Web** 的 OpenClaw 客户端,使用 **Kotlin Multiplatform + Compose Multiplatform** 构建。
It contains several subfolders:
- [commonMain](./composeApp/src/commonMain/kotlin) is for code that’s common for all targets.
- Other folders are for Kotlin code that will be compiled for only the platform indicated in the folder name.
For example, if you want to use Apple’s CoreCrypto for the iOS part of your Kotlin app,
the [iosMain](./composeApp/src/iosMain/kotlin) folder would be the right place for such calls.
Similarly, if you want to edit the Desktop (JVM) specific part, the [jvmMain](./composeApp/src/jvmMain/kotlin)
folder is the appropriate location.
* [/iosApp](./iosApp/iosApp) contains iOS applications. Even if you’re sharing your UI with Compose Multiplatform, 目标不是把 OpenClaw 整体搬到手机运行,而是提供一个稳定、好用的移动端入口:
you need this entry point for your iOS app. This is also where you should add SwiftUI code for your project.
### Build and Run Android Application - 查看会话列表
- 与 OpenClaw 聊天
- 查看状态与默认 agent
- 后续接入推送通知
- 通过中转层(BFF)安全地连接 OpenClaw
To build and run the development version of the Android app, use the run configuration from the run widget ## 当前架构方向
in your IDE’s toolbar or build it directly from the terminal:
- on macOS/Linux
```shell
./gradlew :composeApp:assembleDebug
```
- on Windows
```shell
.\gradlew.bat :composeApp:assembleDebug
```
### Build and Run Web Application 采用三层架构:
To build and run the development version of the web app, use the run configuration from the run widget ```text
in your IDE's toolbar or run it directly from the terminal: OpenClawApp
- for the Wasm target (faster, modern browsers): ↓
- on macOS/Linux BFF / Mobile Gateway
```shell ↓
./gradlew :composeApp:wasmJsBrowserDevelopmentRun OpenClaw
``` ```
- on Windows
```shell
.\gradlew.bat :composeApp:wasmJsBrowserDevelopmentRun
```
- for the JS target (slower, supports older browsers):
- on macOS/Linux
```shell
./gradlew :composeApp:jsBrowserDevelopmentRun
```
- on Windows
```shell
.\gradlew.bat :composeApp:jsBrowserDevelopmentRun
```
### Build and Run iOS Application V1 不把移动端直接做成 OpenClaw 插件/渠道,而是先做一个独立客户端。
To build and run the development version of the iOS app, use the run configuration from the run widget 详细规划见:[`docs/ARCHITECTURE.md`](./docs/ARCHITECTURE.md)
in your IDE’s toolbar or open the [/iosApp](./iosApp) directory in Xcode and run it from there.
--- ## 项目结构
Learn more about [Kotlin Multiplatform](https://www.jetbrains.com/help/kotlin-multiplatform-dev/get-started.html), - `composeApp/`:共享 UI 与跨平台应用代码
[Compose Multiplatform](https://github.com/JetBrains/compose-multiplatform/#compose-multiplatform), - `iosApp/`:iOS 宿主工程
[Kotlin/Wasm](https://kotl.in/wasm/)… - `docs/`:架构、接入与迭代文档
We would appreciate your feedback on Compose/Web and Kotlin/Wasm in the public Slack channel [#compose-web](https://slack-chats.kotlinlang.org/c/compose-web). ## 开发阶段
If you face any issues, please report them on [YouTrack](https://youtrack.jetbrains.com/newIssue?project=CMP).
当前阶段:
1. 建立应用骨架
2. 用 Mock 数据跑通会话/聊天/设置/状态页面
3. 再接入真实 BFF
4. 最后联通 OpenClaw
## 常用命令
### Android
```bash
./gradlew :composeApp:assembleDebug
```
### Web (Wasm)
```bash
./gradlew :composeApp:wasmJsBrowserDevelopmentRun
```
### iOS
使用 Xcode 打开 `iosApp/` 后运行。
+13 -1
View File
@@ -1,4 +1,3 @@
import org.jetbrains.compose.desktop.application.dsl.TargetFormat
import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
import org.jetbrains.kotlin.gradle.dsl.JvmTarget import org.jetbrains.kotlin.gradle.dsl.JvmTarget
@@ -7,6 +6,7 @@ plugins {
alias(libs.plugins.androidApplication) alias(libs.plugins.androidApplication)
alias(libs.plugins.composeMultiplatform) alias(libs.plugins.composeMultiplatform)
alias(libs.plugins.composeCompiler) alias(libs.plugins.composeCompiler)
alias(libs.plugins.kotlinxSerialization)
} }
kotlin { kotlin {
@@ -41,6 +41,13 @@ kotlin {
androidMain.dependencies { androidMain.dependencies {
implementation(libs.compose.uiToolingPreview) implementation(libs.compose.uiToolingPreview)
implementation(libs.androidx.activity.compose) implementation(libs.androidx.activity.compose)
implementation(libs.ktor.client.okhttp)
}
iosMain.dependencies {
implementation(libs.ktor.client.darwin)
}
jsMain.dependencies {
implementation(libs.ktor.client.js)
} }
commonMain.dependencies { commonMain.dependencies {
implementation(libs.compose.runtime) implementation(libs.compose.runtime)
@@ -51,6 +58,11 @@ kotlin {
implementation(libs.compose.uiToolingPreview) implementation(libs.compose.uiToolingPreview)
implementation(libs.androidx.lifecycle.viewmodelCompose) implementation(libs.androidx.lifecycle.viewmodelCompose)
implementation(libs.androidx.lifecycle.runtimeCompose) implementation(libs.androidx.lifecycle.runtimeCompose)
implementation(libs.ktor.client.core)
implementation(libs.ktor.client.contentNegotiation)
implementation(libs.ktor.serialization.kotlinx.json)
implementation(libs.kotlinx.serialization.json)
implementation(libs.multiplatform.settings.no.arg)
} }
commonTest.dependencies { commonTest.dependencies {
implementation(libs.kotlin.test) implementation(libs.kotlin.test)
@@ -1,13 +1,18 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application <application
android:allowBackup="true" android:allowBackup="true"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:label="@string/app_name"
android:networkSecurityConfig="@xml/network_security_config"
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher_round"
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">
<activity <activity
android:exported="true" android:exported="true"
android:name=".MainActivity"> android:name=".MainActivity">
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
@@ -1,48 +1,210 @@
package cn.xiaobai.openclawapp package cn.xiaobai.openclawapp
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
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.fillMaxWidth import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeContentPadding import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.* import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.painterResource import cn.xiaobai.openclawapp.app.MainTab
import cn.xiaobai.openclawapp.app.OpenClawAppState
import openclawapp.composeapp.generated.resources.Res import cn.xiaobai.openclawapp.data.ServerConfig
import openclawapp.composeapp.generated.resources.compose_multiplatform import cn.xiaobai.openclawapp.feature.chat.ChatScreen
import cn.xiaobai.openclawapp.feature.config.ServerConfigScreen
import cn.xiaobai.openclawapp.feature.sessions.SessionListScreen
import cn.xiaobai.openclawapp.feature.settings.SettingsScreen
import cn.xiaobai.openclawapp.feature.status.StatusScreen
import cn.xiaobai.openclawapp.ui.OpenClawTheme
import cn.xiaobai.openclawapp.ui.StatusPill
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Composable @Composable
@Preview
fun App() { fun App() {
MaterialTheme { val appState = remember { OpenClawAppState() }
var showContent by remember { mutableStateOf(false) } val coroutineScope = rememberCoroutineScope()
OpenClawTheme(themeMode = appState.themeMode) {
if (!appState.isConfigured) {
var baseUrl by remember { mutableStateOf(appState.serverConfig.baseUrl) }
var token by remember { mutableStateOf(appState.serverConfig.token) }
var password by remember { mutableStateOf("") }
var agent by remember { mutableStateOf(appState.serverConfig.defaultAgent) }
ServerConfigScreen(
baseUrl = baseUrl,
token = token,
password = password,
defaultAgent = agent,
isConnecting = appState.isConnecting,
errorMessage = appState.configError,
onBaseUrlChange = { baseUrl = it },
onTokenChange = { token = it },
onPasswordChange = { password = it },
onDefaultAgentChange = { agent = it },
onConnect = {
coroutineScope.launch {
appState.clearConfigError()
appState.connect(
ServerConfig(
baseUrl = baseUrl,
token = token,
defaultAgent = agent,
),
password = password,
)
}
},
)
} else {
OpenClawRoot(appState)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun OpenClawRoot(appState: OpenClawAppState) {
val activeSession = appState.activeSessionId?.let(appState.repository::findSession)
val coroutineScope = rememberCoroutineScope()
LaunchedEffect(appState.feedbackMessage) {
if (appState.feedbackMessage != null) {
delay(2200)
appState.clearFeedback()
}
}
LaunchedEffect(appState.isConfigured) {
if (appState.isConfigured) {
appState.syncRemoteIfNeeded()
}
}
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = {
Text(
text = when {
activeSession != null -> activeSession.title
appState.selectedTab == MainTab.Sessions -> "OpenClaw"
appState.selectedTab == MainTab.Status -> "运行状态"
appState.selectedTab == MainTab.Settings -> "设置"
else -> ""
}
)
},
)
},
bottomBar = {
if (activeSession == null) {
NavigationBar {
NavigationBarItem(
selected = appState.selectedTab == MainTab.Sessions,
onClick = { appState.selectedTab = MainTab.Sessions },
icon = { Text("💬") },
label = { Text("会话") },
)
NavigationBarItem(
selected = appState.selectedTab == MainTab.Status,
onClick = { appState.selectedTab = MainTab.Status },
icon = { Text("📡") },
label = { Text("状态") },
)
NavigationBarItem(
selected = appState.selectedTab == MainTab.Settings,
onClick = { appState.selectedTab = MainTab.Settings },
icon = { Text("⚙️") },
label = { Text("设置") },
)
}
}
},
) { innerPadding ->
Column( Column(
modifier = Modifier modifier = Modifier
.background(MaterialTheme.colorScheme.primaryContainer) .fillMaxSize()
.safeContentPadding() .padding(innerPadding),
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
) { ) {
Button(onClick = { showContent = !showContent }) { appState.feedbackMessage?.let { message ->
Text("Click me!") StatusPill(
text = message,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
highlighted = true,
)
} }
AnimatedVisibility(showContent) {
val greeting = remember { Greeting().greet() } when {
Column( activeSession != null -> ChatScreen(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally, sessionTitle = activeSession.title,
) { messages = appState.repository.messagesFor(activeSession.id),
Image(painterResource(Res.drawable.compose_multiplatform), null) isSending = appState.isSending,
Text("Compose: $greeting") isLoading = appState.isSyncing,
errorMessage = appState.syncError,
onBack = appState::closeChat,
onRetry = {
coroutineScope.launch {
appState.clearSyncError()
appState.openSession(activeSession.id)
} }
},
onSend = { text ->
coroutineScope.launch {
appState.sendMessage(activeSession.id, text)
}
},
)
appState.selectedTab == MainTab.Sessions -> SessionListScreen(
modifier = Modifier.fillMaxSize(),
sessions = appState.repository.sessions,
recentSession = appState.repository.recentSession(),
pinnedCount = appState.repository.pinnedCount(),
isLoading = appState.isSyncing,
errorMessage = appState.syncError,
onOpenSession = { sessionId ->
coroutineScope.launch {
appState.openSession(sessionId)
}
},
onTogglePin = appState::togglePin,
onRetry = {
coroutineScope.launch {
appState.clearSyncError()
appState.syncRemoteIfNeeded()
}
},
)
appState.selectedTab == MainTab.Status -> StatusScreen(
modifier = Modifier.fillMaxSize(),
status = appState.repository.status,
)
appState.selectedTab == MainTab.Settings -> SettingsScreen(
modifier = Modifier.fillMaxSize(),
serverConfig = appState.serverConfig,
currentModel = appState.repository.status.currentModel,
availableAgents = appState.repository.availableAgents,
currentTheme = appState.themeMode,
onSelectAgent = appState::updateDefaultAgent,
onSelectTheme = appState::updateTheme,
onDisconnect = appState::disconnect,
)
} }
} }
} }
@@ -0,0 +1,157 @@
package cn.xiaobai.openclawapp.app
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import cn.xiaobai.openclawapp.data.AppPreferences
import cn.xiaobai.openclawapp.data.OpenClawRepository
import cn.xiaobai.openclawapp.data.RemoteOpenClawRepository
import cn.xiaobai.openclawapp.data.RepositoryFactory
import cn.xiaobai.openclawapp.data.ServerConfig
import cn.xiaobai.openclawapp.network.MobileGatewayApi
class OpenClawAppState(
private val preferences: AppPreferences = AppPreferences(),
) {
var selectedTab by mutableStateOf(MainTab.Sessions)
var activeSessionId by mutableStateOf<String?>(null)
var serverConfig by mutableStateOf(preferences.loadServerConfig())
var feedbackMessage by mutableStateOf<String?>(null)
var themeMode by mutableStateOf(preferences.loadThemeMode())
var isSyncing by mutableStateOf(false)
var isSending by mutableStateOf(false)
var isConnecting by mutableStateOf(false)
var syncError by mutableStateOf<String?>(null)
var configError by mutableStateOf<String?>(null)
var repository: OpenClawRepository by mutableStateOf(RepositoryFactory.createRemote(serverConfig))
var isConfigured by mutableStateOf(serverConfig.baseUrl.isNotBlank() && serverConfig.token.isNotBlank())
suspend fun connect(config: ServerConfig, password: String) {
isConnecting = true
configError = null
runCatching {
val resolvedConfig = if (config.token.isBlank()) {
require(password.isNotBlank()) { "请输入 BFF 登录密码或直接填写 token" }
val loginApi = MobileGatewayApi(baseUrl = config.baseUrl, tokenProvider = { "" })
val login = loginApi.login(password)
config.copy(token = login.token)
} else {
config
}
serverConfig = resolvedConfig
preferences.saveServerConfig(resolvedConfig)
repository = RepositoryFactory.createRemote(resolvedConfig)
isConfigured = true
syncError = null
feedbackMessage = "已连接到 ${resolvedConfig.baseUrl}"
}.onFailure {
configError = it.message ?: "连接失败"
feedbackMessage = "连接失败"
}
isConnecting = false
}
fun disconnect() {
isConfigured = false
activeSessionId = null
selectedTab = MainTab.Sessions
syncError = null
configError = null
serverConfig = serverConfig.copy(token = "")
preferences.clearLoginState()
repository = RepositoryFactory.createRemote(serverConfig)
feedbackMessage = "连接已断开"
}
suspend fun syncRemoteIfNeeded() {
val remote = repository as? RemoteOpenClawRepository ?: return
isSyncing = true
syncError = null
runCatching {
remote.refreshStatus()
remote.refreshAgents()
remote.refreshSessions()
}.onFailure {
syncError = it.message ?: "远程同步失败"
feedbackMessage = "Remote 同步失败"
}
isSyncing = false
}
suspend fun openSession(sessionId: String) {
repository.markSessionOpened(sessionId)
activeSessionId = sessionId
val remote = repository as? RemoteOpenClawRepository ?: return
isSyncing = true
runCatching {
remote.refreshMessages(sessionId)
}.onFailure {
syncError = it.message ?: "会话消息加载失败"
feedbackMessage = "消息加载失败"
}
isSyncing = false
}
fun closeChat() {
activeSessionId = null
}
suspend fun sendMessage(sessionId: String, text: String) {
val remote = repository as? RemoteOpenClawRepository ?: return
isSending = true
runCatching {
remote.sendMessageRemote(sessionId, text)
}.onFailure {
syncError = it.message ?: "消息发送失败"
feedbackMessage = "消息发送失败"
}
isSending = false
}
fun updateDefaultAgent(agent: String) {
serverConfig = serverConfig.copy(defaultAgent = agent)
preferences.saveServerConfig(serverConfig)
repository.status = repository.status.copy(defaultAgent = agent)
feedbackMessage = "默认 Agent 已切换到 $agent"
}
fun updateTheme(theme: AppThemeMode) {
themeMode = theme
preferences.saveThemeMode(theme)
feedbackMessage = when (theme) {
AppThemeMode.Dark -> "已切到深色主题"
AppThemeMode.Light -> "已切到浅色主题"
}
}
fun togglePin(sessionId: String) {
val pinned = repository.togglePinned(sessionId)
feedbackMessage = if (pinned) "已置顶会话" else "已取消置顶"
}
fun clearFeedback() {
feedbackMessage = null
}
fun clearSyncError() {
syncError = null
}
fun clearConfigError() {
configError = null
}
}
enum class MainTab {
Sessions,
Status,
Settings,
}
enum class AppThemeMode(val label: String) {
Dark("深色"),
Light("浅色"),
}
@@ -0,0 +1,44 @@
package cn.xiaobai.openclawapp.data
import cn.xiaobai.openclawapp.app.AppThemeMode
import com.russhwolf.settings.Settings
class AppPreferences(
private val settings: Settings = Settings(),
) {
fun loadServerConfig(): ServerConfig {
return ServerConfig(
baseUrl = settings.getStringOrNull(KEY_BASE_URL) ?: "http://192.168.31.116:8788",
token = settings.getStringOrNull(KEY_TOKEN) ?: "",
defaultAgent = settings.getStringOrNull(KEY_DEFAULT_AGENT) ?: "main",
)
}
fun saveServerConfig(config: ServerConfig) {
settings.putString(KEY_BASE_URL, config.baseUrl)
settings.putString(KEY_TOKEN, config.token)
settings.putString(KEY_DEFAULT_AGENT, config.defaultAgent)
}
fun clearLoginState() {
settings.remove(KEY_TOKEN)
}
fun loadThemeMode(): AppThemeMode {
return when (settings.getStringOrNull(KEY_THEME_MODE)) {
AppThemeMode.Light.name -> AppThemeMode.Light
else -> AppThemeMode.Dark
}
}
fun saveThemeMode(themeMode: AppThemeMode) {
settings.putString(KEY_THEME_MODE, themeMode.name)
}
companion object {
private const val KEY_BASE_URL = "server.base_url"
private const val KEY_TOKEN = "server.token"
private const val KEY_DEFAULT_AGENT = "server.default_agent"
private const val KEY_THEME_MODE = "ui.theme_mode"
}
}
@@ -0,0 +1,150 @@
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 流式消息。"
}
}
}
@@ -0,0 +1,38 @@
package cn.xiaobai.openclawapp.data
data class ServerConfig(
val baseUrl: String = "https://mobile-gateway.example.com",
val token: String = "",
val defaultAgent: String = "main",
)
data class SessionSummary(
val id: String,
val title: String,
val lastMessage: String,
val updatedAt: String,
val isPinned: Boolean = false,
val unreadCount: Int = 0,
)
data class ChatMessage(
val id: String,
val role: MessageRole,
val text: String,
val createdAt: String,
val status: String? = null,
)
enum class MessageRole {
User,
Assistant,
System,
}
data class ServerStatus(
val online: Boolean,
val openClawVersion: String,
val currentModel: String,
val defaultAgent: String,
val updatedAt: String,
)
@@ -0,0 +1,15 @@
package cn.xiaobai.openclawapp.data
interface OpenClawRepository {
var availableAgents: List<String>
val sessions: List<SessionSummary>
var status: ServerStatus
fun findSession(sessionId: String): SessionSummary?
fun messagesFor(sessionId: String): List<ChatMessage>
fun recentSession(): SessionSummary?
fun pinnedCount(): Int
fun markSessionOpened(sessionId: String)
fun togglePinned(sessionId: String): Boolean
fun sendMessage(sessionId: String, text: String)
}
@@ -0,0 +1,232 @@
package cn.xiaobai.openclawapp.data
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import cn.xiaobai.openclawapp.network.MobileGatewayApi
import cn.xiaobai.openclawapp.network.SessionSummaryDto
import cn.xiaobai.openclawapp.network.SessionStreamEvent
import cn.xiaobai.openclawapp.network.SseSessionStream
import cn.xiaobai.openclawapp.network.createDefaultHttpClient
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
class RemoteOpenClawRepository(
private val config: ServerConfig,
) : OpenClawRepository {
private val api by lazy {
MobileGatewayApi(
baseUrl = config.baseUrl,
tokenProvider = { config.token },
)
}
private val sseStream by lazy {
SseSessionStream(
client = createDefaultHttpClient(),
baseUrl = config.baseUrl,
tokenProvider = { config.token },
)
}
private val streamScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
private var streamJob: Job? = null
override var availableAgents by mutableStateOf(listOf("main"))
override var sessions by mutableStateOf<List<SessionSummary>>(emptyList())
override var status by mutableStateOf(
ServerStatus(
online = false,
openClawVersion = "unknown",
currentModel = "unknown",
defaultAgent = config.defaultAgent,
updatedAt = "未同步",
)
)
private var recentSessionId by mutableStateOf<String?>(null)
private var messageStore by mutableStateOf<Map<String, List<ChatMessage>>>(emptyMap())
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? = recentSessionId?.let(::findSession)
override fun pinnedCount(): Int = sessions.count { it.isPinned }
override fun markSessionOpened(sessionId: String) {
recentSessionId = sessionId
sessions = sessions.map {
if (it.id == sessionId) it.copy(unreadCount = 0) else it
}
subscribeSessionStream(sessionId)
}
override fun togglePinned(sessionId: String): Boolean {
var pinned = false
sessions = sessions.map {
if (it.id == sessionId) {
pinned = !it.isPinned
it.copy(isPinned = pinned)
} else {
it
}
}.sortedWith(compareByDescending<SessionSummary> { it.isPinned })
return pinned
}
override fun sendMessage(sessionId: String, text: String) {
val currentMessages = messageStore[sessionId].orEmpty()
messageStore = messageStore + (
sessionId to (currentMessages + listOf(
ChatMessage(
id = "local-user-$sessionId-${currentMessages.size + 1}",
role = MessageRole.User,
text = text,
createdAt = "现在",
status = "queued",
),
ChatMessage(
id = "local-thinking-$sessionId-${currentMessages.size + 2}",
role = MessageRole.Assistant,
text = "",
createdAt = "现在",
status = "thinking",
),
))
)
}
suspend fun refreshStatus() {
val remote = api.getStatus()
status = ServerStatus(
online = remote.online,
openClawVersion = remote.openClawVersion,
currentModel = remote.currentModel,
defaultAgent = remote.defaultAgent,
updatedAt = remote.updatedAt,
)
}
suspend fun refreshSessions() {
sessions = api.getSessions().map { dto -> dto.toDomain() }
}
suspend fun refreshAgents() {
availableAgents = api.getAgents().map { it.id.ifBlank { it.name } }
.ifEmpty { listOf(config.defaultAgent) }
}
suspend fun refreshMessages(sessionId: String) {
val remoteMessages = api.getMessages(sessionId).map { dto -> dto.toDomainMessage() }
messageStore = messageStore + (sessionId to remoteMessages)
}
suspend fun sendMessageRemote(sessionId: String, text: String) {
sendMessage(sessionId, text)
api.sendMessage(sessionId, text)
}
private fun subscribeSessionStream(sessionId: String) {
streamJob?.cancel()
streamJob = streamScope.launch {
while (currentCoroutineContext().isActive) {
try {
sseStream.connect(sessionId).collectLatest { event ->
when (event) {
is SessionStreamEvent.Snapshot -> {
messageStore = messageStore + (
sessionId to event.payload.messages.map { dto -> dto.toDomainMessage() }
)
}
is SessionStreamEvent.Delta -> {
val currentMessages = messageStore[sessionId].orEmpty()
val updated = currentMessages.map { message ->
if (message.id == event.payload.id) {
message.copy(
text = event.payload.fullText,
status = event.payload.status ?: "streaming",
)
} else {
message
}
}
val exists = updated.any { it.id == event.payload.id }
val next = if (exists) {
updated
} else {
updated + ChatMessage(
id = event.payload.id,
role = event.payload.role.toMessageRole(),
text = event.payload.fullText,
createdAt = event.payload.createdAt,
status = event.payload.status ?: "streaming",
)
}
messageStore = messageStore + (sessionId to next)
}
is SessionStreamEvent.Completed -> {
val completed = event.payload.toDomainMessage()
val currentMessages = messageStore[sessionId].orEmpty()
.filterNot { it.id.startsWith("local-thinking-") }
val exists = currentMessages.any { it.id == completed.id }
val next = if (exists) {
currentMessages.map { if (it.id == completed.id) completed else it }
} else {
currentMessages + completed
}
messageStore = messageStore + (sessionId to next)
}
}
}
} catch (e: CancellationException) {
throw e
} catch (t: Throwable) {
delay(1500)
}
}
}
}
fun dispose() {
streamJob?.cancel()
streamScope.cancel()
}
private fun SessionSummaryDto.toDomain(): SessionSummary {
return SessionSummary(
id = id,
title = title,
lastMessage = lastMessage ?: "",
updatedAt = updatedAt,
)
}
private fun cn.xiaobai.openclawapp.network.ChatMessageDto.toDomainMessage(): ChatMessage {
return ChatMessage(
id = id,
role = role.toMessageRole(),
text = text,
createdAt = createdAt,
status = status,
)
}
private fun String.toMessageRole(): MessageRole {
return when (lowercase()) {
"user" -> MessageRole.User
"assistant" -> MessageRole.Assistant
else -> MessageRole.System
}
}
}
@@ -0,0 +1,7 @@
package cn.xiaobai.openclawapp.data
object RepositoryFactory {
fun createMock(): OpenClawRepository = MockOpenClawRepository()
fun createRemote(config: ServerConfig): OpenClawRepository = RemoteOpenClawRepository(config)
}
@@ -0,0 +1,282 @@
package cn.xiaobai.openclawapp.feature.chat
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import cn.xiaobai.openclawapp.data.ChatMessage
import cn.xiaobai.openclawapp.data.MessageRole
import cn.xiaobai.openclawapp.ui.EmptyStateCard
import cn.xiaobai.openclawapp.ui.StatusPill
import kotlinx.coroutines.delay
@Composable
fun ChatScreen(
modifier: Modifier = Modifier,
sessionTitle: String,
messages: List<ChatMessage>,
isSending: Boolean,
isLoading: Boolean,
errorMessage: String?,
onBack: () -> Unit,
onRetry: () -> Unit,
onSend: (String) -> Unit,
) {
var input by remember { mutableStateOf("") }
val listState = rememberLazyListState()
LaunchedEffect(messages.size) {
if (messages.isNotEmpty()) {
listState.animateScrollToItem(messages.lastIndex)
}
}
Column(
modifier = modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Card(
modifier = Modifier.fillMaxWidth(),
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) {
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(
title = "还没有消息",
subtitle = "这里以后会展示真实的会话历史、流式回复和工具执行状态。",
)
} else {
LazyColumn(
modifier = Modifier
.weight(1f)
.fillMaxWidth(),
state = listState,
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
itemsIndexed(messages, key = { _, message -> message.id }) { index, message ->
val shouldAnimate = index == messages.lastIndex &&
message.role == MessageRole.Assistant &&
message.createdAt == "现在"
MessageBubble(
message = message,
animateText = shouldAnimate,
)
}
}
}
Card(modifier = Modifier.fillMaxWidth()) {
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(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.Bottom,
) {
OutlinedTextField(
value = input,
onValueChange = { input = it },
modifier = Modifier.weight(1f),
label = { Text("输入消息") },
placeholder = { Text("给 OpenClaw 发一句话") },
maxLines = 4,
enabled = !isSending,
)
Button(
onClick = {
if (input.isNotBlank() && !isSending) {
onSend(input.trim())
input = ""
}
},
enabled = !isSending,
) {
if (isSending) {
CircularProgressIndicator()
} else {
Text("发送")
}
}
}
}
}
}
}
@Composable
private fun RowScope.QuickActionButton(text: String, onClick: () -> Unit) {
Button(onClick = onClick, modifier = Modifier.weight(1f)) {
Text(text)
}
}
@Composable
private fun MessageBubble(
message: ChatMessage,
animateText: Boolean = false,
) {
val alignment = when (message.role) {
MessageRole.User -> Alignment.CenterEnd
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) {
MessageRole.User -> "你"
MessageRole.Assistant -> "OpenClaw"
MessageRole.System -> "系统"
}
var visibleChars by remember(message.id) { mutableIntStateOf(if (animateText) 0 else message.text.length) }
LaunchedEffect(message.id, animateText) {
if (animateText) {
visibleChars = 0
for (i in 1..message.text.length) {
visibleChars = i
delay(14)
}
} else {
visibleChars = message.text.length
}
}
val displayText = message.text.take(visibleChars)
val displayStatus = when {
animateText && visibleChars < message.text.length -> "streaming"
else -> message.status
}
Box(modifier = Modifier.fillMaxWidth(), contentAlignment = alignment) {
Column(
modifier = Modifier.fillMaxWidth(0.88f),
verticalArrangement = Arrangement.spacedBy(6.dp),
horizontalAlignment = if (message.role == MessageRole.User) Alignment.End else Alignment.Start,
) {
Text(
text = label,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Column(
modifier = Modifier
.clip(androidx.compose.foundation.shape.RoundedCornerShape(20.dp))
.background(bubbleColor)
.padding(14.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(text = displayText, style = MaterialTheme.typography.bodyLarge)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = message.createdAt,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.weight(1f),
)
if (displayStatus != null) {
StatusPill(text = displayStatus)
}
}
}
}
}
}
@@ -0,0 +1,112 @@
package cn.xiaobai.openclawapp.feature.config
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import cn.xiaobai.openclawapp.ui.HeroCard
@Composable
fun ServerConfigScreen(
baseUrl: String,
token: String,
password: String,
defaultAgent: String,
isConnecting: Boolean,
errorMessage: String?,
onBaseUrlChange: (String) -> Unit,
onTokenChange: (String) -> Unit,
onPasswordChange: (String) -> Unit,
onDefaultAgentChange: (String) -> Unit,
onConnect: () -> Unit,
) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(20.dp),
verticalArrangement = Arrangement.spacedBy(18.dp),
) {
HeroCard(
title = "连接 OpenClaw",
subtitle = "现在默认直接连接真实 BFF。地址和 token 会自动持久化,下次打开 app 可以直接恢复。",
badge = "Remote Only",
)
Card(modifier = Modifier.fillMaxWidth()) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
OutlinedTextField(
value = baseUrl,
onValueChange = onBaseUrlChange,
modifier = Modifier.fillMaxWidth(),
label = { Text("服务器地址") },
placeholder = { Text("http://192.168.31.116:8788") },
singleLine = true,
)
OutlinedTextField(
value = password,
onValueChange = onPasswordChange,
modifier = Modifier.fillMaxWidth(),
label = { Text("登录密码") },
placeholder = { Text("优先推荐填 BFF 登录密码") },
singleLine = true,
)
OutlinedTextField(
value = token,
onValueChange = onTokenChange,
modifier = Modifier.fillMaxWidth(),
label = { Text("访问令牌(可选)") },
placeholder = { Text("如果已经登录过,也可以直接填 token") },
singleLine = true,
)
OutlinedTextField(
value = defaultAgent,
onValueChange = onDefaultAgentChange,
modifier = Modifier.fillMaxWidth(),
label = { Text("默认 Agent") },
placeholder = { Text("main") },
singleLine = true,
)
}
}
if (errorMessage != null) {
Card(modifier = Modifier.fillMaxWidth()) {
Text(
text = errorMessage,
modifier = Modifier.padding(18.dp),
color = MaterialTheme.colorScheme.error,
)
}
}
Button(
onClick = onConnect,
modifier = Modifier.fillMaxWidth(),
enabled = !isConnecting,
) {
if (isConnecting) {
CircularProgressIndicator()
} else {
Text("登录并进入")
}
}
}
}
@@ -0,0 +1,217 @@
package cn.xiaobai.openclawapp.feature.sessions
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import cn.xiaobai.openclawapp.data.SessionSummary
import cn.xiaobai.openclawapp.ui.EmptyStateCard
import cn.xiaobai.openclawapp.ui.HeroCard
import cn.xiaobai.openclawapp.ui.MetricCard
import cn.xiaobai.openclawapp.ui.StatusPill
@Composable
fun SessionListScreen(
modifier: Modifier = Modifier,
sessions: List<SessionSummary>,
recentSession: SessionSummary?,
pinnedCount: Int,
isLoading: Boolean,
errorMessage: String?,
onOpenSession: (String) -> Unit,
onTogglePin: (String) -> Unit,
onRetry: () -> Unit,
) {
var query by remember { mutableStateOf("") }
val filteredSessions = sessions.filter {
query.isBlank() ||
it.title.contains(query, ignoreCase = true) ||
it.id.contains(query, ignoreCase = true) ||
it.lastMessage.contains(query, ignoreCase = true)
}
LazyColumn(
modifier = modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
item {
HeroCard(
title = "OpenClaw Mobile",
subtitle = "先把会话体验打磨得像个真正可用的 App,再接真实消息流。这样后面联调会轻松很多。",
badge = "${if (isLoading) "Syncing" else "Ready"}",
)
}
item {
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
MetricCard(title = "总会话", value = sessions.size.toString(), modifier = Modifier.weight(1f))
MetricCard(title = "已置顶", value = pinnedCount.toString(), modifier = Modifier.weight(1f))
MetricCard(title = "筛选结果", value = filteredSessions.size.toString(), modifier = Modifier.weight(1f))
}
}
if (isLoading) {
item {
Card(modifier = Modifier.fillMaxWidth()) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
CircularProgressIndicator()
Text("正在同步远程会话和状态…")
}
}
}
}
if (errorMessage != null) {
item {
Card(
modifier = Modifier.fillMaxWidth(),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text("同步失败", style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onErrorContainer)
Text(errorMessage, color = MaterialTheme.colorScheme.onErrorContainer)
Button(onClick = onRetry) {
Text("重试")
}
}
}
}
}
if (recentSession != null) {
item {
Card(
modifier = Modifier.fillMaxWidth(),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.tertiaryContainer,
),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text("最近访问", style = MaterialTheme.typography.labelLarge)
Text(recentSession.title, style = MaterialTheme.typography.titleMedium)
Text(
recentSession.lastMessage,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Button(onClick = { onOpenSession(recentSession.id) }) {
Text("继续查看")
}
}
}
}
}
item {
OutlinedTextField(
value = query,
onValueChange = { query = it },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
label = { Text("搜索会话") },
placeholder = { Text("按标题、ID 或最后一条消息搜索") },
)
}
if (filteredSessions.isEmpty() && !isLoading) {
item {
EmptyStateCard(
title = "没有匹配的会话",
subtitle = "如果你当前走的是 Remote 模式,那下一步就该检查 BFF 接口返回和 DTO 映射了。",
)
}
} else {
items(filteredSessions, key = { it.id }) { session ->
Card(
modifier = Modifier.fillMaxWidth(),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceContainerLow,
),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.clickable { onOpenSession(session.id) }
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
Text(
text = session.title,
style = MaterialTheme.typography.titleMedium,
)
if (session.isPinned) {
StatusPill(text = "置顶")
}
if (session.unreadCount > 0) {
StatusPill(text = "${session.unreadCount} 未读", highlighted = true)
}
}
Text(
text = session.id,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
StatusPill(text = session.updatedAt, highlighted = true)
}
Text(
text = session.lastMessage,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Button(onClick = { onOpenSession(session.id) }) {
Text("打开")
}
Button(onClick = { onTogglePin(session.id) }) {
Text(if (session.isPinned) "取消置顶" else "置顶")
}
}
}
}
}
}
}
}
@@ -0,0 +1,86 @@
package cn.xiaobai.openclawapp.feature.settings
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import cn.xiaobai.openclawapp.app.AppThemeMode
import cn.xiaobai.openclawapp.data.ServerConfig
import cn.xiaobai.openclawapp.ui.HeroCard
import cn.xiaobai.openclawapp.ui.LabelValueCard
import cn.xiaobai.openclawapp.ui.SelectableRowCard
@Composable
fun SettingsScreen(
modifier: Modifier = Modifier,
serverConfig: ServerConfig,
currentModel: String,
availableAgents: List<String>,
currentTheme: AppThemeMode,
onSelectAgent: (String) -> Unit,
onSelectTheme: (AppThemeMode) -> Unit,
onDisconnect: () -> Unit,
) {
LazyColumn(
modifier = modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
item {
HeroCard(
title = "连接配置",
subtitle = "现在 app 默认只走真实 BFF。这里主要管理地址、token 状态、默认 Agent 和主题。",
badge = "Settings",
)
}
item {
LabelValueCard(label = "服务器地址", value = serverConfig.baseUrl)
}
item {
LabelValueCard(label = "当前模型", value = currentModel)
}
item {
LabelValueCard(label = "访问令牌", value = if (serverConfig.token.isBlank()) "未设置" else "已持久化")
}
item {
Text("主题", style = MaterialTheme.typography.titleMedium)
}
items(AppThemeMode.entries) { theme ->
SelectableRowCard(
title = theme.label,
trailing = if (theme == currentTheme) "当前" else null,
selected = theme == currentTheme,
modifier = Modifier.clickable { onSelectTheme(theme) },
)
}
item {
Text("切换默认 Agent", style = MaterialTheme.typography.titleMedium)
}
items(availableAgents) { agent ->
SelectableRowCard(
title = agent,
trailing = if (serverConfig.defaultAgent == agent) "当前" else null,
selected = serverConfig.defaultAgent == agent,
modifier = Modifier.clickable { onSelectAgent(agent) },
)
}
item {
Button(onClick = onDisconnect, modifier = Modifier.fillMaxWidth()) {
Text("退出登录")
}
}
}
}
@@ -0,0 +1,76 @@
package cn.xiaobai.openclawapp.feature.status
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import cn.xiaobai.openclawapp.data.ServerStatus
import cn.xiaobai.openclawapp.ui.HeroCard
import cn.xiaobai.openclawapp.ui.LabelValueCard
import cn.xiaobai.openclawapp.ui.MetricCard
@Composable
fun StatusScreen(
modifier: Modifier = Modifier,
status: ServerStatus,
) {
LazyColumn(
modifier = modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
item {
HeroCard(
title = if (status.online) "链路正常" else "连接异常",
subtitle = "状态页后面会扩展成 OpenClaw、BFF、消息流和推送链路的统一面板。现在先把最关键的几个信号放清楚。",
badge = if (status.online) "Online" else "Offline",
)
}
item {
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
MetricCard(
title = "连接",
value = if (status.online) "在线" else "离线",
modifier = Modifier.weight(1f),
)
MetricCard(
title = "默认 Agent",
value = status.defaultAgent,
modifier = Modifier.weight(1f),
)
}
}
item {
LabelValueCard(
label = "OpenClaw 版本",
value = status.openClawVersion,
)
}
item {
LabelValueCard(
label = "当前模型",
value = status.currentModel,
supporting = "后续这里可以增加 provider 状态、模型切换、额度与响应时延。",
)
}
item {
LabelValueCard(
label = "最后更新时间",
value = status.updatedAt,
)
}
item {
Text(
"状态页最忌讳一上来塞满技术细节。先把在线性、模型和 agent 放稳,后面再扩展统计和事件流。",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
@@ -0,0 +1,83 @@
package cn.xiaobai.openclawapp.network
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.http.contentType
import io.ktor.http.encodeURLPathPart
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json
class MobileGatewayApi(
private val baseUrl: String,
private val tokenProvider: () -> String,
private val client: HttpClient = createDefaultHttpClient(),
) {
suspend fun login(password: String): LoginResponseDto {
return client.post("${baseUrl.trimEnd('/')}/api/auth/login") {
contentType(ContentType.Application.Json)
setBody(LoginRequestDto(password = password))
}.body()
}
suspend fun getStatus(): StatusDto {
return client.get("${baseUrl.trimEnd('/')}/api/status") {
authHeader()
}.body()
}
suspend fun getSessions(): List<SessionSummaryDto> {
return client.get("${baseUrl.trimEnd('/')}/api/sessions") {
authHeader()
}.body()
}
suspend fun getMessages(sessionId: String): List<ChatMessageDto> {
val encodedId = sessionId.encodeURLPathPart()
return client.get("${baseUrl.trimEnd('/')}/api/sessions/$encodedId/messages") {
authHeader()
}.body()
}
suspend fun sendMessage(sessionId: String, message: String): SendMessageResponseDto {
val encodedId = sessionId.encodeURLPathPart()
return client.post("${baseUrl.trimEnd('/')}/api/sessions/$encodedId/messages") {
authHeader()
contentType(ContentType.Application.Json)
setBody(SendMessageRequestDto(message = message))
}.body()
}
suspend fun getAgents(): List<AgentDto> {
return client.get("${baseUrl.trimEnd('/')}/api/agents") {
authHeader()
}.body()
}
private fun io.ktor.client.request.HttpRequestBuilder.authHeader() {
val token = tokenProvider().trim()
if (token.isNotBlank()) {
header(HttpHeaders.Authorization, "Bearer $token")
}
}
}
fun createDefaultHttpClient(): HttpClient {
return HttpClient {
install(ContentNegotiation) {
json(
Json {
ignoreUnknownKeys = true
explicitNulls = false
isLenient = true
}
)
}
}
}
@@ -0,0 +1,57 @@
package cn.xiaobai.openclawapp.network
import kotlinx.serialization.Serializable
@Serializable
data class LoginRequestDto(
val password: String,
)
@Serializable
data class LoginResponseDto(
val token: String,
val user: Map<String, String> = emptyMap(),
)
@Serializable
data class StatusDto(
val online: Boolean,
val openClawVersion: String,
val currentModel: String,
val defaultAgent: String,
val updatedAt: String,
)
@Serializable
data class SessionSummaryDto(
val id: String,
val title: String,
val lastMessage: String? = null,
val updatedAt: String,
)
@Serializable
data class ChatMessageDto(
val id: String,
val role: String,
val text: String,
val createdAt: String,
val status: String? = null,
)
@Serializable
data class SendMessageRequestDto(
val message: String,
)
@Serializable
data class SendMessageResponseDto(
val accepted: Boolean,
val messageId: String? = null,
)
@Serializable
data class AgentDto(
val id: String,
val name: String,
)
@@ -0,0 +1,18 @@
package cn.xiaobai.openclawapp.network
import kotlinx.serialization.Serializable
@Serializable
data class SessionSnapshotEventDto(
val messages: List<ChatMessageDto> = emptyList(),
)
@Serializable
data class MessageDeltaEventDto(
val id: String,
val delta: String,
val fullText: String,
val role: String,
val createdAt: String,
val status: String? = null,
)
@@ -0,0 +1,72 @@
package cn.xiaobai.openclawapp.network
import io.ktor.client.HttpClient
import io.ktor.client.request.header
import io.ktor.client.request.prepareGet
import io.ktor.client.statement.bodyAsChannel
import io.ktor.http.HttpHeaders
import io.ktor.http.isSuccess
import io.ktor.utils.io.readUTF8Line
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.serialization.json.Json
sealed interface SessionStreamEvent {
data class Snapshot(val payload: SessionSnapshotEventDto) : SessionStreamEvent
data class Delta(val payload: MessageDeltaEventDto) : SessionStreamEvent
data class Completed(val payload: ChatMessageDto) : SessionStreamEvent
}
class SseSessionStream(
private val client: HttpClient,
private val baseUrl: String,
private val tokenProvider: () -> String,
) {
private val json = Json { ignoreUnknownKeys = true }
fun connect(sessionId: String): Flow<SessionStreamEvent> = flow {
val url = "${baseUrl.trimEnd('/')}/api/sessions/${encodePath(sessionId)}/stream"
client.prepareGet(url) {
val token = tokenProvider().trim()
if (token.isNotBlank()) {
header(HttpHeaders.Authorization, "Bearer $token")
}
}.execute { response ->
if (!response.status.isSuccess()) {
throw IllegalStateException("SSE connect failed: HTTP ${response.status.value}")
}
val channel = response.bodyAsChannel()
var currentEvent: String? = null
val dataLines = mutableListOf<String>()
while (!channel.isClosedForRead) {
val line = channel.readUTF8Line() ?: break
when {
line.startsWith("event:") -> currentEvent = line.removePrefix("event:").trim()
line.startsWith("data:") -> dataLines += line.removePrefix("data:").trim()
line.isBlank() -> {
val raw = dataLines.joinToString("\n")
when (currentEvent) {
"session.snapshot" -> runCatching {
json.decodeFromString<SessionSnapshotEventDto>(raw)
}.onSuccess { dto -> emit(SessionStreamEvent.Snapshot(dto)) }
"message.delta" -> runCatching {
json.decodeFromString<MessageDeltaEventDto>(raw)
}.onSuccess { dto -> emit(SessionStreamEvent.Delta(dto)) }
"message.completed" -> runCatching {
json.decodeFromString<ChatMessageDto>(raw)
}.onSuccess { dto -> emit(SessionStreamEvent.Completed(dto)) }
}
currentEvent = null
dataLines.clear()
}
}
}
}
}
private fun encodePath(value: String): String = value.replace(":", "%3A")
}
@@ -0,0 +1,245 @@
package cn.xiaobai.openclawapp.ui
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
@Composable
fun SectionHeader(
title: String,
subtitle: String? = null,
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Text(title, style = MaterialTheme.typography.headlineMedium)
if (!subtitle.isNullOrBlank()) {
Text(
subtitle,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
@Composable
fun HeroCard(
title: String,
subtitle: String,
badge: String? = null,
modifier: Modifier = Modifier,
) {
Card(
modifier = modifier.fillMaxWidth(),
shape = RoundedCornerShape(24.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
if (!badge.isNullOrBlank()) {
StatusPill(text = badge, highlighted = true)
}
Text(
title,
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.onPrimaryContainer,
)
Text(
subtitle,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.85f),
)
}
}
}
@Composable
fun LabelValueCard(
label: String,
value: String,
modifier: Modifier = Modifier,
supporting: String? = null,
) {
Card(
modifier = modifier.fillMaxWidth(),
shape = RoundedCornerShape(20.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceContainerLow,
),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
Text(
label,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(value, style = MaterialTheme.typography.titleMedium)
if (!supporting.isNullOrBlank()) {
Text(
supporting,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
@Composable
fun MetricCard(
title: String,
value: String,
modifier: Modifier = Modifier,
) {
Card(
modifier = modifier,
shape = RoundedCornerShape(18.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
),
) {
Column(
modifier = Modifier.padding(14.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Text(
text = title,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.75f),
)
Text(
text = value,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSecondaryContainer,
)
}
}
}
@Composable
fun StatusPill(
text: String,
modifier: Modifier = Modifier,
highlighted: Boolean = false,
) {
val containerColor = if (highlighted) {
MaterialTheme.colorScheme.primaryContainer
} else {
MaterialTheme.colorScheme.surfaceVariant
}
val textColor = if (highlighted) {
MaterialTheme.colorScheme.onPrimaryContainer
} else {
MaterialTheme.colorScheme.onSurfaceVariant
}
Box(
modifier = modifier
.clip(CircleShape)
.background(containerColor)
.padding(horizontal = 10.dp, vertical = 6.dp),
contentAlignment = Alignment.Center,
) {
Text(text = text, style = MaterialTheme.typography.labelMedium, color = textColor)
}
}
@Composable
fun SelectableRowCard(
title: String,
trailing: String? = null,
selected: Boolean = false,
modifier: Modifier = Modifier,
) {
Card(
modifier = modifier.fillMaxWidth(),
shape = RoundedCornerShape(18.dp),
colors = CardDefaults.cardColors(
containerColor = if (selected) {
MaterialTheme.colorScheme.primaryContainer
} else {
MaterialTheme.colorScheme.surfaceContainerLow
}
),
border = BorderStroke(
width = 1.dp,
color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outlineVariant,
),
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 14.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(
title,
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.weight(1f),
)
if (!trailing.isNullOrBlank()) {
StatusPill(text = trailing, highlighted = selected)
}
}
}
}
@Composable
fun EmptyStateCard(
title: String,
subtitle: String,
modifier: Modifier = Modifier,
) {
Card(
modifier = modifier.fillMaxWidth(),
shape = RoundedCornerShape(22.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceContainerLow,
),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(20.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(title, style = MaterialTheme.typography.titleMedium)
Text(
subtitle,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
@@ -0,0 +1,68 @@
package cn.xiaobai.openclawapp.ui
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import cn.xiaobai.openclawapp.app.AppThemeMode
private val OpenClawLightColors = lightColorScheme(
primary = Color(0xFF2D5BFF),
onPrimary = Color.White,
primaryContainer = Color(0xFFDDE4FF),
onPrimaryContainer = Color(0xFF00174A),
secondary = Color(0xFF65558F),
onSecondary = Color.White,
secondaryContainer = Color(0xFFE9DDFF),
onSecondaryContainer = Color(0xFF211047),
tertiary = Color(0xFF006B5E),
onTertiary = Color.White,
tertiaryContainer = Color(0xFF74F8E1),
onTertiaryContainer = Color(0xFF00201B),
background = Color(0xFFF7F9FF),
onBackground = Color(0xFF171C2B),
surface = Color(0xFFF7F9FF),
onSurface = Color(0xFF171C2B),
surfaceVariant = Color(0xFFE1E3EC),
onSurfaceVariant = Color(0xFF454A58),
outlineVariant = Color(0xFFC5C7D0),
)
private val OpenClawDarkColors = darkColorScheme(
primary = Color(0xFFB8C4FF),
onPrimary = Color(0xFF002A78),
primaryContainer = Color(0xFF003DAA),
onPrimaryContainer = Color(0xFFDDE4FF),
secondary = Color(0xFFD0BCFF),
onSecondary = Color(0xFF36275F),
secondaryContainer = Color(0xFF4D3E76),
onSecondaryContainer = Color(0xFFE9DDFF),
tertiary = Color(0xFF54DBC5),
onTertiary = Color(0xFF003730),
tertiaryContainer = Color(0xFF005047),
onTertiaryContainer = Color(0xFF74F8E1),
background = Color(0xFF0F1117),
onBackground = Color(0xFFE5EAF6),
surface = Color(0xFF0F1117),
onSurface = Color(0xFFE5EAF6),
surfaceVariant = Color(0xFF2C313F),
onSurfaceVariant = Color(0xFFC5C7D0),
outlineVariant = Color(0xFF454A58),
)
@Composable
fun OpenClawTheme(
themeMode: AppThemeMode,
content: @Composable () -> Unit,
) {
val colorScheme = when (themeMode) {
AppThemeMode.Light -> OpenClawLightColors
AppThemeMode.Dark -> OpenClawDarkColors
}
MaterialTheme(
colorScheme = colorScheme,
content = content,
)
}
+498
View File
@@ -0,0 +1,498 @@
# OpenClawApp 架构规划(V1)
## 1. 目标
OpenClawApp 不是把 OpenClaw 整体搬到手机上运行,而是做一个 **面向移动端的 OpenClaw 客户端**。
手机端负责:
- 登录与设备绑定
- 会话列表浏览
- 聊天消息收发
- 查看 Agent / Session / Task 状态
- 接收推送通知
- 触发常用控制动作(切换模型、切换 agent、查看状态)
OpenClaw 服务端继续负责:
- Agent 运行
- Tool 调用
- Session 管理
- Subagent / Cron / ACP 等能力
- 模型接入与执行
---
## 2. 核心原则
### 2.1 不直接把 App 做成 OpenClaw 插件
V1 不采用“移动端 App 作为 OpenClaw 渠道插件”的方式接入。
原因:
1. 插件/渠道更适合“消息入口”,不适合承载完整移动端控制台能力。
2. App 后续需要会话列表、状态页、推送、权限控制、文件上传等,这些超出了普通 channel/plugin 的舒适边界。
3. 手机端不应该直接暴露 OpenClaw 内部权限与 provider key。
### 2.2 采用三层架构
推荐架构:
```text
OpenClawApp (Android/iOS/Web)
↓
BFF / Mobile Gateway(自建中转服务)
↓
OpenClaw Gateway / Session Runtime
```
其中:
- **App**:UI + 本地状态 + 用户交互
- **BFF**:鉴权、接口适配、消息转发、推送、聚合查询
- **OpenClaw**:真正的智能体与工具执行系统
---
## 3. 系统分层设计
## 3.1 移动端 App 层
职责:
- 管理服务器配置
- 登录态管理
- 会话列表与消息页展示
- 流式消息渲染
- Agent/模型状态展示
- 本地缓存与离线展示
- 触发推送注册
建议模块:
- `app/core`:配置、常量、环境
- `app/network`:请求封装、鉴权、SSE/WebSocket
- `app/data`:Repository、DTO、缓存模型
- `app/features/sessions`:会话列表
- `app/features/chat`:聊天页
- `app/features/settings`:设置页
- `app/features/status`:运行状态页
- `app/ui`:主题、导航、组件
---
## 3.2 BFF(Backend For Frontend)层
BFF 是整个移动端方案的关键。
职责:
- App 用户鉴权(登录 token / 设备绑定)
- 对 OpenClaw 内部接口做二次封装
- 提供稳定、面向移动端的 API
- 统一消息格式
- 提供流式消息接口(SSE 或 WebSocket)
- 聚合状态(当前模型、当前 agent、session 列表)
- 对接推送服务(FCM / APNs)
- 限流、审计、权限隔离
BFF **不承载 AI 能力**,只做接入层和移动端适配层。
---
## 3.3 OpenClaw 层
保留现有 OpenClaw 能力,BFF 通过以下方式与它对接:
- 查询 session 列表
- 查询 session 历史消息
- 给 session 发消息
- 查询当前模型与 agent 状态
- 查询任务、subagent、cron 执行结果
- 订阅/轮询新消息与执行完成事件
如果后续 OpenClaw 暴露更适合移动端的扩展接口,再考虑写服务端插件,但 **不是 V1 前提**。
---
## 4. 推荐接入方式
## 4.1 V1 接入模式
### App → BFF
统一走 HTTPS API。
- 普通查询:REST
- 实时消息:优先 SSE,其次 WebSocket
- 文件上传:multipart/form-data
### BFF → OpenClaw
优先级:
1. 复用 OpenClaw 已有稳定接口
2. 如现有接口不适合,BFF 做适配/转译
3. 必要时再补一个 OpenClaw 服务端扩展
---
## 4.2 为什么优先 SSE
聊天流式输出场景下,SSE 比 WebSocket 更轻:
- 服务端实现成本低
- 前端接入简单
- 更适合“单向持续推流”的消息场景
- 首版排障更容易
WebSocket 适合后续做:
- typing 状态
- 多事件总线
- 实时任务控制
- 双向推送控制流
**结论:V1 聊天流优先 SSE。**
---
## 5. 安全设计
## 5.1 不在 App 里存 OpenClaw 主密钥
App 不能直接持有:
- OpenClaw provider API keys
- 高权限控制密钥
- 服务器内部凭证
App 只持有:
- App 登录 token
- 短期 refresh token(如果需要)
- 当前用户配置
---
## 5.2 BFF 负责权限隔离
BFF 负责:
- 鉴权
- 用户/设备绑定
- 可访问 session 范围限制
- 关键动作审计
- 限流
- 推送 token 管理
---
## 5.3 建议的部署要求
- BFF 走 HTTPS
- 服务器侧保存 OpenClaw 连接凭据
- 关键操作写日志
- 支持单用户模式(V1 可先只服务你自己)
---
## 6. V1 功能范围(MVP)
V1 只做最小可用闭环:
### 6.1 必做
1. 服务器配置页
- BFF 地址
- 登录 token / 密码
- 默认 agent
2. 会话列表页
- session 名称
- 最后一条消息
- 更新时间
3. 聊天页
- 查看历史消息
- 发送文本消息
- 接收流式回复
- 展示 tool/status 占位信息
4. 设置页
- 查看当前连接状态
- 查看当前模型
- 切换默认 agent
5. 基础状态页
- OpenClaw 在线状态
- 当前模型
- 最近活跃时间
---
### 6.2 暂不做
V1 暂不做:
- 完整文件管理
- 工具调用全过程可视化
- 多账号体系
- 复杂权限模型
- 本地运行 agent
- 离线发送队列
- 复杂群聊/多渠道能力
---
## 7. 推荐 API 设计(BFF 对 App)
## 7.1 认证
### `POST /api/auth/login`
请求:
```json
{
"server": "https://your-bff.example.com",
"password": "***"
}
```
响应:
```json
{
"token": "...",
"user": {
"id": "xiaobai",
"name": "xiaobai"
}
}
```
---
## 7.2 状态
### `GET /api/status`
返回:
```json
{
"online": true,
"openclawVersion": "2026.x",
"currentModel": "cliproxy/gpt-5.4",
"defaultAgent": "main",
"updatedAt": "2026-03-07T00:00:00+08:00"
}
```
---
## 7.3 会话列表
### `GET /api/sessions`
返回:
```json
[
{
"id": "agent:main:main",
"title": "主会话",
"lastMessage": "你好",
"updatedAt": "2026-03-07T00:00:00+08:00"
}
]
```
---
## 7.4 消息历史
### `GET /api/sessions/{id}/messages?cursor=...`
返回标准消息列表,支持分页。
---
## 7.5 发送消息
### `POST /api/sessions/{id}/messages`
请求:
```json
{
"message": "你好"
}
```
响应:
```json
{
"accepted": true,
"messageId": "msg_xxx"
}
```
---
## 7.6 流式消息
### `GET /api/sessions/{id}/stream`
SSE 事件建议:
- `message.delta`
- `message.completed`
- `tool.started`
- `tool.completed`
- `session.updated`
- `error`
---
## 7.7 Agent / 模型
### `GET /api/agents`
### `POST /api/agents/default`
### `GET /api/models/current`
V1 只需要“查询当前模型”和“切换默认 agent”,模型切换可以先不开放。
---
## 8. 客户端数据模型建议
## 8.1 Session
```kotlin
data class SessionSummary(
val id: String,
val title: String,
val lastMessage: String?,
val updatedAt: String,
)
```
## 8.2 Message
```kotlin
data class ChatMessage(
val id: String,
val role: String,
val text: String,
val createdAt: String,
val status: String? = null,
)
```
## 8.3 Status
```kotlin
data class ServerStatus(
val online: Boolean,
val openClawVersion: String,
val currentModel: String,
val defaultAgent: String,
val updatedAt: String,
)
```
---
## 9. UI 结构建议
V1 页面:
1. `ServerConfigScreen`
2. `SessionListScreen`
3. `ChatScreen`
4. `StatusScreen`
5. `SettingsScreen`
导航建议:
- 首次启动:ServerConfig
- 登录后:首页为 SessionList
- 点击 session 进入 Chat
- 底部 tab:Sessions / Status / Settings
---
## 10. 迭代计划
## Phase 1:App 骨架 + Mock 数据
目标:先把 UI 和状态流跑通。
包括:
- 项目目录重构
- 页面路由
- 主题与基础组件
- 假数据仓库
- 会话列表页
- 聊天页
- 设置页
- 状态页
---
## Phase 2:BFF 定义与联调
目标:App 不再吃 Mock 数据,开始走真实接口。
包括:
- 明确 BFF 技术栈
- 定义 API contract
- App 接入真实接口
- SSE 消息流接入
- 基础错误处理
---
## Phase 3:通知与增强
包括:
- 推送通知
- 文件上传
- tool 状态展示
- session 搜索 / pin
- 更完整的状态页
---
## 11. 当前决定
当前项目明确采用以下方向:
1. **不把移动端直接做成 OpenClaw 插件/渠道**
2. **采用 App + BFF + OpenClaw 三层架构**
3. **V1 先做 App 骨架与 Mock 数据**
4. **后续再接真实 BFF 与 OpenClaw**
---
## 12. 下一步
下一步直接进入实现:
1. 建立 App 目录结构
2. 搭建导航
3. 实现以下页面的初版 UI:
- SessionList
- Chat
- Status
- Settings
4. 使用 Mock Repository 跑通完整流程
这一步完成后,再进入 BFF 对接。
+10
View File
@@ -10,3 +10,13 @@ org.gradle.caching=true
#Android #Android
android.nonTransitiveRClass=true android.nonTransitiveRClass=true
android.useAndroidX=true android.useAndroidX=true
android.defaults.buildfeatures.resvalues=true
android.sdk.defaultTargetSdkToCompileSdkIfUnset=false
android.enableAppCompileTimeRClass=false
android.usesSdkInManifest.disallowed=false
android.uniquePackageNames=false
android.dependency.useConstraints=true
android.r8.strictFullModeForKeepRules=false
android.r8.optimizedResourceShrinking=false
android.builtInKotlin=false
android.newDsl=false
+13
View File
@@ -0,0 +1,13 @@
#This file is generated by updateDaemonJvm
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/29ee363f71d060405f729a8f1b7f7aef/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/67a0fee3c4236b6397dcbe8575ca2011/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/29ee363f71d060405f729a8f1b7f7aef/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/67a0fee3c4236b6397dcbe8575ca2011/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/10fc3bf1ee0001078a473afe6e43cfdb/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/658299a896470fbb3103ba3a430ee227/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/29ee363f71d060405f729a8f1b7f7aef/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/ecd23fd7707c683afbcd6052998cb6a9/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/fddf6293b7b991bd01fa68e5b2eab7ec/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/ac151d55def6b6a9a159dc4cb4642851/redirect
toolchainVendor=JETBRAINS
toolchainVersion=21
+13 -1
View File
@@ -1,5 +1,5 @@
[versions] [versions]
agp = "8.11.2" agp = "9.1.0"
android-compileSdk = "36" android-compileSdk = "36"
android-minSdk = "33" android-minSdk = "33"
android-targetSdk = "36" android-targetSdk = "36"
@@ -13,6 +13,9 @@ composeMultiplatform = "1.10.0"
junit = "4.13.2" junit = "4.13.2"
kotlin = "2.3.0" kotlin = "2.3.0"
material3 = "1.10.0-alpha05" material3 = "1.10.0-alpha05"
ktor = "3.3.0"
kotlinxSerializationJson = "1.9.0"
multiplatformSettings = "1.2.0"
[libraries] [libraries]
kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" } kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" }
@@ -32,6 +35,14 @@ compose-material3 = { module = "org.jetbrains.compose.material3:material3", vers
compose-ui = { module = "org.jetbrains.compose.ui:ui", version.ref = "composeMultiplatform" } compose-ui = { module = "org.jetbrains.compose.ui:ui", version.ref = "composeMultiplatform" }
compose-components-resources = { module = "org.jetbrains.compose.components:components-resources", version.ref = "composeMultiplatform" } compose-components-resources = { module = "org.jetbrains.compose.components:components-resources", version.ref = "composeMultiplatform" }
compose-uiToolingPreview = { module = "org.jetbrains.compose.ui:ui-tooling-preview", version.ref = "composeMultiplatform" } compose-uiToolingPreview = { module = "org.jetbrains.compose.ui:ui-tooling-preview", version.ref = "composeMultiplatform" }
ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
ktor-client-contentNegotiation = { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktor" }
ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" }
ktor-client-darwin = { module = "io.ktor:ktor-client-darwin", version.ref = "ktor" }
ktor-client-js = { module = "io.ktor:ktor-client-js", version.ref = "ktor" }
ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }
kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinxSerializationJson" }
multiplatform-settings-no-arg = { module = "com.russhwolf:multiplatform-settings-no-arg", version.ref = "multiplatformSettings" }
[plugins] [plugins]
androidApplication = { id = "com.android.application", version.ref = "agp" } androidApplication = { id = "com.android.application", version.ref = "agp" }
@@ -39,3 +50,4 @@ androidLibrary = { id = "com.android.library", version.ref = "agp" }
composeMultiplatform = { id = "org.jetbrains.compose", version.ref = "composeMultiplatform" } composeMultiplatform = { id = "org.jetbrains.compose", version.ref = "composeMultiplatform" }
composeCompiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } composeCompiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
kotlinxSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
+3
View File
@@ -14,6 +14,9 @@ pluginManagement {
gradlePluginPortal() gradlePluginPortal()
} }
} }
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.10.0"
}
dependencyResolutionManagement { dependencyResolutionManagement {
repositories { repositories {