diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a38a7e..610def1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,19 @@ is in alpha and releases come off `main`. - **Test builds for every change**: each push to `dev` leaves an installable APK on the CI run, signed with a public test key so a newer test build installs over an older one. The version in Settings › About carries the run's number. +- **The activity panel**: the lightning button in a chat, or the line above the message box + ("3 agents working · 1 queued"), opens a full-screen view of what the chat is doing -- + **Context** (how much of the model's window is used, a bar and the breakdown by category), + **Outputs** (the files the chat and its agents wrote, with lines added and removed; tap one to + read it), **Background tasks** (every helper, command and team member as a tree, with its + state, how long it has run, its model, its latest step and what it is writing; open its whole + conversation read-only, or stop it after a confirmation; finished ones folded under "N + finished"), the team's **Room** and the **Plan**. It keeps itself current while it is open. +- **Agents, fewest and most**, in the chat's chips where the model can run a team: how many + agents the chat's team may have, its own included (1 to 4 to begin with). Set it before the + first message or change it in an open chat. +- **Model pictures**: the model picker and the chat's title show each model's picture from the + instance, or its initial where it has none. ### Changed @@ -32,6 +45,12 @@ is in alpha and releases come off `main`. sign-in, the chats, a chat, Files, the viewer, the assistant and Share. - The effort chosen for a **new** chat is now sent with its first message (it was lost until the chat existed). +- **The effort control is the model's own**: none for a model with one level, a **Think before + answering** chip that switches thinking on and off for a model that offers exactly that, and + the effort picker for more levels. "Off" is offered only by a model that can really switch + thinking off. A chat started without a choice starts at the model's start level. +- Requires the beta.5 `/api/v2` of LLeMbas 2.0 for the panel, the team size, the Thinking switch + and the pictures; against an older 2.0 beta the app keeps the effort picker and the jobs chips. - The agent mode "Manual" is translated, and "Plan" no longer reads as a price plan in German, French and Hungarian. diff --git a/app/src/main/java/eu/llembas/android/ui/ModelAvatar.kt b/app/src/main/java/eu/llembas/android/ui/ModelAvatar.kt new file mode 100644 index 0000000..e5e63d0 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/ModelAvatar.kt @@ -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(48) + private val failed = mutableSetOf() + + 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() }, + ) + } + } +} diff --git a/app/src/main/java/eu/llembas/android/ui/chat/ActivityPanel.kt b/app/src/main/java/eu/llembas/android/ui/chat/ActivityPanel.kt new file mode 100644 index 0000000..3a8c885 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/chat/ActivityPanel.kt @@ -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(null) } + var reading by remember { mutableStateOf(null) } + var viewing by remember { mutableStateOf(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, 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(null) } + var error by remember { mutableStateOf(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, + ) + } + } + } + } + } + } + } + } +} diff --git a/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt b/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt index 43fc32e..5f6dfd0 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt @@ -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(null) } var showing by remember { mutableStateOf(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(null) } var chosenEffort by rememberSaveable { mutableStateOf(null) } + var chosenMin by rememberSaveable { mutableStateOf(null) } + var chosenMax by rememberSaveable { mutableStateOf(null) } + var askAgents by remember { mutableStateOf(false) } var planMode by rememberSaveable { mutableStateOf(false) } var agentMode by rememberSaveable { mutableStateOf("edit") } var device by rememberSaveable { mutableStateOf(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, 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, 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, + ) } } diff --git a/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt b/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt index 5a73f24..70be3ec 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt @@ -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 -> diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index b893f33..26e05a2 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -55,11 +55,64 @@ Zpět Zrušit Zavřít - Úsilí: vypnuto Plán Upravit Ručně Automaticky + Aktivita + Otevřít panel aktivity + Kontext + Výstupy + Úlohy na pozadí + Využito: %1$s %% + okno neznámé + Neměřeno. + Spočítal model při poslední odpovědi; kategorie jsou odhadnuté. + Odhad: žádná odpověď ještě nebyla spočítána. + Nabízené nástroje: %1$s. + Zprávy + Systémový pokyn + Paměť a osobní + Soubory s pokyny + Nástroje + Nástroje MCP + Od poslední odpovědi + Rezerva na zhuštění + Volné místo + V tomto chatu se zatím nezapsal žádný soubor. + Na pozadí nic neběží. Pomocníci, příkazy a členové týmu se tu zobrazí, dokud pracují. + Nic neběží. + 1 agent pracuje + Pracující agenti: %1$s + Ve frontě: %1$s + Čeká: %1$s + Dokončeno: %1$s + ve frontě + pracuje + čeká + hotovo + zastaveno + selhalo + Kroky: %1$s, nástroje: %2$s + Otevřít jeho konverzaci + Zastavit %1$s + Zastavit %1$s a členy pod ním? Opustí tým. + Zastavit %1$s? Co dosud udělal, zůstane. + Zatím nic neřekl. + Od systému + Tým: %1$s z %2$s agentů + Místnost + V místnosti zatím nikdo nic neřekl. + hlášení + Agenti + Nejméně + Nejvíce + Včetně vlastního agenta. Při více než jednom může přidat členy, kteří dělají práci, zatímco je vede. + Agenti %1$s–%2$s + Přemýšlet před odpovědí + Náročnost: %1$s + vypnuto + výchozí Povolit to? Povolit jednou Toto vždy povolit diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index f715e3c..ff0a019 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -55,11 +55,64 @@ Zurück Abbrechen Schließen - Aufwand: aus Plan Bearbeiten Manuell Automatisch + Aktivität + Aktivitätsbereich öffnen + Kontext + Ausgaben + Hintergrundaufgaben + %1$s %% belegt + Fenster unbekannt + Nicht gemessen. + Vom Modell bei der letzten Antwort gezählt; die Kategorien sind geschätzt. + Geschätzt: Noch keine Antwort wurde gezählt. + %1$s Werkzeuge angeboten. + Nachrichten + Systemprompt + Gedächtnis und Persönliches + Anweisungsdateien + Werkzeuge + MCP-Werkzeuge + Seit der letzten Antwort + Puffer für die Verdichtung + Freier Platz + In diesem Chat wurde noch keine Datei geschrieben. + Im Hintergrund läuft nichts. Helfer, Befehle und die Mitglieder eines Teams erscheinen hier, solange sie arbeiten. + Nichts läuft. + 1 Agent arbeitet + %1$s Agenten arbeiten + %1$s in der Warteschlange + %1$s warten + %1$s beendet + in der Warteschlange + arbeitet + wartet + fertig + angehalten + fehlgeschlagen + %1$s Schritte, %2$s Werkzeuge + Seine Unterhaltung öffnen + %1$s stoppen + %1$s und die Mitglieder darunter stoppen? Sie verlassen das Team. + %1$s stoppen? Was bisher getan wurde, bleibt. + Noch nichts gesagt. + Vom System + Team: %1$s von %2$s Agenten + Raum + Im Raum wurde noch nichts gesagt. + Bericht + Agenten + Mindestens + Höchstens + Der eigene Agent eingeschlossen. Bei mehr als einem kann er Mitglieder hinzufügen, die die Arbeit machen, während er sie leitet. + Agenten %1$s–%2$s + Vor der Antwort nachdenken + Denkaufwand: %1$s + aus + Standard Das erlauben? Einmal erlauben Dies immer erlauben diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index d4ce505..8adfe8b 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -55,11 +55,64 @@ Volver Cancelar Cerrar - Esfuerzo: desactivado Plan Editar Manual Automático + Actividad + Abrir el panel de actividad + Contexto + Resultados + Tareas en segundo plano + %1$s %% usado + ventana desconocida + Sin medir. + Contado por el modelo en la última respuesta; las categorías son estimaciones. + Estimado: aún no se ha contado ninguna respuesta. + %1$s herramientas ofrecidas. + Mensajes + Prompt de sistema + Memoria y datos personales + Archivos de instrucciones + Herramientas + Herramientas MCP + Desde la última respuesta + Reserva para la compactación + Espacio libre + Todavía no se ha escrito ningún archivo en este chat. + No hay nada en segundo plano. Los ayudantes, los comandos y los miembros de un equipo aparecen aquí mientras trabajan. + Nada en marcha. + 1 agente trabajando + %1$s agentes trabajando + %1$s en cola + %1$s esperando + %1$s terminados + en cola + trabajando + esperando + terminado + detenido + falló + %1$s pasos, %2$s herramientas + Abrir su conversación + Detener %1$s + ¿Detener %1$s y a los miembros que dependen de él? Dejan el equipo. + ¿Detener %1$s? Lo que ha hecho hasta ahora se queda. + Todavía no ha dicho nada. + Del sistema + Equipo: %1$s de %2$s agentes + Sala + Todavía no se ha dicho nada en la sala. + informe + Agentes + Mínimo + Máximo + Su propio agente incluido. Con más de uno, puede añadir miembros que hagan el trabajo mientras los dirige. + Agentes %1$s–%2$s + Razonar antes de responder + Esfuerzo: %1$s + desactivado + predeterminado ¿Permitir esto? Permitir una vez Permitir siempre esto diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 803a626..88211b1 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -55,11 +55,64 @@ Retour Annuler Fermer - Effort : désactivé Plan Modifier Manuel Automatique + Activité + Ouvrir le panneau d’activité + Contexte + Sorties + Tâches en arrière-plan + %1$s %% utilisés + fenêtre inconnue + Non mesuré. + Compté par le modèle lors de la dernière réponse ; les catégories sont estimées. + Estimation : aucune réponse n’a encore été comptée. + %1$s outils proposés. + Messages + Prompt système + Mémoire et informations personnelles + Fichiers d’instructions + Outils + Outils MCP + Depuis la dernière réponse + Réserve de compactage + Espace libre + Aucun fichier n’a encore été écrit dans cette conversation. + Rien ne tourne en arrière-plan. Les assistants, les commandes et les membres d’une équipe s’affichent ici pendant qu’ils travaillent. + Rien en cours. + 1 agent au travail + %1$s agents au travail + %1$s en file d’attente + %1$s en attente + %1$s terminés + en file d’attente + au travail + en attente + terminé + arrêté + échoué + %1$s étapes, %2$s outils + Ouvrir sa conversation + Arrêter %1$s + Arrêter %1$s et les membres qui en dépendent ? Ils quittent l’équipe. + Arrêter %1$s ? Ce qu’il a déjà fait reste. + Rien de dit pour l’instant. + Du système + Équipe : %1$s agents sur %2$s + Salle + Rien n’a encore été dit dans la salle. + rapport + Agents + Au moins + Au plus + Son propre agent compris. Au-delà d’un, il peut ajouter des membres qui font le travail pendant qu’il les dirige. + Agents %1$s–%2$s + Réfléchir avant de répondre + Effort : %1$s + désactivé + par défaut Autoriser ceci ? Autoriser une fois Toujours autoriser ceci diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 59f2830..79f56c8 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -55,11 +55,64 @@ Vissza Mégse Bezárás - Erőfeszítés: kikapcsolva Terv Szerkesztés Kézi Automatikus + Tevékenység + A tevékenységpanel megnyitása + Kontextus + Kimenetek + Háttérfeladatok + %1$s%% foglalt + az ablak ismeretlen + Nincs mérve. + A modell számolta az utolsó válasznál; a kategóriák becslések. + Becslés: még egy válasz sem lett megszámolva. + %1$s eszköz felkínálva. + Üzenetek + Rendszerprompt + Memória és személyes adatok + Utasításfájlok + Eszközök + MCP-eszközök + Az utolsó válasz óta + Tömörítési tartalék + Szabad hely + Ebben a csevegésben még nem íródott fájl. + A háttérben semmi sem fut. A segítők, a parancsok és egy csapat tagjai itt jelennek meg, amíg dolgoznak. + Semmi sem fut. + 1 ügynök dolgozik + %1$s ügynök dolgozik + %1$s sorban áll + %1$s várakozik + %1$s befejezve + sorban áll + dolgozik + várakozik + kész + leállítva + sikertelen + %1$s lépés, %2$s eszköz + A beszélgetésének megnyitása + %1$s leállítása + Leállítja %1$s tagot és az alatta lévőket? Kilépnek a csapatból. + Leállítja: %1$s? Amit eddig elvégzett, megmarad. + Még nem mondott semmit. + A rendszertől + Csapat: %1$s / %2$s ügynök + Szoba + A szobában még senki nem mondott semmit. + jelentés + Ügynökök + Legalább + Legfeljebb + A saját ügynökét is beleértve. Egynél több esetén tagokat vehet fel, akik elvégzik a munkát, amíg ő vezeti őket. + Ügynökök: %1$s–%2$s + Gondolkodjon válasz előtt + Erőfeszítés: %1$s + ki + alapértelmezett Engedélyezzük ezt? Engedélyezés egyszer Ennek mindig engedélyezése diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index c2f22bb..c59b6bf 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -55,11 +55,64 @@ Indietro Annulla Chiudi - Impegno: disattivato Piano Modifica Manuale Automatico + Attività + Apri il pannello attività + Contesto + Risultati + Attività in background + %1$s%% usato + finestra sconosciuta + Non misurato. + Contato dal modello all’ultima risposta; le categorie sono stime. + Stima: nessuna risposta è stata ancora contata. + %1$s strumenti offerti. + Messaggi + Prompt di sistema + Memoria e dati personali + File di istruzioni + Strumenti + Strumenti MCP + Dall’ultima risposta + Riserva per la compattazione + Spazio libero + In questa chat non è ancora stato scritto alcun file. + Nulla è in esecuzione in background. Aiutanti, comandi e membri di una squadra compaiono qui mentre lavorano. + Nulla in esecuzione. + 1 agente al lavoro + %1$s agenti al lavoro + %1$s in coda + %1$s in attesa + %1$s terminati + in coda + al lavoro + in attesa + finito + interrotto + fallito + %1$s passi, %2$s strumenti + Apri la sua conversazione + Ferma %1$s + Fermare %1$s e i membri sotto di lui? Lasciano la squadra. + Fermare %1$s? Ciò che ha fatto finora resta. + Non ha ancora detto nulla. + Dal sistema + Squadra: %1$s di %2$s agenti + Stanza + Nella stanza non è ancora stato detto nulla. + resoconto + Agenti + Minimo + Massimo + Il proprio agente compreso. Con più di uno, può aggiungere membri che fanno il lavoro mentre li guida. + Agenti %1$s–%2$s + Ragiona prima di rispondere + Sforzo: %1$s + disattivato + predefinito Consentire questo? Consenti una volta Consenti sempre questo diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 650ae7a..c479eb3 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -55,11 +55,64 @@ Wstecz Anuluj Zamknij - Wysiłek: wyłączony Plan Edytuj Ręcznie Automatycznie + Aktywność + Otwórz panel aktywności + Kontekst + Wyniki + Zadania w tle + Użyto: %1$s%% + okno nieznane + Nie zmierzono. + Policzone przez model przy ostatniej odpowiedzi; kategorie są szacunkowe. + Szacunek: żadna odpowiedź nie została jeszcze policzona. + Oferowane narzędzia: %1$s. + Wiadomości + Prompt systemowy + Pamięć i dane osobiste + Pliki z instrukcjami + Narzędzia + Narzędzia MCP + Od ostatniej odpowiedzi + Rezerwa na kompakcję + Wolne miejsce + W tym czacie nie zapisano jeszcze żadnego pliku. + W tle nic nie działa. Pomocnicy, polecenia i członkowie zespołu pojawiają się tu, gdy pracują. + Nic nie działa. + 1 agent pracuje + Pracujący agenci: %1$s + W kolejce: %1$s + Czeka: %1$s + Zakończone: %1$s + w kolejce + pracuje + czeka + gotowe + zatrzymane + nie powiodło się + Kroki: %1$s, narzędzia: %2$s + Otwórz jego rozmowę + Zatrzymaj %1$s + Zatrzymać %1$s i członków pod nim? Opuszczą zespół. + Zatrzymać %1$s? To, co już zrobił, zostaje. + Jeszcze nic nie powiedział. + Od systemu + Zespół: %1$s z %2$s agentów + Pokój + W pokoju nikt jeszcze nic nie powiedział. + raport + Agenci + Najmniej + Najwięcej + Wliczając własnego agenta. Przy więcej niż jednym może dodać członków, którzy wykonują pracę, gdy on nimi kieruje. + Agenci %1$s–%2$s + Rozumuj przed odpowiedzią + Rozumowanie: %1$s + wył. + domyślna Zezwolić na to? Zezwól raz Zawsze na to zezwalaj diff --git a/app/src/main/res/values-sk/strings.xml b/app/src/main/res/values-sk/strings.xml index 6d66826..05dd49f 100644 --- a/app/src/main/res/values-sk/strings.xml +++ b/app/src/main/res/values-sk/strings.xml @@ -55,11 +55,64 @@ Späť Zrušiť Zavrieť - Úsilie: vypnuté Plán Upraviť Ručne Automaticky + Aktivita + Otvoriť panel aktivity + Kontext + Výstupy + Úlohy na pozadí + Využité: %1$s %% + okno neznáme + Nezmerané. + Spočítal model pri poslednej odpovedi; kategórie sú odhadnuté. + Odhad: žiadna odpoveď ešte nebola spočítaná. + Ponúknuté nástroje: %1$s. + Správy + Systémový pokyn + Pamäť a osobné + Súbory s pokynmi + Nástroje + Nástroje MCP + Od poslednej odpovede + Rezerva na zhustenie + Voľné miesto + V tomto chate sa zatiaľ nezapísal žiadny súbor. + Na pozadí nič nebeží. Pomocníci, príkazy a členovia tímu sa tu zobrazia, kým pracujú. + Nič nebeží. + 1 agent pracuje + Pracujúci agenti: %1$s + V rade: %1$s + Čaká: %1$s + Dokončené: %1$s + v rade + pracuje + čaká + hotovo + zastavené + zlyhalo + Kroky: %1$s, nástroje: %2$s + Otvoriť jeho konverzáciu + Zastaviť %1$s + Zastaviť %1$s a členov pod ním? Opustia tím. + Zastaviť %1$s? Čo doteraz urobil, zostane. + Zatiaľ nič nepovedal. + Od systému + Tím: %1$s z %2$s agentov + Miestnosť + V miestnosti zatiaľ nikto nič nepovedal. + hlásenie + Agenti + Najmenej + Najviac + Vrátane vlastného agenta. Pri viac ako jednom môže pridať členov, ktorí robia prácu, kým ich vedie. + Agenti %1$s–%2$s + Premýšľať pred odpoveďou + Náročnosť: %1$s + vypnuté + predvolené Povoliť to? Povoliť raz Toto vždy povoliť diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index c2c4dc2..00426e2 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -56,11 +56,64 @@ Back Cancel Close - Effort: off Plan Edit Manual Auto + Activity + Open the activity panel + Context + Outputs + Background tasks + %1$s%% used + window unknown + Not measured. + Counted by the model at the last reply; the categories are estimated. + Estimated: no reply has been counted yet. + %1$s tools offered. + Messages + System prompt + Memory and personal + Instruction files + Tools + MCP tools + Since the last reply + Compaction buffer + Free space + No files written in this chat yet. + Nothing runs in the background. Helpers, commands and a team\'s members show here while they work. + Nothing running. + 1 agent working + %1$s agents working + %1$s queued + %1$s waiting + %1$s finished + queued + working + waiting + done + stopped + failed + %1$s steps, %2$s tools + Open its conversation + Stop %1$s + Stop %1$s and the members under it? They leave the team. + Stop %1$s? What it has done so far stays. + Nothing said yet. + From the system + Team: %1$s of %2$s agents + Room + Nothing has been said in the room yet. + report + Agents + Fewest + Most + Its own agent included. Above one, it can add members that do the work while it leads them. + Agents %1$s–%2$s + Think before answering + Effort: %1$s + off + default Allow this? Allow once Always allow this diff --git a/scripts/gen-strings.py b/scripts/gen-strings.py index 5bf705d..eb86f45 100755 --- a/scripts/gen-strings.py +++ b/scripts/gen-strings.py @@ -31,7 +31,7 @@ LANGS = ("cs", "de", "es", "fr", "hu", "it", "pl", "sk") HEADER = "" sys.path.insert(0, str(Path(__file__).parent)) -from strings import STRINGS # noqa: E402 +from strings import SERVER_ENGLISH, STRINGS # noqa: E402 def android(text: str) -> str: @@ -60,6 +60,31 @@ def server_catalogue(code: str, ref: str | None = None) -> dict[str, str]: return dict(getattr(module, "MESSAGES", {})) +def numbered(server_english: str, translation: str) -> str: + """A server translation with its named placeholders (`%(n)s`) numbered as Android's + (`%1$s`), in the order the server's English names them. `%%` stays as it is: both write a + percent sign that way.""" + names: list[str] = [] + for name in re.findall(r"%\((\w+)\)s", server_english): + if name not in names: + names.append(name) + for i, name in enumerate(names, start=1): + translation = translation.replace(f"%({name})s", f"%{i}$s") + return translation + + +def server_text(catalogue: dict[str, str], key: str, english: str) -> str | None: + """The server's translation of a sentence: by the app's English, or by the server's own + English for it (`SERVER_ENGLISH`), placeholders numbered.""" + if english in catalogue: + return catalogue[english] + source = SERVER_ENGLISH.get(key) + if source and source in catalogue: + text = numbered(source, catalogue[source]) + return None if "%(" in text else text + return None + + def used_keys() -> set[str]: keys: set[str] = set() for path in (ROOT / "app/src").rglob("*"): @@ -105,8 +130,8 @@ def main() -> None: for key, english in STRINGS.items(): if key == "app_name": continue - text = mine.get(key) or catalogue.get(english) - if text and text.count("%1$s") == english.count("%1$s"): + text = mine.get(key) or server_text(catalogue, key, english) + if text and all(text.count(f"%{i}$s") == english.count(f"%{i}$s") for i in (1, 2, 3)): out[key] = text write(RES / f"values-{code}", out) print(f"gen-strings: {code}: {len(out)}/{len(STRINGS) - 1}" + (f" (server {ref[:12]})" if ref else "")) diff --git a/scripts/strings.py b/scripts/strings.py index e011c78..3072b4b 100755 --- a/scripts/strings.py +++ b/scripts/strings.py @@ -68,11 +68,65 @@ STRINGS: dict[str, str] = { "back": "Back", "cancel": "Cancel", "close": "Close", - "effort_off": "Effort: off", "mode_plan": "Plan", "mode_edit": "Edit", "mode_manual": "Manual", "mode_auto": "Auto", + # The activity panel, the team and the level control (server 2.0 beta.5) + "activity": "Activity", + "activity_open": "Open the activity panel", + "activity_context": "Context", + "activity_outputs": "Outputs", + "activity_tasks": "Background tasks", + "activity_used": "%1$s%% used", + "activity_window_unknown": "window unknown", + "activity_not_measured": "Not measured.", + "activity_measured": "Counted by the model at the last reply; the categories are estimated.", + "activity_estimated": "Estimated: no reply has been counted yet.", + "activity_tools_offered": "%1$s tools offered.", + "ctx_messages": "Messages", + "ctx_system": "System prompt", + "ctx_memory": "Memory and personal", + "ctx_instructions": "Instruction files", + "ctx_tools": "Tools", + "ctx_mcp_tools": "MCP tools", + "ctx_since": "Since the last reply", + "ctx_buffer": "Compaction buffer", + "ctx_free": "Free space", + "outputs_empty": "No files written in this chat yet.", + "tasks_empty": "Nothing runs in the background. Helpers, commands and a team's members show here while they work.", + "tasks_none_running": "Nothing running.", + "agents_one_working": "1 agent working", + "agents_n_working": "%1$s agents working", + "agents_n_queued": "%1$s queued", + "agents_n_waiting": "%1$s waiting", + "agents_n_finished": "%1$s finished", + "agent_state_queued": "queued", + "agent_state_working": "working", + "agent_state_waiting": "waiting", + "agent_state_done": "done", + "agent_state_stopped": "stopped", + "agent_state_error": "failed", + "agent_steps": "%1$s steps, %2$s tools", + "agent_open_conversation": "Open its conversation", + "agent_stop": "Stop %1$s", + "agent_stop_member_confirm": "Stop %1$s and the members under it? They leave the team.", + "agent_stop_confirm": "Stop %1$s? What it has done so far stays.", + "agent_nothing_yet": "Nothing said yet.", + "agent_machine": "From the system", + "team_size": "Team: %1$s of %2$s agents", + "team_room": "Room", + "room_empty": "Nothing has been said in the room yet.", + "room_report": "report", + "team_agents": "Agents", + "team_fewest": "Fewest", + "team_most": "Most", + "team_hint": "Its own agent included. Above one, it can add members that do the work while it leads them.", + "team_chip": "Agents %1$s–%2$s", + "thinking_switch": "Think before answering", + "effort_level": "Effort: %1$s", + "level_off": "off", + "level_default": "default", # Cards "card_approval": "Allow this?", "card_allow_once": "Allow once", @@ -142,3 +196,21 @@ STRINGS: dict[str, str] = { "share_sending": "Sending to LLeMbas…", "share_default_prompt": "Have a look at this.", } + + +# The server's own English for a sentence with placeholders, where it differs from the app's +# only in how the placeholders are written (`%(n)s` there, `%1$s` here). Its translation is +# taken from the server's catalogue and its named placeholders numbered in the order the +# English names them -- so "%(steps)s steps, %(tools)s tools" becomes `%1$s`, `%2$s`. +SERVER_ENGLISH: dict[str, str] = { + "activity_used": "%(percent)s%% used", + "activity_tools_offered": "%(n)s tools offered.", + "agents_n_working": "%(n)s agents working", + "agents_n_queued": "%(n)s queued", + "agents_n_waiting": "%(n)s waiting", + "agents_n_finished": "%(n)s finished", + "agent_steps": "%(steps)s steps, %(tools)s tools", + "agent_stop": "Stop %(name)s", + "agent_stop_member_confirm": "Stop %(name)s and the members under it? They leave the team.", + "team_size": "Team: %(size)s of %(max)s agents", +} diff --git a/scripts/strings_own.json b/scripts/strings_own.json index df12da5..938a1ed 100644 --- a/scripts/strings_own.json +++ b/scripts/strings_own.json @@ -4,7 +4,10 @@ "add_instance": "Přidat instanci", "agent_directory": "Složka na zařízení", "agent_directory_hint": "Prázdné: první složka zařízení", + "agent_machine": "Od systému", "agent_no_device": "Právě není propojené žádné zařízení. Spusťte `lembas service` na počítači přihlášeném k této instanci a vraťte se.", + "agent_nothing_yet": "Zatím nic neřekl.", + "agent_stop_confirm": "Zastavit %1$s? Co dosud udělal, zůstane.", "archive": "Archivovat", "assist_hint": "Zeptejte se na cokoli", "assist_include_screen": "Zahrnout obrazovku", @@ -26,7 +29,7 @@ "card_reason": "Proč ne? (nepovinné)", "channel_asks": "Otázky a schválení", "device_name": "LLeMbas pro Android", - "effort_off": "Úsilí: vypnuto", + "effort_level": "Náročnost: %1$s", "empty_agents": "Zatím žádné konverzace s agentem. Spusťte jednu tlačítkem Nová konverzace s agentem na zařízení propojeném s touto instancí.", "empty_chat": "O čem si promluvíme?", "empty_chats": "Zatím žádné konverzace. Ne všichni, kdo bloudí, jsou ztraceni — založte jednu.", @@ -62,6 +65,7 @@ "signin_open_browser": "Otevřít v prohlížeči", "signin_too_new": "Tato instance používá novější rozhraní API pro aplikace než tato aplikace. Aktualizujte aplikaci.", "signin_too_old": "Tato instance používá starší LLeMbas. Tato aplikace potřebuje LLeMbas 2.0 nebo novější.", + "team_chip": "Agenti %1$s–%2$s", "theme_moria": "Moria (temná)", "theme_shire": "Shire (světlý)", "theme_system": "Podle systému", @@ -83,7 +87,10 @@ "add_instance": "Instanz hinzufügen", "agent_directory": "Ordner auf dem Gerät", "agent_directory_hint": "Leer: der erste Ordner des Geräts", + "agent_machine": "Vom System", "agent_no_device": "Gerade ist kein Gerät verknüpft. Starten Sie `lembas service` auf einem Computer, der bei dieser Instanz angemeldet ist, und kommen Sie dann zurück.", + "agent_nothing_yet": "Noch nichts gesagt.", + "agent_stop_confirm": "%1$s stoppen? Was bisher getan wurde, bleibt.", "archive": "Archivieren", "assist_hint": "Fragen Sie irgendetwas", "assist_include_screen": "Bildschirm einbeziehen", @@ -105,7 +112,7 @@ "card_reason": "Warum nicht? (optional)", "channel_asks": "Fragen und Bestätigungen", "device_name": "LLeMbas für Android", - "effort_off": "Aufwand: aus", + "effort_level": "Denkaufwand: %1$s", "empty_agents": "Noch keine Agent-Chats. Starten Sie einen mit „Neuer Agent-Chat“ auf einem Gerät, das mit dieser Instanz verknüpft ist.", "empty_chat": "Worüber sprechen wir?", "empty_chats": "Noch keine Chats. Nicht jeder, der wandert, ist verloren — fangen Sie einen an.", @@ -142,6 +149,7 @@ "signin_open_browser": "Im Browser öffnen", "signin_too_new": "Diese Instanz spricht eine neuere App-API als diese App. Aktualisieren Sie die App.", "signin_too_old": "Auf dieser Instanz läuft ein älteres LLeMbas. Diese App braucht LLeMbas 2.0 oder neuer.", + "team_chip": "Agenten %1$s–%2$s", "theme_moria": "Moria (dunkel)", "theme_shire": "Shire (hell)", "theme_system": "Wie das System", @@ -163,7 +171,10 @@ "add_instance": "Añadir una instancia", "agent_directory": "Carpeta en el dispositivo", "agent_directory_hint": "Vacío: la primera carpeta del dispositivo", + "agent_machine": "Del sistema", "agent_no_device": "Ahora no hay ningún dispositivo vinculado. Inicie `lembas service` en un ordenador con sesión iniciada en esta instancia y vuelva.", + "agent_nothing_yet": "Todavía no ha dicho nada.", + "agent_stop_confirm": "¿Detener %1$s? Lo que ha hecho hasta ahora se queda.", "archive": "Archivar", "assist_hint": "Pregunte lo que quiera", "assist_include_screen": "Incluir pantalla", @@ -185,7 +196,7 @@ "card_reason": "¿Por qué no? (opcional)", "channel_asks": "Preguntas y aprobaciones", "device_name": "LLeMbas para Android", - "effort_off": "Esfuerzo: desactivado", + "effort_level": "Esfuerzo: %1$s", "empty_agents": "Aún no hay chats de agente. Inicie uno con Nuevo chat de agente, en un dispositivo vinculado a esta instancia.", "empty_chat": "¿De qué hablamos?", "empty_chats": "Aún no hay chats. No todos los que vagan están perdidos — empiece uno.", @@ -221,6 +232,7 @@ "signin_open_browser": "Abrir en el navegador", "signin_too_new": "Esta instancia habla una API de aplicaciones más reciente que esta aplicación. Actualice la aplicación.", "signin_too_old": "Esta instancia usa una versión anterior de LLeMbas. Esta aplicación necesita LLeMbas 2.0 o posterior.", + "team_chip": "Agentes %1$s–%2$s", "theme_moria": "Moria (oscuro)", "theme_shire": "Shire (claro)", "theme_system": "Como el sistema", @@ -242,7 +254,10 @@ "add_instance": "Ajouter une instance", "agent_directory": "Dossier sur l'appareil", "agent_directory_hint": "Vide : le premier dossier de l'appareil", + "agent_machine": "Du système", "agent_no_device": "Aucun appareil n'est associé pour l'instant. Lancez `lembas service` sur un ordinateur connecté à cette instance, puis revenez.", + "agent_nothing_yet": "Rien de dit pour l’instant.", + "agent_stop_confirm": "Arrêter %1$s ? Ce qu’il a déjà fait reste.", "archive": "Archiver", "assist_hint": "Demandez n'importe quoi", "assist_include_screen": "Inclure l'écran", @@ -264,7 +279,7 @@ "card_reason": "Pourquoi pas ? (facultatif)", "channel_asks": "Questions et approbations", "device_name": "LLeMbas pour Android", - "effort_off": "Effort : désactivé", + "effort_level": "Effort : %1$s", "empty_agents": "Pas encore de conversation d'agent. Démarrez-en une avec Nouvelle conversation d'agent, sur un appareil associé à cette instance.", "empty_chat": "De quoi allons-nous parler ?", "empty_chats": "Pas encore de conversation. Tous ceux qui errent ne sont pas perdus — commencez-en une.", @@ -301,6 +316,7 @@ "signin_open_browser": "Ouvrir dans le navigateur", "signin_too_new": "Cette instance utilise une API d'application plus récente que cette application. Mettez à jour l'application.", "signin_too_old": "Cette instance utilise une version plus ancienne de LLeMbas. Cette application nécessite LLeMbas 2.0 ou plus récent.", + "team_chip": "Agents %1$s–%2$s", "theme_moria": "Moria (sombre)", "theme_shire": "Shire (clair)", "theme_system": "Comme le système", @@ -322,7 +338,10 @@ "add_instance": "Példány hozzáadása", "agent_directory": "Mappa az eszközön", "agent_directory_hint": "Üres: az eszköz első mappája", + "agent_machine": "A rendszertől", "agent_no_device": "Jelenleg nincs összekapcsolt eszköz. Indítsa el a `lembas service` parancsot egy ebbe a példányba bejelentkezett számítógépen, majd térjen vissza.", + "agent_nothing_yet": "Még nem mondott semmit.", + "agent_stop_confirm": "Leállítja: %1$s? Amit eddig elvégzett, megmarad.", "archive": "Archiválás", "assist_hint": "Kérdezzen bármit", "assist_include_screen": "Képernyő hozzáadása", @@ -344,7 +363,7 @@ "card_reason": "Miért nem? (opcionális)", "channel_asks": "Kérdések és jóváhagyások", "device_name": "LLeMbas Androidra", - "effort_off": "Erőfeszítés: kikapcsolva", + "effort_level": "Erőfeszítés: %1$s", "empty_agents": "Még nincs ügynök-csevegés. Indítson egyet az Új ügynök-csevegés gombbal, egy ehhez a példányhoz kapcsolt eszközön.", "empty_chat": "Miről beszéljünk?", "empty_chats": "Még nincs csevegés. Nem mindenki van elveszve, aki bolyong — kezdjen el egyet.", @@ -381,6 +400,7 @@ "signin_open_browser": "Megnyitás a böngészőben", "signin_too_new": "Ez a példány újabb alkalmazás-API-t használ, mint ez az alkalmazás. Frissítse az alkalmazást.", "signin_too_old": "Ezen a példányon régebbi LLeMbas fut. Ehhez az alkalmazáshoz LLeMbas 2.0 vagy újabb kell.", + "team_chip": "Ügynökök: %1$s–%2$s", "theme_moria": "Moria (sötét)", "theme_shire": "Shire (világos)", "theme_system": "A rendszer szerint", @@ -402,7 +422,10 @@ "add_instance": "Aggiungi un'istanza", "agent_directory": "Cartella sul dispositivo", "agent_directory_hint": "Vuoto: la prima cartella del dispositivo", + "agent_machine": "Dal sistema", "agent_no_device": "Nessun dispositivo è collegato ora. Avvia `lembas service` su un computer connesso a questa istanza, poi torna qui.", + "agent_nothing_yet": "Non ha ancora detto nulla.", + "agent_stop_confirm": "Fermare %1$s? Ciò che ha fatto finora resta.", "archive": "Archivia", "assist_hint": "Chiedi qualsiasi cosa", "assist_include_screen": "Includi lo schermo", @@ -424,7 +447,7 @@ "card_reason": "Perché no? (facoltativo)", "channel_asks": "Domande e approvazioni", "device_name": "LLeMbas per Android", - "effort_off": "Impegno: disattivato", + "effort_level": "Sforzo: %1$s", "empty_agents": "Ancora nessuna chat agente. Avviane una con Nuova chat agente, su un dispositivo collegato a questa istanza.", "empty_chat": "Di cosa parliamo?", "empty_chats": "Ancora nessuna chat. Non tutti quelli che vagano sono perduti — iniziane una.", @@ -460,6 +483,7 @@ "signin_open_browser": "Apri nel browser", "signin_too_new": "Questa istanza usa un'API per l'app più recente di questa app. Aggiorna l'app.", "signin_too_old": "Questa istanza usa una versione precedente di LLeMbas. Questa app richiede LLeMbas 2.0 o successivo.", + "team_chip": "Agenti %1$s–%2$s", "theme_moria": "Moria (scuro)", "theme_shire": "Shire (chiaro)", "theme_system": "Come il sistema", @@ -481,7 +505,10 @@ "add_instance": "Dodaj instancję", "agent_directory": "Folder na urządzeniu", "agent_directory_hint": "Puste: pierwszy folder urządzenia", + "agent_machine": "Od systemu", "agent_no_device": "Żadne urządzenie nie jest teraz połączone. Uruchom `lembas service` na komputerze zalogowanym do tej instancji i wróć.", + "agent_nothing_yet": "Jeszcze nic nie powiedział.", + "agent_stop_confirm": "Zatrzymać %1$s? To, co już zrobił, zostaje.", "archive": "Archiwizuj", "assist_hint": "Zapytaj o cokolwiek", "assist_include_screen": "Dołącz ekran", @@ -503,7 +530,7 @@ "card_reason": "Czemu nie? (opcjonalnie)", "channel_asks": "Pytania i zatwierdzenia", "device_name": "LLeMbas na Androida", - "effort_off": "Wysiłek: wyłączony", + "effort_level": "Rozumowanie: %1$s", "empty_agents": "Brak czatów agenta. Zacznij jeden przyciskiem Nowy czat agenta, na urządzeniu połączonym z tą instancją.", "empty_chat": "O czym porozmawiamy?", "empty_chats": "Nie ma jeszcze czatów. Nie każdy, kto błądzi, jest zgubiony — zacznij jeden.", @@ -539,6 +566,7 @@ "signin_open_browser": "Otwórz w przeglądarce", "signin_too_new": "Ta instancja używa nowszego API aplikacji niż ta aplikacja. Zaktualizuj aplikację.", "signin_too_old": "Ta instancja działa na starszym LLeMbas. Ta aplikacja wymaga LLeMbas 2.0 lub nowszego.", + "team_chip": "Agenci %1$s–%2$s", "theme_moria": "Moria (ciemny)", "theme_shire": "Shire (jasny)", "theme_system": "Jak system", @@ -560,7 +588,10 @@ "add_instance": "Pridať inštanciu", "agent_directory": "Zložka v zariadení", "agent_directory_hint": "Prázdne: prvá zložka zariadenia", + "agent_machine": "Od systému", "agent_no_device": "Práve nie je prepojené žiadne zariadenie. Spustite `lembas service` na počítači prihlásenom do tejto inštancie a vráťte sa.", + "agent_nothing_yet": "Zatiaľ nič nepovedal.", + "agent_stop_confirm": "Zastaviť %1$s? Čo doteraz urobil, zostane.", "archive": "Archivovať", "assist_hint": "Spýtajte sa na čokoľvek", "assist_include_screen": "Zahrnúť obrazovku", @@ -582,7 +613,7 @@ "card_reason": "Prečo nie? (nepovinné)", "channel_asks": "Otázky a schválenia", "device_name": "LLeMbas pre Android", - "effort_off": "Úsilie: vypnuté", + "effort_level": "Náročnosť: %1$s", "empty_agents": "Zatiaľ žiadne konverzácie s agentom. Spustite jednu tlačidlom Nová konverzácia s agentom na zariadení prepojenom s touto inštanciou.", "empty_chat": "O čom sa pozhovárame?", "empty_chats": "Zatiaľ žiadne konverzácie. Nie všetci, čo blúdia, sú stratení — začnite jednu.", @@ -618,6 +649,7 @@ "signin_open_browser": "Otvoriť v prehliadači", "signin_too_new": "Táto inštancia používa novšie API pre aplikácie než táto aplikácia. Aktualizujte aplikáciu.", "signin_too_old": "Táto inštancia beží na staršom LLeMbas. Táto aplikácia potrebuje LLeMbas 2.0 alebo novší.", + "team_chip": "Agenti %1$s–%2$s", "theme_moria": "Moria (tmavá)", "theme_shire": "Shire (svetlá)", "theme_system": "Podľa systému",