feat(rhema-code): add the colors setting with four palettes

The stored `colors` key names a palette — rhema (the default,
Jadeite), aquamarine, black-and-white, or dracula — and the
Appearance page of /settings cycles it live, like the theme and
icon toggles beside it. Each palette carries a dark and a light
appearance under the existing `theme` key; dracula's light side is
derived, the official palette ships only dark.

The appearance decision moves off token comparison: Theme now
answers is_dark() from the ground/text luminance, so palettes
beyond the original two get the right per-profile fallback tones.
This commit is contained in:
vhaudiquet committed 2026-10-17 04:28:31 +08:00
commit 81da26b955
159 files changed
+50628

No files matched your search

@@ -0,0 +1,923 @@
package rs.rhema.phone.ui
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material3.Button
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.collectAsState
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.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.core.content.FileProvider
import rs.rhema.phone.R
import rs.rhema.phone.chat.ChatController
import rs.rhema.phone.data.AgentIdentityCache
import rs.rhema.phone.di.AppContainer
import rs.rhema.phone.net.ClawResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException
// The transcript screen, the design's chat panel as a phone screen:
// avatar rows per turn (the tool cards with their one-sided accent
// border, dim collapsible thinking, the outcome tag), and a composer
// with the round accent send button. The claw owns the conversation —
// this renders what the event stream delivered, nothing more.
@Composable
fun ChatScreen(container: AppContainer, sessionKey: String, onBack: () -> Unit) {
val scope = rememberCoroutineScope()
val controller = remember(sessionKey) { ChatController(container.api, container.sessionCache, scope, sessionKey) }
// The SSE connection lives exactly as long as this screen is composed.
DisposableEffect(sessionKey) {
controller.start()
onDispose { controller.stop() }
}
BackHandler { onBack() }
var draft by rememberSaveable { mutableStateOf("") }
// The claw's presentation identity: the avatar picture (when one is
// set), the initials glyph otherwise, and the agent's name on every
// turn — the same face the web UI shows.
val face = rememberAgentFace(container)
Column(modifier = Modifier.fillMaxSize()) {
ChatHeader(sessionKey, controller.connection, face, onBack)
HorizontalDivider(color = JadeiteBorder)
// Reversed layout: index 0 is the newest turn, pinned to the
// bottom edge. A streaming reply grows against that anchor, so
// the newest text stays on screen without scroll bookkeeping,
// and a reader scrolled into history is never yanked back.
LazyColumn(
modifier = Modifier
.weight(1f)
.fillMaxWidth(),
reverseLayout = true,
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 16.dp),
verticalArrangement = Arrangement.spacedBy(20.dp),
) {
items(turnGroups(controller.items).asReversed(), key = { it.key }) { group ->
TurnGroupRow(group, container, controller, face)
}
}
controller.sendError?.let { err ->
Text(
stringResource(R.string.chat_send_failed, err),
color = JadeiteError,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 10.dp),
verticalAlignment = Alignment.Bottom,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
OutlinedTextField(
value = draft,
onValueChange = { draft = it },
modifier = Modifier.weight(1f),
placeholder = { Text(stringResource(R.string.chat_message_hint)) },
maxLines = 4,
shape = MaterialTheme.shapes.small,
colors = OutlinedTextFieldDefaults.colors(
focusedBorderColor = JadeiteAccent,
unfocusedBorderColor = JadeiteBorder,
focusedContainerColor = JadeiteSunken,
unfocusedContainerColor = JadeiteSunken,
cursorColor = JadeiteAccentText,
focusedTextColor = JadeiteText,
unfocusedTextColor = JadeiteText,
),
)
SendButton(
enabled = !controller.sending && draft.isNotBlank(),
) {
val text = draft
draft = ""
scope.launch {
if (!controller.send(text)) draft = text
}
}
}
}
}
@Composable
private fun ChatHeader(
sessionKey: String,
conn: ChatController.Conn,
face: AgentFace,
onBack: () -> Unit,
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp),
) {
IconButton(onClick = onBack) {
Icon(
Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(R.string.chat_back),
tint = JadeiteText2,
)
}
AppAvatar(face.glyph, accent = face.image == null, size = 34.dp, image = face.image)
Column(modifier = Modifier.weight(1f)) {
Text(
sessionKey.removePrefix("interactive:"),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
StatusDot(tone = connTone(conn))
Text(
connText(conn),
style = MaterialTheme.typography.labelSmall,
color = if (connTone(conn) == DotTone.Error) JadeiteError else JadeiteText3,
)
}
}
}
}
private fun connTone(conn: ChatController.Conn): DotTone = when (conn) {
ChatController.Conn.Connecting -> DotTone.Warn
ChatController.Conn.Live -> DotTone.Ok
ChatController.Conn.Reconnecting -> DotTone.Error
is ChatController.Conn.Failed -> DotTone.Error
}
@Composable
private fun connText(conn: ChatController.Conn): String = when (conn) {
ChatController.Conn.Connecting -> stringResource(R.string.chat_status_connecting)
ChatController.Conn.Live -> stringResource(R.string.chat_status_live)
ChatController.Conn.Reconnecting -> stringResource(R.string.chat_status_reconnecting)
is ChatController.Conn.Failed ->
if (conn.code == 401) {
stringResource(R.string.chat_status_unauthorized)
} else {
stringResource(R.string.chat_status_failed, conn.message)
}
}
@Composable
private fun SendButton(enabled: Boolean, onClick: () -> Unit) {
Surface(
shape = CircleShape,
color = if (enabled) JadeiteAccent else JadeiteElevated,
modifier = Modifier
.size(44.dp)
.clickable(enabled = enabled, onClick = onClick),
) {
Box(contentAlignment = Alignment.Center) {
Icon(
Icons.AutoMirrored.Filled.Send,
contentDescription = stringResource(R.string.chat_send),
tint = if (enabled) JadeiteOnAccent else JadeiteText3,
modifier = Modifier.size(20.dp),
)
}
}
}
// One turn as rendered: a user message, or the agent's stack of
// thinking / tool cards / reply / outcome under one avatar. The flat
// item list folds here — consecutive agent items belong to one turn.
private sealed interface TurnGroup {
val key: String
data class User(val id: Long, val text: String) : TurnGroup {
override val key: String = "u$id"
}
data class Agent(val items: MutableList<ChatController.Item>) : TurnGroup {
override val key: String = "a${items.first().id}"
}
}
private fun turnGroups(items: List<ChatController.Item>): List<TurnGroup> {
val groups = mutableListOf<TurnGroup>()
for (item in items) {
when (item) {
is ChatController.UserMessage -> groups += TurnGroup.User(item.id, item.text)
else -> {
val last = groups.lastOrNull()
if (last is TurnGroup.Agent) last.items += item else groups += TurnGroup.Agent(mutableListOf(item))
}
}
}
return groups
}
@Composable
private fun TurnGroupRow(
group: TurnGroup,
container: AppContainer,
controller: ChatController,
face: AgentFace,
) {
when (group) {
is TurnGroup.User -> Row(
horizontalArrangement = Arrangement.End,
modifier = Modifier.fillMaxWidth(),
) {
// The reader's own words: a right-anchored bubble, elevated
// one step and marked on its trailing edge — no label or
// avatar, the side says whose it is.
Row(
modifier = Modifier
.weight(1f, fill = false)
.height(IntrinsicSize.Min)
.background(JadeiteElevated, MaterialTheme.shapes.small),
) {
Column(
modifier = Modifier
.padding(horizontal = 10.dp, vertical = 8.dp)
.weight(1f, fill = false),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
// Embedded pastes render as chips, not payloads; the
// text around them stays verbatim.
var chip = 0
pasteParts(group.text).forEach { part ->
when (part) {
is PastePart.Text -> Text(part.text, style = MaterialTheme.typography.bodyLarge)
is PastePart.Paste -> {
chip += 1
PasteChip(chipLabel(part.payload, chip))
}
}
}
}
AccentBar(JadeiteAccent)
}
}
is TurnGroup.Agent -> Row(
horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth(),
) {
AppAvatar(face.glyph, accent = face.image == null, image = face.image)
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
face.name ?: stringResource(R.string.chat_agent),
style = MaterialTheme.typography.labelMedium,
fontWeight = FontWeight.Bold,
color = if (group.items.any { it is ChatController.Reply && it.streaming }) {
JadeiteAccentText
} else {
JadeiteText2
},
)
// The design stacks a turn as thinking, tool cards, then the
// reply and its outcome — stream order interleaves them, the
// rendering does not.
group.items.sortedBy { turnPriority(it) }.forEach { item ->
when (item) {
is ChatController.Thinking -> ThinkingBlock(item)
is ChatController.ToolCall ->
if (isShellTool(item.name)) ShellRow(item) else ToolCard(item)
is ChatController.Attachment -> AttachmentCard(item, container)
is ChatController.Consent -> ConsentCard(item, controller)
is ChatController.Reply -> ReplyBlock(item)
is ChatController.Outcome -> OutcomeTag(item.outcome)
is ChatController.UserMessage -> Unit // never grouped here
}
}
}
}
}
}
// Render order inside one agent turn: thinking, tools, attachments,
// questions, reply, outcome.
private fun turnPriority(item: ChatController.Item): Int = when (item) {
is ChatController.Thinking -> 0
is ChatController.ToolCall -> 1
is ChatController.Attachment -> 2
is ChatController.Consent -> 3
is ChatController.Reply -> 4
is ChatController.Outcome -> 5
is ChatController.UserMessage -> 6
}
@Composable
private fun ThinkingBlock(item: ChatController.Thinking) {
// Dim and collapsible: it is the agent's scratch, not its answer.
var expanded by remember(item.id) { mutableStateOf(false) }
val text = if (expanded || item.text.length <= 120) item.text else "${item.text.take(120)}…"
Column(
modifier = Modifier
.fillMaxWidth()
.clickable { expanded = !expanded }
.background(JadeiteSurface, MaterialTheme.shapes.extraSmall)
.padding(8.dp),
) {
Text(
"thinking",
style = MaterialTheme.typography.labelSmall,
color = JadeiteText3,
)
Text(
text,
style = MaterialTheme.typography.bodySmall,
fontStyle = FontStyle.Italic,
color = JadeiteText3,
)
}
}
@Composable
private fun ToolCard(item: ChatController.ToolCall) {
val tint = when {
item.running -> JadeiteText3
item.isError -> JadeiteError
else -> JadeiteOk
}
Row(
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 32.dp)
.height(IntrinsicSize.Min)
.background(JadeiteSurface, MaterialTheme.shapes.extraSmall),
) {
AccentBar(tint)
Row(
modifier = Modifier
.padding(horizontal = 10.dp, vertical = 6.dp)
.weight(1f),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
if (item.running) "…" else if (item.isError) "✗" else "✓",
style = MaterialTheme.typography.labelMedium,
color = tint,
)
Text(
item.name,
style = MaterialTheme.typography.labelMedium,
fontFamily = JadeiteMono,
color = JadeiteText,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
item.summary?.takeIf { it.isNotBlank() }?.let { summary ->
Text(
summary,
style = MaterialTheme.typography.bodySmall,
fontFamily = JadeiteMono,
color = JadeiteText3,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
/** Command rows render as shell lines, not glyph rows (the desktop's
* shell_line); run_command is the bash tool's other name. */
private fun isShellTool(name: String): Boolean = name == "bash" || name == "run_command"
@Composable
private fun ShellRow(item: ChatController.ToolCall) {
val tint = when {
item.running -> JadeiteText3
item.exitCode == 0L && !item.isError -> JadeiteOk
else -> JadeiteError
}
Row(
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 32.dp)
.height(IntrinsicSize.Min)
.background(JadeiteSurface, MaterialTheme.shapes.extraSmall),
) {
AccentBar(tint)
Row(
modifier = Modifier
.padding(horizontal = 10.dp, vertical = 6.dp)
.weight(1f),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
// A shell line reads as the command it ran: dim $ prefix, the
// command, the exit code at its end.
Text(
"$",
style = MaterialTheme.typography.labelMedium,
fontFamily = JadeiteMono,
color = JadeiteText3,
)
Text(
item.command ?: "…",
style = MaterialTheme.typography.labelMedium,
fontFamily = JadeiteMono,
color = JadeiteText,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = false),
)
when {
item.running -> Unit
item.exitCode != null -> Text(
"[${item.exitCode}]",
style = MaterialTheme.typography.labelMedium,
fontFamily = JadeiteMono,
color = if (item.exitCode == 0L) JadeiteOk else JadeiteError,
)
item.isError -> Text(
"✗",
style = MaterialTheme.typography.labelMedium,
color = JadeiteError,
)
}
}
}
}
@Composable
private fun ReplyBlock(item: ChatController.Reply) {
AgentMarkdown(
text = item.text,
streaming = item.streaming,
)
}
@Composable
private fun OutcomeTag(outcome: String) {
Text(
outcome,
style = MaterialTheme.typography.labelSmall,
fontFamily = JadeiteMono,
color = if (outcome.equals("Failed", ignoreCase = true)) JadeiteError else JadeiteText3,
)
}
@Composable
private fun PasteChip(label: String) {
Text(
label,
style = MaterialTheme.typography.labelSmall,
fontFamily = JadeiteMono,
color = JadeiteText3,
modifier = Modifier
.background(JadeiteSunken, MaterialTheme.shapes.extraSmall)
.padding(horizontal = 8.dp, vertical = 2.dp),
)
}
// --- embedded pastes --------------------------------------------------
// The wire form a long paste travels in: MARK, payload, MARK — one
// logical unit inside otherwise plain text (rhema-core's paste module
// is the definition; these are its client-side shape). A mark with no
// partner is literal text.
private const val PASTE_MARK = '\uFFFC'
/** One scanned piece of embedded-form text. */
private sealed interface PastePart {
data class Text(val text: String) : PastePart
data class Paste(val payload: String) : PastePart
}
/** Splits embedded-form text into its parts, left to right. A mark with
* no partner is literal text; malformed input never throws. */
private fun pasteParts(text: String): List<PastePart> {
val parts = mutableListOf<PastePart>()
var rest = text
while (true) {
val start = rest.indexOf(PASTE_MARK)
if (start < 0) break
val after = rest.substring(start + 1)
val end = after.indexOf(PASTE_MARK)
if (end < 0) {
parts += PastePart.Text(rest.substring(0, start + 1))
rest = after
continue
}
if (start > 0) parts += PastePart.Text(rest.substring(0, start))
parts += PastePart.Paste(after.substring(0, end))
rest = after.substring(end + 1)
}
if (rest.isNotEmpty()) parts += PastePart.Text(rest)
return parts
}
/** Rust `str::lines`: \n-split, and a trailing newline ends the last
* line instead of opening an empty one. */
private fun lineCount(text: String): Int {
if (text.isEmpty()) return 0
val lines = text.split('\n')
return if (lines.last().isEmpty()) lines.size - 1 else lines.size
}
/** A chip's label: `▣1 5L` — the anchor's one-based id and the
* payload's line count. */
private fun chipLabel(paste: String, chip: Int): String = "▣$chip ${lineCount(paste)}L"
// --- attachments ------------------------------------------------------
// Only small images preview inline: there is no image loader in the
// app, so the preview is a BitmapFactory decode of the fetched bytes.
private const val INLINE_IMAGE_MAX_BYTES = 2L * 1024 * 1024
private sealed interface AttachState {
data object Idle : AttachState
data object Loading : AttachState
data class Ready(val uri: Uri, val preview: ImageBitmap?, val note: String? = null) : AttachState
data class Failed(val message: String) : AttachState
}
@Composable
private fun AttachmentCard(item: ChatController.Attachment, container: AppContainer) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
// Templates resolve in composition, not at callback time: a lookup
// through LocalContext.current freezes the locale of the first
// composition.
val failedTemplate = stringResource(R.string.chat_attachment_failed)
val openFailed = stringResource(R.string.chat_attachment_open_failed)
var state by remember(item.attachmentId) { mutableStateOf<AttachState>(AttachState.Idle) }
// One fetch: bytes → cache file → shareable uri; small images also
// decode to the inline preview. open hands the uri to ACTION_VIEW.
suspend fun download(open: Boolean) {
state = AttachState.Loading
when (val result = container.api.attachment(item.attachmentId)) {
is ClawResult.Ok -> {
val prepared = withContext(Dispatchers.IO) {
val uri = saveAttachment(context, item.attachmentId, item.name, result.value)
when {
uri == null -> AttachState.Failed(
failedTemplate.format("save failed"),
)
item.media == "image" && result.value.size <= INLINE_IMAGE_MAX_BYTES -> {
val preview = BitmapFactory.decodeByteArray(
result.value,
0,
result.value.size,
)?.asImageBitmap()
AttachState.Ready(uri, preview)
}
else -> AttachState.Ready(uri, preview = null)
}
}
state = prepared
if (prepared is AttachState.Ready && open && !openAttachment(context, prepared.uri)) {
state = prepared.copy(note = openFailed)
}
}
is ClawResult.HttpError ->
state = AttachState.Failed(failedTemplate.format("HTTP ${result.code}"))
is ClawResult.Network ->
state = AttachState.Failed(failedTemplate.format(result.message))
}
}
// Small images fetch themselves on first composition; everything else
// waits for the download row.
LaunchedEffect(item.attachmentId) {
if (item.media == "image" && item.size in 1L..INLINE_IMAGE_MAX_BYTES && state == AttachState.Idle) {
download(open = false)
}
}
val current = state
Row(
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 32.dp)
.height(IntrinsicSize.Min)
.background(JadeiteSurface, MaterialTheme.shapes.extraSmall),
) {
AccentBar(
when (current) {
AttachState.Loading -> JadeiteText3
is AttachState.Failed -> JadeiteError
else -> JadeiteOk
},
)
Column(
modifier = Modifier
.padding(horizontal = 10.dp, vertical = 6.dp)
.weight(1f),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
item.name,
style = MaterialTheme.typography.labelMedium,
fontFamily = JadeiteMono,
color = JadeiteText,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = false),
)
Text(
formatBytes(item.size),
style = MaterialTheme.typography.labelSmall,
fontFamily = JadeiteMono,
color = JadeiteText3,
)
}
item.caption?.takeIf { it.isNotBlank() }?.let { caption ->
Text(caption, style = MaterialTheme.typography.bodySmall, color = JadeiteText2)
}
if (current is AttachState.Ready) {
current.preview?.let { preview ->
Image(
bitmap = preview,
contentDescription = item.name,
contentScale = ContentScale.Fit,
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 240.dp),
)
}
current.note?.let { note ->
Text(note, style = MaterialTheme.typography.bodySmall, color = JadeiteError)
}
}
if (current is AttachState.Failed) {
Text(current.message, style = MaterialTheme.typography.bodySmall, color = JadeiteError)
}
if (current is AttachState.Loading) {
Text(
stringResource(R.string.chat_attachment_downloading),
style = MaterialTheme.typography.labelMedium,
color = JadeiteText3,
)
} else {
Text(
when (current) {
is AttachState.Ready -> stringResource(R.string.chat_attachment_open)
else -> stringResource(R.string.chat_attachment_download)
},
style = MaterialTheme.typography.labelMedium,
color = JadeiteAccentText,
modifier = Modifier.clickable {
when (val s = state) {
is AttachState.Ready -> {
if (!openAttachment(context, s.uri)) {
state = s.copy(note = openFailed)
}
}
else -> scope.launch { download(open = true) }
}
},
)
}
}
}
}
/** Saves the bytes under cache/attachments/ and answers the shareable
* content:// uri; other apps can read the file only through the
* FileProvider mapping, so the name (its extension drives the mime)
* must survive the save. Null when the write failed. */
private fun saveAttachment(context: Context, id: String, name: String, bytes: ByteArray): Uri? {
val dir = File(context.cacheDir, "attachments")
if (!dir.exists() && !dir.mkdirs()) return null
val safe = name.substringAfterLast('/').substringAfterLast('\\').trim().ifBlank { "attachment" }
return try {
val file = File(dir, "$id-$safe")
file.writeBytes(bytes)
FileProvider.getUriForFile(context, context.packageName + ".fileprovider", file)
} catch (e: IOException) {
null
}
}
/** Hands a saved attachment to another app. False when nothing on the
* phone opens it — the card says so, and the file stays for a retry. */
private fun openAttachment(context: Context, uri: Uri): Boolean = try {
val mime = context.contentResolver.getType(uri) ?: "application/octet-stream"
context.startActivity(
Intent(Intent.ACTION_VIEW)
.setDataAndType(uri, mime)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK),
)
true
} catch (e: ActivityNotFoundException) {
false
}
/** B/KB/MB, integer — the mono token beside the file name. */
private fun formatBytes(size: Long): String = when {
size < 1024 -> "$size B"
size < 1024 * 1024 -> "${size / 1024} KB"
else -> "${size / (1024 * 1024)} MB"
}
@Composable
private fun ConsentCard(item: ChatController.Consent, controller: ChatController) {
val scope = rememberCoroutineScope()
var secret by remember(item.id) { mutableStateOf("") }
var busy by remember(item.id) { mutableStateOf(false) }
var failure by remember(item.id) { mutableStateOf<String?>(null) }
// An open question glows warn; a settled card keeps only its tone.
val tint = when (item.granted) {
null -> JadeiteWarn
true -> JadeiteOk
false -> JadeiteText3
}
fun answer(call: suspend () -> ClawResult<Unit>) {
busy = true
scope.launch {
failure = when (val result = call()) {
is ClawResult.Ok -> null
is ClawResult.HttpError -> "HTTP ${result.code}" + (result.body?.let { " — $it" } ?: "")
is ClawResult.Network -> result.message
}
busy = false
}
}
Row(
modifier = Modifier
.fillMaxWidth()
.height(IntrinsicSize.Min)
.background(JadeiteSurface, MaterialTheme.shapes.extraSmall),
) {
AccentBar(tint)
Column(
modifier = Modifier
.padding(horizontal = 10.dp, vertical = 6.dp)
.weight(1f),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
AppBadge(item.kind, tint = tint)
Text(
item.summary,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.weight(1f, fill = false),
)
}
Text(item.detail, style = MaterialTheme.typography.bodySmall, color = JadeiteText2)
when (item.granted) {
true -> Text(
"✓ " + stringResource(R.string.consent_granted),
style = MaterialTheme.typography.labelMedium,
color = JadeiteOk,
)
false -> Text(
"✗ " + stringResource(R.string.consent_denied),
style = MaterialTheme.typography.labelMedium,
color = JadeiteText3,
)
null -> {
if (item.kind == "secret") {
OutlinedTextField(
value = secret,
onValueChange = { secret = it },
modifier = Modifier.fillMaxWidth(),
placeholder = { Text(stringResource(R.string.consent_secret_hint)) },
visualTransformation = PasswordVisualTransformation(),
singleLine = true,
enabled = !busy,
shape = MaterialTheme.shapes.small,
colors = OutlinedTextFieldDefaults.colors(
focusedBorderColor = JadeiteAccent,
unfocusedBorderColor = JadeiteBorder,
focusedContainerColor = JadeiteSunken,
unfocusedContainerColor = JadeiteSunken,
cursorColor = JadeiteAccentText,
focusedTextColor = JadeiteText,
unfocusedTextColor = JadeiteText,
),
)
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (item.kind == "secret") {
Button(
enabled = !busy && secret.isNotBlank(),
onClick = { answer { controller.answerSecret(item.consentId, secret) } },
) {
Text(stringResource(R.string.consent_submit))
}
} else {
Button(
enabled = !busy,
onClick = { answer { controller.grantPhone(item.consentId, true) } },
) {
Text(stringResource(R.string.consent_approve))
}
}
OutlinedButton(
enabled = !busy,
onClick = { answer { controller.denyConsent(item.consentId) } },
) {
Text(stringResource(R.string.consent_deny))
}
}
}
}
failure?.let { fail ->
Text(
stringResource(R.string.consent_answer_failed, fail),
style = MaterialTheme.typography.bodySmall,
color = JadeiteError,
)
}
}
}
}
// The agent's face as this screen renders it: the display name (null
// keeps the string resource's fallback), the initials glyph, and the
// decoded avatar image. The glyph precedence is the web's: the claw's
// `initials`, else the name's first letter, else "R".
private data class AgentFace(val name: String?, val glyph: String, val image: ImageBitmap?)
@Composable
private fun rememberAgentFace(container: AppContainer): AgentFace {
val cache by container.identity.cached.collectAsState(AgentIdentityCache())
var image by remember { mutableStateOf<ImageBitmap?>(null) }
// Decoding off the main thread: an uploaded avatar can weigh the
// claw's full 2 MB image cap.
LaunchedEffect(cache.avatar) {
image = cache.avatar?.let { bytes ->
withContext(Dispatchers.Default) {
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.asImageBitmap()
}
}
}
val identity = cache.identity
val name = identity?.name?.trim()?.takeIf { it.isNotEmpty() }
val glyph = identity?.initials?.trim()?.takeIf { it.isNotEmpty() }
?: name?.take(1)
?: "R"
return AgentFace(name, glyph, image)
}
@@ -0,0 +1,379 @@
package rs.rhema.phone.ui
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
// The design language's shared pieces, mirroring the web components:
// one card voice, one label voice, one badge/dot/callout vocabulary.
// Screens compose these; nothing here knows about the claw API.
/** The uppercase letterspaced section label — the repeated typographic voice. */
@Composable
fun SectionLabel(text: String, modifier: Modifier = Modifier) {
Text(
text,
modifier = modifier,
style = MaterialTheme.typography.labelMedium,
fontWeight = FontWeight.Bold,
color = JadeiteText3,
letterSpacing = MaterialTheme.typography.labelMedium.letterSpacing * 1.4f,
)
}
enum class DotTone { Ok, Warn, Error, Idle }
/** One honest state dot: ok, warn, error, or idle gray. */
@Composable
fun StatusDot(tone: DotTone, modifier: Modifier = Modifier) {
val color = when (tone) {
DotTone.Ok -> JadeiteOk
DotTone.Warn -> JadeiteWarn
DotTone.Error -> JadeiteError
DotTone.Idle -> JadeiteText3
}
Box(modifier = modifier.size(8.dp).clip(RoundedCornerShape(50)).background(color))
}
/** The pill: one small status or tag word, outlined in its tone. */
@Composable
fun AppBadge(text: String, modifier: Modifier = Modifier, tint: Color = JadeiteText3) {
Surface(
modifier = modifier,
shape = RoundedCornerShape(50),
color = Color.Transparent,
border = BorderStroke(1.dp, tint),
) {
Text(
text,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 1.dp),
style = MaterialTheme.typography.labelSmall,
fontFamily = JadeiteMono,
color = tint,
)
}
}
/**
* The avatar square: the agent's picture when the claw has one, the
* accent mark (or a neutral one) otherwise — the same precedence as the
* web's `AgentAvatar`.
*/
@Composable
fun AppAvatar(
mark: String,
accent: Boolean,
modifier: Modifier = Modifier,
size: Dp = 32.dp,
image: ImageBitmap? = null,
) {
val shape = RoundedCornerShape(size / 4)
Box(
modifier = modifier
.size(size)
.clip(shape)
.then(
if (image == null) {
Modifier
.background(if (accent) JadeiteAccent else JadeiteElevated)
.border(
if (accent) 0.dp else 1.dp,
if (accent) Color.Transparent else JadeiteBorderStrong,
shape,
)
} else {
Modifier
},
),
contentAlignment = Alignment.Center,
) {
if (image != null) {
Image(
bitmap = image,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.matchParentSize(),
)
} else {
Text(
mark,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
color = if (accent) JadeiteOnAccent else JadeiteText2,
)
}
}
}
/** The page header: title, optional subtitle, trailing actions. */
@Composable
fun PageHeader(
title: String,
modifier: Modifier = Modifier,
subtitle: String? = null,
actions: (@Composable RowScope.() -> Unit)? = null,
) {
Row(
modifier = modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(modifier = Modifier.weight(1f)) {
Text(title, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold)
subtitle?.let {
Text(it, style = MaterialTheme.typography.bodySmall, color = JadeiteText3)
}
}
actions?.invoke(this)
}
}
/**
* The one card: a titled container whose body rows separate by hairline.
* Rows are the caller's job ([CardRow]); pass `first = true` to the
* card's first row so it draws no divider.
*/
@Composable
fun RhemaCard(
title: String,
modifier: Modifier = Modifier,
meta: String? = null,
content: @Composable ColumnScope.() -> Unit,
) {
Surface(
modifier = modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.medium,
color = JadeiteSurface,
border = BorderStroke(1.dp, JadeiteBorder),
) {
Column {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
title,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
modifier = Modifier.weight(1f, fill = false),
)
meta?.let {
Text(
it,
modifier = Modifier.padding(start = 12.dp),
style = MaterialTheme.typography.bodySmall,
color = JadeiteText3,
)
}
}
HorizontalDivider(color = JadeiteBorder)
Column(content = content)
}
}
}
/**
* One row inside a [RhemaCard]: name and explanation on the left, control
* (or value) on the right. Hairline separation is drawn here except on
* the card's first row.
*/
@Composable
fun CardRow(
title: String,
modifier: Modifier = Modifier,
description: String? = null,
first: Boolean = false,
control: (@Composable () -> Unit)? = null,
) {
if (!first) HorizontalDivider(color = JadeiteBorder)
Row(
modifier = modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = if (description == null) Alignment.CenterVertically else Alignment.Top,
horizontalArrangement = Arrangement.spacedBy(16.dp),
) {
Column(modifier = Modifier.weight(1f)) {
Text(title, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)
description?.let {
Text(it, style = MaterialTheme.typography.bodySmall, color = JadeiteText3)
}
}
control?.invoke()
}
}
/** Tones of [AppCallout]: the inline note vocabulary. */
enum class CalloutTone { Info, Ok, Warn, Error }
/** The toned inline callout — the "changes not applied" voice. */
@Composable
fun AppCallout(
tone: CalloutTone,
text: String,
modifier: Modifier = Modifier,
title: String? = null,
) {
val tint = when (tone) {
CalloutTone.Info -> JadeiteInfo
CalloutTone.Ok -> JadeiteOk
CalloutTone.Warn -> JadeiteWarn
CalloutTone.Error -> JadeiteError
}
val mark = when (tone) {
CalloutTone.Info -> "i"
CalloutTone.Ok -> "✓"
CalloutTone.Warn -> "↺"
CalloutTone.Error -> "✗"
}
Surface(
modifier = modifier.fillMaxWidth(),
shape = RoundedCornerShape(8.dp),
color = tint.copy(alpha = 0.08f),
border = BorderStroke(1.dp, JadeiteBorder),
) {
Row(
modifier = Modifier.padding(12.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Text(
mark,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.Bold,
color = tint,
)
Column {
title?.let {
Text(it, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold)
}
Text(text, style = MaterialTheme.typography.bodySmall, color = JadeiteText2)
}
}
}
}
/**
* The design's select: a sunken field that opens a menu. Options are
* (value, label) pairs; an empty-string value is a legitimate option
* ("(provider default)"), which is why selection is by value.
*/
@Composable
fun RhemaSelect(
selected: String?,
options: List<Pair<String, String>>,
onSelect: (String) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
) {
var open by remember { mutableStateOf(false) }
val label = options.firstOrNull { it.first == selected }?.second ?: selected ?: ""
Box(modifier) {
Surface(
shape = RoundedCornerShape(8.dp),
color = JadeiteSunken,
border = BorderStroke(1.dp, JadeiteBorder),
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(8.dp))
.clickable(enabled = enabled) { open = true },
) {
Row(
modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
label,
modifier = Modifier.weight(1f),
style = MaterialTheme.typography.bodyMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
color = if (selected == null) JadeiteText3 else JadeiteText,
)
Text("▾", style = MaterialTheme.typography.bodySmall, color = JadeiteText3)
}
}
DropdownMenu(
expanded = open,
onDismissRequest = { open = false },
containerColor = JadeiteElevated,
) {
options.forEach { (value, optionLabel) ->
DropdownMenuItem(
text = {
Text(
optionLabel,
style = MaterialTheme.typography.bodyMedium,
fontFamily = if (value.isEmpty()) null else JadeiteMono,
color = if (value == selected) JadeiteAccentText else JadeiteText2,
)
},
onClick = {
open = false
onSelect(value)
},
)
}
}
}
}
/** The tool-card accent bar: the design's one-sided border. The parent row must size itself (IntrinsicSize.Min) for the bar to span it. */
@Composable
fun AccentBar(color: Color, modifier: Modifier = Modifier) {
Box(modifier = modifier.width(3.dp).fillMaxHeight().background(color))
}
/** A quiet icon action: transparent, dim, brightening on press. */
@Composable
fun GhostIcon(
icon: ImageVector,
contentDescription: String,
modifier: Modifier = Modifier,
enabled: Boolean = true,
onClick: () -> Unit,
) {
IconButton(onClick = onClick, enabled = enabled, modifier = modifier) {
Icon(icon, contentDescription = contentDescription, tint = JadeiteText3)
}
}
@@ -0,0 +1,63 @@
package rs.rhema.phone.ui
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLinkStyles
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.mikepenz.markdown.m3.Markdown
import com.mikepenz.markdown.m3.markdownColor
import com.mikepenz.markdown.m3.markdownTypography
import com.mikepenz.markdown.model.markdownDimens
// Agent replies are markdown; this renders them the way the web UI's
// AppMarkdown does. The parser runs the GFM flavour: raw HTML in the
// source stays literal, so model output cannot mount markup here.
// Code and links pin Jadeite tokens; everything else follows the theme.
// Headings step down from the Material display sizes: a chat reply is
// not a document (the web styles ride the same scale).
@Composable
internal fun AgentMarkdown(text: String, modifier: Modifier = Modifier, streaming: Boolean = false) {
// The cursor rides the source itself: the parser treats it as text at
// the stream edge, so it lands where the reply currently ends.
val base = MaterialTheme.typography.bodyLarge
Markdown(
if (streaming) text + "▊" else text,
colors = markdownColor(
codeBackground = JadeiteSunken,
inlineCodeBackground = JadeiteSunken,
dividerColor = JadeiteBorder,
tableBackground = JadeiteSurface,
),
typography = markdownTypography(
h1 = base.copy(fontWeight = FontWeight.Bold),
h2 = base.copy(fontSize = 15.sp, fontWeight = FontWeight.Bold),
h3 = base.copy(fontSize = 14.sp, fontWeight = FontWeight.Bold),
h4 = base.copy(fontSize = 13.sp, fontWeight = FontWeight.Bold),
h5 = base.copy(fontSize = 13.sp, fontWeight = FontWeight.Bold),
h6 = base.copy(fontSize = 13.sp, fontWeight = FontWeight.Bold),
code = MaterialTheme.typography.bodySmall.copy(
fontFamily = JadeiteMono,
color = JadeiteText,
),
inlineCode = base.copy(fontFamily = JadeiteMono, color = JadeiteText),
textLink = TextLinkStyles(
style = SpanStyle(
color = JadeiteAccentText,
textDecoration = TextDecoration.Underline,
),
),
),
// The default 160.dp per cell makes a three-column table wider
// than the phone screen; at 100.dp it fits and only wider tables
// turn into their horizontal-scroll variant.
dimens = markdownDimens(tableCellWidth = 100.dp, tableCellPadding = 8.dp),
modifier = modifier.fillMaxWidth(),
)
}
@@ -0,0 +1,286 @@
package rs.rhema.phone.ui
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
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.ui.Modifier
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import rs.rhema.phone.R
import rs.rhema.phone.di.AppContainer
import rs.rhema.phone.net.ClawResult
import rs.rhema.phone.net.PhoneInfo
import rs.rhema.phone.sensors.PhoneSensors
import kotlinx.coroutines.launch
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.contentOrNull
/**
* The fleet management card: every device the claw has heard from,
* this one marked, every other forgettable. The claw's
* `GET`/`DELETE /v1/phones` are the whole story — the app holds no
* private view of the fleet, so what this shows is what any client sees.
*/
@Composable
fun PhonesCard(container: AppContainer) {
val scope = rememberCoroutineScope()
var phones by remember { mutableStateOf<List<PhoneInfo>?>(null) }
var loadError by remember { mutableStateOf<String?>(null) }
var forgetCandidate by remember { mutableStateOf<PhoneInfo?>(null) }
var forgotName by remember { mutableStateOf<String?>(null) }
val deviceId by container.settings.deviceIdFlow.collectAsState(initial = "")
fun load() {
scope.launch {
when (val result = container.api.phones()) {
is ClawResult.Ok -> {
phones = result.value.phones
loadError = null
}
is ClawResult.HttpError ->
loadError = "HTTP ${result.code}" + (result.body?.let { " — $it" } ?: "")
is ClawResult.Network -> loadError = result.message
}
}
}
LaunchedEffect(Unit) { load() }
RhemaCard(title = stringResource(R.string.card_phones), meta = stringResource(R.string.phones_hint)) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
val currentError = loadError
val list = phones
when {
currentError != null -> AppCallout(
tone = CalloutTone.Error,
text = stringResource(R.string.providers_error, currentError),
)
list == null -> Text(
stringResource(R.string.phones_loading),
style = MaterialTheme.typography.bodySmall,
color = JadeiteText3,
)
list.isEmpty() -> Text(
stringResource(R.string.phones_empty),
style = MaterialTheme.typography.bodySmall,
color = JadeiteText3,
)
else -> {
forgotName?.let { name ->
AppCallout(tone = CalloutTone.Ok, text = stringResource(R.string.phones_forgot_fmt, name))
}
list.forEachIndexed { index, phone ->
val mine = phone.device == deviceId
CardRow(
title = phone.label ?: shortDeviceId(phone.device),
description = fleetRowDescription(phone, mine),
first = index == 0 && forgotName == null,
) {
if (mine) {
AppBadge(stringResource(R.string.phones_this_device))
} else {
OutlinedButton(
onClick = { forgetCandidate = phone },
) {
Text(stringResource(R.string.phones_forget))
}
}
}
}
}
}
}
}
forgetCandidate?.let { candidate ->
val name = candidate.label ?: shortDeviceId(candidate.device)
AlertDialog(
onDismissRequest = { forgetCandidate = null },
title = { Text(stringResource(R.string.phones_forget_title, name)) },
text = { Text(stringResource(R.string.phones_forget_text)) },
confirmButton = {
Button(
onClick = {
forgetCandidate = null
scope.launch {
when (val result = container.api.forgetPhone(candidate.device)) {
is ClawResult.Ok -> {
forgotName = name
load()
}
is ClawResult.HttpError ->
loadError = "HTTP ${result.code}" + (result.body?.let { " — $it" } ?: "")
is ClawResult.Network -> loadError = result.message
}
}
},
) { Text(stringResource(R.string.phones_forget)) }
},
dismissButton = {
TextButton(onClick = { forgetCandidate = null }) {
Text(stringResource(R.string.providers_discard))
}
},
)
}
}
/**
* What this phone reports and what it cannot until the human flips a
* grant: location (a runtime permission) and the two special-app
* toggles Android requires for usage stats and DND control. The state
* re-reads on every ON_RESUME, so coming back from the settings app
* flips the row without a restart.
*/
@Composable
fun ReportingCard() {
val context = LocalContext.current
val lifecycleOwner = LocalLifecycleOwner.current
var resumeKey by remember { mutableIntStateOf(0) }
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) resumeKey++
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
val locationOn = remember(resumeKey) { PhoneSensors.hasLocation(context) }
val usageOn = remember(resumeKey) { PhoneSensors.hasUsageAccess(context) }
val dndOn = remember(resumeKey) {
context.getSystemService(NotificationManager::class.java)
?.isNotificationPolicyAccessGranted == true
}
RhemaCard(
title = stringResource(R.string.card_reporting),
meta = stringResource(R.string.reporting_hint),
) {
CardRow(
title = stringResource(R.string.reporting_location_title),
description = stringResource(R.string.reporting_location_desc),
first = true,
) {
GrantControl(locationOn) { openAppSettings(context) }
}
CardRow(
title = stringResource(R.string.reporting_usage_title),
description = stringResource(R.string.reporting_usage_desc),
) {
GrantControl(usageOn) { openUsageAccessSettings(context) }
}
CardRow(
title = stringResource(R.string.reporting_dnd_title),
description = stringResource(R.string.reporting_dnd_desc),
) {
GrantControl(dndOn) {
context.startActivity(Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS))
}
}
}
}
/** On reads as a quiet badge; off as a button into the system settings. */
@Composable
private fun GrantControl(on: Boolean, onAllow: () -> Unit) {
if (on) {
AppBadge(stringResource(R.string.reporting_on), tint = JadeiteOk)
} else {
OutlinedButton(onClick = onAllow) {
Text(stringResource(R.string.reporting_allow))
}
}
}
private fun openAppSettings(context: Context) {
context.startActivity(
Intent(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", context.packageName, null),
),
)
}
private fun openUsageAccessSettings(context: Context) {
context.startActivity(Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS))
}
/**
* A fleet row's one-line state: battery, network, current app, and how
* long ago any of it landed.
*/
@Composable
private fun fleetRowDescription(phone: PhoneInfo, mine: Boolean): String {
val parts = mutableListOf<String>()
(phone.topics["battery"]?.field("value"))?.contentOrNull?.let { level ->
val charging = phone.topics["battery"]?.field("charging")?.booleanOrNull == true
parts += if (charging) "$level% charging" else "$level%"
}
phone.topics["network"]?.field("value")?.contentOrNull?.let { parts += it }
phone.topics["app"]?.field("label")?.contentOrNull?.let { parts += it }
?: phone.topics["app"]?.field("value")?.contentOrNull
// No label on the payload: the package's last segment is the
// closest readable name ("maps" out of com.google.android.maps).
?.let { pkg -> pkg.substringAfterLast('.').ifEmpty { pkg } }
?.let { parts += it }
val seen = when {
phone.lastSeen <= 0L -> stringResource(R.string.phones_never_reported)
System.currentTimeMillis() - phone.lastSeen < 60_000 ->
stringResource(R.string.phones_seen_just_now)
else -> stringResource(R.string.phones_seen_fmt, relativeTime(phone.lastSeen))
}
if (mine && parts.isEmpty()) parts += stringResource(R.string.phones_never_reported)
val summary = parts.joinToString(" · ")
return if (summary.isEmpty()) seen else "$summary · $seen"
}
private fun JsonObject.field(name: String): JsonPrimitive? = this[name] as? JsonPrimitive
/** A UUID is noise; its first block is enough to tell rows apart. */
private fun shortDeviceId(device: String): String = device.take(8)
private fun relativeTime(thenMillis: Long): String {
val minutes = ((System.currentTimeMillis() - thenMillis) / 60000L).coerceAtLeast(0)
return when {
minutes < 60 -> "${minutes}m"
minutes < 60 * 24 -> "${minutes / 60}h"
else -> "${minutes / (60 * 24)}d"
}
}
@@ -0,0 +1,214 @@
package rs.rhema.phone.ui
import androidx.compose.foundation.clickable
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.fillMaxSize
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.material.icons.Icons
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import rs.rhema.phone.R
import rs.rhema.phone.di.AppContainer
import rs.rhema.phone.net.ClawResult
import rs.rhema.phone.net.SessionInfo
import kotlinx.coroutines.launch
// The session inventory, the design's sidebar as a screen: grouped
// interactive-first rows with an honest state dot and the inbox depth.
// Displayed names drop the `interactive:` prefix; the full key is what
// gets opened.
@Composable
fun SessionsScreen(
container: AppContainer,
onOpenSession: (String) -> Unit,
onOpenSettings: () -> Unit,
) {
val scope = rememberCoroutineScope()
var sessions by remember { mutableStateOf<List<SessionInfo>?>(null) }
var error by remember { mutableStateOf<UiMessage?>(null) }
var loading by remember { mutableStateOf(false) }
val refresh: () -> Unit = {
scope.launch {
loading = true
error = null
// The agent may have renamed or re-faced itself on another
// surface; this button is the manual path for the cached identity.
container.identity.refresh()
when (val result = container.api.sessions()) {
is ClawResult.Ok -> sessions = result.value
is ClawResult.HttpError -> error = UiMessage.Http(result.code, result.body)
is ClawResult.Network -> error = UiMessage.Network(result.message)
}
loading = false
}
}
LaunchedEffect(Unit) { refresh() }
Column(modifier = Modifier.fillMaxSize()) {
PageHeader(
title = stringResource(R.string.sessions_title),
actions = {
GhostIcon(Icons.Filled.Settings, stringResource(R.string.sessions_open_settings), onClick = onOpenSettings)
GhostIcon(Icons.Filled.Refresh, stringResource(R.string.sessions_refresh), enabled = !loading, onClick = refresh)
},
)
val currentError = error
val visible = sessions?.let(::displayable)
when {
currentError != null -> Column(
modifier = Modifier.padding(horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
AppCallout(
tone = CalloutTone.Error,
text = when (currentError) {
is UiMessage.Http -> stringResource(R.string.sessions_http_error, currentError.code) +
(currentError.detail?.let { " — $it" } ?: "")
is UiMessage.Network -> stringResource(R.string.sessions_network_error, currentError.message)
},
)
if (currentError is UiMessage.Http && currentError.code == 401) {
Text(
stringResource(R.string.sessions_unauthorized_hint),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Button(onClick = onOpenSettings) {
Text(stringResource(R.string.sessions_open_settings))
}
}
}
loading && sessions == null -> Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center,
) { CircularProgressIndicator() }
visible != null && visible.isEmpty() -> Text(
stringResource(R.string.sessions_empty),
modifier = Modifier.padding(horizontal = 16.dp),
style = MaterialTheme.typography.bodyMedium,
color = JadeiteText3,
)
visible != null -> SessionsList(
sessions = visible,
onOpenSession = onOpenSession,
)
}
}
}
private data class SessionGroup(val labelKey: String, val rows: List<SessionInfo>)
private const val GROUP_INTERACTIVE = "interactive"
private const val GROUP_OTHER = "other"
// `phone:<device>:<topic>` keys are this device's own status reports,
// not conversations — listed they read as broken empty sessions, so
// they never reach a group.
private fun displayable(sessions: List<SessionInfo>): List<SessionInfo> =
sessions.filterNot { it.key.startsWith("phone:") }
// Interactive keys are the chat surface and lead; other dispatch keys
// read after. Key order is stable within a group.
private fun groupSessions(sessions: List<SessionInfo>): List<SessionGroup> {
val byKey = compareBy<SessionInfo> { it.key }
val visible = displayable(sessions)
val interactive = visible.filter { it.key.startsWith("interactive:") }.sortedWith(byKey)
val others = visible.filterNot { it.key.startsWith("interactive:") }.sortedWith(byKey)
val groups = mutableListOf<SessionGroup>()
if (interactive.isNotEmpty()) {
groups += SessionGroup(GROUP_INTERACTIVE, interactive)
}
if (others.isNotEmpty()) {
groups += SessionGroup(GROUP_OTHER, others)
}
return groups
}
@Composable
private fun SessionsList(sessions: List<SessionInfo>, onOpenSession: (String) -> Unit) {
LazyColumn(modifier = Modifier.fillMaxSize()) {
groupSessions(sessions).forEach { group ->
item(key = group.labelKey) {
SectionLabel(
stringResource(
if (group.labelKey == GROUP_INTERACTIVE) {
R.string.sessions_group_interactive
} else {
R.string.sessions_group_other
},
),
modifier = Modifier.padding(start = 16.dp, top = 12.dp, bottom = 4.dp),
)
}
items(group.rows, key = { it.key }) { session ->
SessionRow(session) { onOpenSession(session.key) }
}
}
}
}
@Composable
private fun SessionRow(session: SessionInfo, onClick: () -> Unit) {
Row(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onClick)
.padding(horizontal = 16.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
StatusDot(tone = stateTone(session.state))
Column(modifier = Modifier.weight(1f)) {
Text(
session.key.removePrefix("interactive:"),
style = MaterialTheme.typography.titleMedium,
maxLines = 1,
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
)
Text(
listOfNotNull(
session.state,
session.revision?.let { "rev $it" },
).joinToString(" · "),
style = MaterialTheme.typography.bodySmall,
fontFamily = JadeiteMono,
color = JadeiteText3,
)
}
val depth = session.inboxDepth
if (depth != null && depth > 0) {
AppBadge(depth.toString(), tint = JadeiteInfo)
}
}
}
/** Leased keys are alive, reacquiring ones are troubled, the rest idle. */
private fun stateTone(state: String?): DotTone = when (state) {
"leased" -> DotTone.Ok
"reacquire" -> DotTone.Warn
else -> DotTone.Idle
}
@@ -0,0 +1,544 @@
package rs.rhema.phone.ui
import androidx.activity.compose.BackHandler
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.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import rs.rhema.phone.R
import rs.rhema.phone.di.AppContainer
import rs.rhema.phone.net.ActivePair
import rs.rhema.phone.net.ClawResult
import rs.rhema.phone.net.ModelCard
import rs.rhema.phone.net.ProvidersState
import kotlinx.coroutines.launch
// Settings in the design language, as a nav of submenus mirroring the
// web UI's settings sidebar: labeled groups ("Phone", "Claw") of one
// page each — status reporting, devices, model providers, connection.
// First launch is the exception: it lands straight on the connection
// page and stays there until GET /healthz succeeds.
@Composable
fun SettingsScreen(container: AppContainer, onConnected: () -> Unit = {}) {
val configured by container.settings.configured.collectAsState(initial = null)
var section by rememberSaveable { mutableStateOf<String?>(null) }
// Back out of a submenu before leaving settings entirely; the
// caller's BackHandler (enabled only when this one is not) takes
// the rest.
BackHandler(enabled = section != null && configured == true) { section = null }
when {
configured == false -> ConnectionPage(container, onConnected = onConnected, onBack = null)
section == null -> SettingsNav { section = it }
else -> when (section) {
SECTION_REPORTING -> SettingsPage(
title = stringResource(R.string.settings_entry_reporting),
onBack = { section = null },
) { ReportingCard() }
SECTION_DEVICES -> SettingsPage(
title = stringResource(R.string.settings_entry_devices),
onBack = { section = null },
) { PhonesCard(container) }
SECTION_PROVIDERS -> SettingsPage(
title = stringResource(R.string.settings_entry_providers),
onBack = { section = null },
) { ProvidersCard(container) }
else -> ConnectionPage(container, onConnected = onConnected, onBack = { section = null })
}
}
}
// The nav entries. Ids are stable spellings (saveable state survives
// rotation through them).
private const val SECTION_REPORTING = "reporting"
private const val SECTION_DEVICES = "devices"
private const val SECTION_PROVIDERS = "providers"
private const val SECTION_CONNECTION = "connection"
private data class SettingsEntry(val id: String, val labelRes: Int, val descRes: Int)
private data class SettingsSection(val labelRes: Int, val entries: List<SettingsEntry>)
private val SECTIONS = listOf(
SettingsSection(
R.string.settings_group_phone,
listOf(
SettingsEntry(
SECTION_REPORTING,
R.string.settings_entry_reporting,
R.string.settings_entry_reporting_desc,
),
SettingsEntry(
SECTION_DEVICES,
R.string.settings_entry_devices,
R.string.settings_entry_devices_desc,
),
),
),
SettingsSection(
R.string.settings_group_claw,
listOf(
SettingsEntry(
SECTION_PROVIDERS,
R.string.settings_entry_providers,
R.string.settings_entry_providers_desc,
),
SettingsEntry(
SECTION_CONNECTION,
R.string.settings_entry_connection,
R.string.settings_entry_connection_desc,
),
),
),
)
@Composable
private fun SettingsNav(onSelect: (String) -> Unit) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
) {
PageHeader(title = stringResource(R.string.settings_page_title))
SECTIONS.forEach { section ->
SectionLabel(
stringResource(section.labelRes),
modifier = Modifier.padding(start = 16.dp, top = 16.dp, bottom = 4.dp),
)
section.entries.forEach { entry ->
Row(
modifier = Modifier
.fillMaxWidth()
.clickable { onSelect(entry.id) }
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Column(modifier = Modifier.weight(1f)) {
Text(
stringResource(entry.labelRes),
style = MaterialTheme.typography.titleMedium,
)
Text(
stringResource(entry.descRes),
style = MaterialTheme.typography.bodySmall,
color = JadeiteText3,
)
}
Text("›", style = MaterialTheme.typography.titleMedium, color = JadeiteText3)
}
}
}
}
}
/** A submenu: a back arrow and title over the page's card. */
@Composable
private fun SettingsPage(title: String, onBack: () -> Unit, content: @Composable () -> Unit) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = onBack) {
Icon(
Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(R.string.settings_back),
tint = JadeiteText2,
)
}
Text(title, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold)
}
Column(modifier = Modifier.padding(horizontal = 16.dp)) { content() }
}
}
/** The connection page: first launch lands here alone (onBack = null
* and the header is the plain Settings title); from the nav it is a
* submenu like the rest. */
@Composable
private fun ConnectionPage(container: AppContainer, onConnected: () -> Unit, onBack: (() -> Unit)?) {
val scope = rememberCoroutineScope()
var baseUrl by rememberSaveable { mutableStateOf("") }
var token by rememberSaveable { mutableStateOf("") }
var busy by rememberSaveable { mutableStateOf(false) }
var status by remember { mutableStateOf<UiMessage?>(null) }
val deviceId by container.settings.deviceIdFlow.collectAsState(initial = "…")
LaunchedEffect(Unit) {
val saved = container.settings.current()
if (saved.baseUrl.isNotBlank()) baseUrl = saved.baseUrl
if (saved.token.isNotBlank()) token = saved.token
}
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
) {
if (onBack == null) {
PageHeader(title = stringResource(R.string.settings_page_title))
} else {
Row(verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = onBack) {
Icon(
Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(R.string.settings_back),
tint = JadeiteText2,
)
}
Text(
stringResource(R.string.settings_entry_connection),
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold,
)
}
}
Column(modifier = Modifier.padding(horizontal = 16.dp)) {
ConnectionCard(
baseUrl = baseUrl,
onBaseUrl = { baseUrl = it },
token = token,
onToken = { token = it },
busy = busy,
onConnect = {
busy = true
status = null
scope.launch {
container.settings.setCredentials(baseUrl.trim(), token.trim())
when (val result = container.api.health()) {
is ClawResult.Ok -> onConnected()
is ClawResult.HttpError -> status = UiMessage.Http(result.code, result.body)
is ClawResult.Network -> status = UiMessage.Network(result.message)
}
busy = false
}
},
status = status,
deviceId = deviceId,
)
}
}
}
@Composable
private fun ConnectionCard(
baseUrl: String,
onBaseUrl: (String) -> Unit,
token: String,
onToken: (String) -> Unit,
busy: Boolean,
onConnect: () -> Unit,
status: UiMessage?,
deviceId: String,
) {
RhemaCard(title = stringResource(R.string.card_connection)) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
OutlinedTextField(
value = baseUrl,
onValueChange = onBaseUrl,
label = { Text(stringResource(R.string.field_base_url)) },
singleLine = true,
enabled = !busy,
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.small,
colors = sunkenFieldColors(),
)
OutlinedTextField(
value = token,
onValueChange = onToken,
label = { Text(stringResource(R.string.field_token)) },
visualTransformation = PasswordVisualTransformation(),
singleLine = true,
enabled = !busy,
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.small,
colors = sunkenFieldColors(),
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(enabled = !busy && baseUrl.isNotBlank(), onClick = onConnect) {
Text(stringResource(R.string.save_and_connect))
}
}
val currentStatus = status
if (currentStatus != null) {
val text: String = when (currentStatus) {
is UiMessage.Http -> stringResource(R.string.settings_health_http, currentStatus.code) +
(currentErrorDetail(currentStatus) ?: "")
is UiMessage.Network -> stringResource(R.string.settings_health_network, currentStatus.message)
}
AppCallout(tone = CalloutTone.Error, text = text)
}
Text(
stringResource(R.string.device_id_fmt, deviceId),
style = MaterialTheme.typography.bodySmall,
fontFamily = JadeiteMono,
color = JadeiteText3,
)
Text(
stringResource(R.string.settings_hint),
style = MaterialTheme.typography.bodySmall,
color = JadeiteText3,
)
}
}
}
private fun currentErrorDetail(status: UiMessage.Http): String? =
status.detail?.let { " — $it" }
/** The Model providers card: the staged pair, its listing, and Save/Discard. */
@Composable
private fun ProvidersCard(container: AppContainer) {
val scope = rememberCoroutineScope()
var state by remember { mutableStateOf<ProvidersState?>(null) }
var loadError by remember { mutableStateOf<String?>(null) }
var listing by remember { mutableStateOf<ListingState>(ListingState.Idle) }
var draftProvider by remember { mutableStateOf<String?>(null) }
var draftModel by remember { mutableStateOf(DEFAULT_MODEL) }
var saving by remember { mutableStateOf(false) }
var savedPair by remember { mutableStateOf<ActivePair?>(null) }
var saveError by remember { mutableStateOf<String?>(null) }
fun defaultOf(id: String?): String =
state?.providers?.firstOrNull { it.id == id }?.defaultModel ?: ""
fun loadModels(id: String) {
listing = ListingState.Loading
scope.launch {
when (val result = container.api.providerModels(id)) {
is ClawResult.Ok -> listing = ListingState.Available(result.value.models)
is ClawResult.HttpError ->
// A 404 is the documented "no live listing", not a
// failure: the instance still switches on its default model.
listing = ListingState.Unavailable("HTTP ${result.code}")
is ClawResult.Network -> listing = ListingState.Unavailable(result.message)
}
}
}
LaunchedEffect(Unit) {
when (val result = container.api.providers()) {
is ClawResult.Ok -> {
state = result.value
val active = result.value.active
draftProvider = active.provider
draftModel = if (active.model == defaultOf(active.provider)) DEFAULT_MODEL else active.model
loadModels(active.provider)
}
is ClawResult.HttpError -> loadError = "HTTP ${result.code}" + (result.body?.let { " — $it" } ?: "")
is ClawResult.Network -> loadError = result.message
}
}
val active = state?.active
val dirty = active != null && draftProvider != null && (
draftProvider != active.provider ||
(draftModel.ifBlank { defaultOf(draftProvider) }) != active.model
)
RhemaCard(
title = stringResource(R.string.card_providers),
meta = stringResource(R.string.providers_hint),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
val currentLoadError = loadError
val currentState = state
when {
currentLoadError != null -> AppCallout(
tone = CalloutTone.Error,
text = stringResource(R.string.providers_error, currentLoadError),
)
currentState == null -> Text(
stringResource(R.string.providers_loading),
style = MaterialTheme.typography.bodySmall,
color = JadeiteText3,
)
else -> {
Text(
stringResource(R.string.providers_field_provider),
style = MaterialTheme.typography.labelMedium,
color = JadeiteText3,
)
RhemaSelect(
selected = draftProvider,
options = currentState.providers.map { it.id to it.id },
enabled = !saving,
onSelect = { id ->
draftProvider = id
draftModel = DEFAULT_MODEL
loadModels(id)
},
)
Text(
stringResource(R.string.providers_field_model),
style = MaterialTheme.typography.labelMedium,
color = JadeiteText3,
)
RhemaSelect(
selected = draftModel,
options = when (val l = listing) {
is ListingState.Available ->
listOf(DEFAULT_MODEL to stringResource(R.string.providers_default_option)) +
l.models.map { it.id to it.id }
else -> listOf(DEFAULT_MODEL to stringResource(R.string.providers_default_option))
},
enabled = !saving,
onSelect = { draftModel = it },
)
if (listing is ListingState.Unavailable) {
Text(
stringResource(R.string.providers_none),
style = MaterialTheme.typography.bodySmall,
color = JadeiteText3,
)
}
if (dirty) {
AppCallout(
tone = CalloutTone.Warn,
title = stringResource(R.string.providers_staged),
text = stringResource(R.string.providers_staged_detail),
)
}
savedPair?.let { pair ->
AppCallout(
tone = CalloutTone.Ok,
text = stringResource(R.string.providers_saved, pair.provider, pair.model),
)
}
saveError?.let { err ->
AppCallout(
tone = CalloutTone.Error,
text = stringResource(R.string.providers_error, err),
)
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(
enabled = dirty && !saving,
onClick = {
val activeNow = state?.active ?: return@OutlinedButton
draftProvider = activeNow.provider
draftModel =
if (activeNow.model == defaultOf(activeNow.provider)) DEFAULT_MODEL else activeNow.model
savedPair = null
saveError = null
},
) {
Text(stringResource(R.string.providers_discard))
}
Button(
enabled = dirty && !saving && draftProvider != null,
onClick = {
val provider = draftProvider ?: return@Button
saving = true
savedPair = null
saveError = null
scope.launch {
when (
val result = container.api.setActiveProvider(
provider,
draftModel.ifBlank { null },
)
) {
is ClawResult.Ok -> {
// The route answers the new pair only;
// carry the provider list forward.
val current = state
state = if (current != null) {
current.copy(active = result.value.active)
} else {
ProvidersState(result.value.active, emptyList())
}
savedPair = result.value.active
draftProvider = result.value.active.provider
draftModel = if (
result.value.active.model == defaultOf(result.value.active.provider)
) {
DEFAULT_MODEL
} else {
result.value.active.model
}
}
is ClawResult.HttpError ->
saveError = "HTTP ${result.code}" + (result.body?.let { " — $it" } ?: "")
is ClawResult.Network -> saveError = result.message
}
saving = false
}
},
) {
Text(stringResource(R.string.providers_save))
}
}
}
}
}
}
}
private sealed interface ListingState {
data object Idle : ListingState
data object Loading : ListingState
data class Available(val models: List<ModelCard>) : ListingState
data class Unavailable(val reason: String) : ListingState
}
private const val DEFAULT_MODEL = ""
/** The design's input voice: sunken ground, hairline border, accent focus. */
@Composable
private fun sunkenFieldColors() = OutlinedTextFieldDefaults.colors(
focusedBorderColor = JadeiteAccent,
unfocusedBorderColor = JadeiteBorder,
focusedContainerColor = JadeiteSunken,
unfocusedContainerColor = JadeiteSunken,
cursorColor = JadeiteAccentText,
focusedTextColor = JadeiteText,
unfocusedTextColor = JadeiteText,
)
@@ -0,0 +1,78 @@
package rs.rhema.phone.ui
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Shapes
import androidx.compose.material3.darkColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
// The Jadeite dark tokens, lifted from crates/rhema-code/src/palette.rs
// DARK: one design system across the TUI, the web UI, and this app.
// Dark is the design's primary; there is deliberately no light scheme
// and no dynamic color — the palette is the brand.
/** The design's dark ground; also the system-bar scrim. */
internal val JadeiteGround = Color(0xFF0F1413)
internal val JadeiteSurface = Color(0xFF171D1B)
internal val JadeiteElevated = Color(0xFF1F2624)
internal val JadeiteSunken = Color(0xFF0A0F0E)
internal val JadeiteBorder = Color(0xFF28312E)
internal val JadeiteBorderStrong = Color(0xFF3D4844)
internal val JadeiteText = Color(0xFFEEF3F1)
internal val JadeiteText2 = Color(0xFFB9C6C1)
internal val JadeiteText3 = Color(0xFF87948F)
internal val JadeiteAccent = Color(0xFF35A882)
internal val JadeiteAccentText = Color(0xFF64C9A3)
internal val JadeiteOnAccent = Color(0xFF07110D)
internal val JadeiteOk = Color(0xFF4FBF94)
internal val JadeiteWarn = Color(0xFFD9A643)
internal val JadeiteError = Color(0xFFE4687A)
internal val JadeiteInfo = Color(0xFF8FA6B8)
/** Machine spellings — keys, model ids, outcomes — render mono. */
internal val JadeiteMono: FontFamily = FontFamily.Monospace
private val JadeiteDark = darkColorScheme(
primary = JadeiteAccent,
onPrimary = JadeiteOnAccent,
primaryContainer = JadeiteElevated,
onPrimaryContainer = JadeiteAccentText,
secondary = JadeiteAccentText,
onSecondary = JadeiteOnAccent,
tertiary = JadeiteInfo,
background = JadeiteGround,
onBackground = JadeiteText,
surface = JadeiteSurface,
onSurface = JadeiteText,
surfaceVariant = JadeiteElevated,
onSurfaceVariant = JadeiteText2,
surfaceContainerLowest = JadeiteGround,
surfaceContainerLow = JadeiteSurface,
surfaceContainer = JadeiteSurface,
surfaceContainerHigh = JadeiteElevated,
surfaceContainerHighest = JadeiteElevated,
outline = JadeiteBorder,
outlineVariant = JadeiteBorderStrong,
error = JadeiteError,
)
// The design's shape language: soft cards on a hairline grid, controls a
// step softer. Default Material radii read as someone else's app.
private val JadeiteShapes = Shapes(
extraSmall = RoundedCornerShape(6.dp),
small = RoundedCornerShape(8.dp),
medium = RoundedCornerShape(10.dp),
large = RoundedCornerShape(14.dp),
)
/** The app's theme: Jadeite dark, always — matching the TUI and the web UI. */
@Composable
fun RhemaTheme(content: @Composable () -> Unit) {
MaterialTheme(
colorScheme = JadeiteDark,
shapes = JadeiteShapes,
content = content,
)
}
@@ -0,0 +1,9 @@
package rs.rhema.phone.ui
// Screen state holds the failure data, not a formatted string; user-visible
// text is resolved with stringResource at render time so configuration
// changes re-resolve it.
sealed interface UiMessage {
data class Http(val code: Int, val detail: String? = null) : UiMessage
data class Network(val message: String) : UiMessage
}