Chats: the activity panel, the model's level control, team size, model pictures
CI / check (push) Canceled after 0s
CI / check (push) Canceled after 0s
The activity panel full screen (Context, Outputs, Background tasks with the team's room, Plan), kept current from the events route, with a summary line above the composer that opens it; an agent's conversation read-only and a stop with confirmation. The effort control follows the model (none, a Thinking switch, the picker); Agents fewest/most where a team is offered; model pictures in the picker and the chat's title. gen-strings takes the server's translation of a sentence with named placeholders (SERVER_ENGLISH); all eight languages complete. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
17 files changed
+1698
-54
No files matched your search
@@ -0,0 +1,97 @@
|
||||
package eu.llembas.android.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.BitmapFactory
|
||||
import android.util.LruCache
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* Models' pictures, fetched once with the token and kept small in memory. A picture that
|
||||
* failed is not asked for again until the app starts anew; the initial stands in for it.
|
||||
*/
|
||||
private object ModelImages {
|
||||
private const val SIDE = 128
|
||||
private val cache = LruCache<String, ImageBitmap>(48)
|
||||
private val failed = mutableSetOf<String>()
|
||||
|
||||
fun cached(path: String): ImageBitmap? = cache.get(path)
|
||||
|
||||
suspend fun load(context: Context, path: String): ImageBitmap? {
|
||||
cache.get(path)?.let { return it }
|
||||
if (path in failed) return null
|
||||
val api = context.lembas.instances.client() ?: return null
|
||||
val bytes = runCatching { api.modelImage(path) }.getOrNull()
|
||||
val image = bytes?.let { decode(it) }
|
||||
if (image == null) failed += path else cache.put(path, image)
|
||||
return image
|
||||
}
|
||||
|
||||
/** Decoded at about [SIDE] pixels a side: an avatar, not the original. */
|
||||
private suspend fun decode(bytes: ByteArray): ImageBitmap? = withContext(Dispatchers.Default) {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return@withContext null
|
||||
var sample = 1
|
||||
while (minOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= SIDE) sample *= 2
|
||||
val options = BitmapFactory.Options().apply { inSampleSize = sample }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)?.asImageBitmap()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A model's picture in a circle, as the web UI shows it beside the model's name: the picture
|
||||
* the instance has for it, or its initial on the theme's soft accent when there is none (or
|
||||
* while it loads, or when it could not be read).
|
||||
*/
|
||||
@Composable
|
||||
fun ModelAvatar(model: ModelInfo?, fallbackName: String, size: Dp = 24.dp, modifier: Modifier = Modifier) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val path = model?.image
|
||||
var image by remember(path) { mutableStateOf(path?.let { ModelImages.cached(it) }) }
|
||||
LaunchedEffect(path) {
|
||||
if (path != null && image == null) image = ModelImages.load(context, path)
|
||||
}
|
||||
Box(modifier.size(size).clip(CircleShape).background(palette.accentSoft), contentAlignment = Alignment.Center) {
|
||||
val shown = image
|
||||
if (shown != null) {
|
||||
Image(shown, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
} else {
|
||||
val name = model?.name?.ifBlank { null } ?: fallbackName
|
||||
Text(
|
||||
name.trim().firstOrNull()?.uppercase() ?: "?",
|
||||
color = palette.ink,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
fontSize = with(LocalDensity.current) { (size * 0.5f).toSp() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,661 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.os.SystemClock
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.automirrored.filled.NoteAdd
|
||||
import androidx.compose.material.icons.filled.Bolt
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material.icons.filled.Groups
|
||||
import androidx.compose.material.icons.filled.StopCircle
|
||||
import androidx.compose.material.icons.filled.Visibility
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
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.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
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.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Activity
|
||||
import eu.llembas.android.api.ActivityAgent
|
||||
import eu.llembas.android.api.ActivityLogic
|
||||
import eu.llembas.android.api.ActivitySummary
|
||||
import eu.llembas.android.api.AgentDetail
|
||||
import eu.llembas.android.api.ContextUse
|
||||
import eu.llembas.android.api.Output
|
||||
import eu.llembas.android.api.RoomMessage
|
||||
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 eu.llembas.android.ui.theme.Palette
|
||||
import eu.llembas.android.ui.viewer.TreeFileViewer
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
// --- The strip above the composer ---------------------------------------------------------
|
||||
|
||||
/** What runs in the background, in one line ("3 agents working · 1 queued"), opening the panel. */
|
||||
@Composable
|
||||
fun ActivityStrip(summary: ActivitySummary, onOpen: () -> Unit) {
|
||||
val counts = ActivityLogic.stripCounts(summary)
|
||||
if (counts.isEmpty()) return
|
||||
val palette = LocalPalette.current
|
||||
val words = counts.map { (state, n) -> stateCount(state, n) }
|
||||
Surface(
|
||||
onClick = onOpen,
|
||||
color = palette.surfaceRaised,
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp).heightIn(min = 48.dp),
|
||||
) {
|
||||
Row(Modifier.padding(horizontal = 12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Bolt, contentDescription = null, tint = palette.accent, modifier = Modifier.size(18.dp))
|
||||
Text(
|
||||
words.joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f).padding(horizontal = 8.dp),
|
||||
)
|
||||
Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = stringResource(R.string.activity_open), tint = palette.inkFaint)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun stateCount(state: String, n: Int): String = when (state) {
|
||||
"working" -> if (n == 1) stringResource(R.string.agents_one_working) else stringResource(R.string.agents_n_working, n.toString())
|
||||
"queued" -> stringResource(R.string.agents_n_queued, n.toString())
|
||||
"waiting" -> stringResource(R.string.agents_n_waiting, n.toString())
|
||||
else -> stringResource(R.string.agents_n_finished, n.toString())
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun stateWord(state: String): String = when (state) {
|
||||
"queued" -> stringResource(R.string.agent_state_queued)
|
||||
"working" -> stringResource(R.string.agent_state_working)
|
||||
"waiting" -> stringResource(R.string.agent_state_waiting)
|
||||
"done" -> stringResource(R.string.agent_state_done)
|
||||
"stopped" -> stringResource(R.string.agent_state_stopped)
|
||||
else -> stringResource(R.string.agent_state_error)
|
||||
}
|
||||
|
||||
/** The state's dot, in the web panel's colours: accent working, warning waiting, success done. */
|
||||
private fun stateColour(palette: Palette, state: String): Color = when (state) {
|
||||
"working" -> palette.accent
|
||||
"queued", "waiting" -> palette.warning
|
||||
"done" -> palette.success
|
||||
"error" -> palette.danger
|
||||
else -> palette.inkFaint
|
||||
}
|
||||
|
||||
/** A context category's colour, as the web's `activity-context__seg--*` maps them to tokens. */
|
||||
private fun categoryColour(palette: Palette, key: String): Color = when (key) {
|
||||
"messages" -> palette.accent
|
||||
"system" -> palette.inkMuted
|
||||
"memory" -> palette.warning
|
||||
"instructions" -> palette.success
|
||||
"tools" -> palette.ink
|
||||
"mcp_tools" -> palette.danger
|
||||
"since" -> palette.inkFaint
|
||||
"buffer" -> palette.borderStrong
|
||||
else -> palette.border
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun categoryName(key: String): String = when (key) {
|
||||
"messages" -> stringResource(R.string.ctx_messages)
|
||||
"system" -> stringResource(R.string.ctx_system)
|
||||
"memory" -> stringResource(R.string.ctx_memory)
|
||||
"instructions" -> stringResource(R.string.ctx_instructions)
|
||||
"tools" -> stringResource(R.string.ctx_tools)
|
||||
"mcp_tools" -> stringResource(R.string.ctx_mcp_tools)
|
||||
"since" -> stringResource(R.string.ctx_since)
|
||||
"buffer" -> stringResource(R.string.ctx_buffer)
|
||||
"free" -> stringResource(R.string.ctx_free)
|
||||
else -> key
|
||||
}
|
||||
|
||||
// --- The panel ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The chat's activity, full screen: Context, Outputs, Background tasks (with the team's room)
|
||||
* and Plan -- the web's activity panel, from `GET /chats/{chat}/activity`. Kept current by the
|
||||
* events route through the view model; without it, read again every few seconds while open.
|
||||
* Everything an agent wrote is a model's words: names, roles and briefs as plain text, the
|
||||
* room and replies through [MarkdownText]'s untrusted rules.
|
||||
*/
|
||||
@Composable
|
||||
fun ActivityPanel(chatId: String, state: ChatState, model: ChatViewModel, canOpenFiles: Boolean, onClose: () -> Unit) {
|
||||
val activity = state.activity
|
||||
val live by rememberUpdatedState(state.activityLive)
|
||||
var now by remember { mutableLongStateOf(SystemClock.elapsedRealtime()) }
|
||||
var stopping by remember { mutableStateOf<ActivityAgent?>(null) }
|
||||
var reading by remember { mutableStateOf<ActivityAgent?>(null) }
|
||||
var viewing by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
model.panel(true)
|
||||
var ticks = 0
|
||||
while (true) {
|
||||
delay(1_000)
|
||||
now = SystemClock.elapsedRealtime()
|
||||
ticks++
|
||||
// Without the events route, the panel reads itself again: cheaply, every 5 s.
|
||||
if (!live && ticks % 5 == 0) model.loadActivity(context = false)
|
||||
}
|
||||
}
|
||||
|
||||
val close = {
|
||||
model.panel(false)
|
||||
onClose()
|
||||
}
|
||||
Dialog(onDismissRequest = close, properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = close) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) }
|
||||
},
|
||||
title = { Text(stringResource(R.string.activity)) },
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
if (activity == null) {
|
||||
Box(Modifier.padding(padding).fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
|
||||
return@Scaffold
|
||||
}
|
||||
LazyColumn(
|
||||
Modifier.padding(padding).fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
item { Section(stringResource(R.string.activity_context)) { ContextSection(activity.context) } }
|
||||
item {
|
||||
Section(stringResource(R.string.activity_outputs), count = activity.outputs.size.takeIf { it > 0 }) {
|
||||
OutputsSection(activity.outputs, canOpenFiles) { viewing = it }
|
||||
}
|
||||
}
|
||||
item {
|
||||
Section(stringResource(R.string.activity_tasks)) {
|
||||
TasksSection(activity, state.activityAt, now, onStop = { stopping = it }, onRead = { reading = it })
|
||||
}
|
||||
}
|
||||
ActivityLogic.plan(activity.plan)?.let { plan ->
|
||||
item { Section(stringResource(R.string.mode_plan)) { PlanBody(plan) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stopping?.let { agent ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { stopping = null },
|
||||
title = { Text(stringResource(R.string.agent_stop, agent.name)) },
|
||||
text = {
|
||||
Text(
|
||||
if (agent.kind == "member") {
|
||||
stringResource(R.string.agent_stop_member_confirm, agent.name)
|
||||
} else {
|
||||
stringResource(R.string.agent_stop_confirm, agent.name)
|
||||
},
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
model.stopAgent(agent)
|
||||
stopping = null
|
||||
}) { Text(stringResource(R.string.stop)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { stopping = null }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
reading?.let { agent -> AgentConversation(chatId, agent, onClose = { reading = null }) }
|
||||
viewing?.let { path -> TreeFileViewer(path, onClose = { viewing = null }) }
|
||||
}
|
||||
|
||||
/** A heading that folds its section away, open to begin with. */
|
||||
@Composable
|
||||
private fun Section(title: String, count: Int? = null, content: @Composable () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(title) { mutableStateOf(true) }
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = !open },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(title, style = MaterialTheme.typography.titleSmall, modifier = Modifier.weight(1f))
|
||||
count?.let { Text(it.toString(), style = MaterialTheme.typography.labelMedium, color = palette.inkMuted, modifier = Modifier.padding(end = 8.dp)) }
|
||||
Icon(if (open) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, contentDescription = null, tint = palette.inkFaint)
|
||||
}
|
||||
if (open) content()
|
||||
HorizontalDivider(Modifier.padding(top = 8.dp), color = palette.border)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Empty(text: String) {
|
||||
Text(text, style = MaterialTheme.typography.bodySmall, color = LocalPalette.current.inkMuted)
|
||||
}
|
||||
|
||||
// --- Context --------------------------------------------------------------------------------
|
||||
|
||||
@Composable
|
||||
private fun ContextSection(context: ContextUse?) {
|
||||
val palette = LocalPalette.current
|
||||
if (context == null) {
|
||||
Empty(stringResource(R.string.activity_not_measured))
|
||||
return
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
val pct = context.percent
|
||||
Text(
|
||||
if (pct != null) stringResource(R.string.activity_used, ActivityLogic.percent(pct)) else ActivityLogic.compactTokens(context.used),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
if (context.limit > 0) {
|
||||
"${ActivityLogic.compactTokens(context.used)} / ${ActivityLogic.compactTokens(context.limit)}"
|
||||
} else {
|
||||
stringResource(R.string.activity_window_unknown)
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
)
|
||||
}
|
||||
val parts = ActivityLogic.barParts(context)
|
||||
if (parts.isNotEmpty()) {
|
||||
// One segment per category, by its tokens; the rest of the window is the bar's own
|
||||
// background. Weights, so the segments always fill exactly the bar's width.
|
||||
Row(Modifier.fillMaxWidth().height(8.dp).clip(RoundedCornerShape(4.dp)).background(palette.surfaceRaised)) {
|
||||
parts.forEach { part -> Box(Modifier.weight(part.tokens.toFloat()).fillMaxHeight().background(categoryColour(palette, part.key))) }
|
||||
val rest = (context.limit - parts.sumOf { it.tokens }).coerceAtLeast(0)
|
||||
if (rest > 0) Spacer(Modifier.weight(rest.toFloat()))
|
||||
}
|
||||
}
|
||||
// Each row a fixed grid: swatch, the name that gives, two number columns of their own
|
||||
// width -- the numbers line up whatever the names say in which language.
|
||||
context.categories.forEach { part ->
|
||||
Row(Modifier.fillMaxWidth().heightIn(min = 24.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(Modifier.size(10.dp).clip(RoundedCornerShape(2.dp)).background(categoryColour(palette, part.key)))
|
||||
Text(
|
||||
categoryName(part.key),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f).padding(horizontal = 8.dp),
|
||||
)
|
||||
Text(
|
||||
ActivityLogic.compactTokens(part.tokens),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
textAlign = TextAlign.End,
|
||||
modifier = Modifier.width(56.dp),
|
||||
)
|
||||
Text(
|
||||
part.percent?.let { "${ActivityLogic.percent(it)}%" } ?: "—",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
textAlign = TextAlign.End,
|
||||
modifier = Modifier.width(56.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(if (context.measured) R.string.activity_measured else R.string.activity_estimated) + " " +
|
||||
stringResource(R.string.activity_tools_offered, context.toolsCount.toString()),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Outputs --------------------------------------------------------------------------------
|
||||
|
||||
@Composable
|
||||
private fun OutputsSection(outputs: List<Output>, canOpen: Boolean, onOpen: (String) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
if (outputs.isEmpty()) {
|
||||
Empty(stringResource(R.string.outputs_empty))
|
||||
return
|
||||
}
|
||||
Column {
|
||||
outputs.forEach { out ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable(enabled = canOpen && out.path.isNotBlank()) { onOpen(out.path) },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
if (out.created) Icons.AutoMirrored.Filled.NoteAdd else Icons.Filled.Description,
|
||||
contentDescription = null,
|
||||
tint = palette.inkMuted,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
Column(Modifier.weight(1f).padding(horizontal = 8.dp)) {
|
||||
Text(out.name.ifBlank { out.path }, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
out.path,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (out.added != null) {
|
||||
Text("+${out.added}", style = MaterialTheme.typography.labelMedium, color = palette.success)
|
||||
Text(" −${out.removed ?: 0}", style = MaterialTheme.typography.labelMedium, color = palette.danger)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Background tasks -----------------------------------------------------------------------
|
||||
|
||||
@Composable
|
||||
private fun TasksSection(activity: Activity, readAt: Long, now: Long, onStop: (ActivityAgent) -> Unit, onRead: (ActivityAgent) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val team = activity.team
|
||||
if (activity.agents.isEmpty() && team == null) {
|
||||
Empty(stringResource(R.string.tasks_empty))
|
||||
return
|
||||
}
|
||||
val (live, ended) = ActivityLogic.split(activity.agents)
|
||||
var showEnded by rememberSaveable { mutableStateOf(false) }
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
val counts = ActivityLogic.stripCounts(activity.summary)
|
||||
Text(
|
||||
if (counts.isEmpty()) stringResource(R.string.tasks_none_running) else counts.map { (s, n) -> stateCount(s, n) }.joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
)
|
||||
team?.let { t ->
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Groups, contentDescription = null, tint = palette.inkMuted, modifier = Modifier.size(18.dp))
|
||||
Text(
|
||||
stringResource(R.string.team_size, t.size.toString(), t.max.toString()),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.padding(start = 6.dp),
|
||||
)
|
||||
}
|
||||
if (t.goal.isNotBlank()) Text(t.goal, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
ActivityLogic.flatten(live).forEach { AgentRow(it, readAt, now, onStop, onRead) }
|
||||
if (ended.isNotEmpty()) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { showEnded = !showEnded },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(if (showEnded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, contentDescription = null, tint = palette.inkFaint)
|
||||
Text(
|
||||
stringResource(R.string.agents_n_finished, ended.size.toString()),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.padding(start = 6.dp),
|
||||
)
|
||||
}
|
||||
if (showEnded) ActivityLogic.flatten(ended).forEach { AgentRow(it, readAt, now, onStop, onRead) }
|
||||
}
|
||||
team?.let { t ->
|
||||
Text(stringResource(R.string.team_room), style = MaterialTheme.typography.titleSmall, modifier = Modifier.padding(top = 12.dp))
|
||||
if (t.room.isEmpty()) Empty(stringResource(R.string.room_empty)) else t.room.forEach { RoomEntry(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One agent: a fixed row (state dot, what it is -- the part that gives, cut not wrapped --,
|
||||
* elapsed time in a column of its own width, the stop button at its tap size), indented by
|
||||
* its depth in the tree; tapped, it opens to its brief, model, latest step and what it is
|
||||
* writing, and the way into its conversation.
|
||||
*/
|
||||
@Composable
|
||||
private fun AgentRow(agent: ActivityAgent, readAt: Long, now: Long, onStop: (ActivityAgent) -> Unit, onRead: (ActivityAgent) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(agent.kind, agent.id) { mutableStateOf(false) }
|
||||
Column(Modifier.fillMaxWidth().padding(start = (16 * agent.depth.coerceIn(0, 4)).dp)) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = !open },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(Modifier.size(8.dp).clip(CircleShape).background(stateColour(palette, agent.state)))
|
||||
Column(Modifier.weight(1f).padding(horizontal = 8.dp)) {
|
||||
Text(agent.name, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (agent.role.isNotBlank()) {
|
||||
Text(agent.role, style = MaterialTheme.typography.labelSmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
ActivityLogic.duration(ActivityLogic.elapsed(agent, readAt, now)),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = palette.inkMuted,
|
||||
textAlign = TextAlign.End,
|
||||
modifier = Modifier.width(64.dp),
|
||||
)
|
||||
Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
|
||||
if (agent.stoppable) {
|
||||
IconButton(onClick = { onStop(agent) }) {
|
||||
Icon(Icons.Filled.StopCircle, contentDescription = stringResource(R.string.agent_stop, agent.name), tint = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (open) {
|
||||
Column(Modifier.padding(start = 16.dp, bottom = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
val facts = listOfNotNull(
|
||||
stateWord(agent.state),
|
||||
agent.agent.ifBlank { null },
|
||||
agent.model.ifBlank { null },
|
||||
if (agent.steps > 0) stringResource(R.string.agent_steps, agent.steps.toString(), agent.tools.toString()) else null,
|
||||
)
|
||||
Text(facts.joinToString(" · "), style = MaterialTheme.typography.labelSmall, color = palette.inkMuted)
|
||||
if (agent.brief.isNotBlank()) Text(agent.brief, style = MaterialTheme.typography.bodySmall)
|
||||
agent.step?.let { step ->
|
||||
Text(
|
||||
listOf(step.label.ifBlank { step.tool }, step.title).filter { it.isNotBlank() }.joinToString(" "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = if (step.error) palette.danger else palette.inkMuted,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (agent.text.isNotBlank()) {
|
||||
Text(agent.text, style = MaterialTheme.typography.bodySmall, color = palette.ink, maxLines = 6, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
if (agent.transcript) {
|
||||
OutlinedButton(onClick = { onRead(agent) }) {
|
||||
Icon(Icons.Filled.Visibility, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Text(stringResource(R.string.agent_open_conversation), modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RoomEntry(entry: RoomMessage) {
|
||||
val palette = LocalPalette.current
|
||||
Row(Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
|
||||
// A report is marked as on the web: a bar of the accent down its side.
|
||||
Box(Modifier.width(3.dp).heightIn(min = 24.dp).background(if (entry.report) palette.accent else Color.Transparent))
|
||||
Column(Modifier.weight(1f).padding(start = 8.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
"#${entry.n} ${entry.from} → ${entry.to.joinToString(", ")}",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f, fill = false),
|
||||
)
|
||||
if (entry.report) {
|
||||
Text(
|
||||
stringResource(R.string.room_report),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.accentInk,
|
||||
modifier = Modifier.padding(start = 6.dp).clip(RoundedCornerShape(4.dp)).background(palette.accent).padding(horizontal = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
MarkdownText(entry.text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- One agent's conversation, read-only ------------------------------------------------------
|
||||
|
||||
/** What a background agent was told and said: `GET /chats/{chat}/agents/{kind}/{id}`, re-read while it works. */
|
||||
@Composable
|
||||
private fun AgentConversation(chatId: String, agent: ActivityAgent, onClose: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
var detail by remember { mutableStateOf<AgentDetail?>(null) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
LaunchedEffect(agent.kind, agent.id) {
|
||||
val api = context.lembas.instances.client() ?: return@LaunchedEffect
|
||||
while (true) {
|
||||
try {
|
||||
detail = api.agent(chatId, agent.kind, agent.id)
|
||||
error = null
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
error = context.explain(e)
|
||||
}
|
||||
if (detail?.agent?.isActive != true) break
|
||||
delay(3_000)
|
||||
}
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = onClose) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = {
|
||||
Column {
|
||||
Text(agent.name, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
val now = detail?.agent ?: agent
|
||||
Text(
|
||||
listOf(stateWord(now.state), now.model).filter { it.isNotBlank() }.joinToString(" · "),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
val turns = detail?.transcript
|
||||
when {
|
||||
turns == null && error != null -> Box(Modifier.padding(padding).fillMaxSize().padding(32.dp), contentAlignment = Alignment.Center) {
|
||||
Text(error.orEmpty(), color = palette.inkMuted, textAlign = TextAlign.Center)
|
||||
}
|
||||
|
||||
turns == null -> Box(Modifier.padding(padding).fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
|
||||
|
||||
else -> LazyColumn(
|
||||
Modifier.padding(padding).fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
if (turns.isEmpty()) item { Empty(stringResource(R.string.agent_nothing_yet)) }
|
||||
items(turns) { turn ->
|
||||
if (turn.role == "user") {
|
||||
Column(
|
||||
Modifier.fillMaxWidth().clip(
|
||||
RoundedCornerShape(8.dp),
|
||||
).background(if (turn.machine) palette.surfaceRaised else palette.bubbleUser).padding(12.dp),
|
||||
) {
|
||||
if (turn.machine) {
|
||||
Text(
|
||||
stringResource(R.string.agent_machine),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
)
|
||||
}
|
||||
Text(turn.text, style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
} else {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
turn.tools.forEach { tool ->
|
||||
Text(
|
||||
listOf(tool.name, tool.title).filter { it.isNotBlank() }.joinToString(" "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = if (tool.isError) palette.danger else palette.inkMuted,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (turn.text.isNotBlank()) MarkdownText(turn.text)
|
||||
if (turn.error.isNotBlank()) Text(turn.error, style = MaterialTheme.typography.bodySmall, color = palette.danger)
|
||||
if (turn.running) {
|
||||
Text(
|
||||
stringResource(R.string.loading_line),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ 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.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.LazyListState
|
||||
import androidx.compose.foundation.lazy.items
|
||||
@@ -35,11 +36,14 @@ 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.Bolt
|
||||
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.Groups
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Psychology
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material3.AlertDialog
|
||||
@@ -57,6 +61,7 @@ import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SheetValue
|
||||
import androidx.compose.material3.Slider
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Text
|
||||
@@ -76,19 +81,25 @@ 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.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.AgentTarget
|
||||
import eu.llembas.android.api.AgentsSetting
|
||||
import eu.llembas.android.api.LinkedDevice
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.ShowCard
|
||||
import eu.llembas.android.assist.Recorder
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.ModelAvatar
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.viewer.FileViewer
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -110,7 +121,9 @@ fun ChatScreen(
|
||||
var editing by remember { mutableStateOf<Message?>(null) }
|
||||
var showing by remember { mutableStateOf<ShowCard?>(null) }
|
||||
var renaming by remember { mutableStateOf(false) }
|
||||
var activityOpen by rememberSaveable { mutableStateOf(false) }
|
||||
val context = LocalContext.current
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
val scope = rememberCoroutineScope()
|
||||
val copy: (String) -> Unit = { text ->
|
||||
context.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText("LLeMbas", text))
|
||||
@@ -122,6 +135,10 @@ fun ChatScreen(
|
||||
// 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) } }
|
||||
// The chat's background agents, followed while the screen is in front and not otherwise.
|
||||
LaunchedEffect(state.chat?.id) {
|
||||
if (state.chat?.id != null) lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { model.watchActivity() }
|
||||
}
|
||||
LaunchedEffect(state.error, state.notice) {
|
||||
(state.error ?: state.notice)?.let {
|
||||
snackbar.showSnackbar(it)
|
||||
@@ -156,14 +173,22 @@ fun ChatScreen(
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Text(
|
||||
state.chat?.title?.ifBlank { null } ?: stringResource(if (agent) R.string.new_agent_chat else R.string.new_chat),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
state.chat?.model?.ifBlank { null }?.let { id ->
|
||||
ModelAvatar(state.models.firstOrNull { it.id == id }, id, size = 28.dp, modifier = Modifier.padding(end = 10.dp))
|
||||
}
|
||||
Text(
|
||||
state.chat?.title?.ifBlank { null } ?: stringResource(if (agent) R.string.new_agent_chat else R.string.new_chat),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
if (state.chat != null) {
|
||||
IconButton(onClick = { activityOpen = true }) {
|
||||
Icon(Icons.Filled.Bolt, contentDescription = stringResource(R.string.activity_open))
|
||||
}
|
||||
IconButton(onClick = { menu = true }) {
|
||||
Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more))
|
||||
}
|
||||
@@ -205,7 +230,9 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
}
|
||||
if (live != null && live.jobs.isNotEmpty()) {
|
||||
state.summary?.let { summary -> ActivityStrip(summary) { activityOpen = true } }
|
||||
// A server without the activity panel: its jobs frame, one chip each, as before.
|
||||
if (state.summary == null && 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) })
|
||||
@@ -284,6 +311,13 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
|
||||
if (activityOpen) {
|
||||
state.chat?.let { chat ->
|
||||
// A device's files are on the device: the panel lists them, the tree cannot open them.
|
||||
ActivityPanel(chat.id, state, model, canOpenFiles = !chat.isAgent, onClose = { activityOpen = false })
|
||||
}
|
||||
}
|
||||
|
||||
showing?.let { file ->
|
||||
state.chat?.id?.let { id -> FileViewer(id, file, onClose = { showing = null }) }
|
||||
}
|
||||
@@ -364,6 +398,9 @@ private fun Composer(model: ChatViewModel, state: ChatState, agent: Boolean) {
|
||||
var text by rememberSaveable { mutableStateOf("") }
|
||||
var chosenModel by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var chosenEffort by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var chosenMin by rememberSaveable { mutableStateOf<Int?>(null) }
|
||||
var chosenMax by rememberSaveable { mutableStateOf<Int?>(null) }
|
||||
var askAgents by remember { mutableStateOf(false) }
|
||||
var planMode by rememberSaveable { mutableStateOf(false) }
|
||||
var agentMode by rememberSaveable { mutableStateOf("edit") }
|
||||
var device by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
@@ -432,14 +469,27 @@ private fun Composer(model: ChatViewModel, state: ChatState, agent: Boolean) {
|
||||
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()) {
|
||||
val info = state.models.firstOrNull { it.id == current }
|
||||
if (info != null) {
|
||||
// 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")
|
||||
// changes at once, as the web page's control does. The control is the model's:
|
||||
// none for one level, a Thinking switch for off and one more, else the picker.
|
||||
val level = info.level(if (chat == null) chosenEffort else chat.effort?.ifBlank { null })
|
||||
LevelControl(info, level) { picked ->
|
||||
if (chat == null) chosenEffort = picked else model.change("effort", picked)
|
||||
}
|
||||
}
|
||||
// The team's size, where a team is offered: the server's word for a chat that
|
||||
// exists, the model's facts for one about to be made.
|
||||
val teamOffered = if (chat != null) state.teamOffered else !newAgent && info?.mayHaveTeam == true
|
||||
if (teamOffered) {
|
||||
val setting = chat?.agents ?: AgentsSetting(chosenMin ?: 1, chosenMax ?: 4)
|
||||
AssistChip(
|
||||
onClick = { askAgents = true },
|
||||
leadingIcon = { Icon(Icons.Filled.Groups, contentDescription = null) },
|
||||
label = { Text(stringResource(R.string.team_chip, setting.min.toString(), setting.max.toString()), maxLines = 1) },
|
||||
)
|
||||
}
|
||||
when {
|
||||
newAgent -> ModeChip(agentMode) { agentMode = it }
|
||||
|
||||
@@ -515,8 +565,9 @@ private fun Composer(model: ChatViewModel, state: ChatState, agent: Boolean) {
|
||||
} else {
|
||||
null
|
||||
},
|
||||
effort = chosenEffort,
|
||||
effort = chosenEffort?.takeIf { picked -> state.models.firstOrNull { it.id == current }?.offered?.contains(picked) == true },
|
||||
agent = if (newAgent) target?.let { AgentTarget(it.id, directory) } else null,
|
||||
agents = if (chosenMin != null || chosenMax != null) AgentsSetting(chosenMin ?: 1, chosenMax ?: 4) else null,
|
||||
)
|
||||
text = ""
|
||||
},
|
||||
@@ -525,6 +576,19 @@ private fun Composer(model: ChatViewModel, state: ChatState, agent: Boolean) {
|
||||
}
|
||||
}
|
||||
|
||||
if (askAgents) {
|
||||
val now = chat?.agents ?: AgentsSetting(chosenMin ?: 1, chosenMax ?: 4)
|
||||
AgentsDialog(now, onDismiss = { askAgents = false }) { picked ->
|
||||
askAgents = false
|
||||
if (chat == null) {
|
||||
chosenMin = picked.min
|
||||
chosenMax = picked.max
|
||||
} else {
|
||||
model.setAgents(picked)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (askDirectory) {
|
||||
var typed by remember { mutableStateOf(directory) }
|
||||
AlertDialog(
|
||||
@@ -593,34 +657,115 @@ private fun ModeChip(current: String, onPick: (String) -> Unit) {
|
||||
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) })
|
||||
val shown = models.firstOrNull { it.id == current }
|
||||
AssistChip(
|
||||
onClick = { open = true },
|
||||
leadingIcon = { ModelAvatar(shown, current ?: "?", size = 20.dp) },
|
||||
label = { Text(shown?.name ?: current ?: "—", maxLines = 1) },
|
||||
)
|
||||
DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
|
||||
models.forEach { m ->
|
||||
DropdownMenuItem(text = { Text(m.name) }, onClick = {
|
||||
open = false
|
||||
onPick(m.id)
|
||||
})
|
||||
DropdownMenuItem(
|
||||
leadingIcon = { ModelAvatar(m, m.id, size = 28.dp) },
|
||||
text = { Text(m.name.ifBlank { m.id }) },
|
||||
onClick = {
|
||||
open = false
|
||||
onPick(m.id)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A level's name: `off` and `default` in words, an effort as the model calls it. */
|
||||
@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)
|
||||
})
|
||||
private fun levelName(level: String): String = when (level) {
|
||||
"off" -> stringResource(R.string.level_off)
|
||||
"default" -> stringResource(R.string.level_default)
|
||||
else -> level
|
||||
}
|
||||
|
||||
/**
|
||||
* How hard the model thinks, by the model's `control`: nothing for one level; a Thinking chip
|
||||
* that is on or off for `off` and one effort; the picker for more.
|
||||
*/
|
||||
@Composable
|
||||
private fun LevelControl(model: ModelInfo, level: String, onPick: (String) -> Unit) {
|
||||
when (model.levelControl) {
|
||||
"switch" -> FilterChip(
|
||||
selected = level != "off",
|
||||
onClick = { onPick(if (level == "off") model.onLevel else "off") },
|
||||
leadingIcon = { Icon(Icons.Filled.Psychology, contentDescription = null) },
|
||||
label = { Text(stringResource(R.string.thinking_switch)) },
|
||||
)
|
||||
|
||||
"slider" -> {
|
||||
var open by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
AssistChip(onClick = { open = true }, label = { Text(stringResource(R.string.effort_level, levelName(level)), maxLines = 1) })
|
||||
DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
|
||||
model.offered.forEach { option ->
|
||||
DropdownMenuItem(
|
||||
text = { Text(levelName(option)) },
|
||||
trailingIcon = { if (option == level) Text("✓") },
|
||||
onClick = {
|
||||
open = false
|
||||
onPick(option)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The team's size: the fewest and the most agents, its own included. Two sliders on one
|
||||
* column, each with its label and value on a row of its own, so the two line up whatever the
|
||||
* words. The most never goes under the fewest; the server checks the pair against its cap.
|
||||
*/
|
||||
@Composable
|
||||
private fun AgentsDialog(now: AgentsSetting, onDismiss: () -> Unit, onSave: (AgentsSetting) -> Unit) {
|
||||
var low by remember { mutableStateOf(now.min.coerceIn(1, AgentsSetting.CAP)) }
|
||||
var high by remember { mutableStateOf(now.max.coerceIn(1, AgentsSetting.CAP)) }
|
||||
val palette = LocalPalette.current
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.team_agents)) },
|
||||
text = {
|
||||
Column {
|
||||
Text(stringResource(R.string.team_hint), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
AgentsSlider(stringResource(R.string.team_fewest), low) {
|
||||
low = it
|
||||
if (high < it) high = it
|
||||
}
|
||||
AgentsSlider(stringResource(R.string.team_most), high) {
|
||||
high = it
|
||||
if (low > it) low = it
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { onSave(AgentsSetting(low, high)) }) { Text(stringResource(R.string.save)) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AgentsSlider(label: String, value: Int, onChange: (Int) -> Unit) {
|
||||
Column(Modifier.padding(top = 12.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(label, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
|
||||
Text(value.toString(), style = MaterialTheme.typography.titleMedium, modifier = Modifier.width(40.dp), textAlign = TextAlign.End)
|
||||
}
|
||||
Slider(
|
||||
value = value.toFloat(),
|
||||
onValueChange = { onChange(Math.round(it).coerceIn(1, AgentsSetting.CAP)) },
|
||||
valueRange = 1f..AgentsSetting.CAP.toFloat(),
|
||||
steps = AgentsSetting.CAP - 2,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -2,17 +2,24 @@ package eu.llembas.android.ui.chat
|
||||
|
||||
import android.app.Application
|
||||
import android.net.Uri
|
||||
import android.os.SystemClock
|
||||
import android.provider.OpenableColumns
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import eu.llembas.android.api.Activity
|
||||
import eu.llembas.android.api.ActivityAgent
|
||||
import eu.llembas.android.api.ActivityFrame
|
||||
import eu.llembas.android.api.ActivitySummary
|
||||
import eu.llembas.android.api.AgentTarget
|
||||
import eu.llembas.android.api.AgentsSetting
|
||||
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.LembasJson
|
||||
import eu.llembas.android.api.LinkedDevice
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.Message
|
||||
@@ -49,6 +56,15 @@ data class ChatState(
|
||||
val unsent: String? = null,
|
||||
/** A card somebody answered elsewhere first: said once, then cleared. */
|
||||
val notice: String? = null,
|
||||
/** The activity panel's facts, once it has been opened; [activityAt] is when they were read. */
|
||||
val activity: Activity? = null,
|
||||
val activityAt: Long = 0,
|
||||
/** The strip's counts, from the events route (or the first read). */
|
||||
val summary: ActivitySummary? = null,
|
||||
/** Whether this chat may have a team: the server's word for a chat that exists. */
|
||||
val teamOffered: Boolean = false,
|
||||
/** Whether the events route is followed; without it an open panel polls. */
|
||||
val activityLive: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -93,6 +109,11 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
it.copy(chat = detail.chat, messages = detail.messages, more = detail.more, models = models, loading = false)
|
||||
}
|
||||
detail.live?.let { follow(it) }
|
||||
// Whether a team is offered and what runs in the background: the cheap read,
|
||||
// without the context count. A server without the panel has no answer.
|
||||
runCatching { client.activity(chatId, context = false) }.onSuccess { a ->
|
||||
_state.update { it.copy(teamOffered = a.teamOffered, summary = a.summary) }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
@@ -161,7 +182,15 @@ 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, agent: AgentTarget? = null) {
|
||||
fun send(
|
||||
text: String,
|
||||
model: String? = null,
|
||||
mode: String? = null,
|
||||
effort: String? = null,
|
||||
temporary: Boolean = false,
|
||||
agent: AgentTarget? = null,
|
||||
agents: AgentsSetting? = null,
|
||||
) {
|
||||
val attached = _state.value.pending
|
||||
val files = attached.map { it.id }
|
||||
if (text.isBlank() && files.isEmpty()) return
|
||||
@@ -171,7 +200,16 @@ 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, agent = agent)
|
||||
val made = client.createChat(
|
||||
text,
|
||||
files,
|
||||
model = model,
|
||||
temporary = temporary,
|
||||
effort = effort,
|
||||
mode = mode,
|
||||
agent = agent,
|
||||
agents = agents,
|
||||
)
|
||||
_state.update { it.copy(chat = made.chat, messages = listOfNotNull(made.message, made.reply)) }
|
||||
made.reply?.let { follow(it.id) }
|
||||
} else {
|
||||
@@ -226,6 +264,84 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
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) }
|
||||
// Another model may serve one request at a time, or more: whether a team is offered
|
||||
// follows it.
|
||||
if (key == "model") {
|
||||
runCatching { api.activity(chat.id, context = false) }.onSuccess { r -> _state.update { it.copy(teamOffered = r.teamOffered) } }
|
||||
}
|
||||
}
|
||||
|
||||
/** The team's size, both ends; the server refuses a pair outside its bounds in its words. */
|
||||
fun setAgents(agents: AgentsSetting) = control { api, chat ->
|
||||
val updated = api.setAgents(chat.id, agents)
|
||||
_state.update { it.copy(chat = updated) }
|
||||
}
|
||||
|
||||
// --- The activity panel ------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Follow the chat's activity while the screen is in front: the events route says when
|
||||
* anything changed, with the strip's counts; an open panel then reads the whole of it
|
||||
* again. Runs until cancelled. A server without the route (or one that refuses it) leaves
|
||||
* the strip to the first read and an open panel to polling.
|
||||
*/
|
||||
suspend fun watchActivity() {
|
||||
val chat = _state.value.chat ?: return
|
||||
val client = runCatching { api() }.getOrNull() ?: return
|
||||
if (_state.value.summary == null) {
|
||||
// A chat its first message just made: whether a team is offered, read once.
|
||||
runCatching { client.activity(chat.id, context = false) }.onSuccess { a ->
|
||||
_state.update { it.copy(teamOffered = a.teamOffered, summary = a.summary) }
|
||||
}
|
||||
}
|
||||
try {
|
||||
StreamClient(client).watch { client.activityEvents(chat.id) }.collect { frame ->
|
||||
if (frame.event != "activity") return@collect
|
||||
val read = runCatching { LembasJson.decodeFromString(ActivityFrame.serializer(), frame.data) }.getOrNull() ?: return@collect
|
||||
val changed = read.version != _state.value.activity?.version
|
||||
_state.update { it.copy(summary = read.summary, activityLive = true) }
|
||||
if (changed && panelOpen) loadActivity()
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
// Nothing to say: the strip and the panel do without the route.
|
||||
} finally {
|
||||
_state.update { it.copy(activityLive = false) }
|
||||
}
|
||||
}
|
||||
|
||||
private var panelOpen = false
|
||||
|
||||
fun panel(open: Boolean) {
|
||||
panelOpen = open
|
||||
if (open) loadActivity()
|
||||
}
|
||||
|
||||
/** Read the panel's facts; [context] false keeps the last count (the costly part). */
|
||||
fun loadActivity(context: Boolean = true) {
|
||||
val chat = _state.value.chat ?: return
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val read = api().activity(chat.id, context)
|
||||
_state.update { s ->
|
||||
s.copy(
|
||||
activity = if (context) read else read.copy(context = s.activity?.context),
|
||||
activityAt = SystemClock.elapsedRealtime(),
|
||||
summary = read.summary,
|
||||
teamOffered = read.teamOffered,
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop a background agent (and, for a member, those under it), then read the panel again. */
|
||||
fun stopAgent(agent: ActivityAgent) = control { api, chat ->
|
||||
api.stopAgent(chat.id, agent.kind, agent.id)
|
||||
loadActivity(context = false)
|
||||
}
|
||||
|
||||
fun delete(then: () -> Unit) = control { api, chat ->
|
||||
|
||||
Reference in new issue
Block a user