Chats as a daily driver: agent chats, photos, copy, rename, offline and recovery
CI / check (push) Canceled after 0s

- New agent chat (Agents tab FAB, route new-agent): GET /devices for the devices linked now; a
  device chip, an optional folder (empty = the device's first root, the server's rule) and the
  mode (manual/edit/auto/plan) go into POST /chats as kind/device/directory/mode. No device
  linked: a sentence saying how. An open agent chat's mode is a chip too.
- Attach: Take a photo (TakePicture into a FileProvider cache file, deleted once uploaded; no
  CAMERA permission), Choose photos (PickMultipleVisualMedia), Choose files.
- Copy under every reply (its text steps) and user message; Rename chat in the menu.
- The new chat's effort is held until the first message and sent with it (EffortChip called
  PATCH, which needs a chat, so the choice was dropped).
- Follow the reply while it streams, decided when the person's own scroll comes to rest; the
  first scroll goes to the real last item (the "older" row shifted the index by one).
- ui/Errors.kt explain(): the server's sentence for a refusal, one "cannot be reached" sentence
  for UnknownHost/Connect/SocketTimeout/NoRouteToHost, used everywhere an error was shown raw.
- A failed send hands its text and attachments back to the composer. A replaced follow's
  CancellationException is no longer shown as an error. A refused stream re-reads the chat.
- The chat list reloads on resume (quietly if rows are shown) and offers Try again.
- Strings: 15 new; Rename chat, Copy message, Copied., Save, Try again, Device and Auto from the
  server's catalogue, the rest translated in strings_own.json. "Plan" was the price plan in
  de/fr/hu (Tarif/Forfait/Csomag) and "Manual" untranslated: own entries fix both.
- ClientTest: an agent chat's body, a plain chat's, and what counts as unreachable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Opus 5.5 committed 2026-11-09 08:09:53 +00:00
1 parent f4891ba402
commit 41dd3c893c
26 files changed
+736 -87

No files matched your search

@@ -89,6 +89,7 @@ class MainActivity : ComponentActivity() {
ChatsScreen(
onOpen = { nav.navigate("chat/$it") },
onNew = { nav.navigate("new") },
onNewAgent = { nav.navigate("new-agent") },
onSettings = { nav.navigate("settings") },
onFiles = { nav.navigate("files") },
)
@@ -102,6 +103,16 @@ class MainActivity : ComponentActivity() {
},
)
}
composable("new-agent") {
ChatScreen(
chatId = null,
agent = true,
onBack = { nav.popBackStack() },
onOpened = { id ->
nav.navigate("chat/$id") { popUpTo("new-agent") { inclusive = true } }
},
)
}
composable("chat/{id}") { entry ->
ChatScreen(chatId = entry.arguments?.getString("id"), onBack = { nav.popBackStack() })
}
@@ -25,6 +25,9 @@ import java.io.IOException
import java.util.concurrent.TimeUnit
import kotlin.coroutines.resumeWithException
/** Where a new agent chat runs: a linked device ([LinkedDevice.id]) and a folder on it. */
data class AgentTarget(val device: String, val directory: String = "")
/** A refusal from the server, in its own words (`{"detail": "…"}`). */
class ApiException(val status: Int, message: String) : IOException(message)
@@ -168,6 +171,7 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
temporary: Boolean = false,
effort: String? = null,
mode: String? = null,
agent: AgentTarget? = null,
): NewChat = send(
"POST",
"/chats",
@@ -178,6 +182,14 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
effort?.let { put("effort", it) }
mode?.let { put("mode", it) }
put("temporary", temporary)
// An agent chat runs on a linked device; an empty directory is the device's first
// allowed one. A device that is no longer linked makes it an ordinary chat on the
// server, rather than losing the message.
agent?.let {
put("kind", "agent")
put("device", it.device)
if (it.directory.isNotBlank()) put("directory", it.directory.trim())
}
},
)
@@ -8,6 +8,7 @@ import eu.llembas.android.api.LiveReply
import eu.llembas.android.api.StreamClient
import eu.llembas.android.lembas
import eu.llembas.android.push.Notifications
import eu.llembas.android.ui.explain
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
@@ -81,7 +82,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
_state.update { it.copy(busy = false) }
if (text.isNotBlank()) ask(text, spoken = true)
} catch (e: Exception) {
_state.update { it.copy(busy = false, error = e.message) }
_state.update { it.copy(busy = false, error = context.explain(e)) }
}
}
}
@@ -115,7 +116,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
if (words.isNotBlank()) speaker.play(api.speech(plain(words)))
}
} catch (e: Exception) {
_state.update { it.copy(error = e.message ?: e.javaClass.simpleName) }
_state.update { it.copy(error = context.explain(e)) }
} finally {
_state.update { it.copy(busy = false) }
}
@@ -26,6 +26,7 @@ import eu.llembas.android.MainActivity
import eu.llembas.android.R
import eu.llembas.android.lembas
import eu.llembas.android.push.Notifications
import eu.llembas.android.ui.explain
import eu.llembas.android.ui.theme.LembasTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@@ -103,7 +104,7 @@ class ShareActivity : ComponentActivity() {
)
finish()
} catch (e: Exception) {
failure.value = e.message ?: e.javaClass.simpleName
failure.value = explain(e)
}
}
}
@@ -0,0 +1,25 @@
package eu.llembas.android.ui
import android.content.Context
import eu.llembas.android.R
import eu.llembas.android.api.ApiException
import java.net.ConnectException
import java.net.NoRouteToHostException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
/**
* A failure in words a person can act on. The server's refusal is its own sentence; a phone
* that cannot reach the instance at all -- no network, a name that does not resolve off the
* home network, a server that is down -- is one sentence saying so, rather than
* "Unable to resolve host" or "failed to connect to /…:443". A certificate the phone does not
* trust keeps its own message: that one names what to fix.
*/
fun Context.explain(e: Throwable): String = when {
e is ApiException -> e.message?.ifBlank { null } ?: getString(R.string.offline)
unreachable(e) -> getString(R.string.offline)
else -> e.message?.ifBlank { null } ?: e.javaClass.simpleName
}
/** Whether a failure means "the instance cannot be reached" rather than "it said no". */
fun unreachable(e: Throwable): Boolean = e is UnknownHostException || e is ConnectException || e is SocketTimeoutException || e is NoRouteToHostException
@@ -4,10 +4,16 @@ package eu.llembas.android.ui.chat
import android.Manifest
import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -21,6 +27,7 @@ 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.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
@@ -29,9 +36,12 @@ 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.ContentCopy
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material.icons.filled.Terminal
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.AssistChip
import androidx.compose.material3.DropdownMenu
@@ -72,6 +82,8 @@ 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.AgentTarget
import eu.llembas.android.api.LinkedDevice
import eu.llembas.android.api.Message
import eu.llembas.android.api.ModelInfo
import eu.llembas.android.api.ShowCard
@@ -83,7 +95,13 @@ import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit = {}, model: ChatViewModel = viewModel(key = chatId ?: "new")) {
fun ChatScreen(
chatId: String?,
onBack: () -> Unit,
onOpened: (String) -> Unit = {},
agent: Boolean = false,
model: ChatViewModel = viewModel(key = chatId ?: if (agent) "new-agent" else "new"),
) {
val state by model.state.collectAsStateWithLifecycle()
val palette = LocalPalette.current
val list = rememberLazyListState()
@@ -91,8 +109,16 @@ fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit =
var menu by remember { mutableStateOf(false) }
var editing by remember { mutableStateOf<Message?>(null) }
var showing by remember { mutableStateOf<ShowCard?>(null) }
var renaming by remember { mutableStateOf(false) }
val context = LocalContext.current
val scope = rememberCoroutineScope()
val copy: (String) -> Unit = { text ->
context.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText("LLeMbas", text))
// Android 13 and newer say "Copied" themselves.
if (Build.VERSION.SDK_INT < 33) scope.launch { snackbar.showSnackbar(context.getString(R.string.copied)) }
}
LaunchedEffect(chatId) { model.open(chatId) }
LaunchedEffect(chatId) { model.open(chatId, agent = agent && chatId == null) }
// 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) } }
@@ -104,8 +130,20 @@ fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit =
}
val live = state.live
val rows = state.messages
LaunchedEffect(rows.size, live?.shown?.size) {
if (rows.isNotEmpty()) list.animateScrollToItem(rows.size - 1)
// To the end when the transcript grows, and while a reply is being written -- but only if
// the person is at the end already: reading back up is not interrupted by the next line.
// Whether to follow is decided when the person's own scroll comes to rest, not when a
// line arrives: by then the line has already made the list longer than the screen.
var following by remember { mutableStateOf(true) }
LaunchedEffect(list.isScrollInProgress) {
if (!list.isScrollInProgress) following = !list.canScrollForward
}
LaunchedEffect(rows.size) {
if (rows.isNotEmpty()) list.toEnd()
}
val growth = live?.let { it.shown.size * 100_000 + (it.tail.text.length + it.tail.thinking.length) } ?: 0
LaunchedEffect(growth) {
if (growth > 0 && following) list.toEnd()
}
Scaffold(
@@ -119,7 +157,7 @@ fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit =
},
title = {
Text(
state.chat?.title?.ifBlank { null } ?: stringResource(R.string.new_chat),
state.chat?.title?.ifBlank { null } ?: stringResource(if (agent) R.string.new_agent_chat else R.string.new_chat),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
@@ -130,6 +168,10 @@ fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit =
Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more))
}
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
DropdownMenuItem(text = { Text(stringResource(R.string.rename_chat)) }, onClick = {
menu = false
renaming = true
})
DropdownMenuItem(text = { Text(stringResource(R.string.continue_reply)) }, onClick = {
menu = false
model.continueChat()
@@ -173,7 +215,7 @@ fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit =
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)
Composer(model, state, agent)
}
},
) { padding ->
@@ -197,9 +239,10 @@ fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit =
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))
Row(Modifier.align(Alignment.End), verticalAlignment = Alignment.CenterVertically) {
message.text?.takeIf { it.isNotBlank() }?.let { words -> CopyButton { copy(words) } }
if (!message.machine && live == null) {
TextButton(onClick = { editing = message }) { Text(stringResource(R.string.edit)) }
}
}
}
@@ -213,8 +256,10 @@ fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit =
else -> Column {
Steps(message.steps, onShow = { showing = it })
ReplyFoot(message)
if (live == null && message == rows.lastOrNull()) {
Row {
val words = replyText(message)
Row(verticalAlignment = Alignment.CenterVertically) {
if (words.isNotBlank()) CopyButton { copy(words) }
if (live == null && message == rows.lastOrNull()) {
TextButton(onClick = { model.regenerate(message) }) { Text(stringResource(R.string.regenerate)) }
}
}
@@ -243,6 +288,22 @@ fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit =
state.chat?.id?.let { id -> FileViewer(id, file, onClose = { showing = null }) }
}
if (renaming) {
var title by remember { mutableStateOf(state.chat?.title.orEmpty()) }
AlertDialog(
onDismissRequest = { renaming = false },
title = { Text(stringResource(R.string.rename_chat)) },
text = { OutlinedTextField(value = title, onValueChange = { title = it }, singleLine = true, modifier = Modifier.fillMaxWidth()) },
confirmButton = {
TextButton(enabled = title.isNotBlank(), onClick = {
model.rename(title)
renaming = false
}) { Text(stringResource(R.string.save)) }
},
dismissButton = { TextButton(onClick = { renaming = false }) { Text(stringResource(R.string.cancel)) } },
)
}
editing?.let { message ->
var text by remember(message.id) { mutableStateOf(message.text.orEmpty()) }
AlertDialog(
@@ -260,28 +321,93 @@ fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit =
}
}
/** To the very end of the transcript: the last row, then down to its foot however tall it is. */
private suspend fun LazyListState.toEnd() {
val last = layoutInfo.totalItemsCount - 1
if (last < 0) return
scrollToItem(last)
scrollBy(1_000_000f)
}
/** A reply's own words, as the person would copy them: its text steps, in order. */
private fun replyText(message: Message): String =
message.steps.filter { it.kind == "text" }.mapNotNull { it.markdown }.joinToString("\n\n").ifBlank { message.text.orEmpty() }
@Composable
private fun CopyButton(onClick: () -> Unit) {
IconButton(onClick = onClick) {
Icon(
Icons.Filled.ContentCopy,
contentDescription = stringResource(R.string.copy_message),
tint = LocalPalette.current.inkFaint,
)
}
}
/** The agent modes, as the web page offers them, in the order of how much the model may do. */
private val AGENT_MODES = listOf("manual", "edit", "auto", "plan")
@Composable
private fun modeName(mode: String): String = when (mode) {
"manual" -> stringResource(R.string.mode_manual)
"edit" -> stringResource(R.string.mode_edit)
"auto" -> stringResource(R.string.mode_auto)
"plan" -> stringResource(R.string.mode_plan)
else -> mode.replaceFirstChar { it.uppercase() }
}
@SuppressLint("MissingPermission")
@Composable
private fun Composer(model: ChatViewModel, state: ChatState) {
private fun Composer(model: ChatViewModel, state: ChatState, agent: Boolean) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
var text by rememberSaveable { mutableStateOf("") }
var chosenModel by rememberSaveable { mutableStateOf<String?>(null) }
var chosenEffort by rememberSaveable { mutableStateOf<String?>(null) }
var planMode by rememberSaveable { mutableStateOf(false) }
var agentMode by rememberSaveable { mutableStateOf("edit") }
var device by rememberSaveable { mutableStateOf<String?>(null) }
var directory by rememberSaveable { mutableStateOf("") }
var askDirectory by remember { mutableStateOf(false) }
var attachMenu by remember { mutableStateOf(false) }
var listening by remember { mutableStateOf(false) }
var photo by remember { mutableStateOf<Uri?>(null) }
val recorder = remember { Recorder(scope) }
val pick = rememberLauncherForActivityResult(ActivityResultContracts.GetMultipleContents()) { model.attach(it) }
val pickFiles = rememberLauncherForActivityResult(ActivityResultContracts.GetMultipleContents()) { model.attach(it) }
val pickPhotos = rememberLauncherForActivityResult(ActivityResultContracts.PickMultipleVisualMedia()) { model.attach(it) }
val takePhoto = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { taken ->
photo?.let { if (taken) model.attach(listOf(it)) }
photo = null
}
val askMic = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) {
recorder.start()
listening = true
}
}
// A message the server did not take comes back here, so nothing typed is lost.
LaunchedEffect(state.unsent) {
state.unsent?.let {
if (text.isBlank()) text = it
model.clearUnsent()
}
}
val chat = state.chat
val current = chat?.model ?: chosenModel ?: state.models.firstOrNull { it.default }?.id
val newAgent = agent && chat == null
// The first linked device is the one a new agent chat runs on until another is chosen.
val target: LinkedDevice? = state.devices.firstOrNull { it.id == device } ?: state.devices.firstOrNull()
val current = chat?.model?.ifBlank { null } ?: chosenModel ?: state.models.firstOrNull { it.default }?.id
val running = state.live != null && state.live.finished == null
Column(Modifier.fillMaxWidth().padding(8.dp)) {
if (newAgent && state.devices.isEmpty() && !state.loading) {
Text(
stringResource(R.string.agent_no_device),
style = MaterialTheme.typography.bodySmall,
color = LocalPalette.current.inkMuted,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
)
}
if (state.pending.isNotEmpty()) {
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
state.pending.forEach { a ->
@@ -295,28 +421,58 @@ private fun Composer(model: ChatViewModel, state: ChatState) {
}
}
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
if (newAgent && state.devices.isNotEmpty()) {
DeviceChip(state.devices, target) { device = it }
AssistChip(
onClick = { askDirectory = true },
leadingIcon = { Icon(Icons.Filled.Folder, contentDescription = null) },
label = { Text(directory.ifBlank { stringResource(R.string.agent_directory) }, maxLines = 1) },
)
}
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") }
// A new chat keeps the choice until its first message makes it; an open one
// changes at once, as the web page's control does.
EffortChip(efforts, if (chat == null) chosenEffort else chat.effort?.ifBlank { null }) { picked ->
if (chat == null) chosenEffort = picked else model.change("effort", picked ?: "off")
}
}
if (chat == null || !chat.isAgent) {
FilterChip(
when {
newAgent -> ModeChip(agentMode) { agentMode = it }
chat != null && chat.isAgent -> ModeChip(chat.mode.ifBlank { "edit" }) { model.change("mode", it) }
else -> 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))
Box {
IconButton(onClick = { attachMenu = true }) {
Icon(Icons.Filled.AttachFile, contentDescription = stringResource(R.string.attach))
}
DropdownMenu(expanded = attachMenu, onDismissRequest = { attachMenu = false }) {
DropdownMenuItem(text = { Text(stringResource(R.string.attach_take_photo)) }, onClick = {
attachMenu = false
model.photoTarget().also { photo = it }.let { takePhoto.launch(it) }
})
DropdownMenuItem(text = { Text(stringResource(R.string.attach_choose_photos)) }, onClick = {
attachMenu = false
pickPhotos.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
})
DropdownMenuItem(text = { Text(stringResource(R.string.attach_choose_files)) }, onClick = {
attachMenu = false
pickFiles.launch("*/*")
})
}
}
TextField(
value = text,
@@ -347,15 +503,90 @@ private fun Composer(model: ChatViewModel, state: ChatState) {
IconButton(onClick = model::stop) { Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop)) }
} else {
IconButton(
enabled = text.isNotBlank() || state.pending.isNotEmpty(),
enabled = (text.isNotBlank() || state.pending.isNotEmpty()) && !state.uploading && (!newAgent || target != null),
onClick = {
model.send(text, model = chosenModel, mode = if (planMode) "plan" else null)
model.send(
text,
model = chosenModel,
mode = if (newAgent) {
agentMode
} else if (planMode) {
"plan"
} else {
null
},
effort = chosenEffort,
agent = if (newAgent) target?.let { AgentTarget(it.id, directory) } else null,
)
text = ""
},
) { Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send)) }
}
}
}
if (askDirectory) {
var typed by remember { mutableStateOf(directory) }
AlertDialog(
onDismissRequest = { askDirectory = false },
title = { Text(stringResource(R.string.agent_directory)) },
text = {
OutlinedTextField(
value = typed,
onValueChange = { typed = it },
singleLine = true,
placeholder = { Text(stringResource(R.string.agent_directory_hint)) },
modifier = Modifier.fillMaxWidth(),
)
},
confirmButton = {
TextButton(onClick = {
directory = typed.trim()
askDirectory = false
}) { Text(stringResource(R.string.save)) }
},
dismissButton = { TextButton(onClick = { askDirectory = false }) { Text(stringResource(R.string.cancel)) } },
)
}
}
@Composable
private fun DeviceChip(devices: List<LinkedDevice>, current: LinkedDevice?, onPick: (String) -> Unit) {
var open by remember { mutableStateOf(false) }
Box {
AssistChip(
onClick = { open = true },
leadingIcon = { Icon(Icons.Filled.Terminal, contentDescription = stringResource(R.string.agent_device)) },
label = { Text(current?.let { it.name.ifBlank { it.host } } ?: "—", maxLines = 1) },
)
DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
devices.forEach { d ->
DropdownMenuItem(
text = { Text(listOf(d.name, d.host).filter { it.isNotBlank() }.distinct().joinToString(" · ")) },
onClick = {
open = false
onPick(d.id)
},
)
}
}
}
}
@Composable
private fun ModeChip(current: String, onPick: (String) -> Unit) {
var open by remember { mutableStateOf(false) }
Box {
AssistChip(onClick = { open = true }, label = { Text(modeName(current)) })
DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
AGENT_MODES.forEach { m ->
DropdownMenuItem(text = { Text(modeName(m)) }, onClick = {
open = false
onPick(m)
})
}
}
}
}
@Composable
@@ -3,20 +3,25 @@ package eu.llembas.android.ui.chat
import android.app.Application
import android.net.Uri
import android.provider.OpenableColumns
import androidx.core.content.FileProvider
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import eu.llembas.android.api.AgentTarget
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.LinkedDevice
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 eu.llembas.android.ui.explain
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
@@ -26,6 +31,7 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import java.io.File
data class ChatState(
val chat: Chat? = null,
@@ -33,10 +39,14 @@ data class ChatState(
val more: Boolean = false,
val live: LiveReply? = null,
val models: List<ModelInfo> = emptyList(),
/** For a new agent chat: the devices linked right now, which it can run on. */
val devices: List<LinkedDevice> = emptyList(),
val pending: List<Attachment> = emptyList(),
val uploading: Boolean = false,
val loading: Boolean = false,
val error: String? = null,
/** A message that could not be sent, handed back to the composer once. */
val unsent: String? = null,
/** A card somebody answered elsewhere first: said once, then cleared. */
val notice: String? = null,
)
@@ -55,19 +65,27 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
?: 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) }
// A follow that was replaced by a newer one is cancelled, not failed: nothing to say.
if (e is CancellationException) return
_state.update { it.copy(error = getApplication<Application>().explain(e), loading = false, uploading = false) }
}
fun clearError() = _state.update { it.copy(error = null, notice = null) }
fun open(chatId: String?) {
fun clearUnsent() = _state.update { it.copy(unsent = null) }
fun rename(title: String) = change("title", title.trim())
/** Open a chat, or (no id) get a new one ready: an agent chat also needs the linked devices. */
fun open(chatId: String?, agent: Boolean = false) {
viewModelScope.launch {
try {
val client = api()
_state.update { it.copy(loading = chatId != null) }
_state.update { it.copy(loading = chatId != null || agent, error = null) }
val models = runCatching { client.models(chatId) }.getOrDefault(emptyList())
if (chatId == null) {
_state.update { it.copy(models = models, loading = false) }
val devices = if (agent) client.devices() else emptyList()
_state.update { it.copy(models = models, devices = devices, loading = false) }
return@launch
}
val detail = client.chat(chatId)
@@ -101,8 +119,15 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
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: CancellationException) {
throw e
} catch (e: Exception) {
fail(e)
// The reply goes on on the server; what it has written so far is read back
// rather than left half-drawn.
_state.update { it.copy(live = null) }
refresh()
return@launch
}
val ended = _state.value.live
_state.update { s ->
@@ -136,8 +161,9 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
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 }
fun send(text: String, model: String? = null, mode: String? = null, effort: String? = null, temporary: Boolean = false, agent: AgentTarget? = null) {
val attached = _state.value.pending
val files = attached.map { it.id }
if (text.isBlank() && files.isEmpty()) return
viewModelScope.launch {
try {
@@ -145,13 +171,15 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
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)
val made = client.createChat(text, files, model = model, temporary = temporary, effort = effort, mode = mode, agent = agent)
_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) {
// Nothing was sent: the words and the attachments go back to the composer.
_state.update { it.copy(pending = attached + it.pending, unsent = text) }
fail(e)
}
}
@@ -221,6 +249,8 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
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) }
// A photo the camera took for this message is the server's now.
if (uri.authority == photoAuthority) runCatching { resolver.delete(uri, null, null) }
}
} catch (e: Exception) {
fail(e)
@@ -229,6 +259,19 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
}
}
private val photoAuthority get() = "${getApplication<Application>().packageName}.files"
/**
* Where the camera writes a photo for the composer: a file in the app's cache, shared with
* the camera app through the FileProvider for exactly this one capture.
*/
fun photoTarget(): Uri {
val app = getApplication<Application>()
val dir = File(app.cacheDir, "camera").apply { mkdirs() }
val file = File(dir, "photo-${System.currentTimeMillis()}.jpg")
return FileProvider.getUriForFile(app, photoAuthority, file)
}
fun unattach(attachment: Attachment) {
_state.update { s -> s.copy(pending = s.pending.filterNot { it.id == attachment.id }) }
}
@@ -33,6 +33,7 @@ import androidx.compose.material3.Scaffold
import androidx.compose.material3.SwipeToDismissBox
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.material3.rememberSwipeToDismissBoxState
@@ -40,6 +41,8 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
@@ -49,6 +52,7 @@ 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.LifecycleResumeEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
@@ -57,6 +61,7 @@ import eu.llembas.android.api.Chat
import eu.llembas.android.api.Doorstep
import eu.llembas.android.api.fit
import eu.llembas.android.lembas
import eu.llembas.android.ui.explain
import eu.llembas.android.ui.signin.refusal
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
@@ -76,10 +81,15 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
private var refused: Int? = null
private var checked = false
fun load(kind: String) {
/**
* Read the list. [quiet] is the reload on coming back to the screen: the rows already shown
* stay without a spinner, and only a change replaces them.
*/
fun load(kind: String, quiet: Boolean = false) {
val switched = kind != this.kind
this.kind = kind
viewModelScope.launch {
_state.update { it.copy(loading = true, error = null) }
_state.update { it.copy(loading = !quiet || switched, error = null, chats = if (switched) emptyList() else it.chats) }
try {
val api = getApplication<Application>().lembas.instances.client() ?: return@launch
// An instance signed in to before it was downgraded, or by 0.1 against a 1.x
@@ -98,7 +108,7 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
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) }
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
}
}
}
@@ -111,7 +121,7 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
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) }
_state.update { it.copy(error = getApplication<Application>().explain(e)) }
}
}
}
@@ -124,7 +134,7 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
getApplication<Application>().lembas.instances.client()
?.updateChat(chat.id, buildJsonObject { put("archived", true) })
}.onFailure { e ->
_state.update { it.copy(error = e.message) }
_state.update { it.copy(error = getApplication<Application>().explain(e)) }
load(kind)
}
}
@@ -133,11 +143,25 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChatsScreen(onOpen: (String) -> Unit, onNew: () -> Unit, onSettings: () -> Unit, onFiles: () -> Unit, model: ChatsViewModel = viewModel()) {
fun ChatsScreen(
onOpen: (String) -> Unit,
onNew: () -> Unit,
onNewAgent: () -> Unit,
onSettings: () -> Unit,
onFiles: () -> 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) }
// Read again each time the list comes back into view -- from a chat, from another app --
// so a new chat, a new title or a finished reply's dot is there without a pull.
var shown by remember { mutableStateOf(false) }
LifecycleResumeEffect(kind) {
model.load(kind, quiet = shown)
shown = true
onPauseOrDispose { }
}
Scaffold(
topBar = {
@@ -154,13 +178,11 @@ fun ChatsScreen(onOpen: (String) -> Unit, onNew: () -> Unit, onSettings: () -> U
)
},
floatingActionButton = {
if (tab == 0) {
ExtendedFloatingActionButton(
onClick = onNew,
icon = { Icon(Icons.Filled.Add, contentDescription = null) },
text = { Text(stringResource(R.string.new_chat)) },
)
}
ExtendedFloatingActionButton(
onClick = if (tab == 0) onNew else onNewAgent,
icon = { Icon(Icons.Filled.Add, contentDescription = null) },
text = { Text(stringResource(if (tab == 0) R.string.new_chat else R.string.new_agent_chat)) },
)
},
) { padding ->
Column(Modifier.padding(padding).fillMaxSize()) {
@@ -169,10 +191,14 @@ fun ChatsScreen(onOpen: (String) -> Unit, onNew: () -> Unit, onSettings: () -> U
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))
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp, top = 8.dp), verticalAlignment = Alignment.CenterVertically) {
// The sentence gives; the button keeps its size.
Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.weight(1f))
TextButton(onClick = { model.load(kind) }) { Text(stringResource(R.string.retry)) }
}
}
PullToRefreshBox(isRefreshing = state.loading, onRefresh = { model.load(kind) }, modifier = Modifier.fillMaxSize()) {
if (state.chats.isEmpty() && !state.loading) {
if (state.chats.isEmpty() && !state.loading && state.error == null) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(
stringResource(if (tab == 0) R.string.empty_chats else R.string.empty_agents),
@@ -47,6 +47,7 @@ import androidx.lifecycle.viewmodel.compose.viewModel
import eu.llembas.android.R
import eu.llembas.android.api.FileEntry
import eu.llembas.android.lembas
import eu.llembas.android.ui.explain
import eu.llembas.android.ui.theme.LocalPalette
import eu.llembas.android.ui.viewer.TreeFileViewer
import kotlinx.coroutines.Job
@@ -91,7 +92,7 @@ class FilesViewModel(app: Application) : AndroidViewModel(app) {
_state.value = FilesState(path = listing.path, parent = listing.parent, entries = listing.entries)
} catch (e: Exception) {
if (e is kotlinx.coroutines.CancellationException) throw e
_state.update { it.copy(loading = false, error = e.message ?: e.javaClass.simpleName) }
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
}
}
}
@@ -47,6 +47,7 @@ import eu.llembas.android.api.ServerFit
import eu.llembas.android.api.fit
import eu.llembas.android.api.normaliseBase
import eu.llembas.android.lembas
import eu.llembas.android.ui.explain
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
@@ -124,7 +125,7 @@ class SignInViewModel(app: Application) : AndroidViewModel(app) {
}
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_expired))
} catch (e: Exception) {
_state.value = SignInState.Failed(e.message ?: e.javaClass.simpleName)
_state.value = SignInState.Failed(getApplication<Application>().explain(e))
}
}
}
@@ -60,6 +60,7 @@ import eu.llembas.android.api.ApiException
import eu.llembas.android.api.ShowCard
import eu.llembas.android.lembas
import eu.llembas.android.ui.MarkdownText
import eu.llembas.android.ui.explain
import eu.llembas.android.ui.theme.LocalPalette
import java.io.IOException
@@ -159,7 +160,7 @@ private fun Viewer(file: Viewed, key: Any, webUrl: (ApiClient) -> String?, load:
else -> Loaded.Failed(e.message ?: context.getString(R.string.viewer_unavailable))
}
} catch (e: IOException) {
Loaded.Failed(e.message ?: e.javaClass.simpleName)
Loaded.Failed(context.explain(e))
}
}