From 0e8897b7da23e8d3e610a9203d4808859a6b4b65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Bene=C5=A1?= Date: Mon, 9 Nov 2026 12:55:09 +0000 Subject: [PATCH] A chat app's shape: new chat first, chats in a drawer, Scheduled The app opens on a new chat (greeting, suggestions, composer) instead of a list. The model is the top bar's title (picture, name, caret) and opens a bottom-sheet picker with pictures, what each model can do and its levels. Chats live in a navigation drawer: search, New chat, New agent chat, Files, Scheduled, then Today / Earlier / Agent chats, Settings with the account at the foot. The transcript: the person's words in a bubble on the right, the model's full width without one; thinking and each round of tools fold into chips that open; fenced code becomes its own block with the language and Copy; attached pictures are thumbnails; a breathing dot while a reply is written; Copy and Regenerate under a reply, and a long-press menu (Copy, Select text, Edit, Regenerate). The composer is one rounded field: attach (+), an Options button that opens the tune sheet (Thinking switch or effort levels, team size, Plan first or the agent's mode, and a new agent chat's device and folder: only what the model offers), the microphone, and Send that becomes Stop. Settings are Material 3 grouped lists. Scheduled (phone first): the list (next run, last status, pause switch), a schedule's page (rule, Run now, Pause, next runs, history with model and Open), and create/edit in words with a preview before saving. Notification channels Scheduled results and Scheduled failures, private on the lock screen with a public version, actions Open and Pause. The /api/v2 routes are provisional (api/Schedules.kt) until the server's contract lands. Screens take their state as data (ChatContent, DrawerContent, SettingsContent, Scheduled*Content), so the screenshot tests draw every one with fake data. 60 strings, in all eight languages. Unit tests for the fence splitter, the drawer's grouping, the chat state the controls read, and schedule times. Co-Authored-By: Claude Opus 5.5 --- app/src/main/AndroidManifest.xml | 5 + .../main/java/eu/llembas/android/LembasApp.kt | 6 +- .../java/eu/llembas/android/MainActivity.kt | 196 ++-- .../java/eu/llembas/android/api/ApiClient.kt | 35 + .../java/eu/llembas/android/api/Models.kt | 3 + .../java/eu/llembas/android/api/Schedules.kt | 85 ++ .../main/java/eu/llembas/android/push/Push.kt | 86 +- .../java/eu/llembas/android/ui/Markdown.kt | 22 +- .../eu/llembas/android/ui/MarkdownSplit.kt | 59 ++ .../java/eu/llembas/android/ui/chat/Blocks.kt | 96 +- .../eu/llembas/android/ui/chat/ChatScreen.kt | 864 ++++++------------ .../llembas/android/ui/chat/ChatViewModel.kt | 129 ++- .../eu/llembas/android/ui/chat/Composer.kt | 579 ++++++++++++ .../eu/llembas/android/ui/chat/ModelPicker.kt | 136 +++ .../eu/llembas/android/ui/chat/Transcript.kt | 556 +++++++++++ .../llembas/android/ui/chats/ChatsScreen.kt | 264 ------ .../eu/llembas/android/ui/home/ChatGroups.kt | 31 + .../java/eu/llembas/android/ui/home/Drawer.kt | 311 +++++++ .../android/ui/scheduled/ScheduleLogic.kt | 33 + .../android/ui/scheduled/ScheduledScreens.kt | 731 +++++++++++++++ .../android/ui/settings/SettingsScreen.kt | 406 ++++++-- app/src/main/res/values-cs/strings.xml | 78 +- app/src/main/res/values-de/strings.xml | 78 +- app/src/main/res/values-es/strings.xml | 78 +- app/src/main/res/values-fr/strings.xml | 78 +- app/src/main/res/values-hu/strings.xml | 78 +- app/src/main/res/values-it/strings.xml | 78 +- app/src/main/res/values-pl/strings.xml | 78 +- app/src/main/res/values-sk/strings.xml | 78 +- app/src/main/res/values/strings.xml | 78 +- .../java/eu/llembas/android/ChatGroupsTest.kt | 44 + .../java/eu/llembas/android/ChatStateTest.kt | 69 ++ .../eu/llembas/android/MarkdownSplitTest.kt | 50 + .../eu/llembas/android/ScheduleLogicTest.kt | 45 + .../java/eu/llembas/android/shots/Fakes.kt | 206 +++++ .../eu/llembas/android/shots/ScreenShots.kt | 131 ++- scripts/strings.py | 80 +- scripts/strings_own.json | 504 +++++++++- 38 files changed, 5282 insertions(+), 1182 deletions(-) create mode 100644 app/src/main/java/eu/llembas/android/api/Schedules.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/MarkdownSplit.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/chat/Composer.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/chat/ModelPicker.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/chat/Transcript.kt delete mode 100644 app/src/main/java/eu/llembas/android/ui/chats/ChatsScreen.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/home/ChatGroups.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/home/Drawer.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/scheduled/ScheduleLogic.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/scheduled/ScheduledScreens.kt create mode 100644 app/src/test/java/eu/llembas/android/ChatGroupsTest.kt create mode 100644 app/src/test/java/eu/llembas/android/ChatStateTest.kt create mode 100644 app/src/test/java/eu/llembas/android/MarkdownSplitTest.kt create mode 100644 app/src/test/java/eu/llembas/android/ScheduleLogicTest.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 39efdc5..a36b2d5 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -124,6 +124,11 @@ android:name=".push.CardActionReceiver" android:exported="false" /> + + + (null) + /** A chat or a schedule a notification, the assistant or a share asked to open; consumed once. */ + private val opening = mutableStateOf(null) override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge() @@ -63,67 +80,142 @@ class MainActivity : ComponentActivity() { } private fun take(intent: Intent?) { - intent?.getStringExtra(Notifications.EXTRA_CHAT)?.let { opening.value = it } + val chat = intent?.getStringExtra(Notifications.EXTRA_CHAT) + val schedule = intent?.getStringExtra(Notifications.EXTRA_SCHEDULE) + if (chat != null || schedule != null) opening.value = Opening(chat, schedule) } @Composable - private fun Root(open: String?, opened: () -> Unit) { + private fun Root(open: Opening?, opened: () -> Unit) { // null while the store is read; then the instance in use, which may be none. val loaded by remember { lembas.instances.active.map { Loaded(it) } }.collectAsState(initial = null) val instance = loaded?.instance when { loaded == null -> Box(Modifier.fillMaxSize()) - instance == null -> SignInScreen() + else -> key(instance.id) { Home(instance, open, opened) } + } + } - else -> key(instance.id) { - val nav = rememberNavController() - LaunchedEffect(open) { - open?.let { - nav.navigate("chat/$it") - opened() - } + /** + * The signed-in app: a new chat first, as the AI apps open, with every chat, Files, + * Scheduled and Settings in the navigation drawer. A chat or a new chat is a top-level + * page (opening one replaces the last; Back leaves the app); Files, Scheduled and + * Settings open over it and Back returns. + */ + @Composable + private fun Home(instance: Instance, open: Opening?, opened: () -> Unit) { + val nav = rememberNavController() + val drawer = rememberDrawerState(DrawerValue.Closed) + val scope = rememberCoroutineScope() + val chats: ChatsViewModel = viewModel() + val list by chats.state.collectAsStateWithLifecycle() + val entry by nav.currentBackStackEntryAsState() + val route = entry?.destination?.route + val current = entry?.arguments?.getString("id")?.takeIf { route == "chat/{id}" } + val top: (String) -> Unit = { target -> + scope.launch { drawer.close() } + nav.navigate(target) { + popUpTo(nav.graph.id) { inclusive = true } + launchSingleTop = true + } + } + val over: (String) -> Unit = { target -> + scope.launch { drawer.close() } + nav.navigate(target) + } + // The list is read again each time the drawer opens, so a new title or a finished + // reply's dot is there without a pull. + LaunchedEffect(drawer.isOpen) { if (drawer.isOpen) chats.load() } + LaunchedEffect(open) { + open?.let { + when { + it.chat != null -> top("chat/${it.chat}") + it.schedule != null -> over("schedule/${it.schedule}") } - NavHost(nav, startDestination = "chats") { - composable("chats") { - ChatsScreen( - onOpen = { nav.navigate("chat/$it") }, - onNew = { nav.navigate("new") }, - onNewAgent = { nav.navigate("new-agent") }, - onSettings = { nav.navigate("settings") }, - onFiles = { nav.navigate("files") }, - ) - } - composable("new") { - ChatScreen( - chatId = null, - onBack = { nav.popBackStack() }, - onOpened = { id -> - nav.navigate("chat/$id") { popUpTo("new") { inclusive = true } } - }, - ) - } - composable("new-agent") { - ChatScreen( - chatId = null, - agent = true, - onBack = { nav.popBackStack() }, - onOpened = { id -> - nav.navigate("chat/$id") { popUpTo("new-agent") { inclusive = true } } - }, - ) - } - composable("chat/{id}") { entry -> - ChatScreen(chatId = entry.arguments?.getString("id"), onBack = { nav.popBackStack() }) - } - composable("files") { FilesScreen(onBack = { nav.popBackStack() }) } - composable("settings") { - SettingsScreen(onBack = { nav.popBackStack() }, onAddInstance = { nav.navigate("add") }) - } - // Signing in to one more instance makes it the one in use, which starts a - // fresh navigation for it (the `key` above). - composable("add") { SignInScreen(onDone = { nav.popBackStack("chats", inclusive = false) }) } + opened() + } + } + val actions = remember { + object : DrawerActions { + override fun newChat() = top("new") + + override fun newAgentChat() = top("new-agent") + + override fun open(chatId: String) = top("chat/$chatId") + + override fun archive(chat: Chat) = chats.archive(chat) + + override fun files() = over("files") + + override fun scheduled() = over("scheduled") + + override fun settings() = over("settings") + + override fun more() = chats.more() + + override fun retry() = chats.load() + } + } + val menu: () -> Unit = { scope.launch { drawer.open() } } + ModalNavigationDrawer( + drawerState = drawer, + // The drawer opens by a swipe only from a chat: elsewhere the swipe is Back's. + gesturesEnabled = drawer.isOpen || route == "new" || route == "new-agent" || route == "chat/{id}", + drawerContent = { + DrawerContent(list, current, listOf(instance.name, instance.email).filter { it.isNotBlank() }.joinToString(" · "), actions) + }, + ) { + NavHost(nav, startDestination = "new") { + composable("new") { + ChatScreen( + chatId = null, + onMenu = menu, + onNewChat = { top("new") }, + onLeave = { top("new") }, + onOpened = { id -> top("chat/$id") }, + ) } + composable("new-agent") { + ChatScreen( + chatId = null, + agent = true, + onMenu = menu, + onNewChat = { top("new") }, + onLeave = { top("new") }, + onOpened = { id -> top("chat/$id") }, + ) + } + composable("chat/{id}") { e -> + ChatScreen( + chatId = e.arguments?.getString("id"), + onMenu = menu, + onNewChat = { top("new") }, + onLeave = { top("new") }, + ) + } + composable("files") { FilesScreen(onBack = { nav.popBackStack() }) } + composable("scheduled") { + ScheduledScreen(onBack = { nav.popBackStack() }, onOpen = { over("schedule/$it") }, onNew = { over("schedule-new") }) + } + composable("schedule/{id}") { e -> + val id = e.arguments?.getString("id").orEmpty() + ScheduleScreen(id, onBack = { nav.popBackStack() }, onEdit = { over("schedule-edit/$it") }, onOpenChat = { top("chat/$it") }) + } + composable("schedule-new") { + ScheduleEditScreen(null, onBack = { nav.popBackStack() }, onSaved = { id -> + nav.navigate("schedule/$id") { popUpTo("schedule-new") { inclusive = true } } + }) + } + composable("schedule-edit/{id}") { e -> + ScheduleEditScreen(e.arguments?.getString("id"), onBack = { nav.popBackStack() }, onSaved = { nav.popBackStack() }) + } + composable("settings") { + SettingsScreen(onBack = { nav.popBackStack() }, onAddInstance = { over("add") }) + } + // Signing in to one more instance makes it the one in use, which starts a + // fresh navigation for it (the `key` above). + composable("add") { SignInScreen(onDone = { nav.popBackStack() }) } } } } diff --git a/app/src/main/java/eu/llembas/android/api/ApiClient.kt b/app/src/main/java/eu/llembas/android/api/ApiClient.kt index c1a3bff..d28246b 100644 --- a/app/src/main/java/eu/llembas/android/api/ApiClient.kt +++ b/app/src/main/java/eu/llembas/android/api/ApiClient.kt @@ -252,6 +252,41 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli suspend fun stopMember(chatId: String, name: String): List = send("POST", "/chats/$chatId/team/${segment(name)}/stop", null).stopped + // --- Scheduled tasks (provisional routes; see api/Schedules.kt) --------------------------- + suspend fun schedules(): List = get("/schedules").schedules + + suspend fun schedule(id: String): Schedule = get("/schedules/${segment(id)}").schedule + + suspend fun scheduleRuns(id: String, before: String? = null): ScheduleRuns = + get("/schedules/${segment(id)}/runs" + (before?.let { "?before=${segment(it)}" } ?: "")) + + /** Words to a rule, an instruction and the next runs; nothing is saved. */ + suspend fun compileSchedule(words: String): SchedulePreview = + send("POST", "/schedules/compile", buildJsonObject { put("text", words) }).preview + + /** Save a preview: a new schedule, or (with [id]) the one being edited. */ + suspend fun saveSchedule(preview: SchedulePreview, id: String? = null): Schedule { + val body = buildJsonObject { + put("title", preview.title) + put("instruction", preview.instruction) + preview.rule?.let { put("rule", it) } + } + return if (id == null) { + send("POST", "/schedules", body).schedule + } else { + send("PATCH", "/schedules/${segment(id)}", body).schedule + } + } + + suspend fun pauseSchedule(id: String, paused: Boolean): Schedule = + send("POST", "/schedules/${segment(id)}/" + if (paused) "pause" else "resume", null).schedule + + suspend fun runScheduleNow(id: String) { + send("POST", "/schedules/${segment(id)}/run", null) + } + + suspend fun deleteSchedule(id: String) = empty(authed("$v2/schedules/${segment(id)}").delete().build()) + // --- Model pictures -------------------------------------------------------------------------- /** diff --git a/app/src/main/java/eu/llembas/android/api/Models.kt b/app/src/main/java/eu/llembas/android/api/Models.kt index e9dd354..16cf86c 100644 --- a/app/src/main/java/eu/llembas/android/api/Models.kt +++ b/app/src/main/java/eu/llembas/android/api/Models.kt @@ -486,6 +486,9 @@ data class PushPayload( @SerialName("message_id") val messageId: String? = null, @SerialName("interaction_id") val interactionId: String? = null, val ask: String? = null, + /** A scheduled task's result or failure (`kind` `schedule` or `schedule_failed`). */ + @SerialName("schedule_id") val scheduleId: String? = null, + @SerialName("run_id") val runId: String? = null, ) // --- The activity panel (`GET /chats/{chat}/activity`) ------------------------------------- diff --git a/app/src/main/java/eu/llembas/android/api/Schedules.kt b/app/src/main/java/eu/llembas/android/api/Schedules.kt new file mode 100644 index 0000000..2e88e47 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/api/Schedules.kt @@ -0,0 +1,85 @@ +package eu.llembas.android.api + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonObject + +// --- Scheduled tasks (`/api/v2/schedules`) ------------------------------------------------ +// +// Provisional: written against the server's scheduling plan before its routes and contract +// fixtures landed. Every field has a default, so a server that says less still parses; the +// contract re-pin is where these meet the server's real shapes (and `ContractTest` holds them). + +/** + * One run of a schedule: when it was due and how it went. [status] is `ok`, `silent` (nothing + * worth saying), `failed`, `missed`, `skipped`, `waiting` (no model free yet) or `running`; + * [timing] `on_time`, `late` or `catch_up`. [error] is the server's sentence, never a model's. + */ +@Serializable +data class ScheduleRun( + val id: String = "", + @SerialName("due_at") val dueAt: String? = null, + @SerialName("started_at") val startedAt: String? = null, + @SerialName("finished_at") val finishedAt: String? = null, + val status: String = "", + val timing: String = "", + val model: String = "", + /** `pinned`, or the reason another model ran it (`switched: busy`). */ + @SerialName("model_reason") val modelReason: String = "", + @SerialName("chat_id") val chatId: String? = null, + @SerialName("message_id") val messageId: String? = null, + @SerialName("report_path") val reportPath: String? = null, + val error: String = "", + /** How many runs were missed before this one (`missed ×N`). */ + val missed: Int = 0, + val notified: Boolean = false, +) + +/** + * A scheduled task. [rule] is the recurrence in words, as the server says it ("Every weekday at + * 08:00"); [instruction] what the model is asked each time. [notify] is `always`, `matters` or + * `never`; [mode] `fresh` (a chat per run) or `continue` (one growing chat). + */ +@Serializable +data class Schedule( + val id: String, + val title: String = "", + val instruction: String = "", + val rule: String = "", + val paused: Boolean = false, + @SerialName("next_runs") val nextRuns: List = emptyList(), + @SerialName("last_run") val lastRun: ScheduleRun? = null, + val model: String = "", + val notify: String = "", + val mode: String = "", + @SerialName("failure_streak") val failureStreak: Int = 0, + @SerialName("chat_id") val chatId: String? = null, +) { + val nextRun: String? get() = nextRuns.firstOrNull() +} + +@Serializable +data class ScheduleList(val schedules: List = emptyList()) + +@Serializable +data class ScheduleEnvelope(val schedule: Schedule) + +@Serializable +data class ScheduleRuns(val runs: List = emptyList(), val more: Boolean = false) + +/** + * What the server made of a person's words: a title, the rule in words, the instruction the + * model will be given, and the next five runs -- shown before anything is saved. [rule] is the + * server's own form of the rule, handed back unchanged when the preview is saved. + */ +@Serializable +data class SchedulePreview( + val title: String = "", + @SerialName("rule_text") val ruleText: String = "", + val instruction: String = "", + @SerialName("next_runs") val nextRuns: List = emptyList(), + val rule: JsonObject? = null, +) + +@Serializable +data class SchedulePreviewEnvelope(val preview: SchedulePreview) diff --git a/app/src/main/java/eu/llembas/android/push/Push.kt b/app/src/main/java/eu/llembas/android/push/Push.kt index 36a4e53..470c2ce 100644 --- a/app/src/main/java/eu/llembas/android/push/Push.kt +++ b/app/src/main/java/eu/llembas/android/push/Push.kt @@ -98,19 +98,14 @@ object Notifications { const val EXTRA_CHAT = "eu.llembas.android.CHAT" const val EXTRA_INSTANCE = "eu.llembas.android.INSTANCE" + const val EXTRA_SCHEDULE = "eu.llembas.android.SCHEDULE" + fun show(context: Context, instance: String, payload: PushPayload) { if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return + if (payload.kind == "schedule" || payload.kind == "schedule_failed") return scheduled(context, instance, payload) val chatId = payload.chatId ?: payload.url.removePrefix("/chat/").takeIf { payload.url.startsWith("/chat/") } val id = (chatId ?: payload.url).hashCode() - val open = PendingIntent.getActivity( - context, - id, - Intent(context, MainActivity::class.java) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP) - .putExtra(EXTRA_CHAT, chatId) - .putExtra(EXTRA_INSTANCE, instance), - PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, - ) + val open = opener(context, instance, id, chatId = chatId) val channel = when (payload.kind) { "ask" -> LembasApp.CHANNEL_ASKS else -> LembasApp.CHANNEL_REPLIES @@ -134,6 +129,60 @@ object Notifications { NotificationManagerCompat.from(context).notify(id, builder.build()) } + /** + * A scheduled task's result or failure, on its own channel. The result's first lines are + * the account's, so the lock screen gets the public version instead: the app's name and + * "a scheduled task finished" (or failed), nothing of what it said. Open goes to the run's + * result (its chat) or else the schedule; Pause pauses the schedule from here. + */ + private fun scheduled(context: Context, instance: String, payload: PushPayload) { + val failed = payload.kind == "schedule_failed" + val id = (payload.runId ?: payload.scheduleId ?: payload.url).hashCode() + val channel = if (failed) LembasApp.CHANNEL_SCHEDULED_FAILURES else LembasApp.CHANNEL_SCHEDULED + val open = opener(context, instance, id, chatId = payload.chatId, scheduleId = payload.scheduleId.takeIf { payload.chatId == null }) + val public = NotificationCompat.Builder(context, channel) + .setSmallIcon(R.drawable.ic_notification) + .setContentTitle(context.getString(R.string.app_name)) + .setContentText(context.getString(if (failed) R.string.scheduled_failed_public else R.string.scheduled_result_public)) + .build() + val builder = NotificationCompat.Builder(context, channel) + .setSmallIcon(R.drawable.ic_notification) + .setContentTitle(payload.title) + .setContentText(payload.body) + .setStyle(NotificationCompat.BigTextStyle().bigText(payload.body)) + .setAutoCancel(true) + .setContentIntent(open) + .setCategory(if (failed) Notification.CATEGORY_ERROR else Notification.CATEGORY_STATUS) + .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) + .setPublicVersion(public) + .addAction(0, context.getString(R.string.viewer_open), open) + payload.scheduleId?.let { schedule -> + builder.addAction(0, context.getString(R.string.schedule_pause), pause(context, instance, schedule, id)) + } + NotificationManagerCompat.from(context).notify(id, builder.build()) + } + + private fun opener(context: Context, instance: String, id: Int, chatId: String?, scheduleId: String? = null): PendingIntent = PendingIntent.getActivity( + context, + id, + Intent(context, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP) + .putExtra(EXTRA_CHAT, chatId) + .putExtra(EXTRA_SCHEDULE, scheduleId) + .putExtra(EXTRA_INSTANCE, instance), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + + private fun pause(context: Context, instance: String, schedule: String, notification: Int): PendingIntent = PendingIntent.getBroadcast( + context, + ("pause$schedule").hashCode(), + Intent(context, ScheduleActionReceiver::class.java) + .putExtra("instance", instance) + .putExtra("schedule", schedule) + .putExtra("notification", notification), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + private fun answer(context: Context, instance: String, chat: String, card: String, verdict: String, notification: Int): PendingIntent = PendingIntent.getBroadcast( context, @@ -170,3 +219,22 @@ class CardActionReceiver : BroadcastReceiver() { } } } + +/** A scheduled task's Pause, from its notification. */ +class ScheduleActionReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val pending = goAsync() + val instance = intent.getStringExtra("instance") ?: return pending.finish() + val schedule = intent.getStringExtra("schedule") ?: return pending.finish() + background.launch { + try { + Push.instance(context, instance)?.let { found -> + runCatching { context.lembas.instances.clientFor(found).pauseSchedule(schedule, true) } + } + NotificationManagerCompat.from(context).cancel(intent.getIntExtra("notification", 0)) + } finally { + pending.finish() + } + } + } +} diff --git a/app/src/main/java/eu/llembas/android/ui/Markdown.kt b/app/src/main/java/eu/llembas/android/ui/Markdown.kt index ea462f6..e0a34eb 100644 --- a/app/src/main/java/eu/llembas/android/ui/Markdown.kt +++ b/app/src/main/java/eu/llembas/android/ui/Markdown.kt @@ -9,6 +9,7 @@ import android.util.TypedValue import android.widget.TextView import androidx.compose.runtime.Composable import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb @@ -56,18 +57,33 @@ fun markwon(context: Context, codeBg: Int, link: Int): Markwon = Markwon.builder ) .build() +/** + * [markdown] drawn by Markwon in a TextView. With [onLongPress] the text is not selectable: a + * long press is the message's menu instead (which offers Select text); without it, as in the + * activity panel's room, the text selects as usual. + */ @Composable -fun MarkdownText(markdown: String, modifier: Modifier = Modifier, color: Color? = null) { +fun MarkdownText(markdown: String, modifier: Modifier = Modifier, color: Color? = null, onLongPress: (() -> Unit)? = null) { val context = LocalContext.current val palette = LocalPalette.current val ink = (color ?: palette.ink).toArgb() val engine = remember(palette) { markwon(context, palette.codeBg.toArgb(), palette.accent.toArgb()) } + val longPress = rememberUpdatedState(onLongPress) + val pressable = onLongPress != null AndroidView( modifier = modifier, factory = { ctx -> TextView(ctx).apply { - setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f) - setTextIsSelectable(true) + setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f) + setLineSpacing(0f, 1.2f) + if (pressable) { + setOnLongClickListener { + longPress.value?.invoke() + true + } + } else { + setTextIsSelectable(true) + } movementMethod = LinkMovementMethod.getInstance() } }, diff --git a/app/src/main/java/eu/llembas/android/ui/MarkdownSplit.kt b/app/src/main/java/eu/llembas/android/ui/MarkdownSplit.kt new file mode 100644 index 0000000..4fc6e50 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/MarkdownSplit.kt @@ -0,0 +1,59 @@ +package eu.llembas.android.ui + +/** + * A reply's markdown in the pieces the transcript draws differently: prose (Markwon, in a + * TextView) and fenced code blocks (their own box, with the language and a Copy button). Only + * a fence at the start of a line (at most three spaces in, as CommonMark has it) is taken out; + * anything deeper -- a fence inside a list item -- stays in the prose for Markwon to draw. + * + * A fence that is not closed yet runs to the end: while a reply is being written, the code it + * is in the middle of is already a code block, not markdown that changes shape when it closes. + */ +sealed interface Segment { + data class Prose(val markdown: String) : Segment + + data class Code(val language: String, val code: String, val closed: Boolean = true) : Segment +} + +private val OPENING = Regex("^ {0,3}(`{3,}|~{3,})\\s*([^`\\s]*).*$") + +fun splitFences(markdown: String): List { + val out = mutableListOf() + val prose = StringBuilder() + val lines = markdown.split("\n") + var i = 0 + + fun flushProse() { + val text = prose.toString().trim('\n') + if (text.isNotBlank()) out += Segment.Prose(text) + prose.clear() + } + + while (i < lines.size) { + val open = OPENING.matchEntire(lines[i]) + if (open == null) { + prose.append(lines[i]).append('\n') + i++ + continue + } + flushProse() + val fence = open.groupValues[1] + val language = open.groupValues[2] + val closing = Regex("^ {0,3}${Regex.escape(fence.substring(0, 1))}{${fence.length},}\\s*$") + val code = mutableListOf() + i++ + var closed = false + while (i < lines.size) { + if (closing.matches(lines[i])) { + closed = true + i++ + break + } + code += lines[i] + i++ + } + out += Segment.Code(language, code.joinToString("\n"), closed) + } + flushProse() + return out +} diff --git a/app/src/main/java/eu/llembas/android/ui/chat/Blocks.kt b/app/src/main/java/eu/llembas/android/ui/chat/Blocks.kt index adbd1ab..a1dde83 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/Blocks.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/Blocks.kt @@ -54,83 +54,13 @@ import eu.llembas.android.api.ToolCall import eu.llembas.android.ui.MarkdownText import eu.llembas.android.ui.theme.LocalPalette -private val Rounded = RoundedCornerShape(10.dp) +private val Rounded = RoundedCornerShape(12.dp) -/** The person's own turn: their words as typed (never markdown), and what they attached. */ +/** A reply's steps, as the transcript draws them ([StepsCompact]); the assistant's sheet uses it. */ @Composable -fun UserBubble(message: Message, modifier: Modifier = Modifier) { - val palette = LocalPalette.current - Column( - modifier - .fillMaxWidth() - .padding(start = 48.dp) - .background(palette.bubbleUser, Rounded) - .border(1.dp, palette.border, Rounded) - .padding(12.dp), - ) { - if (!message.text.isNullOrBlank()) Text(message.text, color = palette.ink) - message.attachments.forEach { a -> - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 6.dp)) { - Icon(Icons.Filled.AttachFile, contentDescription = null, modifier = Modifier.size(16.dp), tint = palette.inkMuted) - Spacer(Modifier.width(4.dp)) - Text(a.name, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) - } - } - if (message.queued) { - Text(stringResource(R.string.queued), style = MaterialTheme.typography.labelSmall, color = palette.inkFaint) - } - } -} +fun Steps(steps: List, modifier: Modifier = Modifier, onShow: ((ShowCard) -> Unit)? = null) = StepsCompact(steps, modifier, onShow) -/** - * A reply's steps, in the order they happened: the same table of contents the web page draws. - * [onShow] opens a `show` card's file; without it (the assistant's sheet) the card only names it. - */ -@Composable -fun Steps(steps: List, modifier: Modifier = Modifier, onShow: ((ShowCard) -> Unit)? = null) { - Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) { - steps.forEach { step -> - when (step.kind) { - "thinking" -> Thinking(step) - "text" -> MarkdownText(step.markdown.orEmpty(), modifier = Modifier.fillMaxWidth()) - "tools" -> step.calls.forEach { ToolCallBlock(it, onShow = onShow) } - "steer" -> step.messages.forEach { Steered(it.text) } - } - } - } -} - -@Composable -private fun Thinking(step: Step) { - val palette = LocalPalette.current - var open by rememberSaveable(step.index, step.open) { mutableStateOf(false) } - Column( - Modifier.fillMaxWidth().background(palette.bgSunken, Rounded).clickable { open = !open }.padding(10.dp), - ) { - Row(verticalAlignment = Alignment.CenterVertically) { - Icon(Icons.Filled.Psychology, contentDescription = null, modifier = Modifier.size(16.dp), tint = palette.inkFaint) - Spacer(Modifier.width(6.dp)) - Text( - stringResource(if (step.open) R.string.thinking else R.string.thought) + (step.label?.let { " $it" } ?: ""), - style = MaterialTheme.typography.labelMedium, - color = palette.inkMuted, - ) - } - AnimatedVisibility(open) { - Text(step.text.orEmpty(), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, modifier = Modifier.padding(top = 6.dp)) - } - } -} - -@Composable -private fun Steered(text: String) { - val palette = LocalPalette.current - Row(Modifier.fillMaxWidth().padding(start = 24.dp)) { - Text("↳ $text", style = MaterialTheme.typography.bodySmall, color = palette.inkMuted) - } -} - -private fun iconFor(kind: String): ImageVector = when (kind) { +internal fun iconFor(kind: String): ImageVector = when (kind) { "shell" -> Icons.Filled.Terminal "edit" -> Icons.Filled.Edit "read" -> Icons.AutoMirrored.Filled.Article @@ -250,21 +180,3 @@ private fun ShowCardRow(show: ShowCard, depth: Int, onShow: ((ShowCard) -> Unit) } } } - -/** A finished or failed reply's foot: what it cost, and why it stopped if it did. */ -@Composable -fun ReplyFoot(message: Message) { - val palette = LocalPalette.current - message.error?.let { - Text(it, color = palette.danger, style = MaterialTheme.typography.bodySmall) - } - val m = message.metrics ?: return - if (m.completionTokens == 0 && m.elapsedMs == 0L) return - val parts = buildList { - message.model?.let { add(it) } - if (m.completionTokens > 0) add("${if (m.estimated) "~" else ""}${m.completionTokens} tok") - if (m.tokPerSecond > 0) add("${"%.1f".format(m.tokPerSecond)} tok/s") - if (m.percent > 0) add("${m.percent}%") - } - Text(parts.joinToString(" · "), style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, modifier = Modifier.widthIn(max = 600.dp)) -} 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 5f6dfd0..93f5f6d 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 @@ -2,76 +2,71 @@ package eu.llembas.android.ui.chat -import android.Manifest -import android.annotation.SuppressLint import android.content.ClipData import android.content.ClipboardManager -import android.content.pm.PackageManager -import android.net.Uri import android.os.Build -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.PickVisualMediaRequest -import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.background import androidx.compose.foundation.gestures.scrollBy import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.IntrinsicSize 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.imePadding import androidx.compose.foundation.layout.navigationBarsPadding 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.LazyListState import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape 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.Archive 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.Delete +import androidx.compose.material.icons.filled.DriveFileRenameOutline +import androidx.compose.material.icons.filled.EditNote +import androidx.compose.material.icons.filled.Menu 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.PlayArrow import androidx.compose.material.icons.filled.Terminal import androidx.compose.material3.AlertDialog import androidx.compose.material3.AssistChip import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.FilterChip import androidx.compose.material3.Icon import androidx.compose.material3.IconButton -import androidx.compose.material3.InputChip import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.SheetValue -import androidx.compose.material3.Slider import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton -import androidx.compose.material3.TextField import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope @@ -84,52 +79,40 @@ 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 -@OptIn(ExperimentalMaterial3Api::class) +/** + * One chat, with its model behind it: the transcript, the composer, and the sheets and panels + * that open over them. [chatId] null is a new chat (an agent chat with [agent]); its first + * message makes it, and [onOpened] then moves the route to it. + */ @Composable fun ChatScreen( chatId: String?, - onBack: () -> Unit, + onMenu: () -> Unit, + onNewChat: () -> Unit, + onLeave: () -> Unit, onOpened: (String) -> Unit = {}, agent: Boolean = false, model: ChatViewModel = viewModel(key = chatId ?: if (agent) "new-agent" else "new"), ) { val state by model.state.collectAsStateWithLifecycle() - val palette = LocalPalette.current - val list = rememberLazyListState() val snackbar = remember { SnackbarHostState() } - var menu by remember { mutableStateOf(false) } - 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 + var showing by remember { mutableStateOf(null) } val lifecycle = LocalLifecycleOwner.current.lifecycle - val scope = rememberCoroutineScope() - val copy: (String) -> Unit = { text -> - context.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText("LLeMbas", text)) - // Android 13 and newer say "Copied" themselves. - if (Build.VERSION.SDK_INT < 33) scope.launch { snackbar.showSnackbar(context.getString(R.string.copied)) } - } + val isAgent = agent || state.chat?.isAgent == true LaunchedEffect(chatId) { model.open(chatId, agent = agent && chatId == null) } // A new chat gets its id from its first message; the route follows, so Back and a @@ -145,150 +128,199 @@ fun ChatScreen( model.clearError() } } + + ChatContent( + state = state, + actions = model, + agent = isAgent, + snackbar = snackbar, + onMenu = onMenu, + onNewChat = onNewChat, + onLeave = onLeave, + onActivity = { activityOpen = true }, + onShow = { showing = it }, + ) + + 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 }) } + } +} + +/** + * The chat as it is drawn, from [state] alone: what the screenshot tests render with fake data. + * Everything it does goes through [actions]. + */ +@Composable +fun ChatContent( + state: ChatState, + actions: ChatActions, + agent: Boolean, + snackbar: SnackbarHostState = remember { SnackbarHostState() }, + onMenu: () -> Unit = {}, + onNewChat: () -> Unit = {}, + onLeave: () -> Unit = {}, + onActivity: () -> Unit = {}, + onShow: (ShowCard) -> Unit = {}, +) { + val palette = LocalPalette.current + val context = LocalContext.current + val scope = rememberCoroutineScope() + val list = rememberLazyListState() + var menu by remember { mutableStateOf(false) } + var picking by remember { mutableStateOf(false) } + var tuning by remember { mutableStateOf(false) } + var renaming by remember { mutableStateOf(false) } + var editing by remember { mutableStateOf(null) } + var suggestion by remember { mutableStateOf("") } + var suggested by remember { mutableIntStateOf(0) } + val copy: (String) -> Unit = { text -> + context.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText("LLeMbas", text)) + // Android 13 and newer say "Copied" themselves. + if (Build.VERSION.SDK_INT < 33) scope.launch { snackbar.showSnackbar(context.getString(R.string.copied)) } + } + val chat = state.chat val live = state.live val rows = state.messages + val info = state.modelInfo + // To the end when the transcript grows, and while a reply is being written -- but only if // the person is at the end already: reading back up is not interrupted by the next line. - // Whether to follow is decided when the person's own scroll comes to rest, not when a - // line arrives: by then the line has already made the list longer than the screen. var following by remember { mutableStateOf(true) } LaunchedEffect(list.isScrollInProgress) { if (!list.isScrollInProgress) following = !list.canScrollForward } - LaunchedEffect(rows.size) { - if (rows.isNotEmpty()) list.toEnd() - } + LaunchedEffect(rows.size) { if (rows.isNotEmpty()) list.toEnd() } val growth = live?.let { it.shown.size * 100_000 + (it.tail.text.length + it.tail.thinking.length) } ?: 0 - LaunchedEffect(growth) { - if (growth > 0 && following) list.toEnd() - } + LaunchedEffect(growth) { if (growth > 0 && following) list.toEnd() } - Scaffold( - snackbarHost = { SnackbarHost(snackbar) }, - topBar = { - TopAppBar( - navigationIcon = { - IconButton(onClick = onBack) { - Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) - } - }, - title = { - 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)) + CompositionLocalProvider(LocalCopy provides copy) { + Scaffold( + containerColor = palette.bg, + snackbarHost = { SnackbarHost(snackbar) }, + topBar = { + TopAppBar( + colors = TopAppBarDefaults.topAppBarColors(containerColor = palette.bg, scrolledContainerColor = palette.bg), + navigationIcon = { + IconButton(onClick = onMenu) { Icon(Icons.Filled.Menu, contentDescription = stringResource(R.string.chats_open)) } + }, + title = { + ModelTitle( + model = info, + fallback = state.modelId ?: stringResource(R.string.app_name), + subtitle = chat?.title?.ifBlank { null }, + onClick = { picking = true }, + ) + }, + actions = { + if (chat != null) { + IconButton(onClick = onNewChat) { Icon(Icons.Filled.EditNote, contentDescription = stringResource(R.string.new_chat)) } + Box { + IconButton(onClick = { menu = true }) { Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more)) } + DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { + MenuItem(Icons.Filled.Bolt, stringResource(R.string.activity)) { + menu = false + onActivity() + } + MenuItem(Icons.Filled.DriveFileRenameOutline, stringResource(R.string.rename_chat)) { + menu = false + renaming = true + } + MenuItem(Icons.Filled.PlayArrow, stringResource(R.string.continue_reply)) { + menu = false + actions.continueChat() + } + MenuItem(Icons.Filled.Archive, stringResource(R.string.archive)) { + menu = false + actions.change("archived", "true") + onLeave() + } + MenuItem(Icons.Filled.Delete, stringResource(R.string.delete)) { + menu = false + actions.delete(onLeave) + } + } + } } + }, + ) + }, + bottomBar = { + Column(Modifier.background(palette.bg).navigationBarsPadding().imePadding().padding(horizontal = 12.dp).padding(bottom = 8.dp)) { + if (state.loading) LinearProgressIndicator(Modifier.fillMaxWidth().padding(bottom = 4.dp)) + if (rows.isEmpty() && chat == null && !agent) { + Suggestions { + suggestion = it + suggested++ + } + } + live?.plan?.let { plan -> + Surface(color = palette.surfaceRaised, shape = RoundedCornerShape(16.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) { + Column(Modifier.heightIn(max = 180.dp).padding(horizontal = 16.dp, vertical = 8.dp)) { PlanBody(plan) } + } + } + if (chat?.plan != null && live == null && chat.mode == "plan") { + TextButton(onClick = actions::executePlan) { Text(stringResource(R.string.plan_carry_out)) } + } + state.summary?.let { summary -> ActivityStrip(summary, onActivity) } + // 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()), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + live.jobs.forEach { job -> + AssistChip(onClick = { + }, label = { Text("${job.id} · ${job.description.ifBlank { job.command }} · ${job.state}", maxLines = 1) }) + } + } + } + if (live != null && live.status.isNotBlank()) { Text( - state.chat?.title?.ifBlank { null } ?: stringResource(if (agent) R.string.new_agent_chat else R.string.new_chat), + live.status, + style = MaterialTheme.typography.labelSmall, + color = palette.inkFaint, maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp), ) } - }, - 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)) - } - DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { - DropdownMenuItem(text = { Text(stringResource(R.string.rename_chat)) }, onClick = { - menu = false - renaming = true - }) - DropdownMenuItem(text = { Text(stringResource(R.string.continue_reply)) }, onClick = { - menu = false - model.continueChat() - }) - DropdownMenuItem(text = { Text(stringResource(R.string.archive)) }, onClick = { - menu = false - model.change("archived", "true") - onBack() - }) - DropdownMenuItem(text = { Text(stringResource(R.string.delete)) }, onClick = { - menu = false - model.delete(onBack) - }) - } - } - }, - ) - }, - bottomBar = { - Column(Modifier.background(palette.surface).navigationBarsPadding().imePadding()) { - if (state.loading || state.uploading) LinearProgressIndicator(Modifier.fillMaxWidth()) - live?.plan?.let { plan -> - Column(Modifier.fillMaxWidth().heightIn(max = 180.dp).padding(horizontal = 16.dp, vertical = 8.dp)) { - PlanBody(plan) + // A new value each tap, so the same suggestion twice still fills the field. + androidx.compose.runtime.key(suggested) { + Composer(state, actions, agent, onTune = { tuning = true }, initial = suggestion) } } - state.chat?.plan?.let { _ -> - if (live == null && state.chat?.mode == "plan") { - TextButton(onClick = { model.executePlan() }, modifier = Modifier.padding(horizontal = 8.dp)) { - Text(stringResource(R.string.plan_carry_out)) - } - } - } - 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) }) - } - } - } - if (live != null && live.status.isNotBlank()) { - Text(live.status, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, modifier = Modifier.padding(horizontal = 16.dp)) - } - Composer(model, state, agent) - } - }, - ) { padding -> - LazyColumn( - state = list, - modifier = Modifier.fillMaxSize().padding(padding), - contentPadding = PaddingValues(16.dp), - verticalArrangement = Arrangement.spacedBy(16.dp), - ) { - if (state.more) { - item { TextButton(onClick = model::older) { Text(stringResource(R.string.older)) } } - } + }, + ) { padding -> if (rows.isEmpty() && !state.loading) { - item { - Box(Modifier.fillMaxWidth().padding(top = 96.dp), contentAlignment = Alignment.Center) { - Text(stringResource(R.string.empty_chat), color = palette.inkMuted) - } - } - } - items(rows, key = { it.id }) { message -> - when { - message.isUser -> Column { - UserBubble(message) - Row(Modifier.align(Alignment.End), verticalAlignment = Alignment.CenterVertically) { - message.text?.takeIf { it.isNotBlank() }?.let { words -> CopyButton { copy(words) } } - if (!message.machine && live == null) { - TextButton(onClick = { editing = message }) { Text(stringResource(R.string.edit)) } - } - } + Greeting(state, agent, onTune = { tuning = true }, modifier = Modifier.padding(padding)) + } else { + LazyColumn( + state = list, + modifier = Modifier.fillMaxSize().padding(padding), + contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 24.dp), + verticalArrangement = Arrangement.spacedBy(20.dp), + ) { + if (state.more) { + item { TextButton(onClick = actions::older) { Text(stringResource(R.string.older)) } } } + items(rows, key = { it.id }) { message -> + when { + message.isUser -> UserMessage(message, canEdit = !message.machine && live == null, onEdit = { editing = message }) - live != null && live.messageId == message.id && live.finished == null -> Column { - Steps(live.shown, onShow = { showing = it }) - if (live.shown.isEmpty()) Text(stringResource(R.string.loading_line), color = palette.inkFaint) - live.metrics?.let { m -> ReplyFoot(message.copy(metrics = m)) } - } + live != null && live.messageId == message.id && live.finished == null -> + AssistantMessage(message, live.shown, writing = true, canRegenerate = false, onRegenerate = {}, onShow = onShow) - else -> Column { - Steps(message.steps, onShow = { showing = it }) - ReplyFoot(message) - val words = replyText(message) - Row(verticalAlignment = Alignment.CenterVertically) { - if (words.isNotBlank()) CopyButton { copy(words) } - if (live == null && message == rows.lastOrNull()) { - TextButton(onClick = { model.regenerate(message) }) { Text(stringResource(R.string.regenerate)) } - } + else -> AssistantMessage( + message, + message.steps, + writing = false, + canRegenerate = live == null && message == rows.lastOrNull(), + onRegenerate = { actions.regenerate(message) }, + onShow = onShow, + ) } } } @@ -296,41 +328,41 @@ fun ChatScreen( } } + if (picking) { + ModalBottomSheet(onDismissRequest = { picking = false }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) { + ModelPickerContent(state.models, state.modelId, onPick = { id -> + picking = false + if (chat == null) actions.updateDraft { it.copy(model = id) } else actions.change("model", id) + }) + } + } + if (tuning) { + ModalBottomSheet(onDismissRequest = { tuning = false }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) { + TuneContent(state, actions, agent) + } + } + // A card the reply is waiting on, as a sheet over the chat. One at a time, in the order asked. live?.cards?.firstOrNull()?.let { card -> ModalBottomSheet( onDismissRequest = {}, // Not dismissable by a swipe: the reply is stopped until the card is answered, and // a card swiped away would leave it waiting with nothing on screen to say why. - sheetState = rememberModalBottomSheetState( - skipPartiallyExpanded = true, - confirmValueChange = { it != SheetValue.Hidden }, - ), + sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true, confirmValueChange = { it != SheetValue.Hidden }), ) { - CardSheet(card) { answer -> model.answer(card, answer) } + CardSheet(card) { answer -> actions.answer(card, answer) } } } - 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 }) } - } - if (renaming) { - var title by remember { mutableStateOf(state.chat?.title.orEmpty()) } + var title by remember { mutableStateOf(chat?.title.orEmpty()) } AlertDialog( onDismissRequest = { renaming = false }, title = { Text(stringResource(R.string.rename_chat)) }, text = { OutlinedTextField(value = title, onValueChange = { title = it }, singleLine = true, modifier = Modifier.fillMaxWidth()) }, confirmButton = { TextButton(enabled = title.isNotBlank(), onClick = { - model.rename(title) + actions.rename(title) renaming = false }) { Text(stringResource(R.string.save)) } }, @@ -346,7 +378,7 @@ fun ChatScreen( text = { OutlinedTextField(value = text, onValueChange = { text = it }, modifier = Modifier.fillMaxWidth()) }, confirmButton = { TextButton(onClick = { - model.edit(message, text) + actions.edit(message, text) editing = null }) { Text(stringResource(R.string.card_send)) } }, @@ -355,6 +387,11 @@ fun ChatScreen( } } +@Composable +private fun MenuItem(icon: androidx.compose.ui.graphics.vector.ImageVector, text: String, onClick: () -> Unit) { + DropdownMenuItem(leadingIcon = { Icon(icon, contentDescription = null) }, text = { Text(text) }, onClick = onClick) +} + /** To the very end of the transcript: the last row, then down to its foot however tall it is. */ private suspend fun LazyListState.toEnd() { val last = layoutInfo.totalItemsCount - 1 @@ -363,409 +400,74 @@ private suspend fun LazyListState.toEnd() { scrollBy(1_000_000f) } -/** A reply's own words, as the person would copy them: its text steps, in order. */ -private fun replyText(message: Message): String = - message.steps.filter { it.kind == "text" }.mapNotNull { it.markdown }.joinToString("\n\n").ifBlank { message.text.orEmpty() } - -@Composable -private fun CopyButton(onClick: () -> Unit) { - IconButton(onClick = onClick) { - Icon( - Icons.Filled.ContentCopy, - contentDescription = stringResource(R.string.copy_message), - tint = LocalPalette.current.inkFaint, - ) - } -} - -/** The agent modes, as the web page offers them, in the order of how much the model may do. */ -private val AGENT_MODES = listOf("manual", "edit", "auto", "plan") - -@Composable -private fun modeName(mode: String): String = when (mode) { - "manual" -> stringResource(R.string.mode_manual) - "edit" -> stringResource(R.string.mode_edit) - "auto" -> stringResource(R.string.mode_auto) - "plan" -> stringResource(R.string.mode_plan) - else -> mode.replaceFirstChar { it.uppercase() } -} - -@SuppressLint("MissingPermission") -@Composable -private fun Composer(model: ChatViewModel, state: ChatState, agent: Boolean) { - val context = LocalContext.current - val scope = rememberCoroutineScope() - 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) } - var directory by rememberSaveable { mutableStateOf("") } - var askDirectory by remember { mutableStateOf(false) } - var attachMenu by remember { mutableStateOf(false) } - var listening by remember { mutableStateOf(false) } - var photo by remember { mutableStateOf(null) } - val recorder = remember { Recorder(scope) } - val pickFiles = rememberLauncherForActivityResult(ActivityResultContracts.GetMultipleContents()) { model.attach(it) } - val pickPhotos = rememberLauncherForActivityResult(ActivityResultContracts.PickMultipleVisualMedia()) { model.attach(it) } - val takePhoto = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { taken -> - photo?.let { if (taken) model.attach(listOf(it)) } - photo = null - } - val askMic = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> - if (granted) { - recorder.start() - listening = true - } - } - // A message the server did not take comes back here, so nothing typed is lost. - LaunchedEffect(state.unsent) { - state.unsent?.let { - if (text.isBlank()) text = it - model.clearUnsent() - } - } - val chat = state.chat - val newAgent = agent && chat == null - // The first linked device is the one a new agent chat runs on until another is chosen. - val target: LinkedDevice? = state.devices.firstOrNull { it.id == device } ?: state.devices.firstOrNull() - val current = chat?.model?.ifBlank { null } ?: chosenModel ?: state.models.firstOrNull { it.default }?.id - val running = state.live != null && state.live.finished == null - - Column(Modifier.fillMaxWidth().padding(8.dp)) { - if (newAgent && state.devices.isEmpty() && !state.loading) { - Text( - stringResource(R.string.agent_no_device), - style = MaterialTheme.typography.bodySmall, - color = LocalPalette.current.inkMuted, - modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), - ) - } - if (state.pending.isNotEmpty()) { - Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) { - state.pending.forEach { a -> - InputChip( - selected = false, - onClick = { model.unattach(a) }, - label = { Text(a.name, maxLines = 1) }, - trailingIcon = { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.remove)) }, - ) - } - } - } - Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) { - if (newAgent && state.devices.isNotEmpty()) { - DeviceChip(state.devices, target) { device = it } - AssistChip( - onClick = { askDirectory = true }, - leadingIcon = { Icon(Icons.Filled.Folder, contentDescription = null) }, - label = { Text(directory.ifBlank { stringResource(R.string.agent_directory) }, maxLines = 1) }, - ) - } - ModelChip(state.models, current) { id -> - if (chat == null) chosenModel = id else model.change("model", id) - } - val 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. 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 } - - chat != null && chat.isAgent -> ModeChip(chat.mode.ifBlank { "edit" }) { model.change("mode", it) } - - else -> FilterChip( - selected = if (chat == null) planMode else chat.mode == "plan", - onClick = { - if (chat == null) planMode = !planMode else model.change("mode", if (chat.mode == "plan") "" else "plan") - }, - label = { Text(stringResource(R.string.mode_plan)) }, - ) - } - } - Row(verticalAlignment = Alignment.Bottom) { - Box { - IconButton(onClick = { attachMenu = true }) { - Icon(Icons.Filled.AttachFile, contentDescription = stringResource(R.string.attach)) - } - DropdownMenu(expanded = attachMenu, onDismissRequest = { attachMenu = false }) { - DropdownMenuItem(text = { Text(stringResource(R.string.attach_take_photo)) }, onClick = { - attachMenu = false - model.photoTarget().also { photo = it }.let { takePhoto.launch(it) } - }) - DropdownMenuItem(text = { Text(stringResource(R.string.attach_choose_photos)) }, onClick = { - attachMenu = false - pickPhotos.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) - }) - DropdownMenuItem(text = { Text(stringResource(R.string.attach_choose_files)) }, onClick = { - attachMenu = false - pickFiles.launch("*/*") - }) - } - } - TextField( - value = text, - onValueChange = { text = it }, - placeholder = { Text(stringResource(if (listening) R.string.listening else R.string.composer_hint)) }, - modifier = Modifier.weight(1f).heightIn(max = 200.dp), - ) - IconButton(onClick = { - if (listening) { - listening = false - scope.launch { - val wav = recorder.stop() - if (wav.isNotEmpty()) { - runCatching { context.lembas.instances.client()?.transcribe(wav) } - .onSuccess { heard -> if (!heard.isNullOrBlank()) text = (text + " " + heard).trim() } - } - } - } else if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) { - recorder.start() - listening = true - } else { - askMic.launch(Manifest.permission.RECORD_AUDIO) - } - }) { - Icon(if (listening) Icons.Filled.Stop else Icons.Filled.Mic, contentDescription = stringResource(R.string.dictate)) - } - if (running && text.isBlank()) { - IconButton(onClick = model::stop) { Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop)) } - } else { - IconButton( - enabled = (text.isNotBlank() || state.pending.isNotEmpty()) && !state.uploading && (!newAgent || target != null), - onClick = { - model.send( - text, - model = chosenModel, - mode = if (newAgent) { - agentMode - } else if (planMode) { - "plan" - } else { - null - }, - 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 = "" - }, - ) { Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send)) } - } - } - } - - 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( - onDismissRequest = { askDirectory = false }, - title = { Text(stringResource(R.string.agent_directory)) }, - text = { - OutlinedTextField( - value = typed, - onValueChange = { typed = it }, - singleLine = true, - placeholder = { Text(stringResource(R.string.agent_directory_hint)) }, - modifier = Modifier.fillMaxWidth(), - ) - }, - confirmButton = { - TextButton(onClick = { - directory = typed.trim() - askDirectory = false - }) { Text(stringResource(R.string.save)) } - }, - dismissButton = { TextButton(onClick = { askDirectory = false }) { Text(stringResource(R.string.cancel)) } }, - ) - } -} - -@Composable -private fun DeviceChip(devices: List, current: LinkedDevice?, onPick: (String) -> Unit) { - var open by remember { mutableStateOf(false) } - Box { - AssistChip( - onClick = { open = true }, - leadingIcon = { Icon(Icons.Filled.Terminal, contentDescription = stringResource(R.string.agent_device)) }, - label = { Text(current?.let { it.name.ifBlank { it.host } } ?: "—", maxLines = 1) }, - ) - DropdownMenu(expanded = open, onDismissRequest = { open = false }) { - devices.forEach { d -> - DropdownMenuItem( - text = { Text(listOf(d.name, d.host).filter { it.isNotBlank() }.distinct().joinToString(" · ")) }, - onClick = { - open = false - onPick(d.id) - }, - ) - } - } - } -} - -@Composable -private fun ModeChip(current: String, onPick: (String) -> Unit) { - var open by remember { mutableStateOf(false) } - Box { - AssistChip(onClick = { open = true }, label = { Text(modeName(current)) }) - DropdownMenu(expanded = open, onDismissRequest = { open = false }) { - AGENT_MODES.forEach { m -> - DropdownMenuItem(text = { Text(modeName(m)) }, onClick = { - open = false - onPick(m) - }) - } - } - } -} - -@Composable -private fun ModelChip(models: List, current: String?, onPick: (String) -> Unit) { - var open by remember { mutableStateOf(false) } - Box { - 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( - 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 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. + * A new chat's empty page: the model's picture and a greeting. A new agent chat says where it + * will run instead, and that line opens the tune sheet where the device and folder are chosen. */ @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)) } +private fun Greeting(state: ChatState, agent: Boolean, onTune: () -> Unit, modifier: Modifier = Modifier) { 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 - } + Column( + modifier.fillMaxSize().padding(horizontal = 32.dp), + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally, + ) { + if (agent) { + Box(Modifier.size(64.dp).background(palette.accentSoft, RoundedCornerShape(20.dp)), contentAlignment = Alignment.Center) { + Icon(Icons.Filled.Terminal, contentDescription = null, tint = palette.accent, modifier = Modifier.size(32.dp)) } - }, - confirmButton = { TextButton(onClick = { onSave(AgentsSetting(low, high)) }) { Text(stringResource(R.string.save)) } }, - dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } }, - ) -} + Spacer(Modifier.height(20.dp)) + Text(stringResource(R.string.agent_greeting), style = MaterialTheme.typography.headlineSmall, textAlign = TextAlign.Center) + Spacer(Modifier.height(8.dp)) + val device = state.device + val where = when { + device == null -> stringResource(R.string.agent_no_device) + else -> stringResource( + R.string.agent_runs_on, + device.name.ifBlank { device.host }, + state.draft.directory.ifBlank { stringResource(R.string.agent_directory_default) }, + ) + } + TextButton(onClick = onTune) { Text(where, textAlign = TextAlign.Center, color = palette.inkMuted) } + } else { + ModelAvatar(state.modelInfo, state.modelId ?: "?", size = 64.dp) + Spacer(Modifier.height(20.dp)) + Text(stringResource(R.string.empty_chat), style = MaterialTheme.typography.headlineSmall, textAlign = TextAlign.Center) + } + } +} + +/** The empty chat's suggestions: a sideways row of cards, all one height (the tallest's). */ +@OptIn(ExperimentalLayoutApi::class) @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) +private fun Suggestions(onPick: (String) -> Unit) { + val palette = LocalPalette.current + val all = listOf( + R.string.suggest_explain to R.string.suggest_explain_line, + R.string.suggest_write to R.string.suggest_write_line, + R.string.suggest_plan to R.string.suggest_plan_line, + R.string.suggest_check to R.string.suggest_check_line, + ) + Row( + Modifier.fillMaxWidth().height(IntrinsicSize.Max).horizontalScroll(rememberScrollState()).padding(bottom = 10.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + all.forEach { (title, line) -> + val t = stringResource(title) + val l = stringResource(line) + Surface( + onClick = { onPick("$t $l") }, + shape = RoundedCornerShape(16.dp), + color = palette.surfaceRaised, + border = androidx.compose.foundation.BorderStroke(1.dp, palette.border), + modifier = Modifier.width(184.dp).fillMaxHeight(), + ) { + Column(Modifier.padding(horizontal = 14.dp, vertical = 10.dp)) { + Text(t, style = MaterialTheme.typography.titleSmall) + Text(l, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted) + } + } } - 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 70be3ec..a332c05 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 @@ -65,16 +65,83 @@ data class ChatState( val teamOffered: Boolean = false, /** Whether the events route is followed; without it an open panel polls. */ val activityLive: Boolean = false, + /** What a chat not made yet will be made with: chosen in the top bar and the tune sheet. */ + val draft: Draft = Draft(), ) +/** + * The choices for a chat its first message makes. Nothing here is sent until then; an open + * chat changes at once instead (`PATCH`), as the web page's controls do. + */ +data class Draft( + val model: String? = null, + val effort: String? = null, + val agents: AgentsSetting? = null, + val plan: Boolean = false, + val agentMode: String = "edit", + val device: String? = null, + val directory: String = "", +) + +/** The model in force: the chat's, else the one chosen for the new chat, else the default. */ +val ChatState.modelId: String? + get() = chat?.model?.ifBlank { null } ?: draft.model ?: models.firstOrNull { it.default }?.id ?: models.firstOrNull()?.id + +val ChatState.modelInfo: ModelInfo? get() = models.firstOrNull { it.id == modelId } + +/** The thinking level in force, by the model's levels; null for a model with no choice. */ +val ChatState.level: String? + get() = modelInfo?.takeIf { it.levelControl != "none" }?.level(if (chat == null) draft.effort else chat.effort?.ifBlank { null }) + +/** Whether a team may be asked for: the server's word for a chat that exists, the model's facts for a new one. */ +fun ChatState.offersTeam(agent: Boolean): Boolean = if (chat != null) teamOffered else !agent && modelInfo?.mayHaveTeam == true + +/** The team's size in force. */ +val ChatState.agents: AgentsSetting get() = chat?.agents ?: draft.agents ?: AgentsSetting() + +/** Whether a reply is being written right now. */ +val ChatState.running: Boolean get() = live != null && live.finished == null + +/** The linked device a new agent chat runs on: the chosen one, else the first. */ +val ChatState.device: LinkedDevice? get() = devices.firstOrNull { it.id == draft.device } ?: devices.firstOrNull() + +/** + * What the chat screen asks of its model. Every action has a do-nothing default, so the + * screenshot tests draw the screen with fake data and no server behind it. + */ +interface ChatActions { + fun send(text: String) {} + fun stop() {} + fun regenerate(message: Message) {} + fun edit(message: Message, text: String) {} + fun continueChat() {} + fun executePlan() {} + fun answer(card: Card, answer: CardAnswer) {} + fun change(key: String, value: String?) {} + fun setAgents(agents: AgentsSetting) {} + fun updateDraft(change: (Draft) -> Draft) {} + fun attach(uris: List) {} + fun unattach(attachment: Attachment) {} + fun photoTarget(): Uri? = null + fun rename(title: String) {} + fun delete(then: () -> Unit) {} + fun older() {} + fun clearUnsent() {} +} + /** * One chat: its transcript, the reply being written, and every control. A new chat has no id * until its first message makes it, as on the web page -- there is no empty chat. */ -class ChatViewModel(app: Application) : AndroidViewModel(app) { +class ChatViewModel(app: Application) : + AndroidViewModel(app), + ChatActions { private val _state = MutableStateFlow(ChatState()) val state = _state.asStateFlow() private var following: Job? = null + + /** Whether this screen makes an agent chat (until its first message makes it). */ + private var agentChat = false private var api: ApiClient? = null private suspend fun api(): ApiClient = api ?: getApplication().lembas.instances.client()?.also { api = it } @@ -88,12 +155,15 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) { fun clearError() = _state.update { it.copy(error = null, notice = null) } - fun clearUnsent() = _state.update { it.copy(unsent = null) } + override fun clearUnsent() = _state.update { it.copy(unsent = null) } - fun rename(title: String) = change("title", title.trim()) + override fun updateDraft(change: (Draft) -> Draft) = _state.update { it.copy(draft = change(it.draft)) } + + override fun rename(title: String) = change("title", title.trim()) /** Open a chat, or (no id) get a new one ready: an agent chat also needs the linked devices. */ fun open(chatId: String?, agent: Boolean = false) { + agentChat = agent viewModelScope.launch { try { val client = api() @@ -120,7 +190,7 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) { } } - fun older() { + override fun older() { val chat = _state.value.chat ?: return val first = _state.value.messages.firstOrNull() ?: return viewModelScope.launch { @@ -182,15 +252,24 @@ 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, - agents: AgentsSetting? = null, - ) { + /** + * Send [text] (and what is attached). A chat that does not exist yet is made by it, with the + * draft's choices -- each only where the model offers it. + */ + override fun send(text: String) { + val now = _state.value + val draft = now.draft + val newAgent = agentChat && now.chat == null + val model = draft.model + val mode = when { + newAgent -> draft.agentMode + draft.plan -> "plan" + else -> null + } + val effort = draft.effort?.takeIf { picked -> now.modelInfo?.offered?.contains(picked) == true } + val agent = if (newAgent) now.device?.let { AgentTarget(it.id, draft.directory) } else null + val agents = draft.agents + val temporary = false val attached = _state.value.pending val files = attached.map { it.id } if (text.isBlank() && files.isEmpty()) return @@ -223,33 +302,33 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) { } } - fun stop() { + override fun stop() { val chat = _state.value.chat ?: return val live = _state.value.live ?: return viewModelScope.launch { runCatching { api().stop(chat.id, live.messageId) }.onFailure(::fail) } } - fun regenerate(message: Message) = control { api, chat -> + override fun regenerate(message: Message) = control { api, chat -> val turn = api.regenerate(chat.id, message.id) _state.update { s -> s.copy(messages = s.messages.map { if (it.id == message.id) turn.reply ?: it else it }) } turn.reply?.let { follow(it.id) } } - fun edit(message: Message, text: String) = control { api, chat -> + override fun edit(message: Message, text: String) = control { api, chat -> val turn = api.edit(chat.id, message.id, text) // Everything after the edited turn is gone on the server; read it back. refresh() turn.reply?.let { follow(it.id) } } - fun continueChat() = control { api, chat -> took(api.continueChat(chat.id)) } + override fun continueChat() = control { api, chat -> took(api.continueChat(chat.id)) } - fun executePlan() = control { api, chat -> + override fun executePlan() = control { api, chat -> took(api.executePlan(chat.id)) refresh() } - fun answer(card: Card, answer: CardAnswer) = control { api, chat -> + override fun answer(card: Card, answer: CardAnswer) = control { api, chat -> try { api.answer(chat.id, card.id, answer) } catch (e: ApiException) { @@ -261,7 +340,7 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) { _state.update { s -> s.copy(live = s.live?.let { l -> l.copy(cards = l.cards.filterNot { it.id == card.id }) }) } } - fun change(key: String, value: String?) = control { api, chat -> + override 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 @@ -272,7 +351,7 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) { } /** The team's size, both ends; the server refuses a pair outside its bounds in its words. */ - fun setAgents(agents: AgentsSetting) = control { api, chat -> + override fun setAgents(agents: AgentsSetting) = control { api, chat -> val updated = api.setAgents(chat.id, agents) _state.update { it.copy(chat = updated) } } @@ -344,12 +423,12 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) { loadActivity(context = false) } - fun delete(then: () -> Unit) = control { api, chat -> + override fun delete(then: () -> Unit) = control { api, chat -> api.deleteChat(chat.id) then() } - fun attach(uris: List) { + override fun attach(uris: List) { if (uris.isEmpty()) return viewModelScope.launch { _state.update { it.copy(uploading = true) } @@ -381,14 +460,14 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) { * Where the camera writes a photo for the composer: a file in the app's cache, shared with * the camera app through the FileProvider for exactly this one capture. */ - fun photoTarget(): Uri { + override fun photoTarget(): Uri { val app = getApplication() val dir = File(app.cacheDir, "camera").apply { mkdirs() } val file = File(dir, "photo-${System.currentTimeMillis()}.jpg") return FileProvider.getUriForFile(app, photoAuthority, file) } - fun unattach(attachment: Attachment) { + override fun unattach(attachment: Attachment) { _state.update { s -> s.copy(pending = s.pending.filterNot { it.id == attachment.id }) } } diff --git a/app/src/main/java/eu/llembas/android/ui/chat/Composer.kt b/app/src/main/java/eu/llembas/android/ui/chat/Composer.kt new file mode 100644 index 0000000..70b7929 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/chat/Composer.kt @@ -0,0 +1,579 @@ +package eu.llembas.android.ui.chat + +import android.Manifest +import android.annotation.SuppressLint +import android.content.pm.PackageManager +import android.net.Uri +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.PickVisualMediaRequest +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.ArrowUpward +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Folder +import androidx.compose.material.icons.filled.Mic +import androidx.compose.material.icons.filled.PhotoCamera +import androidx.compose.material.icons.filled.PhotoLibrary +import androidx.compose.material.icons.filled.Stop +import androidx.compose.material.icons.filled.Tune +import androidx.compose.material.icons.filled.UploadFile +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.FilterChip +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.IconButtonDefaults +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Slider +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextField +import androidx.compose.material3.TextFieldDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.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.input.KeyboardCapitalization +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 eu.llembas.android.R +import eu.llembas.android.api.AgentsSetting +import eu.llembas.android.api.LinkedDevice +import eu.llembas.android.assist.Recorder +import eu.llembas.android.lembas +import eu.llembas.android.ui.theme.LocalPalette +import kotlinx.coroutines.launch + +private val Field = RoundedCornerShape(28.dp) + +/** The agent modes, as the web page offers them, in the order of how much the model may do. */ +val AGENT_MODES = listOf("manual", "edit", "auto", "plan") + +@Composable +fun modeName(mode: String): String = when (mode) { + "manual" -> stringResource(R.string.mode_manual) + "edit" -> stringResource(R.string.mode_edit) + "auto" -> stringResource(R.string.mode_auto) + "plan" -> stringResource(R.string.mode_plan) + else -> mode.replaceFirstChar { it.uppercase() } +} + +/** A level's name: `off` and `default` in words, an effort as the model calls it. */ +@Composable +fun levelName(level: String): String = when (level) { + "off" -> stringResource(R.string.level_off) + "default" -> stringResource(R.string.level_default) + else -> level +} + +/** + * The words on the tune button: what is set, briefly ("Thinking · Plan", "high · Agents 1–4"), + * or nothing when all is as it starts. + */ +@Composable +fun tuneSummary(state: ChatState, agent: Boolean): String { + val parts = mutableListOf() + val info = state.modelInfo + val level = state.level + if (info != null && level != null) { + when (info.levelControl) { + "switch" -> if (level != "off") parts += stringResource(R.string.thinking) + "slider" -> parts += levelName(level) + } + } + val chat = state.chat + when { + agent || chat?.isAgent == true -> parts += modeName(chat?.mode?.ifBlank { null } ?: state.draft.agentMode) + (chat == null && state.draft.plan) || chat?.mode == "plan" -> parts += stringResource(R.string.mode_plan) + } + if (state.offersTeam(agent) && state.agents.max > 1) { + parts += stringResource(R.string.team_chip, state.agents.min.toString(), state.agents.max.toString()) + } + return parts.joinToString(" · ") +} + +/** + * The composer: one rounded field with the attachments above the words and the controls + * under them -- attach (+), the tune button (thinking, team, mode), the microphone, and Send, + * which becomes Stop while a reply is being written and nothing new is typed. The controls' + * row is a shared track: every icon keeps its 48 dp, the tune button's words give. + */ +@SuppressLint("MissingPermission") +@Composable +fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: () -> Unit, modifier: Modifier = Modifier, initial: String = "") { + val palette = LocalPalette.current + val context = LocalContext.current + val scope = rememberCoroutineScope() + var text by rememberSaveable { mutableStateOf(initial) } + var attachMenu by remember { mutableStateOf(false) } + var listening by remember { mutableStateOf(false) } + var photo by remember { mutableStateOf(null) } + val recorder = remember { Recorder(scope) } + val pickFiles = rememberLauncherForActivityResult(ActivityResultContracts.GetMultipleContents()) { actions.attach(it) } + val pickPhotos = rememberLauncherForActivityResult(ActivityResultContracts.PickMultipleVisualMedia()) { actions.attach(it) } + val takePhoto = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { taken -> + photo?.let { if (taken) actions.attach(listOf(it)) } + photo = null + } + val askMic = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + if (granted) { + recorder.start() + listening = true + } + } + // A message the server did not take comes back here, so nothing typed is lost. + LaunchedEffect(state.unsent) { + state.unsent?.let { + if (text.isBlank()) text = it + actions.clearUnsent() + } + } + // A suggestion from the empty chat lands here (a new value each tap). + LaunchedEffect(initial) { if (initial.isNotBlank()) text = initial } + val newAgent = agent && state.chat == null + val canSend = (text.isNotBlank() || state.pending.isNotEmpty()) && !state.uploading && (!newAgent || state.device != null) + val summary = tuneSummary(state, agent) + + Surface( + shape = Field, + color = palette.surfaceRaised, + border = BorderStroke(1.dp, palette.border), + modifier = modifier.fillMaxWidth(), + ) { + Column { + if (state.uploading) LinearProgressIndicator(Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 4.dp)) + if (state.pending.isNotEmpty()) { + Row( + Modifier.horizontalScroll(rememberScrollState()).padding(start = 12.dp, end = 12.dp, top = 12.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + state.pending.forEach { a -> + Box { + AttachmentTile(a, side = 64.dp) + Box( + Modifier + .align(Alignment.TopEnd) + .padding(2.dp) + .size(22.dp) + .clip(CircleShape) + .background(palette.ink) + .clickable { actions.unattach(a) }, + contentAlignment = Alignment.Center, + ) { + Icon( + Icons.Filled.Close, + contentDescription = stringResource(R.string.remove), + tint = palette.surface, + modifier = Modifier.size(14.dp), + ) + } + } + } + } + } + TextField( + value = text, + onValueChange = { text = it }, + placeholder = { + Text( + stringResource( + if (listening) { + R.string.listening + } else if (agent) { + R.string.composer_hint_agent + } else { + R.string.composer_hint + }, + ), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + }, + keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences), + colors = TextFieldDefaults.colors( + focusedContainerColor = Color.Transparent, + unfocusedContainerColor = Color.Transparent, + disabledContainerColor = Color.Transparent, + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent, + disabledIndicatorColor = Color.Transparent, + ), + textStyle = MaterialTheme.typography.bodyLarge, + maxLines = 8, + modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp), + ) + Row(Modifier.fillMaxWidth().padding(start = 4.dp, end = 6.dp, bottom = 4.dp), verticalAlignment = Alignment.CenterVertically) { + Box { + IconButton(onClick = { attachMenu = true }) { + Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.attach), tint = palette.inkMuted) + } + DropdownMenu(expanded = attachMenu, onDismissRequest = { attachMenu = false }) { + DropdownMenuItem( + leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) }, + text = { Text(stringResource(R.string.attach_take_photo)) }, + onClick = { + attachMenu = false + actions.photoTarget()?.also { photo = it }?.let { takePhoto.launch(it) } + }, + ) + DropdownMenuItem( + leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) }, + text = { Text(stringResource(R.string.attach_choose_photos)) }, + onClick = { + attachMenu = false + pickPhotos.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) + }, + ) + DropdownMenuItem( + leadingIcon = { Icon(Icons.Filled.UploadFile, contentDescription = null) }, + text = { Text(stringResource(R.string.attach_choose_files)) }, + onClick = { + attachMenu = false + pickFiles.launch("*/*") + }, + ) + } + } + // The tune button: the icon, and what is set in a few words. It sits in the one + // part of the row that gives, so the icons after it keep their place. + Box(Modifier.weight(1f), contentAlignment = Alignment.CenterStart) { + Surface( + onClick = onTune, + shape = RoundedCornerShape(50), + color = if (summary.isEmpty()) Color.Transparent else palette.accentSoft, + ) { + Row(Modifier.heightIn(min = 36.dp).padding(horizontal = 10.dp), verticalAlignment = Alignment.CenterVertically) { + Icon( + Icons.Filled.Tune, + contentDescription = stringResource(R.string.tune), + tint = if (summary.isEmpty()) palette.inkMuted else palette.accent, + modifier = Modifier.size(20.dp), + ) + if (summary.isNotEmpty()) { + Text( + summary, + style = MaterialTheme.typography.labelLarge, + color = palette.ink, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(start = 6.dp), + ) + } + } + } + } + IconButton(onClick = { + if (listening) { + listening = false + scope.launch { + val wav = recorder.stop() + if (wav.isNotEmpty()) { + runCatching { context.lembas.instances.client()?.transcribe(wav) } + .onSuccess { heard -> if (!heard.isNullOrBlank()) text = (text + " " + heard).trim() } + } + } + } else if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) { + recorder.start() + listening = true + } else { + askMic.launch(Manifest.permission.RECORD_AUDIO) + } + }) { + Icon( + if (listening) Icons.Filled.Stop else Icons.Filled.Mic, + contentDescription = stringResource(R.string.dictate), + tint = if (listening) palette.danger else palette.inkMuted, + ) + } + if (state.running && text.isBlank() && state.pending.isEmpty()) { + IconButton( + onClick = actions::stop, + colors = IconButtonDefaults.iconButtonColors(containerColor = palette.ink, contentColor = palette.surface), + ) { + Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop)) + } + } else { + IconButton( + enabled = canSend, + onClick = { + actions.send(text) + text = "" + }, + colors = IconButtonDefaults.iconButtonColors( + containerColor = palette.accent, + contentColor = palette.accentInk, + disabledContainerColor = palette.surfaceActive, + disabledContentColor = palette.inkFaint, + ), + ) { + Icon(Icons.Filled.ArrowUpward, contentDescription = stringResource(R.string.send)) + } + } + } + } + } +} + +// --- The tune sheet -------------------------------------------------------------------------- + +/** + * What can be tuned for this chat, and only what its model and kind offer: how hard the model + * thinks (a switch for on or off, choices for several levels), the team's size, and the mode + * (Plan first for a chat, the agent's mode for an agent chat). A new agent chat also chooses + * its device and folder here. + */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +fun TuneContent(state: ChatState, actions: ChatActions, agent: Boolean, modifier: Modifier = Modifier) { + val palette = LocalPalette.current + val chat = state.chat + val info = state.modelInfo + val level = state.level + val newAgent = agent && chat == null + var askDirectory by remember { mutableStateOf(false) } + Column(modifier.fillMaxWidth().padding(bottom = 24.dp)) { + Text(stringResource(R.string.tune), style = MaterialTheme.typography.titleLarge, modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp)) + + if (newAgent) { + TuneHeader(stringResource(R.string.agent_device)) + if (state.devices.isEmpty()) { + Text( + stringResource(R.string.agent_no_device), + style = MaterialTheme.typography.bodyMedium, + color = palette.inkMuted, + modifier = Modifier.padding(horizontal = 24.dp), + ) + } else { + DeviceChoices(state.devices, state.device) { id -> actions.updateDraft { it.copy(device = id) } } + } + TuneRow( + title = stringResource(R.string.agent_directory), + subtitle = state.draft.directory.ifBlank { stringResource(R.string.agent_directory_hint) }, + onClick = { askDirectory = true }, + leading = { Icon(Icons.Filled.Folder, contentDescription = null, tint = palette.inkMuted) }, + ) + } + + if (info != null && level != null) { + when (info.levelControl) { + "switch" -> TuneRow( + title = stringResource(R.string.thinking_switch), + subtitle = stringResource(R.string.thinking_switch_hint), + onClick = { pickLevel(actions, chat == null, if (level == "off") info.onLevel else "off") }, + trailing = { + Switch(checked = level != "off", onCheckedChange = { on -> pickLevel(actions, chat == null, if (on) info.onLevel else "off") }) + }, + ) + + "slider" -> { + TuneHeader(stringResource(R.string.effort)) + FlowRow(Modifier.padding(horizontal = 24.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + info.offered.forEach { option -> + FilterChip( + selected = option == level, + onClick = { pickLevel(actions, chat == null, option) }, + label = { Text(levelName(option)) }, + modifier = Modifier.heightIn(min = 48.dp), + ) + } + } + } + } + } + + if (state.offersTeam(agent)) { + TuneHeader(stringResource(R.string.team_agents)) + Text( + stringResource(R.string.team_hint), + style = MaterialTheme.typography.bodySmall, + color = palette.inkMuted, + modifier = Modifier.padding(horizontal = 24.dp), + ) + val now = state.agents + Column(Modifier.padding(horizontal = 24.dp)) { + AgentsSlider(stringResource(R.string.team_fewest), now.min) { v -> + setTeam(actions, chat == null, AgentsSetting(v, maxOf(v, now.max))) + } + AgentsSlider(stringResource(R.string.team_most), now.max) { v -> + setTeam(actions, chat == null, AgentsSetting(minOf(now.min, v), v)) + } + } + } + + when { + newAgent || chat?.isAgent == true -> { + TuneHeader(stringResource(R.string.agent_mode)) + val current = chat?.mode?.ifBlank { null } ?: if (chat == null) state.draft.agentMode else "edit" + FlowRow(Modifier.padding(horizontal = 24.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + AGENT_MODES.forEach { m -> + FilterChip( + selected = m == current, + onClick = { if (chat == null) actions.updateDraft { it.copy(agentMode = m) } else actions.change("mode", m) }, + label = { Text(modeName(m)) }, + modifier = Modifier.heightIn(min = 48.dp), + ) + } + } + } + + else -> { + val on = if (chat == null) state.draft.plan else chat.mode == "plan" + TuneRow( + title = stringResource(R.string.plan_first), + subtitle = stringResource(R.string.plan_first_hint), + onClick = { setPlan(actions, chat == null, !on) }, + trailing = { Switch(checked = on, onCheckedChange = { setPlan(actions, chat == null, it) }) }, + ) + } + } + } + + if (askDirectory) { + var typed by remember { mutableStateOf(state.draft.directory) } + androidx.compose.material3.AlertDialog( + onDismissRequest = { askDirectory = false }, + title = { Text(stringResource(R.string.agent_directory)) }, + text = { + OutlinedTextField( + value = typed, + onValueChange = { typed = it }, + singleLine = true, + placeholder = { Text(stringResource(R.string.agent_directory_hint)) }, + modifier = Modifier.fillMaxWidth(), + ) + }, + confirmButton = { + androidx.compose.material3.TextButton(onClick = { + actions.updateDraft { it.copy(directory = typed.trim()) } + askDirectory = false + }) { Text(stringResource(R.string.save)) } + }, + dismissButton = { androidx.compose.material3.TextButton(onClick = { askDirectory = false }) { Text(stringResource(R.string.cancel)) } }, + ) + } +} + +private fun pickLevel(actions: ChatActions, draft: Boolean, level: String) { + if (draft) actions.updateDraft { it.copy(effort = level) } else actions.change("effort", level) +} + +private fun setTeam(actions: ChatActions, draft: Boolean, agents: AgentsSetting) { + if (draft) actions.updateDraft { it.copy(agents = agents) } else actions.setAgents(agents) +} + +private fun setPlan(actions: ChatActions, draft: Boolean, on: Boolean) { + if (draft) actions.updateDraft { it.copy(plan = on) } else actions.change("mode", if (on) "plan" else "") +} + +@Composable +private fun TuneHeader(text: String) { + Text( + text, + style = MaterialTheme.typography.labelLarge, + color = LocalPalette.current.accent, + modifier = Modifier.padding(start = 24.dp, end = 24.dp, top = 20.dp, bottom = 8.dp), + ) +} + +/** A row of the sheet: words that give, and a control that keeps its size. */ +@Composable +private fun TuneRow( + title: String, + subtitle: String? = null, + onClick: () -> Unit, + leading: (@Composable () -> Unit)? = null, + trailing: (@Composable () -> Unit)? = null, +) { + val palette = LocalPalette.current + Row( + Modifier.fillMaxWidth().clickable(onClick = onClick).heightIn(min = 64.dp).padding(horizontal = 24.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (leading != null) { + leading() + Spacer(Modifier.width(16.dp)) + } + Column(Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.bodyLarge) + subtitle?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) } + } + if (trailing != null) { + Spacer(Modifier.width(16.dp)) + trailing() + } + } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun DeviceChoices(devices: List, current: LinkedDevice?, onPick: (String) -> Unit) { + FlowRow(Modifier.padding(horizontal = 24.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + devices.forEach { d -> + FilterChip( + selected = d.id == current?.id, + onClick = { onPick(d.id) }, + label = { Text(listOf(d.name, d.host).filter { it.isNotBlank() }.distinct().joinToString(" · "), maxLines = 1) }, + modifier = Modifier.heightIn(min = 48.dp), + ) + } + } +} + +/** + * One end of the team's size: its label and value on a row of their own, so the two sliders + * line up whatever the words, and the slider under them. + */ +@Composable +fun AgentsSlider(label: String, value: Int, onChange: (Int) -> Unit) { + var shown by remember(value) { mutableStateOf(value.toFloat()) } + Column(Modifier.padding(top = 8.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(label, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.weight(1f)) + Text(Math.round(shown).toString(), style = MaterialTheme.typography.titleMedium, modifier = Modifier.width(40.dp), textAlign = TextAlign.End) + } + Slider( + value = shown, + onValueChange = { shown = it }, + onValueChangeFinished = { onChange(Math.round(shown).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/ModelPicker.kt b/app/src/main/java/eu/llembas/android/ui/chat/ModelPicker.kt new file mode 100644 index 0000000..1288885 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/chat/ModelPicker.kt @@ -0,0 +1,136 @@ +package eu.llembas.android.ui.chat + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ArrowDropDown +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import eu.llembas.android.R +import eu.llembas.android.api.ModelInfo +import eu.llembas.android.ui.ModelAvatar +import eu.llembas.android.ui.theme.LocalPalette + +/** A context window in the way people say it: 8K, 128K, 1M. */ +fun compactContext(tokens: Int): String = when { + tokens >= 1_000_000 && tokens % 1_000_000 == 0 -> "${tokens / 1_000_000}M" + tokens >= 1_000_000 -> "%.1fM".format(tokens / 1_000_000.0) + else -> "${Math.round(tokens / 1024.0)}K" +} + +/** What a model can do, in a few words for the picker: sees images, uses tools, its window. */ +@Composable +fun modelNotes(model: ModelInfo): String = buildList { + if (model.vision) add(stringResource(R.string.model_sees_images)) + if (model.tools) add(stringResource(R.string.model_uses_tools)) + if (model.context > 0) add(stringResource(R.string.model_context, compactContext(model.context))) +}.joinToString(" · ") + +/** How the model thinks, for the picker: a switch, or its levels by name; null for one level. */ +@Composable +fun modelLevels(model: ModelInfo): String? = when (model.levelControl) { + "switch" -> stringResource(R.string.model_thinking_switchable) + "slider" -> stringResource(R.string.model_levels, model.offered.map { levelName(it) }.joinToString(", ")) + else -> null +} + +/** + * The top bar's title: the model's picture and name, and a caret that says it opens; under it, + * smaller, the chat's title once it has one. The name gives before the caret does. + */ +@Composable +fun ModelTitle(model: ModelInfo?, fallback: String, subtitle: String?, onClick: () -> Unit) { + val palette = LocalPalette.current + Surface(onClick = onClick, shape = RoundedCornerShape(12.dp), color = Color.Transparent) { + Row(Modifier.heightIn(min = 48.dp).padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically) { + ModelAvatar(model, fallback, size = 28.dp) + Spacer(Modifier.width(10.dp)) + Column(Modifier.weight(1f, fill = false)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + model?.name?.ifBlank { null } ?: fallback, + style = MaterialTheme.typography.titleMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false), + ) + Icon(Icons.Filled.ArrowDropDown, contentDescription = stringResource(R.string.model_choose), tint = palette.inkMuted) + } + subtitle?.let { + Text(it, style = MaterialTheme.typography.labelMedium, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + } + } +} + +/** + * The model picker (a bottom sheet's content): each model with its picture, its name, what it + * can do and how it thinks; the one in use is ticked. Rows are at least 72 dp and their words + * wrap rather than overflow. + */ +@Composable +fun ModelPickerContent(models: List, current: String?, onPick: (String) -> Unit, modifier: Modifier = Modifier) { + val palette = LocalPalette.current + Column(modifier.fillMaxWidth()) { + Text( + stringResource(R.string.model_choose), + style = MaterialTheme.typography.titleLarge, + modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp), + ) + LazyColumn(Modifier.fillMaxWidth().padding(bottom = 16.dp)) { + items(models, key = { it.id }) { m -> + val chosen = m.id == current + Row( + Modifier + .fillMaxWidth() + .clickable { onPick(m.id) } + .heightIn(min = 72.dp) + .padding(horizontal = 24.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + ModelAvatar(m, m.id, size = 44.dp) + Spacer(Modifier.width(16.dp)) + Column(Modifier.weight(1f)) { + Text(m.name.ifBlank { m.id }, style = MaterialTheme.typography.titleMedium) + modelNotes(m).takeIf { it.isNotEmpty() }?.let { + Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) + } + modelLevels(m)?.let { + Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint) + } + } + if (chosen) { + Spacer(Modifier.width(12.dp)) + Icon( + Icons.Filled.CheckCircle, + contentDescription = stringResource(R.string.model_in_use), + tint = palette.accent, + modifier = Modifier.size(24.dp), + ) + } + } + } + } + } +} diff --git a/app/src/main/java/eu/llembas/android/ui/chat/Transcript.kt b/app/src/main/java/eu/llembas/android/ui/chat/Transcript.kt new file mode 100644 index 0000000..a2dad48 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/chat/Transcript.kt @@ -0,0 +1,556 @@ +package eu.llembas.android.ui.chat + +import android.content.Context +import android.graphics.BitmapFactory +import android.util.LruCache +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.core.RepeatMode +import androidx.compose.animation.core.animateFloat +import androidx.compose.animation.core.infiniteRepeatable +import androidx.compose.animation.core.rememberInfiniteTransition +import androidx.compose.animation.core.tween +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.Description +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.ExpandLess +import androidx.compose.material.icons.filled.ExpandMore +import androidx.compose.material.icons.filled.Image +import androidx.compose.material.icons.filled.Psychology +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material.icons.filled.SelectAll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +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.res.stringResource +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import eu.llembas.android.R +import eu.llembas.android.api.Attachment +import eu.llembas.android.api.Message +import eu.llembas.android.api.ShowCard +import eu.llembas.android.api.Step +import eu.llembas.android.api.ToolCall +import eu.llembas.android.lembas +import eu.llembas.android.ui.MarkdownText +import eu.llembas.android.ui.Segment +import eu.llembas.android.ui.splitFences +import eu.llembas.android.ui.theme.LocalPalette +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** Copies a text to the clipboard (and says so where Android does not). Provided by the chat. */ +val LocalCopy = compositionLocalOf<(String) -> Unit> { {} } + +private val Bubble = RoundedCornerShape(topStart = 20.dp, topEnd = 6.dp, bottomStart = 20.dp, bottomEnd = 20.dp) +private val Block = RoundedCornerShape(12.dp) +private val Pill = RoundedCornerShape(50) + +/** + * The person's turn: their words in a bubble on the right (never markdown), what they attached + * above it as thumbnails. A long press offers Copy and, where the turn can still change, Edit. + */ +@OptIn(ExperimentalFoundationApi::class) +@Composable +fun UserMessage(message: Message, canEdit: Boolean, onEdit: () -> Unit, modifier: Modifier = Modifier) { + val palette = LocalPalette.current + val copy = LocalCopy.current + var menu by remember { mutableStateOf(false) } + Column(modifier.fillMaxWidth().padding(start = 48.dp), horizontalAlignment = Alignment.End) { + if (message.attachments.isNotEmpty()) { + Row( + Modifier.horizontalScroll(rememberScrollState()).padding(bottom = 8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + message.attachments.forEach { AttachmentTile(it, side = 96.dp) } + } + } + if (!message.text.isNullOrBlank()) { + Box { + Text( + message.text, + color = palette.ink, + style = MaterialTheme.typography.bodyLarge, + modifier = Modifier + .clip(Bubble) + .background(palette.bubbleUser) + .combinedClickable(onClick = {}, onLongClick = { menu = true }) + .padding(horizontal = 16.dp, vertical = 10.dp), + ) + DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { + DropdownMenuItem( + leadingIcon = { Icon(Icons.Filled.ContentCopy, contentDescription = null) }, + text = { Text(stringResource(R.string.copy_message)) }, + onClick = { + menu = false + copy(message.text) + }, + ) + if (canEdit) { + DropdownMenuItem( + leadingIcon = { Icon(Icons.Filled.Edit, contentDescription = null) }, + text = { Text(stringResource(R.string.edit)) }, + onClick = { + menu = false + onEdit() + }, + ) + } + } + } + } + if (message.queued) { + Text( + stringResource(R.string.queued), + style = MaterialTheme.typography.labelSmall, + color = palette.inkFaint, + modifier = Modifier.padding(top = 4.dp, end = 4.dp), + ) + } + } +} + +/** + * The model's turn, full width and without a bubble: its steps (thinking and tools folded into + * chips that open), its words as markdown, and under it Copy, Regenerate and what it cost. While + * it is being written, a quiet pulse says so. A long press on the words offers the same, and + * Select text. + */ +@Composable +fun AssistantMessage( + message: Message, + steps: List, + writing: Boolean, + canRegenerate: Boolean, + onRegenerate: () -> Unit, + onShow: ((ShowCard) -> Unit)?, + modifier: Modifier = Modifier, +) { + val palette = LocalPalette.current + val copy = LocalCopy.current + var menu by remember { mutableStateOf(false) } + var selecting by remember { mutableStateOf(false) } + val words = replyText(message.copy(steps = steps)) + Column(modifier.fillMaxWidth()) { + Box { + StepsCompact(steps, onShow = onShow, onLongPress = { menu = true }) + DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { + DropdownMenuItem( + leadingIcon = { Icon(Icons.Filled.ContentCopy, contentDescription = null) }, + text = { Text(stringResource(R.string.copy_message)) }, + onClick = { + menu = false + copy(words) + }, + ) + DropdownMenuItem( + leadingIcon = { Icon(Icons.Filled.SelectAll, contentDescription = null) }, + text = { Text(stringResource(R.string.select_text)) }, + onClick = { + menu = false + selecting = true + }, + ) + if (canRegenerate) { + DropdownMenuItem( + leadingIcon = { Icon(Icons.Filled.Refresh, contentDescription = null) }, + text = { Text(stringResource(R.string.regenerate)) }, + onClick = { + menu = false + onRegenerate() + }, + ) + } + } + } + if (writing) { + Writing(Modifier.padding(top = if (steps.isEmpty()) 0.dp else 8.dp), withLine = steps.isEmpty()) + } else { + message.error?.let { + Text(it, color = palette.danger, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(top = 8.dp)) + } + // The actions and the foot share one row: the icons keep their 48 dp, the foot gives. + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 2.dp)) { + if (words.isNotBlank()) { + IconButton(onClick = { copy(words) }) { + Icon( + Icons.Filled.ContentCopy, + contentDescription = stringResource(R.string.copy_message), + tint = palette.inkFaint, + modifier = Modifier.size(18.dp), + ) + } + } + if (canRegenerate) { + IconButton(onClick = onRegenerate) { + Icon( + Icons.Filled.Refresh, + contentDescription = stringResource(R.string.regenerate), + tint = palette.inkFaint, + modifier = Modifier.size(20.dp), + ) + } + } + footLine(message)?.let { line -> + Text( + line, + style = MaterialTheme.typography.labelSmall, + color = palette.inkFaint, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f).padding(start = 4.dp), + ) + } + } + } + } + if (selecting) { + AlertDialog( + onDismissRequest = { selecting = false }, + confirmButton = { TextButton(onClick = { selecting = false }) { Text(stringResource(R.string.close)) } }, + text = { + SelectionContainer(Modifier.heightIn(max = 480.dp).verticalScroll(rememberScrollState())) { + Text(words, style = MaterialTheme.typography.bodyMedium) + } + }, + ) + } +} + +/** A reply's own words, as the person would copy them: its text steps, in order. */ +fun replyText(message: Message): String = + message.steps.filter { it.kind == "text" }.mapNotNull { it.markdown }.joinToString("\n\n").ifBlank { message.text.orEmpty() } + +/** What a finished reply cost, in one quiet line: model, tokens, speed. Null when nothing was counted. */ +private fun footLine(message: Message): String? { + val m = message.metrics ?: return message.model + if (m.completionTokens == 0 && m.elapsedMs == 0L) return message.model + return buildList { + message.model?.let { add(it) } + if (m.completionTokens > 0) add("${if (m.estimated) "~" else ""}${m.completionTokens} tok") + if (m.tokPerSecond > 0) add("${"%.1f".format(m.tokPerSecond)} tok/s") + }.joinToString(" · ").ifBlank { null } +} + +/** Three dots that breathe, and (before the first word) the loading line beside them. */ +@Composable +fun Writing(modifier: Modifier = Modifier, withLine: Boolean = false) { + val palette = LocalPalette.current + val pulse = rememberInfiniteTransition(label = "writing") + Row(modifier.heightIn(min = 32.dp), verticalAlignment = Alignment.CenterVertically) { + repeat(3) { i -> + val alpha by pulse.animateFloat( + initialValue = 0.25f, + targetValue = 1f, + animationSpec = infiniteRepeatable(tween(600, delayMillis = i * 150), RepeatMode.Reverse), + label = "dot$i", + ) + Box(Modifier.padding(end = 4.dp).size(8.dp).alpha(alpha).clip(CircleShape).background(palette.accent)) + } + if (withLine) { + Text( + stringResource(R.string.loading_line), + color = palette.inkFaint, + style = MaterialTheme.typography.bodyMedium, + modifier = Modifier.padding(start = 8.dp), + ) + } + } +} + +/** + * A reply's steps in the order they happened. Prose is markdown; thinking and each round of + * tools are one chip that opens; a `show` card stays in view, because it is something put in + * front of the person. + */ +@Composable +fun StepsCompact(steps: List, modifier: Modifier = Modifier, onShow: ((ShowCard) -> Unit)? = null, onLongPress: (() -> Unit)? = null) { + Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) { + steps.forEach { step -> + when (step.kind) { + "thinking" -> ThinkingChip(step) + "text" -> RichMarkdown(step.markdown.orEmpty(), onLongPress = onLongPress) + "tools" -> ToolsChip(step, onShow) + "steer" -> step.messages.forEach { Steered(it.text) } + } + } + } +} + +/** Markdown with its fenced code taken out into [CodeBlock]s, each with its own Copy. */ +@Composable +fun RichMarkdown(markdown: String, modifier: Modifier = Modifier, onLongPress: (() -> Unit)? = null) { + val segments = remember(markdown) { splitFences(markdown) } + Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp)) { + segments.forEach { segment -> + when (segment) { + is Segment.Prose -> MarkdownText(segment.markdown, modifier = Modifier.fillMaxWidth(), onLongPress = onLongPress) + is Segment.Code -> CodeBlock(segment.language, segment.code) + } + } + } +} + +/** A code block: its language and Copy above, the code below in its own sideways scroller. */ +@Composable +fun CodeBlock(language: String, code: String, modifier: Modifier = Modifier) { + val palette = LocalPalette.current + val copy = LocalCopy.current + Column(modifier.fillMaxWidth().clip(Block).background(palette.codeBg).border(1.dp, palette.codeBorder, Block)) { + Row(Modifier.fillMaxWidth().padding(start = 14.dp), verticalAlignment = Alignment.CenterVertically) { + Text( + language.ifBlank { stringResource(R.string.code) }, + style = MaterialTheme.typography.labelMedium, + color = palette.inkFaint, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + IconButton(onClick = { copy(code) }) { + Icon( + Icons.Filled.ContentCopy, + contentDescription = stringResource(R.string.copy_code), + tint = palette.inkMuted, + modifier = Modifier.size(18.dp), + ) + } + } + HorizontalDivider(color = palette.codeBorder) + Text( + code, + fontFamily = FontFamily.Monospace, + fontSize = 13.sp, + lineHeight = 19.sp, + color = palette.ink, + softWrap = false, + modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(14.dp), + ) + } +} + +/** A chip that opens: the icon, one line, and a chevron; [content] below when open. */ +@Composable +private fun FoldChip( + open: Boolean, + onToggle: () -> Unit, + leading: @Composable () -> Unit, + label: String, + monospace: Boolean = false, + tint: androidx.compose.ui.graphics.Color? = null, + content: @Composable () -> Unit, +) { + val palette = LocalPalette.current + Column(Modifier.fillMaxWidth()) { + Surface(onClick = onToggle, shape = Pill, color = palette.surfaceRaised, border = androidx.compose.foundation.BorderStroke(1.dp, palette.border)) { + Row(Modifier.padding(start = 10.dp, end = 8.dp, top = 6.dp, bottom = 6.dp), verticalAlignment = Alignment.CenterVertically) { + Box(Modifier.size(18.dp), contentAlignment = Alignment.Center) { leading() } + Spacer(Modifier.width(8.dp)) + Text( + label, + style = MaterialTheme.typography.labelLarge, + fontFamily = if (monospace) FontFamily.Monospace else null, + color = tint ?: palette.inkMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false), + ) + Icon( + if (open) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, + contentDescription = null, + tint = palette.inkFaint, + modifier = Modifier.padding(start = 4.dp).size(18.dp), + ) + } + } + AnimatedVisibility(open) { Box(Modifier.padding(top = 8.dp)) { content() } } + } +} + +@Composable +private fun ThinkingChip(step: Step) { + val palette = LocalPalette.current + var open by rememberSaveable(step.index, step.open) { mutableStateOf(false) } + val label = if (step.open) stringResource(R.string.thinking) + "…" else stringResource(R.string.thought) + (step.label?.let { " $it" } ?: "") + FoldChip( + open = open, + onToggle = { open = !open }, + leading = { Icon(Icons.Filled.Psychology, contentDescription = null, tint = palette.inkFaint, modifier = Modifier.size(18.dp)) }, + label = label, + ) { + Row(Modifier.fillMaxWidth().heightIn(min = 24.dp)) { + Box(Modifier.width(2.dp).heightIn(min = 24.dp).background(palette.border)) + Text( + step.text.orEmpty(), + style = MaterialTheme.typography.bodySmall, + color = palette.inkMuted, + modifier = Modifier.padding(start = 12.dp), + ) + } + } +} + +/** + * One round of tools as one chip: a single call by its title ("bake --slow"), several by their + * count. Open, each call is its block (command, change, output). A `show` card is drawn apart, + * always in view. + */ +@Composable +private fun ToolsChip(step: Step, onShow: ((ShowCard) -> Unit)?) { + val palette = LocalPalette.current + val (shows, calls) = step.calls.partition { it.show != null && it.status != "error" && it.error.isNullOrEmpty() } + if (calls.isNotEmpty()) { + var open by rememberSaveable(step.index, calls.firstOrNull()?.id) { mutableStateOf(false) } + val failed = calls.any { it.status == "error" || !it.error.isNullOrEmpty() } + val running = calls.any { it.status == "running" || it.status == "pending" } + val single = calls.singleOrNull() + val label = single?.let { it.block.title.ifBlank { it.name } } ?: stringResource(R.string.tools_used, calls.size.toString()) + FoldChip( + open = open, + onToggle = { open = !open }, + leading = { + if (running) { + CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(14.dp)) + } else { + Icon( + iconFor(single?.block?.kind ?: "tool"), + contentDescription = null, + tint = if (failed) palette.danger else palette.inkFaint, + modifier = Modifier.size(18.dp), + ) + } + }, + label = label, + monospace = single?.block?.kind == "shell", + tint = if (failed) palette.danger else null, + ) { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { calls.forEach { ToolCallBlock(it, onShow = onShow) } } + } + } + shows.forEach { call -> ToolCallBlock(call, onShow = onShow) } +} + +@Composable +private fun Steered(text: String) { + val palette = LocalPalette.current + Text("↳ $text", style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, modifier = Modifier.padding(start = 24.dp)) +} + +// --- Attachments --------------------------------------------------------------------------- + +/** + * Attached pictures, fetched once with the token and kept small in memory; a picture that could + * not be read is not asked for again until the app starts anew. + */ +private object Thumbnails { + private const val SIDE = 320 + private val cache = LruCache(32) + private val failed = mutableSetOf() + + fun cached(id: String): ImageBitmap? = cache.get(id) + + suspend fun load(context: Context, id: String): ImageBitmap? { + cache.get(id)?.let { return it } + if (id in failed) return null + val api = context.lembas.instances.client() ?: return null + val bytes = runCatching { api.attachmentBytes(id) }.getOrNull() + val image = bytes?.let { decode(it) } + if (image == null) failed += id else cache.put(id, image) + return image + } + + 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 + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })?.asImageBitmap() + } +} + +/** + * An attachment as a square tile of [side]: a picture as its thumbnail, anything else as its + * kind's icon and its name. The tile's size is fixed, so a row of them lines up whatever the + * names. + */ +@Composable +fun AttachmentTile(attachment: Attachment, side: Dp, modifier: Modifier = Modifier) { + val palette = LocalPalette.current + val context = LocalContext.current + Box(modifier.size(side).clip(Block).background(palette.surfaceRaised).border(1.dp, palette.border, Block), contentAlignment = Alignment.Center) { + if (attachment.image) { + var image by remember(attachment.id) { mutableStateOf(Thumbnails.cached(attachment.id)) } + LaunchedEffect(attachment.id) { if (image == null) image = Thumbnails.load(context, attachment.id) } + val shown = image + if (shown != null) { + Image(shown, contentDescription = attachment.name, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize()) + } else { + Icon(Icons.Filled.Image, contentDescription = attachment.name, tint = palette.inkFaint) + } + } else { + Column(Modifier.padding(8.dp), horizontalAlignment = Alignment.CenterHorizontally) { + Icon(Icons.Filled.Description, contentDescription = null, tint = palette.inkMuted) + Spacer(Modifier.height(4.dp)) + Text( + attachment.name, + style = MaterialTheme.typography.labelSmall, + color = palette.inkMuted, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = side - 16.dp), + ) + } + } + } +} diff --git a/app/src/main/java/eu/llembas/android/ui/chats/ChatsScreen.kt b/app/src/main/java/eu/llembas/android/ui/chats/ChatsScreen.kt deleted file mode 100644 index 8eb48a3..0000000 --- a/app/src/main/java/eu/llembas/android/ui/chats/ChatsScreen.kt +++ /dev/null @@ -1,264 +0,0 @@ -@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) - -package eu.llembas.android.ui.chats - -import android.app.Application -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.Chat -import androidx.compose.material.icons.filled.Add -import androidx.compose.material.icons.filled.Folder -import androidx.compose.material.icons.filled.Settings -import androidx.compose.material.icons.filled.Terminal -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExtendedFloatingActionButton -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.PrimaryTabRow -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SwipeToDismissBox -import androidx.compose.material3.Tab -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.material3.pulltorefresh.PullToRefreshBox -import androidx.compose.material3.rememberSwipeToDismissBoxState -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.lifecycle.AndroidViewModel -import androidx.lifecycle.compose.LifecycleResumeEffect -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.compose.viewModel -import eu.llembas.android.R -import eu.llembas.android.api.Chat -import eu.llembas.android.api.Doorstep -import eu.llembas.android.api.fit -import eu.llembas.android.lembas -import eu.llembas.android.ui.explain -import eu.llembas.android.ui.signin.refusal -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.launch -import kotlinx.serialization.json.buildJsonObject -import kotlinx.serialization.json.put - -data class ChatsState(val chats: List = emptyList(), val more: Boolean = false, val loading: Boolean = false, val error: String? = null) - -class ChatsViewModel(app: Application) : AndroidViewModel(app) { - private val _state = MutableStateFlow(ChatsState()) - val state = _state.asStateFlow() - private var kind = "chat" - - /** Why this instance is refused, once it was asked what it is; null while it fits. */ - private var refused: Int? = null - private var checked = false - - /** - * Read the list. [quiet] is the reload on coming back to the screen: the rows already shown - * stay without a spinner, and only a change replaces them. - */ - fun load(kind: String, quiet: Boolean = false) { - val switched = kind != this.kind - this.kind = kind - viewModelScope.launch { - _state.update { it.copy(loading = !quiet || switched, error = null, chats = if (switched) emptyList() else it.chats) } - try { - val api = getApplication().lembas.instances.client() ?: return@launch - // An instance signed in to before it was downgraded, or by 0.1 against a 1.x - // server, is refused here as at sign-in. Unreachable is not refused: the chat - // list's own error says that better. - if (!checked) { - runCatching { Doorstep().discover(api.base) }.onSuccess { - checked = true - refused = refusal(fit(it)) - } - } - refused?.let { said -> - _state.value = ChatsState(error = getApplication().getString(said)) - return@launch - } - val page = api.chats(kind = kind) - _state.value = ChatsState(chats = page.chats, more = page.more) - } catch (e: Exception) { - _state.update { it.copy(loading = false, error = getApplication().explain(e)) } - } - } - } - - fun more() { - val last = _state.value.chats.lastOrNull() ?: return - viewModelScope.launch { - try { - val api = getApplication().lembas.instances.client() ?: return@launch - val page = api.chats(kind = kind, before = last.id) - _state.update { it.copy(chats = it.chats + page.chats, more = page.more) } - } catch (e: Exception) { - _state.update { it.copy(error = getApplication().explain(e)) } - } - } - } - - /** Out of the way, and reversible: the web UI's Archive. */ - fun archive(chat: Chat) { - _state.update { s -> s.copy(chats = s.chats.filterNot { it.id == chat.id }) } - viewModelScope.launch { - runCatching { - getApplication().lembas.instances.client() - ?.updateChat(chat.id, buildJsonObject { put("archived", true) }) - }.onFailure { e -> - _state.update { it.copy(error = getApplication().explain(e)) } - load(kind) - } - } - } -} - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun ChatsScreen( - onOpen: (String) -> Unit, - onNew: () -> Unit, - onNewAgent: () -> Unit, - onSettings: () -> Unit, - onFiles: () -> Unit, - model: ChatsViewModel = viewModel(), -) { - val state by model.state.collectAsStateWithLifecycle() - var tab by rememberSaveable { mutableIntStateOf(0) } - val kind = if (tab == 0) "chat" else "agent" - // Read again each time the list comes back into view -- from a chat, from another app -- - // so a new chat, a new title or a finished reply's dot is there without a pull. - var shown by remember { mutableStateOf(false) } - LifecycleResumeEffect(kind) { - model.load(kind, quiet = shown) - shown = true - onPauseOrDispose { } - } - - Scaffold( - topBar = { - TopAppBar( - title = { Text(stringResource(R.string.app_name)) }, - actions = { - IconButton(onClick = onFiles) { - Icon(Icons.Filled.Folder, contentDescription = stringResource(R.string.files)) - } - IconButton(onClick = onSettings) { - Icon(Icons.Filled.Settings, contentDescription = stringResource(R.string.settings)) - } - }, - ) - }, - floatingActionButton = { - ExtendedFloatingActionButton( - onClick = if (tab == 0) onNew else onNewAgent, - icon = { Icon(Icons.Filled.Add, contentDescription = null) }, - text = { Text(stringResource(if (tab == 0) R.string.new_chat else R.string.new_agent_chat)) }, - ) - }, - ) { padding -> - Column(Modifier.padding(padding).fillMaxSize()) { - PrimaryTabRow(selectedTabIndex = tab) { - Tab(selected = tab == 0, onClick = { tab = 0 }, text = { Text(stringResource(R.string.tab_chats)) }) - Tab(selected = tab == 1, onClick = { tab = 1 }, text = { Text(stringResource(R.string.tab_agents)) }) - } - state.error?.let { - Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp, top = 8.dp), verticalAlignment = Alignment.CenterVertically) { - // The sentence gives; the button keeps its size. - Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.weight(1f)) - TextButton(onClick = { model.load(kind) }) { Text(stringResource(R.string.retry)) } - } - } - PullToRefreshBox(isRefreshing = state.loading, onRefresh = { model.load(kind) }, modifier = Modifier.fillMaxSize()) { - if (state.chats.isEmpty() && !state.loading && state.error == null) { - Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { - Text( - stringResource(if (tab == 0) R.string.empty_chats else R.string.empty_agents), - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(32.dp), - ) - } - } - LazyColumn(Modifier.fillMaxSize()) { - items(state.chats, key = { it.id }) { chat -> - ChatRow(chat, onOpen = { onOpen(chat.id) }, onArchive = { model.archive(chat) }) - HorizontalDivider() - } - if (state.more) { - item { - LaunchedEffect(state.chats.size) { model.more() } - } - } - } - } - } - } -} - -@Composable -private fun ChatRow(chat: Chat, onOpen: () -> Unit, onArchive: () -> Unit) { - val swipe = rememberSwipeToDismissBoxState() - SwipeToDismissBox(state = swipe, onDismiss = { onArchive() }, backgroundContent = { - Box( - Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surfaceContainerHigh).padding(horizontal = 24.dp), - contentAlignment = Alignment.CenterStart, - ) { - Text(stringResource(R.string.archive), color = MaterialTheme.colorScheme.onSurfaceVariant) - } - }) { - ListItem( - modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen), - leadingContent = { - Icon( - if (chat.isAgent) Icons.Filled.Terminal else Icons.AutoMirrored.Filled.Chat, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - }, - headlineContent = { Text(chat.title.ifBlank { stringResource(R.string.new_chat) }, maxLines = 1, overflow = TextOverflow.Ellipsis) }, - supportingContent = { - val line = listOfNotNull(chat.model.ifBlank { null }, chat.device?.directory?.ifBlank { null }).joinToString(" · ") - if (line.isNotEmpty()) Text(line, maxLines = 1, overflow = TextOverflow.Ellipsis) - }, - trailingContent = { - Row(verticalAlignment = Alignment.CenterVertically) { - if (chat.unread || chat.running) { - Box( - Modifier.size(10.dp).clip(CircleShape).background( - if (chat.running) MaterialTheme.colorScheme.secondary else MaterialTheme.colorScheme.primary, - ), - ) - } - } - }, - ) - } -} diff --git a/app/src/main/java/eu/llembas/android/ui/home/ChatGroups.kt b/app/src/main/java/eu/llembas/android/ui/home/ChatGroups.kt new file mode 100644 index 0000000..6e3368a --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/home/ChatGroups.kt @@ -0,0 +1,31 @@ +package eu.llembas.android.ui.home + +import eu.llembas.android.api.Chat +import java.time.LocalDate +import java.time.OffsetDateTime +import java.time.ZoneId + +/** + * The drawer's list in its sections: the chats of today, the earlier ones, and the agent chats + * (which run on a linked computer) on their own. Each keeps the server's order, newest first. + */ +data class ChatGroups(val today: List = emptyList(), val earlier: List = emptyList(), val agents: List = emptyList()) { + val isEmpty: Boolean get() = today.isEmpty() && earlier.isEmpty() && agents.isEmpty() +} + +/** The day a chat was last written in, where the phone is; null when the server did not say. */ +fun Chat.day(zone: ZoneId): LocalDate? = (updatedAt ?: createdAt)?.let { stamp -> + runCatching { OffsetDateTime.parse(stamp).atZoneSameInstant(zone).toLocalDate() }.getOrNull() +} + +/** + * Split [chats] for the drawer, keeping those whose title holds [query] (any case; blank keeps + * all). A chat without a date counts as earlier. + */ +fun groupChats(chats: List, query: String, today: LocalDate, zone: ZoneId): ChatGroups { + val wanted = query.trim() + val shown = if (wanted.isEmpty()) chats else chats.filter { it.title.contains(wanted, ignoreCase = true) } + val (agents, plain) = shown.partition { it.isAgent } + val (now, before) = plain.partition { it.day(zone) == today } + return ChatGroups(today = now, earlier = before, agents = agents) +} diff --git a/app/src/main/java/eu/llembas/android/ui/home/Drawer.kt b/app/src/main/java/eu/llembas/android/ui/home/Drawer.kt new file mode 100644 index 0000000..4eec594 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/home/Drawer.kt @@ -0,0 +1,311 @@ +package eu.llembas.android.ui.home + +import android.app.Application +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListScope +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.filled.Archive +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.EditNote +import androidx.compose.material.icons.filled.Folder +import androidx.compose.material.icons.filled.Schedule +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material.icons.filled.Terminal +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalDrawerSheet +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TextField +import androidx.compose.material3.TextFieldDefaults +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.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.graphics.vector.ImageVector +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.viewModelScope +import eu.llembas.android.R +import eu.llembas.android.api.Chat +import eu.llembas.android.api.Doorstep +import eu.llembas.android.api.fit +import eu.llembas.android.lembas +import eu.llembas.android.ui.explain +import eu.llembas.android.ui.signin.refusal +import eu.llembas.android.ui.theme.LocalPalette +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import java.time.LocalDate +import java.time.ZoneId + +data class ChatsState(val chats: List = emptyList(), val more: Boolean = false, val loading: Boolean = false, val error: String? = null) + +/** The drawer's list: every chat of the instance in use, both kinds, newest first. */ +class ChatsViewModel(app: Application) : AndroidViewModel(app) { + private val _state = MutableStateFlow(ChatsState()) + val state = _state.asStateFlow() + + /** Why this instance is refused, once it was asked what it is; null while it fits. */ + private var refused: Int? = null + private var checked = false + + /** Read the list; the rows already shown stay while it is read again. */ + fun load() { + viewModelScope.launch { + _state.update { it.copy(loading = true, error = null) } + try { + val api = getApplication().lembas.instances.client() ?: return@launch + // An instance signed in to before it was downgraded is refused here as at + // sign-in. Unreachable is not refused: the list's own error says that better. + if (!checked) { + runCatching { Doorstep().discover(api.base) }.onSuccess { + checked = true + refused = refusal(fit(it)) + } + } + refused?.let { said -> + _state.value = ChatsState(error = getApplication().getString(said)) + return@launch + } + val page = api.chats() + _state.value = ChatsState(chats = page.chats, more = page.more) + } catch (e: Exception) { + _state.update { it.copy(loading = false, error = getApplication().explain(e)) } + } + } + } + + fun more() { + val last = _state.value.chats.lastOrNull() ?: return + viewModelScope.launch { + try { + val api = getApplication().lembas.instances.client() ?: return@launch + val page = api.chats(before = last.id) + _state.update { it.copy(chats = it.chats + page.chats, more = page.more) } + } catch (e: Exception) { + _state.update { it.copy(error = getApplication().explain(e)) } + } + } + } + + /** Out of the way, and reversible: the web UI's Archive. */ + fun archive(chat: Chat) { + _state.update { s -> s.copy(chats = s.chats.filterNot { it.id == chat.id }) } + viewModelScope.launch { + runCatching { + getApplication().lembas.instances.client() + ?.updateChat(chat.id, buildJsonObject { put("archived", true) }) + }.onFailure { e -> + _state.update { it.copy(error = getApplication().explain(e)) } + load() + } + } + } +} + +/** Where the drawer can go, besides a chat. */ +interface DrawerActions { + fun newChat() {} + fun newAgentChat() {} + fun open(chatId: String) {} + fun archive(chat: Chat) {} + fun files() {} + fun scheduled() {} + fun settings() {} + fun more() {} + fun retry() {} +} + +/** + * The navigation drawer: New chat at the top, search, Files and Scheduled, then the chats -- + * today's, the earlier ones, and the agent chats -- and Settings with the account at the foot. + * A long press on a chat offers Archive. + */ +@Composable +fun DrawerContent( + state: ChatsState, + current: String?, + account: String, + actions: DrawerActions, + modifier: Modifier = Modifier, + today: LocalDate = LocalDate.now(), + zone: ZoneId = ZoneId.systemDefault(), +) { + val palette = LocalPalette.current + var query by rememberSaveable { mutableStateOf("") } + val groups = remember(state.chats, query, today) { groupChats(state.chats, query, today, zone) } + ModalDrawerSheet(modifier = modifier, drawerContainerColor = palette.surface, drawerShape = RoundedCornerShape(topEnd = 24.dp, bottomEnd = 24.dp)) { + Column(Modifier.fillMaxHeight()) { + Row(Modifier.fillMaxWidth().padding(start = 24.dp, end = 8.dp, top = 12.dp), verticalAlignment = Alignment.CenterVertically) { + Text(stringResource(R.string.app_name), style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f)) + IconButton(onClick = actions::newChat) { Icon(Icons.Filled.EditNote, contentDescription = stringResource(R.string.new_chat)) } + } + TextField( + value = query, + onValueChange = { query = it }, + singleLine = true, + placeholder = { Text(stringResource(R.string.chats_search)) }, + leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) }, + trailingIcon = { + if (query.isNotEmpty()) { + IconButton(onClick = { query = "" }) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.clear)) } + } + }, + shape = RoundedCornerShape(28.dp), + colors = TextFieldDefaults.colors( + focusedContainerColor = palette.surfaceRaised, + unfocusedContainerColor = palette.surfaceRaised, + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent, + ), + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), + ) + LazyColumn(Modifier.weight(1f)) { + item { DrawerItem(Icons.Filled.EditNote, stringResource(R.string.new_chat), onClick = actions::newChat) } + item { DrawerItem(Icons.Filled.Terminal, stringResource(R.string.new_agent_chat), onClick = actions::newAgentChat) } + item { DrawerItem(Icons.Filled.Folder, stringResource(R.string.files), onClick = actions::files) } + item { DrawerItem(Icons.Filled.Schedule, stringResource(R.string.scheduled), onClick = actions::scheduled) } + item { HorizontalDivider(color = palette.border, modifier = Modifier.padding(horizontal = 28.dp, vertical = 8.dp)) } + state.error?.let { error -> + item { + Row(Modifier.fillMaxWidth().padding(start = 28.dp, end = 12.dp), verticalAlignment = Alignment.CenterVertically) { + Text(error, color = palette.danger, style = MaterialTheme.typography.bodySmall, modifier = Modifier.weight(1f)) + TextButton(onClick = actions::retry) { Text(stringResource(R.string.retry)) } + } + } + } + section(R.string.chats_today, groups.today, current, actions) + section(R.string.chats_earlier, groups.earlier, current, actions) + section(R.string.chats_agents, groups.agents, current, actions) + if (groups.isEmpty && !state.loading && state.error == null) { + item { + Text( + stringResource(if (query.isBlank()) R.string.empty_chats else R.string.chats_none_found), + style = MaterialTheme.typography.bodyMedium, + color = palette.inkMuted, + modifier = Modifier.padding(horizontal = 28.dp, vertical = 12.dp), + ) + } + } + if (state.more && query.isBlank()) { + item { LaunchedEffect(state.chats.size) { actions.more() } } + } + } + HorizontalDivider(color = palette.border) + DrawerItem(Icons.Filled.Settings, stringResource(R.string.settings), subtitle = account.ifBlank { null }, onClick = actions::settings) + Spacer(Modifier.size(8.dp)) + } + } +} + +private fun LazyListScope.section(title: Int, chats: List, current: String?, actions: DrawerActions) { + if (chats.isEmpty()) return + item(key = "h$title") { + Text( + stringResource(title), + style = MaterialTheme.typography.labelLarge, + color = LocalPalette.current.inkFaint, + modifier = Modifier.padding(start = 28.dp, end = 28.dp, top = 12.dp, bottom = 4.dp), + ) + } + items(chats, key = { it.id }) { chat -> ChatItem(chat, chat.id == current, actions) } +} + +@Composable +private fun DrawerItem(icon: ImageVector, label: String, subtitle: String? = null, onClick: () -> Unit) { + val palette = LocalPalette.current + Surface( + onClick = onClick, + shape = RoundedCornerShape(28.dp), + color = Color.Transparent, + modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp), + ) { + Row(Modifier.heightIn(min = 52.dp).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) { + Icon(icon, contentDescription = null, tint = palette.inkMuted, modifier = Modifier.size(22.dp)) + Spacer(Modifier.width(16.dp)) + Column(Modifier.weight(1f)) { + Text(label, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) + subtitle?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) } + } + } + } +} + +/** One chat: its title (which gives), and a dot for news or for a reply being written. */ +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun ChatItem(chat: Chat, selected: Boolean, actions: DrawerActions) { + val palette = LocalPalette.current + var menu by remember { mutableStateOf(false) } + Box(Modifier.fillMaxWidth().padding(horizontal = 12.dp)) { + Row( + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(28.dp)) + .background(if (selected) palette.accentSoft else Color.Transparent) + .combinedClickable(onClick = { actions.open(chat.id) }, onLongClick = { menu = true }) + .heightIn(min = 48.dp) + .padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + chat.title.ifBlank { stringResource(R.string.new_chat) }, + style = MaterialTheme.typography.bodyLarge, + color = if (selected) palette.ink else palette.inkMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + if (chat.unread || chat.running) { + Spacer(Modifier.width(12.dp)) + Box(Modifier.size(8.dp).clip(CircleShape).background(if (chat.running) palette.leaf else palette.accent)) + } + } + DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { + DropdownMenuItem( + leadingIcon = { Icon(Icons.Filled.Archive, contentDescription = null) }, + text = { Text(stringResource(R.string.archive)) }, + onClick = { + menu = false + actions.archive(chat) + }, + ) + } + } +} diff --git a/app/src/main/java/eu/llembas/android/ui/scheduled/ScheduleLogic.kt b/app/src/main/java/eu/llembas/android/ui/scheduled/ScheduleLogic.kt new file mode 100644 index 0000000..20e097e --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/scheduled/ScheduleLogic.kt @@ -0,0 +1,33 @@ +package eu.llembas.android.ui.scheduled + +import java.time.OffsetDateTime +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.util.Locale + +/** How a run's status is drawn: its colour family, not its words. */ +enum class Tone { Good, Quiet, Bad, Waiting, Neutral } + +object ScheduleLogic { + fun tone(status: String): Tone = when (status) { + "ok" -> Tone.Good + "silent" -> Tone.Quiet + "failed", "missed" -> Tone.Bad + "waiting", "running" -> Tone.Waiting + else -> Tone.Neutral + } + + /** + * A moment the server named (ISO 8601 with an offset), where the phone is, short: + * "Tue 10 Mar, 08:00". Null for nothing or for something that is not a time. + */ + fun moment(iso: String?, zone: ZoneId = ZoneId.systemDefault(), locale: Locale = Locale.getDefault()): String? { + if (iso.isNullOrBlank()) return null + val at = runCatching { OffsetDateTime.parse(iso).atZoneSameInstant(zone) }.getOrNull() ?: return null + return DateTimeFormatter.ofPattern("EEE d MMM, HH:mm", locale).format(at) + } + + /** At most [n] upcoming runs, as the preview lists them; unreadable ones are left out. */ + fun upcoming(runs: List, n: Int = 5, zone: ZoneId = ZoneId.systemDefault(), locale: Locale = Locale.getDefault()): List = + runs.mapNotNull { moment(it, zone, locale) }.take(n) +} diff --git a/app/src/main/java/eu/llembas/android/ui/scheduled/ScheduledScreens.kt b/app/src/main/java/eu/llembas/android/ui/scheduled/ScheduledScreens.kt new file mode 100644 index 0000000..4490a1f --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/scheduled/ScheduledScreens.kt @@ -0,0 +1,731 @@ +@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) + +package eu.llembas.android.ui.scheduled + +import android.app.Application +import androidx.compose.foundation.background +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.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +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.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.Pause +import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.filled.Schedule +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExtendedFloatingActionButton +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.material3.pulltorefresh.PullToRefreshBox +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.graphics.Color +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.lifecycle.AndroidViewModel +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.compose.viewModel +import eu.llembas.android.R +import eu.llembas.android.api.ApiClient +import eu.llembas.android.api.ApiException +import eu.llembas.android.api.Schedule +import eu.llembas.android.api.SchedulePreview +import eu.llembas.android.api.ScheduleRun +import eu.llembas.android.lembas +import eu.llembas.android.ui.explain +import eu.llembas.android.ui.theme.LocalPalette +import eu.llembas.android.ui.theme.Palette +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch + +/** A server without the scheduling routes answers 404 (or 405): it is older, not broken. */ +private fun Throwable.unsupported(): Boolean = this is ApiException && (status == 404 || status == 405) + +private suspend fun Application.api(): ApiClient = lembas.instances.client() ?: throw ApiException(401, "Not signed in.") + +// --- The list -------------------------------------------------------------------------------- + +data class ScheduledState( + val schedules: List = emptyList(), + val loading: Boolean = false, + val error: String? = null, + val unsupported: Boolean = false, +) + +class ScheduledViewModel(app: Application) : AndroidViewModel(app) { + private val _state = MutableStateFlow(ScheduledState()) + val state = _state.asStateFlow() + + fun load() { + viewModelScope.launch { + _state.update { it.copy(loading = true, error = null) } + try { + _state.value = ScheduledState(schedules = getApplication().api().schedules()) + } catch (e: Exception) { + _state.update { + if (e.unsupported()) { + it.copy( + loading = false, + unsupported = true, + ) + } else { + it.copy(loading = false, error = getApplication().explain(e)) + } + } + } + } + } + + /** Pause or resume; the switch moves at once and comes back if the server says no. */ + fun pause(schedule: Schedule, paused: Boolean) { + _state.update { s -> s.copy(schedules = s.schedules.map { if (it.id == schedule.id) it.copy(paused = paused) else it }) } + viewModelScope.launch { + try { + val saved = getApplication().api().pauseSchedule(schedule.id, paused) + _state.update { s -> s.copy(schedules = s.schedules.map { if (it.id == saved.id) saved else it }) } + } catch (e: Exception) { + _state.update { s -> + s.copy( + schedules = s.schedules.map { if (it.id == schedule.id) schedule else it }, + error = getApplication().explain(e), + ) + } + } + } + } +} + +@Composable +fun ScheduledScreen(onBack: () -> Unit, onOpen: (String) -> Unit, onNew: () -> Unit, model: ScheduledViewModel = viewModel()) { + val state by model.state.collectAsStateWithLifecycle() + LifecycleResumeEffect(Unit) { + model.load() + onPauseOrDispose { } + } + ScheduledContent(state, onBack = onBack, onOpen = onOpen, onNew = onNew, onPause = model::pause, onRetry = model::load) +} + +/** + * Scheduled tasks: one card each, with the rule in words, the last run's status and the next + * run, and a switch that pauses it. The card's words give; the switch keeps its size. + */ +@Composable +fun ScheduledContent( + state: ScheduledState, + onBack: () -> Unit = {}, + onOpen: (String) -> Unit = {}, + onNew: () -> Unit = {}, + onPause: (Schedule, Boolean) -> Unit = { _, _ -> }, + onRetry: () -> Unit = {}, +) { + val palette = LocalPalette.current + Scaffold( + containerColor = palette.bg, + topBar = { BackBar(stringResource(R.string.scheduled), onBack) }, + floatingActionButton = { + if (!state.unsupported) { + ExtendedFloatingActionButton( + onClick = onNew, + icon = { Icon(Icons.Filled.Add, contentDescription = null) }, + text = { Text(stringResource(R.string.schedule_new)) }, + containerColor = palette.accent, + contentColor = palette.accentInk, + ) + } + }, + ) { padding -> + PullToRefreshBox(isRefreshing = state.loading, onRefresh = onRetry, modifier = Modifier.fillMaxSize().padding(padding)) { + when { + state.unsupported -> Message(stringResource(R.string.scheduled_unsupported)) + + state.schedules.isEmpty() && state.error != null -> Message(state.error, retry = onRetry) + + state.schedules.isEmpty() && !state.loading -> Message(stringResource(R.string.scheduled_empty)) + + else -> LazyColumn( + Modifier.fillMaxSize(), + contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 96.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + state.error?.let { item { Text(it, color = palette.danger, style = MaterialTheme.typography.bodyMedium) } } + items(state.schedules, key = { it.id }) { s -> ScheduleCard(s, onOpen = { onOpen(s.id) }, onPause = { onPause(s, it) }) } + } + } + } + } +} + +@Composable +private fun ScheduleCard(schedule: Schedule, onOpen: () -> Unit, onPause: (Boolean) -> Unit) { + val palette = LocalPalette.current + Surface(onClick = onOpen, shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, modifier = Modifier.fillMaxWidth()) { + Row(Modifier.padding(start = 16.dp, end = 12.dp, top = 14.dp, bottom = 14.dp), verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text( + schedule.title.ifBlank { schedule.instruction }, + style = MaterialTheme.typography.titleMedium, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + if (schedule.rule.isNotBlank()) { + Text(schedule.rule, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) + } + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 4.dp)) { + schedule.lastRun?.let { StatusChip(it.status, it.missed) } + val next = when { + schedule.paused -> stringResource(R.string.schedule_paused) + else -> ScheduleLogic.moment(schedule.nextRun)?.let { stringResource(R.string.schedule_next, it) } + } + next?.let { + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = palette.inkFaint, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(start = if (schedule.lastRun != null) 8.dp else 0.dp), + ) + } + } + } + Spacer(Modifier.width(12.dp)) + Switch(checked = !schedule.paused, onCheckedChange = { on -> onPause(!on) }) + } + } +} + +/** A run's status in words, on its tone's soft colour. */ +@Composable +fun StatusChip(status: String, missed: Int = 0) { + val palette = LocalPalette.current + val (ink, soft) = toneColours(palette, ScheduleLogic.tone(status)) + val words = when (status) { + "ok" -> stringResource(R.string.run_ok) + "silent" -> stringResource(R.string.run_silent) + "failed" -> stringResource(R.string.run_failed) + "missed" -> stringResource(R.string.run_missed, maxOf(missed, 1).toString()) + "skipped" -> stringResource(R.string.run_skipped) + "waiting" -> stringResource(R.string.run_waiting) + "running" -> stringResource(R.string.run_running) + else -> status + } + Box(Modifier.background(soft, RoundedCornerShape(8.dp)).padding(horizontal = 8.dp, vertical = 3.dp)) { + Text(words, style = MaterialTheme.typography.labelMedium, color = ink, maxLines = 1) + } +} + +private fun toneColours(palette: Palette, tone: Tone): Pair = when (tone) { + Tone.Good -> palette.success to palette.successSoft + Tone.Bad -> palette.danger to palette.dangerSoft + Tone.Waiting -> palette.warning to palette.warningSoft + Tone.Quiet, Tone.Neutral -> palette.inkMuted to palette.surfaceActive +} + +@Composable +private fun BackBar(title: String, onBack: () -> Unit, actions: @Composable () -> Unit = {}) { + val palette = LocalPalette.current + TopAppBar( + colors = TopAppBarDefaults.topAppBarColors(containerColor = palette.bg, scrolledContainerColor = palette.bg), + title = { Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) } }, + actions = { actions() }, + ) +} + +@Composable +private fun Message(text: String, retry: (() -> Unit)? = null) { + val palette = LocalPalette.current + Column( + Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(32.dp), + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Icon(Icons.Filled.Schedule, contentDescription = null, tint = palette.inkFaint, modifier = Modifier.size(48.dp)) + Spacer(Modifier.height(16.dp)) + Text(text, style = MaterialTheme.typography.bodyLarge, color = palette.inkMuted, textAlign = TextAlign.Center) + retry?.let { TextButton(onClick = it) { Text(stringResource(R.string.retry)) } } + } +} + +// --- One schedule ----------------------------------------------------------------------------- + +data class ScheduleState( + val schedule: Schedule? = null, + val runs: List = emptyList(), + val more: Boolean = false, + val loading: Boolean = false, + val error: String? = null, + val notice: String? = null, +) + +class ScheduleViewModel(app: Application) : AndroidViewModel(app) { + private val _state = MutableStateFlow(ScheduleState()) + val state = _state.asStateFlow() + private var id: String? = null + + fun open(id: String) { + this.id = id + viewModelScope.launch { + _state.update { it.copy(loading = true, error = null) } + try { + val api = getApplication().api() + val schedule = api.schedule(id) + val runs = runCatching { api.scheduleRuns(id) }.getOrNull() + _state.update { it.copy(schedule = schedule, runs = runs?.runs.orEmpty(), more = runs?.more == true, loading = false) } + } catch (e: Exception) { + _state.update { it.copy(loading = false, error = getApplication().explain(e)) } + } + } + } + + fun more() { + val schedule = _state.value.schedule ?: return + val last = _state.value.runs.lastOrNull() ?: return + viewModelScope.launch { + runCatching { getApplication().api().scheduleRuns(schedule.id, last.id) } + .onSuccess { page -> _state.update { it.copy(runs = it.runs + page.runs, more = page.more) } } + } + } + + fun runNow() = act { api, s -> + api.runScheduleNow(s.id) + _state.update { it.copy(notice = getApplication().getString(R.string.schedule_started)) } + id?.let(::open) + } + + fun pause(paused: Boolean) = act { api, s -> _state.update { it.copy(schedule = api.pauseSchedule(s.id, paused)) } } + + fun delete(then: () -> Unit) = act { api, s -> + api.deleteSchedule(s.id) + then() + } + + fun clear() = _state.update { it.copy(error = null, notice = null) } + + private fun act(block: suspend (ApiClient, Schedule) -> Unit) { + val schedule = _state.value.schedule ?: return + viewModelScope.launch { + try { + block(getApplication().api(), schedule) + } catch (e: Exception) { + _state.update { it.copy(error = getApplication().explain(e)) } + } + } + } +} + +@Composable +fun ScheduleScreen( + id: String, + onBack: () -> Unit, + onEdit: (String) -> Unit, + onOpenChat: (String) -> Unit, + model: ScheduleViewModel = viewModel(key = "schedule-$id"), +) { + val state by model.state.collectAsStateWithLifecycle() + val snackbar = remember { SnackbarHostState() } + LifecycleResumeEffect(id) { + model.open(id) + onPauseOrDispose { } + } + LaunchedEffect(state.error, state.notice) { + (state.notice ?: state.error.takeIf { state.schedule != null })?.let { + snackbar.showSnackbar(it) + model.clear() + } + } + ScheduleContent( + state, + snackbar = snackbar, + onBack = onBack, + onEdit = { onEdit(id) }, + onDelete = { model.delete(onBack) }, + onRunNow = model::runNow, + onPause = model::pause, + onOpenRun = { run -> run.chatId?.let(onOpenChat) }, + onMore = model::more, + ) +} + +/** + * One schedule: what it does and when, Run now and Pause side by side (equal halves), the next + * runs, and its history -- each run's status, when, the model that ran it and why, and Open for + * its result. + */ +@Composable +fun ScheduleContent( + state: ScheduleState, + snackbar: SnackbarHostState = remember { SnackbarHostState() }, + onBack: () -> Unit = {}, + onEdit: () -> Unit = {}, + onDelete: () -> Unit = {}, + onRunNow: () -> Unit = {}, + onPause: (Boolean) -> Unit = {}, + onOpenRun: (ScheduleRun) -> Unit = {}, + onMore: () -> Unit = {}, +) { + val palette = LocalPalette.current + val schedule = state.schedule + var deleting by remember { mutableStateOf(false) } + Scaffold( + containerColor = palette.bg, + snackbarHost = { SnackbarHost(snackbar) }, + topBar = { + BackBar(schedule?.title?.ifBlank { null } ?: stringResource(R.string.scheduled), onBack) { + if (schedule != null) { + IconButton(onClick = onEdit) { Icon(Icons.Filled.Edit, contentDescription = stringResource(R.string.edit)) } + IconButton(onClick = { deleting = true }) { Icon(Icons.Filled.Delete, contentDescription = stringResource(R.string.delete)) } + } + } + }, + ) { padding -> + if (schedule == null) { + Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) { + if (state.loading) CircularProgressIndicator() else state.error?.let { Message(it) } + } + } else { + ScheduleBody(state, schedule, padding, onRunNow, onPause, onOpenRun, onMore) + } + } + if (deleting) { + AlertDialog( + onDismissRequest = { deleting = false }, + title = { Text(stringResource(R.string.schedule_delete_confirm)) }, + confirmButton = { + TextButton(onClick = { + deleting = false + onDelete() + }) { Text(stringResource(R.string.delete), color = palette.danger) } + }, + dismissButton = { TextButton(onClick = { deleting = false }) { Text(stringResource(R.string.cancel)) } }, + ) + } +} + +@Composable +private fun ScheduleBody( + state: ScheduleState, + schedule: Schedule, + padding: PaddingValues, + onRunNow: () -> Unit, + onPause: (Boolean) -> Unit, + onOpenRun: (ScheduleRun) -> Unit, + onMore: () -> Unit, +) { + val palette = LocalPalette.current + LazyColumn( + Modifier.fillMaxSize().padding(padding), + contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 32.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + item { + Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, modifier = Modifier.fillMaxWidth()) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Filled.Schedule, contentDescription = null, tint = palette.accent, modifier = Modifier.size(20.dp)) + Spacer(Modifier.width(8.dp)) + Text(schedule.rule, style = MaterialTheme.typography.titleMedium, modifier = Modifier.weight(1f)) + } + Text(schedule.instruction, style = MaterialTheme.typography.bodyMedium) + val facts = listOfNotNull( + schedule.model.ifBlank { null }?.let { stringResource(R.string.schedule_model, it) }, + notifyWords(schedule.notify), + ) + if (facts.isNotEmpty()) { + Text(facts.joinToString(" · "), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint) + } + } + } + } + item { + Row(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) { + FilledTonalButton(onClick = onRunNow, modifier = Modifier.weight(1f).heightIn(min = 48.dp)) { + Icon(Icons.Filled.PlayArrow, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.schedule_run_now), maxLines = 1, overflow = TextOverflow.Ellipsis) + } + OutlinedButton(onClick = { onPause(!schedule.paused) }, modifier = Modifier.weight(1f).heightIn(min = 48.dp)) { + Icon(if (schedule.paused) Icons.Filled.PlayArrow else Icons.Filled.Pause, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(8.dp)) + Text( + stringResource(if (schedule.paused) R.string.schedule_resume else R.string.schedule_pause), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + } + val next = ScheduleLogic.upcoming(schedule.nextRuns) + if (next.isNotEmpty() && !schedule.paused) { + item { Header(stringResource(R.string.schedule_next_runs)) } + item { + Surface(shape = RoundedCornerShape(16.dp), color = palette.surfaceRaised, modifier = Modifier.fillMaxWidth()) { + Column(Modifier.padding(vertical = 8.dp)) { + next.forEach { + Text(it, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp)) + } + } + } + } + } + item { Header(stringResource(R.string.schedule_history)) } + if (state.runs.isEmpty()) { + item { + Text( + stringResource(R.string.schedule_no_runs), + style = MaterialTheme.typography.bodyMedium, + color = palette.inkMuted, + modifier = Modifier.padding(horizontal = 4.dp), + ) + } + } + items(state.runs, key = { it.id }) { run -> RunRow(run, onOpen = { onOpenRun(run) }) } + if (state.more) item { LaunchedEffect(state.runs.size) { onMore() } } + } +} + +@Composable +private fun notifyWords(notify: String): String? = when (notify) { + "always" -> stringResource(R.string.notify_always) + "matters", "when_matters" -> stringResource(R.string.notify_matters) + "never" -> stringResource(R.string.notify_never) + else -> null +} + +@Composable +private fun Header(text: String) { + Text( + text, + style = MaterialTheme.typography.labelLarge, + color = LocalPalette.current.accent, + modifier = Modifier.padding(start = 4.dp, top = 16.dp, bottom = 4.dp), + ) +} + +/** A run: its status (a fixed column, so the times line up), when, the model, and Open. */ +@Composable +private fun RunRow(run: ScheduleRun, onOpen: () -> Unit) { + val palette = LocalPalette.current + Surface(shape = RoundedCornerShape(16.dp), color = palette.surfaceRaised, modifier = Modifier.fillMaxWidth()) { + Row(Modifier.heightIn(min = 64.dp).padding(start = 12.dp, end = 4.dp, top = 8.dp, bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) { + Box(Modifier.width(112.dp)) { StatusChip(run.status, run.missed) } + Column(Modifier.weight(1f)) { + Text(ScheduleLogic.moment(run.startedAt ?: run.dueAt) ?: "—", style = MaterialTheme.typography.bodyMedium) + val model = when { + run.model.isBlank() -> null + run.modelReason.startsWith("switched") -> stringResource(R.string.run_model_switched, run.model) + else -> run.model + } + model?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) } + if (run.error.isNotBlank()) { + Text(run.error, style = MaterialTheme.typography.bodySmall, color = palette.danger, maxLines = 2, overflow = TextOverflow.Ellipsis) + } + } + if (run.chatId != null) TextButton(onClick = onOpen) { Text(stringResource(R.string.viewer_open)) } + } + } +} + +// --- Create and edit ------------------------------------------------------------------------ + +data class EditState( + val words: String = "", + val preview: SchedulePreview? = null, + val compiling: Boolean = false, + val saving: Boolean = false, + val error: String? = null, + val unsupported: Boolean = false, +) + +class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) { + private val _state = MutableStateFlow(EditState()) + val state = _state.asStateFlow() + private var editing: String? = null + private var started = false + + /** Begin: empty for a new schedule, the schedule's own words for one being edited. */ + fun start(id: String?) { + if (started) return + started = true + editing = id + if (id == null) return + viewModelScope.launch { + runCatching { getApplication().api().schedule(id) }.onSuccess { s -> + _state.update { it.copy(words = listOf(s.rule, s.instruction).filter { w -> w.isNotBlank() }.joinToString(": ")) } + } + } + } + + fun words(text: String) = _state.update { it.copy(words = text, preview = null) } + + /** The server reads the words: the rule, the instruction and the next runs come back. */ + fun preview() { + val words = _state.value.words.trim() + if (words.isEmpty()) return + viewModelScope.launch { + _state.update { it.copy(compiling = true, error = null) } + try { + val preview = getApplication().api().compileSchedule(words) + _state.update { it.copy(preview = preview, compiling = false) } + } catch (e: Exception) { + _state.update { + it.copy(compiling = false, unsupported = e.unsupported(), error = if (e.unsupported()) null else getApplication().explain(e)) + } + } + } + } + + fun save(then: (String) -> Unit) { + val preview = _state.value.preview ?: return + viewModelScope.launch { + _state.update { it.copy(saving = true, error = null) } + try { + val saved = getApplication().api().saveSchedule(preview, editing) + then(saved.id) + } catch (e: Exception) { + _state.update { it.copy(saving = false, error = getApplication().explain(e)) } + } + } + } +} + +@Composable +fun ScheduleEditScreen( + id: String?, + onBack: () -> Unit, + onSaved: (String) -> Unit, + model: ScheduleEditViewModel = viewModel(key = "schedule-edit-${id ?: "new"}"), +) { + val state by model.state.collectAsStateWithLifecycle() + LaunchedEffect(id) { model.start(id) } + ScheduleEditContent(state, editing = id != null, onBack = onBack, onWords = model::words, onPreview = model::preview, onSave = { model.save(onSaved) }) +} + +/** + * A schedule in words: the person says when and what, the server reads it, and the preview + * shows what it understood -- the rule in words, the instruction, the next five runs -- before + * anything is saved. Save stays at the foot, out of the way of the keyboard. + */ +@Composable +fun ScheduleEditContent( + state: EditState, + editing: Boolean, + onBack: () -> Unit = {}, + onWords: (String) -> Unit = {}, + onPreview: () -> Unit = {}, + onSave: () -> Unit = {}, +) { + val palette = LocalPalette.current + Scaffold( + containerColor = palette.bg, + topBar = { BackBar(stringResource(if (editing) R.string.schedule_edit else R.string.schedule_new), onBack) }, + bottomBar = { + Box(Modifier.background(palette.bg).navigationBarsPadding().imePadding().padding(16.dp)) { + Button( + onClick = onSave, + enabled = state.preview != null && !state.saving, + modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp), + ) { Text(stringResource(R.string.save)) } + } + }, + ) { padding -> + Column( + Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(horizontal = 16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text(stringResource(R.string.schedule_words_hint), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) + OutlinedTextField( + value = state.words, + onValueChange = onWords, + minLines = 3, + placeholder = { Text(stringResource(R.string.schedule_words_example)) }, + shape = RoundedCornerShape(16.dp), + modifier = Modifier.fillMaxWidth(), + ) + FilledTonalButton( + onClick = onPreview, + enabled = state.words.isNotBlank() && !state.compiling, + modifier = Modifier.heightIn(min = 48.dp), + ) { + if (state.compiling) { + CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(8.dp)) + } + Text(stringResource(R.string.schedule_preview)) + } + if (state.unsupported) Text(stringResource(R.string.scheduled_unsupported), color = palette.inkMuted) + state.error?.let { Text(it, color = palette.danger, style = MaterialTheme.typography.bodyMedium) } + state.preview?.let { p -> + Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, modifier = Modifier.fillMaxWidth()) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text(stringResource(R.string.schedule_understood), style = MaterialTheme.typography.labelLarge, color = palette.accent) + if (p.title.isNotBlank()) Text(p.title, style = MaterialTheme.typography.titleMedium) + Row(verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Filled.Schedule, contentDescription = null, tint = palette.inkMuted, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(8.dp)) + Text(p.ruleText, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.weight(1f)) + } + Text(p.instruction, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) + val next = ScheduleLogic.upcoming(p.nextRuns) + if (next.isNotEmpty()) { + Text( + stringResource(R.string.schedule_next_runs), + style = MaterialTheme.typography.labelLarge, + modifier = Modifier.padding(top = 8.dp), + ) + next.forEach { Text(it, style = MaterialTheme.typography.bodyMedium) } + } + } + } + } + Spacer(Modifier.height(24.dp)) + } + } +} diff --git a/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt b/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt index 0534f41..59e31aa 100644 --- a/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt @@ -5,29 +5,46 @@ package eu.llembas.android.ui.settings import android.app.Activity import android.content.Intent import android.provider.Settings +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.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +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.ArrowBack -import androidx.compose.material3.Button -import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material.icons.automirrored.filled.Logout +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Assistant +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material.icons.filled.Info +import androidx.compose.material.icons.filled.Notifications +import androidx.compose.material.icons.filled.NotificationsActive +import androidx.compose.material.icons.filled.Palette +import androidx.compose.material.icons.filled.RecordVoiceOver +import androidx.compose.material.icons.filled.SystemUpdate +import androidx.compose.material.icons.filled.Timer import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton import androidx.compose.material3.RadioButton import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue @@ -37,18 +54,50 @@ import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import eu.llembas.android.BuildConfig import eu.llembas.android.R +import eu.llembas.android.auth.Instance import eu.llembas.android.auth.Prefs import eu.llembas.android.lembas import eu.llembas.android.push.Push +import eu.llembas.android.ui.theme.LocalPalette import eu.llembas.android.update.Updater import kotlinx.coroutines.launch -@OptIn(ExperimentalMaterial3Api::class) +/** What the settings page does; every action has a do-nothing default for the screenshots. */ +interface SettingsActions { + fun use(instance: Instance) {} + fun add() {} + fun signOut(instance: Instance) {} + fun theme(value: String) {} + fun enablePush(instance: Instance) {} + fun notificationSettings() {} + fun assistantSettings() {} + fun assistantTemporary(on: Boolean) {} + fun readAloud(on: Boolean) {} + fun checkUpdate() {} +} + +/** What the settings page shows. */ +data class SettingsState( + val instances: List = emptyList(), + val active: Instance? = null, + val prefs: Prefs = Prefs(), + val hasDistributor: Boolean = false, + val pushNote: String? = null, + val updateNote: String? = null, + val version: String = "", + val selfUpdate: Boolean = false, +) + @Composable fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) { val context = LocalContext.current @@ -59,10 +108,87 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) { val prefs by store.prefs.collectAsState(initial = Prefs()) var pushNote by remember { mutableStateOf(null) } var updateNote by remember { mutableStateOf(null) } + val distributors = remember { Push.distributors(context) } + val actions = remember { + object : SettingsActions { + override fun use(instance: Instance) { + scope.launch { store.use(instance.id) } + } + override fun add() = onAddInstance() + + override fun signOut(instance: Instance) { + scope.launch { + Push.disable(context, instance) + runCatching { store.clientFor(instance).signOut() } + store.remove(instance.id) + } + } + + override fun theme(value: String) { + scope.launch { store.savePrefs { it.copy(theme = value) } } + } + + override fun enablePush(instance: Instance) { + (context as? Activity)?.let { activity -> + Push.enable(activity, instance) { ok -> pushNote = context.getString(if (ok) R.string.push_on else R.string.push_failed) } + } + } + + override fun notificationSettings() { + context.startActivity( + Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS) + .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + ) + } + + override fun assistantSettings() { + context.startActivity(Intent(Settings.ACTION_VOICE_INPUT_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + } + + override fun assistantTemporary(on: Boolean) { + scope.launch { store.savePrefs { it.copy(assistantTemporary = on) } } + } + + override fun readAloud(on: Boolean) { + scope.launch { store.savePrefs { it.copy(readAloudSpoken = on) } } + } + + override fun checkUpdate() { + scope.launch { updateNote = Updater(context).checkAndOffer() } + } + } + } + SettingsContent( + SettingsState( + instances = instances, + active = active, + prefs = prefs, + hasDistributor = distributors.isNotEmpty(), + pushNote = pushNote, + updateNote = updateNote, + version = BuildConfig.VERSION_NAME, + selfUpdate = BuildConfig.SELF_UPDATE, + ), + actions, + onBack, + ) +} + +/** + * Settings as Material 3 grouped lists: each group a header and one rounded surface of rows, + * every row at least 56 dp with its icon, its words (which wrap) and its control (which keeps + * its size). + */ +@Composable +fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -> Unit = {}) { + val palette = LocalPalette.current Scaffold( + containerColor = palette.bg, topBar = { TopAppBar( + colors = TopAppBarDefaults.topAppBarColors(containerColor = palette.bg, scrolledContainerColor = palette.bg), title = { Text(stringResource(R.string.settings)) }, navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) } @@ -70,103 +196,201 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) { ) }, ) { padding -> - Column( - Modifier.padding(padding).fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), - verticalArrangement = Arrangement.spacedBy(12.dp), - ) { - Section(stringResource(R.string.settings_instances)) - instances.forEach { instance -> - Row( - Modifier.fillMaxWidth().clickable { scope.launch { store.use(instance.id) } }, - verticalAlignment = Alignment.CenterVertically, - ) { - RadioButton(selected = instance.id == active?.id, onClick = { scope.launch { store.use(instance.id) } }) - Column(Modifier.weight(1f)) { - Text(instance.name.ifBlank { instance.base }) - Text( - "${instance.email} · ${instance.base}", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, + LazyColumn(Modifier.fillMaxSize().padding(padding), contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 32.dp)) { + item { + Group(stringResource(R.string.settings_instances)) { + state.instances.forEachIndexed { i, instance -> + if (i > 0) Rule() + val inUse = instance.id == state.active?.id + Row( + Modifier.fillMaxWidth().clickable { actions.use(instance) }.heightIn(min = 72.dp).padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Initial(instance.name.ifBlank { instance.base }) + Spacer(Modifier.width(16.dp)) + Column(Modifier.weight(1f)) { + Text( + instance.name.ifBlank { + instance.base + }, + style = MaterialTheme.typography.bodyLarge, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + instance.email, + style = MaterialTheme.typography.bodyMedium, + color = palette.inkMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + instance.base, + style = MaterialTheme.typography.bodySmall, + color = palette.inkFaint, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + if (inUse) { + Spacer(Modifier.width(12.dp)) + Icon(Icons.Filled.CheckCircle, contentDescription = stringResource(R.string.instance_in_use), tint = palette.accent) + } + } + } + if (state.instances.isNotEmpty()) Rule() + SettingRow(Icons.Filled.Add, stringResource(R.string.add_instance), onClick = actions::add) + state.active?.let { current -> + Rule() + SettingRow(Icons.AutoMirrored.Filled.Logout, stringResource(R.string.sign_out), tint = palette.danger, onClick = { + actions.signOut(current) + }) + } + } + } + item { + Group(stringResource(R.string.settings_theme)) { + listOf("" to R.string.theme_system, "moria" to R.string.theme_moria, "shire" to R.string.theme_shire).forEachIndexed { i, (value, label) -> + if (i > 0) Rule() + SettingRow( + Icons.Filled.Palette, + stringResource(label), + onClick = { actions.theme(value) }, + trailing = { RadioButton(selected = state.prefs.theme == value, onClick = { actions.theme(value) }) }, + showIcon = i == 0, ) } } } - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - active?.let { current -> - OutlinedButton(onClick = { - scope.launch { - Push.disable(context, current) - runCatching { store.clientFor(current).signOut() } - store.remove(current.id) - } - }) { Text(stringResource(R.string.sign_out)) } - OutlinedButton(onClick = onAddInstance) { - Text(stringResource(R.string.add_instance)) - } + item { + Group(stringResource(R.string.settings_notifications)) { + SettingRow( + Icons.Filled.NotificationsActive, + stringResource(R.string.push_enable), + subtitle = state.pushNote ?: stringResource(if (state.hasDistributor) R.string.push_explained else R.string.push_no_distributor), + enabled = state.hasDistributor && state.active != null, + onClick = { state.active?.let(actions::enablePush) }, + ) + Rule() + SettingRow( + Icons.Filled.Notifications, + stringResource(R.string.notification_settings), + subtitle = stringResource(R.string.notification_settings_hint), + onClick = actions::notificationSettings, + ) } } - - HorizontalDivider() - Section(stringResource(R.string.settings_theme)) - listOf("" to R.string.theme_system, "moria" to R.string.theme_moria, "shire" to R.string.theme_shire).forEach { (value, label) -> - Row( - Modifier.fillMaxWidth().clickable { scope.launch { store.savePrefs { it.copy(theme = value) } } }, - verticalAlignment = Alignment.CenterVertically, - ) { - RadioButton(selected = prefs.theme == value, onClick = { scope.launch { store.savePrefs { it.copy(theme = value) } } }) - Text(stringResource(label)) + item { + Group(stringResource(R.string.settings_assistant)) { + SettingRow( + Icons.Filled.Assistant, + stringResource(R.string.assistant_open_settings), + subtitle = stringResource(R.string.assistant_explained), + onClick = actions::assistantSettings, + ) + Rule() + SettingRow( + Icons.Filled.Timer, + stringResource(R.string.assistant_temporary), + onClick = { actions.assistantTemporary(!state.prefs.assistantTemporary) }, + trailing = { Switch(checked = state.prefs.assistantTemporary, onCheckedChange = actions::assistantTemporary) }, + ) + Rule() + SettingRow( + Icons.Filled.RecordVoiceOver, + stringResource(R.string.assistant_read_aloud), + onClick = { actions.readAloud(!state.prefs.readAloudSpoken) }, + trailing = { Switch(checked = state.prefs.readAloudSpoken, onCheckedChange = actions::readAloud) }, + ) } + Text( + stringResource(R.string.assistant_samsung), + style = MaterialTheme.typography.bodySmall, + color = palette.inkFaint, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) } - - HorizontalDivider() - Section(stringResource(R.string.settings_notifications)) - val distributors = remember { Push.distributors(context) } - Text( - stringResource(if (distributors.isEmpty()) R.string.push_no_distributor else R.string.push_explained), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - active?.let { current -> - Button(enabled = distributors.isNotEmpty(), onClick = { - (context as? Activity)?.let { activity -> - Push.enable(activity, current) { ok -> - pushNote = context.getString(if (ok) R.string.push_on else R.string.push_failed) - } + item { + Group(stringResource(R.string.settings_about)) { + SettingRow(Icons.Filled.Info, stringResource(R.string.about_version, state.version), onClick = {}) + if (state.selfUpdate) { + Rule() + SettingRow( + Icons.Filled.SystemUpdate, + stringResource(R.string.update_check), + subtitle = state.updateNote, + onClick = actions::checkUpdate, + ) } - }) { Text(stringResource(R.string.push_enable)) } - } - pushNote?.let { Text(it, style = MaterialTheme.typography.bodySmall) } - - HorizontalDivider() - Section(stringResource(R.string.settings_assistant)) - Text(stringResource(R.string.assistant_explained), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - Button(onClick = { - context.startActivity(Intent(Settings.ACTION_VOICE_INPUT_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) - }) { Text(stringResource(R.string.assistant_open_settings)) } - Text(stringResource(R.string.assistant_samsung), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { - Text(stringResource(R.string.assistant_temporary), modifier = Modifier.weight(1f)) - Switch(checked = prefs.assistantTemporary, onCheckedChange = { on -> scope.launch { store.savePrefs { it.copy(assistantTemporary = on) } } }) - } - Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { - Text(stringResource(R.string.assistant_read_aloud), modifier = Modifier.weight(1f)) - Switch(checked = prefs.readAloudSpoken, onCheckedChange = { on -> scope.launch { store.savePrefs { it.copy(readAloudSpoken = on) } } }) - } - - HorizontalDivider() - Section(stringResource(R.string.settings_about)) - Text(stringResource(R.string.about_version, BuildConfig.VERSION_NAME)) - if (BuildConfig.SELF_UPDATE) { - OutlinedButton(onClick = { - scope.launch { updateNote = Updater(context).checkAndOffer() } - }) { Text(stringResource(R.string.update_check)) } - updateNote?.let { Text(it, style = MaterialTheme.typography.bodySmall) } + } } } } } @Composable -private fun Section(title: String) { - Text(title, style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary) +private fun Group(title: String, content: @Composable () -> Unit) { + val palette = LocalPalette.current + Text( + title, + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.SemiBold, + color = palette.accent, + modifier = Modifier.padding(start = 16.dp, top = 24.dp, bottom = 8.dp), + ) + Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, modifier = Modifier.fillMaxWidth()) { + Column { content() } + } +} + +@Composable +private fun Rule() = HorizontalDivider(color = LocalPalette.current.border, modifier = Modifier.padding(start = 56.dp)) + +/** + * A settings row: an icon in a fixed 24 dp column (or its empty place, so a group's words start + * on one line), the words that give, and the control that keeps its size. + */ +@Composable +private fun SettingRow( + icon: ImageVector, + title: String, + onClick: () -> Unit, + subtitle: String? = null, + tint: Color? = null, + enabled: Boolean = true, + showIcon: Boolean = true, + trailing: (@Composable () -> Unit)? = null, +) { + val palette = LocalPalette.current + val ink = if (!enabled) palette.inkFaint else tint ?: palette.ink + Row( + Modifier + .fillMaxWidth() + .clickable(enabled = enabled, onClick = onClick) + .heightIn(min = 56.dp) + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Box(Modifier.size(24.dp), contentAlignment = Alignment.Center) { + if (showIcon) Icon(icon, contentDescription = null, tint = tint ?: palette.inkMuted) + } + Spacer(Modifier.width(16.dp)) + Column(Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.bodyLarge, color = ink) + subtitle?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) } + } + if (trailing != null) { + Spacer(Modifier.width(12.dp)) + trailing() + } + } +} + +/** An instance's initial in a circle, where a picture would be. */ +@Composable +private fun Initial(name: String) { + val palette = LocalPalette.current + Box(Modifier.size(40.dp).clip(CircleShape).background(palette.accentSoft), contentAlignment = Alignment.Center) { + Text(name.trim().firstOrNull()?.uppercase() ?: "?", style = MaterialTheme.typography.titleMedium, color = palette.accent) + } } diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 26e05a2..3533266 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -14,10 +14,7 @@ Tato instance používá starší LLeMbas. Tato aplikace potřebuje LLeMbas 2.0 nebo novější. Tato instance používá novější rozhraní API pro aplikace než tato aplikace. Aktualizujte aplikaci. Nová konverzace - Konverzace - Agenti Zatím žádné konverzace. Ne všichni, kdo bloudí, jsou ztraceni — založte jednu. - Zatím žádné konverzace s agentem. Spusťte jednu tlačítkem Nová konverzace s agentem na zařízení propojeném s touto instancí. Nová konverzace s agentem Zařízení 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. @@ -110,9 +107,82 @@ 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í + Otevřít chaty + Hledat v chatech + Dnes + Dříve + Chaty s agentem + Žádný chat to nemá v názvu. + Vymazat + Řekněte agentovi, co má udělat + Možnosti + Úsilí + Pomalejší a lepší u těžkých otázek. + Nejdřív plán + Model napíše plán, který schválíte, než začne jednat. + Režim + Co má agent udělat? + Běží na %1$s, ve složce %2$s + jeho první složka + Vyberte model + Používá se + Vidí obrázky + Používá nástroje + kontext %1$s + Přemýšlení zapnout či vypnout + Úsilí: %1$s + Kód + Zkopírovat kód + Vybrat text + Použité nástroje: %1$s + Vysvětli + jak něco funguje, jednoduše + Napiš + e-mail, poznámku nebo příspěvek + Naplánuj + výlet, týden nebo projekt + Zkontroluj + text, chyby a tón + Používá se + Nastavení oznámení + Které druhy přicházejí a jak: odpovědi, otázky, výsledky a selhání naplánovaných úloh. + Naplánováno + Nic není naplánováno. Požádejte o něco, co se má stát každé ráno, nebo jednou příští týden. + Tato instance zatím naplánované úlohy nenabízí. Přijdou s novějším LLeMbas na serveru. + Nový plán + Upravit plán + Příště: %1$s + Pozastaveno + Pozastavit + Pokračovat + Spustit teď + Spuštěno. Výsledek se objeví v historii. + Příští spuštění + Historie + Zatím neběžel. + Model: %1$s + Smazat tento plán? Jeho dřívější výsledky zůstanou ve svých chatech. + Řekněte vlastními slovy kdy a co. Než se cokoli uloží, uvidíte, jak to bylo pochopeno. + Každý pracovní den v 7:30 shrň zprávy o obnovitelné energii + Náhled + Pochopeno jako + Dá vědět pokaždé + Dá vědět, když na tom záleží + Nedá vědět nikdy + Hotovo + Nic nového + Selhalo + Zmeškáno ×%1$s + Vynecháno + Čeká na model + Běží + %1$s (první volba byla zaneprázdněná) + Výsledky naplánovaných úloh + Selhání naplánovaných úloh + Naplánovaná úloha má výsledek. + Naplánovaná úloha selhala. 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 ff0a019..51202a0 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -14,10 +14,7 @@ Auf dieser Instanz läuft ein älteres LLeMbas. Diese App braucht LLeMbas 2.0 oder neuer. Diese Instanz spricht eine neuere App-API als diese App. Aktualisieren Sie die App. Neuer Chat - Chats - Agenten Noch keine Chats. Nicht jeder, der wandert, ist verloren — fangen Sie einen an. - Noch keine Agent-Chats. Starten Sie einen mit „Neuer Agent-Chat“ auf einem Gerät, das mit dieser Instanz verknüpft ist. Neuer Agent-Chat Gerät 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. @@ -110,9 +107,82 @@ 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 + Chats öffnen + Chats durchsuchen + Heute + Früher + Agenten-Chats + Kein Chat hat das im Titel. + Leeren + Sag dem Agenten, was er tun soll + Optionen + Aufwand + Langsamer, und besser bei schwierigen Fragen. + Erst planen + Das Modell schreibt einen Plan, den du genehmigst, bevor es handelt. + Modus + Was soll der Agent tun? + Läuft auf %1$s, in %2$s + seinem ersten Ordner + Modell wählen + In Verwendung + Sieht Bilder + Nutzt Werkzeuge + %1$s Kontext + Nachdenken an oder aus + Aufwand: %1$s + Code + Code kopieren + Text auswählen + %1$s Werkzeuge genutzt + Erkläre + einfach, wie etwas funktioniert + Schreibe + eine E-Mail, eine Notiz oder einen Beitrag + Plane + eine Reise, eine Woche oder ein Projekt + Prüfe + einen Text auf Fehler und Ton + In Verwendung + Benachrichtigungseinstellungen + Welche Arten ankommen und wie: Antworten, Fragen, geplante Ergebnisse und Fehler. + Geplant + Nichts ist geplant. Bitte um etwas, das jeden Morgen geschehen soll, oder einmal nächste Woche. + Diese Instanz bietet noch keine geplanten Aufgaben. Sie kommen mit einem neueren LLeMbas auf dem Server. + Neuer Zeitplan + Zeitplan bearbeiten + Nächstes Mal: %1$s + Pausiert + Pausieren + Fortsetzen + Jetzt ausführen + Gestartet. Das Ergebnis erscheint im Verlauf. + Nächste Läufe + Verlauf + Er ist noch nicht gelaufen. + Modell: %1$s + Diesen Zeitplan löschen? Seine bisherigen Ergebnisse bleiben in ihren Chats. + Sag in eigenen Worten, wann und was. Bevor etwas gespeichert wird, siehst du, wie es verstanden wurde. + Jeden Werktag um 7:30 die Nachrichten über erneuerbare Energie zusammenfassen + Vorschau + Verstanden als + Meldet sich jedes Mal + Meldet sich, wenn es wichtig ist + Meldet sich nie + Fertig + Nichts Neues + Fehlgeschlagen + Verpasst ×%1$s + Übersprungen + Wartet auf ein Modell + Läuft + %1$s (die erste Wahl war beschäftigt) + Geplante Ergebnisse + Geplante Fehler + Eine geplante Aufgabe hat ein Ergebnis. + Eine geplante Aufgabe ist fehlgeschlagen. 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 8adfe8b..b21f4d3 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -14,10 +14,7 @@ Esta instancia usa una versión anterior de LLeMbas. Esta aplicación necesita LLeMbas 2.0 o posterior. Esta instancia habla una API de aplicaciones más reciente que esta aplicación. Actualice la aplicación. Nuevo chat - Chats - Agentes Aún no hay chats. No todos los que vagan están perdidos — empiece uno. - Aún no hay chats de agente. Inicie uno con Nuevo chat de agente, en un dispositivo vinculado a esta instancia. Nuevo chat de agente Dispositivo Ahora no hay ningún dispositivo vinculado. Inicie `lembas service` en un ordenador con sesión iniciada en esta instancia y vuelva. @@ -110,9 +107,82 @@ 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 + Abrir los chats + Buscar chats + Hoy + Antes + Chats de agente + Ningún chat lo tiene en el título. + Borrar + Dile al agente qué hacer + Opciones + Esfuerzo + Más lento, y mejor con preguntas difíciles. + Primero un plan + El modelo escribe un plan que apruebas antes de que actúe. + Modo + ¿Qué debe hacer el agente? + Se ejecuta en %1$s, en %2$s + su primera carpeta + Elegir un modelo + En uso + Ve imágenes + Usa herramientas + contexto de %1$s + Razonamiento sí o no + Esfuerzo: %1$s + Código + Copiar código + Seleccionar texto + Usó %1$s herramientas + Explica + cómo funciona algo, con palabras sencillas + Escribe + un correo, una nota o una publicación + Planifica + un viaje, una semana o un proyecto + Revisa + un texto: errores y tono + En uso + Ajustes de notificaciones + Qué tipos llegan y cómo: respuestas, preguntas, resultados y fallos programados. + Programado + No hay nada programado. Pide algo que ocurra cada mañana, o una vez la semana que viene. + Esta instancia aún no ofrece tareas programadas. Llegan con un LLeMbas más reciente en el servidor. + Nueva programación + Editar programación + Próxima: %1$s + En pausa + Pausar + Reanudar + Ejecutar ahora + Iniciado. El resultado aparece en su historial. + Próximas ejecuciones + Historial + Aún no se ha ejecutado. + Modelo: %1$s + ¿Eliminar esta programación? Sus resultados anteriores se quedan en sus chats. + Di cuándo y qué, con tus palabras. Verás lo que se entendió antes de guardar nada. + Cada día laborable a las 7:30, resume las noticias sobre energías renovables + Vista previa + Entendido como + Avisa siempre + Avisa cuando importa + No avisa nunca + Hecho + Nada nuevo + Fallidos + Perdida ×%1$s + Omitida + Esperando un modelo + En ejecución + %1$s (la primera opción estaba ocupada) + Resultados programados + Fallos programados + Una tarea programada tiene un resultado. + Una tarea programada falló. ¿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 88211b1..8fef4c4 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -14,10 +14,7 @@ Cette instance utilise une version plus ancienne de LLeMbas. Cette application nécessite LLeMbas 2.0 ou plus récent. Cette instance utilise une API d\'application plus récente que cette application. Mettez à jour l\'application. Nouvelle conversation - Conversations - Agents Pas encore de conversation. Tous ceux qui errent ne sont pas perdus — commencez-en une. - Pas encore de conversation d\'agent. Démarrez-en une avec Nouvelle conversation d\'agent, sur un appareil associé à cette instance. Nouvelle conversation d\'agent Appareil Aucun appareil n\'est associé pour l\'instant. Lancez `lembas service` sur un ordinateur connecté à cette instance, puis revenez. @@ -110,9 +107,82 @@ 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 + Ouvrir les discussions + Rechercher dans les discussions + Aujourd’hui + Plus tôt + Discussions d’agent + Aucune discussion ne l’a dans son titre. + Effacer + Dites à l’agent quoi faire + Options + Effort + Plus lent, et meilleur sur les questions difficiles. + D’abord un plan + Le modèle rédige un plan que vous approuvez avant qu’il agisse. + Mode + Que doit faire l’agent ? + S’exécute sur %1$s, dans %2$s + son premier dossier + Choisir un modèle + Utilisé + Voit les images + Utilise des outils + contexte de %1$s + Réflexion activable + Effort : %1$s + Code + Copier le code + Sélectionner le texte + %1$s outils utilisés + Explique + simplement comment quelque chose fonctionne + Rédige + un e-mail, une note ou un billet + Planifie + un voyage, une semaine ou un projet + Relis + un texte : fautes et ton + Utilisée + Réglages des notifications + Quels types arrivent, et comment : réponses, questions, résultats et échecs planifiés. + Planifié + Rien n’est planifié. Demandez quelque chose chaque matin, ou une fois la semaine prochaine. + Cette instance ne propose pas encore de tâches planifiées. Elles arrivent avec un LLeMbas plus récent sur le serveur. + Nouvelle planification + Modifier la planification + Prochaine : %1$s + En pause + Mettre en pause + Reprendre + Exécuter maintenant + Lancé. Le résultat apparaît dans l’historique. + Prochaines exécutions + Historique + Elle ne s’est pas encore exécutée. + Modèle : %1$s + Supprimer cette planification ? Ses résultats passés restent dans leurs discussions. + Dites quand et quoi, avec vos mots. Vous verrez ce qui a été compris avant tout enregistrement. + Chaque jour ouvré à 7 h 30, résume l’actualité des énergies renouvelables + Aperçu + Compris comme + Prévient à chaque fois + Prévient quand c’est important + Ne prévient jamais + Terminé + Rien de neuf + Échecs + Manquée ×%1$s + Sautée + En attente d’un modèle + En cours + %1$s (le premier choix était occupé) + Résultats planifiés + Échecs planifiés + Une tâche planifiée a un résultat. + Une tâche planifiée a échoué. 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 79f56c8..5d0f0f2 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -14,10 +14,7 @@ Ezen a példányon régebbi LLeMbas fut. Ehhez az alkalmazáshoz LLeMbas 2.0 vagy újabb kell. Ez a példány újabb alkalmazás-API-t használ, mint ez az alkalmazás. Frissítse az alkalmazást. Új csevegés - Csevegések - Ügynökök Még nincs csevegés. Nem mindenki van elveszve, aki bolyong — kezdjen el egyet. - 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. Új ügynök-csevegés Eszköz 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. @@ -110,9 +107,82 @@ 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 + Csevegések megnyitása + Keresés a csevegésekben + Ma + Korábban + Ügynök-csevegések + Egy csevegés címében sincs ilyen. + Törlés + Mondja meg az ügynöknek, mit tegyen + Beállítások + Ráfordítás + Lassabb, de jobb a nehéz kérdéseknél. + Előbb terv + A modell tervet ír, amelyet jóváhagy, mielőtt cselekszik. + Mód + Mit tegyen az ügynök? + Itt fut: %1$s, ebben: %2$s + az első mappája + Modell kiválasztása + Használatban + Látja a képeket + Eszközöket használ + %1$s kontextus + Gondolkodás be- vagy kikapcsolva + Ráfordítás: %1$s + Kód + Kód másolása + Szöveg kijelölése + %1$s eszköz használva + Magyarázd el, + hogyan működik valami, egyszerűen + Írj + e-mailt, jegyzetet vagy bejegyzést + Tervezz meg + egy utat, egy hetet vagy egy projektet + Ellenőrizz + egy szöveget: hibák és hangnem + Használatban + Értesítési beállítások + Milyen értesítések jönnek és hogyan: válaszok, kérdések, ütemezett eredmények és hibák. + Ütemezett + Nincs semmi ütemezve. Kérjen valamit minden reggelre, vagy egyszer a jövő hétre. + Ez a példány még nem kínál ütemezett feladatokat. Egy újabb LLeMbas-szal érkeznek a szerveren. + Új ütemezés + Ütemezés szerkesztése + Következő: %1$s + Szüneteltetve + Szüneteltetés + Folytatás + Futtatás most + Elindítva. Az eredmény az előzményekben jelenik meg. + Következő futások + Előzmények + Még nem futott. + Modell: %1$s + Törli ezt az ütemezést? A korábbi eredményei megmaradnak a csevegéseikben. + Mondja el saját szavaival, mikor és mit. Mentés előtt látja, mit értett meg belőle. + Minden hétköznap 7:30-kor foglald össze a megújuló energiáról szóló híreket + Előnézet + Így értelmezve + Mindig szól + Szól, ha számít + Soha nem szól + Kész + Semmi új + Sikertelen + Kimaradt ×%1$s + Kihagyva + Modellre vár + Fut + %1$s (az első választás foglalt volt) + Ütemezett eredmények + Ütemezett hibák + Egy ütemezett feladatnak eredménye van. + Egy ütemezett feladat sikertelen volt. 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 c59b6bf..be74ae1 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -14,10 +14,7 @@ Questa istanza usa una versione precedente di LLeMbas. Questa app richiede LLeMbas 2.0 o successivo. Questa istanza usa un\'API per l\'app più recente di questa app. Aggiorna l\'app. Nuova chat - Chat - Agenti Ancora nessuna chat. Non tutti quelli che vagano sono perduti — iniziane una. - Ancora nessuna chat agente. Avviane una con Nuova chat agente, su un dispositivo collegato a questa istanza. Nuova chat agente Dispositivo Nessun dispositivo è collegato ora. Avvia `lembas service` su un computer connesso a questa istanza, poi torna qui. @@ -110,9 +107,82 @@ 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 + Apri le chat + Cerca nelle chat + Oggi + Prima + Chat con agente + Nessuna chat lo ha nel titolo. + Svuota + Di’ all’agente cosa fare + Opzioni + Impegno + Più lento, e migliore con le domande difficili. + Prima un piano + Il modello scrive un piano da approvare prima di agire. + Modalità + Cosa deve fare l’agente? + Gira su %1$s, in %2$s + la sua prima cartella + Scegli un modello + In uso + Vede le immagini + Usa strumenti + contesto di %1$s + Ragionamento attivabile + Impegno: %1$s + Codice + Copia codice + Seleziona testo + Usati %1$s strumenti + Spiega + come funziona qualcosa, in parole semplici + Scrivi + un’email, una nota o un post + Pianifica + un viaggio, una settimana o un progetto + Controlla + un testo: errori e tono + In uso + Impostazioni delle notifiche + Quali tipi arrivano e come: risposte, domande, risultati e errori pianificati. + Pianificato + Non c’è niente in programma. Chiedi qualcosa ogni mattina, o una volta la settimana prossima. + Questa istanza non offre ancora attività pianificate. Arrivano con un LLeMbas più recente sul server. + Nuova pianificazione + Modifica pianificazione + Prossima: %1$s + In pausa + Metti in pausa + Riprendi + Esegui ora + Avviato. Il risultato appare nella cronologia. + Prossime esecuzioni + Cronologia + Non è ancora stata eseguita. + Modello: %1$s + Eliminare questa pianificazione? I risultati passati restano nelle loro chat. + Di’ quando e cosa, con parole tue. Vedrai cosa è stato capito prima di salvare. + Ogni giorno feriale alle 7:30, riassumi le notizie sulle energie rinnovabili + Anteprima + Capito come + Avvisa ogni volta + Avvisa quando conta + Non avvisa mai + Fatto + Niente di nuovo + Non riusciti + Saltata ×%1$s + Ignorata + In attesa di un modello + In esecuzione + %1$s (la prima scelta era occupata) + Risultati pianificati + Errori pianificati + Un’attività pianificata ha un risultato. + Un’attività pianificata non è riuscita. 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 c479eb3..8ab26d8 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -14,10 +14,7 @@ Ta instancja działa na starszym LLeMbas. Ta aplikacja wymaga LLeMbas 2.0 lub nowszego. Ta instancja używa nowszego API aplikacji niż ta aplikacja. Zaktualizuj aplikację. Nowy czat - Czaty - Agenci Nie ma jeszcze czatów. Nie każdy, kto błądzi, jest zgubiony — zacznij jeden. - Brak czatów agenta. Zacznij jeden przyciskiem Nowy czat agenta, na urządzeniu połączonym z tą instancją. Nowy czat agenta Urządzenie Żadne urządzenie nie jest teraz połączone. Uruchom `lembas service` na komputerze zalogowanym do tej instancji i wróć. @@ -110,9 +107,82 @@ 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 + Otwórz czaty + Szukaj czatów + Dzisiaj + Wcześniej + Czaty z agentem + Żaden czat nie ma tego w tytule. + Wyczyść + Powiedz agentowi, co ma zrobić + Opcje + Wysiłek + Wolniej, i lepiej przy trudnych pytaniach. + Najpierw plan + Model pisze plan do zatwierdzenia, zanim zacznie działać. + Tryb + Co ma zrobić agent? + Działa na %1$s, w %2$s + jego pierwszym folderze + Wybierz model + W użyciu + Widzi obrazy + Używa narzędzi + kontekst %1$s + Myślenie włączane lub wyłączane + Wysiłek: %1$s + Kod + Kopiuj kod + Zaznacz tekst + Użyte narzędzia: %1$s + Wyjaśnij + prostymi słowami, jak coś działa + Napisz + e-mail, notatkę lub wpis + Zaplanuj + podróż, tydzień lub projekt + Sprawdź + tekst pod kątem błędów i tonu + W użyciu + Ustawienia powiadomień + Jakie rodzaje przychodzą i jak: odpowiedzi, pytania, wyniki i błędy zaplanowanych zadań. + Zaplanowane + Nic nie jest zaplanowane. Poproś o coś, co ma się dziać każdego ranka albo raz w przyszłym tygodniu. + Ta instancja nie oferuje jeszcze zaplanowanych zadań. Pojawią się z nowszym LLeMbas na serwerze. + Nowy harmonogram + Edytuj harmonogram + Następnie: %1$s + Wstrzymano + Wstrzymaj + Wznów + Uruchom teraz + Uruchomiono. Wynik pojawi się w historii. + Następne uruchomienia + Historia + Jeszcze się nie uruchomił. + Model: %1$s + Usunąć ten harmonogram? Jego wcześniejsze wyniki zostaną w swoich czatach. + Powiedz własnymi słowami, kiedy i co. Zanim cokolwiek zostanie zapisane, zobaczysz, jak to zrozumiano. + W każdy dzień roboczy o 7:30 streść wiadomości o energii odnawialnej + Podgląd + Zrozumiano jako + Powiadamia za każdym razem + Powiadamia, gdy to ważne + Nigdy nie powiadamia + Gotowe + Nic nowego + Nieudane + Pominięto ×%1$s + Pominięto + Czeka na model + Działa + %1$s (pierwszy wybór był zajęty) + Wyniki zaplanowanych zadań + Błędy zaplanowanych zadań + Zaplanowane zadanie ma wynik. + Zaplanowane zadanie się nie powiodło. 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 05dd49f..c456acc 100644 --- a/app/src/main/res/values-sk/strings.xml +++ b/app/src/main/res/values-sk/strings.xml @@ -14,10 +14,7 @@ Táto inštancia beží na staršom LLeMbas. Táto aplikácia potrebuje LLeMbas 2.0 alebo novší. Táto inštancia používa novšie API pre aplikácie než táto aplikácia. Aktualizujte aplikáciu. Nová konverzácia - Konverzácie - Agenti Zatiaľ žiadne konverzácie. Nie všetci, čo blúdia, sú stratení — začnite jednu. - Zatiaľ žiadne konverzácie s agentom. Spustite jednu tlačidlom Nová konverzácia s agentom na zariadení prepojenom s touto inštanciou. Nová konverzácia s agentom Zariadenie Práve nie je prepojené žiadne zariadenie. Spustite `lembas service` na počítači prihlásenom do tejto inštancie a vráťte sa. @@ -110,9 +107,82 @@ 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é + Otvoriť čety + Hľadať v četoch + Dnes + Skôr + Čety s agentom + Žiadny čet to nemá v názve. + Vymazať + Povedzte agentovi, čo má urobiť + Možnosti + Úsilie + Pomalšie a lepšie pri ťažkých otázkach. + Najprv plán + Model napíše plán, ktorý schválite, skôr než začne konať. + Režim + Čo má agent urobiť? + Beží na %1$s, v priečinku %2$s + jeho prvý priečinok + Vyberte model + Používa sa + Vidí obrázky + Používa nástroje + kontext %1$s + Premýšľanie zapnúť alebo vypnúť + Úsilie: %1$s + Kód + Skopírovať kód + Vybrať text + Použité nástroje: %1$s + Vysvetli + jednoducho, ako niečo funguje + Napíš + e-mail, poznámku alebo príspevok + Naplánuj + výlet, týždeň alebo projekt + Skontroluj + text, chyby a tón + Používa sa + Nastavenia upozornení + Ktoré druhy prichádzajú a ako: odpovede, otázky, výsledky a zlyhania naplánovaných úloh. + Naplánované + Nič nie je naplánované. Požiadajte o niečo, čo sa má stať každé ráno, alebo raz budúci týždeň. + Táto inštancia zatiaľ neponúka naplánované úlohy. Prídu s novším LLeMbas na serveri. + Nový plán + Upraviť plán + Nabudúce: %1$s + Pozastavené + Pozastaviť + Pokračovať + Spustiť teraz + Spustené. Výsledok sa objaví v histórii. + Ďalšie spustenia + História + Ešte nebežal. + Model: %1$s + Zmazať tento plán? Jeho doterajšie výsledky zostanú vo svojich četoch. + Povedzte vlastnými slovami kedy a čo. Skôr než sa čokoľvek uloží, uvidíte, ako to bolo pochopené. + Každý pracovný deň o 7:30 zhrň správy o obnoviteľnej energii + Náhľad + Pochopené ako + Dá vedieť zakaždým + Dá vedieť, keď na tom záleží + Nedá vedieť nikdy + Hotovo + Nič nové + Zlyhalo + Zmeškané ×%1$s + Vynechané + Čaká na model + Beží + %1$s (prvá voľba bola zaneprázdnená) + Výsledky naplánovaných úloh + Zlyhania naplánovaných úloh + Naplánovaná úloha má výsledok. + Naplánovaná úloha zlyhala. 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 00426e2..c3ed192 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -15,10 +15,7 @@ This instance runs an older LLeMbas. This app needs LLeMbas 2.0 or newer. This instance speaks a newer app API than this app. Update the app. New chat - Chats - Agents No chats yet. Not all those who wander are lost — start one. - No agent chats yet. Start one with New agent chat, on a device linked to this instance. New agent chat Device No device is linked right now. Start `lembas service` on a computer signed in to this instance, then come back. @@ -111,9 +108,82 @@ 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 + Open the chats + Search chats + Today + Earlier + Agent chats + No chat has that in its title. + Clear + Tell the agent what to do + Options + Effort + Slower, and better at hard questions. + Plan first + The model writes a plan for you to approve before it acts. + Mode + What should the agent do? + Runs on %1$s, in %2$s + its first folder + Choose a model + In use + Sees images + Uses tools + %1$s context + Thinking on or off + Effort: %1$s + Code + Copy code + Select text + Used %1$s tools + Explain + how something works, in plain words + Write + an email, a note or a post + Plan + a trip, a week or a project + Check + a text for mistakes and tone + In use + Notification settings + Which kinds arrive, and how: replies, questions, scheduled results and failures. + Scheduled + Nothing is scheduled. Ask for something to happen every morning, or once next week. + This instance does not offer scheduled tasks yet. They come with a newer LLeMbas on the server. + New schedule + Edit schedule + Next: %1$s + Paused + Pause + Resume + Run now + Started. The result appears in its history. + Next runs + History + It has not run yet. + Model: %1$s + Delete this schedule? Its past results stay in their chats. + Say when and what, in your own words. You will see what was understood before anything is saved. + Every weekday at 7:30, sum up the news about renewable energy + Preview + Understood as + Tells you every time + Tells you when it matters + Never tells you + Done + Nothing new + Failed + Missed ×%1$s + Skipped + Waiting for a model + Running + %1$s (the first choice was busy) + Scheduled results + Scheduled failures + A scheduled task has a result. + A scheduled task failed. Allow this? Allow once Always allow this diff --git a/app/src/test/java/eu/llembas/android/ChatGroupsTest.kt b/app/src/test/java/eu/llembas/android/ChatGroupsTest.kt new file mode 100644 index 0000000..f8ed01e --- /dev/null +++ b/app/src/test/java/eu/llembas/android/ChatGroupsTest.kt @@ -0,0 +1,44 @@ +package eu.llembas.android + +import eu.llembas.android.api.Chat +import eu.llembas.android.ui.home.groupChats +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.LocalDate +import java.time.ZoneId + +class ChatGroupsTest { + private val zone = ZoneId.of("Europe/Bratislava") + private val today = LocalDate.of(2026, 3, 10) + + private fun chat(id: String, title: String, updated: String?, kind: String = "chat") = Chat(id = id, title = title, kind = kind, updatedAt = updated) + + @Test + fun todayEarlierAndAgentsKeepTheirOrder() { + val chats = listOf( + chat("a", "Bread", "2026-03-10T08:00:00+00:00"), + chat("b", "Repo", "2026-03-10T07:00:00+00:00", kind = "agent"), + chat("c", "Honey", "2026-03-09T12:00:00+00:00"), + chat("d", "Old", null), + ) + val groups = groupChats(chats, "", today, zone) + assertEquals(listOf("a"), groups.today.map { it.id }) + assertEquals(listOf("c", "d"), groups.earlier.map { it.id }) + assertEquals(listOf("b"), groups.agents.map { it.id }) + } + + @Test + fun theDayIsThePhones() { + // 23:30 UTC on the 9th is already the 10th in Central Europe. + val groups = groupChats(listOf(chat("a", "Late", "2026-03-09T23:30:00+00:00")), "", today, zone) + assertEquals(listOf("a"), groups.today.map { it.id }) + } + + @Test + fun searchMatchesTheTitleInAnyCase() { + val chats = listOf(chat("a", "Lembas bread", null), chat("b", "Ropes", null)) + assertEquals(listOf("a"), groupChats(chats, " BREAD ", today, zone).earlier.map { it.id }) + assertTrue(groupChats(chats, "nothing", today, zone).isEmpty) + } +} diff --git a/app/src/test/java/eu/llembas/android/ChatStateTest.kt b/app/src/test/java/eu/llembas/android/ChatStateTest.kt new file mode 100644 index 0000000..c570678 --- /dev/null +++ b/app/src/test/java/eu/llembas/android/ChatStateTest.kt @@ -0,0 +1,69 @@ +package eu.llembas.android + +import eu.llembas.android.api.AgentsSetting +import eu.llembas.android.api.Chat +import eu.llembas.android.api.LembasJson +import eu.llembas.android.api.LinkedDevice +import eu.llembas.android.api.ModelList +import eu.llembas.android.ui.chat.ChatState +import eu.llembas.android.ui.chat.Draft +import eu.llembas.android.ui.chat.agents +import eu.llembas.android.ui.chat.compactContext +import eu.llembas.android.ui.chat.device +import eu.llembas.android.ui.chat.level +import eu.llembas.android.ui.chat.modelId +import eu.llembas.android.ui.chat.offersTeam +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** What the top bar, the composer and the tune sheet read from a chat's state. */ +class ChatStateTest { + private val models = LembasJson.decodeFromString( + ModelList.serializer(), + requireNotNull(javaClass.classLoader!!.getResource("models.json")).readText(), + ).models + + @Test + fun theModelIsTheChatsThenTheDraftsThenTheDefault() { + assertEquals("qwen", ChatState(models = models).modelId) + assertEquals("gpt-oss", ChatState(models = models, draft = Draft(model = "gpt-oss")).modelId) + assertEquals("vision-small", ChatState(models = models, chat = Chat(id = "c", model = "vision-small"), draft = Draft(model = "gpt-oss")).modelId) + } + + @Test + fun theLevelFollowsTheModelsControl() { + // A switch model starts at its effort; one level is no choice at all. + assertEquals("medium", ChatState(models = models).level) + assertEquals("off", ChatState(models = models, draft = Draft(effort = "off")).level) + assertNull(ChatState(models = models, draft = Draft(model = "vision-small")).level) + // A level the model does not offer falls back to its own. + assertEquals("high", ChatState(models = models, chat = Chat(id = "c", model = "gpt-oss", effort = "extreme")).level) + } + + @Test + fun aTeamIsOfferedByTheServerOrGuessedForANewChat() { + assertTrue(ChatState(models = models).offersTeam(agent = false)) + assertFalse(ChatState(models = models).offersTeam(agent = true)) + assertFalse(ChatState(models = models, draft = Draft(model = "gpt-oss")).offersTeam(agent = false)) + assertTrue(ChatState(models = models, chat = Chat(id = "c", model = "gpt-oss"), teamOffered = true).offersTeam(agent = false)) + assertEquals(AgentsSetting(2, 6), ChatState(draft = Draft(agents = AgentsSetting(2, 6))).agents) + } + + @Test + fun aNewAgentChatRunsOnTheChosenDeviceOrTheFirst() { + val devices = listOf(LinkedDevice("d1"), LinkedDevice("d2")) + assertEquals("d1", ChatState(devices = devices).device?.id) + assertEquals("d2", ChatState(devices = devices, draft = Draft(device = "d2")).device?.id) + assertNull(ChatState().device) + } + + @Test + fun contextWindowsAreSaidShort() { + assertEquals("128K", compactContext(131072)) + assertEquals("8K", compactContext(8192)) + assertEquals("1M", compactContext(1_000_000)) + } +} diff --git a/app/src/test/java/eu/llembas/android/MarkdownSplitTest.kt b/app/src/test/java/eu/llembas/android/MarkdownSplitTest.kt new file mode 100644 index 0000000..8e5d98a --- /dev/null +++ b/app/src/test/java/eu/llembas/android/MarkdownSplitTest.kt @@ -0,0 +1,50 @@ +package eu.llembas.android + +import eu.llembas.android.ui.Segment +import eu.llembas.android.ui.splitFences +import org.junit.Assert.assertEquals +import org.junit.Test + +class MarkdownSplitTest { + @Test + fun proseOnlyIsOnePiece() { + assertEquals(listOf(Segment.Prose("Hello *there*.")), splitFences("Hello *there*.\n")) + } + + @Test + fun aFenceBetweenProse() { + val split = splitFences("Here is how:\n\n```sh\nbake --slow\n```\n\nDone.") + assertEquals( + listOf(Segment.Prose("Here is how:"), Segment.Code("sh", "bake --slow"), Segment.Prose("Done.")), + split, + ) + } + + @Test + fun anUnclosedFenceRunsToTheEndWhileWritten() { + val split = splitFences("Code:\n```kotlin\nval a = 1\nval b") + assertEquals(listOf(Segment.Prose("Code:"), Segment.Code("kotlin", "val a = 1\nval b", closed = false)), split) + } + + @Test + fun aLongerFenceHoldsAShorterOne() { + val split = splitFences("````md\n```\ninner\n```\n````") + assertEquals(listOf(Segment.Code("md", "```\ninner\n```")), split) + } + + @Test + fun tildesAndNoLanguage() { + assertEquals(listOf(Segment.Code("", "x")), splitFences("~~~\nx\n~~~")) + } + + @Test + fun aFenceInsideAListStaysProse() { + val text = "1. Run it:\n\n ```sh\n make\n ```" + assertEquals(listOf(Segment.Prose(text)), splitFences(text)) + } + + @Test + fun inlineBackticksAreNotAFence() { + assertEquals(listOf(Segment.Prose("Use ``` to fence code.")), splitFences("Use ``` to fence code.")) + } +} diff --git a/app/src/test/java/eu/llembas/android/ScheduleLogicTest.kt b/app/src/test/java/eu/llembas/android/ScheduleLogicTest.kt new file mode 100644 index 0000000..e9e45a0 --- /dev/null +++ b/app/src/test/java/eu/llembas/android/ScheduleLogicTest.kt @@ -0,0 +1,45 @@ +package eu.llembas.android + +import eu.llembas.android.api.LembasJson +import eu.llembas.android.api.ScheduleList +import eu.llembas.android.ui.scheduled.ScheduleLogic +import eu.llembas.android.ui.scheduled.Tone +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import java.time.ZoneId +import java.util.Locale + +class ScheduleLogicTest { + private val zone = ZoneId.of("Europe/Bratislava") + + @Test + fun statusesHaveTones() { + assertEquals(Tone.Good, ScheduleLogic.tone("ok")) + assertEquals(Tone.Quiet, ScheduleLogic.tone("silent")) + assertEquals(Tone.Bad, ScheduleLogic.tone("failed")) + assertEquals(Tone.Bad, ScheduleLogic.tone("missed")) + assertEquals(Tone.Waiting, ScheduleLogic.tone("waiting")) + assertEquals(Tone.Neutral, ScheduleLogic.tone("something new")) + } + + @Test + fun aMomentIsShownWhereThePhoneIs() { + assertEquals("Tue 10 Mar, 08:00", ScheduleLogic.moment("2026-03-10T07:00:00+00:00", zone, Locale.ENGLISH)) + assertNull(ScheduleLogic.moment("tomorrow", zone, Locale.ENGLISH)) + assertNull(ScheduleLogic.moment(null, zone, Locale.ENGLISH)) + } + + @Test + fun upcomingKeepsFiveReadableRuns() { + val runs = (1..7).map { "2026-03-1${it}T07:00:00+00:00" } + "nonsense" + assertEquals(5, ScheduleLogic.upcoming(runs, zone = zone, locale = Locale.ENGLISH).size) + } + + @Test + fun aScheduleListThatSaysLittleStillParses() { + val list = LembasJson.decodeFromString(ScheduleList.serializer(), """{"schedules":[{"id":"s1","paused":true,"later":1}]}""") + assertEquals("s1", list.schedules.single().id) + assertNull(list.schedules.single().nextRun) + } +} diff --git a/app/src/test/java/eu/llembas/android/shots/Fakes.kt b/app/src/test/java/eu/llembas/android/shots/Fakes.kt index c3d4bfa..c301c3d 100644 --- a/app/src/test/java/eu/llembas/android/shots/Fakes.kt +++ b/app/src/test/java/eu/llembas/android/shots/Fakes.kt @@ -1,14 +1,220 @@ package eu.llembas.android.shots +import eu.llembas.android.api.ActivitySummary +import eu.llembas.android.api.AgentsSetting +import eu.llembas.android.api.Attachment +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 +import eu.llembas.android.api.Metrics import eu.llembas.android.api.ModelList +import eu.llembas.android.api.Schedule +import eu.llembas.android.api.SchedulePreview +import eu.llembas.android.api.ScheduleRun +import eu.llembas.android.api.Step +import eu.llembas.android.api.Tail +import eu.llembas.android.api.ToolBlock +import eu.llembas.android.api.ToolCall +import eu.llembas.android.auth.Instance +import eu.llembas.android.auth.Prefs +import eu.llembas.android.ui.chat.ChatState +import eu.llembas.android.ui.chat.Draft +import eu.llembas.android.ui.home.ChatsState +import eu.llembas.android.ui.scheduled.EditState +import eu.llembas.android.ui.scheduled.ScheduleState +import eu.llembas.android.ui.scheduled.ScheduledState +import eu.llembas.android.ui.settings.SettingsState +import java.time.LocalDate /** Made-up data for the screenshots: the server's own contract files where they fit. */ object Fakes { private fun text(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")).readText() + /** The day the drawer is drawn on: chats updated on it are "Today". */ + val today: LocalDate = LocalDate.of(2026, 3, 10) + val models = LembasJson.decodeFromString(ModelList.serializer(), text("models")).models val question = LembasJson.decodeFromString(Message.serializer(), text("message_user")) val answer = LembasJson.decodeFromString(Message.serializer(), text("message_assistant")) + + private val packing = Message( + id = "m3", + role = "user", + text = "Plan a three-day walk to the hills. What should I pack?", + attachments = listOf(Attachment(id = "a1", name = "map.jpg", image = true), Attachment(id = "a2", name = "route.gpx", mime = "application/gpx+xml")), + ) + + private val packingSteps = listOf( + Step( + index = 0, + kind = "thinking", + text = "Three days, hills, early spring: warm layers, water, food that keeps.", + label = "for 4 seconds · 120 tokens", + ), + Step( + index = 0, + kind = "tools", + calls = listOf( + ToolCall(id = "c1", name = "web_search", status = "ok", block = ToolBlock(kind = "web", title = "weather in the hills next week")), + ToolCall( + id = "c2", + name = "read", + status = "ok", + text = "Day 1: 18 km\nDay 2: 22 km\nDay 3: 15 km", + block = ToolBlock(kind = "read", title = "notes/route.md"), + ), + ), + ), + Step( + index = 1, + kind = "text", + markdown = "Here is a list for **three days**, light enough to carry:\n\n" + + "- Lembas, wrapped in leaves (one bite fills a grown man)\n" + + "- A warm cloak and a spare pair of socks\n" + + "- Two litres of water, and a way to refill it\n\n" + + "```python\ndef pack(days):\n return [\"lembas\"] * days + [\"cloak\", \"rope\"]\n```\n\n" + + "The second day is the longest: start early.", + ), + ) + + private val packingAnswer = Message( + id = "m4", + role = "assistant", + model = "qwen", + steps = packingSteps, + metrics = Metrics(completionTokens = 412, elapsedMs = 9000, tokPerSecond = 45.8), + ) + + val chat = Chat(id = "c1", title = "Packing for the road", model = "qwen", updatedAt = "2026-03-10T09:00:00+00:00") + + val newChat = ChatState(models = models) + + val newAgentChat = ChatState( + models = models, + devices = listOf(LinkedDevice(id = "d1", name = "Workstation", host = "workstation"), LinkedDevice(id = "d2", name = "Laptop", host = "laptop")), + draft = Draft(directory = "~/src/garden"), + ) + + val transcript = ChatState( + chat = chat, + messages = listOf(question, answer, packing, packingAnswer), + models = models, + teamOffered = true, + summary = ActivitySummary(working = 2, active = 2, total = 2), + ) + + /** The last reply while it is being written: its tools done, its words coming in. */ + val writing = transcript.copy( + messages = listOf(question, answer, packing, packingAnswer.copy(steps = emptyList(), complete = false)), + live = LiveReply(messageId = "m4", steps = packingSteps.take(2), tail = Tail(text = "Here is a list for **three days**, light enough")), + summary = null, + ) + + /** A chat on a model with effort levels, a team and a plan: the tune sheet with everything. */ + val tuned = transcript.copy( + chat = chat.copy(model = "gpt-oss", effort = "high", mode = "plan", agents = AgentsSetting(1, 4)), + ) + + val chats = ChatsState( + chats = listOf( + chat, + Chat(id = "c2", title = "Repairing the garden gate", kind = "agent", updatedAt = "2026-03-10T08:00:00+00:00", running = true), + Chat(id = "c3", title = "A letter to the mayor about the bridge", updatedAt = "2026-03-10T07:00:00+00:00", unread = true), + Chat(id = "c4", title = "Sourdough timings", updatedAt = "2026-03-09T18:00:00+00:00"), + Chat(id = "c5", title = "Translate the recipe into Slovak", updatedAt = "2026-03-08T10:00:00+00:00"), + Chat(id = "c6", title = "Why do leaves keep bread fresh, and does it work with any leaf or only some?", updatedAt = "2026-03-01T10:00:00+00:00"), + Chat(id = "c7", title = "Clean up the build scripts", kind = "agent", updatedAt = "2026-03-02T10:00:00+00:00"), + ), + ) + + private val home = Instance(id = "i1", base = "https://llm.example.org", name = "Home", email = "frodo@example.org", sealedToken = "") + private val work = Instance(id = "i2", base = "https://ai.example.com", name = "Work", email = "f.baggins@example.com", sealedToken = "") + + val settings = SettingsState( + instances = listOf(home, work), + active = home, + prefs = Prefs(theme = "", assistantTemporary = true), + hasDistributor = true, + version = "1.0.0-beta.3", + selfUpdate = true, + ) + + private val ok = + ScheduleRun(id = "r1", dueAt = "2026-03-10T06:30:00+00:00", startedAt = "2026-03-10T06:30:02+00:00", status = "ok", model = "qwen", chatId = "c9") + private val nextRuns = (11..17).map { "2026-03-${it}T06:30:00+00:00" } + + val schedules = listOf( + Schedule( + id = "s1", + title = "Morning news on renewables", + instruction = "Sum up the news about renewable energy from the last day, in five points.", + rule = "Every weekday at 07:30", + nextRuns = nextRuns, + lastRun = ok, + model = "qwen", + notify = "matters", + ), + Schedule( + id = "s2", + title = "Check the garden sensors", + instruction = "Read the sensors and tell me if the soil is too dry.", + rule = "Every 3 hours", + nextRuns = listOf("2026-03-10T12:00:00+00:00"), + lastRun = ScheduleRun(id = "r2", status = "silent"), + ), + Schedule( + id = "s3", + title = "Weekly backup report", + instruction = "Summarise last week's backups and anything that failed.", + rule = "Every Monday at 09:00", + paused = true, + lastRun = ScheduleRun(id = "r3", status = "failed", error = "The model could not be reached."), + ), + Schedule( + id = "s4", + title = "Dentist", + instruction = "Remind me to call the dentist.", + rule = "Once, on Thursday at 10:00", + nextRuns = listOf("2026-03-12T09:00:00+00:00"), + lastRun = ScheduleRun(id = "r4", status = "waiting"), + ), + ) + + val scheduled = ScheduledState(schedules = schedules) + + val schedule = ScheduleState( + schedule = schedules[0], + runs = listOf( + ok, + ScheduleRun( + id = "r0", + startedAt = "2026-03-09T06:41:00+00:00", + status = "ok", + model = "gpt-oss", + modelReason = "switched: qwen busy", + chatId = "c8", + ), + ScheduleRun(id = "r-1", dueAt = "2026-03-06T06:30:00+00:00", status = "silent", model = "qwen"), + ScheduleRun(id = "r-2", dueAt = "2026-03-05T06:30:00+00:00", status = "missed", missed = 2), + ScheduleRun( + id = "r-3", + startedAt = "2026-03-04T06:30:00+00:00", + status = "failed", + model = "qwen", + error = "The model stopped answering after 10 minutes.", + ), + ), + ) + + val editing = EditState( + words = "Every weekday at 7:30, sum up the news about renewable energy in five points", + preview = SchedulePreview( + title = "Morning news on renewables", + ruleText = "Every weekday at 07:30", + instruction = "Sum up the news about renewable energy from the last day, in five points.", + nextRuns = nextRuns, + ), + ) } diff --git a/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt b/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt index 23dd46c..0fececd 100644 --- a/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt +++ b/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt @@ -1,28 +1,143 @@ package eu.llembas.android.shots -import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.DrawerValue +import androidx.compose.material3.ModalNavigationDrawer +import androidx.compose.material3.Surface +import androidx.compose.material3.rememberDrawerState +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp -import eu.llembas.android.ui.chat.Steps -import eu.llembas.android.ui.chat.UserBubble +import eu.llembas.android.ui.chat.ChatActions +import eu.llembas.android.ui.chat.ChatContent +import eu.llembas.android.ui.chat.ModelPickerContent +import eu.llembas.android.ui.chat.TuneContent +import eu.llembas.android.ui.chat.modelId +import eu.llembas.android.ui.home.DrawerActions +import eu.llembas.android.ui.home.DrawerContent +import eu.llembas.android.ui.scheduled.ScheduleContent +import eu.llembas.android.ui.scheduled.ScheduleEditContent +import eu.llembas.android.ui.scheduled.ScheduledContent +import eu.llembas.android.ui.settings.SettingsActions +import eu.llembas.android.ui.settings.SettingsContent +import eu.llembas.android.ui.theme.LocalPalette import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.robolectric.annotation.GraphicsMode +import java.time.ZoneOffset -/** The app's screens with made-up data ([Fakes]), as a phone shows them. See [shoot]. */ +private object NoChatActions : ChatActions + +private object NoDrawerActions : DrawerActions + +private object NoSettingsActions : SettingsActions + +/** + * The app's screens with made-up data ([Fakes]), as a phone shows them: each in Shire and + * Moria, at a large phone's size and, where things crowd, a small one's and with large type. + * See [shoot]. These are looked at after every design change; they assert nothing. + */ @RunWith(RobolectricTestRunner::class) @GraphicsMode(GraphicsMode.Mode.NATIVE) @Config(sdk = [35], qualifiers = "xhdpi") class ScreenShots { @Test - fun transcript() = shoot("transcript") { - Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) { - UserBubble(Fakes.question) - Steps(Fakes.answer.steps) + fun newChat() { + shoot("01-new-chat") { ChatContent(Fakes.newChat, NoChatActions, agent = false) } + shoot("01-new-chat", Phone.Small) { ChatContent(Fakes.newChat, NoChatActions, agent = false) } + } + + @Test + fun newAgentChat() = shoot("02-new-agent-chat") { ChatContent(Fakes.newAgentChat, NoChatActions, agent = true) } + + @Test + fun transcript() { + shoot("03-transcript") { ChatContent(Fakes.transcript, NoChatActions, agent = false) } + shoot("03-transcript", Phone.Small) { ChatContent(Fakes.transcript, NoChatActions, agent = false) } + shoot("03-transcript", Phone.Small, fontScale = 1.5f) { ChatContent(Fakes.transcript, NoChatActions, agent = false) } + } + + @Test + fun writing() = shoot("04-writing") { ChatContent(Fakes.writing, NoChatActions, agent = false) } + + @Test + fun drawer() { + val drawn: @Composable () -> Unit = { + ModalNavigationDrawer( + drawerState = rememberDrawerState(DrawerValue.Open), + drawerContent = { + DrawerContent( + Fakes.chats, + current = "c1", + account = "Home · frodo@example.org", + actions = NoDrawerActions, + today = Fakes.today, + zone = ZoneOffset.UTC, + ) + }, + ) { ChatContent(Fakes.transcript, NoChatActions, agent = false) } + } + shoot("05-drawer", content = drawn) + shoot("05-drawer", Phone.Small, content = drawn) + } + + @Test + fun modelPicker() = shoot("06-model-picker") { + SheetOver { ModelPickerContent(Fakes.models, Fakes.transcript.modelId, onPick = {}) } + } + + @Test + fun tune() = shoot("07-tune") { + SheetOver { TuneContent(Fakes.tuned, NoChatActions, agent = false) } + } + + @Test + fun settings() { + shoot("08-settings") { SettingsContent(Fakes.settings, NoSettingsActions) } + shoot("08-settings", Phone.Small) { SettingsContent(Fakes.settings, NoSettingsActions) } + } + + @Test + fun scheduled() { + shoot("09-scheduled") { ScheduledContent(Fakes.scheduled) } + shoot("09-scheduled", Phone.Small) { ScheduledContent(Fakes.scheduled) } + } + + @Test + fun schedule() = shoot("10-schedule") { ScheduleContent(Fakes.schedule) } + + @Test + fun scheduleEdit() = shoot("11-schedule-edit") { ScheduleEditContent(Fakes.editing, editing = false) } +} + +/** + * A bottom sheet's content as the sheet shows it, over a dimmed page: the sheet itself is a + * window of its own, which a screenshot of the page does not hold. + */ +@Composable +private fun SheetOver(content: @Composable () -> Unit) { + val palette = LocalPalette.current + Box(Modifier.fillMaxSize().background(palette.bg)) { + Box(Modifier.fillMaxSize().background(palette.inkInverse.copy(alpha = 0.5f))) + Surface( + color = palette.surface, + shape = RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp), + modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth(), + ) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Box(Modifier.padding(vertical = 16.dp).size(width = 32.dp, height = 4.dp).background(palette.inkFaint, RoundedCornerShape(2.dp))) + content() + } } } } diff --git a/scripts/strings.py b/scripts/strings.py index 3072b4b..31b3c83 100755 --- a/scripts/strings.py +++ b/scripts/strings.py @@ -27,10 +27,7 @@ STRINGS: dict[str, str] = { "signin_too_new": "This instance speaks a newer app API than this app. Update the app.", # Chats "new_chat": "New chat", - "tab_chats": "Chats", - "tab_agents": "Agents", "empty_chats": "No chats yet. Not all those who wander are lost — start one.", - "empty_agents": "No agent chats yet. Start one with New agent chat, on a device linked to this instance.", "new_agent_chat": "New agent chat", "agent_device": "Device", "agent_no_device": "No device is linked right now. Start `lembas service` on a computer signed in to this instance, then come back.", @@ -124,9 +121,84 @@ STRINGS: dict[str, str] = { "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", + # The redesign: drawer, composer, tune sheet, model picker, transcript + "chats_open": "Open the chats", + "chats_search": "Search chats", + "chats_today": "Today", + "chats_earlier": "Earlier", + "chats_agents": "Agent chats", + "chats_none_found": "No chat has that in its title.", + "clear": "Clear", + "composer_hint_agent": "Tell the agent what to do", + "tune": "Options", + "effort": "Effort", + "thinking_switch_hint": "Slower, and better at hard questions.", + "plan_first": "Plan first", + "plan_first_hint": "The model writes a plan for you to approve before it acts.", + "agent_mode": "Mode", + "agent_greeting": "What should the agent do?", + "agent_runs_on": "Runs on %1$s, in %2$s", + "agent_directory_default": "its first folder", + "model_choose": "Choose a model", + "model_in_use": "In use", + "model_sees_images": "Sees images", + "model_uses_tools": "Uses tools", + "model_context": "%1$s context", + "model_thinking_switchable": "Thinking on or off", + "model_levels": "Effort: %1$s", + "code": "Code", + "copy_code": "Copy code", + "select_text": "Select text", + "tools_used": "Used %1$s tools", + "suggest_explain": "Explain", + "suggest_explain_line": "how something works, in plain words", + "suggest_write": "Write", + "suggest_write_line": "an email, a note or a post", + "suggest_plan": "Plan", + "suggest_plan_line": "a trip, a week or a project", + "suggest_check": "Check", + "suggest_check_line": "a text for mistakes and tone", + "instance_in_use": "In use", + "notification_settings": "Notification settings", + "notification_settings_hint": "Which kinds arrive, and how: replies, questions, scheduled results and failures.", + # Scheduled tasks + "scheduled": "Scheduled", + "scheduled_empty": "Nothing is scheduled. Ask for something to happen every morning, or once next week.", + "scheduled_unsupported": "This instance does not offer scheduled tasks yet. They come with a newer LLeMbas on the server.", + "schedule_new": "New schedule", + "schedule_edit": "Edit schedule", + "schedule_next": "Next: %1$s", + "schedule_paused": "Paused", + "schedule_pause": "Pause", + "schedule_resume": "Resume", + "schedule_run_now": "Run now", + "schedule_started": "Started. The result appears in its history.", + "schedule_next_runs": "Next runs", + "schedule_history": "History", + "schedule_no_runs": "It has not run yet.", + "schedule_model": "Model: %1$s", + "schedule_delete_confirm": "Delete this schedule? Its past results stay in their chats.", + "schedule_words_hint": "Say when and what, in your own words. You will see what was understood before anything is saved.", + "schedule_words_example": "Every weekday at 7:30, sum up the news about renewable energy", + "schedule_preview": "Preview", + "schedule_understood": "Understood as", + "notify_always": "Tells you every time", + "notify_matters": "Tells you when it matters", + "notify_never": "Never tells you", + "run_ok": "Done", + "run_silent": "Nothing new", + "run_failed": "Failed", + "run_missed": "Missed ×%1$s", + "run_skipped": "Skipped", + "run_waiting": "Waiting for a model", + "run_running": "Running", + "run_model_switched": "%1$s (the first choice was busy)", + "channel_scheduled": "Scheduled results", + "channel_scheduled_failures": "Scheduled failures", + "scheduled_result_public": "A scheduled task has a result.", + "scheduled_failed_public": "A scheduled task failed.", # Cards "card_approval": "Allow this?", "card_allow_once": "Allow once", diff --git a/scripts/strings_own.json b/scripts/strings_own.json index 938a1ed..a1b73e1 100644 --- a/scripts/strings_own.json +++ b/scripts/strings_own.json @@ -3,10 +3,13 @@ "about_version": "LLeMbas pro Android %1$s", "add_instance": "Přidat instanci", "agent_directory": "Složka na zařízení", + "agent_directory_default": "jeho první složka", "agent_directory_hint": "Prázdné: první složka zařízení", + "agent_greeting": "Co má agent udělat?", "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_runs_on": "Běží na %1$s, ve složce %2$s", "agent_stop_confirm": "Zastavit %1$s? Co dosud udělal, zůstane.", "archive": "Archivovat", "assist_hint": "Zeptejte se na cokoli", @@ -28,21 +31,43 @@ "card_approval": "Povolit to?", "card_reason": "Proč ne? (nepovinné)", "channel_asks": "Otázky a schválení", + "channel_scheduled": "Výsledky naplánovaných úloh", + "channel_scheduled_failures": "Selhání naplánovaných úloh", + "chats_agents": "Chaty s agentem", + "chats_earlier": "Dříve", + "chats_none_found": "Žádný chat to nemá v názvu.", + "chats_open": "Otevřít chaty", + "chats_search": "Hledat v chatech", + "chats_today": "Dnes", + "code": "Kód", + "composer_hint_agent": "Řekněte agentovi, co má udělat", "device_name": "LLeMbas pro Android", - "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í.", + "effort": "Úsilí", "empty_chat": "O čem si promluvíme?", "empty_chats": "Zatím žádné konverzace. Ne všichni, kdo bloudí, jsou ztraceni — založte jednu.", + "instance_in_use": "Používá se", "listening": "Naslouchám…", "loading_line": "Pečou se lembasy…", "mode_manual": "Ručně", + "model_context": "kontext %1$s", + "model_in_use": "Používá se", + "model_levels": "Úsilí: %1$s", + "model_thinking_switchable": "Přemýšlení zapnout či vypnout", + "model_uses_tools": "Používá nástroje", "more": "Více", "new_agent_chat": "Nová konverzace s agentem", + "notification_settings": "Nastavení oznámení", + "notification_settings_hint": "Které druhy přicházejí a jak: odpovědi, otázky, výsledky a selhání naplánovaných úloh.", + "notify_always": "Dá vědět pokaždé", + "notify_matters": "Dá vědět, když na tom záleží", + "notify_never": "Nedá vědět nikdy", "offline": "Instance není dostupná. Zkontrolujte připojení telefonu a to, zda se dostane na adresu instance.", "older": "Starší zprávy", "output_cut": "Výstup je zde zkrácen. Celý ho najdete na webové stránce.", "plan_approve": "Schválit plán", "plan_carry_out": "Provést plán", + "plan_first": "Nejdřív plán", + "plan_first_hint": "Model napíše plán, který schválíte, než začne jednat.", "plan_what_to_change": "Co by se mělo změnit?", "push_enable": "Zapnout upozornění", "push_explained": "Upozornění chodí přes UnifiedPush, bez služeb Google: doručuje je distribuční aplikace, kterou jste zvolili; jsou zašifrované jen pro tento telefon.", @@ -50,6 +75,29 @@ "push_no_distributor": "Abyste se dozvěděli, že je odpověď hotová, nainstalujte distributora UnifiedPush, například ntfy, a pak se vraťte sem. Bez něj aplikace nové odpovědi ukáže, jen když je otevřená.", "push_on": "Upozornění jsou pro tuto instanci zapnutá.", "regenerate": "Vygenerovat znovu", + "run_missed": "Zmeškáno ×%1$s", + "run_model_switched": "%1$s (první volba byla zaneprázdněná)", + "run_silent": "Nic nového", + "run_skipped": "Vynecháno", + "run_waiting": "Čeká na model", + "schedule_delete_confirm": "Smazat tento plán? Jeho dřívější výsledky zůstanou ve svých chatech.", + "schedule_edit": "Upravit plán", + "schedule_history": "Historie", + "schedule_model": "Model: %1$s", + "schedule_new": "Nový plán", + "schedule_next": "Příště: %1$s", + "schedule_next_runs": "Příští spuštění", + "schedule_no_runs": "Zatím neběžel.", + "schedule_paused": "Pozastaveno", + "schedule_started": "Spuštěno. Výsledek se objeví v historii.", + "schedule_understood": "Pochopeno jako", + "schedule_words_example": "Každý pracovní den v 7:30 shrň zprávy o obnovitelné energii", + "schedule_words_hint": "Řekněte vlastními slovy kdy a co. Než se cokoli uloží, uvidíte, jak to bylo pochopeno.", + "scheduled_empty": "Nic není naplánováno. Požádejte o něco, co se má stát každé ráno, nebo jednou příští týden.", + "scheduled_failed_public": "Naplánovaná úloha selhala.", + "scheduled_result_public": "Naplánovaná úloha má výsledek.", + "scheduled_unsupported": "Tato instance zatím naplánované úlohy nenabízí. Přijdou s novějším LLeMbas na serveru.", + "select_text": "Vybrat text", "settings_about": "O aplikaci", "settings_assistant": "Asistent", "settings_instances": "Instance", @@ -65,11 +113,22 @@ "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ší.", + "suggest_check": "Zkontroluj", + "suggest_check_line": "text, chyby a tón", + "suggest_explain": "Vysvětli", + "suggest_explain_line": "jak něco funguje, jednoduše", + "suggest_plan": "Naplánuj", + "suggest_plan_line": "výlet, týden nebo projekt", + "suggest_write": "Napiš", + "suggest_write_line": "e-mail, poznámku nebo příspěvek", "team_chip": "Agenti %1$s–%2$s", "theme_moria": "Moria (temná)", "theme_shire": "Shire (světlý)", "theme_system": "Podle systému", + "thinking_switch_hint": "Pomalejší a lepší u těžkých otázek.", "tile_ask": "Zeptat se LLeMbas", + "tools_used": "Použité nástroje: %1$s", + "tune": "Možnosti", "update_allow_installs": "Povolte aplikaci LLeMbas instalovat aktualizace a pak to zkontrolujte znovu.", "update_bad_file": "Stažený soubor neodpovídal verzi a byl zahozen.", "update_check": "Zkontrolovat aktualizaci", @@ -86,10 +145,13 @@ "about_version": "LLeMbas für Android %1$s", "add_instance": "Instanz hinzufügen", "agent_directory": "Ordner auf dem Gerät", + "agent_directory_default": "seinem ersten Ordner", "agent_directory_hint": "Leer: der erste Ordner des Geräts", + "agent_greeting": "Was soll der Agent tun?", "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_runs_on": "Läuft auf %1$s, in %2$s", "agent_stop_confirm": "%1$s stoppen? Was bisher getan wurde, bleibt.", "archive": "Archivieren", "assist_hint": "Fragen Sie irgendetwas", @@ -111,22 +173,44 @@ "card_approval": "Das erlauben?", "card_reason": "Warum nicht? (optional)", "channel_asks": "Fragen und Bestätigungen", + "channel_scheduled": "Geplante Ergebnisse", + "channel_scheduled_failures": "Geplante Fehler", + "chats_agents": "Agenten-Chats", + "chats_earlier": "Früher", + "chats_none_found": "Kein Chat hat das im Titel.", + "chats_open": "Chats öffnen", + "chats_search": "Chats durchsuchen", + "chats_today": "Heute", + "code": "Code", + "composer_hint_agent": "Sag dem Agenten, was er tun soll", "device_name": "LLeMbas für Android", - "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.", + "effort": "Aufwand", "empty_chat": "Worüber sprechen wir?", "empty_chats": "Noch keine Chats. Nicht jeder, der wandert, ist verloren — fangen Sie einen an.", + "instance_in_use": "In Verwendung", "listening": "Hört zu…", "loading_line": "Lembas wird gebacken…", "mode_manual": "Manuell", "mode_plan": "Plan", + "model_context": "%1$s Kontext", + "model_in_use": "In Verwendung", + "model_levels": "Aufwand: %1$s", + "model_thinking_switchable": "Nachdenken an oder aus", + "model_uses_tools": "Nutzt Werkzeuge", "more": "Mehr", "new_agent_chat": "Neuer Agent-Chat", + "notification_settings": "Benachrichtigungseinstellungen", + "notification_settings_hint": "Welche Arten ankommen und wie: Antworten, Fragen, geplante Ergebnisse und Fehler.", + "notify_always": "Meldet sich jedes Mal", + "notify_matters": "Meldet sich, wenn es wichtig ist", + "notify_never": "Meldet sich nie", "offline": "Die Instanz ist nicht erreichbar. Prüfen Sie die Verbindung des Telefons und ob es die Adresse der Instanz erreicht.", "older": "Frühere Nachrichten", "output_cut": "Die Ausgabe ist hier verkürzt. Vollständig finden Sie sie auf der Webseite.", "plan_approve": "Plan bestätigen", "plan_carry_out": "Plan ausführen", + "plan_first": "Erst planen", + "plan_first_hint": "Das Modell schreibt einen Plan, den du genehmigst, bevor es handelt.", "plan_what_to_change": "Was soll sich ändern?", "push_enable": "Benachrichtigungen einschalten", "push_explained": "Benachrichtigungen kommen über UnifiedPush, ohne Google-Dienste: Die von Ihnen gewählte Distributor-App trägt sie, verschlüsselt nur für dieses Telefon.", @@ -134,6 +218,29 @@ "push_no_distributor": "Um erfahren zu lassen, wenn eine Antwort fertig ist, installieren Sie einen UnifiedPush-Distributor wie ntfy und kommen Sie dann hierher zurück. Ohne einen zeigt die App neue Antworten nur, wenn sie geöffnet ist.", "push_on": "Benachrichtigungen sind für diese Instanz eingeschaltet.", "regenerate": "Neu generieren", + "run_missed": "Verpasst ×%1$s", + "run_model_switched": "%1$s (die erste Wahl war beschäftigt)", + "run_silent": "Nichts Neues", + "run_skipped": "Übersprungen", + "run_waiting": "Wartet auf ein Modell", + "schedule_delete_confirm": "Diesen Zeitplan löschen? Seine bisherigen Ergebnisse bleiben in ihren Chats.", + "schedule_edit": "Zeitplan bearbeiten", + "schedule_history": "Verlauf", + "schedule_model": "Modell: %1$s", + "schedule_new": "Neuer Zeitplan", + "schedule_next": "Nächstes Mal: %1$s", + "schedule_next_runs": "Nächste Läufe", + "schedule_no_runs": "Er ist noch nicht gelaufen.", + "schedule_paused": "Pausiert", + "schedule_started": "Gestartet. Das Ergebnis erscheint im Verlauf.", + "schedule_understood": "Verstanden als", + "schedule_words_example": "Jeden Werktag um 7:30 die Nachrichten über erneuerbare Energie zusammenfassen", + "schedule_words_hint": "Sag in eigenen Worten, wann und was. Bevor etwas gespeichert wird, siehst du, wie es verstanden wurde.", + "scheduled_empty": "Nichts ist geplant. Bitte um etwas, das jeden Morgen geschehen soll, oder einmal nächste Woche.", + "scheduled_failed_public": "Eine geplante Aufgabe ist fehlgeschlagen.", + "scheduled_result_public": "Eine geplante Aufgabe hat ein Ergebnis.", + "scheduled_unsupported": "Diese Instanz bietet noch keine geplanten Aufgaben. Sie kommen mit einem neueren LLeMbas auf dem Server.", + "select_text": "Text auswählen", "settings_about": "Über", "settings_assistant": "Assistent", "settings_instances": "Instanzen", @@ -149,11 +256,22 @@ "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.", + "suggest_check": "Prüfe", + "suggest_check_line": "einen Text auf Fehler und Ton", + "suggest_explain": "Erkläre", + "suggest_explain_line": "einfach, wie etwas funktioniert", + "suggest_plan": "Plane", + "suggest_plan_line": "eine Reise, eine Woche oder ein Projekt", + "suggest_write": "Schreibe", + "suggest_write_line": "eine E-Mail, eine Notiz oder einen Beitrag", "team_chip": "Agenten %1$s–%2$s", "theme_moria": "Moria (dunkel)", "theme_shire": "Shire (hell)", "theme_system": "Wie das System", + "thinking_switch_hint": "Langsamer, und besser bei schwierigen Fragen.", "tile_ask": "LLeMbas fragen", + "tools_used": "%1$s Werkzeuge genutzt", + "tune": "Optionen", "update_allow_installs": "Erlauben Sie LLeMbas, Updates zu installieren, und prüfen Sie dann erneut.", "update_bad_file": "Der Download stimmte nicht mit der Version überein und wurde verworfen.", "update_check": "Nach einem Update suchen", @@ -170,10 +288,13 @@ "about_version": "LLeMbas para Android %1$s", "add_instance": "Añadir una instancia", "agent_directory": "Carpeta en el dispositivo", + "agent_directory_default": "su primera carpeta", "agent_directory_hint": "Vacío: la primera carpeta del dispositivo", + "agent_greeting": "¿Qué debe hacer el agente?", "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_runs_on": "Se ejecuta en %1$s, en %2$s", "agent_stop_confirm": "¿Detener %1$s? Lo que ha hecho hasta ahora se queda.", "archive": "Archivar", "assist_hint": "Pregunte lo que quiera", @@ -195,21 +316,43 @@ "card_approval": "¿Permitir esto?", "card_reason": "¿Por qué no? (opcional)", "channel_asks": "Preguntas y aprobaciones", + "channel_scheduled": "Resultados programados", + "channel_scheduled_failures": "Fallos programados", + "chats_agents": "Chats de agente", + "chats_earlier": "Antes", + "chats_none_found": "Ningún chat lo tiene en el título.", + "chats_open": "Abrir los chats", + "chats_search": "Buscar chats", + "chats_today": "Hoy", + "code": "Código", + "composer_hint_agent": "Dile al agente qué hacer", "device_name": "LLeMbas para Android", - "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.", + "effort": "Esfuerzo", "empty_chat": "¿De qué hablamos?", "empty_chats": "Aún no hay chats. No todos los que vagan están perdidos — empiece uno.", + "instance_in_use": "En uso", "listening": "Escuchando…", "loading_line": "Horneando lembas…", "mode_manual": "Manual", + "model_context": "contexto de %1$s", + "model_in_use": "En uso", + "model_levels": "Esfuerzo: %1$s", + "model_thinking_switchable": "Razonamiento sí o no", + "model_uses_tools": "Usa herramientas", "more": "Más", "new_agent_chat": "Nuevo chat de agente", + "notification_settings": "Ajustes de notificaciones", + "notification_settings_hint": "Qué tipos llegan y cómo: respuestas, preguntas, resultados y fallos programados.", + "notify_always": "Avisa siempre", + "notify_matters": "Avisa cuando importa", + "notify_never": "No avisa nunca", "offline": "No se puede acceder a la instancia. Compruebe la conexión del teléfono y que llegue a la dirección de la instancia.", "older": "Mensajes anteriores", "output_cut": "La salida está acortada aquí. La tiene completa en la página web.", "plan_approve": "Aprobar el plan", "plan_carry_out": "Llevar a cabo el plan", + "plan_first": "Primero un plan", + "plan_first_hint": "El modelo escribe un plan que apruebas antes de que actúe.", "plan_what_to_change": "¿Qué debería cambiar?", "push_enable": "Activar las notificaciones", "push_explained": "Las notificaciones llegan mediante UnifiedPush, sin servicios de Google: la aplicación distribuidora que eligió las transporta, cifradas solo para este teléfono.", @@ -217,6 +360,29 @@ "push_no_distributor": "Para que le avisen cuando una respuesta esté lista, instale un distribuidor de UnifiedPush como ntfy y luego vuelva aquí. Sin uno, la aplicación muestra las respuestas nuevas solo cuando está abierta.", "push_on": "Las notificaciones están activadas para esta instancia.", "regenerate": "Regenerar", + "run_missed": "Perdida ×%1$s", + "run_model_switched": "%1$s (la primera opción estaba ocupada)", + "run_silent": "Nada nuevo", + "run_skipped": "Omitida", + "run_waiting": "Esperando un modelo", + "schedule_delete_confirm": "¿Eliminar esta programación? Sus resultados anteriores se quedan en sus chats.", + "schedule_edit": "Editar programación", + "schedule_history": "Historial", + "schedule_model": "Modelo: %1$s", + "schedule_new": "Nueva programación", + "schedule_next": "Próxima: %1$s", + "schedule_next_runs": "Próximas ejecuciones", + "schedule_no_runs": "Aún no se ha ejecutado.", + "schedule_paused": "En pausa", + "schedule_started": "Iniciado. El resultado aparece en su historial.", + "schedule_understood": "Entendido como", + "schedule_words_example": "Cada día laborable a las 7:30, resume las noticias sobre energías renovables", + "schedule_words_hint": "Di cuándo y qué, con tus palabras. Verás lo que se entendió antes de guardar nada.", + "scheduled_empty": "No hay nada programado. Pide algo que ocurra cada mañana, o una vez la semana que viene.", + "scheduled_failed_public": "Una tarea programada falló.", + "scheduled_result_public": "Una tarea programada tiene un resultado.", + "scheduled_unsupported": "Esta instancia aún no ofrece tareas programadas. Llegan con un LLeMbas más reciente en el servidor.", + "select_text": "Seleccionar texto", "settings_about": "Acerca de", "settings_assistant": "Asistente", "settings_instances": "Instancias", @@ -232,11 +398,22 @@ "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.", + "suggest_check": "Revisa", + "suggest_check_line": "un texto: errores y tono", + "suggest_explain": "Explica", + "suggest_explain_line": "cómo funciona algo, con palabras sencillas", + "suggest_plan": "Planifica", + "suggest_plan_line": "un viaje, una semana o un proyecto", + "suggest_write": "Escribe", + "suggest_write_line": "un correo, una nota o una publicación", "team_chip": "Agentes %1$s–%2$s", "theme_moria": "Moria (oscuro)", "theme_shire": "Shire (claro)", "theme_system": "Como el sistema", + "thinking_switch_hint": "Más lento, y mejor con preguntas difíciles.", "tile_ask": "Preguntar a LLeMbas", + "tools_used": "Usó %1$s herramientas", + "tune": "Opciones", "update_allow_installs": "Permita que LLeMbas instale actualizaciones y vuelva a comprobarlo.", "update_bad_file": "La descarga no coincidía con la versión y se descartó.", "update_check": "Buscar una actualización", @@ -253,10 +430,13 @@ "about_version": "LLeMbas pour Android %1$s", "add_instance": "Ajouter une instance", "agent_directory": "Dossier sur l'appareil", + "agent_directory_default": "son premier dossier", "agent_directory_hint": "Vide : le premier dossier de l'appareil", + "agent_greeting": "Que doit faire l’agent ?", "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_runs_on": "S’exécute sur %1$s, dans %2$s", "agent_stop_confirm": "Arrêter %1$s ? Ce qu’il a déjà fait reste.", "archive": "Archiver", "assist_hint": "Demandez n'importe quoi", @@ -278,22 +458,44 @@ "card_approval": "Autoriser ceci ?", "card_reason": "Pourquoi pas ? (facultatif)", "channel_asks": "Questions et approbations", + "channel_scheduled": "Résultats planifiés", + "channel_scheduled_failures": "Échecs planifiés", + "chats_agents": "Discussions d’agent", + "chats_earlier": "Plus tôt", + "chats_none_found": "Aucune discussion ne l’a dans son titre.", + "chats_open": "Ouvrir les discussions", + "chats_search": "Rechercher dans les discussions", + "chats_today": "Aujourd’hui", + "code": "Code", + "composer_hint_agent": "Dites à l’agent quoi faire", "device_name": "LLeMbas pour Android", - "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.", + "effort": "Effort", "empty_chat": "De quoi allons-nous parler ?", "empty_chats": "Pas encore de conversation. Tous ceux qui errent ne sont pas perdus — commencez-en une.", + "instance_in_use": "Utilisée", "listening": "Écoute…", "loading_line": "Cuisson des lembas…", "mode_manual": "Manuel", "mode_plan": "Plan", + "model_context": "contexte de %1$s", + "model_in_use": "Utilisé", + "model_levels": "Effort : %1$s", + "model_thinking_switchable": "Réflexion activable", + "model_uses_tools": "Utilise des outils", "more": "Plus", "new_agent_chat": "Nouvelle conversation d'agent", + "notification_settings": "Réglages des notifications", + "notification_settings_hint": "Quels types arrivent, et comment : réponses, questions, résultats et échecs planifiés.", + "notify_always": "Prévient à chaque fois", + "notify_matters": "Prévient quand c’est important", + "notify_never": "Ne prévient jamais", "offline": "L'instance est injoignable. Vérifiez la connexion du téléphone et qu'il atteint bien l'adresse de l'instance.", "older": "Messages précédents", "output_cut": "La sortie est raccourcie ici. Vous la trouverez en entier sur la page web.", "plan_approve": "Approuver le plan", "plan_carry_out": "Exécuter le plan", + "plan_first": "D’abord un plan", + "plan_first_hint": "Le modèle rédige un plan que vous approuvez avant qu’il agisse.", "plan_what_to_change": "Qu'est-ce qui doit changer ?", "push_enable": "Activer les notifications", "push_explained": "Les notifications arrivent par UnifiedPush, sans services Google : l'application distributrice que vous avez choisie les transporte, chiffrées pour ce téléphone uniquement.", @@ -301,6 +503,29 @@ "push_no_distributor": "Pour être averti quand une réponse est prête, installez un distributeur UnifiedPush tel que ntfy, puis revenez ici. Sans cela, l'application affiche les nouvelles réponses seulement quand elle est ouverte.", "push_on": "Les notifications sont activées pour cette instance.", "regenerate": "Régénérer", + "run_missed": "Manquée ×%1$s", + "run_model_switched": "%1$s (le premier choix était occupé)", + "run_silent": "Rien de neuf", + "run_skipped": "Sautée", + "run_waiting": "En attente d’un modèle", + "schedule_delete_confirm": "Supprimer cette planification ? Ses résultats passés restent dans leurs discussions.", + "schedule_edit": "Modifier la planification", + "schedule_history": "Historique", + "schedule_model": "Modèle : %1$s", + "schedule_new": "Nouvelle planification", + "schedule_next": "Prochaine : %1$s", + "schedule_next_runs": "Prochaines exécutions", + "schedule_no_runs": "Elle ne s’est pas encore exécutée.", + "schedule_paused": "En pause", + "schedule_started": "Lancé. Le résultat apparaît dans l’historique.", + "schedule_understood": "Compris comme", + "schedule_words_example": "Chaque jour ouvré à 7 h 30, résume l’actualité des énergies renouvelables", + "schedule_words_hint": "Dites quand et quoi, avec vos mots. Vous verrez ce qui a été compris avant tout enregistrement.", + "scheduled_empty": "Rien n’est planifié. Demandez quelque chose chaque matin, ou une fois la semaine prochaine.", + "scheduled_failed_public": "Une tâche planifiée a échoué.", + "scheduled_result_public": "Une tâche planifiée a un résultat.", + "scheduled_unsupported": "Cette instance ne propose pas encore de tâches planifiées. Elles arrivent avec un LLeMbas plus récent sur le serveur.", + "select_text": "Sélectionner le texte", "settings_about": "À propos", "settings_assistant": "Assistant", "settings_instances": "Instances", @@ -316,11 +541,22 @@ "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.", + "suggest_check": "Relis", + "suggest_check_line": "un texte : fautes et ton", + "suggest_explain": "Explique", + "suggest_explain_line": "simplement comment quelque chose fonctionne", + "suggest_plan": "Planifie", + "suggest_plan_line": "un voyage, une semaine ou un projet", + "suggest_write": "Rédige", + "suggest_write_line": "un e-mail, une note ou un billet", "team_chip": "Agents %1$s–%2$s", "theme_moria": "Moria (sombre)", "theme_shire": "Shire (clair)", "theme_system": "Comme le système", + "thinking_switch_hint": "Plus lent, et meilleur sur les questions difficiles.", "tile_ask": "Demander à LLeMbas", + "tools_used": "%1$s outils utilisés", + "tune": "Options", "update_allow_installs": "Autorisez LLeMbas à installer des mises à jour, puis vérifiez à nouveau.", "update_bad_file": "Le téléchargement ne correspondait pas à la version et a été rejeté.", "update_check": "Rechercher une mise à jour", @@ -337,10 +573,13 @@ "about_version": "LLeMbas Androidra %1$s", "add_instance": "Példány hozzáadása", "agent_directory": "Mappa az eszközön", + "agent_directory_default": "az első mappája", "agent_directory_hint": "Üres: az eszköz első mappája", + "agent_greeting": "Mit tegyen az ügynök?", "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_runs_on": "Itt fut: %1$s, ebben: %2$s", "agent_stop_confirm": "Leállítja: %1$s? Amit eddig elvégzett, megmarad.", "archive": "Archiválás", "assist_hint": "Kérdezzen bármit", @@ -362,22 +601,44 @@ "card_approval": "Engedélyezzük ezt?", "card_reason": "Miért nem? (opcionális)", "channel_asks": "Kérdések és jóváhagyások", + "channel_scheduled": "Ütemezett eredmények", + "channel_scheduled_failures": "Ütemezett hibák", + "chats_agents": "Ügynök-csevegések", + "chats_earlier": "Korábban", + "chats_none_found": "Egy csevegés címében sincs ilyen.", + "chats_open": "Csevegések megnyitása", + "chats_search": "Keresés a csevegésekben", + "chats_today": "Ma", + "code": "Kód", + "composer_hint_agent": "Mondja meg az ügynöknek, mit tegyen", "device_name": "LLeMbas Androidra", - "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.", + "effort": "Ráfordítás", "empty_chat": "Miről beszéljünk?", "empty_chats": "Még nincs csevegés. Nem mindenki van elveszve, aki bolyong — kezdjen el egyet.", + "instance_in_use": "Használatban", "listening": "Hallgatja…", "loading_line": "Lembas sül…", "mode_manual": "Kézi", "mode_plan": "Terv", + "model_context": "%1$s kontextus", + "model_in_use": "Használatban", + "model_levels": "Ráfordítás: %1$s", + "model_thinking_switchable": "Gondolkodás be- vagy kikapcsolva", + "model_uses_tools": "Eszközöket használ", "more": "Továbbiak", "new_agent_chat": "Új ügynök-csevegés", + "notification_settings": "Értesítési beállítások", + "notification_settings_hint": "Milyen értesítések jönnek és hogyan: válaszok, kérdések, ütemezett eredmények és hibák.", + "notify_always": "Mindig szól", + "notify_matters": "Szól, ha számít", + "notify_never": "Soha nem szól", "offline": "A példány nem érhető el. Ellenőrizze a telefon kapcsolatát, és hogy eléri-e a példány címét.", "older": "Korábbi üzenetek", "output_cut": "A kimenet itt lerövidítve jelenik meg. A teljes szöveg a weblapon található.", "plan_approve": "Terv jóváhagyása", "plan_carry_out": "Terv végrehajtása", + "plan_first": "Előbb terv", + "plan_first_hint": "A modell tervet ír, amelyet jóváhagy, mielőtt cselekszik.", "plan_what_to_change": "Mi változzon?", "push_enable": "Értesítések bekapcsolása", "push_explained": "Az értesítések a UnifiedPush-on keresztül érkeznek, Google-szolgáltatások nélkül: az Ön által választott elosztó alkalmazás szállítja őket, titkosítva, csak ehhez a telefonhoz.", @@ -385,6 +646,29 @@ "push_no_distributor": "Hogy értesítést kapjon, amikor egy válasz elkészül, telepítsen egy UnifiedPush-elosztót, például az ntfy-t, majd jöjjön vissza ide. Ha nincs ilyen, az alkalmazás csak akkor mutatja az új válaszokat, amikor meg van nyitva.", "push_on": "Az értesítések be vannak kapcsolva ehhez a példányhoz.", "regenerate": "Újragenerálás", + "run_missed": "Kimaradt ×%1$s", + "run_model_switched": "%1$s (az első választás foglalt volt)", + "run_silent": "Semmi új", + "run_skipped": "Kihagyva", + "run_waiting": "Modellre vár", + "schedule_delete_confirm": "Törli ezt az ütemezést? A korábbi eredményei megmaradnak a csevegéseikben.", + "schedule_edit": "Ütemezés szerkesztése", + "schedule_history": "Előzmények", + "schedule_model": "Modell: %1$s", + "schedule_new": "Új ütemezés", + "schedule_next": "Következő: %1$s", + "schedule_next_runs": "Következő futások", + "schedule_no_runs": "Még nem futott.", + "schedule_paused": "Szüneteltetve", + "schedule_started": "Elindítva. Az eredmény az előzményekben jelenik meg.", + "schedule_understood": "Így értelmezve", + "schedule_words_example": "Minden hétköznap 7:30-kor foglald össze a megújuló energiáról szóló híreket", + "schedule_words_hint": "Mondja el saját szavaival, mikor és mit. Mentés előtt látja, mit értett meg belőle.", + "scheduled_empty": "Nincs semmi ütemezve. Kérjen valamit minden reggelre, vagy egyszer a jövő hétre.", + "scheduled_failed_public": "Egy ütemezett feladat sikertelen volt.", + "scheduled_result_public": "Egy ütemezett feladatnak eredménye van.", + "scheduled_unsupported": "Ez a példány még nem kínál ütemezett feladatokat. Egy újabb LLeMbas-szal érkeznek a szerveren.", + "select_text": "Szöveg kijelölése", "settings_about": "Névjegy", "settings_assistant": "Asszisztens", "settings_instances": "Példányok", @@ -400,11 +684,22 @@ "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.", + "suggest_check": "Ellenőrizz", + "suggest_check_line": "egy szöveget: hibák és hangnem", + "suggest_explain": "Magyarázd el,", + "suggest_explain_line": "hogyan működik valami, egyszerűen", + "suggest_plan": "Tervezz meg", + "suggest_plan_line": "egy utat, egy hetet vagy egy projektet", + "suggest_write": "Írj", + "suggest_write_line": "e-mailt, jegyzetet vagy bejegyzést", "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", + "thinking_switch_hint": "Lassabb, de jobb a nehéz kérdéseknél.", "tile_ask": "Kérdés az LLeMbas-tól", + "tools_used": "%1$s eszköz használva", + "tune": "Beállítások", "update_allow_installs": "Engedélyezze, hogy az LLeMbas frissítéseket telepítsen, majd ellenőrizze újra.", "update_bad_file": "A letöltés nem egyezett a verzióval, és el lett dobva.", "update_check": "Frissítés keresése", @@ -421,10 +716,13 @@ "about_version": "LLeMbas per Android %1$s", "add_instance": "Aggiungi un'istanza", "agent_directory": "Cartella sul dispositivo", + "agent_directory_default": "la sua prima cartella", "agent_directory_hint": "Vuoto: la prima cartella del dispositivo", + "agent_greeting": "Cosa deve fare l’agente?", "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_runs_on": "Gira su %1$s, in %2$s", "agent_stop_confirm": "Fermare %1$s? Ciò che ha fatto finora resta.", "archive": "Archivia", "assist_hint": "Chiedi qualsiasi cosa", @@ -446,21 +744,43 @@ "card_approval": "Consentire questo?", "card_reason": "Perché no? (facoltativo)", "channel_asks": "Domande e approvazioni", + "channel_scheduled": "Risultati pianificati", + "channel_scheduled_failures": "Errori pianificati", + "chats_agents": "Chat con agente", + "chats_earlier": "Prima", + "chats_none_found": "Nessuna chat lo ha nel titolo.", + "chats_open": "Apri le chat", + "chats_search": "Cerca nelle chat", + "chats_today": "Oggi", + "code": "Codice", + "composer_hint_agent": "Di’ all’agente cosa fare", "device_name": "LLeMbas per Android", - "effort_level": "Sforzo: %1$s", - "empty_agents": "Ancora nessuna chat agente. Avviane una con Nuova chat agente, su un dispositivo collegato a questa istanza.", + "effort": "Impegno", "empty_chat": "Di cosa parliamo?", "empty_chats": "Ancora nessuna chat. Non tutti quelli che vagano sono perduti — iniziane una.", + "instance_in_use": "In uso", "listening": "In ascolto…", "loading_line": "I lembas stanno cuocendo…", "mode_manual": "Manuale", + "model_context": "contesto di %1$s", + "model_in_use": "In uso", + "model_levels": "Impegno: %1$s", + "model_thinking_switchable": "Ragionamento attivabile", + "model_uses_tools": "Usa strumenti", "more": "Altro", "new_agent_chat": "Nuova chat agente", + "notification_settings": "Impostazioni delle notifiche", + "notification_settings_hint": "Quali tipi arrivano e come: risposte, domande, risultati e errori pianificati.", + "notify_always": "Avvisa ogni volta", + "notify_matters": "Avvisa quando conta", + "notify_never": "Non avvisa mai", "offline": "L'istanza non è raggiungibile. Controlla la connessione del telefono e che raggiunga l'indirizzo dell'istanza.", "older": "Messaggi precedenti", "output_cut": "L'output qui è abbreviato. Lo trovi per intero sulla pagina web.", "plan_approve": "Approva il piano", "plan_carry_out": "Esegui il piano", + "plan_first": "Prima un piano", + "plan_first_hint": "Il modello scrive un piano da approvare prima di agire.", "plan_what_to_change": "Cosa dovrebbe cambiare?", "push_enable": "Attiva le notifiche", "push_explained": "Le notifiche arrivano tramite UnifiedPush, senza servizi Google: l'app di distribuzione che hai scelto le trasporta, cifrate solo per questo telefono.", @@ -468,6 +788,29 @@ "push_no_distributor": "Per essere avvisato quando una risposta è pronta, installa un distributore UnifiedPush come ntfy, poi torna qui. Senza uno, l'app mostra le nuove risposte solo quando è aperta.", "push_on": "Le notifiche sono attive per questa istanza.", "regenerate": "Rigenera", + "run_missed": "Saltata ×%1$s", + "run_model_switched": "%1$s (la prima scelta era occupata)", + "run_silent": "Niente di nuovo", + "run_skipped": "Ignorata", + "run_waiting": "In attesa di un modello", + "schedule_delete_confirm": "Eliminare questa pianificazione? I risultati passati restano nelle loro chat.", + "schedule_edit": "Modifica pianificazione", + "schedule_history": "Cronologia", + "schedule_model": "Modello: %1$s", + "schedule_new": "Nuova pianificazione", + "schedule_next": "Prossima: %1$s", + "schedule_next_runs": "Prossime esecuzioni", + "schedule_no_runs": "Non è ancora stata eseguita.", + "schedule_paused": "In pausa", + "schedule_started": "Avviato. Il risultato appare nella cronologia.", + "schedule_understood": "Capito come", + "schedule_words_example": "Ogni giorno feriale alle 7:30, riassumi le notizie sulle energie rinnovabili", + "schedule_words_hint": "Di’ quando e cosa, con parole tue. Vedrai cosa è stato capito prima di salvare.", + "scheduled_empty": "Non c’è niente in programma. Chiedi qualcosa ogni mattina, o una volta la settimana prossima.", + "scheduled_failed_public": "Un’attività pianificata non è riuscita.", + "scheduled_result_public": "Un’attività pianificata ha un risultato.", + "scheduled_unsupported": "Questa istanza non offre ancora attività pianificate. Arrivano con un LLeMbas più recente sul server.", + "select_text": "Seleziona testo", "settings_about": "Informazioni", "settings_assistant": "Assistente", "settings_instances": "Istanze", @@ -483,11 +826,22 @@ "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.", + "suggest_check": "Controlla", + "suggest_check_line": "un testo: errori e tono", + "suggest_explain": "Spiega", + "suggest_explain_line": "come funziona qualcosa, in parole semplici", + "suggest_plan": "Pianifica", + "suggest_plan_line": "un viaggio, una settimana o un progetto", + "suggest_write": "Scrivi", + "suggest_write_line": "un’email, una nota o un post", "team_chip": "Agenti %1$s–%2$s", "theme_moria": "Moria (scuro)", "theme_shire": "Shire (chiaro)", "theme_system": "Come il sistema", + "thinking_switch_hint": "Più lento, e migliore con le domande difficili.", "tile_ask": "Chiedi a LLeMbas", + "tools_used": "Usati %1$s strumenti", + "tune": "Opzioni", "update_allow_installs": "Consenti a LLeMbas di installare gli aggiornamenti, poi controlla di nuovo.", "update_bad_file": "Il download non corrispondeva alla versione ed è stato scartato.", "update_check": "Controlla aggiornamenti", @@ -504,10 +858,13 @@ "about_version": "LLeMbas na Androida %1$s", "add_instance": "Dodaj instancję", "agent_directory": "Folder na urządzeniu", + "agent_directory_default": "jego pierwszym folderze", "agent_directory_hint": "Puste: pierwszy folder urządzenia", + "agent_greeting": "Co ma zrobić agent?", "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_runs_on": "Działa na %1$s, w %2$s", "agent_stop_confirm": "Zatrzymać %1$s? To, co już zrobił, zostaje.", "archive": "Archiwizuj", "assist_hint": "Zapytaj o cokolwiek", @@ -529,21 +886,43 @@ "card_approval": "Zezwolić na to?", "card_reason": "Czemu nie? (opcjonalnie)", "channel_asks": "Pytania i zatwierdzenia", + "channel_scheduled": "Wyniki zaplanowanych zadań", + "channel_scheduled_failures": "Błędy zaplanowanych zadań", + "chats_agents": "Czaty z agentem", + "chats_earlier": "Wcześniej", + "chats_none_found": "Żaden czat nie ma tego w tytule.", + "chats_open": "Otwórz czaty", + "chats_search": "Szukaj czatów", + "chats_today": "Dzisiaj", + "code": "Kod", + "composer_hint_agent": "Powiedz agentowi, co ma zrobić", "device_name": "LLeMbas na Androida", - "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ą.", + "effort": "Wysiłek", "empty_chat": "O czym porozmawiamy?", "empty_chats": "Nie ma jeszcze czatów. Nie każdy, kto błądzi, jest zgubiony — zacznij jeden.", + "instance_in_use": "W użyciu", "listening": "Słucham…", "loading_line": "Lembasy się pieczą…", "mode_manual": "Ręcznie", + "model_context": "kontekst %1$s", + "model_in_use": "W użyciu", + "model_levels": "Wysiłek: %1$s", + "model_thinking_switchable": "Myślenie włączane lub wyłączane", + "model_uses_tools": "Używa narzędzi", "more": "Więcej", "new_agent_chat": "Nowy czat agenta", + "notification_settings": "Ustawienia powiadomień", + "notification_settings_hint": "Jakie rodzaje przychodzą i jak: odpowiedzi, pytania, wyniki i błędy zaplanowanych zadań.", + "notify_always": "Powiadamia za każdym razem", + "notify_matters": "Powiadamia, gdy to ważne", + "notify_never": "Nigdy nie powiadamia", "offline": "Instancja jest nieosiągalna. Sprawdź połączenie telefonu i czy dociera on do adresu instancji.", "older": "Wcześniejsze wiadomości", "output_cut": "Wynik jest tu skrócony. Cały znajduje się na stronie internetowej.", "plan_approve": "Zatwierdź plan", "plan_carry_out": "Wykonaj plan", + "plan_first": "Najpierw plan", + "plan_first_hint": "Model pisze plan do zatwierdzenia, zanim zacznie działać.", "plan_what_to_change": "Co powinno się zmienić?", "push_enable": "Włącz powiadomienia", "push_explained": "Powiadomienia przychodzą przez UnifiedPush, bez usług Google: niesie je wybrana aplikacja dystrybucyjna, zaszyfrowane tylko dla tego telefonu.", @@ -551,6 +930,29 @@ "push_no_distributor": "Aby dostawać informacje, kiedy odpowiedź jest gotowa, zainstaluj dystrybutora UnifiedPush, na przykład ntfy, a potem wróć tutaj. Bez niego aplikacja pokazuje nowe odpowiedzi tylko wtedy, gdy jest otwarta.", "push_on": "Powiadomienia są włączone dla tej instancji.", "regenerate": "Wygeneruj ponownie", + "run_missed": "Pominięto ×%1$s", + "run_model_switched": "%1$s (pierwszy wybór był zajęty)", + "run_silent": "Nic nowego", + "run_skipped": "Pominięto", + "run_waiting": "Czeka na model", + "schedule_delete_confirm": "Usunąć ten harmonogram? Jego wcześniejsze wyniki zostaną w swoich czatach.", + "schedule_edit": "Edytuj harmonogram", + "schedule_history": "Historia", + "schedule_model": "Model: %1$s", + "schedule_new": "Nowy harmonogram", + "schedule_next": "Następnie: %1$s", + "schedule_next_runs": "Następne uruchomienia", + "schedule_no_runs": "Jeszcze się nie uruchomił.", + "schedule_paused": "Wstrzymano", + "schedule_started": "Uruchomiono. Wynik pojawi się w historii.", + "schedule_understood": "Zrozumiano jako", + "schedule_words_example": "W każdy dzień roboczy o 7:30 streść wiadomości o energii odnawialnej", + "schedule_words_hint": "Powiedz własnymi słowami, kiedy i co. Zanim cokolwiek zostanie zapisane, zobaczysz, jak to zrozumiano.", + "scheduled_empty": "Nic nie jest zaplanowane. Poproś o coś, co ma się dziać każdego ranka albo raz w przyszłym tygodniu.", + "scheduled_failed_public": "Zaplanowane zadanie się nie powiodło.", + "scheduled_result_public": "Zaplanowane zadanie ma wynik.", + "scheduled_unsupported": "Ta instancja nie oferuje jeszcze zaplanowanych zadań. Pojawią się z nowszym LLeMbas na serwerze.", + "select_text": "Zaznacz tekst", "settings_about": "Informacje", "settings_assistant": "Asystent", "settings_instances": "Instancje", @@ -566,11 +968,22 @@ "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.", + "suggest_check": "Sprawdź", + "suggest_check_line": "tekst pod kątem błędów i tonu", + "suggest_explain": "Wyjaśnij", + "suggest_explain_line": "prostymi słowami, jak coś działa", + "suggest_plan": "Zaplanuj", + "suggest_plan_line": "podróż, tydzień lub projekt", + "suggest_write": "Napisz", + "suggest_write_line": "e-mail, notatkę lub wpis", "team_chip": "Agenci %1$s–%2$s", "theme_moria": "Moria (ciemny)", "theme_shire": "Shire (jasny)", "theme_system": "Jak system", + "thinking_switch_hint": "Wolniej, i lepiej przy trudnych pytaniach.", "tile_ask": "Zapytaj LLeMbas", + "tools_used": "Użyte narzędzia: %1$s", + "tune": "Opcje", "update_allow_installs": "Zezwól LLeMbas na instalowanie aktualizacji, a potem sprawdź ponownie.", "update_bad_file": "Pobrany plik nie zgadzał się z wersją i został odrzucony.", "update_check": "Sprawdź aktualizację", @@ -587,10 +1000,13 @@ "about_version": "LLeMbas pre Android %1$s", "add_instance": "Pridať inštanciu", "agent_directory": "Zložka v zariadení", + "agent_directory_default": "jeho prvý priečinok", "agent_directory_hint": "Prázdne: prvá zložka zariadenia", + "agent_greeting": "Čo má agent urobiť?", "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_runs_on": "Beží na %1$s, v priečinku %2$s", "agent_stop_confirm": "Zastaviť %1$s? Čo doteraz urobil, zostane.", "archive": "Archivovať", "assist_hint": "Spýtajte sa na čokoľvek", @@ -612,21 +1028,43 @@ "card_approval": "Povoliť to?", "card_reason": "Prečo nie? (nepovinné)", "channel_asks": "Otázky a schválenia", + "channel_scheduled": "Výsledky naplánovaných úloh", + "channel_scheduled_failures": "Zlyhania naplánovaných úloh", + "chats_agents": "Čety s agentom", + "chats_earlier": "Skôr", + "chats_none_found": "Žiadny čet to nemá v názve.", + "chats_open": "Otvoriť čety", + "chats_search": "Hľadať v četoch", + "chats_today": "Dnes", + "code": "Kód", + "composer_hint_agent": "Povedzte agentovi, čo má urobiť", "device_name": "LLeMbas pre Android", - "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.", + "effort": "Úsilie", "empty_chat": "O čom sa pozhovárame?", "empty_chats": "Zatiaľ žiadne konverzácie. Nie všetci, čo blúdia, sú stratení — začnite jednu.", + "instance_in_use": "Používa sa", "listening": "Počúvam…", "loading_line": "Pečú sa lembasy…", "mode_manual": "Ručne", + "model_context": "kontext %1$s", + "model_in_use": "Používa sa", + "model_levels": "Úsilie: %1$s", + "model_thinking_switchable": "Premýšľanie zapnúť alebo vypnúť", + "model_uses_tools": "Používa nástroje", "more": "Viac", "new_agent_chat": "Nová konverzácia s agentom", + "notification_settings": "Nastavenia upozornení", + "notification_settings_hint": "Ktoré druhy prichádzajú a ako: odpovede, otázky, výsledky a zlyhania naplánovaných úloh.", + "notify_always": "Dá vedieť zakaždým", + "notify_matters": "Dá vedieť, keď na tom záleží", + "notify_never": "Nedá vedieť nikdy", "offline": "Inštancia nie je dostupná. Skontrolujte pripojenie telefónu a či sa dostane na adresu inštancie.", "older": "Staršie správy", "output_cut": "Výstup je tu skrátený. Celý nájdete na webovej stránke.", "plan_approve": "Schváliť plán", "plan_carry_out": "Vykonať plán", + "plan_first": "Najprv plán", + "plan_first_hint": "Model napíše plán, ktorý schválite, skôr než začne konať.", "plan_what_to_change": "Čo by sa malo zmeniť?", "push_enable": "Zapnúť upozornenia", "push_explained": "Upozornenia chodia cez UnifiedPush, bez služieb Google: doručuje ich distribučná aplikácia, ktorú ste zvolili, zašifrované len pre tento telefón.", @@ -634,6 +1072,29 @@ "push_no_distributor": "Aby ste sa dozvedeli, že je odpoveď hotová, nainštalujte distributora UnifiedPush, napríklad ntfy, a potom sa vráťte sem. Bez neho aplikácia nové odpovede ukáže, len keď je otvorená.", "push_on": "Upozornenia sú pre túto inštanciu zapnuté.", "regenerate": "Vygenerovať znova", + "run_missed": "Zmeškané ×%1$s", + "run_model_switched": "%1$s (prvá voľba bola zaneprázdnená)", + "run_silent": "Nič nové", + "run_skipped": "Vynechané", + "run_waiting": "Čaká na model", + "schedule_delete_confirm": "Zmazať tento plán? Jeho doterajšie výsledky zostanú vo svojich četoch.", + "schedule_edit": "Upraviť plán", + "schedule_history": "História", + "schedule_model": "Model: %1$s", + "schedule_new": "Nový plán", + "schedule_next": "Nabudúce: %1$s", + "schedule_next_runs": "Ďalšie spustenia", + "schedule_no_runs": "Ešte nebežal.", + "schedule_paused": "Pozastavené", + "schedule_started": "Spustené. Výsledok sa objaví v histórii.", + "schedule_understood": "Pochopené ako", + "schedule_words_example": "Každý pracovný deň o 7:30 zhrň správy o obnoviteľnej energii", + "schedule_words_hint": "Povedzte vlastnými slovami kedy a čo. Skôr než sa čokoľvek uloží, uvidíte, ako to bolo pochopené.", + "scheduled_empty": "Nič nie je naplánované. Požiadajte o niečo, čo sa má stať každé ráno, alebo raz budúci týždeň.", + "scheduled_failed_public": "Naplánovaná úloha zlyhala.", + "scheduled_result_public": "Naplánovaná úloha má výsledok.", + "scheduled_unsupported": "Táto inštancia zatiaľ neponúka naplánované úlohy. Prídu s novším LLeMbas na serveri.", + "select_text": "Vybrať text", "settings_about": "O aplikácii", "settings_assistant": "Asistent", "settings_instances": "Inštancie", @@ -649,11 +1110,22 @@ "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ší.", + "suggest_check": "Skontroluj", + "suggest_check_line": "text, chyby a tón", + "suggest_explain": "Vysvetli", + "suggest_explain_line": "jednoducho, ako niečo funguje", + "suggest_plan": "Naplánuj", + "suggest_plan_line": "výlet, týždeň alebo projekt", + "suggest_write": "Napíš", + "suggest_write_line": "e-mail, poznámku alebo príspevok", "team_chip": "Agenti %1$s–%2$s", "theme_moria": "Moria (tmavá)", "theme_shire": "Shire (svetlá)", "theme_system": "Podľa systému", + "thinking_switch_hint": "Pomalšie a lepšie pri ťažkých otázkach.", "tile_ask": "Spýtať sa LLeMbas", + "tools_used": "Použité nástroje: %1$s", + "tune": "Možnosti", "update_allow_installs": "Povoľte aplikácii LLeMbas instalovať aktualizácie a potom to skontrolujte znova.", "update_bad_file": "Stiahnutý súbor nezodpovedal verzii a bol zahodený.", "update_check": "Skontrolovať aktualizáciu",