feat(android): Compose client with encrypted settings, WebSocket streaming chat and session list
This commit is contained in:
parent
8896bdc963
commit
1c5f7f582f
19 changed files with 865 additions and 0 deletions
|
|
@ -0,0 +1,7 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Debug builds only: allow plain http/ws for local development (emulator 10.0.2.2, LAN). -->
|
||||
<network-security-config>
|
||||
<base-config cleartextTrafficPermitted="true">
|
||||
<trust-anchors><certificates src="system" /></trust-anchors>
|
||||
</base-config>
|
||||
</network-security-config>
|
||||
20
android/app/src/main/AndroidManifest.xml
Normal file
20
android/app/src/main/AndroidManifest.xml
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:label="@string/app_name"
|
||||
android:icon="@android:drawable/sym_def_app_icon"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:theme="@android:style/Theme.Material.NoActionBar">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
</manifest>
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
package dev.openclaw.client
|
||||
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import dev.openclaw.client.ui.ChatScreen
|
||||
import dev.openclaw.client.ui.ChatViewModel
|
||||
import dev.openclaw.client.ui.SessionsScreen
|
||||
import dev.openclaw.client.ui.SettingsScreen
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
setContent {
|
||||
MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme()) {
|
||||
Surface {
|
||||
val vm: ChatViewModel = viewModel()
|
||||
val state by vm.state.collectAsStateWithLifecycle()
|
||||
val nav = rememberNavController()
|
||||
NavHost(nav, startDestination = if (state.settings.isConfigured) "chat" else "settings") {
|
||||
composable("chat") {
|
||||
ChatScreen(vm, state, onSessions = { nav.navigate("sessions") }, onSettings = { nav.navigate("settings") })
|
||||
}
|
||||
composable("sessions") {
|
||||
SessionsScreen(vm, state, onBack = { nav.popBackStack() }, onOpen = { nav.popBackStack() })
|
||||
}
|
||||
composable("settings") {
|
||||
SettingsScreen(vm, state, onBack = {
|
||||
if (!nav.popBackStack()) nav.navigate("chat") { popUpTo("settings") { inclusive = true } }
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,121 @@
|
|||
package dev.openclaw.client.ui
|
||||
|
||||
import android.app.Application
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dev.openclaw.client.data.OpenClawApi
|
||||
import dev.openclaw.client.data.ServerSettings
|
||||
import dev.openclaw.client.data.Session
|
||||
import dev.openclaw.client.data.SettingsStore
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
data class ChatLine(val role: String, val text: String, val tool: String = "")
|
||||
|
||||
data class UiState(
|
||||
val settings: ServerSettings = ServerSettings(),
|
||||
val sessionId: String? = null,
|
||||
val lines: List<ChatLine> = emptyList(),
|
||||
val sessions: List<Session> = emptyList(),
|
||||
val busy: Boolean = false,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val store = SettingsStore(app)
|
||||
private val _state = MutableStateFlow(UiState(settings = store.load()))
|
||||
val state: StateFlow<UiState> = _state
|
||||
private var job: Job? = null
|
||||
|
||||
private fun api() = OpenClawApi(_state.value.settings)
|
||||
|
||||
fun saveSettings(s: ServerSettings) {
|
||||
store.save(s)
|
||||
_state.update { it.copy(settings = store.load(), error = null) }
|
||||
}
|
||||
|
||||
fun testConnection(s: ServerSettings, onResult: (String) -> Unit) = viewModelScope.launch {
|
||||
val msg = runCatching {
|
||||
OpenClawApi(s).sessions(); "Verbindung OK"
|
||||
}.getOrElse { "Fehler: ${it.message}" }
|
||||
onResult(msg)
|
||||
}
|
||||
|
||||
fun newChat() {
|
||||
job?.cancel()
|
||||
_state.update { it.copy(sessionId = null, lines = emptyList(), busy = false, error = null) }
|
||||
}
|
||||
|
||||
fun dismissError() = _state.update { it.copy(error = null) }
|
||||
|
||||
fun refreshSessions() = viewModelScope.launch {
|
||||
runCatching { api().sessions() }
|
||||
.onSuccess { list -> _state.update { it.copy(sessions = list) } }
|
||||
.onFailure { e -> _state.update { it.copy(error = e.message) } }
|
||||
}
|
||||
|
||||
fun openSession(id: String) = viewModelScope.launch {
|
||||
job?.cancel()
|
||||
runCatching { api().messages(id) }
|
||||
.onSuccess { msgs ->
|
||||
val lines = msgs.flatMap { m ->
|
||||
when (m.role) {
|
||||
"user" -> listOf(ChatLine("user", m.content))
|
||||
"assistant" -> buildList {
|
||||
if (m.content.isNotBlank()) add(ChatLine("assistant", m.content))
|
||||
m.toolCalls.forEach { add(ChatLine("tool", it.arguments, it.name)) }
|
||||
}
|
||||
else -> emptyList()
|
||||
}
|
||||
}
|
||||
_state.update { it.copy(sessionId = id, lines = lines, busy = false) }
|
||||
}
|
||||
.onFailure { e -> _state.update { it.copy(error = e.message) } }
|
||||
}
|
||||
|
||||
fun deleteSession(id: String) = viewModelScope.launch {
|
||||
runCatching { api().deleteSession(id) }
|
||||
.onSuccess {
|
||||
if (_state.value.sessionId == id) newChat()
|
||||
refreshSessions()
|
||||
}
|
||||
.onFailure { e -> _state.update { it.copy(error = e.message) } }
|
||||
}
|
||||
|
||||
fun send(text: String) {
|
||||
val t = text.trim()
|
||||
if (t.isEmpty() || _state.value.busy) return
|
||||
_state.update { it.copy(lines = it.lines + ChatLine("user", t) + ChatLine("assistant", ""), busy = true, error = null) }
|
||||
job = viewModelScope.launch {
|
||||
api().stream(_state.value.sessionId, t).collect { ev ->
|
||||
when (ev.type) {
|
||||
"session" -> _state.update { it.copy(sessionId = ev.sessionId) }
|
||||
"delta" -> appendToLast(ev.text)
|
||||
"tool_call" -> _state.update {
|
||||
// keep a fresh assistant bubble after the tool line for the follow-up answer
|
||||
val base = if (it.lines.lastOrNull()?.let { l -> l.role == "assistant" && l.text.isEmpty() } == true) it.lines.dropLast(1) else it.lines
|
||||
it.copy(lines = base + ChatLine("tool", ev.args, ev.tool) + ChatLine("assistant", ""))
|
||||
}
|
||||
"done" -> _state.update { s ->
|
||||
s.copy(busy = false, lines = s.lines.filterNot { it.role == "assistant" && it.text.isEmpty() })
|
||||
}
|
||||
"error" -> _state.update { s ->
|
||||
s.copy(busy = false, error = ev.text, lines = s.lines.filterNot { it.role == "assistant" && it.text.isEmpty() })
|
||||
}
|
||||
}
|
||||
}
|
||||
_state.update { it.copy(busy = false) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun appendToLast(delta: String) = _state.update { s ->
|
||||
val lines = s.lines.toMutableList()
|
||||
val last = lines.lastOrNull()
|
||||
if (last != null && last.role == "assistant") lines[lines.lastIndex] = last.copy(text = last.text + delta)
|
||||
else lines += ChatLine("assistant", delta)
|
||||
s.copy(lines = lines)
|
||||
}
|
||||
}
|
||||
163
android/app/src/main/java/dev/openclaw/client/ui/Screens.kt
Normal file
163
android/app/src/main/java/dev/openclaw/client/ui/Screens.kt
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
package dev.openclaw.client.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.List
|
||||
import androidx.compose.material.icons.automirrored.filled.Send
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Build
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import dev.openclaw.client.data.OpenClawApi
|
||||
import dev.openclaw.client.data.ServerSettings
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ChatScreen(vm: ChatViewModel, state: UiState, onSessions: () -> Unit, onSettings: () -> Unit) {
|
||||
var input by remember { mutableStateOf("") }
|
||||
val listState = rememberLazyListState()
|
||||
LaunchedEffect(state.lines.size, state.lines.lastOrNull()?.text?.length) {
|
||||
if (state.lines.isNotEmpty()) listState.animateScrollToItem(state.lines.lastIndex)
|
||||
}
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("OpenClaw") },
|
||||
navigationIcon = { IconButton(onClick = onSessions) { Icon(Icons.AutoMirrored.Filled.List, "Sessions") } },
|
||||
actions = {
|
||||
IconButton(onClick = vm::newChat) { Icon(Icons.Filled.Add, "Neuer Chat") }
|
||||
IconButton(onClick = onSettings) { Icon(Icons.Filled.Settings, "Einstellungen") }
|
||||
},
|
||||
)
|
||||
},
|
||||
) { pad ->
|
||||
Column(Modifier.padding(pad).fillMaxSize().imePadding()) {
|
||||
if (!state.settings.isConfigured) {
|
||||
Card(Modifier.padding(12.dp).fillMaxWidth().clickable(onClick = onSettings)) {
|
||||
Text("Bitte zuerst Server-URL und Token in den Einstellungen eintragen.", Modifier.padding(16.dp))
|
||||
}
|
||||
}
|
||||
state.error?.let {
|
||||
Card(
|
||||
Modifier.padding(horizontal = 12.dp, vertical = 4.dp).fillMaxWidth().clickable(onClick = vm::dismissError),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer),
|
||||
) { Text(it, Modifier.padding(12.dp)) }
|
||||
}
|
||||
LazyColumn(Modifier.weight(1f).fillMaxWidth(), state = listState, contentPadding = PaddingValues(12.dp)) {
|
||||
itemsIndexed(state.lines) { _, line -> Bubble(line) }
|
||||
if (state.busy) item { LinearProgressIndicator(Modifier.fillMaxWidth().padding(top = 8.dp)) }
|
||||
}
|
||||
Row(Modifier.fillMaxWidth().padding(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedTextField(
|
||||
value = input, onValueChange = { input = it }, modifier = Modifier.weight(1f),
|
||||
placeholder = { Text("Nachricht…") }, maxLines = 5,
|
||||
enabled = state.settings.isConfigured,
|
||||
)
|
||||
IconButton(
|
||||
onClick = { vm.send(input); input = "" },
|
||||
enabled = !state.busy && input.isNotBlank() && state.settings.isConfigured,
|
||||
) { Icon(Icons.AutoMirrored.Filled.Send, "Senden") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Bubble(line: ChatLine) {
|
||||
val isUser = line.role == "user"
|
||||
if (line.role == "tool") {
|
||||
Row(Modifier.fillMaxWidth().padding(vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Build, null, Modifier.size(14.dp), tint = MaterialTheme.colorScheme.outline)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("${line.tool}(${line.text.take(120)})", style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = FontFamily.Monospace, color = MaterialTheme.colorScheme.outline)
|
||||
}
|
||||
return
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().padding(vertical = 4.dp), contentAlignment = if (isUser) Alignment.CenterEnd else Alignment.CenterStart) {
|
||||
Text(
|
||||
line.text.ifEmpty { "…" },
|
||||
Modifier.widthIn(max = 320.dp)
|
||||
.background(
|
||||
if (isUser) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant,
|
||||
RoundedCornerShape(14.dp),
|
||||
).padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun SessionsScreen(vm: ChatViewModel, state: UiState, onBack: () -> Unit, onOpen: () -> Unit) {
|
||||
LaunchedEffect(Unit) { vm.refreshSessions() }
|
||||
Scaffold(topBar = {
|
||||
TopAppBar(title = { Text("Sessions") },
|
||||
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Zurück") } })
|
||||
}) { pad ->
|
||||
if (state.sessions.isEmpty()) {
|
||||
Box(Modifier.padding(pad).fillMaxSize(), contentAlignment = Alignment.Center) { Text(state.error ?: "Noch keine Sessions") }
|
||||
}
|
||||
LazyColumn(Modifier.padding(pad).fillMaxSize()) {
|
||||
items(state.sessions, key = { it.id }) { s ->
|
||||
ListItem(
|
||||
headlineContent = { Text(s.title.ifBlank { "(ohne Titel)" }, maxLines = 1) },
|
||||
supportingContent = { Text(s.updatedAt.take(16).replace('T', ' ') + " UTC") },
|
||||
trailingContent = { IconButton(onClick = { vm.deleteSession(s.id) }) { Icon(Icons.Filled.Delete, "Löschen") } },
|
||||
modifier = Modifier.clickable { vm.openSession(s.id); onOpen() },
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun SettingsScreen(vm: ChatViewModel, state: UiState, onBack: () -> Unit) {
|
||||
var url by remember { mutableStateOf(state.settings.serverUrl) }
|
||||
var token by remember { mutableStateOf(state.settings.token) }
|
||||
var status by remember { mutableStateOf<String?>(null) }
|
||||
val urlError = if (url.isBlank()) null else OpenClawApi.validateUrl(url)
|
||||
Scaffold(topBar = {
|
||||
TopAppBar(title = { Text("Einstellungen") },
|
||||
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Zurück") } })
|
||||
}) { pad ->
|
||||
Column(Modifier.padding(pad).padding(16.dp).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
OutlinedTextField(url, { url = it }, Modifier.fillMaxWidth(), label = { Text("Server-URL") },
|
||||
placeholder = { Text("https://claw.example.org") }, singleLine = true,
|
||||
isError = urlError != null, supportingText = { urlError?.let { Text(it) } },
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri))
|
||||
OutlinedTextField(token, { token = it }, Modifier.fillMaxWidth(), label = { Text("Token") }, singleLine = true,
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
|
||||
Text("Token und URL werden verschlüsselt (Android Keystore) gespeichert. Release-Builds erlauben nur HTTPS.",
|
||||
style = MaterialTheme.typography.bodySmall)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(enabled = urlError == null && url.isNotBlank() && token.isNotBlank(), onClick = {
|
||||
vm.saveSettings(ServerSettings(url, token)); onBack()
|
||||
}) { Text("Speichern") }
|
||||
OutlinedButton(enabled = urlError == null && url.isNotBlank(), onClick = {
|
||||
status = "Teste…"; vm.testConnection(ServerSettings(url.trim().trimEnd('/'), token.trim())) { status = it }
|
||||
}) { Text("Verbindung testen") }
|
||||
}
|
||||
status?.let { Text(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
3
android/app/src/main/res/values/strings.xml
Normal file
3
android/app/src/main/res/values/strings.xml
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
<resources>
|
||||
<string name="app_name">OpenClaw</string>
|
||||
</resources>
|
||||
7
android/app/src/main/res/xml/network_security_config.xml
Normal file
7
android/app/src/main/res/xml/network_security_config.xml
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Release: HTTPS/WSS only, system CAs only. -->
|
||||
<network-security-config>
|
||||
<base-config cleartextTrafficPermitted="false">
|
||||
<trust-anchors><certificates src="system" /></trust-anchors>
|
||||
</base-config>
|
||||
</network-security-config>
|
||||
22
android/app/src/test/java/dev/openclaw/client/ModelsTest.kt
Normal file
22
android/app/src/test/java/dev/openclaw/client/ModelsTest.kt
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
package dev.openclaw.client
|
||||
|
||||
import dev.openclaw.client.data.AgentEvent
|
||||
import dev.openclaw.client.data.Message
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class ModelsTest {
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
|
||||
@Test fun decodesEvent() {
|
||||
val e = json.decodeFromString(AgentEvent.serializer(), """{"type":"delta","text":"Hi","session_id":"s1","extra":1}""")
|
||||
assertEquals("delta", e.type); assertEquals("Hi", e.text); assertEquals("s1", e.sessionId)
|
||||
}
|
||||
|
||||
@Test fun decodesStoredMessageWithToolCalls() {
|
||||
val m = json.decodeFromString(Message.serializer(),
|
||||
"""{"id":2,"role":"assistant","content":"","tool_calls":[{"id":"c1","name":"time_now","arguments":"{}"}],"created_at":"x"}""")
|
||||
assertEquals("time_now", m.toolCalls.single().name)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue