A native client for a LLeMbas instance on the server's /api/v2, and the phone's digital assistant. - Sign in by device code; the token sealed in the Android Keystore; several instances. - Chats and agent chats: the list, a chat with its reply streaming as JSON server-sent events (reconnecting, whole blocks), thinking, tool calls, steered messages, the plan, jobs, stop, edit, regenerate, continue, the model, effort and Plan mode, attachments and dictation. - Cards in a sheet, answered as the page's form says it; first answer wins. - Notifications through UnifiedPush, no Google services; an approval can be answered from its notification. - The digital assistant: a VoiceInteractionService with its session (a sheet over the current app, "Include screen" off by default), a recognition service through the instance's speech-to-text, the lock-screen path that asks to unlock before sending, a Quick Settings tile and an Ask shortcut. - Share to LLeMbas; Moria and Shire from the server's tokens; nine languages; a self-updater in the `full` flavour, none in `fdroid`. Generated and pinned from the server, each checked in CI: the theme (tokens.lock.json), the contract (contract/lock.json, server 2124ba9), the strings and the icons. Built and tested only on GitHub Actions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
96 files changed
+7932
No files matched your search
@@ -0,0 +1,79 @@
|
||||
package eu.llembas.android.ui
|
||||
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.text.method.LinkMovementMethod
|
||||
import android.util.TypedValue
|
||||
import android.widget.TextView
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import io.noties.markwon.AbstractMarkwonPlugin
|
||||
import io.noties.markwon.Markwon
|
||||
import io.noties.markwon.MarkwonConfiguration
|
||||
import io.noties.markwon.core.MarkwonTheme
|
||||
import io.noties.markwon.ext.strikethrough.StrikethroughPlugin
|
||||
import io.noties.markwon.ext.tables.TablePlugin
|
||||
|
||||
/** Schemes a link from a model may open. Anything else -- `javascript:`, `intent:`, `file:` -- is inert. */
|
||||
private val OPENABLE = setOf("http", "https", "mailto")
|
||||
|
||||
/**
|
||||
* Markdown from a model, drawn natively. Model output is untrusted here exactly as on the web
|
||||
* page, so the rules are the server's: no images are loaded at all (an image URL can carry what
|
||||
* the model read out of a page to somebody else's server), raw HTML is shown as text (there is
|
||||
* no HTML plugin), and a link opens outside the app, in the browser, and only for the schemes
|
||||
* above.
|
||||
*/
|
||||
fun markwon(context: Context, codeBg: Int, link: Int): Markwon = Markwon.builder(context)
|
||||
.usePlugin(StrikethroughPlugin.create())
|
||||
.usePlugin(TablePlugin.create(context))
|
||||
.usePlugin(
|
||||
object : AbstractMarkwonPlugin() {
|
||||
override fun configureTheme(builder: MarkwonTheme.Builder) {
|
||||
builder.codeBackgroundColor(codeBg).codeBlockBackgroundColor(codeBg).linkColor(link)
|
||||
}
|
||||
|
||||
override fun configureConfiguration(builder: MarkwonConfiguration.Builder) {
|
||||
builder.linkResolver { view, url ->
|
||||
val uri = Uri.parse(url)
|
||||
if (uri.scheme?.lowercase() in OPENABLE) {
|
||||
try {
|
||||
view.context.startActivity(Intent(Intent.ACTION_VIEW, uri).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
} catch (_: ActivityNotFoundException) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.build()
|
||||
|
||||
@Composable
|
||||
fun MarkdownText(markdown: String, modifier: Modifier = Modifier, color: Color? = null) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val ink = (color ?: palette.ink).toArgb()
|
||||
val engine = remember(palette) { markwon(context, palette.codeBg.toArgb(), palette.accent.toArgb()) }
|
||||
AndroidView(
|
||||
modifier = modifier,
|
||||
factory = { ctx ->
|
||||
TextView(ctx).apply {
|
||||
setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f)
|
||||
setTextIsSelectable(true)
|
||||
movementMethod = LinkMovementMethod.getInstance()
|
||||
}
|
||||
},
|
||||
update = { view ->
|
||||
view.setTextColor(ink)
|
||||
engine.setMarkdown(view, markdown)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
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.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Article
|
||||
import androidx.compose.material.icons.filled.AttachFile
|
||||
import androidx.compose.material.icons.filled.Build
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.Groups
|
||||
import androidx.compose.material.icons.filled.Language
|
||||
import androidx.compose.material.icons.filled.Psychology
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
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.vector.ImageVector
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.ui.MarkdownText
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
private val Rounded = RoundedCornerShape(10.dp)
|
||||
|
||||
/** The person's own turn: their words as typed (never markdown), and what they attached. */
|
||||
@Composable
|
||||
fun UserBubble(message: Message, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
Column(
|
||||
modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 48.dp)
|
||||
.background(palette.bubbleUser, Rounded)
|
||||
.border(1.dp, palette.border, Rounded)
|
||||
.padding(12.dp),
|
||||
) {
|
||||
if (!message.text.isNullOrBlank()) Text(message.text, color = palette.ink)
|
||||
message.attachments.forEach { a ->
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 6.dp)) {
|
||||
Icon(Icons.Filled.AttachFile, contentDescription = null, modifier = Modifier.size(16.dp), tint = palette.inkMuted)
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Text(a.name, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
if (message.queued) {
|
||||
Text(stringResource(R.string.queued), style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A reply's steps, in the order they happened: the same table of contents the web page draws. */
|
||||
@Composable
|
||||
fun Steps(steps: List<Step>, modifier: Modifier = Modifier) {
|
||||
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
steps.forEach { step ->
|
||||
when (step.kind) {
|
||||
"thinking" -> Thinking(step)
|
||||
"text" -> MarkdownText(step.markdown.orEmpty(), modifier = Modifier.fillMaxWidth())
|
||||
"tools" -> step.calls.forEach { ToolCallBlock(it) }
|
||||
"steer" -> step.messages.forEach { Steered(it.text) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Thinking(step: Step) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(step.index, step.open) { mutableStateOf(false) }
|
||||
Column(
|
||||
Modifier.fillMaxWidth().background(palette.bgSunken, Rounded).clickable { open = !open }.padding(10.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Psychology, contentDescription = null, modifier = Modifier.size(16.dp), tint = palette.inkFaint)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
stringResource(if (step.open) R.string.thinking else R.string.thought) + (step.label?.let { " $it" } ?: ""),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = palette.inkMuted,
|
||||
)
|
||||
}
|
||||
AnimatedVisibility(open) {
|
||||
Text(step.text.orEmpty(), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, modifier = Modifier.padding(top = 6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Steered(text: String) {
|
||||
val palette = LocalPalette.current
|
||||
Row(Modifier.fillMaxWidth().padding(start = 24.dp)) {
|
||||
Text("↳ $text", style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
|
||||
private fun iconFor(kind: String): ImageVector = when (kind) {
|
||||
"shell" -> Icons.Filled.Terminal
|
||||
"edit" -> Icons.Filled.Edit
|
||||
"read" -> Icons.AutoMirrored.Filled.Article
|
||||
"search" -> Icons.Filled.Search
|
||||
"web" -> Icons.Filled.Language
|
||||
"task" -> Icons.Filled.Groups
|
||||
else -> Icons.Filled.Build
|
||||
}
|
||||
|
||||
/**
|
||||
* One tool call, the way its kind is read (`services/tool_blocks.py`): a command shows the
|
||||
* command, an edit its change, a read the file. What came back is behind a tap, in its own
|
||||
* scroller, so a megabyte of output never becomes the page.
|
||||
*/
|
||||
@Composable
|
||||
fun ToolCallBlock(call: ToolCall, depth: Int = 0) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(call.id ?: call.block.title) { mutableStateOf(call.block.kind == "edit") }
|
||||
val failed = call.status == "error" || !call.error.isNullOrEmpty()
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = (depth * 16).dp)
|
||||
.border(1.dp, if (failed) palette.danger else palette.border, Rounded)
|
||||
.clickable { open = !open }
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(iconFor(call.block.kind), contentDescription = null, modifier = Modifier.size(16.dp), tint = palette.inkMuted)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
call.block.title.ifBlank { call.name },
|
||||
fontFamily = if (call.block.kind == "shell") FontFamily.Monospace else null,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
maxLines = if (open) 6 else 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
call.block.chips.forEach { chip ->
|
||||
Text(chip, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
}
|
||||
call.purpose?.takeIf { it.isNotBlank() }?.let {
|
||||
Text(it, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
|
||||
}
|
||||
AnimatedVisibility(open) {
|
||||
val output = listOfNotNull(call.diff, call.text, call.error).joinToString("\n").trim()
|
||||
Column {
|
||||
if (output.isNotEmpty()) {
|
||||
Text(
|
||||
output,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = 12.sp,
|
||||
color = if (failed) palette.danger else palette.ink,
|
||||
modifier = Modifier
|
||||
.padding(top = 8.dp)
|
||||
.fillMaxWidth()
|
||||
.heightIn(max = 320.dp)
|
||||
.background(palette.codeBg, Rounded)
|
||||
.verticalScroll(rememberScrollState())
|
||||
.horizontalScroll(rememberScrollState())
|
||||
.padding(8.dp),
|
||||
)
|
||||
}
|
||||
if (call.truncated) {
|
||||
Text(stringResource(R.string.output_cut), style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
|
||||
}
|
||||
call.children?.forEach { ToolCallBlock(it, depth + 1) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A finished or failed reply's foot: what it cost, and why it stopped if it did. */
|
||||
@Composable
|
||||
fun ReplyFoot(message: Message) {
|
||||
val palette = LocalPalette.current
|
||||
message.error?.let {
|
||||
Text(it, color = palette.danger, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
val m = message.metrics ?: return
|
||||
if (m.completionTokens == 0 && m.elapsedMs == 0L) return
|
||||
val parts = buildList {
|
||||
message.model?.let { add(it) }
|
||||
if (m.completionTokens > 0) add("${if (m.estimated) "~" else ""}${m.completionTokens} tok")
|
||||
if (m.tokPerSecond > 0) add("${"%.1f".format(m.tokPerSecond)} tok/s")
|
||||
if (m.percent > 0) add("${m.percent}%")
|
||||
}
|
||||
Text(parts.joinToString(" · "), style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, modifier = Modifier.widthIn(max = 600.dp))
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
@file:OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class, androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
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.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Card
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.CardItem
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.Plan
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
/** The sentinel the web card's "Something else" row submits (`interaction.OTHER`). */
|
||||
private const val OTHER = "__other__"
|
||||
|
||||
/**
|
||||
* A card the reply is waiting on, with the controls the web page gives it. Whatever is pressed
|
||||
* becomes a [CardAnswer] in the page form's own terms, so the server reads it through the same
|
||||
* lines (`answer_card`) and first answer wins wherever it was given.
|
||||
*/
|
||||
@Composable
|
||||
fun CardSheet(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
Column(
|
||||
Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(20.dp).navigationBarsPadding(),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
if (card.why.isNotBlank()) {
|
||||
Text(card.why, style = MaterialTheme.typography.labelMedium, color = LocalPalette.current.inkMuted)
|
||||
}
|
||||
when (card.kind) {
|
||||
"approval" -> Approval(card, onAnswer)
|
||||
"plan" -> PlanCard(card, onAnswer)
|
||||
else -> Questions(card, onAnswer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val edits = remember { mutableStateMapOf<String, String>() }
|
||||
var reason by remember { mutableStateOf("") }
|
||||
var refusing by remember { mutableStateOf(false) }
|
||||
Text(stringResource(R.string.card_approval), style = MaterialTheme.typography.titleMedium)
|
||||
card.items.forEach { item ->
|
||||
if (item.editable) {
|
||||
OutlinedTextField(
|
||||
value = edits[item.key] ?: item.title,
|
||||
onValueChange = { edits[item.key] = it },
|
||||
textStyle = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
} else {
|
||||
Text(item.title, fontFamily = FontFamily.Monospace)
|
||||
}
|
||||
if (item.detail.isNotBlank()) Text(item.detail, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
if (item.purpose.isNotBlank()) Text(item.purpose, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
}
|
||||
// A corrected command goes with an allow, never with a refusal.
|
||||
val texts = edits.filter { (key, value) -> card.items.firstOrNull { it.key == key }?.title != value }
|
||||
if (refusing) {
|
||||
OutlinedTextField(
|
||||
value = reason,
|
||||
onValueChange = { reason = it },
|
||||
label = { Text(stringResource(R.string.card_reason)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = { onAnswer(CardAnswer(verdict = "deny", reason = reason)) }) { Text(stringResource(R.string.card_deny)) }
|
||||
TextButton(onClick = { refusing = false }) { Text(stringResource(R.string.cancel)) }
|
||||
}
|
||||
} else {
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = { onAnswer(CardAnswer(verdict = "allow", texts = texts)) }) { Text(stringResource(R.string.card_allow_once)) }
|
||||
OutlinedButton(onClick = { onAnswer(CardAnswer(verdict = "allow_always", texts = texts)) }) {
|
||||
Text(stringResource(R.string.card_allow_always))
|
||||
}
|
||||
TextButton(onClick = { refusing = true }) { Text(stringResource(R.string.card_deny)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Questions(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val picked = remember { mutableStateMapOf<String, Set<String>>() }
|
||||
val typed = remember { mutableStateMapOf<String, String>() }
|
||||
card.items.forEach { item ->
|
||||
if (item.header.isNotBlank()) Text(item.header, style = MaterialTheme.typography.labelMedium, color = palette.inkMuted)
|
||||
Text(item.title, style = MaterialTheme.typography.titleMedium)
|
||||
item.options.forEach { option ->
|
||||
val chosen = option.label in (picked[item.key] ?: emptySet())
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().clickable { picked[item.key] = toggle(item, picked[item.key], option.label) },
|
||||
) {
|
||||
if (item.multiple) {
|
||||
Checkbox(checked = chosen, onCheckedChange = { picked[item.key] = toggle(item, picked[item.key], option.label) })
|
||||
} else {
|
||||
RadioButton(selected = chosen, onClick = { picked[item.key] = toggle(item, picked[item.key], option.label) })
|
||||
}
|
||||
Column {
|
||||
Text(option.label + if (option.recommended) " · " + stringResource(R.string.card_recommended) else "")
|
||||
if (option.description.isNotBlank()) {
|
||||
Text(option.description, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (item.freeText) {
|
||||
OutlinedTextField(
|
||||
value = typed[item.key].orEmpty(),
|
||||
onValueChange = { typed[item.key] = it },
|
||||
label = { Text(stringResource(if (item.options.isEmpty()) R.string.card_answer else R.string.card_something_else)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
val ready = card.items.all { !picked[it.key].isNullOrEmpty() || !typed[it.key].isNullOrBlank() }
|
||||
Button(
|
||||
enabled = ready,
|
||||
onClick = {
|
||||
val choices = card.items.associate { item ->
|
||||
val picks = picked[item.key].orEmpty().toList()
|
||||
// Typed beside options is "something else": the sentinel says so, as the page's does.
|
||||
item.key to if (!typed[item.key].isNullOrBlank() && item.options.isNotEmpty()) picks + OTHER else picks
|
||||
}.filterValues { it.isNotEmpty() }
|
||||
onAnswer(CardAnswer(choices = choices, texts = typed.filterValues { it.isNotBlank() }))
|
||||
},
|
||||
) { Text(stringResource(R.string.card_send)) }
|
||||
}
|
||||
|
||||
private fun toggle(item: CardItem, now: Set<String>?, label: String): Set<String> {
|
||||
val set = now.orEmpty()
|
||||
return when {
|
||||
!item.multiple -> setOf(label)
|
||||
label in set -> set - label
|
||||
else -> set + label
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PlanCard(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
val item = card.items.firstOrNull() ?: return
|
||||
var mode by remember { mutableStateOf("edit") }
|
||||
var revising by remember { mutableStateOf(false) }
|
||||
var feedback by remember { mutableStateOf("") }
|
||||
val plan = item.plan?.let { runCatching { LembasJson.decodeFromJsonElement(Plan.serializer(), it) }.getOrNull() }
|
||||
Text(plan?.title?.ifBlank { null } ?: item.title, style = MaterialTheme.typography.titleMedium)
|
||||
plan?.let { PlanBody(it) }
|
||||
if (item.modeChoice) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
RadioButton(selected = mode == "edit", onClick = { mode = "edit" })
|
||||
Text(stringResource(R.string.mode_edit))
|
||||
RadioButton(selected = mode == "manual", onClick = { mode = "manual" })
|
||||
Text(stringResource(R.string.mode_manual))
|
||||
}
|
||||
}
|
||||
if (revising) {
|
||||
OutlinedTextField(
|
||||
value = feedback,
|
||||
onValueChange = { feedback = it },
|
||||
label = { Text(stringResource(R.string.plan_what_to_change)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Button(onClick = { onAnswer(CardAnswer(verdict = "deny", reason = feedback)) }) { Text(stringResource(R.string.card_send)) }
|
||||
} else {
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = {
|
||||
onAnswer(CardAnswer(verdict = "allow", choices = if (item.modeChoice) mapOf(item.key to listOf(mode)) else emptyMap()))
|
||||
}) { Text(stringResource(R.string.plan_approve)) }
|
||||
OutlinedButton(onClick = { revising = true }) { Text(stringResource(R.string.plan_revise)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A plan's phases and tasks, ticked as the reply works through them. */
|
||||
@Composable
|
||||
fun PlanBody(plan: Plan) {
|
||||
val palette = LocalPalette.current
|
||||
if (plan.summary.isNotBlank()) Text(plan.summary, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
plan.phases.forEach { phase ->
|
||||
if (plan.phases.size > 1) Text(phase.title, style = MaterialTheme.typography.labelLarge)
|
||||
phase.tasks.forEach { task ->
|
||||
val mark = when (task.status) {
|
||||
"done" -> "✓"
|
||||
"doing" -> "▸"
|
||||
"dropped" -> "–"
|
||||
else -> "○"
|
||||
}
|
||||
Text("$mark ${task.text}", style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
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.material.icons.filled.AttachFile
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.AssistChip
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.InputChip
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SheetValue
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
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.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.assist.Recorder
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit = {}, model: ChatViewModel = viewModel(key = chatId ?: "new")) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
val palette = LocalPalette.current
|
||||
val list = rememberLazyListState()
|
||||
val snackbar = remember { SnackbarHostState() }
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
var editing by remember { mutableStateOf<Message?>(null) }
|
||||
|
||||
LaunchedEffect(chatId) { model.open(chatId) }
|
||||
// A new chat gets its id from its first message; the route follows, so Back and a
|
||||
// rotation land on the chat rather than on an empty composer.
|
||||
LaunchedEffect(state.chat?.id) { state.chat?.id?.let { if (it != chatId) onOpened(it) } }
|
||||
LaunchedEffect(state.error, state.notice) {
|
||||
(state.error ?: state.notice)?.let {
|
||||
snackbar.showSnackbar(it)
|
||||
model.clearError()
|
||||
}
|
||||
}
|
||||
val live = state.live
|
||||
val rows = state.messages
|
||||
LaunchedEffect(rows.size, live?.shown?.size) {
|
||||
if (rows.isNotEmpty()) list.animateScrollToItem(rows.size - 1)
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
snackbarHost = { SnackbarHost(snackbar) },
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Text(
|
||||
state.chat?.title?.ifBlank { null } ?: stringResource(R.string.new_chat),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
},
|
||||
actions = {
|
||||
if (state.chat != null) {
|
||||
IconButton(onClick = { menu = true }) {
|
||||
Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more))
|
||||
}
|
||||
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.continue_reply)) }, onClick = {
|
||||
menu = false
|
||||
model.continueChat()
|
||||
})
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.archive)) }, onClick = {
|
||||
menu = false
|
||||
model.change("archived", "true")
|
||||
onBack()
|
||||
})
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.delete)) }, onClick = {
|
||||
menu = false
|
||||
model.delete(onBack)
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
Column(Modifier.background(palette.surface).navigationBarsPadding().imePadding()) {
|
||||
if (state.loading || state.uploading) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
live?.plan?.let { plan ->
|
||||
Column(Modifier.fillMaxWidth().heightIn(max = 180.dp).padding(horizontal = 16.dp, vertical = 8.dp)) {
|
||||
PlanBody(plan)
|
||||
}
|
||||
}
|
||||
state.chat?.plan?.let { _ ->
|
||||
if (live == null && state.chat?.mode == "plan") {
|
||||
TextButton(onClick = { model.executePlan() }, modifier = Modifier.padding(horizontal = 8.dp)) {
|
||||
Text(stringResource(R.string.plan_carry_out))
|
||||
}
|
||||
}
|
||||
}
|
||||
if (live != null && live.jobs.isNotEmpty()) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()).padding(horizontal = 12.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
live.jobs.forEach { job ->
|
||||
AssistChip(onClick = {}, label = { Text("${job.id} · ${job.description.ifBlank { job.command }} · ${job.state}", maxLines = 1) })
|
||||
}
|
||||
}
|
||||
}
|
||||
if (live != null && live.status.isNotBlank()) {
|
||||
Text(live.status, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, modifier = Modifier.padding(horizontal = 16.dp))
|
||||
}
|
||||
Composer(model, state)
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
LazyColumn(
|
||||
state = list,
|
||||
modifier = Modifier.fillMaxSize().padding(padding),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
if (state.more) {
|
||||
item { TextButton(onClick = model::older) { Text(stringResource(R.string.older)) } }
|
||||
}
|
||||
if (rows.isEmpty() && !state.loading) {
|
||||
item {
|
||||
Box(Modifier.fillMaxWidth().padding(top = 96.dp), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.empty_chat), color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
items(rows, key = { it.id }) { message ->
|
||||
when {
|
||||
message.isUser -> Column {
|
||||
UserBubble(message)
|
||||
if (!message.machine && live == null) {
|
||||
TextButton(onClick = { editing = message }, modifier = Modifier.align(Alignment.End)) {
|
||||
Text(stringResource(R.string.edit))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
live != null && live.messageId == message.id && live.finished == null -> Column {
|
||||
Steps(live.shown)
|
||||
if (live.shown.isEmpty()) Text(stringResource(R.string.loading_line), color = palette.inkFaint)
|
||||
live.metrics?.let { m -> ReplyFoot(message.copy(metrics = m)) }
|
||||
}
|
||||
|
||||
else -> Column {
|
||||
Steps(message.steps)
|
||||
ReplyFoot(message)
|
||||
if (live == null && message == rows.lastOrNull()) {
|
||||
Row {
|
||||
TextButton(onClick = { model.regenerate(message) }) { Text(stringResource(R.string.regenerate)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A card the reply is waiting on, as a sheet over the chat. One at a time, in the order asked.
|
||||
live?.cards?.firstOrNull()?.let { card ->
|
||||
ModalBottomSheet(
|
||||
onDismissRequest = {},
|
||||
// Not dismissable by a swipe: the reply is stopped until the card is answered, and
|
||||
// a card swiped away would leave it waiting with nothing on screen to say why.
|
||||
sheetState = rememberModalBottomSheetState(
|
||||
skipPartiallyExpanded = true,
|
||||
confirmValueChange = { it != SheetValue.Hidden },
|
||||
),
|
||||
) {
|
||||
CardSheet(card) { answer -> model.answer(card, answer) }
|
||||
}
|
||||
}
|
||||
|
||||
editing?.let { message ->
|
||||
var text by remember(message.id) { mutableStateOf(message.text.orEmpty()) }
|
||||
AlertDialog(
|
||||
onDismissRequest = { editing = null },
|
||||
title = { Text(stringResource(R.string.edit)) },
|
||||
text = { OutlinedTextField(value = text, onValueChange = { text = it }, modifier = Modifier.fillMaxWidth()) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
model.edit(message, text)
|
||||
editing = null
|
||||
}) { Text(stringResource(R.string.card_send)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { editing = null }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
@Composable
|
||||
private fun Composer(model: ChatViewModel, state: ChatState) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var text by rememberSaveable { mutableStateOf("") }
|
||||
var chosenModel by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var planMode by rememberSaveable { mutableStateOf(false) }
|
||||
var listening by remember { mutableStateOf(false) }
|
||||
val recorder = remember { Recorder(scope) }
|
||||
val pick = rememberLauncherForActivityResult(ActivityResultContracts.GetMultipleContents()) { model.attach(it) }
|
||||
val askMic = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (granted) {
|
||||
recorder.start()
|
||||
listening = true
|
||||
}
|
||||
}
|
||||
val chat = state.chat
|
||||
val current = chat?.model ?: chosenModel ?: state.models.firstOrNull { it.default }?.id
|
||||
val running = state.live != null && state.live.finished == null
|
||||
|
||||
Column(Modifier.fillMaxWidth().padding(8.dp)) {
|
||||
if (state.pending.isNotEmpty()) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
state.pending.forEach { a ->
|
||||
InputChip(
|
||||
selected = false,
|
||||
onClick = { model.unattach(a) },
|
||||
label = { Text(a.name, maxLines = 1) },
|
||||
trailingIcon = { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.remove)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
ModelChip(state.models, current) { id ->
|
||||
if (chat == null) chosenModel = id else model.change("model", id)
|
||||
}
|
||||
val efforts = state.models.firstOrNull { it.id == current }?.efforts.orEmpty()
|
||||
if (efforts.isNotEmpty()) {
|
||||
EffortChip(efforts, chat?.effort) { model.change("effort", it ?: "off") }
|
||||
}
|
||||
if (chat == null || !chat.isAgent) {
|
||||
FilterChip(
|
||||
selected = if (chat == null) planMode else chat.mode == "plan",
|
||||
onClick = {
|
||||
if (chat == null) planMode = !planMode else model.change("mode", if (chat.mode == "plan") "" else "plan")
|
||||
},
|
||||
label = { Text(stringResource(R.string.mode_plan)) },
|
||||
)
|
||||
} else {
|
||||
AssistChip(onClick = {}, label = { Text(chat.mode.replaceFirstChar { it.uppercase() }) })
|
||||
}
|
||||
}
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
IconButton(onClick = { pick.launch("*/*") }) {
|
||||
Icon(Icons.Filled.AttachFile, contentDescription = stringResource(R.string.attach))
|
||||
}
|
||||
TextField(
|
||||
value = text,
|
||||
onValueChange = { text = it },
|
||||
placeholder = { Text(stringResource(if (listening) R.string.listening else R.string.composer_hint)) },
|
||||
modifier = Modifier.weight(1f).heightIn(max = 200.dp),
|
||||
)
|
||||
IconButton(onClick = {
|
||||
if (listening) {
|
||||
listening = false
|
||||
scope.launch {
|
||||
val wav = recorder.stop()
|
||||
if (wav.isNotEmpty()) {
|
||||
runCatching { context.lembas.instances.client()?.transcribe(wav) }
|
||||
.onSuccess { heard -> if (!heard.isNullOrBlank()) text = (text + " " + heard).trim() }
|
||||
}
|
||||
}
|
||||
} else if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
|
||||
recorder.start()
|
||||
listening = true
|
||||
} else {
|
||||
askMic.launch(Manifest.permission.RECORD_AUDIO)
|
||||
}
|
||||
}) {
|
||||
Icon(if (listening) Icons.Filled.Stop else Icons.Filled.Mic, contentDescription = stringResource(R.string.dictate))
|
||||
}
|
||||
if (running && text.isBlank()) {
|
||||
IconButton(onClick = model::stop) { Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop)) }
|
||||
} else {
|
||||
IconButton(
|
||||
enabled = text.isNotBlank() || state.pending.isNotEmpty(),
|
||||
onClick = {
|
||||
model.send(text, model = chosenModel, mode = if (planMode) "plan" else null)
|
||||
text = ""
|
||||
},
|
||||
) { Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ModelChip(models: List<ModelInfo>, current: String?, onPick: (String) -> Unit) {
|
||||
var open by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
AssistChip(onClick = { open = true }, label = { Text(models.firstOrNull { it.id == current }?.name ?: current ?: "—", maxLines = 1) })
|
||||
DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
|
||||
models.forEach { m ->
|
||||
DropdownMenuItem(text = { Text(m.name) }, onClick = {
|
||||
open = false
|
||||
onPick(m.id)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EffortChip(efforts: List<String>, current: String?, onPick: (String?) -> Unit) {
|
||||
var open by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
AssistChip(onClick = { open = true }, label = { Text(current ?: stringResource(R.string.effort_off)) })
|
||||
DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.effort_off)) }, onClick = {
|
||||
open = false
|
||||
onPick(null)
|
||||
})
|
||||
efforts.forEach { e ->
|
||||
DropdownMenuItem(text = { Text(e) }, onClick = {
|
||||
open = false
|
||||
onPick(e)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.app.Application
|
||||
import android.net.Uri
|
||||
import android.provider.OpenableColumns
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Attachment
|
||||
import eu.llembas.android.api.Card
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.api.Turn
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
|
||||
data class ChatState(
|
||||
val chat: Chat? = null,
|
||||
val messages: List<Message> = emptyList(),
|
||||
val more: Boolean = false,
|
||||
val live: LiveReply? = null,
|
||||
val models: List<ModelInfo> = emptyList(),
|
||||
val pending: List<Attachment> = emptyList(),
|
||||
val uploading: Boolean = false,
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
/** A card somebody answered elsewhere first: said once, then cleared. */
|
||||
val notice: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* One chat: its transcript, the reply being written, and every control. A new chat has no id
|
||||
* until its first message makes it, as on the web page -- there is no empty chat.
|
||||
*/
|
||||
class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ChatState())
|
||||
val state = _state.asStateFlow()
|
||||
private var following: Job? = null
|
||||
private var api: ApiClient? = null
|
||||
|
||||
private suspend fun api(): ApiClient = api ?: getApplication<Application>().lembas.instances.client()?.also { api = it }
|
||||
?: throw ApiException(401, "Not signed in.")
|
||||
|
||||
private fun fail(e: Throwable) {
|
||||
_state.update { it.copy(error = e.message ?: e.javaClass.simpleName, loading = false, uploading = false) }
|
||||
}
|
||||
|
||||
fun clearError() = _state.update { it.copy(error = null, notice = null) }
|
||||
|
||||
fun open(chatId: String?) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val client = api()
|
||||
_state.update { it.copy(loading = chatId != null) }
|
||||
val models = runCatching { client.models(chatId) }.getOrDefault(emptyList())
|
||||
if (chatId == null) {
|
||||
_state.update { it.copy(models = models, loading = false) }
|
||||
return@launch
|
||||
}
|
||||
val detail = client.chat(chatId)
|
||||
_state.update {
|
||||
it.copy(chat = detail.chat, messages = detail.messages, more = detail.more, models = models, loading = false)
|
||||
}
|
||||
detail.live?.let { follow(it) }
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun older() {
|
||||
val chat = _state.value.chat ?: return
|
||||
val first = _state.value.messages.firstOrNull() ?: return
|
||||
viewModelScope.launch {
|
||||
runCatching { api().messages(chat.id, first.id) }
|
||||
.onSuccess { page -> _state.update { it.copy(messages = page.messages + it.messages, more = page.more) } }
|
||||
.onFailure(::fail)
|
||||
}
|
||||
}
|
||||
|
||||
/** Follow a reply to its end, then whatever the queue started after it. */
|
||||
private fun follow(messageId: String) {
|
||||
val chat = _state.value.chat ?: return
|
||||
following?.cancel()
|
||||
following = viewModelScope.launch {
|
||||
_state.update { it.copy(live = LiveReply(messageId)) }
|
||||
try {
|
||||
StreamClient(api()).follow(chat.id, messageId).collect { frame ->
|
||||
_state.update { s -> s.copy(live = (s.live ?: LiveReply(messageId)).apply(frame.event, frame.data)) }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
val ended = _state.value.live
|
||||
_state.update { s ->
|
||||
val finished = ended?.finished
|
||||
s.copy(
|
||||
live = null,
|
||||
messages = if (finished != null) s.messages.map { if (it.id == finished.id) finished else it } else s.messages,
|
||||
chat = s.chat?.let { c -> ended?.title?.let { c.copy(title = it) } ?: c },
|
||||
)
|
||||
}
|
||||
// The queue handed a waiting prompt to a fresh reply: the transcript has moved on
|
||||
// the server, so it is read again rather than patched.
|
||||
ended?.next?.let { next ->
|
||||
refresh()
|
||||
follow(next)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun refresh() {
|
||||
val chat = _state.value.chat ?: return
|
||||
runCatching { api().chat(chat.id) }.onSuccess { d ->
|
||||
_state.update { it.copy(chat = d.chat, messages = d.messages, more = d.more) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun took(turn: Turn) {
|
||||
_state.update { s ->
|
||||
s.copy(messages = s.messages.filterNot { m -> m.id == turn.message?.id || m.id == turn.reply?.id } + listOfNotNull(turn.message, turn.reply))
|
||||
}
|
||||
turn.reply?.let { follow(it.id) }
|
||||
}
|
||||
|
||||
fun send(text: String, model: String? = null, mode: String? = null, effort: String? = null, temporary: Boolean = false) {
|
||||
val files = _state.value.pending.map { it.id }
|
||||
if (text.isBlank() && files.isEmpty()) return
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val client = api()
|
||||
val chat = _state.value.chat
|
||||
_state.update { it.copy(pending = emptyList()) }
|
||||
if (chat == null) {
|
||||
val made = client.createChat(text, files, model = model, temporary = temporary, effort = effort, mode = mode)
|
||||
_state.update { it.copy(chat = made.chat, messages = listOfNotNull(made.message, made.reply)) }
|
||||
made.reply?.let { follow(it.id) }
|
||||
} else {
|
||||
took(client.sendMessage(chat.id, text, files))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
val chat = _state.value.chat ?: return
|
||||
val live = _state.value.live ?: return
|
||||
viewModelScope.launch { runCatching { api().stop(chat.id, live.messageId) }.onFailure(::fail) }
|
||||
}
|
||||
|
||||
fun regenerate(message: Message) = control { api, chat ->
|
||||
val turn = api.regenerate(chat.id, message.id)
|
||||
_state.update { s -> s.copy(messages = s.messages.map { if (it.id == message.id) turn.reply ?: it else it }) }
|
||||
turn.reply?.let { follow(it.id) }
|
||||
}
|
||||
|
||||
fun edit(message: Message, text: String) = control { api, chat ->
|
||||
val turn = api.edit(chat.id, message.id, text)
|
||||
// Everything after the edited turn is gone on the server; read it back.
|
||||
refresh()
|
||||
turn.reply?.let { follow(it.id) }
|
||||
}
|
||||
|
||||
fun continueChat() = control { api, chat -> took(api.continueChat(chat.id)) }
|
||||
|
||||
fun executePlan() = control { api, chat ->
|
||||
took(api.executePlan(chat.id))
|
||||
refresh()
|
||||
}
|
||||
|
||||
fun answer(card: Card, answer: CardAnswer) = control { api, chat ->
|
||||
try {
|
||||
api.answer(chat.id, card.id, answer)
|
||||
} catch (e: ApiException) {
|
||||
// First answer wins -- on the phone, the page or the device. A 409 is "somebody
|
||||
// already answered", and the stream's next `ask` frame clears the card.
|
||||
if (e.status != 409) throw e
|
||||
_state.update { it.copy(notice = e.message) }
|
||||
}
|
||||
_state.update { s -> s.copy(live = s.live?.let { l -> l.copy(cards = l.cards.filterNot { it.id == card.id }) }) }
|
||||
}
|
||||
|
||||
fun change(key: String, value: String?) = control { api, chat ->
|
||||
val updated = api.updateChat(chat.id, JsonObject(mapOf(key to JsonPrimitive(value))))
|
||||
_state.update { it.copy(chat = updated) }
|
||||
}
|
||||
|
||||
fun delete(then: () -> Unit) = control { api, chat ->
|
||||
api.deleteChat(chat.id)
|
||||
then()
|
||||
}
|
||||
|
||||
fun attach(uris: List<Uri>) {
|
||||
if (uris.isEmpty()) return
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(uploading = true) }
|
||||
try {
|
||||
val resolver = getApplication<Application>().contentResolver
|
||||
for (uri in uris) {
|
||||
val (name, bytes) = withContext(Dispatchers.IO) {
|
||||
val name = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
|
||||
if (c.moveToFirst()) c.getString(0) else null
|
||||
} ?: "file"
|
||||
name to (resolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0))
|
||||
}
|
||||
val mime = resolver.getType(uri) ?: "application/octet-stream"
|
||||
val stored = api().upload(name, mime, bytes, _state.value.chat?.id)
|
||||
_state.update { it.copy(pending = it.pending + stored) }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
_state.update { it.copy(uploading = false) }
|
||||
}
|
||||
}
|
||||
|
||||
fun unattach(attachment: Attachment) {
|
||||
_state.update { s -> s.copy(pending = s.pending.filterNot { it.id == attachment.id }) }
|
||||
}
|
||||
|
||||
private fun control(block: suspend (ApiClient, Chat) -> Unit) {
|
||||
val chat = _state.value.chat ?: return
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
block(api(), chat)
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.chats
|
||||
|
||||
import android.app.Application
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
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.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.Chat
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.PrimaryTabRow
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SwipeToDismissBox
|
||||
import androidx.compose.material3.Tab
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
|
||||
import androidx.compose.material3.rememberSwipeToDismissBoxState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
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.draw.clip
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.put
|
||||
|
||||
data class ChatsState(val chats: List<Chat> = emptyList(), val more: Boolean = false, val loading: Boolean = false, val error: String? = null)
|
||||
|
||||
class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ChatsState())
|
||||
val state = _state.asStateFlow()
|
||||
private var kind = "chat"
|
||||
|
||||
fun load(kind: String) {
|
||||
this.kind = kind
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client() ?: return@launch
|
||||
val page = api.chats(kind = kind)
|
||||
_state.value = ChatsState(chats = page.chats, more = page.more)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = e.message) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun more() {
|
||||
val last = _state.value.chats.lastOrNull() ?: return
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client() ?: return@launch
|
||||
val page = api.chats(kind = kind, before = last.id)
|
||||
_state.update { it.copy(chats = it.chats + page.chats, more = page.more) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = e.message) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Out of the way, and reversible: the web UI's Archive. */
|
||||
fun archive(chat: Chat) {
|
||||
_state.update { s -> s.copy(chats = s.chats.filterNot { it.id == chat.id }) }
|
||||
viewModelScope.launch {
|
||||
runCatching {
|
||||
getApplication<Application>().lembas.instances.client()
|
||||
?.updateChat(chat.id, buildJsonObject { put("archived", true) })
|
||||
}.onFailure { e ->
|
||||
_state.update { it.copy(error = e.message) }
|
||||
load(kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ChatsScreen(onOpen: (String) -> Unit, onNew: () -> Unit, onSettings: () -> Unit, model: ChatsViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
var tab by rememberSaveable { mutableIntStateOf(0) }
|
||||
val kind = if (tab == 0) "chat" else "agent"
|
||||
LaunchedEffect(kind) { model.load(kind) }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.app_name)) },
|
||||
actions = {
|
||||
IconButton(onClick = onSettings) {
|
||||
Icon(Icons.Filled.Settings, contentDescription = stringResource(R.string.settings))
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
floatingActionButton = {
|
||||
if (tab == 0) {
|
||||
ExtendedFloatingActionButton(
|
||||
onClick = onNew,
|
||||
icon = { Icon(Icons.Filled.Add, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.new_chat)) },
|
||||
)
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||
PrimaryTabRow(selectedTabIndex = tab) {
|
||||
Tab(selected = tab == 0, onClick = { tab = 0 }, text = { Text(stringResource(R.string.tab_chats)) })
|
||||
Tab(selected = tab == 1, onClick = { tab = 1 }, text = { Text(stringResource(R.string.tab_agents)) })
|
||||
}
|
||||
state.error?.let {
|
||||
Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
}
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = { model.load(kind) }, modifier = Modifier.fillMaxSize()) {
|
||||
if (state.chats.isEmpty() && !state.loading) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
stringResource(if (tab == 0) R.string.empty_chats else R.string.empty_agents),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(32.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.chats, key = { it.id }) { chat ->
|
||||
ChatRow(chat, onOpen = { onOpen(chat.id) }, onArchive = { model.archive(chat) })
|
||||
HorizontalDivider()
|
||||
}
|
||||
if (state.more) {
|
||||
item {
|
||||
LaunchedEffect(state.chats.size) { model.more() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChatRow(chat: Chat, onOpen: () -> Unit, onArchive: () -> Unit) {
|
||||
val swipe = rememberSwipeToDismissBoxState()
|
||||
SwipeToDismissBox(state = swipe, onDismiss = { onArchive() }, backgroundContent = {
|
||||
Box(
|
||||
Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surfaceContainerHigh).padding(horizontal = 24.dp),
|
||||
contentAlignment = Alignment.CenterStart,
|
||||
) {
|
||||
Text(stringResource(R.string.archive), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}) {
|
||||
ListItem(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen),
|
||||
leadingContent = {
|
||||
Icon(
|
||||
if (chat.isAgent) Icons.Filled.Terminal else Icons.AutoMirrored.Filled.Chat,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
headlineContent = { Text(chat.title.ifBlank { stringResource(R.string.new_chat) }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = {
|
||||
val line = listOfNotNull(chat.model.ifBlank { null }, chat.device?.directory?.ifBlank { null }).joinToString(" · ")
|
||||
if (line.isNotEmpty()) Text(line, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
},
|
||||
trailingContent = {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (chat.unread || chat.running) {
|
||||
Box(
|
||||
Modifier.size(10.dp).clip(CircleShape).background(
|
||||
if (chat.running) MaterialTheme.colorScheme.secondary else MaterialTheme.colorScheme.primary,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.settings
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.provider.Settings
|
||||
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.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
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.RadioButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
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.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.BuildConfig
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.push.Push
|
||||
import eu.llembas.android.update.Updater
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val store = context.lembas.instances
|
||||
val scope = rememberCoroutineScope()
|
||||
val instances by store.instances.collectAsState(initial = emptyList())
|
||||
val active by store.active.collectAsState(initial = null)
|
||||
val prefs by store.prefs.collectAsState(initial = Prefs())
|
||||
var pushNote by remember { mutableStateOf<String?>(null) }
|
||||
var updateNote by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.settings)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) }
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(
|
||||
Modifier.padding(padding).fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Section(stringResource(R.string.settings_instances))
|
||||
instances.forEach { instance ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { scope.launch { store.use(instance.id) } },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
RadioButton(selected = instance.id == active?.id, onClick = { scope.launch { store.use(instance.id) } })
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(instance.name.ifBlank { instance.base })
|
||||
Text(
|
||||
"${instance.email} · ${instance.base}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
active?.let { current ->
|
||||
OutlinedButton(onClick = {
|
||||
scope.launch {
|
||||
Push.disable(context, current)
|
||||
runCatching { store.clientFor(current).signOut() }
|
||||
store.remove(current.id)
|
||||
}
|
||||
}) { Text(stringResource(R.string.sign_out)) }
|
||||
OutlinedButton(onClick = onAddInstance) {
|
||||
Text(stringResource(R.string.add_instance))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Section(stringResource(R.string.settings_theme))
|
||||
listOf("" to R.string.theme_system, "moria" to R.string.theme_moria, "shire" to R.string.theme_shire).forEach { (value, label) ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { scope.launch { store.savePrefs { it.copy(theme = value) } } },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
RadioButton(selected = prefs.theme == value, onClick = { scope.launch { store.savePrefs { it.copy(theme = value) } } })
|
||||
Text(stringResource(label))
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Section(stringResource(R.string.settings_notifications))
|
||||
val distributors = remember { Push.distributors(context) }
|
||||
Text(
|
||||
stringResource(if (distributors.isEmpty()) R.string.push_no_distributor else R.string.push_explained),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
active?.let { current ->
|
||||
Button(enabled = distributors.isNotEmpty(), onClick = {
|
||||
(context as? Activity)?.let { activity ->
|
||||
Push.enable(activity, current) { ok ->
|
||||
pushNote = context.getString(if (ok) R.string.push_on else R.string.push_failed)
|
||||
}
|
||||
}
|
||||
}) { Text(stringResource(R.string.push_enable)) }
|
||||
}
|
||||
pushNote?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
|
||||
HorizontalDivider()
|
||||
Section(stringResource(R.string.settings_assistant))
|
||||
Text(stringResource(R.string.assistant_explained), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Button(onClick = {
|
||||
context.startActivity(Intent(Settings.ACTION_VOICE_INPUT_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}) { Text(stringResource(R.string.assistant_open_settings)) }
|
||||
Text(stringResource(R.string.assistant_samsung), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stringResource(R.string.assistant_temporary), modifier = Modifier.weight(1f))
|
||||
Switch(checked = prefs.assistantTemporary, onCheckedChange = { on -> scope.launch { store.savePrefs { it.copy(assistantTemporary = on) } } })
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stringResource(R.string.assistant_read_aloud), modifier = Modifier.weight(1f))
|
||||
Switch(checked = prefs.readAloudSpoken, onCheckedChange = { on -> scope.launch { store.savePrefs { it.copy(readAloudSpoken = on) } } })
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Section(stringResource(R.string.settings_about))
|
||||
Text(stringResource(R.string.about_version, BuildConfig.VERSION_NAME))
|
||||
if (BuildConfig.SELF_UPDATE) {
|
||||
OutlinedButton(onClick = {
|
||||
scope.launch { updateNote = Updater(context).checkAndOffer() }
|
||||
}) { Text(stringResource(R.string.update_check)) }
|
||||
updateNote?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Section(title: String) {
|
||||
Text(title, style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.signin
|
||||
|
||||
import android.app.Application
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import androidx.browser.customtabs.CustomTabsIntent
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.safeDrawingPadding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
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.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Doorstep
|
||||
import eu.llembas.android.api.normaliseBase
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** Where the sign-in is. The token arrives once, by device code, as `lembas login` gets it. */
|
||||
sealed interface SignInState {
|
||||
data object Address : SignInState
|
||||
data object Finding : SignInState
|
||||
data class Code(val userCode: String, val verify: String) : SignInState
|
||||
data class Failed(val message: String) : SignInState
|
||||
data object Done : SignInState
|
||||
}
|
||||
|
||||
/** The newest API this app reads. A server with a newer one is told about, not guessed at. */
|
||||
const val APP_API = 1
|
||||
|
||||
class SignInViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow<SignInState>(SignInState.Address)
|
||||
val state = _state.asStateFlow()
|
||||
private var polling: Job? = null
|
||||
|
||||
fun start(typed: String) {
|
||||
polling?.cancel()
|
||||
polling = viewModelScope.launch {
|
||||
_state.value = SignInState.Finding
|
||||
val doorstep = Doorstep()
|
||||
try {
|
||||
val base = normaliseBase(typed)
|
||||
val found = doorstep.discover(base)
|
||||
if (found.service != "lembas" || found.appApi < 1 || "app" !in found.scopes) {
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_too_old))
|
||||
return@launch
|
||||
}
|
||||
if (found.appApi > APP_API) {
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_too_new))
|
||||
return@launch
|
||||
}
|
||||
val device = getApplication<Application>().getString(R.string.device_name)
|
||||
val code = doorstep.deviceCode(found.login.device.code, device, "${Build.MANUFACTURER} ${Build.MODEL}")
|
||||
_state.value = SignInState.Code(code.userCode, code.verificationUriComplete.ifEmpty { code.verificationUri })
|
||||
var interval = code.interval.coerceAtLeast(2) * 1000L
|
||||
val until = System.currentTimeMillis() + code.expiresIn * 1000L
|
||||
while (System.currentTimeMillis() < until) {
|
||||
delay(interval)
|
||||
val answer = doorstep.deviceToken(found.login.device.token, code.deviceCode)
|
||||
when {
|
||||
answer.accessToken != null -> {
|
||||
val account = answer.account
|
||||
getApplication<Application>().lembas.instances.add(
|
||||
base = found.baseUrl.ifEmpty { base }.trimEnd('/'),
|
||||
name = found.name,
|
||||
email = account?.email.orEmpty(),
|
||||
token = answer.accessToken,
|
||||
)
|
||||
_state.value = SignInState.Done
|
||||
return@launch
|
||||
}
|
||||
|
||||
answer.error == "slow_down" -> interval += 5000L
|
||||
|
||||
answer.error == "authorization_pending" -> Unit
|
||||
|
||||
answer.error == "access_denied" -> {
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_denied))
|
||||
return@launch
|
||||
}
|
||||
|
||||
else -> {
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_expired))
|
||||
return@launch
|
||||
}
|
||||
}
|
||||
}
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_expired))
|
||||
} catch (e: Exception) {
|
||||
_state.value = SignInState.Failed(e.message ?: e.javaClass.simpleName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun reset() {
|
||||
polling?.cancel()
|
||||
_state.value = SignInState.Address
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SignInScreen(onDone: () -> Unit = {}, model: SignInViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LaunchedEffect(state) { if (state == SignInState.Done) onDone() }
|
||||
var address by rememberSaveable { mutableStateOf("") }
|
||||
val context = LocalContext.current
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().safeDrawingPadding().imePadding().padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text(stringResource(R.string.app_name), style = MaterialTheme.typography.headlineMedium)
|
||||
Text(
|
||||
stringResource(R.string.signin_intro),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.widthIn(max = 420.dp),
|
||||
)
|
||||
when (val s = state) {
|
||||
SignInState.Address, is SignInState.Failed -> {
|
||||
OutlinedTextField(
|
||||
value = address,
|
||||
onValueChange = { address = it },
|
||||
label = { Text(stringResource(R.string.signin_address)) },
|
||||
placeholder = { Text("llm.example.org") },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Go),
|
||||
keyboardActions = KeyboardActions(onGo = { if (address.isNotBlank()) model.start(address) }),
|
||||
modifier = Modifier.fillMaxWidth().widthIn(max = 420.dp),
|
||||
)
|
||||
if (s is SignInState.Failed) {
|
||||
Text(s.message, color = MaterialTheme.colorScheme.error, modifier = Modifier.widthIn(max = 420.dp))
|
||||
}
|
||||
Button(onClick = { model.start(address) }, enabled = address.isNotBlank()) {
|
||||
Text(stringResource(R.string.signin_continue))
|
||||
}
|
||||
}
|
||||
|
||||
SignInState.Finding, SignInState.Done -> CircularProgressIndicator()
|
||||
|
||||
is SignInState.Code -> {
|
||||
Text(stringResource(R.string.signin_code_intro), modifier = Modifier.widthIn(max = 420.dp))
|
||||
Text(s.userCode, fontFamily = FontFamily.Monospace, fontSize = 32.sp, style = MaterialTheme.typography.headlineLarge)
|
||||
Button(onClick = { CustomTabsIntent.Builder().build().launchUrl(context, Uri.parse(s.verify)) }) {
|
||||
Text(stringResource(R.string.signin_open_browser))
|
||||
}
|
||||
CircularProgressIndicator()
|
||||
OutlinedButton(onClick = { model.reset() }) { Text(stringResource(R.string.cancel)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package eu.llembas.android.ui.theme
|
||||
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.ColorScheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
|
||||
/** The palette in use, for the parts Material's scheme has no slot for (code, bubbles, soft tints). */
|
||||
val LocalPalette = staticCompositionLocalOf { Moria }
|
||||
|
||||
private fun scheme(p: Palette, dark: Boolean): ColorScheme {
|
||||
val base = if (dark) darkColorScheme() else lightColorScheme()
|
||||
return base.copy(
|
||||
primary = p.accent,
|
||||
onPrimary = p.accentInk,
|
||||
primaryContainer = p.accentSoft,
|
||||
onPrimaryContainer = p.ink,
|
||||
secondary = p.leaf,
|
||||
onSecondary = p.inkInverse,
|
||||
background = p.bg,
|
||||
onBackground = p.ink,
|
||||
surface = p.surface,
|
||||
onSurface = p.ink,
|
||||
surfaceVariant = p.surfaceRaised,
|
||||
onSurfaceVariant = p.inkMuted,
|
||||
surfaceContainerLowest = p.bgSunken,
|
||||
surfaceContainerLow = p.surface,
|
||||
surfaceContainer = p.surfaceRaised,
|
||||
surfaceContainerHigh = p.surfaceHover,
|
||||
surfaceContainerHighest = p.surfaceActive,
|
||||
outline = p.borderStrong,
|
||||
outlineVariant = p.border,
|
||||
error = p.danger,
|
||||
onError = p.inkInverse,
|
||||
errorContainer = p.dangerSoft,
|
||||
onErrorContainer = p.ink,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Moria (dark) or Shire (light), from the server's own tokens (`Tokens.kt`, generated). Dynamic
|
||||
* colour is off on purpose: the app looks like the web UI it sits beside, not like the wallpaper.
|
||||
* An empty choice follows the system's light or dark setting.
|
||||
*/
|
||||
@Composable
|
||||
fun LembasTheme(choice: String = "", content: @Composable () -> Unit) {
|
||||
val dark = when (choice) {
|
||||
"moria" -> true
|
||||
"shire" -> false
|
||||
else -> isSystemInDarkTheme()
|
||||
}
|
||||
val palette = if (dark) Moria else Shire
|
||||
CompositionLocalProvider(LocalPalette provides palette) {
|
||||
MaterialTheme(colorScheme = scheme(palette, dark), content = content)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v1.6.0. Do not edit.
|
||||
package eu.llembas.android.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
data class Palette(
|
||||
val bg: Color,
|
||||
val bgSunken: Color,
|
||||
val surface: Color,
|
||||
val surfaceRaised: Color,
|
||||
val surfaceHover: Color,
|
||||
val surfaceActive: Color,
|
||||
val border: Color,
|
||||
val borderStrong: Color,
|
||||
val ink: Color,
|
||||
val inkMuted: Color,
|
||||
val inkFaint: Color,
|
||||
val inkInverse: Color,
|
||||
val accent: Color,
|
||||
val accentHover: Color,
|
||||
val accentInk: Color,
|
||||
val accentSoft: Color,
|
||||
val leaf: Color,
|
||||
val danger: Color,
|
||||
val dangerSoft: Color,
|
||||
val success: Color,
|
||||
val successSoft: Color,
|
||||
val warning: Color,
|
||||
val warningSoft: Color,
|
||||
val bubbleUser: Color,
|
||||
val codeBg: Color,
|
||||
val codeBorder: Color,
|
||||
)
|
||||
|
||||
val Moria = Palette(
|
||||
bg = Color(0xFF0B0D10L),
|
||||
bgSunken = Color(0xFF07090BL),
|
||||
surface = Color(0xFF11151AL),
|
||||
surfaceRaised = Color(0xFF171C22L),
|
||||
surfaceHover = Color(0xFF1D232BL),
|
||||
surfaceActive = Color(0xFF232B34L),
|
||||
border = Color(0xFF26303AL),
|
||||
borderStrong = Color(0xFF5C6976L),
|
||||
ink = Color(0xFFE2E8ECL),
|
||||
inkMuted = Color(0xFFA6B2BCL),
|
||||
inkFaint = Color(0xFF808D98L),
|
||||
inkInverse = Color(0xFF07090BL),
|
||||
accent = Color(0xFF8FD8E8L),
|
||||
accentHover = Color(0xFFB4E6F1L),
|
||||
accentInk = Color(0xFF061418L),
|
||||
accentSoft = Color(0x1F8FD8E8L),
|
||||
leaf = Color(0xFF7EE081L),
|
||||
danger = Color(0xFFF0735FL),
|
||||
dangerSoft = Color(0x21F0735FL),
|
||||
success = Color(0xFF5FD6B0L),
|
||||
successSoft = Color(0x215FD6B0L),
|
||||
warning = Color(0xFFF0A840L),
|
||||
warningSoft = Color(0x21F0A840L),
|
||||
bubbleUser = Color(0xFF161C23L),
|
||||
codeBg = Color(0xFF07090BL),
|
||||
codeBorder = Color(0xFF26303AL),
|
||||
)
|
||||
|
||||
val Shire = Palette(
|
||||
bg = Color(0xFFF1EAD6L),
|
||||
bgSunken = Color(0xFFE7DEC6L),
|
||||
surface = Color(0xFFF8F3E5L),
|
||||
surfaceRaised = Color(0xFFFCF9F0L),
|
||||
surfaceHover = Color(0xFFECE4CFL),
|
||||
surfaceActive = Color(0xFFE2D8BDL),
|
||||
border = Color(0xFFCBBF9DL),
|
||||
borderStrong = Color(0xFF2A2E22L),
|
||||
ink = Color(0xFF1F2418L),
|
||||
inkMuted = Color(0xFF474D3BL),
|
||||
inkFaint = Color(0xFF5E6250L),
|
||||
inkInverse = Color(0xFFF8F3E5L),
|
||||
accent = Color(0xFF285F3CL),
|
||||
accentHover = Color(0xFF1F4D30L),
|
||||
accentInk = Color(0xFFF8F3E5L),
|
||||
accentSoft = Color(0x1A285F3CL),
|
||||
leaf = Color(0xFF3D6B1CL),
|
||||
danger = Color(0xFFA3321FL),
|
||||
dangerSoft = Color(0x1AA3321FL),
|
||||
success = Color(0xFF2B6A55L),
|
||||
successSoft = Color(0x1A2B6A55L),
|
||||
warning = Color(0xFF7E5200L),
|
||||
warningSoft = Color(0x1A7E5200L),
|
||||
bubbleUser = Color(0xFFECE4CFL),
|
||||
codeBg = Color(0xFFF1EAD6L),
|
||||
codeBorder = Color(0xFFCBBF9DL),
|
||||
)
|
||||
Reference in new issue
Block a user